Compare commits

...
Author SHA1 Message Date
Mr0Bread 5006e1934d fix(agents): confirm a Markdown code block copy with a check (#5488)
The Copy button in the top-right corner of a Markdown code block (agent replies) gave no sign that a click did anything: it copied silently and looked the same. After a successful copy it now shows a check in the success colour for two seconds and its label reads "Copied", then goes back to "Copy Code". Reply-level copy already behaves this way (`ReplyActions`).

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 01:41:31 +08:00
Mr0Bread 14d6d6892d fix(agents): skip code fences when titling a task from its prompt (#5486)
Starting an Agent Task with a pasted Markdown block named the tab "```text". The task title is the first non-empty line of the prompt (`title_of`), which for a pasted block is the opening code fence. The same title also names the worktree branch.
`title_of` now skips lines that open a code fence (``` or ~~~) and uses the first line after them.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 01:41:22 +08:00
Mr0Bread 080b7e80e7 perf(agents): stop re-rendering and rescanning the whole conversation for every streamed chunk (#5467)
While an agent streams, the visible session did work proportional to the whole conversation for every chunk: every earlier turn's reply and fold re-rendered, and the Composer re-read every tool output to rebuild the session assets. In a 170-turn conversation (2212 entries) that cost 12 ms per chunk in the stream and 7 ms in the composer; now it is 3 ms and 1 ms. Visible output, folding, turn numbers and reply actions are unchanged.
Root cause: the stream rebuilds its derived data for each chunk, and the props that carry it are new objects each time, so `memo` never held.
- `Entry:agent` (`session/messages.tsx`): `reply` (a fresh `ReplyTurn` from `replyTurns`) and `time` (a fresh `ReplyTimes` from `replyTimes`) for every earlier agent message.
- `TurnFold` (`session/ProcessRows.tsx`, rendered from `session/Stream.tsx`): a fresh `row`, the whole `entries` array, and fresh `children` elements. It was not memoized at all.
- `ProcessRun`: fresh `row` and `thinking` map each chunk.
- `extractSessionAssets` (`sessionAssetsModel.ts`, called from `SessionAssets.tsx`): re-parsed every tool entry's output each time `entries` changed.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 01:38:09 +08:00
Mr0Bread 92d94a7ac4 perf(ui): prefetch only the lazy views a window is likely to open (#5464)
After start-up, the workbench window loaded the code of every lazy view in the background, one chunk at a time, whether or not the user ever opened it: 122 extra chunks, +2.1 MB of JS and +3.0 MB of JS heap, plus ~300 ms of task time in the main window. `lazyComponent` / `lazyWhen` now take `{ prefetch: true }`, and `prefetchLazyComponents` loads only the components that set it. Everything else loads when it is first rendered, as it always could. Only the main workbench window prefetches (`mountWindowRoot(..., { prefetchLazy: true })`); auxiliary windows never did.
Opted in (what most sessions open early, where a blank first frame would show): Terminal tool window, Agents tool window + task and new-task editors, Commit and Git tool windows, the Settings dialog shell (not its pages), Search Everywhere / Find in Files / Recent files / File structure overlays, the markdown preview editor, the project switcher popup. Left on demand: all database, debugger, plugins, notebook, logcat, remote/deployment, github, python-console, web, build-tools, templates views, all settings pages (they already preload on page reveal via `preloadBuiltinPage`), edit-configurations, merge/compare/local-history editors, Run and Find tool windows (their stripes only appear on use, so the view mounts as it appears).

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 01:37:47 +08:00
Mr0Bread 518a62ea6c perf(agents): stop rendering and revealing a kept-alive session while its tab is hidden (#5462)
A kept-alive agent session tab (up to 5 per pane) that sits behind another tab kept rendering every streamed chunk like a visible one: the whole conversation re-rendered, the composer re-scanned all tool output (`extractSessionAssets`), and the reply's smooth-text reveal kept running its ~60 Hz `requestAnimationFrame` repaint. Up to 4 hidden tabs paid this on every chunk of a running task.
Now a hidden session stops reading conversation entries from the store (`useAgentsWhileShown` in `SessionEditor.tsx`) and the reveal is not live while hidden (`reveal.ts`). Shown again, it takes the latest entries in one render and paints unseen text whole instead of pacing it in. Visible tabs and docked sessions are unchanged.
```text
chunk -> store.entries
  visible tab:  TaskSession -> Stream, SessionComposer      (as before)
  hidden tab:   TaskSession keeps the entries it had, nothing re-renders

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 01:37:31 +08:00
Mr0Bread d16a87cf58 perf(vcs): stop polling for git process exit (#5459)
Every cancellable git read (`run_cancellable`, `run_bounded`, saved-credential transport, and GnuPG via `capture_command`) waited for the process to exit by calling `try_wait` and then sleeping a fixed 20 ms. A command that finishes in a few milliseconds therefore cost about 10 ms more on average than the same command through `wait_with_output`, and every git call made while opening or refreshing the Git tool window pays it. The wait now blocks on the output readers' completion (a channel that disconnects when both pipes reach EOF), so it wakes the moment the child closes its pipes, then polls `try_wait` with a 0.1 ms backoff capped at 20 ms for the reaping. Cancellation and output-limit checks still run at least every 20 ms, as before.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-24 01:37:12 +08:00
LU XIANGRUIandwildcatDownstairs f9fd1257c7 feat(python): show and edit an interpreter's sys.path (#5432)
Settings → Python → All Interpreters gets **Show Paths for Selected Interpreter** (toolbar and context menu). The dialog lists the interpreter's own `sys.path` (queried from the interpreter on a blocking thread, cancellable, with a reload button) and lets you add and remove folders outside the project. Until now there was no way to see `sys.path` or to put such a folder on the import path short of setting `PYTHONPATH` by hand in every run configuration.
Added folders are saved per interpreter in the global settings layer (`languages.python.interpreterPaths`, keyed by the interpreter's executable, like the interpreter list itself), so they apply to every project that uses the interpreter, as in PyCharm. They follow the interpreter that is actually used: basedpyright / Pyright get them as `extraPaths` for the interpreter that server analyses with, and run, debug, tests and the Python Console get them on `PYTHONPATH` for the interpreter the launch names (else the one of the project or workspace member it runs in), so Run and Debug of the same file agree. They are listed under External Libraries unless they are inside or around the project's own folders, which stay editable.
A folder that no longer exists is marked **Missing**, one `PYTHONPATH` cannot hold (not absolute, or with its separator in the name) is marked **Invalid**; neither is passed on. Duplicates and folders already on `sys.path` are not added. Removing an interpreter from the list drops its folders.
Not in this PR: removing the interpreter's own entries (PyCharm's excluded paths); ty, pyrefly, pylsp and notebook kernels don't get the folders. Docker / Compose run targets are not rows of this list, so they have no paths dialog.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 01:34:36 +08:00
LU XIANGRUIandwildcatDownstairs e57a709d19 feat(python): create and detect Pipenv environments (#5449)
"Add Python Interpreter" has a new **Pipenv Environment** type. It runs `pipenv --python <base>` in the project, which writes a `Pipfile` (importing `requirements.txt` if there is one) when the project has none. With **Install packages from Pipfile** checked, it then runs `pipenv install --dev`. The result becomes the project interpreter. If the project already has a Pipenv environment, it is reused and `--python` is not passed, because pipenv replaces an environment built on another Python without asking. When the versions differ, nothing is changed and the dialog says so. The project's Pipenv environment is also detected: it is listed as `Python 3.13 (Pipenv: <project>)` with the Pipfile icon, and it is the project interpreter when none is configured (after a `.venv` or pixi environment in the project, before the mise/asdf pin).
Until now Pipenv was only a run wrapper (`pipenv run`). Its environments were listed as plain virtualenvs named after their folder (`shop-Kpos5yRM`) and were never tied to their project. Detection does not start pipenv, which takes about a second. It looks for the `Pipfile` the way pipenv does, in the opened folder or one above it, and computes the folder name pipenv gives that project's environment: the folder name, `-`, and 8 characters of the URL-safe base64 SHA-256 of the `Pipfile` path. It looks for that name in `WORKON_HOME`, `~/.virtualenvs` and `$XDG_DATA_HOME/virtualenvs`, after the project's own `.venv`. An environment found elsewhere in the list is labelled as Pipenv's only if its `.project` names a folder with a `Pipfile` and its name matches. `ide-sdk` now depends on `sha2` and `base64`; both were already in `Cargo.lock`.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 01:28:27 +08:00
l0ng-ai abab90ca60 fix(maven): refresh stale SNAPSHOT sources on dependency reload (#5490)
After a SNAPSHOT dependency was republished and the project reloaded, navigating into it still showed the old sources: SNAPSHOT file names never change, the cached sources jar was reused as long as it existed, and open library editors kept their text. A sources jar older than its binary jar is now stale and replaced atomically; Maven reload waits for jdtls to finish importing, refreshes stale cached SNAPSHOT sources before reattaching archives, and refreshes open library editors. First-time source downloads still follow the Maven setting.
2026-11-24 01:09:14 +08:00
LU XIANGRUIandwildcatDownstairs 9d94b00911 feat(python): add type annotations from the inferred types (#5357)
basedpyright shows inferred types as inlay hints, and each hint carries the `textEdits` that insert it, including the import it needs (`from typing import Any`). The IDE dropped those edits, so an inferred type could not become an annotation. Inlay hints now keep `textEdits` over IPC, and Alt+Enter in Python offers PyCharm's:
- **Add type annotation ': int'** on an unannotated `name = value` assignment in a function or at module level (not in class bodies, where it would turn a dataclass/NamedTuple attribute into a field, nor for `global`/`nonlocal` names);
- **Add return type annotation '-> str'** on a function header;
- **Add type hints for function 'f'** on a function header: the return type plus the types of defaulted parameters (`limit: int = 10`), taken from hover and kept only when they name builtins, which need no import.
Annotations Python evaluates (signatures, module variables) use `X | Y` or `list[X]` only when `requires-python` allows them (3.10 / 3.9) or the file has `from __future__ import annotations`; a local variable's annotation is never evaluated. The intention asks the server for the hints itself, so it works with type hints turned off in Settings; a variable the server shows no hint for falls back to its hover type under the same builtin rule.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 00:40:35 +08:00
LU XIANGRUIandwildcatDownstairs cc1cc4cce5 feat(python): convert %-formatting and str.format() to f-strings (#5356)
Alt+Enter on a Python `%`-format expression said "No intentions available". It now offers PyCharm's **Convert to f-string literal** and **Replace with str.format() call**; on a `str.format()` call it offers **Convert to f-string literal**. Neither basedpyright nor Ruff offers these (Ruff's UP031/UP032 only report when a project enables pyupgrade rules, and the fix is not a quick fix).
`%` conversions `s r a d i u f e g x o` with flags, widths and precisions map to the equivalent format specs (`%5s` → `{x!s:>5}`, `%-8.3e` → `{x:<8.3e}`); `%d` keeps its truncation as `{int(x)}` unless the value is an int literal or `len()`/`int()`/`ord()` (`%05d` % `len(a)` → `{len(a):05d}`); `%(key)s` works with a dict literal; `%%` and literal braces are escaped, and `\N{NAME}` escapes are kept as they are. `.format()` fields support auto and manual numbering, keywords, `.attr` / `[0]` accessors, `!r` and specs. The conversion is not offered when it could change behaviour or produce invalid code: bytes, `*`/`**` arguments, `%c`, `*` widths, a precision on an integer conversion, nested format specs, a wrong argument count, an argument that would be dropped or evaluated twice, an argument containing the string's quote, a backslash or `#` (f-strings before Python 3.12), or, for `.format()`, a key that is a Python keyword. As in PyCharm, a single `%` operand that is not a tuple literal is taken as one value.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 00:30:27 +08:00
wangfeiandhapput 2478f67066 fix(workbench): keep project tab tint on hover (#5477)
Follow-up to #4481: hovering a coloured project tab made the custom colour disappear. The hover rule layered the opaque `--bg-hover` surface on top of the tint (`linear-gradient(var(--bg-hover), var(--bg-hover)), var(--tab-tint-mix)`), so while the pointer was over the tab only the plain grey hover surface remained.
The hover rule now mixes the project colour into the hover surface instead, mirroring how the selected rule mixes into `--bg-island`:
```css
.item[data-tinted]:hover {
  background: color-mix(in srgb, var(--project-color) 12%, var(--bg-hover));
}

Co-authored-by: happut <[email protected]>
2026-11-24 00:10:02 +08:00
zhzhsxandzhzhsx dc2924db17 fix(terminal): send the final size to a newly started PTY (#5473)
A new project's first terminal can end up with the wrong size. While the shell is starting, the terminal may resize, for example when the font finishes loading. That new size never reaches the shell. Full-screen programs such as vim then draw at the old width and the text looks broken. This fix sends the current size once the shell is ready.

Co-authored-by: zhzhsx <[email protected]>
2026-11-24 00:09:43 +08:00
l0ng-ai 348f4c2a2e fix(keymap): support mouse wheel shortcuts (#5483) 2026-11-23 23:58:16 +08:00
l0ng-ai 431b87c717 fix(remote): use the correct filesystem for file dialogs (#5479)
In an SSH or WSL window, Export Test Results passed a path picked in the desktop's Save dialog to the project host. Project-side pickers (Export Test Results, Save As, patch and Git dialogs, Maven/Gradle linking, scopes, coverage and Java sources, database source files, deployment destinations, tool and plugin paths) now browse the project host, with overwrite confirmation kept; flows whose files belong to the desktop (keymap and color scheme import/export, database and ACP imports, Clone) read and write through the desktop process. Follow-up to #5439.
2026-11-23 23:22:47 +08:00
l0ng-ai 3a53d13315 fix(editor): refresh Java inheritance markers after Maven import (#5478)
Interface methods could show no "is implemented" marker: the gutter cached the empty implementation results jdtls gave before the Maven import put the implementations on the classpath, and nothing invalidated them. When jdtls reports the project status after an import (generated sources attached first), the backend now emits an inheritance refresh next to the semantic-token refresh, and the gutter drops its cached markers and asks again. Covers implemented/overridden markers on interfaces, abstract classes and concrete overrides.
2026-11-23 23:20:57 +08:00
Mr0Bread 23f591289c perf(ipc): send binary command arguments as base64 instead of number arrays (#5436)
Pasting an image into a terminal or a Markdown file, or saving bytes from the UI, sent the data as a JSON array of numbers (3.6x the size), which Tauri and the remote server parse into a serde_json::Value first (~50x the bytes in memory: a 20 MB image took ~2.2 GB peak heap and 640 ms). Binary command arguments (fs_create_file_bytes, term_store_image) now travel as base64 text (IpcBytes): the same 20 MB takes ~112 MB and 32 ms. Native image drops reuse the base64 they already have.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 22:32:58 +08:00
l0ng-ai 8684e95778 fix(vcs): title git HTTPS credential prompts Username / Password instead of SSH (#5474) 2026-11-23 22:27:28 +08:00
Bert Verhelstandbertyhell 9d9e3f1c4f fix(java): don't reuse a launch snapshot copied while another build rewrote the outputs (#5420)
A Java launch that delegates to Maven could snapshot a dependency module's target/classes while an external mvn was rewriting it, then reuse that incomplete snapshot on every later launch (NoClassDefFoundError until the cache was cleared). A snapshot is now reused only while the live module outputs still match it (paths, sizes and modification times of the output tree, read from metadata only); output directories that appear after capture also invalidate it.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 22:24:59 +08:00
Bert Verhelstandbertyhell 5eff75cab5 fix(remote): keep scratches and generated requests on the host that writes them (#5439)
In a remote (SSH/WSL) window, Generate Request in HTTP Client failed with Permission denied: the scratches folder was resolved on the desktop and its path sent to the remote host. Scratches and generated HTTP requests now live in the data directory of the host that writes them (created on demand, rechecked on later calls), and remote IPC routing is installed before session listeners run.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 22:24:23 +08:00
185 changed files with 6186 additions and 755 deletions

No files matched your search

Generated
+3
View File
@@ -4253,6 +4253,7 @@ dependencies = [
name = "ide-core"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"dunce",
"encoding_rs",
"libc",
@@ -4846,6 +4847,7 @@ dependencies = [
name = "ide-sdk"
version = "0.1.50"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
"dunce",
"flate2",
@@ -4857,6 +4859,7 @@ dependencies = [
"quick-xml 0.42.0",
"serde",
"serde_json",
"sha2 0.10.9",
"specta",
"tar",
"tempfile",
+4 -1
View File
@@ -4234,8 +4234,11 @@ fn file_uri(path: &Path) -> String {
out
}
/// The title of a task: the first line of the prompt that says something. A pasted Markdown
/// block opens with a code fence (```` ```text ````), which names no task.
fn title_of(prompt: &AgentPrompt) -> String {
let line = prompt.text.lines().map(str::trim).find(|l| !l.is_empty());
let is_fence = |l: &str| l.starts_with("```") || l.starts_with("~~~");
let line = prompt.text.lines().map(str::trim).find(|l| !l.is_empty() && !is_fence(l));
let line = match line {
Some(l) => l.to_owned(),
None => prompt.files.first().map(|f| file_name(&f.0)).unwrap_or_else(|| "Image".into()),
+2
View File
@@ -1731,6 +1731,8 @@ fn prompts_become_acp_content_blocks() {
assert_eq!(old["entries"][0]["attachments"], json!([]));
assert!(old["entries"][1].get("attachments").is_none());
assert_eq!(title_of(&AgentPrompt { files: p.files.clone(), ..AgentPrompt::default() }), "my file.rs");
let pasted = AgentPrompt { text: "```text\n\n ## Fix the tab title\n```".into(), ..AgentPrompt::default() };
assert_eq!(title_of(&pasted), "## Fix the tab title");
assert!(clean(text(" ")).is_none());
}
-2
View File
@@ -17,6 +17,4 @@ serde_json.workspace = true
specta.workspace = true
tracing.workspace = true
dirs.workspace = true
[dev-dependencies]
tempfile.workspace = true
+56 -8
View File
@@ -1008,12 +1008,7 @@ pub fn build_for_launches(
if plan.system == BuildSystem::Maven
&& let Some(m) = &model.maven
{
maven_launch_projects(root, m, module, test)
.iter()
.flat_map(|p| {
launch_class_dirs(plan.system, &subdir(root, &p.dir), test && subdir(root, &p.dir) == module)
})
.collect()
maven_launch_output_dirs(root, m, module, test).into_iter().filter(|dir| dir.is_dir()).collect()
} else {
launch_class_dirs(plan.system, module, test)
}
@@ -1021,6 +1016,60 @@ pub fn build_for_launches(
Ok(modules.iter().map(|m| LaunchBuild { class_dirs: class_dirs(m), failure: failure.clone() }).collect())
}
/// Maven output directories for a launch, including directories that have yet to be created.
pub fn maven_launch_output_dirs(root: &Path, model: &maven::MavenModel, module: &Path, test: bool) -> Vec<PathBuf> {
maven_launch_projects(root, model, module, test)
.into_iter()
.flat_map(|p| {
let dir = subdir(root, &p.dir);
maven_output_dirs(&dir, test && dir == module)
})
.collect()
}
/// The class directories of a Maven launch that must hold classes after its build: those of
/// the launch projects with sources in a conventional JVM source root. One that is missing
/// or holds no class was caught mid-rewrite, e.g. cleaned by a concurrent `mvn` (#5404).
pub fn launch_required_class_dirs(root: &Path, model: &BuildModel, module: &Path, test: bool) -> Vec<PathBuf> {
fn has_sources(dir: &Path, depth: u32) -> bool {
let Ok(entries) = std::fs::read_dir(dir) else { return false };
entries.flatten().any(|e| {
let p = e.path();
if p.is_dir() {
depth > 0 && has_sources(&p, depth - 1)
} else {
// A package-info.java without annotations compiles to nothing.
p.file_name() != Some("package-info.java".as_ref())
&& p.extension().is_some_and(|x| x == "java" || x == "kt" || x == "groovy" || x == "scala")
}
})
}
let compiles = |dir: &Path, set: &str| {
["java", "kotlin", "groovy", "scala"].iter().any(|lang| has_sources(&dir.join("src").join(set).join(lang), 32))
};
let Some(m) = &model.maven else { return Vec::new() };
let mut dirs = Vec::new();
for p in maven_launch_projects(root, m, module, test) {
let dir = subdir(root, &p.dir);
if test && dir == module && compiles(&dir, "test") {
dirs.push(subdir(&dir, "target/test-classes"));
}
if compiles(&dir, "main") {
dirs.push(subdir(&dir, "target/classes"));
}
}
dirs
}
fn maven_output_dirs(module: &Path, test: bool) -> Vec<PathBuf> {
let mut dirs = Vec::new();
if test {
dirs.push(subdir(module, "target/test-classes"));
}
dirs.push(subdir(module, "target/classes"));
dirs
}
fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<PathBuf> {
let sets: &[&str] = if test { &["test", "main"] } else { &["main"] };
let dirs: Vec<PathBuf> = match system {
@@ -1031,8 +1080,7 @@ fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<Path
.map(|d| subdir(module, &format!("build/{d}/{s}")))
})
.collect(),
BuildSystem::Maven if test => vec![subdir(module, "target/test-classes"), subdir(module, "target/classes")],
BuildSystem::Maven => vec![subdir(module, "target/classes")],
BuildSystem::Maven => maven_output_dirs(module, test),
_ => Vec::new(),
};
dirs.into_iter().filter(|d| d.is_dir()).collect()
+263 -13
View File
@@ -3,7 +3,13 @@
use super::MavenProject;
use crate::process;
use ide_core::{CancellationToken, IdeError, IdeResult};
use std::collections::HashSet;
use std::fs::{self, File};
use std::path::{Component, Path, PathBuf};
use std::time::SystemTime;
const DEPENDENCY_PLUGIN: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1";
const SOURCE_REFRESH_WORKERS: usize = 4;
#[derive(Debug, PartialEq, Eq)]
pub struct Artifact {
@@ -11,6 +17,29 @@ pub struct Artifact {
pub name: String,
pub version: String,
pub sources: PathBuf,
binary: PathBuf,
}
fn valid_part(part: &str) -> bool {
!part.is_empty()
&& part != "."
&& part != ".."
&& part.chars().all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c))
}
fn modified_file(path: &Path) -> Option<SystemTime> {
let metadata = fs::metadata(path).ok()?;
if metadata.is_file() { metadata.modified().ok() } else { None }
}
impl Artifact {
fn stale_binary(&self) -> Option<SystemTime> {
if !self.version.ends_with("-SNAPSHOT") {
return None;
}
let binary = modified_file(&self.binary)?;
(modified_file(&self.sources)? < binary).then_some(binary)
}
}
/// Resolve only jars inside the selected local repository, including custom repositories.
@@ -28,16 +57,14 @@ pub fn artifact(jar: &Path, repository: &Path) -> Option<Artifact> {
}
let n = parts.len();
let (name, version, file) = (parts[n - 3], parts[n - 2], parts[n - 1]);
let valid = |s: &str| {
!s.is_empty() && s != "." && s != ".." && s.chars().all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c))
};
if !parts[..n - 1].iter().all(|s| valid(s)) || file != format!("{name}-{version}.jar") {
if !parts[..n - 1].iter().all(|s| valid_part(s)) || file != format!("{name}-{version}.jar") {
return None;
}
Some(Artifact {
group: parts[..n - 3].join("."),
name: name.into(),
version: version.into(),
binary: jar.to_owned(),
sources: jar.with_file_name(format!("{name}-{version}-sources.jar")),
})
}
@@ -48,26 +75,58 @@ pub fn download(
artifact: &Artifact,
repository: &Path,
cancel: &CancellationToken,
) -> IdeResult<Option<PathBuf>> {
resolve(root, project, artifact, repository, &[], artifact.stale_binary(), cancel)
}
fn resolve(
root: &Path,
project: &MavenProject,
artifact: &Artifact,
repository: &Path,
profile_args: &[String],
stale: Option<SystemTime>,
cancel: &CancellationToken,
) -> IdeResult<Option<PathBuf>> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if artifact.sources.is_file() {
if stale.is_none() && artifact.sources.is_file() {
return Ok(Some(artifact.sources.clone()));
}
let mut args = vec!["-B".into(), "-N".into(), "-Dstyle.color=never".into()];
args.extend(project.options.clone());
args.extend([
format!("-Dmaven.repo.local={}", repository.display()),
"org.apache.maven.plugins:maven-dependency-plugin:3.8.1:get".into(),
format!("-Dartifact={}:{}:{}:jar:sources", artifact.group, artifact.name, artifact.version),
"-Dtransitive=false".into(),
]);
args.extend(project.options.iter().cloned());
args.extend(profile_args.iter().cloned());
args.push(format!("-Dmaven.repo.local={}", repository.display()));
let coordinate = format!("-Dartifact={}:{}:{}:jar:sources", artifact.group, artifact.name, artifact.version);
let stage = if let Some(binary) = stale {
// Keep the existing attachment readable while Maven resolves the timestamped snapshot.
// Disable Resolver's in-place copy to the base -SNAPSHOT filename.
let stage =
tempfile::Builder::new().prefix(".openidea-sources-").tempdir_in(artifact.sources.parent().unwrap())?;
args.extend([
"-U".into(),
"-Daether.artifactResolver.snapshotNormalization=false".into(),
format!("{DEPENDENCY_PLUGIN}:copy"),
coordinate,
"-Dmdep.useBaseVersion=true".into(),
format!("-DoutputDirectory={}", stage.path().display()),
]);
Some((stage, binary))
} else {
args.extend([format!("{DEPENDENCY_PLUGIN}:get"), coordinate, "-Dtransitive=false".into()]);
None
};
let output = process::run(&project.command, &args, &root.join(&project.dir), &project.env, cancel, |_, _| {})?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if artifact.sources.is_file() {
if let Some((stage, binary)) = stage {
let resolved = stage.path().join(artifact.sources.file_name().unwrap());
if output.success && resolved.is_file() {
return replace_stale_sources(artifact, &resolved, binary, cancel);
}
} else if artifact.sources.is_file() {
return Ok(Some(artifact.sources.clone()));
}
let coordinate = format!("{}:{}:jar:sources:{}", artifact.group, artifact.name, artifact.version);
@@ -83,6 +142,115 @@ pub fn download(
))
}
fn replace_stale_sources(
artifact: &Artifact,
resolved: &Path,
binary: SystemTime,
cancel: &CancellationToken,
) -> IdeResult<Option<PathBuf>> {
// Maven can fall back to a locally installed snapshot. Keep its timestamp if it returned
// the same bytes so a later reload can retry when newer sources are available.
let hash = |path| -> std::io::Result<_> { Ok(blake3::Hasher::new().update_reader(File::open(path)?)?.finalize()) };
if hash(resolved)? == hash(&artifact.sources)? {
return Ok(None);
}
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
match artifact.stale_binary() {
Some(current) if current == binary => {
File::options().write(true).open(resolved)?.set_modified(SystemTime::now().max(binary))?;
fs::rename(resolved, &artifact.sources)?;
Ok(Some(artifact.sources.clone()))
}
None if artifact.sources.is_file() => Ok(Some(artifact.sources.clone())),
_ => Ok(None),
}
}
/// Resolved Maven dependencies with an existing attachment. Binaries may still be
/// updating during import, so freshness is checked when the refresh runs.
pub fn cached_snapshots<'a>(
repository: &Path,
projects: impl Iterator<Item = (usize, &'a MavenProject)>,
) -> Vec<(usize, Artifact)> {
let mut seen = HashSet::new();
let mut candidates = Vec::new();
for (owner, project) in projects {
let mut dependencies: Vec<_> = project.dependencies.iter().collect();
while let Some(dep) = dependencies.pop() {
if !dep.resolved() {
continue;
}
dependencies.extend(&dep.children);
let Some(version) = dep.version.as_deref().filter(|v| v.ends_with("-SNAPSHOT") && valid_part(v)) else {
continue;
};
if dep.scope == "system"
|| dep.classifier.is_some()
|| !matches!(dep.kind.as_str(), "jar" | "bundle" | "maven-plugin" | "ejb")
|| !valid_part(&dep.artifact_id)
|| !dep.group_id.split('.').all(valid_part)
{
continue;
}
let name = &dep.artifact_id;
let jar = repository
.join(dep.group_id.replace('.', "/"))
.join(name)
.join(version)
.join(format!("{name}-{version}.jar"));
if let Some(artifact) = artifact(&jar, repository)
&& artifact.sources.is_file()
&& seen.insert(jar)
{
candidates.push((owner, artifact));
}
}
}
candidates
}
/// Refresh only previously attached snapshots. Maven subprocesses are bounded
/// and share the build reload's cancellation token.
pub fn refresh_snapshots(
root: &Path,
projects: &[MavenProject],
repository: &Path,
candidates: &[(usize, Artifact)],
profiles: &[String],
cancel: &CancellationToken,
) -> Vec<PathBuf> {
let profile_args = if profiles.is_empty() { vec![] } else { vec![format!("-P{}", profiles.join(","))] };
let profile_args = &profile_args;
let stale: Vec<_> = candidates.iter().filter(|(_, artifact)| artifact.stale_binary().is_some()).collect();
let batch_size = stale.len().div_ceil(SOURCE_REFRESH_WORKERS).max(1);
std::thread::scope(|scope| {
let workers: Vec<_> = stale
.chunks(batch_size)
.map(|batch| {
scope.spawn(move || {
let mut refreshed = Vec::new();
for (owner, artifact) in batch.iter().copied() {
if cancel.is_cancelled() {
break;
}
let Some(binary) = artifact.stale_binary() else { continue };
match resolve(root, &projects[*owner], artifact, repository, profile_args, Some(binary), cancel)
{
Ok(Some(_)) => refreshed.push(artifact.binary.clone()),
Ok(None) => {}
Err(e) => tracing::debug!(path = %artifact.sources.display(), "Maven sources refresh: {e}"),
}
}
refreshed
})
})
.collect();
workers.into_iter().flat_map(|worker| worker.join().expect("Maven sources worker")).collect()
})
}
#[cfg(test)]
mod tests {
use super::*;
@@ -121,4 +289,86 @@ mod tests {
assert_eq!(artifact(Path::new(path), repository), None, "{path}");
}
}
#[test]
fn selects_existing_snapshot_attachments_from_the_resolved_tree() {
use crate::maven::{MavenDependency, Omission};
let repo = tempfile::tempdir().unwrap();
let dependency = |name: &str, version: &str, cached: bool| {
if cached {
let dir = repo.path().join("example").join(name).join(version);
fs::create_dir_all(&dir).unwrap();
fs::write(dir.join(format!("{name}-{version}-sources.jar")), b"cached").unwrap();
}
MavenDependency {
group_id: "example".into(),
artifact_id: name.into(),
version: Some(version.into()),
kind: "jar".into(),
..Default::default()
}
};
let transitive = dependency("transitive", "1-SNAPSHOT", true);
let direct = MavenDependency { children: vec![transitive.clone()], ..dependency("direct", "1-SNAPSHOT", true) };
let omitted =
MavenDependency { omitted: Some(Omission::Conflict), ..dependency("omitted", "1-SNAPSHOT", true) };
let projects = [
MavenProject {
dependencies: vec![
direct,
omitted,
dependency("missing", "1-SNAPSHOT", false),
dependency("release", "1", true),
],
..Default::default()
},
MavenProject { dependencies: vec![transitive], ..Default::default() },
];
let mut found: Vec<_> = cached_snapshots(repo.path(), projects.iter().enumerate())
.into_iter()
.map(|(owner, artifact)| (owner, artifact.name))
.collect();
found.sort();
assert_eq!(found, [(0, "direct".into()), (0, "transitive".into())]);
}
#[cfg(unix)]
#[test]
fn downloads_sources_again_when_the_snapshot_binary_is_newer() {
use std::fs::FileTimes;
use std::os::unix::fs::PermissionsExt;
use std::time::Duration;
let dir = tempfile::tempdir().unwrap();
let repository = dir.path().join("repository");
let jar = repository.join("example/lib/1-SNAPSHOT/lib-1-SNAPSHOT.jar");
fs::create_dir_all(jar.parent().unwrap()).unwrap();
fs::write(&jar, b"new binary").unwrap();
let artifact = artifact(&jar, &repository).unwrap();
fs::write(&artifact.sources, b"old sources").unwrap();
File::open(&artifact.sources)
.unwrap()
.set_times(FileTimes::new().set_modified(SystemTime::now() - Duration::from_secs(60)))
.unwrap();
let launcher = dir.path().join("mvn");
fs::write(
&launcher,
"#!/bin/sh\nfor arg do\n case \"$arg\" in\n -DoutputDirectory=*) out=\"${arg#*=}\" ;;\n esac\ndone\nprintf 'new sources' > \"$out/lib-1-SNAPSHOT-sources.jar\"\n",
)
.unwrap();
fs::set_permissions(&launcher, fs::Permissions::from_mode(0o755)).unwrap();
let cancel = CancellationToken::new();
cancel.cancel();
assert!(download(dir.path(), &MavenProject::default(), &artifact, &repository, &cancel).is_err());
assert_eq!(fs::read(&artifact.sources).unwrap(), b"old sources");
let project = MavenProject { command: launcher.to_string_lossy().into_owned(), ..Default::default() };
let cancel = CancellationToken::new();
let path = download(dir.path(), &project, &artifact, &repository, &cancel).unwrap().unwrap();
assert_eq!(fs::read(&path).unwrap(), b"new sources");
assert_eq!(
download(dir.path(), &MavenProject::default(), &artifact, &repository, &CancellationToken::new()).unwrap(),
Some(path)
);
}
}
+1
View File
@@ -6,6 +6,7 @@ edition.workspace = true
license.workspace = true
[dependencies]
base64.workspace = true
dunce.workspace = true
encoding_rs.workspace = true
serde.workspace = true
+2
View File
@@ -324,6 +324,8 @@ pub enum LspRefreshKind {
InlayHints,
SemanticTokens,
CodeLens,
/// An import or classpath update may have changed inheritance search results.
Inheritance,
/// The Dart server published a document's Flutter outline.
FlutterOutline,
}
+122
View File
@@ -0,0 +1,122 @@
//! Binary arguments of IPC commands travel as base64 text: [`IpcBytes`] is a `Vec<u8>` that
//! serializes as a standard padded base64 string and is a plain `string` in the generated
//! bindings.
//!
//! A plain `Vec<u8>` is a JSON array of numbers, 3.6 times the size of the bytes, and parsing it
//! into a `serde_json::Value` (the remote protocol and Tauri both do) takes about 50 times the
//! bytes in memory: 20 MB become about 1 GB. Base64 is 1.33 times the size and one string.
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use std::ops::Deref;
/// A binary argument or result of an IPC command.
#[derive(Clone, Default, PartialEq, Eq, specta::Type)]
#[specta(transparent)]
pub struct IpcBytes(#[specta(type = String)] pub Vec<u8>);
impl IpcBytes {
pub fn into_vec(self) -> Vec<u8> {
self.0
}
}
impl fmt::Debug for IpcBytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "IpcBytes({} bytes)", self.0.len())
}
}
impl Serialize for IpcBytes {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&STANDARD.encode(&self.0))
}
}
impl<'de> Deserialize<'de> for IpcBytes {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct Base64;
impl Visitor<'_> for Base64 {
type Value = IpcBytes;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a base64 string")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<IpcBytes, E> {
STANDARD.decode(v).map(IpcBytes).map_err(|e| E::custom(format!("invalid base64: {e}")))
}
}
d.deserialize_str(Base64)
}
}
impl Deref for IpcBytes {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.0
}
}
impl From<Vec<u8>> for IpcBytes {
fn from(bytes: Vec<u8>) -> Self {
Self(bytes)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::{Value, json};
fn round_trip(bytes: Vec<u8>) {
let value = serde_json::to_value(IpcBytes(bytes.clone())).unwrap();
let text = value.as_str().expect("serializes as a string");
assert_eq!(text.len(), bytes.len().div_ceil(3) * 4);
assert_eq!(serde_json::from_value::<IpcBytes>(value).unwrap().into_vec(), bytes);
}
#[test]
fn round_trips_empty_every_byte_and_large_input() {
round_trip(Vec::new());
round_trip((0..=255).collect());
round_trip((0..=255).rev().cycle().take(5 * 1024 * 1024 + 1).collect());
}
#[test]
fn round_trips_through_a_json_document() {
let bytes: Vec<u8> = (0..=255).collect();
let text = serde_json::to_string(&json!({ "data": IpcBytes(bytes.clone()) })).unwrap();
#[derive(Deserialize)]
struct Args {
data: IpcBytes,
}
assert_eq!(serde_json::from_str::<Args>(&text).unwrap().data.into_vec(), bytes);
}
/// The old wire form of a `Vec<u8>`: 3.6 times the bytes. The string must stay near 4/3.
#[test]
fn serialized_form_is_a_string_about_a_third_larger_than_the_bytes() {
let bytes: Vec<u8> = (0..=255).cycle().take(1_000_000).collect();
let json = serde_json::to_string(&IpcBytes(bytes.clone())).unwrap();
assert!(json.starts_with('"') && json.ends_with('"'));
assert!(json.len() <= bytes.len().div_ceil(3) * 4 + 2, "{} bytes for {}", json.len(), bytes.len());
let as_array = serde_json::to_string(&bytes).unwrap();
assert!(json.len() * 2 < as_array.len(), "{} vs {}", json.len(), as_array.len());
}
#[test]
fn rejects_what_is_not_base64() {
for bad in [json!([1, 2, 3]), json!(7), Value::Null, json!("not base64!"), json!("QQ"), json!("QQ=a")] {
assert!(serde_json::from_value::<IpcBytes>(bad.clone()).is_err(), "{bad}");
}
}
#[test]
fn debug_does_not_print_the_bytes() {
assert_eq!(format!("{:?}", IpcBytes(vec![0; 3])), "IpcBytes(3 bytes)");
}
}
+2
View File
@@ -12,6 +12,7 @@ pub mod ids;
pub mod ignored;
pub mod input;
pub mod inspection_settings;
pub mod ipc_bytes;
pub mod ipc_path;
pub mod java_runtime;
pub mod jsonc;
@@ -37,6 +38,7 @@ pub mod wsl;
pub use error::{IdeError, IdeResult};
pub use event::{EventSink, IdeEvent, NullSink, SharedSink};
pub use ids::*;
pub use ipc_bytes::IpcBytes;
pub use ipc_path::IpcPath;
pub use text::*;
pub use tokio_util::sync::CancellationToken;
+4
View File
@@ -1396,6 +1396,9 @@ pub struct PythonSettings {
pub hide_other_project_interpreters: bool,
/// Show each interpreter's path under its name on the interpreters page.
pub show_interpreter_paths: bool,
/// Folders the user added to an interpreter's `sys.path` (All Interpreters › Show Paths),
/// by interpreter executable; absolute or `~/`.
pub interpreter_paths: BTreeMap<String, Vec<String>>,
}
impl Default for PythonSettings {
@@ -1407,6 +1410,7 @@ impl Default for PythonSettings {
hidden_interpreters: Vec::new(),
hide_other_project_interpreters: false,
show_interpreter_paths: true,
interpreter_paths: BTreeMap::new(),
}
}
}
+136 -54
View File
@@ -9,13 +9,16 @@ use ide_command::command;
use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult};
use ide_build::maven::completion::{PomCompletion, PomCompletionOption};
use ide_build::maven::sources;
use ide_build::maven::{PomGoto, PomManagedDeclaration, PomNavigationOptions};
use ide_build::pom_edit::{ArtifactKey, Exclusion};
use ide_build::{BuildModel, BuildTool, SyncOptions, SyncProgress};
use ide_core::settings::Settings;
use ide_core::{DocId, FileEdit, IdeError, IdeEvent, IdeResult, Location, Pos, Range, RequestId, WorkspaceEdit};
use std::collections::HashMap;
use std::path::Path;
use ide_core::{
CancellationToken, DocId, FileEdit, IdeError, IdeEvent, IdeResult, Location, Pos, Range, RequestId, WorkspaceEdit,
};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
@@ -281,6 +284,35 @@ pub async fn gradle_unlink_projects(host: &Host, window: &str, paths: Vec<String
set_gradle_projects(host, window, paths, false).await
}
struct MavenSourceRefresh {
root: PathBuf,
repository: PathBuf,
candidates: Vec<(usize, sources::Artifact)>,
}
fn cached_maven_sources(
model: &BuildModel,
scopes: Vec<workspace::Scope>,
window_root: &Path,
build_dir: Option<&str>,
) -> Vec<MavenSourceRefresh> {
let Some(maven) = &model.maven else { return Vec::new() };
scopes
.into_iter()
.filter(|scope| workspace::selected(scope, window_root, BuildTool::Maven, build_dir))
.filter_map(|scope| {
let repository = ide_sdk::apply::maven_local_repository(&scope.root, &scope.settings)
.or_else(ide_build::maven::default_local_repo)?;
let projects = maven.projects.iter().enumerate().filter(|(_, project)| {
Path::new(project.project_root.as_deref().unwrap_or_default()) == scope.root
|| (project.project_root.is_none() && scope.root == window_root)
});
let candidates = sources::cached_snapshots(&repository, projects);
(!candidates.is_empty()).then_some(MavenSourceRefresh { root: scope.root, repository, candidates })
})
.collect()
}
/// Runs Maven (`help:effective-pom dependency:tree`) or Gradle (`tasks --all`) in the
/// background, reporting progress on `on_progress`; cancellable with `cancel_request(request)`.
/// Returns the refreshed model; a failed build is reported in its `syncError`.
@@ -377,72 +409,122 @@ pub async fn build_sync(
let scopes = workspace::scopes(&p, &config)?;
let model = workspace::load_scopes(&p.root, &scopes);
let updates = workspace::update_files(&p.root, &scopes, &model, tool);
Ok::<_, IdeError>((model, profiles_changed, offline_changed, updates))
let snapshots = if tool == BuildTool::Maven && !offline {
cached_maven_sources(&model, scopes, &p.root, build_dir.as_deref())
} else {
Vec::new()
};
Ok::<_, IdeError>((model, profiles_changed || offline_changed, updates, snapshots))
})
.await
.map_err(join_err);
host.end_request(request);
let (model, profiles_changed, offline_changed, updates) = result??;
if completion_token.is_cancelled() {
return Err(IdeError::cancelled());
}
// Gradle may report project folders outside the project (`includeFlat`), and a Maven
// reactor may have gained or dropped modules beside it: index and list them.
project.refresh_index_scope();
let p = project.clone();
tokio::task::spawn_blocking(move || p.refresh_repositories());
// New source folders and dependency versions: the Project view and External Libraries reload.
project.sink.emit(ide_core::IdeEvent::ProjectRootsChanged { root: project.root.clone().into() });
if tool == BuildTool::Maven
&& model.maven.is_some()
&& let Some(bridge) = &project.kotlin_bridge
{
bridge.configure_maven(offline, bridge_profiles);
}
// jdtls re-imports on pom changes but misses artifacts added to ~/.m2
// meanwhile ("missing artifact" stays until Invalidate Caches); asking it
// to update the project configurations re-resolves them (#436). The same
// holds for Gradle: it reuses its cached classpath on restart, so a
// dependency added to `build.gradle` stays unresolved until told to sync.
let lsp = project.lsp.clone();
let documents = project.documents.clone();
tokio::spawn(async move {
if profiles_changed || offline_changed {
// jdtls takes the profiles and offline mode from its Maven settings (see `ide_sdk::maven_profiles`).
lsp.reconfigure().await;
let result = async {
let (mut model, reconfigure, updates, snapshots) = result??;
if completion_token.is_cancelled() {
return Err(IdeError::cancelled());
}
let first = updates.first().cloned();
for file in updates {
let uri = ide_lsp::path_to_uri_string(&file);
if let Err(e) = lsp.java_update_project_configs(&file, vec![uri]).await {
tracing::debug!("java/projectConfigurationsUpdate: {e}");
}
}
let changed = {
let lsp = lsp.clone();
tokio::task::spawn_blocking(move || lsp.changed_library_archives()).await.unwrap_or_default()
};
if let Some(file) = first
&& let Err(e) = lsp.java_refresh_archives(&file, &changed).await
// A reactor or Gradle build may have changed its external project folders.
project.refresh_index_scope();
let p = project.clone();
tokio::task::spawn_blocking(move || p.refresh_repositories());
project.sink.emit(IdeEvent::ProjectRootsChanged { root: project.root.clone().into() });
if tool == BuildTool::Maven
&& model.maven.is_some()
&& let Some(bridge) = &project.kotlin_bridge
{
tracing::debug!("openidea.java.refreshArchives: {e}");
bridge.configure_maven(offline, bridge_profiles.clone());
}
refresh_library_classes(&lsp, &documents).await;
});
Ok(model)
let lsp = project.lsp.clone();
let documents = project.documents.clone();
if snapshots.is_empty() {
tokio::spawn(async move {
update_java_projects(&lsp, &updates, reconfigure, None).await;
refresh_library_archives(&lsp, &documents, &updates, Vec::new()).await;
});
} else {
// JDT LS resolves the binary jars while importing Maven projects.
update_java_projects(&lsp, &updates, reconfigure, Some(&completion_token)).await;
let cancel = completion_token.clone();
let (updated, refreshed) = tokio::task::spawn_blocking(move || {
let mut refreshed = Vec::new();
if let Some(maven) = &model.maven {
for batch in snapshots {
if cancel.is_cancelled() {
break;
}
refreshed.extend(sources::refresh_snapshots(
&batch.root,
&maven.projects,
&batch.repository,
&batch.candidates,
&bridge_profiles,
&cancel,
));
}
}
(model, refreshed)
})
.await
.map_err(join_err)?;
model = updated;
tokio::spawn(async move {
refresh_library_archives(&lsp, &documents, &updates, refreshed).await;
});
}
if completion_token.is_cancelled() {
return Err(IdeError::cancelled());
}
Ok(model)
}
.await;
host.end_request(request);
result
}
/// Open library classes whose jar was replaced in place (a SNAPSHOT installed
/// again keeps its path) show the new contents, like a reopened one.
async fn refresh_library_classes(lsp: &Arc<ide_lsp::LspManager>, documents: &Arc<ide_workspace::Documents>) {
async fn update_java_projects(
lsp: &ide_lsp::LspManager,
updates: &[PathBuf],
reconfigure: bool,
wait: Option<&CancellationToken>,
) {
if reconfigure {
// jdtls takes the profiles and offline mode from its Maven settings.
lsp.reconfigure().await;
}
// JDT LS caches its classpath and re-imports on build-file changes. Ask it to
// re-resolve dependencies even when the build files stayed the same (#436).
if let Err(e) = lsp.java_update_project_configs(updates, wait).await {
tracing::debug!("Updating Java project configurations: {e}");
}
}
/// Re-read open library classes whose binary or attached sources changed in place.
async fn refresh_library_archives(
lsp: &Arc<ide_lsp::LspManager>,
documents: &Arc<ide_workspace::Documents>,
updates: &[PathBuf],
refreshed: Vec<PathBuf>,
) {
let changed = {
let lsp = lsp.clone();
tokio::task::spawn_blocking(move || lsp.changed_library_archives()).await.unwrap_or_default()
};
let archives: HashSet<_> = changed.into_iter().chain(refreshed).collect();
if let Err(e) = lsp.java_refresh_archives(updates, &archives).await {
tracing::debug!("openidea.java.refreshArchives: {e}");
}
let changed = {
let (lsp, documents) = (lsp.clone(), documents.clone());
tokio::task::spawn_blocking(move || {
lsp.invalidate_library_archives(&archives);
documents
.open_documents()
.into_iter()
.filter_map(|doc| Some((doc, documents.virtual_uri(doc).ok().flatten()?)))
.filter(|(_, uri)| lsp.library_class_changed(uri))
.filter(|(_, uri)| {
lsp.library_class_changed(uri)
|| ide_lsp::LspManager::library_archive(uri).is_some_and(|archive| archives.contains(&archive))
})
.collect::<Vec<_>>()
})
.await
+9 -1
View File
@@ -44,7 +44,15 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
&& config.request == "launch"
&& let Ok(project) = host.project(window)
{
super::python::prepare_debug(&mut config, &super::python::paths(&project))?;
let python = super::python::debug_python(&config);
let paths = super::python::with_user_paths(
super::python::paths(&project),
&host.config_dir,
&project,
python.as_deref(),
config.cwd.as_deref(),
);
super::python::prepare_debug(&mut config, &paths)?;
}
let label = window;
let (sink, flush_output) = output::coalescing_sink(host.window_sink(label));
+12 -2
View File
@@ -1,7 +1,7 @@
use super::Channel;
use crate::{Host, Project};
use ide_command::command;
use ide_core::{IdeError, IdeResult, RequestId};
use ide_core::{IdeError, IdeResult, IpcBytes, RequestId};
use ide_vfs::FileEntry;
use ide_workspace::DeletionUndo;
use std::path::{Path, PathBuf};
@@ -209,7 +209,7 @@ pub fn fs_create_file(host: &Host, window: &str, path: PathBuf) -> IdeResult<()>
}
#[command(trust = always)]
pub async fn fs_create_file_bytes(host: &Host, window: &str, path: PathBuf, data: Vec<u8>) -> IdeResult<()> {
pub async fn fs_create_file_bytes(host: &Host, window: &str, path: PathBuf, data: IpcBytes) -> IdeResult<()> {
let project = host.project(window).ok();
host.blocking(move || {
ide_vfs::create_file_bytes(&path, &data)?;
@@ -228,6 +228,15 @@ pub fn fs_create_dir(path: PathBuf) -> IdeResult<()> {
ide_vfs::create_dir(&path)
}
/// The scratch files' folder of this host (`<data dir>/scratches`), created. A remote window
/// keeps its scratches on the server, where its file commands run.
#[command(trust = always)]
pub fn fs_scratches_dir(host: &Host) -> IdeResult<ide_core::IpcPath> {
let dir = host.data_dir.join("scratches");
std::fs::create_dir_all(&dir)?;
Ok(dir.into())
}
/// Toggle Read-only Attribute: sets the writable bit (and the open document's
/// state). Returns whether the file is read-only now.
#[command(trust = always)]
@@ -383,6 +392,7 @@ ide_command::domain!(
fs_read_dir,
fs_read_text,
fs_rename,
fs_scratches_dir,
fs_set_writable,
fs_synchronize_directories,
fs_undo_delete,
+267 -8
View File
@@ -6,14 +6,20 @@ use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::fs;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::SystemTime;
#[derive(Debug, Serialize, Deserialize)]
pub(super) struct Outputs {
fingerprint: Option<LaunchFingerprint>,
pub snapshot: PathBuf,
pub originals: Vec<PathBuf>,
/// Live output and snapshot metadata at publication. Older records may hold an
/// incomplete copy and are rebuilt once (#5404).
#[serde(default)]
output_stamps: Option<Vec<OutputStamp>>,
#[serde(skip)]
pub failure: Option<String>,
/// Whether this result replaces jdtls diagnostics with a clean Maven build or a
@@ -23,12 +29,93 @@ pub(super) struct Outputs {
}
impl Outputs {
fn reusable(&self, fingerprint: &Option<LaunchFingerprint>, snapshots: &Path) -> bool {
fn reusable(
&self,
fingerprint: &Option<LaunchFingerprint>,
snapshots: &Path,
output_dirs: impl Iterator<Item = PathBuf>,
cancel: &CancellationToken,
) -> bool {
fingerprint.is_some()
&& self.fingerprint == *fingerprint
&& self.snapshot.parent() == Some(snapshots)
&& !self.originals.is_empty()
&& (0..self.originals.len()).all(|i| self.snapshot.join(i.to_string()).is_dir())
&& self.output_stamps.as_ref().is_some_and(|stamps| {
stamps.len() == self.originals.len()
&& output_dirs.eq(self.originals.iter().cloned())
&& self.originals.iter().zip(stamps).enumerate().all(|(i, (dir, stamp))| {
Contents::scan(dir, cancel).is_some_and(|live| live.stamp() == stamp.live)
&& Contents::scan(&self.snapshot.join(i.to_string()), cancel)
.is_some_and(|copy| copy.class_stamp() == stamp.snapshot_classes)
})
})
}
}
#[derive(Debug, Serialize, Deserialize)]
struct OutputStamp {
live: u64,
// A launched app may write non-class files under its snapshot classpath root.
snapshot_classes: u64,
}
/// Relative paths, sizes and mtimes are enough to detect ordinary compiler rewrites
/// without reading class or resource bytes.
#[derive(Debug, PartialEq, Eq)]
struct Contents(Vec<(PathBuf, u64, SystemTime)>);
impl Contents {
fn scan(root: &Path, cancel: &CancellationToken) -> Option<Self> {
if !fs::metadata(root).ok()?.is_dir() {
return None;
}
let mut files = Vec::new();
let mut pending = vec![root.to_path_buf()];
while let Some(dir) = pending.pop() {
if cancel.is_cancelled() {
return None;
}
for entry in fs::read_dir(dir).ok()? {
let entry = entry.ok()?;
let meta = entry.metadata().ok()?;
let path = entry.path();
if meta.is_dir() {
pending.push(path);
} else {
files.push((path.strip_prefix(root).ok()?.to_path_buf(), meta.len(), meta.modified().ok()?));
}
}
}
files.sort_unstable_by(|a, b| a.0.cmp(&b.0));
Some(Self(files))
}
fn stamp(&self) -> u64 {
let mut hasher = DefaultHasher::new();
self.0.hash(&mut hasher);
hasher.finish()
}
fn classes(&self) -> impl Iterator<Item = &(PathBuf, u64, SystemTime)> {
self.0.iter().filter(|(path, _, _)| path.extension().is_some_and(|ext| ext == "class"))
}
fn class_stamp(&self) -> u64 {
let mut hasher = DefaultHasher::new();
for file in self.classes() {
file.hash(&mut hasher);
}
hasher.finish()
}
fn matches_copy(&self, copy: &Self) -> bool {
// Copying preserves relative paths and sizes. Each tree has its own mtimes.
self.0.len() == copy.0.len()
&& self
.0
.iter()
.zip(&copy.0)
.all(|((path, len, _), (copied, copied_len, _))| path == copied && len == copied_len)
}
}
@@ -280,13 +367,23 @@ impl Session {
}
if let Some(outputs) = previous.as_ref()
&& policy != BuildPolicy::Rebuild
&& outputs.reusable(&before, &snapshots)
&& let Some(maven) = &model.maven
&& outputs.reusable(
&before,
&snapshots,
compile::maven_launch_output_dirs(root, maven, module, test).into_iter().filter(|dir| dir.is_dir()),
cancel,
)
&& !cancel.is_cancelled()
{
tracing::info!(module = %module.display(), test, "Reusing Maven launch snapshot");
let mut outputs = previous.unwrap();
outputs.authoritative = true;
return Ok(Ok(outputs));
}
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
// Retain a non-reusable record even on failure, so removing the final mixed
// source still delegates to Maven to clean its old classes on the next launch.
fs::create_dir_all(record.parent().unwrap())?;
@@ -317,6 +414,7 @@ impl Session {
let snapshot = tempfile::Builder::new().prefix("launch-").tempdir_in(&snapshots)?.keep();
// Retain every new snapshot even if copying or publishing its record fails.
self.unreferenced.push(snapshot.clone());
let scanned: Vec<_> = originals.iter().map(|dir| Contents::scan(dir, cancel)).collect();
for (i, source) in originals.iter().enumerate() {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
@@ -327,8 +425,43 @@ impl Session {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let mut outputs = Outputs { fingerprint: None, snapshot, originals, failure, authoritative };
if outputs.failure.is_none() && pending.before.is_some() && pending.before == after {
// The fingerprint covers build inputs only. Another build (an external `mvn`) can
// rewrite the outputs meanwhile without changing them (#5404): record the snapshot
// only if the outputs held still through the copy and hold every module's classes.
let copied: Option<Vec<Contents>> =
(0..originals.len()).map(|i| Contents::scan(&snapshot.join(i.to_string()), cancel)).collect();
let output_stamps: Option<Vec<OutputStamp>> = copied.as_ref().and_then(|copied| {
originals
.iter()
.zip(&scanned)
.zip(copied)
.map(|((dir, before), copy)| {
let before = before.as_ref()?;
let live = Contents::scan(dir, cancel)?;
(live == *before && before.matches_copy(copy))
.then(|| OutputStamp { live: live.stamp(), snapshot_classes: copy.class_stamp() })
})
.collect()
});
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let consistent = output_stamps.is_some();
let complete = copied.as_ref().is_some_and(|copied| {
compile::launch_required_class_dirs(root, model, &pending.module, test).iter().all(|dir| {
originals.iter().position(|o| o == dir).is_some_and(|i| copied[i].classes().next().is_some())
})
});
if failure.is_none() && !(consistent && complete) {
tracing::warn!(
module = %pending.module.display(),
consistent,
complete,
"Maven outputs changed or lacked classes while copying the launch snapshot; it will not be reused"
);
}
let mut outputs = Outputs { fingerprint: None, snapshot, originals, output_stamps, failure, authoritative };
if outputs.failure.is_none() && pending.before.is_some() && pending.before == after && consistent && complete {
outputs.fingerprint = pending.before;
write_record(&pending.record, &outputs)?;
self.unreferenced.retain(|path| path != &outputs.snapshot);
@@ -722,7 +855,7 @@ mod tests {
assert!(reused.authoritative);
assert_eq!(fs::read_to_string(root.join("calls")).unwrap().lines().count(), 1);
fs::write(root.join("src/main/kotlin/Main.kt"), "updated").unwrap();
fs::write(root.join("target/classes/Main.class"), "JDT stub").unwrap();
let rebuilt = session
.build(
root,
@@ -735,6 +868,7 @@ mod tests {
.unwrap();
assert_ne!(rebuilt.snapshot, first.snapshot);
assert!(rebuilt.authoritative);
assert_eq!(fs::read_to_string(rebuilt.snapshot.join("0/Main.class")).unwrap(), "first");
let calls = fs::read_to_string(root.join("calls")).unwrap();
assert_eq!(calls.lines().count(), 2);
assert!(calls.lines().last().unwrap().contains("clean"));
@@ -756,8 +890,6 @@ mod tests {
let second = build().unwrap();
assert_eq!(snapshot, second.snapshot);
assert_eq!(fs::read_to_string(root.join("calls")).unwrap().lines().count(), 1);
fs::write(root.join("target/classes/Main.class"), "JDT stub").unwrap();
assert_eq!(snapshot, build().unwrap().snapshot);
assert_eq!(fs::read_to_string(snapshot.join("0/Main.class")).unwrap(), "first");
fs::write(root.join("src/main/kotlin/Main.kt"), "updated").unwrap();
let updated = build().unwrap();
@@ -893,6 +1025,7 @@ mod tests {
fingerprint: None,
snapshot: retained.clone(),
originals: Vec::new(),
output_stamps: None,
failure: None,
authoritative: false,
};
@@ -953,6 +1086,132 @@ mod tests {
drop(session);
assert!(!outputs.snapshot.exists());
}
/// An external `mvn` removes a dependency module's classes (`clean`) while this launch
/// builds and copies the outputs, and compiles them again only after the copy (#5404).
/// The sources never change, so only the copied outputs can tell the snapshot is broken.
fn assert_outputs_cleaned_by_an_external_build_are_not_reused(clean: &str) {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = reactor_fixture(root);
let script = root.join("mvnw");
let mut text = fs::read_to_string(&script).unwrap();
text.push_str("echo resource > lib/target/classes/app.yml\n");
text.push_str(&format!("if [ -f external-build ]; then {clean}; fi\n"));
fs::write(&script, text).unwrap();
let cancel = CancellationToken::new();
let mut session = Session::new(root.join("cache"));
let a = root.join("a");
fs::write(root.join("external-build"), "").unwrap();
let first = session.build(root, &model, &a, BuildOptions::default(), None, &cancel).unwrap();
assert!(!first.snapshot.join("1/Main.class").exists());
// The external build finished: the classes are complete again, sources unchanged.
fs::remove_file(root.join("external-build")).unwrap();
fs::create_dir_all(root.join("lib/target/classes")).unwrap();
fs::write(root.join("lib/target/classes/Main.class"), "lib").unwrap();
let second = session.build(root, &model, &a, BuildOptions::default(), None, &cancel).unwrap();
assert_ne!(second.snapshot, first.snapshot, "the incomplete snapshot must not be reused");
assert_eq!(fs::read_to_string(second.snapshot.join("1/Main.class")).unwrap(), "lib");
assert_eq!(calls(root).len(), 2);
let third = session.build(root, &model, &a, BuildOptions::default(), None, &cancel).unwrap();
assert_eq!(third.snapshot, second.snapshot, "a complete snapshot is reused");
assert_eq!(calls(root).len(), 2);
}
#[test]
fn a_snapshot_of_classes_cleaned_by_an_external_build_is_not_reused() {
assert_outputs_cleaned_by_an_external_build_are_not_reused("rm lib/target/classes/Main.class");
}
#[test]
fn a_snapshot_missing_an_output_directory_removed_by_an_external_build_is_not_reused() {
assert_outputs_cleaned_by_an_external_build_are_not_reused("rm -r lib/target/classes");
}
#[test]
fn a_partially_recompiled_dependency_snapshot_is_not_reused() {
assert_outputs_cleaned_by_an_external_build_are_not_reused(
"echo other > lib/target/classes/Other.class; rm lib/target/classes/Main.class",
);
}
#[test]
fn a_new_output_directory_invalidates_a_test_launch_snapshot() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = fixture(root);
let cancel = CancellationToken::new();
let mut session = Session::new(root.join("cache"));
let mut build =
|| session.build(root, &model, root, BuildOptions { test: true, ..Default::default() }, None, &cancel);
let first = build().unwrap();
assert_eq!(first.originals, [root.join("target/classes")]);
fs::create_dir_all(root.join("target/test-classes")).unwrap();
fs::write(root.join("target/test-classes/GeneratedTest.class"), "test").unwrap();
let second = build().unwrap();
assert_ne!(first.snapshot, second.snapshot);
assert!(second.snapshot.join("0/GeneratedTest.class").is_file());
assert_eq!(second.snapshot, build().unwrap().snapshot);
assert_eq!(calls(root).len(), 2);
}
#[test]
fn a_record_without_output_stamps_is_rebuilt_once() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = fixture(root);
let cancel = CancellationToken::new();
let mut session = Session::new(root.join("cache"));
let first = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
// A count-only record may still hold a partial copy.
let record = root.join("cache/java-launch/records/main.json");
let mut json: serde_json::Value = serde_json::from_slice(&fs::read(&record).unwrap()).unwrap();
json.as_object_mut().unwrap().remove("output_stamps").unwrap();
json["contents"] = serde_json::json!([{ "files": 1, "bytes": 5, "classes": 1 }]);
fs::write(&record, serde_json::to_vec(&json).unwrap()).unwrap();
let rebuilt = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert_ne!(rebuilt.snapshot, first.snapshot);
let reused = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert_eq!(reused.snapshot, rebuilt.snapshot);
// A file the launched app wrote under its classpath root keeps the snapshot.
fs::write(reused.snapshot.join("0/app.log"), "log").unwrap();
let kept = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert_eq!(kept.snapshot, reused.snapshot);
// A snapshot that lost a class since it was recorded is rebuilt.
fs::remove_file(reused.snapshot.join("0/Main.class")).unwrap();
let again = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
assert_ne!(again.snapshot, reused.snapshot);
assert_eq!(calls(root).len(), 3);
}
#[test]
fn contents_tell_a_rewritten_output_from_its_copy() {
let dir = tempfile::tempdir().unwrap();
let classes = dir.path().join("classes");
let cancel = CancellationToken::new();
let scan = |path: &Path| Contents::scan(path, &cancel);
fs::create_dir_all(classes.join("pkg")).unwrap();
fs::write(classes.join("pkg/A.class"), "a").unwrap();
fs::write(classes.join("app.yml"), "yml").unwrap();
let class = fs::File::options().write(true).open(classes.join("pkg/A.class")).unwrap();
let resource = fs::File::options().write(true).open(classes.join("app.yml")).unwrap();
let before = SystemTime::now();
resource.set_modified(before + std::time::Duration::from_secs(10)).unwrap();
let contents = scan(&classes).unwrap();
ide_vfs::copy(&classes, &dir.path().join("copy")).unwrap();
assert!(contents.matches_copy(&scan(&dir.path().join("copy")).unwrap()));
// A rewrite can preserve both the class file's size and the tree's newest mtime.
class.set_modified(before + std::time::Duration::from_secs(1)).unwrap();
let rewritten = scan(&classes).unwrap();
assert!(contents.matches_copy(&rewritten));
assert_ne!(rewritten.stamp(), contents.stamp());
fs::rename(classes.join("pkg/A.class"), classes.join("pkg/B.class")).unwrap();
let renamed = scan(&classes).unwrap();
assert!(!rewritten.matches_copy(&renamed));
assert_ne!(renamed.stamp(), rewritten.stamp());
assert!(scan(&dir.path().join("missing")).is_none());
}
#[test]
fn deleting_the_last_mixed_source_keeps_maven_delegation_after_failure() {
let dir = tempfile::tempdir().unwrap();
+34 -1
View File
@@ -3,7 +3,7 @@ use ide_core::IdeResult;
use ide_dap::LaunchConfig;
use ide_workspace::roots::RootKind;
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
pub(super) fn paths(project: &Project) -> Vec<PathBuf> {
let mut paths = vec![project.root.clone()];
@@ -19,6 +19,39 @@ pub(super) fn paths(project: &Project) -> Vec<PathBuf> {
paths
}
/// `paths` plus the folders added to the paths of the interpreter a launch uses (All
/// Interpreters › Show Paths): `command` when it names a Python executable, else the
/// interpreter of the project or workspace member at `near`. Run, Debug and the console
/// resolve it the same way, so the same file imports the same modules in each.
pub(super) fn with_user_paths(
mut paths: Vec<PathBuf>,
config_dir: &Path,
project: &Project,
command: Option<&str>,
near: Option<&Path>,
) -> Vec<PathBuf> {
let named = command
.filter(|c| ide_sdk::apply::is_python_command(c))
.map(PathBuf::from)
.filter(|p| p.is_absolute() && p.is_file())
.map(|p| ide_core::project_roots::resolve(&project.root, &p));
let python = named.or_else(|| super::sdk::effective_python(config_dir, project, near));
if let Some(python) = python {
for path in ide_sdk::apply::interpreter_user_paths(&python, &project.settings.effective()) {
if !paths.contains(&path) {
paths.push(path);
}
}
}
paths
}
/// The interpreter a debugpy launch names (`"python": "<executable>"`), if it names one.
pub(super) fn debug_python(config: &LaunchConfig) -> Option<String> {
let extra: serde_json::Value = serde_json::from_str(config.extra_json.as_deref()?).ok()?;
extra.get("python")?.as_str().map(str::to_owned)
}
pub(super) fn prepare_debug(config: &mut LaunchConfig, paths: &[PathBuf]) -> IdeResult<()> {
// Adapter-specific env takes precedence over the common launch fields in DAP.
let mut extra: Option<serde_json::Value> = config.extra_json.as_deref().and_then(|s| serde_json::from_str(s).ok());
+23 -9
View File
@@ -488,14 +488,17 @@ async fn start_inner(
}
// A Python configuration pointing at a missing interpreter fails in the depth of
// process spawn otherwise; name the cause and the fix like PyCharm's "Invalid SDK".
if matches!(config.kind.as_str(), "python" | "pytest" | "django-test")
&& !Path::new(&config.command).is_file()
&& Path::new(&config.command).components().count() > 1
{
return Err(IdeError::invalid(format!(
"The configured Python interpreter does not exist: {}\nSelect a working interpreter in Settings › Languages & Frameworks › Python Interpreter.",
config.command
)));
let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "django-test");
if is_python && Path::new(&config.command).components().count() > 1 {
let cwd = project.root.join(config.cwd.as_deref().unwrap_or(Path::new("")));
let executable = ide_core::project_roots::resolve(&cwd, Path::new(&config.command));
if !executable.is_file() {
return Err(IdeError::invalid(format!(
"The configured Python interpreter does not exist: {}\nSelect a working interpreter in Settings › Languages & Frameworks › Python Interpreter.",
config.command
)));
}
config.command = ide_core::ipc_path::to_ipc(&executable);
}
if config.kind == "tomcat" {
if host.processes.list().iter().any(|r| r.running && r.config_id == config.id) {
@@ -518,10 +521,21 @@ async fn start_inner(
})
.await?;
}
let mut python_paths = if *root != project.root { vec![root.clone()] } else { super::python::paths(&project) };
if is_python {
let near = ide_run::scope::owner(&project.root, &config);
python_paths = super::python::with_user_paths(
python_paths,
&host.config_dir,
&project,
Some(&config.command),
Some(&near),
);
}
let encoding = settings.console.encoding;
let options = StartOptions {
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
python_paths: if *root != project.root { vec![root.clone()] } else { super::python::paths(&project) },
python_paths,
ruby_reporter: ruby_reporter_dir(host, &config),
};
project.require_trust()?;
+121 -2
View File
@@ -120,6 +120,49 @@ pub async fn sdk_python_interpreter(host: &Host, window: &str, path: PathBuf) ->
.map_err(join_err)?
}
/// `sys.path` of the interpreter `python`, for All Interpreters › Show Paths.
#[command(trust = outside_restricted)]
pub async fn sdk_python_sys_path(
host: &Host,
window: &str,
python: PathBuf,
request: RequestId,
) -> IdeResult<Vec<ide_core::IpcPath>> {
host.require_trust_if_project(window)?;
let cancel = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || {
let paths = ide_sdk::libraries::python_sys_path(&python, &cancel);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let paths = paths.ok_or_else(|| {
IdeError::invalid(format!(
"Cannot read sys.path of {}: the interpreter failed or did not answer in time",
python.display()
))
})?;
Ok(paths.iter().map(|p| p.as_path().into()).collect())
})
.await
.map_err(join_err);
host.end_request(request);
result?
}
/// For each folder added to an interpreter's paths, why it stays off the import path
/// (`None`: it is used). The folders may not be saved yet.
#[command(trust = outside_restricted)]
pub async fn sdk_python_user_path_problems(
host: &Host,
window: &str,
paths: Vec<String>,
) -> IdeResult<Vec<Option<ide_sdk::apply::UserPathProblem>>> {
host.require_trust_if_project(window)?;
tokio::task::spawn_blocking(move || paths.iter().map(|p| ide_sdk::apply::user_path(p).err()).collect())
.await
.map_err(join_err)
}
/// The interpreter of the workspace member `near` belongs to, else the project's.
pub(crate) fn effective_python(
config_dir: &std::path::Path,
@@ -336,7 +379,9 @@ pub async fn sdk_locate_tools(
.map_err(join_err)
}
/// Creates a Python environment with `tool` (`venv` / `uv` / `poetry`); output streams through `on_output`.
/// Creates a Python environment with `tool` (`venv` / `uv` / `poetry` / `pipenv`); output streams through
/// `on_output`. `install_packages` also installs what the project's `Pipfile` declares (pipenv).
#[allow(clippy::too_many_arguments)]
#[command(trust = outside_restricted)]
pub async fn sdk_python_create_venv(
host: &Host,
@@ -344,13 +389,14 @@ pub async fn sdk_python_create_venv(
tool: ide_sdk::python::VenvTool,
base: PathBuf,
location: PathBuf,
install_packages: bool,
request: RequestId,
on_output: Channel<String>,
) -> IdeResult<Sdk> {
host.require_trust_if_project(window)?;
let cancel = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || {
ide_sdk::python::create_venv(tool, &base, &location, &cancel, &|line| {
ide_sdk::python::create_venv(tool, &base, &location, install_packages, &cancel, &|line| {
let _ = on_output.send(line);
})
})
@@ -436,6 +482,77 @@ mod tests {
python
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_launch_takes_the_user_paths_of_the_interpreter_it_uses() {
use crate::ops::python::{debug_python, with_user_paths};
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let (root, bare, own) = (base.join("project"), base.join("bare"), base.join("own"));
let (for_main, for_own) = (base.join("for-main"), base.join("for-own"));
for dir in [&root, &bare, &own, &for_main, &for_own] {
std::fs::create_dir(dir).unwrap();
}
let (main_python, own_python) = (fake_venv(&root, ".venv"), fake_venv(&own, ".venv"));
ide_workspace::workspace::Workspace::attach(&root, "ws", vec![root.clone(), bare.clone(), own.clone()])
.unwrap();
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(|_| {})),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
let project = host.project("main").unwrap();
let text = |p: &Path| p.to_string_lossy().into_owned();
project
.settings
.set(
ide_workspace::SettingsScope::Global,
"languages.python.interpreterPaths",
serde_json::json!({ text(&main_python): [text(&for_main)], text(&own_python): [text(&for_own)] }),
)
.unwrap();
let paths = |command: Option<&str>, near: &Path| {
with_user_paths(Vec::new(), &host.config_dir, &project, command, Some(near))
};
// A member without a Python of its own runs on the primary project's interpreter;
// a member with its own virtualenv on that one.
assert_eq!(paths(None, &root), std::slice::from_ref(&for_main));
assert_eq!(paths(None, &bare), std::slice::from_ref(&for_main));
assert_eq!(paths(None, &own), std::slice::from_ref(&for_own));
// The interpreter a launch names wins over where it runs; a manager's command does not name one.
assert_eq!(paths(Some(&text(&own_python)), &bare), std::slice::from_ref(&for_own));
assert_eq!(paths(Some("uv"), &own), std::slice::from_ref(&for_own));
assert_eq!(paths(Some("python3"), &bare), std::slice::from_ref(&for_main));
// What is already on the path is neither repeated nor dropped.
let kept = with_user_paths(vec![root.clone(), for_main.clone()], &host.config_dir, &project, None, Some(&root));
assert_eq!(kept, [root.clone(), for_main]);
// Debug resolves a relative command against its working directory before sending it.
let debug_interpreter = bare.join("..").join(own_python.strip_prefix(&base).unwrap());
let mut launch = ide_dap::LaunchConfig {
name: "Python".into(),
adapter: "debugpy".into(),
request: "launch".into(),
program: None,
args: vec![],
cwd: Some(bare.as_path().into()),
env: Default::default(),
extra_json: Some(serde_json::json!({ "python": text(&debug_interpreter) }).to_string()),
};
assert_eq!(debug_python(&launch), Some(text(&debug_interpreter)));
assert_eq!(paths(debug_python(&launch).as_deref(), &bare), [for_own]);
launch.extra_json = Some(serde_json::json!({ "python": ["uv", "run", "python"] }).to_string());
assert_eq!(debug_python(&launch), None);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_hand_picked_venv_is_resolved_like_a_detected_interpreter() {
let temp = tempfile::tempdir().unwrap();
@@ -549,4 +666,6 @@ ide_command::domain!(
sdk_python_packages,
sdk_python_pip,
sdk_python_project_interpreters,
sdk_python_sys_path,
sdk_python_user_path_problems,
);
+5 -4
View File
@@ -1,7 +1,7 @@
use super::{Channel, Emit};
use crate::Host;
use ide_command::command;
use ide_core::{IdeResult, TerminalId};
use ide_core::{IdeResult, IpcBytes, TerminalId};
use ide_terminal::{TerminalInfo, TerminalOptions};
mod images;
@@ -9,7 +9,7 @@ mod images;
const MAX_IMAGE_BYTES: usize = 20 * 1024 * 1024;
#[command(trust = always)]
pub async fn term_store_image(host: &Host, id: TerminalId, data: Vec<u8>, mime: String) -> IdeResult<String> {
pub async fn term_store_image(host: &Host, id: TerminalId, data: IpcBytes, mime: String) -> IdeResult<String> {
if data.len() > MAX_IMAGE_BYTES {
return Err(ide_core::IdeError::invalid("image is too large to paste (limit 20 MB)"));
}
@@ -201,10 +201,11 @@ mod tests {
project_environment: false,
});
let id = TerminalId::next();
let error = term_store_image(&host, id, vec![0; MAX_IMAGE_BYTES + 1], "image/png".into()).await.unwrap_err();
let error =
term_store_image(&host, id, vec![0; MAX_IMAGE_BYTES + 1].into(), "image/png".into()).await.unwrap_err();
assert_eq!(error.kind, ErrorKind::InvalidInput);
assert_eq!(error.message, "image is too large to paste (limit 20 MB)");
let error = term_store_image(&host, id, vec![0; MAX_IMAGE_BYTES], "image/png".into()).await.unwrap_err();
let error = term_store_image(&host, id, vec![0; MAX_IMAGE_BYTES].into(), "image/png".into()).await.unwrap_err();
assert_eq!(error.message, "terminal session not found");
assert!(!host.data_dir.join("terminal-images").exists());
}
@@ -20,6 +20,7 @@ pub(crate) fn merge(server: Vec<InlayHint>, plugin: Vec<PluginInlayHint>, range:
padding_right: h.padding_right,
tooltip: h.tooltip,
parts: Vec::new(),
text_edits: Vec::new(),
}));
out.sort_by_key(|h| (h.position.line, h.position.col));
out
@@ -50,6 +51,7 @@ mod tests {
padding_right: true,
tooltip: None,
parts: Vec::new(),
text_edits: Vec::new(),
}
}
+6 -1
View File
@@ -200,7 +200,12 @@ impl Host {
// resolve imports into them. A container target already supplies its own
// `extraPaths` (the site-packages snapshot); don't mix local sources into it.
if !container_python {
ide_sdk::apply::configure_python_extra_paths(cfg, &python_dependency_roots(&effective, root));
let mut paths = python_dependency_roots(&effective, root);
// The folders added to the paths of the interpreter this server analyses with.
if let Some(python) = ide_sdk::apply::python_server_interpreter(root, server_root, &effective) {
paths.extend(ide_sdk::apply::interpreter_user_paths(&python, &effective));
}
ide_sdk::apply::configure_python_extra_paths(cfg, &paths);
}
if cfg.name == "jdtls" {
// A workspace member keeps its build model under its own key (Build Project).
+2 -1
View File
@@ -27,7 +27,8 @@ use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, OnceLock};
pub const PROTOCOL_VERSION: u32 = 2;
/// 3: binary arguments (`IpcBytes`) are base64 strings, not arrays of numbers.
pub const PROTOCOL_VERSION: u32 = 3;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
+70
View File
@@ -0,0 +1,70 @@
//! Binary command arguments over the remote protocol: base64 strings, not arrays of numbers.
use ide_core::{IpcBytes, NullSink};
use ide_host::rpc::{self, Dispatcher, Invoke};
use ide_host::{Host, HostConfig};
use ide_jsonrpc::{Handler, Peer};
use serde_json::{Value, json};
use std::sync::{Arc, OnceLock};
struct Client;
impl Handler for Client {
fn on_notification(&self, _: &str, _: Value) {}
fn on_request(&self, method: &str, _: Value) -> Result<Value, (i64, String)> {
Err((ide_jsonrpc::codes::METHOD_NOT_FOUND, method.to_owned()))
}
}
async fn connect(base: &std::path::Path) -> Peer {
let host = Arc::new(Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |window| window,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
let (client_io, server_io) = tokio::io::duplex(1 << 20);
let (sr, sw) = tokio::io::split(server_io);
tokio::spawn(rpc::serve(host, Dispatcher::standard(), Arc::new(OnceLock::new()), sr, sw));
let (cr, cw) = tokio::io::split(client_io);
Peer::connect(cr, cw, Arc::new(Client))
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn file_bytes_cross_the_protocol_as_base64() {
let tmp = tempfile::tempdir().unwrap();
let peer = connect(tmp.path()).await;
let bytes: Vec<u8> = (0..=255).cycle().take(3 * 1024 * 1024 + 1).collect();
let path = tmp.path().join("image.bin");
let args = json!({ "path": path, "data": IpcBytes(bytes.clone()) });
assert!(args["data"].is_string());
// Measure the envelope separately so the assertion is independent of the temp directory.
let envelope = serde_json::to_vec(&json!({ "path": path, "data": "" })).unwrap();
let body = serde_json::to_vec(&args).unwrap();
assert_eq!(body.len(), envelope.len() + bytes.len().div_ceil(3) * 4);
let call = Invoke { window: "main".into(), cmd: "fs_create_file_bytes".into(), args };
peer.request::<_, Value>("invoke", call, None).await.map_err(rpc::error_from_reply).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), bytes);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn an_array_of_numbers_is_not_accepted_as_bytes() {
let tmp = tempfile::tempdir().unwrap();
let peer = connect(tmp.path()).await;
let path = tmp.path().join("old.bin");
let call = Invoke {
window: "main".into(),
cmd: "fs_create_file_bytes".into(),
args: json!({ "path": path, "data": [1, 2, 3] }),
};
let error = peer.request::<_, Value>("invoke", call, None).await.map_err(rpc::error_from_reply).unwrap_err();
assert!(error.message.contains("argument data"), "{error:?}");
assert!(!path.exists());
}
+7
View File
@@ -74,6 +74,13 @@ async fn serves_projects_files_documents_search_and_runs() {
let info: ServerInfo = peer.request("initialize", json!({ "version": rpc::PROTOCOL_VERSION }), None).await.unwrap();
assert_eq!(info.protocol, rpc::PROTOCOL_VERSION);
let scratch_path = base.join("data/scratches");
assert!(!scratch_path.exists());
let expected = serde_json::to_value(ide_core::IpcPath::from(scratch_path.clone())).unwrap();
assert_eq!(invoke(&peer, "fs_scratches_dir", json!({})).await.unwrap(), expected);
assert!(scratch_path.is_dir());
assert_eq!(invoke(&peer, "fs_scratches_dir", json!({})).await.unwrap(), expected);
let opened = invoke(&peer, "open_project", json!({ "path": project })).await.unwrap();
assert_eq!(opened["name"], "demo");
assert_eq!(opened["trusted"], false);
+8 -4
View File
@@ -21,7 +21,7 @@ async fn storage_requires_a_registered_terminal() {
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
assert!(ops::term::term_store_image(&host, TerminalId::next(), vec![1], "image/png".into()).await.is_err());
assert!(ops::term::term_store_image(&host, TerminalId::next(), vec![1].into(), "image/png".into()).await.is_err());
assert!(!data_dir.join("terminal-images").exists());
let terminal = host
.terminals
@@ -41,11 +41,15 @@ async fn storage_requires_a_registered_terminal() {
)
.unwrap();
for mime in ["image/png", "audio/mpeg", "video/mp4"] {
let path = ops::term::term_store_image(&host, terminal.id, vec![1, 2, 3], mime.into()).await.unwrap();
let path = ops::term::term_store_image(&host, terminal.id, vec![1, 2, 3].into(), mime.into()).await.unwrap();
assert_eq!(std::fs::read(path).unwrap(), [1, 2, 3]);
}
assert!(ops::term::term_store_image(&host, terminal.id, vec![1], "application/octet-stream".into()).await.is_err());
assert!(
ops::term::term_store_image(&host, terminal.id, vec![1].into(), "application/octet-stream".into())
.await
.is_err()
);
host.terminals.kill(terminal.id).unwrap();
assert!(ops::term::term_store_image(&host, terminal.id, vec![4], "image/png".into()).await.is_err());
assert!(ops::term::term_store_image(&host, terminal.id, vec![4].into(), "image/png".into()).await.is_err());
assert_eq!(std::fs::read_dir(data_dir.join("terminal-images")).unwrap().count(), 3);
}
+19
View File
@@ -968,6 +968,7 @@ pub fn inlay_hint(conv: &Conv, path: &Path, h: lsp::InlayHint) -> InlayHint {
_ => InlayKind::Other,
};
let tooltip = h.tooltip.map(tooltip_text);
let text_edits = conv.text_edits(path, h.text_edits.unwrap_or_default());
InlayHint {
position: conv.pos(path, h.position),
label,
@@ -976,6 +977,7 @@ pub fn inlay_hint(conv: &Conv, path: &Path, h: lsp::InlayHint) -> InlayHint {
padding_right: h.padding_right.unwrap_or(false),
tooltip,
parts,
text_edits,
}
}
@@ -1589,6 +1591,23 @@ mod tests {
assert!(h.padding_left && !h.padding_right);
assert_eq!(h.parts.len(), 2);
assert!(h.parts.iter().all(|p| p.location.is_none()));
assert!(h.text_edits.is_empty());
}
#[test]
fn inlay_text_edits_carry_over() {
let conv = Conv::utf16();
let h: lsp::InlayHint = serde_json::from_value(json!({
"position": {"line": 2, "character": 5}, "label": ": Any", "kind": 1,
"textEdits": [
{"range": {"start": {"line": 2, "character": 5}, "end": {"line": 2, "character": 5}}, "newText": ": Any"},
{"range": {"start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 0}}, "newText": "from typing import Any\n"}
]
}))
.unwrap();
let h = inlay_hint(&conv, Path::new("/a"), h);
let edits: Vec<_> = h.text_edits.iter().map(|e| (e.range.start, e.new_text.as_str())).collect();
assert_eq!(edits, [(p(2, 5), ": Any"), (p(0, 0), "from typing import Any\n")]);
}
#[cfg(unix)]
+62 -35
View File
@@ -8,10 +8,12 @@
use crate::LspManager;
use crate::server::{Running, Server};
use ide_core::error::ErrorKind;
use ide_core::event::LspRefreshKind;
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use specta::Type;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -646,10 +648,8 @@ impl LspManager {
/// jdtls reports `ProjectStatus` when an import or project update ends (a POM
/// change, a Maven sync, other Maven profiles), but does not check open documents
/// again against the new classpath: their errors would stay until the next edit.
/// Nor does it ask for a semantic tokens refresh: a file outside any project (its
/// import failed, say on an unresolvable parent POM) gets no tokens, and would stay
/// uncoloured after the import is fixed. Generated Maven sources are attached
/// first, so the recheck and the new tokens see them.
/// Open editors may have cached empty tokens or inheritance results during the import.
/// Attach generated Maven sources before refreshing either, so both see the new classpath.
pub(crate) fn java_projects_updated(self: &Arc<Self>, server: Arc<Server>, generation: u64) {
let uris: Vec<String> = self
.docs
@@ -666,10 +666,9 @@ impl LspManager {
self.runtime.spawn(async move {
let Some(run) = server.running_gen(generation) else { return };
mgr.sync_generated_sources(&server, &run).await;
mgr.sink().emit(ide_core::IdeEvent::LspRefresh {
server: server.id,
kind: ide_core::event::LspRefreshKind::SemanticTokens,
});
for kind in [LspRefreshKind::SemanticTokens, LspRefreshKind::Inheritance] {
mgr.sink().emit(ide_core::IdeEvent::LspRefresh { server: server.id, kind });
}
for uri in uris {
let params =
json!({ "command": "java.project.refreshDiagnostics", "arguments": [uri, "thisFile", false] });
@@ -853,37 +852,65 @@ impl LspManager {
}
}
/// Tells jdtls the build files of `uris` changed (`java/projectConfigurationsUpdate`),
/// so it re-imports their projects (e.g. after `~/.m2` gained an artifact it could
/// not resolve). Best-effort: skipped while jdtls is not already running.
pub async fn java_update_project_configs(&self, path: &Path, uris: Vec<String>) -> IdeResult<()> {
if uris.is_empty() {
return Ok(());
}
fn running_java_projects<'a>(&self, files: &'a [PathBuf]) -> Vec<(Running, Vec<&'a Path>)> {
let java = LanguageId::new("java");
let Some(server) = self.servers_for(&java, path).into_iter().find(|s| s.name == SERVER) else {
return Ok(());
};
let Some(run) = server.running() else { return Ok(()) };
let identifiers: Vec<Value> = uris.iter().map(|u| json!({ "uri": u })).collect();
run.peer
.notify("java/projectConfigurationsUpdate", json!({ "identifiers": identifiers }))
.map_err(|e| crate::rpc_err(&server.name, "java/projectConfigurationsUpdate", e))
let mut targets = HashMap::new();
for file in files {
if let Some(server) = self.servers_for(&java, file).into_iter().find(|s| s.name == SERVER)
&& let Some(run) = server.running()
{
let (_, paths) = targets.entry(server.id).or_insert_with(|| (run, Vec::new()));
paths.push(file.as_path());
}
}
targets.into_values().collect()
}
/// Asks jdtls to re-read library archives replaced in place (`openidea.java.refreshArchives`):
/// a SNAPSHOT installed again keeps its path, and JDT would keep showing the classes it read
/// from the old archive. Best-effort: skipped while jdtls is not already running.
pub async fn java_refresh_archives(&self, path: &Path, archives: &[PathBuf]) -> IdeResult<()> {
let java = LanguageId::new("java");
let Some(server) = self.servers_for(&java, path).into_iter().find(|s| s.name == SERVER) else {
return Ok(());
};
if server.running().is_none() {
return Ok(());
/// Re-imports projects even when their build files did not change. Wait for
/// the Maven configuration job when a source refresh depends on its binaries.
pub async fn java_update_project_configs(
&self,
files: &[PathBuf],
wait: Option<&CancellationToken>,
) -> IdeResult<()> {
const UPDATE: &str = "openidea.java.updateProjectConfigurations";
let mut result = Ok(());
for (run, paths) in self.running_java_projects(files) {
let uris: Vec<_> = paths.iter().map(|path| crate::path_to_uri_string(path)).collect();
let supports_wait = run.caps.read().commands().iter().any(|command| command == UPDATE);
let updated = match wait.filter(|_| supports_wait) {
Some(cancel) => self
.jdtls_request(
paths[0],
"workspace/executeCommand",
json!({ "command": UPDATE, "arguments": uris }),
BUILD_TIMEOUT,
cancel,
)
.await
.map(|_| ()),
None => {
let identifiers: Vec<_> = uris.into_iter().map(|uri| json!({ "uri": uri })).collect();
run.peer
.notify("java/projectConfigurationsUpdate", json!({ "identifiers": identifiers }))
.map_err(|e| crate::rpc_err(SERVER, "java/projectConfigurationsUpdate", e))
}
};
result = result.and(updated);
}
let archives = archives.iter().map(|a| Value::String(a.to_string_lossy().into_owned())).collect();
self.jdtls_command(path, "openidea.java.refreshArchives", archives).await.map(|_| ())
result
}
/// Asks jdtls to re-read library archives replaced in place.
pub async fn java_refresh_archives(&self, files: &[PathBuf], archives: &HashSet<PathBuf>) -> IdeResult<()> {
let mut archives: Vec<_> = archives.iter().map(|a| Value::String(a.to_string_lossy().into_owned())).collect();
archives.sort_by(|a, b| a.as_str().cmp(&b.as_str()));
let mut result = Ok(());
for (_, paths) in self.running_java_projects(files) {
let refreshed = self.jdtls_command(paths[0], "openidea.java.refreshArchives", archives.clone()).await;
result = result.and(refreshed.map(|_| ()));
}
result
}
/// Pause autobuild before resolving the launch classpath. That query takes the
+11 -1
View File
@@ -280,7 +280,7 @@ pub struct LspManager {
virtual_docs: Mutex<HashMap<String, VirtualDocument>>,
/// Modification time of the archive behind a cached library class, so a jar
/// replaced in place (a SNAPSHOT installed again) is read again.
virtual_stamps: Mutex<HashMap<String, std::time::SystemTime>>,
virtual_stamps: Mutex<HashMap<String, virtual_doc::ArchiveStamp>>,
injections: injections::State,
/// Open notebooks by path. Locked before `docs` when both are.
notebooks: Mutex<HashMap<PathBuf, notebook::NotebookState>>,
@@ -3631,6 +3631,16 @@ impl LspManager {
archives
}
/// Drop cached text after JDT LS reopens the archives. A request could have
/// read the old attachment while the binary already had its new timestamp.
pub fn invalidate_library_archives(&self, archives: &std::collections::HashSet<PathBuf>) {
if !archives.is_empty() {
self.virtual_docs
.lock()
.retain(|uri, _| !virtual_doc::archive(uri).is_some_and(|archive| archives.contains(&archive)));
}
}
/// Contents of a virtual document, from the server that owns `uri`:
/// `workspace/textDocumentContent` (LSP 3.18) when the server serves the
/// scheme, jdtls' `java/classFileContents` for `jdt:` URIs. A `jar:` entry
+2
View File
@@ -261,6 +261,8 @@ pub struct InlayHint {
/// The label's parts when the server split it (empty for a plain label);
/// their values concatenate to `label`.
pub parts: Vec<InlayLabelPart>,
/// The edits that turn the hint into code (an annotation and any import it needs).
pub text_edits: Vec<TextEdit>,
}
/// One part of an inlay hint label, e.g. a type name that navigates to its declaration.
+23 -5
View File
@@ -192,9 +192,22 @@ pub(crate) fn archive(uri: &str) -> Option<std::path::PathBuf> {
}
}
/// Modification time of the archive a `jar:` or `jdt:` library class comes from.
pub(crate) fn archive_modified(uri: &str) -> Option<std::time::SystemTime> {
std::fs::metadata(archive(uri)?).and_then(|m| m.modified()).ok()
/// Timestamps for a library document's archive and its replaceable SNAPSHOT attachment.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct ArchiveStamp {
archive: std::time::SystemTime,
sources: Option<std::time::SystemTime>,
}
pub(crate) fn archive_modified(uri: &str) -> Option<ArchiveStamp> {
let modified = |path: &std::path::Path| std::fs::metadata(path).and_then(|m| m.modified()).ok();
let archive = archive(uri)?;
let sources = archive
.file_name()
.and_then(|name| name.to_str())
.and_then(|name| name.strip_suffix("-SNAPSHOT.jar"))
.and_then(|name| modified(&archive.with_file_name(format!("{name}-SNAPSHOT-sources.jar"))));
Some(ArchiveStamp { archive: modified(&archive)?, sources })
}
/// Whether `uri` is jdtls' class `package.name`, in any archive.
@@ -433,9 +446,14 @@ mod tests {
let uri = format!("jar:file://{}!/p/C.class", jar.display());
assert_eq!(archive(&uri), Some(jar.clone()));
let before = archive_modified(&uri).unwrap();
std::fs::write(dir.path().join("lib-1.0-SNAPSHOT-sources.jar"), b"PK").unwrap();
let with_sources = archive_modified(&uri).unwrap();
assert_eq!(before.archive, with_sources.archive);
assert_ne!(with_sources, before);
let file = std::fs::File::options().write(true).open(&jar).unwrap();
file.set_modified(before + std::time::Duration::from_secs(5)).unwrap();
assert_ne!(archive_modified(&uri), Some(before));
file.set_modified(before.archive + std::time::Duration::from_secs(5)).unwrap();
assert_ne!(archive_modified(&uri), Some(with_sources));
std::fs::remove_file(&jar).unwrap();
assert_eq!(archive_modified(&uri), None);
}
+9 -7
View File
@@ -3166,7 +3166,7 @@ async fn open_java_files_are_checked_again_after_a_project_update() {
}
#[tokio::test(flavor = "multi_thread")]
async fn a_project_update_refreshes_java_semantic_tokens() {
async fn a_project_update_refreshes_java_tokens_and_inheritance() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let _ = h.open("A.java", "class A { private String name; }");
h.wait_status("jdtls", ServerStatus::Ready).await;
@@ -3175,20 +3175,22 @@ async fn a_project_update_refreshes_java_semantic_tokens() {
h.events
.lock()
.iter()
.filter(|e| matches!(e, IdeEvent::LspRefresh { kind: LspRefreshKind::SemanticTokens, .. }))
.count()
.filter_map(|e| match e {
IdeEvent::LspRefresh { kind, .. } => Some(*kind),
_ => None,
})
.collect::<Vec<_>>()
};
state
.peer()
.notify("language/status", json!({ "type": "Message", "message": "Updating project configurations..." }))
.unwrap();
tokio::time::sleep(Duration::from_millis(200)).await;
assert_eq!(refreshes(), 0);
assert!(refreshes().is_empty());
// jdtls answers with no tokens for a file outside any project and sends no
// `workspace/semanticTokens/refresh` once a later import takes it in.
// A later import may add tokens and implementation targets to open editors.
state.peer().notify("language/status", json!({ "type": "ProjectStatus", "message": "OK" })).unwrap();
eventually(|| refreshes() == 1).await;
eventually(|| refreshes() == [LspRefreshKind::SemanticTokens, LspRefreshKind::Inheritance]).await;
}
#[tokio::test(flavor = "multi_thread")]
+2
View File
@@ -6,6 +6,7 @@ edition.workspace = true
license.workspace = true
[dependencies]
base64.workspace = true
dirs.workspace = true
dunce.workspace = true
ignore.workspace = true
@@ -16,6 +17,7 @@ ide-vfs.workspace = true
quick-xml = "0.42"
serde.workspace = true
serde_json.workspace = true
sha2 = "0.10"
specta.workspace = true
tempfile.workspace = true
toml.workspace = true
+157 -9
View File
@@ -66,9 +66,10 @@ pub fn ruff_configuration(root: &Path, configured: &str) -> IdeResult<Option<Pat
/// The project interpreter: the configured one, else a project virtualenv
/// (`.venv`, `venv`, …) or pixi environment (`.pixi/envs/<env>`) in the project
/// root, else the Python the project pins for mise / asdf. A configured
/// interpreter whose executable is gone (uninstalled, moved) is skipped like
/// PyCharm's "Invalid" SDKs, so runs fall back instead of failing on a dead path.
/// root, else the project's Pipenv environment, else the Python the project pins
/// for mise / asdf. A configured interpreter whose executable is gone (uninstalled,
/// moved) is skipped like PyCharm's "Invalid" SDKs, so runs fall back instead of
/// failing on a dead path.
/// `None` when the project interpreter is a run target's (see [`crate::container_python`]).
pub fn python_interpreter(root: &Path, s: &Settings) -> Option<PathBuf> {
if s.languages.python.run_target().is_some() {
@@ -80,6 +81,72 @@ pub fn python_interpreter(root: &Path, s: &Settings) -> Option<PathBuf> {
.or_else(|| pinned::pinned_python(root))
}
/// An absolute or `~/` path from the settings; `None` for anything else.
pub fn absolute_setting_path(s: &str) -> Option<PathBuf> {
setting_path(Path::new(""), s).filter(|p| p.is_absolute())
}
/// Why a folder added to an interpreter's paths stays off the import path.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub enum UserPathProblem {
/// Not an existing folder.
Missing,
/// Not absolute or `~/`, or it holds the separator of `PYTHONPATH`.
Invalid,
}
/// A folder added to an interpreter's paths (All Interpreters › Show Paths), as it goes on the
/// import path.
pub fn user_path(s: &str) -> Result<PathBuf, UserPathProblem> {
let path = absolute_setting_path(s).ok_or(UserPathProblem::Invalid)?;
// `PYTHONPATH` cannot hold a path with its separator in it: joining would fail every launch.
if std::env::join_paths([&path]).is_err() {
return Err(UserPathProblem::Invalid);
}
if !path.is_dir() {
return Err(UserPathProblem::Missing);
}
Ok(path)
}
/// Whether the settings key `key` names the interpreter `python`. Paths are compared as
/// written, not through symlinks: a virtualenv's `python` links to its base interpreter, and
/// the two are different interpreters.
fn names_interpreter(key: &str, python: &Path) -> bool {
let Some(key) = absolute_setting_path(key) else { return false };
if cfg!(windows) {
let fold = |p: &Path| p.to_string_lossy().replace('\\', "/").to_lowercase();
fold(&key) == fold(python)
} else {
key == python
}
}
/// The folders the user added to `python`'s paths that can be imported from.
pub fn interpreter_user_paths(python: &Path, s: &Settings) -> Vec<PathBuf> {
let mut out = Vec::new();
for (interpreter, paths) in &s.languages.python.interpreter_paths {
if !names_interpreter(interpreter, python) {
continue;
}
for path in paths.iter().filter_map(|p| user_path(p).ok()) {
if !out.contains(&path) {
out.push(path);
}
}
}
out
}
/// The interpreter a Python language server started for `server_root` analyses with: that
/// folder's own virtualenv unless an interpreter is configured, else the project interpreter.
pub fn python_server_interpreter(root: &Path, server_root: &Path, s: &Settings) -> Option<PathBuf> {
project_venv_python(server_root)
.filter(|_| non_empty(&s.languages.python.interpreter).is_none())
.or_else(|| python_interpreter(root, s))
}
/// An explicit project interpreter wins; otherwise use the closest virtualenv to the file.
pub fn python_interpreter_near(root: &Path, near: Option<&Path>, s: &Settings) -> Option<PathBuf> {
if s.languages.python.run_target().is_some() {
@@ -1160,9 +1227,7 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
let name = name.as_str();
if PYTHON_SERVERS.contains(&name) {
let python = project_venv_python(server_root)
.filter(|_| non_empty(&s.languages.python.interpreter).is_none())
.or_else(|| python_interpreter(root, s));
let python = python_server_interpreter(root, server_root, s);
if let Some(python) = python {
let p = python.to_string_lossy().into_owned();
match name {
@@ -1688,7 +1753,8 @@ fn configure_angular(cfg: &mut LanguageServerConfig, root: &Path, server_root: &
}
}
fn is_python_command(cmd: &str) -> bool {
/// Whether `cmd` is a Python executable by its name (`python`, `python3.12`, `python.exe`).
pub fn is_python_command(cmd: &str) -> bool {
let name = Path::new(cmd).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let name = name.strip_suffix(".exe").unwrap_or(&name);
name == "python"
@@ -1901,10 +1967,17 @@ pub fn apply_to_run_configs_in(configs: &mut [RunConfig], root: &Path, fallback:
let mut path_dirs: Vec<PathBuf> = Vec::new();
match c.kind.as_str() {
"python" | "pytest" | "django-test" => {
let python = toolchain("python", &owner);
let command = Path::new(&c.command);
let own = !c.detected && command.components().count() > 1 && is_python_command(&c.command);
let python = if own {
let cwd = root.join(c.cwd.as_deref().unwrap_or(Path::new("")));
Some(ide_core::project_roots::resolve(&cwd, command))
} else {
toolchain("python", &owner)
};
// The member's explicit interpreter, else the inherited one, else the
// member's own venv / pin.
if let Some(py) = explicit_python.as_ref().or(inherited_python.as_ref()).or(python.as_ref()) {
if !own && let Some(py) = explicit_python.as_ref().or(inherited_python.as_ref()).or(python.as_ref()) {
let runner = PY_RUNNERS.contains(&c.command.as_str());
if (c.kind == "python" || c.kind == "django-test") && (runner || is_python_command(&c.command)) {
if runner && c.args.first().map(String::as_str) == Some("run") {
@@ -2249,6 +2322,81 @@ fn conda_activation(python: &Path, name: &str, conda_exe: Option<PathBuf>, on_pa
}
}
#[cfg(test)]
mod python_user_path_tests {
use super::*;
fn venv(dir: &Path) -> PathBuf {
let python = dir.join(".venv").join(crate::bin_dir()).join(crate::exe("python"));
std::fs::create_dir_all(python.parent().unwrap()).unwrap();
std::fs::write(&python, "").unwrap();
std::fs::write(dir.join(".venv/pyvenv.cfg"), "").unwrap();
python
}
fn text(p: &Path) -> String {
p.to_string_lossy().into_owned()
}
#[test]
fn user_paths_follow_the_interpreter_and_skip_what_cannot_be_imported() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
let (lib, other) = (root.join("shared"), root.join("other"));
std::fs::create_dir_all(&lib).unwrap();
std::fs::create_dir_all(&other).unwrap();
let python = venv(&root);
let other_python = root.join("other-python");
let mut s = Settings::default();
s.languages.python.interpreter_paths = [
// Gone, duplicated, relative and a file: none of them reach the import path.
(text(&python), vec![text(&lib), text(&root.join("gone")), text(&lib), "relative".into(), text(&python)]),
(text(&other_python), vec![text(&other)]),
]
.into();
assert_eq!(interpreter_user_paths(&python, &s), std::slice::from_ref(&lib));
assert_eq!(interpreter_user_paths(&other_python, &s), [other]);
assert!(interpreter_user_paths(&root.join("unknown-python"), &s).is_empty());
}
#[test]
fn a_folder_that_stays_off_the_import_path_says_why() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
assert_eq!(user_path(&text(&root)), Ok(root.clone()));
assert_eq!(user_path(&text(&root.join("gone"))), Err(UserPathProblem::Missing));
assert_eq!(user_path("relative/dir"), Err(UserPathProblem::Invalid));
assert_eq!(user_path(" "), Err(UserPathProblem::Invalid));
// One entry with the separator in it would make `PYTHONPATH` impossible to build.
#[cfg(unix)]
{
let odd = root.join("libs:v2");
std::fs::create_dir(&odd).unwrap();
assert_eq!(user_path(&text(&odd)), Err(UserPathProblem::Invalid));
let mut s = Settings::default();
s.languages.python.interpreter_paths = [("/bin/python".into(), vec![text(&odd), text(&root)])].into();
assert_eq!(interpreter_user_paths(Path::new("/bin/python"), &s), [root]);
}
}
#[test]
fn a_language_server_takes_the_interpreter_of_its_own_folder() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
let sub = root.join("services/api");
let (python, sub_python) = (venv(&root), venv(&sub));
let mut s = Settings::default();
assert_eq!(python_server_interpreter(&root, &root, &s), Some(python.clone()));
assert_eq!(python_server_interpreter(&root, &sub, &s), Some(sub_python));
// A configured interpreter is the one every server of the project uses.
s.languages.python.interpreter = text(&python);
assert_eq!(python_server_interpreter(&root, &sub, &s), Some(python));
s.languages.python.interpreter = "target:docker".into();
assert_eq!(python_server_interpreter(&root, &root, &s), None);
}
}
#[cfg(test)]
mod java_compiler_tests {
use super::*;
+254 -9
View File
@@ -2,10 +2,10 @@
use crate::exec::{executables_in, query, search_path, which};
use crate::{Sdk, SdkKind, bin_dir, exe, home_dir, pinned, venv_of};
use ide_core::process::host_var_os;
use ide_core::process::{host_var_os, host_var_os_in};
use ide_core::version_managers::{self, Tool};
use std::collections::HashSet;
use std::ffi::OsString;
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::time::Duration;
@@ -55,7 +55,7 @@ fn tool_of(kind: SdkKind) -> Option<Tool> {
fn pinned_first(sdks: &mut Vec<Sdk>, kind: SdkKind, root: &Path) {
let Some((dir, _)) = tool_of(kind).and_then(|t| pinned::pinned_install(root, t)) else { return };
let Some(i) = sdks.iter().position(|s| s.path.starts_with(&dir)) else { return };
let at = sdks.iter().take_while(|s| s.source == "venv").count().min(i);
let at = sdks.iter().take_while(|s| matches!(s.source.as_str(), "venv" | "pipenv")).count().min(i);
let sdk = sdks.remove(i);
sdks.insert(at, sdk);
}
@@ -81,7 +81,8 @@ fn dedupe_by_real_path(paths: Vec<(PathBuf, &'static str)>) -> Vec<(PathBuf, &'s
/// Project-local virtualenv directories checked by auto-detection, in order.
pub(crate) const PROJECT_VENVS: [&str; 4] = [".venv", "venv", "env", ".env"];
/// `<root>/<venv>/bin/python` of the first project virtualenv or pixi environment.
/// `<root>/<venv>/bin/python` of the first project virtualenv or pixi environment, else the
/// interpreter of the project's Pipenv environment.
pub(crate) fn project_venv_python(root: &Path) -> Option<PathBuf> {
PROJECT_VENVS
.iter()
@@ -94,6 +95,101 @@ pub(crate) fn project_venv_python(root: &Path) -> Option<PathBuf> {
[env.join(exe("python")), env.join("bin").join(exe("python"))].into_iter().find(|p| p.is_file())
})
})
.or_else(|| pipenv_env_python(root))
}
/// Pipenv's active workon home first, followed by the other conventional location.
fn workon_homes(home: &Path, env: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
let var = |key: &str| env(key).filter(|v| !v.is_empty()).map(PathBuf::from);
let data = var("XDG_DATA_HOME").unwrap_or_else(|| home.join(".local/share"));
let mut defaults = [home.join(".virtualenvs"), data.join("virtualenvs")];
if !cfg!(windows) {
defaults.swap(0, 1);
}
var("WORKON_HOME").into_iter().chain(defaults).collect()
}
/// How many folders pipenv searches for a `Pipfile`, the project's own and those above it
/// (`PIPENV_MAX_DEPTH`, 10 by default).
const PIPFILE_MAX_DEPTH: usize = 10;
/// The folder of the `Pipfile` pipenv uses for a project opened at `root`: the nearest one in
/// `root` or the folders above it, searched as pipenv does.
pub(crate) fn pipfile_dir(root: &Path) -> Option<PathBuf> {
root.ancestors().take(PIPFILE_MAX_DEPTH).find(|dir| dir.join("Pipfile").is_file()).map(Path::to_path_buf)
}
/// The folder name pipenv gives the environment of the project whose `Pipfile` is in `dir`
/// (`venv_locator._get_virtualenv_hash`): the folder's name with shell-special characters
/// replaced and cut to 42 characters, `-`, and the URL-safe base64 of the first 6 bytes of
/// the SHA-256 of the `Pipfile` path.
pub(crate) fn pipenv_env_name(dir: &Path) -> String {
use base64::Engine;
use sha2::Digest;
let name: String = (dir.file_name().unwrap_or_default().to_string_lossy().chars())
.map(|c| if " &$`!*@\"()[]\\\r\n\t".contains(c) { '_' } else { c })
.take(42)
.collect();
let digest = sha2::Sha256::digest(dir.join("Pipfile").to_string_lossy().as_bytes());
format!("{name}-{}", base64::engine::general_purpose::URL_SAFE.encode(&digest[..6]))
}
/// The project a Pipenv virtualenv belongs to. Pipenv records the project folder in
/// `<venv>/.project`; virtualenvwrapper does too, so the environment must also carry the
/// name pipenv derives from that project's `Pipfile`, or be the project's own `.venv`.
fn pipenv_project(venv: &Path) -> Option<PathBuf> {
let project = PathBuf::from(std::fs::read_to_string(venv.join(".project")).ok()?.trim());
let named = venv.file_name().is_some_and(|name| *name.to_string_lossy() == pipenv_env_name(&project));
(project.is_absolute() && project.join("Pipfile").is_file() && (named || venv == project.join(".venv")))
.then_some(project)
}
/// The interpreter of the Pipenv environment `pipenv --venv` names for the project at `root`,
/// found without starting pipenv, which takes about a second.
fn pipenv_env_python(root: &Path) -> Option<PathBuf> {
let dir = pipfile_dir(root)?;
let var = |key: &str| host_var_os_in(&dir, key);
let homes = home_dir().map(|home| workon_homes(&home, var)).unwrap_or_default();
pipenv_env_in(&dir, &homes, var("PIPENV_CUSTOM_VENV_NAME").as_deref())
}
/// A project-local environment, an explicitly selected path or name, or Pipenv's hashed name.
fn pipenv_env_in(dir: &Path, homes: &[PathBuf], custom_name: Option<&OsStr>) -> Option<PathBuf> {
let dot_venv = dir.join(".venv");
let python_in = |env: &Path| {
let python = env.join(bin_dir()).join(exe("python"));
(env.join("pyvenv.cfg").is_file() && python.is_file()).then_some(python)
};
if dot_venv.is_file() {
let pointer = std::fs::read_to_string(&dot_venv).ok()?;
let pointer = pointer.trim();
if !pointer.is_empty() {
let path = Path::new(pointer);
let components = path.components().filter(|part| *part != std::path::Component::CurDir);
let home = if components.count() > 1 || pointer.ends_with(std::path::is_separator) {
dir.join(path)
} else {
homes.first()?.join(path)
};
return python_in(&dunce::canonicalize(home).ok()?);
}
}
if let Some(python) = python_in(&dot_venv) {
return Some(python);
}
if let Some(name) = custom_name.filter(|name| !name.is_empty()) {
let path = Path::new(name);
return if path.is_absolute() { python_in(path) } else { python_in(&homes.first()?.join(path)) };
}
// Pipenv hashes the path it was started in, which may or may not have its symlinks resolved.
let mut names: Vec<String> = [Some(dir.to_path_buf()), dunce::canonicalize(dir).ok()]
.into_iter()
.flatten()
.map(|d| pipenv_env_name(&d))
.collect();
names.dedup();
homes.iter().flat_map(|home| names.iter().map(move |name| home.join(name))).find_map(|home| python_in(&home))
}
/// `/usr/bin/python3` on macOS is a stub that opens an installer dialog when
@@ -223,15 +319,22 @@ fn python(root: Option<&Path>) -> Vec<Sdk> {
found.push((python, "pixi"));
}
}
if let Some(python) = pipenv_env_python(root) {
// The selected Pipenv environment may already be a project-local virtualenv.
if let Some((_, source)) = found.iter_mut().find(|(path, _)| *path == python) {
*source = "pipenv";
} else {
found.push((python, "pipenv"));
}
}
}
if let Ok(venv) = std::env::var("VIRTUAL_ENV") {
found.push((Path::new(&venv).join(bin_dir()).join(exe("python")), "venv"));
}
if let Some(home) = home_dir() {
// Virtualenvs managed by virtualenvwrapper / pipenv / poetry.
let env_dirs = [".virtualenvs", ".local/share/virtualenvs"].map(|d| home.join(d));
let var = |key: &str| host_var_os(key);
for dir in env_dirs.into_iter().chain(poetry_venv_dirs(Host::current(), &home, var)) {
for dir in workon_homes(&home, var).into_iter().chain(poetry_venv_dirs(Host::current(), &home, var)) {
for env in subdirs(&dir) {
found.push((env.join(bin_dir()).join(exe("python")), "venv"));
}
@@ -333,7 +436,11 @@ fn python(root: Option<&Path>) -> Vec<Sdk> {
seen_real.insert(p.canonicalize().unwrap_or_else(|_| p.clone()))
}
})
.map(|(p, source)| if venv_of(&p).is_some() && source != "conda" { (p, "venv") } else { (p, source) })
.map(
|(p, source)| {
if venv_of(&p).is_some() && !matches!(source, "conda" | "pipenv") { (p, "venv") } else { (p, source) }
},
)
.collect();
par_map(&candidates, |(path, source)| python_sdk(path, source, root))
}
@@ -357,7 +464,18 @@ pub fn python_interpreter_sdk(path: &Path, root: Option<&Path>) -> Option<Sdk> {
{
return None;
}
Some(python_sdk_with_version(&path, if venv_of(&path).is_some() { "venv" } else { "system" }, root, version))
let source = if let Some(home) = venv_of(&path) {
let pipenv_home = root.and_then(pipenv_env_python).and_then(|p| venv_of(&p));
if pipenv_home.is_some_and(|p| dunce::canonicalize(p).is_ok_and(|p| dunce::canonicalize(&home).ok() == Some(p)))
{
"pipenv"
} else {
"venv"
}
} else {
"system"
};
Some(python_sdk_with_version(&path, source, root, version))
}
pub(crate) fn python_sdk(path: &Path, source: &str, root: Option<&Path>) -> Option<Sdk> {
@@ -370,7 +488,17 @@ pub(crate) fn python_sdk(path: &Path, source: &str, root: Option<&Path>) -> Opti
fn python_sdk_with_version(path: &Path, source: &str, root: Option<&Path>, version: String) -> Sdk {
let short = version.split('.').take(2).collect::<Vec<_>>().join(".");
let venv = venv_of(path);
let pipenv = if source == "pipenv" {
root.and_then(pipfile_dir)
} else {
venv.as_deref().filter(|_| source == "venv").and_then(pipenv_project)
};
let source = if pipenv.is_some() { "pipenv" } else { source };
let label = match (&venv, source) {
(_, "pipenv") => {
let project = pipenv.as_deref().and_then(Path::file_name).unwrap_or_default().to_string_lossy();
format!("Python {short} (Pipenv: {project})")
}
(Some(home), _) => {
let dir = home.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
// `.venv` inside a project reads better as the folder that holds it (the project,
@@ -433,7 +561,7 @@ fn pixi_env_name(python: &Path) -> Option<String> {
pixi_env_home(python)?.file_name().map(|n| n.to_string_lossy().into_owned())
}
fn pyvenv_version(python: &Path) -> Option<String> {
pub(crate) fn pyvenv_version(python: &Path) -> Option<String> {
let cfg = std::fs::read_to_string(venv_of(python)?.join("pyvenv.cfg")).ok()?;
cfg.lines().find_map(|l| {
let (k, v) = l.split_once('=')?;
@@ -1119,6 +1247,106 @@ mod pixi_tests {
}
}
#[cfg(test)]
mod pipenv_tests {
use super::*;
fn venv(home: &Path, project: &Path) -> PathBuf {
let python = home.join(bin_dir()).join(exe("python"));
std::fs::create_dir_all(python.parent().unwrap()).unwrap();
std::fs::write(&python, "").unwrap();
std::fs::write(home.join("pyvenv.cfg"), "version = 3.12.1\n").unwrap();
std::fs::write(home.join(".project"), project.to_string_lossy().as_bytes()).unwrap();
python
}
#[test]
fn environments_are_named_as_pipenv_names_them() {
// `sanitize(folder)[:42] + "-" + urlsafe_b64encode(sha256(Pipfile path).digest()[:6])`, from pipenv.
assert_eq!(pipenv_env_name(Path::new("/home/me/My Shop (2)")), "My_Shop__2_-6rNTtAUD");
}
#[test]
fn the_environment_named_for_the_pipfile_is_the_projects() {
let tmp = tempfile::tempdir().unwrap();
let tmp = dunce::canonicalize(tmp.path()).unwrap();
let (shop, blog) = (tmp.join("shop"), tmp.join("blog"));
for project in [&shop, &blog] {
std::fs::create_dir_all(project.join("src/pkg")).unwrap();
std::fs::write(project.join("Pipfile"), "").unwrap();
}
let homes = [tmp.join("missing"), tmp.join(".virtualenvs"), tmp.join("workon")];
// virtualenvwrapper's `mkproject` writes `.project` too: its environment is not pipenv's,
// though it comes first and its project has a Pipfile.
let wrapper = venv(&homes[1].join("shop"), &shop);
let shop_python = venv(&homes[2].join(pipenv_env_name(&shop)), &shop);
let blog_python = venv(&homes[2].join(pipenv_env_name(&blog)), &blog);
assert_eq!(pipenv_env_in(&shop, &homes, None), Some(shop_python.clone()));
assert_eq!(pipenv_env_in(&blog, &homes, None), Some(blog_python));
// Opened in a sub-folder, the project is the one pipenv finds above it.
assert_eq!(pipfile_dir(&shop.join("src/pkg")), Some(shop.clone()));
assert_eq!(pipfile_dir(&tmp), None);
let sdk = python_sdk(&shop_python, "venv", Some(&blog)).unwrap();
assert_eq!((sdk.name.as_str(), sdk.source.as_str()), ("Python 3.12 (Pipenv: shop)", "pipenv"));
assert_eq!(
sdk.home.as_deref().map(|h| h.to_path_buf()),
shop_python.parent().unwrap().parent().map(Into::into)
);
let sdk = python_sdk(&wrapper, "venv", None).unwrap();
assert_eq!((sdk.name.as_str(), sdk.source.as_str()), ("Python 3.12 (shop)", "venv"));
}
#[test]
fn a_pipenv_environment_inside_the_project_is_named_as_pipenvs() {
let tmp = tempfile::tempdir().unwrap();
let shop = tmp.path().join("shop");
std::fs::create_dir_all(&shop).unwrap();
std::fs::write(shop.join("Pipfile"), "").unwrap();
let python = venv(&shop.join(".venv"), &shop);
assert_eq!(project_venv_python(&shop), Some(python.clone()));
assert_eq!(pipenv_env_in(&shop, &[], None), Some(python.clone()));
assert_eq!(python_sdk(&python, "venv", Some(&shop)).unwrap().name, "Python 3.12 (Pipenv: shop)");
}
#[test]
fn pipenv_uses_the_explicit_environment_without_a_project_marker() {
let tmp = tempfile::tempdir().unwrap();
let tmp = dunce::canonicalize(tmp.path()).unwrap();
let shop = tmp.join("shop");
let subdir = shop.join("src");
std::fs::create_dir_all(&subdir).unwrap();
std::fs::write(shop.join("Pipfile"), "").unwrap();
let homes = [tmp.join("workon")];
venv(&homes[0].join(pipenv_env_name(&shop)), &shop);
let named = homes[0].join("named");
let named_python = venv(&named, &shop);
std::fs::remove_file(named.join(".project")).unwrap();
let outside = tmp.join("outside");
let external_python = venv(&outside, &shop);
std::fs::remove_file(outside.join(".project")).unwrap();
let marker = shop.join(".venv");
let name = Some(OsStr::new("named"));
assert_eq!(pipenv_env_in(&shop, &homes, name), Some(named_python.clone()));
assert_eq!(pipenv_env_in(&shop, &[], Some(outside.as_os_str())), Some(external_python.clone()));
for pointer in ["../outside".into(), outside.to_string_lossy()] {
std::fs::write(&marker, format!(" {pointer}\n")).unwrap();
assert_eq!(pipenv_env_in(&shop, &homes, name), Some(external_python.clone()));
assert_eq!(project_venv_python(&subdir), Some(external_python.clone()));
}
let sdk = detect(SdkKind::Python, Some(&subdir)).into_iter().next().unwrap();
assert_eq!(sdk.path.to_path_buf(), external_python);
assert_eq!((sdk.name.as_str(), sdk.source.as_str()), ("Python 3.12 (Pipenv: shop)", "pipenv"));
std::fs::write(&marker, "named").unwrap();
assert_eq!(pipenv_env_in(&shop, &homes, None), Some(named_python));
std::fs::write(&marker, "missing").unwrap();
assert_eq!(pipenv_env_in(&shop, &homes, name), None);
}
}
#[cfg(test)]
mod conda_tests {
use super::*;
@@ -1261,6 +1489,23 @@ mod env_manager_dir_tests {
);
}
#[test]
fn workon_homes_follow_pipenv_and_virtualenvwrapper() {
let home = Path::new("/home/me");
let order = |xdg: PathBuf| {
let wrapper = home.join(".virtualenvs");
if cfg!(windows) { [wrapper, xdg] } else { [xdg, wrapper] }
};
let defaults = order(home.join(".local/share/virtualenvs"));
assert_eq!(workon_homes(home, env(&[("WORKON_HOME", "")])), defaults);
assert_eq!(
workon_homes(home, env(&[("WORKON_HOME", "/envs"), ("XDG_DATA_HOME", "/xdg/data")])),
std::iter::once(PathBuf::from("/envs"))
.chain(order(PathBuf::from("/xdg/data/virtualenvs")))
.collect::<Vec<_>>()
);
}
#[test]
fn poetry_overrides_come_first_and_empty_ones_are_ignored() {
let home = Path::new("/home/me");
+1 -1
View File
@@ -1629,7 +1629,7 @@ pub fn usages_bundle(data_dir: &Path) -> Option<PathBuf> {
install_bundle(
data_dir,
"java-usages",
"1.17.0",
"1.18.0",
include_bytes!("../../../java/java-usages/openidea-java-usages.jar"),
)
}
+83 -3
View File
@@ -384,15 +384,33 @@ fn tool(bin: Option<PathBuf>, name: &str) -> Option<PathBuf> {
// ------------------------------------------------------------------ python
fn python_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn python_groups(root: &Path, project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
let Some(python) = crate::apply::python_interpreter(root, s) else { return Vec::new() };
let mut files = vec![python.clone()];
files.extend(crate::venv_of(&python).map(|v| v.join("pyvenv.cfg")));
cached_cancellable(root, "python", python.display().to_string(), &files, cancel, || {
python_libraries(&python, Some(root)).into_iter().collect()
let structure = &s.project_structure;
let folders: Vec<PathBuf> = [root, project]
.into_iter()
.map(Path::to_path_buf)
.chain(structure.content_roots.iter().chain(&structure.dependencies).map(|p| PathBuf::from(p.trim())))
.collect();
let user = outside_folders(crate::apply::interpreter_user_paths(&python, s), &folders);
let key = std::iter::once(&python).chain(&user).map(|p| p.display().to_string()).collect::<Vec<_>>().join("\n");
cached_cancellable(root, "python", key, &files, cancel, || {
let mut group = python_libraries(&python, Some(root));
if let Some(group) = &mut group {
group.roots.extend(library_roots(user));
}
group.into_iter().collect()
})
}
/// `paths` without the ones inside, or around, one of the project's `folders`: a library root
/// opens its files read-only, and the project's own code stays editable.
fn outside_folders(paths: Vec<PathBuf>, folders: &[PathBuf]) -> Vec<PathBuf> {
paths.into_iter().filter(|p| !folders.iter().any(|f| p.starts_with(f) || f.starts_with(p))).collect()
}
/// Standard library and site-packages folders of a Python interpreter.
pub fn python_libraries(python: &Path, root: Option<&Path>) -> Option<LibraryGroup> {
// In a neutral directory: the working directory comes first on `sys.path` for `-c`.
@@ -402,6 +420,16 @@ pub fn python_libraries(python: &Path, root: Option<&Path>) -> Option<LibraryGro
group(name, "python", library_roots(parse_python_paths(&out)))
}
/// `sys.path` of `python` started on its own; `None` when it cannot run or was cancelled.
pub fn python_sys_path(python: &Path, cancel: &CancellationToken) -> Option<Vec<PathBuf>> {
// In a neutral directory and without the IDE's own `PYTHONPATH`: neither belongs to the
// interpreter. `-c` puts `''` first for the working directory; a hook may add non-strings.
let dir = crate::python::neutral_dir()?;
let script = "import json,sys;print(json.dumps([p for p in sys.path if isinstance(p,str) and p]))";
let out = query_in_cancellable(python, &["-c", script], dir.path(), &[("PYTHONPATH", "")], QUERY_TIMEOUT, cancel)?;
Some(parse_python_paths(&out))
}
pub(crate) fn parse_python_paths(out: &str) -> Vec<PathBuf> {
let json = out.lines().rev().find(|l| l.trim_start().starts_with('[')).unwrap_or("[]");
serde_json::from_str::<Vec<Option<String>>>(json)
@@ -1090,6 +1118,58 @@ fn package_label(dep: &crate::zig::ZonDependency, hash: &str) -> String {
}
}
#[cfg(test)]
mod python_tests {
use super::*;
#[test]
fn user_paths_inside_or_around_the_project_are_not_library_roots() {
let folders = [PathBuf::from("/work/app"), PathBuf::from("/work/attached")];
let paths = ["/work/app/stubs", "/work/app", "/work", "/work/attached/src", "/shared/lib", "/work/apple"];
assert_eq!(
outside_folders(paths.iter().map(PathBuf::from).collect(), &folders),
[PathBuf::from("/shared/lib"), PathBuf::from("/work/apple")]
);
}
#[test]
fn external_libraries_list_user_paths_outside_the_project_only() {
let Some(python) = crate::exec::which("python3") else { return };
let tmp = tempfile::tempdir().unwrap();
let base = tmp.path().canonicalize().unwrap();
let (root, attached, shared) = (base.join("app"), base.join("attached"), base.join("shared"));
for dir in [&root.join("stubs"), &attached.join("src"), &shared] {
std::fs::create_dir_all(dir).unwrap();
}
let text = |p: &Path| p.to_string_lossy().into_owned();
let mut s = Settings::default();
s.languages.python.interpreter = text(&python);
s.project_structure.dependencies = vec![text(&attached)];
s.languages.python.interpreter_paths =
[(text(&python), vec![text(&root.join("stubs")), text(&attached.join("src")), text(&base), text(&shared)])]
.into();
let groups = python_groups(&root, &root, &s, &CancellationToken::new());
let roots: Vec<&Path> = groups.iter().flat_map(|g| &g.roots).map(|r| Path::new(&*r.path)).collect();
assert!(roots.contains(&shared.as_path()), "{roots:?}");
// The project's own folders stay editable: a library root opens read-only.
for inside in [root.join("stubs"), attached.join("src"), base.clone()] {
assert!(!roots.contains(&inside.as_path()), "{roots:?}");
}
}
#[test]
fn sys_path_is_the_interpreters_own_and_can_be_cancelled() {
let Some(python) = crate::exec::which("python3") else { return };
let paths = python_sys_path(&python, &CancellationToken::new()).unwrap();
// Site hooks can add non-filesystem entries for editable packages.
assert!(paths.iter().any(|p| p.is_absolute()), "{paths:?}");
let cancelled = CancellationToken::new();
cancelled.cancel();
assert_eq!(python_sys_path(&python, &cancelled), None);
assert_eq!(python_sys_path(Path::new("/no/such/python"), &CancellationToken::new()), None);
}
}
#[cfg(test)]
mod go_cache_tests {
use super::*;
+81 -2
View File
@@ -28,18 +28,22 @@ pub enum VenvTool {
Poetry,
/// `conda create -n <name> -y` for a bare name, else `-p <location>` (conda must be on PATH).
Conda,
/// `pipenv --python <base>` in the project (pipenv must be on PATH).
Pipenv,
}
/// Creates a virtualenv at `location` with `tool` and returns its interpreter.
/// `base` is the interpreter uv / venv build on, or the one poetry's env uses.
/// `base` is the interpreter uv / venv build on, or the one poetry's / pipenv's env uses.
/// `install` also installs the packages the project declares, for the tool that reads them (pipenv).
pub fn create_venv(
tool: VenvTool,
base: &Path,
location: &Path,
install: bool,
cancel: &CancellationToken,
on_line: &dyn Fn(String),
) -> IdeResult<Sdk> {
create_venv_with(tool, base, location, which, cancel, on_line)
create_venv_with(tool, base, location, install, which, cancel, on_line)
}
/// [`create_venv`] with the tool lookup injectable (tests fake `uv` / `poetry`).
@@ -47,6 +51,7 @@ pub(crate) fn create_venv_with(
tool: VenvTool,
base: &Path,
location: &Path,
install: bool,
which: impl Fn(&str) -> Option<PathBuf>,
cancel: &CancellationToken,
on_line: &dyn Fn(String),
@@ -86,6 +91,7 @@ pub(crate) fn create_venv_with(
}
VenvTool::Poetry => create_poetry_env(base, location, &which, cancel, on_line),
VenvTool::Conda => create_conda_env(base, location, &which, cancel, on_line),
VenvTool::Pipenv => create_pipenv_env(base, location, install, &which, cancel, on_line),
}
}
@@ -117,6 +123,79 @@ fn create_poetry_env(
.map(PathBuf::from)
.ok_or_else(|| IdeError::internal("poetry created no environment".to_owned()))?;
let python = home.join(bin_dir()).join(exe("python"));
crate::discover::python_sdk(&python, "pipenv", Some(project))
.ok_or_else(|| IdeError::internal(format!("{} was not created", python.display())))
}
/// An environment that already exists is reused rather than rebuilt: the tools replace one
/// built on another Python without asking, losing its packages. If `base` is another Python
/// version than the environment's, nothing is changed and the error says how to go on.
fn reuse_existing_env(home: &Path, base: &Path, remove: &str) -> IdeResult<()> {
let short = |version: &str| version.split('.').take(2).collect::<Vec<_>>().join(".");
let existing = crate::discover::pyvenv_version(&home.join(bin_dir()).join(exe("python")));
let wanted = query_in(base, &["--version"], None, &[], Duration::from_secs(15))
.and_then(|v| v.strip_prefix("Python ").map(str::to_owned));
match (existing.as_deref().map(short), wanted.as_deref().map(short)) {
(Some(existing), Some(wanted)) if existing != wanted => Err(IdeError::new(
ide_core::error::ErrorKind::AlreadyExists,
format!(
"{} already holds a Python {existing} environment, not Python {wanted} like the base interpreter. \
Select it under Existing environment, or remove it first with `{remove}`.",
home.display()
),
)),
_ => Ok(()),
}
}
/// Pipenv's environment for the project (`location` is a hint inside it, as for Poetry: pipenv
/// keeps its envs under `WORKON_HOME`). `pipenv --python <base>` creates it when `pipenv --venv`
/// finds none, writing a `Pipfile` (from `requirements.txt` if there is one) when the project
/// has none. `install` then runs `pipenv install --dev` for the packages of the `Pipfile`.
fn create_pipenv_env(
base: &Path,
location: &Path,
install: bool,
which: &dyn Fn(&str) -> Option<PathBuf>,
cancel: &CancellationToken,
on_line: &dyn Fn(String),
) -> IdeResult<Sdk> {
let pipenv = which("pipenv")
.ok_or_else(|| IdeError::unavailable("Pipenv is not installed (install it from https://pipenv.pypa.io)"))?;
let project = location
.parent()
.filter(|p| p.is_dir())
.ok_or_else(|| IdeError::invalid("Pipenv environments need an open project directory"))?;
// No prompts or spinner, and the project's own environment even when the IDE was
// started from inside another virtualenv.
const ENV: [(&str, &str); 3] = [("PIPENV_YES", "1"), ("PIPENV_NOSPIN", "1"), ("PIPENV_IGNORE_VIRTUALENVS", "1")];
let env = ENV.map(|(k, v)| (k.to_owned(), v.to_owned()));
let venv = || {
query_in_cancellable(&pipenv, &["--venv"], project, &ENV, Duration::from_secs(30), cancel)
.map(PathBuf::from)
.filter(|home| home.join("pyvenv.cfg").is_file())
};
match venv() {
Some(home) => reuse_existing_env(&home, base, "pipenv --rm")?,
None => {
let args = ["--python".to_owned(), base.to_string_lossy().into_owned()];
stream(&pipenv, &args, Some(project), &env, cancel, on_line)?;
}
}
// Decided after creation: pipenv may just have written the `Pipfile`, or found one above the project.
let pipfile_dir = crate::discover::pipfile_dir(project);
if install && pipfile_dir.is_some() {
stream(&pipenv, &["install".to_owned(), "--dev".to_owned()], Some(project), &env, cancel, on_line)?;
}
let home = venv().ok_or_else(|| IdeError::internal("pipenv created no environment".to_owned()))?;
// Pipenv records the project only when it creates the environment: one it reuses after an
// interrupted creation has no `.project`, and detection would not know whose it is.
let record = home.join(".project");
if !record.exists() {
let owner = pipfile_dir.as_deref().unwrap_or(project);
let _ = std::fs::write(record, owner.to_string_lossy().as_bytes());
}
let python = home.join(bin_dir()).join(exe("python"));
crate::discover::python_sdk(&python, "venv", Some(project))
.ok_or_else(|| IdeError::internal(format!("{} was not created", python.display())))
}
+101
View File
@@ -578,6 +578,31 @@ fn run_configs_use_selected_interpreter_and_package_manager() {
assert_eq!(configs[6].args, ["manage.py", "test", "polls"]);
}
#[test]
fn saved_python_configs_keep_their_explicit_interpreter() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
let default = fake_venv(root, ".venv");
let override_python = fake_venv(&root.join("member"), ".override");
let relative_python = override_python.strip_prefix(root.join("member")).unwrap();
let mut settings = Settings::default();
settings.languages.python.interpreter = default.to_string_lossy().into_owned();
for command in [&override_python, relative_python] {
for kind in ["python", "pytest", "django-test"] {
let command = command.to_string_lossy();
let mut config = run(kind, &command, &["main.py"]);
config.detected = false;
config.cwd = Some(Path::new("member").into());
apply_to_run_configs(std::slice::from_mut(&mut config), root, &settings);
assert_eq!(config.command, command);
assert_eq!(config.env["VIRTUAL_ENV"], root.join("member/.override").to_string_lossy());
let saved = without_derived(&config, root, &settings);
assert_eq!(saved.command, command);
}
}
}
#[test]
fn npm_config_runs_on_its_own_node_interpreter() {
if cfg!(windows) {
@@ -1485,6 +1510,7 @@ fn env_tools_are_reported_missing_before_they_run() {
crate::python::VenvTool::Uv,
&base,
&location,
false,
none,
&Default::default(),
&|_| {},
@@ -1495,6 +1521,7 @@ fn env_tools_are_reported_missing_before_they_run() {
crate::python::VenvTool::Poetry,
&base,
&location,
false,
none,
&Default::default(),
&|_| {},
@@ -1505,12 +1532,24 @@ fn env_tools_are_reported_missing_before_they_run() {
crate::python::VenvTool::Conda,
&base,
&location,
false,
none,
&Default::default(),
&|_| {},
)
.unwrap_err();
assert!(conda.message.contains("conda is not installed"), "{}", conda.message);
let pipenv = crate::python::create_venv_with(
crate::python::VenvTool::Pipenv,
&base,
&location,
true,
none,
&Default::default(),
&|_| {},
)
.unwrap_err();
assert!(pipenv.message.contains("Pipenv is not installed"), "{}", pipenv.message);
// An existing environment is refused before any tool runs.
std::fs::create_dir_all(&location).unwrap();
std::fs::write(location.join("pyvenv.cfg"), "home = /python").unwrap();
@@ -1518,6 +1557,7 @@ fn env_tools_are_reported_missing_before_they_run() {
crate::python::VenvTool::Uv,
&base,
&location,
false,
none,
&Default::default(),
&|_| {},
@@ -1540,6 +1580,7 @@ fn an_existing_conda_environment_is_not_recreated() {
crate::python::VenvTool::Conda,
&base,
&location,
false,
none,
&Default::default(),
&|_| {},
@@ -1590,6 +1631,7 @@ fn a_named_conda_environment_is_found_where_conda_put_it() {
crate::python::VenvTool::Conda,
&base,
Path::new("ds"),
false,
which,
&Default::default(),
&|_| {},
@@ -1601,6 +1643,65 @@ fn a_named_conda_environment_is_found_where_conda_put_it() {
assert!(again.message.contains("named ds already exists"), "{}", again.message);
}
#[test]
#[cfg(unix)]
fn pipenv_creates_the_projects_environment_and_never_replaces_one() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let tmp = dunce::canonicalize(tmp.path()).unwrap();
let project = tmp.join("shop");
let home = tmp.join("workon").join(crate::discover::pipenv_env_name(&project));
std::fs::create_dir_all(&project).unwrap();
let python = tmp.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();
// `--venv` fails until the environment exists; `--python` creates it outside the project,
// records the project in `.project` and writes a Pipfile.
let pipenv = tmp.join("pipenv");
std::fs::write(
&pipenv,
format!(
"#!/bin/sh\nhome='{home}'\nif [ \"$1\" = --venv ]; then [ -f \"$home/pyvenv.cfg\" ] || exit 1; echo \"$home\"; exit 0; fi\n\
[ \"$PIPENV_YES\" = 1 ] || exit 3\necho \"$@\" >> calls\n[ \"$1\" = --python ] || exit 0\n\
mkdir -p \"$home/bin\"\ncp '{python}' \"$home/bin/python\"\necho 'version = 3.12.1' > \"$home/pyvenv.cfg\"\n\
touch Pipfile\npwd -P > \"$home/.project\"\n",
home = home.display(),
python = python.display()
),
)
.unwrap();
std::fs::set_permissions(&pipenv, std::fs::Permissions::from_mode(0o755)).unwrap();
let which = |tool: &str| (tool == "pipenv").then(|| pipenv.clone());
let create = |install: bool| {
crate::python::create_venv_with(
crate::python::VenvTool::Pipenv,
&python,
&project.join(".venv"),
install,
which,
&Default::default(),
&|_| {},
)
};
let calls = || std::fs::read_to_string(project.join("calls")).unwrap_or_default();
// The project had no Pipfile: the one pipenv writes is installed from, as asked.
let sdk = create(true).unwrap();
assert_eq!(&*sdk.path, home.join("bin/python").as_path());
assert_eq!((sdk.name.as_str(), sdk.source.as_str()), ("Python 3.12 (Pipenv: shop)", "pipenv"));
assert_eq!(calls(), format!("--python {}\ninstall --dev\n", python.display()));
// An existing environment is reused, never created again with `--python` (which replaces one
// of another version); one pipenv left without `.project` is still the project's.
std::fs::remove_file(home.join(".project")).unwrap();
assert_eq!(create(false).unwrap().source, "pipenv");
assert_eq!(calls().lines().count(), 2);
// On another Python than the base, nothing runs and the error says what to do.
std::fs::write(home.join("pyvenv.cfg"), "version = 3.11.4\n").unwrap();
let err = create(true).unwrap_err();
assert!(err.message.contains("Python 3.11 environment, not Python 3.12"), "{}", err.message);
assert!(err.message.contains("pipenv --rm"), "{}", err.message);
assert_eq!(calls().lines().count(), 2);
}
#[test]
fn neutral_dir_is_fresh_and_empty() {
let a = crate::python::neutral_dir().unwrap();
+105 -1
View File
@@ -13,6 +13,8 @@ use std::time::{Duration, Instant};
/// How long a cancelled git's process group (remote helpers, `ssh`, credential helpers) gets
/// to exit on `SIGTERM` before `SIGKILL`: git removes its `index.lock` on `SIGTERM`.
const KILL_GRACE: Duration = Duration::from_millis(20);
/// Longest the wait for a captured child sleeps before it looks at cancellation again.
const POLL: Duration = Duration::from_millis(20);
/// A throwaway index file in the repository's Git directory.
pub(crate) struct TempIndex(PathBuf);
@@ -653,9 +655,13 @@ pub(crate) fn capture_command(
}
_ => None,
};
// When both readers finish, their senders disconnect the channel and wake the child wait.
let (closed_tx, closed) = mpsc::channel::<()>();
let capture = |mut pipe: Box<dyn Read + Send>| {
let overflow = overflow.clone();
let closed_tx = closed_tx.clone();
std::thread::spawn(move || {
let _closed_tx = closed_tx;
let mut bytes = Vec::new();
(&mut pipe).take(max.saturating_add(1) as u64).read_to_end(&mut bytes)?;
if bytes.len() > max {
@@ -667,6 +673,9 @@ pub(crate) fn capture_command(
};
let stdout = capture(Box::new(child.stdout.take().expect("piped stdout")));
let stderr = capture(Box::new(child.stderr.take().expect("piped stderr")));
drop(closed_tx);
let mut pipes_open = true;
let mut backoff = Duration::from_micros(100);
let status = loop {
if cancel.is_cancelled() || overflow.load(std::sync::atomic::Ordering::Acquire) {
terminate_tree(&mut child, KILL_GRACE);
@@ -684,7 +693,15 @@ pub(crate) fn capture_command(
if let Some(status) = child.try_wait()? {
break status;
}
std::thread::sleep(Duration::from_millis(20));
if pipes_open {
// Cancellation and overflow are only noticed between wake-ups, so wait at most one
// `POLL` for them; the pipes closing ends the wait at once.
pipes_open = !matches!(closed.recv_timeout(POLL), Err(mpsc::RecvTimeoutError::Disconnected));
} else {
// Reap promptly after EOF, but back off if the child keeps running without its pipes.
std::thread::sleep(backoff);
backoff = (backoff * 2).min(POLL);
}
};
if let Some(w) = writer {
let _ = w.join();
@@ -1245,3 +1262,90 @@ mod index_lock_tests {
assert!(!retryable_index_conflict(&["reset"], &out));
}
}
#[cfg(all(test, unix))]
mod capture_tests {
use super::*;
fn sh(script: &str) -> Command {
let mut cmd = Command::new("sh");
cmd.args(["-c", script]);
cmd
}
#[test]
fn a_cancelled_capture_kills_a_long_running_child() {
let cancel = CancellationToken::new();
let trigger = cancel.clone();
let canceller = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(100));
trigger.cancel();
});
let start = Instant::now();
let error = capture_command(sh("sleep 60"), None, &cancel, usize::MAX, "sh").err().unwrap();
canceller.join().unwrap();
assert_eq!(error.to_string(), IdeError::cancelled().to_string());
assert!(start.elapsed() < Duration::from_secs(30));
}
#[test]
fn cancelling_before_the_start_spawns_nothing() {
let cancel = CancellationToken::new();
cancel.cancel();
let dir = tempfile::tempdir().unwrap();
let marker = dir.path().join("ran");
let mut cmd = sh(r#"touch "$1""#);
cmd.arg("sh").arg(&marker);
assert!(capture_command(cmd, None, &cancel, usize::MAX, "sh").is_err());
assert!(!marker.exists());
}
#[test]
fn megabytes_on_both_streams_are_captured_whole() {
// Both pipes fill at once: a wait that stopped draining one while blocked on the other,
// or on the exit, would deadlock here.
const SIZE: usize = 6_000_000;
let script = format!("(yes e | head -c {SIZE} >&2) & yes o | head -c {SIZE}; wait; exit 3");
let out = capture_command(sh(&script), None, &CancellationToken::new(), usize::MAX, "sh").unwrap();
assert_eq!((out.stdout.len(), out.stderr.len()), (SIZE, SIZE));
assert!(out.stdout.chunks(2).all(|c| c.starts_with(b"o")));
assert!(out.stderr.chunks(2).all(|c| c.starts_with(b"e")));
assert_eq!(out.code, Some(3));
}
#[test]
fn exit_status_and_both_streams_are_preserved() {
let out = capture_command(sh("echo out; echo err >&2; exit 7"), None, &CancellationToken::new(), 1 << 20, "sh")
.unwrap();
assert_eq!((out.stdout, out.stderr, out.code), (b"out\n".to_vec(), b"err\n".to_vec(), Some(7)));
}
#[test]
fn stdin_reaches_the_child() {
let out = capture_command(sh("cat"), Some(b"piped"), &CancellationToken::new(), 1 << 20, "sh").unwrap();
assert_eq!(out.stdout, b"piped");
}
#[test]
fn output_over_the_limit_stops_the_child() {
let start = Instant::now();
let error = capture_command(sh("yes"), None, &CancellationToken::new(), 1000, "sh").err().unwrap();
assert!(error.to_string().contains("exceeds 1000 bytes"), "{error}");
assert!(start.elapsed() < Duration::from_secs(30));
}
#[test]
fn a_child_that_closes_its_pipes_but_keeps_running_is_still_cancellable() {
let cancel = CancellationToken::new();
let trigger = cancel.clone();
let canceller = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(200));
trigger.cancel();
});
let start = Instant::now();
let error = capture_command(sh("exec >&- 2>&-; sleep 60"), None, &cancel, usize::MAX, "sh").err().unwrap();
canceller.join().unwrap();
assert_eq!(error.to_string(), IdeError::cancelled().to_string());
assert!(start.elapsed() < Duration::from_secs(30));
}
}
+12 -2
View File
@@ -113,7 +113,13 @@ fn restrict_project_layer(below: &Json, layer: &mut Json) {
// The IDE-wide interpreter list, its view options and the project interpreters of
// other projects belong to the user's settings, not to one project.
if let Some(python) = layer.get_mut("languages").and_then(|l| l.get_mut("python")).and_then(Json::as_object_mut) {
for key in ["interpreters", "hiddenInterpreters", "hideOtherProjectInterpreters", "showInterpreterPaths"] {
for key in [
"interpreters",
"hiddenInterpreters",
"hideOtherProjectInterpreters",
"showInterpreterPaths",
"interpreterPaths",
] {
python.remove(key);
}
}
@@ -730,6 +736,8 @@ mod tests {
let store = SettingsStore::load(&cfg, Some(&proj));
store.set(SettingsScope::Global, "languages.python.interpreters", json!(["/envs/a/bin/python"])).unwrap();
store.set(SettingsScope::Global, "languages.python.showInterpreterPaths", json!(false)).unwrap();
let paths = json!({ "/envs/a/bin/python": ["/shared/lib"] });
store.set(SettingsScope::Global, "languages.python.interpreterPaths", paths).unwrap();
let loaded = SettingsStore::load(&cfg, Some(&proj)).effective();
assert_eq!(loaded.languages.python.interpreters, ["/envs/a/bin/python"]);
assert!(!loaded.languages.python.show_interpreter_paths);
@@ -739,10 +747,12 @@ mod tests {
proj.join(".openidea/settings.toml"),
"[languages.python]\ninterpreters = [\"/proj/bin/python\"]\n\
hiddenInterpreters = [\"/envs/a/bin/python\"]\nhideOtherProjectInterpreters = true\n\
showInterpreterPaths = true\n",
showInterpreterPaths = true\n\
[languages.python.interpreterPaths]\n\"/envs/a/bin/python\" = [\"/proj/evil\"]\n",
)
.unwrap();
let loaded = SettingsStore::load(&cfg, Some(&proj)).effective();
assert_eq!(loaded.languages.python.interpreter_paths["/envs/a/bin/python"], ["/shared/lib"]);
assert_eq!(loaded.languages.python.interpreters, ["/envs/a/bin/python"]);
assert!(loaded.languages.python.hidden_interpreters.is_empty());
assert!(!loaded.languages.python.hide_other_project_interpreters);
+1 -1
View File
@@ -64,7 +64,7 @@ JSON-RPC 2.0 with `Content-Length` framing (`ide-jsonrpc`), over the server's st
| notification `plugin` | server → client | `{ window, event }` from code plugins of the remote project |
| request `plugin_secret` | server → client | `{ plugin, name }` → `string` or `null`: a secret from the desktop's keychain |
The protocol version is `PROTOCOL_VERSION` in `rpc.rs`. Errors are `IdeError`s carried as JSON in the JSON-RPC error message, so the frontend sees the same `kind` / `message` as for a local command.
The protocol version is `PROTOCOL_VERSION` in `rpc.rs`; the desktop refuses a server that speaks another one. Change it when an existing command's argument or result changes shape. A binary argument is an `IpcBytes` (a base64 string in JSON, `string` in the bindings), never a `Vec<u8>`, which is an array of numbers about 3.6 times the size. Errors are `IdeError`s carried as JSON in the JSON-RPC error message, so the frontend sees the same `kind` / `message` as for a local command.
## Routing commands
+7 -1
View File
@@ -43,7 +43,8 @@ The project interpreter is chosen in this order:
1. The interpreter set in **Settings › Languages & Frameworks › Python Interpreter**.
2. A virtualenv in the project: `.venv`, `venv`, `env` or `.env` (a folder with `pyvenv.cfg`), or a pixi environment in `.pixi/envs/`.
3. The Python version the project pins for mise or asdf (`mise.toml`, `.tool-versions` and the other mise config files).
3. The Pipenv environment for the nearest `Pipfile`, including one selected by a `.venv` file or `PIPENV_CUSTOM_VENV_NAME`.
4. The Python version the project pins for mise or asdf (`mise.toml`, `.tool-versions` and the other mise config files).
The interpreter list on that page also shows what the IDE detects on the machine: the active `VIRTUAL_ENV`, virtualenvs made by virtualenvwrapper, pipenv and Poetry, pyenv versions, Pythons installed by uv, mise and asdf installs, conda environments (Miniconda, Anaconda, Miniforge, Mambaforge, micromamba, and every env that `conda env list` shows), and the `python` executables on `PATH`.
@@ -51,6 +52,10 @@ The selected interpreter is passed to basedpyright and Pyright (`python.pythonPa
The **Python Interpreter** item in the status bar shows the current interpreter. Click it to switch, or to open **Add New Interpreter…** and **Interpreter Settings…**.
### Interpreter paths
**Settings › Languages & Frameworks › Python › All Interpreters › Show Paths for Selected Interpreter** lists the interpreter's `sys.path` and lets you add folders outside the project to it, such as a checkout of a shared library. The added folders are saved per interpreter in the IDE settings, so they apply to every project that uses it. basedpyright and Pyright get them as `extraPaths`, runs, debug sessions, tests and the Python Console get them on `PYTHONPATH`, and they are listed under **External Libraries**. At run time they are searched before the interpreter's own entries. A folder that no longer exists is marked as missing and skipped, and so is one that `PYTHONPATH` cannot hold (not absolute, or with its separator in the name). A folder inside the project is not listed under External Libraries, so its files stay editable. The interpreter's own entries cannot be removed, and a Docker or Compose run target has no paths of its own to edit.
### A Docker or Compose run target as the interpreter
When the project's dependencies are installed only in an image, choose a Docker or Docker Compose [run target](/en/guide/remote/containers#docker-and-docker-compose-run-targets) as the interpreter: the interpreter list and the status bar item show those targets next to the local interpreters.
@@ -69,6 +74,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.
- **Pipenv Environment**: `pipenv --python <base>` in the project (pipenv must be on `PATH`). Pipenv writes a `Pipfile` when the project has none, importing `requirements.txt` if there is one. With **Install packages from Pipfile** it then runs `pipenv install --dev`. An environment the project already has is reused; if it was built on another Python version than the base interpreter, nothing is changed and the dialog says so (remove it with `pipenv --rm` to start over).
- **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.
+1 -1
View File
@@ -64,7 +64,7 @@ openidea-server --stdio | --mcp-stdio [--project <path>] | --connect <host> <por
| 通知 `plugin` | 服务端 → 客户端 | `{ window, event }`:远程项目中代码插件发出的事件 |
| 请求 `plugin_secret` | 服务端 → 客户端 | `{ plugin, name }` → `string` 或 `null`:从桌面端钥匙串取密钥 |
协议版本是 `rpc.rs` 中的 `PROTOCOL_VERSION`。错误是以 JSON 形式放在 JSON-RPC 错误消息里的 `IdeError`,所以前端看到的 `kind` / `message` 与本地命令完全一样。
协议版本是 `rpc.rs` 中的 `PROTOCOL_VERSION`;桌面端会拒绝使用其他版本协议的服务端。已有命令的参数或结果形态改变时要修改它。二进制参数使用 `IpcBytes`(JSON 中是 base64 字符串,绑定中是 `string`),不要用 `Vec<u8>`——它会变成体积约 3.6 倍的数字数组。错误是以 JSON 形式放在 JSON-RPC 错误消息里的 `IdeError`,所以前端看到的 `kind` / `message` 与本地命令完全一样。
## 命令路由
+7 -1
View File
@@ -43,7 +43,8 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
1. **设置 › 语言和框架 › Python 解释器** 中选定的解释器。
2. 项目里的虚拟环境:`.venv`、`venv`、`env` 或 `.env`(含 `pyvenv.cfg` 的目录),或 `.pixi/envs/` 下的 pixi 环境。
3. 项目通过 mise 或 asdf 固定的 Python 版本(`mise.toml`、`.tool-versions` 等 mise 配置文件)。
3. 最近的 `Pipfile` 对应的 Pipenv 环境,包括通过 `.venv` 文件或 `PIPENV_CUSTOM_VENV_NAME` 指定的环境。
4. 项目通过 mise 或 asdf 固定的 Python 版本(`mise.toml`、`.tool-versions` 等 mise 配置文件)。
该页面的解释器列表还会列出 IDE 在本机找到的解释器:当前激活的 `VIRTUAL_ENV`,virtualenvwrapper、pipenv 和 Poetry 创建的虚拟环境,pyenv 的各个版本,uv 安装的 Python,mise 和 asdf 的安装,conda 环境(Miniconda、Anaconda、Miniforge、Mambaforge、micromamba,以及 `conda env list` 能看到的所有环境),还有 `PATH` 上的 `python` 可执行文件。
@@ -51,6 +52,10 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
状态栏上的 **Python 解释器** 显示当前解释器,点击可以切换,也可以打开 **添加新的解释器…** 和 **解释器设置…**。
### 解释器路径
**设置 › 语言和框架 › Python › 所有解释器 › 显示所选解释器的路径** 列出该解释器的 `sys.path`,并可以把项目之外的文件夹(例如共享库的检出目录)添加进去。添加的文件夹按解释器保存在 IDE 设置中,因此对使用该解释器的每个项目生效。basedpyright 和 Pyright 通过 `extraPaths` 获得这些文件夹,运行、调试、测试和 Python 控制台通过 `PYTHONPATH` 获得,它们也会显示在 **External Libraries** 下。运行时它们会先于解释器自带的条目被搜索。已不存在的文件夹会标记为缺失并被跳过;`PYTHONPATH` 无法容纳的文件夹(不是绝对路径,或名称中含有分隔符)同样会被跳过。位于项目内的文件夹不会列在 External Libraries 下,其中的文件仍可编辑。解释器自带的条目不能删除,Docker 或 Compose 运行目标没有可编辑的路径。
### 以 Docker 或 Compose 运行目标作为解释器
如果项目的依赖只安装在镜像里,可以把 Docker 或 Docker Compose [运行目标](/zh/guide/remote/containers#docker-和-docker-compose-运行目标)选为解释器:解释器列表和状态栏项会把这些目标列在本地解释器旁边。
@@ -69,6 +74,7 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
- **Virtualenv 环境**:用你选的基础解释器执行 `python -m venv`。
- **uv 环境**:执行 `uv venv <location> --python <base>`(`PATH` 上需要有 uv)。
- **Poetry 环境**:在项目中执行 `poetry env use <base>`。
- **Pipenv 环境**:在项目中执行 `pipenv --python <base>`(`PATH` 上需要有 pipenv)。项目没有 `Pipfile` 时,Pipenv 会写入一个,有 `requirements.txt` 时从中导入。勾选 **安装 Pipfile 中的软件包** 时,随后执行 `pipenv install --dev`。项目已有的环境会被复用;如果它的 Python 版本与基础解释器不同,不做任何改动并在对话框中提示(可用 `pipenv --rm` 删除后重建)。
- **Conda 环境**:执行 `conda create -n <名称>`,环境建在 conda 的 envs 目录中,Python 版本为所选版本。
也可以直接选择已有的解释器或环境目录。新解释器会成为项目解释器。
+1
View File
@@ -38,6 +38,7 @@ Object.assign(window, {
paddingRight: false,
tooltip: null,
parts: [],
textEdits: [],
},
]);
},
+31
View File
@@ -93,6 +93,37 @@ for (const activation of ["double-click", "Enter"] as const) {
});
}
test("records a modified wheel gesture and runs the assigned action", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
await settings.getByRole("treeitem", { name: "Keymap", exact: true }).click();
await settings.getByRole("textbox", { name: "Search actions" }).fill("Find Action");
const row = settings.getByRole("tree", { name: "Actions" }).getByRole("treeitem", { name: /Find Action/ });
await row.click({ button: "right" });
await page.getByRole("menuitem", { name: "Add Mouse Shortcut", exact: true }).click();
const recorder = page.getByRole("dialog", { name: "Mouse Shortcut: Find Action…", exact: true });
const pad = recorder.getByRole("textbox", { name: "Mouse shortcut" });
await pad.hover();
const scrollUp = async () => {
await page.keyboard.down("Control");
await page.mouse.wheel(0, -120);
await page.keyboard.up("Control");
};
await scrollUp();
await expect(pad).toHaveText("⌃Wheel Up");
const search = page.getByRole("dialog", { name: "Search Everywhere", exact: true });
await expect(search).toBeHidden();
await recorder.getByRole("button", { name: "OK", exact: true }).click();
await expect(row).toContainText("⌃Wheel Up");
await settings.getByRole("button", { name: "OK", exact: true }).click();
await expect(settings).toBeHidden();
await page.mouse.move(700, 450);
await page.mouse.wheel(0, 120);
await expect(search).toBeHidden();
await scrollUp();
await expect(search).toBeVisible();
});
test("rectangular drag remains configurable after removal and saves a middle mouse binding", async ({
workbench: page,
}) => {
+1 -2
View File
@@ -12,9 +12,8 @@ test("the scratch language chooser fits short windows and keeps recents separate
const { setScratchBackend } = await import(/* @vite-ignore */ scratch);
const { rememberLanguage } = await import(/* @vite-ignore */ store);
setScratchBackend({
dataDir: async () => "/test-app-data",
scratchesDir: async () => "/test-app-data/scratches",
listNames: async () => [],
createDir: async () => {},
createFile: async () => {},
languages: async () => [
...Array.from({ length: 24 }, (_, i) => {
+3 -3
View File
@@ -11,11 +11,11 @@ test("local terminal stores clipboard media and pastes one shell-quoted argument
configurable: true,
value: { transformCallback: () => 1 },
});
const stored: { id: number; data: number[]; mime: string }[] = [];
const stored: { id: number; data: string; mime: string }[] = [];
const writes: string[] = [];
commands.termSpawn = async () => ({ status: "ok", data: { id: 838, title: "pwsh", pid: 1 } });
commands.clipboardFileList = async () => ({ status: "ok", data: [] });
commands.termStoreImage = async (id: number, data: number[], mime: string) => {
commands.termStoreImage = async (id: number, data: string, mime: string) => {
stored.push({ id, data, mime });
return { status: "ok", data: "C:\\Temp\\a'b c\\image.png" };
};
@@ -47,6 +47,6 @@ test("local terminal stores clipboard media and pastes one shell-quoted argument
}
});
expect(observed.claimed).toBe(true);
expect(observed.stored).toEqual([{ id: 838, data: [137, 80, 78, 71], mime: "image/png" }]);
expect(observed.stored).toEqual([{ id: 838, data: "iVBORw==", mime: "image/png" }]);
expect(observed.writes).toEqual(["'C:\\Temp\\a''b c\\image.png'"]);
});
+40
View File
@@ -0,0 +1,40 @@
import { expect, test } from "./fixtures";
test("hovering a tinted project tab keeps its colour", async ({ workbench: page }) => {
await page.evaluate(async () => {
const tabColors = "/src/workbench/tabColors.ts";
const windowGroups = "/src/platform/windowGroups.ts";
const { setTabColorOverride } = await import(/* @vite-ignore */ tabColors);
const { useWindowGroup } = await import(/* @vite-ignore */ windowGroups);
setTabColorOverride("/tinted", "#d24b8f");
useWindowGroup.setState({
tabs: [
{ label: "main", name: "acme-api", root: "/plain", current: true },
{ label: "second", name: "acme-api", root: "/plain2", current: false },
{ label: "third", name: "acme-api", root: "/tinted", current: false },
],
});
});
const plain = page.locator('[data-project-tab="second"]');
const tinted = page.locator('[data-project-tab="third"]');
await expect(tinted).toBeVisible();
// A blank strip inside the tab: right of the hover close button, left of the centred label.
const strip = async (tab: typeof plain) => {
const box = (await tab.boundingBox())!;
return { x: box.x + 34, y: box.y + box.height / 2 - 5, width: 8, height: 10 };
};
const shoot = async (tab: typeof plain) => page.screenshot({ clip: await strip(tab), animations: "disabled" });
await tinted.hover();
const tintedHover = await shoot(tinted);
await page.mouse.move(700, 600);
const tintedRest = await shoot(tinted);
await plain.hover();
const plainHover = await shoot(plain);
// The opaque hover surface must not swallow the tint: a tinted tab renders differently from a plain one.
expect(tintedHover.equals(plainHover)).toBe(false);
// Hover still gives feedback on the tinted tab itself.
expect(tintedHover.equals(tintedRest)).toBe(false);
});
+1 -1
View File
@@ -2,7 +2,7 @@ Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: OpenIDEA Java usages
Bundle-SymbolicName: ai.openidea.usages;singleton:=true
Bundle-Version: 1.17.0
Bundle-Version: 1.18.0
Bundle-RequiredExecutionEnvironment: JavaSE-21
Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core,
org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime,
+1 -1
View File
@@ -88,7 +88,7 @@ is not a claim of full IntelliJ feature parity.
## Rebuild and delivery
The checked-in jar is embedded by ide-sdk `include_bytes!`, installed as
`java-usages-1.17.0.jar`, and added alongside existing initialization bundles.
`java-usages-1.18.0.jar`, and added alongside existing initialization bundles.
Users need no compiler, Maven or Python. Manifest/install version must change
when replacing the bundle because OSGi caches bundles.
Binary file not shown.
+1
View File
@@ -19,6 +19,7 @@
</delegateCommandHandler>
<delegateCommandHandler class="ai.openidea.archives.RefreshArchivesCommand">
<command id="openidea.java.refreshArchives"/>
<command id="openidea.java.updateProjectConfigurations"/>
</delegateCommandHandler>
<delegateCommandHandler class="ai.openidea.sources.GeneratedSourcesCommand">
<command id="openidea.java.generatedSources"/>
@@ -1,10 +1,12 @@
package ai.openidea.archives;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
@@ -16,6 +18,8 @@ import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler;
import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin;
import org.eclipse.jdt.ls.core.internal.ProjectUtils;
import org.eclipse.lsp4j.TextDocumentIdentifier;
/**
* Re-reads library archives replaced in place (a SNAPSHOT installed again keeps its path). The
@@ -26,6 +30,17 @@ import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin;
public final class RefreshArchivesCommand implements IDelegateCommandHandler {
@Override
public Object executeCommand(String command, List<Object> arguments, IProgressMonitor monitor) throws Exception {
if ("openidea.java.updateProjectConfigurations".equals(command)) {
List<TextDocumentIdentifier> files = arguments.stream()
.filter(String.class::isInstance)
.map(uri -> new TextDocumentIdentifier((String) uri))
.toList();
Collection<IProject> projects = ProjectUtils.getProjectsFromDocumentIdentifiers(files);
if (!projects.isEmpty()) {
JavaLanguageServerPlugin.getProjectsManager().updateProjects(projects, true).join(0, monitor);
}
return null;
}
IJavaModel model = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot());
model.refreshExternalArchives(null, monitor);
Set<IPath> archives = new HashSet<>();
+3
View File
@@ -286,6 +286,7 @@ fs_read_range always project_host bin
fs_read_text always project_host bindings async
fs_rename always project_host bindings async
fs_resolve_reference always project_host bindings async
fs_scratches_dir always project_host bindings sync
fs_set_writable always project_host bindings sync
fs_synchronize_directories always project_host bindings async
fs_undo_delete always project_host bindings async
@@ -601,6 +602,8 @@ sdk_python_interpreter outside_restricted project_host bin
sdk_python_packages outside_restricted project_host bindings async
sdk_python_pip outside_restricted project_host bindings async
sdk_python_project_interpreters outside_restricted project_host bindings async
sdk_python_sys_path outside_restricted project_host bindings async
sdk_python_user_path_problems outside_restricted project_host bindings async
search_start always project_host bindings async
search_validate always project_host bindings sync
set_recent_project_groups always desktop bindings sync
+41 -5
View File
@@ -680,7 +680,7 @@ export const commands = {
* `charset` (writes the BOM for `utf-8-bom` / UTF-16).
*/
fsCreateFile: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_create_file", { path })),
fsCreateFileBytes: (path: string, data: number[]) => typedError<null, IdeError>(__TAURI_INVOKE("fs_create_file_bytes", { path, data })),
fsCreateFileBytes: (path: string, data: IpcBytes) => typedError<null, IdeError>(__TAURI_INVOKE("fs_create_file_bytes", { path, data })),
/** Moving to the trash can take a while (large trees): kept off the main thread. */
fsDelete: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_delete", { path })),
/** Moves an item to the Trash and returns the snapshot for Project View Undo. */
@@ -707,6 +707,11 @@ export const commands = {
fsRename: (from: string, to: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_rename", { from, to })),
/** The existing file or directory a path written in `from` names (`href`, `url()`, a string literal). */
fsResolveReference: (from: IpcPath, value: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("fs_resolve_reference", { from, value })),
/**
* The scratch files' folder of this host (`<data dir>/scratches`), created. A remote window
* keeps its scratches on the server, where its file commands run.
*/
fsScratchesDir: () => typedError<IpcPath, IdeError>(__TAURI_INVOKE("fs_scratches_dir")),
/**
* Toggle Read-only Attribute: sets the writable bit (and the open document's
* state). Returns whether the file is read-only now.
@@ -1641,8 +1646,11 @@ export const commands = {
* with the Maven / Gradle dependency jars of the build model.
*/
sdkProjectLibraries: (request: RequestId, onGroups: Channel<LibraryGroup[]>) => typedError<LibraryGroup[], IdeError>(__TAURI_INVOKE("sdk_project_libraries", { request, onGroups })),
/** Creates a Python environment with `tool` (`venv` / `uv` / `poetry`); output streams through `on_output`. */
sdkPythonCreateVenv: (tool: VenvTool, base: string, location: string, request: RequestId, onOutput: Channel<string>) => typedError<Sdk, IdeError>(__TAURI_INVOKE("sdk_python_create_venv", { tool, base, location, request, onOutput })),
/**
* Creates a Python environment with `tool` (`venv` / `uv` / `poetry` / `pipenv`); output streams through
* `on_output`. `install_packages` also installs what the project's `Pipfile` declares (pipenv).
*/
sdkPythonCreateVenv: (tool: VenvTool, base: string, location: string, installPackages: boolean, request: RequestId, onOutput: Channel<string>) => typedError<Sdk, IdeError>(__TAURI_INVOKE("sdk_python_create_venv", { tool, base, location, installPackages, request, onOutput })),
/** The interpreter the project uses: the configured one, else its virtualenv. */
sdkPythonEffective: (near: string | null) => typedError<string | null, IdeError>(__TAURI_INVOKE("sdk_python_effective", { near })),
/** An existing Python executable or virtualenv folder as an SDK; `None` if Python cannot run. */
@@ -1670,6 +1678,13 @@ export const commands = {
sdkPythonPip: (python: string, requirement: string, uninstall: boolean, upgrade: boolean, request: RequestId, onOutput: Channel<string>) => typedError<null, IdeError>(__TAURI_INVOKE("sdk_python_pip", { python, requirement, uninstall, upgrade, request, onOutput })),
/** The Python interpreters of the recently opened projects, each with its project. */
sdkPythonProjectInterpreters: () => typedError<ProjectInterpreter[], IdeError>(__TAURI_INVOKE("sdk_python_project_interpreters")),
/** `sys.path` of the interpreter `python`, for All Interpreters › Show Paths. */
sdkPythonSysPath: (python: string, request: RequestId) => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("sdk_python_sys_path", { python, request })),
/**
* For each folder added to an interpreter's paths, why it stays off the import path
* (`None`: it is used). The folders may not be saved yet.
*/
sdkPythonUserPathProblems: (paths: string[]) => typedError<(UserPathProblem | null)[], IdeError>(__TAURI_INVOKE("sdk_python_user_path_problems", { paths })),
/**
* Find in Files. Results stream through `on_event`; ends with `Done`.
* Cancel with `cancel_request(request)`.
@@ -1818,7 +1833,7 @@ export const commands = {
* to start the shell takes tens of milliseconds, a frozen UI if run there.
*/
termSpawn: (options: TerminalOptions, onOutput: Channel<string>) => typedError<TerminalInfo, IdeError>(__TAURI_INVOKE("term_spawn", { options, onOutput })),
termStoreImage: (id: TerminalId, data: number[], mime: string) => typedError<string, IdeError>(__TAURI_INVOKE("term_store_image", { id, data, mime })),
termStoreImage: (id: TerminalId, data: IpcBytes, mime: string) => typedError<string, IdeError>(__TAURI_INVOKE("term_store_image", { id, data, mime })),
termWrite: (id: TerminalId, data: string) => typedError<null, IdeError>(__TAURI_INVOKE("term_write", { id, data })),
/**
* Installs (or reinstalls) a tool into `<app-data>/tools`, streaming output through
@@ -8125,6 +8140,8 @@ export type InlayHint = {
* their values concatenate to `label`.
*/
parts: InlayLabelPart[],
/** The edits that turn the hint into code (an annotation and any import it needs). */
textEdits: TextEdit[],
};
/** Editor › Inlay Hints. */
@@ -8366,6 +8383,9 @@ export type InvalidateCachesOptions = {
buildCaches?: boolean,
};
/** A binary argument or result of an IPC command. */
export type IpcBytes = string;
/** A path field of an IPC type. */
export type IpcPath = string;
@@ -9197,6 +9217,8 @@ export type LogcatLine = {
};
export type LspRefreshKind = "inlayHints" | "semanticTokens" | "codeLens" |
/** An import or classpath update may have changed inheritance search results. */
"inheritance" |
/** The Dart server published a document's Flutter outline. */
"flutterOutline";
@@ -11373,6 +11395,11 @@ export type PythonSettings = {
hideOtherProjectInterpreters?: boolean,
/** Show each interpreter's path under its name on the interpreters page. */
showInterpreterPaths?: boolean,
/**
* Folders the user added to an interpreter's `sys.path` (All Interpreters › Show Paths),
* by interpreter executable; absolute or `~/`.
*/
interpreterPaths?: { [key in string]: string[] },
};
/** Color Scheme › Language Defaults › Rainbow brackets: which delimiters are coloured. */
@@ -13655,6 +13682,13 @@ export type UpstreamTracking = {
branch: string,
};
/** Why a folder added to an interpreter's paths stays off the import path. */
export type UserPathProblem =
/** Not an existing folder. */
"missing" |
/** Not absolute or `~/`, or it holds the separator of `PYTHONPATH`. */
"invalid";
export type Variable = Variable_Serialize | Variable_Deserialize;
export type Variable_Deserialize = {
@@ -13759,7 +13793,9 @@ export type VenvTool =
/** `poetry env use <base>` in the project, then `poetry env info --path`. */
"poetry" |
/** `conda create -n <name> -y` for a bare name, else `-p <location>` (conda must be on PATH). */
"conda";
"conda" |
/** `pipenv --python <base>` in the project (pipenv must be on PATH). */
"pipenv";
/** What a view or custom editor shows. */
export type View = {
+2 -2
View File
@@ -172,10 +172,10 @@ it.each([
vi.stubGlobal(
"Worker",
class {
onmessage?: (e: { data: { data: number[] } }) => void;
onmessage?: (e: { data: { data: string } }) => void;
terminate() {}
postMessage() {
queueMicrotask(() => this.onmessage?.({ data: { data: [137, 80, 78, 71] } }));
queueMicrotask(() => this.onmessage?.({ data: { data: "iVBORw==" } }));
}
},
);
+4 -7
View File
@@ -1,12 +1,9 @@
import { toBase64 } from "@/platform/base64";
// Keep binary conversion off the editor thread, including for large clipboard images.
self.onmessage = async (event: MessageEvent<Blob | string>) => {
self.onmessage = async (event: MessageEvent<Blob>) => {
try {
const source = event.data;
const data =
typeof source === "string"
? Array.from(atob(source.slice(source.indexOf(",") + 1)), (byte) => byte.charCodeAt(0))
: Array.from(new Uint8Array(await source.arrayBuffer()));
self.postMessage({ data });
self.postMessage({ data: toBase64(new Uint8Array(await event.data.arrayBuffer())) });
} catch (error) {
self.postMessage({ error: String(error) });
}
+22 -8
View File
@@ -3,6 +3,7 @@ import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { history, undo } from "@codemirror/commands";
import { IpcError, commands } from "@/platform/ipc";
import { handleFileDrop } from "@/workbench/fileDrop";
import { imageName, imageTarget, markdownImages, relativeImagePath, saveImage } from "./markdownImages";
const views: EditorView[] = [];
@@ -38,9 +39,7 @@ describe("Markdown images", () => {
.mockRejectedValueOnce(new IpcError({ kind: "alreadyExists", message: "exists" }))
.mockRejectedValueOnce(new IpcError({ kind: "alreadyExists", message: "exists" }))
.mockResolvedValue(null);
expect(await saveImage("/p/docs/readme.md", "assets", "photo.png", [0, 255], create)).toBe(
"![](assets/photo-2.png)",
);
expect(await saveImage("/p/docs/readme.md", "assets", "photo.png", "AP8=", create)).toBe("![](assets/photo-2.png)");
expect(create.mock.calls.map(([path]) => path)).toEqual([
"/p/docs/assets/photo.png",
"/p/docs/assets/photo-1.png",
@@ -49,7 +48,7 @@ describe("Markdown images", () => {
});
it("does not retry permission failures", async () => {
const create = vi.fn().mockRejectedValue(new IpcError({ kind: "permissionDenied", message: "denied" }));
await expect(saveImage("/p/a.md", "assets", "a.png", [], create)).rejects.toThrow("denied");
await expect(saveImage("/p/a.md", "assets", "a.png", "", create)).rejects.toThrow("denied");
expect(create).toHaveBeenCalledTimes(1);
});
it("computes nested paths and encodes spaces and Markdown delimiters", () => {
@@ -82,10 +81,10 @@ describe("Markdown images", () => {
vi.stubGlobal(
"Worker",
class {
onmessage?: (e: { data: { data: number[] } }) => void;
onmessage?: (e: { data: { data: string } }) => void;
terminate() {}
postMessage() {
queueMicrotask(() => this.onmessage?.({ data: { data: [137, 80, 78, 71] } }));
queueMicrotask(() => this.onmessage?.({ data: { data: "iVBORw==" } }));
}
},
);
@@ -98,16 +97,31 @@ describe("Markdown images", () => {
paste(editor, [new File(["png"], "image.png", { type: "image/png" })]);
await vi.waitFor(() => expect(create).toHaveBeenCalledTimes(1));
expect(create.mock.calls[0]![0]).toMatch(hasFile ? /assets\/image\.png$/ : /assets\/image-\d{8}-\d{6}\.png$/);
expect(create.mock.calls[0]![1]).toBe("iVBORw==");
});
it("writes the base64 from a native image drop directly", async () => {
const invoke = vi.fn().mockResolvedValue("data:image/png;base64,AP8=");
vi.stubGlobal("__TAURI_INTERNALS__", { invoke });
const create = vi.spyOn(commands, "fsCreateFileBytes").mockResolvedValue({ status: "ok", data: null });
const editor = view();
vi.spyOn(editor, "posAtCoords").mockReturnValue(7);
await handleFileDrop(["/source/photo.png"], 0, 0);
expect(invoke).toHaveBeenCalledWith("fs_read_image", { path: "/source/photo.png" }, undefined);
await vi.waitFor(() => expect(create).toHaveBeenCalledWith("/project/docs/assets/photo.png", "AP8="));
expect(editor.state.doc.toString()).toBe("before ![](assets/photo.png)after");
});
it("inserts a paste as one isolated undo step and tracks edits during saving", async () => {
vi.stubGlobal(
"Worker",
class {
onmessage?: (e: { data: { data: number[] } }) => void;
onmessage?: (e: { data: { data: string } }) => void;
terminate() {}
postMessage() {
queueMicrotask(() => this.onmessage?.({ data: { data: [137, 80, 78, 71] } }));
queueMicrotask(() => this.onmessage?.({ data: { data: "iVBORw==" } }));
}
},
);
+7 -4
View File
@@ -65,8 +65,8 @@ export async function saveImage(
markdown: string,
folder: string,
name: string,
data: number[],
create = (path: string, bytes: number[]) => call(commands.fsCreateFileBytes(path, bytes)),
data: string,
create = (path: string, base64: string) => call(commands.fsCreateFileBytes(path, base64)),
): Promise<string> {
const dot = name.lastIndexOf(".");
const stem = dot > 0 ? name.slice(0, dot) : name;
@@ -82,12 +82,15 @@ export async function saveImage(
}
}
function imageBytes(blob: Blob | string): Promise<number[]> {
/** The image as base64, the form `fsCreateFileBytes` takes. */
function imageBytes(blob: Blob | string): Promise<string> {
if ((typeof blob === "string" ? blob.length * 0.75 : blob.size) > MAX_IMAGE_BYTES)
return Promise.reject(new Error(tx("Image exceeds 16 MB.")));
// The data URL from fs_read_image already contains standard base64.
if (typeof blob === "string") return Promise.resolve(blob.slice(blob.indexOf(",") + 1));
return new Promise((resolve, reject) => {
const worker = new Worker(new URL("./imageBytes.worker.ts", import.meta.url), { type: "module" });
worker.onmessage = (event: MessageEvent<{ data: number[]; error?: string }>) => {
worker.onmessage = (event: MessageEvent<{ data: string; error?: string }>) => {
worker.terminate();
if (event.data.error) reject(new Error(event.data.error));
else resolve(event.data.data);
+3 -2
View File
@@ -52,7 +52,8 @@ import { call, commands, isErrorKind, isTauri } from "@/platform/ipc";
import { openLightweightEditor } from "./openLightweightEditor";
import { windowBackgroundHex } from "@/workbench/theme";
import { hoverActionsAt } from "@/platform/hoverActions";
import { save as saveFileDialog, type DialogFilter as SaveDialogFilter } from "@/platform/dialog";
import { chooseSavePath } from "@/platform/choosePath";
import type { DialogFilter as SaveDialogFilter } from "@/platform/dialog";
import { isUntitledUri, untitledTitle } from "@/platform/virtualDocs";
import { isRemoteWindow } from "@/platform/remote";
import { auxiliaryWindow } from "@/platform/auxWindow";
@@ -1299,7 +1300,7 @@ export class EditorController implements SlotHost {
* every tab showing it becomes a file tab.
*/
private async saveUntitled(model: import("./model/document").DocModel): Promise<boolean> {
const path = await saveFileDialog({
const path = await chooseSavePath({
title: tx("Save As"),
defaultPath: this.saveAsSuggestion(model),
filters: await languageFilters(),
+39 -1
View File
@@ -1,8 +1,10 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { useEditorRegistry, type TextEditorHandle } from "@/editor/api";
import { useProject } from "@/platform/project";
import { registerAction } from "@/platform/actions";
import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
import { fontZoom, resetAllEditorsFontZoom, setFontZoom, stepAllEditorsFontZoom, wheelZoom } from "./cm/prefs";
import { resetWheelZoomGesture } from "@/platform/wheelZoom";
@@ -57,6 +59,42 @@ describe("editor font zoom (active editor by default, all editors when configure
expect(zoomOf(view)).toBe(0);
});
it("zooms when no enabled keymap action claims the gesture", () => {
const original = useKeymap.getState();
const view = makeView();
const run = vi.fn();
let enabled = true;
const unregister = registerAction({ id: "test.wheel", title: "Test", enabled: () => enabled, run });
const uninstall = installKeyboardDispatcher(window);
useKeymap.setState({ overrides: { "test.wheel": ["Ctrl+WheelUp"] } });
const scroll = (deltaY: number) => {
const event = new WheelEvent("wheel", {
bubbles: true,
cancelable: true,
ctrlKey: true,
deltaY,
deltaMode: WheelEvent.DOM_DELTA_LINE,
});
view.contentDOM.dispatchEvent(event);
expect(event.defaultPrevented).toBe(true);
};
try {
scroll(-1);
expect(run).toHaveBeenCalledOnce();
expect(zoomOf(view)).toBe(0);
scroll(1);
expect(zoomOf(view)).toBe(-1);
enabled = false;
scroll(-1);
expect(run).toHaveBeenCalledOnce();
expect(zoomOf(view)).toBe(0);
} finally {
uninstall();
unregister();
useKeymap.setState(original);
}
});
it("zooms every open editor from ⌘/Ctrl+wheel when wheelZoomScope is 'all' (#2480)", () => {
useProject.setState({ settings: { editor: { general: { wheelZoomScope: "all" } } } } as never);
const first = makeView();
+1
View File
@@ -11,6 +11,7 @@ import { VirtualBanner } from "./view/Banner";
const ipc = vi.hoisted(() => ({ support: vi.fn(), sources: vi.fn(), cancel: vi.fn(), choose: vi.fn() }));
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
isTauri: () => true,
commands: { lspCanDownloadSources: ipc.support, lspLibrarySources: ipc.sources, cancelRequest: ipc.cancel },
}));
vi.mock("@tauri-apps/plugin-dialog", () => ({ open: ipc.choose }));
+3 -2
View File
@@ -1,6 +1,7 @@
import { useEffect, useState } from "react";
import { create } from "zustand";
import { registerActions } from "@/platform/actions";
import { choosePath } from "@/platform/choosePath";
import { call, commands, isCancelled, nextRequestId, onIdeEvent, type RequestId } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
@@ -26,8 +27,8 @@ async function retrieve(path: string, choose: boolean) {
try {
let sources: string | null = null;
if (choose) {
const { open } = await import("@/platform/dialog");
const selected = await open({
const selected = await choosePath({
directory: false,
title: tx("Choose Sources…"),
filters: [{ name: tx("Source archives"), extensions: ["jar", "zip"] }],
});
+1
View File
@@ -40,6 +40,7 @@ const hint: InlayHint = {
location: { path: "/p/foo.rs", range: { start: { line: 4, col: 7 }, end: { line: 4, col: 10 } } },
},
],
textEdits: [],
};
const views: EditorView[] = [];
+1
View File
@@ -25,6 +25,7 @@ const ok = (label: string) => ({
paddingLeft: false,
paddingRight: false,
tooltip: null,
textEdits: [],
},
] as InlayHint[],
});
+4
View File
@@ -10,6 +10,7 @@ import { indentUnit } from "@codemirror/language";
import { diff } from "@codemirror/merge";
import { commands, isCancelled, type CodeAction, type Diagnostic } from "@/platform/ipc";
import {
asyncIntentionProviders,
contributedIntentions,
contributedIntentionsAsync,
contributedQuickFixes,
@@ -881,5 +882,8 @@ export function intentionsExtension(): Extension {
bulbPlugin,
floatingBulb,
intentionProviders.of((view) => languageSemantics(docOf(view)?.language)?.intentions?.(view) ?? []),
asyncIntentionProviders.of(
async (view, signal) => (await languageSemantics(docOf(view)?.language)?.asyncIntentions?.(view, signal)) ?? [],
),
];
}
+2
View File
@@ -57,6 +57,8 @@ export interface LanguageSemantics {
constructDocumentation?(name: string): string | null;
/** Bulb intentions contributed on this language's documents. */
intentions?(view: EditorView): ContributedIntention[];
/** Intentions that need the language server's answer first; `signal` aborts when the caret moved on. */
asyncIntentions?(view: EditorView, signal: AbortSignal): Promise<ContributedIntention[]>;
/** Fallback for the Implement Methods action when the server offers no code action. */
implementMethods?(view: EditorView): Promise<boolean>;
}
+4 -1
View File
@@ -13,6 +13,8 @@ import {
type PythonSymbolKind,
} from "./highlight";
import { implementPythonAbstractMethods, pythonMemberIntentions } from "./members";
import { pythonTypeHintIntentions } from "./typeHints";
import { pythonStringIntentions } from "./stringFormat";
/** Server tokens these kinds override: the kind's own classes replace the generic ones. */
const VARIABLE_KINDS = new Set<PythonSymbolKind>([
@@ -52,7 +54,8 @@ const pythonSemantics: LanguageSemantics = {
}
},
isLocal: ({ type, kind }) => (kind ? kind === "localVariable" || kind === "parameter" : type === "parameter"),
intentions: pythonMemberIntentions,
intentions: (view) => [...pythonMemberIntentions(view), ...pythonStringIntentions(view)],
asyncIntentions: pythonTypeHintIntentions,
implementMethods: implementPythonAbstractMethods,
};
@@ -0,0 +1,118 @@
import { describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { completedSyntaxTree } from "@/test/syntax";
import { findLanguageDescription, loadSupport } from "../../../core/cm/languages";
import { stringConversions } from "./stringFormat";
/** `expr`'s conversions with the caret on its first character, by kind. */
async function convert(expr: string): Promise<Record<string, string>> {
const support = await loadSupport(findLanguageDescription("Python", "demo.py")!);
const source = `x = ${expr}\n`;
const state = EditorState.create({ doc: source, extensions: [support!] });
const found = stringConversions(completedSyntaxTree(state), state.doc, 4);
return Object.fromEntries(found.map((c) => [c.kind, c.text]));
}
describe("Python string formatting conversions", () => {
it("converts %-formatting to an f-string and to str.format()", async () => {
expect(await convert(`"Hello %s, you are %d" % (name, age)`)).toEqual({
fString: `f"Hello {name}, you are {int(age)}"`,
format: `"Hello {}, you are {}".format(name, int(age))`,
});
expect(await convert(`'%s' % user.name`)).toEqual({ fString: `f'{user.name}'`, format: `'{}'.format(user.name)` });
});
it("maps flags, widths, precisions and conversions", async () => {
expect((await convert(`"%5s|%-5s|%r|%.2f|%05d|%+x|%-8.3e|%%" % (a, b, c, d, e, f, g)`)).fString).toBe(
`f"{a!s:>5}|{b!s:<5}|{c!r}|{d:.2f}|{int(e):05d}|{f:+x}|{g:<8.3e}|%"`,
);
});
it("supports a mapping with a dict literal and escapes braces", async () => {
expect(await convert(`"{%(n)s} %(m)r" % {"n": 1, 'm': x}`)).toEqual({
fString: `f"{{{1}}} {x!r}"`,
format: `"{{{n}}} {m!r}".format(n=1, m=x)`,
});
});
it("converts str.format() calls to f-strings", async () => {
expect((await convert(`"{} in {}".format(count, path)`)).fString).toBe(`f"{count} in {path}"`);
expect((await convert(`"{1}-{0}-{1}".format(a, b)`)).fString).toBe(`f"{b}-{a}-{b}"`);
expect((await convert(`"{name!r:>10} {{x}}".format(name=user.name)`)).fString).toBe(`f"{user.name!r:>10} {{x}}"`);
expect((await convert(`"{0.real} {1[0]}".format(a + b, items)`)).fString).toBe(`f"{(a + b).real} {items[0]}"`);
expect((await convert(`r'\\d{}'.format(n)`)).fString).toBe(`rf'\\d{n}'`);
expect((await convert(`u"{}".format({1: 2})`)).fString).toBe(`f"{ {1: 2}}"`);
});
it("offers nothing when the result could behave differently or be invalid", async () => {
for (const expr of [
`b"%s" % x`,
`"%s %s" % (a,)`,
`"%s" % (*a,)`,
`"%c" % 65`,
`"%*d" % (3, 4)`,
`"%(a)s" % mapping`,
`"{}".format(*args)`,
`"{}".format(**kw)`,
`"{}".format(a, b)`,
`"{0}{0}".format(next(it))`,
`"{:{w}}".format(a, w=3)`,
`"{x[key]}".format(x=d)`,
`"{}".format(d["key"])`,
`"{}".format("\\n".join(lines))`,
])
expect(await convert(expr), expr).toEqual({});
expect((await convert(`'{}'.format(d["key"])`)).fString).toBe(`f'{d["key"]}'`);
});
it("keeps %d's truncation with int() unless the value is an int already", async () => {
expect(await convert(`"%d%%" % (ratio * 100)`)).toEqual({
fString: `f"{int(ratio * 100)}%"`,
format: `"{}%".format(int(ratio * 100))`,
});
expect((await convert(`"%s of %d tasks, %i/%d" % (len(done), len(tasks), 3, int(x))`)).fString).toBe(
`f"{len(done)} of {len(tasks)} tasks, {3}/{int(x)}"`,
);
expect(await convert(`"%(n)d is %(n)s" % {"n": x}`)).toEqual({ fString: `f"{int(x)} is {x}"` });
});
it("leaves \\N{...} escapes alone, except in raw strings", async () => {
expect(await convert(`"\\N{BULLET} %s" % x`)).toEqual({
fString: `f"\\N{BULLET} {x}"`,
format: `"\\N{BULLET} {}".format(x)`,
});
expect((await convert(`"\\N{BULLET} {}".format(x)`)).fString).toBe(`f"\\N{BULLET} {x}"`);
expect((await convert(`"\\\\N{x} %s" % y`)).fString).toBe(`f"\\\\N{{x}} {y}"`);
expect((await convert(`r"\\N{x} %s" % y`)).fString).toBe(`rf"\\N{{x}} {y}"`);
});
it("declines integer precisions and keyword names in .format()", async () => {
expect(await convert(`"%.2d" % h`)).toEqual({});
expect(await convert(`"%(class)s" % {"class": c}`)).toEqual({ fString: `f"{c}"` });
});
it("does not rewrite format expressions with missing or inconsistent field references", async () => {
for (const expr of [
`"%(name)s" % {"other": value}`,
`"%(name)s" % {}`,
`"{}{0}".format(a)`,
`"{0}{}".format(a, b)`,
`"{name}".format(name=)`,
])
expect(await convert(expr), expr).toEqual({});
});
it("uses valid Python syntax for field accessors", async () => {
expect(await convert(`"{0[001]}".format(items)`)).toEqual({ fString: `f"{items[1]}"` });
expect(await convert(`"{0.class}".format(obj)`)).toEqual({});
});
it("keeps the order and evaluation count of arguments with side effects", async () => {
expect(await convert(`"{1}-{0}".format(first(), second())`)).toEqual({});
expect(await convert(`"{b}-{a}".format(a=first(), b=second())`)).toEqual({});
expect(await convert(`"%(name)s" % {"name": first(), "name": second()}`)).toEqual({});
expect(await convert(`"%(b)s-%(a)s" % {"a": first(), "b": second()}`)).toEqual({
format: `"{b}-{a}".format(a=first(), b=second())`,
});
});
});
@@ -0,0 +1,360 @@
/**
* PyCharm's "Convert to f-string literal" and "Replace with str.format() call"
* on `%`-formatting and `str.format()` calls. A conversion that could change
* what the code does, or produce code an older Python rejects, is not offered.
* As in PyCharm, a single `%` operand that is not a tuple literal is taken as one
* value: a variable holding a tuple would format differently after conversion.
*/
import { syntaxTree } from "@codemirror/language";
import type { Text } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import type { SyntaxNode, Tree } from "@lezer/common";
import type { ContributedIntention } from "@/editor/api";
import { tx } from "@/platform/i18n";
import { docOf } from "../../lsp";
export interface StringConversion {
kind: "fString" | "format";
from: number;
to: number;
text: string;
}
interface Field {
/** Auto-numbered (null), positional index or keyword. */
key: number | string | null;
/** `.attr` / `[0]` accessors after the field name. */
tail: string;
conv: string;
spec: string;
/** A `%d`/`%i`/`%u` field: `%` truncates a float with `int()`, a `d` format spec raises. */
int?: boolean;
}
/** Literal text, already brace-escaped as it appears in the result. */
type Part = string | Field;
interface Arg {
text: string;
node: SyntaxNode | null;
}
interface Literal {
prefix: string;
raw: boolean;
quote: string;
body: string;
}
function literal(text: string): Literal | null {
const prefix = /^[A-Za-z]*/.exec(text)![0];
if (/[bBfFtT]/.test(prefix)) return null;
const rest = text.slice(prefix.length);
const quote = rest.startsWith('"""') || rest.startsWith("'''") ? rest.slice(0, 3) : rest[0]!;
return {
prefix: prefix.replace(/[uU]/, ""),
raw: /[rR]/.test(prefix),
quote,
body: rest.slice(quote.length, rest.length - quote.length),
};
}
/** Comma-separated groups of `node`'s children, brackets dropped. */
function groups(node: SyntaxNode): SyntaxNode[][] {
const out: SyntaxNode[][] = [[]];
for (let c = node.firstChild; c; c = c.nextSibling) {
if (/^[([{]$|^[)\]}]$/.test(c.name)) continue;
if (c.name === ",") out.push([]);
else out[out.length - 1]!.push(c);
}
return out.filter((g) => g.length);
}
const argOf = (doc: Text, g: SyntaxNode[]): Arg => ({
text: doc.sliceString(g[0]!.from, g[g.length - 1]!.to),
node: g.length === 1 ? g[0]! : null,
});
const escapeBraces = (s: string) => s.replace(/[{}]/g, "$&$&");
/** Length of a `\\` or `\N{NAME}` escape at `i` of a non-raw literal; its braces are not fields. */
function escapeLength(body: string, i: number): number {
if (body[i] !== "\\") return 0;
if (body[i + 1] === "\\") return 2;
if (body[i + 1] !== "N" || body[i + 2] !== "{") return 0;
const end = body.indexOf("}", i);
return end < 0 ? 0 : end + 1 - i;
}
const PERCENT = /%(?:\((\w+)\))?([#0 +-]*)(\d+)?(?:\.(\d+))?[hlL]?([diouxXeEfFgGrsa%])/y;
/** The fields of a `%` format string; null when a conversion has no f-string equivalent. */
export function percentParts(body: string, raw = false): Part[] | null {
const parts: Part[] = [];
let text = "";
for (let i = 0; i < body.length;) {
const escape = raw ? 0 : escapeLength(body, i);
if (escape) {
text += body.slice(i, i + escape);
i += escape;
continue;
}
if (body[i] !== "%") {
text += escapeBraces(body[i++]!);
continue;
}
PERCENT.lastIndex = i;
const m = PERCENT.exec(body);
if (!m) return null;
i = PERCENT.lastIndex;
const [all, key, flags = "", width = "", precision] = m;
const type = m[5]!;
if (type === "%") {
if (all !== "%%") return null;
text += "%";
continue;
}
const prec = precision === undefined ? "" : `.${precision}`;
// An integer's `%` precision pads with zeros; a format spec rejects it.
if (prec && "diuoxX".includes(type)) return null;
const int = "diu".includes(type);
let conv = "";
let spec: string;
if ("sra".includes(type)) {
conv = type === "s" && !width && !prec ? "" : `!${type}`;
spec = (width ? (flags.includes("-") ? "<" : ">") : "") + width + prec;
} else {
const align = flags.includes("-") ? "<" : "";
const sign = flags.includes("+") ? "+" : flags.includes(" ") ? " " : "";
const zero = flags.includes("0") && !align && width ? "0" : "";
const rest = align + sign + (flags.includes("#") ? "#" : "") + zero + width + prec;
spec = int ? rest && `${rest}d` : rest + type;
}
parts.push(text, { key: key ?? null, tail: "", conv, spec: spec && `:${spec}`, ...(int && { int }) });
text = "";
}
parts.push(text);
return parts;
}
const FIELD = /^(\d+|[A-Za-z_]\w*)?((?:\.[A-Za-z_]\w*|\[\d+\])*)(![rsa])?(:[^{}]*)?$/;
/** The fields of a `str.format` string; null for nested or malformed fields. */
export function formatParts(body: string, raw = false): Part[] | null {
const parts: Part[] = [];
let text = "";
for (let i = 0; i < body.length;) {
const escape = raw ? 0 : escapeLength(body, i);
if (escape) {
text += body.slice(i, i + escape);
i += escape;
continue;
}
const c = body[i]!;
if ((c === "{" || c === "}") && body[i + 1] === c) {
text += c + c;
i += 2;
continue;
}
if (c === "}") return null;
if (c !== "{") {
text += c;
i++;
continue;
}
const end = body.indexOf("}", i);
const m = end < 0 ? null : FIELD.exec(body.slice(i + 1, end));
if (!m) return null;
const [, name, tail = "", conv = "", spec = ""] = m;
parts.push(text, { key: name === undefined ? null : /^\d/.test(name) ? Number(name) : name, tail, conv, spec });
text = "";
i = end + 1;
}
parts.push(text);
return parts;
}
/** An int literal, or `len()` / `int()` / `ord()`: `%d` of it needs no `int()`. */
function isInt(arg: Arg): boolean {
const node = arg.node;
if (node?.name === "Number") return /^(?:\d[\d_]*|0[xob][\da-f_]+)$/i.test(arg.text);
const callee = node?.name === "CallExpression" ? node.firstChild : null;
return callee?.name === "VariableName" && /^(?:len|int|ord)\($/.test(arg.text.slice(0, callee.to - node!.from + 1));
}
/** The argument as a `%d` value: wrapped in `int()` unless it is one already. */
function asInt(arg: Arg): Arg {
if (isInt(arg)) return arg;
const inner = arg.node?.name === "ParenthesizedExpression" ? arg.text.slice(1, -1) : arg.text;
return { text: "int(" + inner + ")", node: null };
}
const KEYWORDS = new Set(
"False None True and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield".split(
" ",
),
);
const ATOMIC = new Set(["VariableName", "MemberExpression", "CallExpression", "SubscriptExpression"]);
/** `parts` with each field's argument inlined, or null if that is not safe. */
function inline(parts: Part[], positional: Arg[], keyword: Map<string, Arg>, quote: string): string | null {
const used = new Map<Arg, number>();
let next = 0;
let out = "";
for (const part of parts) {
if (typeof part === "string") {
out += part;
continue;
}
if (part.key === null && next < 0) return null;
if (typeof part.key === "number") {
if (next > 0) return null;
next = -1;
}
const arg =
part.key === null
? positional[next++]
: typeof part.key === "number"
? positional[part.key]
: keyword.get(part.key);
if (!arg) return null;
used.set(arg, (used.get(arg) ?? 0) + 1);
const value = part.int ? asInt(arg) : arg;
const text = value.text;
// Before Python 3.12 an f-string field cannot hold its quote, a backslash or a comment.
if (text.includes("\\") || text.includes("#") || text.includes(quote[0]!)) return null;
if (text.includes("\n") && quote.length === 1) return null;
const bare = value !== arg || (arg.node && arg.node.name !== "LambdaExpression" && !text.includes(":="));
let expr = bare ? text : `(${text})`;
if (part.tail) {
if ([...part.tail.matchAll(/\.(\w+)/g)].some(([, attr]) => KEYWORDS.has(attr!))) return null;
const accessors = part.tail.replace(/\[0+(?=\d)/g, "[");
expr = (arg.node && ATOMIC.has(arg.node.name) ? expr : `(${text})`) + accessors;
}
if (expr.startsWith("{")) expr = ` ${expr}`;
out += `{${expr}${part.conv}${part.spec}}`;
}
const all = [...positional, ...keyword.values()];
// Every argument is evaluated once by the call: unused or repeated side effects would change.
for (const arg of all) {
const n = used.get(arg) ?? 0;
if (n === 0 || (n > 1 && arg.node?.name !== "VariableName")) return null;
}
// A call or dict evaluates arguments in source order. Inlining follows field order.
if (all.some((arg) => arg.node?.name !== "VariableName") && [...used.keys()].some((arg, i) => arg !== all[i]))
return null;
return out;
}
/** The `%` operands: positional arguments, or the entries of a dict literal. */
function percentArgs(doc: Text, rhs: SyntaxNode): { positional: Arg[]; keyword: Map<string, Arg> } | null {
const keyword = new Map<string, Arg>();
if (rhs.name === "TupleExpression") {
const items = groups(rhs);
if (items.some((g) => g[0]!.name === "*")) return null;
return { positional: items.map((g) => argOf(doc, g)), keyword };
}
if (rhs.name === "DictionaryExpression") {
for (const g of groups(rhs)) {
const [key, colon, ...value] = g;
if (key?.name !== "String" || colon?.name !== ":" || !value.length) return null;
const k = /^["']([A-Za-z_]\w*)["']$/.exec(doc.sliceString(key.from, key.to));
if (!k || keyword.has(k[1]!)) return null;
keyword.set(k[1]!, argOf(doc, value));
}
return { positional: [], keyword };
}
return { positional: [{ text: doc.sliceString(rhs.from, rhs.to), node: rhs }], keyword };
}
function percentConversions(doc: Text, node: SyntaxNode): StringConversion[] {
const [str, op, rhs] = [node.firstChild, node.firstChild?.nextSibling, node.lastChild];
if (str?.name !== "String" || op?.name !== "ArithOp" || doc.sliceString(op.from, op.to) !== "%" || !rhs) return [];
const lit = literal(doc.sliceString(str.from, str.to));
const parts = lit && percentParts(lit.body, lit.raw);
const args = rhs && percentArgs(doc, rhs);
if (!lit || !parts || !args) return [];
const fields = parts.filter((p): p is Field => typeof p !== "string");
const named = fields.every((f) => f.key !== null);
if (named) {
if (args.positional.length || fields.some((f) => typeof f.key !== "string" || !args.keyword.has(f.key))) return [];
} else if (args.keyword.size || fields.length !== args.positional.length || fields.some((f) => f.key !== null)) {
return [];
}
const out: StringConversion[] = [];
const inlined = inline(parts, args.positional, args.keyword, lit.quote);
if (inlined !== null)
out.push({
kind: "fString",
from: node.from,
to: node.to,
text: `${lit.prefix}f${lit.quote}${inlined}${lit.quote}`,
});
const body = parts.map((p) => (typeof p === "string" ? p : `{${p.key ?? ""}${p.conv}${p.spec}}`)).join("");
// `.format(k=…)` needs keys that are not keywords, and a key used as `%d` and as text cannot be both.
const intKeys = new Set(fields.filter((f) => f.int).map((f) => f.key));
const mixed = fields.some((f) => !f.int && intKeys.has(f.key));
if (named && (mixed || [...args.keyword.keys()].some((k) => KEYWORDS.has(k)))) return out;
const callArgs = named
? [...args.keyword].map(([k, v]) => `${k}=${(intKeys.has(k) ? asInt(v) : v).text}`)
: args.positional.map((a, i) => (fields[i]!.int ? asInt(a) : a).text);
out.push({
kind: "format",
from: node.from,
to: node.to,
text: `${lit.prefix}${lit.quote}${body}${lit.quote}.format(${callArgs.join(", ")})`,
});
return out;
}
function formatConversion(doc: Text, call: SyntaxNode): StringConversion[] {
const member = call.firstChild;
const str = member?.firstChild;
const name = member?.lastChild;
const argList = call.getChild("ArgList");
if (member?.name !== "MemberExpression" || str?.name !== "String" || name?.name !== "PropertyName" || !argList)
return [];
if (doc.sliceString(name.from, name.to) !== "format") return [];
const lit = literal(doc.sliceString(str.from, str.to));
const parts = lit && formatParts(lit.body, lit.raw);
if (!lit || !parts) return [];
const positional: Arg[] = [];
const keyword = new Map<string, Arg>();
for (const g of groups(argList)) {
if (g[0]!.name === "*" || g[0]!.name === "**" || g.some((node) => node.type.isError)) return [];
if (g[1]?.name === "AssignOp") {
const key = doc.sliceString(g[0]!.from, g[0]!.to);
if (!g[2] || keyword.has(key)) return [];
keyword.set(key, argOf(doc, g.slice(2)));
} else positional.push(argOf(doc, g));
}
const inlined = inline(parts, positional, keyword, lit.quote);
return inlined === null
? []
: [{ kind: "fString", from: call.from, to: call.to, text: `${lit.prefix}f${lit.quote}${inlined}${lit.quote}` }];
}
/** Conversions of the `%` expression or `.format()` call around `pos`, innermost first. */
export function stringConversions(tree: Tree, doc: Text, pos: number): StringConversion[] {
for (let n: SyntaxNode | null = tree.resolveInner(pos, 1); n; n = n.parent) {
if (n.name === "BinaryExpression") {
const found = percentConversions(doc, n);
if (found.length) return found;
} else if (n.name === "CallExpression") {
const found = formatConversion(doc, n);
if (found.length) return found;
} else if (/Statement$|^Body$|^Script$/.test(n.name)) break;
}
return [];
}
export function pythonStringIntentions(view: EditorView): ContributedIntention[] {
if (docOf(view)?.uiMode !== "Python" || !view.state.selection.main.empty) return [];
return stringConversions(syntaxTree(view.state), view.state.doc, view.state.selection.main.head).map((c) => ({
id: `python.${c.kind}`,
label: c.kind === "fString" ? tx("Convert to f-string literal") : tx("Replace with str.format() call"),
icon: "bulb",
run: () =>
view.dispatch({ changes: { from: c.from, to: c.to, insert: c.text }, userEvent: "input", scrollIntoView: true }),
}));
}
@@ -0,0 +1,233 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { InlayHint } from "@/bindings";
import { completedSyntaxState, completedSyntaxTree } from "@/test/syntax";
import { findLanguageDescription, loadSupport } from "../../../core/cm/languages";
const ipc = vi.hoisted(() => ({ lspInlayHints: vi.fn(), lspHover: vi.fn() }));
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
});
const files = vi.hoisted(() => ({ readFileLines: vi.fn() }));
vi.mock("../../files", () => files);
const { annotationTarget, builtinHoverType, minorNeeded, requiredMinor, pythonTypeHintIntentions } =
await import("./typeHints");
const { lspDoc } = await import("../../lsp");
const { useProject } = await import("@/platform/project");
const support = await loadSupport(findLanguageDescription("Python", "demo.py")!);
async function targetAt(source: string, marker: string, delta = 0) {
const state = EditorState.create({ doc: source, extensions: [support!] });
const target = annotationTarget(completedSyntaxTree(state), state.doc, source.indexOf(marker) + delta);
if (target?.kind !== "function")
return target && { kind: target.kind, end: source.slice(0, target.slot.end), evaluated: target.evaluated };
return {
kind: target.kind,
name: target.name,
returns: target.returns && source.slice(0, target.returns.end),
params: target.params.map((p) => source.slice(0, p.end).split(/\W/).pop()),
};
}
describe("Python type annotation targets", () => {
const source =
"class A:\n def run(self, path, limit=10, *rest, flag: bool = False, mode='r', **kw):\n" +
" count = len(path)\n a = b = 1\n x, y = 1, 2\n typed: int = 3\n return count\n";
it("finds a plain assignment target, with the caret on either side of the name", async () => {
expect(await targetAt(source, "count =")).toEqual({
kind: "variable",
end: source.slice(0, source.indexOf("count =") + 5),
evaluated: false,
});
expect((await targetAt(source, "count =", 5))?.kind).toBe("variable");
expect((await targetAt("total = 0\n", "total"))?.evaluated).toBe(true);
});
it("skips chained, tuple and annotated targets and other statements", async () => {
expect(await targetAt(source, "a = b")).toBeNull();
expect(await targetAt(source, "x, y")).toBeNull();
expect(await targetAt(source, "typed")).toBeNull();
expect(await targetAt(source, "return count", 3)).toBeNull();
});
it("skips class attributes and names declared global or nonlocal", async () => {
expect(await targetAt("@dataclass\nclass C:\n retries = 3\n", "retries")).toBeNull();
expect(await targetAt("def f():\n global hits, total\n total = 1\n", "total =")).toBeNull();
expect(
await targetAt("def f():\n x = 0\n def g():\n nonlocal x\n x = 1\n", "x = 1"),
).toBeNull();
expect(await targetAt("def f():\n global hits\n total = 1\n", "total =")).not.toBeNull();
expect(await targetAt("total = 0\n\ndef f():\n global total\n total = 1\n", "total = 0")).not.toBeNull();
expect(await targetAt("def f():\n x = 0\n def g():\n nonlocal x\n", "x = 0")).not.toBeNull();
});
it("finds a function header with its unannotated defaulted parameters", async () => {
expect(await targetAt(source, "def run", 5)).toEqual({
kind: "function",
name: "run",
returns: source.slice(0, source.indexOf("**kw)") + 5),
params: ["limit", "mode"],
});
expect((await targetAt('def connect(host="localhost", port=8080):\n pass\n', "connect"))?.params).toEqual([
"host",
"port",
]);
expect((await targetAt("def f() -> int:\n pass\n", "f("))?.returns).toBeNull();
});
});
describe("annotation syntax by Python version", () => {
it("knows which types need 3.9 or 3.10 when evaluated", () => {
expect(minorNeeded(": str | None")).toBe(10);
expect(minorNeeded("-> list[int]")).toBe(9);
expect(minorNeeded(": List[int]")).toBe(0);
expect(minorNeeded(": int")).toBe(0);
});
it("reads the lowest version from requires-python", () => {
expect(requiredMinor(["[project]", 'requires-python = ">=3.10"'])).toBe(10);
expect(requiredMinor(["requires-python = '~=3.8'"])).toBe(8);
expect(requiredMinor(["[project]", 'name = "x"'])).toBe(0);
});
});
describe("builtinHoverType", () => {
it("keeps types made of builtins only", () => {
expect(builtinHoverType("```python\n(parameter) limit: int\n```")).toBe("int");
expect(builtinHoverType("```python\n(variable) names: list[str]\n```")).toBe("list[str]");
expect(builtinHoverType("```python\n(parameter) mode: str | None\n```")).toBe("str | None");
expect(builtinHoverType("```python\n(parameter) p: Path\n```")).toBeNull();
expect(builtinHoverType("```python\n(parameter) x: None\n```")).toBeNull();
expect(builtinHoverType("```python\n(variable) v: Unknown\n```")).toBeNull();
});
});
describe("pythonTypeHintIntentions", () => {
const ctx = { doc: 3, path: "/p/m.py", language: "python", uiMode: "Python", readOnly: false };
const views: EditorView[] = [];
const range = (line: number, col: number) => ({ start: { line, col }, end: { line, col } });
const hint = (line: number, col: number, label: string, edits: [number, number, string][]): InlayHint => ({
position: { line, col },
label,
kind: "type",
paddingLeft: false,
paddingRight: false,
tooltip: null,
parts: [],
textEdits: edits.map(([l, c, text]) => ({ range: range(l, c), new_text: text })),
});
const hover = (text: string) => ({
status: "ok",
data: { contents: { kind: "markdown", value: text }, range: null },
});
function mount(doc: string, caret: string, delta = 0) {
const state = completedSyntaxState(
EditorState.create({
doc,
selection: { anchor: doc.indexOf(caret) + delta },
extensions: [support!, lspDoc.of(ctx)],
}),
);
const view = new EditorView({ state, parent: document.body });
views.push(view);
return view;
}
async function run(view: EditorView, label: string) {
const found = await pythonTypeHintIntentions(view, new AbortController().signal);
await found.find((i) => i.label === label)!.run();
return { labels: found.map((i) => i.label), text: view.state.doc.toString() };
}
afterEach(() => {
for (const v of views.splice(0)) v.destroy();
vi.clearAllMocks();
useProject.setState({ project: null });
});
it("inserts a variable's hint with its import edit", async () => {
ipc.lspInlayHints.mockResolvedValue({
status: "ok",
data: [
hint(3, 9, ": Any", [
[3, 9, ": Any"],
[0, 0, "from typing import Any\n"],
]),
],
});
const view = mount("import os\n\ndef f():\n chart = make()\n", "chart");
// A local's annotation never runs, so no version lookup.
expect(await run(view, "Add type annotation ': Any'")).toEqual({
labels: ["Add type annotation ': Any'"],
text: "from typing import Any\nimport os\n\ndef f():\n chart: Any = make()\n",
});
expect(files.readFileLines).not.toHaveBeenCalled();
});
it("merges the return hint with hovered parameter types, once per import", async () => {
files.readFileLines.mockResolvedValue(['requires-python = ">=3.10"']);
useProject.setState({ project: { root: "/p" } } as never);
ipc.lspInlayHints.mockResolvedValue({
status: "ok",
data: [hint(0, 29, "-> str | None", [[0, 29, " -> str | None"]])],
});
ipc.lspHover.mockImplementation(async (_id: number, _doc: number, pos: { col: number }) =>
hover(pos.col < 20 ? "(parameter) host: str" : "(parameter) port: int"),
);
const view = mount('def connect(host="h", port=1):\n return None\n', "connect");
expect(await run(view, "Add type hints for function 'connect'")).toEqual({
labels: ["Add return type annotation '-> str | None'", "Add type hints for function 'connect'"],
text: 'def connect(host: str = "h", port: int = 1) -> str | None:\n return None\n',
});
});
it("declines 3.10 syntax in an evaluated annotation for an older or unknown Python", async () => {
files.readFileLines.mockResolvedValue(['requires-python = ">=3.8"']);
useProject.setState({ project: { root: "/p" } } as never);
ipc.lspInlayHints.mockResolvedValue({ status: "ok", data: [hint(0, 5, ": str | None", [[0, 5, ": str | None"]])] });
ipc.lspHover.mockResolvedValue(hover("(variable) maybe: str | None"));
const old = await pythonTypeHintIntentions(mount("maybe = find()\n", "maybe"), new AbortController().signal);
expect(old).toEqual([]);
const future = mount("from __future__ import annotations\nmaybe = find()\n", "maybe");
ipc.lspInlayHints.mockResolvedValue({ status: "ok", data: [hint(1, 5, ": str | None", [[1, 5, ": str | None"]])] });
expect((await run(future, "Add type annotation ': str | None'")).text).toContain("maybe: str | None = find()");
});
it("only postpones annotation evaluation for an actual future import of annotations", async () => {
files.readFileLines.mockResolvedValue(['requires-python = ">=3.8"']);
useProject.setState({ project: { root: "/p" } } as never);
ipc.lspInlayHints.mockResolvedValue({ status: "ok", data: [] });
ipc.lspHover.mockResolvedValue(hover("(variable) maybe: str | None"));
for (const prefix of [
'"""\nfrom __future__ import annotations\n"""',
"from __future__ import division as annotations",
"from __future__ import division # annotations",
]) {
const view = mount(`${prefix}\nmaybe = find()\n`, "maybe");
expect(await pythonTypeHintIntentions(view, new AbortController().signal)).toEqual([]);
}
for (const prefix of [
"from __future__ import (\n annotations,\n)",
"from __future__ import annotations; pass",
]) {
const view = mount(`${prefix}\nmaybe = find()\n`, "maybe");
expect((await run(view, "Add type annotation ': str | None'")).text).toContain("maybe: str | None = find()");
}
});
it("falls back to hover for older servers returning hints without insertion edits", async () => {
ipc.lspInlayHints.mockResolvedValue({
status: "ok",
data: [{ ...hint(0, 5, ": int", []), textEdits: undefined }],
});
ipc.lspHover.mockResolvedValue(hover("(variable) count: int"));
const view = mount("count = 1\n", "count");
expect((await run(view, "Add type annotation ': int'")).text).toEqual("count: int = 1\n");
});
});
+266
View File
@@ -0,0 +1,266 @@
/**
* PyCharm's "Add type hint for variable" and "Add type hints for function",
* filled with the types the server infers: its type inlay hints carry the edit
* that inserts them (and any import they need); a parameter's type comes from
* hovering it, kept only when it names builtins, which need no import.
* Annotations Python evaluates (signatures, module variables) use `X | Y` and
* `list[X]` only when `requires-python` or `from __future__ import annotations`
* allows them.
*/
import { syntaxTree } from "@codemirror/language";
import type { Text } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import type { SyntaxNode, Tree } from "@lezer/common";
import { whenSynced, type ContributedIntention } from "@/editor/api";
import { commands, nextRequestId, type InlayHint, type TextEdit } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { docOf, lspRequest } from "../../lsp";
import { offsetToPos, offsetsToRange, posToOffset, textEditsToChanges } from "../../positions";
import { readFileLines } from "../../files";
import { useProject } from "@/platform/project";
/** A name to annotate: the end of the name is where its annotation goes. */
interface Slot {
end: number;
/** For a defaulted parameter, where its value starts: `name=value` becomes `name: T = value` (PEP 8). */
value?: number;
}
export type AnnotationTarget =
/** `evaluated`: a module variable, whose annotation runs at import; a local's never runs. */
| { kind: "variable"; slot: Slot; evaluated: boolean }
| { kind: "function"; name: string; header: { from: number; to: number }; returns: Slot | null; params: Slot[] };
/** The unannotated variable assignment or function header at `pos`. */
export function annotationTarget(tree: Tree, doc: Text, pos: number): AnnotationTarget | null {
let start = tree.resolveInner(pos, 1);
if (start.name !== "VariableName" && tree.resolveInner(pos, -1).name === "VariableName")
start = tree.resolveInner(pos, -1);
for (let n: SyntaxNode | null = start; n; n = n.parent) {
if (n.name === "VariableName" && n.parent?.name === "AssignStatement") {
const statement = n.parent;
// Only `name = value`: an annotated, tuple or chained target takes no annotation.
const simple =
statement.firstChild?.from === n.from &&
n.nextSibling?.name === "AssignOp" &&
statement.getChildren("AssignOp").length === 1;
if (!simple) return null;
const scope = scopeOf(statement);
// A class body's annotated name becomes a field (dataclass, NamedTuple, pydantic…).
if (scope?.name !== "FunctionDefinition" && scope?.name !== "Script") return null;
if (declaredGlobal(scope, doc, doc.sliceString(n.from, n.to))) return null;
return { kind: "variable", slot: { end: n.to }, evaluated: scope.name === "Script" };
}
if (n.name === "FunctionDefinition") {
const params = n.getChild("ParamList");
const body = n.getChild("Body");
const name = n.getChild("VariableName");
if (!params || !body || !name || pos > body.from) return null;
const slots: Slot[] = [];
// Only defaulted parameters: `self` / `cls` have no default.
for (let c = params.firstChild; c; c = c.nextSibling) {
if (c.name !== "VariableName") continue;
const star = c.prevSibling?.name === "*" || c.prevSibling?.name === "**";
if (!star && c.nextSibling?.name === "AssignOp")
slots.push({ end: c.to, value: c.nextSibling?.nextSibling?.from });
}
const returns = n.getChild("TypeDef") ? null : { end: params.to };
return {
kind: "function",
name: doc.sliceString(name.from, name.to),
header: { from: n.from, to: body.from },
returns,
params: slots,
};
}
if (/Statement$|^Body$|^Script$/.test(n.name)) return null;
}
return null;
}
/** The function, class, lambda or module whose scope `node` is in. */
function scopeOf(node: SyntaxNode): SyntaxNode | null {
for (let n = node.parent; n; n = n.parent)
if (/^(?:FunctionDefinition|ClassDefinition|LambdaExpression|Script)$/.test(n.name)) return n;
return null;
}
/** `name` is declared `global` / `nonlocal` in function `scope` itself, where annotating it is a SyntaxError. */
function declaredGlobal(scope: SyntaxNode, doc: Text, name: string): boolean {
if (scope.name !== "FunctionDefinition") return false;
let found = false;
scope
.getChild("Body")
?.cursor()
.iterate((n) => {
if (/^(?:FunctionDefinition|ClassDefinition|LambdaExpression)$/.test(n.name)) return false;
if (n.name !== "ScopeStatement") return;
const names = doc
.sliceString(n.from, n.to)
.replace(/^\s*(?:global|nonlocal)\s+/, "")
.split(/\s*,\s*/);
if (names.includes(name)) found = true;
return false;
});
return found;
}
/** The Python minor version (3.x) an evaluated annotation `type` needs: 10 for `X | Y`, 9 for `list[X]`. */
export function minorNeeded(type: string): number {
if (type.includes("|")) return 10;
return /\b(?:list|dict|set|frozenset|tuple|type)\[/.test(type) ? 9 : 0;
}
/** The lowest Python 3 minor version `requires-python` allows, or 0 when unknown. */
export function requiredMinor(pyproject: readonly string[]): number {
const spec = pyproject.map((l) => /^\s*requires-python\s*=\s*["']([^"']*)["']/.exec(l)?.[1]).find(Boolean);
const m = spec && /(?:>=|~=|==)\s*3\.(\d+)/.exec(spec);
return m ? Number(m[1]) : 0;
}
/** The newest syntax the file's evaluated annotations may use (99: anything, under the future import). */
async function annotationMinor(tree: Tree, text: Text): Promise<number> {
const top = tree.topNode;
const imports = [top, ...top.getChildren("StatementGroup")].flatMap((node) => node.getChildren("ImportStatement"));
for (const statement of imports) {
const from = statement.firstChild;
const module = from?.nextSibling;
if (
from?.name !== "from" ||
module?.name !== "VariableName" ||
module.nextSibling?.name !== "import" ||
text.sliceString(module.from, module.to) !== "__future__"
)
continue;
const features = statement.getChildren("VariableName").slice(1);
const annotations = features.some(
(name) => name.prevSibling?.name !== "as" && text.sliceString(name.from, name.to) === "annotations",
);
if (annotations) return 99;
}
const root = useProject.getState().project?.root;
const lines = root ? await readFileLines(`${root}/pyproject.toml`).catch(() => null) : null;
return lines ? requiredMinor(lines) : 0;
}
const BUILTINS = new Set([
"int",
"float",
"complex",
"bool",
"str",
"bytes",
"bytearray",
"list",
"dict",
"set",
"frozenset",
"tuple",
"object",
"None",
]);
/** The type in a hover such as `(parameter) count: int`, when it names only builtins. */
export function builtinHoverType(markdown: string): string | null {
const m = /\((?:parameter|variable)\) [A-Za-z_]\w*: ([^\n`]+)/.exec(markdown);
const type = m?.[1]?.trim();
if (!type || type === "None") return null;
const names = type.match(/[A-Za-z_][\w.]*/g) ?? [];
return names.every((name) => BUILTINS.has(name)) ? type : null;
}
/** The type hint the server shows at `offset` with the edits that insert it. */
function hintAt(doc: Text, hints: readonly InlayHint[], offset: number, prefix: string): InlayHint | undefined {
return hints.find(
(h) =>
h.kind === "type" && h.textEdits?.length && h.label.startsWith(prefix) && posToOffset(doc, h.position) === offset,
);
}
interface Annotation {
label: string;
edits: TextEdit[];
}
async function hoverAnnotation(view: EditorView, { end, value }: Slot): Promise<Annotation | null> {
const doc = docOf(view)!;
const hover = await lspRequest(() =>
commands.lspHover(nextRequestId(), doc.doc, offsetToPos(view.state.doc, end - 1)),
);
const type = hover && builtinHoverType(hover.contents.value);
if (!type) return null;
const at = offsetsToRange(view.state.doc, end, value ?? end);
return { label: `: ${type}`, edits: [{ range: at, new_text: value === undefined ? `: ${type}` : `: ${type} = ` }] };
}
function apply(view: EditorView, edits: readonly TextEdit[]): void {
const unique = [...new Map(edits.map((e) => [JSON.stringify(e), e])).values()];
view.dispatch({ changes: textEditsToChanges(view.state.doc, unique), userEvent: "input", scrollIntoView: true });
}
/** Annotation intentions at the caret, once the server answered. */
export async function pythonTypeHintIntentions(view: EditorView, signal: AbortSignal): Promise<ContributedIntention[]> {
const doc = docOf(view);
const selection = view.state.selection.main;
if (doc?.uiMode !== "Python" || !selection.empty) return [];
const state = view.state;
const tree = syntaxTree(state);
const target = annotationTarget(tree, state.doc, selection.head);
if (!target) return [];
await whenSynced(view);
const line = state.doc.lineAt(selection.head);
const span = target.kind === "function" ? target.header : { from: line.from, to: line.to };
const hints = await lspRequest(() =>
commands.lspInlayHints(doc.doc, offsetsToRange(state.doc, span.from, span.to)),
).catch(() => [] as InlayHint[]);
const evaluated = target.kind === "function" || target.evaluated;
const minor = evaluated ? await annotationMinor(tree, state.doc) : 99;
if (signal.aborted || view.state.doc !== state.doc) return [];
const usable = (a: Annotation | null): Annotation | null => (a && minorNeeded(a.label) <= minor ? a : null);
const fromHint = (h: InlayHint | undefined): Annotation | null =>
h ? { label: h.label.trim(), edits: h.textEdits } : null;
if (target.kind === "variable") {
const found = usable(
fromHint(hintAt(state.doc, hints, target.slot.end, ":")) ??
(await hoverAnnotation(view, target.slot).catch(() => null)),
);
if (!found || signal.aborted || view.state.doc !== state.doc) return [];
const annotation = found.label;
return [
{
id: "python.addVariableType",
label: tx`Add type annotation '${annotation}'`,
icon: "bulb",
run: () => apply(view, found.edits),
},
];
}
const returns = target.returns && usable(fromHint(hintAt(state.doc, hints, target.returns.end, "->")));
const params = (
await Promise.all(target.params.map((p) => hoverAnnotation(view, p).then(usable, () => null)))
).filter((a): a is Annotation => !!a);
if (signal.aborted || view.state.doc !== state.doc) return [];
const out: ContributedIntention[] = [];
if (returns) {
const annotation = returns.label;
out.push({
id: "python.addReturnType",
label: tx`Add return type annotation '${annotation}'`,
icon: "bulb",
run: () => apply(view, returns.edits),
});
}
if (params.length) {
const name = target.name;
const edits = [...(returns?.edits ?? []), ...params.flatMap((p) => p.edits)];
out.push({
id: "python.addFunctionTypes",
label: tx`Add type hints for function '${name}'`,
icon: "bulb",
run: () => apply(view, edits),
});
}
return out;
}
@@ -11,7 +11,7 @@
* of the file in batches; results are cached per document text, and markers
* follow their lines in between.
* The cache outlives the editor view (switching tabs remounts it) until other
* files change or a language server settles: on some servers (jdtls) every
* files change, a language server settles or its classpath changes: on some servers (jdtls) every
* implementation search walks the whole workspace, so asking again is costly.
* Library sources ask no inheritors from the server (`isLibrarySource`).
*/
@@ -119,11 +119,15 @@ function watchChanges() {
// documents: re-render them instead of waiting for an edit or a settling server.
for (const plugin of live) plugin.refreshSoon();
});
// Answers (outlines too) given while a server was starting or indexing may be incomplete.
onServerSettled(() => {
// Answers (outlines too) given while a server was starting or importing may be incomplete.
const refreshCaches = () => {
docMarkers.clear();
forgetInheritanceGraph();
for (const plugin of live) plugin.refreshSoon();
};
onServerSettled(refreshCaches);
onIdeEvent("lspRefresh", (e) => {
if (e.kind === "inheritance") refreshCaches();
});
// Go to Declaration and the like go first: in-flight marker requests are cancelled and
// asked again once the navigation is done.
+65
View File
@@ -9,13 +9,25 @@ import {
commands,
type ClassInheritance,
type HierarchyItem,
type IdeEvent,
type Location,
type OutlineItem,
type Pos,
type SymbolKind,
} from "@/platform/ipc";
import { setInvokeRoute } from "@/platform/tauriCore";
const nav = vi.hoisted(() => ({ navigateTo: vi.fn(async () => {}), openPopup: vi.fn() }));
const ideListeners = vi.hoisted(() => new Map<string, Set<(event: IdeEvent) => void>>());
vi.mock("@/platform/ipc", async (orig) => ({
...(await orig<typeof import("@/platform/ipc")>()),
onIdeEvent: (type: string, listener: (event: IdeEvent) => void) => {
let listeners = ideListeners.get(type);
if (!listeners) ideListeners.set(type, (listeners = new Set()));
listeners.add(listener);
return () => listeners.delete(listener);
},
}));
vi.mock("@/editor/lsp/navigation", async (orig) => ({
...(await orig<typeof import("@/editor/lsp/navigation")>()),
navigateTo: nav.navigateTo,
@@ -623,6 +635,59 @@ describe("clicking a marker", () => {
});
describe("inheritance gutter", () => {
it.each([
{ type: "interface", source: SHAPE, outline: SHAPE_OUTLINE },
{ type: "abstract class", source: BASE, outline: BASE_OUTLINE },
])(
"refreshes implementation and override markers when a Java project update finishes ($type)",
async ({ source, outline }) => {
vi.useFakeTimers();
let indexed = false;
const target = "/p/service/target/generated-sources/example/ServiceImpl.java";
const queries = vi.fn<MarkerDeps["implementations"]>(async (positions) =>
positions.map(({ line }) => (indexed ? [loc(target, line + 2)] : [])),
);
setInvokeRoute(async (command, args) => {
if (command === "doc_outline") return outline;
if (command === "lsp_type_hierarchy") {
throw { kind: "unavailable", message: "no type hierarchy", data: null };
}
if (command === "lsp_implementations") return queries((args as { positions: Pos[] }).positions);
return null;
});
const ctx = { doc: 12, path: `/p/api/${outline[0]!.name}.java`, language: "java", uiMode: null, readOnly: false };
const view = new EditorView({
doc: Text.of(source),
extensions: [lspDoc.of(ctx), iconAreaExtension, implementationGutter(ctx)],
parent: document.body,
});
const kinds = () =>
[...view.dom.querySelectorAll<HTMLElement>('[class*="cm-openidea-lineMarker-"]')].map((el) => el.dataset.kind);
const emit = (event: IdeEvent) => {
for (const listener of ideListeners.get(event.type) ?? []) listener(event);
};
try {
await vi.advanceTimersByTimeAsync(500);
expect(queries).toHaveBeenCalledTimes(1);
expect(kinds()).toEqual([]);
indexed = true;
emit({ type: "lspRefresh", server: 1, kind: "semanticTokens" });
await vi.advanceTimersByTimeAsync(500);
expect(queries).toHaveBeenCalledTimes(1);
emit({ type: "lspRefresh", server: 1, kind: "inheritance" });
await vi.advanceTimersByTimeAsync(500);
expect(queries).toHaveBeenCalledTimes(2);
expect(kinds()).toEqual(["implemented", "implemented", "overridden"]);
} finally {
view.destroy();
setInvokeRoute(null);
vi.useRealTimers();
}
},
);
it.each([
{ kind: "overriding", language: "java", declaration: "@SuperBuilder" },
{ kind: "overridden", language: "java", declaration: "@Data" },
+1 -1
View File
@@ -679,7 +679,7 @@ function CustomAgentModal({
try {
const trimmed = name.trim();
const title = trimmed ? tx`Select ${trimmed}` : tx("Select executable");
const path = await backend.chooseExecutable(title, command);
const path = await backend.chooseExecutable(title, command, "desktop");
if (path) setCommand(path);
setError(null);
} catch (e) {
+18
View File
@@ -35,6 +35,7 @@ const FENCE = `\`\`\`mermaid\n${DIAGRAM}\n\`\`\`\n`;
beforeEach(() => {
vi.clearAllMocks();
readImage.mockReset().mockResolvedValue(PIXEL);
copyText.mockReset().mockResolvedValue(undefined);
resetMermaidForTests();
mermaid.render.mockReset().mockImplementation(async (id: string, text: string) => {
// Like mermaid: a measuring node under <body> while rendering.
@@ -70,6 +71,23 @@ it("keeps one copy control outside each code block when effects restart", () =>
}
});
it("confirms a code block copy, then goes back to Copy Code", async () => {
vi.useFakeTimers({ shouldAdvanceTime: true });
try {
render(<Markdown text={"```ts\nconst a = 1;\n```"} cwd="/repo" />);
fireEvent.click(screen.getByRole("button", { name: "Copy Code" }));
const copied = await screen.findByRole("button", { name: "Copied" });
expect(copyText).toHaveBeenCalledWith("const a = 1;");
expect(copied).toHaveAttribute("data-copied");
await vi.advanceTimersByTimeAsync(2000);
const again = screen.getByRole("button", { name: "Copy Code" });
expect(again).toBe(copied);
expect(again).not.toHaveAttribute("data-copied");
} finally {
vi.useRealTimers();
}
});
it.each([
"<style>body{outline:7px solid red}</style>",
'<form action="https://example.com/x"><button>go</button></form>',
+27 -6
View File
@@ -234,6 +234,27 @@ async function linkSymbols(root: HTMLElement, spans: HTMLElement[], cwd: string)
);
}
const COPIED_MS = 2000;
const copiedTimers = new WeakMap<HTMLElement, ReturnType<typeof setTimeout>>();
function setCopyState(button: HTMLElement, copied: boolean) {
const label = tx(copied ? "Copied" : "Copy Code");
button.title = label;
button.setAttribute("aria-label", label);
button.replaceChildren(iconNode(copied ? "check" : "copy", 14));
button.toggleAttribute("data-copied", copied);
}
/** Shows a check on a code block's Copy button for a moment. */
function flashCopied(button: HTMLElement) {
clearTimeout(copiedTimers.get(button));
setCopyState(button, true);
copiedTimers.set(
button,
setTimeout(() => setCopyState(button, false), COPIED_MS),
);
}
/** Highlighting, Copy buttons and file links over freshly rendered `root`. */
function enhance(root: HTMLElement, cwd: string, images: MessageImages): () => void {
let alive = true;
@@ -255,10 +276,7 @@ function enhance(root: HTMLElement, cwd: string, images: MessageImages): () => v
const copy = document.createElement("button");
copy.type = "button";
copy.className = styles.codeCopy!;
const label = tx("Copy Code");
copy.title = label;
copy.setAttribute("aria-label", label);
copy.appendChild(iconNode("copy", 14));
setCopyState(copy, false);
copy.dataset.copy = text;
const block = pre.parentElement!;
block.appendChild(copy);
@@ -280,7 +298,10 @@ function enhance(root: HTMLElement, cwd: string, images: MessageImages): () => v
});
return () => {
alive = false;
copies.forEach((copy) => copy.remove());
copies.forEach((copy) => {
clearTimeout(copiedTimers.get(copy));
copy.remove();
});
disposeImages();
};
}
@@ -421,7 +442,7 @@ export function Markdown({
const target = e.target as HTMLElement;
const copy = target.closest<HTMLElement>("button[data-copy]");
if (copy) {
void copyText(copy.dataset.copy ?? "");
void copyText(copy.dataset.copy ?? "").then(() => flashCopied(copy));
return;
}
const code = target.closest<HTMLElement>("code");
+5 -1
View File
@@ -560,9 +560,13 @@
}
.codeBlock:hover > .codeCopy,
.markdown :global([data-mermaid]:hover) .codeCopy,
.codeCopy:focus-visible {
.codeCopy:focus-visible,
.codeCopy[data-copied] {
opacity: 1;
}
.codeCopy[data-copied] {
color: var(--success);
}
/* A drawn diagram carries its own tools at the top-right; Copy moves aside. */
.markdown :global([data-mermaid][data-mermaid-state="ok"]) .codeCopy {
right: 56px;
+19 -5
View File
@@ -36,9 +36,24 @@ export function SessionEditor({ input, docked = false }: { input: EditorInput; d
return <TaskSession key={id} id={id} docked={docked} />;
}
/**
* What `select` reads from the store while this tab is `shown`. Hidden behind another tab, it keeps
* what it had when it was hidden: a conversation streaming in the background renders nothing here,
* and the tab catches up in one render when it is shown again.
*/
function useAgentsWhileShown<T>(shown: boolean, select: (s: ReturnType<typeof useAgents.getState>) => T): T {
const held = useRef<{ value: T } | null>(null);
return useAgents((s) => {
if (shown || !held.current) held.current = { value: select(s) };
return held.current.value;
});
}
function TaskSession({ id, docked }: { id: string; docked: boolean }) {
// A kept-alive tab stays mounted behind the shown one: it isn't read there, nor searched.
const shown = useEditorShown();
const task = useAgents((s) => s.tasks.get(id));
const entries = useAgents((s) => s.entries.get(id));
const entries = useAgentsWhileShown(shown, (s) => s.entries.get(id));
// Grouping needs commits of the task's own: local checkouts keep the flat list.
const isolation = useAgents((s) => s.tasks.get(id)?.isolation);
const grouped = useChangesOptions((s) => s.groupByCommit) && isolation === "worktree";
@@ -58,10 +73,11 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
// The subagent conversation shown, with the subagents that lead to it (empty: the task's own).
const [path, setPath] = useState<string[]>([]);
const view = path.at(-1) ?? null;
const viewEntries = useAgents((s) => s.entries.get(entriesKey(id, view)));
const viewEntries = useAgentsWhileShown(shown, (s) => s.entries.get(entriesKey(id, view)));
const loadError = useAgents((s) => s.entryLoads.get(entriesKey(id, view))?.error);
// Each subagent's card, from its parent's conversation.
const cards = useAgents(
const cards = useAgentsWhileShown(
shown,
useShallow((s) => path.map((sub, i) => findSubagent(s.entries.get(entriesKey(id, path[i - 1] ?? null)), sub))),
);
// Connecting to the project's agents clears what was loaded before: a tab restored with the
@@ -87,8 +103,6 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
scheduleChanges(id);
});
}, [id, connected, refreshRoot]);
// A kept-alive tab stays mounted behind the shown one: it isn't read there, nor searched.
const shown = useEditorShown();
useEffect(() => {
if (shown && (!docked || !changesOpen)) return markVisible(id);
}, [id, docked, changesOpen, shown]);
+168
View File
@@ -0,0 +1,168 @@
import { Profiler } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, render, screen } from "@testing-library/react";
import type { AgentEntry, AgentEvent, AgentTask } from "@/bindings";
import { EditorShownProvider } from "@/workbench/contributions";
import { SessionEditor } from "./SessionEditor";
import { SESSION_KIND, sessionKey } from "./model";
import { extractSessionAssets } from "./sessionAssetsModel";
import { caretOf, textOf, typeIn } from "./composerTesting";
import { connect, disconnect, useAgents } from "./store";
const backend = vi.hoisted(() => ({
channel: null as { onmessage: (event: AgentEvent) => void } | null,
tasks: [] as AgentTask[],
entries: [] as AgentEntry[],
}));
vi.mock("@tauri-apps/api/core", async (original) => ({
...(await original<typeof import("@tauri-apps/api/core")>()),
Channel: class {
onmessage = () => {};
},
}));
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
isTauri: () => true,
commands: {
agentSubscribe: async (channel: typeof backend.channel) => {
backend.channel = channel;
return { status: "ok", data: backend.tasks };
},
agentProviders: async () => ({ status: "ok", data: [] }),
agentCommands: async () => ({ status: "ok", data: [] }),
agentChanges: async () => ({ status: "ok", data: [] }),
agentGroupedChanges: async () => ({ status: "ok", data: { uncommitted: [], commits: [] } }),
agentEntries: async () => ({ status: "ok", data: backend.entries }),
vcsBranchInfo: async () => ({ status: "ok", data: { head: "main" } }),
vcsRemotes: async () => ({ status: "ok", data: [] }),
},
}));
vi.mock("@tauri-apps/api/webview", () => ({
getCurrentWebview: () => ({ onDragDropEvent: () => Promise.resolve(() => {}) }),
}));
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
editorService: () => ({ closeInput: vi.fn(), openInput: vi.fn(), openTabs: () => [] }),
toolWindowService: () => ({ show: vi.fn() }),
}));
vi.mock("./sessionAssetsModel", async (original) => {
const model = await original<typeof import("./sessionAssetsModel")>();
return { ...model, extractSessionAssets: vi.fn(model.extractSessionAssets) };
});
const TURNS = 30;
const task: AgentTask = {
id: "one",
title: "one",
provider: "codex",
status: "running",
isolation: "local",
model: null,
cwd: "/project",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
};
const conversation = (): AgentEntry[] =>
Array.from({ length: TURNS }, (_, i): AgentEntry[] => [
{ type: "user", text: `Question ${i}`, attachments: [], sentMs: null },
{ type: "agent", text: `Answer ${i}` },
]).flat();
const LAST = TURNS * 2 - 1;
const input = { kind: SESSION_KIND, key: sessionKey("one"), data: { task: "one" } };
/** One chunk of the reply in flight, through the path the backend's events take. */
let streamed = "Answer 29";
const stream = (chunks: number) => {
for (let i = 0; i < chunks; i++) {
const text = ` chunk ${i} of the reply.`;
act(() =>
backend.channel!.onmessage({
type: "append",
task: "one",
subagent: null,
index: LAST,
from: streamed.length,
text,
}),
);
streamed += text;
}
};
const settle = () => act(() => new Promise<void>((done) => setTimeout(done, 250)));
let commits = 0;
const session = (shown: boolean) => (
<Profiler id="session" onRender={() => commits++}>
<EditorShownProvider value={shown}>
<SessionEditor input={input} />
</EditorShownProvider>
</Profiler>
);
beforeEach(async () => {
vi.spyOn(document, "hasFocus").mockReturnValue(true);
disconnect();
localStorage.clear();
backend.tasks = [task];
backend.entries = conversation();
streamed = "Answer 29";
commits = 0;
vi.mocked(extractSessionAssets).mockClear();
useAgents.setState({ sessionLocation: "editor" });
await connect();
});
afterEach(() => {
disconnect();
vi.useRealTimers();
vi.restoreAllMocks();
});
describe("a kept-alive session hidden behind another tab", () => {
it("does no render work while its reply streams", async () => {
// Freeze the working indicator's clock while counting streamed renders.
vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] });
const view = render(session(true));
expect(await screen.findByText("Answer 29")).toBeInTheDocument();
view.rerender(session(false));
await settle();
commits = 0;
vi.mocked(extractSessionAssets).mockClear();
const frames = vi.spyOn(window, "requestAnimationFrame");
stream(20);
await settle();
expect({
commits,
assetScans: vi.mocked(extractSessionAssets).mock.calls.length,
revealFrames: frames.mock.calls.length,
}).toEqual({ commits: 0, assetScans: 0, revealFrames: 0 });
});
it("shows the whole reply and the draft at once when it is shown again", async () => {
const view = render(session(true));
expect(await screen.findByText("Answer 29")).toBeInTheDocument();
const message = screen.getByRole("textbox", { name: "Message" });
typeIn(message, "Draft to keep", 3);
view.rerender(session(false));
stream(20);
await settle();
expect(screen.queryByText(/chunk 19 of the reply/)).not.toBeInTheDocument();
view.rerender(session(true));
// No frame has run: the unseen text isn't paced in.
expect(screen.getByText(new RegExp(`${streamed}$`.replace(/\./g, "\\.")))).toBeInTheDocument();
expect(textOf(screen.getByRole("textbox", { name: "Message" }))).toBe("Draft to keep");
expect(caretOf(screen.getByRole("textbox", { name: "Message" }))).toBe(3);
});
});
+3 -3
View File
@@ -117,7 +117,7 @@ export function activate(): () => void {
icon: "toolwindow-agents",
anchor: "right",
order: 0.5,
component: lazyComponent(() => import("./AgentsView").then((m) => m.AgentsView)),
component: lazyComponent(() => import("./AgentsView").then((m) => m.AgentsView), { prefetch: true }),
headerMenu: useAgentsHeaderMenu,
plainTitle: true,
headerActions: lazyComponent(() => import("./AgentsView").then((m) => m.AgentsHeaderActions)),
@@ -137,7 +137,7 @@ export function activate(): () => void {
}),
registerEditorKind({
kind: SESSION_KIND,
component: lazyComponent(() => import("./SessionEditor").then((m) => m.SessionEditor)),
component: lazyComponent(() => import("./SessionEditor").then((m) => m.SessionEditor), { prefetch: true }),
title: (input) => {
const data = input.data as { task: string; title?: string };
return useAgents.getState().tasks.get(data.task)?.title ?? data.title ?? "Agent Task";
@@ -166,7 +166,7 @@ export function activate(): () => void {
}),
registerEditorKind({
kind: HOME_KIND,
component: lazyComponent(() => import("./HomeEditor").then((m) => m.HomeEditor)),
component: lazyComponent(() => import("./HomeEditor").then((m) => m.HomeEditor), { prefetch: true }),
title: () => "New Agent Task",
icon: (input) => {
const task = useAgents.getState().tasks.get((input.data as { task: string }).task);
+6 -3
View File
@@ -1,5 +1,7 @@
/** Agents of the ACP Registry: listing, install / update / remove (`agent_registry_*`). */
import { open } from "@/platform/dialog";
import { choosePath } from "@/platform/choosePath";
import { readDesktopText } from "@/platform/desktopFiles";
import { Channel } from "@tauri-apps/api/core";
import type {
AcpImportOutcome,
@@ -31,7 +33,7 @@ export interface CommandsBackend {
providers(): Promise<AgentProvider[]>;
set(id: string, command: string | null): Promise<void>;
setEnv(id: string, env: Record<string, string>): Promise<void>;
chooseExecutable(title: string, current?: string): Promise<string | null>;
chooseExecutable(title: string, current?: string, location?: "desktop"): Promise<string | null>;
saveCustom(input: CustomAgentInput): Promise<void>;
removeCustom(id: string): Promise<void>;
importAcp(text: string): Promise<AcpImportOutcome[]>;
@@ -56,7 +58,8 @@ export const tauriCommands: CommandsBackend = {
updateCli: (id, offer, request) => call(commands.agentCliUpdate(id, offer, request)),
cancel: tauriRegistry.cancel,
providers: () => call(commands.agentProviders()),
chooseExecutable: async (title, current) => {
chooseExecutable: async (title, current, location) => {
if (location !== "desktop") return choosePath({ title, defaultPath: current, directory: false });
const picked = await open({ title, defaultPath: current || undefined, directory: false, multiple: false });
return typeof picked === "string" ? picked : null;
},
@@ -81,7 +84,7 @@ export const tauriCommands: CommandsBackend = {
filters: [{ name: tx("ACP config"), extensions: ["json"] }],
});
if (typeof picked !== "string") return null;
return call(commands.fsReadText(picked));
return readDesktopText(picked);
},
};
+34
View File
@@ -1,4 +1,6 @@
import { act, renderHook } from "@testing-library/react";
import type { ReactNode } from "react";
import { EditorShownProvider } from "@/workbench/contributions";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { REVEAL_HORIZON_MS, revealBoundary, revealStep, useRevealedText, withoutBrokenTail } from "./reveal";
@@ -67,6 +69,16 @@ describe("useRevealedText", () => {
expect(result.current.length).toBe(102);
});
it("starts pacing appended text when smooth reveal becomes live in a shown tab", () => {
const { result, rerender } = renderHook(({ text, live }) => useRevealedText(text, live), {
initialProps: { text: "Hi", live: false },
});
rerender({ text: "Hi there", live: true });
expect(result.current).toBe("Hi");
frame(200);
expect(result.current).toBe("Hi there");
});
it("never paints part of a grapheme", () => {
const family = "👨‍👩‍👧";
const { result, rerender } = renderHook(({ text }) => useRevealedText(text, true), {
@@ -101,4 +113,26 @@ describe("useRevealedText", () => {
rerender({ text: "Other", live: true });
expect(result.current).toBe("Other");
});
it("paints no frames while hidden, and shows what arrived meanwhile whole when shown again", () => {
let shown = true;
const { result, rerender } = renderHook(({ text }) => useRevealedText(text, true), {
initialProps: { text: "Hi" },
wrapper: ({ children }: { children: ReactNode }) => (
<EditorShownProvider value={shown}>{children}</EditorShownProvider>
),
});
shown = false;
rerender({ text: "Hi there" });
rerender({ text: `Hi there${"x".repeat(100)}` });
expect(result.current).toBe(`Hi there${"x".repeat(100)}`);
expect(frames).toHaveLength(0);
shown = true;
rerender({ text: `Hi there${"x".repeat(200)}` });
expect(result.current).toBe(`Hi there${"x".repeat(200)}`);
rerender({ text: `Hi there${"x".repeat(300)}` });
expect(result.current).toBe(`Hi there${"x".repeat(200)}`);
frame(200);
expect(result.current).toBe(`Hi there${"x".repeat(300)}`);
});
});
+12 -6
View File
@@ -5,6 +5,7 @@
* burst catches up faster rather than jumping. The store keeps the whole text: only what
* is painted is paced.
*/
import { useEditorShown } from "@/workbench/contributions";
import { useEffect, useState } from "react";
/** The backlog is drained over this long. Longer reads smoother but trails the model. */
@@ -60,14 +61,19 @@ export function withoutBrokenTail(text: string): string {
/**
* The part of `text` to paint. While `live`, appended text is revealed at a pace; a text
* that isn't the painted one continued (another message, an edit), or one that stops
* being live, is shown whole at once.
* being live, is shown whole at once. Hidden behind another tab it is not live: nothing
* is painted there, and shown again it has all of the text at once.
*/
export function useRevealedText(text: string, live: boolean): string {
const [state, setState] = useState({ text, count: text.length });
export function useRevealedText(text: string, streaming: boolean): string {
const shown = useEditorShown();
const live = streaming && shown;
const [state, setState] = useState({ text, count: text.length, shown });
let count = state.count;
if (state.text !== text || (!live && count !== text.length)) {
count = live && text.startsWith(state.text.slice(0, count)) ? Math.min(count, text.length) : text.length;
setState({ text, count });
if (state.text !== text || state.shown !== shown || (!live && count !== text.length)) {
// Catch up immediately when showing a hidden tab.
count =
live && state.shown && text.startsWith(state.text.slice(0, count)) ? Math.min(count, text.length) : text.length;
setState({ text, count, shown });
}
const behind = count < text.length;
useEffect(() => {
+86 -46
View File
@@ -1,14 +1,23 @@
import type { AgentEntry, AgentTask } from "@/bindings";
import type { AgentTask } from "@/bindings";
import { useTx } from "@/platform/i18n";
import { Icon } from "@/ui";
import clsx from "clsx";
import { memo, useLayoutEffect, useRef, type ReactNode } from "react";
import { createContext, memo, useContext, useLayoutEffect, useRef, type ReactNode } from "react";
import { formatDuration } from "../conversation";
import styles from "../Session.module.css";
import { summarizeWork, workParts, type WorkSummary } from "../timeline";
import { liveTool, type ConversationRow, type IndexedEntry, type ToolEntryData } from "./conversationRows";
import {
liveTool,
rowEntries,
sameRow,
type ConversationRow,
type IndexedEntry,
type ProcessRow,
type ToolEntryData,
type TurnRow,
} from "./conversationRows";
import { Fold } from "./Folds";
import { shortTitle } from "./shared";
import { samePropsExcept, shortTitle } from "./shared";
import { ThoughtEntry, ToolEntry } from "./toolEntries";
/** "Edited 2 files · Read 4 files": what a run of work did; "Reasoning" when it only thought. */
@@ -19,42 +28,81 @@ function workSummaryText(work: WorkSummary, tx: ReturnType<typeof useTx>, toolCa
return parts;
}
/** A finished turn's work, folded under its message: one line saying what it did and for how long. */
export function TurnFold({
row,
entries,
children,
}: {
row: Extract<ConversationRow, { kind: "turn" }>;
entries: readonly AgentEntry[];
children: ReactNode;
}) {
const tx = useTx();
const { turn } = row;
const work = summarizeWork(entries.slice(turn.user + 1, turn.reply));
const parts = workSummaryText(work, tx, 0);
const messages = entries.slice(turn.user + 1, turn.reply).filter((e) => e.type === "agent").length;
if (messages) parts.push(tx(messages === 1 ? "1 message" : "{count} messages").replace("{count}", String(messages)));
const took = turn.sentMs != null && turn.doneMs != null ? formatDuration(turn.doneMs - turn.sentMs) : null;
/** Renders the rows inside an open turn; the stream owns what a row needs (`Stream`). */
export const RowRenderer = createContext<(row: ConversationRow) => ReactNode>(() => null);
/** A finished turn's work, opened: its rows, painted only while the turn is open. */
function TurnBody({ row }: { row: TurnRow }) {
const renderRow = useContext(RowRenderer);
return (
<Fold
id={`turn:${turn.user}`}
className={clsx(styles.turnFold, styles.process)}
summary={
<summary className={styles.processSummary}>
<Icon name="chevron-right" size={12} className={styles.processChevron} />
<span className={styles.processParts}>{parts.join(" · ")}</span>
{work.added > 0 && <span className={styles.added}>+{work.added}</span>}
{work.removed > 0 && <span className={styles.removed}>−{work.removed}</span>}
{took && <span className={styles.muted}>{took}</span>}
</summary>
}
>
<div className={styles.turnBody}>{children}</div>
</Fold>
<div className={styles.turnBody}>
{row.rows.map((inner) => (
<div key={inner.index} className={styles.conversationRow}>
{renderRow(inner)}
</div>
))}
</div>
);
}
/** A finished turn's work, folded under its message: one line saying what it did and for how long. */
export const TurnFold = memo(
function TurnFold({ row }: { row: TurnRow }) {
const tx = useTx();
const { turn } = row;
const entries = row.rows.flatMap(rowEntries);
const work = summarizeWork(entries);
const parts = workSummaryText(work, tx, 0);
const messages = entries.filter((e) => e.type === "agent").length;
if (messages)
parts.push(tx(messages === 1 ? "1 message" : "{count} messages").replace("{count}", String(messages)));
const took = turn.sentMs != null && turn.doneMs != null ? formatDuration(turn.doneMs - turn.sentMs) : null;
return (
<Fold
id={`turn:${turn.user}`}
className={clsx(styles.turnFold, styles.process)}
summary={
<summary className={styles.processSummary}>
<Icon name="chevron-right" size={12} className={styles.processChevron} />
<span className={styles.processParts}>{parts.join(" · ")}</span>
{work.added > 0 && <span className={styles.added}>+{work.added}</span>}
{work.removed > 0 && <span className={styles.removed}>−{work.removed}</span>}
{took && <span className={styles.muted}>{took}</span>}
</summary>
}
>
<TurnBody row={row} />
</Fold>
);
},
(a, b) => sameRow(a.row, b.row),
);
interface ProcessRunProps {
row: ProcessRow;
task: AgentTask;
lastIndex: number;
busy: boolean;
/** How long each finished thought took, by entry index. */
thinking: ReadonlyMap<number, number> | null;
onDiagramDrawn: () => void;
}
/** Whether the run holds what the agent is doing right now. */
const holdsLive = ({ row, busy, lastIndex }: ProcessRunProps) =>
busy && row.entries.some(({ index }) => index === lastIndex);
/** The rows, the thought durations and the last entry are rebuilt with every chunk: compare what the run paints. */
const sameRun = samePropsExcept<ProcessRunProps>({
row: (a, b) => sameRow(a.row, b.row),
busy: () => true,
lastIndex: (a, b) => holdsLive(a) === holdsLive(b),
thinking: (a, b) =>
a.row.entries.every(
({ index, entry }) => entry.type !== "thought" || a.thinking?.get(index) === b.thinking?.get(index),
),
});
/** Reasoning and tool calls between messages, folded into one row. */
export const ProcessRun = memo(function ProcessRun({
row,
@@ -63,15 +111,7 @@ export const ProcessRun = memo(function ProcessRun({
busy,
thinking,
onDiagramDrawn,
}: {
row: Extract<ConversationRow, { kind: "process" }>;
task: AgentTask;
lastIndex: number;
busy: boolean;
/** How long each finished thought took, by entry index. */
thinking: ReadonlyMap<number, number> | null;
onDiagramDrawn: () => void;
}) {
}: ProcessRunProps) {
const tx = useTx();
const tools = row.entries.filter(
(item): item is IndexedEntry & { entry: ToolEntryData } => item.entry.type === "tool",
@@ -134,4 +174,4 @@ export const ProcessRun = memo(function ProcessRun({
</div>
</Fold>
);
});
}, sameRun);
+32 -36
View File
@@ -52,7 +52,7 @@ import {
import { FindBar } from "./FindBar";
import { KeepFoldHeader, OpenFolds } from "./Folds";
import { Entry } from "./messages";
import { ProcessRun, TurnFold } from "./ProcessRows";
import { ProcessRun, RowRenderer, TurnFold } from "./ProcessRows";
import { type QuestionAnswer } from "./QuestionForm";
import { providerName } from "./shared";
import { WorkingRow } from "./WorkingRow";
@@ -514,13 +514,7 @@ export function Stream({
);
const renderConversationRow = (row: ConversationRow): ReactNode =>
row.kind === "turn" ? (
<TurnFold row={row} entries={entries ?? []}>
{row.rows.map((inner) => (
<div key={inner.index} className={styles.conversationRow}>
{renderConversationRow(inner)}
</div>
))}
</TurnFold>
<TurnFold row={row} />
) : row.kind === "process" ? (
<ProcessRun
row={row}
@@ -636,35 +630,37 @@ export function Stream({
) : entries.length === 0 && !busy && !loadError ? (
<EmptyState title="No conversation history" />
) : (
rows.map((row) => {
const images = toolImages(row);
return (
<div
key={row.index}
className={styles.conversationRow}
data-message={
(row.kind === "entry" && (row.entry.type === "user" || row.entry.type === "agent")) || undefined
}
data-process={row.kind !== "entry" || row.entry.type !== "user" || undefined}
data-author={authorHeaders.has(row.index) || undefined}
>
{authorHeaders.has(row.index) && (
<div className={styles.agentAuthor}>
<div className={styles.role}>
<Icon name={providerIcon(task.provider)} size={13} />
<span>{providerName(task.provider)}</span>
<RowRenderer.Provider value={renderConversationRow}>
{rows.map((row) => {
const images = toolImages(row);
return (
<div
key={row.index}
className={styles.conversationRow}
data-message={
(row.kind === "entry" && (row.entry.type === "user" || row.entry.type === "agent")) || undefined
}
data-process={row.kind !== "entry" || row.entry.type !== "user" || undefined}
data-author={authorHeaders.has(row.index) || undefined}
>
{authorHeaders.has(row.index) && (
<div className={styles.agentAuthor}>
<div className={styles.role}>
<Icon name={providerIcon(task.provider)} size={13} />
<span>{providerName(task.provider)}</span>
</div>
</div>
</div>
)}
{renderConversationRow(row)}
{images.length > 0 && (
<div className={styles.toolImages}>
<ImageStrip images={images} />
</div>
)}
</div>
);
})
)}
{renderConversationRow(row)}
{images.length > 0 && (
<div className={styles.toolImages}>
<ImageStrip images={images} />
</div>
)}
</div>
);
})}
</RowRenderer.Provider>
)}
<WorkingRow task={task} entries={entries} subagent={subagent} />
</div>
@@ -0,0 +1,76 @@
import { describe, expect, it } from "vitest";
import type { AgentEntry } from "@/bindings";
import { foldedTurns } from "../timeline";
import { conversationRows, foldTurnRows, rowEntries, sameRow } from "./conversationRows";
const user = (text: string): AgentEntry => ({
type: "user",
text,
attachments: [],
steered: false,
sentMs: 1000,
doneMs: 5000,
});
const agent = (text: string): AgentEntry => ({ type: "agent", text });
const tool = (id: string, added = 0): AgentEntry => ({
type: "tool",
id,
title: id,
kind: "edit",
status: "completed",
locations: [],
output: null,
diffs: added ? [{ path: `/${id}.ts`, added, removed: 0 }] : [],
});
const rowsOf = (entries: AgentEntry[], busy = false) => {
const rows = conversationRows(entries, 0);
return foldTurnRows(rows, foldedTurns(entries, 0, busy));
};
describe("sameRow", () => {
const entries = [user("a"), tool("t1"), tool("t2"), agent("done"), user("b"), agent("streaming")];
it("sees the rows of the same conversation as the same, whichever copy it was built from", () => {
const again = rowsOf(entries);
expect(again.map((row) => row.kind)).toEqual(["entry", "turn", "entry", "entry", "entry"]);
rowsOf(entries).forEach((row, i) => expect(sameRow(row, again[i]!)).toBe(true));
});
it("leaves the rows a streamed chunk did not touch the same and the grown one different", () => {
const before = rowsOf(entries, true);
const after = rowsOf([...entries.slice(0, -1), agent("streaming on")], true);
expect(after.map((row, i) => sameRow(before[i]!, row))).toEqual([true, true, true, true, false]);
});
it("tells a turn whose work changed from one whose work did not", () => {
const [, turn] = rowsOf(entries);
const [, edited] = rowsOf([entries[0]!, tool("t1"), tool("t2", 7), ...entries.slice(3)]);
expect(sameRow(turn!, edited!)).toBe(false);
});
it("tells a run that gained a call from the run before", () => {
const run = conversationRows([user("a"), tool("t1"), tool("t2")], 0)[1]!;
const longer = conversationRows([user("a"), tool("t1"), tool("t2"), tool("t3")], 0)[1]!;
expect(run.kind).toBe("process");
expect(sameRow(run, longer)).toBe(false);
});
it("tells rows of different places apart even when they hold the same entry", () => {
const shared = agent("same");
expect(sameRow(conversationRows([shared], 0)[0]!, conversationRows([user("x"), shared], 1)[0]!)).toBe(false);
});
it("tells a turn that finished at another time from the turn before", () => {
const later = [{ ...(entries[0] as Extract<AgentEntry, { type: "user" }>), doneMs: 9000 }, ...entries.slice(1)];
expect(sameRow(rowsOf(entries)[1]!, rowsOf(later)[1]!)).toBe(false);
});
});
describe("rowEntries", () => {
it("lists the entries a folded turn paints, work first", () => {
const entries = [user("a"), tool("t1"), tool("t2"), agent("done")];
const [, turn] = rowsOf(entries);
expect(rowEntries(turn!)).toEqual([entries[1], entries[2]]);
});
});
@@ -14,6 +14,8 @@ export type ConversationRow =
| { kind: "turn"; index: number; turn: FoldedTurn; rows: ConversationRow[] };
export type EntryRow = Extract<ConversationRow, { kind: "entry" }>;
export type ProcessRow = Extract<ConversationRow, { kind: "process" }>;
export type TurnRow = Extract<ConversationRow, { kind: "turn" }>;
export const liveTool = (entry: AgentEntry) =>
entry.type === "tool" && (entry.status === "running" || entry.status === "pending");
@@ -68,3 +70,38 @@ export function foldTurnRows(rows: ConversationRow[], turns: ReadonlyMap<number,
}
return out;
}
/** The entries a row paints, in order. */
export function rowEntries(row: ConversationRow): AgentEntry[] {
if (row.kind === "entry") return [row.entry];
return row.kind === "process" ? row.entries.map(({ entry }) => entry) : row.rows.flatMap(rowEntries);
}
/**
* Whether two rows paint the same entries. Rows are rebuilt for every streamed chunk: a row's
* identity says nothing, and only the one the chunk grew differs.
*/
export function sameRow(a: ConversationRow, b: ConversationRow): boolean {
if (a === b) return true;
if (a.index !== b.index) return false;
switch (a.kind) {
case "entry":
return b.kind === "entry" && a.entry === b.entry;
case "process":
return (
b.kind === "process" &&
a.entries.length === b.entries.length &&
a.entries.every(({ entry }, i) => entry === b.entries[i]!.entry)
);
case "turn":
return (
b.kind === "turn" &&
a.turn.user === b.turn.user &&
a.turn.reply === b.turn.reply &&
a.turn.sentMs === b.turn.sentMs &&
a.turn.doneMs === b.turn.doneMs &&
a.rows.length === b.rows.length &&
a.rows.every((row, i) => sameRow(row, b.rows[i]!))
);
}
}
+34 -16
View File
@@ -19,7 +19,7 @@ import { isBusy, type ReplyTimes, type ReplyTurn } from "../model";
import { useRevealedText } from "../reveal";
import { forkTask, rerunFrom, resendMessage } from "../store";
import { PermissionLine, QuestionForm, type QuestionAnswer } from "./QuestionForm";
import { type UserEntry } from "./shared";
import { samePropsExcept, type UserEntry } from "./shared";
import { SubagentCard, ThoughtEntry, ToolEntry } from "./toolEntries";
/** When a message was sent, or when the turn behind a reply finished, and how long it took. */
@@ -92,19 +92,7 @@ function AgentMessage({
);
}
export const Entry = memo(function Entry({
task,
entry,
turn,
turnCount,
reply,
time,
thoughtMs,
working,
drafts,
onOpenSubagent,
onDiagramDrawn,
}: {
interface EntryProps {
task: AgentTask;
entry: AgentEntry;
/** Number of the turn this message started (from 0), when it started one. */
@@ -120,7 +108,21 @@ export const Entry = memo(function Entry({
drafts: RefObject<Map<string, QuestionAnswer[]>>;
onOpenSubagent: (id: string) => void;
onDiagramDrawn: () => void;
}) {
}
function EntryView({
task,
entry,
turn,
turnCount,
reply,
time,
thoughtMs,
working,
drafts,
onOpenSubagent,
onDiagramDrawn,
}: EntryProps) {
switch (entry.type) {
case "user":
return <UserMessage task={task} entry={entry} turn={turn} turnCount={turnCount} />;
@@ -220,7 +222,23 @@ export const Entry = memo(function Entry({
</div>
);
}
});
}
/** The reply and its times are rebuilt from the conversation with every chunk: what they say is what counts. */
export const Entry = memo(
EntryView,
samePropsExcept<EntryProps>({
reply: (a, b) =>
a.reply === b.reply ||
(!!a.reply &&
!!b.reply &&
a.reply.turn === b.reply.turn &&
a.reply.steered === b.reply.steered &&
a.reply.prompt === b.reply.prompt),
time: (a, b) =>
a.time === b.time || (!!a.time && !!b.time && a.time.sentMs === b.time.sentMs && a.time.doneMs === b.time.doneMs),
}),
);
function AgentErrorText({ message }: { message: string }) {
return <span>{useAgentErrorText(message)}</span>;
+16
View File
@@ -20,3 +20,19 @@ export type UserEntry = Extract<AgentEntry, { type: "user" }>;
/** Agent-written titles with the task's own folder dropped from paths. */
export const shortTitle = (task: AgentTask, title: string) => title.replaceAll(`${task.cwd}/`, "");
/**
* `memo`'s comparison for props rebuilt with every render without changing: a prop named in
* `by` is equal when its rule says so, any other prop when it is the same value.
*/
export function samePropsExcept<P extends object>(by: { [K in keyof P]?: (a: P, b: P) => boolean }) {
return (a: P, b: P) => {
const keys = Object.keys(a) as Array<keyof P>;
if (keys.length !== Object.keys(b).length) return false;
for (const key of keys) {
const rule = by[key];
if (!(rule ? rule(a, b) : Object.is(a[key], b[key]))) return false;
}
return true;
};
}
+155 -65
View File
@@ -828,6 +828,67 @@ function relativeIfUnder(bases: readonly string[], absPath: string): string | nu
return null;
}
type FileAsset = Extract<SessionArtifact, { kind: "file" }>;
/** The artifact a path names for the session, or `null` when it is no artifact. */
function fileAsset(
rawPath: string,
source: "edit" | "read" | "mention",
cwd: string,
bases: readonly string[],
): FileAsset | null {
const trimmed = rawPath.trim();
if (!trimmed || /^[a-z][a-z\d+.-]*:/i.test(trimmed)) return null;
const abs = trimmed.startsWith("/") ? resolveTyped("", trimmed) : resolveTyped(cwd, trimmed);
if (!isArtifactCandidate(abs, source)) return null;
return {
key: `file:${abs}`,
kind: "file",
name: basename(abs) || abs,
path: abs,
rel: relativeIfUnder(bases, abs),
externalBinary: EXTERNAL_BINARY_EXTENSIONS.has(extOf(abs)),
};
}
type ForgeItemFields<T> = Omit<T, "title" | "state" | "hasExplicitTitle" | "hasExplicitState">;
interface IssueTouch {
created?: boolean;
title?: string | null;
fallbackTitle?: string | null;
state?: IssueAssetState | null;
}
/** What one entry says about the session's assets, in the order it says it. */
type Finding =
| {
kind: "pr";
item: ForgeItemFields<SessionPullRequest>;
title?: string | null;
state?: PullRequestAssetState | null;
}
| { kind: "issue"; item: ForgeItemFields<SessionIssue>; opts: IssueTouch }
| {
kind: "reference";
refKind: "commit" | "discussion";
key: string;
idLabel: string;
repo: string;
url: string;
title?: string | null;
}
| { kind: "website"; key: string; url: string; fallbackTitle: string; label?: string | null }
| { kind: "file"; asset: FileAsset };
/**
* Findings of each entry, kept while the entry is the same object. A streamed chunk replaces
* the last entry and leaves the rest as they were, so only the replaced one is read again.
* Findings depend on where the task runs: the same entry read for another folder or default
* repository is read again.
*/
const findings = new WeakMap<AgentEntry, { scope: string; found: Finding[] }>();
export interface ExtractAssetsOptions {
task: Pick<AgentTask, "cwd" | "projectRoot">;
entries: readonly AgentEntry[] | null;
@@ -861,7 +922,7 @@ export function extractSessionAssets({
let seq = 0;
const touchPr = (
item: Omit<SessionPullRequest, "title" | "state" | "hasExplicitTitle" | "hasExplicitState">,
item: ForgeItemFields<SessionPullRequest>,
title?: string | null,
state?: PullRequestAssetState | null,
bumpOrder = true,
@@ -890,15 +951,7 @@ export function extractSessionAssets({
});
};
const touchIssue = (
item: Omit<SessionIssue, "title" | "state" | "hasExplicitTitle" | "hasExplicitState">,
opts: {
created?: boolean;
title?: string | null;
fallbackTitle?: string | null;
state?: IssueAssetState | null;
} = {},
) => {
const touchIssue = (item: ForgeItemFields<SessionIssue>, opts: IssueTouch = {}) => {
const cleanTitle = opts.title?.trim() || null;
if (opts.created || createdIssues.has(item.key)) {
// Promote from `references` if it was seen before `gh issue create` completed.
@@ -1008,27 +1061,20 @@ export function extractSessionAssets({
});
};
const touchFile = (rawPath: string, source: "edit" | "read" | "mention") => {
const trimmed = rawPath.trim();
if (!trimmed || /^[a-z][a-z\d+.-]*:/i.test(trimmed)) return;
const abs = trimmed.startsWith("/") ? resolveTyped("", trimmed) : resolveTyped(task.cwd, trimmed);
if (!isArtifactCandidate(abs, source)) return;
const key = `file:${abs}`;
const existing = files.get(key);
const touchFile = (asset: FileAsset) => {
const existing = files.get(asset.key);
if (existing) {
existing.seq = ++seq;
return;
}
const ext = extOf(abs);
files.set(key, {
key,
kind: "file",
name: basename(abs) || abs,
path: abs,
rel: relativeIfUnder(bases, abs),
externalBinary: EXTERNAL_BINARY_EXTENSIONS.has(ext),
seq: ++seq,
});
files.set(asset.key, { ...asset, seq: ++seq });
};
/** What the entry being read says about assets, in the order it says it. */
let found: Finding[] = [];
const foundFile = (rawPath: string, source: "edit" | "read" | "mention") => {
const asset = fileAsset(rawPath, source, task.cwd, bases);
if (asset) found.push({ kind: "file", asset });
};
const ingestUrl = (
@@ -1043,38 +1089,50 @@ export function extractSessionAssets({
if (!classified) return;
switch (classified.kind) {
case "pr":
touchPr(classified, meaningfulLabel(label, classified.idLabel));
found.push({ kind: "pr", item: classified, title: meaningfulLabel(label, classified.idLabel) });
break;
case "issue":
touchIssue(classified, {
created: opts.createdIssue,
title: meaningfulLabel(label, classified.idLabel),
fallbackTitle: classified.fallbackTitle ?? null,
found.push({
kind: "issue",
item: classified,
opts: {
created: opts.createdIssue,
title: meaningfulLabel(label, classified.idLabel),
fallbackTitle: classified.fallbackTitle ?? null,
},
});
break;
case "discussion":
touchOtherReference(
"discussion",
classified.key,
classified.idLabel,
classified.repo,
classified.url,
meaningfulLabel(label, classified.idLabel),
);
found.push({
kind: "reference",
refKind: "discussion",
key: classified.key,
idLabel: classified.idLabel,
repo: classified.repo,
url: classified.url,
title: meaningfulLabel(label, classified.idLabel),
});
break;
case "commit":
touchOtherReference(
"commit",
classified.key,
classified.idLabel,
classified.repo,
classified.url,
meaningfulLabel(label, classified.idLabel),
);
found.push({
kind: "reference",
refKind: "commit",
key: classified.key,
idLabel: classified.idLabel,
repo: classified.repo,
url: classified.url,
title: meaningfulLabel(label, classified.idLabel),
});
break;
case "website":
if (opts.allowWebsites) {
touchWebsite(classified.key, classified.url, classified.fallbackTitle, label);
found.push({
kind: "website",
key: classified.key,
url: classified.url,
fallbackTitle: classified.fallbackTitle,
label,
});
}
break;
}
@@ -1092,13 +1150,13 @@ export function extractSessionAssets({
for (const meta of extractJsonMetadata(output)) {
const classified = classifyUrl(meta.url);
if (classified?.kind === "pr") {
touchPr(classified, meta.title, meta.state);
found.push({ kind: "pr", item: classified, title: meta.title, state: meta.state });
} else if (classified?.kind === "issue") {
const state: IssueAssetState | null = meta.state === "closed" ? "closed" : meta.state ? "open" : null;
touchIssue(classified, {
created: created.createdIssue,
title: meta.title ?? created.issueTitle,
state,
found.push({
kind: "issue",
item: classified,
opts: { created: created.createdIssue, title: meta.title ?? created.issueTitle, state },
});
}
}
@@ -1119,18 +1177,18 @@ export function extractSessionAssets({
// Markdown relative/absolute file links (`[Report](docs/report.md)`).
for (const m of prose.matchAll(/\[([^\][\n]{1,200})\]\(\s*([^)\s]+)\s*\)/g)) {
const file = fileHref(m[2]!, task.cwd);
if (file) touchFile(file.path, "mention");
if (file) foundFile(file.path, "mention");
}
// `@file` mentions in messages.
for (const tok of messageTokens(prose)) {
if (tok.kind !== "file") continue;
const mention = parseMention(tok.value);
if (mention && !mention.dir) touchFile(mention.rel, "mention");
if (mention && !mention.dir) foundFile(mention.rel, "mention");
}
// Inline code spans naming an artifact file (`storage_session_spec.docx`, `/tmp/report.md`).
for (const m of prose.matchAll(/`([^`\n]{3,240})`/g)) {
const link = pathLink(m[1]!, task.cwd);
if (link) touchFile(link.path, "mention");
if (link) foundFile(link.path, "mention");
}
};
@@ -1142,28 +1200,28 @@ export function extractSessionAssets({
touchPr(classified, bpr.title, state);
}
for (const entry of entries ?? []) {
const readEntry = (entry: AgentEntry) => {
if (entry.type === "user") {
ingestProse(entry.text);
const imageCount = entry.images?.length ?? 0;
const attachedFiles = entry.attachments.slice(0, Math.max(0, entry.attachments.length - imageCount));
for (const a of attachedFiles) touchFile(a, "mention");
continue;
for (const a of attachedFiles) foundFile(a, "mention");
return;
}
if (entry.type === "agent" || entry.type === "message") {
ingestProse(entry.text);
continue;
return;
}
if (entry.type === "subagent") {
if (entry.prompt) ingestProse(entry.prompt);
if (entry.reply) ingestProse(entry.reply);
continue;
return;
}
if (entry.type === "tool") {
const edited = entry.kind === "edit" || entry.kind === "move" || entry.diffs.length > 0;
for (const diff of entry.diffs) touchFile(diff.path, "edit");
for (const diff of entry.diffs) foundFile(diff.path, "edit");
if (edited || entry.kind === "read") {
for (const loc of entry.locations) touchFile(loc, edited ? "edit" : "read");
for (const loc of entry.locations) foundFile(loc, edited ? "edit" : "read");
}
if (entry.kind === "fetch") {
for (const link of extractLinks(entry.title)) {
@@ -1199,7 +1257,7 @@ export function extractSessionAssets({
linkLabel: createsPr?.titleFlag || createsIssue?.titleFlag || null,
});
}
continue;
return;
}
// Other tools (e.g. GitHub / Linear / Datadog MCP calls): inspect structured JSON and explicit links.
for (const link of extractLinks(entry.title)) {
@@ -1207,6 +1265,38 @@ export function extractSessionAssets({
}
if (entry.output) ingestToolOutput(entry.output);
}
};
const touch = (finding: Finding) => {
switch (finding.kind) {
case "pr":
touchPr(finding.item, finding.title, finding.state);
break;
case "issue":
touchIssue(finding.item, finding.opts);
break;
case "reference":
touchOtherReference(finding.refKind, finding.key, finding.idLabel, finding.repo, finding.url, finding.title);
break;
case "website":
touchWebsite(finding.key, finding.url, finding.fallbackTitle, finding.label);
break;
case "file":
touchFile(finding.asset);
break;
}
};
const scope = `${task.cwd}\0${task.projectRoot ?? ""}\0${defaultGithubRepo ?? ""}`;
for (const entry of entries ?? []) {
let known = findings.get(entry);
if (known?.scope !== scope) {
found = [];
readEntry(entry);
known = { scope, found };
findings.set(entry, known);
}
known.found.forEach(touch);
}
// Apply live `gh api` metadata enrichment (`title` and `state`).
@@ -0,0 +1,132 @@
/**
* Assets are read from the conversation after every streamed chunk: the entries a chunk
* leaves alone must not be scanned again, however long the conversation is.
*/
import { describe, expect, it } from "vitest";
import type { AgentEntry, AgentTask } from "@/bindings";
import { extractSessionAssets } from "./sessionAssetsModel";
const task = { cwd: "/repo", projectRoot: "/repo" } satisfies Pick<AgentTask, "cwd" | "projectRoot">;
/** A finished `gh` call whose output names a pull request; `reads.count` counts how often the output is read. */
function ghCall(i: number, reads: { count: number }): AgentEntry {
const entry: AgentEntry = {
type: "tool",
id: `gh-${i}`,
title: `gh pr view ${1000 + i}`,
kind: "execute",
status: "completed",
locations: [],
output: null,
diffs: [],
};
Object.defineProperty(entry, "output", {
get() {
reads.count++;
return `https://github.com/acme/app/pull/${1000 + i}`;
},
});
return entry;
}
const agent = (text: string): AgentEntry => ({ type: "agent", text });
const pullRequests = (entries: AgentEntry[]) =>
extractSessionAssets({ task, entries }).pullRequests.map((pr) => pr.idLabel);
describe("assets while a reply streams", () => {
it("does not read the output of earlier tool calls again for each chunk", () => {
const reads = { count: 0 };
const earlier = Array.from({ length: 200 }, (_, i) => ghCall(i, reads));
pullRequests([...earlier, agent("")]);
expect(reads.count).toBeGreaterThan(0);
reads.count = 0;
for (let chunk = 1; chunk <= 20; chunk++) pullRequests([...earlier, agent("word ".repeat(chunk))]);
expect(reads.count).toBe(0);
});
it("shows a reference the streamed message names as soon as its text has it", () => {
const reads = { count: 0 };
const earlier = [ghCall(0, reads), ghCall(1, reads)];
expect(pullRequests([...earlier, agent("Opened it: https://github.com/acme/app/pu")])).toEqual(["#1001", "#1000"]);
expect(pullRequests([...earlier, agent("Opened it: https://github.com/acme/app/pull/77 for review")])).toEqual([
"#77",
"#1001",
"#1000",
]);
});
it("ranks a conversation the same when it reads it from what it kept", () => {
const tool = (extra: Partial<Extract<AgentEntry, { type: "tool" }>>): AgentEntry => ({
type: "tool",
id: "t",
title: "tool",
kind: "other",
status: "completed",
locations: [],
output: null,
diffs: [],
...extra,
});
const entries: AgentEntry[] = [
{
type: "user",
text: "See [the spec](https://github.com/acme/app/issues/5) and @docs/spec.md",
attachments: ["/repo/notes.md"],
steered: false,
},
tool({ kind: "edit", diffs: [{ path: "/repo/docs/report.md", added: 3, removed: 0 }] }),
tool({
kind: "execute",
title: 'gh pr create --title "Add the thing"',
output: "https://github.com/acme/app/pull/40\n",
}),
tool({
kind: "execute",
title: "gh issue create",
output:
'https://github.com/acme/app/issues/41 {"url":"https://github.com/acme/app/issues/41","title":"Bug","state":"OPEN"}',
}),
tool({ kind: "fetch", title: "Fetch https://docs.example.com/guide" }),
agent(
"Done: https://github.com/acme/app/pull/40 and `/tmp/summary.md`, again [spec](https://github.com/acme/app/issues/5)",
),
];
const read = () => extractSessionAssets({ task, entries, remoteUrl: "[email protected]:acme/app.git" });
const first = read();
expect(first.pullRequests.length + first.createdIssues.length + first.references.length).toBeGreaterThan(2);
expect(first.artifacts.length).toBeGreaterThan(1);
expect(read()).toEqual(first);
expect(
extractSessionAssets({ task, entries: structuredClone(entries), remoteUrl: "[email protected]:acme/app.git" }),
).toEqual(first);
});
it("reads an entry again where the task runs elsewhere", () => {
const entries: AgentEntry[] = [{ ...agent("Wrote `docs/out.md`") }];
const rel = (cwd: string) =>
extractSessionAssets({ task: { cwd, projectRoot: cwd }, entries }).artifacts.map((a) =>
a.kind === "file" ? a.path : a.url,
);
expect(rel("/one")).toEqual(["/one/docs/out.md"]);
expect(rel("/two")).toEqual(["/two/docs/out.md"]);
});
it("shows what a replaced entry says now", () => {
const running: AgentEntry = {
type: "tool",
id: "gh",
title: "gh pr create",
kind: "execute",
status: "running",
locations: [],
output: null,
diffs: [],
};
expect(pullRequests([running])).toEqual([]);
expect(pullRequests([{ ...running, status: "completed", output: "https://github.com/acme/app/pull/9" }])).toEqual([
"#9",
]);
});
});
+1 -6
View File
@@ -1125,12 +1125,7 @@ describe("scrolling", () => {
it("defers prepending during a pointer drag and preserves the first row's viewport position", async () => {
const entries = Array.from({ length: 90 }, (_, i): AgentEntry => ({ type: "agent", text: `History ${i}` }));
useAgents.setState({ entries: new Map([["A", entries]]) });
// Mount hidden so the initial batch hasn't yet restored the bottom offset.
const view = render(
<EditorShownProvider value={false}>
<SessionEditor input={input("A")} />
</EditorShownProvider>,
);
const view = render(<SessionEditor input={input("A")} />);
const el = stream();
Object.defineProperty(el, "scrollHeight", {
configurable: true,
+318
View File
@@ -0,0 +1,318 @@
/**
* A streamed chunk changes the last message only: the rows of the history above it must
* not render again, however long the conversation is.
*/
import { act, render, screen, within } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { AgentEntry, AgentEvent, AgentTask } from "@/bindings";
import { useProject } from "@/platform/project";
import { SessionEditor } from "./SessionEditor";
import { SESSION_KIND, sessionKey } from "./model";
import { connect, disconnect, useAgents } from "./store";
const harness = vi.hoisted(() => ({
tasks: [] as unknown[],
/** The agents store only subscribes in the desktop app; nothing else here may take the desktop paths. */
tauri: false,
channel: null as null | { onmessage: (event: unknown) => void },
/** Renders of each agent message by its text, and of each fold by its id. */
replies: new Map<string, number>(),
folds: new Map<string, number>(),
}));
vi.mock("@tauri-apps/api/core", async (original) => ({
...(await original<typeof import("@tauri-apps/api/core")>()),
Channel: class {
onmessage: (event: unknown) => void = () => {};
constructor() {
harness.channel = this;
}
},
}));
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
isTauri: () => harness.tauri,
commands: {
agentSubscribe: async () => ({ status: "ok", data: harness.tasks }),
agentProviders: async () => ({ status: "ok", data: [] }),
agentEntries: async () => ({ status: "ok", data: [] }),
agentChanges: async () => ({ status: "ok", data: [] }),
agentGroupedChanges: async () => ({
status: "ok",
data: { uncommitted: [], commits: [] },
}),
agentContextUsage: async () => ({
status: "error",
error: { kind: "unavailable", message: "none" },
}),
vcsBranchInfo: async () => ({ status: "ok", data: { head: "main" } }),
vcsBranches: async () => ({ status: "ok", data: [] }),
fsProbe: async () => ({
status: "ok",
data: { size: 1, binary: false, tooLarge: false },
}),
},
}));
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
editorService: () => ({ closeInput: vi.fn(), openInput: vi.fn() }),
maybeEditorService: () => ({ activePath: () => null }),
toolWindowService: () => ({ show: vi.fn() }),
}));
// Counts renders of what the rows paint. The factories run before the imports bind, hence the dynamic import.
vi.mock("./AgentReply", async (original) => {
const { createElement } = await import("react");
const actual = await original<typeof import("./AgentReply")>();
return {
...actual,
AgentReply: (props: Parameters<typeof actual.AgentReply>[0]) => {
harness.replies.set(props.text, (harness.replies.get(props.text) ?? 0) + 1);
return createElement(actual.AgentReply, props);
},
};
});
vi.mock("./session/Folds", async (original) => {
const { createElement } = await import("react");
const actual = await original<typeof import("./session/Folds")>();
return {
...actual,
Fold: (props: Parameters<typeof actual.Fold>[0]) => {
if (props.id) harness.folds.set(props.id, (harness.folds.get(props.id) ?? 0) + 1);
return createElement(actual.Fold, props);
},
};
});
const task: AgentTask = {
id: "T",
title: "T",
provider: "codex",
status: "running",
isolation: "local",
model: null,
cwd: "/project",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
};
const input = {
kind: SESSION_KIND,
key: sessionKey(task.id),
data: { task: task.id },
};
const user = (text: string): AgentEntry => ({
type: "user",
text,
attachments: [],
steered: false,
sentMs: 1000,
doneMs: 5000,
});
/** Finished turns as agents write them: a question, reasoning, tool calls, a reply. */
function history(turns: number): AgentEntry[] {
return Array.from({ length: turns }, (_, i): AgentEntry[] => [
user(`Question ${i}`),
{ type: "thought", text: `Thinking ${i}`, startedMs: 1000 },
{
type: "tool",
id: `read-${i}`,
title: `Read src/file${i}.ts`,
kind: "read",
status: "completed",
locations: [],
output: null,
diffs: [],
startedMs: 1100,
endedMs: 1200,
},
{
type: "tool",
id: `edit-${i}`,
title: `Edit src/file${i}.ts`,
kind: "edit",
status: "completed",
locations: [],
output: null,
diffs: [{ path: `/project/src/file${i}.ts`, added: 2, removed: 1 }],
startedMs: 1300,
endedMs: 1400,
},
{ type: "agent", text: `Reply ${i}` },
]).flat();
}
const send = (event: AgentEvent) => act(() => harness.channel!.onmessage(event));
/** Opens a conversation of `turns` finished turns and a new one whose reply starts streaming. */
async function openStreaming(turns: number): Promise<{ stream: (chunks: number) => string; at: number }> {
const entries = [...history(turns), user("Now?")];
harness.tasks = [task];
harness.tauri = true;
await connect();
harness.tauri = false;
useAgents.setState({ entries: new Map([[task.id, entries]]) });
render(<SessionEditor input={input} />);
await screen.findByText(`Reply ${turns - 1}`);
send({
type: "entry",
task: task.id,
subagent: null,
index: entries.length,
entry: { type: "agent", text: "" },
});
let text = "";
return {
/** Index of the streaming reply: what comes next in the conversation follows it. */
at: entries.length,
stream(chunks) {
for (let i = 0; i < chunks; i++) {
const chunk = `word${i} `;
send({
type: "append",
task: task.id,
subagent: null,
index: entries.length,
from: text.length,
text: chunk,
});
text += chunk;
}
return text;
},
};
}
beforeEach(() => {
harness.replies.clear();
harness.folds.clear();
harness.channel = null;
disconnect();
useProject.setState({ settings: { agents: { smoothText: false } } as never });
});
afterEach(() => {
disconnect();
useProject.setState({ settings: null });
});
describe("streaming into a long conversation", () => {
it.each([
{ turns: 5, foldTurns: true },
{ turns: 40, foldTurns: true },
{ turns: 5, foldTurns: false },
{ turns: 40, foldTurns: false },
])(
"renders none of the $turns earlier turns again for a chunk (fold turns: $foldTurns)",
async ({ turns, foldTurns }) => {
useProject.setState({
settings: { agents: { smoothText: false, foldTurns } } as never,
});
const { stream } = await openStreaming(turns);
// The first chunk opens the streaming message; what follows is the steady state.
stream(1);
harness.replies.clear();
harness.folds.clear();
const text = stream(20);
await screen.findByText(/word19$/);
const renders = (counts: Map<string, number>, keep: (key: string) => boolean) =>
[...counts].filter(([key]) => keep(key)).map(([key, count]) => `${key}: ${count}`);
expect({
earlierReplies: renders(harness.replies, (reply) => reply.startsWith("Reply ")),
folds: renders(harness.folds, () => true),
}).toEqual({ earlierReplies: [], folds: [] });
// The message that grows does render for every chunk: the counters see renders at all.
expect(harness.replies.get(text)).toBeGreaterThan(0);
},
);
it("still shows what a new turn changes in the turns above it", async () => {
useProject.setState({ settings: { agents: { smoothText: false, foldTurns: true } } as never });
const { stream, at } = await openStreaming(3);
stream(3);
send({
type: "entry",
task: task.id,
subagent: null,
index: at + 1,
entry: {
type: "tool",
id: "late",
title: "Read late.ts",
kind: "read",
status: "completed",
locations: [],
output: null,
diffs: [],
},
});
send({
type: "entry",
task: task.id,
subagent: null,
index: at + 2,
entry: { type: "agent", text: "Final answer" },
});
const copies = () => screen.getAllByRole("button", { name: "Copy Markdown" }).length;
// The turn in progress has no actions yet; the three before it do, and its work is open.
expect(copies()).toBe(3);
expect(harness.folds.has(`turn:${at - 1}`)).toBe(false);
send({ type: "entry", task: task.id, subagent: null, index: at + 3, entry: user("Next?") });
// The turn that began mid-stream has ended: its reply has actions and its work is folded.
expect(copies()).toBe(4);
expect(harness.folds.has(`turn:${at - 1}`)).toBe(true);
expect(screen.getByText("Final answer")).toBeInTheDocument();
expect(screen.getByText("Next?")).toBeInTheDocument();
});
it.each([{ foldTurns: true }, { foldTurns: false }])(
"still shows an earlier edit that arrives while a reply streams (fold turns: $foldTurns)",
async ({ foldTurns }) => {
useProject.setState({ settings: { agents: { smoothText: false, foldTurns } } as never });
const { stream } = await openStreaming(3);
stream(3);
const added = () => within(document.body).queryAllByText("+7").length;
expect(added()).toBe(0);
// Turn 1's edit (index 8) is rewritten, and so is the reply of turn 2 (index 14).
send({
type: "entry",
task: task.id,
subagent: null,
index: 8,
entry: {
type: "tool",
id: "edit-1",
title: "Edit src/file1.ts",
kind: "edit",
status: "completed",
locations: [],
output: null,
diffs: [{ path: "/project/src/file1.ts", added: 7, removed: 1 }],
},
});
send({
type: "entry",
task: task.id,
subagent: null,
index: 14,
entry: { type: "agent", text: "Reply 2, revised" },
});
expect(await screen.findByText("Reply 2, revised")).toBeInTheDocument();
expect(added()).toBe(1);
expect(screen.getByText("Reply 1")).toBeInTheDocument();
},
);
});
+2 -5
View File
@@ -4,7 +4,7 @@ import clsx from "clsx";
import { create } from "zustand";
import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { isTauri } from "@/platform/ipc";
import { choosePath } from "@/platform/choosePath";
import { EDIT_SCOPES_ACTION, useCustomScopeList } from "@/platform/search";
import { Button, IconButton, Input, Radio, Select, T } from "@/ui";
import { SCOPE_LABELS, currentFile, type ScopeChoice, type ScopeKind } from "./scope";
@@ -40,10 +40,7 @@ export function AnalysisDialogHost() {
}
async function browseDirectory(initial: string): Promise<string | null> {
if (!isTauri()) return null;
const { open } = await import("@/platform/dialog");
const picked = await open({ directory: true, multiple: false, defaultPath: initial || undefined });
return typeof picked === "string" ? picked : null;
return choosePath({ directory: true, defaultPath: initial });
}
const KINDS: ScopeKind[] = ["project", "directory", "file", "changed", "custom"];
+5 -13
View File
@@ -10,6 +10,7 @@ import { tx } from "@/platform/i18n";
import { create } from "zustand";
import { Channel } from "@tauri-apps/api/core";
import { executeAction } from "@/platform/actions";
import { choosePath, choosePaths } from "@/platform/choosePath";
import {
call,
commands,
@@ -427,15 +428,12 @@ export function classifyPickedPoms(root: string, picked: readonly string[]): { l
export async function addProjects(dialogTitle?: string) {
const root = useProject.getState().project?.root;
if (!root || useProject.getState().project?.workspace || !isTauri()) return;
const { open } = await import("@/platform/dialog");
const picked = await open({
const paths = await choosePaths({
title: dialogTitle ?? tx`Add Maven Projects`,
directory: false,
multiple: true,
defaultPath: root,
filters: [{ name: "pom.xml", extensions: ["xml"] }],
});
const paths = typeof picked === "string" ? [picked] : (picked ?? []);
if (!paths.length) return;
const { link, rejected } = classifyPickedPoms(root, paths);
if (link.length) await setLinked(root, link, true);
@@ -470,14 +468,11 @@ export async function importModuleFromExistingSources() {
} catch {
/* Tests and hosts without the tool-window service still link the POM. */
}
const { open } = await import("@/platform/dialog");
const picked = await open({
const path = await choosePath({
title: tx`Import Module from Existing Sources`,
directory: true,
multiple: false,
defaultPath: root,
});
const path = typeof picked === "string" ? picked : picked?.[0];
if (!path) return;
const pom = mavenPomForImport(path);
if (!(await directoryListsPom(pom))) {
@@ -532,16 +527,13 @@ export async function linkGradleProjects() {
!isTauri()
)
return;
const { open } = await import("@/platform/dialog");
const picked = await open({
const paths = await choosePaths({
title: tx`Link Gradle Projects`,
directory: false,
multiple: true,
defaultPath: root,
filters: [{ name: "Gradle build files", extensions: ["gradle", "kts"] }],
});
const paths = typeof picked === "string" ? [picked] : picked;
if (!paths?.length || useProject.getState().project?.root !== root || gen !== generation) return;
if (!paths.length || useProject.getState().project?.root !== root || gen !== generation) return;
const model = await call(commands.gradleLinkProjects(paths));
if (useProject.getState().project?.root !== root || gen !== generation) return;
const configs = await call(commands.runConfigs()).catch(() => useBuild.getState().configs);
+2 -4
View File
@@ -5,6 +5,7 @@
*/
import { useMemo, useState } from "react";
import { create } from "zustand";
import { choosePath } from "@/platform/choosePath";
import { call, commands, isTauri } from "@/platform/ipc";
import { basename } from "@/platform/project";
import { Dialog, Icon, List, T } from "@/ui";
@@ -28,9 +29,7 @@ import styles from "./Coverage.module.css";
const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e));
async function pickReport(): Promise<string | null> {
const { open } = await import("@/platform/dialog");
const file = await open({
multiple: false,
return choosePath({
directory: false,
title: "Import Coverage Report",
filters: [
@@ -41,7 +40,6 @@ async function pickReport(): Promise<string | null> {
{ name: "All files", extensions: ["*"] },
],
});
return typeof file === "string" ? file : null;
}
/** Imports `path` (asks for a file without one) and shows it like a run's suite. */
+2 -1
View File
@@ -1,6 +1,7 @@
/** Query History (browse / paste / delete) and Import Data from File dialogs. */
import { useEffect, useMemo, useState } from "react";
import { call, commands, type DbHistoryEntry } from "@/platform/ipc";
import { readDesktopText } from "@/platform/desktopFiles";
import { editorsFor } from "@/editor/api";
import { Checkbox, Dialog, EmptyState, IconButton, Input, List, Select, T } from "@/ui";
import { notifications } from "@/workbench/contributions";
@@ -157,7 +158,7 @@ export function ImportDialog({ id, schema, table }: { id: string; schema: string
filters: [{ name: "CSV / TSV", extensions: ["csv", "tsv", "txt"] }],
});
if (typeof f !== "string") return;
const content = await call(commands.fsReadText(f));
const content = await readDesktopText(f);
setFile(f);
setText(content);
setSep(guessSeparator(content));
+3 -4
View File
@@ -1,4 +1,5 @@
import { useEffect, useState } from "react";
import { choosePaths } from "@/platform/choosePath";
import { call, commands, type DbJdbcDriver } from "@/platform/ipc";
import { useTx } from "@/platform/i18n";
import { Button, Dialog, IconButton, Input, Select, T } from "@/ui";
@@ -85,14 +86,12 @@ export function JdbcDriverProfiles({
setBusy(true);
setError(null);
try {
const { open } = await import("@/platform/dialog");
const files = await open({
const files = await choosePaths({
title: tx("Choose JDBC Driver and Dependency JARs"),
multiple: true,
directory: false,
filters: [{ name: tx("Java archives"), extensions: ["jar"] }],
});
if (files && draft) {
if (files.length && draft) {
const jars = [...new Set([...draft.jars, ...files])];
set({ jars });
const names = await call(commands.dbJdbcDriverClasses(jars));
Loaded 100 of 185 files, more files were not shown because too many files have changed in this diff. Show more