| 1 | use std::collections::{BTreeMap, BTreeSet, VecDeque}; |
| 2 | |
| 3 | use serde::{Deserialize, Serialize}; |
| 4 | |
| 5 | use super::{ThreadEdgeKind, ThreadOrigin, ThreadRecord}; |
| 6 | |
| 7 | pub const MAX_THREAD_GRAPH_NODES: usize = 256; |
| 8 | |
| 9 | #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] |
| 10 | #[serde(rename_all = "snake_case")] |
| 11 | pub enum ThreadGraphNodeKind { |
| 12 | Conversation, |
| 13 | Fork, |
| 14 | FleetCoordinator, |
| 15 | FleetWorker, |
| 16 | Subagent, |
| 17 | Unknown, |
| 18 | } |
| 19 | |
| 20 | impl ThreadGraphNodeKind { |
| 21 | #[must_use] |
| 22 | pub fn from_thread(thread: &ThreadRecord) -> Self { |
| 23 | match thread.origin { |
| 24 | Some(ThreadOrigin::Conversation | ThreadOrigin::Automation) => Self::Conversation, |
| 25 | Some(ThreadOrigin::Fork) => Self::Fork, |
| 26 | Some(ThreadOrigin::FleetCoordinator) => Self::FleetCoordinator, |
| 27 | Some(ThreadOrigin::FleetWorker) => Self::FleetWorker, |
| 28 | Some(ThreadOrigin::Subagent) => Self::Subagent, |
| 29 | None if thread.parent_edge_kind == Some(ThreadEdgeKind::Fork) => Self::Fork, |
| 30 | None => Self::Unknown, |
| 31 | } |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] |
| 36 | #[serde(rename_all = "snake_case")] |
| 37 | pub enum ThreadGraphEdgeKind { |
| 38 | Fork, |
| 39 | Spawned, |
| 40 | Coordinates, |
| 41 | ResumedFrom, |
| 42 | Unknown, |
| 43 | } |
| 44 | |
| 45 | impl From<ThreadEdgeKind> for ThreadGraphEdgeKind { |
| 46 | fn from(kind: ThreadEdgeKind) -> Self { |
| 47 | match kind { |
| 48 | ThreadEdgeKind::Fork => Self::Fork, |
| 49 | ThreadEdgeKind::Spawned => Self::Spawned, |
| 50 | ThreadEdgeKind::Coordinates => Self::Coordinates, |
| 51 | ThreadEdgeKind::ResumedFrom => Self::ResumedFrom, |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 57 | pub struct ThreadGraphNode { |
| 58 | pub thread_id: String, |
| 59 | pub kind: ThreadGraphNodeKind, |
| 60 | pub status: String, |
| 61 | #[serde(skip_serializing_if = "Option::is_none")] |
| 62 | pub run_id: Option<String>, |
| 63 | #[serde(skip_serializing_if = "Option::is_none")] |
| 64 | pub task_id: Option<String>, |
| 65 | pub archived: bool, |
| 66 | } |
| 67 | |
| 68 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 69 | pub struct ThreadGraphEdge { |
| 70 | pub from: String, |
| 71 | pub to: String, |
| 72 | pub kind: ThreadGraphEdgeKind, |
| 73 | } |
| 74 | |
| 75 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 76 | pub struct ThreadGraphResponse { |
| 77 | pub root_thread_id: String, |
| 78 | pub nodes: Vec<ThreadGraphNode>, |
| 79 | pub edges: Vec<ThreadGraphEdge>, |
| 80 | pub truncated: bool, |
| 81 | } |
| 82 | |
| 83 | #[must_use] |
| 84 | pub fn build_children_index(threads: &[ThreadRecord]) -> BTreeMap<String, Vec<String>> { |
| 85 | let mut index: BTreeMap<String, Vec<String>> = BTreeMap::new(); |
| 86 | for thread in threads { |
| 87 | if let Some(parent) = thread.parent_thread_id.as_deref() |
| 88 | && parent != thread.id |
| 89 | { |
| 90 | index |
| 91 | .entry(parent.to_string()) |
| 92 | .or_default() |
| 93 | .push(thread.id.clone()); |
| 94 | } |
| 95 | } |
| 96 | for children in index.values_mut() { |
| 97 | children.sort(); |
| 98 | children.dedup(); |
| 99 | } |
| 100 | index |
| 101 | } |
| 102 | |
| 103 | #[must_use] |
| 104 | pub fn build_thread_graph( |
| 105 | root_id: &str, |
| 106 | threads: &[ThreadRecord], |
| 107 | status_for: impl Fn(&ThreadRecord) -> String, |
| 108 | max_nodes: usize, |
| 109 | ) -> Option<ThreadGraphResponse> { |
| 110 | let by_id: BTreeMap<&str, &ThreadRecord> = threads.iter().map(|t| (t.id.as_str(), t)).collect(); |
| 111 | let root = *by_id.get(root_id)?; |
| 112 | let children_index = build_children_index(threads); |
| 113 | let cap = max_nodes.clamp(1, MAX_THREAD_GRAPH_NODES); |
| 114 | |
| 115 | let mut visited = BTreeSet::new(); |
| 116 | let mut queue = VecDeque::new(); |
| 117 | let mut nodes = Vec::new(); |
| 118 | let mut edges = Vec::new(); |
| 119 | let mut truncated = false; |
| 120 | |
| 121 | visited.insert(root.id.clone()); |
| 122 | queue.push_back(root); |
| 123 | |
| 124 | while let Some(thread) = queue.pop_front() { |
| 125 | nodes.push(ThreadGraphNode { |
| 126 | thread_id: thread.id.clone(), |
| 127 | kind: ThreadGraphNodeKind::from_thread(thread), |
| 128 | status: status_for(thread), |
| 129 | run_id: thread.run_id.clone(), |
| 130 | task_id: thread.task_id.clone(), |
| 131 | archived: thread.archived, |
| 132 | }); |
| 133 | if let Some(children) = children_index.get(&thread.id) { |
| 134 | for child_id in children { |
| 135 | let Some(&child) = by_id.get(child_id.as_str()) else { |
| 136 | continue; |
| 137 | }; |
| 138 | if visited.contains(&child.id) { |
| 139 | continue; |
| 140 | } |
| 141 | if visited.len() >= cap { |
| 142 | truncated = true; |
| 143 | continue; |
| 144 | } |
| 145 | visited.insert(child.id.clone()); |
| 146 | edges.push(ThreadGraphEdge { |
| 147 | from: thread.id.clone(), |
| 148 | to: child.id.clone(), |
| 149 | kind: child |
| 150 | .parent_edge_kind |
| 151 | .map(Into::into) |
| 152 | .unwrap_or(ThreadGraphEdgeKind::Unknown), |
| 153 | }); |
| 154 | queue.push_back(child); |
| 155 | } |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | Some(ThreadGraphResponse { |
| 160 | root_thread_id: root.id.clone(), |
| 161 | nodes, |
| 162 | edges, |
| 163 | truncated, |
| 164 | }) |
| 165 | } |
| 166 | |
| 167 | #[cfg(test)] |
| 168 | mod tests { |
| 169 | use super::*; |
| 170 | use chrono::Utc; |
| 171 | use std::path::PathBuf; |
| 172 | |
| 173 | fn thread( |
| 174 | id: &str, |
| 175 | parent: Option<&str>, |
| 176 | origin: Option<ThreadOrigin>, |
| 177 | edge: Option<ThreadEdgeKind>, |
| 178 | ) -> ThreadRecord { |
| 179 | let now = Utc::now(); |
| 180 | ThreadRecord { |
| 181 | schema_version: 2, |
| 182 | id: id.to_string(), |
| 183 | whale_id: None, |
| 184 | child_posture: None, |
| 185 | origin, |
| 186 | created_at: now, |
| 187 | updated_at: now, |
| 188 | model: "test-model".to_string(), |
| 189 | model_provider: None, |
| 190 | model_provider_id: None, |
| 191 | reasoning_effort: None, |
| 192 | allowed_tools: None, |
| 193 | disallowed_tools: Vec::new(), |
| 194 | add_dirs: Vec::new(), |
| 195 | workspace: PathBuf::from("."), |
| 196 | mode: "agent".to_string(), |
| 197 | permission_posture: None, |
| 198 | allow_shell: false, |
| 199 | trust_mode: false, |
| 200 | auto_approve: false, |
| 201 | latest_turn_id: None, |
| 202 | latest_response_bookmark: None, |
| 203 | archived: false, |
| 204 | system_prompt: None, |
| 205 | task_id: None, |
| 206 | parent_thread_id: parent.map(str::to_string), |
| 207 | parent_edge_kind: edge, |
| 208 | run_id: None, |
| 209 | title: None, |
| 210 | session_id: None, |
| 211 | saved_session_checkpoint: None, |
| 212 | last_read: None, |
| 213 | executor: None, |
| 214 | environment: None, |
| 215 | agent_preset: None, |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | #[test] |
| 220 | fn thread_graph_builds_fork_coordinator_worker_subagent_and_legacy_unknown_edges() { |
| 221 | let root = thread("root", None, Some(ThreadOrigin::Conversation), None); |
| 222 | let fork = thread( |
| 223 | "fork-1", |
| 224 | Some("root"), |
| 225 | Some(ThreadOrigin::Fork), |
| 226 | Some(ThreadEdgeKind::Fork), |
| 227 | ); |
| 228 | let mut coord = thread( |
| 229 | "coord-1", |
| 230 | Some("root"), |
| 231 | Some(ThreadOrigin::FleetCoordinator), |
| 232 | Some(ThreadEdgeKind::Coordinates), |
| 233 | ); |
| 234 | coord.run_id = Some("run-1".to_string()); |
| 235 | let mut worker = thread( |
| 236 | "worker-1", |
| 237 | Some("coord-1"), |
| 238 | Some(ThreadOrigin::FleetWorker), |
| 239 | Some(ThreadEdgeKind::Coordinates), |
| 240 | ); |
| 241 | worker.run_id = Some("run-1".to_string()); |
| 242 | worker.task_id = Some("task-1".to_string()); |
| 243 | let mut subagent = thread( |
| 244 | "sub-1", |
| 245 | Some("worker-1"), |
| 246 | Some(ThreadOrigin::Subagent), |
| 247 | Some(ThreadEdgeKind::Spawned), |
| 248 | ); |
| 249 | subagent.archived = true; |
| 250 | let legacy = thread("legacy-1", Some("root"), None, None); |
| 251 | |
| 252 | let threads = vec![root, fork, coord, worker, subagent, legacy]; |
| 253 | let index = build_children_index(&threads); |
| 254 | assert_eq!(index["root"], vec!["coord-1", "fork-1", "legacy-1"]); |
| 255 | |
| 256 | let graph = build_thread_graph("root", &threads, |_| "idle".to_string(), 64) |
| 257 | .expect("graph should exist"); |
| 258 | assert!(!graph.truncated); |
| 259 | assert_eq!(graph.nodes.len(), 6); |
| 260 | assert_eq!(graph.edges.len(), 5); |
| 261 | |
| 262 | let legacy_node = graph |
| 263 | .nodes |
| 264 | .iter() |
| 265 | .find(|n| n.thread_id == "legacy-1") |
| 266 | .unwrap(); |
| 267 | assert_eq!(legacy_node.kind, ThreadGraphNodeKind::Unknown); |
| 268 | let legacy_edge = graph.edges.iter().find(|e| e.to == "legacy-1").unwrap(); |
| 269 | assert_eq!(legacy_edge.kind, ThreadGraphEdgeKind::Unknown); |
| 270 | |
| 271 | let sub_node = graph.nodes.iter().find(|n| n.thread_id == "sub-1").unwrap(); |
| 272 | assert_eq!(sub_node.kind, ThreadGraphNodeKind::Subagent); |
| 273 | assert!(sub_node.archived); |
| 274 | |
| 275 | let bounded = |
| 276 | build_thread_graph("root", &threads, |_| "idle".to_string(), 2).expect("bounded graph"); |
| 277 | assert!(bounded.truncated); |
| 278 | assert_eq!(bounded.nodes.len(), 2); |
| 279 | } |
| 280 | } |
| 281 |