use std::collections::HashMap;
use std::collections::HashSet;
use crate::ChatRole;
use crate::agent::registry::{AgentHandle, NonAgentCallHandle, ParentKey};
use crate::gui::dialog;
use crate::gui::session_view::{
MAX_TOOL_TOOLTIP_WIDTH, SessionEntry, ToolBlockView, ToolCallEntry, build_ledger, tool_block,
truncate_at_boundary,
};
use crate::gui::theme;
use crate::gui::widgets;
use chrono::{DateTime, Utc};
use iced::widget::{Column, Row, Space, button, column, container, mouse_area, row, text, tooltip};
use iced::{Alignment, Element, Length};
use iced_fonts::lucide;
use super::Message;
use crate::Workspace;
mod trace_line;
const MAX_PREVIOUS_GROUPS: usize = 5;
const MAX_GROUP_LABEL_CHARS: usize = 104;
const MAX_METRIC_TOOLTIP_WIDTH: f32 = 360.0;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum StopTarget {
Research(String),
Launch(String),
}
#[derive(Debug, Clone)]
pub(crate) enum RunningMessage {
StopRequest(StopTarget),
StopConfirmed,
StopDismissed,
StopFinished(Result<String, String>),
ToggleAgentExpanded { agent_id: String, generation: u64 },
}
pub(crate) fn view(
workspaces: &HashMap<String, Workspace>,
pending_stop: Option<&StopTarget>,
expanded: &HashSet<(String, u64)>,
) -> Element<'static, Message> {
let agents = crate::agent::registry::AGENT_REGISTRY.list();
let calls = crate::agent::registry::NON_AGENT_CALLS.list();
let sections = build_sections(build_groups(&agents, &calls), workspaces);
let body: Element<'_, RunningMessage> = if sections.is_empty() {
widgets::empty_state_placeholder(
lucide::radar::<iced::Theme, iced::Renderer>(),
"Nothing is currently running.",
theme::TEXT_MUTED,
)
} else {
let mut content = Column::new().spacing(theme::SPACE_20);
for section in §ions {
content = content.push(render_section(section, expanded));
}
widgets::vscroll(content)
};
let confirm_layer: Element<'_, RunningMessage> = if let Some(target) = pending_stop {
stop_confirm_dialog(target)
} else {
widgets::no_dialog()
};
widgets::page_with_dialog(body, confirm_layer).map(Message::RunningAgents)
}
#[derive(Debug, Clone)]
enum DisplayItem {
Agent(Box<AgentCard>),
Call(CallRow),
}
#[derive(Debug, Clone)]
struct AgentCard {
handle: AgentHandle,
}
#[derive(Debug, Clone)]
struct CallRow {
handle: NonAgentCallHandle,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum GroupKind {
Ticket,
AnalyzeRound,
Research,
Launch,
Singleton,
Unattributed,
}
#[derive(Debug, Clone)]
struct DisplayGroup {
kind: GroupKind,
key: String,
workspace: String,
label: Option<String>,
items: Vec<DisplayItem>,
run_lifetime: bool,
}
#[derive(Debug, Clone)]
struct WorkspaceSection {
workspace: String,
label: String,
groups: Vec<DisplayGroup>,
}
impl DisplayGroup {
fn sort_key(&self) -> (u8, String) {
let order = match self.kind {
GroupKind::Ticket => 0,
GroupKind::AnalyzeRound => 1,
GroupKind::Research => 2,
GroupKind::Launch => 3,
GroupKind::Singleton => 4,
GroupKind::Unattributed => 5,
};
(order, self.key.clone())
}
}
fn parent_group_kind(parent: &ParentKey) -> GroupKind {
match parent {
ParentKey::Ticket(_) => GroupKind::Ticket,
ParentKey::AnalyzeRound(_) => GroupKind::AnalyzeRound,
ParentKey::Research(_) => GroupKind::Research,
ParentKey::Launch(_) => GroupKind::Launch,
}
}
fn parent_group_key(parent: &ParentKey) -> &str {
match parent {
ParentKey::Ticket(id) => id,
ParentKey::AnalyzeRound(key) | ParentKey::Research(key) | ParentKey::Launch(key) => key,
}
}
fn build_groups(agents: &[AgentHandle], calls: &[NonAgentCallHandle]) -> Vec<DisplayGroup> {
let mut groups: Vec<DisplayGroup> = Vec::new();
let find_group =
|kind: GroupKind, key: &str, workspace: &str, groups: &mut Vec<DisplayGroup>| -> usize {
let research = kind == GroupKind::Research;
let workspace_agnostic = research || kind == GroupKind::Launch;
if let Some(idx) = groups.iter().position(|g| {
g.kind == kind && g.key == key && (workspace_agnostic || g.workspace == workspace)
}) {
if research && groups[idx].workspace == key && workspace != key {
groups[idx].workspace = workspace.to_string();
}
return idx;
}
groups.push(DisplayGroup {
kind,
key: key.to_string(),
workspace: workspace.to_string(),
label: None,
items: Vec::new(),
run_lifetime: false,
});
groups.len() - 1
};
let adopt_label = |label: &Option<String>, group: &mut DisplayGroup| {
if group.label.is_none() && label.is_some() {
group.label.clone_from(label);
}
};
for agent in agents {
let workspace = agent.workspace_name.clone();
if let Some(parent) = &agent.parent_key {
let idx = find_group(
parent_group_kind(parent),
parent_group_key(parent),
&workspace,
&mut groups,
);
adopt_label(&agent.parent_label, &mut groups[idx]);
groups[idx]
.items
.push(DisplayItem::Agent(Box::new(AgentCard {
handle: agent.clone(),
})));
} else {
let idx = find_group(GroupKind::Singleton, &workspace, &workspace, &mut groups);
groups[idx]
.items
.push(DisplayItem::Agent(Box::new(AgentCard {
handle: agent.clone(),
})));
}
}
for call in calls {
let workspace = call.workspace.clone();
if let Some(parent) = &call.parent_key {
let idx = find_group(
parent_group_kind(parent),
parent_group_key(parent),
&workspace,
&mut groups,
);
adopt_label(&call.parent_label, &mut groups[idx]);
if call.run_lifetime {
groups[idx].run_lifetime = true;
} else {
groups[idx].items.push(DisplayItem::Call(CallRow {
handle: call.clone(),
}));
}
} else {
let idx = find_group(GroupKind::Unattributed, &workspace, &workspace, &mut groups);
groups[idx].items.push(DisplayItem::Call(CallRow {
handle: call.clone(),
}));
}
}
groups
}
fn build_sections(
groups: Vec<DisplayGroup>,
workspaces: &std::collections::HashMap<String, Workspace>,
) -> Vec<WorkspaceSection> {
let mut sections: Vec<WorkspaceSection> = Vec::new();
for group in groups {
let label = workspace_label_for(&group.workspace, workspaces);
if let Some(section) = sections.iter_mut().find(|s| s.workspace == group.workspace) {
section.groups.push(group);
} else {
sections.push(WorkspaceSection {
workspace: group.workspace.clone(),
label,
groups: vec![group],
});
}
}
sections.sort_by(|a, b| a.label.cmp(&b.label));
for section in &mut sections {
section.groups.sort_by_key(DisplayGroup::sort_key);
}
sections
}
fn render_section(
section: &WorkspaceSection,
expanded: &HashSet<(String, u64)>,
) -> Element<'static, RunningMessage> {
let mut groups = Column::new().spacing(theme::SPACE_10);
for group in §ion.groups {
groups = groups.push(render_group(group, expanded));
}
groups.into()
}
fn group_title(group: &DisplayGroup) -> (String, Option<String>) {
match &group.kind {
GroupKind::Ticket => match &group.label {
Some(title) => (title.clone(), Some(group.key.clone())),
None => (group.key.clone(), None),
},
GroupKind::AnalyzeRound => (
group.label.as_deref().map_or_else(
|| "Analyze round".to_string(),
|l| truncate_at_boundary(l, MAX_GROUP_LABEL_CHARS),
),
None,
),
GroupKind::Research => (
group.label.as_deref().map_or_else(
|| "Research run".to_string(),
|l| truncate_at_boundary(l, MAX_GROUP_LABEL_CHARS),
),
None,
),
GroupKind::Launch => (
group
.label
.as_deref()
.map_or_else(|| "Launch".to_string(), str::to_string),
None,
),
GroupKind::Singleton => ("Standalone".to_string(), None),
GroupKind::Unattributed => ("Other LLM work".to_string(), None),
}
}
fn render_group(
group: &DisplayGroup,
expanded: &HashSet<(String, u64)>,
) -> Element<'static, RunningMessage> {
let (title, id) = group_title(group);
let mut header_parts: Vec<Element<'_, RunningMessage>> = Vec::new();
let header = if group.kind == GroupKind::Ticket {
match id {
Some(id) => format!("[{id}] {title}"),
None => title.clone(),
}
} else {
title.clone()
};
header_parts.push(
text(header)
.size(theme::TEXT_12)
.color(theme::TEXT_SECONDARY)
.into(),
);
if group.run_lifetime {
header_parts.push(
text("run active")
.size(theme::TEXT_11)
.color(theme::TEXT_SECONDARY)
.into(),
);
}
let stop = match group.kind {
GroupKind::Research => Some(("Cancel run", StopTarget::Research(group.key.clone()))),
GroupKind::Launch => Some(("Stop launch", StopTarget::Launch(group.key.clone()))),
_ => None,
};
if let Some((label, target)) = stop {
header_parts.push(Space::new().width(Length::Fill).into());
header_parts.push(
button(text(label).size(theme::TEXT_11))
.style(theme::button_danger)
.on_press(RunningMessage::StopRequest(target))
.into(),
);
}
let mut items = Column::new().spacing(theme::SPACE_6);
for item in &group.items {
match item {
DisplayItem::Agent(card) => {
let is_expanded =
expanded.contains(&(card.handle.agent_id.clone(), card.handle.generation));
items = items.push(render_agent_card(card, is_expanded));
}
DisplayItem::Call(call) => {
items = items.push(render_call_row(call));
}
}
}
column![
Row::with_children(header_parts)
.spacing(theme::SPACE_8)
.align_y(Alignment::Center),
items,
]
.spacing(theme::SPACE_6)
.into()
}
fn stop_confirm_dialog(target: &StopTarget) -> Element<'static, RunningMessage> {
let (title, body, keep, confirm): (&str, &[&str], &str, &str) = match target {
StopTarget::Research(_) => (
"Cancel this research run?",
&[
"Confirming will:",
"• stop all agents of this run — an in-flight tool or LLM call \
may finish, but no further work happens;\n\
• stop the orchestrator — no more rounds, no report, and \
nothing is delivered to the Manager;\n\
• remove the run's temporary traces and its run folder — \
dispatching the cleanup agent while the orchestrator is still \
running, a direct sweep otherwise;\n\
• remove the run permanently — it can never resume.",
],
"Keep run",
"Cancel run",
),
StopTarget::Launch(_) => (
"Stop this launch?",
&[
"Confirming will:",
"• stop the launch — an in-flight tool or LLM call may finish, \
but no further work happens;\n\
• mark the branch as deliberately stopped — automatic recovery \
never restarts it;\n\
• drop the launch's pending messages — they are not replayed \
when the service restarts.",
],
"Keep launch",
"Stop launch",
),
};
widgets::modal_backdrop(
dialog::confirm_dialog(
dialog::dialog_title(title),
dialog::dialog_body(body.iter().copied()),
[
dialog::DialogAction::secondary(keep, RunningMessage::StopDismissed),
dialog::DialogAction::danger(confirm, RunningMessage::StopConfirmed),
],
),
RunningMessage::StopDismissed,
0.5,
)
}
fn fallback_workspace_label(workspace: &str) -> String {
if workspace.is_empty() {
"workspace".to_string()
} else {
format!("{workspace} (external)")
}
}
fn workspace_label_for(
name: &str,
workspaces: &std::collections::HashMap<String, Workspace>,
) -> String {
if name.is_empty() {
"workspace".to_string()
} else if workspaces.contains_key(name) {
name.to_string()
} else {
fallback_workspace_label(name)
}
}
fn render_agent_card(card: &AgentCard, expanded: bool) -> Element<'static, RunningMessage> {
let h = &card.handle;
let (fg, _bg) = theme::role_badge_color(&h.role);
let role: crate::Role = h.role.parse().unwrap_or(crate::Role::Engineer);
let icon = theme::role_icon(&role).size(theme::TEXT_24).color(fg);
let elapsed = format_elapsed(h.started_at);
let snapshot = crate::session::TRANSCRIPT_REGISTRY.snapshot(&h.agent_id);
let ledger = snapshot
.as_ref()
.map(|snapshot| build_ledger(&snapshot.history))
.unwrap_or_default();
let groups = derive_trace_groups(current_turn_entries(&ledger));
let token_count = snapshot.as_ref().and_then(|s| s.token_count);
let mut content = Column::new()
.spacing(theme::SPACE_6)
.align_x(Alignment::Start)
.width(Length::Fill);
let first_row = Row::new()
.spacing(theme::SPACE_12)
.align_y(Alignment::Center)
.push(icon)
.push(render_metrics(token_count, &elapsed));
content = content.push(first_row);
let lines = visible_lines(&groups, expanded);
if !lines.iter().any(|line| matches!(line, GroupLine::Line(_))) {
content = content.push(clanking_placeholder());
}
for group in render_visible_groups(&groups, lines) {
content = content.push(group);
}
if let Some(activity) = &h.activity {
content = content.push(
text(activity.to_owned())
.size(theme::TEXT_13)
.color(theme::ACCENT),
);
}
let on_press = RunningMessage::ToggleAgentExpanded {
agent_id: h.agent_id.clone(),
generation: h.generation,
};
mouse_area(
container(content)
.width(Length::Fill)
.padding(theme::PAD_8)
.style(theme::surface_card_style),
)
.on_press(on_press)
.into()
}
fn trace_line_text(line: &str) -> iced::widget::Text<'static, iced::Theme, iced::Renderer> {
text(line.to_owned())
.size(theme::NARRATION_TEXT_SIZE)
.font(theme::FONT_ITALIC)
.color(theme::TEXT_SECONDARY)
.wrapping(iced::widget::text::Wrapping::WordOrGlyph)
}
fn clanking_placeholder() -> iced::widget::Text<'static, iced::Theme, iced::Renderer> {
text("clanking")
.size(theme::TEXT_13)
.color(theme::TEXT_SECONDARY)
}
fn render_metrics(token_count: Option<u64>, elapsed: &str) -> Element<'static, RunningMessage> {
let mut metrics = Row::new()
.spacing(theme::SPACE_12)
.align_y(Alignment::Center);
if let Some(token_count) = token_count {
metrics = metrics.push(
tooltip(
text(theme::format_compact_tokens(token_count))
.size(theme::TEXT_11)
.color(theme::TEXT_SECONDARY),
render_metric_tooltip(format!("Session tokens: {token_count}")),
tooltip::Position::Top,
)
.gap(theme::SPACE_4)
.style(theme::tooltip_style),
);
}
metrics = metrics.push(
tooltip(
text(elapsed.to_owned())
.size(theme::TEXT_11)
.color(theme::TEXT_SECONDARY),
render_metric_tooltip("Elapsed run time since the agent started".to_string()),
tooltip::Position::Top,
)
.gap(theme::SPACE_4)
.style(theme::tooltip_style),
);
metrics.into()
}
enum GroupLine<'a> {
Line(trace_line::Line<'a>),
Blank,
}
fn render_visible_groups<'a>(
groups: &'a [TraceGroup<'a>],
lines: Vec<GroupLine<'a>>,
) -> Vec<Element<'static, RunningMessage>> {
let start = groups.len() - lines.len();
let current = groups.len().saturating_sub(1);
groups[start..]
.iter()
.zip(lines)
.enumerate()
.map(|(offset, (group, line))| render_trace_group(group, start + offset == current, line))
.collect()
}
fn visible_lines<'a>(groups: &'a [TraceGroup<'a>], expanded: bool) -> Vec<GroupLine<'a>> {
let depth = if expanded { MAX_PREVIOUS_GROUPS + 1 } else { 1 };
let start = groups.len().saturating_sub(depth);
let mut lines: Vec<GroupLine<'a>> = groups[start..]
.iter()
.map(|group| group_line(group).map_or(GroupLine::Blank, GroupLine::Line))
.collect();
if let Some(GroupLine::Blank) = lines.last() {
let held = lines[..lines.len() - 1]
.iter()
.rev()
.find_map(|line| match line {
GroupLine::Line(line) => Some((line.text.clone(), line.hover)),
GroupLine::Blank => None,
})
.or_else(|| {
groups[..start]
.iter()
.rev()
.find_map(group_line)
.map(|line| (line.text, line.hover))
});
if let Some((text, hover)) = held {
*lines.last_mut().expect("non-empty tail") =
GroupLine::Line(trace_line::Line { text, hover });
}
}
let mut shown: HashSet<String> = HashSet::new();
for line in lines.iter_mut().rev() {
let GroupLine::Line(group_line) = line else {
continue;
};
if !shown.insert(group_line.text.clone()) {
*line = GroupLine::Blank;
}
}
lines
}
fn group_line<'a>(group: &TraceGroup<'a>) -> Option<trace_line::Line<'a>> {
group
.steps
.iter()
.rev()
.find_map(|step| trace_line::line_for_step(step.narration, step.reasoning))
}
fn render_trace_group<'a>(
group: &TraceGroup<'a>,
expand_current: bool,
line: GroupLine<'a>,
) -> Element<'static, RunningMessage> {
let mut column = Column::new()
.spacing(theme::SPACE_4)
.align_x(Alignment::Start);
match line {
GroupLine::Line(line) => {
column = column.push(reasoning_tooltip(
line.hover,
trace_line_text(&line.text).into(),
));
}
GroupLine::Blank => {}
}
if expand_current {
let (newest, earlier) = group
.steps
.split_last()
.expect("a trace group always carries at least one step");
if !earlier.is_empty() {
column = column.push(
text(collapsed_calls_line(earlier))
.size(theme::TEXT_10)
.color(theme::TEXT_SECONDARY),
);
}
for entry in newest.calls {
column = column.push(tool_row(entry));
}
} else {
column = column.push(
text(collapsed_calls_line(&group.steps))
.size(theme::TEXT_10)
.color(theme::TEXT_SECONDARY),
);
}
column.into()
}
fn tool_row(entry: &ToolCallEntry) -> Element<'static, RunningMessage> {
let block = tool_block(&entry.tool, ToolBlockView::Compact);
if entry.result.is_none() {
Row::new()
.spacing(theme::SPACE_6)
.align_y(Alignment::Center)
.push(block)
.push(super::activity_dot())
.into()
} else {
block
}
}
fn reasoning_tooltip<'a>(
reasoning: Option<&str>,
line: Element<'a, RunningMessage>,
) -> Element<'a, RunningMessage> {
let Some(reasoning) = reasoning else {
return line;
};
let tooltip_content: Element<'static, RunningMessage> = container(
text(reasoning.to_string())
.size(theme::TEXT_11)
.color(theme::TEXT_SECONDARY)
.wrapping(iced::widget::text::Wrapping::WordOrGlyph),
)
.max_width(MAX_TOOL_TOOLTIP_WIDTH)
.into();
tooltip(line, tooltip_content, tooltip::Position::Top)
.gap(theme::SPACE_4)
.style(theme::tooltip_style)
.into()
}
fn collapsed_calls_line(steps: &[TraceStep<'_>]) -> String {
let mut order: Vec<String> = Vec::new();
let mut counts: HashMap<String, usize> = HashMap::new();
for step in steps {
for call in step.calls {
let base = call.tool.name.replace('_', " ");
let display = if call.result.is_none() {
format!("{base} …")
} else {
base
};
if !counts.contains_key(&display) {
order.push(display.clone());
}
*counts.entry(display).or_default() += 1;
}
}
order
.iter()
.map(|name| {
let c = counts[name];
if c > 1 {
format!("{name} x{c}")
} else {
name.clone()
}
})
.collect::<Vec<_>>()
.join(", ")
}
pub(crate) fn prune_expanded(expanded: &mut HashSet<(String, u64)>, agents: &[AgentHandle]) {
let live: HashSet<(String, u64)> = agents
.iter()
.map(|h| (h.agent_id.clone(), h.generation))
.collect();
expanded.retain(|key| live.contains(key));
}
struct TraceStep<'a> {
narration: &'a str,
reasoning: Option<&'a str>,
calls: &'a [ToolCallEntry],
}
struct TraceGroup<'a> {
steps: Vec<TraceStep<'a>>,
}
fn is_user_turn_boundary(entry: &SessionEntry) -> bool {
matches!(entry, SessionEntry::Message { role: ChatRole::User, content, .. }
if content.as_deref().is_some_and(|c| {
!c.trim().is_empty() && !c.starts_with(crate::util::INJECTED_IMAGE_TAG)
}))
}
fn current_turn_entries(entries: &[SessionEntry]) -> &[SessionEntry] {
let start = entries
.iter()
.rposition(is_user_turn_boundary)
.map_or(0, |i| i + 1);
&entries[start..]
}
fn derive_trace_groups(entries: &[SessionEntry]) -> Vec<TraceGroup<'_>> {
let mut groups: Vec<TraceGroup> = Vec::new();
let mut current: Option<TraceGroup> = None;
for entry in entries {
match entry {
SessionEntry::ToolRound {
narration,
reasoning,
calls,
} => {
let narration = narration.as_deref().unwrap_or_default();
if !narration.trim().is_empty()
&& let Some(group) = current.take()
{
groups.push(group);
}
let group = current.get_or_insert_with(|| TraceGroup { steps: Vec::new() });
group.steps.push(TraceStep {
narration,
reasoning: reasoning.as_deref(),
calls,
});
}
SessionEntry::Message { .. } => {
if is_user_turn_boundary(entry)
&& let Some(group) = current.take()
{
groups.push(group);
}
}
}
}
if let Some(group) = current.take() {
groups.push(group);
}
groups
}
fn render_metric_tooltip(label: String) -> Element<'static, RunningMessage> {
container(
text(label)
.size(theme::TEXT_11)
.color(theme::TEXT_PRIMARY)
.wrapping(iced::widget::text::Wrapping::WordOrGlyph),
)
.max_width(MAX_METRIC_TOOLTIP_WIDTH)
.into()
}
fn render_call_row(call: &CallRow) -> Element<'static, RunningMessage> {
let h = &call.handle;
let elapsed = format_elapsed(h.started_at);
let purpose = crate::agent::registry::call_kind_label(h.kind);
row![
lucide::zap::<iced::Theme, iced::Renderer>()
.size(theme::TEXT_16)
.color(theme::ACCENT),
text(purpose)
.size(theme::TEXT_12)
.color(theme::TEXT_SECONDARY),
Space::new().width(Length::Fill),
text(elapsed)
.size(theme::TEXT_11)
.color(theme::TEXT_SECONDARY),
]
.spacing(theme::SPACE_6)
.align_y(Alignment::Center)
.into()
}
fn format_elapsed(started_at: DateTime<Utc>) -> String {
let now = Utc::now();
let secs = now.signed_duration_since(started_at).num_seconds().max(0);
if secs < 60 {
format!("{secs}s")
} else if secs < 3600 {
format!("{}m {:02}s", secs / 60, secs % 60)
} else {
format!("{}h {:02}m", secs / 3600, (secs % 3600) / 60)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ChatMessage;
use crate::agent::registry::{AgentHandle, RunningTool};
use crate::gui::session_view::build_ledger;
fn parent(spec: &str) -> Option<ParentKey> {
let (kind, key) = spec.split_once(':')?;
let key = key.to_string();
Some(match kind {
"t" => ParentKey::Ticket(key),
"a" => ParentKey::AnalyzeRound(key),
"r" => ParentKey::Research(key),
_ => ParentKey::Launch(key),
})
}
fn agent(id: &str, role: &str, workspace: &str, parent_spec: &str) -> AgentHandle {
AgentHandle {
agent_id: id.to_string(),
role: role.to_string(),
ticket_id: None,
workspace_path: format!("/ws/{workspace}"),
workspace_name: workspace.to_string(),
parent_key: parent(parent_spec),
parent_label: None,
started_at: Utc::now(),
generation: 0,
activity: None,
paused: false,
}
}
fn call(
kind: &'static str,
workspace: &str,
parent_spec: &str,
run_lifetime: bool,
) -> NonAgentCallHandle {
NonAgentCallHandle {
kind,
workspace: workspace.to_string(),
started_at: Utc::now(),
parent_key: parent(parent_spec),
parent_label: None,
run_lifetime,
}
}
type AgentRow = (&'static str, &'static str, &'static str, &'static str);
type CallRow = (&'static str, &'static str, &'static str, bool);
type GroupRow = (GroupKind, &'static str, usize, Option<&'static str>, bool);
struct GroupCase {
name: &'static str,
agents: &'static [AgentRow],
calls: &'static [CallRow],
total: usize,
groups: &'static [GroupRow],
}
fn case(
name: &'static str,
agents: &'static [AgentRow],
calls: &'static [CallRow],
total: usize,
groups: &'static [GroupRow],
) -> GroupCase {
GroupCase {
name,
agents,
calls,
total,
groups,
}
}
#[test]
fn build_groups_keeps_runs_and_rounds_apart() {
let cases = [
case(
"ticket agents and synthesis share the ticket group",
&[
("a1", "analyst", "ws1", "t:T1"),
("mgr", "manager", "ws1", ""),
],
&[("synthesis", "ws1", "t:T1", false)],
2,
&[(GroupKind::Ticket, "T1", 2, None, false)],
),
case(
"two analyze rounds never mix members",
&[
("a1", "analyst", "ws1", "a:roundA"),
("a2", "analyst", "ws1", "a:roundA"),
("b1", "analyst", "ws1", "a:roundB"),
],
&[("consolidate", "ws1", "a:roundA", false)],
2,
&[
(GroupKind::AnalyzeRound, "roundA", 3, None, false),
(GroupKind::AnalyzeRound, "roundB", 1, None, false),
],
),
case(
"research run members share one key across phases",
&[
("x1", "analyst", "ws1", "r:run1"),
("x2", "analyst", "ws1", "r:run1"),
("y1", "analyst", "ws1", "r:run2"),
],
&[
("synthesize", "ws1", "r:run1", false),
("research_orchestrator", "ws1", "r:run1", true),
],
2,
&[
(GroupKind::Research, "run1", 3, None, true),
(GroupKind::Research, "run2", 1, None, false),
],
),
case(
"a run resolves to the real workspace across ephemeral workers",
&[
("w1", "worker", "run1", "r:run1"),
("r1", "analyst", "ws1", "r:run1"),
("r2", "analyst", "ws1", "r:run2"),
("w2", "worker", "run2", "r:run2"),
],
&[],
2,
&[
(GroupKind::Research, "run1", 2, Some("ws1"), false),
(GroupKind::Research, "run2", 2, Some("ws1"), false),
],
),
case(
"cross-workspace round keys never merge groups",
&[
("a1", "analyst", "ws1", "a:abc123"),
("b1", "analyst", "ws2", "a:abc123"),
],
&[],
2,
&[
(GroupKind::AnalyzeRound, "abc123", 1, Some("ws1"), false),
(GroupKind::AnalyzeRound, "abc123", 1, Some("ws2"), false),
],
),
];
for case in cases {
let agents: Vec<_> = case
.agents
.iter()
.map(|&(id, role, ws, p)| agent(id, role, ws, p))
.collect();
let calls: Vec<_> = case
.calls
.iter()
.map(|&(k, ws, p, run)| call(k, ws, p, run))
.collect();
let groups = build_groups(&agents, &calls);
assert_case(&case, &groups);
}
}
fn assert_case(case: &GroupCase, groups: &[DisplayGroup]) {
let name = case.name;
assert_eq!(groups.len(), case.total, "case {name}: group count");
for row in case.groups {
let (kind, key, items) = (&row.0, row.1, row.2);
let (workspace, run_lifetime) = (row.3, row.4);
let found = groups.iter().find(|group| {
&group.kind == kind
&& group.key == key
&& workspace.is_none_or(|ws| group.workspace == ws)
});
let group = found.unwrap_or_else(|| panic!("case {name}: no {kind:?} group {key:?}"));
assert_eq!(group.items.len(), items, "case {name}: {key} members");
if let Some(ws) = workspace {
assert_eq!(group.workspace, ws, "case {name}: {key} workspace");
}
assert_eq!(
group.run_lifetime, run_lifetime,
"case {name}: {key} run lifetime"
);
}
}
#[test]
fn singleton_and_unattributed_groups_stay_generic_per_workspace() {
let cases: &[(&str, &[AgentRow], &[CallRow], usize)] = &[
(
"one singleton group per workspace",
&[
("mgr_ws1", "manager", "ws1", ""),
("mnt_ws2", "maintainer", "ws2", ""),
],
&[("some_orchestrator_call", "ws1", "", false)],
2,
),
(
"group headers never repeat the workspace",
&[("mgr", "manager", "ws1", "")],
&[("some_orchestrator_call", "ws1", "", false)],
1,
),
];
for &(name, agent_rows, call_rows, singletons) in cases {
let agents: Vec<_> = agent_rows
.iter()
.map(|&(id, role, ws, p)| agent(id, role, ws, p))
.collect();
let calls: Vec<_> = call_rows
.iter()
.map(|&(k, ws, p, run)| call(k, ws, p, run))
.collect();
let groups = build_groups(&agents, &calls);
let count = |kind: &GroupKind| groups.iter().filter(|g| &g.kind == kind).count();
assert_eq!(
count(&GroupKind::Singleton),
singletons,
"case {name}: singletons"
);
assert_eq!(
count(&GroupKind::Unattributed),
1,
"case {name}: unattributed"
);
let unattributed = groups.iter().find(|g| g.kind == GroupKind::Unattributed);
assert_eq!(
unattributed.unwrap().workspace,
"ws1",
"case {name}: workspace"
);
for group in &groups {
let (title, _) = group_title(group);
assert!(
!title.contains("ws1"),
"case {name}: no workspace in {title}"
);
}
}
}
#[test]
fn sort_key_orders_groups_by_kind() {
let group = |kind: GroupKind| DisplayGroup {
kind,
key: "ws".to_string(),
workspace: "ws".to_string(),
label: None,
items: Vec::new(),
run_lifetime: false,
};
let mut groups = [
group(GroupKind::Unattributed),
group(GroupKind::Ticket),
group(GroupKind::Research),
];
groups.sort_by_key(DisplayGroup::sort_key);
let kinds: Vec<_> = groups.iter().map(|group| group.kind.clone()).collect();
let expected = [
GroupKind::Ticket,
GroupKind::Research,
GroupKind::Unattributed,
];
assert_eq!(kinds, expected);
}
#[test]
fn ticket_group_label_comes_from_members_not_the_key() {
let mut analyst = agent("a1", "analyst", "ws1", "t:T1");
analyst.parent_label = Some("Fix the login flow".to_string());
let mut synthesis = call("synthesis", "ws1", "t:T1", false);
synthesis.parent_label = Some("Fix the login flow".to_string());
let groups = build_groups(&[analyst], &[synthesis]);
let ticket = groups.iter().find(|g| g.kind == GroupKind::Ticket);
let ticket = ticket.expect("ticket group exists");
assert_eq!(
ticket.label.as_deref(),
Some("Fix the login flow"),
"label from a member"
);
let (title, secondary) = group_title(ticket);
assert_eq!(title, "Fix the login flow");
assert_eq!(secondary.as_deref(), Some("T1"));
}
#[test]
fn sections_group_by_workspace_and_keep_kind_order() {
let mut workspaces = std::collections::HashMap::new();
workspaces.insert(
"ws2".to_string(),
Workspace {
path: "/ws/ws2".to_string(),
..Default::default()
},
);
let agents = vec![
agent("t_agent", "engineer", "ws1", "t:T1"),
agent("mgr_ws2", "manager", "ws2", ""),
agent("mgr_ws1", "manager", "ws1", ""),
];
let sections = build_sections(build_groups(&agents, &[]), &workspaces);
assert_eq!(sections.len(), 2, "one section per workspace");
assert_eq!(sections[0].workspace, "ws1");
assert_eq!(sections[1].workspace, "ws2");
assert_eq!(sections[0].groups[0].kind, GroupKind::Ticket);
assert_eq!(sections[0].groups[1].kind, GroupKind::Singleton);
assert_eq!(sections[1].label, "ws2");
assert_eq!(sections[0].label, "ws1 (external)");
}
fn assistant_tool_call(narration: &str, calls: &[(&str, serde_json::Value)]) -> ChatMessage {
assistant_tool_call_reasoning(narration, calls, None)
}
fn assistant_tool_call_reasoning(
narration: &str,
calls: &[(&str, serde_json::Value)],
reasoning: Option<&str>,
) -> ChatMessage {
let calls_json: Vec<serde_json::Value> = calls
.iter()
.map(|(name, args)| {
serde_json::json!({
"id": "call_1",
"name": name,
"arguments": serde_json::to_string(args).unwrap_or_default(),
})
})
.collect();
let content = if narration.is_empty() {
serde_json::Value::Null
} else {
serde_json::Value::String(narration.to_string())
};
let mut body = serde_json::json!({ "content": content, "tool_calls": calls_json });
if let Some(reasoning) = reasoning {
body["reasoning"] = serde_json::json!(reasoning);
}
ChatMessage::assistant(body.to_string())
}
fn round(narration: &str) -> ChatMessage {
assistant_tool_call(narration, &[("read", serde_json::json!({"path": "a.rs"}))])
}
fn thinking(narration: &str, reasoning: &str) -> ChatMessage {
assistant_tool_call_reasoning(
narration,
&[("read", serde_json::json!({"path": "a.rs"}))],
Some(reasoning),
)
}
fn user_turn(text: &str) -> ChatMessage {
ChatMessage::user(format!(
"{text}\n\n<timestamp>2026-01-01 00:00:00 (UTC)</timestamp>"
))
}
fn injected_image() -> ChatMessage {
let marker = format!("[IMAGE:{}]", "data:image/png;base64,xxx");
ChatMessage::user(crate::util::injected_image_user_message(&[marker]))
}
fn assert_trace_groups(name: &str, groups: &[TraceGroup<'_>], expected: &[&[&str]]) {
assert_eq!(groups.len(), expected.len(), "case {name}: group count");
for (group, steps) in groups.iter().zip(expected) {
assert_eq!(
group.steps.len(),
steps.len(),
"case {name}: steps in group"
);
for (step, wanted) in group.steps.iter().zip(*steps) {
assert_eq!(step.narration, *wanted, "case {name}: step narration");
}
}
}
type TurnCase<'a> = (&'a str, Vec<ChatMessage>, Vec<Vec<&'a str>>);
#[test]
fn narration_and_turn_boundaries_derive_groups() {
let cases: &[TurnCase] = &[
("empty history produces no groups", Vec::new(), Vec::new()),
(
"a content-only assistant message is not a group",
vec![
user_turn("hello"),
ChatMessage::assistant("Final answer here."),
],
Vec::new(),
),
(
"a new narration starts a new group",
vec![round("Reading the file"), round("Editing it")],
vec![vec!["Reading the file"], vec!["Editing it"]],
),
(
"consecutive no-narration rounds accumulate",
vec![round(""), round("")],
vec![vec!["", ""]],
),
(
"a real user turn resets the group",
vec![round("Narration"), user_turn("ok now fix it"), round("")],
vec![vec!["Narration"], vec![""]],
),
(
"an injected image user message does not reset the group",
vec![round(""), injected_image(), round("")],
vec![vec!["", ""]],
),
(
"an empty user message is not a turn boundary",
vec![round(""), ChatMessage::user(""), round("")],
vec![vec!["", ""]],
),
];
for (name, history, expected) in cases {
let ledger = build_ledger(history);
let groups = derive_trace_groups(&ledger);
let expected: Vec<&[&str]> = expected.iter().map(Vec::as_slice).collect();
assert_trace_groups(name, &groups, &expected);
}
}
fn entry(name: &str, args: serde_json::Value, result: Option<&str>) -> ToolCallEntry {
ToolCallEntry {
tool_call_id: String::new(),
tool: RunningTool::from_tool_call(&crate::ToolCall {
id: String::new(),
name: name.to_string(),
arguments: args,
}),
result: result.map(ToString::to_string),
}
}
fn step(calls: &[ToolCallEntry]) -> TraceStep<'_> {
TraceStep {
narration: "",
reasoning: None,
calls,
}
}
#[test]
fn collapsed_calls_line_counts_and_orders() {
let read_calls = [
entry("read_file", serde_json::json!({"path": "a.rs"}), Some("ok")),
entry("list_files", serde_json::json!({"path": "."}), Some("ok")),
];
let edit_calls = [
entry("read_file", serde_json::json!({"path": "b.rs"}), Some("ok")),
entry("read_file", serde_json::json!({"path": "c.rs"}), None),
];
let steps = vec![step(&read_calls), step(&edit_calls)];
assert_eq!(
collapsed_calls_line(&steps),
"read file x2, list files, read file …"
);
}
#[test]
fn rounds_carry_results_for_in_flight_distinction() {
let calls_json = serde_json::json!([
{"id": "call_a", "name": "read", "arguments": "{\"path\": \"a.rs\"}"},
{"id": "call_b", "name": "edit", "arguments": "{\"path\": \"b.rs\"}"},
]);
let body = serde_json::json!({ "content": null, "tool_calls": calls_json });
let history = vec![
ChatMessage::assistant(body.to_string()),
ChatMessage::tool_result("call_a", "contents of a.rs"),
];
let ledger = build_ledger(&history);
let groups = derive_trace_groups(&ledger);
assert_eq!(groups.len(), 1);
let round = &groups[0].steps[0].calls;
assert_eq!(round.len(), 2, "both calls preserved in the round");
let settled = round
.iter()
.find(|c| c.tool_call_id == "call_a")
.expect("call_a");
assert_eq!(
settled.result.as_deref(),
Some("contents of a.rs"),
"matched tool result attaches to call_a"
);
let in_flight = round
.iter()
.find(|c| c.tool_call_id == "call_b")
.expect("call_b");
assert_eq!(
in_flight.result, None,
"call_b has no result yet → in-flight"
);
}
fn shown_lines(groups: &[TraceGroup<'_>], expanded: bool) -> Vec<String> {
visible_lines(groups, expanded)
.into_iter()
.map(|line| match line {
GroupLine::Line(line) => line.text,
GroupLine::Blank => "<blank>".to_string(),
})
.collect()
}
#[test]
fn the_line_follows_the_newest_step_and_holds_the_previous_one() {
const DRIFT: &str = "The parser struct is missing the offset field, so the columns drift.";
const CHECKED: &str = "Checking the whole file first.";
let cases: &[(&str, Vec<ChatMessage>, &str, Option<&str>)] = &[
(
"the line follows the newest step",
vec![
thinking("Now editing the parser", "Reading the whole file first."),
thinking("", DRIFT),
],
DRIFT,
Some(DRIFT),
),
(
"a silent step keeps the previous line",
vec![thinking("", CHECKED), round("")],
CHECKED,
None,
),
(
"a whitespace-only narration keeps it too",
vec![thinking("", CHECKED), round(" ")],
CHECKED,
None,
),
];
for (name, history, text, hover) in cases {
let ledger = build_ledger(history);
let groups = derive_trace_groups(&ledger);
assert_eq!(groups.len(), 1, "case {name}: one group");
let line = group_line(&groups[0])
.unwrap_or_else(|| panic!("case {name}: the group carries text"));
assert_eq!(line.text, *text, "case {name}: line text");
if let Some(hover) = hover {
assert_eq!(line.hover, Some(*hover), "case {name}: hover");
}
}
}
type TextlessCase<'a> = (
&'a str,
Vec<ChatMessage>,
usize,
bool,
Option<&'a [&'a str]>,
Option<&'a [&'a str]>,
);
#[test]
fn textless_groups_hold_or_drop_the_line() {
const CHECKED: &str = "Checking the whole file first.";
let cases: &[TextlessCase] = &[
(
"a textless group holds the previous group's line",
vec![thinking("", CHECKED), round("---")],
2,
true,
Some(&[CHECKED]),
None,
),
(
"a turn's first group falls back to the placeholder",
vec![round("---")],
1,
true,
Some(&["<blank>"]),
None,
),
(
"a held line is not shown twice in the previous group's list",
vec![thinking("", CHECKED), round("---")],
2,
false,
Some(&[CHECKED]),
Some(&["<blank>", CHECKED]),
),
(
"a repeated line is dropped even when older groups sit between",
vec![
thinking("", "The same line here."),
user_turn("go on"),
round("Something else."),
user_turn("now the rest"),
thinking("", "The same line here."),
],
3,
false,
None,
Some(&["<blank>", "Something else.", "The same line here."]),
),
(
"a textless previous group renders no line rather than a placeholder",
vec![round("---"), round("Now editing.")],
2,
false,
None,
Some(&["<blank>", "Now editing."]),
),
];
for (name, history, count, textless, collapsed, expanded) in cases {
let ledger = build_ledger(history);
let groups = derive_trace_groups(&ledger);
assert_eq!(groups.len(), *count, "case {name}: group count");
if *textless {
assert!(
group_line(&groups[groups.len() - 1]).is_none(),
"case {name}: the new group has no text"
);
}
if let Some(collapsed) = collapsed {
assert_eq!(
shown_lines(&groups, false),
*collapsed,
"case {name}: collapsed"
);
}
if let Some(expanded) = expanded {
assert_eq!(
shown_lines(&groups, true),
*expanded,
"case {name}: expanded"
);
}
}
}
}