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

..
Автор SHA1 Повідомлення Дата
l0ng-ai 34828bd710 fix(agents): Complete project skills and custom commands in the agent composer
The `/` completion of the New Task page only listed the commands the agent
offered in its last session, cached once for all projects, and matched them
by substring. Before a project's first session, or after a session in another
project, its skills were missing, and `/trig` never matched `/triage`.

- Remember the commands an agent offered per project root (settings stay shared).
- New `agent_commands` command: the agent's last list for the project (or the
  task's own list in a session) merged with, for Claude Code, the skills
  (`.claude/skills/*/SKILL.md`) and custom commands (`.claude/commands/**/*.md`,
  nested as `dir:name`) found from the working directory upward and in
  `~/.claude`. The agent's entries win on a name; skills with
  `user-invocable: false` are left out. Discovery runs off the command thread.
- Sessions discover from the task's own directory (worktree or checkout).
- Command matching ranks prefix, plugin-name prefix, substring, then letters in order.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 20:59:52 +08:00
26 змінених файлів з 644 додано та 821 видалено

No files matched your search

Створено
-1
Переглянути файл
@@ -4146,7 +4146,6 @@ dependencies = [
name = "ide-jsonrpc"
version = "0.1.17"
dependencies = [
"encoding_rs",
"futures",
"ide-core",
"parking_lot",
+56 -23
Переглянути файл
@@ -10,6 +10,7 @@
mod config;
mod model;
mod provider;
mod skills;
mod timeline;
mod worktree;
@@ -53,10 +54,12 @@ pub struct AgentPaths {
pub store_dir: PathBuf,
/// Parent of the tasks' worktrees.
pub worktrees_dir: PathBuf,
/// Settings and commands each agent offered last time (shared by all projects).
/// Settings each agent offered last time (shared by all projects), and its commands per project.
pub models_file: PathBuf,
/// User-defined agents, one `<id>.toml` each (`name`, `command`, `args`, `env`).
pub custom_agents_dir: Option<PathBuf>,
/// The user's home: its `.claude` holds their own skills and commands.
pub home_dir: Option<PathBuf>,
}
/// Starts the ACP server of a provider in a directory, speaking to `client`.
@@ -80,8 +83,9 @@ struct Shared {
struct Known {
#[serde(default)]
config: Vec<AgentConfigOption>,
#[serde(default)]
commands: Vec<AgentCommand>,
/// By project root: skills and custom commands differ per project.
#[serde(default, rename = "projectCommands")]
commands: HashMap<String, Vec<AgentCommand>>,
}
impl Shared {
@@ -96,8 +100,18 @@ impl Shared {
}
}
fn known(&self, provider: &str) -> Known {
self.known.lock().get(provider).cloned().unwrap_or_default()
fn known_config(&self, provider: &str) -> Vec<AgentConfigOption> {
self.known.lock().get(provider).map(|k| k.config.clone()).unwrap_or_default()
}
/// The commands the agent offered last time in this project.
fn known_commands(&self, provider: &str) -> Vec<AgentCommand> {
let cache = self.known.lock();
cache.get(provider).and_then(|k| k.commands.get(&self.root_key())).cloned().unwrap_or_default()
}
fn root_key(&self) -> String {
self.paths.project_root.to_string_lossy().into_owned()
}
fn remember(&self, provider: &str, config: Option<&[AgentConfigOption]>, commands: Option<&[AgentCommand]>) {
@@ -109,8 +123,11 @@ impl Shared {
known.config = c.to_vec();
changed = true;
}
if let Some(c) = commands.filter(|c| !c.is_empty() && known.commands != *c) {
known.commands = c.to_vec();
let root = self.root_key();
if let Some(c) =
commands.filter(|c| !c.is_empty() && known.commands.get(&root).map(Vec::as_slice) != Some(c))
{
known.commands.insert(root, c.to_vec());
changed = true;
}
if !changed {
@@ -238,25 +255,42 @@ impl AgentManager {
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref());
let list = specs
.iter()
.map(|p| {
let known = self.shared.known(&p.id);
AgentProvider {
id: p.id.clone(),
name: p.name.clone(),
command: std::iter::once(p.command.as_str())
.chain(p.args.iter().map(String::as_str))
.collect::<Vec<_>>()
.join(" "),
installed: provider::installed(&p.command),
config: known.config,
commands: known.commands,
}
.map(|p| AgentProvider {
id: p.id.clone(),
name: p.name.clone(),
command: std::iter::once(p.command.as_str())
.chain(p.args.iter().map(String::as_str))
.collect::<Vec<_>>()
.join(" "),
installed: provider::installed(&p.command),
config: self.shared.known_config(&p.id),
commands: self.shared.known_commands(&p.id),
})
.collect();
*self.shared.providers.write() = specs;
list
}
/// The slash commands to complete for `provider`, in `task`'s directory or (without one)
/// in the project: what the agent offered last time there, plus, for Claude Code, the
/// skills and custom commands on disk it has not listed.
pub async fn commands(&self, provider: &str, task: Option<&str>) -> IdeResult<Vec<AgentCommand>> {
let (provider, offered, cwd) = match task {
Some(id) => {
let task = self.task(id)?;
let s = task.state.lock();
(s.task.provider.clone(), s.task.commands.clone(), s.task.cwd.0.clone())
}
None => (provider.to_owned(), self.shared.known_commands(provider), self.shared.paths.project_root.clone()),
};
if provider != "claude" {
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))
}
fn task(&self, id: &str) -> IdeResult<Arc<Task>> {
self.tasks.read().get(id).cloned().ok_or_else(|| IdeError::not_found(format!("no agent task {id}")))
}
@@ -289,8 +323,7 @@ impl AgentManager {
}
};
// Until the session reports its own, show what the agent offered last time with the choices applied.
let known = self.shared.known(&spec.id);
let mut config = known.config;
let mut config = self.shared.known_config(&spec.id);
for choice in &req.config {
if let Some(o) = config.iter_mut().find(|o| o.id == choice.id) {
o.current = Some(choice.value.clone());
@@ -312,7 +345,7 @@ impl AgentManager {
created_ms: now,
updated_ms: now,
config,
commands: known.commands,
commands: self.shared.known_commands(&spec.id),
usage: None,
queue: Vec::new(),
};
+281
Переглянути файл
@@ -0,0 +1,281 @@
//! 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`.
use crate::AgentCommand;
use std::collections::HashSet;
use std::path::Path;
const MAX_DESCRIPTION: usize = 200;
/// Command directories nest this deep at most (`a/b/c.md` → `a:b:c`).
const MAX_DEPTH: usize = 4;
/// The commands Claude Code finds from `cwd`: nearest directory first, the user's last;
/// the first of a name wins.
pub(crate) fn discover(cwd: &Path, home: Option<&Path>) -> Vec<AgentCommand> {
let mut out = Vec::new();
let mut seen = HashSet::new();
let mut add = |found: Vec<AgentCommand>| {
for c in found {
if seen.insert(c.name.clone()) {
out.push(c);
}
}
};
for dir in cwd.ancestors() {
if home.is_some_and(|h| h == dir) {
break;
}
add(in_dir(&dir.join(".claude")));
}
if let Some(home) = home {
add(in_dir(&home.join(".claude")));
}
out
}
/// `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 names: HashSet<String> = first.iter().map(|c| c.name.clone()).collect();
let mut out = first;
out.extend(more.into_iter().filter(|c| !names.contains(&c.name)));
out
}
fn in_dir(claude: &Path) -> Vec<AgentCommand> {
if !claude.is_dir() {
return Vec::new();
}
let mut out = skills(&claude.join("skills"));
commands(&claude.join("commands"), "", 0, &mut out);
out
}
fn skills(dir: &Path) -> Vec<AgentCommand> {
let mut out: Vec<AgentCommand> = sorted(dir)
.into_iter()
.filter_map(|path| {
let text = std::fs::read_to_string(path.join("SKILL.md")).ok()?;
let meta = Frontmatter::parse(&text);
if meta.get("user-invocable").is_some_and(|v| v.eq_ignore_ascii_case("false")) {
return None;
}
let name = meta.get("name").filter(|n| !n.is_empty()).map(str::to_owned).or_else(|| file_name(&path))?;
Some(meta.command(name, &text))
})
.collect();
out.sort_by(|a, b| a.name.cmp(&b.name));
out
}
fn commands(dir: &Path, prefix: &str, depth: usize, out: &mut Vec<AgentCommand>) {
if depth > MAX_DEPTH {
return;
}
for path in sorted(dir) {
let Some(name) = file_name(&path) else { continue };
if path.is_dir() {
commands(&path, &format!("{prefix}{name}:"), depth + 1, out);
} else if let Some(stem) = name.strip_suffix(".md")
&& let Ok(text) = std::fs::read_to_string(&path)
{
out.push(Frontmatter::parse(&text).command(format!("{prefix}{stem}"), &text));
}
}
}
fn sorted(dir: &Path) -> Vec<std::path::PathBuf> {
let mut paths: Vec<_> = std::fs::read_dir(dir)
.into_iter()
.flatten()
.flatten()
.map(|e| e.path())
.filter(|p| file_name(p).is_some_and(|n| !n.starts_with('.')))
.collect();
paths.sort();
paths
}
fn file_name(path: &Path) -> Option<String> {
path.file_name()?.to_str().map(str::to_owned)
}
/// The `key: value` lines between the leading `---` fences (folded `>` / `|` values joined).
struct Frontmatter {
fields: Vec<(String, String)>,
/// Where the body starts.
body: usize,
}
impl Frontmatter {
fn parse(text: &str) -> Self {
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
let mut lines = text.split_inclusive('\n');
let mut offset = 0;
let mut fields: Vec<(String, String)> = Vec::new();
match lines.next() {
Some(first) if first.trim_end() == "---" => offset += first.len(),
_ => return Self { fields, body: 0 },
}
for line in lines {
offset += line.len();
let line = line.trim_end();
if line == "---" {
return Self { fields, body: offset };
}
if line.starts_with([' ', '\t']) {
if let Some((_, value)) = fields.last_mut() {
if !value.is_empty() {
value.push(' ');
}
value.push_str(line.trim());
}
continue;
}
if let Some((key, value)) = line.split_once(':') {
let value = value.trim();
let value = if matches!(value, ">" | "|" | ">-" | "|-") { "" } else { unquote(value) };
fields.push((key.trim().to_owned(), value.to_owned()));
}
}
// No closing fence: not frontmatter.
Self { fields: Vec::new(), body: 0 }
}
fn get(&self, key: &str) -> Option<&str> {
self.fields.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str())
}
/// `description`, else the body's first line.
fn command(&self, name: String, text: &str) -> AgentCommand {
let description = self.get("description").filter(|d| !d.is_empty()).map(str::to_owned).unwrap_or_else(|| {
let body = text.get(self.body..).unwrap_or_default();
body.lines()
.map(|l| l.trim().trim_start_matches('#').trim())
.find(|l| !l.is_empty())
.unwrap_or_default()
.to_owned()
});
AgentCommand {
name,
description: truncate(&description),
hint: self.get("argument-hint").filter(|h| !h.is_empty()).map(str::to_owned),
}
}
}
fn unquote(value: &str) -> &str {
for q in ['"', '\''] {
if let Some(inner) = value.strip_prefix(q).and_then(|v| v.strip_suffix(q)) {
return inner;
}
}
value
}
fn truncate(s: &str) -> String {
match s.char_indices().nth(MAX_DESCRIPTION) {
Some((i, _)) => format!("{}…", s[..i].trim_end()),
None => s.to_owned(),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn write(path: &Path, text: &str) {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
fn names(cmds: &[AgentCommand]) -> Vec<&str> {
cmds.iter().map(|c| c.name.as_str()).collect()
}
fn cmd(name: &str, description: &str) -> AgentCommand {
AgentCommand { name: name.into(), description: description.into(), hint: None }
}
#[test]
fn project_and_user_skills_and_commands() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
let repo = tmp.path().join("work").join("idea");
let skills = repo.join(".claude/skills");
write(
&skills.join("triage/SKILL.md"),
"---\nname: triage\ndescription: One pass over open issues and PRs\n---\n# Triage\n",
);
write(&skills.join("issue-fix/SKILL.md"), "---\nname: issue-fix\ndescription: \"Fix an issue\"\n---\n");
// No frontmatter name: the directory's.
write(&skills.join("verify/SKILL.md"), "---\ndescription: >\n Build and\n drive the app\n---\n");
write(&skills.join("hidden/SKILL.md"), "---\nname: hidden\nuser-invocable: false\n---\n");
write(&skills.join("no-skill-file/README.md"), "nothing");
write(&repo.join(".claude/commands/review.md"), "---\nargument-hint: <pr>\n---\nReview a pull request\n");
write(&repo.join(".claude/commands/git/commit.md"), "# Commit the staged changes\n");
// A parent directory's commands apply too.
write(&tmp.path().join("work/.claude/commands/parent.md"), "---\ndescription: from above\n---\n");
// The user's: shadowed by the project's skill of the same name.
write(&home.join(".claude/skills/triage/SKILL.md"), "---\nname: triage\ndescription: user triage\n---\n");
write(&home.join(".claude/skills/lint/SKILL.md"), "---\nname: lint\ndescription: user lint\n---\n");
write(&home.join(".claude/commands/brooks-review.md"), "---\ndescription: Review\n---\n");
let found = discover(&repo, Some(&home));
assert_eq!(
names(&found),
["issue-fix", "triage", "verify", "git:commit", "review", "parent", "lint", "brooks-review"]
);
let by = |n: &str| found.iter().find(|c| c.name == n).unwrap();
assert_eq!(by("triage").description, "One pass over open issues and PRs");
assert_eq!(by("issue-fix").description, "Fix an issue");
assert_eq!(by("verify").description, "Build and drive the app");
assert_eq!(by("git:commit").description, "Commit the staged changes");
assert_eq!(
(by("review").description.as_str(), by("review").hint.as_deref()),
("Review a pull request", Some("<pr>"))
);
}
#[test]
fn nothing_without_claude_dirs() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
let repo = home.join("plain");
std::fs::create_dir_all(&repo).unwrap();
assert!(discover(&repo, Some(&home)).is_empty());
}
#[test]
fn walking_up_stops_at_home() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
// Above home: not the user's, and not this project's.
write(&tmp.path().join(".claude/commands/outside.md"), "x\n");
write(&home.join(".claude/commands/mine.md"), "x\n");
let repo = home.join("src/app");
std::fs::create_dir_all(&repo).unwrap();
assert_eq!(names(&discover(&repo, Some(&home))), ["mine"]);
}
#[test]
fn the_agents_entries_win() {
let merged = merge(
vec![cmd("triage", "from the agent"), cmd("compact", "Compact")],
vec![cmd("triage", "from disk"), cmd("verify", "Verify")],
);
assert_eq!(names(&merged), ["triage", "compact", "verify"]);
assert_eq!(merged[0].description, "from the agent");
}
#[test]
fn frontmatter_edge_cases() {
let f = Frontmatter::parse("no fence\n");
assert!(f.fields.is_empty());
let f = Frontmatter::parse("---\nname: x\nunterminated\n");
assert!(f.get("name").is_none());
let f = Frontmatter::parse("\u{feff}---\r\nname: 'quoted'\r\n---\r\nbody\r\n");
assert_eq!(f.get("name"), Some("quoted"));
assert_eq!(truncate(&"é".repeat(MAX_DESCRIPTION + 5)).chars().count(), MAX_DESCRIPTION + 1);
}
}
+49 -1
Переглянути файл
@@ -93,6 +93,10 @@ impl Handler for FakeAgent {
}
fn manager(dir: &Path, agent: Arc<FakeAgent>) -> AgentManager {
manager_at(dir, &dir.join("models.json"), agent)
}
fn manager_at(dir: &Path, models_file: &Path, agent: Arc<FakeAgent>) -> AgentManager {
let connector: Connector = Arc::new(move |_spec, _cwd, client, _stderr| {
let (a, b) = duplex(1 << 20);
let (ar, aw) = tokio::io::split(a);
@@ -107,14 +111,54 @@ fn manager(dir: &Path, agent: Arc<FakeAgent>) -> AgentManager {
project_root: dir.to_path_buf(),
store_dir: dir.join("store"),
worktrees_dir: dir.join("worktrees"),
models_file: dir.join("models.json"),
models_file: models_file.to_path_buf(),
custom_agents_dir: None,
home_dir: None,
},
tokio::runtime::Handle::current(),
connector,
)
}
#[tokio::test(flavor = "multi_thread")]
async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
let tmp = tempfile::tempdir().unwrap();
let (a, b, models) = (tmp.path().join("a"), tmp.path().join("b"), tmp.path().join("models.json"));
std::fs::create_dir_all(a.join(".claude/skills/triage")).unwrap();
std::fs::create_dir_all(&b).unwrap();
std::fs::write(a.join(".claude/skills/triage/SKILL.md"), "---\nname: triage\ndescription: Triage\n---\n").unwrap();
let names = |c: Vec<AgentCommand>| c.into_iter().map(|c| c.name).collect::<Vec<_>>();
let mgr_a = manager_at(&a, &models, Arc::new(FakeAgent::default()));
// Before any session: the skills on disk.
assert_eq!(names(mgr_a.commands("claude", None).await.unwrap()), ["triage"]);
let task = mgr_a
.create(NewAgentTask {
prompt: text("Fix the lexer"),
provider: "claude".into(),
config: Vec::new(),
isolation: Isolation::Local,
base: None,
})
.await
.unwrap();
wait_for(&mgr_a, &task.id, AgentStatus::NeedsInput).await;
assert_eq!(names(mgr_a.commands("claude", None).await.unwrap()), ["review", "triage"]);
assert_eq!(names(mgr_a.commands("claude", Some(&task.id)).await.unwrap()), ["review", "triage"]);
// Other agents get only what they offered.
assert!(mgr_a.commands("codex", None).await.unwrap().is_empty());
mgr_a.shutdown();
// Another project shares the settings but not the commands.
let mgr_b = manager_at(&b, &models, Arc::new(FakeAgent::default()));
let claude = mgr_b.providers().into_iter().find(|p| p.id == "claude").unwrap();
assert_eq!(claude.config.len(), 2);
assert!(claude.commands.is_empty());
assert!(mgr_b.commands("claude", None).await.unwrap().is_empty());
let mgr_a = manager_at(&a, &models, Arc::new(FakeAgent::default()));
assert_eq!(names(mgr_a.providers().into_iter().find(|p| p.id == "claude").unwrap().commands), ["review"]);
}
async fn wait_for(mgr: &AgentManager, id: &str, status: AgentStatus) {
for _ in 0..500 {
if mgr.task(id).unwrap().state.lock().task.status == status {
@@ -299,6 +343,9 @@ fn prompts_become_acp_content_blocks() {
blocks(&p, &[Some("fn a() {}".into())])[1],
json!({"type": "resource", "resource": {"uri": "file:///p/my%20file.rs", "text": "fn a() {}"}})
);
// A slash command goes through as typed: the agent runs it.
let skill = clean(text(" /triage dry-run\n")).unwrap();
assert_eq!(blocks(&skill, &[]), [json!({"type": "text", "text": "/triage dry-run"})]);
let old = upgrade(
json!({"task": {"id": "t"}, "entries": [{"type": "user", "text": "hi"}, {"type": "agent", "text": "a"}]}),
);
@@ -375,6 +422,7 @@ async fn real_claude_task_in_a_worktree() {
worktrees_dir: tmp.path().join("wt"),
models_file: tmp.path().join("models.json"),
custom_agents_dir: None,
home_dir: None,
},
tokio::runtime::Handle::current(),
);
+12 -14
Переглянути файл
@@ -14,7 +14,7 @@ use std::pin::Pin;
use std::process::Stdio;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, BufReader};
use tokio::process::{Child, Command};
pub const PORT_PLACEHOLDER: &str = "${port}";
@@ -457,19 +457,17 @@ fn pump_lines<R: AsyncRead + Unpin + Send + 'static>(
name: String,
sink: Arc<parking_lot::Mutex<Vec<String>>>,
) {
tokio::spawn(ide_jsonrpc::output::read_lines(stream, move |line| {
tracing::debug!(target: "ide_dap::adapter", "[{name}] {line}");
push_line(&sink, line);
}));
}
/// Appends to the recent-output buffer of an adapter (the last 40 lines).
pub(crate) fn push_line(sink: &parking_lot::Mutex<Vec<String>>, line: String) {
let mut buf = sink.lock();
if buf.len() >= 40 {
buf.remove(0);
}
buf.push(line);
tokio::spawn(async move {
let mut lines = BufReader::new(stream).lines();
while let Ok(Some(line)) = lines.next_line().await {
tracing::debug!(target: "ide_dap::adapter", "[{name}] {line}");
let mut buf = sink.lock();
if buf.len() >= 40 {
buf.remove(0);
}
buf.push(line);
}
});
}
const LOOPBACK: &str = "127.0.0.1";
+2 -21
Переглянути файл
@@ -95,21 +95,7 @@ pub struct Connection {
impl Connection {
/// Starts reader/writer tasks over `reader`/`writer`. Must be called inside a Tokio runtime.
pub fn start<R, W>(reader: R, writer: W) -> (Self, mpsc::UnboundedReceiver<Incoming>)
where
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
{
Self::start_with_output(reader, writer, Box::new(|_| {}))
}
/// [`start`](Self::start) that hands lines outside the protocol (an adapter's
/// own output on stdout, decoded) to `on_output`.
pub fn start_with_output<R, W>(
reader: R,
mut writer: W,
on_output: Box<dyn Fn(String) + Send + Sync>,
) -> (Self, mpsc::UnboundedReceiver<Incoming>)
pub fn start<R, W>(reader: R, mut writer: W) -> (Self, mpsc::UnboundedReceiver<Incoming>)
where
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
@@ -147,14 +133,9 @@ impl Connection {
let reader_inner = inner.clone();
tokio::spawn(async move {
let mut reader = BufReader::new(reader);
let mut noise = |line: &[u8]| {
let text = ide_jsonrpc::output::decode(line);
tracing::warn!("dap: output outside the protocol: {text}");
on_output(text);
};
loop {
let msg = tokio::select! {
msg = framing::read_message_or_noise(&mut reader, &mut noise) => msg,
msg = framing::read_message(&mut reader) => msg,
_ = reader_inner.cancel.cancelled() => break,
};
match msg {
+1 -4
Переглянути файл
@@ -681,10 +681,7 @@ impl DebugManager {
}
let io = self.launcher.launch(spec.clone(), reuse_port).await?;
let stderr = io.stderr.clone();
let (conn, incoming) = {
let stderr = stderr.clone();
Connection::start_with_output(io.reader, io.writer, Box::new(move |line| adapter::push_line(&stderr, line)))
};
let (conn, incoming) = Connection::start(io.reader, io.writer);
let session =
Arc::new(Session::new(id, owner, name, adapter_name, parent, request, conn, spec, io.port, io.child));
self.sessions.lock().insert(id, session.clone());
-1
Переглянути файл
@@ -15,4 +15,3 @@ futures.workspace = true
parking_lot.workspace = true
thiserror.workspace = true
tracing.workspace = true
encoding_rs.workspace = true
+46 -112
Переглянути файл
@@ -6,10 +6,7 @@
//! * [`Peer`]: a JSON-RPC 2.0 endpoint with request/response correlation,
//! cancellation (`$/cancelRequest`) and handlers for server→client traffic.
pub mod output;
pub mod framing {
use crate::output::trim_line_end as trim_line;
use std::io::{Error, ErrorKind};
use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncReadExt, AsyncWrite, AsyncWriteExt};
@@ -24,19 +21,6 @@ pub mod framing {
/// matched case-insensitively, unknown headers (e.g. `Content-Type`) are
/// ignored, and both `\r\n` and bare `\n` line endings are accepted.
pub async fn read_message<R: AsyncBufRead + Unpin>(reader: &mut R) -> std::io::Result<Option<Vec<u8>>> {
read_message_or_noise(reader, &mut |line| {
tracing::warn!("jsonrpc: ignoring output outside the protocol: {}", crate::output::decode(line));
})
.await
}
/// [`read_message`] that hands lines which can't start a message header (a
/// launcher's or runtime's own output on stdout, in any encoding) to `on_noise`
/// and skips them, instead of failing on them.
pub async fn read_message_or_noise<R: AsyncBufRead + Unpin>(
reader: &mut R,
on_noise: &mut (dyn FnMut(&[u8]) + Send),
) -> std::io::Result<Option<Vec<u8>>> {
let mut content_length: Option<usize> = None;
let mut saw_any = false;
let mut line = Vec::with_capacity(64);
@@ -53,11 +37,6 @@ pub mod framing {
if n as u64 >= MAX_HEADER_LINE {
return Err(Error::new(ErrorKind::InvalidData, "header line too long"));
}
if !saw_any && header(&line).is_none() {
// Output without a final newline, then EOF (`pause` waiting for a key).
on_noise(trim_line(&line));
return Ok(None);
}
return Err(Error::new(ErrorKind::UnexpectedEof, "EOF inside message header"));
}
let text = trim_line(&line);
@@ -71,18 +50,12 @@ pub mod framing {
// Tolerate stray blank lines between messages.
continue;
}
let Some((name, value)) = header(text) else {
if !saw_any {
on_noise(text);
continue;
}
return Err(Error::new(
ErrorKind::InvalidData,
format!("malformed header line: {:?}", crate::output::decode(text)),
));
};
saw_any = true;
if name.eq_ignore_ascii_case("content-length") {
let text = std::str::from_utf8(text).map_err(|_| Error::new(ErrorKind::InvalidData, "non-UTF-8 header"))?;
let Some((name, value)) = text.split_once(':') else {
return Err(Error::new(ErrorKind::InvalidData, format!("malformed header line: {text:?}")));
};
if name.trim().eq_ignore_ascii_case("content-length") {
let len: usize = value
.trim()
.parse()
@@ -99,12 +72,12 @@ pub mod framing {
Ok(Some(body))
}
/// `name: value` with a header-like name (a token, no spaces), else `None`.
fn header(line: &[u8]) -> Option<(&str, &str)> {
let text = std::str::from_utf8(trim_line(line)).ok()?;
let (name, value) = text.split_once(':')?;
let token = !name.is_empty() && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
token.then_some((name, value))
fn trim_line(line: &[u8]) -> &[u8] {
let mut end = line.len();
while end > 0 && matches!(line[end - 1], b'\n' | b'\r') {
end -= 1;
}
&line[..end]
}
/// Writes one framed message and flushes once.
@@ -153,7 +126,7 @@ use serde_json::{Value, json};
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
use tokio::io::{AsyncRead, AsyncWrite, BufReader};
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, BufReader};
use tokio::sync::{mpsc, oneshot, watch};
use tokio_util::sync::CancellationToken;
@@ -232,8 +205,6 @@ struct Inner {
/// Fired by [`Peer::kill`]; stops tasks and kills the child.
kill: CancellationToken,
pid: Option<u32>,
/// Fired when the reader task has stopped (EOF, error or kill).
reader_done: CancellationToken,
}
impl Inner {
@@ -279,20 +250,10 @@ pub enum Framing {
}
impl Framing {
async fn read<R: tokio::io::AsyncBufRead + Unpin>(
self,
reader: &mut R,
on_noise: &mut (dyn FnMut(&[u8]) + Send),
) -> std::io::Result<Option<Vec<u8>>> {
async fn read<R: tokio::io::AsyncBufRead + Unpin>(self, reader: &mut R) -> std::io::Result<Option<Vec<u8>>> {
match self {
Framing::ContentLength => framing::read_message_or_noise(reader, on_noise).await,
Framing::Lines => loop {
let Some(line) = framing::read_line_message(reader).await? else { return Ok(None) };
match line.iter().find(|b| !b.is_ascii_whitespace()) {
Some(b'{' | b'[') => return Ok(Some(line)),
_ => on_noise(&line),
}
},
Framing::ContentLength => framing::read_message(reader).await,
Framing::Lines => framing::read_line_message(reader).await,
}
}
@@ -304,9 +265,6 @@ impl Framing {
}
}
/// How long a process that exited is given for its last output to be read.
const OUTPUT_DRAIN: std::time::Duration = std::time::Duration::from_secs(1);
/// A connected JSON-RPC peer. Cloning shares the connection.
#[derive(Clone)]
pub struct Peer {
@@ -324,9 +282,8 @@ impl Drop for KillOnDrop {
}
impl Peer {
/// Spawns `command` and speaks JSON-RPC over its stdio. Stderr lines, and
/// stdout lines that are not part of a message (a launcher's own output), are
/// decoded (see [`output::decode`]) and forwarded to `tracing` and to `on_stderr`.
/// Spawns `command` and speaks JSON-RPC over its stdio. Stderr lines are
/// forwarded to `tracing` and to `on_stderr`.
///
/// Must be called from within a Tokio runtime.
pub fn spawn(
@@ -367,44 +324,42 @@ impl Peer {
let stderr = child.stderr.take();
let pid = child.id();
let on_output: Arc<dyn Fn(String) + Send + Sync> = Arc::from(on_stderr);
let peer = Self::start(stdout, stdin, handler, false, pid, framing, Some(on_output.clone()));
let peer = Self::start(stdout, stdin, handler, false, pid, framing);
let stderr_task = stderr.map(|stderr| {
if let Some(stderr) = stderr {
let name = command.to_owned();
tokio::spawn(output::read_lines(stderr, move |text| {
tracing::debug!(target: "ide_jsonrpc::stderr", "[{name}] {text}");
on_output(text);
}))
});
tokio::spawn(async move {
let mut reader = BufReader::new(stderr);
let mut line = Vec::new();
loop {
line.clear();
match reader.read_until(b'\n', &mut line).await {
Ok(0) | Err(_) => break,
Ok(_) => {
let text = String::from_utf8_lossy(&line).trim_end_matches(['\r', '\n']).to_owned();
tracing::debug!(target: "ide_jsonrpc::stderr", "[{name}] {text}");
on_stderr(text);
}
}
}
});
}
peer.supervise(child, stderr_task);
peer.supervise(child);
Ok(peer)
}
/// Kills `child` when the connection is torn down; closes the connection when it exits.
/// After an exit of its own, the connection is reported closed only once what the
/// process wrote last (stderr, stray stdout) has been read, so a crash report has it.
fn supervise(&self, mut child: tokio::process::Child, stderr_task: Option<tokio::task::JoinHandle<()>>) {
fn supervise(&self, mut child: tokio::process::Child) {
let inner = self.inner.clone();
tokio::spawn(async move {
let (status, killed) = tokio::select! {
status = child.wait() => (status.ok(), false),
let status = tokio::select! {
status = child.wait() => status.ok(),
_ = inner.kill.cancelled() => {
let _ = child.start_kill();
(child.wait().await.ok(), true)
child.wait().await.ok()
}
};
if !killed {
// Bounded: a grandchild may keep the pipes open.
let drained = async {
if let Some(task) = stderr_task {
let _ = task.await;
}
inner.reader_done.cancelled().await;
};
let _ = tokio::time::timeout(OUTPUT_DRAIN, drained).await;
}
inner.mark_closed(status.and_then(|s| s.code()));
});
}
@@ -418,7 +373,7 @@ impl Peer {
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
{
Self::start(reader, writer, handler, true, None, Framing::ContentLength, None)
Self::start(reader, writer, handler, true, None, Framing::ContentLength)
}
/// [`connect`](Self::connect) with the given wire framing.
@@ -427,7 +382,7 @@ impl Peer {
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
{
Self::start(reader, writer, handler, true, None, framing, None)
Self::start(reader, writer, handler, true, None, framing)
}
/// [`Peer::connect`] over streams served by `child` (a server reached over a socket
@@ -444,8 +399,8 @@ impl Peer {
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
{
let peer = Self::start(reader, writer, handler, true, child.id(), Framing::ContentLength, None);
peer.supervise(child, None);
let peer = Self::start(reader, writer, handler, true, child.id(), Framing::ContentLength);
peer.supervise(child);
peer
}
@@ -456,7 +411,6 @@ impl Peer {
close_on_eof: bool,
pid: Option<u32>,
framing: Framing,
on_noise: Option<Arc<dyn Fn(String) + Send + Sync>>,
) -> Self
where
R: AsyncRead + Unpin + Send + 'static,
@@ -472,7 +426,6 @@ impl Peer {
closed,
kill: CancellationToken::new(),
pid,
reader_done: CancellationToken::new(),
});
// Writer: a single task drains the queue so messages never interleave.
@@ -523,39 +476,20 @@ impl Peer {
let inner = inner.clone();
tokio::spawn(async move {
let mut reader = BufReader::new(reader);
let seen_message = AtomicBool::new(false);
let mut noise = |line: &[u8]| {
let text = output::decode(line);
if seen_message.load(Ordering::Relaxed) {
tracing::debug!("jsonrpc: output outside the protocol: {text}");
} else {
tracing::warn!("jsonrpc: output before the first message: {text}");
}
if let Some(f) = &on_noise {
f(text);
}
};
loop {
let msg = tokio::select! {
msg = framing.read(&mut reader, &mut noise) => msg,
msg = framing.read(&mut reader) => msg,
_ = inner.kill.cancelled() => break,
};
match msg {
Ok(Some(body)) => {
seen_message.store(true, Ordering::Relaxed);
dispatch(&inner, &handler, &notif_tx, &body);
}
Ok(Some(body)) => dispatch(&inner, &handler, &notif_tx, &body),
Ok(None) => break,
Err(e) => {
tracing::warn!("jsonrpc read failed: {e}");
if let Some(f) = &on_noise {
f(format!("invalid protocol output: {e}"));
}
break;
}
}
}
inner.reader_done.cancel();
inner.close_transport();
if close_on_eof || inner.kill.is_cancelled() {
inner.mark_closed(None);
-136
Переглянути файл
@@ -1,136 +0,0 @@
//! Text a server process writes outside the protocol: stderr, and stray stdout
//! lines (a launcher script's or the runtime's own messages) before a message.
//!
//! Such text is often not UTF-8: on Windows, `cmd.exe`, batch files and native
//! launchers write in the system code page (GBK on a Chinese system).
use encoding_rs::Encoding;
use tokio::io::{AsyncBufReadExt, AsyncRead, BufReader};
/// `bytes` as text: UTF-8 when valid, else (on Windows) the console / ANSI code
/// page, else UTF-8 with replacement characters.
pub fn decode(bytes: &[u8]) -> String {
decode_with(bytes, &native_code_pages())
}
/// [`decode`] trying the given Windows code pages, in order, after UTF-8.
pub fn decode_with(bytes: &[u8], code_pages: &[u32]) -> String {
if let Ok(s) = std::str::from_utf8(bytes) {
return s.to_owned();
}
for enc in code_pages.iter().filter_map(|&cp| encoding_for_code_page(cp)) {
let (text, had_errors) = enc.decode_without_bom_handling(bytes);
if !had_errors {
return text.into_owned();
}
}
String::from_utf8_lossy(bytes).into_owned()
}
/// The `encoding_rs` encoding of a Windows code page, when it has one.
pub fn encoding_for_code_page(cp: u32) -> Option<&'static Encoding> {
Some(match cp {
65001 => encoding_rs::UTF_8,
936 => encoding_rs::GBK,
54936 => encoding_rs::GB18030,
950 => encoding_rs::BIG5,
932 => encoding_rs::SHIFT_JIS,
949 => encoding_rs::EUC_KR,
866 => encoding_rs::IBM866,
874 => encoding_rs::WINDOWS_874,
1250 => encoding_rs::WINDOWS_1250,
1251 => encoding_rs::WINDOWS_1251,
1252 => encoding_rs::WINDOWS_1252,
1253 => encoding_rs::WINDOWS_1253,
1254 => encoding_rs::WINDOWS_1254,
1255 => encoding_rs::WINDOWS_1255,
1256 => encoding_rs::WINDOWS_1256,
1257 => encoding_rs::WINDOWS_1257,
1258 => encoding_rs::WINDOWS_1258,
20866 => encoding_rs::KOI8_R,
21866 => encoding_rs::KOI8_U,
_ => return None,
})
}
/// The OEM (console) and ANSI code pages: console programs and batch files write in
/// the former, GUI-subsystem and Java launchers in the latter.
#[cfg(windows)]
fn native_code_pages() -> [u32; 2] {
#[link(name = "kernel32")]
unsafe extern "system" {
fn GetOEMCP() -> u32;
fn GetACP() -> u32;
}
// SAFETY: argument-less Win32 queries.
unsafe { [GetOEMCP(), GetACP()] }
}
#[cfg(not(windows))]
fn native_code_pages() -> [u32; 0] {
[]
}
/// Removes a trailing `\n` / `\r\n` (and stray `\r`s before it).
pub fn trim_line_end(line: &[u8]) -> &[u8] {
let mut end = line.len();
while end > 0 && matches!(line[end - 1], b'\n' | b'\r') {
end -= 1;
}
&line[..end]
}
/// Reads `stream` to its end, calling `on_line` with each line decoded by [`decode`].
/// Unlike `AsyncBufReadExt::lines`, a line that is not UTF-8 does not end the stream.
pub async fn read_lines<R: AsyncRead + Unpin>(stream: R, mut on_line: impl FnMut(String)) {
let mut reader = BufReader::new(stream);
let mut line = Vec::new();
loop {
line.clear();
match reader.read_until(b'\n', &mut line).await {
Ok(0) | Err(_) => break,
Ok(_) => on_line(decode(trim_line_end(&line))),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// `请按任意键继续. . .`, what `pause` prints on a Chinese Windows (code page 936).
const PAUSE_GBK: &[u8] = b"\xc7\xeb\xb0\xb4\xc8\xce\xd2\xe2\xbc\xfc\xbc\xcc\xd0\xf8. . .";
#[test]
fn utf8_passes_through() {
assert_eq!(decode_with("héllo 中文".as_bytes(), &[936]), "héllo 中文");
}
#[test]
fn code_page_text_is_decoded() {
assert_eq!(decode_with(PAUSE_GBK, &[936, 936]), "请按任意键继续. . .");
// The first code page that decodes cleanly wins.
assert_eq!(decode_with(PAUSE_GBK, &[437, 936]), "请按任意键继续. . .");
assert_eq!(decode_with(b"caf\xe9", &[1252]), "café");
}
#[test]
fn undecodable_text_is_lossy_utf8() {
let out = decode_with(PAUSE_GBK, &[]);
assert!(out.contains('\u{FFFD}') && out.ends_with(". . ."), "{out}");
assert_eq!(decode_with(b"a\xffb", &[65001]), "a\u{FFFD}b");
}
#[tokio::test]
async fn read_lines_survives_non_utf8_lines() {
let mut input = b"first\r\n".to_vec();
input.extend_from_slice(b"\xff\xfe broken\n");
input.extend_from_slice(b"last");
let mut lines = Vec::new();
read_lines(&input[..], |l| lines.push(l)).await;
assert_eq!(lines.len(), 3);
assert_eq!(lines[0], "first");
assert!(lines[1].ends_with(" broken"));
assert_eq!(lines[2], "last");
}
}
-67
Переглянути файл
@@ -44,46 +44,6 @@ mod framing_tests {
assert!(read_all(long.as_bytes()).await.is_err(), "header too long");
}
async fn read_with_noise(input: &[u8]) -> (std::io::Result<Vec<Vec<u8>>>, Vec<String>) {
let mut reader = BufReader::new(input);
let mut noise = Vec::new();
let mut out = Vec::new();
let result = loop {
match read_message_or_noise(&mut reader, &mut |l| noise.push(crate::output::decode(l))).await {
Ok(Some(msg)) => out.push(msg),
Ok(None) => break Ok(out),
Err(e) => break Err(e),
}
};
(result, noise)
}
#[tokio::test]
async fn output_between_messages_is_reported_and_skipped() {
let input = b"OpenJDK 64-Bit Server VM warning: Sharing is only supported\r\n\xc7\xeb\xb0\xb4 \xff\n\
Content-Length: 2\r\n\r\n{}Picked up JAVA_TOOL_OPTIONS: -Dx\nContent-Length: 4\r\n\r\nnull";
let (msgs, noise) = read_with_noise(input).await;
assert_eq!(msgs.unwrap(), vec![b"{}".to_vec(), b"null".to_vec()]);
assert_eq!(noise.len(), 3, "{noise:?}");
assert_eq!(noise[0], "OpenJDK 64-Bit Server VM warning: Sharing is only supported");
assert_eq!(noise[2], "Picked up JAVA_TOOL_OPTIONS: -Dx");
}
#[tokio::test]
async fn unterminated_output_then_eof_is_reported() {
// `pause` prints its prompt without a newline and the process is gone.
let (msgs, noise) = read_with_noise(b"Press any key to continue . . . ").await;
assert!(msgs.unwrap().is_empty());
assert_eq!(noise, ["Press any key to continue . . . "]);
}
#[tokio::test]
async fn garbage_inside_a_header_is_still_an_error() {
let (msgs, _) = read_with_noise(b"Content-Length: 2\r\nnot a header\r\n\r\n{}").await;
let e = msgs.unwrap_err();
assert!(e.to_string().contains("not a header"), "{e}");
}
#[tokio::test]
async fn handles_partial_reads() {
let (mut client, server) = tokio::io::duplex(4);
@@ -391,30 +351,3 @@ async fn kill_terminates_process() {
peer.kill();
tokio::time::timeout(Duration::from_secs(5), peer.closed()).await.unwrap();
}
/// A launcher that prints in the system code page and exits before speaking the
/// protocol: `jdtls.bat` on a Chinese Windows when its Python step fails, then
/// `pause` prints `请按任意键继续. . .` in GBK on stdout.
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn output_before_the_handshake_is_reported_not_dropped() {
let lines = Arc::new(Mutex::new(Vec::new()));
let sink = lines.clone();
let script = r"printf 'python: not found\n' >&2; printf '\307\353\260\264\310\316\322\342\274\374\274\314\320\370. . .\r\n'; exit 1";
let peer = Peer::spawn(
"sh",
&["-c".into(), script.into()],
&std::env::temp_dir(),
&[],
Arc::new(NoopHandler),
Box::new(move |l| sink.lock().push(l)),
)
.unwrap();
let init = peer.request::<_, Value>("initialize", json!({}), None).await;
assert!(matches!(init, Err(RpcError::Closed)), "{init:?}");
assert_eq!(tokio::time::timeout(Duration::from_secs(5), peer.closed()).await.unwrap(), Some(1));
// Everything the process wrote is in by the time the close is reported.
let lines = lines.lock().clone();
assert!(lines.iter().any(|l| l == "python: not found"), "{lines:?}");
assert!(lines.iter().any(|l| l.ends_with(". . .") && l.len() > 6), "{lines:?}");
}
-4
Переглянути файл
@@ -406,10 +406,6 @@ impl LspManager {
}
Err(e) => {
tracing::warn!("{}: initialize failed: {e}", server.name);
if matches!(e, RpcError::Closed) {
// The server is exiting: let it, so the crash report has its exit code and last output.
let _ = tokio::time::timeout(Duration::from_secs(3), peer.closed()).await;
}
peer.kill();
// Treated like a crash so transient failures retry with backoff.
self.spawn_supervisor(server, generation, peer);
+7 -2
Переглянути файл
@@ -14,7 +14,7 @@ use std::net::{SocketAddr, TcpStream, ToSocketAddrs};
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::io::AsyncRead;
use tokio::io::{AsyncBufReadExt, AsyncRead, BufReader};
pub(crate) const PORT_PLACEHOLDER: &str = "${port}";
pub(crate) const ROOT_PLACEHOLDER: &str = "${root}";
@@ -157,7 +157,12 @@ pub(crate) fn connect_or_start(
}
fn pump_lines<R: AsyncRead + Unpin + Send + 'static>(stream: R, on_line: Arc<dyn Fn(String) + Send + Sync>) {
tokio::spawn(ide_jsonrpc::output::read_lines(stream, move |line| on_line(line)));
tokio::spawn(async move {
let mut lines = BufReader::new(stream).lines();
while let Ok(Some(line)) = lines.next_line().await {
on_line(line);
}
});
}
#[cfg(test)]
-67
Переглянути файл
@@ -1,67 +0,0 @@
//! A stdio server that dies before the handshake: what it printed (on stderr, and
//! on stdout outside the protocol, in any encoding) must reach the crash message.
#![cfg(unix)]
use ide_core::event::ServerStatus;
use ide_core::{DocId, IdeEvent, LanguageId};
use ide_language::{LanguageConfig, LanguageRegistry, LanguageServerConfig};
use ide_lsp::{LspManager, ProcessLauncher};
use parking_lot::Mutex;
use std::sync::Arc;
use std::time::Duration;
/// Shaped like `jdtls.bat` on a Chinese Windows whose Python step fails: an error on
/// stderr, then `pause` prompting in GBK on stdout (`请按任意键继续. . .`), reading one
/// key from stdin, exiting with an error.
const LAUNCHER: &str = r#"#!/bin/sh
echo "'python' is not recognized as an internal or external command" >&2
printf '\307\353\260\264\310\316\322\342\274\374\274\314\320\370. . . '
head -c 1 >/dev/null
printf '\r\n'
exit 1
"#;
#[tokio::test(flavor = "multi_thread")]
async fn crash_before_the_handshake_reports_what_the_server_printed() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().to_path_buf();
let script = root.join("fake-jdtls");
std::fs::write(&script, LAUNCHER).unwrap();
std::fs::set_permissions(&script, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
let server: LanguageServerConfig =
toml::from_str(&format!("name = \"fake\"\ncommand = {:?}", script.to_string_lossy())).unwrap();
let lang: LanguageConfig = toml::from_str("id = \"java\"\nname = \"Java\"\nextensions = [\"java\"]").unwrap();
let lang = LanguageConfig { language_servers: vec![server], ..lang };
let registry = Arc::new(LanguageRegistry::from_configs(vec![lang]));
let events = Arc::new(Mutex::new(Vec::new()));
let sink = {
let events = events.clone();
Arc::new(move |e: IdeEvent| events.lock().push(e))
};
let mgr = LspManager::with_launcher(root.clone(), registry, sink, Arc::new(ProcessLauncher));
let path = root.join("A.java");
std::fs::write(&path, "class A {}\n").unwrap();
mgr.did_open(DocId::next(), &path, &LanguageId::new("java"), 1, "class A {}\n");
let crashed = || {
events.lock().iter().find_map(|e| match e {
IdeEvent::LanguageServer { status: ServerStatus::Crashed, message, .. } => message.clone(),
_ => None,
})
};
let mut message = None;
for _ in 0..1000 {
message = crashed();
if message.is_some() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
let message = message.expect("the server is reported as crashed");
assert!(message.starts_with("fake exited with code 1:\n"), "{message}");
assert!(message.contains("'python' is not recognized"), "{message}");
// The stdout prompt, decoded (code page 936 on Windows, lossily elsewhere).
assert!(message.contains(". . ."), "{message}");
mgr.shutdown_all().await;
}
-358
Переглянути файл
@@ -1,358 +0,0 @@
//! Starting jdtls on the JVM directly instead of through its launcher scripts.
//!
//! The release ships `bin/jdtls` (Python), `bin/jdtls.py` and, for Windows,
//! `bin/jdtls.bat`, which runs `python` and then `pause`. Each needs a Python
//! interpreter; without one the batch file prints `pause`'s prompt in the console
//! code page and exits. The command line the script builds is reproduced here, so
//! only a JDK is needed.
use crate::java::{Jdk, jdk_at};
use ide_language::LanguageServerConfig;
use std::path::{Path, PathBuf};
/// The parts of a jdtls install the JVM is started with.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct JdtlsInstall {
/// `plugins/org.eclipse.equinox.launcher_<version>.jar`.
pub launcher: PathBuf,
/// The shared, read-only OSGi configuration for this platform (`config_win`, `config_mac_arm`…).
pub config: PathBuf,
}
/// Names of the release's launcher scripts; anything else is the user's own wrapper.
const SCRIPTS: &[&str] = &["jdtls", "jdtls.bat", "jdtls.cmd", "jdtls.py"];
/// The directory with `plugins/` of the jdtls `executable` belongs to (`<home>/bin/jdtls`,
/// or Homebrew's `<prefix>/bin/jdtls` wrapper with the install under `libexec`).
pub fn jdtls_home(executable: &Path) -> Option<PathBuf> {
let exe = dunce::canonicalize(executable).ok()?;
let home = exe.parent()?.parent()?;
[home.to_path_buf(), home.join("libexec")].into_iter().find(|h| h.join("plugins").is_dir())
}
/// Shared configuration directories to try, best first, for `os` / `arch`
/// (`std::env::consts` values), as the release names them.
pub fn config_dir_names(os: &str, arch: &str) -> Vec<String> {
let base = match os {
"windows" => "config_win",
"macos" => "config_mac",
_ => "config_linux",
};
let mut names = Vec::new();
if arch == "aarch64" {
names.push(format!("{base}_arm"));
}
names.push(base.to_owned());
names
}
/// The launcher jar and configuration of the install at `home`, when it has the
/// release layout.
pub fn find_install(home: &Path, os: &str, arch: &str) -> Option<JdtlsInstall> {
let plugins = home.join("plugins");
let unversioned = plugins.join("org.eclipse.equinox.launcher.jar");
let launcher = if unversioned.is_file() {
unversioned
} else {
let mut jars: Vec<PathBuf> = std::fs::read_dir(&plugins)
.ok()?
.flatten()
.map(|e| e.path())
.filter(|p| {
p.file_name().and_then(|n| n.to_str()).is_some_and(|n| {
// Not the native fragments (`org.eclipse.equinox.launcher.win32.win32.x86_64_…`).
n.starts_with("org.eclipse.equinox.launcher_") && n.ends_with(".jar")
})
})
.collect();
jars.sort();
jars.pop()?
};
let config =
config_dir_names(os, arch).into_iter().map(|n| home.join(n)).find(|d| d.join("config.ini").is_file())?;
Some(JdtlsInstall { launcher, config })
}
/// Arguments meant for the launcher script, sorted out.
#[derive(Debug, Default, PartialEq, Eq)]
struct ScriptArgs {
jvm: Vec<String>,
java: Option<String>,
data: Option<String>,
rest: Vec<String>,
}
fn split_script_args(args: &[String]) -> ScriptArgs {
let mut out = ScriptArgs::default();
let mut it = args.iter();
while let Some(a) = it.next() {
if let Some(v) = a.strip_prefix("--jvm-arg=") {
out.jvm.push(v.to_owned());
} else if a == "--jvm-arg" {
out.jvm.extend(it.next().cloned());
} else if let Some(v) = a.strip_prefix("--java-executable=") {
out.java = Some(v.to_owned());
} else if a == "--java-executable" {
out.java = it.next().cloned();
} else if a == "-data" {
out.data = it.next().cloned();
} else if let Some(v) = a.strip_prefix("-data=") {
out.data = Some(v.to_owned());
} else if a != "--validate-java-version" && a != "--no-validate-java-version" {
out.rest.push(a.clone());
}
}
out
}
/// The JVM command line `bin/jdtls` builds: its system properties and module
/// options, the user's `--jvm-arg`s, then the Equinox launcher with `-data`.
pub fn java_args(install: &JdtlsInstall, java_major: u32, script_args: &[String]) -> Vec<String> {
let parsed = split_script_args(script_args);
let mut args: Vec<String> = Vec::new();
if java_major >= 24 {
args.extend(["-Djdk.xml.maxGeneralEntitySizeLimit=0".into(), "-Djdk.xml.totalEntitySizeLimit=0".into()]);
}
args.extend(
[
"-Declipse.application=org.eclipse.jdt.ls.core.id1",
"-Dosgi.bundles.defaultStartLevel=4",
"-Declipse.product=org.eclipse.jdt.ls.core.product",
"-Dosgi.checkConfiguration=true",
]
.map(String::from),
);
args.push(format!("-Dosgi.sharedConfiguration.area={}", install.config.to_string_lossy()));
args.extend(
[
"-Dosgi.sharedConfiguration.area.readOnly=true",
"-Dosgi.configuration.cascaded=true",
"-Xms1G",
"--add-modules=ALL-SYSTEM",
"--add-opens",
"java.base/java.util=ALL-UNNAMED",
"--add-opens",
"java.base/java.lang=ALL-UNNAMED",
]
.map(String::from),
);
args.extend(parsed.jvm);
args.extend(["-jar".to_owned(), install.launcher.to_string_lossy().into_owned()]);
if let Some(data) = parsed.data {
args.extend(["-data".to_owned(), data]);
}
args.extend(parsed.rest);
args
}
/// Rewrites a jdtls launch (`command` = the release's script, `JAVA_HOME` chosen by
/// [`crate::java::configure_jdtls`]) to start `java` directly. Left unchanged when the
/// command is someone's own wrapper, the install has another layout, or no JDK is set
/// (the launch then reports why).
pub fn launch_directly(cfg: &mut LanguageServerConfig) {
if cfg.name != "jdtls" || cfg.launch_error.is_some() {
return;
}
let search = cfg.env.get("PATH").map(std::ffi::OsString::from).or_else(|| std::env::var_os("PATH"));
let Some(script) = search.and_then(|s| ide_run::which::find_executable(&cfg.command, &s)) else { return };
let is_script = dunce::canonicalize(&script)
.ok()
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_ascii_lowercase()))
.is_some_and(|n| SCRIPTS.contains(&n.as_str()));
if !is_script {
return;
}
let Some(install) =
jdtls_home(&script).and_then(|h| find_install(&h, std::env::consts::OS, std::env::consts::ARCH))
else {
return;
};
let own_java = split_script_args(&cfg.args).java.map(PathBuf::from);
let jdk: Option<(PathBuf, Jdk)> = match own_java {
Some(java) => java.parent().and_then(Path::parent).and_then(jdk_at).map(|jdk| (java, jdk)),
None => cfg.env.get("JAVA_HOME").and_then(|h| jdk_at(Path::new(h))).map(|jdk| {
let java = crate::java::java_executable(&jdk.home);
(java, jdk)
}),
};
let Some((java, jdk)) = jdk.filter(|(java, _)| java.is_file()) else { return };
cfg.args = java_args(&install, jdk.major, &cfg.args);
cfg.command = java.to_string_lossy().into_owned();
}
#[cfg(test)]
mod tests {
use super::*;
fn strings(args: &[&str]) -> Vec<String> {
args.iter().map(|s| s.to_string()).collect()
}
/// What [`crate::java::configure_jdtls`] and the settings pass to the script.
fn script_args(data: &str, agent: &str) -> Vec<String> {
strings(&[
"--jvm-arg=-Xmx2G",
"-data",
data,
"--jvm-arg=-Djava.import.generatesMetadataFilesAtProjectRoot=false",
&format!("--jvm-arg=-javaagent:{agent}"),
])
}
#[test]
fn windows_command_line() {
// The reporter's layout: a managed install under %APPDATA%, JDK 25, a user name with a space and CJK.
let tools = r"C:\Users\张 三\AppData\Roaming\ai.l0ng.openidea\tools\jdtls";
let install = JdtlsInstall {
launcher: PathBuf::from(format!(r"{tools}\plugins\org.eclipse.equinox.launcher_1.7.0.v20250424-1814.jar")),
config: PathBuf::from(format!(r"{tools}\config_win")),
};
let data = r"C:\Users\张 三\AppData\Roaming\ai.l0ng.openidea\lsp\jdtls\0123456789abcdef";
let agent = r"C:\Users\张 三\AppData\Roaming\ai.l0ng.openidea\tools\lombok\bin\lombok.jar";
let args = java_args(&install, 25, &script_args(data, agent));
assert_eq!(
args,
strings(&[
"-Djdk.xml.maxGeneralEntitySizeLimit=0",
"-Djdk.xml.totalEntitySizeLimit=0",
"-Declipse.application=org.eclipse.jdt.ls.core.id1",
"-Dosgi.bundles.defaultStartLevel=4",
"-Declipse.product=org.eclipse.jdt.ls.core.product",
"-Dosgi.checkConfiguration=true",
&format!(r"-Dosgi.sharedConfiguration.area={tools}\config_win"),
"-Dosgi.sharedConfiguration.area.readOnly=true",
"-Dosgi.configuration.cascaded=true",
"-Xms1G",
"--add-modules=ALL-SYSTEM",
"--add-opens",
"java.base/java.util=ALL-UNNAMED",
"--add-opens",
"java.base/java.lang=ALL-UNNAMED",
"-Xmx2G",
"-Djava.import.generatesMetadataFilesAtProjectRoot=false",
&format!("-javaagent:{agent}"),
"-jar",
&format!(r"{tools}\plugins\org.eclipse.equinox.launcher_1.7.0.v20250424-1814.jar"),
"-data",
data,
])
);
}
#[test]
fn unix_command_line() {
let install = JdtlsInstall {
launcher: PathBuf::from(
"/Users/me/Library/Application Support/ai.l0ng.openidea/tools/jdtls/plugins/org.eclipse.equinox.launcher_1.7.0.jar",
),
config: PathBuf::from("/Users/me/Library/Application Support/ai.l0ng.openidea/tools/jdtls/config_mac_arm"),
};
let args = java_args(
&install,
21,
&strings(&["--jvm-arg", "-Dlog.level=ALL", "--no-validate-java-version", "-data", "/d", "--extra"]),
);
assert_eq!(args[0], "-Declipse.application=org.eclipse.jdt.ls.core.id1", "no JDK 24+ flags on 21");
assert!(args.contains(&"-Dosgi.sharedConfiguration.area=/Users/me/Library/Application Support/ai.l0ng.openidea/tools/jdtls/config_mac_arm".to_owned()));
assert_eq!(
args[args.len() - 7..],
strings(&[
"java.base/java.lang=ALL-UNNAMED",
"-Dlog.level=ALL",
"-jar",
"/Users/me/Library/Application Support/ai.l0ng.openidea/tools/jdtls/plugins/org.eclipse.equinox.launcher_1.7.0.jar",
"-data",
"/d",
"--extra",
])
);
assert!(!args.iter().any(|a| a.contains("validate-java-version")));
}
#[test]
fn config_dirs_per_platform() {
assert_eq!(config_dir_names("windows", "x86_64"), ["config_win"]);
assert_eq!(config_dir_names("windows", "aarch64"), ["config_win_arm", "config_win"]);
assert_eq!(config_dir_names("macos", "aarch64"), ["config_mac_arm", "config_mac"]);
assert_eq!(config_dir_names("linux", "x86_64"), ["config_linux"]);
}
#[test]
fn finds_the_launcher_and_configuration_of_a_release_layout() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path();
std::fs::create_dir_all(home.join("plugins")).unwrap();
for jar in [
"org.eclipse.equinox.launcher_1.7.0.v20250424-1814.jar",
"org.eclipse.equinox.launcher.win32.win32.x86_64_1.2.1300.v20250331-1702.jar",
"org.eclipse.jdt.ls.core_1.50.0.jar",
] {
std::fs::write(home.join("plugins").join(jar), "").unwrap();
}
assert_eq!(find_install(home, "windows", "x86_64"), None, "no configuration");
for config in ["config_win", "config_mac", "config_mac_arm"] {
std::fs::create_dir_all(home.join(config)).unwrap();
std::fs::write(home.join(config).join("config.ini"), "").unwrap();
}
let win = find_install(home, "windows", "x86_64").unwrap();
assert_eq!(win.launcher, home.join("plugins/org.eclipse.equinox.launcher_1.7.0.v20250424-1814.jar"));
assert_eq!(win.config, home.join("config_win"));
assert_eq!(find_install(home, "windows", "aarch64").unwrap().config, home.join("config_win"));
assert_eq!(find_install(home, "macos", "aarch64").unwrap().config, home.join("config_mac_arm"));
}
#[cfg(unix)]
#[test]
fn rewrites_the_release_script_to_java() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path().join("jdtls");
std::fs::create_dir_all(home.join("bin")).unwrap();
std::fs::create_dir_all(home.join("plugins")).unwrap();
std::fs::write(home.join("plugins/org.eclipse.equinox.launcher_1.7.0.jar"), "").unwrap();
for config in config_dir_names(std::env::consts::OS, std::env::consts::ARCH) {
std::fs::create_dir_all(home.join(&config)).unwrap();
std::fs::write(home.join(&config).join("config.ini"), "").unwrap();
}
let script = home.join("bin/jdtls");
std::fs::write(&script, "#!/usr/bin/env python3\n").unwrap();
std::fs::set_permissions(&script, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
let jdk = dir.path().join("jdk-25");
std::fs::create_dir_all(jdk.join("bin")).unwrap();
std::fs::write(jdk.join("release"), "JAVA_VERSION=\"25.0.1\"\n").unwrap();
std::fs::write(jdk.join("bin/java"), "").unwrap();
let cfg = |command: &str| -> LanguageServerConfig {
let mut cfg: LanguageServerConfig =
toml::from_str(&format!("name = \"jdtls\"\ncommand = {command:?}")).unwrap();
cfg.env.insert("PATH".into(), home.join("bin").to_string_lossy().into_owned());
cfg.env.insert("JAVA_HOME".into(), jdk.to_string_lossy().into_owned());
cfg.args = strings(&["-data", "/ws", "--jvm-arg=-Xmx1G"]);
cfg
};
let mut direct = cfg("jdtls");
launch_directly(&mut direct);
let java = dunce::canonicalize(&jdk).unwrap().join("bin/java");
assert_eq!(Path::new(&direct.command), java);
assert_eq!(direct.args[0], "-Djdk.xml.maxGeneralEntitySizeLimit=0");
assert!(direct.args.iter().any(|a| a == "-Xmx1G"));
let jar = direct.args.iter().position(|a| a == "-jar").unwrap();
assert!(direct.args[jar + 1].ends_with("org.eclipse.equinox.launcher_1.7.0.jar"));
assert_eq!(direct.args[jar + 2..], strings(&["-data", "/ws"]));
// Someone's own wrapper, or no usable JDK: the command is kept.
std::fs::write(home.join("bin/my-jdtls"), "#!/bin/sh\n").unwrap();
std::fs::set_permissions(home.join("bin/my-jdtls"), std::os::unix::fs::PermissionsExt::from_mode(0o755))
.unwrap();
let mut own = cfg("my-jdtls");
launch_directly(&mut own);
assert_eq!(own.command, "my-jdtls");
let mut no_jdk = cfg("jdtls");
no_jdk.env.remove("JAVA_HOME");
launch_directly(&mut no_jdk);
assert_eq!(no_jdk.command, "jdtls");
let mut failing = cfg("jdtls");
failing.launch_error = Some("needs JDK 25".into());
launch_directly(&mut failing);
assert_eq!(failing.command, "jdtls");
}
}
-1
Переглянути файл
@@ -10,7 +10,6 @@ mod discover;
mod exec;
pub mod godot;
pub mod java;
pub mod jdtls;
pub mod libraries;
pub mod locate;
pub mod lombok;
+15 -1
Переглянути файл
@@ -1,6 +1,6 @@
use crate::state::AppState;
use ide_agent::{
AgentChange, AgentEntry, AgentEvent, AgentPrompt, AgentProvider, AgentQueued, AgentTask, NewAgentTask,
AgentChange, AgentCommand, AgentEntry, AgentEvent, AgentPrompt, AgentProvider, AgentQueued, AgentTask, NewAgentTask,
};
use ide_core::{IdeResult, IpcPath};
use std::sync::Arc;
@@ -27,6 +27,20 @@ pub fn agent_providers(window: Window, state: State<'_, AppState>) -> IdeResult<
Ok(state.project(window.label())?.agents.providers())
}
/// Slash commands to complete for `provider` in `task`'s directory, or in the project
/// before a task exists (skills and custom commands on disk included).
#[tauri::command]
#[specta::specta]
pub async fn agent_commands(
window: Window,
state: State<'_, AppState>,
provider: String,
task: Option<String>,
) -> IdeResult<Vec<AgentCommand>> {
let project = state.project(window.label())?;
project.agents.commands(&provider, task.as_deref()).await
}
#[tauri::command]
#[specta::specta]
pub fn agent_entries(window: Window, state: State<'_, AppState>, task: String) -> IdeResult<Vec<AgentEntry>> {
+1
Переглянути файл
@@ -62,6 +62,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
app::log_frontend,
agent::agent_subscribe,
agent::agent_providers,
agent::agent_commands,
agent::agent_entries,
agent::agent_create,
agent::agent_prompt,
+1 -1
Переглянути файл
@@ -293,7 +293,6 @@ impl AppState {
&bundles,
lombok.jar(),
);
ide_sdk::jdtls::launch_directly(cfg);
}
}));
}
@@ -418,6 +417,7 @@ impl AppState {
.join(&project_key),
models_file: self.data_dir.join("agents").join("models.json"),
custom_agents_dir: Some(self.config_dir.join("agents")),
home_dir: dirs::home_dir(),
},
tauri::async_runtime::handle().inner().clone(),
));
+5
Переглянути файл
@@ -56,6 +56,11 @@ export const commands = {
/** Streams the project's agent events to this window; returns every task. */
agentSubscribe: (onEvent: Channel<AgentEvent>) => typedError<AgentTask[], IdeError>(__TAURI_INVOKE("agent_subscribe", { onEvent })),
agentProviders: () => typedError<AgentProvider[], IdeError>(__TAURI_INVOKE("agent_providers")),
/**
* Slash commands to complete for `provider` in `task`'s directory, or in the project
* before a task exists (skills and custom commands on disk included).
*/
agentCommands: (provider: string, task: string | null) => typedError<AgentCommand[], IdeError>(__TAURI_INVOKE("agent_commands", { provider, task })),
agentEntries: (task: string) => typedError<AgentEntry[], IdeError>(__TAURI_INVOKE("agent_entries", { task })),
agentCreate: (request: NewAgentTask) => typedError<AgentTask, IdeError>(__TAURI_INVOKE("agent_create", { request })),
/** Sends a message; while the agent works it is queued, or with `now` it interrupts the turn. */
+3 -2
Переглянути файл
@@ -9,7 +9,7 @@ import { Composer } from "./Composer";
import { canSend, emptyDraft } from "./composerModel";
import { ConfigPickers } from "./ConfigPickers";
import { providerIcon } from "./model";
import { HOME, startTask, updateDraft, useAgents } from "./store";
import { HOME, NO_COMMANDS, startTask, updateDraft, useAgentCommands, useAgents } from "./store";
import styles from "./Home.module.css";
export function HomeEditor() {
@@ -36,6 +36,7 @@ export function HomeEditor() {
}, []);
const provider = providers.find((p) => p.id === draft.provider) ?? providers[0];
const agentCommands = useAgentCommands(provider?.id, null, provider?.commands ?? NO_COMMANDS);
// Installed agents first; the rest under a "Not installed" title, with the command they need.
const installed = providers.filter((p) => p.installed);
const missing = providers.filter((p) => !p.installed);
@@ -70,7 +71,7 @@ export function HomeEditor() {
placeholder="Describe a task for the agent. @ references a file, / runs a command"
root={root}
projectRoot={root}
commands={provider?.commands ?? []}
commands={agentCommands}
history={history}
config={provider?.config ?? []}
onConfig={setOption}
+3 -1
Переглянути файл
@@ -25,6 +25,7 @@ import {
sendMessage,
sendQueuedNow,
setTaskConfig,
useAgentCommands,
useAgents,
} from "./store";
import styles from "./Session.module.css";
@@ -279,6 +280,7 @@ function SessionComposer({ task, entries }: { task: AgentTask; entries: AgentEnt
const project = useProject((s) => s.project);
const composer = useAgents((s) => s.composers.get(task.id)) ?? emptyDraft();
const [sending, setSending] = useState(false);
const agentCommands = useAgentCommands(task.provider, task.id, task.commands);
const busy = isBusy(task.status);
// ↑ recalls this conversation's messages, newest first.
const history = useMemo(
@@ -304,7 +306,7 @@ function SessionComposer({ task, entries }: { task: AgentTask; entries: AgentEnt
placeholder={busy ? "Queue a message for when the agent is done (⌘↵ sends it now)" : "Reply to the agent"}
root={task.cwd}
projectRoot={project?.root ?? task.cwd}
commands={task.commands}
commands={agentCommands}
history={history}
config={task.config}
onConfig={setOption}
+15
Переглянути файл
@@ -66,6 +66,21 @@ describe("agent composer", () => {
expect(matchCommands(cmds, "rev").map((c) => c.name)).toEqual(["review", "pr-review"]);
});
it("matches commands by prefix, plugin name, substring, then letters in order", () => {
const cmds = ["triage", "verify", "issue-fix", "brooks-lint:brooks-review", "pr-review", "init"].map((name) => ({
name,
description: "",
hint: null,
}));
const names = (q: string) => matchCommands(cmds, q).map((c) => c.name);
expect(names("trig")).toEqual(["triage"]);
expect(names("brooks-r")).toEqual(["brooks-lint:brooks-review"]);
expect(names("rev")).toEqual(["brooks-lint:brooks-review", "pr-review"]);
expect(names("if")).toEqual(["verify", "issue-fix"]);
expect(names("xyz")).toEqual([]);
expect(names("")).toHaveLength(cmds.length);
});
it("sends only the files still mentioned", () => {
const prompt = toPrompt({
text: " look at @src/a.rs:3-5 and @b.rs ",
+88
Переглянути файл
@@ -0,0 +1,88 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import type { AgentCommand, AgentProvider } from "@/bindings";
const agentCommands = vi.fn();
const agentCreate = vi.fn();
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return {
...real,
isTauri: () => true,
commands: {
...real.commands,
agentCommands: (provider: string, task: string | null) => agentCommands(provider, task),
agentCreate: (request: unknown) => agentCreate(request),
vcsBranches: () => Promise.resolve({ status: "ok", data: [] }),
},
};
});
vi.mock("@tauri-apps/api/webview", () => ({
getCurrentWebview: () => ({ onDragDropEvent: () => Promise.resolve(() => {}) }),
}));
import { HomeEditor } from "./HomeEditor";
import { HOME, updateComposer, useAgents } from "./store";
import { emptyDraft } from "./composerModel";
const command = (name: string, description: string): AgentCommand => ({ name, description, hint: null });
const claude: AgentProvider = {
id: "claude",
name: "Claude Code",
command: "npx",
installed: true,
config: [],
// Offered by the agent's last session in this project.
commands: [command("compact", "Free up context")],
};
beforeEach(() => {
agentCommands.mockReset();
agentCreate.mockReset().mockResolvedValue({ status: "error", error: { kind: "invalid", message: "stop here" } });
useAgents.setState({
providers: [claude],
draft: { provider: "claude", config: {}, isolation: "local", base: null },
});
updateComposer(HOME, emptyDraft());
});
describe("New Task composer commands", () => {
it("completes the project's skills merged with the agent's commands", async () => {
agentCommands.mockResolvedValue({
status: "ok",
data: [
command("compact", "Free up context"),
command("triage", "One pass over open issues and PRs"),
command("issue-fix", "Fix an issue"),
],
});
render(<HomeEditor />);
await waitFor(() => expect(agentCommands).toHaveBeenCalledWith("claude", null));
const box = screen.getByRole("textbox");
fireEvent.change(box, { target: { value: "/trig" } });
const list = await screen.findByRole("listbox", { name: "Commands" });
const options = within(list).getAllByRole("option");
expect(options.map((o) => o.textContent)).toEqual(["/triageOne pass over open issues and PRs"]);
fireEvent.keyDown(box, { key: "Enter" });
expect(useAgents.getState().composers.get(HOME)?.text).toBe("/triage ");
// Sent as typed, so the agent runs the skill.
fireEvent.change(box, { target: { value: "/triage dry-run" } });
fireEvent.keyDown(box, { key: "Enter" });
await waitFor(() => expect(agentCreate).toHaveBeenCalled());
expect(agentCreate.mock.calls[0]![0]).toMatchObject({ prompt: { text: "/triage dry-run" }, provider: "claude" });
});
it("offers nothing the project does not have", async () => {
agentCommands.mockResolvedValue({ status: "ok", data: [command("compact", "Free up context")] });
render(<HomeEditor />);
await waitFor(() => expect(agentCommands).toHaveBeenCalled());
const box = screen.getByRole("textbox");
fireEvent.change(box, { target: { value: "/trig" } });
expect(screen.queryByRole("listbox", { name: "Commands" })).toBeNull();
fireEvent.change(box, { target: { value: "/com" } });
expect(await screen.findByRole("option")).toHaveTextContent("/compact");
});
});
+21 -3
Переглянути файл
@@ -40,11 +40,29 @@ export function applyCompletion(text: string, c: Completion, insert: string): {
return { text: next, caret: c.from + insert.length + 1 };
}
/** Commands matching `query`, prefix matches first. */
/**
* Commands matching `query`: prefix matches first (a plugin's "plugin:name" also by its
* name), then substrings, then names holding its letters in order ("trig" → "triage").
*/
export function matchCommands(commands: readonly AgentCommand[], query: string): AgentCommand[] {
const q = query.toLowerCase();
const hits = commands.filter((c) => c.name.toLowerCase().includes(q));
return hits.sort((a, b) => Number(!a.name.toLowerCase().startsWith(q)) - Number(!b.name.toLowerCase().startsWith(q)));
const rank = (name: string) => {
const n = name.toLowerCase();
if (n.startsWith(q) || n.slice(n.lastIndexOf(":") + 1).startsWith(q)) return 0;
if (n.includes(q)) return 1;
return inOrder(n, q) ? 2 : -1;
};
return commands
.map((command) => ({ command, rank: rank(command.name) }))
.filter((m) => m.rank >= 0)
.sort((a, b) => a.rank - b.rank)
.map((m) => m.command);
}
function inOrder(text: string, query: string): boolean {
let i = 0;
for (const ch of text) if (ch === query[i]) i++;
return i >= query.length;
}
/** `@rel` with a line range suffix when given ("@src/a.rs:10-20"). */
+38 -1
Переглянути файл
@@ -1,7 +1,16 @@
/** Agent tasks of the open project, mirrored from `ide-agent` through `agentSubscribe`. */
import { Channel } from "@tauri-apps/api/core";
import { useEffect, useState } from "react";
import { create } from "zustand";
import type { AgentChange, AgentEntry, AgentEvent, AgentProvider, AgentTask, Isolation } from "@/bindings";
import type {
AgentChange,
AgentCommand,
AgentEntry,
AgentEvent,
AgentProvider,
AgentTask,
Isolation,
} from "@/bindings";
import { call, commands, isTauri } from "@/platform/ipc";
import { editorService, notifications } from "@/workbench/contributions";
import { canSend, emptyDraft, toPrompt, type ComposerDraft, type FileRef } from "./composerModel";
@@ -212,6 +221,34 @@ async function refreshProviders() {
if (providers) useAgents.setState({ providers });
}
export const NO_COMMANDS: readonly AgentCommand[] = [];
/**
* Slash commands to complete: what the agent offered (`offered`; fetched again when it
* changes) plus, for Claude Code, the skills and custom commands on disk. Without `task`,
* those of the project.
*/
export function useAgentCommands(
provider: string | undefined,
task: string | null,
offered: readonly AgentCommand[],
): readonly AgentCommand[] {
const [found, setFound] = useState<{ for: unknown[]; list: readonly AgentCommand[] } | null>(null);
useEffect(() => {
if (!provider || !isTauri()) return;
let alive = true;
call(commands.agentCommands(provider, task))
.then((list) => alive && setFound({ for: [provider, task, offered], list }))
.catch(() => {});
return () => {
alive = false;
};
}, [provider, task, offered]);
// Until the list for these arguments arrives, what the agent offered.
const current = found && found.for[0] === provider && found.for[1] === task && found.for[2] === offered;
return current ? found.list : offered;
}
export function openTask(task: string) {
// The title rides along so a restored tab has it before the tasks load.
const title = useAgents.getState().tasks.get(task)?.title;