1use std::collections::{BTreeMap, BTreeSet, HashMap};
5
6use rig_core::message::{AssistantContent, Message, UserContent};
7use serde::Serialize;
8
9use crate::{
10 acp::{
11 PermissionOption, PermissionRecord, PermissionStatus, PlanStep, ToolDiff, ToolLocation,
12 ToolStatus,
13 },
14 agent::{
15 error::Code,
16 session::{Answer, Conversation, DeliveryKind, DeliveryState, Event, Kind},
17 },
18 runs, store,
19 types::{DeliveryBlock, EvalId, RequestStatus, RunId},
20};
21
22use super::{
23 Outcome,
24 details::{self, ResultView, ToolKind},
25};
26
27#[derive(Debug, Clone, Serialize)]
28#[serde(
29 tag = "kind",
30 rename_all = "camelCase",
31 rename_all_fields = "camelCase"
32)]
33pub enum Block {
34 Text {
35 text: String,
36 },
37 Thought {
38 text: String,
39 },
40 Tool {
41 #[serde(default, skip_serializing_if = "Option::is_none")]
42 call_id: Option<String>,
43 name: String,
44 #[serde(default, skip_serializing_if = "Option::is_none")]
45 title: Option<String>,
46 arguments: String,
47 result: Option<ToolResult>,
48 tool_kind: ToolKind,
49 status: ToolStatus,
50 summary: String,
51 #[serde(default, skip_serializing_if = "Vec::is_empty")]
52 locations: Vec<ToolLocation>,
53 #[serde(default, skip_serializing_if = "Option::is_none")]
54 diff: Option<ToolDiff>,
55 },
56 Plan {
57 steps: Vec<PlanStep>,
58 },
59 Permission {
60 permission_id: String,
61 title: String,
62 tool_kind: ToolKind,
63 summary: String,
64 #[serde(default, skip_serializing_if = "Option::is_none")]
65 detail: Option<String>,
66 options: Vec<PermissionOption>,
67 status: PermissionStatus,
68 #[serde(default, skip_serializing_if = "Option::is_none")]
69 selected_option_id: Option<String>,
70 },
71 Notice {
72 text: String,
73 },
74 Handoff {
75 from: String,
76 to: String,
77 summary: String,
78 },
79 Run {
80 card: RunCard,
81 },
82}
83
84#[derive(Debug, Clone, Serialize)]
86#[serde(rename_all = "camelCase")]
87pub struct ToolResult {
88 pub output: String,
89 pub failed: Option<bool>,
90 pub exit_code: Option<i32>,
91 pub omitted_lines: usize,
92 pub output_truncated: bool,
93}
94
95#[derive(Debug, Clone, Serialize)]
96#[serde(rename_all = "camelCase")]
97pub struct RunCard {
98 pub id: RunId,
99 pub state: Option<runs::State>,
100 pub failed: Vec<EvalId>,
101 pub waiting: Vec<EvalId>,
102}
103
104#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
105#[serde(tag = "kind", rename_all = "camelCase")]
106pub enum TurnState {
107 Running,
108 WaitingPermission,
110 Completed,
111 Stopped,
112 Interrupted,
113 Failed {
114 message: String,
115 },
116}
117
118#[derive(Debug, Clone, Serialize)]
119#[serde(rename_all = "camelCase")]
120pub struct Turn {
121 pub user: String,
122 pub blocks: Vec<Block>,
123 pub state: TurnState,
124}
125
126struct Fold {
127 turn: Turn,
128 delivered: BTreeSet<usize>,
129 delivery_blocks: BTreeMap<(usize, usize, DeliveryKind, DeliveryBlock), usize>,
130 calls: HashMap<String, usize>,
131 permissions: HashMap<String, usize>,
132 plan_block: Option<usize>,
133}
134
135impl Fold {
136 fn new(user: String) -> Self {
137 Self {
138 turn: Turn {
139 user,
140 blocks: Vec::new(),
141 state: TurnState::Interrupted,
142 },
143 delivered: BTreeSet::new(),
144 delivery_blocks: BTreeMap::new(),
145 calls: HashMap::new(),
146 permissions: HashMap::new(),
147 plan_block: None,
148 }
149 }
150
151 fn event(&mut self, event: &Event) {
152 let blocks = &mut self.turn.blocks;
153 match &event.kind {
154 Kind::Delivery(delivery) if !delivery.block.is_attempt() => {
155 let key = (
156 delivery.turn,
157 delivery.attempt,
158 delivery.kind,
159 delivery.block.clone(),
160 );
161 let index = *self.delivery_blocks.entry(key).or_insert_with(|| {
162 let index = blocks.len();
163 match delivery.kind {
164 DeliveryKind::Text => blocks.push(Block::Text {
165 text: String::new(),
166 }),
167 DeliveryKind::Summary => blocks.push(Block::Thought {
168 text: String::new(),
169 }),
170 }
171 index
172 });
173 match &mut blocks[index] {
174 Block::Text { text } | Block::Thought { text } => {
175 if delivery.state == DeliveryState::Delta {
176 text.push_str(&delivery.text);
177 } else {
178 text.clone_from(&delivery.text);
179 }
180 }
181 _ => unreachable!("recorded delivery block"),
182 }
183 if delivery.kind == DeliveryKind::Text {
184 self.delivered.insert(delivery.turn);
185 }
186 }
187 Kind::AcpToolCall(call) => {
188 let index = blocks.len();
189 self.calls.insert(call.call_id.clone(), index);
190 let result = call.output.as_ref().map(|output| ToolResult {
191 output: output.clone(),
192 failed: Some(call.status == ToolStatus::Failed),
193 exit_code: None,
194 omitted_lines: 0,
195 output_truncated: call.output_truncated,
196 });
197 blocks.push(Block::Tool {
198 call_id: Some(call.call_id.clone()),
199 name: call.name.clone(),
200 title: (!call.title.is_empty()).then(|| call.title.clone()),
201 arguments: call.arguments.clone(),
202 result,
203 tool_kind: call.tool_kind,
204 status: call.status,
205 summary: call.summary.clone(),
206 locations: call.locations.clone(),
207 diff: call.diff.clone(),
208 });
209 }
210 Kind::AcpToolUpdate(update) => {
211 let Some(Block::Tool {
212 title,
213 tool_kind,
214 status,
215 summary,
216 locations,
217 diff,
218 result,
219 ..
220 }) = self
221 .calls
222 .get(&update.call_id)
223 .and_then(|index| blocks.get_mut(*index))
224 else {
225 return;
226 };
227 if let Some(new_title) = &update.title {
228 *title = Some(new_title.clone());
229 }
230 if let Some(kind) = update.tool_kind {
231 *tool_kind = kind;
232 }
233 if let Some(new_status) = update.status {
234 *status = new_status;
235 }
236 if let Some(new_summary) = &update.summary {
237 *summary = new_summary.clone();
238 }
239 if let Some(new_locations) = &update.locations {
240 *locations = new_locations.clone();
241 }
242 if let Some(new_diff) = &update.diff {
243 *diff = Some(new_diff.clone());
244 }
245 if update.output.is_some() || update.failed.is_some() || update.exit_code.is_some()
246 {
247 let failed = update
248 .failed
249 .or_else(|| Some(*status == ToolStatus::Failed));
250 let existing_output = result
251 .as_ref()
252 .map(|r| r.output.clone())
253 .unwrap_or_default();
254 let output = update.output.clone().unwrap_or(existing_output);
255 *result = Some(ToolResult {
256 output,
257 failed,
258 exit_code: update.exit_code,
259 omitted_lines: 0,
260 output_truncated: update.output_truncated,
261 });
262 }
263 }
264 Kind::AcpPlan(plan) => {
265 if let Some(index) = self.plan_block
266 && let Some(Block::Plan { steps }) = blocks.get_mut(index)
267 {
268 *steps = plan.steps.clone();
269 } else {
270 let index = blocks.len();
271 blocks.push(Block::Plan {
272 steps: plan.steps.clone(),
273 });
274 self.plan_block = Some(index);
275 }
276 }
277 Kind::AcpPermission(perm) => {
278 if let Some(&index) = self.permissions.get(&perm.permission_id)
279 && let Some(Block::Permission {
280 status,
281 selected_option_id,
282 ..
283 }) = blocks.get_mut(index)
284 {
285 *status = perm.status;
286 if perm.selected_option_id.is_some() {
287 *selected_option_id = perm.selected_option_id.clone();
288 }
289 } else {
290 let index = blocks.len();
291 self.permissions.insert(perm.permission_id.clone(), index);
292 blocks.push(Block::Permission {
293 permission_id: perm.permission_id.clone(),
294 title: perm.title.clone(),
295 tool_kind: perm.tool_kind,
296 summary: perm.summary.clone(),
297 detail: perm.detail.clone(),
298 options: perm.options.clone(),
299 status: perm.status,
300 selected_option_id: perm.selected_option_id.clone(),
301 });
302 }
303 }
304 Kind::Notice { text } => {
305 blocks.push(Block::Notice { text: text.clone() });
306 }
307 Kind::Handoff(handoff) => {
308 blocks.push(Block::Handoff {
309 from: handoff.from.clone(),
310 to: handoff.to.clone(),
311 summary: handoff.summary.clone(),
312 });
313 }
314 Kind::Message(message) | Kind::ToolOutcome(message) => match message.message() {
315 Message::Assistant { content, .. } => {
316 for (part_index, part) in content.iter().enumerate() {
317 match part {
318 AssistantContent::Text(text)
319 if !self.delivered.contains(&message.turn) =>
320 {
321 blocks.push(Block::Text {
322 text: text.text.clone(),
323 });
324 }
325 AssistantContent::ToolCall(call) => {
326 let index = blocks.len();
327 let wire_id = call.id.wire().into_owned();
328 self.calls.insert(wire_id.clone(), index);
329 let name = call.function.name.as_str();
330 let tool_kind = ToolKind::for_name(name);
331 let summary = if tool_kind == ToolKind::Read {
332 let (path, pattern) = message.builtin_target_parts(part_index);
333 details::read_summary(name, path, pattern)
334 } else {
335 details::summary(name, &call.function.arguments)
336 };
337 blocks.push(Block::Tool {
338 call_id: Some(wire_id),
339 name: name.to_owned(),
340 title: None,
341 arguments: call.function.arguments.to_string(),
342 result: None,
343 tool_kind,
344 status: ToolStatus::Running,
345 summary,
346 locations: Vec::new(),
347 diff: None,
348 });
349 }
350 _ => {}
351 }
352 }
353 }
354 Message::User { content } => {
355 for (index, result) in content
356 .iter()
357 .filter_map(|part| match part {
358 UserContent::ToolResult(result) => Some(result),
359 _ => None,
360 })
361 .enumerate()
362 {
363 let Some(Block::Tool {
364 result: saved,
365 tool_kind,
366 status,
367 summary,
368 ..
369 }) = self
370 .calls
371 .get(result.call.wire().as_ref())
372 .and_then(|index| blocks.get_mut(*index))
373 else {
374 continue;
375 };
376 let failed = message.is_error.get(index).copied();
377 *status = if failed == Some(true) {
378 ToolStatus::Failed
379 } else {
380 ToolStatus::Completed
381 };
382 if let Some(saved) = saved {
383 saved.failed = failed;
384 continue;
385 }
386 let view = ResultView::new(*tool_kind, result.content.iter());
387 if let Some(code) = view.exit_code {
388 summary.push_str(&format!(" (exit {code})"));
389 }
390 *saved = Some(ToolResult {
391 output: view.output,
392 failed,
393 exit_code: view.exit_code,
394 omitted_lines: view.omitted_lines,
395 output_truncated: view.truncated,
396 });
397 }
398 }
399 Message::System { .. } => {}
400 },
401 Kind::RunReference { run } => blocks.push(Block::Run {
402 card: RunCard {
403 id: run.clone(),
404 state: None,
405 failed: Vec::new(),
406 waiting: Vec::new(),
407 },
408 }),
409 Kind::Answer(answer) => {
410 self.turn.state = match outcome(answer) {
411 Outcome::Completed => {
412 let Answer::Completed(text) = answer else {
413 unreachable!("completed answer")
414 };
415 if !text.is_empty()
416 && !blocks
417 .iter()
418 .any(|block| matches!(block, Block::Text { .. }))
419 {
420 blocks.push(Block::Text { text: text.clone() });
421 }
422 TurnState::Completed
423 }
424 Outcome::Stopped => TurnState::Stopped,
425 Outcome::Failed => {
426 let Answer::Failed { message, .. } = answer else {
427 unreachable!("failed answer")
428 };
429 TurnState::Failed {
430 message: message
431 .clone()
432 .unwrap_or_else(|| "The Chat turn failed.".into()),
433 }
434 }
435 Outcome::Interrupted => TurnState::Interrupted,
436 Outcome::Running => unreachable!("an answer ends the turn"),
437 };
438 }
439 _ => {}
440 }
441 }
442}
443
444pub(super) fn turns(
445 conversation: Option<&Conversation>,
446 running: bool,
447 live_permissions: &[PermissionRecord],
448) -> Vec<Turn> {
449 let mut turns = BTreeMap::new();
450 for event in conversation
451 .iter()
452 .flat_map(|conversation| conversation.events())
453 {
454 let Some(send) = event.send else { continue };
455 if let Kind::Send(start) = &event.kind {
456 turns.insert(send, Fold::new(start.text.clone().unwrap_or_default()));
457 } else if let Some(fold) = turns.get_mut(&send) {
458 fold.event(event);
459 }
460 }
461
462 if let Some((_, last_fold)) = turns.iter_mut().next_back() {
465 for perm in live_permissions {
466 if let Some(&idx) = last_fold.permissions.get(&perm.permission_id)
467 && let Some(Block::Permission {
468 status,
469 selected_option_id,
470 ..
471 }) = last_fold.turn.blocks.get_mut(idx)
472 {
473 *status = perm.status;
474 if perm.selected_option_id.is_some() {
475 *selected_option_id = perm.selected_option_id.clone();
476 }
477 } else if matches!(
478 perm.status,
479 PermissionStatus::Pending
480 | PermissionStatus::Selected
481 | PermissionStatus::Delivering
482 ) {
483 let idx = last_fold.turn.blocks.len();
484 last_fold
485 .permissions
486 .insert(perm.permission_id.clone(), idx);
487 last_fold.turn.blocks.push(Block::Permission {
488 permission_id: perm.permission_id.clone(),
489 title: perm.title.clone(),
490 tool_kind: perm.tool_kind,
491 summary: perm.summary.clone(),
492 detail: perm.detail.clone(),
493 options: perm.options.clone(),
494 status: perm.status,
495 selected_option_id: perm.selected_option_id.clone(),
496 });
497 }
498 }
499 }
500
501 let has_pending_permission = live_permissions
502 .iter()
503 .any(|perm| perm.status == PermissionStatus::Pending);
504 if running
505 && let Some(mut last) = turns.last_entry()
506 && matches!(last.get().turn.state, TurnState::Interrupted)
507 {
508 last.get_mut().turn.state = if has_pending_permission {
509 TurnState::WaitingPermission
510 } else {
511 TurnState::Running
512 };
513 }
514
515 for fold in turns.values_mut() {
517 if !matches!(
518 fold.turn.state,
519 TurnState::Running | TurnState::WaitingPermission
520 ) {
521 for block in &mut fold.turn.blocks {
522 if let Block::Tool { status, .. } = block
523 && matches!(status, ToolStatus::Pending | ToolStatus::Running)
524 {
525 *status = ToolStatus::Cancelled;
526 }
527 }
528 }
529 }
530
531 turns.into_values().map(|fold| fold.turn).collect()
532}
533
534pub(super) async fn update_runs(
537 state: &std::path::Path,
538 worktree: &std::path::Path,
539 session: &crate::types::SessionId,
540 turns: &mut [Turn],
541) {
542 let mut present_runs: BTreeSet<RunId> = turns
543 .iter()
544 .flat_map(|turn| turn.blocks.iter())
545 .filter_map(|block| match block {
546 Block::Run { card } => Some(card.id.clone()),
547 _ => None,
548 })
549 .collect();
550
551 if let Ok(admitted) = store::read_chat_runs(state, worktree, session).await {
552 for (run_id, send) in admitted {
553 if present_runs.contains(&run_id) {
554 continue;
555 }
556 let target_idx = send
557 .and_then(|s| s.checked_sub(1))
558 .filter(|&idx| idx < turns.len())
559 .or_else(|| turns.len().checked_sub(1));
560 if let Some(turn) = target_idx.and_then(|idx| turns.get_mut(idx)) {
561 turn.blocks.push(Block::Run {
562 card: RunCard {
563 id: run_id.clone(),
564 state: None,
565 failed: Vec::new(),
566 waiting: Vec::new(),
567 },
568 });
569 present_runs.insert(run_id);
570 }
571 }
572 }
573
574 let mut cards: BTreeMap<RunId, RunCard> = BTreeMap::new();
575 for card in turns
576 .iter_mut()
577 .flat_map(|turn| turn.blocks.iter_mut())
578 .filter_map(|block| match block {
579 Block::Run { card } => Some(card),
580 _ => None,
581 })
582 {
583 use std::collections::btree_map::Entry;
584 match cards.entry(card.id.clone()) {
585 Entry::Occupied(current) => *card = current.get().clone(),
586 Entry::Vacant(slot) => {
587 if let Ok(view) = store::read_run_snapshot(state, card.id.as_str()).await
588 && matches!(
589 &view.run.origin,
590 Some(runs::Origin::Chat { session_id, .. }) if session_id == session
591 )
592 {
593 *card = run_card(view);
594 }
595 slot.insert(card.clone());
596 }
597 }
598 }
599}
600
601fn run_card(view: store::RunView) -> RunCard {
602 let mut card = RunCard {
603 id: view.run.id.clone(),
604 state: Some(runs::saved_state(&view)),
605 failed: Vec::new(),
606 waiting: Vec::new(),
607 };
608 for request in view.requests {
609 match request.status() {
610 RequestStatus::Red | RequestStatus::Error => card.failed.push(request.eval_id.clone()),
611 status if status.is_human_wait() => card.waiting.push(request.eval_id.clone()),
612 _ => {}
613 }
614 }
615 card
616}
617
618pub(super) fn outcome(answer: &Answer) -> Outcome {
619 match answer {
620 Answer::Completed(_) => Outcome::Completed,
621 Answer::Failed {
622 code: Some(Code::Cancelled),
623 ..
624 } => Outcome::Stopped,
625 Answer::Failed { .. } => Outcome::Failed,
626 Answer::Empty => Outcome::Interrupted,
627 }
628}
629
630pub(super) fn last_outcome(conversation: &Conversation) -> Option<Outcome> {
631 conversation
632 .events()
633 .iter()
634 .rev()
635 .find_map(|event| match &event.kind {
636 Kind::Answer(answer) => Some(outcome(answer)),
637 Kind::Send(_) => Some(Outcome::Interrupted),
638 _ => None,
639 })
640}