Порівняти коміти

..
Автор SHA1 Повідомлення Дата
l0ng-ai 2fd5833321 feat(plugins): a plugin command can answer Escape in the editor (API 1.10)
`[[contributes.keymaps]]` accepts `key = "Escape"` with a required `when`.
Plain keys stayed out of plugin shortcuts, and Escape could not be added as a
shortcut anyway: the IDE's own keymap uses it, so the binding would be dropped.
It becomes the editor's lowest-precedence Escape handler instead: the command
runs once popups, completion, rename, selection, extra carets and Vim had no
use for the key, and only while its `when` holds (the latest plugin's binding
first). `when` is accepted only on such a binding; manifests that set it
elsewhere, or bind Escape on one platform only, are refused.
2026-11-17 07:14:58 +08:00
时雨遥 53495fbc26 fix(terminal): tab spinner stops while an interactive program without a progress report waits for input (#3838)
Closes #3831

An interactive program is one long command to the shell, so OSC 133 C/D kept the tab spinning from launch to exit for programs that send no OSC 9;4 report (Claude Code, Codex). A running command that turned on bracketed paste or the alternate screen reads the keyboard itself; its tab now spins only while it keeps drawing (output at most 400 ms apart for 500 ms, until 1.5 s of silence; typing echo excluded). A progress report still decides when present, and plain commands spin from start to end as before.

Co-authored-by: StarryKira <[email protected]>
2026-11-17 04:37:15 +08:00
l0ng-ai 224099992a feat(python): create a Conda environment by name in conda's envs directory (#3839)
The Add Python Interpreter dialog asks for a Conda environment's name (the
project folder's by default) instead of a location. The backend runs
`conda create -n <name>` for a bare name, refuses a name conda already lists,
and finds the new prefix from `conda env list`; a path still creates the
environment at that prefix with `-p`.
2026-11-17 04:29:39 +08:00
l0ng-ai 0dafd649da fix(python): readable environment creation log and status refresh after creating one (#3837)
Tool output is shown as a terminal would show the line: backspaces erase
(conda's spinner), a carriage return rewrites the line (pip progress) and
ANSI sequences are dropped.

The interpreter status widget re-reads interpreters when one is created or
added in Settings. A conda environment lives outside the project, so no file
event announced it, and when the configured path was already set the widget
kept showing "Invalid interpreter" and an interpreter list without it.
2026-11-17 04:24:28 +08:00
l0ng-ai d2c5532ccb fix(completion): complete at every caret (#3836)
With several carets, picking a completion inserted it at the main caret only
and collapsed the selection. The item now goes in at each caret whose text
around it matches the main caret's (the typed prefix, and what a replacing
edit overwrites). Snippets go in as plain text with each caret at the first
stop. Items the server inserts itself (kotlin-lsp) keep the carets, and the
server's edit is repeated at the others when it lands.
2026-11-17 04:18:31 +08:00
28 змінених файлів з 839 додано та 70 видалено

No files matched your search

+55 -3
Переглянути файл
@@ -13,6 +13,7 @@
//! [[contributes.keymaps]]
//! command = "check"
//! key = "Ctrl+Alt+C" # `mac` for a different binding on macOS (`Meta+Alt+C`)
//! # key = "Escape" + when = "…" # API 1.10: Escape in an editor that the IDE had no use for
//!
//! [[contributes.statusBar]]
//! id = "branch"
@@ -203,8 +204,16 @@ struct KeymapDecl {
key: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
mac: Option<String>,
/// Only with an `Escape` binding (API 1.10): when the command clears something.
#[serde(default, skip_serializing_if = "Option::is_none")]
when: Option<String>,
}
/// The one plain key a plugin may bind (API 1.10): in a focused editor, after the IDE's own uses of
/// Escape (popups, completion, rename, selection, extra carets, Vim) found nothing to do, like a
/// handler at the end of IDEA's EditorEscape chain.
const ESCAPE: &str = "Escape";
const MODIFIERS: [&str; 4] = ["Meta", "Ctrl", "Alt", "Shift"];
const NAMED_KEYS: [&str; 22] = [
"Enter",
@@ -262,9 +271,21 @@ pub fn validate_binding(binding: &str) -> Result<(), String> {
pub(super) fn keymap(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
let d: KeymapDecl = decode(KEYMAPS, decl)?;
declared_command(pkg, KEYMAPS, &d.command)?;
validate_binding(&d.key).map_err(|e| format!("contributes.keymaps: {e}"))?;
if let Some(m) = &d.mac {
validate_binding(m).map_err(|e| format!("contributes.keymaps: {e}"))?;
let escape = d.key == ESCAPE || d.mac.as_deref() == Some(ESCAPE);
if escape {
if d.key != ESCAPE || d.mac.as_deref().is_some_and(|m| m != ESCAPE) {
return Err("contributes.keymaps: an Escape binding is Escape on every platform".into());
}
pkg.manifest.needs_api("contributes.keymaps key = \"Escape\"", 10)?;
let when = d.when.as_deref().ok_or("contributes.keymaps: an Escape binding needs a `when` clause")?;
validate_when(when).map_err(|e| format!("contributes.keymaps: {e}"))?;
} else if d.when.is_some() {
return Err("contributes.keymaps: `when` is only for an Escape binding".into());
}
for binding in std::iter::once(&d.key).chain(&d.mac) {
if binding != ESCAPE {
validate_binding(binding).map_err(|e| format!("contributes.keymaps: {e}"))?;
}
}
Ok(UiDecl::new(d.command.clone(), d.key.clone(), json(&d)?))
}
@@ -1114,6 +1135,37 @@ mod tests {
}
}
#[test]
fn escape_bindings_need_api_1_10_and_a_when_clause() {
let pkg = |api: &str| {
let manifest = ide_extension::Manifest::parse(&format!(
"id='test'\nname='Test'\nversion='1.0.0'\nengines.openidea='{api}'\n[[contributes.commands]]\nid='clear'\ntitle='Clear'"
))
.unwrap();
Package::new(manifest, std::path::PathBuf::from("/unused"))
};
let check = |api: &str, decl: &str| keymap(&pkg(api), toml::from_str(decl).unwrap());
let escape = "command='clear'\nkey='Escape'\nwhen='plugin.test.active'";
let ok = check("^1.10", escape).unwrap();
assert_eq!(ok.json["when"], "plugin.test.active");
assert!(check("^1.10", &format!("{escape}\nmac='Escape'")).is_ok());
for (api, decl, error) in [
("^1.9", escape, "1.10"),
("^1.10", "command='clear'\nkey='Escape'", "when"),
("^1.10", "command='clear'\nkey='Escape'\nwhen='a &&'", "when"),
("^1.10", &format!("{escape}\nmac='Meta+K'") as &str, "every platform"),
("^1.10", "command='clear'\nkey='Ctrl+K'\nmac='Escape'\nwhen='x'", "every platform"),
("^1.10", "command='clear'\nkey='Ctrl+K'\nwhen='x'", "only for an Escape"),
("^1.10", "command='clear'\nkey='Enter'", "needs Ctrl"),
("^1.10", "command='clear'\nkey='Shift+Escape'", "needs Ctrl"),
] {
let err = check(api, decl).unwrap_err();
assert!(err.contains(error), "{api} {decl}\n→ {err}");
}
// Other bindings are unchanged.
assert!(check("^1.9", "command='clear'\nkey='Ctrl+Alt+C'").is_ok());
}
#[test]
fn bindings_need_a_modifier() {
for ok in ["Ctrl+Alt+C", "Meta+Shift+K", "F5", "Shift+F6", "Meta+K Meta+C", "Alt+Enter"] {
+1 -1
Переглянути файл
@@ -116,7 +116,7 @@ fn is_python_name(name: &str) -> bool {
/// Prefixes named by `conda env list`: `base * /opt/conda`, `myenv /opt/conda/envs/myenv`,
/// a `--prefix` env shown as a bare path, comment lines skipped (#2240).
fn conda_env_list_prefixes(output: &str) -> Vec<PathBuf> {
pub(crate) fn conda_env_list_prefixes(output: &str) -> Vec<PathBuf> {
output
.lines()
.map(|l| l.trim_start_matches(['#', '*', ' ']).trim_end())
+52 -17
Переглянути файл
@@ -26,7 +26,7 @@ pub enum VenvTool {
Uv,
/// `poetry env use <base>` in the project, then `poetry env info --path`.
Poetry,
/// `conda create -p <location> -y` (conda must be on PATH).
/// `conda create -n <name> -y` for a bare name, else `-p <location>` (conda must be on PATH).
Conda,
}
@@ -121,7 +121,8 @@ fn create_poetry_env(
.ok_or_else(|| IdeError::internal(format!("{} was not created", python.display())))
}
/// `conda create -p <location> -y` builds an environment at the requested prefix.
/// `conda create -n <name> -y` builds a named environment in conda's envs directory when
/// `location` is a bare name, `conda create -p <location> -y` one at that prefix otherwise.
/// `base` pins the Python version (`python=<major.minor>`) when it reports one, so the
/// created env matches the interpreter the user picked rather than conda's default.
fn create_conda_env(
@@ -131,7 +132,9 @@ fn create_conda_env(
cancel: &CancellationToken,
on_line: &dyn Fn(String),
) -> IdeResult<Sdk> {
if location.join("conda-meta").is_dir() {
// A bare name is a named environment in conda's own envs directory (`conda create -n`).
let name = conda_env_name(location);
if name.is_none() && location.join("conda-meta").is_dir() {
return Err(IdeError::new(
ide_core::error::ErrorKind::AlreadyExists,
format!("{} already contains a conda environment", location.display()),
@@ -139,28 +142,60 @@ fn create_conda_env(
}
let conda = which("conda")
.ok_or_else(|| IdeError::unavailable("conda is not installed (install it from https://docs.conda.io)"))?;
if let Some(parent) = location.parent() {
let prefixes = || {
query_in(&conda, &["env", "list"], None, &[], Duration::from_secs(15))
.map(|list| crate::discover::conda_env_list_prefixes(&list))
.unwrap_or_default()
};
if let Some(name) = name {
if prefixes().iter().any(|p| p.file_name().is_some_and(|n| n == name)) {
return Err(IdeError::new(
ide_core::error::ErrorKind::AlreadyExists,
format!("A conda environment named {name} already exists"),
));
}
} else if let Some(parent) = location.parent() {
std::fs::create_dir_all(parent)?;
}
let mut args = vec!["create".to_owned(), "-p".to_owned(), location.to_string_lossy().into_owned(), "-y".to_owned()];
if let Some(version) = query_in(base, &["--version"], None, &[], Duration::from_secs(15))
.and_then(|v| v.strip_prefix("Python ").map(str::to_owned))
{
let short = version.split('.').take(2).collect::<Vec<_>>().join(".");
if !short.is_empty() {
args.push(format!("python={short}"));
}
}
stream(&conda, &args, None, &[], cancel, on_line)?;
let version = query_in(base, &["--version"], None, &[], Duration::from_secs(15))
.and_then(|v| v.strip_prefix("Python ").map(str::to_owned));
stream(&conda, &conda_create_args(location, version.as_deref()), None, &[], cancel, on_line)?;
let prefix = match name {
Some(name) => prefixes()
.into_iter()
.find(|p| p.file_name().is_some_and(|n| n == name))
.ok_or_else(|| IdeError::internal(format!("conda did not report the environment {name}")))?,
None => location.to_path_buf(),
};
// Conda keeps `python.exe` at the prefix root on Windows, not under Scripts/.
let python = [location.join(exe("python")), location.join(bin_dir()).join(exe("python"))]
let python = [prefix.join(exe("python")), prefix.join(bin_dir()).join(exe("python"))]
.into_iter()
.find(|p| p.is_file())
.unwrap_or_else(|| location.join(bin_dir()).join(exe("python")));
crate::discover::python_sdk(&python, "conda", location.parent().and_then(Path::parent))
.unwrap_or_else(|| prefix.join(bin_dir()).join(exe("python")));
crate::discover::python_sdk(&python, "conda", prefix.parent().and_then(Path::parent))
.ok_or_else(|| IdeError::internal(format!("{} was not created", python.display())))
}
/// The environment name when `location` is a bare name rather than a path.
fn conda_env_name(location: &Path) -> Option<&str> {
let text = location.to_str()?;
(!text.is_empty() && !text.contains(['/', '\\', ':']) && text != "." && text != "..").then_some(text)
}
/// `conda create -n <name>` for a bare name, `-p <prefix>` for a path, with the base's `major.minor` Python.
pub(crate) fn conda_create_args(location: &Path, version: Option<&str>) -> Vec<String> {
let mut args = match conda_env_name(location) {
Some(name) => vec!["create".to_owned(), "-n".to_owned(), name.to_owned()],
None => vec!["create".to_owned(), "-p".to_owned(), location.to_string_lossy().into_owned()],
};
args.push("-y".to_owned());
let short = version.map(|v| v.split('.').take(2).collect::<Vec<_>>().join(".")).unwrap_or_default();
if !short.is_empty() {
args.push(format!("python={short}"));
}
args
}
/// Arguments of `base -m venv location`. `-I` (isolated mode) keeps the working
/// directory off `sys.path`: a project's `logging.py` or `typing.py` there would
/// otherwise shadow the standard library modules venv imports. (`-P` does just
+53
Переглянути файл
@@ -1319,6 +1319,59 @@ fn an_existing_conda_environment_is_not_recreated() {
assert!(err.message.contains("already contains a conda environment"), "{}", err.message);
}
#[test]
fn conda_creates_named_environments_in_its_envs_directory() {
use crate::python::conda_create_args;
use std::path::Path;
assert_eq!(conda_create_args(Path::new("demo"), Some("3.12.4")), ["create", "-n", "demo", "-y", "python=3.12"]);
assert_eq!(conda_create_args(Path::new("/work/app/.conda"), None), ["create", "-p", "/work/app/.conda", "-y"]);
for path in [r"C:\envs\demo", "envs/demo", "D:demo", ".."] {
assert_eq!(conda_create_args(Path::new(path), None)[1], "-p", "{path}");
}
}
#[test]
#[cfg(unix)]
fn a_named_conda_environment_is_found_where_conda_put_it() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("miniconda3");
let conda = tmp.path().join("conda");
// `create -n <name>` makes <root>/envs/<name> with a copy of the base python; `env list` names every env.
let python = tmp.path().join("python");
std::fs::write(&python, "#!/bin/sh\necho 'Python 3.12.1'\n").unwrap();
std::fs::set_permissions(&python, std::fs::Permissions::from_mode(0o755)).unwrap();
std::fs::write(
&conda,
format!(
"#!/bin/sh\nroot='{root}'\nif [ \"$1\" = env ]; then echo '# conda environments:'; echo \"base $root\"; \
for e in \"$root\"/envs/*/; do [ -d \"$e\" ] && echo \"$(basename \"$e\") ${{e%/}}\"; done; exit 0; fi\n\
[ \"$1 $2\" = 'create -n' ] || exit 2\nmkdir -p \"$root/envs/$3/bin\"\ncp '{python}' \"$root/envs/$3/bin/python\"\necho created\n",
root = root.display(),
python = python.display()
),
)
.unwrap();
std::fs::set_permissions(&conda, std::fs::Permissions::from_mode(0o755)).unwrap();
std::fs::create_dir_all(&root).unwrap();
let base = python.clone();
let which = |tool: &str| (tool == "conda").then(|| conda.clone());
let create = || {
crate::python::create_venv_with(
crate::python::VenvTool::Conda,
&base,
Path::new("ds"),
which,
&Default::default(),
&|_| {},
)
};
let sdk = create().unwrap();
assert_eq!(&*sdk.path, root.join("envs/ds/bin/python").as_path());
let again = create().unwrap_err();
assert!(again.message.contains("named ds already exists"), "{}", again.message);
}
#[test]
fn neutral_dir_is_fresh_and_empty() {
let a = crate::python::neutral_dir().unwrap();
+1 -1
Переглянути файл
@@ -67,7 +67,7 @@ On **Settings › Languages & Frameworks › Python Interpreter**, choose **Add
- **Virtualenv Environment**: `python -m venv` from the base interpreter you pick.
- **uv Environment**: `uv venv <location> --python <base>` (uv must be on `PATH`).
- **Poetry Environment**: `poetry env use <base>` in the project.
- **Conda Environment**: `conda create -p <location>`, with the base interpreter's Python version.
- **Conda Environment**: `conda create -n <name>` in conda's envs directory, with the chosen Python version.
You can also select an existing interpreter or environment folder. The new interpreter becomes the project interpreter.
+18
Переглянути файл
@@ -132,6 +132,24 @@ mac = "Meta+Alt+C" # optional; macOS uses `key` as written when it is mis
the user already uses that keystroke, or when the action already has a binding. The user
can rebind it in **Settings › Keymap**.
### Escape in the editor
API 1.10 lets a command answer a plain <kbd>Escape</kbd> in a focused editor, to clear
something the plugin shows there (a highlight, a mode):
```toml
[[contributes.keymaps]]
command = "clear-highlight"
key = "Escape"
when = "plugin.my-plugin.highlighting" # required; set it with set-context while there is something to clear
```
- It runs only after everything the IDE does with Escape in the editor found nothing to do:
closing a popup, completion or rename, collapsing a selection or extra carets, Vim.
- `when` is required and `key` (and `mac`, if given) must be `Escape`. Escape is the only plain
key a plugin can bind, and `when` is accepted only on such a binding.
- When several plugins' `when` hold, the most recently loaded one runs.
## Menus
```toml
+1 -1
Переглянути файл
@@ -104,7 +104,7 @@ Each contribution point is a table (`[contributes.settings]`) or an array of tab
| ------------------- | -------------------------------------------------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `commands` | `id`, `title`, `category?`, `when?`, `icon?` | to run them | [Commands and actions](/en/plugins/guides/commands) |
| `menus` | `menu`, `command`, `when?`, `view?`, `submenu?` | no | [Commands and actions](/en/plugins/guides/commands) |
| `keymaps` | `command`, `key`, `mac?` | no | [Commands and actions](/en/plugins/guides/commands) |
| `keymaps` | `command`, `key`, `mac?`, `when?` (Escape only) | no | [Commands and actions](/en/plugins/guides/commands) |
| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no | [Views and decorations](/en/plugins/guides/views) |
| `settings` | `schema` (a JSON file), or `pages` (API 1.3), `title?` | no | [Lifecycle and events](/en/plugins/lifecycle#settings) |
| `secrets` | `name`, `label`, `description?` | to use them | [Permissions and capabilities](/en/plugins/capabilities#secrets) |
+1 -1
Переглянути файл
@@ -67,7 +67,7 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
- **Virtualenv 环境**:用你选的基础解释器执行 `python -m venv`。
- **uv 环境**:执行 `uv venv <location> --python <base>`(`PATH` 上需要有 uv)。
- **Poetry 环境**:在项目中执行 `poetry env use <base>`。
- **Conda 环境**:执行 `conda create -p <location>`,Python 版本与基础解释器一致。
- **Conda 环境**:执行 `conda create -n <名称>`,环境建在 conda 的 envs 目录中,Python 版本为所选版本。
也可以直接选择已有的解释器或环境目录。新解释器会成为项目解释器。
+15
Переглянути файл
@@ -119,6 +119,21 @@ mac = "Meta+Alt+C" # 可选;缺省时 macOS 原样使用 `key`
- 插件快捷键只是默认值,优先级低于 IDE:按键映射预设或用户已经占用该按键、或该动作已有绑定时,
插件的快捷键会被丢弃。用户可以在 **设置 › 按键映射** 中重新绑定。
### 编辑器中的 Escape
API 1.10 起,命令可以响应焦点编辑器中单独按下的 <kbd>Escape</kbd>,用来清除插件在编辑器里显示的内容(高亮、某种模式):
```toml
[[contributes.keymaps]]
command = "clear-highlight"
key = "Escape"
when = "plugin.my-plugin.highlighting" # 必填;有内容可清除时用 set-context 设置
```
- 只有 IDE 在编辑器里对 Escape 的处理都没有生效时才会执行:关闭弹窗、补全或重命名,收起选区或多余的光标,Vim。
- 必须写 `when`,且 `key`(以及给出的 `mac`)必须是 `Escape`。Escape 是插件唯一能绑定的单独按键,`when` 也只用于这种绑定。
- 多个插件的 `when` 同时成立时,执行最后加载的那个插件的命令。
## 菜单
```toml
+1 -1
Переглянути файл
@@ -104,7 +104,7 @@ optional = ["net:api.openai.com", "secrets"]
| ------------------- | ---------------------------------------------------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `commands` | `id`、`title`、`category?`、`when?`、`icon?` | 执行时需要 | [命令与动作](/zh/plugins/guides/commands) |
| `menus` | `menu`、`command`、`when?`、`view?`、`submenu?` | 否 | [命令与动作](/zh/plugins/guides/commands) |
| `keymaps` | `command`、`key`、`mac?` | 否 | [命令与动作](/zh/plugins/guides/commands) |
| `keymaps` | `command`、`key`、`mac?`、`when?`(仅 Escape) | 否 | [命令与动作](/zh/plugins/guides/commands) |
| `statusBar` | `id`、`text`、`tooltip?`、`command?`、`align?`、`priority?` | 否 | [视图与装饰](/zh/plugins/guides/views) |
| `settings` | `schema`(JSON 文件)或 `pages`(API 1.3)、`title?` | 否 | [生命周期与事件](/zh/plugins/lifecycle) |
| `secrets` | `name`、`label`、`description?` | 使用时需要 | [权限与能力](/zh/plugins/capabilities) |
+5 -1
Переглянути файл
@@ -150,7 +150,7 @@ work), but 0.1 code no longer runs: rebuild it against the 1.0 SDK.
| `providers` | `kinds`, `languages` (editor providers, see _Providers_) | yes |
| `secrets` | `name`, `label`, `description?` (see _Network_) | to use them |
| `menus` | `menu` (`editor.context`, `projectView.context`, `editorTab.context`, `viewItem.context`, `tools`, `commit.message`; API 1.4: `editor.title`, `mainToolbar`, `problems.context`, `searchResults.context`), `view?`, `command`, `when?` | no |
| `keymaps` | `command`, `key`, `mac?` (`Ctrl+Alt+C`; a chord: `Meta+K Meta+C`) | no |
| `keymaps` | `command`, `key`, `mac?` (`Ctrl+Alt+C`; a chord: `Meta+K Meta+C`); `key = "Escape"` with a required `when` (API 1.10) runs after the editor's own Escape handling | no |
| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no |
| `settings` | `schema` (JSON file) or `pages` (API 1.3), `title?` — see _Settings_ | no |
| `views` | `id`, `title`, `icon?` (an icon name or a package SVG), `location` (`left`, `right`, `bottom`, `services`), `web?` (_Web views_), `group?`, `when?` (API 1.3) | without `web` |
@@ -443,6 +443,10 @@ matching SDK. Released 1.9 plugins keep working. New in 1.10:
`build.dependencies`) returns the Maven / Gradle graph the Dependency Analyzer
has, as a flat list with conflict and omission status, behind the low-risk
`build.read` capability. No build tool runs. See _Build dependency graph_.
- **Escape in the editor.** `[[contributes.keymaps]]` takes `key = "Escape"` with a
required `when`: the command runs on a plain Escape in a focused editor once the
IDE's own Escape handling (popups, completion, rename, selection, extra carets,
Vim) found nothing to do.
### API 1.9
+1 -1
Переглянути файл
@@ -11531,7 +11531,7 @@ export type VenvTool =
"uv" |
/** `poetry env use <base>` in the project, then `poetry env info --path`. */
"poetry" |
/** `conda create -p <location> -y` (conda must be on PATH). */
/** `conda create -n <name> -y` for a bare name, else `-p <location>` (conda must be on PATH). */
"conda";
/** What a view or custom editor shows. */
+55
Переглянути файл
@@ -0,0 +1,55 @@
import { EditorSelection, EditorState } from "@codemirror/state";
import { EditorView, keymap, runScopeHandlers } from "@codemirror/view";
import { defaultKeymap } from "@codemirror/commands";
import { afterEach, describe, expect, it, vi } from "vitest";
import { registerAction } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { addEscapeBinding, escapeAction, escapeBindings } from "./escapeBindings";
const off: (() => void)[] = [];
afterEach(() => {
off.splice(0).forEach((dispose) => dispose());
setContext("plugin.scope.active", false);
});
const escape = (view: EditorView) =>
runScopeHandlers(view, new KeyboardEvent("keydown", { key: "Escape", keyCode: 27 }), "editor");
describe("plugin Escape bindings", () => {
it("run only after the editor's own Escape handling found nothing to do", () => {
const run = vi.fn();
off.push(registerAction({ id: "plugin.scope.clear", title: "Clear", run }));
off.push(addEscapeBinding("plugin.scope.clear", "plugin.scope.active"));
const view = new EditorView({
state: EditorState.create({
doc: "one two",
selection: EditorSelection.create([EditorSelection.cursor(0), EditorSelection.cursor(4)]),
extensions: [EditorState.allowMultipleSelections.of(true), escapeBindings, keymap.of(defaultKeymap)],
}),
});
setContext("plugin.scope.active", true);
// Extra carets first: Escape keeps the main one, the plugin is not asked.
expect(escape(view)).toBe(true);
expect(view.state.selection.ranges).toHaveLength(1);
expect(run).not.toHaveBeenCalled();
expect(escape(view)).toBe(true);
expect(run).toHaveBeenCalledTimes(1);
// Its `when` is false: Escape is left to whatever else handles it.
setContext("plugin.scope.active", false);
expect(escape(view)).toBe(false);
expect(run).toHaveBeenCalledTimes(1);
view.destroy();
});
it("prefers the latest binding whose when holds and skips missing actions", () => {
off.push(registerAction({ id: "plugin.a.clear", title: "A", run: () => {} }));
off.push(registerAction({ id: "plugin.b.clear", title: "B", run: () => {} }));
off.push(addEscapeBinding("plugin.a.clear", "plugin.scope.active"));
const b = addEscapeBinding("plugin.b.clear", "plugin.scope.active");
off.push(addEscapeBinding("plugin.gone.clear", "plugin.scope.active"));
setContext("plugin.scope.active", true);
expect(escapeAction()).toBe("plugin.b.clear");
b();
expect(escapeAction()).toBe("plugin.a.clear");
});
});
+50
Переглянути файл
@@ -0,0 +1,50 @@
/**
* Plugin Escape bindings (`[[contributes.keymaps]] key = "Escape"` with `when`, API 1.10): run in
* a focused editor only after everything the IDE does with Escape there (popups, completion,
* rename, selection, extra carets, Vim) found nothing to do — the lowest-precedence Escape key,
* like a handler at the end of IDEA's EditorEscape chain. The first binding whose `when` holds
* runs; a later plugin's binding is tried first.
*/
import { Prec } from "@codemirror/state";
import { keymap } from "@codemirror/view";
import { executeAction, getAction } from "@/platform/actions";
import { evaluateWhen } from "@/platform/context";
interface EscapeBinding {
action: string;
when: string;
}
const bindings: EscapeBinding[] = [];
export function addEscapeBinding(action: string, when: string): () => void {
const binding = { action, when };
bindings.push(binding);
return () => {
const i = bindings.indexOf(binding);
if (i >= 0) bindings.splice(i, 1);
};
}
/** The action a plain Escape in an editor runs now, if any. */
export function escapeAction(): string | null {
for (let i = bindings.length - 1; i >= 0; i--) {
const { action, when } = bindings[i]!;
if (getAction(action) && evaluateWhen(when)) return action;
}
return null;
}
export const escapeBindings = Prec.lowest(
keymap.of([
{
key: "Escape",
run: () => {
const action = escapeAction();
if (!action) return false;
void executeAction(action);
return true;
},
},
]),
);
+10 -3
Переглянути файл
@@ -43,6 +43,7 @@ import { usePlugins } from "./store";
import { pluginActionId } from "./points";
import { defineUiPoint } from "./projection";
import { declareStatusItem } from "./runtimeUi";
import { addEscapeBinding, escapeBindings } from "./escapeBindings";
import { registerWindowView } from "./views/viewWindows";
import {
CUSTOM_EDITOR_KIND,
@@ -261,6 +262,8 @@ interface KeymapDecl {
command: string;
key: string;
mac?: string | null;
/** With an Escape binding (API 1.10). */
when?: string | null;
}
// --- status bar -------------------------------------------------------------------
@@ -443,9 +446,12 @@ export function defineViewUiPoints(): () => void {
defineUiPoint<KeymapDecl>("keymaps", {
title: "Shortcuts",
project: ({ pluginId, decl }) =>
registerExtensionBindings(pluginActionId(pluginId, decl.command), [
isMacHost() ? (decl.mac ?? decl.key) : decl.key,
]),
// Escape (only ever with `when`) is the editor's last Escape handler, not a shortcut.
decl.key === "Escape" && decl.when
? addEscapeBinding(pluginActionId(pluginId, decl.command), decl.when)
: registerExtensionBindings(pluginActionId(pluginId, decl.command), [
isMacHost() ? (decl.mac ?? decl.key) : decl.key,
]),
}),
defineUiPoint<StatusDecl>("statusBar", {
title: "Status Bar Items",
@@ -494,6 +500,7 @@ export function defineViewUiPoints(): () => void {
},
}),
registerEditorContribution({ id: "plugins.editorPanels", extensions: () => editorPanelUpdates }),
registerEditorContribution({ id: "plugins.escapeBindings", extensions: () => escapeBindings }),
defineUiPoint<EditorPanelDecl>("editorPanels", {
title: "Editor Panels",
project: ({ pluginId, decl }) => projectEditorPanel(pluginId, decl),
+15 -4
Переглянути файл
@@ -94,21 +94,32 @@ describe("Add Python Interpreter", () => {
mocks.createVenv.mockImplementation(() => new Promise((r) => (finish = r)));
open();
await waitFor(() => expect(screen.getByRole("button", { name: "Base interpreter" })).toBeInTheDocument());
for (const [label, tool] of [
["uv Environment", "uv"],
["Conda Environment", "conda"],
// Conda asks for a name (the project's by default) and keeps the env in its envs directory.
for (const [label, tool, target] of [
["uv Environment", "uv", "/project/.venv"],
["Conda Environment", "conda", "project"],
] as const) {
fireEvent.click(screen.getByRole("button", { name: label }));
fireEvent.click(screen.getByRole("button", { name: "OK" }));
expect(mocks.createVenv).toHaveBeenLastCalledWith(
tool,
"/usr/bin/python3",
"/project/.venv",
target,
expect.anything(),
expect.anything(),
);
await act(async () => finish(ok(VENV)));
}
fireEvent.change(screen.getByLabelText("Name:"), { target: { value: " ds " } });
fireEvent.click(screen.getByRole("button", { name: "OK" }));
expect(mocks.createVenv).toHaveBeenLastCalledWith(
"conda",
"/usr/bin/python3",
"ds",
expect.anything(),
expect.anything(),
);
await act(async () => finish(ok(VENV)));
fireEvent.click(screen.getByRole("button", { name: "Poetry Environment" }));
await waitFor(() => expect(screen.getByLabelText("Location:")).toBeDisabled());
fireEvent.click(screen.getByRole("button", { name: "OK" }));
+20
Переглянути файл
@@ -34,6 +34,7 @@ vi.mock("@/workbench/contributions", () => ({
}));
import { isStatusWidgetAvailable } from "@/workbench/statusBarWidgets";
import { activatePythonStatus, interpreterChoices, isPythonPath, nearMember } from "../languages/PythonStatus";
import { rememberSdk, useSdks } from "../languages/api";
let dispose: () => void;
beforeEach(() => {
@@ -50,6 +51,7 @@ beforeEach(() => {
afterEach(() => {
cleanup();
dispose();
useSdks.setState({ byKind: {} });
});
const mount = () => {
@@ -210,6 +212,24 @@ describe("Python interpreter status", () => {
await act(async () => finish([{ path: "/old/python", name: "Python 3.12" } as Sdk]));
expect(screen.queryByRole("button")).toBeNull();
});
it("picks up an environment created outside the project", async () => {
vi.useFakeTimers({ shouldAdvanceTime: true });
try {
const python = "C:\\Users\\me\\miniconda3\\envs\\demo\\python.exe";
useProject.setState({ settings: { languages: { python: { interpreter: python } } } as never });
mocks.files.mockResolvedValue([{ path: "/project/main.py" }]);
mount();
await screen.findByRole("button", { name: "Python Interpreter: Invalid interpreter" });
// conda creates the environment in its envs directory, the configured path stays the same.
mocks.effective.mockResolvedValue(python);
act(() => rememberSdk("python", { path: python, name: "Python 3.12 (demo)", source: "conda" } as Sdk));
await act(() => vi.advanceTimersByTimeAsync(400));
await screen.findByRole("button", { name: "Python Interpreter: Python 3.12 (demo)" });
expect(mocks.detect).toHaveBeenCalledTimes(2);
} finally {
vi.useRealTimers();
}
});
it("opens the Python page for both settings entries", async () => {
const run = vi.fn();
const off = registerAction({ id: "file.settings", title: "Settings…", run });
+15
Переглянути файл
@@ -0,0 +1,15 @@
import { describe, expect, it } from "vitest";
import { terminalLine } from "../languages/api";
describe("terminalLine", () => {
it.each([
["Solving environment: -\b\\\b|\b/\bdone", "Solving environment: done"],
["Downloading 10%\rDownloading 55%\rDownloading 100%", "Downloading 100%"],
["Collecting pip\r\n", "Collecting pip"],
["\x1b[32mSuccessfully installed\x1b[0m six", "Successfully installed six"],
["\x1b]0;conda\x07Preparing transaction", "Preparing transaction"],
["progress 99%\rdone", "doneress 99%"],
["\tindented\x07", "\tindented"],
])("renders %j as %j", (raw, line) => expect(terminalLine(raw)).toBe(line));
it.each(["", "\b\b", "\x1b[2K\r", " "])("drops %j", (raw) => expect(terminalLine(raw)).toBeNull());
});
+44 -26
Переглянути файл
@@ -37,6 +37,8 @@ export function AddInterpreterDialog({
const bases = useMemo(() => list.filter((s) => s.source !== "venv"), [list]);
const [base, setBase] = useState<string | null>(null);
const [location, setLocation] = useState(`${root}/.venv`);
// Conda keeps named environments in its own envs directory, so only a name is asked for.
const [envName, setEnvName] = useState(() => root.replaceAll("\\", "/").split("/").filter(Boolean).at(-1) ?? "env");
const [existing, setExisting] = useState<string | null>(null);
const [browsed, setBrowsed] = useState<Sdk[]>([]);
const [busy, setBusy] = useState<{ cancel: () => void } | null>(null);
@@ -92,6 +94,7 @@ export function AddInterpreterDialog({
});
};
const target = (kind === "conda" ? envName : location).trim();
const ok = () => {
if (busy) return;
setError(null);
@@ -103,9 +106,9 @@ export function AddInterpreterDialog({
});
return;
}
if (!baseValue || !location.trim()) return;
if (!baseValue || !target) return;
setLog([]);
const job = createVenv(kind, baseValue, location.trim(), (line) => setLog((l) => [...l.slice(-200), line]));
const job = createVenv(kind, baseValue, target, (line) => setLog((l) => [...l.slice(-200), line]));
setBusy({ cancel: job.cancel });
job.promise
.then((sdk) => {
@@ -116,11 +119,11 @@ export function AddInterpreterDialog({
.finally(() => setBusy(null));
};
const canOk = !busy && (mode === "new" ? !!baseValue && !!location.trim() : !!existing?.trim());
const canOk = !busy && (mode === "new" ? !!baseValue && !!target : !!existing?.trim());
const note = {
venv: tx("Runs “<base> -m venv <location>”; the new interpreter becomes the project interpreter."),
conda: tx(
"Runs “conda create -p <location> python=<version>”: a new environment with only Python in it; the new interpreter becomes the project interpreter.",
"Runs “conda create -n <name> python=<version>”: a new environment with only Python in it, in conda's envs directory; the new interpreter becomes the project interpreter.",
),
uv: tx("Runs “uv venv <location> --python <base>”; the new interpreter becomes the project interpreter."),
poetry: tx(
@@ -191,28 +194,43 @@ export function AddInterpreterDialog({
</div>
{mode === "new" ? (
<>
<label htmlFor={ids.location}>
<T>Location:</T>
</label>
<div className={styles.pathRow}>
<Input
id={ids.location}
className={styles.pathInput}
value={location}
onChange={(e) => setLocation(e.target.value)}
disabled={kind === "poetry"}
/>
<IconButton
icon="folder-open"
size="small"
title="Browse…"
disabled={kind === "poetry"}
onClick={async () => {
const p = await choosePath({ directory: true, title: "Virtualenv Location", defaultPath: root });
if (p) setLocation(p);
}}
/>
</div>
{kind === "conda" ? (
<>
<label htmlFor={ids.location}>
<T>Name:</T>
</label>
<Input id={ids.location} value={envName} onChange={(e) => setEnvName(e.target.value)} />
</>
) : (
<>
<label htmlFor={ids.location}>
<T>Location:</T>
</label>
<div className={styles.pathRow}>
<Input
id={ids.location}
className={styles.pathInput}
value={location}
onChange={(e) => setLocation(e.target.value)}
disabled={kind === "poetry"}
/>
<IconButton
icon="folder-open"
size="small"
title="Browse…"
disabled={kind === "poetry"}
onClick={async () => {
const p = await choosePath({
directory: true,
title: "Virtualenv Location",
defaultPath: root,
});
if (p) setLocation(p);
}}
/>
</div>
</>
)}
<label htmlFor={ids.base}>{kind === "conda" ? <T>Python version:</T> : <T>Base interpreter:</T>}</label>
<div className={styles.pathRow}>
<Select
+12 -2
Переглянути файл
@@ -8,7 +8,7 @@ import { notifications, registerStatusItem } from "@/workbench/contributions";
import { useEditorRegistry } from "@/editor/api";
import { BarButton, Menu, type MenuItem } from "@/ui";
import { Icon } from "@/ui/icons";
import { effectivePython, interpreterTarget, targetChoices, type Sdk } from "./api";
import { effectivePython, interpreterTarget, targetChoices, useSdks, type Sdk } from "./api";
import { tildify } from "./components";
import { validateRunTargets } from "@/platform/remoteSettings";
import { interpreterIcon, interpreterPathKey } from "./interpreters";
@@ -117,7 +117,10 @@ function PythonStatus() {
visible || configured
? await Promise.all([
effectivePython(nearMember(members, active)),
(detected ??= call(commands.sdkDetect("python"))),
(detected ??= call(commands.sdkDetect("python"))).then((found) => [
...(useSdks.getState().byKind.python ?? []),
...found,
]),
])
: [null, [] as Sdk[]];
if (live && sequence === request) usePopup.setState({ status: { root, configured, visible, python, sdks } });
@@ -147,6 +150,13 @@ function PythonStatus() {
detected = undefined;
schedule();
}),
// An environment created or added in Settings may live outside the project (conda's
// envs directory), so no file event announces it; the configured path may not change.
useSdks.subscribe((s, prev) => {
if (s.byKind.python === prev.byKind.python) return;
detected = undefined;
schedule();
}),
];
return () => {
live = false;
+27 -1
Переглянути файл
@@ -85,13 +85,39 @@ export interface Streamed<T> {
cancel: () => void;
}
/**
* A line of tool output as a terminal shows it: backspaces erase (conda's `-\|/` spinner),
* a carriage return starts the line over (pip's progress bar), colour and other control
* sequences go. Null when nothing visible is left.
*/
export function terminalLine(raw: string): string | null {
// eslint-disable-next-line no-control-regex
const plain = raw.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]/g, "");
let line = "";
for (const segment of plain.split("\r")) {
if (!segment) continue;
let text = "";
for (const ch of segment) {
if (ch === "\b") text = text.slice(0, -1);
// eslint-disable-next-line no-control-regex
else if (ch === "\t" || !/[\x00-\x1f\x7f]/.test(ch)) text += ch;
}
// A carriage return overwrites from the line start; the last non-empty rewrite wins.
if (text.trim()) line = text.length >= line.length ? text : text + line.slice(text.length);
}
return line.trim() ? line.trimEnd() : null;
}
function streamed<T>(
run: (request: ReturnType<typeof nextRequestId>, ch: Channel<string>) => Promise<T>,
onLine: (line: string) => void,
): Streamed<T> {
const request = nextRequestId();
const channel = new Channel<string>();
channel.onmessage = onLine;
channel.onmessage = (raw) => {
const line = terminalLine(raw);
if (line !== null) onLine(line);
};
return { promise: run(request, channel), cancel: () => void commands.cancelRequest(request) };
}
+4 -5
Переглянути файл
@@ -366,11 +366,10 @@ function GroupTabs({ group }: { group: string }) {
const status = session?.status;
const dead = status === "exited" || status === "error";
// Running / done marker (#2233): a command at work spins, a finished one
// shows a filled dot, an idle shell at the prompt shows none. A program that
// reports its own progress (OSC 9;4) decides for itself (#3831): an
// interactive agent CLI is one long command to the shell, and it clears the
// report while it waits for input between turns.
const busy = status === "starting" || (!!session?.commandRunning && session.progress !== "cleared");
// shows a filled dot, an idle shell at the prompt shows none. Nor does a
// program waiting for input, such as an agent CLI between turns (#3831):
// by its own progress report (OSC 9;4), else by whether it keeps drawing.
const busy = !!session?.working || status === "starting";
const mark = busy ? (
<Spinner size={10} variant="spokes" label="Running" />
) : dead ? (
+260
Переглянути файл
@@ -0,0 +1,260 @@
/**
* The tab's running marker (#3831): a plain command spins from start to end;
* an interactive program (an agent CLI, a REPL, an editor) spins only while it
* keeps producing output, not while it waits for input.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { DENSE_MS, ECHO_MS, OutputActivity, QUIET_MS, SUSTAIN_MS } from "./activity";
import { TerminalSession } from "./session";
const ipc = vi.hoisted(() => ({
call: vi.fn(async (v: unknown) => v),
commands: { termSpawn: vi.fn(), termKill: vi.fn(), termResize: vi.fn(), termIsBusy: vi.fn(), termWrite: vi.fn() },
}));
vi.mock("@/platform/ipc", () => ({ call: ipc.call, commands: ipc.commands, isTauri: () => true }));
vi.mock("@tauri-apps/api/core", async (importOriginal) => ({
...(await importOriginal<object>()),
Channel: class {
onmessage: ((chunk: string) => void) | null = null;
},
}));
describe("output activity", () => {
/** Output every `step` ms over `span` ms, starting at `from`. */
const stream = (a: OutputActivity, from: number, span: number, step = 100) => {
for (let t = from; t <= from + span; t += step) a.output(t);
return from + span;
};
it("is at work once output is sustained, until it has been quiet", () => {
const a = new OutputActivity();
expect(a.active(0)).toBe(false);
a.output(1000);
expect(a.active(1000)).toBe(false);
const end = stream(a, 1000, SUSTAIN_MS);
expect(a.active(end)).toBe(true);
expect(a.active(end + QUIET_MS)).toBe(true);
expect(a.active(end + QUIET_MS + 1)).toBe(false);
expect(a.quietAt).toBe(end + QUIET_MS);
});
it.each([
["one redraw (a resize, a status line)", [5000]],
["a burst shorter than the threshold", [5000, 5100, 5200]],
["separate redraws", [5000, 5000 + QUIET_MS + 1, 5000 + 2 * (QUIET_MS + 1)]],
["two redraws a moment apart", [5000, 5000 + SUSTAIN_MS + 100]],
["a clock ticking every second", Array.from({ length: 30 }, (_, i) => 5000 + i * 1000)],
["a monitor refreshing every 1.5 s", Array.from({ length: 30 }, (_, i) => 5000 + i * 1500)],
["output just too sparse", Array.from({ length: 30 }, (_, i) => 5000 + i * (DENSE_MS + 1))],
])("ignores %s", (_, times) => {
const a = new OutputActivity();
for (const t of times) {
a.output(t);
expect(a.active(t)).toBe(false);
}
});
it.each([
["at once", 10],
["late, over a slow connection", ECHO_MS - 1],
])("does not take the echo of typing for work when it arrives %s", (_, delay) => {
const a = new OutputActivity();
for (let t = 0; t < 5000; t += 200) {
a.input(t);
a.output(t + delay);
expect(a.active(t + delay)).toBe(false);
}
});
it("keeps working while the user types into a busy program", () => {
const a = new OutputActivity();
stream(a, 0, 2000);
// A follow-up typed for far longer than the quiet time, the program still redrawing.
for (let t = 2000; t < 2000 + 4 * QUIET_MS; t += 100) {
if (t % 200 === 0) a.input(t);
a.output(t + 10);
expect(a.active(t + 10)).toBe(true);
}
});
it("keeps working on an elapsed-seconds counter alone", () => {
const a = new OutputActivity();
let t = stream(a, 0, 2000);
for (let i = 0; i < 20; i++) {
t += 1000;
a.output(t);
expect(a.active(t)).toBe(true);
}
});
it("starts over after a reset", () => {
const a = new OutputActivity();
const end = stream(a, 0, 2000);
a.reset();
expect(a.active(end)).toBe(false);
});
});
describe("the session's working state", () => {
let session: TerminalSession;
beforeEach(() => {
vi.useFakeTimers();
session = new TerminalSession({ key: "k", cwd: "/repo", onChange() {}, onFocus() {} });
});
afterEach(() => {
session.dispose();
vi.useRealTimers();
vi.clearAllMocks();
});
/** Writes `data`, then lets `ms` pass. */
const feed = async (data: string, ms = 0) => {
const written = new Promise<void>((resolve) => session.term.write(data, resolve));
await vi.advanceTimersByTimeAsync(ms);
await written;
};
/** A program redrawing every 100 ms for `ms`. */
const redraw = async (ms: number) => {
for (let t = 0; t < ms; t += 100) await feed("\r\x1b[K* Working", 100);
};
const C = "\x1b]133;C\x07";
const D = "\x1b]133;D;0\x07";
const PASTE_ON = "\x1b[?2004h";
const PASTE_OFF = "\x1b[?2004l";
it("is idle at the prompt, even while the prompt redraws", async () => {
await feed(`${D}${PASTE_ON}$ `);
await redraw(1000);
expect(session.state).toMatchObject({ commandRunning: false, working: false });
});
it("keeps a plain command working from start to end, with or without output", async () => {
await feed(`${PASTE_ON}$ sleep 30\r\n${PASTE_OFF}${C}`);
expect(session.state.working).toBe(true);
await feed("", 60_000);
expect(session.state.working).toBe(true);
await redraw(1000);
await feed("", 60_000);
expect(session.state.working).toBe(true);
await feed(`${D}${PASTE_ON}$ `);
expect(session.state).toMatchObject({ commandRunning: false, working: false });
});
it.each([
["an agent CLI (bracketed paste)", PASTE_ON, PASTE_OFF],
["a full-screen program (alternate screen)", "\x1b[?1049h", "\x1b[?1049l"],
])("follows the output of %s", async (_, enter, leave) => {
await feed(`${PASTE_OFF}${C}`);
expect(session.state.working).toBe(true);
// The program starts and draws its screen once, then waits for input.
await feed(`${enter}\x1b]0;Agent\x07> `, QUIET_MS + 10);
expect(session.state).toMatchObject({ commandRunning: true, working: false });
await feed("", 60_000);
expect(session.state.working).toBe(false);
// A turn: it redraws while it works, then falls silent.
await redraw(SUSTAIN_MS + 200);
expect(session.state.working).toBe(true);
await redraw(3000);
expect(session.state.working).toBe(true);
await feed("", QUIET_MS + 10);
expect(session.state).toMatchObject({ commandRunning: true, working: false });
// A lone redraw between turns is not work.
await feed("\r\x1b[K> ", QUIET_MS + 10);
expect(session.state.working).toBe(false);
await feed(`${leave}${D}`);
expect(session.state).toMatchObject({ commandRunning: false, working: false });
});
it("does not count the echo of what the user types into an idle program", async () => {
ipc.commands.termSpawn.mockImplementationOnce(async () => ({ id: 7, title: "zsh" }));
await session.start();
await feed(`${PASTE_OFF}${C}${PASTE_ON}> `, QUIET_MS + 10);
for (let i = 0; i < 20; i++) {
session.input("a");
await feed("a", 100);
}
expect(session.state.working).toBe(false);
});
it.each([
["the alternate screen", "\x1b[?1049h"],
["bracketed paste", PASTE_ON],
])("ignores %s left on by an earlier program", async (_, enter) => {
// Killed before it could restore the terminal; the shell's prompt returns.
await feed(`${C}${enter}`);
await feed(`${D}$ `);
await feed(C);
expect(session.state.working).toBe(true);
await feed("", 60_000);
expect(session.state.working).toBe(true);
});
it("starts over when a program run instead of a shell is restarted", async () => {
session.dispose();
session = new TerminalSession({
key: "k",
cwd: "/repo",
onChange() {},
onFocus() {},
command: { program: "tool", args: [] },
});
ipc.commands.termSpawn.mockImplementation(async () => ({ id: 9, title: "tool" }));
await session.start();
expect(session.state).toMatchObject({ commandRunning: true, working: true });
await feed(`${PASTE_ON}> `, QUIET_MS + 10);
expect(session.state.working).toBe(false);
session.exited(0);
await vi.advanceTimersByTimeAsync(100);
session.restart();
await vi.advanceTimersByTimeAsync(0);
expect(session.state).toMatchObject({ status: "running", commandRunning: true, working: true });
});
it("leaves no timer behind when disposed", async () => {
await feed(`${C}${PASTE_ON}> `);
await redraw(1000);
session.dispose();
expect(vi.getTimerCount()).toBe(0);
});
it("takes the program's own progress report over its output", async () => {
const PROGRESS = (state: number) => `\x1b]9;4;${state}\x07`;
// Interactive and silent, but it reports work in flight.
await feed(`${C}${PASTE_ON}> `, QUIET_MS + 10);
expect(session.state.working).toBe(false);
await feed(PROGRESS(3), 60_000);
expect(session.state.working).toBe(true);
// Still redrawing, but it reports being done.
await feed(PROGRESS(0));
await redraw(2000);
expect(session.state.working).toBe(false);
// The next command has reported nothing: its output counts again.
await feed(`${PASTE_OFF}${D}${C}`);
expect(session.state.working).toBe(true);
// A plain command that cleared its report is done, too.
await feed(PROGRESS(0));
expect(session.state.working).toBe(false);
});
it("stops when the session exits", async () => {
await feed(`${PASTE_OFF}${C}`);
expect(session.state.working).toBe(true);
session.exited(1);
expect(session.state.working).toBe(false);
});
it("reports each change once", async () => {
const onChange = vi.fn();
session.rebind({ onChange, onFocus() {} });
onChange.mockClear();
await feed(`${PASTE_OFF}${C}${PASTE_ON}> `, QUIET_MS + 10);
await redraw(3000);
await feed("", QUIET_MS + 10);
// Not once per write: the command starts, the program turns interactive, works, falls silent.
expect(onChange.mock.calls.map(([, s]) => (s as { working: boolean }).working)).toEqual([true, false, true, false]);
});
});
+48
Переглянути файл
@@ -0,0 +1,48 @@
/**
* Whether the program in a terminal is at work, judged from its output (#3831).
* An interactive program (an agent CLI, a REPL, an editor) is one long command
* to the shell, so the command marks say nothing about it: it redraws
* continuously while it works and falls silent while it waits for input.
*/
/** Output must keep coming this long to count: a single redraw (resize, focus, a status line) is not work. */
export const SUSTAIN_MS = 500;
/** "Keeps coming": no longer apart than this. A clock or a monitor refreshing every second is not work. */
export const DENSE_MS = 400;
/** Silence this long ends the work; an elapsed-seconds counter keeps it going. */
export const QUIET_MS = 1500;
/** Output this soon after a keystroke is its echo. */
export const ECHO_MS = 400;
export class OutputActivity {
private streakStart: number | null = null;
private lastOutput = 0;
private lastInput = Number.NEGATIVE_INFINITY;
input(now: number) {
this.lastInput = now;
}
output(now: number) {
// Typing into a program at work must not hide its output.
const active = this.active(now);
if (!active && now - this.lastInput < ECHO_MS) return;
if (this.streakStart === null || now - this.lastOutput > (active ? QUIET_MS : DENSE_MS)) this.streakStart = now;
this.lastOutput = now;
}
active(now: number): boolean {
return (
this.streakStart !== null && now - this.lastOutput <= QUIET_MS && this.lastOutput - this.streakStart >= SUSTAIN_MS
);
}
/** When `active` turns false unless more output arrives. */
get quietAt(): number {
return this.lastOutput + QUIET_MS;
}
reset() {
this.streakStart = null;
}
}
+71
Переглянути файл
@@ -14,6 +14,7 @@ import { Channel } from "@tauri-apps/api/core";
import { call, commands, isTauri, type TerminalId } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { editorService, notifications, registerFontZoomSurface } from "@/workbench/contributions";
import { OutputActivity } from "./activity";
import { fitScheduler, settledResize } from "./fit";
import { watchWindowsPty, windowsPty } from "./windowsPty";
import { installTerminalDrop } from "./drop";
@@ -72,6 +73,13 @@ export interface SessionSnapshot {
* view, so only its own report separates working from waiting for input.
*/
progress: "active" | "cleared" | null;
/**
* The running command is at work (#3831): as its progress report says; without
* one, always for a plain command, and for an interactive program (an agent
* CLI, a REPL, an editor) only while it keeps producing output, not while it
* waits for input.
*/
working: boolean;
/** Current directory (initial cwd, updated by OSC 7). */
cwd: string;
/**
@@ -114,6 +122,8 @@ export interface SessionOptions {
/** Mouse-tracking DEC private modes (X10, normal, button, any-event, encodings). */
const MOUSE_MODES = new Set([9, 1000, 1001, 1002, 1003, 1005, 1006, 1015, 1016]);
/** Bracketed paste and the alternate screen: DEC private modes of a program that reads the keyboard itself. */
const INPUT_MODES = new Set([47, 1047, 1049, 2004]);
const CLEAR_SCROLLBACK_MARKER = "\x1b]133;OpenIDEA;ClearScrollback\x07";
let audio: AudioContext | null = null;
@@ -257,6 +267,10 @@ export class TerminalSession {
private commandStartedAt: number | null = null;
/** Ctrl-C was typed while the current command ran: it was stopped, not finished. */
private commandInterrupted = false;
private readonly activity = new OutputActivity();
private activityTimer: ReturnType<typeof setTimeout> | null = null;
/** Input modes the running command asked for; see `interactive`. */
private readonly inputModes = new Set<number>();
/** Bumped on restart so late output from a previous PTY is ignored. */
private generation = 0;
/** WebKitGTK delivers one IME commit' worth of text more than once; see `ImeCommitGate`. */
@@ -283,6 +297,7 @@ export class TerminalSession {
appTitle: null,
commandRunning: false,
progress: null,
working: false,
cwd: opts.cwd,
unseenDone: false,
};
@@ -357,6 +372,10 @@ export class TerminalSession {
}),
this.term.onData((data) => this.fromTerminal(data)),
this.term.onBinary((data) => this.input(data)),
this.term.onWriteParsed(() => {
this.activity.output(Date.now());
this.syncWorking();
}),
this.term.onTitleChange((title) => this.update({ appTitle: title.trim() || null })),
// OSC 7: `file://host/path` — shells report their cwd so relative links resolve correctly.
this.term.parser.registerOscHandler(7, (data) => {
@@ -376,6 +395,7 @@ export class TerminalSession {
this.commandInterrupted = false;
// A new command in the tab: the previous completion has been seen, and
// the new program has not reported progress yet.
this.resetActivity();
this.update({ commandRunning: true, unseenDone: false, progress: null });
} else if (data === "D" || data.startsWith("D;")) {
const status = data.length > 2 ? Number.parseInt(data.slice(2), 10) : Number.NaN;
@@ -383,6 +403,7 @@ export class TerminalSession {
this.commandStartedAt = null;
const interrupted = this.commandInterrupted;
this.commandInterrupted = false;
this.resetActivity();
this.update({ commandRunning: false, progress: null });
// A D without a C (shell startup, a restored tab's first prompt) is
// not a command finishing.
@@ -419,6 +440,8 @@ export class TerminalSession {
if (!this.searchSelection && workflowSettings().terminal.copyOnSelection && this.term.hasSelection())
this.copySelection();
}),
this.term.parser.registerCsiHandler({ prefix: "?", final: "h" }, (params) => this.noteInputModes(params, true)),
this.term.parser.registerCsiHandler({ prefix: "?", final: "l" }, (params) => this.noteInputModes(params, false)),
// Mouse reporting off: ignore the application's requests to enable mouse tracking.
this.term.parser.registerCsiHandler({ prefix: "?", final: "h" }, (params) => {
if (workflowSettings().terminal.mouseReporting) return false;
@@ -543,9 +566,54 @@ export class TerminalSession {
private update(patch: Partial<SessionSnapshot>) {
this.snapshot = { ...this.snapshot, ...patch };
this.snapshot.working = this.isWorking();
this.opts.onChange(this.key, this.snapshot);
}
/**
* The running program takes input itself: it asked for bracketed paste or the
* alternate screen. Only its own requests count, not a mode an earlier program
* left on (one killed inside the alternate screen).
*/
private get interactive(): boolean {
return this.inputModes.size > 0;
}
private noteInputModes(params: (number | number[])[], on: boolean): boolean {
for (const p of params) {
const mode = Array.isArray(p) ? p[0] : p;
if (mode === undefined || !INPUT_MODES.has(mode)) continue;
if (on) this.inputModes.add(mode);
else this.inputModes.delete(mode);
}
return false;
}
/** A command starts or ends: what the previous one asked for and drew no longer counts. */
private resetActivity() {
this.inputModes.clear();
this.activity.reset();
}
private isWorking(): boolean {
const { status, commandRunning, progress } = this.snapshot;
if (!commandRunning || status === "exited" || status === "error") return false;
if (progress) return progress === "active";
return !this.interactive || this.activity.active(Date.now());
}
/** Re-judges `working` after output, and again once the output has been quiet long enough. */
private syncWorking() {
if (this.disposed) return;
if (this.activityTimer !== null) clearTimeout(this.activityTimer);
this.activityTimer = null;
const working = this.isWorking();
if (working !== this.snapshot.working) this.update({});
if (!this.snapshot.commandRunning || !this.interactive) return;
const wait = this.activity.quietAt - Date.now();
if (wait >= 0) this.activityTimer = setTimeout(() => this.syncWorking(), wait + 1);
}
private linksAt(y: number): ILink[] | undefined {
const line = this.term.buffer.active.getLine(y - 1);
if (!line) return undefined;
@@ -714,6 +782,7 @@ export class TerminalSession {
if (this.disposed || this.snapshot.status === "starting" || this.snapshot.status === "running") return;
const generation = ++this.generation;
this.outputTail = "";
this.resetActivity();
const custom = this.opts.command;
this.update({
status: "starting",
@@ -841,6 +910,7 @@ export class TerminalSession {
}
// Ctrl-C stops the running command: its D mark must not count as a completion (#3712).
if (this.snapshot.commandRunning && data.includes("\x03")) this.commandInterrupted = true;
this.activity.input(Date.now());
void call(commands.termWrite(this.ptyId, data)).catch((error) => {
notifications().notify({
level: "error",
@@ -971,6 +1041,7 @@ export class TerminalSession {
this.opts.command?.onExit?.(null, true);
this.fitter.cancel();
this.ptyResize.cancel();
if (this.activityTimer !== null) clearTimeout(this.activityTimer);
this.pendingInput = "";
this.resizeObserver?.disconnect();
this.host.removeEventListener("mousedown", this.onMiddleClick);
+1
Переглянути файл
@@ -443,6 +443,7 @@ describe("terminal tab titles", () => {
appTitle,
commandRunning,
progress: null,
working: commandRunning,
cwd: "/p",
unseenDone: false,
},
+2 -1
Переглянути файл
@@ -2327,5 +2327,6 @@
"When off, Settings opens as a dialog in the project window, which is faster": "When off, Settings opens as a dialog in the project window, which is faster",
"Run code inside the Java applications you start": "Run code inside the Java applications you start",
"Java agents of {list} were not added: they load only in local projects.": "Java agents of {list} were not added: they load only in local projects.",
"Java agent": "Java agent"
"Java agent": "Java agent",
"Runs “conda create -n <name> python=<version>”: a new environment with only Python in it, in conda's envs directory; the new interpreter becomes the project interpreter.": "Runs “conda create -n <name> python=<version>”: a new environment with only Python in it, in conda's envs directory; the new interpreter becomes the project interpreter."
}
+1 -1
Переглянути файл
@@ -5322,7 +5322,7 @@
"{count} modified action": "已修改 {count} 个操作",
"{count} modified actions": "已修改 {count} 个操作",
"Runs “<base> -m venv <location>”; the new interpreter becomes the project interpreter.": "运行“<base> -m venv <location>”;新的解释器将成为项目解释器。",
"Runs “conda create -p <location> python=<version>”: a new environment with only Python in it; the new interpreter becomes the project interpreter.": "运行“conda create -p <location> python=<version>”:新建一个只包含 Python 的环境;新的解释器将成为项目解释器。",
"Runs “conda create -n <name> python=<version>”: a new environment with only Python in it, in conda's envs directory; the new interpreter becomes the project interpreter.": "运行“conda create -n <name> python=<version>”:在 conda 的 envs 目录中新建一个只包含 Python 的环境;新的解释器将成为项目解释器。",
"Python version": "Python 版本",
"Python {short}": "Python {short}",
"Runs “poetry env use <base>” in the project; poetry keeps the environment under its own cache directory.": "在项目中运行“poetry env use <base>”;Poetry 会将环境保存在其自己的缓存目录下。",