mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 16:04:21 +00:00
feat(agents): add Hermes Agent with a profile picker and richer tool-call view (#4542)
Adds Hermes Agent as a built-in ACP agent, with a Hermes profile picker. The tool-call view also gets richer: kind icons, duration, status, exit codes, a terminal block for commands, and links to the files a tool touched (omitted when the title already names the file). Co-authored-by: PawelSzymanski89 <26041449+PawelSzymanski89@users.noreply.github.com>
This commit is contained in:
co-authored by
PawelSzymanski89
parent
977ce62bf0
commit
efce16d45d
@@ -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));
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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 需要登录时,任务中会提示该运行哪条命令。
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -16,6 +16,7 @@ agent_entries always project_host bin
|
||||
agent_external_sessions trusted project_host bindings async
|
||||
agent_fork trusted project_host bindings async
|
||||
agent_grouped_changes trusted project_host bindings async
|
||||
agent_hermes_profiles trusted project_host bindings async
|
||||
agent_import_session trusted project_host bindings async
|
||||
agent_mcp_discover_sources always project_host bindings async
|
||||
agent_mcp_import always project_host bindings sync
|
||||
|
||||
+33
-2
@@ -57,6 +57,8 @@ export const commands = {
|
||||
agentFork: (task: string, turns: number | null) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_fork", { task, turns })),
|
||||
/** The task's uncommitted changes and the commits made since it started. */
|
||||
agentGroupedChanges: (task: string) => typedError<AgentChanges, IdeError>(__TAURI_INVOKE("agent_grouped_changes", { task })),
|
||||
/** Hermes Agent profiles on this machine (`default` first); empty without Hermes. */
|
||||
agentHermesProfiles: () => typedError<HermesProfile[], IdeError>(__TAURI_INVOKE("agent_hermes_profiles")),
|
||||
/** Imports an external session as a task: its first turn loads and replays it. */
|
||||
agentImportSession: (provider: string, sessionId: string) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_import_session", { provider, sessionId })),
|
||||
/** Discovers external MCP configuration files on disk (CLI user configs + workspace `.mcp.json`). */
|
||||
@@ -2267,11 +2269,15 @@ steered?: boolean } | { type: "agent"; text: string } |
|
||||
/** A question that can be answered while the agent keeps working, or after the turn ends. */
|
||||
{ type: "question"; id: string; title: string; questions: AgentQuestion[];
|
||||
/** The submitted answers, or `Skipped`; `None` while unanswered. */
|
||||
chosen: string | null } | { type: "thought"; text: string } | { type: "tool"; id: string; title: string;
|
||||
chosen: string | null } | { type: "thought"; text: string;
|
||||
/** When the reasoning started (ms since the epoch); `None` in tasks saved before. */
|
||||
startedMs?: number | null } | { type: "tool"; id: string; title: string;
|
||||
/** ACP tool kind: `read`, `edit`, `execute`, `search`, `fetch`, `think`… */
|
||||
kind: string; status: AgentToolStatus; locations: IpcPath[];
|
||||
/** Text the tool reported (command output…), truncated. */
|
||||
output: string | null; diffs: AgentToolDiff[] } | { type: "plan"; items: AgentPlanItem[] } |
|
||||
output: string | null; diffs: AgentToolDiff[];
|
||||
/** When the call started and ended (ms since the epoch); `None` in tasks saved before. */
|
||||
startedMs?: number | null; endedMs?: number | null } | { type: "plan"; items: AgentPlanItem[] } |
|
||||
/** A subagent the agent started: its own session, whose entries are listed separately. */
|
||||
{ type: "subagent";
|
||||
/** The subagent's session id. */
|
||||
@@ -2570,6 +2576,13 @@ export type AgentSecuritySettings = {
|
||||
blockedCommands?: string[],
|
||||
};
|
||||
|
||||
export type AgentSessionStats = {
|
||||
/** The last turn's tokens (`session/prompt` result `usage`). */
|
||||
tokens?: AgentTokens | null,
|
||||
/** How many times the agent compressed the conversation (Hermes `compressionDepth`). */
|
||||
compressions?: number,
|
||||
};
|
||||
|
||||
/** Settings › Agents: what the conversation shows and how messages are sent. */
|
||||
export type AgentSettings = AgentSettings_Serialize | AgentSettings_Deserialize;
|
||||
|
||||
@@ -2749,6 +2762,8 @@ export type AgentTask_Deserialize = {
|
||||
background?: AgentBackgroundTask[],
|
||||
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`. */
|
||||
mcpOverrides?: { [key in string]: boolean },
|
||||
/** Token counts of the last turn and context compressions, when the agent reports them. */
|
||||
stats?: AgentSessionStats,
|
||||
};
|
||||
|
||||
export type AgentTask_Serialize = {
|
||||
@@ -2797,6 +2812,8 @@ export type AgentTask_Serialize = {
|
||||
background: AgentBackgroundTask[],
|
||||
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`. */
|
||||
mcpOverrides?: { [key in string]: boolean },
|
||||
/** Token counts of the last turn and context compressions, when the agent reports them. */
|
||||
stats: AgentSessionStats,
|
||||
};
|
||||
|
||||
/** Token pricing (Credits per 1M tokens) and context window capacity for one tier. */
|
||||
@@ -2808,6 +2825,12 @@ export type AgentTokenPricing = {
|
||||
contextTokens?: number | null,
|
||||
};
|
||||
|
||||
export type AgentTokens = {
|
||||
input: number,
|
||||
cached: number,
|
||||
output: number,
|
||||
};
|
||||
|
||||
export type AgentToolDiff = {
|
||||
path: IpcPath,
|
||||
added: number,
|
||||
@@ -6760,6 +6783,14 @@ export type HeapSummary = {
|
||||
analysisMs: number,
|
||||
};
|
||||
|
||||
/** A profile and the name Hermes shows for it (`hermes profile list`). */
|
||||
export type HermesProfile = {
|
||||
/** What `hermes -p` takes; `default` is the Hermes home itself. */
|
||||
name: string,
|
||||
/** `display_name` from the profile's `profile.yaml`, else the name. */
|
||||
label: string,
|
||||
};
|
||||
|
||||
export type HierarchyChoice = {
|
||||
id: string,
|
||||
makeAbstract: boolean,
|
||||
|
||||
@@ -22,7 +22,7 @@ import { Button, Dialog, Icon, IconButton, Input, List, ProgressBar, SearchField
|
||||
import { useSettingsForm } from "@/workbench/contributions";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
import { isPerModelOption } from "./composerModel";
|
||||
import { providerIcon } from "./model";
|
||||
import { providerIcon, slugifyId } from "./model";
|
||||
import {
|
||||
DISTRIBUTION_LABEL,
|
||||
afterInstall,
|
||||
@@ -621,14 +621,6 @@ function Details({
|
||||
);
|
||||
}
|
||||
|
||||
/** Suggests an agent-file id for a display name (`"My Agent!"` → `"my-agent"`). */
|
||||
function slugifyId(name: string): string {
|
||||
return name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "");
|
||||
}
|
||||
|
||||
/** Splits arguments on whitespace, honoring single and double quotes. */
|
||||
function parseArgs(text: string): string[] {
|
||||
const out: string[] = [];
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
/** The Hermes profile a task runs in, next to the model picker. */
|
||||
import { useEffect, useState } from "react";
|
||||
import type { HermesProfile } from "@/bindings";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { Icon, Select } from "@/ui";
|
||||
import { hermesAgentId, providerIcon } from "./model";
|
||||
import { refreshProviders, useAgents } from "./store";
|
||||
|
||||
const isHermes = (provider: string | undefined) => provider === "hermes" || !!provider?.startsWith("hermes-");
|
||||
|
||||
/** The profiles on this computer; empty for other agents or without Hermes. */
|
||||
function useHermesProfiles(provider: string | undefined): HermesProfile[] {
|
||||
const [profiles, setProfiles] = useState<HermesProfile[]>([]);
|
||||
const hermes = isHermes(provider);
|
||||
useEffect(() => {
|
||||
if (!hermes) return;
|
||||
let live = true;
|
||||
void call(commands.agentHermesProfiles())
|
||||
.then((list) => live && setProfiles(list))
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [hermes]);
|
||||
return hermes ? profiles : [];
|
||||
}
|
||||
|
||||
/** The profile `provider` runs in, by the name Hermes shows for it. */
|
||||
const hermesProfileOf = (profiles: readonly HermesProfile[], provider: string) =>
|
||||
profiles.find((p) => hermesAgentId(p.name) === provider) ?? null;
|
||||
|
||||
/**
|
||||
* Each profile is an agent of its own (`hermes -p <name> acp`, `hermes` for `default`), made
|
||||
* on first choice, so the agent picker's memory keeps the profile like it keeps the model.
|
||||
*/
|
||||
export function HermesProfilePicker({
|
||||
provider,
|
||||
onChange,
|
||||
}: {
|
||||
provider: string | undefined;
|
||||
/** Without it the picker only shows the profile: a session stays in the one it started in. */
|
||||
onChange?: (provider: string) => void;
|
||||
}) {
|
||||
const tx = useTx();
|
||||
const profiles = useHermesProfiles(provider);
|
||||
const providers = useAgents((s) => s.providers);
|
||||
if (!provider || profiles.length < 2) return null;
|
||||
const choose = async (name: string) => {
|
||||
const id = hermesAgentId(name);
|
||||
if (!providers.some((p) => p.id === id)) {
|
||||
const label = profiles.find((p) => p.name === name)?.label ?? name;
|
||||
await call(
|
||||
commands.agentCustomSave({ id, name: `Hermes (${label})`, command: "hermes", args: ["-p", name, "acp"] }),
|
||||
);
|
||||
await refreshProviders();
|
||||
}
|
||||
onChange?.(id);
|
||||
};
|
||||
return (
|
||||
<Select
|
||||
variant="ghost"
|
||||
aria-label={tx("Hermes profile")}
|
||||
disabled={!onChange}
|
||||
value={hermesProfileOf(profiles, provider)?.name ?? null}
|
||||
options={profiles.map((p) => ({ value: p.name, label: p.label, verbatim: true }))}
|
||||
renderValue={(o) => (
|
||||
<>
|
||||
<Icon name={providerIcon(provider)} size={14} /> {o?.label ?? provider}
|
||||
</>
|
||||
)}
|
||||
onChange={(name) => void choose(name)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,18 @@
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import type { AgentConfigOption, AgentProvider, NewAgentTask } from "@/bindings";
|
||||
import type { AgentConfigOption, AgentProvider, CustomAgentInput, NewAgentTask } from "@/bindings";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { HomeEditor } from "./HomeEditor";
|
||||
import homeStyles from "./Home.module.css";
|
||||
import { HOME, disconnect, savedDraft, updateComposer, useAgents } from "./store";
|
||||
|
||||
const backend = vi.hoisted(() => ({ providers: [] as AgentProvider[], create: vi.fn(), probe: vi.fn() }));
|
||||
const backend = vi.hoisted(() => ({
|
||||
providers: [] as AgentProvider[],
|
||||
create: vi.fn(),
|
||||
probe: vi.fn(),
|
||||
saveCustom: vi.fn(),
|
||||
hermesProfiles: [] as { name: string; label: string }[],
|
||||
}));
|
||||
const ok = <T,>(data: T) => Promise.resolve({ status: "ok", data });
|
||||
vi.mock("@/platform/ipc", async (original) => ({
|
||||
...(await original<typeof import("@/platform/ipc")>()),
|
||||
@@ -26,6 +32,12 @@ vi.mock("@/platform/ipc", async (original) => ({
|
||||
vcsBranchInfo: () => ok({ head: "main" }),
|
||||
vcsBranches: () => ok([]),
|
||||
agentCreate: (req: NewAgentTask) => backend.create(req),
|
||||
agentHermesProfiles: () => ok(backend.hermesProfiles),
|
||||
agentCustomSave: (input: CustomAgentInput) => {
|
||||
backend.saveCustom(input);
|
||||
backend.providers = [...backend.providers, { ...backend.providers[0]!, id: input.id, args: input.args ?? [] }];
|
||||
return ok(null);
|
||||
},
|
||||
},
|
||||
}));
|
||||
vi.mock("@/workbench/contributions", async (original) => ({
|
||||
@@ -235,3 +247,32 @@ it("does not reuse a previous page's cached agent version when opened again", as
|
||||
function agentTooltip() {
|
||||
return screen.getByRole("button", { name: "Agent" }).parentElement?.getAttribute("data-tooltip");
|
||||
}
|
||||
|
||||
it("offers Hermes profiles next to the model and starts the chosen one with -p", async () => {
|
||||
backend.saveCustom.mockReset();
|
||||
backend.hermesProfiles = [
|
||||
{ name: "default", label: "qb" },
|
||||
{ name: "Dom 2", label: "Dom 2" },
|
||||
];
|
||||
const { unmount } = render(<HomeEditor />);
|
||||
await screen.findByRole("button", { name: "Model" });
|
||||
expect(screen.queryByRole("button", { name: "Hermes profile" })).toBeNull();
|
||||
unmount();
|
||||
|
||||
const hermes = { ...backend.providers[0]!, id: "hermes", name: "Hermes Agent", args: ["acp"] };
|
||||
backend.providers = [hermes];
|
||||
useAgents.setState({ providers: [hermes], draft: savedDraft({ provider: "hermes", config: {} }) });
|
||||
render(<HomeEditor />);
|
||||
const picker = await screen.findByRole("button", { name: "Hermes profile" });
|
||||
expect(picker).toHaveTextContent("qb");
|
||||
fireEvent.click(picker);
|
||||
fireEvent.click(screen.getByRole("option", { name: "Dom 2" }));
|
||||
await waitFor(() => expect(useAgents.getState().draft.provider).toBe("hermes-dom-2"));
|
||||
expect(backend.saveCustom).toHaveBeenCalledWith({
|
||||
id: "hermes-dom-2",
|
||||
name: "Hermes (Dom 2)",
|
||||
command: "hermes",
|
||||
args: ["-p", "Dom 2", "acp"],
|
||||
});
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Hermes profile" })).toHaveTextContent("Dom 2"));
|
||||
});
|
||||
|
||||
@@ -13,6 +13,7 @@ import { Composer } from "./Composer";
|
||||
import { SubmitButton } from "./SubmitButton";
|
||||
import { canSend, emptyDraft } from "./composerModel";
|
||||
import { ConfigPickers } from "./ConfigPickers";
|
||||
import { HermesProfilePicker } from "./HermesProfilePicker";
|
||||
import { McpPicker } from "./McpPicker";
|
||||
import { useEffortFocus } from "./effortFocus";
|
||||
import { useAgentFontZoomSurface } from "./fontZoom";
|
||||
@@ -221,6 +222,10 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
|
||||
}
|
||||
/>
|
||||
</span>
|
||||
<HermesProfilePicker
|
||||
provider={provider?.id}
|
||||
onChange={(id) => updateDraft({ provider: id, config: {} })}
|
||||
/>
|
||||
<ConfigPickers
|
||||
key={provider?.id}
|
||||
config={config}
|
||||
|
||||
@@ -69,6 +69,7 @@ const KNOWN_AGENTS: ReadonlyArray<{ id: string; name: string }> = [
|
||||
{ id: "cursor", name: "Cursor" },
|
||||
{ id: "gemini", name: "Gemini CLI" },
|
||||
{ id: "opencode", name: "OpenCode" },
|
||||
{ id: "hermes", name: "Hermes Agent" },
|
||||
];
|
||||
|
||||
function formatKeyValues(items: readonly McpKeyValue[]): string {
|
||||
|
||||
@@ -1897,3 +1897,129 @@
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
}
|
||||
|
||||
/* Tool calls: an accent by what the call does, a pulse while it runs, its end and time on the right. */
|
||||
.toolEntry {
|
||||
--tool-accent: var(--fg-subtle);
|
||||
animation: entryIn 180ms ease-out;
|
||||
}
|
||||
.kind-read,
|
||||
.kind-search {
|
||||
--tool-accent: var(--info);
|
||||
}
|
||||
.kind-edit,
|
||||
.kind-delete,
|
||||
.kind-move {
|
||||
--tool-accent: var(--warning);
|
||||
}
|
||||
.kind-execute {
|
||||
--tool-accent: var(--success);
|
||||
}
|
||||
.kind-fetch {
|
||||
--tool-accent: var(--accent);
|
||||
}
|
||||
.toolKindIcon {
|
||||
flex: none;
|
||||
color: var(--tool-accent);
|
||||
}
|
||||
.toolLive .toolKindIcon {
|
||||
animation: toolPulse 1.2s ease-in-out infinite;
|
||||
}
|
||||
.toolPath {
|
||||
flex: none;
|
||||
max-width: 180px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
padding: 0 4px;
|
||||
border: none;
|
||||
border-radius: var(--radius-small);
|
||||
background: none;
|
||||
color: var(--link);
|
||||
font: inherit;
|
||||
font-size: var(--agent-fs-small, var(--fs-small));
|
||||
cursor: pointer;
|
||||
}
|
||||
.toolPath:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
.toolEnd {
|
||||
display: inline-flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
margin-left: auto;
|
||||
font-size: var(--agent-fs-small, var(--fs-small));
|
||||
}
|
||||
.toolDone {
|
||||
color: var(--success);
|
||||
}
|
||||
.toolSpinner {
|
||||
color: var(--tool-accent);
|
||||
}
|
||||
.exitCode {
|
||||
flex: none;
|
||||
padding: 0 5px;
|
||||
border-radius: var(--radius-small);
|
||||
background: color-mix(in srgb, var(--success) 18%, transparent);
|
||||
color: var(--success);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--agent-fs-small, var(--fs-small));
|
||||
}
|
||||
.exitFailed {
|
||||
background: color-mix(in srgb, var(--danger) 18%, transparent);
|
||||
color: var(--danger);
|
||||
}
|
||||
.terminalBlock {
|
||||
margin: 4px 0 4px 22px;
|
||||
border: 1px solid var(--border);
|
||||
border-left: 2px solid var(--tool-accent);
|
||||
border-radius: var(--radius-small);
|
||||
background: var(--bg-elev);
|
||||
overflow: hidden;
|
||||
}
|
||||
.terminalCommand,
|
||||
.terminalOutput {
|
||||
margin: 0;
|
||||
padding: 6px 10px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--agent-fs-small, var(--fs-small));
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
.terminalOutput {
|
||||
max-height: 240px;
|
||||
overflow: auto;
|
||||
border-top: 1px solid var(--border);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.prompt {
|
||||
color: var(--tool-accent);
|
||||
user-select: none;
|
||||
}
|
||||
.thoughtEntry {
|
||||
animation: entryIn 180ms ease-out;
|
||||
}
|
||||
.thoughtTook {
|
||||
flex: none;
|
||||
margin-left: 6px;
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
@keyframes entryIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(4px);
|
||||
}
|
||||
}
|
||||
@keyframes toolPulse {
|
||||
50% {
|
||||
opacity: 0.35;
|
||||
}
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.toolEntry,
|
||||
.thoughtEntry,
|
||||
.toolLive .toolKindIcon {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import type {
|
||||
AgentLimit,
|
||||
AgentPrompt,
|
||||
AgentRetry,
|
||||
AgentTokens,
|
||||
AgentUsage,
|
||||
} from "@/bindings";
|
||||
import { tx } from "@/platform/i18n";
|
||||
@@ -599,6 +600,14 @@ export function costLabel(c: AgentCost): string {
|
||||
}
|
||||
}
|
||||
|
||||
/** The last turn's tokens: "in 77.3k · cached 51.3k · out 509". */
|
||||
export function turnTokensLabel(t: AgentTokens): string {
|
||||
const parts = [tx`in ${tokens(t.input)}`];
|
||||
if (t.cached) parts.push(tx`cached ${tokens(t.cached)}`);
|
||||
parts.push(tx`out ${tokens(t.output)}`);
|
||||
return parts.join(" · ");
|
||||
}
|
||||
|
||||
/** `850`, `83.1k`, `1M`. */
|
||||
function tokens(n: number): string {
|
||||
if (n >= 1_000_000) return `${+(n / 1_000_000).toFixed(1)}M`;
|
||||
|
||||
@@ -66,11 +66,25 @@ const PROVIDER_ICONS = new Set([
|
||||
"vibe",
|
||||
"omp",
|
||||
"deepseek-harness",
|
||||
"hermes",
|
||||
]);
|
||||
|
||||
/** The agent's logo; custom agents get the generic agents icon. */
|
||||
export const providerIcon = (provider: string) =>
|
||||
PROVIDER_ICONS.has(provider) ? `agent-${provider}` : "toolwindow-agents";
|
||||
/** Suggests an agent-file id for a display name (`"My Agent!"` → `"my-agent"`). */
|
||||
export function slugifyId(name: string): string {
|
||||
return name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "");
|
||||
}
|
||||
|
||||
/** The agent a Hermes profile runs as: `hermes` for `default`, else `hermes-<slug>` (`hermes -p <name> acp`). */
|
||||
export const hermesAgentId = (profile: string) => (profile === "default" ? "hermes" : `hermes-${slugifyId(profile)}`);
|
||||
|
||||
/** The agent's logo; custom agents get the generic agents icon, Hermes profiles Hermes'. */
|
||||
export function providerIcon(provider: string): string {
|
||||
if (PROVIDER_ICONS.has(provider)) return `agent-${provider}`;
|
||||
return provider.startsWith("hermes-") ? "agent-hermes" : "toolwindow-agents";
|
||||
}
|
||||
|
||||
export interface TaskGroup {
|
||||
status: "needsInput" | "failed" | "limited" | "running" | "ready" | "archived";
|
||||
|
||||
@@ -61,12 +61,15 @@ export const ProcessRun = memo(function ProcessRun({
|
||||
task,
|
||||
lastIndex,
|
||||
busy,
|
||||
thinking,
|
||||
onDiagramDrawn,
|
||||
}: {
|
||||
row: Extract<ConversationRow, { kind: "process" }>;
|
||||
task: AgentTask;
|
||||
lastIndex: number;
|
||||
busy: boolean;
|
||||
/** How long each finished thought took, by entry index. */
|
||||
thinking: ReadonlyMap<number, number> | null;
|
||||
onDiagramDrawn: () => void;
|
||||
}) {
|
||||
const tx = useTx();
|
||||
@@ -122,6 +125,7 @@ export const ProcessRun = memo(function ProcessRun({
|
||||
key={index}
|
||||
task={task}
|
||||
text={entry.text}
|
||||
took={thinking?.get(index) ?? null}
|
||||
working={busy && index === lastIndex}
|
||||
onDiagramDrawn={onDiagramDrawn}
|
||||
/>
|
||||
|
||||
@@ -8,6 +8,7 @@ import clsx from "clsx";
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode, type RefObject } from "react";
|
||||
import { Composer } from "../Composer";
|
||||
import { ConfigPickers } from "../ConfigPickers";
|
||||
import { HermesProfilePicker } from "../HermesProfilePicker";
|
||||
import { McpPicker } from "../McpPicker";
|
||||
import styles from "../Session.module.css";
|
||||
import { SessionAssets } from "../SessionAssets";
|
||||
@@ -280,6 +281,7 @@ export function SessionComposer({
|
||||
]}
|
||||
toolbar={
|
||||
<>
|
||||
<HermesProfilePicker provider={task.provider} />
|
||||
<ConfigPickers
|
||||
config={pickerConfig}
|
||||
onChange={setOption}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useTx } from "@/platform/i18n";
|
||||
import { basename, useProject } from "@/platform/project";
|
||||
import { Icon, IconButton, showContextMenu, T } from "@/ui";
|
||||
import styles from "../Session.module.css";
|
||||
import { costLabel, limitLabel, usageLabel, workTime } from "../composerModel";
|
||||
import { costLabel, limitLabel, turnTokensLabel, usageLabel, workTime } from "../composerModel";
|
||||
import { formatDuration, formatSentAt } from "../conversation";
|
||||
import { branchLabel, hasTaskTerminal, isBusy, providerIcon, statusLabel } from "../model";
|
||||
import { useAgents } from "../store";
|
||||
@@ -87,6 +87,11 @@ export function SessionStatus({
|
||||
</span>
|
||||
)}
|
||||
{task.model && !pickedModel && <span className={styles.fact}>{task.model}</span>}
|
||||
{!!task.stats?.compressions && (
|
||||
<span className={styles.fact} title={tx("The agent compressed the conversation to fit its context")}>
|
||||
{tx("compressed ×{count}").replace("{count}", String(task.stats.compressions))}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{/* Ready is the usual state: only the others are worth a word. */}
|
||||
{task.status !== "ready" && (
|
||||
@@ -148,10 +153,12 @@ function Meters({ task, entries }: { task: AgentTask; entries: AgentEntry[] | nu
|
||||
const reported = useAgents((s) => s.limits.get(task.provider));
|
||||
const limits = show?.showUsageLimits !== false ? (reported ?? []) : [];
|
||||
const cost = show?.showCost === true ? task.usage?.cost : null;
|
||||
const turnTokens = show?.showContextUsage !== false && !busy ? task.stats?.tokens : null;
|
||||
const work = show?.showWorkTime !== false && entries ? workTime(entries, busy ? now : null) : 0;
|
||||
return (
|
||||
<span className={styles.meters}>
|
||||
{usage && <Usage usage={usage} />}
|
||||
{turnTokens && <span title={tx("Tokens of the last turn")}>{turnTokensLabel(turnTokens)}</span>}
|
||||
{limits.map((l) => (
|
||||
<Limit key={l.window} limit={l} now={now} />
|
||||
))}
|
||||
|
||||
@@ -39,7 +39,7 @@ import {
|
||||
import { selectionIn } from "../selection";
|
||||
import styles from "../Session.module.css";
|
||||
import { useAgents } from "../store";
|
||||
import { foldedTurns } from "../timeline";
|
||||
import { foldedTurns, thoughtDurations } from "../timeline";
|
||||
import {
|
||||
conversationRows,
|
||||
foldTurnRows,
|
||||
@@ -382,6 +382,7 @@ export function Stream({
|
||||
const turns = useMemo(() => (entries && !subagent ? turnNumbers(entries) : null), [entries, subagent]);
|
||||
const replies = useMemo(() => (entries && !subagent ? replyTurns(entries) : null), [entries, subagent]);
|
||||
const times = useMemo(() => (entries && !subagent ? replyTimes(entries) : null), [entries, subagent]);
|
||||
const thinking = useMemo(() => (entries ? thoughtDurations(entries) : null), [entries]);
|
||||
const busy = subagent ? subagentWorking(subagent.status) : isBusy(task.status);
|
||||
const lastIndex = entries ? entries.length - 1 : -1;
|
||||
// Keep the row stable when earlier history is prepended; its author can move with the work.
|
||||
@@ -413,12 +414,13 @@ export function Stream({
|
||||
turnCount={turns?.size ?? 0}
|
||||
reply={replies?.get(row.index)}
|
||||
time={times?.get(row.index) ?? null}
|
||||
thoughtMs={thinking?.get(row.index) ?? null}
|
||||
working={row.index === lastIndex && busy}
|
||||
onOpenSubagent={onOpenSubagent}
|
||||
onDiagramDrawn={onDiagramDrawn}
|
||||
/>
|
||||
),
|
||||
[task, turns, replies, times, lastIndex, busy, onOpenSubagent, onDiagramDrawn],
|
||||
[task, turns, replies, times, thinking, lastIndex, busy, onOpenSubagent, onDiagramDrawn],
|
||||
);
|
||||
const renderConversationRow = (row: ConversationRow): ReactNode =>
|
||||
row.kind === "turn" ? (
|
||||
@@ -430,7 +432,14 @@ export function Stream({
|
||||
))}
|
||||
</TurnFold>
|
||||
) : row.kind === "process" ? (
|
||||
<ProcessRun row={row} task={task} lastIndex={lastIndex} busy={busy} onDiagramDrawn={onDiagramDrawn} />
|
||||
<ProcessRun
|
||||
row={row}
|
||||
task={task}
|
||||
lastIndex={lastIndex}
|
||||
busy={busy}
|
||||
thinking={thinking}
|
||||
onDiagramDrawn={onDiagramDrawn}
|
||||
/>
|
||||
) : (
|
||||
renderRow(row)
|
||||
);
|
||||
|
||||
@@ -99,6 +99,7 @@ export const Entry = memo(function Entry({
|
||||
turnCount,
|
||||
reply,
|
||||
time,
|
||||
thoughtMs,
|
||||
working,
|
||||
onOpenSubagent,
|
||||
onDiagramDrawn,
|
||||
@@ -111,6 +112,8 @@ export const Entry = memo(function Entry({
|
||||
reply?: ReplyTurn;
|
||||
/** When the turn this reply answered was asked and finished. */
|
||||
time?: ReplyTimes | null;
|
||||
/** How long a finished thought took. */
|
||||
thoughtMs?: number | null;
|
||||
working: boolean;
|
||||
onOpenSubagent: (id: string) => void;
|
||||
onDiagramDrawn: () => void;
|
||||
@@ -131,7 +134,15 @@ export const Entry = memo(function Entry({
|
||||
/>
|
||||
);
|
||||
case "thought":
|
||||
return <ThoughtEntry task={task} text={entry.text} working={working} onDiagramDrawn={onDiagramDrawn} />;
|
||||
return (
|
||||
<ThoughtEntry
|
||||
task={task}
|
||||
text={entry.text}
|
||||
took={thoughtMs ?? null}
|
||||
working={working}
|
||||
onDiagramDrawn={onDiagramDrawn}
|
||||
/>
|
||||
);
|
||||
case "tool":
|
||||
return <ToolEntry task={task} entry={entry} />;
|
||||
case "plan":
|
||||
|
||||
@@ -1,21 +1,26 @@
|
||||
import type { AgentEntry, AgentTask } from "@/bindings";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { basename } from "@/platform/project";
|
||||
import { Icon, IconButton, Spinner, T } from "@/ui";
|
||||
import clsx from "clsx";
|
||||
import { memo, useLayoutEffect } from "react";
|
||||
import { AgentReply } from "../AgentReply";
|
||||
import { Markdown } from "../Markdown";
|
||||
import styles from "../Session.module.css";
|
||||
import { useAgentSettings } from "../agentSettings";
|
||||
import { formatDuration } from "../conversation";
|
||||
import { Markdown, openPathLink } from "../Markdown";
|
||||
import { subagentTitle, subagentWorking, type SubagentEntry } from "../model";
|
||||
import { useRevealedText } from "../reveal";
|
||||
import { toolDuration, toolRun } from "../timeline";
|
||||
import { cancelTask } from "../store";
|
||||
import { openChangeDiff } from "./ChangesPane";
|
||||
import { Fold } from "./Folds";
|
||||
import { liveTool } from "./conversationRows";
|
||||
import { shortTitle, useNow } from "./shared";
|
||||
|
||||
/** A location as the agent reported it: absolute on any platform, or relative to the task's folder. */
|
||||
const isAbsolute = (path: string) => path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path) || path.startsWith("\\\\");
|
||||
|
||||
const TOOL_ICONS: Record<string, string> = {
|
||||
read: "file",
|
||||
edit: "edit",
|
||||
@@ -40,11 +45,14 @@ function thoughtPreview(text: string): string {
|
||||
export function ThoughtEntry({
|
||||
task,
|
||||
text,
|
||||
took,
|
||||
working,
|
||||
onDiagramDrawn,
|
||||
}: {
|
||||
task: AgentTask;
|
||||
text: string;
|
||||
/** How long the finished thought took, when its times are known. */
|
||||
took: number | null;
|
||||
working: boolean;
|
||||
onDiagramDrawn: () => void;
|
||||
}) {
|
||||
@@ -70,6 +78,9 @@ export function ThoughtEntry({
|
||||
) : (
|
||||
<span className={styles.thoughtPreview}>{thoughtPreview(text) || <T>Reasoning</T>}</span>
|
||||
)}
|
||||
{!working && took != null && took >= 1000 && (
|
||||
<span className={styles.thoughtTook}>{formatDuration(took)}</span>
|
||||
)}
|
||||
</summary>
|
||||
}
|
||||
>
|
||||
@@ -89,12 +100,36 @@ export const ToolEntry = memo(function ToolEntry({
|
||||
entry: Extract<AgentEntry, { type: "tool" }>;
|
||||
}) {
|
||||
const { expandToolOutput } = useAgentSettings();
|
||||
const tx = useTx();
|
||||
const live = liveTool(entry);
|
||||
const took = toolDuration(entry);
|
||||
const run = entry.kind === "execute" ? toolRun(entry) : null;
|
||||
const title = shortTitle(task, entry.title || entry.kind);
|
||||
// A title that already names the file ("Read pom.xml") needs no second link to it.
|
||||
const links =
|
||||
entry.kind === "execute" ? [] : entry.locations.slice(0, 3).filter((path) => !title.includes(basename(path)));
|
||||
const head = (
|
||||
<>
|
||||
<Icon name={TOOL_ICONS[entry.kind] ?? "run"} size={14} />
|
||||
<span className={clsx(styles.toolTitle, liveTool(entry) && styles.shimmer)} title={entry.title || entry.kind}>
|
||||
{shortTitle(task, entry.title || entry.kind)}
|
||||
<Icon name={TOOL_ICONS[entry.kind] ?? "run"} size={14} className={styles.toolKindIcon} />
|
||||
<span className={clsx(styles.toolTitle, live && styles.shimmer)} title={entry.title || entry.kind}>
|
||||
{title}
|
||||
</span>
|
||||
{links.map((path) => (
|
||||
<button
|
||||
key={path}
|
||||
type="button"
|
||||
className={styles.toolPath}
|
||||
title={path}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
openPathLink({
|
||||
path: isAbsolute(path) ? path : `${task.cwd}/${path}`,
|
||||
});
|
||||
}}
|
||||
>
|
||||
{basename(path)}
|
||||
</button>
|
||||
))}
|
||||
{entry.diffs.map((d) => (
|
||||
<button
|
||||
key={d.path}
|
||||
@@ -109,12 +144,27 @@ export const ToolEntry = memo(function ToolEntry({
|
||||
<span className={styles.added}>+{d.added}</span> <span className={styles.removed}>−{d.removed}</span>
|
||||
</button>
|
||||
))}
|
||||
{entry.status === "failed" && <Icon name="error" size={12} />}
|
||||
{run?.exitCode != null && (
|
||||
<span className={clsx(styles.exitCode, run.exitCode !== 0 && styles.exitFailed)} title={tx("Exit code")}>
|
||||
{run.exitCode}
|
||||
</span>
|
||||
)}
|
||||
<span className={styles.toolEnd}>
|
||||
{took != null && <span className={styles.muted}>{formatDuration(took)}</span>}
|
||||
{live ? (
|
||||
<Spinner size={10} className={styles.toolSpinner} label={tx("Running")} />
|
||||
) : entry.status === "failed" ? (
|
||||
<Icon name="error" size={12} />
|
||||
) : (
|
||||
entry.status === "completed" && <Icon name="check" size={12} className={styles.toolDone} />
|
||||
)}
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
const className = clsx(styles.process, styles.toolEntry, styles[`kind-${entry.kind}`], live && styles.toolLive);
|
||||
if (!entry.output)
|
||||
return (
|
||||
<div className={clsx(styles.process, styles.toolEntry)}>
|
||||
<div className={className}>
|
||||
<div className={styles.tool}>
|
||||
<span className={styles.toolChevronSpacer} aria-hidden="true" />
|
||||
{head}
|
||||
@@ -122,10 +172,10 @@ export const ToolEntry = memo(function ToolEntry({
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div className={clsx(styles.process, styles.toolEntry)}>
|
||||
<div className={className}>
|
||||
<Fold
|
||||
className={styles.toolDetails}
|
||||
open={liveTool(entry) || expandToolOutput}
|
||||
open={live || expandToolOutput}
|
||||
// A `!` command the user ran from the composer: its output is what they asked for.
|
||||
defaultOpen={entry.id.startsWith("shell-")}
|
||||
summary={
|
||||
@@ -135,7 +185,16 @@ export const ToolEntry = memo(function ToolEntry({
|
||||
</summary>
|
||||
}
|
||||
>
|
||||
<pre className={styles.output}>{entry.output}</pre>
|
||||
{run?.command ? (
|
||||
<div className={styles.terminalBlock}>
|
||||
<pre className={styles.terminalCommand}>
|
||||
<span className={styles.prompt}>$</span> {run.command}
|
||||
</pre>
|
||||
{run.output && <pre className={styles.terminalOutput}>{run.output}</pre>}
|
||||
</div>
|
||||
) : (
|
||||
<pre className={styles.output}>{entry.output}</pre>
|
||||
)}
|
||||
</Fold>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { AgentEntry } from "@/bindings";
|
||||
import { foldedTurns, summarizeWork, workParts } from "./timeline";
|
||||
import { foldedTurns, summarizeWork, thoughtDurations, toolDuration, toolRun, workParts } from "./timeline";
|
||||
|
||||
const user = (text: string, extra: Partial<Extract<AgentEntry, { type: "user" }>> = {}): AgentEntry => ({
|
||||
type: "user",
|
||||
@@ -65,3 +65,55 @@ describe("foldedTurns", () => {
|
||||
expect(foldedTurns([user("q"), tool("read"), agent("a")], 1, false).size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
// Fragments of a real Hermes 0.22.2 ACP stream (`hermes acp`), as the timeline folds them.
|
||||
describe("Hermes tool calls", () => {
|
||||
type Tool = Extract<AgentEntry, { type: "tool" }>;
|
||||
const call = (kind: string, extra: Partial<Tool> = {}) => tool(kind, extra) as Tool;
|
||||
const terminal = call("execute", {
|
||||
title: "terminal: echo ok + 2 commands",
|
||||
output:
|
||||
"$ echo ok >> notes.txt && wc -l notes.txt && cat notes.txt\n" +
|
||||
"terminal result\n- **output:** 3 notes.txt\nline1\nline2\nok\n- **exit_code:** 0",
|
||||
startedMs: 1000,
|
||||
endedMs: 2400,
|
||||
});
|
||||
|
||||
it("splits a terminal call into its command, output and exit code", () => {
|
||||
expect(toolRun(terminal)).toEqual({
|
||||
command: "echo ok >> notes.txt && wc -l notes.txt && cat notes.txt",
|
||||
output: "3 notes.txt\nline1\nline2\nok",
|
||||
exitCode: 0,
|
||||
});
|
||||
expect(toolRun({ ...terminal, output: "$ false\nterminal result\n- **output:**\n- **exit_code:** 1" })).toEqual({
|
||||
command: "false",
|
||||
output: "",
|
||||
exitCode: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps plain output of other agents as it is", () => {
|
||||
expect(toolRun(call("execute", { output: "ok" }))).toEqual({ command: null, output: "ok", exitCode: null });
|
||||
});
|
||||
|
||||
it("times a call once it ended", () => {
|
||||
expect(toolDuration(terminal)).toBe(1400);
|
||||
expect(toolDuration({ ...terminal, endedMs: null })).toBeNull();
|
||||
expect(toolDuration(call("read"))).toBeNull();
|
||||
});
|
||||
|
||||
it("times each thought until what came next or the end of its turn", () => {
|
||||
const entries: AgentEntry[] = [
|
||||
user("go", { doneMs: 9000 }),
|
||||
{ type: "thought", text: "plan", startedMs: 1000 },
|
||||
tool("search", { startedMs: 2500 }),
|
||||
{ type: "thought", text: "done", startedMs: 6000 },
|
||||
{ type: "agent", text: "ok" },
|
||||
{ type: "thought", text: "old" },
|
||||
];
|
||||
expect([...thoughtDurations(entries)]).toEqual([
|
||||
[1, 1500],
|
||||
[3, 3000],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -140,3 +140,58 @@ export function foldedTurns(entries: readonly AgentEntry[], from: number, busy:
|
||||
});
|
||||
return turns;
|
||||
}
|
||||
|
||||
/** A command a tool ran and how it ended, read from its output (Hermes: `$ cmd`, `- **exit_code:** 0`). */
|
||||
export interface ToolRun {
|
||||
command: string | null;
|
||||
output: string;
|
||||
exitCode: number | null;
|
||||
}
|
||||
|
||||
/** Splits an `execute` tool's text into its command, output and exit code, where it names them. */
|
||||
export function toolRun(entry: ToolEntry): ToolRun {
|
||||
const text = entry.output ?? "";
|
||||
const command = /^\$ (.+)$/m.exec(text)?.[1] ?? null;
|
||||
const code = /^- \*\*exit_code:\*\* (-?\d+)\s*$/m.exec(text);
|
||||
const output = /^- \*\*output:\*\* ?([\s\S]*?)(?=^- \*\*exit_code:\*\*|(?![\s\S]))/m.exec(text)?.[1];
|
||||
return {
|
||||
command,
|
||||
output: (output ?? (command ? text.replace(`$ ${command}`, "") : text)).trim(),
|
||||
exitCode: code ? Number(code[1]) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/** How long a tool call took, once it ended; `null` while it runs or when its times aren't known. */
|
||||
export function toolDuration(entry: ToolEntry): number | null {
|
||||
const { startedMs, endedMs } = entry;
|
||||
return startedMs != null && endedMs != null ? Math.max(0, endedMs - startedMs) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* How long each finished thought took, by index: from its start to the start of what came
|
||||
* next that keeps time (a tool call, another thought) or else the end of its turn.
|
||||
*/
|
||||
export function thoughtDurations(entries: readonly AgentEntry[]): Map<number, number> {
|
||||
const out = new Map<number, number>();
|
||||
let open: { index: number; started: number } | null = null;
|
||||
let turnEnd: number | null = null;
|
||||
// An untimed entry (older history) says nothing about when the open thought ended.
|
||||
const close = (at: number | null | undefined) => {
|
||||
if (at == null) return;
|
||||
if (open) out.set(open.index, Math.max(0, at - open.started));
|
||||
open = null;
|
||||
};
|
||||
entries.forEach((e, i) => {
|
||||
if (e.type === "user" && !e.steered) {
|
||||
close(turnEnd);
|
||||
open = null;
|
||||
turnEnd = e.doneMs ?? null;
|
||||
} else if (e.type === "tool") close(e.startedMs);
|
||||
else if (e.type === "thought" && e.startedMs != null) {
|
||||
close(e.startedMs);
|
||||
open = { index: i, started: e.startedMs };
|
||||
}
|
||||
});
|
||||
close(turnEnd);
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -2701,6 +2701,15 @@
|
||||
"Detect commands that can be run right from Markdown files": "Detect commands that can be run right from Markdown files",
|
||||
"Run commands from": "Run commands from",
|
||||
"Markdown file parent directory": "Markdown file parent directory",
|
||||
"Hermes profile": "Hermes profile",
|
||||
"Exit code": "Exit code",
|
||||
"Running": "Running",
|
||||
"The agent compressed the conversation to fit its context": "The agent compressed the conversation to fit its context",
|
||||
"compressed ×{count}": "compressed ×{count}",
|
||||
"Tokens of the last turn": "Tokens of the last turn",
|
||||
"in {count}": "in {count}",
|
||||
"cached {count}": "cached {count}",
|
||||
"out {count}": "out {count}",
|
||||
"Open Build tool window": "Open Build tool window",
|
||||
"Focus Build tool window": "Focus Build tool window",
|
||||
"Only on errors": "Only on errors",
|
||||
|
||||
@@ -9075,6 +9075,14 @@
|
||||
"Detect commands that can be run right from Markdown files": "检测可以直接从 Markdown 文件运行的命令",
|
||||
"Run commands from": "运行命令的目录",
|
||||
"Markdown file parent directory": "Markdown 文件的父目录",
|
||||
"Hermes profile": "Hermes 配置文件",
|
||||
"Exit code": "退出码",
|
||||
"The agent compressed the conversation to fit its context": "智能体压缩了对话以适应其上下文",
|
||||
"compressed ×{count}": "已压缩 ×{count}",
|
||||
"Tokens of the last turn": "上一轮的令牌",
|
||||
"in {count}": "输入 {count}",
|
||||
"cached {count}": "缓存 {count}",
|
||||
"out {count}": "输出 {count}",
|
||||
"Open Build tool window": "打开构建工具窗口",
|
||||
"Focus Build tool window": "聚焦构建工具窗口",
|
||||
"Only on errors": "仅在出错时",
|
||||
|
||||
@@ -269,6 +269,7 @@ const ICONS = {
|
||||
"agent-kiro": "openidea/agents/kiro",
|
||||
"agent-vibe": "openidea/agents/vibe",
|
||||
"agent-omp": "openidea/agents/omp",
|
||||
"agent-hermes": "openidea/agents/hermes",
|
||||
"agent-deepseek-harness": "brands/deepseek",
|
||||
"toolwindow-maven": "toolwindows/maven",
|
||||
"toolwindow-gradle": "toolwindows/gradle",
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
|
||||
<path fill="#c9a227" d="M7.25 1h1.5v14h-1.5z" />
|
||||
<path fill="#c9a227" d="M2 3.2 6.5 4.6v1.6L2 4.8zm12 0-4.5 1.4v1.6L14 4.8z" />
|
||||
<path fill="none" stroke="#6fa8dc" stroke-width="1.4" d="M5 7.5c3 1.2 3 2.3 0 3.5s0 2.3 3 3m3-6.5c-3 1.2-3 2.3 0 3.5s0 2.3-3 3" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 356 B |
Reference in New Issue
Block a user