Compare commits

..
Author SHA1 Message Date
l0ng-ai 9b4358f046 fix(database): show a running SQL statement in the editor and results
The console only tracked the running request for Run and Cancel; statement
marks and result tabs arrived after the request ended, and the Results view
said "No results" in the meantime. While a request runs, the submitted
statements are now highlighted with a spinner in the gutter and a ticking
elapsed time, and the Results view opens with an executing bar above the
previous result. Edits made meanwhile move the marks, and the outcomes land
on their statements. Cancel or an error clears the indication and keeps the
previous result and marks.

Fixes #4565
2026-11-20 04:05:59 +08:00
l0ng-ai 8daaef38d9 fix(run): keep Run Anything controls visible on short windows (#4581)
Run Anything had a fixed 620px popup with a 360px list cap and a footer that could fall off short windows. The popup now fits the viewport as a column whose list shrinks, uses the shared search field with combobox semantics, shows the completion of the selected entry in the field, pages by the visible row count (compact-aware), and keeps a wrapping footer with the navigation hints.
2026-11-20 03:39:37 +08:00
Chris Schofield efd4e454ee feat(appearance): make Compact Mode match IntelliJ's compact density (#4593)
Compact Mode only lowered the title bar and narrowed the stripes: row heights, toolbar widgets and icons were fixed in code, and nothing in JS (where virtualised list row heights are set) could tell whether the mode was on. A small density store now mirrors the setting for JS, and Compact Mode uses IntelliJ's *.compact theme values: tree/list rows 22 (VCS log 24), toolbar widgets 26, toolbar and stripe icons 16, status bar 24, island gap 4, and chrome text 1px smaller.

Co-authored-by: ChildishForces <[email protected]>
2026-11-20 03:26:32 +08:00
l0ng-ai 0379c37a49 fix(usages): keep results and previews readable in narrow windows (#4580)
The Show Usages popup and the Find usages view used fixed header heights, a flexible spacer and a fixed preview height, so in narrow windows the title, file names and line numbers were clipped and the preview pushed results off screen. Headers now wrap their actions, rows use a file / line / text grid with truncation, and the preview shrinks with the viewport.
2026-11-20 03:21:33 +08:00
l0ng-ai 98da80b2b3 fix(editor): keep the current breadcrumb visible (#4579)
Long breadcrumb trails hid the current file or symbol when the editor or status bar ran out of room. Both trails now scroll to the current location (with edge fades) and keep earlier entries reachable by wheel, trackpad or keyboard. The status bar reserves a minimum width for the path and moves lower-priority widgets into its overflow menu. Code breadcrumbs use the editor font and highlight the symbol at the caret.
2026-11-20 03:05:31 +08:00
l0ng-ai 5c2e7ff92a fix(editor): fit intention previews beside or below the list (#4578)
The intention preview had a fixed 420px width beside the list, which pushed the action list away from the caret or got clipped in narrow windows. The preview now opens to the right when there is room, to the left when that keeps the list by the caret, and below the list in narrow windows. Preview code follows the editor's font settings and theme and wraps long lines.
2026-11-20 02:54:44 +08:00
l0ng-ai e86a853048 fix(run): keep configuration names visible in narrow sidebars (#4573)
A long run target could take the whole row in the Run/Debug Configurations sidebar, leaving the configuration name at zero width and forcing horizontal scrolling. Target labels now truncate in wide panes, narrow panes (container query) hide the muted target and scope, and the row tooltip carries the full name, target, scope and command. Type headings are semibold.
2026-11-20 02:53:44 +08:00
l0ng-ai fd8f0eb99c fix(editor): make quick documentation fit narrow windows (#4568)
Quick Documentation used a fixed 600px cap and kept its caret anchor after the window shrank, so short documents looked cramped and the actions could end up off screen. The popup now sizes to a 300-500px content width, keeps its actions together in the lower-right corner while the document scrolls, and clamps the anchor to the current viewport.
2026-11-20 02:52:46 +08:00
l0ng-ai 121e1fa535 fix(completion): fit the lookup to the editor and its font (#4566)
The lookup reserved a fixed 420px row, so long names pushed the signature and type past the editor edge, and the body-level tooltip ignored temporary editor zoom. It now sizes to its content within the editor's tooltip bounds, truncates each field, applies the label alignment through CodeMirror's own offset so the viewport clamp accounts for it, and follows the editor's current font size.
2026-11-20 02:51:47 +08:00
lleviathe 5859cf9f5b feat(mcp): show background projects in the status bar (#4590)
A Background Projects status bar item shows how many projects the MCP server holds open without a window, only while there are any (and never in a remote window). Its popup lists each project with its badge, state and path, opens one in its own window or unloads it, and offers Unload All and MCP Server Settings. The Settings page's Open now list uses the same rows.

Co-authored-by: lleviathe <[email protected]>
2026-11-20 02:49:08 +08:00
l0ng-ai 21b187f2d5 test: fix main's spacing-scale and model-refresh failures (#4591)
pnpm test failed on main twice: the HTTP Client's redirect list from #4519 used gap: 2px instead of --space-0-5, and the agent model-refresh test's IPC mock lacked vcsRemotes, which the session's origin lookup reads since #4554.
2026-11-20 02:47:51 +08:00
Aditya Aggarwalandaditya-786 121d7edc15 feat(spring): find Feign clients for a controller endpoint (#4584)
A Spring controller endpoint gets Find Feign Clients (gutter menu, editor context menu, Find Action; Java and Kotlin): it matches the HTTP method and literal route across the trusted workspace and uses the controller module's spring.application.name to leave out clients of other services. One known match opens directly; otherwise a chooser lists the interface methods, with unresolved service names and explicit URLs marked Possible match.

Co-authored-by: aditya-786 <[email protected]>
2026-11-20 02:44:16 +08:00
Gabriel Gondim b9256a7260 fix(deployment): use Commit selection for upload shortcuts (#4585)
Deployment actions run by shortcut, Find Action or the Tools menu used the Project view's selection (else the editor's file) even in the Commit tool window, where only the context menu passed the selected changes. The changes tree now provides its selection while Commit or Git > Local Changes is focused, without deleted files, and Deployment takes it after a menu's paths.

Co-authored-by: GGVidal <[email protected]>
2026-11-20 02:28:50 +08:00
Mansur Akhmadiandmansur-akhmadi 47b4cb55ba feat(run): Sort Alphabetically / Sort by Duration in the test results toolbar (#4576)
The test results toolbar gets Sorting Options with Sort Alphabetically (by name at every level, ignoring case, numbers by value) and Sort by Duration (slowest first at every level, a suite by its total, untimed last; disabled and not applied while the run is in progress). The two replace each other, run after the filters and are kept with Show Passed / Show Ignored.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-20 01:31:29 +08:00
Vadim LazukandInf1mum da1bcd67cd fix(http-client): keep the request method across redirects and show the hops (#4519)
reqwest's automatic redirects turned a POST into a plain GET on a 301 or 302, such as the http to https redirect in #4486, and hid the redirect. Redirects are now followed by hand, as IntelliJ's HTTP Client does: 301, 302, 303, 307 and 308, at most 50 times. A 303 continues as GET without the body; the other statuses keep the method and body. Authorization and cookie headers are not re-sent to another host. The followed hops are listed in the response view.

Co-authored-by: Inf1mum <[email protected]>
2026-11-20 01:30:22 +08:00
Mr0Bread 67a4797cf4 fix(editor): preserve dirty state across concurrent saves (#4571)
Typing while a save was pending could leave the editor clean although the newest edit was not written: the save reply cleared the dirty flag even after a dirty event for a newer version, and a delayed clean event for the earlier write could clear it too. DocDirty now carries the document version from under the backend lock; the editor applies a clean transition only when that version is the synced one and no edits are pending, and a save reply only confirms the version it sent.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-20 01:28:48 +08:00
l0ng-ai 39523bc419 fix(terminal): float search over the output area (#4560)
Find in Terminal took a full-width row and shrank the grid. Wide, tall panes now show a compact search bar over the output's upper-right corner, keeping the full grid; it moves to the lower right when it would cover the active match. Short panes use an inline bar and narrow panes put the controls in two rows.
2026-11-20 01:23:38 +08:00
Mr0Bread 639c76d54c test(documents): protect dirty state on failed saves (#4567)
Tests that a failed save keeps the edited buffer dirty and emits no clean-state event: text the encoding can't represent, permission denial (Unix, with a retry after restoring permissions) and a file replaced by a directory. Disk bytes and the replacement directory stay untouched.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-20 01:21:12 +08:00
l0ng-ai d5f29ea256 fix(build-tools): keep toolbar actions reachable in narrow panes (#4558)
The Maven and Gradle toolbars used one fixed row, which clipped actions in narrow panes. Narrow panes keep reload or cancel, run and execute visible and group the rest in More Actions; widening the pane restores the full toolbar, keeping the offline and skip-tests toggle states.
2026-11-20 01:06:13 +08:00
l0ng-ai f9455549a7 fix(vcs): keep branch rows readable in narrow popups (#4551)
Git Branches uses the interface font for branch names, tracked branches and refs, tapers indentation at deeper levels and limits the width of secondary refs, so deeply nested branches keep room for the name, commit counts and submenu arrow. The full branch and tracked ref show on hover.
2026-11-20 00:45:28 +08:00
l0ng-ai dd14e8b040 fix(run): keep classpath and target probes from opening console windows on Windows (#4562)
On Windows the GUI-subsystem app gave console children their own window unless they were spawned with CREATE_NO_WINDOW. Three probes used a bare std Command: the Maven classpath probe behind delegated Run/Debug, the .NET target-path probe and go list for file-scoped Go tests. The first two now go through ide_core::process::prepare; the Go probe, whose environment is already built, gets the flag. The other backend spawn sites already prepare.
2026-11-20 00:42:56 +08:00
Paweł SzymańskiandPawelSzymanski89 efce16d45d feat(agents): add Hermes Agent with a profile picker and richer tool-call view (#4542)
Adds Hermes Agent as a built-in ACP agent, with a Hermes profile picker. The tool-call view also gets richer: kind icons, duration, status, exit codes, a terminal block for commands, and links to the files a tool touched (omitted when the title already names the file).

Co-authored-by: PawelSzymanski89 <[email protected]>
2026-11-20 00:32:51 +08:00
l0ng-ai 977ce62bf0 fix(search): improve recent file and location layouts (#4548)
Recent Files keeps directories beside file names and gives the list and filter more room in narrow windows. Recent Locations snippets follow the editor font and line spacing, and long file names leave room for the change label and timestamp.
2026-11-20 00:22:22 +08:00
l0ng-ai 479123dcf3 fix(plugins): give a child's status only with the last of its output (#4572)
poll and wait returned the exit status as soon as the process ended. Reader threads could still be copying its pipes, or more output could be buffered than one chunk holds, so a caller stopping at the first status parsed a truncated result. The status now comes only with the chunk that drains the output once both pipes reached the end. WIT, SDK and guide docs say so, and point to run_command for a command's whole output.
2026-11-20 00:18:30 +08:00
l0ng-ai 09301ca12d test(bench): skip browser tests where Playwright's Chromium isn't installed (#4570)
Since #4489 and #4491, harness tests under pnpm test launched Chromium, but CI's Frontend job installs no Playwright browsers, so Frontend failed on every pull request. Those tests now skip when the build they launch (headless shell, or the full browser for the chromium channel) is missing. The legacy artifact-date test compares whole seconds, which every file system keeps.
2026-11-20 00:03:28 +08:00
l0ng-ai 485c1ac40b fix(search): fit Search Everywhere within a compact popup (#4546)
Search Everywhere opens at 700 px wide and up to 600 px tall, query and footer included. Long lists and the code preview fit inside that height, so more of the editor stays visible.
2026-11-20 00:02:05 +08:00
l0ng-ai 6d756ec472 fix(editor): keep diagnostics in place through edits when another source updates (#4563)
Whenever any diagnostic source published, the editor converted every source's stored line/column ranges against the current text again. So lists published earlier, notably checks of the saved file (build, PHPStan, Kotlin bridge), jumped to the wrong code after typing. Each source's list is now anchored to the text it arrived for, and placed through the edits made since then. The editor-side counterpart of #4482.
2026-11-19 23:40:34 +08:00
257 changed files with 5581 additions and 892 deletions

No files matched your search

+22 -1
View File
@@ -3,7 +3,7 @@
use crate::model::{
AgentCommand, AgentCommandSource, AgentConfigOption, AgentConfigValue, AgentConfigVia, AgentCost, AgentLimit,
AgentModelPricing, AgentUsage,
AgentModelPricing, AgentTokens, AgentUsage,
};
use serde_json::{Value, json};
@@ -272,6 +272,18 @@ pub(crate) fn usage_of(update: &Value) -> Option<AgentUsage> {
Some(AgentUsage { used: tokens("used")?, size: tokens("size").filter(|s| *s > 0)?, cost })
}
/// The `usage` of a `session/prompt` result: `{ inputTokens, cachedReadTokens, outputTokens }`.
pub(crate) fn tokens_of(result: &Value) -> Option<AgentTokens> {
let usage = result.get("usage")?;
let tokens = |key: &str| usage.get(key).and_then(Value::as_u64).map_or(0, |n| u32::try_from(n).unwrap_or(u32::MAX));
let tokens = AgentTokens {
input: tokens("inputTokens"),
cached: tokens("cachedReadTokens"),
output: tokens("outputTokens"),
};
(tokens != AgentTokens::default()).then_some(tokens)
}
/// The usage-limit windows a [`crate::LIMITS_UPDATE`] carries; malformed entries are skipped.
pub(crate) fn limits_of(update: &Value) -> Vec<AgentLimit> {
let limits = update.get("limits").and_then(Value::as_array).into_iter().flatten();
@@ -368,6 +380,15 @@ mod tests {
c.iter().map(|o| (o.id.as_str(), o.current.as_deref())).collect()
}
#[test]
fn a_hermes_prompt_result_reports_the_turns_tokens() {
let result = json!({"stopReason": "end_turn", "usage": {"cachedReadTokens": 51306, "inputTokens": 77284,
"outputTokens": 509, "thoughtTokens": 0, "totalTokens": 77793}});
assert_eq!(tokens_of(&result), Some(AgentTokens { input: 77284, cached: 51306, output: 509 }));
assert_eq!(tokens_of(&json!({"stopReason": "end_turn"})), None);
assert_eq!(tokens_of(&json!({"usage": {}})), None);
}
#[test]
fn config_options_win_over_the_older_fields() {
let r = json!({
+111
View File
@@ -0,0 +1,111 @@
//! Hermes Agent profiles on disk: `default` is the Hermes home itself, the others are
//! `<home>/profiles/<name>` directories holding one of Hermes' identity files.
use std::path::{Path, PathBuf};
use serde::Serialize;
use specta::Type;
const PROFILE_FILES: &[&str] = &["config.yaml", ".env", "SOUL.md", "profile.yaml", "auth.json", "state.db"];
/// Hermes' home directory (`~/.hermes`; `%LOCALAPPDATA%\hermes` on Windows).
pub fn root(home: Option<&Path>) -> Option<PathBuf> {
#[cfg(windows)]
if let Some(local) = std::env::var_os("LOCALAPPDATA") {
return Some(PathBuf::from(local).join("hermes"));
}
home.map(|h| h.join(".hermes"))
}
/// The profile names under `root`: `default` first, then the others by name; none without `root`.
pub fn profiles(root: &Path) -> Vec<String> {
if !root.is_dir() {
return Vec::new();
}
let mut named: Vec<String> = std::fs::read_dir(root.join("profiles"))
.into_iter()
.flatten()
.flatten()
.filter(|e| PROFILE_FILES.iter().any(|f| e.path().join(f).exists()))
.filter_map(|e| e.file_name().to_str().map(str::to_owned))
.filter(|name| name != "default")
.collect();
named.sort();
std::iter::once("default".to_owned()).chain(named).collect()
}
/// A profile and the name Hermes shows for it (`hermes profile list`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Type)]
pub struct HermesProfile {
/// What `hermes -p` takes; `default` is the Hermes home itself.
pub name: String,
/// `display_name` from the profile's `profile.yaml`, else the name.
pub label: String,
}
/// [`profiles`] with the names Hermes shows for them.
pub fn labeled_profiles(root: &Path) -> Vec<HermesProfile> {
profiles(root)
.into_iter()
.map(|name| {
let home = if name == "default" { root.to_path_buf() } else { root.join("profiles").join(&name) };
let label = display_name(&home).unwrap_or_else(|| name.clone());
HermesProfile { name, label }
})
.collect()
}
/// The top-level `display_name:` of `<home>/profile.yaml`, the only key read (no YAML parser).
fn display_name(home: &Path) -> Option<String> {
let text = std::fs::read_to_string(home.join("profile.yaml")).ok()?;
let value = text.lines().find_map(|l| l.strip_prefix("display_name:"))?;
let value = value.trim().trim_matches(['"', '\'']).trim();
(!value.is_empty()).then(|| value.to_owned())
}
/// The home of the profile an agent id stands for: `hermes` and `hermes-default` are the
/// default profile, `hermes-<slug>` the profile whose name slugifies to `<slug>`.
pub fn profile_home(root: &Path, provider: &str) -> Option<PathBuf> {
let slug = match provider {
"hermes" | "hermes-default" => return Some(root.to_path_buf()),
_ => provider.strip_prefix("hermes-")?,
};
profiles(root).into_iter().find(|p| crate::provider::slugify_id(p) == slug).map(|p| root.join("profiles").join(p))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lists_default_and_profiles_with_an_identity_file() {
let dir = tempfile::tempdir().unwrap();
assert!(profiles(&dir.path().join("missing")).is_empty());
let root = dir.path().join(".hermes");
std::fs::create_dir_all(root.join("profiles/empty")).unwrap();
assert_eq!(profiles(&root), ["default"]);
for (name, file) in [("work", "config.yaml"), ("Dom 2", "SOUL.md"), ("db", "state.db")] {
std::fs::create_dir_all(root.join("profiles").join(name)).unwrap();
std::fs::write(root.join("profiles").join(name).join(file), "").unwrap();
}
std::fs::write(root.join("profiles/stray.yaml"), "").unwrap();
assert_eq!(profiles(&root), ["default", "Dom 2", "db", "work"]);
assert_eq!(profile_home(&root, "hermes"), Some(root.clone()));
assert_eq!(profile_home(&root, "hermes-dom-2"), Some(root.join("profiles/Dom 2")));
assert_eq!(profile_home(&root, "hermes-empty"), None);
assert_eq!(profile_home(&root, "claude"), None);
}
#[test]
fn labels_profiles_with_their_display_name() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join(".hermes");
std::fs::create_dir_all(root.join("profiles/work")).unwrap();
std::fs::write(root.join("profile.yaml"), "description: mine\ndisplay_name: \"qb\"\n").unwrap();
std::fs::write(root.join("profiles/work/profile.yaml"), "ui_meta:\n display_name: nested\n").unwrap();
let label = |name: &str, label: &str| HermesProfile { name: name.into(), label: label.into() };
assert_eq!(labeled_profiles(&root), [label("default", "qb"), label("work", "work")]);
std::fs::remove_file(root.join("profile.yaml")).unwrap();
assert_eq!(labeled_profiles(&root)[0], label("default", "default"));
}
}
+34 -4
View File
@@ -14,6 +14,7 @@ mod config;
mod conversation;
mod elicitation;
mod external;
pub mod hermes;
pub mod mcp;
mod model;
mod native;
@@ -709,7 +710,8 @@ impl AgentManager {
/// The slash commands to complete for `provider`, in `task`'s directory or (without one)
/// in the project: what the agent offered last time there, unadvertised builtins,
/// and, for Claude Code, skills and custom commands on disk it has not listed.
/// and, for Claude Code, skills and custom commands on disk it has not listed (for Hermes,
/// its profile's skills).
pub async fn commands(&self, provider: &str, task: Option<&str>) -> IdeResult<Vec<AgentCommand>> {
let (provider, offered, cwd) = match task {
Some(id) => {
@@ -743,10 +745,18 @@ impl AgentManager {
offered.push(command);
}
}
let home = self.shared.paths.home_dir.clone();
if provider == "hermes" || provider.starts_with("hermes-") {
let found = blocking(move || {
let profile = hermes::root(home.as_deref()).and_then(|root| hermes::profile_home(&root, &provider));
Ok(profile.map(|p| skills::hermes(&p)).unwrap_or_default())
})
.await?;
return Ok(skills::merge(offered, found));
}
if provider != "claude" && provider != "claude-acp" {
return Ok(offered);
}
let home = self.shared.paths.home_dir.clone();
let found = blocking(move || Ok(skills::discover(&cwd, home.as_deref()))).await?;
Ok(skills::merge(offered, found))
}
@@ -832,6 +842,7 @@ impl AgentManager {
retry: None,
background: Box::default(),
mcp_overrides: BTreeMap::new(),
stats: Box::default(),
};
let file = TaskFile {
task: task.clone(),
@@ -949,6 +960,7 @@ impl AgentManager {
retry: None,
background: Box::default(),
mcp_overrides: req.mcp_overrides,
stats: Box::default(),
};
let file = TaskFile {
task: task.clone(),
@@ -1316,6 +1328,7 @@ impl AgentManager {
resets_ms: None,
retry: None,
background: Box::default(),
stats: Box::default(),
..s.task.clone()
};
TaskFile {
@@ -2653,7 +2666,13 @@ impl Task {
.await;
}
match result {
Ok(v) => Ok(v.get("stopReason").and_then(Value::as_str).unwrap_or("end_turn").to_owned()),
Ok(v) => {
if let Some(tokens) = config::tokens_of(&v) {
self.state.lock().task.stats.tokens = Some(tokens);
self.emit_task();
}
Ok(v.get("stopReason").and_then(Value::as_str).unwrap_or("end_turn").to_owned())
}
Err(e) => Err(self.failure(e)),
}
}
@@ -3187,6 +3206,17 @@ impl Task {
return;
}
if kind == "session_info_update" {
let depth = update.pointer("/_meta/hermes/sessionProvenance/compressionDepth").and_then(Value::as_u64);
if let Some(depth) = depth.and_then(|d| u32::try_from(d).ok()) {
let changed = {
let mut s = self.state.lock();
std::mem::replace(&mut s.task.stats.compressions, depth) != depth
};
if changed {
self.persist();
self.emit_task();
}
}
// The agent's own title for the session replaces the first line of the prompt,
// unless the user named the task.
let title = update.get("title").and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty());
@@ -4038,7 +4068,7 @@ fn entry_event(
entry: &AgentEntry,
) -> AgentEvent {
let text = match entry {
AgentEntry::Agent { text } | AgentEntry::Thought { text } => Some(text),
AgentEntry::Agent { text } | AgentEntry::Thought { text, .. } => Some(text),
_ => None,
};
let Some(text) = text else {
+31
View File
@@ -108,6 +108,29 @@ pub struct AgentTask {
/// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub mcp_overrides: BTreeMap<String, bool>,
/// Token counts of the last turn and context compressions, when the agent reports them.
// Boxed so that `AgentEvent::Task` stays within clippy's `large_enum_variant` bound on Windows.
#[serde(default)]
pub stats: Box<AgentSessionStats>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentSessionStats {
/// The last turn's tokens (`session/prompt` result `usage`).
#[serde(default)]
pub tokens: Option<AgentTokens>,
/// How many times the agent compressed the conversation (Hermes `compressionDepth`).
#[serde(default)]
pub compressions: u32,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentTokens {
pub input: u32,
pub cached: u32,
pub output: u32,
}
/// A task the agent runs in the background while the conversation goes on.
@@ -479,6 +502,9 @@ pub enum AgentEntry {
},
Thought {
text: String,
/// When the reasoning started (ms since the epoch); `None` in tasks saved before.
#[serde(default)]
started_ms: Option<f64>,
},
Tool {
id: String,
@@ -490,6 +516,11 @@ pub enum AgentEntry {
/// Text the tool reported (command output…), truncated.
output: Option<String>,
diffs: Vec<AgentToolDiff>,
/// When the call started and ended (ms since the epoch); `None` in tasks saved before.
#[serde(default)]
started_ms: Option<f64>,
#[serde(default)]
ended_ms: Option<f64>,
},
Plan {
items: Vec<AgentPlanItem>,
+11 -1
View File
@@ -82,6 +82,7 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
("kiro", "Kiro", Driver::Acp, &["kiro-cli", "acp"], "Run `kiro-cli login` in a terminal."),
("vibe", "Mistral Vibe", Driver::Acp, &["vibe-acp"], "Run `vibe` in a terminal and sign in."),
("omp", "OMP", Driver::Acp, &["omp", "acp"], "Run `omp` in a terminal and sign in."),
("hermes", "Hermes Agent", Driver::Acp, &["hermes", "acp"], "Run `hermes model` in a terminal."),
];
fn builtins() -> Vec<ProviderSpec> {
@@ -503,7 +504,7 @@ fn validated_custom_id(id: &str) -> IdeResult<String> {
}
/// Turns an `acp.json` server name into a file-stem id (`"My Agent!"` → `"my-agent"`).
fn slugify_id(name: &str) -> String {
pub(crate) fn slugify_id(name: &str) -> String {
let mut id = String::with_capacity(name.len());
for c in name.chars() {
if c.is_ascii_alphanumeric() {
@@ -716,6 +717,15 @@ mod tests {
use super::*;
use serde_json::json;
#[test]
fn hermes_is_built_in_over_acp() {
let spec = builtin_spec("hermes").unwrap();
assert_eq!(spec.driver, Driver::Acp);
let info = describe(&spec);
assert_eq!((info.name.as_str(), info.command.as_str()), ("Hermes Agent", "hermes acp"));
assert_eq!(info.login_hint.as_deref(), Some("Run `hermes model` in a terminal."));
}
#[test]
fn qoder_global_and_cn_editions_are_both_built_in() {
let info = |id: &str| describe(&load(None, None).into_iter().find(|s| s.id == id).unwrap());
+33 -1
View File
@@ -1,6 +1,7 @@
//! Claude Code's slash commands on disk, for completion before (or without) a session:
//! skills (`.claude/skills/<dir>/SKILL.md`) and custom commands (`.claude/commands/**/*.md`)
//! of the working directory and every directory above it, then the user's `~/.claude`.
//! of the working directory and every directory above it, then the user's `~/.claude`; and
//! the skills of a Hermes profile (`<profile>/skills`).
use crate::{AgentCommand, AgentCommandSource};
use std::collections::HashSet;
@@ -34,6 +35,19 @@ pub(crate) fn discover(cwd: &Path, home: Option<&Path>) -> Vec<AgentCommand> {
out
}
/// The skills of a Hermes profile: `<profile>/skills/<skill>` and `<profile>/skills/<category>/<skill>`;
/// the first of a name wins.
pub(crate) fn hermes(profile: &Path) -> Vec<AgentCommand> {
let root = profile.join("skills");
let mut found = skills(&root);
for category in sorted(&root).into_iter().filter(|p| !p.join("SKILL.md").exists()) {
found.extend(skills(&category));
}
let mut seen = HashSet::new();
found.retain(|c| seen.insert(c.name.clone()));
found
}
/// `first` (the agent's own list) plus the commands of `more` it lacks.
pub(crate) fn merge(first: Vec<AgentCommand>, more: Vec<AgentCommand>) -> Vec<AgentCommand> {
let mut out = first;
@@ -256,6 +270,24 @@ mod tests {
);
}
#[test]
fn hermes_skills_flat_and_in_categories() {
let tmp = tempfile::tempdir().unwrap();
let profile = tmp.path();
assert!(hermes(profile).is_empty());
for dir in ["skills/plan", "skills/dev/review", "skills/dev/plan", "skills/empty"] {
std::fs::create_dir_all(profile.join(dir)).unwrap();
}
for dir in ["skills/plan", "skills/dev/review", "skills/dev/plan"] {
std::fs::write(profile.join(dir).join("SKILL.md"), "---\ndescription: d\n---\n").unwrap();
}
let names: Vec<_> = hermes(profile).into_iter().map(|c| (c.name, c.source)).collect();
assert_eq!(
names,
[("plan".to_owned(), AgentCommandSource::Skill), ("review".to_owned(), AgentCommandSource::Skill)]
);
}
#[test]
fn nothing_without_claude_dirs() {
let tmp = tempfile::tempdir().unwrap();
+51 -2
View File
@@ -909,6 +909,27 @@ async fn authenticates_and_retries_session_setup_once_on_auth_error() {
mgr3.shutdown();
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn hermes_profiles_complete_their_own_skills() {
let tmp = tempfile::tempdir().unwrap();
let skill = |dir: &str, name: &str| {
let dir = tmp.path().join(dir).join(name);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("SKILL.md"), format!("---\nname: {name}\ndescription: d\n---\n")).unwrap();
};
skill(".hermes/skills", "plan");
skill(".hermes/profiles/dom/skills/home", "lights");
std::fs::write(tmp.path().join(".hermes/profiles/dom/config.yaml"), "").unwrap();
let mgr = manager_at(tmp.path(), &tmp.path().join("models.json"), Arc::new(FakeAgent::default()));
let names = |c: Vec<AgentCommand>| c.into_iter().map(|c| c.name).collect::<Vec<_>>();
assert!(names(mgr.commands("hermes", None).await.unwrap()).contains(&"plan".to_owned()));
let dom = names(mgr.commands("hermes-dom", None).await.unwrap());
assert!(dom.contains(&"lights".to_owned()) && !dom.contains(&"plan".to_owned()));
assert!(!names(mgr.commands("claude", None).await.unwrap()).contains(&"plan".to_owned()));
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
let tmp = tempfile::tempdir().unwrap();
@@ -1877,6 +1898,32 @@ async fn real_claude_task_in_a_worktree() {
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn hermes_session_info_names_the_task_and_counts_compressions() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
// "again" ends the turn at once; the default prompt waits for a permission answer.
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let handle = mgr.task(&task.id).unwrap();
let info = |title: &str, depth: u32| {
json!({"sessionUpdate": "session_info_update", "title": title, "updatedAt": "2026-11-18T18:35:32.068362+00:00",
"_meta": {"hermes": {"sessionProvenance": {"sessionKind": "root", "parentHermesSessionId": null,
"compressionDepth": depth}}}})
};
handle.on_update(None, &info("Make a 3-step plan and carry it out: 1) list the…", 0));
handle.on_update(None, &info("List files and edit notes.txt", 0));
let t = handle.state.lock().task.clone();
assert_eq!(t.title, "List files and edit notes.txt", "the agent's latest title wins");
assert_eq!(t.stats.compressions, 0);
handle.on_update(None, &info("List files and edit notes.txt", 2));
assert_eq!(handle.state.lock().task.stats.compressions, 2);
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn renamed_titles_survive_updates_forks_and_restart() {
let tmp = tempfile::tempdir().unwrap();
@@ -3531,11 +3578,13 @@ fn streamed_text_is_sent_as_appends() {
);
let replaced = entry_event("t", &mut streamed, None, 3, &agent("Other"));
assert!(matches!(replaced, AgentEvent::Entry { .. }), "text that doesn't extend the sent text is sent whole");
let thought = entry_event("t", &mut streamed, None, 4, &AgentEntry::Thought { text: "hmm…".into() });
let thought = AgentEntry::Thought { text: "hmm…".into(), started_ms: None };
let thought = entry_event("t", &mut streamed, None, 4, &thought);
assert!(matches!(thought, AgentEvent::Entry { index: 4, .. }), "a new message starts whole");
let tool = AgentEntry::Error { message: "x".into() };
entry_event("t", &mut streamed, None, 4, &tool);
let again = entry_event("t", &mut streamed, None, 4, &AgentEntry::Thought { text: "hmm… ok".into() });
let again = AgentEntry::Thought { text: "hmm… ok".into(), started_ms: None };
let again = entry_event("t", &mut streamed, None, 4, &again);
assert!(matches!(again, AgentEvent::Entry { .. }), "an entry replaced by another kind forgets its text");
let long = "é".repeat(5000);
+41 -4
View File
@@ -85,6 +85,8 @@ impl Timeline {
locations: locations(update.get("locations")),
output: None,
diffs: Vec::new(),
started_ms: Some(crate::now_ms()),
ended_ms: None,
};
let index = match self.tools.get(&id) {
Some(&i) => {
@@ -134,17 +136,22 @@ impl Timeline {
fn append_text(&mut self, thought: bool, text: &str) -> usize {
match self.entries.last_mut() {
Some(AgentEntry::Agent { text: t }) if !thought => t.push_str(text),
Some(AgentEntry::Thought { text: t }) if thought => t.push_str(text),
Some(AgentEntry::Thought { text: t, .. }) if thought => t.push_str(text),
_ => {
let text = text.to_owned();
return self.push(if thought { AgentEntry::Thought { text } } else { AgentEntry::Agent { text } });
return self.push(if thought {
AgentEntry::Thought { text, started_ms: Some(crate::now_ms()) }
} else {
AgentEntry::Agent { text }
});
}
}
self.entries.len() - 1
}
fn merge_tool(&mut self, index: usize, update: &Value) {
let AgentEntry::Tool { title, kind, status, locations: locs, output, diffs, .. } = &mut self.entries[index]
let AgentEntry::Tool { title, kind, status, locations: locs, output, diffs, ended_ms, .. } =
&mut self.entries[index]
else {
return;
};
@@ -156,6 +163,9 @@ impl Timeline {
}
if let Some(s) = tool_status(update.get("status")) {
*status = s;
if matches!(s, AgentToolStatus::Completed | AgentToolStatus::Failed) && ended_ms.is_none() {
*ended_ms = Some(crate::now_ms());
}
}
if update.get("locations").is_some_and(Value::is_array) {
*locs = locations(update.get("locations"));
@@ -183,6 +193,11 @@ impl Timeline {
}
}
if !text.is_empty() {
// The command a call announced (`$ cmd`) stays above the result that replaces it.
let command = output.as_deref().and_then(|o| o.lines().next()).filter(|l| l.starts_with("$ "));
if let Some(command) = command.filter(|c| !text.starts_with(c)) {
text = format!("{command}\n{text}");
}
*output = Some(tail(text));
}
if !new_diffs.is_empty() {
@@ -432,11 +447,14 @@ mod tests {
assert_eq!(t.apply(&chunk("lo")).changed, vec![0]);
t.apply(&json!({"sessionUpdate": "agent_thought_chunk", "content": {"type": "text", "text": "hmm"}}));
t.apply(&chunk("again"));
// The thought's start is the clock's: it is there, and the rest compares exactly.
let AgentEntry::Thought { started_ms, .. } = &mut t.entries[1] else { panic!("{:?}", t.entries) };
assert!(started_ms.take().is_some());
assert_eq!(
t.entries,
vec![
AgentEntry::Agent { text: "Hello".into() },
AgentEntry::Thought { text: "hmm".into() },
AgentEntry::Thought { text: "hmm".into(), started_ms: None },
AgentEntry::Agent { text: "again".into() },
]
);
@@ -528,6 +546,25 @@ mod tests {
assert!(matches!(t.entries[2], AgentEntry::User { done_ms: None, .. }));
}
#[test]
fn a_hermes_terminal_call_keeps_its_command_and_times() {
let text = |t: &str| serde_json::json!([{"type": "content", "content": {"type": "text", "text": t}}]);
let mut t = Timeline::default();
t.apply(&serde_json::json!({"sessionUpdate": "tool_call", "toolCallId": "tc-0b98b5e30a28",
"kind": "execute", "title": "terminal: echo ok + 2 commands", "locations": [],
"content": text("$ echo ok >> notes.txt && wc -l notes.txt")}));
let AgentEntry::Tool { started_ms, ended_ms, .. } = &t.entries[0] else { panic!() };
assert!(started_ms.is_some() && ended_ms.is_none());
t.apply(&serde_json::json!({"sessionUpdate": "tool_call_update", "toolCallId": "tc-0b98b5e30a28",
"kind": "execute", "status": "completed",
"content": text("terminal result\n- **output:** 3 notes.txt\n- **exit_code:** 0")}));
let AgentEntry::Tool { output, status, ended_ms, .. } = &t.entries[0] else { panic!() };
assert_eq!(*status, AgentToolStatus::Completed);
assert!(ended_ms.is_some());
let expected = "$ echo ok >> notes.txt && wc -l notes.txt\nterminal result\n- **output:** 3 notes.txt\n";
assert_eq!(output.as_deref(), Some(format!("{expected}- **exit_code:** 0").as_str()));
}
#[test]
fn long_output_keeps_its_tail() {
let s = tail("é".repeat(MAX_OUTPUT));
+3 -4
View File
@@ -236,10 +236,9 @@ fn classpath(
}
args.extend(["dependency:build-classpath", output_arg.as_str(), scope_arg.as_str(), "-q"]);
let top_dir = subdir(root, &target.top.dir);
let status = ProcCommand::new(&target.top.command)
.args(&args)
.envs(&target.top.env)
.current_dir(&top_dir)
let mut command = ProcCommand::new(&target.top.command);
command.args(&args).envs(&target.top.env).current_dir(&top_dir);
let status = ide_core::process::prepare(&mut command)
.output()
.map_err(|e| IdeError::internal(format!("cannot resolve the compile classpath: {e}")))?;
if !status.status.success() {
+2
View File
@@ -89,6 +89,8 @@ pub enum IdeEvent {
DocDirty {
doc: DocId,
dirty: bool,
/// Text version when this transition occurred, including when it was saved.
version: u32,
},
/// A complete workspace edit can be undone as one operation.
WorkspaceEditApplied {
+11
View File
@@ -33,6 +33,16 @@ pub fn agent_providers(host: &Host, window: &str) -> IdeResult<Vec<AgentProvider
Ok(providers)
}
/// Hermes Agent profiles on this machine (`default` first); empty without Hermes.
#[command(trust = trusted)]
pub async fn agent_hermes_profiles(host: &Host, window: &str) -> IdeResult<Vec<ide_agent::hermes::HermesProfile>> {
host.require_trust(window)?;
let root = ide_agent::hermes::root(dirs::home_dir().as_deref());
tokio::task::spawn_blocking(move || root.map(|r| ide_agent::hermes::labeled_profiles(&r)).unwrap_or_default())
.await
.map_err(join_err)
}
/// Refreshes the model catalog; force bypasses freshness, not the cooldown.
#[command(trust = trusted)]
pub fn agent_refresh_models(
@@ -1075,6 +1085,7 @@ ide_command::domain!(
agent_external_sessions,
agent_fork,
agent_grouped_changes,
agent_hermes_profiles,
agent_import_session,
agent_mcp_discover_sources,
agent_mcp_import,
+28 -6
View File
@@ -406,15 +406,16 @@ impl Proc {
}
}
/// What it printed since the last call, each stream at most `max` bytes.
/// What it printed since the last call, each stream at most `max` bytes. The status
/// comes with the last chunk only: once it ended, its pipes reached the end and
/// nothing is left to read, so a caller can stop at the first chunk that has one.
fn chunk(&self, max: usize) -> ProcessChunk {
let mut state = self.state.lock();
let eof = state.readers == 0;
ProcessChunk {
stdout: take_text(&mut state.stdout, max, eof),
stderr: take_text(&mut state.stderr, max, eof),
status: state.status,
}
let stdout = take_text(&mut state.stdout, max, eof);
let stderr = take_text(&mut state.stderr, max, eof);
let drained = eof && state.stdout.is_empty() && state.stderr.is_empty();
ProcessChunk { stdout, stderr, status: state.status.filter(|_| drained) }
}
}
@@ -4126,6 +4127,27 @@ mod tests {
api.release_process(id);
}
#[cfg(unix)]
#[test]
fn the_status_comes_with_the_last_of_the_output() {
let tmp = tempfile::tempdir().unwrap();
let api = shell_api(tmp.path());
let token = CancellationToken::new();
let id = api.start_process(shell("printf 'abcdefghij'; printf 'xyz' >&2"), None, None).unwrap();
let first = api.wait_process(id, 4, Duration::from_secs(5), &token).unwrap();
assert_eq!((first.stdout.as_str(), first.stderr.as_str(), first.status), ("abcd", "xyz", None));
let mut stdout = first.stdout;
let status = loop {
let chunk = api.poll_process(id, 4).unwrap();
stdout.push_str(&chunk.stdout);
if let Some(status) = chunk.status {
break status;
}
};
assert_eq!((stdout.as_str(), status), ("abcdefghij", 0));
api.release_process(id);
}
#[test]
fn programs_run_only_as_approved() {
let tmp = tempfile::tempdir().unwrap();
+16 -1
View File
@@ -65,8 +65,23 @@ pub fn build_with_redirect(proxy: &ProxySettings, redirect: reqwest::redirect::P
/// The client for the current proxy settings, rebuilt when they change.
pub fn shared() -> IdeResult<reqwest::Client> {
static CLIENT: Mutex<Option<(Arc<ProxySettings>, reqwest::Client)>> = Mutex::new(None);
cached_client(&CLIENT, build)
}
/// The client the HTTP Client executes requests with: redirects off, `exec`
/// follows them by hand — that is what lets a `POST` stay a `POST` on a
/// 301/302 and puts the redirect chain into the response.
pub fn shared_without_redirects() -> IdeResult<reqwest::Client> {
static CLIENT: Mutex<Option<(Arc<ProxySettings>, reqwest::Client)>> = Mutex::new(None);
cached_client(&CLIENT, |proxy| build_with_redirect(proxy, reqwest::redirect::Policy::none()))
}
fn cached_client(
slot: &Mutex<Option<(Arc<ProxySettings>, reqwest::Client)>>,
build: fn(&ProxySettings) -> IdeResult<reqwest::Client>,
) -> IdeResult<reqwest::Client> {
let proxy = ide_core::proxy_settings::proxy();
let mut cached = CLIENT.lock();
let mut cached = slot.lock();
if let Some((settings, client)) = cached.as_ref()
&& **settings == *proxy
{
+288 -15
View File
@@ -13,6 +13,19 @@ use std::time::Instant;
/// Bodies above this are cut (the full size is still reported).
pub const MAX_BODY: usize = 16 * 1024 * 1024;
/// Redirects followed per request; beyond this the redirect response itself is
/// returned (IntelliJ's HTTP Client follows the same number).
pub const MAX_REDIRECTS: usize = 50;
/// Responses whose `Location` is followed: 301, 302, 303, 307 and 308, the set
/// IntelliJ's HTTP Client redirects on.
const REDIRECT_STATUSES: [u16; 5] = [301, 302, 303, 307, 308];
/// Request headers not re-sent to a redirect on another host. IntelliJ's HTTP
/// Client strips the same set and restores it when the redirect stays on the
/// original host.
const SENSITIVE_HEADERS: [&str; 5] = ["authorization", "cookie", "cookie2", "www-authenticate", "proxy-authorization"];
/// A request ready to send: variables substituted, includes read.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -24,6 +37,15 @@ pub struct PreparedRequest {
pub body: Option<String>,
}
/// One followed redirect: the response and the `Location` it pointed to.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct RedirectHop {
pub status: u16,
pub status_text: String,
pub location: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct HttpResponse {
@@ -32,6 +54,9 @@ pub struct HttpResponse {
pub version: String,
pub headers: Vec<(String, String)>,
pub content_type: Option<String>,
/// Followed redirects, first hop first; empty when not redirected.
#[serde(default)]
pub redirects: Vec<RedirectHop>,
/// Body as text (lossy UTF-8); `None` for binary bodies.
pub body: Option<String>,
/// Size in bytes as received (after decompression).
@@ -128,25 +153,84 @@ fn looks_textual(content_type: Option<&str>, bytes: &[u8]) -> bool {
}
}
/// Sends `req`; cancelled when `cancel` fires.
/// The request for one hop: `req`'s headers and body against `url`, the
/// sensitive headers dropped when the redirect crosses to another host.
fn request_to(
client: &reqwest::Client,
method: &reqwest::Method,
req: &PreparedRequest,
body: Option<&str>,
original: &reqwest::Url,
url: &reqwest::Url,
) -> IdeResult<reqwest::Request> {
let same_host = url.host_str() == original.host_str();
let mut builder = client.request(method.clone(), url.clone());
for (k, v) in &req.headers {
if same_host || !SENSITIVE_HEADERS.iter().any(|s| k.eq_ignore_ascii_case(s)) {
builder = builder.header(k, v);
}
}
if let Some(body) = body {
builder = builder.body(body.to_owned());
}
builder.build().map_err(|e| IdeError::invalid(format!("invalid request: {e}")))
}
/// Sends `request`; cancelled when `cancel` fires.
async fn send(
client: &reqwest::Client,
request: reqwest::Request,
cancel: &CancellationToken,
) -> IdeResult<reqwest::Response> {
let send = client.execute(request);
tokio::select! {
r = send => r.map_err(|e| IdeError::new(ide_core::error::ErrorKind::Io, describe(&e))),
() = cancel.cancelled() => Err(IdeError::cancelled()),
}
}
/// Sends `req`, following redirects the way IntelliJ's HTTP Client does:
/// 301, 302, 303, 307 and 308 up to [`MAX_REDIRECTS`] times, `303` continuing
/// as `GET` without the body, the other statuses keeping the method and body —
/// so a `POST` redirected to `https` on the same host is re-sent as a `POST`.
/// Sensitive headers (Authorization, cookies, proxy credentials) are not
/// re-sent across hosts. The followed hops are reported in the response.
/// Cancelled when `cancel` fires.
pub async fn execute(req: &PreparedRequest, cancel: &CancellationToken) -> IdeResult<HttpResponse> {
let client = crate::client::shared()?;
let client = crate::client::shared_without_redirects()?;
let method = reqwest::Method::from_bytes(req.method.as_bytes())
.map_err(|_| IdeError::invalid(format!("invalid method {}", req.method)))?;
let mut builder = client.request(method, &req.url);
for (k, v) in &req.headers {
builder = builder.header(k, v);
}
if let Some(body) = &req.body {
builder = builder.body(body.clone());
}
let request = builder.build().map_err(|e| IdeError::invalid(format!("invalid request: {e}")))?;
let original = req.url.parse::<reqwest::Url>().map_err(|e| IdeError::invalid(format!("invalid request: {e}")))?;
let mut url = original.clone();
let mut method = method;
let mut body = req.body.clone();
let mut redirects = Vec::new();
let started = Instant::now();
let send = client.execute(request);
let mut response = tokio::select! {
r = send => r.map_err(|e| IdeError::new(ide_core::error::ErrorKind::Io, describe(&e)))?,
() = cancel.cancelled() => return Err(IdeError::cancelled()),
};
let mut response;
loop {
let request = request_to(&client, &method, req, body.as_deref(), &original, &url)?;
response = send(&client, request, cancel).await?;
let status = response.status();
if redirects.len() >= MAX_REDIRECTS || !REDIRECT_STATUSES.contains(&status.as_u16()) {
break;
}
let next = response
.headers()
.get(reqwest::header::LOCATION)
.and_then(|v| v.to_str().ok())
.and_then(|location| url.join(location).ok());
let Some(next) = next else { break };
redirects.push(RedirectHop {
status: status.as_u16(),
status_text: status.canonical_reason().unwrap_or("").to_owned(),
location: next.to_string(),
});
if status == reqwest::StatusCode::SEE_OTHER {
method = reqwest::Method::GET;
body = None;
}
url = next;
}
let ttfb = started.elapsed();
let status = response.status();
let version = format!("{:?}", response.version());
@@ -179,6 +263,7 @@ pub async fn execute(req: &PreparedRequest, cancel: &CancellationToken) -> IdeRe
version,
headers,
content_type,
redirects,
body,
size: size as f64,
truncated: size > bytes.len(),
@@ -249,6 +334,47 @@ mod tests {
assert_eq!(url("GET https://api.test/cb?u=http://x\n"), "https://api.test/cb?u=http://x");
}
/// A loopback server answering each accepted connection with the next of
/// `responses`, returning every request as its head and body.
async fn scripted(responses: Vec<String>) -> (u16, tokio::task::JoinHandle<Vec<(String, String)>>) {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let handle = tokio::spawn(async move {
let mut seen = Vec::new();
for response in responses {
let (mut socket, _) = listener.accept().await.unwrap();
let mut request = Vec::new();
let (head, body) = loop {
let mut buffer = [0u8; 4096];
let read = socket.read(&mut buffer).await.unwrap();
assert!(read > 0, "request ended before its body");
request.extend_from_slice(&buffer[..read]);
let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") else { continue };
let head = String::from_utf8_lossy(&request[..end]).into_owned();
let length: usize = head
.lines()
.find_map(|line| {
let (name, value) = line.split_once(':')?;
name.eq_ignore_ascii_case("content-length").then(|| value.trim().parse().unwrap())
})
.unwrap_or(0);
if request.len() >= end + 4 + length {
break (head, String::from_utf8_lossy(&request[end + 4..end + 4 + length]).into_owned());
}
};
seen.push((head, body));
socket.write_all(response.as_bytes()).await.unwrap();
}
seen
});
(port, handle)
}
fn response(status_line: &str, headers: &str, body: &str) -> String {
format!("HTTP/1.1 {status_line}\r\n{headers}Content-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len())
}
#[tokio::test]
async fn sends_exact_environment_numbers_to_a_local_server() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
@@ -341,6 +467,7 @@ mod tests {
assert_eq!(r.status_text, "Created");
assert_eq!(r.body.as_deref(), Some("{\"ok\":true}"));
assert!(r.headers.iter().any(|(k, v)| k == "x-a" && v == "b"));
assert!(r.redirects.is_empty());
assert!(r.total_ms >= r.ttfb_ms);
}
@@ -369,4 +496,150 @@ mod tests {
let err = execute(&req, &cancel).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
}
#[tokio::test]
async fn post_keeps_method_and_body_on_301_302_307_308() {
for status_line in ["301 Moved Permanently", "302 Found", "307 Temporary Redirect", "308 Permanent Redirect"] {
let status: u16 = status_line[..3].parse().unwrap();
let (port, server) =
scripted(vec![response(status_line, "Location: /landing\r\n", ""), response("200 OK", "", "ok")]).await;
let req = PreparedRequest {
name: None,
method: "POST".into(),
url: format!("http://127.0.0.1:{port}/submit"),
headers: vec![("Content-Type".into(), "application/json".into())],
body: Some("{\"a\":1}".into()),
};
let r = execute(&req, &CancellationToken::new()).await.unwrap();
let seen = server.await.unwrap();
let (head, body) = &seen[1];
assert_eq!(head.lines().next().unwrap(), "POST /landing HTTP/1.1", "{status_line}");
assert!(head.to_ascii_lowercase().contains("content-type: application/json"), "{head}");
assert_eq!(body, "{\"a\":1}", "{status_line}");
assert_eq!(r.status, 200, "{status_line}");
assert_eq!(r.body.as_deref(), Some("ok"), "{status_line}");
assert_eq!(
r.redirects,
vec![RedirectHop {
status,
status_text: status_line[4..].to_owned(),
location: format!("http://127.0.0.1:{port}/landing"),
}],
"{status_line}"
);
}
}
#[tokio::test]
async fn see_other_303_resends_as_get_without_the_body() {
let (port, server) =
scripted(vec![response("303 See Other", "Location: /after\r\n", ""), response("200 OK", "", "done")]).await;
let req = PreparedRequest {
name: None,
method: "POST".into(),
url: format!("http://127.0.0.1:{port}/submit"),
headers: vec![],
body: Some("{\"a\":1}".into()),
};
let r = execute(&req, &CancellationToken::new()).await.unwrap();
let seen = server.await.unwrap();
assert_eq!(seen[1].0.lines().next().unwrap(), "GET /after HTTP/1.1");
assert_eq!(seen[1].1, "");
assert_eq!(r.status, 200);
assert_eq!(r.body.as_deref(), Some("done"));
assert_eq!(r.redirects[0].status, 303);
}
#[tokio::test]
async fn same_host_redirect_keeps_authorization() {
let (port, server) = scripted(vec![
response("301 Moved Permanently", "Location: /landing\r\n", ""),
response("200 OK", "", "ok"),
])
.await;
let req = PreparedRequest {
name: None,
method: "GET".into(),
url: format!("http://127.0.0.1:{port}/start"),
headers: vec![("Authorization".into(), "Bearer secret".into())],
body: None,
};
execute(&req, &CancellationToken::new()).await.unwrap();
let seen = server.await.unwrap();
assert!(seen[1].0.to_ascii_lowercase().contains("authorization: bearer secret"), "{}", seen[1].0);
}
#[tokio::test]
async fn cross_host_redirect_keeps_the_method_but_drops_authorization() {
let (port_b, server_b) = scripted(vec![response("200 OK", "", "moved")]).await;
let (port_a, server_a) = scripted(vec![response(
"301 Moved Permanently",
&format!("Location: http://127.0.0.1:{port_b}/x\r\n"),
"",
)])
.await;
let req = PreparedRequest {
name: None,
method: "POST".into(),
url: format!("http://localhost:{port_a}/start"),
headers: vec![("Authorization".into(), "Bearer secret".into())],
body: Some("{\"a\":1}".into()),
};
let r = execute(&req, &CancellationToken::new()).await.unwrap();
let seen_a = server_a.await.unwrap();
let seen_b = server_b.await.unwrap();
assert!(seen_a[0].0.to_ascii_lowercase().contains("authorization: bearer secret"), "{}", seen_a[0].0);
assert_eq!(seen_b[0].0.lines().next().unwrap(), "POST /x HTTP/1.1");
assert!(!seen_b[0].0.to_ascii_lowercase().contains("authorization"), "{}", seen_b[0].0);
assert_eq!(seen_b[0].1, "{\"a\":1}");
assert_eq!(r.status, 200);
assert_eq!(r.body.as_deref(), Some("moved"));
assert_eq!(r.redirects.len(), 1);
}
#[tokio::test]
async fn redirects_beyond_the_limit_return_the_last_redirect_response() {
let responses = vec![response("301 Moved Permanently", "Location: /loop\r\n", ""); MAX_REDIRECTS + 1];
let (port, server) = scripted(responses).await;
let req = PreparedRequest {
name: None,
method: "GET".into(),
url: format!("http://127.0.0.1:{port}/start"),
headers: vec![],
body: None,
};
let r = execute(&req, &CancellationToken::new()).await.unwrap();
let seen = server.await.unwrap();
assert_eq!(r.status, 301);
assert_eq!(r.status_text, "Moved Permanently");
assert_eq!(r.redirects.len(), MAX_REDIRECTS);
assert_eq!(seen.len(), MAX_REDIRECTS + 1);
}
#[tokio::test]
async fn redirect_chain_is_recorded_across_hops() {
let (port, server) = scripted(vec![
response("302 Found", "Location: /b\r\n", ""),
response("302 Found", "Location: /c\r\n", ""),
response("200 OK", "", "end"),
])
.await;
let req = PreparedRequest {
name: None,
method: "GET".into(),
url: format!("http://127.0.0.1:{port}/a"),
headers: vec![],
body: None,
};
let r = execute(&req, &CancellationToken::new()).await.unwrap();
let seen = server.await.unwrap();
assert_eq!(r.status, 200);
assert_eq!(r.body.as_deref(), Some("end"));
assert_eq!(r.redirects.len(), 2);
assert_eq!(r.redirects[0].status, 302);
assert_eq!(r.redirects[0].location, format!("http://127.0.0.1:{port}/b"));
assert_eq!(r.redirects[1].status, 302);
assert_eq!(r.redirects[1].location, format!("http://127.0.0.1:{port}/c"));
assert_eq!(seen[2].0.lines().next().unwrap(), "GET /c HTTP/1.1");
}
}
@@ -1 +1 @@
9ec6fcb9763867a747206b0efaf8bbeac7934a4ec0d1915623557839cf2dba5e
b59392bcc1999048f0ab922ec659bc21d9e825c696fa41d9f0a40c85627a5b2c
@@ -1 +1 @@
2015380825fc406a6466f90658443f824ef06311894b82acae2ecc1446ff0813
034b99891313c03eb2a6b8c3cb2e4784129e1936965be803512f1d869b1768c2
@@ -1 +1 @@
7388e5ef7a5bff42f41ed613bfb75a8da835f93a63f8fb26358bb50b77b44c00
29ec0a96e2a0f6965915c7c25e35036743fc27a49037df588c217e8abfff93e3
@@ -1 +1 @@
aded25a93667f14a683b0bbb7547b35eed23e4971fdf2761496b09fd898b5034
87b367cfdd65c360920eff7be4d6a8d6b939721f6398aa6a01e39a289590699e
@@ -1 +1 @@
178bba6e74a51c0911502524f253cf7148854c46883c3f7f96d2c968e70522f5
7d034ee1a4b99615642d5bf033802f8e4662216d45b209c4c7a24eb8f1338f48
@@ -1 +1 @@
786e1abf853d615bf0eab7315280b3884e4c2ff6362c23a41a917d6af4c050e9
3fdf985273ec14ae623fa84602a9220cfbfb2e0e587ab192fc2bcb8d990ce9e3
@@ -1 +1 @@
77a825aa6adc3aa39ee390204e1fd35a12425d0a38552f116c74497dac446046
8434e9271e27a6778bb3d5922e8925f3fd9f1d35377e5dddf5b5eb5416bd09bb
@@ -1 +1 @@
352246ecdba1e3d43127c7b808a3b1cdf48cf0b4ae7d85d532ffaae734158e15
9fa7468ce385ff33c1f3b99c84711e0d11a84b10e8e4f95b358fcd2ccc96e255
@@ -1 +1 @@
da9abe9bd086f7808cc1520a592f47c843f26ecc0a5291110915467f57816dc4
5220a5bfb6ec0467a72e63e21d690e70b7d46b4f2eaff4116a8a79220a5eca8f
@@ -1 +1 @@
322b82aa432e072f8ae1d4345d321d227dbcb9376bd113c166b816254e7ddf13
a962127d1c6e37e85b81973a272a5d6b383cc2884b41bb2d82e8640ef5f8f943
@@ -1 +1 @@
e1ff50682e4aa18ca6bb96547cdd7b2815ad700e6ecaa3aede6d9f20205d4cdb
92ad3e43e7f343004dcf26a51e282e97ed694cc9bd7325ff75aa5b18f1a2eeb6
@@ -1 +1 @@
d3757cea9bcc8e33521c50c66b396d8ece2a90d830c2e57e651ebeb018536c62
2200ed0d44dbafb70ad864cb9569b0b2c37cf9eec1582b05efa903a9e8ec89ee
@@ -1 +1 @@
409e7017849fc68bd3241bfa5357366259e1eb634fb71ef69d4b857bec0aa821
644612ee4228010f141042ea0eab5431b8386370f863a70b63cd3315f69d963a
@@ -1 +1 @@
0b217ad8f0c8f802c1d670422d9621d07553985b9852f3efb724b17688cfa3b9
2af5d46516bfc1d38ad1f24d6cf3c57e2d6db6b0d3225748f55c4f13110430fb
@@ -1 +1 @@
8cc7d2ce4e21838f8f1b0f5bd56aea61257fe288f6b7189343ccf849a78de665
0ee0773cefd61b8144d0550718e1988a1e60438bee826c3867350e28886a56f7
@@ -1 +1 @@
19b8af5e283a0a6ae866538096d2fa95e51020a9fd423768224c2ae4cfcefa27
941cb9008aaab11464b193c37b91e2476d771ec526247713f291c6642caf5995
@@ -1 +1 @@
ccaa7d24825c05409dbcfe1491276b229ee6d712f2ba18556413a87d851c475c
06d70aae3152c88d1299a9b33f151b0baa4a77c3ca7145215c6f6e0aa40727b2
@@ -1 +1 @@
b0ae383f86a8059e0bc723ca1cd21dfa76a0faa68975a1b827b44ebe1ffad2f1
86eb87758e4f7c0242a18f12a113c31d418da64d7198041120f19401a5707bfb
@@ -1 +1 @@
38eadb34cc096538f2b529beb07d10860323356c554dd8171ccc7ca25ebfec8e
4442bb686fa18e8e8a52fd1cd8683b8767ec7908ffc1454dff476d9cb1711be9
@@ -1 +1 @@
1c5c9a19b4dc05219b3c144b21cad6e05a98fe5c01da7c67383cc39223b6e4d8
dd51f1b8634ff6305ba1a69c8457bd586996200a2b18e4a08d0cfa2fb60abaf6
@@ -1 +1 @@
d76fe0c659ef337ae7bb9c75ecfa5a9bcdff2eb92d487ca0df2aefa77bd21daf
4319f2655ee1e240b33f4b96c23fff59c61aa62d6ccc628715e5ff9fe38c2717
@@ -1 +1 @@
f671d361a8de5eead5c4ed801bfeacafb7b0aa82abefddbe2436c4d679a56d37
50c4fd7e08a4187afae0e00c775a61578b82bbad056807ad063ee47e79e2cef1
@@ -1 +1 @@
5cbb5a91f8676fbc0178535f58213eca341c52e210264ffe3da9eb2a47ef02af
220666302d814e6d8bde346954205c94c82320d5584d46f01672fd7d32400bf3
@@ -1 +1 @@
79d5d589c64b66fab58f6fc2cd2a10e91ad23e0dc34b356f6d6d51d7fdcca8b0
4ee484afaa1a1f71a9e544582d90db3260307fc89b8f514aaaff883df2761ba6
@@ -1 +1 @@
4eb1b77f62effb313bf67c1dfe34b8e0718bf5afaf84c8252d664b9a9888d040
3fba59ce802d88a2a1c026480a2cb8ce4d9539eb7b88f5a18bf6232f7adef147
@@ -1 +1 @@
a36c3f0d92237f226d47325dc4e33312f9179e0e05673154fc07d61f6e68f86e
73433da25d5304d0a3cb83d750d02feb5e270ee7e9f680c4ee9d923afa9aa066
@@ -1 +1 @@
2b48734dcf4a8cdf0db0ec80628754a836a0efb2f11dac9fd0fcf80572a23dfe
12df43f99eac93f4e1a070635780ad653932cf69a14595175d8ba6d4f0a4445c
@@ -1 +1 @@
fc1cb738668cee77a4d2a7b48d5543a29d568a8d2231921f5257de6a835be307
427b63c11188689262101cde971af0a92e54bd6c88a4e3cc8fdfa1a7c8c95fce
@@ -1 +1 @@
f609a501e4e752055d9c8f0ff20d1397b0085587f1435af2928e47fe8507f6ca
07ae58fe39746b779b1e466d7bbbb666ba550f427c7bf8de97d7ede647c00bc0
@@ -1 +1 @@
dcacc16856c9b9f11245e4b8c686b1ef6532a0f4090cdf531dafb76f0663a00a
f9912644c28512e37299834123cd4c94f6ed11f29bd38ddbc1c92df168447494
@@ -1 +1 @@
ca252d45f83c5e5b9378d6acec40319db2d6acc636d13bf7e79a5339869f7f09
ea0eec8c07d6469d3ab63c3bb08c85b01208be1757edffe5eabcb7be79ccf537
@@ -1 +1 @@
f54f4b5ac28e44b8d288104a6290557743e68d2b50af4583dc51a01aca7e7777
1ce55fabaa5ea1ddf770c8a1ad7f7b60a843c82c453d42289088c4b2fec61d84
@@ -1 +1 @@
cc98a2e2e74b14a84d3272b41211679a15d06abd4dd664bd87da5ece439e0c00
3356b4ec918c668c4c249f84afb9bafcd06c073ba86235b6ceea7ef6220cdaf5
+1 -1
View File
@@ -230,7 +230,7 @@ pub async fn target_path(root: &Path, config: &RunConfig) -> IdeResult<String> {
}
let mut command = std::process::Command::new(&config.command);
command.args(args).current_dir(root);
ide_core::process::host_env(&mut command);
ide_core::process::prepare(&mut command);
if !config.extras.include_system_env {
command.env_clear();
} else {
+5
View File
@@ -124,6 +124,11 @@ fn package_info(mut command: Command, dir: &Path, flags: &[String]) -> IdeResult
}
}
command.arg(".").current_dir(dir).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(ide_core::process::CREATE_NO_WINDOW);
}
let mut child = command.spawn()?;
let stdout = child.stdout.take();
let stderr = child.stderr.take();
+1 -1
View File
@@ -672,7 +672,7 @@ impl Documents {
fn set_dirty(&self, doc: DocId, st: &mut DocState, dirty: bool) {
if st.dirty != dirty {
st.dirty = dirty;
self.sink.emit(IdeEvent::DocDirty { doc, dirty });
self.sink.emit(IdeEvent::DocDirty { doc, dirty, version: st.doc.version() });
}
}
+113
View File
@@ -228,6 +228,109 @@ fn dirty_events(events: &[IdeEvent]) -> Vec<bool> {
events.iter().filter_map(|e| if let IdeEvent::DocDirty { dirty, .. } = e { Some(*dirty) } else { None }).collect()
}
fn assert_failed_save_preserves_edit(f: &Fixture, doc: DocId, text: &str, before: usize) {
let snapshot = f.docs.snapshot(doc).unwrap();
assert!(snapshot.dirty, "failed save marked the document clean");
assert_eq!(snapshot.text, text, "failed save changed the unsaved buffer");
assert!(!dirty_events(&f.events.lock()[before..]).contains(&false), "failed save emitted a clean-state event");
}
#[test]
fn unencodable_save_preserves_the_dirty_buffer_and_disk_bytes() {
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, b"caf\xe9").unwrap();
let doc = f.docs.open(&path).unwrap().id;
assert_eq!(f.docs.set_encoding(doc, "windows-1252", true).unwrap().encoding, "windows-1252");
let reloaded = f.docs.snapshot(doc).unwrap();
assert_eq!(reloaded.text, "café");
f.docs.edit(doc, reloaded.version, change(4, 4, "漢")).unwrap();
let original = fs::read(&path).unwrap();
let before = f.events.lock().len();
let err = f.docs.save(doc).expect_err("Windows-1252 cannot encode the edit");
assert_eq!(err.kind, ErrorKind::InvalidInput, "{err}");
assert_failed_save_preserves_edit(&f, doc, "café漢", before);
assert_eq!(fs::read(&path).unwrap(), original, "failed encoding changed disk bytes");
}
#[cfg(unix)]
#[test]
fn permission_denied_save_preserves_the_edit_and_can_be_retried() {
use std::os::unix::fs::PermissionsExt;
struct RestorePermissions<'a>(&'a Path, fs::Permissions);
impl Drop for RestorePermissions<'_> {
fn drop(&mut self) {
let result = fs::set_permissions(self.0, self.1.clone());
if !std::thread::panicking() {
result.expect("restore fixture permissions");
}
}
}
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, b"original").unwrap();
let doc = f.docs.open(&path).unwrap().id;
f.docs.edit(doc, 0, change(0, 8, "edited")).unwrap();
{
let _dir_permissions = RestorePermissions(&f.root, fs::metadata(&f.root).unwrap().permissions());
let _file_permissions = RestorePermissions(&path, fs::metadata(&path).unwrap().permissions());
// Deny both sibling temp-file creation and the fallback write to the existing file.
fs::set_permissions(&path, fs::Permissions::from_mode(0o444)).unwrap();
fs::set_permissions(&f.root, fs::Permissions::from_mode(0o555)).unwrap();
let sibling = fs::OpenOptions::new().write(true).create_new(true).open(f.root.join("probe"));
let in_place = fs::OpenOptions::new().write(true).open(&path);
for (probe, access) in [(sibling, "create a sibling file"), (in_place, "open the target for writing")] {
match probe {
Ok(_) => {
eprintln!("skipping permission-denied save: test process can {access} despite permission bits");
return;
}
Err(err) => assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied, "{access}: {err}"),
}
}
let before = f.events.lock().len();
let err = f.docs.save(doc).expect_err("neither atomic nor in-place save should be writable");
assert_eq!(err.kind, ErrorKind::PermissionDenied, "{err}");
assert_failed_save_preserves_edit(&f, doc, "edited", before);
assert_eq!(fs::read(&path).unwrap(), b"original", "failed write changed disk bytes");
}
let before = f.events.lock().len();
f.docs.save(doc).expect("retry after restoring file and directory permissions");
assert_eq!(fs::read(&path).unwrap(), b"edited");
assert!(!f.docs.snapshot(doc).unwrap().dirty, "successful retry left the document dirty");
assert_eq!(dirty_events(&f.events.lock()[before..]), vec![false]);
}
#[test]
fn save_to_a_path_replaced_by_a_directory_preserves_the_dirty_buffer() {
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, b"original").unwrap();
let doc = f.docs.open(&path).unwrap().id;
f.docs.edit(doc, 0, change(0, 8, "edited")).unwrap();
assert!(f.docs.snapshot(doc).unwrap().dirty);
fs::remove_file(&path).unwrap();
fs::create_dir(&path).unwrap();
let before = f.events.lock().len();
f.docs.save(doc).expect_err("save must not replace a directory with a file");
assert_failed_save_preserves_edit(&f, doc, "edited", before);
assert!(fs::symlink_metadata(&path).unwrap().is_dir(), "save removed the replacement directory");
assert_eq!(fs::read_dir(&path).unwrap().count(), 0, "save left artifacts inside the replacement directory");
assert_eq!(fs::read_dir(&f.root).unwrap().count(), 1, "save left artifacts beside the replacement directory");
}
#[test]
fn autosave_leaves_a_file_changed_on_disk_after_an_edit() {
let f = fixture();
@@ -249,6 +352,16 @@ fn autosave_leaves_a_file_changed_on_disk_after_an_edit() {
f.docs.edit(info.id, 1, change(0, 0, "x")).unwrap();
assert!(f.docs.autosave(info.id).unwrap());
assert_eq!(fs::read_to_string(&path).unwrap(), "xedited\nbeta\n");
let transitions: Vec<_> = f
.events
.lock()
.iter()
.filter_map(|event| match event {
IdeEvent::DocDirty { doc, dirty, version } if *doc == info.id => Some((*version, *dirty)),
_ => None,
})
.collect();
assert_eq!(transitions, [(1, true), (1, false), (2, true), (2, false)]);
}
#[test]
+1
View File
@@ -27,6 +27,7 @@ These agents are built in. Install the agent's own CLI and sign in once in a ter
| Auggie | `auggie --acp` | `auggie login` |
| Kiro | `kiro-cli acp` | `kiro-cli login` |
| Mistral Vibe | `vibe-acp` | `vibe` |
| Hermes Agent | `hermes acp` | `hermes model` |
**Claude Code** and **Codex** are driven through their own protocols (Claude Code's stream-json mode and `codex app-server`). Their ACP adapters (`claude-acp`, `codex-acp`) are no longer listed; tasks that already use them keep working, and an [agent file](#add-a-custom-agent) for either id lists it again. If an agent needs you to sign in, the task tells you which command to run.
+2
View File
@@ -136,6 +136,8 @@ With tabs placed left or right, the tab column is as wide as its longest name, u
As in IntelliJ IDEA, there is no per-file save: files are saved when you switch to another application or to the built-in terminal, and **File › Save All** (`⌘S` / `Ctrl+S`) saves everything at once. **Settings › Appearance & Behavior › System Settings**, section **Autosave**, can also save after the IDE has been idle for a while.
If you keep typing during a save, edits not included in that write stay marked as unsaved.
Changes made outside the IDE are picked up when you switch back to its window. **Reload from Disk** (`⌥⌘Y` / `Ctrl+Alt+Y`) reloads the current file now.
## Related
+4 -2
View File
@@ -111,7 +111,7 @@ The toolbar has **Stop Request**, **Reload History** and **Clear History**. The
- HTTP/1.1 and HTTP/2. gzip, deflate and brotli responses are decoded.
- TLS certificates are verified against the system trust store.
- Redirects are followed.
- Redirects are followed (up to 50): a 303 continues as GET without the body, other redirects keep the method and body, and the hops are shown in the response.
- Cookies are not kept between requests.
- Connections time out after 30 seconds; there is no overall request timeout.
- The proxy comes from **Settings › Appearance & Behavior › System Settings › HTTP Proxy**.
@@ -135,7 +135,9 @@ In Java and Kotlin `@FeignClient` interfaces, click the **Go to Feign Endpoint**
The built-in index matches HTTP methods and literal paths, including whole `{variable}` segments. A literal Feign `name` or `value` narrows candidates against an unambiguous `spring.application.name` in the destination module's `src/main/resources/application.properties`, `.yml` or `.yaml` (also under `resources/config`). Configuration is never inherited from a parent module or test sources. Conflicting profile names, dynamic or missing identities, and clients with explicit/dynamic `url` retain method/path candidates. No HTTP request is sent.
This is source navigation, not service-discovery or effective runtime configuration resolution. Custom source sets, composed/aliased annotations, inherited mappings, dynamic mapping paths, `@RequestLine`, Ant/regex path patterns and reverse controller-to-client navigation are outside this first version. Navigation reads bounded local configuration and rechecks current controller text, including unsaved editor changes.
To see which Feign interfaces declare a request to a Spring endpoint, open the endpoint’s gutter menu and choose **Find Feign Clients**. You can also invoke the action from the editor menu or Find Action with the caret in the controller method. A single service match opens directly. When several clients match, the chooser shows each interface method and its source path. Clients whose service cannot be established appear below known matches as **Possible match**, even when only one is found. A client known to target another service is excluded.
Navigation reads local source and module configuration, including unsaved editor changes. Custom source sets, composed or aliased annotations, inherited mappings, dynamic mapping paths, `@RequestLine`, Ant/regex path patterns, and runtime service discovery are outside its scope.
## Not supported
+2
View File
@@ -155,6 +155,8 @@ When a project loads and unloads:
**Open now** lists the loaded projects, each with what it is doing (answering a request, kept open by a run, or how long it has been idle and when it unloads) and an **Unload** button. Unloading does not wait for **Apply**. The project loads again on the next tool call that names it, if the setting still serves it.
While any project is loaded, the **Background Projects** item in the status bar (a layers icon and the count) opens the same list. Each row has the **Open in New Window** and **Unload** icon buttons, and below the list are **Unload All** and **MCP Server Settings…**.
What trust decides: a trusted project works as one open in a window, with its language servers and the tools that write. A listed folder you have not trusted opens in Restricted Mode and gets only the read-only tools.
A background project has no window, so some tools differ:
+1 -1
View File
@@ -26,7 +26,7 @@ The same page also has:
- **Different tool window background**: set tool windows apart from the editor.
- **Background Image**: an image shown through the project window, with its **Opacity**, **Fill** (scale, original size or tile) and **Anchor**.
- **Accessibility**: **Use contrast scrollbars** and **Adjust colors for red-green vision deficiency** (for protanopia and deuteranopia).
- **Compact mode** under **UI Options**.
- **Compact mode** under **UI Options**, also in **View › Appearance**. As in IntelliJ IDEA, it uses shorter tree and list rows, a smaller main toolbar, tool window stripes and status bar, 16px toolbar and stripe icons, and 1px smaller text in the toolbar, status bar, editor tabs and tool window headers.
## Editor color scheme
+4
View File
@@ -318,5 +318,9 @@ let out = host::run_command(&Command::new("forge").arg("build").env("FOUNDRY_PRO
- Calls are cancelled with the task or call and killed at timeout; run anything slow
inside `host::begin_task`. Dropping a `Child` kills it, and disabling or reclaiming the
plugin ends its children.
- A `Child`'s `poll` and `wait` return what it printed since the last read. `status` comes
with the chunk that holds the last of its output, so read until it is set. Output nobody
reads keeps only its last 1 MiB per stream: for the whole output of a command that ends,
use `run_command`.
- In **Settings › Plugins** the user can choose the executable of a `process:` grant
globally or per project; the plugin keeps calling its declared program name.
+1
View File
@@ -27,6 +27,7 @@ OpenIDEA 本身不带模型或账号:它启动你已安装并登录的 agent
| Auggie | `auggie --acp` | `auggie login` |
| Kiro | `kiro-cli acp` | `kiro-cli login` |
| Mistral Vibe | `vibe-acp` | `vibe` |
| Hermes Agent | `hermes acp` | `hermes model` |
**Claude Code** 和 **Codex** 通过它们自己的协议驱动(Claude Code 的 stream-json 模式和 `codex app-server`)。它们的 ACP 适配器(`claude-acp`、`codex-acp`)不再列出;已经在用它们的任务照常运行,为这两个 id 写一个 [agent 文件](#添加自定义-agent)也会重新列出。agent 需要登录时,任务中会提示该运行哪条命令。
+2
View File
@@ -136,6 +136,8 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
和 IntelliJ IDEA 一样,这里没有逐个文件保存的概念:切换到其他应用或内置终端时文件会自动保存,**文件 › 全部保存**(`⌘S` / `Ctrl+S`)立即保存所有文件。**设置 › 外观与行为 › 系统设置** 的 **自动保存** 一节还可以设置在 IDE 空闲一段时间后保存。
如果在保存期间继续编辑,未写入磁盘的改动仍会标记为未保存。
在 IDE 之外修改的文件,会在切回 IDE 窗口时同步。**从磁盘重新加载**(`⌥⌘Y` / `Ctrl+Alt+Y`)立即重新加载当前文件。
## 相关页面
+4 -2
View File
@@ -111,7 +111,7 @@ OpenIDEA 会从请求文件所在目录开始,逐级向上查找到项目根
- 支持 HTTP/1.1 和 HTTP/2,自动解码 gzip、deflate 和 brotli。
- TLS 证书按系统信任库校验。
- 自动跟随重定向。
- 自动跟随重定向(最多 50 次):303 之后以不带请求体的 GET 继续,其余重定向保留方法与请求体,并在响应中显示跳转链。
- 请求之间不保留 Cookie。
- 连接超时为 30 秒,没有整体请求超时。
- 代理使用 **设置 › 外观与行为 › 系统设置 › HTTP 代理** 中的配置。
@@ -135,7 +135,9 @@ OpenIDEA 会为 Java 和 Kotlin 中的 Spring Web 端点(带 `@RequestMapping`
内置索引按 HTTP 方法和字面量路径匹配控制器,支持完整的 `{variable}` 路径段。Feign 的字面量 `name` 或 `value` 会与目标模块 `src/main/resources` 或其 `config` 子目录中 `application.properties`、`.yml`、`.yaml` 的明确 `spring.application.name` 比较。不会继承父模块或测试资源的配置。配置身份缺失、动态或有冲突,以及客户端指定显式或动态 `url` 时,仍保留方法和路径匹配的候选。导航不会发送 HTTP 请求。
这是源码导航,不解析服务发现或运行时生效配置。首个版本不支持自定义源码目录、组合或别名注解、继承映射、动态路径、`@RequestLine`、Ant/正则路径模式及控制器到客户端的反向导航。配置读取有数量和大小限制;跳转前会重新检查当前控制器文本,包括未保存的编辑。
要查看哪些 Feign 接口声明了对 Spring 端点的请求,请打开端点的装订线菜单并选择**查找 Feign 客户端**。光标位于控制器方法中时,也可以从编辑器菜单或查找操作中执行。只有一个服务匹配时会直接打开该声明。多个结果会列出各接口方法及其源码路径。无法确认目标服务的客户端排在已知匹配之后,并标为**可能匹配**,即便只有一个候选也会显示选择器。明确指向其他服务的客户端会被排除。
导航读取本地源码和模块配置,包括未保存的修改。暂不支持自定义源码目录、组合或别名注解、继承映射、动态映射路径、`@RequestLine`、Ant/正则路径模式和运行时服务发现。
## 暂不支持
+2
View File
@@ -154,6 +154,8 @@ stdio 配置大致如下(路径以你机器上的为准):
**当前已打开** 列出已加载的项目,每个项目显示它正在做什么(正在处理请求、因某个运行保持打开,或已空闲多久以及何时卸载),并带有 **卸载** 按钮。卸载不必等到 **应用**。如果设置仍然提供该项目,下一次指向它的工具调用会再次加载它。
只要有项目处于加载状态,状态栏中的 **后台项目**(层叠图标和数量)就会打开同样的列表。每一行有 **在新窗口中打开** 和 **卸载** 两个图标按钮,列表下方是 **全部卸载** 和 **MCP 服务器设置…**。
信任决定什么:受信任的项目与在窗口中打开的项目一样,可以使用语言服务器和会写入的工具。你没有信任的列出文件夹会以受限模式打开,只开放只读工具。
后台项目没有窗口,所以有些工具不同:
+1 -1
View File
@@ -26,7 +26,7 @@ description: "选择界面主题和编辑器配色方案,导入 IntelliJ 主
- **不同的工具窗口背景**:让工具窗口与编辑器区分开。
- **背景图像**:透过项目窗口显示的图像,可设置 **不透明度**、**填充**(缩放、原始大小或平铺)和 **位置**。
- **辅助功能**:**使用对比度滚动条** 和 **针对红绿色觉缺陷调整颜色**(适用于红色盲和绿色盲)。
- **UI 选项** 下的 **紧凑模式**。
- **UI 选项** 下的 **紧凑模式**,也可在 **视图 › 外观** 中切换。与 IntelliJ IDEA 一致:树和列表的行更矮,主工具栏、工具窗口栏和状态栏更紧凑,工具栏和工具窗口栏图标为 16px,工具栏、状态栏、编辑器标签页和工具窗口标题的文字小 1px。
## 编辑器配色方案
+2
View File
@@ -272,4 +272,6 @@ let out = host::run_command(&Command::new("forge").arg("build").env("FOUNDRY_PRO
- 环境变量只能追加:名称已存在于准备好的环境中(包括登录 shell 的 `PATH`)会报错。最多 64 项。
- 调用会随任务或调用一起取消,超时即终止;耗时的工作请放进 `host::begin_task`。丢弃 `Child` 会终止进程,
禁用或回收插件会结束它启动的所有子进程。
- `Child` 的 `poll` 和 `wait` 返回上次读取之后的输出;`status` 随包含最后一段输出的那次结果返回,读到它为止。
没有读取的输出每个流只保留最后 1 MiB;要拿到会结束的命令的完整输出,请用 `run_command`。
- 用户可以在 **设置 › 插件** 中为 `process:` 授权全局或按项目选择可执行文件;插件仍使用其声明的程序名调用。
+3 -2
View File
@@ -947,8 +947,9 @@ test("indents process-run thoughts and tool calls clearly and aligns output-less
const expandableToolChevron = toolRows[0]!
.querySelector<SVGElement>("[class*='_toolChevron_']")!
.getBoundingClientRect();
const completedReadIcon = [...toolRows[1]!.querySelectorAll("svg")].at(-1)!.getBoundingClientRect();
const runningReadIcon = toolRows[2]!.querySelector("svg")!.getBoundingClientRect();
const kindIcon = (row: HTMLElement) => row.querySelector<SVGElement>("[class*='_toolKindIcon_']")!;
const completedReadIcon = kindIcon(toolRows[1]!).getBoundingClientRect();
const runningReadIcon = kindIcon(toolRows[2]!).getBoundingClientRect();
return {
summaryChevronCenter: summaryChevron.left + summaryChevron.width / 2,
guideLeft: processBody.left,
+40 -2
View File
@@ -6,6 +6,9 @@ import type { Page } from "@playwright/test";
import { expect, stubDesktop, test } from "./fixtures";
const ROOT = "/dev/acme-api";
const NESTED_REF = "teams/payments/reporting/month-end/exports/regions/europe/accounting/invoice-export";
const TRACKING_REF = "origin/releases/payments/month-end/reconciliation/invoice-export";
const BRANCH_FIXTURE = { root: ROOT, ref: NESTED_REF, upstream: TRACKING_REF };
async function openBranches(page: Page) {
await page.evaluate(async () => {
@@ -22,7 +25,7 @@ async function openBranches(page: Page) {
test.beforeEach(async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async (root) => {
await page.evaluate(async ({ root, ref, upstream }) => {
const h = window.__ipc.handlers;
const branch = (name: string, current = false) => ({
name,
@@ -47,6 +50,7 @@ test.beforeEach(async ({ workbench: page }) => {
h.vcs_tags = () => [];
h.vcs_branches = () => [
branch("main", true),
{ ...branch(ref), upstream, ahead: 2, behind: 3 },
...Array.from({ length: 40 }, (_, i) => branch(`task-${i}-a-long-branch-name-that-gets-cut-off`)),
];
const vcsModule = "/src/features/vcs/store.ts";
@@ -54,7 +58,41 @@ test.beforeEach(async ({ workbench: page }) => {
useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false });
await refreshNow();
await loadBranches();
}, ROOT);
}, BRANCH_FIXTURE);
});
test("narrow Git Branches keeps a deeply nested branch and its controls readable", async ({ workbench: page }) => {
await page.evaluate(() => {
localStorage.setItem("openidea.vcs.branchesPopup.size", JSON.stringify({ w: 280, h: 420 }));
});
const popup = await openBranches(page);
const search = popup.getByRole("textbox", { name: "Search branches and actions" });
await search.fill("invoice-export");
const row = popup.getByRole("option", { name: /invoice-export/ });
await expect(row).toBeVisible();
const name = row.locator("[class*=branchName]");
const tracking = row.getByText(TRACKING_REF, { exact: true });
const chevron = row.locator("svg").last();
const folder = popup.getByRole("option", { name: "accounting", exact: true });
const rowBox = (await row.boundingBox())!;
const nameBox = (await name.boundingBox())!;
const trackingBox = (await tracking.boundingBox())!;
const chevronBox = (await chevron.boundingBox())!;
const indent = (option: typeof row) =>
option.locator("[data-row-key]").evaluate((el) => parseFloat(getComputedStyle(el).paddingInlineStart));
expect(await indent(row)).toBeGreaterThan(await indent(folder));
expect(chevronBox.x + chevronBox.width).toBeLessThanOrEqual(rowBox.x + rowBox.width);
expect(nameBox.width).toBeGreaterThan(42);
expect(trackingBox.width).toBeGreaterThan(12);
expect(trackingBox.width).toBeLessThan(rowBox.width * 0.4);
await expect(name).toHaveCSS("font-size", "13px");
await expect(tracking).toHaveCSS("font-size", "13px");
await expect(row.getByRole("img", { name: "3 incoming commits" })).toBeVisible();
await expect(row.getByRole("img", { name: "2 outgoing commits" })).toBeVisible();
await expect(row.locator("[data-row-key]")).toHaveAttribute("title", NESTED_REF);
await expect(tracking).toHaveAttribute("title", TRACKING_REF);
await chevron.click();
await expect(page.getByRole("menu", { name: `Branch ${NESTED_REF}` })).toBeVisible();
});
test("Git Branches resizes by its corner and right edge and reopens at that size", async ({ workbench: page }) => {
+99
View File
@@ -0,0 +1,99 @@
import type { Page } from "@playwright/test";
import type { BuildModel, BuildTool } from "../src/platform/ipc";
import { expect, stubDesktop, test } from "./fixtures";
const model: BuildModel = {
maven: {
projects: [
{
pom: "pom.xml",
dir: "",
groupId: "com.example",
artifactId: "orders",
version: "1.0.0",
packaging: "jar",
displayName: "Orders service",
parent: null,
modules: [],
aggregated: false,
plugins: [],
dependencies: [],
profiles: [],
javaVersion: 21,
command: "mvn",
options: [],
env: {},
},
],
profiles: [],
syncedAt: 1,
stale: false,
syncError: null,
},
gradle: [
{
dir: "",
command: "gradle",
env: {},
javaVersion: 21,
syncedAt: 1,
stale: false,
syncError: null,
projects: [{ path: ":", name: "orders", dir: "", buildFile: "build.gradle", tasks: [] }],
},
],
};
async function showTool(page: Page, tool: BuildTool) {
await stubDesktop(page);
await page.evaluate(
async ({ tool, model }) => {
window.__ipc.handlers.build_model = () => model;
window.__ipc.handlers.run_configs = () => [];
const buildStore = "/src/features/build-tools/store.ts";
await (await import(/* @vite-ignore */ buildStore)).loadModel();
const layout = "/src/workbench/toolwindows/store.ts";
const { setToolWindowSize, showToolWindow } = await import(/* @vite-ignore */ layout);
showToolWindow(tool, true);
setToolWindowSize("right", 190);
},
{ tool, model },
);
}
async function setWidth(page: Page, width: number) {
await page.evaluate(async (px) => {
const layout = "/src/workbench/toolwindows/store.ts";
(await import(/* @vite-ignore */ layout)).setToolWindowSize("right", px);
}, width);
}
for (const tool of ["maven", "gradle"] as const) {
const name = tool === "maven" ? "Maven" : "Gradle";
test(`${name} keeps its toolbar actions reachable as the pane resizes`, async ({ workbench: page }) => {
await showTool(page, tool);
const toolbar = page.getByRole("toolbar", { name: `${name} actions` });
const more = toolbar.getByRole("button", { name: "More Actions", exact: true });
const menu = page.getByRole("menu", { name: "More Actions", exact: true });
const skipTests = "Toggle 'Skip Tests' Mode";
await expect(toolbar.getByRole("button", { name: `Reload All ${name} Projects` })).toBeVisible();
await expect(toolbar.getByRole("button", { name: new RegExp(`Execute ${name}`) })).toBeVisible();
await expect(page.getByRole("tree", { name: `${name} projects` })).toBeVisible();
expect(await toolbar.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await more.click();
await expect(menu.getByRole("menuitem", { name: "Analyze Dependencies…" })).toBeVisible();
await expect(menu.getByRole("menuitem", { name: "Expand All" })).toBeVisible();
await menu.getByRole("menuitemcheckbox", { name: skipTests, checked: false }).click();
await expect(menu).toBeHidden();
await more.click();
await expect(menu.getByRole("menuitemcheckbox", { name: skipTests, checked: true })).toBeVisible();
await setWidth(page, 360);
await expect(menu).toBeHidden();
await expect(more).toBeHidden();
await expect(toolbar.getByRole("button", { name: skipTests, pressed: true })).toBeVisible();
await expect(toolbar.getByRole("button", { name: "Collapse All" })).toBeVisible();
await setWidth(page, 190);
await expect(more).toBeVisible();
await expect(menu).toBeHidden();
});
}
+225
View File
@@ -65,6 +65,7 @@ test("completion lists the server's items and inserts the chosen one", async ({
const popup = page.locator(".cm-tooltip-autocomplete");
await expect(popup.getByText("total", { exact: true })).toBeVisible();
await expect(popup.getByText("toDto", { exact: true })).toBeVisible();
expect((await popup.boundingBox())!.width).toBeLessThan(360);
const field = popup.locator("li").filter({ has: page.locator(".cm-completionLabel", { hasText: /^total$/ }) });
await expect(field.locator(".cm-completionDetail")).toHaveCount(0);
await expect(field.locator(".cm-lsp-type")).toHaveText("BigDecimal");
@@ -83,6 +84,17 @@ test("completion lists the server's items and inserts the chosen one", async ({
const label = await method.locator(".cm-completionLabel").boundingBox();
// Subpixel rounding differs per platform/font; a mis-set inset is a whole icon column off.
expect(Math.abs(label!.x - wordStart)).toBeLessThanOrEqual(2);
const zoomedSize = await editor.locator(".cm-content").evaluate(async (content) => {
const viewModule = "/node_modules/.vite/deps/@codemirror_view.js";
const prefsModule = "/src/editor/core/cm/prefs.ts";
const { EditorView } = await import(/* @vite-ignore */ viewModule);
const { stepFontZoom } = await import(/* @vite-ignore */ prefsModule);
const fontSize = Number.parseFloat(getComputedStyle(content).fontSize);
stepFontZoom(EditorView.findFromDOM(content as HTMLElement)!, 6);
return `${fontSize + 6}px`;
});
await expect(editor.locator(".cm-content")).toHaveCSS("font-size", zoomedSize);
await expect(method.locator(".cm-completionLabel")).toHaveCSS("font-size", zoomedSize);
await page.keyboard.type("toD");
await expect(popup.getByText("total", { exact: true })).toBeHidden();
// Refreshing the results rebuilds the list; the hint bar must stay below it, not jump to the top.
@@ -98,6 +110,76 @@ test("completion lists the server's items and inserts the chosen one", async ({
expect((await ipcCalls(page, "lsp_completion")).length).toBeGreaterThan(0);
});
test("long completion signatures fit the editor when the workbench is narrowed", async ({ workbench: page }) => {
const editor = await openSample(page);
const label = "transformOrder" + "AcrossParticipatingRegions".repeat(5);
await page.evaluate((label) => {
const item: CompletionItem = {
label,
labelDetail: "(order: Order, options: TransformationOptions)",
labelDescription: "Promise<TransformationResult>",
detail: `${label}(order: Order, options: TransformationOptions): Promise<TransformationResult>`,
kind: "method",
documentation: { kind: "markdown", value: "Transforms the order." },
sortText: null,
filterText: null,
preselect: true,
deprecated: false,
insertText: `${label}()`,
isSnippet: false,
replaceRange: null,
replaceRangeTab: null,
additionalEdits: [],
commitCharacters: [],
command: null,
data: null,
server: 1,
};
window.__ipc.handlers.lsp_completion = () => ({ isIncomplete: false, items: [item] });
}, label);
await editor.locator(".cm-line", { hasText: "return order.toDto()" }).click();
await page.keyboard.press("End");
await page.keyboard.press("Enter");
await page.keyboard.type("order.");
await page.keyboard.press("Control+Space");
const popup = page.locator(".cm-tooltip-autocomplete");
const option = popup.getByRole("option").filter({
has: page.locator(".cm-completionLabel", { hasText: label }),
});
await expect(option.locator(".cm-completionLabel")).toHaveText(label);
await page.setViewportSize({ width: 580, height: 900 });
const bounds = (await editor.boundingBox())!;
await expect
.poll(async () => {
const box = (await popup.boundingBox())!;
return Math.max(bounds.x - box.x, box.x + box.width - (bounds.x + bounds.width));
})
.toBeLessThanOrEqual(2);
const geometry = await option.evaluate((row) => {
const label = row.querySelector<HTMLElement>(".cm-completionLabel")!;
const type = row.querySelector<HTMLElement>(".cm-lsp-type")!;
return {
nameTruncated: label.scrollWidth > label.clientWidth,
nameWidth: label.clientWidth,
typeWidth: type.clientWidth,
typeOverflow: type.getBoundingClientRect().right - row.getBoundingClientRect().right,
};
});
expect(geometry.nameTruncated).toBe(true);
expect(geometry.nameWidth).toBeGreaterThan(40);
expect(geometry.typeWidth).toBeGreaterThan(16);
expect(geometry.typeOverflow).toBeLessThanOrEqual(1);
await page.keyboard.press("F1");
await expect(popup.locator(".cm-completionInfo")).toContainText(
`${label}(order: Order, options: TransformationOptions)`,
);
await page.keyboard.press("Enter");
await expect(popup).toBeHidden();
await expect(editor.locator(".cm-activeLine")).toContainText(`order.${label}()`);
});
test("documentation shows beside the lookup instead of being clipped by it", async ({ workbench: page }, info) => {
const editor = await openSample(page);
await page.evaluate(async () => {
@@ -345,6 +427,70 @@ test("Find Usages from the editor context menu lists every usage by file and ope
).toHaveAttribute("aria-selected", "true");
});
test("usage locations and preview stay readable as the available space changes", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1040, height: 760 });
const editor = await openSample(page);
await page.evaluate(
({ file, other }) => {
const locations = [
{ path: file, range: { start: { line: 16, col: 8 }, end: { line: 16, col: 15 } } },
{ path: file, range: { start: { line: 20, col: 27 }, end: { line: 20, col: 34 } } },
{ path: other, range: { start: { line: 0, col: 0 }, end: { line: 0, col: 7 } } },
];
window.__ipc.handlers.lsp_references = () => ({
locations,
classified: [{ location: locations[2], kind: "code", text: "service.submit(order)" }],
incomplete: null,
librariesSkipped: true,
});
},
{ file: FILE, other: `${ROOT}/domain/checkout/processing/calculations/PaymentProcessingService.kt` },
);
await caretAt(editor, page, "val order: Order", "service");
await page.keyboard.press("Meta+Alt+F7");
const popup = page.getByRole("dialog", { name: "Usages" });
const scope = popup.getByRole("button", { name: "Scope" });
const openWindow = popup.getByRole("button", { name: /^Open in Find Window/ });
await expect(popup.getByTestId("usage-row")).toHaveCount(3);
await popup.getByRole("button", { name: "Show Preview" }).click();
const code = popup.getByRole("region", { name: "Preview" });
await expect(code.locator(".cm-content")).toContainText("service.find(status");
await page.setViewportSize({ width: 480, height: 470 });
const within = async (child: Locator, parent: Locator) => {
const [c, p] = await Promise.all([child.boundingBox(), parent.boundingBox()]);
return (
!!c &&
!!p &&
c.x >= p.x - 1 &&
c.y >= p.y - 1 &&
c.x + c.width <= p.x + p.width + 1 &&
c.y + c.height <= p.y + p.height + 1
);
};
await expect.poll(() => within(scope, popup)).toBe(true);
await expect.poll(() => within(openWindow, popup)).toBe(true);
await expect.poll(() => within(code, popup)).toBe(true);
const results = popup.getByRole("listbox", { name: "Usages" });
await expect.poll(() => within(popup.getByTestId("usage-row").last(), results)).toBe(true);
const firstRow = popup.getByTestId("usage-row").first();
const file = firstRow.getByText("build.gradle.kts", { exact: true });
await expect(file).toBeVisible();
const [filename, snippet] = await Promise.all([file.boundingBox(), firstRow.locator("mark").boundingBox()]);
expect(filename!.x + filename!.width).toBeLessThan(snippet!.x);
await openWindow.click();
const tree = page.getByRole("tree", { name: "Usages" });
const target = tree.getByRole("treeitem", { name: /^17 service\.find\(status/ });
await target.click();
const preview = page.getByRole("region", { name: "Preview" });
await expect(preview).toContainText("service.find(status");
await expect.poll(async () => (await preview.boundingBox())!.y > (await tree.boundingBox())!.y).toBe(true);
await page.setViewportSize({ width: 1040, height: 760 });
await expect.poll(async () => (await preview.boundingBox())!.x > (await tree.boundingBox())!.x).toBe(true);
await expect(preview).toContainText("service.find(status");
});
test("⇧F6 renames in place and sends the server's edit to be applied", async ({ workbench: page }) => {
const editor = await openSample(page);
await page.evaluate(
@@ -416,6 +562,85 @@ test("indexed single-file rename previews all anchors and applies only after con
expect(apply.edit).toMatchObject({ preconditions: [{ path: FILE, hash: "indexed-snapshot" }] });
});
test("intention previews fit narrow windows and wrap long code lines", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1600, height: 900 });
const editor = await openSample(page);
await page.evaluate(async () => {
const path = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ path);
const { settings } = useProject.getState();
useProject.setState({ settings: { ...settings, editor: { ...settings?.editor, fontSize: 16 } } });
});
await expect(editor.locator(".cm-content")).toHaveCSS("font-size", "16px");
const replacement = "com.acme.orders." + "SharedDevelopmentOrderModel".repeat(6);
await page.evaluate(
({ file, replacement, edit }) => {
window.__ipc.handlers.lsp_code_actions = () => [
{
title: "Replace Order with the fully qualified shared development order model",
kind: "quickfix",
isPreferred: true,
disabledReason: null,
edit: { files: [{ kind: "edit", path: file, edits: [{ range: edit, new_text: replacement }] }] },
command: null,
data: null,
server: 1,
},
...Array.from({ length: 11 }, (_, i) => ({
title: `Create alternative Order model ${i + 1}`,
kind: "quickfix",
isPreferred: false,
disabledReason: null,
edit: null,
command: null,
data: null,
server: 1,
})),
];
window.__ipc.handlers.lsp_execute_code_action = () => [];
},
{ file: FILE, replacement, edit: range(20, 19, 24) },
);
await caretAt(editor, page, "val order: Order", "Order ");
await page.keyboard.press("Alt+Enter");
const popup = page.getByRole("dialog", { name: "Intentions", exact: true });
const options = popup.getByRole("listbox", { name: "Intentions" });
const preview = popup.locator('[aria-label="Preview"]');
await expect(preview.locator("pre")).toContainText(replacement);
const wide = (await options.boundingBox())!;
const widePreview = (await preview.boundingBox())!;
expect(widePreview.x).toBeGreaterThanOrEqual(wide.x + wide.width - 1);
await page.setViewportSize({ width: 1050, height: 900 });
await expect
.poll(async () => {
const list = (await options.boundingBox())!;
const code = (await preview.boundingBox())!;
return code.x + code.width - list.x;
})
.toBeLessThanOrEqual(1);
await page.setViewportSize({ width: 520, height: 540 });
await expect
.poll(async () => {
const menu = (await popup.boundingBox())!;
const list = (await options.boundingBox())!;
const code = (await preview.boundingBox())!;
return {
popupFits: menu.x >= 0 && menu.y >= 0 && menu.x + menu.width <= 521 && menu.y + menu.height <= 541,
previewBelow: code.y >= list.y + list.height - 1,
previewFits: code.x >= menu.x && code.x + code.width <= menu.x + menu.width + 1,
};
})
.toEqual({ popupFits: true, previewBelow: true, previewFits: true });
expect(await preview.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(preview.locator("pre")).toHaveCSS("font-size", "16px");
await expect(options).toBeFocused();
await page.keyboard.press("Enter");
await expect(popup).toBeHidden();
await expect.poll(() => ipcCalls(page, "lsp_execute_code_action")).toHaveLength(1);
});
test("diagnostics underline the range and ⌥⏎ applies the preferred quick fix", async ({ workbench: page }) => {
const editor = await openSample(page);
await page.evaluate(
+48
View File
@@ -0,0 +1,48 @@
import { expect, test } from "./fixtures";
/** Heights IDEA's Islands theme uses in compact mode (`*.compact` keys), against the defaults. */
const SIZES = {
normal: { titleBar: 40, treeRow: 24, stripeIcon: 20, statusBar: 34, runButton: 30 },
compact: { titleBar: 32, treeRow: 22, stripeIcon: 16, statusBar: 24, runButton: 26 },
};
async function measure(page: import("@playwright/test").Page) {
return page.evaluate(() => {
const height = (selector: string) => document.querySelector(selector)?.getBoundingClientRect().height ?? null;
return {
titleBar: height("header"),
treeRow: height('[role="tree"][aria-label="Project"] [role="treeitem"]'),
stripeIcon: height("[data-stripe-button] svg"),
statusBar: height('footer[aria-label="Status bar"]'),
runButton: height("[data-run-chooser] + * button"),
};
});
}
test("Compact Mode shrinks rows, toolbars, stripes and the status bar like IDEA", async ({ workbench: page }, info) => {
// Plain-browser mode has no settings backend: set what the toggle action would store.
const setCompact = (compactMode: boolean) =>
page.evaluate(async (compactMode) => {
const projectPath = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectPath);
const settings = useProject.getState().settings;
useProject.setState({
settings: {
...settings,
appearance: { ...settings?.appearance, theme: "dark", syncWithOs: false, compactMode },
},
});
}, compactMode);
await setCompact(false);
await expect.poll(() => measure(page)).toEqual(SIZES.normal);
await info.attach("normal", { body: await page.screenshot({ animations: "disabled" }), contentType: "image/png" });
await setCompact(true);
await expect(page.locator("html")).toHaveAttribute("data-compact", "");
await expect.poll(() => measure(page)).toEqual(SIZES.compact);
await info.attach("compact", { body: await page.screenshot({ animations: "disabled" }), contentType: "image/png" });
await setCompact(false);
await expect.poll(() => measure(page)).toEqual(SIZES.normal);
});
+58
View File
@@ -133,6 +133,64 @@ test("breadcrumbs follow the caret into the symbol under it", async ({ workbench
await expect(bar).toBeHidden();
});
test("narrow breadcrumb bars keep the current symbol visible and allow opening earlier crumbs", async ({
workbench: page,
}) => {
const editor = await openFromTree(page, "build.gradle.kts");
const path = page.getByRole("navigation", { name: "Breadcrumbs", exact: true });
const code = page.getByRole("navigation", { name: "Code breadcrumbs" });
await editor.locator(".cm-line", { hasText: "service.find(status" }).click();
await expect(code).toContainText("list()");
await page.evaluate(async () => {
const documentModule = "/src/editor/core/model/document.ts";
const editorModule = "/src/editor/core/controller.ts";
const projectModule = "/src/platform/project.ts";
const schemaModule = "/src/features/settings/model/schema.ts";
const [{ useOutline }, { useEditorStatus }, { useProject }, { DEFAULT_SETTINGS }] = await Promise.all([
import(/* @vite-ignore */ documentModule),
import(/* @vite-ignore */ editorModule),
import(/* @vite-ignore */ projectModule),
import(/* @vite-ignore */ schemaModule),
]);
const base = useProject.getState().settings ?? DEFAULT_SETTINGS;
useProject.setState({ settings: { ...base, editor: { ...base.editor, fontSize: 17 } } });
const activePath = useEditorStatus.getState().status.path;
let outline = useOutline.getState()[activePath];
for (const name of ["OrderProcessingStrategies", "SalesApplicationRouting", "CheckoutWorkspaceConfiguration"]) {
outline = [{ ...outline[0], name, detail: null, children: outline }];
}
useOutline.setState({ [activePath]: outline });
});
await page.setViewportSize({ width: 620, height: 620 });
const fullyInBar = (bar: typeof path, label: string) =>
bar.evaluate((nav, text) => {
const crumb = [...nav.querySelectorAll("button")].find((button) => button.textContent === text);
if (!crumb) return false;
const { left, right } = nav.getBoundingClientRect();
const rect = crumb.getBoundingClientRect();
return rect.width > 0 && rect.left >= left - 1 && rect.right <= right + 1;
}, label);
for (const bar of [path, code]) {
await expect.poll(() => fullyInBar(bar, "list()")).toBe(true);
await expect(bar.locator('[aria-current="location"]')).toHaveText("list()");
}
await expect(code.locator('[aria-current="location"]')).toHaveCSS("font-size", "17px");
await code.hover();
await page.mouse.wheel(0, -1200);
await expect.poll(() => fullyInBar(code, "CheckoutWorkspaceConfiguration")).toBe(true);
const current = path.locator('[aria-current="location"]');
await current.focus();
await current.press("Home");
const project = path.getByRole("button", { name: /acme-api/ }).first();
await expect(project).toBeFocused();
await expect.poll(() => fullyInBar(path, "acme-api")).toBe(true);
await project.press("ArrowDown");
await expect(page.getByRole("listbox", { name: "acme-api" })).toBeVisible();
});
/** What the in-memory backend has saved for `path`. */
const saved = (page: Page, path: string) =>
page.evaluate(async (path) => {
+110 -6
View File
@@ -2,13 +2,10 @@ import { expect, stubDesktop, test } from "./fixtures";
test.use({ video: "on" });
test("Feign navigation selects the named service and offers ambiguous source targets", async ({
workbench: page,
}, testInfo) => {
test.beforeEach(async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
const backend = "/src/editor/core/backend.ts";
const contributions = "/src/workbench/contributions.ts";
const { docBackend } = await import(backend);
const files: Map<string, string> = docBackend().files;
const root = "/dev/acme-api";
@@ -37,7 +34,9 @@ class UserController {
files.set(`${root}/${service}/src/main/resources/application.properties`, `spring.application.name=${service}\n`);
}
window.__ipc.handlers.spring_route_sources = () =>
[...files].filter(([p]) => p.endsWith("UserController.java")).map(([path, text]) => ({ path, text }));
[...files]
.filter(([path, text]) => /\.(java|kt)$/.test(path) && text.includes("Mapping"))
.map(([path, text]) => ({ path, text }));
window.__ipc.handlers.fs_read_text = ({ path }) => {
if (!files.has(String(path))) throw { kind: "notFound", message: "No fixture file" };
return files.get(String(path));
@@ -60,7 +59,21 @@ class UserController {
hidden: false,
}));
window.__ipc.handlers.lsp_goto = () => [];
await (await import(contributions)).editorService().openFile(`${root}/client/src/main/java/UserClient.java`);
window.__ipc.handlers.fs_probe = ({ path }) => ({
size: files.get(String(path))?.length ?? 0,
binary: false,
tooLarge: false,
});
window.__ipc.handlers.find_files = () => [];
});
});
test("Feign navigation selects the named service and offers ambiguous source targets", async ({
workbench: page,
}, testInfo) => {
await page.evaluate(async () => {
const contributions = "/src/workbench/contributions.ts";
await (await import(contributions)).editorService().openFile("/dev/acme-api/client/src/main/java/UserClient.java");
});
await expect(page.locator(".cm-content").last()).toContainText("@FeignClient");
await page.screenshot({ path: testInfo.outputPath("feign-source.png"), animations: "disabled" });
@@ -111,3 +124,94 @@ class UserController {
await declarations.getByRole("option").filter({ hasText: "admin/" }).click();
await expect(page.locator(".cm-content").last()).toContainText('return "admin"');
});
test("a Spring endpoint lists Feign clients by module and flags unresolved services", async ({
workbench: page,
}, testInfo) => {
await page.evaluate(async () => {
const backend = "/src/editor/core/backend.ts";
const contributions = "/src/workbench/contributions.ts";
const files: Map<string, string> = (await import(backend)).docBackend().files;
const root = "/dev/acme-api";
const original = `${root}/client/src/main/java/UserClient.java`;
const template = files.get(original)!;
files.delete(original);
for (const [module, type, service] of [
["orders", "OrderUsers", "users"],
["admin-ui", "AdminUsers", "admin"],
["gateway", "GatewayUsers", "${SERVICE}"],
] as const) {
files.set(
`${root}/${module}/src/main/java/${type}.java`,
template.replace("UserClient", type).replace('"users"', `"${service}"`),
);
}
files.set(
`${root}/billing/src/main/kotlin/BillingUsers.kt`,
`package shop
import org.springframework.cloud.openfeign.FeignClient
import org.springframework.web.bind.annotation.GetMapping
@FeignClient("users")
interface BillingUsers {
@GetMapping("/users/{userId}")
fun find(): String
}`,
);
await (await import(contributions)).editorService().openFile(`${root}/users/src/main/java/UserController.java`);
});
await page.locator('[data-icon-source="spring"][title="GET /users/{id}"]').click();
await expect(page.getByRole("menuitem", { name: "Generate Request in HTTP Client" })).toBeVisible();
await page.screenshot({ path: testInfo.outputPath("controller-menu.png"), animations: "disabled" });
await page.getByRole("menuitem", { name: "Find Feign Clients" }).click({ timeout: 5_000 });
const picker = page.getByRole("dialog", { name: "Feign Clients" });
const rows = picker.getByRole("option");
await expect(rows).toHaveCount(3);
await expect(rows.nth(0)).toContainText("BillingUsers.find");
await expect(rows.nth(0)).toContainText("billing");
await expect(rows.nth(1)).toContainText("OrderUsers.find");
await expect(rows.nth(1)).toContainText("orders");
await expect(rows.nth(2)).toContainText("GatewayUsers.find");
await expect(rows.nth(2)).toContainText("Possible match");
await page.screenshot({ path: testInfo.outputPath("feign-clients.png"), animations: "disabled" });
await rows.nth(0).click();
await expect(page.locator(".cm-content").last()).toContainText("interface BillingUsers");
});
test("one possible client requires a choice and a changed workspace invalidates that choice", async ({
workbench: page,
}) => {
await page.evaluate(async () => {
const backend = "/src/editor/core/backend.ts";
const api = "/src/editor/api.ts";
const actions = "/src/platform/actions.ts";
const contributions = "/src/workbench/contributions.ts";
const root = "/dev/acme-api";
const files: Map<string, string> = (await import(backend)).docBackend().files;
files.set(`${root}/users/src/main/resources/application.properties`, "spring.application.name=${SERVICE}");
await (await import(contributions)).editorService().openFile(`${root}/users/src/main/java/UserController.java`);
const view = (await import(api)).activeEditor().view;
view.dispatch({ selection: { anchor: view.state.doc.toString().indexOf("return") } });
await (await import(actions)).executeAction("http.findFeignClients");
});
const picker = page.getByRole("dialog", { name: "Feign Clients" });
const candidate = picker.getByRole("option");
await expect(candidate).toHaveCount(1);
await expect(candidate).toContainText("Possible match");
await page.evaluate(async () => {
const backend = "/src/editor/core/backend.ts";
const ipc = "/src/platform/ipc.ts";
const path = "/dev/acme-api/users/src/main/resources/application.properties";
(await import(backend)).docBackend().files.set(path, "spring.application.name=users");
(await import(ipc)).emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [path], removed: [] });
});
await candidate.click();
await expect(picker).not.toBeVisible();
await expect(page.locator(".cm-content").last()).toContainText("class UserController");
await page.evaluate(async () => {
const actions = "/src/platform/actions.ts";
await (await import(actions)).executeAction("http.findFeignClients");
});
await expect(page.locator(".cm-content").last()).toContainText("interface UserClient");
});
+73
View File
@@ -0,0 +1,73 @@
import type { Page } from "@playwright/test";
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
async function quickDocumentation(page: Page, markdown: string) {
const editor = await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
await page.evaluate((value) => {
window.__ipc.handlers.lsp_hover = () => ({ contents: { kind: "markdown", value }, range: null });
}, markdown);
const line = editor.locator(".cm-line", { hasText: "return order.toDto()" });
await line.click();
await page.keyboard.press("End");
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("F1");
const popup = page.getByRole("dialog", { name: "Documentation", exact: true });
await expect(popup.locator(".cm-lsp-markdown")).toBeVisible();
return popup;
}
test("short quick documentation uses a readable width and a compact corner of actions", async ({ workbench: page }) => {
const popup = await quickDocumentation(page, "Returns the total.");
const back = popup.getByRole("button", { name: "Back", exact: true });
const dock = popup.getByRole("button", { name: "Show in Documentation Tool Window" });
await expect(dock).toBeVisible();
const bounds = (await popup.boundingBox())!;
expect(bounds.width).toBeGreaterThanOrEqual(298);
expect(bounds.width).toBeLessThan(320);
const backBounds = (await back.boundingBox())!;
const dockBounds = (await dock.boundingBox())!;
expect(backBounds.x).toBeGreaterThan(bounds.x + bounds.width / 2);
expect(bounds.x + bounds.width - dockBounds.x - dockBounds.width).toBeLessThan(16);
await expect(popup.locator(".cm-lsp-markdown")).toHaveCSS("font-size", "13px");
await page.keyboard.press("Escape");
await expect(popup).toBeHidden();
});
test("long quick documentation scrolls with its actions in view", async ({ workbench: page }) => {
const signature = "fun calculateTotal(order: Order, options: ExtendedPricingOptions): CalculationResult";
const markdown = [
`\`\`\`kotlin\n${signature}\n\`\`\``,
...Array.from({ length: 22 }, (_, i) => {
return `Section ${i + 1}. Explains the applicable pricing rules, shipping restrictions and currency options.`;
}),
"End of pricing documentation.",
].join("\n\n");
const popup = await quickDocumentation(page, markdown);
const dock = popup.getByRole("button", { name: "Show in Documentation Tool Window" });
await expect(dock).toBeVisible();
expect((await popup.boundingBox())!.width).toBeLessThan(508);
await page.setViewportSize({ width: 430, height: 500 });
await expect
.poll(async () => {
const box = (await popup.boundingBox())!;
return Math.max(-box.x, -box.y, box.x + box.width - 430, box.y + box.height - 500);
})
.toBeLessThanOrEqual(1);
const body = popup.locator(".cm-lsp-markdown").locator("..");
const last = popup.getByText("End of pricing documentation.");
const dockBefore = (await dock.boundingBox())!;
await expect(body.locator("pre")).toContainText(signature);
const scroll = await body.evaluate((node) => {
node.scrollTop = node.scrollHeight;
return { top: node.scrollTop, horizontalOverflow: node.scrollWidth - node.clientWidth };
});
expect(scroll.top).toBeGreaterThan(0);
expect(scroll.horizontalOverflow).toBeLessThanOrEqual(1);
const lastBounds = (await last.boundingBox())!;
expect(lastBounds.y + lastBounds.height).toBeLessThanOrEqual(dockBefore.y + 1);
expect(await dock.boundingBox()).toEqual(dockBefore);
await expect(dock).toBeInViewport();
});
+94
View File
@@ -0,0 +1,94 @@
import type { Page } from "@playwright/test";
import { expect, stubDesktop, test } from "./fixtures";
async function openRecent(page: Page, kind: "recentFiles" | "recentLocations") {
await page.evaluate(async (id) => {
const actions = "/src/platform/actions.ts";
void (await import(/* @vite-ignore */ actions)).executeAction(`navigate.${id}`);
}, kind);
}
test("Recent Files keeps directories beside names and leaves room for files in a narrow window", async ({
workbench: page,
}) => {
await stubDesktop(page);
await page.evaluate(() => {
window.__ipc.handlers.recent_files = () => ["/dev/acme-api/src/orders/InvoiceService.ts"];
});
await openRecent(page, "recentFiles");
const dialog = page.getByRole("dialog", { name: "Recent Files", exact: true });
const files = dialog.getByRole("listbox", { name: "Recent files" });
const row = files.getByRole("option").first();
const name = row.getByText("InvoiceService.ts", { exact: true });
const directory = row.getByText("src/orders", { exact: true });
await expect(name).toBeVisible();
const nameRight = await name.evaluate((el) => el.getBoundingClientRect().right);
const dirLeft = (await directory.boundingBox())!.x;
expect(dirLeft - nameRight).toBeLessThanOrEqual(8);
await page.setViewportSize({ width: 400, height: 500 });
expect((await files.boundingBox())!.width).toBeGreaterThan(200);
expect((await dialog.getByRole("textbox", { name: "Filter recent files" }).boundingBox())!.width).toBeGreaterThan(
200,
);
await expect.poll(() => directory.evaluate((el) => el.getBoundingClientRect().width)).toBeGreaterThan(20);
await expect(dialog.getByRole("button", { name: /Recent Locations/ })).toBeVisible();
const footer = dialog.locator("footer");
await expect(footer).toBeInViewport({ ratio: 1 });
expect(
await dialog.locator("[data-dialog-body]").evaluate((el) => el.scrollHeight - el.clientHeight),
).toBeLessThanOrEqual(1);
});
test("Recent Locations keeps all snippet lines visible when the editor font grows", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
const tracking = "/src/features/search/common/tracking.ts";
const { useTracking } = await import(/* @vite-ignore */ tracking);
useTracking.setState({
locations: [
{
path: "/dev/acme-api/src/orders/CalculateOutstandingInvoicesForTheMonthlyReconciliation.ts",
line: 41,
col: 4,
changed: true,
time: Date.now(),
snippet: ["const invoices = await repository.openInvoices();", "return sum(invoices);", "}"],
snippetStart: 40,
},
],
});
});
await openRecent(page, "recentLocations");
const dialog = page.getByRole("dialog", { name: "Recent Locations", exact: true });
const row = dialog.getByRole("option").first();
const code = row.locator("pre");
await expect(code).toContainText("return sum(invoices);");
await page.evaluate(async () => {
const project = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ project);
const { settings } = useProject.getState();
useProject.setState({
settings: {
...settings,
editor: {
...settings?.editor,
fontFamily: "Fira Code",
fallbackFont: "Maple Mono NF CN",
fontSize: 19,
lineHeight: 30,
},
},
});
});
await expect(code).toHaveCSS("font-size", "19px");
await expect(code).toHaveCSS("line-height", "30px");
await expect(code).toHaveCSS("font-family", /"Fira Code".*"Maple Mono NF CN"/);
expect((await code.boundingBox())!.height).toBe(90);
await page.setViewportSize({ width: 400, height: 500 });
const filter = dialog.getByRole("textbox", { name: "Filter recent locations" });
expect((await filter.boundingBox())!.width).toBeGreaterThan(200);
await expect(row.getByText("changed", { exact: true })).toBeInViewport({ ratio: 1 });
await expect(filter).toBeFocused();
});
+79
View File
@@ -0,0 +1,79 @@
import { expect, test } from "./fixtures";
test("Run Anything keeps its command field and shortcuts visible as its results scroll", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1080, height: 740 });
await page.evaluate(async () => {
const projectModule = "/src/platform/project.ts";
const contributionsModule = "/src/workbench/contributions.ts";
const historyModule = "/src/features/run-anything/model.ts";
const [{ useProject }, { registerRunAnythingProvider }, { pushHistory }] = await Promise.all([
import(/* @vite-ignore */ projectModule),
import(/* @vite-ignore */ contributionsModule),
import(/* @vite-ignore */ historyModule),
]);
const root = useProject.getState().project.root;
for (const command of ["git status", "git diff --stat", "pnpm lint", "pnpm test"]) pushHistory(root, command);
const tasks = Array.from({ length: 8 }, (_, i) => {
const command = `npm run verify-${i + 1}`;
return {
key: command,
label: `Verify checkout configuration ${i + 1}`,
detail: "checkout-service / workspace verification",
completion: command,
run: () => {
document.body.dataset.runAnythingCommand = command;
},
};
});
registerRunAnythingProvider({
id: "test-verify",
order: -100,
group: "Run Configurations",
items: (line: string) => tasks.filter((task) => task.completion.includes(line)),
});
});
await page.keyboard.press("Control");
await page.keyboard.press("Control");
const popup = page.getByRole("dialog", { name: "Run Anything", exact: true });
const field = popup.getByLabel("Command line", { exact: true });
const results = popup.getByRole("listbox", { name: "Run Anything entries" });
const hint = popup.getByText(/Enter to run, Tab to complete|Tab to complete, Enter to run/);
await expect(field).toBeFocused();
await page.setViewportSize({ width: 560, height: 340 });
await expect
.poll(async () => {
const [shell, footer] = await Promise.all([popup.boundingBox(), hint.boundingBox()]);
return (
!!shell &&
!!footer &&
Math.abs(shell.x - (560 - shell.width) / 2) < 2 &&
shell.x >= 14 &&
footer.y + footer.height <= shell.y + shell.height + 1
);
})
.toBe(true);
await expect.poll(() => results.evaluate((el) => el.scrollHeight > el.clientHeight)).toBe(true);
await field.fill("verify");
await field.press("ArrowDown");
await expect(field).toHaveValue("npm run verify-1");
const selected = results.getByRole("option", { selected: true });
await expect(selected).toContainText("Verify checkout configuration 1");
await expect(field).toHaveAttribute("aria-activedescendant", (await selected.getAttribute("id"))!);
await field.press("Tab");
await expect(field).toHaveValue("npm run verify-1");
await expect(field).toBeFocused();
await field.press("Shift+Tab");
const history = popup.getByRole("button", { name: "Clear History" });
await expect(history).toBeFocused();
await history.press("Enter");
await expect(history).toBeHidden();
await expect(field).toBeFocused();
await field.press("ArrowDown");
await field.press("Enter");
await expect(popup).toBeHidden();
await expect(page.locator("body")).toHaveAttribute("data-run-anything-command", "npm run verify-1");
});
+25 -3
View File
@@ -1,8 +1,8 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
async function openConfigurations(page: Page) {
await page.evaluate(async () => {
async function openConfigurations(page: Page, target?: string) {
await page.evaluate(async (target) => {
const path = "/src/features/run/store.ts";
const { useRun } = await import(/* @vite-ignore */ path);
const base = {
@@ -21,6 +21,7 @@ async function openConfigurations(page: Page) {
...base,
id: "layout:app",
name: "Payments development server",
target,
beforeLaunch: [{ kind: "run", target: "layout:prepare" }],
},
{ ...base, id: "layout:prepare", name: "Prepare generated sources for the payments development server" },
@@ -29,10 +30,31 @@ async function openConfigurations(page: Page) {
loaded: true,
editorOpen: true,
});
});
}, target);
await expect(page.getByRole("dialog", { name: "Run/Debug Configurations", exact: true })).toBeVisible();
}
test("long run target names leave room for configuration names in the sidebar", async ({ workbench: page }) => {
const target = "payments-development-shared-staging-runner-west";
await openConfigurations(page, target);
const dialog = page.getByRole("dialog", { name: "Run/Debug Configurations", exact: true });
const tree = dialog.getByRole("tree", { name: "Run configurations", exact: true });
const row = tree.getByRole("treeitem", { name: /^Payments development server/ });
const name = row.getByText("Payments development server", { exact: true });
const badge = row.getByText(`@ ${target}`, { exact: true });
await expect(badge).toBeVisible();
for (const width of [1100, 520]) {
await page.setViewportSize({ width, height: 820 });
await expect.poll(async () => (await name.boundingBox())!.width).toBeGreaterThan(width === 1100 ? 80 : 50);
await expect.poll(() => tree.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
}
await expect(badge).toBeHidden();
await expect(row).toHaveAttribute("title", new RegExp(`Payments development server @ ${target}`));
await expect(dialog.getByRole("textbox", { name: "Name", exact: true })).toHaveValue("Payments development server");
});
test("run configuration sidebar resizes with mouse and keyboard and remembers the layout", async ({
workbench: page,
}) => {
+19
View File
@@ -21,6 +21,25 @@ async function searchFiles(page: Page) {
return dialog;
}
test("the popup leaves room around results with or without the preview", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1200, height: 900 });
const dialog = await searchFiles(page);
const preview = dialog.getByRole("region", { name: "Preview", exact: true });
const footer = dialog.locator("footer");
const expectPopupSize = async () => {
const { width, height } = (await dialog.boundingBox())!;
expect(width).toBeCloseTo(700, 0);
expect(height).toBeCloseTo(600, 0);
await expect(footer).toBeInViewport({ ratio: 1 });
};
await expect(preview).toBeVisible();
await expectPopupSize();
await dialog.getByRole("button", { name: "Preview", exact: true }).click();
await expect(preview).toBeHidden();
await expectPopupSize();
});
for (const count of [1, 2, 24]) {
test(`without the preview the results list shows its rows (${count} results)`, async ({ workbench: page }) => {
await stubDesktop(page);
+64
View File
@@ -60,6 +60,70 @@ for (const { width, split } of [{ width: 220 }, { width: 280 }, { width: 520 },
});
}
test("wide terminal search leaves the grid in place and avoids covering the active match", async ({
workbench: page,
}) => {
await page.evaluate(async () => {
const path = "/src/workbench/toolwindows/store.ts";
const layout = await import(path);
layout.setToolWindowSize("bottom", 280);
layout.showToolWindow("terminal", true);
});
const terminal = page.getByRole("region", { name: "Terminal", exact: true });
await expect(terminal.locator(".xterm-helper-textarea")).toBeFocused();
const panel = terminal.getByRole("tabpanel");
const before = (await panel.boundingBox())!;
await page.evaluate(async () => {
const path = "/src/features/terminal/runtime.ts";
const { activeSession } = await import(path);
const { term } = activeSession();
await new Promise<void>((resolve) =>
term.write(`\x1b[2J\x1b[1;${term.cols - 16}Hright-edge\x1b[1;2Hleft-side\x1b[6;1H`, resolve),
);
});
await page.keyboard.press("Meta+f");
const search = terminal.getByRole("search", { name: "Find in terminal" });
const input = search.getByRole("textbox", { name: "Find in terminal" });
await expect(input).toBeFocused();
expect(await panel.boundingBox()).toEqual(before);
const top = (await search.boundingBox())!;
expect(top.y).toBeCloseTo(before.y, 0);
expect(top.x + top.width).toBeCloseTo(before.x + before.width, 0);
expect(top.width).toBeLessThan(before.width);
await input.fill("right-edge");
await expect(search.locator("[aria-live=polite]")).toHaveText("1/1");
await expect
.poll(async () => {
const box = (await search.boundingBox())!;
return box.y + box.height;
})
.toBeCloseTo(before.y + before.height, 0);
await expect(input).toBeFocused();
expect(await panel.boundingBox()).toEqual(before);
await input.fill("left-side");
await expect(search.locator("[aria-live=polite]")).toHaveText("1/1");
await expect.poll(async () => (await search.boundingBox())!.y).toBeCloseTo(before.y, 0);
await page.evaluate(async () => {
const path = "/src/workbench/toolwindows/store.ts";
const { setToolWindowSize } = await import(path);
setToolWindowSize("bottom", 130);
});
await expect
.poll(async () => {
const box = (await search.boundingBox())!;
return box.y + box.height - (await panel.boundingBox())!.y;
})
.toBeCloseTo(0, 0);
await expect(input).toHaveValue("left-side");
await page.keyboard.press("Escape");
await expect(search).toBeHidden();
await expect(terminal.locator(".xterm-helper-textarea")).toBeFocused();
});
test("terminal highlights visible occurrences of selected text in a single overlay layer", async ({
workbench: page,
}) => {
+1 -1
View File
@@ -1 +1 @@
32c888d5f7724d52cd5c46562f64cfab58cf9ec54c80e43638309fa85304e152
dd2064150ef1e9a70c4f7c33e8f4396f131db951d9818eab5f854a7e9ce71e11
@@ -1 +1 @@
fc8d32f7b4d6d0cd2cf747c328f17f523475e3dfae8617db7435e9cd137b91ae
d7233de85619c0a9479f4d6fbd87bc6105b9f72b7daacf701f2e1212a01b2768
+1 -1
View File
@@ -1 +1 @@
9654a8eb4583b170c69359a581bb2a8c0476b7486c9dc0f4dea8a75ff63f018f
396b7103d40247c6d1b489d0003a934374f27d9dffb9bcb33e7ae2811829ac31
+1 -1
View File
@@ -1 +1 @@
4208f2136cf0811df94c42edd0c06fea12b2f9fd4d1a6250f7002d81ab8542d0
2324da549433c9c88d67cfae6a0207716c5a61e41bb06648cc3b233a5fb7a41a
+1 -1
View File
@@ -1 +1 @@
992ac6522f7294083aa6edf6c35cba2862129d917a9dafe55f630194873c7687
8cd17db5f028d4c211f00af52ebc4408e0dd41d75f20e7cc5a6dcaec0b888c89
+1 -1
View File
@@ -1 +1 @@
55adac462ebb73b453399e5493ee2aea4efea5c1e9470d601b2062e580177225
862dfc0bbaa9ecb954727ba5586e083d6ae0aeae4f71af54df0675f3d8a2db29
+1 -1
View File
@@ -1 +1 @@
586742d4b056ba631f66b7b1e38e26e7378aa9a0e213319ad46b8d3ba1789794
c84b047226c6bed4ba0a0c851e16a37813945eb46fd4a5028c97a64d2a81411d
+1 -1
View File
@@ -1 +1 @@
ccc598ac4c7dbad4bbc5355a09fb5b26d556bd7736a9541667aabd1fecd3d5d3
400458a210f3d794787dece4d5c178bddf7af04a9bca141fa574d532ab669bc0
+1 -1
View File
@@ -1 +1 @@
4fcaa47727482ae30a5b480cd83609759a976f48de7216651d08f6da01667212
a1aa1d621b40c30b1252a7506a8c74e1eabd90abd40fff5a7b04028c7ac6811e
+1 -1
View File
@@ -1 +1 @@
eadc5daa2eb67abaaf55a0f8d5efa6d1bf78006f768880d12e95c9d7d662b333
841c9840b33a780ee29e04cf4fa79ed4dd7b30d428d3b90841fcd7eb059223ba
+1 -1
View File
@@ -1 +1 @@
18431dce88b25566e463ff518c810e92c77d5df97998e1bc0a3c7d9f7ad99363
31394076ed408e043633604e5ae46b519d259d3317b849f8a0f1d774935815ad
+1 -1
View File
@@ -1 +1 @@
c9892ec85b11080ea1080f408e1f5f1558554e4488aee6467454b0e627512dcd
1d5d4bb8502dec07b7ec420d57f627ffdb4f7126b6a5e5d2bcda77e222a8a680
+1 -1
View File
@@ -1 +1 @@
d9e50c56321d2dbf8261754ce604842a38d61e57f7e52b7d3f66077776f9244b
939e477e32de648ed96d634f040be546207504ea2d58a14cc480a0038f1f5c46
+1 -1
View File
@@ -1 +1 @@
77d083fb8ed777715a98477d447b240ccd59db610251dfb1a103b6d2d8d0599e
aa71bdd8d76b43cc103e61b870504ab4ebab9f4235b84736a8a63e26a962d527
+1 -1
View File
@@ -1 +1 @@
b9d8c8a1d3d30d39ee0fc2b65ca0ce6e5a0520be772c99eafdec9c7785c4766b
435187598694fd7e3a43bc40d2b1824d7e4631632b1da202db6d28b0fac867f2
+3 -2
View File
@@ -1487,8 +1487,8 @@ pub struct Child {
impl Child {
/// What it printed since the last read, up to 1 MiB per stream, or one
/// whole character when `max_bytes` is smaller;
/// `status` is `Some` once it ended.
/// whole character when `max_bytes` is smaller. `status` is `Some` in the
/// chunk that holds the last of its output: poll until it is set.
pub fn poll(&self, max_bytes: u32) -> Result<Chunk, Error> {
imp::child_poll(&self.inner, max_bytes)
}
@@ -1509,6 +1509,7 @@ impl Child {
}
/// Waits up to `timeout_ms` for it to end (0 only checks), then reads it.
/// When more is left than one chunk holds, `status` comes with a later [`poll`](Self::poll).
pub fn wait(&self, timeout_ms: u32) -> Result<Chunk, Error> {
imp::child_wait(&self.inner, timeout_ms)
}
+8 -4
View File
@@ -150,7 +150,8 @@ interface process {
}
/// What a kept-running program printed since the last call, and its exit
/// code once it ended (`none` while it still runs).
/// code with the last of its output (`none` while it still runs or output
/// is left to read, so the first chunk with a status is the final one).
record chunk {
/// Up to 1 MiB per stream; unpolled output keeps the last 1 MiB.
/// `poll` takes up to `max-bytes`, or one whole character when that
@@ -165,10 +166,13 @@ interface process {
/// (the ninth `start` is `invalid`). They also end with the plugin:
/// stopping, disabling or reclaiming it kills what it started.
resource child {
/// What it printed since the last call, and its status once it ends.
/// What it printed since the last call; the status comes with the
/// chunk that holds the last of its output.
poll: func(max-bytes: u32) -> result<chunk, error>;
/// Waits up to `timeout-ms` for it to end (0 only checks), then
/// reports what it printed since the last call.
/// Waits up to `timeout-ms` for it to end and its output to reach the
/// end (0 only checks), then reports what it printed since the last
/// call. When more is left than one chunk holds, the status comes
/// with a later `poll`.
wait: func(timeout-ms: u32) -> result<chunk, error>;
/// Writes to its stdin; fails once it ended or stdin was closed.
write: func(text: string) -> result<_, error>;
+1
View File
@@ -16,6 +16,7 @@ agent_entries always project_host bin
agent_external_sessions trusted project_host bindings async
agent_fork trusted project_host bindings async
agent_grouped_changes trusted project_host bindings async
agent_hermes_profiles trusted project_host bindings async
agent_import_session trusted project_host bindings async
agent_mcp_discover_sources always project_host bindings async
agent_mcp_import always project_host bindings sync
+45 -3
View File
@@ -57,6 +57,8 @@ export const commands = {
agentFork: (task: string, turns: number | null) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_fork", { task, turns })),
/** The task's uncommitted changes and the commits made since it started. */
agentGroupedChanges: (task: string) => typedError<AgentChanges, IdeError>(__TAURI_INVOKE("agent_grouped_changes", { task })),
/** Hermes Agent profiles on this machine (`default` first); empty without Hermes. */
agentHermesProfiles: () => typedError<HermesProfile[], IdeError>(__TAURI_INVOKE("agent_hermes_profiles")),
/** Imports an external session as a task: its first turn loads and replays it. */
agentImportSession: (provider: string, sessionId: string) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_import_session", { provider, sessionId })),
/** Discovers external MCP configuration files on disk (CLI user configs + workspace `.mcp.json`). */
@@ -2267,11 +2269,15 @@ steered?: boolean } | { type: "agent"; text: string } |
/** A question that can be answered while the agent keeps working, or after the turn ends. */
{ type: "question"; id: string; title: string; questions: AgentQuestion[];
/** The submitted answers, or `Skipped`; `None` while unanswered. */
chosen: string | null } | { type: "thought"; text: string } | { type: "tool"; id: string; title: string;
chosen: string | null } | { type: "thought"; text: string;
/** When the reasoning started (ms since the epoch); `None` in tasks saved before. */
startedMs?: number | null } | { type: "tool"; id: string; title: string;
/** ACP tool kind: `read`, `edit`, `execute`, `search`, `fetch`, `think`… */
kind: string; status: AgentToolStatus; locations: IpcPath[];
/** Text the tool reported (command output…), truncated. */
output: string | null; diffs: AgentToolDiff[] } | { type: "plan"; items: AgentPlanItem[] } |
output: string | null; diffs: AgentToolDiff[];
/** When the call started and ended (ms since the epoch); `None` in tasks saved before. */
startedMs?: number | null; endedMs?: number | null } | { type: "plan"; items: AgentPlanItem[] } |
/** A subagent the agent started: its own session, whose entries are listed separately. */
{ type: "subagent";
/** The subagent's session id. */
@@ -2570,6 +2576,13 @@ export type AgentSecuritySettings = {
blockedCommands?: string[],
};
export type AgentSessionStats = {
/** The last turn's tokens (`session/prompt` result `usage`). */
tokens?: AgentTokens | null,
/** How many times the agent compressed the conversation (Hermes `compressionDepth`). */
compressions?: number,
};
/** Settings › Agents: what the conversation shows and how messages are sent. */
export type AgentSettings = AgentSettings_Serialize | AgentSettings_Deserialize;
@@ -2749,6 +2762,8 @@ export type AgentTask_Deserialize = {
background?: AgentBackgroundTask[],
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`. */
mcpOverrides?: { [key in string]: boolean },
/** Token counts of the last turn and context compressions, when the agent reports them. */
stats?: AgentSessionStats,
};
export type AgentTask_Serialize = {
@@ -2797,6 +2812,8 @@ export type AgentTask_Serialize = {
background: AgentBackgroundTask[],
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`. */
mcpOverrides?: { [key in string]: boolean },
/** Token counts of the last turn and context compressions, when the agent reports them. */
stats: AgentSessionStats,
};
/** Token pricing (Credits per 1M tokens) and context window capacity for one tier. */
@@ -2808,6 +2825,12 @@ export type AgentTokenPricing = {
contextTokens?: number | null,
};
export type AgentTokens = {
input: number,
cached: number,
output: number,
};
export type AgentToolDiff = {
path: IpcPath,
added: number,
@@ -6760,6 +6783,14 @@ export type HeapSummary = {
analysisMs: number,
};
/** A profile and the name Hermes shows for it (`hermes profile list`). */
export type HermesProfile = {
/** What `hermes -p` takes; `default` is the Hermes home itself. */
name: string,
/** `display_name` from the profile's `profile.yaml`, else the name. */
label: string,
};
export type HierarchyChoice = {
id: string,
makeAbstract: boolean,
@@ -6943,6 +6974,8 @@ export type HttpResponse = {
version: string,
headers: ([string, string])[],
contentType: string | null,
/** Followed redirects, first hop first; empty when not redirected. */
redirects?: RedirectHop[],
/** Body as text (lossy UTF-8); `None` for binary bodies. */
body: string | null,
/** Size in bytes as received (after decompression). */
@@ -7012,7 +7045,9 @@ ignoreRules?: IpcPath[] } |
/** Part of a grouped transaction; the editor must not record a file-local undo. */
workspaceEdit?: boolean } |
/** A document's dirty flag changed (saved / modified externally). */
{ type: "docDirty"; doc: DocId; dirty: boolean } |
{ type: "docDirty"; doc: DocId; dirty: boolean;
/** Text version when this transition occurred, including when it was saved. */
version: number } |
/** A complete workspace edit can be undone as one operation. */
{ type: "workspaceEditApplied"; id: number; paths: IpcPath[];
/**
@@ -10284,6 +10319,13 @@ export type RecentProjectGroup = {
expanded?: boolean,
};
/** One followed redirect: the response and the `Location` it pointed to. */
export type RedirectHop = {
status: number,
statusText: string,
location: string,
};
export type RefactoringProblem = {
severity: ProblemSeverity,
message: string,
+7 -3
View File
@@ -16,6 +16,7 @@ import {
type DocumentInfo,
type DocumentLanguage,
type FoldRange,
type IdeEvent,
type LanguageInfo_Serialize,
type LineEnding,
type OutlineItem,
@@ -38,6 +39,8 @@ export interface DocPatchedEvent {
changes: TextChange[];
}
export type DocDirtyEvent = Extract<IdeEvent, { type: "docDirty" }>;
export interface DocBackend {
open(path: string): Promise<DocumentInfo>;
/** Opens a read-only language-server document (library or disk class contents). */
@@ -71,7 +74,7 @@ export interface DocBackend {
*/
languageOf?(path: string, firstLine?: string): Promise<DocumentLanguage>;
onPatched(handler: (e: DocPatchedEvent) => void): () => void;
onDirty(handler: (e: { doc: DocId; dirty: boolean }) => void): () => void;
onDirty(handler: (e: DocDirtyEvent) => void): () => void;
/** Files changed on disk (used to refresh nothing but closed-file state). */
onFsChanged?(handler: (e: { removed: string[] }) => void): () => void;
/**
@@ -393,7 +396,7 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
const docs = new Map<DocId, MemDoc>();
const byPath = new Map<string, DocId>();
const patched = new Set<(e: DocPatchedEvent) => void>();
const dirtyHandlers = new Set<(e: { doc: DocId; dirty: boolean }) => void>();
const dirtyHandlers = new Set<(e: DocDirtyEvent) => void>();
let nextId = 1;
const store = new Map(Object.entries(files));
const savedBoms = new Map<string, boolean>();
@@ -442,7 +445,8 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
};
const setDirty = (d: MemDoc, before: boolean) => {
const now = d.text !== d.saved || d.hasBom !== d.savedBom;
if (now !== before) dirtyHandlers.forEach((h) => h({ doc: d.id, dirty: now }));
if (now !== before)
dirtyHandlers.forEach((h) => h({ type: "docDirty", doc: d.id, dirty: now, version: d.version }));
};
const delay = <T>(v: () => T): Promise<T> =>
backend.latency > 0
+168
View File
@@ -30,6 +30,14 @@ async function settle() {
for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0));
}
function deferred() {
let resolve!: () => void;
const promise = new Promise<void>((done) => {
resolve = done;
});
return { promise, resolve };
}
function setup(files: Record<string, string>, settings = {}) {
_resetLanguages();
const backend: MemoryBackend = createMemoryBackend(files);
@@ -217,6 +225,166 @@ describe("DocumentManager + slots", () => {
expect(useDocMeta.getState()["/p/a.txt"]?.dirty).toBe(false);
});
it.each(["dirty before response", "dirty after response", "clean and dirty after response"] as const)(
"keeps a newer edit dirty with %s",
async (order) => {
const path = "/p/a.txt";
const { backend, manager } = setup({ [path]: "base\n" }, { files: { autoSave: false } });
const model = await manager.acquire(path);
const slot = new EditorSlot(model, "t1", host);
const events: Array<() => void> = [];
const originalOnDirty = backend.onDirty.bind(backend);
let deferDirty = false;
const onDirty = vi.spyOn(backend, "onDirty").mockImplementation((handler) =>
originalOnDirty((event) => {
if (deferDirty) events.push(() => handler(event));
else handler(event);
}),
);
manager.stop();
manager.start();
const response = deferred();
const originalSave = backend.save.bind(backend);
const save = vi.spyOn(backend, "save").mockImplementationOnce(async (doc) => {
await originalSave(doc);
await response.promise;
});
const transitions: boolean[] = [];
const unsubscribe = useDocMeta.subscribe((state, previous) => {
const dirty = state[path]?.dirty;
if (dirty !== undefined && dirty !== previous[path]?.dirty) transitions.push(dirty);
});
let pending: Promise<void> | undefined;
try {
slot.dispatchLocal({ changes: { from: 4, insert: " saved" } });
await model.sync.whenIdle();
expect(transitions).toEqual([true]);
deferDirty = order === "clean and dirty after response";
pending = model.save("explicit");
await vi.waitFor(() => expect(backend.files.get(path)).toBe("base saved\n"));
expect(await backend.snapshot(model.doc)).toMatchObject({ text: "base saved\n", dirty: false });
transitions.length = 0;
deferDirty = order !== "dirty before response";
slot.dispatchLocal({ changes: { from: 10, insert: " newer" } });
await model.sync.whenIdle();
expect(await backend.snapshot(model.doc)).toMatchObject({ text: "base saved newer\n", dirty: true });
response.resolve();
await pending;
expect(slot.currentState().doc.toString()).toBe("base saved newer\n");
expect(backend.files.get(path)).toBe("base saved\n");
expect(model.getMeta().dirty).toBe(true);
const deferredCount = order === "dirty before response" ? 0 : order === "dirty after response" ? 1 : 2;
expect(events).toHaveLength(deferredCount);
events.splice(0).forEach((deliver) => deliver());
expect(useDocMeta.getState()[path]?.dirty).toBe(true);
expect(transitions).not.toContain(false);
deferDirty = false;
await model.save("explicit");
expect(backend.files.get(path)).toBe("base saved newer\n");
expect(await backend.snapshot(model.doc)).toMatchObject({ text: "base saved newer\n", dirty: false });
expect(useDocMeta.getState()[path]?.dirty).toBe(false);
expect(transitions.at(-1)).toBe(false);
} finally {
response.resolve();
try {
await pending;
} finally {
unsubscribe();
save.mockRestore();
onDirty.mockRestore();
slot.dispose();
manager.releaseProjectDocuments();
manager.stop();
}
}
},
);
it("marks an unchanged buffer clean when its save succeeds", async () => {
const path = "/p/a.txt";
const { backend, manager } = setup({ [path]: "base\n" });
const model = await manager.acquire(path);
const slot = new EditorSlot(model, "t1", host);
const transitions: Array<{ dirty: boolean; persisted: string | undefined }> = [];
const unsubscribe = useDocMeta.subscribe((state, previous) => {
const dirty = state[path]?.dirty;
if (dirty !== undefined && dirty !== previous[path]?.dirty)
transitions.push({ dirty, persisted: backend.files.get(path) });
});
try {
slot.dispatchLocal({ changes: { from: 4, insert: " saved" } });
await model.save("explicit");
expect(slot.currentState().doc.toString()).toBe("base saved\n");
expect(await backend.snapshot(model.doc)).toMatchObject({ text: "base saved\n", dirty: false });
expect(transitions).toEqual([
{ dirty: true, persisted: "base\n" },
{ dirty: false, persisted: "base saved\n" },
]);
} finally {
unsubscribe();
slot.dispose();
manager.releaseProjectDocuments();
manager.stop();
}
});
it("reconciles a save that includes an edit whose acknowledgement is still pending", async () => {
const path = "/p/a.txt";
const { backend, manager } = setup({ [path]: "base\n" }, { files: { autoSave: false } });
const model = await manager.acquire(path);
const slot = new EditorSlot(model, "t1", host);
const write = deferred();
const editReply = deferred();
const originalSave = backend.save.bind(backend);
const originalEdit = backend.edit.bind(backend);
const edit = vi.spyOn(backend, "edit");
const save = vi.spyOn(backend, "save").mockImplementationOnce(async (doc) => {
await write.promise;
await originalSave(doc);
});
let pending: Promise<void> | undefined;
try {
slot.dispatchLocal({ changes: { from: 4, insert: " first" } });
await model.sync.whenIdle();
pending = model.save("explicit");
await vi.waitFor(() => expect(save).toHaveBeenCalledWith(model.doc));
edit.mockImplementationOnce(async (...args) => {
const version = await originalEdit(...args);
await editReply.promise;
return version;
});
slot.dispatchLocal({ changes: { from: 10, insert: " second" } });
const synced = model.sync.whenIdle();
await vi.waitFor(async () => {
expect(await backend.snapshot(model.doc)).toMatchObject({ text: "base first second\n", dirty: true });
});
write.resolve();
await pending;
editReply.resolve();
await synced;
expect(slot.currentState().doc.toString()).toBe("base first second\n");
expect(backend.files.get(path)).toBe("base first second\n");
expect(useDocMeta.getState()[path]?.dirty).toBe(false);
} finally {
editReply.resolve();
write.resolve();
try {
await pending;
} finally {
edit.mockRestore();
save.mockRestore();
slot.dispose();
manager.releaseProjectDocuments();
manager.stop();
}
}
});
it.each(["explicit", "auto"] as const)(
"%s save leaves untouched documents byte-for-byte unchanged",
async (reason) => {
+32 -12
View File
@@ -28,7 +28,7 @@ import {
} from "@/editor/api";
import { isUntitledUri, isVirtualUri } from "@/platform/virtualDocs";
import { DocSync, type Scheduler, frameScheduler } from "../sync/DocSync";
import type { DocBackend, LanguageInfo } from "../backend";
import type { DocBackend, DocDirtyEvent, LanguageInfo } from "../backend";
import {
findLanguageDescription,
languageInfo,
@@ -261,6 +261,7 @@ export class DocModel {
handoffRelease = false;
private refreshTimer: ReturnType<typeof setTimeout> | undefined;
private saving: Promise<void> = Promise.resolve();
private backendDirty: DocDirtyEvent | null = null;
private meta: DocMeta;
constructor(
@@ -321,6 +322,7 @@ export class DocModel {
changes: eventChanges,
});
},
onSynced: () => this.applyBackendClean(),
onDiscarded: (reason) => {
logError(`document ${this.path}: unsaved edits replaced by the file's content`, reason);
manager.notify({
@@ -345,6 +347,26 @@ export class DocModel {
if (!this.closed) useDocMeta.setState({ [this.path]: this.meta });
}
onBackendDirty(event: DocDirtyEvent) {
if (this.backendDirty && event.version < this.backendDirty.version) return;
this.backendDirty = event;
if (event.dirty) {
if (!this.meta.dirty) this.setMeta({ dirty: true });
} else this.applyBackendClean();
}
private applyBackendClean() {
const event = this.backendDirty;
if (event && !event.dirty) this.markClean(event.version);
}
private markClean(version: number) {
// A clean event can arrive before an edit acknowledgement or after a newer edit.
if (!this.meta.dirty || !this.sync.idle || this.sync.serverVersion !== version) return;
this.modified.clear();
this.setMeta({ dirty: false });
}
ctx(): EditorDocContext {
return {
doc: this.doc,
@@ -713,16 +735,20 @@ export class DocModel {
// an explicit save asks for one (Save As re-points the buffer, or stays
// dirty on Cancel).
if (reason === "auto") return;
if (await this.manager.saveAs(this)) this.modified.clear();
await this.manager.saveAs(this);
return;
}
const backend = this.manager.backend;
const version = this.sync.serverVersion;
const observedDirty = this.backendDirty;
// Autosave never overwrites external changes made after the buffer was edited.
if (reason === "auto" && backend.autosave) {
if (!(await backend.autosave(this.doc))) return;
} else await backend.save(this.doc);
this.modified.clear();
this.setMeta({ dirty: false });
// The reply does not identify what was saved. It only confirms the version
// we sent if the buffer and the observed backend dirty state haven't moved on.
if (this.backendDirty === observedDirty && (!observedDirty || observedDirty.version <= version))
this.markClean(version);
_emitEditorEvent({ type: "docSaved", doc: this.doc, path: this.path });
};
this.saving = this.saving.then(run, run);
@@ -732,6 +758,7 @@ export class DocModel {
/** Save As turned this untitled buffer into the file `info` points at. */
retarget(info: DocumentInfo) {
const old = this.path;
if (!this.backendDirty?.dirty || this.backendDirty.version < info.version) this.markClean(info.version);
this.path = info.path;
this.info = languageInfo(info.language);
this.editorconfig = info.editorconfig ?? null;
@@ -743,7 +770,6 @@ export class DocModel {
hasBom: info.hasBom,
lineEnding: info.lineEnding,
canReloadEncoding: info.canReloadEncoding,
dirty: false,
};
useDocMeta.setState((s) => {
const next = { ...s };
@@ -803,13 +829,7 @@ export class DocumentManager {
this.workspaceHistory.start(),
this.backend.onPatched((e) => this.byId.get(e.doc)?.sync.remote(e)),
this.backend.onLanguage?.((e) => this.byId.get(e.doc)?.setLanguage(e.language, e.uiMode)) ?? (() => {}),
this.backend.onDirty((e) => {
const m = this.byId.get(e.doc);
if (m && m.getMeta().dirty !== e.dirty) {
m.setMeta({ dirty: e.dirty });
if (!e.dirty) m.modified.clear();
}
}),
this.backend.onDirty((e) => this.byId.get(e.doc)?.onBackendDirty(e)),
);
let prev = useEditorRegistry.getState().contributions;
this.disposers.push(
+4
View File
@@ -38,6 +38,8 @@ export interface SyncHost {
applyRemote(changes: ChangeSet, workspaceEdit?: boolean): void;
/** A locally produced batch accepted by the versioned backend. */
onLocalCommitted?(baseVersion: number, version: number, changes: ChangeSet): void;
/** The local buffer has no pending edits or resync. */
onSynced?(): void;
/** Called after a hard resync discarded local changes the backend never saw. */
onDiscarded?(reason: unknown): void;
/** Non-recoverable transport errors (logged by default). */
@@ -157,6 +159,7 @@ export class DocSync {
if (this.disposed || patch.version <= this.serverVersion) return;
this.pendingRemote.push(patch);
this.drainRemote();
this.resolveIdle();
}
dispose() {
@@ -356,6 +359,7 @@ export class DocSync {
private resolveIdle(force = false) {
if (!force && !this.idle) return;
if (this.idle && !this.disposed) this.host.onSynced?.();
const waiters = this.idleWaiters;
this.idleWaiters = [];
waiters.forEach((w) => w());
+34
View File
@@ -101,6 +101,40 @@ describe("untitled editor input", () => {
expect(JSON.stringify(session)).not.toContain("untitled:");
});
it("keeps edits made after a Save As write dirty when retargeting the tab", async () => {
await ctrl!.openUntitled({ focus: false });
const slot = ctrl!.slotFor(activeTab().id)!;
const model = await editActive("draft");
const path = "/p/saved.txt";
vi.mocked(save).mockResolvedValue(path);
let release!: () => void;
const response = new Promise<void>((resolve) => {
release = resolve;
});
const originalSaveAs = backend.saveAs.bind(backend);
const saveAs = vi.spyOn(backend, "saveAs").mockImplementationOnce(async (...args) => {
const info = await originalSaveAs(...args);
await response;
return info;
});
const pending = model.save("explicit");
try {
await vi.waitFor(() => expect(backend.files.get(path)).toBe("draft\n"));
slot.dispatchLocal({ changes: { from: 5, insert: " newer" } });
await model.sync.whenIdle();
release();
await pending;
expect(activeTab().input.path).toBe(path);
expect(slot.currentState().doc.toString()).toBe("draft newer\n");
expect(backend.files.get(path)).toBe("draft\n");
expect(await backend.snapshot(model.doc)).toMatchObject({ text: "draft newer\n", dirty: true });
expect(useDocMeta.getState()[path]?.dirty).toBe(true);
} finally {
release();
await pending.finally(() => saveAs.mockRestore());
}
});
it("offers the registered languages as save-as types", async () => {
await ctrl!.openUntitled({ focus: false });
const slot = ctrl!.slotFor(activeTab().id)!;
Loaded 100 of 257 files, more files were not shown because too many files have changed in this diff. Show more