1use std::collections::HashMap;
12use std::path::Path;
13
14use super::parse::*;
15use super::types::*;
16use super::SubagentWatcher;
17
18#[path = "jsonl_change_steps.rs"]
19pub mod steps;
20
21impl SubagentWatcher {
22 pub(super) fn process_jsonl_change(&self, parent_agent: &str, parent_block_id: &str, jsonl_path: &Path, live: bool) {
36 let Some(change) = steps::Change::of(parent_agent, parent_block_id, jsonl_path, live) else {
37 return;
38 };
39 let Some((new_events, new_offset, meta)) = self.read_new_lines(&change, jsonl_path) else {
40 return;
41 };
42 let (is_new, info_snapshot, completed) = match self.record_change(&change, jsonl_path, &new_events, new_offset, meta) {
44 steps::Recorded::Quiet { id_learned, name_learned } => {
45 self.announce_learned(&change, id_learned, name_learned);
46 return;
47 }
48 steps::Recorded::Changed { is_new, info_snapshot, completed, id_learned, name_learned } => {
49 self.announce_learned(&change, id_learned, name_learned);
50 (is_new, info_snapshot, completed)
51 }
52 };
53
54 if is_new {
55 self.announce_spawn(&change, &info_snapshot);
56 }
57 if !new_events.is_empty() {
58 self.announce_activity(&change, &new_events, &info_snapshot);
59 }
60 if completed {
61 self.announce_completion(&change, &info_snapshot);
62 }
63 self.announce_dispatch(&change, &info_snapshot, is_new, completed);
64 }
65
66 pub(super) fn flush_pending_dispatch_activity(&self) {
73 let batch: HashMap<String, PendingDispatchActivity> = {
74 let mut pending = self.pending_activity.lock().unwrap();
75 std::mem::take(&mut *pending)
76 };
77 for (dispatch_id, pending) in batch {
78 for spawn in &pending.spawned {
79 self.broadcast_member_spawned(
80 spawn,
81 &pending.parent_agent,
82 &pending.parent_block_id,
83 &pending.session_id,
84 &dispatch_id,
85 );
86 }
87
88 if !pending.members.is_empty() {
89 let new_events: usize = pending.members.iter().map(|(_, evs)| evs.len()).sum();
90 self.event_bus.broadcast_typed::<crate::backend::mps_events::DispatchActivity>(&super::events::DispatchActivityEvent {
91 dispatch_id: dispatch_id.to_string(),
92 parent_agent: pending.parent_agent.to_string(),
93 parent_block_id: pending.parent_block_id.to_string(),
94 session_id: pending.session_id.to_string(),
95 new_events: new_events,
96 members: pending.members.iter().map(|(agent_id, events)| super::events::DispatchMemberEvents { agent_id: agent_id.clone(), events: events.clone() }).collect(),
97 });
98 }
99
100 for done in &pending.completed {
101 self.broadcast_member_completed(
102 done,
103 &pending.parent_agent,
104 &pending.parent_block_id,
105 &pending.session_id,
106 &dispatch_id,
107 );
108 }
109
110 if let Some(info) = &pending.latest_info {
111 self.broadcast_dispatch_updated(info);
112 }
113 }
114 }
115
116 fn broadcast_member_spawned(
119 &self,
120 spawn: &PendingSpawn,
121 parent_agent: &str,
122 parent_block_id: &str,
123 session_id: &str,
124 dispatch_id: &str,
125 ) {
126 self.event_bus.broadcast_typed::<crate::backend::mps_events::SubagentSpawned>(&super::events::SubagentSpawnedEvent {
127 agent_id: spawn.agent_id.to_string(),
128 slug: spawn.slug.to_string(),
129 parent_agent: parent_agent.to_string(),
130 parent_block_id: parent_block_id.to_string(),
131 session_id: session_id.to_string(),
132 model: spawn.model.clone(),
133 dispatch_id: dispatch_id.to_string(),
134 });
135 tracing::info!(
136 agent_id = %spawn.agent_id,
137 slug = %spawn.slug,
138 parent = %parent_agent,
139 parent_block_id = %parent_block_id,
140 session_id = %session_id,
141 dispatch_id = %dispatch_id,
142 "subagent spawned"
143 );
144 }
145
146 fn broadcast_member_completed(
149 &self,
150 done: &PendingCompletion,
151 parent_agent: &str,
152 parent_block_id: &str,
153 session_id: &str,
154 dispatch_id: &str,
155 ) {
156 self.event_bus.broadcast_typed::<crate::backend::mps_events::SubagentCompleted>(&super::events::SubagentCompletedEvent {
157 agent_id: done.agent_id.to_string(),
158 parent_agent: Some(parent_agent.to_string()),
159 parent_block_id: parent_block_id.to_string(),
160 total_events: done.total_events,
161 dispatch_id: dispatch_id.to_string(),
162 });
163 tracing::info!(
164 agent_id = %done.agent_id,
165 total_events = done.total_events,
166 parent_block_id = %parent_block_id,
167 session_id = %session_id,
168 dispatch_id = %dispatch_id,
169 "subagent completed"
170 );
171 }
172
173 fn update_dispatch_membership(
183 &self,
184 workflow_id: &str,
185 parent_agent: &str,
186 parent_block_id: &str,
187 session_id: &str,
188 member_spawned: bool,
189 member_completed: bool,
190 ) {
191 if !member_spawned && !member_completed {
192 return;
193 }
194
195 let info = {
196 let mut dispatches = self.dispatches.lock().unwrap();
197 let state = Self::dispatch_entry(
198 &mut dispatches,
199 workflow_id,
200 parent_agent,
201 parent_block_id,
202 session_id,
203 );
204 if member_spawned {
205 state.member_files += 1;
206 }
207 if member_completed {
208 state.members_completed += 1;
209 }
210 Self::refresh_dispatch_info(state);
211 state.info.clone()
212 };
213 self.queue_dispatch_updated(workflow_id, parent_agent, parent_block_id, session_id, info);
214 }
215
216 fn queue_dispatch_updated(
221 &self,
222 dispatch_id: &str,
223 parent_agent: &str,
224 parent_block_id: &str,
225 session_id: &str,
226 info: AgentDispatch,
227 ) {
228 let mut pending = self.pending_activity.lock().unwrap();
229 let entry = pending
230 .entry(dispatch_id.to_string())
231 .or_insert_with(|| PendingDispatchActivity::new(parent_agent, parent_block_id, session_id));
232 entry.latest_info = Some(info);
233 }
234
235 pub(super) fn process_journal_change(
238 &self,
239 parent_agent: &str,
240 parent_block_id: &str,
241 journal_path: &Path,
242 ) {
243 let workflow_id = match parse_workflow_id(journal_path) {
244 Some(id) => id,
245 None => return,
246 };
247 let session_id = derive_session_id(journal_path);
248
249 let offset = {
251 let dispatches = self.dispatches.lock().unwrap();
252 dispatches
253 .get(&workflow_id)
254 .map(|w| w.journal_offset)
255 .unwrap_or(0)
256 };
257
258 let (started, results, new_offset) = match read_journal_counts(journal_path, offset) {
259 Ok(r) => r,
260 Err(e) => {
261 tracing::debug!(
262 workflow_id = %workflow_id,
263 error = %e,
264 "failed to read workflow journal"
265 );
266 return;
267 }
268 };
269 if new_offset == offset {
272 return;
273 }
274
275 let has_new_records = started > 0 || results > 0;
276 let info = {
277 let mut dispatches = self.dispatches.lock().unwrap();
278 let state = Self::dispatch_entry(
279 &mut dispatches,
280 &workflow_id,
281 parent_agent,
282 parent_block_id,
283 &session_id,
284 );
285 state.journal_offset = new_offset;
290 if has_new_records {
291 state.journal_started += started;
292 state.journal_results += results;
293 Self::refresh_dispatch_info(state);
294 }
295 state.info.clone()
296 };
297 if has_new_records {
301 self.queue_dispatch_updated(&workflow_id, parent_agent, parent_block_id, &session_id, info);
302 }
303 }
304
305 fn dispatch_entry<'a>(
306 dispatches: &'a mut HashMap<String, DispatchState>,
307 workflow_id: &str,
308 parent_agent: &str,
309 parent_block_id: &str,
310 session_id: &str,
311 ) -> &'a mut DispatchState {
312 dispatches
313 .entry(workflow_id.to_string())
314 .or_insert_with(|| DispatchState {
315 info: AgentDispatch {
316 dispatch_id: workflow_id.to_string(),
317 kind: DispatchKind::Workflow,
318 parent_agent: parent_agent.to_string(),
319 parent_block_id: parent_block_id.to_string(),
320 session_id: session_id.to_string(),
321 member_count: 0,
322 members_done: 0,
323 status: DispatchStatus::Running,
324 last_event_at: now_millis(),
325 dispatch_name: None,
326 },
327 journal_offset: 0,
328 journal_started: 0,
329 journal_results: 0,
330 member_files: 0,
331 members_completed: 0,
332 })
333 }
334
335 fn refresh_dispatch_info(state: &mut DispatchState) {
339 state.info.member_count = state.journal_started.max(state.member_files);
340 state.info.members_done = state.journal_results.max(state.members_completed);
341 state.info.last_event_at = now_millis();
342 Self::recompute_dispatch_status(state);
353 }
354
355 pub(super) fn recompute_dispatch_status(state: &mut DispatchState) {
360 let counts_complete = state.info.member_count > 0
361 && state.info.members_done >= state.info.member_count;
362 let quiet = now_millis().saturating_sub(state.info.last_event_at) > 60_000;
363 state.info.status = if counts_complete && quiet {
364 DispatchStatus::Completed
365 } else {
366 DispatchStatus::Running
367 };
368 }
369
370 pub(super) fn refresh_dispatch_status(state: &mut DispatchState) {
382 if state.info.status == DispatchStatus::Abandoned {
383 return;
384 }
385 Self::recompute_dispatch_status(state);
386 }
387
388 pub(super) fn broadcast_subagent_named(&self, agent_id: &str, display_name: &str) {
391 self.event_bus.broadcast_typed::<crate::backend::mps_events::SubagentNamed>(&super::events::SubagentNamedEvent {
392 agent_id: agent_id.to_string(),
393 display_name: display_name.to_string(),
394 });
395 }
396
397 pub(super) fn broadcast_subagent_updated(&self, agent_id: &str, parent_block_id: &str) {
402 self.event_bus.broadcast_typed::<crate::backend::mps_events::SubagentUpdated>(&super::events::SubagentUpdatedEvent {
403 agent_id: agent_id.to_string(),
404 parent_block_id: parent_block_id.to_string(),
405 });
406 }
407
408 pub(super) fn broadcast_dispatch_updated(&self, info: &AgentDispatch) {
409 self.event_bus.broadcast_typed::<crate::backend::mps_events::DispatchUpdated>(&super::events::DispatchUpdatedEvent {
410 dispatch_id: info.dispatch_id.to_string(),
411 kind: info.kind.clone(),
412 parent_agent: info.parent_agent.to_string(),
413 parent_block_id: info.parent_block_id.to_string(),
414 session_id: info.session_id.to_string(),
415 member_count: info.member_count,
416 members_done: info.members_done,
417 status: info.status.clone(),
418 dispatch_name: info.dispatch_name.clone(),
419 });
420 }
421}
422
423#[cfg(test)]
424#[path = "jsonl_change_tests.rs"]
425mod change_tests;