diff --git a/CHANGELOG.md b/CHANGELOG.md index 04c0bd5e..f1f5e2df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,18 @@ and listed with their assets on the prompt, a hook's text, a tool's arguments or its answer, on this machine, for a week (ADR-0098). The agent's own tools (its shell, its edits) do not pass devstack and are not shown. +- **A lane shows its agents' sessions in time.** The lane's Activity has a + second view, Timeline: per session, the prompts (when, never what), the + model's turns, every tool call by where it went (devstack, an upstream, + another MCP server, the agent's own tools, sub-agents) with how long it + took, what changed the lane and the hooks given; below, how full the + context was and the tokens summed up (cache read, written, input, output). + Pauses longer than two minutes are pushed together; hovering a call says + the tokens used until then. The turns, tokens and the agent's own tools + come from the agent's transcript, which the hub reads only once + **Read transcripts** is switched on (off by default), for Claude Code and + Codex, taking only times, counts and names (ADR-0099). The activity list + of the Skills page moved here. ## [0.42.0] - 2026-11-06 diff --git a/crates/devstack-hub/src/activity.rs b/crates/devstack-hub/src/activity.rs index 99dbcd37..cc9ae369 100644 --- a/crates/devstack-hub/src/activity.rs +++ b/crates/devstack-hub/src/activity.rs @@ -56,6 +56,11 @@ pub enum Record { /// `session-end`: the end was kept for the next start. #[serde(default, skip_serializing_if = "std::ops::Not::not")] recorded: bool, + /// Where the agent keeps the session's transcript, as its hook's + /// input names it: the path only, never what is in it. The + /// timeline reads it when switched on (`transcript`). + #[serde(default, skip_serializing_if = "Option::is_none")] + transcript: Option, }, /// A tool call through `devstack mcp`. Tool { @@ -251,6 +256,10 @@ pub fn view( let mut out = Vec::new(); for r in records { let mut v = serde_json::to_value(r).expect("serialises"); + // The transcript's path is the timeline's, not the page's. + if let Some(o) = v.as_object_mut() { + o.remove("transcript"); + } // A record without a session of its own (a tool call, a lane's // stop): the latest session that started in its tree before it. let own = matches!( @@ -299,6 +308,9 @@ pub fn view( if out.len() > MAX { out.drain(..out.len() - MAX); } + if let Some(t) = tree { + sessions.retain(|s| s.tree == t); + } sessions.sort_by_key(|s| std::cmp::Reverse(s.last)); View { sessions, @@ -361,6 +373,7 @@ mod tests { tree: tree.into(), hooks: Vec::new(), recorded: event == "session-end", + transcript: None, } } @@ -441,6 +454,7 @@ mod tests { tree: "/a".into(), hooks: Vec::new(), recorded: false, + transcript: None, }, ]; let v = view(&records, None, None, None, &prefixes, &index); diff --git a/crates/devstack-hub/src/agenthooks.rs b/crates/devstack-hub/src/agenthooks.rs index dcd0b4fc..4aeebe1d 100644 --- a/crates/devstack-hub/src/agenthooks.rs +++ b/crates/devstack-hub/src/agenthooks.rs @@ -312,7 +312,8 @@ struct Input { /// Why a session starts: `startup`, `resume`, `clear`, `compact`. #[serde(default)] source: Option, - /// The session's transcript (`session-end`): named at the next start. + /// The session's transcript: named at the next start (`session-end`), + /// and recorded for the timeline (its path only). #[serde(default, alias = "transcriptPath")] transcript_path: Option, } @@ -483,6 +484,7 @@ fn record( tree: cwd.map(tree_of).unwrap_or_default(), hooks, recorded, + transcript: input.transcript_path.clone().filter(|s| !s.is_empty()), }; if let Err(e) = crate::activity::write(at.state, &r) { (at.warn)(e); diff --git a/crates/devstack-hub/src/lib.rs b/crates/devstack-hub/src/lib.rs index f4153873..6c479f12 100644 --- a/crates/devstack-hub/src/lib.rs +++ b/crates/devstack-hub/src/lib.rs @@ -56,6 +56,7 @@ mod share; mod shared; mod stdio; mod summary; +mod transcript; pub mod tray; pub mod upstreams; mod watchdog; @@ -664,6 +665,11 @@ fn router(state: AppState) -> axum::Router { .route("/hub/pool/skills/{name}", delete(pool::skill_remove)) .route("/hub/skills", get(poolskills::get)) .route("/hub/activity", get(activity_get)) + .route("/hub/activity/timeline", get(timeline_get)) + .route( + "/hub/activity/transcripts", + get(transcripts_get).put(transcripts_put), + ) .route("/hub/skills/sync", post(poolskills::sync)) .route("/hub/skills/agents/{id}", put(poolskills::agent)) .route("/hub/skills/sets/{pool}/{set}", put(poolskills::auto)) @@ -2914,9 +2920,14 @@ async fn activity_get(State(s): State, Query(q): Query) .filter_map(|v| v.pool.map(|p| (p.pool, p.name, v.prefix))) .collect(); let index = agenthooks::read_index(&state); + // A tree as the records write it, whatever separators or case the page used. + let tree = q + .tree + .as_deref() + .map(|t| activity::tree_of(std::path::Path::new(t))); activity::view( &records, - q.tree.as_deref(), + tree.as_deref(), q.session.as_deref(), q.since, &prefixes, @@ -2930,6 +2941,62 @@ async fn activity_get(State(s): State, Query(q): Query) } } +#[derive(Deserialize)] +struct TimelineQuery { + session: String, + #[serde(default)] + agent: Option, +} + +/// `GET /hub/activity/timeline?session=&agent=`: a session in time, from +/// devstack's records and, when switched on, the agent's transcript. +async fn timeline_get(State(s): State, Query(q): Query) -> Response { + let ups = s.upstreams.clone(); + let got = tokio::task::spawn_blocking(move || { + let state = activity::state(); + let records = activity::read(&state); + let prefixes: activity::Prefixes = ups + .views() + .unwrap_or_default() + .into_iter() + .filter_map(|v| v.pool.map(|p| (p.pool, p.name, v.prefix))) + .collect(); + let index = agenthooks::read_index(&state); + let enabled = transcript::Setting::load(&state).enabled; + transcript::timeline( + &records, + &q.session, + q.agent.as_deref(), + &prefixes, + &index, + enabled, + ) + }) + .await; + match got { + Ok(Some(v)) => Json(v).into_response(), + Ok(None) => err(StatusCode::NOT_FOUND, "no such session"), + Err(e) => err(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()), + } +} + +/// `GET /hub/activity/transcripts`: whether the hub reads the agents' +/// transcripts for the timeline (off until switched on). +async fn transcripts_get() -> Response { + Json(transcript::Setting::load(&activity::state())).into_response() +} + +/// `PUT /hub/activity/transcripts {enabled}`: switch it on or off. +async fn transcripts_put(Json(b): Json) -> Response { + match transcript::Setting::save(b, &activity::state()) { + Ok(()) => { + devstack_daemon::diag::info("transcripts", serde_json::json!({ "enabled": b.enabled })); + Json(b).into_response() + } + Err(e) => err(StatusCode::INTERNAL_SERVER_ERROR, e), + } +} + /// `DELETE /hub/upstreams/{name}`: it and its credential go. async fn upstream_remove(State(s): State, Path(name): Path) -> Response { on_upstreams(&s, move |ups| { diff --git a/crates/devstack-hub/src/transcript.rs b/crates/devstack-hub/src/transcript.rs new file mode 100644 index 00000000..225250d3 --- /dev/null +++ b/crates/devstack-hub/src/transcript.rs @@ -0,0 +1,960 @@ +//! A coding agent's session in time (the lane's Activity, view Timeline): +//! what devstack recorded for it, and, once switched on, what the agent's +//! own transcript tells: the model's turns with their tokens, every tool +//! call with how long it took, when a prompt came. +//! +//! - **Only times, counts and names.** A reader takes from the transcript +//! the moments, the model's name, the token counts and the tools' names; +//! never a prompt, an answer, a tool's arguments or its output. Nothing +//! of it is kept: the hub reads the file when the page asks, on this +//! machine. The path comes from the agent's hooks (`transcript_path`). +//! - **Off until switched on**, per machine (`transcripts.json` in the +//! hub's state). Off, the timeline holds devstack's records only. +//! - **A reader per agent.** Every agent keeps its own format: Claude Code +//! a JSONL of messages with their `usage`, Codex a rollout of events with +//! `token_count`. An agent without a reader shows devstack's records. + +use crate::activity::{Prefixes, Record}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::collections::HashMap; +use std::io::BufRead as _; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +/// The setting's file in the hub's state. +const SETTING: &str = "transcripts.json"; + +/// Whether the hub reads the agents' transcripts. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Setting { + pub enabled: bool, +} + +impl Setting { + pub fn load(state: &Path) -> Self { + std::fs::read_to_string(state.join(SETTING)) + .ok() + .and_then(|s| serde_json::from_str(&s).ok()) + .unwrap_or_default() + } + + pub fn save(self, state: &Path) -> Result<(), String> { + std::fs::create_dir_all(state).map_err(|e| e.to_string())?; + let path = state.join(SETTING); + std::fs::write(&path, serde_json::to_string(&self).expect("serialises")) + .map_err(|e| format!("{}: {e}", path.display())) + } +} + +/// An answer of the model: when, which model, the tokens it took. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +pub struct Turn { + pub at: u64, + #[serde(skip_serializing_if = "Option::is_none")] + pub model: Option, + /// Input not from the cache. + pub input: u64, + pub cache_write: u64, + pub cache_read: u64, + pub output: u64, + /// A sub-agent's. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub sidechain: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Kind { + /// One of devstack's own tools. + Devstack, + /// A pool upstream's, through `devstack mcp`. + Upstream, + /// Another MCP server's. + Mcp, + /// The agent's own tool (shell, editing, reading). + Builtin, + /// A sub-agent. + Agent, +} + +/// A tool call: its name and how long it took. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Call { + pub at: u64, + /// None: no answer (yet). + pub ms: Option, + pub tool: String, + pub kind: Kind, + pub ok: bool, + /// `Upstream`: which; `Mcp`: the server. + #[serde(skip_serializing_if = "Option::is_none")] + pub upstream: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum MarkKind { + Prompt, + Interrupt, + Compact, + Clear, + Error, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct Mark { + pub at: u64, + pub kind: MarkKind, +} + +/// What a reader took from a transcript. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Parsed { + pub turns: Vec, + pub calls: Vec, + pub marks: Vec, +} + +/// The format of an agent's transcripts, by the agent's id; None: devstack +/// cannot read this agent's. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Format { + Claude, + Codex, +} + +fn format(agent: &str) -> Option { + match agent { + "claude-code" | "claude" => Some(Format::Claude), + "codex" => Some(Format::Codex), + _ => None, + } +} + +/// A reader's state after the lines it was fed. +#[derive(Debug, Clone)] +enum State { + Claude(Claude), + Codex(Codex), +} + +impl State { + fn line(&mut self, l: &Value) { + match self { + State::Claude(c) => c.line(l), + State::Codex(c) => c.line(l), + } + } + + fn parsed(&self) -> Parsed { + match self { + State::Claude(c) => c.out.clone(), + State::Codex(c) => c.parsed(), + } + } +} + +/// A file followed: how far it was read, and the reader's state there. A +/// transcript only grows while its session runs, so it is read once and +/// then only what was added. +#[derive(Debug, Clone)] +struct Followed { + format: Format, + sidechain: bool, + offset: u64, + state: State, +} + +impl Followed { + fn new(format: Format, sidechain: bool) -> Self { + let state = match format { + Format::Claude => State::Claude(Claude { + sidechain, + ..Claude::default() + }), + Format::Codex => State::Codex(Codex::default()), + }; + Followed { + format, + sidechain, + offset: 0, + state, + } + } + + /// Read what was added since the last time: whole lines only (one being + /// written is read the next time). A file shorter than what was read + /// was written anew: from its start. + fn read(&mut self, path: &Path) -> std::io::Result<()> { + use std::io::{Seek as _, SeekFrom}; + let mut file = std::fs::File::open(path)?; + if file.metadata()?.len() < self.offset { + *self = Followed::new(self.format, self.sidechain); + } + file.seek(SeekFrom::Start(self.offset))?; + let mut r = std::io::BufReader::new(file); + let mut buf = Vec::new(); + loop { + buf.clear(); + let n = r.read_until(b'\n', &mut buf)?; + if n == 0 || buf.last() != Some(&b'\n') { + return Ok(()); + } + self.offset += n as u64; + // A line that is not JSON is skipped. + if let Ok(v) = serde_json::from_slice::(&buf) { + self.state.line(&v); + } + } + } +} + +/// A session's transcript at `path` read on from where `files` left it; a +/// Claude Code session with its sub-agents' files beside it +/// (`/subagents/*.jsonl`). None: the transcript cannot be read. +fn session(format: Format, path: &Path, files: &mut HashMap) -> Option { + let main = files + .entry(path.to_path_buf()) + .or_insert_with(|| Followed::new(format, false)); + main.read(path).ok()?; + let mut out = main.state.parsed(); + if format == Format::Claude + && let Ok(rd) = std::fs::read_dir(path.with_extension("").join("subagents")) + { + for e in rd.flatten() { + let p = e.path(); + if p.extension().is_none_or(|x| x != "jsonl") { + continue; + } + let f = files + .entry(p.clone()) + .or_insert_with(|| Followed::new(format, true)); + if f.read(&p).is_ok() { + out.turns.extend(f.state.parsed().turns); + } + } + out.turns.sort_by_key(|t| t.at); + } + Some(out) +} + +/// An ISO 8601 time as Unix ms. +fn ms(v: &Value) -> Option { + let t: jiff::Timestamp = v.as_str()?.parse().ok()?; + u64::try_from(t.as_millisecond()).ok() +} + +fn num(v: &Value) -> u64 { + v.as_u64().unwrap_or(0) +} + +/// A tool's name as the agent calls it: an MCP server's `mcp____`. +fn split_mcp(name: &str) -> Option<(&str, &str)> { + name.strip_prefix("mcp__")?.split_once("__") +} + +/// Claude Code: a JSONL of messages. An answer of the model comes as one +/// line per part with the same `message.id` and its `usage`; a tool call is +/// a `tool_use` part, its answer a `tool_result` in a later user line; a +/// prompt is a user line with text; a compaction a `compact_boundary`. A +/// sub-agent's turns are marked `isSidechain`, or kept beside the transcript +/// (`/subagents/*.jsonl`). Fed line by line. +#[derive(Debug, Clone, Default)] +struct Claude { + out: Parsed, + /// A message's turn, by its id: the first line's time, the last line's usage. + turns: HashMap, + /// A call waiting for its answer, by the tool_use id. + open: HashMap, + /// A sub-agent's file: every turn is its. + sidechain: bool, +} + +impl Claude { + fn line(&mut self, l: &Value) { + let Some(at) = ms(&l["timestamp"]) else { + if l["type"] == "system" && l["subtype"] == "compact_boundary" { + // Without a time of its own: right after the last thing seen. + let at = self.out.turns.last().map_or(0, |t| t.at + 1); + self.out.marks.push(Mark { + at, + kind: MarkKind::Compact, + }); + } + return; + }; + let side = self.sidechain || l["isSidechain"] == true; + match l["type"].as_str() { + Some("assistant") => { + let m = &l["message"]; + if l["isApiErrorMessage"] == true { + self.out.marks.push(Mark { + at, + kind: MarkKind::Error, + }); + return; + } + let u = &m["usage"]; + let turn = Turn { + at, + model: m["model"] + .as_str() + .filter(|s| !s.starts_with('<')) + .map(String::from), + input: num(&u["input_tokens"]), + cache_write: num(&u["cache_creation_input_tokens"]), + cache_read: num(&u["cache_read_input_tokens"]), + output: num(&u["output_tokens"]), + sidechain: side, + }; + let id = m["id"].as_str().unwrap_or_default().to_string(); + match self.turns.get(&id).filter(|_| !id.is_empty()) { + Some(&i) => { + let t = &mut self.out.turns[i]; + t.input = t.input.max(turn.input); + t.cache_write = t.cache_write.max(turn.cache_write); + t.cache_read = t.cache_read.max(turn.cache_read); + t.output = t.output.max(turn.output); + } + None => { + self.turns.insert(id, self.out.turns.len()); + self.out.turns.push(turn); + } + } + if side { + return; + } + for c in m["content"].as_array().into_iter().flatten() { + if c["type"] != "tool_use" { + return; + } + let name = c["name"].as_str().unwrap_or("?"); + let (tool, kind, upstream) = match split_mcp(name) { + Some((server, tool)) => { + (tool.to_string(), Kind::Mcp, Some(server.to_string())) + } + None if name == "Task" || name == "Agent" => { + (name.to_string(), Kind::Agent, None) + } + None => (name.to_string(), Kind::Builtin, None), + }; + if let Some(id) = c["id"].as_str() { + self.open.insert(id.to_string(), self.out.calls.len()); + } + self.out.calls.push(Call { + at, + ms: None, + tool, + kind, + ok: true, + upstream, + }); + } + } + Some("user") if !side => { + let content = &l["message"]["content"]; + let mut text = content.as_str().map(str::to_string); + for c in content.as_array().into_iter().flatten() { + match c["type"].as_str() { + Some("tool_result") => { + if let Some(&i) = + c["tool_use_id"].as_str().and_then(|id| self.open.get(id)) + { + let call = &mut self.out.calls[i]; + call.ms = Some(at.saturating_sub(call.at)); + call.ok = c["is_error"] != true; + } + } + Some("text") if text.is_none() => { + text = c["text"].as_str().map(str::to_string); + } + _ => {} + } + } + // Read only to tell what the line is, never kept. + let Some(text) = text else { return }; + // Not the user's: text the agent added, a summary, a + // background task's notice (`origin`). + if l["isMeta"] == true || l["isCompactSummary"] == true || l["origin"].is_object() { + return; + } + let t = text.trim_start(); + if t.starts_with("[Request interrupted") { + self.out.marks.push(Mark { + at, + kind: MarkKind::Interrupt, + }); + } else if t.starts_with("/clear") { + self.out.marks.push(Mark { + at, + kind: MarkKind::Clear, + }); + } else if !(t.starts_with(" self.out.marks.push(Mark { + at, + kind: MarkKind::Compact, + }), + _ => {} + } + } +} + +/// Codex: a rollout of events. `token_count` carries the last turn's usage +/// (`last_token_usage`; given twice, the second time with the same total), +/// `user_message` a prompt (an older rollout has none: `task_started` +/// instead), `turn_aborted` an interruption; a call is a `function_call` (or `custom_tool_call`) with +/// its output by `call_id`, an MCP server's tool an `mcp_tool_call_end` with +/// its server and duration; `turn_context` names the model. Fed line by +/// line. +#[derive(Debug, Clone, Default)] +struct Codex { + out: Parsed, + model: Option, + open: HashMap, + mcp_ids: Vec, + /// The total of the last `token_count`: the same again is no new turn. + total: Option, + /// `task_started`: the prompts of a rollout without `user_message`. + tasks: Vec, +} + +impl Codex { + fn line(&mut self, l: &Value) { + let Some(at) = ms(&l["timestamp"]) else { + return; + }; + let p = &l["payload"]; + match (l["type"].as_str(), p["type"].as_str()) { + (Some("turn_context"), _) => { + self.model = p["model"].as_str().map(String::from).or(self.model.take()); + } + (Some("event_msg"), Some("user_message")) => self.out.marks.push(Mark { + at, + kind: MarkKind::Prompt, + }), + (Some("event_msg"), Some("task_started")) => self.tasks.push(Mark { + at, + kind: MarkKind::Prompt, + }), + (Some("event_msg"), Some("turn_aborted")) => self.out.marks.push(Mark { + at, + kind: MarkKind::Interrupt, + }), + (Some("event_msg"), Some("context_compacted")) | (Some("compacted"), _) => { + self.out.marks.push(Mark { + at, + kind: MarkKind::Compact, + }); + } + (Some("event_msg"), Some("stream_error" | "error")) => self.out.marks.push(Mark { + at, + kind: MarkKind::Error, + }), + (Some("event_msg"), Some("token_count")) => { + let u = &p["info"]["last_token_usage"]; + let sum = p["info"]["total_token_usage"]["total_tokens"].as_u64(); + if u.is_null() || (sum.is_some() && sum == self.total) { + return; + } + self.total = sum; + let cached = num(&u["cached_input_tokens"]); + let written = num(&u["cache_write_input_tokens"]); + self.out.turns.push(Turn { + at, + model: self.model.clone(), + input: num(&u["input_tokens"]).saturating_sub(cached + written), + cache_write: written, + cache_read: cached, + output: num(&u["output_tokens"]), + sidechain: false, + }); + } + (Some("event_msg"), Some("mcp_tool_call_end")) => { + let inv = &p["invocation"]; + let took = codex_duration(&p["duration"]); + if let Some(id) = p["call_id"].as_str() { + self.mcp_ids.push(id.to_string()); + } + self.out.calls.push(Call { + at: took.map_or(at, |d| at.saturating_sub(d)), + ms: took, + tool: inv["tool"].as_str().unwrap_or("?").to_string(), + kind: Kind::Mcp, + ok: p["result"].get("Err").is_none() && p["result"]["Ok"]["isError"] != true, + upstream: inv["server"].as_str().map(String::from), + }); + } + (Some("response_item"), Some("function_call" | "custom_tool_call")) => { + if let Some(id) = p["call_id"].as_str() { + self.open.insert(id.to_string(), self.out.calls.len()); + } + self.out.calls.push(Call { + at, + ms: None, + tool: p["name"].as_str().unwrap_or("?").to_string(), + kind: Kind::Builtin, + ok: true, + upstream: None, + }); + } + (Some("response_item"), Some("function_call_output" | "custom_tool_call_output")) => { + if let Some(&i) = p["call_id"].as_str().and_then(|id| self.open.get(id)) { + let c = &mut self.out.calls[i]; + c.ms = Some(at.saturating_sub(c.at)); + } + } + _ => {} + } + } + + fn parsed(&self) -> Parsed { + let mut out = self.out.clone(); + if !out.marks.iter().any(|m| m.kind == MarkKind::Prompt) { + out.marks.extend(self.tasks.iter().copied()); + out.marks.sort_by_key(|m| m.at); + } + // An MCP tool's call shows once: as the MCP event, which names its server. + let mcp: Vec = self + .mcp_ids + .iter() + .filter_map(|id| self.open.get(id).copied()) + .collect(); + let mut i = 0; + out.calls.retain(|_| { + i += 1; + !mcp.contains(&(i - 1)) + }); + out.calls.sort_by_key(|c| c.at); + out + } +} + +/// A whole file, as one look reads it. +#[cfg(test)] +fn claude(path: &Path) -> Parsed { + session(Format::Claude, path, &mut HashMap::new()).unwrap_or_default() +} + +#[cfg(test)] +fn codex(path: &Path) -> Parsed { + session(Format::Codex, path, &mut HashMap::new()).unwrap_or_default() +} + +/// Codex's duration: `{secs, nanos}`, or a string such as `1.2s`. +fn codex_duration(v: &Value) -> Option { + if let Some(s) = v["secs"].as_u64() { + return Some(s * 1000 + v["nanos"].as_u64().unwrap_or(0) / 1_000_000); + } + let s = v.as_str()?; + if let Some(ms) = s.strip_suffix("ms") { + return ms.trim().parse::().ok().map(|x| x as u64); + } + s.strip_suffix('s')? + .trim() + .parse::() + .ok() + .map(|x| (x * 1000.0) as u64) +} + +/// A call through `devstack mcp`: one of devstack's own tools, or an +/// upstream's by its prefix (`__`). +fn through_devstack(tool: &str, prefixes: &Prefixes) -> (Kind, Option) { + match tool + .split_once("__") + .and_then(|(p, _)| prefixes.iter().find(|(_, _, x)| x == p)) + { + Some((_, name, _)) => (Kind::Upstream, Some(name.clone())), + None => (Kind::Devstack, None), + } +} + +/// The MCP servers' calls that went through devstack: the server's name is +/// devstack's (the agent registered it so), or the call matches one of +/// devstack's records (same tool, within two seconds). +fn classify(calls: &mut [Call], own: &[(u64, String)], prefixes: &Prefixes) { + for c in calls.iter_mut().filter(|c| c.kind == Kind::Mcp) { + let by_name = c.upstream.as_deref().is_some_and(|s| s == "devstack"); + let by_record = own + .iter() + .any(|(at, tool)| tool == &c.tool && at.abs_diff(c.at) < 2_000); + if by_name || by_record { + (c.kind, c.upstream) = through_devstack(&c.tool, prefixes); + } + } +} + +/// The transcripts followed, by path. +static FILES: Mutex>> = Mutex::new(None); + +/// A session's transcript, read on from where the last look left it. +fn cached(format: Format, path: &Path) -> Option { + let mut g = FILES.lock().unwrap_or_else(|e| e.into_inner()); + let files = g.get_or_insert_with(HashMap::new); + // A handful of sessions (and their sub-agents) are looked at; the rest go. + if files.len() > 64 { + files.clear(); + } + session(format, path, files) +} + +/// `agent`'s session `session` in time: devstack's records of it and, with +/// `enabled`, its transcript's turns, calls and marks. None: no such session. +pub fn timeline( + records: &[Record], + session: &str, + agent: Option<&str>, + prefixes: &Prefixes, + index: &crate::agenthooks::Index, + enabled: bool, +) -> Option { + let view = crate::activity::view(records, None, Some(session), None, prefixes, index); + let s = view + .sessions + .iter() + .find(|s| s.session == session && agent.is_none_or(|a| a == s.agent))? + .clone(); + let hooks: Vec<&Value> = view + .records + .iter() + .filter(|r| r["kind"] == "hook") + .collect(); + let own: Vec = view + .records + .iter() + .filter(|r| r["kind"] == "tool") + .map(|r| { + let tool = r["tool"].as_str().unwrap_or("?").to_string(); + let took = r["ms"].as_u64().unwrap_or(0); + let (kind, upstream) = through_devstack(&tool, prefixes); + Call { + // Recorded when it ended. + at: r["at"].as_u64().unwrap_or(0).saturating_sub(took), + ms: Some(took), + tool, + kind, + ok: r["ok"] == true, + upstream, + } + }) + .collect(); + // The latest path the session's hooks named. + let path = records.iter().rev().find_map(|r| match r { + Record::Hook { + session: Some(id), + agent: a, + transcript: Some(t), + .. + } if id == session && a == &s.agent => Some(PathBuf::from(t)), + _ => None, + }); + let (source, why, parsed) = match (enabled, format(&s.agent), path) { + (false, ..) => ("activity", Some("off"), None), + (true, None, _) => ("activity", Some("agent"), None), + (true, Some(_), None) => ("activity", Some("missing"), None), + (true, Some(f), Some(p)) => match cached(f, &p) { + Some(parsed) => ("transcript", None, Some(parsed)), + None => ("activity", Some("missing"), None), + }, + }; + let (turns, calls, marks) = match parsed { + Some(mut p) => { + let mine: Vec<(u64, String)> = own + .iter() + .map(|c| (c.at + c.ms.unwrap_or(0), c.tool.clone())) + .collect(); + classify(&mut p.calls, &mine, prefixes); + (p.turns, p.calls, p.marks) + } + None => (Vec::new(), own, Vec::new()), + }; + let mut v = serde_json::to_value(&s).expect("serialises"); + v["source"] = source.into(); + if let Some(w) = why { + v["why"] = w.into(); + } + v["turns"] = serde_json::to_value(turns).expect("serialises"); + v["calls"] = serde_json::to_value(calls).expect("serialises"); + v["marks"] = serde_json::to_value(marks).expect("serialises"); + v["hooks"] = serde_json::to_value(hooks).expect("serialises"); + Some(v) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Write as _; + + fn file(lines: &[Value]) -> tempfile::NamedTempFile { + let mut f = tempfile::NamedTempFile::new().unwrap(); + for l in lines { + writeln!(f, "{l}").unwrap(); + } + f + } + + const T0: &str = "2026-11-09T13:00:00.000Z"; + fn at(s: u64) -> String { + format!("2026-11-09T13:00:{s:02}.000Z") + } + fn base() -> u64 { + ms(&Value::from(T0)).unwrap() + } + + #[test] + fn claude_turns_once_per_message_calls_with_their_time_prompts_without_text() { + let f = file(&[ + serde_json::json!({"type":"user","timestamp":at(0),"message":{"role":"user","content":"secret prompt text"}}), + serde_json::json!({"type":"assistant","timestamp":at(2),"message":{"id":"m1","model":"claude-opus","content":[{"type":"text","text":"x"}],"usage":{"input_tokens":2,"cache_creation_input_tokens":900,"cache_read_input_tokens":60000,"output_tokens":10}}}), + serde_json::json!({"type":"assistant","timestamp":at(3),"message":{"id":"m1","model":"claude-opus","content":[{"type":"tool_use","id":"t1","name":"Bash","input":{"command":"rm -rf secret"}}],"usage":{"input_tokens":2,"cache_creation_input_tokens":900,"cache_read_input_tokens":60000,"output_tokens":248}}}), + serde_json::json!({"type":"assistant","timestamp":at(3),"message":{"id":"m1","model":"claude-opus","content":[{"type":"tool_use","id":"t2","name":"mcp__devstack__nuts_timetrack__start_timer","input":{}}],"usage":{"input_tokens":2,"cache_creation_input_tokens":900,"cache_read_input_tokens":60000,"output_tokens":248}}}), + serde_json::json!({"type":"user","timestamp":at(8),"message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","is_error":true,"content":"secret output"}]}}), + serde_json::json!({"type":"user","timestamp":at(9),"message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t2","content":"ok"}]}}), + serde_json::json!({"type":"system","subtype":"compact_boundary","timestamp":at(20)}), + serde_json::json!({"type":"user","timestamp":at(21),"isCompactSummary":true,"message":{"role":"user","content":"summary"}}), + serde_json::json!({"type":"user","timestamp":at(30),"message":{"role":"user","content":[{"type":"text","text":"[Request interrupted by user]"}]}}), + serde_json::json!({"type":"user","timestamp":at(31),"isMeta":true,"message":{"role":"user","content":""}}), + serde_json::json!({"type":"user","timestamp":at(32),"origin":{"kind":"task-notification"},"message":{"role":"user","content":"done"}}), + serde_json::json!({"type":"assistant","timestamp":at(40),"isSidechain":true,"message":{"id":"m2","model":"claude-haiku","content":[{"type":"tool_use","id":"t3","name":"Read"}],"usage":{"input_tokens":5,"output_tokens":7}}}), + ]); + let p = claude(f.path()); + let b = base(); + assert_eq!(p.turns.len(), 2, "{:?}", p.turns); + assert_eq!( + p.turns[0], + Turn { + at: b + 2000, + model: Some("claude-opus".into()), + input: 2, + cache_write: 900, + cache_read: 60000, + output: 248, + sidechain: false + } + ); + assert!(p.turns[1].sidechain); + // A sub-agent's calls are its own: not on the main agent's rows. + assert_eq!(p.calls.len(), 2); + assert_eq!( + (p.calls[0].tool.as_str(), p.calls[0].ms, p.calls[0].ok), + ("Bash", Some(5000), false) + ); + assert_eq!(p.calls[1].kind, Kind::Mcp); + assert_eq!(p.calls[1].upstream.as_deref(), Some("devstack")); + assert_eq!(p.calls[1].tool, "nuts_timetrack__start_timer"); + let kinds: Vec = p.marks.iter().map(|m| m.kind).collect(); + assert_eq!( + kinds, + [MarkKind::Prompt, MarkKind::Compact, MarkKind::Interrupt] + ); + // Nothing of what was said or done is in what the reader took. + let all = format!("{p:?}"); + for word in ["secret", "summary", "rm -rf"] { + assert!(!all.contains(word), "{word} in {all}"); + } + } + + #[test] + fn claude_reads_the_sub_agents_kept_beside_the_transcript() { + let d = tempfile::tempdir().unwrap(); + let main = d.path().join("s1.jsonl"); + std::fs::write(&main, format!("{}\n", serde_json::json!({"type":"assistant","timestamp":at(1),"message":{"id":"a","usage":{"output_tokens":1}}}))).unwrap(); + std::fs::create_dir_all(d.path().join("s1").join("subagents")).unwrap(); + std::fs::write( + d.path().join("s1").join("subagents").join("agent-x.jsonl"), + format!("{}\n", serde_json::json!({"type":"assistant","timestamp":at(5),"message":{"id":"b","usage":{"output_tokens":9}}})), + ) + .unwrap(); + let p = claude(&main); + assert_eq!( + p.turns + .iter() + .map(|t| (t.output, t.sidechain)) + .collect::>(), + [(1, false), (9, true)] + ); + } + + #[test] + fn codex_turns_from_token_counts_and_mcp_calls_once() { + let f = file(&[ + serde_json::json!({"timestamp":at(0),"type":"turn_context","payload":{"model":"gpt-5-codex"}}), + serde_json::json!({"timestamp":at(1),"type":"event_msg","payload":{"type":"user_message","message":"secret"}}), + serde_json::json!({"timestamp":at(2),"type":"response_item","payload":{"type":"function_call","name":"shell","arguments":"{\"cmd\":\"secret\"}","call_id":"c1"}}), + serde_json::json!({"timestamp":at(6),"type":"response_item","payload":{"type":"function_call_output","call_id":"c1","output":"secret"}}), + serde_json::json!({"timestamp":at(7),"type":"response_item","payload":{"type":"function_call","name":"mcp__devstack__up","call_id":"c2"}}), + serde_json::json!({"timestamp":at(9),"type":"event_msg","payload":{"type":"mcp_tool_call_end","call_id":"c2","invocation":{"server":"devstack","tool":"up","arguments":{}},"duration":{"secs":2,"nanos":0},"result":{"Ok":{"content":[]}}}}), + serde_json::json!({"timestamp":at(10),"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"total_tokens":1050},"last_token_usage":{"input_tokens":1000,"cached_input_tokens":800,"output_tokens":50}}}}), + serde_json::json!({"timestamp":at(11),"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"total_tokens":1050},"last_token_usage":{"input_tokens":1000,"cached_input_tokens":800,"output_tokens":50}}}}), + serde_json::json!({"timestamp":at(11),"type":"event_msg","payload":{"type":"token_count","info":null}}), + serde_json::json!({"timestamp":at(12),"type":"event_msg","payload":{"type":"turn_aborted"}}), + ]); + let p = codex(f.path()); + let b = base(); + assert_eq!( + p.turns, + [Turn { + at: b + 10_000, + model: Some("gpt-5-codex".into()), + input: 200, + cache_write: 0, + cache_read: 800, + output: 50, + sidechain: false + }] + ); + assert_eq!(p.calls.len(), 2, "{:?}", p.calls); + assert_eq!( + (p.calls[0].tool.as_str(), p.calls[0].ms), + ("shell", Some(4000)) + ); + assert_eq!( + ( + p.calls[1].tool.as_str(), + p.calls[1].kind, + p.calls[1].ms, + p.calls[1].at + ), + ("up", Kind::Mcp, Some(2000), b + 7000) + ); + assert_eq!( + p.marks.iter().map(|m| m.kind).collect::>(), + [MarkKind::Prompt, MarkKind::Interrupt] + ); + assert!(!format!("{p:?}").contains("secret")); + } + + fn hook(at: u64, session: &str, transcript: Option<&Path>) -> Record { + Record::Hook { + at, + event: "session-start".into(), + agent: "claude-code".into(), + session: Some(session.into()), + tree: "/w".into(), + hooks: Vec::new(), + recorded: false, + transcript: transcript.map(|p| p.to_string_lossy().into_owned()), + } + } + fn tool(at: u64, name: &str, took: u64) -> Record { + Record::Tool { + at, + tool: name.into(), + client: None, + tree: "/w".into(), + pid: 1, + ms: took, + ok: true, + } + } + + #[test] + fn the_timeline_holds_devstacks_records_until_transcripts_are_switched_on() { + let b = base(); + let f = file(&[ + serde_json::json!({"type":"user","timestamp":at(0),"message":{"content":"go"}}), + serde_json::json!({"type":"assistant","timestamp":at(2),"message":{"id":"m","content":[{"type":"tool_use","id":"t","name":"mcp__ds__tt__start_timer"}],"usage":{"output_tokens":5}}}), + serde_json::json!({"type":"user","timestamp":at(3),"message":{"content":[{"type":"tool_result","tool_use_id":"t"}]}}), + ]); + let records = [ + hook(b, "s", Some(f.path())), + tool(b + 3000, "tt__start_timer", 900), + ]; + let prefixes: Prefixes = vec![("default".into(), "timetrack".into(), "tt".into())]; + let index = crate::agenthooks::Index::default(); + + let off = timeline(&records, "s", None, &prefixes, &index, false).unwrap(); + assert_eq!(off["source"], "activity"); + assert_eq!(off["why"], "off"); + assert_eq!(off["calls"][0]["kind"], "upstream"); + assert_eq!(off["calls"][0]["upstream"], "timetrack"); + assert_eq!(off["calls"][0]["at"], b + 2100); + assert!(off["turns"].as_array().unwrap().is_empty()); + // The path stays with the hub. + assert!(off["hooks"][0].get("transcript").is_none()); + + let on = timeline(&records, "s", Some("claude-code"), &prefixes, &index, true).unwrap(); + assert_eq!(on["source"], "transcript"); + assert_eq!(on["turns"][0]["output"], 5); + // The server is named `ds` here: the call still is devstack's, by its record. + assert_eq!(on["calls"][0]["kind"], "upstream"); + assert_eq!(on["calls"][0]["tool"], "tt__start_timer"); + assert_eq!(on["marks"][0]["kind"], "prompt"); + + assert!(timeline(&records, "other", None, &prefixes, &index, true).is_none()); + } + + #[test] + fn the_timeline_says_why_it_has_no_transcript() { + let index = crate::agenthooks::Index::default(); + let gone = timeline( + &[hook(1, "s", Some(Path::new("/nowhere/x.jsonl")))], + "s", + None, + &Vec::new(), + &index, + true, + ) + .unwrap(); + assert_eq!(gone["why"], "missing"); + let mut r = hook(1, "s", None); + if let Record::Hook { agent, .. } = &mut r { + *agent = "aider".into(); + } + assert_eq!( + timeline(&[r], "s", None, &Vec::new(), &index, true).unwrap()["why"], + "agent" + ); + } + + #[test] + fn a_growing_transcript_is_read_on_from_where_it_was_left() { + let d = tempfile::tempdir().unwrap(); + let path = d.path().join("s.jsonl"); + let turn = |id: &str, s: u64, out: u64| { + serde_json::json!({"type":"assistant","timestamp":at(s),"message":{"id":id,"content":[],"usage":{"output_tokens":out}}}).to_string() + }; + let mut files = HashMap::new(); + // The second line is being written: not read yet. + let half = turn("b", 2, 7); + std::fs::write(&path, format!("{}\n{}", turn("a", 1, 5), &half[..10])).unwrap(); + let p = session(Format::Claude, &path, &mut files).unwrap(); + assert_eq!(p.turns.iter().map(|t| t.output).collect::>(), [5]); + let first = files[&path].offset; + // Written on: only what was added is read, the turn of `a` grows. + std::fs::write( + &path, + format!("{}\n{half}\n{}\n", turn("a", 1, 5), turn("a", 1, 9)), + ) + .unwrap(); + let p = session(Format::Claude, &path, &mut files).unwrap(); + assert!(files[&path].offset > first); + assert_eq!(p.turns.iter().map(|t| t.output).collect::>(), [9, 7]); + assert_eq!(p, claude(&path)); + // Written anew (shorter): from its start. + std::fs::write(&path, format!("{}\n", turn("c", 3, 1))).unwrap(); + let p = session(Format::Claude, &path, &mut files).unwrap(); + assert_eq!(p.turns.iter().map(|t| t.output).collect::>(), [1]); + // Gone: not read. + std::fs::remove_file(&path).unwrap(); + assert!(session(Format::Claude, &path, &mut files).is_none()); + } + + #[test] + fn the_setting_is_off_until_saved() { + let d = tempfile::tempdir().unwrap(); + assert!(!Setting::load(d.path()).enabled); + Setting { enabled: true }.save(d.path()).unwrap(); + assert!(Setting::load(d.path()).enabled); + } +} diff --git a/docs/adr/0098-the-skills-page-shows-the-flow-of-the-hooks-and-the-agents-activity.md b/docs/adr/0098-the-skills-page-shows-the-flow-of-the-hooks-and-the-agents-activity.md index 67c523d7..ace9932d 100644 --- a/docs/adr/0098-the-skills-page-shows-the-flow-of-the-hooks-and-the-agents-activity.md +++ b/docs/adr/0098-the-skills-page-shows-the-flow-of-the-hooks-and-the-agents-activity.md @@ -1,6 +1,6 @@ # ADR-0098: The Skills page shows the flow of the hooks and the agents' activity; devstack keeps only what happened, on this machine, for a week -- **Status:** Accepted (card in the pull request); built +- **Status:** Accepted (card in the pull request); built; its activity list moved to a lane's timeline ([ADR-0099](0099-a-lane-shows-its-agents-sessions-in-time-from-their-transcripts-when-switched-on.md)) - **Date:** 2026-11-06 - **Deciders:** project owner - **Related:** [ADR-0094](0094-a-skill-carries-hooks-that-give-text-to-the-agents.md) (hooks, and its addenda: `lane-stop`, `session-end`, an upstream set up in the agent), [ADR-0069](0069-devstack-mcp-can-carry-the-tools-of-upstream-mcp-servers.md) (upstreams through `devstack mcp`), [ADR-0037](0037-pool-telemetry.md) (the pool's telemetry, which this is not part of); issue #482 @@ -94,3 +94,12 @@ event), `crates/devstack-hub/src/agenthooks.rs` (`record`), (`activity_get`, the `activity` event), `crates/devstack-hub/src/poolskills.rs` (`hook_details`), `ui/src/lib/flow.ts`, `ui/src/components/SkillsFlow.vue`, `ui/src/views/SkillsView.vue`, `docs/dashboard-api.md`. + +## Addendum 2026-11-09: the activity list moved to a lane + +[ADR-0099](0099-a-lane-shows-its-agents-sessions-in-time-from-their-transcripts-when-switched-on.md) +shows a session in time on a lane's Activity (view Timeline), with the +hooks and tool calls recorded here. The list beside the flow went there; +the flow keeps, per hook, when it was given last, and the tool calls by +skill. A hook's record now also keeps the path of the session's transcript +(never its content), left out of `GET /hub/activity`. diff --git a/docs/adr/0099-a-lane-shows-its-agents-sessions-in-time-from-their-transcripts-when-switched-on.md b/docs/adr/0099-a-lane-shows-its-agents-sessions-in-time-from-their-transcripts-when-switched-on.md new file mode 100644 index 00000000..429584df --- /dev/null +++ b/docs/adr/0099-a-lane-shows-its-agents-sessions-in-time-from-their-transcripts-when-switched-on.md @@ -0,0 +1,110 @@ +# ADR-0099: A lane shows its agents' sessions in time; the hub reads their transcripts when switched on, and takes only times, counts and names + +- **Status:** Accepted (card in the pull request); built +- **Date:** 2026-11-09 +- **Deciders:** project owner +- **Related:** [ADR-0098](0098-the-skills-page-shows-the-flow-of-the-hooks-and-the-agents-activity.md) (the activity this extends; its list moves here), [ADR-0094](0094-a-skill-carries-hooks-that-give-text-to-the-agents.md) (the hooks whose input names the transcript) + +## Context + +A developer asked how many tokens their agent had used by the time of a +tool call, and how long the calls took, along the session. devstack's own +records ([ADR-0098](0098-the-skills-page-shows-the-flow-of-the-hooks-and-the-agents-activity.md)) +cannot say: an MCP call carries no token counts, and the agent's own tools +(shell, edits, reads) never pass devstack. The agent itself writes both +down, in its transcript: Claude Code a JSONL with each answer's `usage` +and each `tool_use` with its `tool_result`, Codex a rollout with +`token_count` events and its calls. Each agent's hook input names the file +(`transcript_path`). There is no common format. + +## Decision + +The owner approved the review card in the conversation on **2026-11-09**, +all five points: + +| # | Category | Point | Beats | Reversing costs | +|---|---|---|---|---| +| 1 | trust | For each agent a reader of its own reads that agent's transcript, Claude Code and Codex first; it takes only times, the model's name, token counts, tool names and durations, never a prompt, a text or an argument, and keeps nothing. | A `PostToolUse` hook that records each call (its input holds commands and file contents) | Low: switched off, the activity stays as before | +| 2 | trust | Reading transcripts is a setting per machine, off by default. | On by default | Low | +| 3 | concept | A session gets a timeline of tool calls (the agent's own too) and tokens summed up, from the transcript, not from the activity's files. | Token counts on devstack's MCP records (which have none) | Medium | +| 4 | contract | `GET /hub/activity/timeline?session=&agent=` answers the calls (start, duration, tool, ok), the turns with their tokens and the marks; `GET`/`PUT /hub/activity/transcripts` the setting. | Parsing the transcript in the browser | Low: new endpoints | +| 5 | term | The timeline is a view of a lane's Activity (Journal, Timeline), with a choice of session; the activity list moves there from the Skills page, the flow stays. | A third tab on the Skills page | Low | + +As built: + +1. **The path.** A hook's record keeps the `transcript_path` of its input + (`transcript`), the path only; `GET /hub/activity` leaves it out. +2. **The readers** (`crates/devstack-hub/src/transcript.rs`). Claude Code: + one turn per `message.id` (an answer comes as one line per part), its + time the first line's, its usage the largest seen; a call from its + `tool_use` to its `tool_result` (`is_error`: failed); `mcp____` + an MCP server's, `Task`/`Agent` a sub-agent; a sub-agent's turns + (`isSidechain`, or `/subagents/*.jsonl`) count, its calls do not + show; a user line with text a prompt, unless the agent added it + (`isMeta`, a summary, `origin`: a background task's notice, a local + command); `[Request interrupted` an interruption; `compact_boundary` a + compaction; `isApiErrorMessage` an error. Codex: a turn per + `token_count` whose total moved (it comes twice), cached input read from + the cache; `user_message` a prompt (`task_started` in a rollout without + one); `function_call`/`custom_tool_call` to its output; an MCP tool once, + from `mcp_tool_call_end` with its server and duration; `turn_aborted` an + interruption. The text a reader looks at to tell a prompt from the rest + is read, never kept. +3. **Through devstack or not.** An MCP call went through devstack when its + server is named `devstack`, or one of devstack's records has the same + tool within two seconds; then it is devstack's own tool or an upstream's + by its prefix, like the activity. +4. **A file read on, not again.** The hub keeps, per file, how far it read + and the reader's state there, and reads only the lines added since + (whole lines: one being written waits for the next look); a file shorter + than that was written anew and is read from its start. A transcript of + 47 MB reads in about 130 ms the first time; a running session's look + every five seconds reads only its new lines. At most 64 files are kept. +5. **The view.** Rows: prompts (numbered, no text), the model's turns (as + tall as their output), the calls by where they went (devstack, upstreams, + other MCP servers, built-in, sub-agents; overlapping calls one below the + other, a failed one red), what changed the lane (its journal and the + daemon's events), the hooks given. Below, the context per turn (what the + model read in: a compaction shows as a drop) and the tokens summed up, + stacked (cache read, written, input, output; cache read starts hidden, + it dwarfs the rest). A pause longer than two minutes is pushed together. + Hovering a call says how long it took and the tokens until then; a + crosshair reads the charts. Zoom 1× to 8×. A running session is read + again every five seconds. + +Decided while building, not on the card: + +- The Skills page keeps when each hook was given last and the tool calls by + skill; clicking a hook no longer narrows a list (the list moved). +- `GET /hub/activity?tree=` takes a tree as the page knows it (any case, + any separator) and narrows the sessions too. + +## Alternatives considered + +- **A `PostToolUse` hook per call.** Would see the agent's own tools + without reading a transcript, but its input carries the command and the + file contents, it runs a process per call, and it still has no tokens. +- **Parsing in the browser.** The dashboard would need the file, and with + it everything in it. +- **Keeping a copy of the counts.** Not needed: the agent keeps its + transcript, and a timeline read when asked cannot outlive the user's own + file. + +## Consequences + +- A session started before this version has no path recorded: its timeline + says the transcript was not found and shows devstack's records. +- Whether Codex's hook input names `transcript_path` is not yet seen in a + real session; without it a Codex session shows devstack's records. +- An agent with a new transcript format needs its reader changed; until + then it shows fewer turns or calls, never more than the file holds. + +## Enforced by + +`crates/devstack-hub/src/transcript.rs` (the setting, the readers, the +timeline), `crates/devstack-hub/src/activity.rs` (`transcript` on a hook's +record, left out of `/hub/activity`), `crates/devstack-hub/src/agenthooks.rs` +(`record`), `crates/devstack-hub/src/lib.rs` (`timeline_get`, +`transcripts_get`, `transcripts_put`), `ui/src/lib/timeline.ts`, +`ui/src/components/SessionTimeline.vue`, `ui/src/components/AgentTimeline.vue`, +`ui/src/views/EventsView.vue`, `docs/dashboard-api.md`. diff --git a/docs/adr/README.md b/docs/adr/README.md index bd9aca89..c9d06447 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -180,4 +180,5 @@ stay. | [0095](0095-the-daemon-ends-with-the-last-tree.md) | The daemon ends with the last tree; a stack has no start of its own, a stop always takes a tree's containers | Accepted (card in the pull request); built | | [0096](0096-a-port-held-now-refuses-the-start-one-up-of-a-tree-at-a-time.md) | A port held now refuses the start, whoever holds it (a stopped stack's containers too); one `up` of a tree at a time | Accepted (card in the pull request); built | | [0097](0097-the-dashboards-mark-says-what-needs-attention.md) | The dashboard's mark and favicon carry a red or yellow dot for what needs attention, from an `attention` event of the hub; the mark flips to the nut | Accepted (card in the pull request); built | -| [0098](0098-the-skills-page-shows-the-flow-of-the-hooks-and-the-agents-activity.md) | The Skills page shows the flow of the hooks and the agents' activity; devstack keeps only what happened, on this machine, for a week | Accepted (card in the pull request); built | +| [0098](0098-the-skills-page-shows-the-flow-of-the-hooks-and-the-agents-activity.md) | The Skills page shows the flow of the hooks and the agents' activity; devstack keeps only what happened, on this machine, for a week | Accepted (card in the pull request); built; its activity list moved to a lane's timeline (ADR-0099) | +| [0099](0099-a-lane-shows-its-agents-sessions-in-time-from-their-transcripts-when-switched-on.md) | A lane shows its agents' sessions in time; the hub reads their transcripts when switched on, and takes only times, counts and names | Accepted (card in the pull request); built | diff --git a/docs/dashboard-api.md b/docs/dashboard-api.md index 7cc5c3f5..20007753 100644 --- a/docs/dashboard-api.md +++ b/docs/dashboard-api.md @@ -102,7 +102,10 @@ and `Referrer-Policy: no-referrer`. The dashboard has no inline script. | `DELETE /hub/pool/skills/{name}` | cookie + Origin | admins only: stop handing it out: `204`; audited | | `POST /hub/pool/skills/refresh[?set=]` | cookie + Origin | admins only: have the coordinator fetch the sets (or one) again: `202` | | `GET /hub/skills` | cookie | the pools' skill sets on this machine (ADR-0074), the agents looked for again (one installed since shows, switched off) and the state told on `/hub/events` too: `{agents: [{id, name, dir, project?, enabled, hooks}], sets: [{pool, set, source, state: "offered"\|"accepted"\|"declined"\|"changed", auto, fetched?, commit?, error?, skills: [{name, description, sha256, installed, pending, enabled, group?, tags?, updated?, agents, repos?, trees?, hooks?}]}], conflicts: [{dir, name, reason}], errors?, synced?}`; also on `/hub/events` as `{"type":"skills","skills":...}`, first and on every change. Per skill ([ADR-0077](adr/0077-a-sets-skills-are-grouped-and-switched-one-by-one.md)): `enabled` (switched on; older hubs leave it out), `group` and `tags` (from `metadata` in its frontmatter), `updated` (when this hub wrote it, Unix ms), `agents` (the names of the agents whose folder holds it). [ADR-0079](adr/0079-skills-local-to-a-working-tree.md): an agent's `project` is its skill folder in a working tree; a skill's `repos` binds it to repositories (it goes into the agents' folders of their working trees, not the user folders), `trees` are the working trees it is in, and `installed` means in every folder it goes to. [ADR-0094](adr/0094-a-skill-carries-hooks-that-give-text-to-the-agents.md): a skill's `hooks` is how many hooks its `hooks.toml` has (left out when none), an agent's `hooks` whether it gets them. [ADR-0098](adr/0098-the-skills-page-shows-the-flow-of-the-hooks-and-the-agents-activity.md): a skill switched on carries `hook_details: [{index, event: "session-start"\|"prompt-submit"\|"lane-stop"\|"session-end", pattern?, once: "session"\|"match", upstream?, preview, agents, applies, why?}]` (`preview` the first 160 characters of its text; `agents` the names of the agents that get it; `applies` whether its upstream is there, accepted or set up in an agent, `why` when not); older hubs leave it out | -| `GET /hub/activity?tree=&session=&since=` | cookie | what devstack did for the coding agents ([ADR-0098](adr/0098-the-skills-page-shows-the-flow-of-the-hooks-and-the-agents-activity.md)), kept on this machine for seven days: `{sessions: [{agent, session, tree, started, last, ended}], records: [Record]}`, a record `{kind: "hook", at, event, agent, session?, tree, hooks: [{pool, set, skill, index}], recorded?}` (a hook given; `recorded`: a `session-end` kept for the next start) or `{kind: "tool", at, tool, client?, tree, pid, ms, ok, session?, agent?, upstream?, skills?}` (a tool call through `devstack mcp`; `upstream` and `skills` for a pool's upstream's tool: the skills whose hooks name it). Never a prompt, a hook's text, a tool's arguments or its answer. A record without a session (a tool call, a lane's stop) is put to the latest session that started in its working tree (`tree`, the folder holding `.git`, lower case on Windows) before it; `tree`, `session` and `since` (Unix ms) narrow the answer, at most the latest 500 records; on `/hub/events` `{"type":"activity","at"}` says a record was added | +| `GET /hub/activity?tree=&session=&since=` | cookie | what devstack did for the coding agents ([ADR-0098](adr/0098-the-skills-page-shows-the-flow-of-the-hooks-and-the-agents-activity.md)), kept on this machine for seven days: `{sessions: [{agent, session, tree, started, last, ended}], records: [Record]}`, a record `{kind: "hook", at, event, agent, session?, tree, hooks: [{pool, set, skill, index}], recorded?}` (a hook given; `recorded`: a `session-end` kept for the next start) or `{kind: "tool", at, tool, client?, tree, pid, ms, ok, session?, agent?, upstream?, skills?}` (a tool call through `devstack mcp`; `upstream` and `skills` for a pool's upstream's tool: the skills whose hooks name it). Never a prompt, a hook's text, a tool's arguments or its answer. A record without a session (a tool call, a lane's stop) is put to the latest session that started in its working tree (`tree`, the folder holding `.git`, lower case on Windows) before it; `tree` (taken in any case and with either separator; it narrows the sessions too), `session` and `since` (Unix ms) narrow the answer, at most the latest 500 records; on `/hub/events` `{"type":"activity","at"}` says a record was added | +| `GET /hub/activity/timeline?session=&agent=` | cookie | a session in time ([ADR-0099](adr/0099-a-lane-shows-its-agents-sessions-in-time-from-their-transcripts-when-switched-on.md)): the session's `{agent, session, tree, started, last, ended}` and `source: "transcript"\|"activity"`, `why?: "off"\|"agent"\|"missing"` (the transcript was not read: not switched on, no reader for this agent, not found), `turns: [{at, model?, input, cache_write, cache_read, output, sidechain?}]` (an answer of the model; `input` not from the cache), `calls: [{at, ms\|null, tool, kind: "devstack"\|"upstream"\|"mcp"\|"builtin"\|"agent", ok, upstream?}]` (`at` its start; `upstream` the upstream's or the MCP server's name), `marks: [{at, kind: "prompt"\|"interrupt"\|"compact"\|"clear"\|"error"}]` and `hooks: [Record]` (the hooks given in it). Without the transcript, `calls` are devstack's records and `turns`/`marks` empty. Never a prompt, a text, an argument or an answer; 404 for a session not known | +| `GET /hub/activity/transcripts` | cookie | `{enabled}`: whether the hub reads the agents' transcripts for the timeline; off until switched on | +| `PUT /hub/activity/transcripts` | cookie | `{enabled}`: switch it on or off; answers the setting | | `PUT /hub/skills/agents/{id} {enabled}` | cookie + Origin | install into that agent's user skill folder (and, for bound skills and devstack's generated ones, its folder in the working trees), or no longer (what devstack installed there goes); the state after it, `409` with why | | `PUT /hub/skills/sets/{pool}/{set}/skills/{name} {enabled}`, `PUT /hub/skills/sets/{pool}/{set}/groups/{group} {enabled}` | cookie + Origin | switch a skill of an accepted set, or every skill of a group (`-`: the skills without one), on or off (ADR-0077); off, it goes from the agents' folders unless changed there; the state after it, `409` with why | | `POST /hub/skills/sets/{pool}/{set}/accept {auto}`, `.../decline`, `.../update`; `PUT /hub/skills/sets/{pool}/{set} {auto}` | cookie + Origin | accept a set from its source (updates at once with `auto`, else they wait), decline or remove it, take its waiting updates, change `auto`; the state after it | diff --git a/ui/src/api/mock/activity.ts b/ui/src/api/mock/activity.ts index 256c70ef..a6f64b25 100644 --- a/ui/src/api/mock/activity.ts +++ b/ui/src/api/mock/activity.ts @@ -65,8 +65,8 @@ export const mockHookDetails: Record = { export function mockActivity(session?: string): ActivityView { const now = Date.now(); const min = 60_000; - const main = '~/src/shop'; - const lane = '~/src/shop-feat-cart'; + const main = 'c:/work/shop'; + const lane = 'c:/work/shop-agent-login-fix'; const at = (m: number) => now - m * min; const records: ActivityRecord[] = [ { kind: 'hook', at: at(95), event: 'session-start', agent: 'claude-code', session: 'a1f3', tree: main, hooks: [ref('work-session', 0)] }, @@ -80,6 +80,7 @@ export function mockActivity(session?: string): ActivityView { { kind: 'tool', at: at(24), tool: 'timetrack__start_timer', client: 'claude-code', tree: lane, pid: 5200, ms: 210, ok: true, session: 'b7c2', agent: 'claude-code', upstream: 'timetrack', skills: ['work-session', 'session-end'] }, { kind: 'hook', at: at(23), event: 'prompt-submit', agent: 'claude-code', session: 'b7c2', tree: lane, hooks: [ref('work-issue', 0)] }, { kind: 'tool', at: at(18), tool: 'up', client: 'claude-code', tree: lane, pid: 5200, ms: 41_000, ok: true, session: 'b7c2', agent: 'claude-code' }, + { kind: 'hook', at: at(11), event: 'prompt-submit', agent: 'claude-code', session: 'b7c2', tree: lane, hooks: [ref('work-issue', 0)] }, { kind: 'tool', at: at(9), tool: 'logs', client: 'claude-code', tree: lane, pid: 5200, ms: 60, ok: true, session: 'b7c2', agent: 'claude-code' }, { kind: 'tool', at: at(6), tool: 'lane_stop', client: 'claude-code', tree: lane, pid: 5200, ms: 2_300, ok: false, session: 'b7c2', agent: 'claude-code' }, { kind: 'tool', at: at(4), tool: 'lane_stop', client: 'claude-code', tree: lane, pid: 5200, ms: 2_100, ok: true, session: 'b7c2', agent: 'claude-code' }, diff --git a/ui/src/api/mock/index.ts b/ui/src/api/mock/index.ts index 7c86cedb..3b7765c9 100644 --- a/ui/src/api/mock/index.ts +++ b/ui/src/api/mock/index.ts @@ -21,6 +21,7 @@ import { crmSeed, docsSeed, failedReason, shopSeed, stamp } from './data'; import { Abort, MockStack, sleep, type Listener } from './stack'; import { MockPool } from './pool'; import { mockActivity, mockHookDetails } from './activity'; +import { mockTimeline, mockTranscripts } from './timeline'; import { autoShift, daemonPorts, hubPorts, refusal, type MockLane } from './ports'; import { runningHolders } from '@/lib/shift'; @@ -660,6 +661,15 @@ export class MockTransport implements Transport { // Skill sets (ADR-0074). if (p === '/hub/skills' && method === 'GET') return json(200, this.hub.poolSkillState); if (p === '/hub/activity' && method === 'GET') return json(200, mockActivity(url.searchParams.get('session') ?? undefined)); + if (p === '/hub/activity/timeline' && method === 'GET') { + const t = mockTimeline(url.searchParams.get('session') ?? ''); + return t ? json(200, t) : json(404, { error: 'no such session' }); + } + if (p === '/hub/activity/transcripts' && method === 'GET') return json(200, mockTranscripts); + if (p === '/hub/activity/transcripts' && method === 'PUT') { + mockTranscripts.enabled = Boolean(body?.enabled); + return json(200, mockTranscripts); + } if (p === '/hub/skills/sync' && method === 'POST') return json(200, this.hub.poolSkillState); const sa = /^\/hub\/skills\/agents\/([^/]+)$/.exec(p); if (sa && method === 'PUT') { diff --git a/ui/src/api/mock/timeline.ts b/ui/src/api/mock/timeline.ts new file mode 100644 index 00000000..3c3b8a56 --- /dev/null +++ b/ui/src/api/mock/timeline.ts @@ -0,0 +1,81 @@ +// A session in time as the mock hub answers `GET /hub/activity/timeline`: +// built from the mock's activity, with turns, built-in calls and marks as an +// agent's transcript gives them. Seeded, so it looks the same on each load. +import type { ActivityRecord, SessionTimeline, TimelineCall, TimelineMark, TimelineTurn } from '../types'; +import { mockActivity } from './activity'; + +function rng(seed: number) { + let s = seed; + return () => { + s = (s * 1664525 + 1013904223) % 2 ** 32; + return s / 2 ** 32; + }; +} + +const BUILTIN = ['Read', 'Read', 'Grep', 'Bash', 'Edit', 'Edit', 'Glob', 'Bash', 'Write']; + +/** Whether the mock reads transcripts: on, so the view shows everything; `PUT` switches it. */ +export const mockTranscripts = { enabled: true }; + +export function mockTimeline(session: string): SessionTimeline | null { + const view = mockActivity(); + const s = view.sessions.find((x) => x.session === session); + if (!s) return null; + const records = view.records.filter((r) => r.session === session || (r.kind === 'hook' && !r.session && r.tree === s.tree && r.at >= s.started && r.at <= s.last + 60_000)); + const hooks = records.filter((r): r is Extract => r.kind === 'hook'); + const ownCalls: TimelineCall[] = records + .filter((r): r is Extract => r.kind === 'tool') + .map((r) => ({ at: r.at - r.ms, ms: r.ms, tool: r.tool, kind: r.upstream ? 'upstream' : 'devstack', ok: r.ok, ...(r.upstream ? { upstream: r.upstream } : {}) })); + const base = { ...s, hooks }; + if (!mockTranscripts.enabled) return { ...base, source: 'activity', why: 'off', turns: [], calls: ownCalls, marks: [] }; + + // Prompts: at the session's start, and wherever a prompt's hook fired; a + // pause before each but the first (the agent waited for the user). + const rand = rng(session.charCodeAt(0) * 97 + session.length); + const prompts = [...new Set([s.started + 5_000, ...hooks.filter((h) => h.event === 'prompt-submit').map((h) => h.at)])].sort((a, b) => a - b); + const marks: TimelineMark[] = prompts.map((at) => ({ at, kind: 'prompt' })); + const turns: TimelineTurn[] = []; + const calls: TimelineCall[] = [...ownCalls]; + let ctx = 18_000; + const end = s.ended ? s.last : Date.now() - 20_000; + prompts.forEach((p, i) => { + // The agent works for a while after each prompt, then waits. + const until = Math.min(prompts[i + 1] ?? end, p + (i === prompts.length - 1 ? end - p : 2 * 60_000 + rand() * 6 * 60_000)); + let t = p + 2_000; + while (t < until) { + const output = Math.round(80 + rand() * (rand() < 0.15 ? 2400 : 600)); + const write = Math.round(200 + rand() * 2500); + turns.push({ at: t, model: 'claude-opus', input: 2 + Math.round(rand() * 6), cache_write: write, cache_read: ctx, output }); + ctx += write; + // Most turns call a built-in tool; now and then a sub-agent. + if (rand() < 0.06) { + const ms = 20_000 + rand() * 50_000; + calls.push({ at: t + 400, ms: Math.round(ms), tool: 'Agent', kind: 'agent', ok: true }); + for (let k = 0; k < 4; k++) turns.push({ at: t + 3_000 + k * (ms / 5), model: 'claude-haiku', input: 5, cache_write: 900, cache_read: 4_000 + k * 900, output: 300, sidechain: true }); + t += ms + 2_000; + continue; + } + if (rand() < 0.85) { + const tool = BUILTIN[Math.floor(rand() * BUILTIN.length)]; + const ms = tool === 'Bash' ? 800 + rand() * 25_000 : 40 + rand() * 600; + calls.push({ at: t + 300, ms: Math.round(ms), tool, kind: 'builtin', ok: rand() > 0.06 }); + t += ms + 1_500 + rand() * 9_000; + } else t += 4_000 + rand() * 8_000; + } + }); + // The context grew past what fits once: compacted. + if (turns.length > 30) { + const at = turns[Math.floor(turns.length * 0.6)].at - 500; + marks.push({ at, kind: 'compact' }); + let shrink = 0; + for (const u of turns) { + if (u.at < at || u.sidechain) continue; + if (!shrink) shrink = Math.round(u.cache_read * 0.7); + u.cache_read = Math.max(12_000, u.cache_read - shrink); + } + } + if (prompts.length > 2) marks.push({ at: prompts[1] - 40_000, kind: 'interrupt' }); + calls.sort((a, b) => a.at - b.at); + marks.sort((a, b) => a.at - b.at); + return { ...base, source: 'transcript', turns, calls, marks }; +} diff --git a/ui/src/api/transport.ts b/ui/src/api/transport.ts index bc9025fe..12e3a0fe 100644 --- a/ui/src/api/transport.ts +++ b/ui/src/api/transport.ts @@ -130,6 +130,10 @@ export const paths = { const s = p.toString(); return `/hub/activity${s ? `?${s}` : ''}`; }, + /** A session in time: its turns, calls and marks. */ + timeline: (session: string, agent: string) => `/hub/activity/timeline?${new URLSearchParams({ session, agent }).toString()}`, + /** Whether the hub reads the agents' transcripts (off by default). */ + transcripts: '/hub/activity/transcripts', /** Every registered stack's ports and their overlaps (ADR-0082). */ hubPorts: '/hub/ports', skillsSync: '/hub/skills/sync', diff --git a/ui/src/api/types.ts b/ui/src/api/types.ts index 7e425925..697938f1 100644 --- a/ui/src/api/types.ts +++ b/ui/src/api/types.ts @@ -197,6 +197,53 @@ export type ActivitySession = { agent: string; session: string; tree: string; st export type ActivityView = { sessions: ActivitySession[]; records: ActivityRecord[] }; +/** An answer of the model in a session: when, which model, the tokens it took. */ +export type TimelineTurn = { + at: number; + model?: string; + /** Input not from the cache, written to the cache, read from it; output. */ + input: number; + cache_write: number; + cache_read: number; + output: number; + /** A sub-agent's: its tokens count, the context is its own. */ + sidechain?: boolean; +}; + +/** Where a call went: devstack's own tool, a pool upstream's through it, another MCP server, the agent's built-in tool, a sub-agent. */ +export type TimelineCallKind = 'devstack' | 'upstream' | 'mcp' | 'builtin' | 'agent'; + +/** A tool call: its name and how long it took, never its arguments or answer. */ +export type TimelineCall = { + at: number; + /** null: it has no answer yet (still running, or the session ended first). */ + ms: number | null; + tool: string; + kind: TimelineCallKind; + ok: boolean; + /** `upstream`: which; `mcp`: the server. */ + upstream?: string; +}; + +/** A moment in a session: a prompt sent (never its text), an interruption, the context compacted or cleared, an error of the model's API. */ +export type TimelineMark = { at: number; kind: 'prompt' | 'interrupt' | 'compact' | 'clear' | 'error' }; + +/** A session in time (`GET /hub/activity/timeline`). */ +export type SessionTimeline = ActivitySession & { + /** Where the turns and calls come from: the agent's transcript, or devstack's records only. */ + source: 'transcript' | 'activity'; + /** Why the transcript was not read: `off` (not switched on), `agent` (no reader for this agent), `missing` (not found). */ + why?: 'off' | 'agent' | 'missing'; + turns: TimelineTurn[]; + calls: TimelineCall[]; + marks: TimelineMark[]; + /** The hooks devstack gave in it. */ + hooks: Extract[]; +}; + +/** Whether the hub reads the agents' transcripts for the timeline (`/hub/activity/transcripts`); off by default. */ +export type TranscriptSetting = { enabled: boolean }; + /** A pool's skill set as an admin names it (`/hub/pool/skills`). */ export type PoolSkillSet = { name: string; diff --git a/ui/src/components/AgentTimeline.vue b/ui/src/components/AgentTimeline.vue new file mode 100644 index 00000000..bcedaf65 --- /dev/null +++ b/ui/src/components/AgentTimeline.vue @@ -0,0 +1,181 @@ + + + + + diff --git a/ui/src/components/SessionTimeline.test.ts b/ui/src/components/SessionTimeline.test.ts new file mode 100644 index 00000000..866c422f --- /dev/null +++ b/ui/src/components/SessionTimeline.test.ts @@ -0,0 +1,43 @@ +// A session in time: its rows, the pause pushed together, the tokens; a +// session without its transcript shows devstack's records only. +import { describe, expect, it } from 'vitest'; +import { createApp, h, nextTick } from 'vue'; +import { mockTimeline, mockTranscripts } from '@/api/mock/timeline'; +import SessionTimeline from './SessionTimeline.vue'; + +async function mount(session: string) { + const timeline = mockTimeline(session)!; + const el = document.createElement('div'); + document.body.appendChild(el); + const app = createApp({ render: () => h(SessionTimeline, { timeline, lane: [{ at: timeline.started + 60_000, title: 'api: restart', text: 'via the MCP server', tone: 'accent' }], now: Date.now() }) }); + app.mount(el); + await nextTick(); + return { el, timeline, unmount: () => (app.unmount(), el.remove()) }; +} + +describe('the session timeline', () => { + it('shows prompts, calls by where they went, and the tokens', async () => { + mockTranscripts.enabled = true; + const { el, timeline, unmount } = await mount('b7c2'); + expect(timeline.source).toBe('transcript'); + expect(el.querySelectorAll('[data-testid="session-timeline-prompts"] .prompt').length).toBe(timeline.marks.filter((m) => m.kind === 'prompt').length); + expect(el.querySelector('[data-testid="session-timeline-calls-devstack"]')).not.toBeNull(); + expect(el.querySelector('[data-testid="session-timeline-calls-builtin"]')).not.toBeNull(); + expect(el.querySelector('[data-testid="session-timeline-tokens"]')).not.toBeNull(); + expect(el.querySelector('[data-testid="session-timeline-total"]')!.textContent).toMatch(/Tokens\s+\d/); + // The wait between the prompts is pushed together. + expect(el.querySelectorAll('[data-testid="session-timeline-gap"]').length).toBeGreaterThan(0); + unmount(); + }); + + it('shows only what devstack recorded while transcripts are not read', async () => { + mockTranscripts.enabled = false; + const { el, timeline, unmount } = await mount('b7c2'); + expect(timeline.why).toBe('off'); + expect(el.querySelector('[data-testid="session-timeline-calls-builtin"]')).toBeNull(); + expect(el.querySelector('[data-testid="session-timeline-calls-devstack"]')).not.toBeNull(); + expect(el.querySelector('[data-testid="session-timeline-tokens"]')).toBeNull(); + unmount(); + mockTranscripts.enabled = true; + }); +}); diff --git a/ui/src/components/SessionTimeline.vue b/ui/src/components/SessionTimeline.vue new file mode 100644 index 00000000..e0d644ac --- /dev/null +++ b/ui/src/components/SessionTimeline.vue @@ -0,0 +1,600 @@ + + + + + diff --git a/ui/src/components/SkillsFlow.test.ts b/ui/src/components/SkillsFlow.test.ts index 1fd1b188..7034570b 100644 --- a/ui/src/components/SkillsFlow.test.ts +++ b/ui/src/components/SkillsFlow.test.ts @@ -1,5 +1,5 @@ // The Skills page's flow (#482): hooks as nodes with their tooltip, a hook -// that is not given greyed with why, a click narrowing the activity. +// that is not given greyed with why. import { describe, expect, it } from 'vitest'; import { createApp, h, nextTick } from 'vue'; import type { PoolSkillsState } from '@/api/types'; @@ -16,7 +16,7 @@ const state: PoolSkillsState = { async function mount(s: PoolSkillsState = state) { const el = document.createElement('div'); document.body.appendChild(el); - const app = createApp({ render: () => h(SkillsFlow, { state: s, activity: mockActivity(), session: '', now: Date.now() }) }); + const app = createApp({ render: () => h(SkillsFlow, { state: s, activity: mockActivity(), now: Date.now() }) }); app.mount(el); await nextTick(); return { el, unmount: () => (app.unmount(), el.remove()) }; @@ -44,19 +44,6 @@ describe('the flow tab', () => { unmount(); }); - it('narrows the activity to a hook on a click, and back', async () => { - const { el, unmount } = await mount(); - const count = () => el.querySelectorAll('[data-testid="skills-flow-record"]').length; - const all = count(); - el.querySelector('[data-key="default/core/work-issue#0"]')!.click(); - await nextTick(); - expect(count()).toBe(2); - el.querySelector('[data-testid="skills-flow-all"]')!.click(); - await nextTick(); - expect(count()).toBe(all); - unmount(); - }); - it('says so when no skill switched on carries hooks', async () => { const { el, unmount } = await mount({ ...state, sets: [] }); expect(el.querySelector('[data-testid="skills-flow-empty"]')!.textContent).toContain('No skill switched on carries hooks'); diff --git a/ui/src/components/SkillsFlow.vue b/ui/src/components/SkillsFlow.vue index 0ef1802a..ddbd740f 100644 --- a/ui/src/components/SkillsFlow.vue +++ b/ui/src/components/SkillsFlow.vue @@ -1,31 +1,23 @@