mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-22 19:49:35 -10:00
Compare commits
34
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
60882d647f | ||
|
|
1ad8b06a1a | ||
|
|
2ca0e195e5 | ||
|
|
750d35dd6e | ||
|
|
f0273690b9 | ||
|
|
04611c0388 | ||
|
|
1cfc71ae58 | ||
|
|
8daaef38d9 | ||
|
|
efd4e454ee | ||
|
|
0379c37a49 | ||
|
|
98da80b2b3 | ||
|
|
5c2e7ff92a | ||
|
|
e86a853048 | ||
|
|
fd8f0eb99c | ||
|
|
121e1fa535 | ||
|
|
5859cf9f5b | ||
|
|
21b187f2d5 | ||
|
|
121d7edc15 | ||
|
|
9c0dcb94cf | ||
|
|
b9256a7260 | ||
|
|
47b4cb55ba | ||
|
|
da1bcd67cd | ||
|
|
67a4797cf4 | ||
|
|
39523bc419 | ||
|
|
639c76d54c | ||
|
|
d5f29ea256 | ||
|
|
f9455549a7 | ||
|
|
dd14e8b040 | ||
|
|
efce16d45d | ||
|
|
977ce62bf0 | ||
|
|
479123dcf3 | ||
|
|
09301ca12d | ||
|
|
485c1ac40b | ||
|
|
6d756ec472 |
No files matched your search
@@ -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!({
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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>,
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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
@@ -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
@@ -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
|
||||
@@ -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 {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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() });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -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 需要登录时,任务中会提示该运行哪条命令。
|
||||
|
||||
|
||||
@@ -136,6 +136,8 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
|
||||
|
||||
和 IntelliJ IDEA 一样,这里没有逐个文件保存的概念:切换到其他应用或内置终端时文件会自动保存,**文件 › 全部保存**(`⌘S` / `Ctrl+S`)立即保存所有文件。**设置 › 外观与行为 › 系统设置** 的 **自动保存** 一节还可以设置在 IDE 空闲一段时间后保存。
|
||||
|
||||
如果在保存期间继续编辑,未写入磁盘的改动仍会标记为未保存。
|
||||
|
||||
在 IDE 之外修改的文件,会在切回 IDE 窗口时同步。**从磁盘重新加载**(`⌥⌘Y` / `Ctrl+Alt+Y`)立即重新加载当前文件。
|
||||
|
||||
## 相关页面
|
||||
|
||||
@@ -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/正则路径模式和运行时服务发现。
|
||||
|
||||
## 暂不支持
|
||||
|
||||
|
||||
@@ -154,6 +154,8 @@ stdio 配置大致如下(路径以你机器上的为准):
|
||||
|
||||
**当前已打开** 列出已加载的项目,每个项目显示它正在做什么(正在处理请求、因某个运行保持打开,或已空闲多久以及何时卸载),并带有 **卸载** 按钮。卸载不必等到 **应用**。如果设置仍然提供该项目,下一次指向它的工具调用会再次加载它。
|
||||
|
||||
只要有项目处于加载状态,状态栏中的 **后台项目**(层叠图标和数量)就会打开同样的列表。每一行有 **在新窗口中打开** 和 **卸载** 两个图标按钮,列表下方是 **全部卸载** 和 **MCP 服务器设置…**。
|
||||
|
||||
信任决定什么:受信任的项目与在窗口中打开的项目一样,可以使用语言服务器和会写入的工具。你没有信任的列出文件夹会以受限模式打开,只开放只读工具。
|
||||
|
||||
后台项目没有窗口,所以有些工具不同:
|
||||
|
||||
@@ -26,7 +26,7 @@ description: "选择界面主题和编辑器配色方案,导入 IntelliJ 主
|
||||
- **不同的工具窗口背景**:让工具窗口与编辑器区分开。
|
||||
- **背景图像**:透过项目窗口显示的图像,可设置 **不透明度**、**填充**(缩放、原始大小或平铺)和 **位置**。
|
||||
- **辅助功能**:**使用对比度滚动条** 和 **针对红绿色觉缺陷调整颜色**(适用于红色盲和绿色盲)。
|
||||
- **UI 选项** 下的 **紧凑模式**。
|
||||
- **UI 选项** 下的 **紧凑模式**,也可在 **视图 › 外观** 中切换。与 IntelliJ IDEA 一致:树和列表的行更矮,主工具栏、工具窗口栏和状态栏更紧凑,工具栏和工具窗口栏图标为 16px,工具栏、状态栏、编辑器标签页和工具窗口标题的文字小 1px。
|
||||
|
||||
## 编辑器配色方案
|
||||
|
||||
|
||||
@@ -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:` 授权全局或按项目选择可执行文件;插件仍使用其声明的程序名调用。
|
||||
@@ -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,
|
||||
|
||||
@@ -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 }) => {
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
}
|
||||
@@ -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,160 @@ test("indexed single-file rename previews all anchors and applies only after con
|
||||
expect(apply.edit).toMatchObject({ preconditions: [{ path: FILE, hash: "indexed-snapshot" }] });
|
||||
});
|
||||
|
||||
test("rename keeps the typed name, uses the editor font and shows long preview names in a narrow dialog", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const editor = await openSample(page);
|
||||
await page.evaluate(
|
||||
async ({ file, prepared }) => {
|
||||
const projectModule = "/src/platform/project.ts";
|
||||
const schemaModule = "/src/features/settings/model/schema.ts";
|
||||
const [{ useProject }, { DEFAULT_SETTINGS }] = await Promise.all([
|
||||
import(/* @vite-ignore */ projectModule),
|
||||
import(/* @vite-ignore */ schemaModule),
|
||||
]);
|
||||
const base = useProject.getState().settings ?? DEFAULT_SETTINGS;
|
||||
useProject.setState({ settings: { ...base, editor: { ...base.editor, fontSize: 17 } } });
|
||||
window.__ipc.handlers.lsp_prepare_rename = () => prepared;
|
||||
window.__ipc.handlers.lsp_rename = (args) => ({
|
||||
preview: true,
|
||||
incomplete: null,
|
||||
edit: {
|
||||
files: [
|
||||
{
|
||||
kind: "edit",
|
||||
path: file,
|
||||
edits: [{ range: prepared, new_text: args.newName }],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
window.__ipc.handlers.apply_workspace_edit = () => null;
|
||||
},
|
||||
{ file: FILE, prepared: range(20, 12, 17) },
|
||||
);
|
||||
|
||||
await caretAt(editor, page, "val order: Order", "order");
|
||||
await page.keyboard.press("Shift+F6");
|
||||
await expect(page.getByText(/Press ⇧F6 to show dialog/)).toBeVisible();
|
||||
const name = "checkoutOrderWithDeliveryInstructionsAndInventoryReservation";
|
||||
await page.keyboard.insertText(name);
|
||||
await page.keyboard.press("Shift+F6");
|
||||
await page.setViewportSize({ width: 440, height: 520 });
|
||||
const dialog = page.getByRole("dialog", { name: "Rename 'order'", exact: true });
|
||||
const input = dialog.getByRole("textbox", { name: "New name" });
|
||||
await expect(input).toBeFocused();
|
||||
await expect(input).toHaveValue(name);
|
||||
await expect(input).toHaveCSS("font-size", "17px");
|
||||
const [label, field] = await Promise.all([
|
||||
dialog.getByText("New name", { exact: true }).boundingBox(),
|
||||
input.boundingBox(),
|
||||
]);
|
||||
expect(label!.x + label!.width).toBeLessThan(field!.x);
|
||||
const rename = dialog.getByRole("button", { name: "Rename", exact: true });
|
||||
|
||||
await input.fill("");
|
||||
await expect(rename).toBeDisabled();
|
||||
await input.press("Enter");
|
||||
await expect(dialog).toBeVisible();
|
||||
expect(await ipcCalls(page, "lsp_rename")).toHaveLength(0);
|
||||
await input.fill(name);
|
||||
await input.press("Enter");
|
||||
|
||||
const summary = `Rename 'order' to '${name}'`;
|
||||
const preview = page.getByRole("dialog", { name: summary, exact: true });
|
||||
const context = preview.getByText(summary, { exact: true });
|
||||
await expect(context).toBeVisible();
|
||||
const geometry = await context.evaluate((element) => ({
|
||||
client: element.clientWidth,
|
||||
content: element.scrollWidth,
|
||||
}));
|
||||
expect(geometry.content).toBeLessThanOrEqual(geometry.client + 1);
|
||||
await expect(preview.getByText("1 occurrence in 1 file")).toBeVisible();
|
||||
expect(await ipcCalls(page, "apply_workspace_edit")).toHaveLength(0);
|
||||
await preview.getByRole("button", { name: "Do Refactor" }).click();
|
||||
await expect.poll(() => ipcCalls(page, "apply_workspace_edit")).toHaveLength(1);
|
||||
});
|
||||
|
||||
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(
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -113,3 +113,60 @@ test("stops at a breakpoint, shows frames and variables, steps and resumes", asy
|
||||
await expect.poll(() => ipcCalls(page, "debug_resume")).toHaveLength(1);
|
||||
await expect(debug.getByText("CreateOrderRequest(sku='A-1', qty=2)")).toBeHidden();
|
||||
});
|
||||
|
||||
test("Evaluate keeps a multiline expression and its result visible in a short dialog", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 580, height: 420 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async (session) => {
|
||||
const handlers = window.__ipc.handlers;
|
||||
handlers.debug_capabilities = () => ({});
|
||||
handlers.debug_completions = () => [];
|
||||
handlers.debug_evaluate_in = () => ({
|
||||
name: "orderSummary",
|
||||
typeName: "OrderSummary",
|
||||
value: "total = 36",
|
||||
variablesReference: 210,
|
||||
evaluateName: null,
|
||||
});
|
||||
handlers.debug_variables = () => [
|
||||
{ name: "tax", value: "4", typeName: "int", variablesReference: 0, evaluateName: null },
|
||||
];
|
||||
const stateModule = "/src/features/debugger/state.ts";
|
||||
const { adoptSession } = await import(/* @vite-ignore */ stateModule);
|
||||
adoptSession(session, { name: "Checkout", adapter: "debugpy", status: "paused", selectedFrame: 11 });
|
||||
}, SESSION);
|
||||
|
||||
await page.keyboard.press("Alt+F8");
|
||||
const dialog = page.getByRole("dialog", { name: "Evaluate expression" });
|
||||
const field = dialog.getByRole("textbox", { name: "Expression" });
|
||||
const expression = ["orderSummary(", ...Array.from({ length: 12 }, (_, i) => ` item${i},`), ")"].join("\n");
|
||||
await field.fill(expression);
|
||||
await field.press("Enter");
|
||||
const result = dialog.getByRole("tree", { name: "Evaluation result" });
|
||||
const row = result.getByRole("treeitem").first();
|
||||
await expect(row).toContainText("total = 36");
|
||||
await expect
|
||||
.poll(() =>
|
||||
dialog.locator("[data-dialog-body]").evaluate((body) => {
|
||||
const area = body.querySelector("textarea")!;
|
||||
const resultRow = body.querySelector('[role="treeitem"]')!.getBoundingClientRect();
|
||||
const bounds = body.getBoundingClientRect();
|
||||
return (
|
||||
body.scrollHeight <= body.clientHeight + 1 &&
|
||||
area.scrollHeight > area.clientHeight &&
|
||||
resultRow.top >= bounds.top &&
|
||||
resultRow.bottom <= bounds.bottom
|
||||
);
|
||||
}),
|
||||
)
|
||||
.toBe(true);
|
||||
await row.click();
|
||||
await row.press("ArrowRight");
|
||||
await expect(result.getByText("tax", { exact: true })).toBeVisible();
|
||||
|
||||
await field.fill("otherExpression");
|
||||
await dialog.getByRole("button", { name: "History", exact: true }).click();
|
||||
await page.getByRole("menuitem", { name: /orderSummary/ }).click();
|
||||
await expect(field).toHaveValue(expression);
|
||||
await expect(field).toBeFocused();
|
||||
});
|
||||
@@ -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) => {
|
||||
@@ -174,6 +232,48 @@ test("⌘R replaces every match in the file", async ({ workbench: page }) => {
|
||||
await expect(editor.locator(".cm-line", { hasText: "OrderDto" })).toHaveCount(2);
|
||||
});
|
||||
|
||||
test("the inline find and replace controls stay inside a narrow editor pane", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1120, height: 760 });
|
||||
const editor = await openFromTree(page, "build.gradle.kts");
|
||||
await editor.locator(".cm-content").click();
|
||||
await page.keyboard.press("Meta+r");
|
||||
const bar = page.getByRole("search", { name: "Replace in file" });
|
||||
const find = bar.getByRole("textbox", { name: "Find" });
|
||||
const replace = bar.getByRole("textbox", { name: "Replace" });
|
||||
const next = bar.getByRole("button", { name: /Next Occurrence/ });
|
||||
await find.fill("OrderDto");
|
||||
await find.press("Tab");
|
||||
await expect(replace).toBeFocused();
|
||||
await replace.fill("OrderView");
|
||||
const navigationIsBelowFind = async () => {
|
||||
const [input, button] = await Promise.all([find.boundingBox(), next.boundingBox()]);
|
||||
return !!input && !!button && button.y >= input.y + input.height;
|
||||
};
|
||||
const controlsFit = () =>
|
||||
bar.evaluate((panel) => {
|
||||
const bounds = panel.getBoundingClientRect();
|
||||
return [...panel.querySelectorAll("button, textarea")].every((element) => {
|
||||
const control = element.getBoundingClientRect();
|
||||
return control.width > 0 && control.left >= bounds.left && control.right <= bounds.right;
|
||||
});
|
||||
});
|
||||
await expect.poll(navigationIsBelowFind).toBe(false);
|
||||
|
||||
await page.setViewportSize({ width: 590, height: 760 });
|
||||
await expect.poll(controlsFit).toBe(true);
|
||||
await expect.poll(navigationIsBelowFind).toBe(true);
|
||||
await page.setViewportSize({ width: 495, height: 760 });
|
||||
await expect.poll(controlsFit).toBe(true);
|
||||
await expect(find).toHaveValue("OrderDto");
|
||||
await expect(replace).toHaveValue("OrderView");
|
||||
await next.click();
|
||||
await expect(bar.getByText(/^[12]\/2$/)).toBeVisible();
|
||||
await bar.getByRole("button", { name: "Replace All" }).click();
|
||||
await expect(editor.locator(".cm-line", { hasText: "OrderView" })).toHaveCount(2);
|
||||
await bar.getByRole("button", { name: "Close", exact: true }).click();
|
||||
await expect(bar).toBeHidden();
|
||||
});
|
||||
|
||||
test("Markdown preview highlights ⌘F matches, selected words and scales diagrams with font zoom", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
@@ -538,3 +638,15 @@ test("dragging the Markdown split divider resizes and reflows editor and preview
|
||||
.poll(async () => Math.round((await reopenedEditor.boundingBox())!.width))
|
||||
.toBe(Math.round(initialEditor));
|
||||
});
|
||||
|
||||
test("Markdown Preview only leaves the Project view clickable", async ({ workbench: page }) => {
|
||||
await openFromTree(page, "README.md");
|
||||
await page.getByRole("button", { name: "Preview Only" }).click();
|
||||
await expect(page.getByRole("document", { name: "Markdown preview" })).toBeVisible();
|
||||
|
||||
const row = page.getByRole("treeitem", { name: "build.gradle.kts", exact: true });
|
||||
// A hidden editor panel used to leave an implicit resize region over everything left of the preview,
|
||||
// which swallowed the click.
|
||||
await row.click();
|
||||
await expect(row).toHaveAttribute("aria-selected", "true");
|
||||
});
|
||||
+110
-6
@@ -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");
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
+76
-3
@@ -3,15 +3,21 @@
|
||||
* the process. Processes are stubbed at the IPC layer; `crates/ide-run` covers spawning them.
|
||||
*/
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { RunConfig } from "../src/bindings";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const RUN_ID = 7;
|
||||
|
||||
/** One saved `npm run dev` configuration; `run_start` prints `output` and exits with `exit` unless null. */
|
||||
async function stubRun(page: Page, output: { kind: string; text: string }[], exit: number | null) {
|
||||
async function stubRun(
|
||||
page: Page,
|
||||
output: { kind: string; text: string }[],
|
||||
exit: number | null,
|
||||
overrides: Partial<RunConfig> = {},
|
||||
) {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ output, exit, runId }) => {
|
||||
async ({ output, exit, runId, overrides }) => {
|
||||
const config = {
|
||||
id: "npm:dev",
|
||||
name: "dev",
|
||||
@@ -23,6 +29,7 @@ async function stubRun(page: Page, output: { kind: string; text: string }[], exi
|
||||
detected: false,
|
||||
isTest: false,
|
||||
debugAdapter: null,
|
||||
...overrides,
|
||||
};
|
||||
const h = window.__ipc.handlers;
|
||||
h.run_configs = () => [config];
|
||||
@@ -43,7 +50,7 @@ async function stubRun(page: Page, output: { kind: string; text: string }[], exi
|
||||
await loadConfigs();
|
||||
selectConfig(config.id);
|
||||
},
|
||||
{ output, exit, runId: RUN_ID },
|
||||
{ output, exit, runId: RUN_ID, overrides },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -177,6 +184,72 @@ test("Go reruns keep each package's exact failures and the original configuratio
|
||||
]);
|
||||
});
|
||||
|
||||
test("test results keep counts, actions and selected output visible as the pane narrows", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1060, height: 740 });
|
||||
const goPackage = "example.com/checkout";
|
||||
const name = "TestCheckoutTotalsWithDiscountsAndPendingInventoryReservations";
|
||||
const message = "expected subtotal 42, got 37";
|
||||
const records = [
|
||||
{ Action: "run", Test: name },
|
||||
{ Action: "output", Test: name, Output: message + "\n" },
|
||||
{ Action: "fail", Test: name, Elapsed: 0.125 },
|
||||
{ Action: "pass", Test: "TestPayment", Elapsed: 0.02 },
|
||||
{ Action: "skip", Test: "TestDelayedShipping" },
|
||||
{ Action: "fail", Elapsed: 0.17 },
|
||||
];
|
||||
await stubRun(
|
||||
page,
|
||||
records.map((record) => ({ kind: "stdout", text: JSON.stringify({ Package: goPackage, ...record }) + "\n" })),
|
||||
1,
|
||||
{
|
||||
id: "go:checkout-tests",
|
||||
name: "Checkout tests",
|
||||
kind: "go",
|
||||
command: "go",
|
||||
args: ["test", "-json"],
|
||||
isTest: true,
|
||||
},
|
||||
);
|
||||
await page.keyboard.press("Control+r");
|
||||
const run = page.getByRole("region", { name: "Run", exact: true });
|
||||
const tree = run.getByRole("tree", { name: "Test results" });
|
||||
const row = tree.getByRole("treeitem", { name: new RegExp(name) });
|
||||
await row.click();
|
||||
const output = run.getByRole("log");
|
||||
await expect(output).toContainText(message);
|
||||
await expect.poll(async () => (await output.boundingBox())!.x > (await tree.boundingBox())!.x).toBe(true);
|
||||
await page.setViewportSize({ width: 540, height: 740 });
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const [list, console] = await Promise.all([tree.boundingBox(), output.boundingBox()]);
|
||||
return !!list && !!console && console.y >= list.y + list.height - 1;
|
||||
})
|
||||
.toBe(true);
|
||||
const summary = run.getByRole("status").filter({ hasText: "1 failing" });
|
||||
for (const count of ["1 failing", "1 passed", "1 ignored"]) await expect(summary.getByText(count)).toBeVisible();
|
||||
await expect(row).toHaveAttribute("aria-selected", "true");
|
||||
await expect(row.getByText("125 ms")).toBeVisible();
|
||||
await expect(output).toContainText(message);
|
||||
const toolbar = run.getByRole("toolbar", { name: "Test results" });
|
||||
await toolbar.getByRole("button", { name: "More Actions" }).click();
|
||||
await expect(page.getByRole("menuitem", { name: "Collapse All" })).toBeVisible();
|
||||
await expect(page.getByRole("menuitem", { name: "Export Test Results…" })).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
const divider = run.getByRole("separator");
|
||||
const treeHeight = async () => (await tree.boundingBox())!.height;
|
||||
const beforeResize = await treeHeight();
|
||||
await divider.press("ArrowDown");
|
||||
await expect.poll(treeHeight).toBeGreaterThan(beforeResize + 1);
|
||||
const customizedHeight = await treeHeight();
|
||||
await page.setViewportSize({ width: 1060, height: 740 });
|
||||
await expect.poll(async () => (await output.boundingBox())!.x > (await tree.boundingBox())!.x).toBe(true);
|
||||
await page.setViewportSize({ width: 540, height: 740 });
|
||||
await expect.poll(async () => Math.abs((await treeHeight()) - customizedHeight)).toBeLessThan(2);
|
||||
await expect(output).toContainText(message);
|
||||
});
|
||||
|
||||
test("CMake builds the selected target in Build before starting only the application in Run", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
@@ -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,
|
||||
}) => {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,6 +1,7 @@
|
||||
// @vitest-environment node
|
||||
import { chromium, type Browser, type Page } from "@playwright/test";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { chromiumInstalled } from "../../perf/lib/lifecycle.ts";
|
||||
import { track } from "./measure.ts";
|
||||
|
||||
let browser: Browser;
|
||||
@@ -29,7 +30,7 @@ afterAll(async () => {
|
||||
|
||||
const existingResult = () => document.querySelector("#result") !== null;
|
||||
|
||||
describe("tracking the current action", () => {
|
||||
describe.skipIf(!chromiumInstalled(true))("tracking the current action", () => {
|
||||
it("rejects an action that declines to run even with an old result visible", async () => {
|
||||
await expect(
|
||||
track(page, { action: "unavailable", arg: null, first: existingResult, done: existingResult, timeoutMs: 1000 }),
|
||||
|
||||
@@ -1,26 +1,30 @@
|
||||
// @vitest-environment node
|
||||
import { expect, test } from "vitest";
|
||||
import { launchBrowser } from "../../perf/lib/lifecycle.ts";
|
||||
import { chromiumInstalled, launchBrowser } from "../../perf/lib/lifecycle.ts";
|
||||
import { track } from "./measure.ts";
|
||||
|
||||
test("track times out on Node's clock when animation frames stop", { timeout: 20_000 }, async () => {
|
||||
const runtime = await launchBrowser({ headless: true });
|
||||
try {
|
||||
const page = await runtime.browser.newPage();
|
||||
await page.evaluate(() => {
|
||||
// Install the otherwise undeclared probe consumed by the serialized measurement.
|
||||
const w = window as unknown as { __openideaPerf: unknown };
|
||||
w.__openideaPerf = {
|
||||
editorState: () => null,
|
||||
runAction: async () => true,
|
||||
};
|
||||
window.requestAnimationFrame = () => 0;
|
||||
});
|
||||
// The platform-clock boundary is the regression; a fake Node clock cannot drive Chromium.
|
||||
await expect(
|
||||
track(page, { action: "fixture.action", arg: null, first: () => false, done: () => false, timeoutMs: 20 }),
|
||||
).rejects.toThrow("page measurement timed out");
|
||||
} finally {
|
||||
await runtime.close();
|
||||
}
|
||||
});
|
||||
test.skipIf(!chromiumInstalled(true))(
|
||||
"track times out on Node's clock when animation frames stop",
|
||||
{ timeout: 20_000 },
|
||||
async () => {
|
||||
const runtime = await launchBrowser({ headless: true });
|
||||
try {
|
||||
const page = await runtime.browser.newPage();
|
||||
await page.evaluate(() => {
|
||||
// Install the otherwise undeclared probe consumed by the serialized measurement.
|
||||
const w = window as unknown as { __openideaPerf: unknown };
|
||||
w.__openideaPerf = {
|
||||
editorState: () => null,
|
||||
runAction: async () => true,
|
||||
};
|
||||
window.requestAnimationFrame = () => 0;
|
||||
});
|
||||
// The platform-clock boundary is the regression; a fake Node clock cannot drive Chromium.
|
||||
await expect(
|
||||
track(page, { action: "fixture.action", arg: null, first: () => false, done: () => false, timeoutMs: 20 }),
|
||||
).rejects.toThrow("page measurement timed out");
|
||||
} finally {
|
||||
await runtime.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
+145
-137
@@ -4,6 +4,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from
|
||||
import { chromium, type Browser, type BrowserContext, type Page } from "@playwright/test";
|
||||
import { createServer, type ViteDevServer } from "vite";
|
||||
import { Harness } from "./harness.ts";
|
||||
import { chromiumInstalled } from "./lifecycle.ts";
|
||||
import { installInPage } from "./inpage.ts";
|
||||
|
||||
let server: ViteDevServer;
|
||||
@@ -66,150 +67,157 @@ async function fixtureFile(text = "start\nend") {
|
||||
await h.setCursor(0);
|
||||
}
|
||||
|
||||
describe("current-operation UI measurements", () => {
|
||||
it("observes startup without input, but rejects pre-existing DOM even after a no-op key", async () => {
|
||||
expect(await h.inPage((p) => p.waitShown("#result", "ready", 500))).toBeGreaterThanOrEqual(0);
|
||||
await expect(h.measure(async () => {}, "#result", "ready", 80)).rejects.toThrow("timed out");
|
||||
await expect(
|
||||
h.measure(
|
||||
() =>
|
||||
page.evaluate(() => {
|
||||
document.querySelector("#result")!.textContent = "ready before input";
|
||||
}),
|
||||
"#result",
|
||||
"ready",
|
||||
80,
|
||||
),
|
||||
).rejects.toThrow("timed out");
|
||||
await expect(
|
||||
h.measure(
|
||||
// Another channel (OPENIDEA_PERF_CHANNEL=chrome) is the installed browser itself.
|
||||
describe.skipIf(!chromiumInstalled(false) && !process.env.OPENIDEA_PERF_CHANNEL)(
|
||||
"current-operation UI measurements",
|
||||
() => {
|
||||
it("observes startup without input, but rejects pre-existing DOM even after a no-op key", async () => {
|
||||
expect(await h.inPage((p) => p.waitShown("#result", "ready", 500))).toBeGreaterThanOrEqual(0);
|
||||
await expect(h.measure(async () => {}, "#result", "ready", 80)).rejects.toThrow("timed out");
|
||||
await expect(
|
||||
h.measure(
|
||||
() =>
|
||||
page.evaluate(() => {
|
||||
document.querySelector("#result")!.textContent = "ready before input";
|
||||
}),
|
||||
"#result",
|
||||
"ready",
|
||||
80,
|
||||
),
|
||||
).rejects.toThrow("timed out");
|
||||
await expect(
|
||||
h.measure(
|
||||
async () => {
|
||||
await page.evaluate(() => {
|
||||
document.querySelector("#result")!.textContent = "ready changed before input";
|
||||
});
|
||||
await page.keyboard.press("Shift");
|
||||
},
|
||||
"#result",
|
||||
"ready",
|
||||
80,
|
||||
),
|
||||
).rejects.toThrow("timed out");
|
||||
await expect(h.measure(() => page.keyboard.press("Shift"), "#result", "ready", 80)).rejects.toThrow("timed out");
|
||||
});
|
||||
|
||||
it("waits for input and the resulting target change, not an earlier frame", async () => {
|
||||
let changedAt = 0;
|
||||
const result = h.measure(
|
||||
async () => {
|
||||
await page.evaluate(() => {
|
||||
document.querySelector("#result")!.textContent = "ready changed before input";
|
||||
await h.inPage((p) => p.afterNextPaint());
|
||||
await page.keyboard.press("a");
|
||||
await h.inPage((p) => p.afterNextPaint());
|
||||
changedAt = await page.evaluate(() => {
|
||||
document.querySelector("#result")!.textContent = "ready now";
|
||||
return performance.now();
|
||||
});
|
||||
await page.keyboard.press("Shift");
|
||||
},
|
||||
"#result",
|
||||
"ready",
|
||||
80,
|
||||
),
|
||||
).rejects.toThrow("timed out");
|
||||
await expect(h.measure(() => page.keyboard.press("Shift"), "#result", "ready", 80)).rejects.toThrow("timed out");
|
||||
});
|
||||
|
||||
it("waits for input and the resulting target change, not an earlier frame", async () => {
|
||||
let changedAt = 0;
|
||||
const result = h.measure(
|
||||
async () => {
|
||||
await h.inPage((p) => p.afterNextPaint());
|
||||
await page.keyboard.press("a");
|
||||
await h.inPage((p) => p.afterNextPaint());
|
||||
changedAt = await page.evaluate(() => {
|
||||
document.querySelector("#result")!.textContent = "ready now";
|
||||
return performance.now();
|
||||
});
|
||||
},
|
||||
"#result",
|
||||
"ready",
|
||||
1_000,
|
||||
);
|
||||
const latency = await result;
|
||||
expect((await h.inPage((p) => p.lastInput)) + latency).toBeGreaterThanOrEqual(changedAt);
|
||||
});
|
||||
|
||||
it("propagates trigger failure and cancels its waiter without browser rejection", async () => {
|
||||
const errors: string[] = [];
|
||||
page.on("pageerror", (error) => errors.push(error.message));
|
||||
await expect(
|
||||
h.measure(
|
||||
async () => {
|
||||
throw new Error("trigger failed");
|
||||
},
|
||||
"#missing",
|
||||
null,
|
||||
80,
|
||||
),
|
||||
).rejects.toThrow("trigger failed");
|
||||
await expect(h.measure(async () => false, "#missing", null, 80)).rejects.toThrow("returned false");
|
||||
await h.inPage(async (p) => {
|
||||
await p.afterNextPaint();
|
||||
await p.afterNextPaint();
|
||||
1_000,
|
||||
);
|
||||
const latency = await result;
|
||||
expect((await h.inPage((p) => p.lastInput)) + latency).toBeGreaterThanOrEqual(changedAt);
|
||||
});
|
||||
expect(errors).toEqual([]);
|
||||
expect(await h.inPage((p) => p.waitShown("#result", "ready", 80))).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
|
||||
it.each(["ignoreOpen", "wrongContents"])("requires the requested path and seeded contents with %s", async (fault) => {
|
||||
await fixtureFile();
|
||||
await mode(fault);
|
||||
await expect(h.openFile("/two/Same.ts", "different", 100)).rejects.toThrow("requested editor");
|
||||
});
|
||||
|
||||
it("does not finish before the open action succeeds, even with matching existing contents", async () => {
|
||||
await fixtureFile();
|
||||
await mode("delayOpen");
|
||||
let completed = false;
|
||||
const opening = h.openFile("/one/Same.ts", "start\nend").finally(() => {
|
||||
completed = true;
|
||||
});
|
||||
await page.waitForFunction(() => "__releaseOpen" in window);
|
||||
try {
|
||||
await h.inPage((p) => p.afterNextPaint());
|
||||
expect(completed).toBe(false);
|
||||
} finally {
|
||||
await page.evaluate(() => {
|
||||
if (!("__releaseOpen" in window) || typeof window.__releaseOpen !== "function")
|
||||
throw new Error("open action was not held");
|
||||
window.__releaseOpen();
|
||||
it("propagates trigger failure and cancels its waiter without browser rejection", async () => {
|
||||
const errors: string[] = [];
|
||||
page.on("pageerror", (error) => errors.push(error.message));
|
||||
await expect(
|
||||
h.measure(
|
||||
async () => {
|
||||
throw new Error("trigger failed");
|
||||
},
|
||||
"#missing",
|
||||
null,
|
||||
80,
|
||||
),
|
||||
).rejects.toThrow("trigger failed");
|
||||
await expect(h.measure(async () => false, "#missing", null, 80)).rejects.toThrow("returned false");
|
||||
await h.inPage(async (p) => {
|
||||
await p.afterNextPaint();
|
||||
await p.afterNextPaint();
|
||||
});
|
||||
await opening;
|
||||
}
|
||||
});
|
||||
|
||||
it("awaits the open action and rejects failed actions even with a matching editor", async () => {
|
||||
await fixtureFile();
|
||||
await mode("rejectOpen");
|
||||
await expect(h.openFile("/one/Same.ts")).rejects.toThrow("open failed");
|
||||
});
|
||||
|
||||
it("measures real typing, including automatic brackets, indentation and backspace", async () => {
|
||||
await fixtureFile("function f() {\n}\n");
|
||||
await h.setCursor(14);
|
||||
expect(await h.typeMeasured("const n = (1 + 2);\n\b", 0)).toHaveLength(20);
|
||||
});
|
||||
|
||||
it.each(["swallowTyping", "wrongCaret", "missingSample", "wrongFocus"])("rejects typing with %s", async (fault) => {
|
||||
await fixtureFile();
|
||||
if (fault === "wrongFocus") await page.locator("#other").click();
|
||||
else await mode(fault);
|
||||
await expect(h.typeMeasured("x", 0)).rejects.toThrow(/typing|caret|sample|focus/);
|
||||
});
|
||||
|
||||
it("checks the whole document after bounded per-key observations", async () => {
|
||||
await fixtureFile("start\n" + "unchanged\n".repeat(200) + "end");
|
||||
expect(await h.typeMeasured("ok", 0)).toHaveLength(2);
|
||||
await mode("mutateDistant");
|
||||
await expect(h.typeMeasured("x", 0)).rejects.toThrow("outside the intended insertion");
|
||||
});
|
||||
|
||||
it("requires both cursor destination and viewport displacement for the jump", async () => {
|
||||
await fixtureFile(Array.from({ length: 1_000 }, (_, i) => `export class Repository${i} {}`).join("\n"));
|
||||
await mode("disableJump");
|
||||
await expect(h.jumpToEnd(100)).rejects.toThrow("timed out");
|
||||
await page.evaluate(() => {
|
||||
const w = window as unknown as { __fixture: Record<string, boolean> };
|
||||
w.__fixture.disableJump = false;
|
||||
expect(errors).toEqual([]);
|
||||
expect(await h.inPage((p) => p.waitShown("#result", "ready", 80))).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
expect(await h.jumpToEnd(1_000)).toBeGreaterThanOrEqual(0);
|
||||
expect((await h.editorState())!.head).toBe((await h.editorState())!.length);
|
||||
});
|
||||
|
||||
it("requires each completion arrow to advance exactly one selected item", async () => {
|
||||
await fixtureFile("");
|
||||
await h.measure(() => page.keyboard.press("g"), ".cm-tooltip-autocomplete li", "getOrder", 2_000);
|
||||
await page.waitForSelector('.cm-tooltip-autocomplete li[aria-selected="true"]');
|
||||
expect(await h.completionArrowsMeasured(3, 0)).toHaveLength(3);
|
||||
await mode("disableArrows");
|
||||
await expect(h.completionArrowsMeasured(1, 0)).rejects.toThrow("completion selection");
|
||||
});
|
||||
});
|
||||
it.each(["ignoreOpen", "wrongContents"])(
|
||||
"requires the requested path and seeded contents with %s",
|
||||
async (fault) => {
|
||||
await fixtureFile();
|
||||
await mode(fault);
|
||||
await expect(h.openFile("/two/Same.ts", "different", 100)).rejects.toThrow("requested editor");
|
||||
},
|
||||
);
|
||||
|
||||
it("does not finish before the open action succeeds, even with matching existing contents", async () => {
|
||||
await fixtureFile();
|
||||
await mode("delayOpen");
|
||||
let completed = false;
|
||||
const opening = h.openFile("/one/Same.ts", "start\nend").finally(() => {
|
||||
completed = true;
|
||||
});
|
||||
await page.waitForFunction(() => "__releaseOpen" in window);
|
||||
try {
|
||||
await h.inPage((p) => p.afterNextPaint());
|
||||
expect(completed).toBe(false);
|
||||
} finally {
|
||||
await page.evaluate(() => {
|
||||
if (!("__releaseOpen" in window) || typeof window.__releaseOpen !== "function")
|
||||
throw new Error("open action was not held");
|
||||
window.__releaseOpen();
|
||||
});
|
||||
await opening;
|
||||
}
|
||||
});
|
||||
|
||||
it("awaits the open action and rejects failed actions even with a matching editor", async () => {
|
||||
await fixtureFile();
|
||||
await mode("rejectOpen");
|
||||
await expect(h.openFile("/one/Same.ts")).rejects.toThrow("open failed");
|
||||
});
|
||||
|
||||
it("measures real typing, including automatic brackets, indentation and backspace", async () => {
|
||||
await fixtureFile("function f() {\n}\n");
|
||||
await h.setCursor(14);
|
||||
expect(await h.typeMeasured("const n = (1 + 2);\n\b", 0)).toHaveLength(20);
|
||||
});
|
||||
|
||||
it.each(["swallowTyping", "wrongCaret", "missingSample", "wrongFocus"])("rejects typing with %s", async (fault) => {
|
||||
await fixtureFile();
|
||||
if (fault === "wrongFocus") await page.locator("#other").click();
|
||||
else await mode(fault);
|
||||
await expect(h.typeMeasured("x", 0)).rejects.toThrow(/typing|caret|sample|focus/);
|
||||
});
|
||||
|
||||
it("checks the whole document after bounded per-key observations", async () => {
|
||||
await fixtureFile("start\n" + "unchanged\n".repeat(200) + "end");
|
||||
expect(await h.typeMeasured("ok", 0)).toHaveLength(2);
|
||||
await mode("mutateDistant");
|
||||
await expect(h.typeMeasured("x", 0)).rejects.toThrow("outside the intended insertion");
|
||||
});
|
||||
|
||||
it("requires both cursor destination and viewport displacement for the jump", async () => {
|
||||
await fixtureFile(Array.from({ length: 1_000 }, (_, i) => `export class Repository${i} {}`).join("\n"));
|
||||
await mode("disableJump");
|
||||
await expect(h.jumpToEnd(100)).rejects.toThrow("timed out");
|
||||
await page.evaluate(() => {
|
||||
const w = window as unknown as { __fixture: Record<string, boolean> };
|
||||
w.__fixture.disableJump = false;
|
||||
});
|
||||
expect(await h.jumpToEnd(1_000)).toBeGreaterThanOrEqual(0);
|
||||
expect((await h.editorState())!.head).toBe((await h.editorState())!.length);
|
||||
});
|
||||
|
||||
it("requires each completion arrow to advance exactly one selected item", async () => {
|
||||
await fixtureFile("");
|
||||
await h.measure(() => page.keyboard.press("g"), ".cm-tooltip-autocomplete li", "getOrder", 2_000);
|
||||
await page.waitForSelector('.cm-tooltip-autocomplete li[aria-selected="true"]');
|
||||
expect(await h.completionArrowsMeasured(3, 0)).toHaveLength(3);
|
||||
await mode("disableArrows");
|
||||
await expect(h.completionArrowsMeasured(1, 0)).rejects.toThrow("completion selection");
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -1,6 +1,6 @@
|
||||
// @vitest-environment node
|
||||
import { expect, test, vi } from "vitest";
|
||||
import { launchBrowser, withDeadline } from "./lifecycle.ts";
|
||||
import { chromiumInstalled, launchBrowser, withDeadline } from "./lifecycle.ts";
|
||||
|
||||
test("a deadline rejects an unanswered operation and releases its timer", async () => {
|
||||
vi.useFakeTimers();
|
||||
@@ -15,7 +15,7 @@ test("a deadline rejects an unanswered operation and releases its timer", async
|
||||
}
|
||||
});
|
||||
|
||||
test.each(["blocked renderer", "missing animation frames"])(
|
||||
test.skipIf(!chromiumInstalled(true)).each(["blocked renderer", "missing animation frames"])(
|
||||
"Node deadline survives %s and browser cleanup terminates it",
|
||||
{ timeout: 20_000 },
|
||||
async (mode) => {
|
||||
|
||||
@@ -1,6 +1,19 @@
|
||||
import { chromium, type Browser, type LaunchOptions } from "@playwright/test";
|
||||
import { existsSync } from "node:fs";
|
||||
import type { Server } from "node:http";
|
||||
|
||||
/**
|
||||
* Whether Playwright's Chromium is installed (`pnpm exec playwright install chromium`):
|
||||
* `headless` launches use its headless shell, the `chromium` channel the full browser.
|
||||
* Unit tests that drive a real browser skip without it, as in CI's Frontend job.
|
||||
*/
|
||||
export function chromiumInstalled(headless: boolean): boolean {
|
||||
const full = chromium.executablePath();
|
||||
if (!headless) return existsSync(full);
|
||||
const build = /^(.*[\\/])chromium-(\d+)[\\/]/.exec(full);
|
||||
return !!build && existsSync(`${build[1]}chromium_headless_shell-${build[2]}`);
|
||||
}
|
||||
|
||||
export class DeadlineError extends Error {
|
||||
constructor(label: string, timeoutMs: number) {
|
||||
super(`${label} timed out after ${timeoutMs} ms (wall clock)`);
|
||||
|
||||
@@ -193,7 +193,8 @@ describe("Rust trial lifecycle", () => {
|
||||
|
||||
it("keeps legacy inspection useful and reports artifact dates", async () => {
|
||||
const root = fixture();
|
||||
const date = new Date(Date.now() - 120_000);
|
||||
// Whole seconds: file times don't keep every millisecond on all file systems.
|
||||
const date = new Date(Math.floor((Date.now() - 120_000) / 1000) * 1000);
|
||||
artifacts(join(root, "target/criterion"), ["ide-text"], date);
|
||||
expect(await runRust({ root, packages: ["ide-text"], noRun: true })).toBe(0);
|
||||
const current = report(root);
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
32c888d5f7724d52cd5c46562f64cfab58cf9ec54c80e43638309fa85304e152
|
||||
dd2064150ef1e9a70c4f7c33e8f4396f131db951d9818eab5f854a7e9ce71e11
|
||||
@@ -1 +1 @@
|
||||
fc8d32f7b4d6d0cd2cf747c328f17f523475e3dfae8617db7435e9cd137b91ae
|
||||
d7233de85619c0a9479f4d6fbd87bc6105b9f72b7daacf701f2e1212a01b2768
|
||||
+1
-1
@@ -1 +1 @@
|
||||
9654a8eb4583b170c69359a581bb2a8c0476b7486c9dc0f4dea8a75ff63f018f
|
||||
396b7103d40247c6d1b489d0003a934374f27d9dffb9bcb33e7ae2811829ac31
|
||||
@@ -1 +1 @@
|
||||
4208f2136cf0811df94c42edd0c06fea12b2f9fd4d1a6250f7002d81ab8542d0
|
||||
2324da549433c9c88d67cfae6a0207716c5a61e41bb06648cc3b233a5fb7a41a
|
||||
+1
-1
@@ -1 +1 @@
|
||||
992ac6522f7294083aa6edf6c35cba2862129d917a9dafe55f630194873c7687
|
||||
8cd17db5f028d4c211f00af52ebc4408e0dd41d75f20e7cc5a6dcaec0b888c89
|
||||
+1
-1
@@ -1 +1 @@
|
||||
55adac462ebb73b453399e5493ee2aea4efea5c1e9470d601b2062e580177225
|
||||
862dfc0bbaa9ecb954727ba5586e083d6ae0aeae4f71af54df0675f3d8a2db29
|
||||
+1
-1
@@ -1 +1 @@
|
||||
586742d4b056ba631f66b7b1e38e26e7378aa9a0e213319ad46b8d3ba1789794
|
||||
c84b047226c6bed4ba0a0c851e16a37813945eb46fd4a5028c97a64d2a81411d
|
||||
+1
-1
@@ -1 +1 @@
|
||||
ccc598ac4c7dbad4bbc5355a09fb5b26d556bd7736a9541667aabd1fecd3d5d3
|
||||
400458a210f3d794787dece4d5c178bddf7af04a9bca141fa574d532ab669bc0
|
||||
@@ -1 +1 @@
|
||||
4fcaa47727482ae30a5b480cd83609759a976f48de7216651d08f6da01667212
|
||||
a1aa1d621b40c30b1252a7506a8c74e1eabd90abd40fff5a7b04028c7ac6811e
|
||||
+1
-1
@@ -1 +1 @@
|
||||
eadc5daa2eb67abaaf55a0f8d5efa6d1bf78006f768880d12e95c9d7d662b333
|
||||
841c9840b33a780ee29e04cf4fa79ed4dd7b30d428d3b90841fcd7eb059223ba
|
||||
+1
-1
@@ -1 +1 @@
|
||||
18431dce88b25566e463ff518c810e92c77d5df97998e1bc0a3c7d9f7ad99363
|
||||
31394076ed408e043633604e5ae46b519d259d3317b849f8a0f1d774935815ad
|
||||
+1
-1
@@ -1 +1 @@
|
||||
c9892ec85b11080ea1080f408e1f5f1558554e4488aee6467454b0e627512dcd
|
||||
1d5d4bb8502dec07b7ec420d57f627ffdb4f7126b6a5e5d2bcda77e222a8a680
|
||||
+1
-1
@@ -1 +1 @@
|
||||
d9e50c56321d2dbf8261754ce604842a38d61e57f7e52b7d3f66077776f9244b
|
||||
939e477e32de648ed96d634f040be546207504ea2d58a14cc480a0038f1f5c46
|
||||
+1
-1
@@ -1 +1 @@
|
||||
77d083fb8ed777715a98477d447b240ccd59db610251dfb1a103b6d2d8d0599e
|
||||
aa71bdd8d76b43cc103e61b870504ab4ebab9f4235b84736a8a63e26a962d527
|
||||
+1
-1
@@ -1 +1 @@
|
||||
b9d8c8a1d3d30d39ee0fc2b65ca0ce6e5a0520be772c99eafdec9c7785c4766b
|
||||
435187598694fd7e3a43bc40d2b1824d7e4631632b1da202db6d28b0fac867f2
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
Loaded 100 of 276 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user