arabica-cli 0.13.1

Arabica: a terminal coding agent with a fullscreen TUI, ACP support for Zed, and one-shot runs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
//! Translates Structure's canonical Events into ACP `session/update`
//! notifications, live, as they occur.
//!
//! [`AcpObserver`] is installed as the [`SessionEventObserver`] for exactly
//! one `dispatch` call (one `session/prompt`), so every Event it ever sees
//! belongs to that one call: no `run_id` bookkeeping is needed to tell one
//! prompt's Events apart from another's. It is handed *every* Event,
//! including the internal ones Structure never puts on an ordinary client
//! transport (`docs/protocol.md` ยง1) -- that boundary is about the generic
//! event stream, not this mapping, and `model.response.item` (internal) is
//! exactly where the assistant's text and reasoning live.

use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use agent_client_protocol::schema::v1::{
    ContentBlock, ContentChunk, Diff, ImageContent, Plan, PlanEntry, PlanEntryPriority,
    PlanEntryStatus, SessionId as AcpSessionId, SessionNotification, SessionUpdate, ToolCall,
    ToolCallContent, ToolCallId, ToolCallLocation, ToolCallStatus, ToolCallUpdate,
    ToolCallUpdateFields, ToolKind,
};
use agent_client_protocol::{Client, ConnectionTo};
use arabica_model::{RuntimeItem, RuntimeRole};
use arabica_protocol::{Event, EventEnvelope};
use arabica_provider::{ModelProgress, ModelProgressSink};
use arabica_session::{EventVisibility, SessionEventObserver};
use serde_json::Value;

/// Forwards one `dispatch` call's Events to the ACP client as live
/// `session/update` notifications.
pub struct AcpObserver {
    connection: ConnectionTo<Client>,
    session_id: AcpSessionId,
    workspace_root: PathBuf,
    streamed: Mutex<StreamedContent>,
    open_calls: Mutex<OpenToolCalls>,
}

#[derive(Default)]
struct StreamedContent {
    message: String,
    reasoning: String,
}

impl AcpObserver {
    pub fn new(
        connection: ConnectionTo<Client>,
        session_id: AcpSessionId,
        workspace_root: PathBuf,
    ) -> Self {
        Self {
            connection,
            session_id,
            workspace_root,
            streamed: Mutex::new(StreamedContent::default()),
            open_calls: Mutex::new(OpenToolCalls::default()),
        }
    }

    pub fn progress_sink(self: &Arc<Self>) -> ModelProgressSink {
        let observer = Arc::clone(self);
        ModelProgressSink::new(move |progress| {
            let update = match progress {
                ModelProgress::Start => {
                    *observer
                        .streamed
                        .lock()
                        .expect("stream state lock poisoned") = StreamedContent::default();
                    return;
                }
                ModelProgress::Message(text) => {
                    observer
                        .streamed
                        .lock()
                        .expect("stream state lock poisoned")
                        .message
                        .push_str(&text);
                    SessionUpdate::AgentMessageChunk(ContentChunk::new(ContentBlock::from(text)))
                }
                ModelProgress::Reasoning(text) => {
                    observer
                        .streamed
                        .lock()
                        .expect("stream state lock poisoned")
                        .reasoning
                        .push_str(&text);
                    SessionUpdate::AgentThoughtChunk(ContentChunk::new(ContentBlock::from(text)))
                }
            };
            observer.send(update);
        })
    }

    fn send(&self, update: SessionUpdate) {
        if let Err(error) = self
            .connection
            .send_notification(SessionNotification::new(self.session_id.clone(), update))
        {
            eprintln!("structure acp: dropped a session/update: {error}");
        }
    }
}

impl SessionEventObserver for AcpObserver {
    fn observe(&self, envelope: &EventEnvelope, _visibility: EventVisibility) {
        let mut updates = updates_for(&envelope.event, &envelope.run_id, &self.workspace_root);
        updates.extend(
            self.open_calls
                .lock()
                .expect("open tool calls lock poisoned")
                .track(&envelope.event, &envelope.run_id),
        );
        if let Event::ModelResponseItem { item, .. } = &envelope.event {
            let streamed = self.streamed.lock().expect("stream state lock poisoned");
            let already_sent = match item {
                RuntimeItem::Message(message) if message.role == RuntimeRole::Assistant => {
                    Some(streamed.message.as_str())
                }
                RuntimeItem::Reasoning(_) => Some(streamed.reasoning.as_str()),
                _ => None,
            };
            if let Some(already_sent) = already_sent
                && !already_sent.is_empty()
                && updates.len() == 1
            {
                match &mut updates[0] {
                    SessionUpdate::AgentMessageChunk(chunk)
                    | SessionUpdate::AgentThoughtChunk(chunk) => {
                        if let ContentBlock::Text(text) = &mut chunk.content
                            && let Some(rest) = text.text.strip_prefix(already_sent)
                        {
                            text.text = rest.to_owned();
                            if text.text.is_empty() {
                                updates.clear();
                            }
                        }
                    }
                    _ => {}
                }
            }
        }
        for update in updates {
            self.send(update);
        }
    }
}

/// The ACP tool call id for one Structure call, stable across every update
/// for that call within this run: `run_id` and `call_id` alone are already
/// unique within one run, since Structure's own tool-loop guard assigns
/// `call_id` per call, so no extra counter is needed. `pub(super)`: also used
/// by `permission.rs` so the permission dialog names the same tool call the
/// observer already announced.
pub(super) fn acp_tool_call_id(
    run_id: &Option<arabica_protocol::RunId>,
    call_id: &str,
) -> ToolCallId {
    match run_id {
        Some(run_id) => ToolCallId::new(format!("{run_id}:{call_id}")),
        None => ToolCallId::new(call_id.to_owned()),
    }
}

pub fn tool_kind(name: &str) -> ToolKind {
    match name {
        "read_file" | "list_dir" => ToolKind::Read,
        "grep" | "find_files" => ToolKind::Search,
        "write_file" | "edit_files" => ToolKind::Edit,
        "delete_file" => ToolKind::Delete,
        "shell" => ToolKind::Execute,
        _ => ToolKind::Other,
    }
}

pub fn tool_call_title(name: &str, arguments: &Value) -> String {
    let path = arguments.get("path").and_then(Value::as_str);
    match name {
        "read_file" => path.map_or_else(|| "Read file".to_owned(), |path| format!("Read {path}")),
        "list_dir" => path.map_or_else(
            || "List directory".to_owned(),
            |path| format!("List {path}"),
        ),
        "write_file" => {
            path.map_or_else(|| "Write file".to_owned(), |path| format!("Write {path}"))
        }
        "delete_file" => {
            path.map_or_else(|| "Delete file".to_owned(), |path| format!("Delete {path}"))
        }
        "edit_files" => {
            let count = arguments
                .get("edits")
                .and_then(Value::as_array)
                .map_or(0, Vec::len);
            match count {
                1 => "Edit 1 file".to_owned(),
                count => format!("Edit {count} files"),
            }
        }
        "grep" => arguments
            .get("pattern")
            .and_then(Value::as_str)
            .map_or_else(
                || "Search".to_owned(),
                |pattern| format!("Search for {pattern:?}"),
            ),
        "find_files" => arguments.get("glob").and_then(Value::as_str).map_or_else(
            || "Find files".to_owned(),
            |glob| format!("Find files matching {glob:?}"),
        ),
        "shell" => arguments
            .get("command")
            .and_then(Value::as_str)
            .map_or_else(
                || "Run command".to_owned(),
                |command| format!("Run `{command}`"),
            ),
        other => other.to_owned(),
    }
}

fn resolve_path(workspace_root: &Path, arguments: &Value) -> Option<PathBuf> {
    arguments
        .get("path")
        .and_then(Value::as_str)
        .map(|path| workspace_root.join(path))
}

fn tool_call_locations(workspace_root: &Path, arguments: &Value) -> Vec<ToolCallLocation> {
    resolve_path(workspace_root, arguments)
        .map(|path| vec![ToolCallLocation::new(path)])
        .unwrap_or_default()
}

/// Best-effort diff content for the two edit tools, built from the call's
/// own arguments rather than reading the file. For `write_file`, the tool's
/// own contract is "replace with this complete content", so a diff with no
/// `old_text` is accurate regardless of what was there before. For
/// `edit_files`, only the matched `old_string`/`new_string` pair is known --
/// not the whole file -- so the diff covers exactly that changed span, not
/// full before/after file contents. `pub(super)`: `permission.rs` shows the
/// same diff in the permission dialog as the observer shows in the
/// `tool_call` announcement.
pub(super) fn diff_content(
    workspace_root: &Path,
    name: &str,
    arguments: &Value,
) -> Vec<ToolCallContent> {
    match name {
        "write_file" => {
            let Some(path) = resolve_path(workspace_root, arguments) else {
                return Vec::new();
            };
            let Some(content) = arguments.get("content").and_then(Value::as_str) else {
                return Vec::new();
            };
            vec![ToolCallContent::Diff(Diff::new(path, content))]
        }
        "edit_files" => arguments
            .get("edits")
            .and_then(Value::as_array)
            .into_iter()
            .flatten()
            .filter_map(|edit| {
                let path = workspace_root.join(edit.get("path")?.as_str()?);
                let old_string = edit.get("old_string")?.as_str()?;
                let new_string = edit.get("new_string")?.as_str()?;
                Some(ToolCallContent::Diff(
                    Diff::new(path, new_string).old_text(old_string),
                ))
            })
            .collect(),
        _ => Vec::new(),
    }
}

fn message_chunks(content: &[arabica_model::ContentBlock]) -> Vec<ContentBlock> {
    content
        .iter()
        .filter_map(|block| match block {
            arabica_model::ContentBlock::Text { text } if !text.is_empty() => {
                Some(ContentBlock::from(text.as_str()))
            }
            _ => None,
        })
        .collect()
}

/// Replay includes user messages that clients already display locally during
/// live prompts. Keep those echoes out of the live observer's update stream.
pub(super) fn replay_updates_for(
    event: &Event,
    run_id: &Option<arabica_protocol::RunId>,
    workspace_root: &Path,
) -> Vec<SessionUpdate> {
    if let Event::MessageAccepted { content, images } = event {
        // Text first, then each image as its own chunk, matching the order
        // the desktop composer sends them in.
        let text = (!content.is_empty() || images.is_empty())
            .then(|| ContentBlock::from(content.as_str()));
        return text
            .into_iter()
            .chain(images.iter().map(|image| {
                ContentBlock::Image(ImageContent::new(
                    image.data_base64.clone(),
                    image.media_type.clone(),
                ))
            }))
            .map(|block| SessionUpdate::UserMessageChunk(ContentChunk::new(block)))
            .collect();
    }
    updates_for(event, run_id, workspace_root)
}

/// Map runtime events to live `session/update` notifications.
pub(super) fn updates_for(
    event: &Event,
    run_id: &Option<arabica_protocol::RunId>,
    workspace_root: &Path,
) -> Vec<SessionUpdate> {
    match event {
        Event::ModelResponseItem { item, .. } => match item {
            RuntimeItem::Message(message) if message.role == RuntimeRole::Assistant => {
                message_chunks(&message.content)
                    .into_iter()
                    .map(|block| {
                        let mut chunk = ContentChunk::new(block);
                        if let Some(id) = &message.id {
                            chunk = chunk.message_id(id.as_str());
                        }
                        SessionUpdate::AgentMessageChunk(chunk)
                    })
                    .collect()
            }
            RuntimeItem::Reasoning(reasoning) if !reasoning.summary.is_empty() => {
                let mut chunk = ContentChunk::new(ContentBlock::from(reasoning.summary.join("\n\n")));
                if let Some(id) = &reasoning.id {
                    chunk = chunk.message_id(id.as_str());
                }
                vec![SessionUpdate::AgentThoughtChunk(chunk)]
            }
            // Tool calls and their results also arrive as their own
            // dedicated `tool.call.*` Events below, which carry the
            // canonical call_id/name/result; reporting them again from the
            // raw model-response item would double the client's view of the
            // same call.
            RuntimeItem::Message(_) | RuntimeItem::Reasoning(_) | RuntimeItem::ToolCall(_)
            | RuntimeItem::ToolResult(_) => Vec::new(),
        },
        Event::ToolCallRequested {
            call_id,
            name,
            arguments,
            ..
        } => {
            let mut call = ToolCall::new(acp_tool_call_id(run_id, call_id), tool_call_title(name, arguments))
                .name(name.clone())
                .kind(tool_kind(name))
                .status(ToolCallStatus::Pending)
                .raw_input(arguments.clone())
                .locations(tool_call_locations(workspace_root, arguments));
            let diff = diff_content(workspace_root, name, arguments);
            if !diff.is_empty() {
                call = call.content(diff);
            }
            vec![SessionUpdate::ToolCall(call)]
        }
        // Either signal means the call cleared its gate and is now actually
        // running: a call with no permission gate at all only ever produces
        // `classified`, and a gated call may produce both, in which case the
        // second, identical `in_progress` update is a harmless duplicate.
        Event::ToolCallClassified { call_id, .. } => vec![in_progress(run_id, call_id)],
        Event::ToolCallPermissionResolved {
            call_id,
            outcome: arabica_protocol::ToolPermissionOutcome::Allowed,
            ..
        } => vec![in_progress(run_id, call_id)],
        Event::ToolCallCompleted {
            call_id,
            result,
            is_error,
            ..
        } => {
            let status = if *is_error {
                ToolCallStatus::Failed
            } else {
                ToolCallStatus::Completed
            };
            vec![SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
                acp_tool_call_id(run_id, call_id),
                ToolCallUpdateFields::new()
                    .status(status)
                    .content(vec![ToolCallContent::from(result.as_str())]),
            ))]
        }
        Event::PlanUpdated { entries, .. } => vec![SessionUpdate::Plan(Plan::new(
            entries
                .iter()
                .map(|entry| {
                    let status = match entry.status {
                        arabica_protocol::PlanEntryStatus::Pending => PlanEntryStatus::Pending,
                        arabica_protocol::PlanEntryStatus::InProgress => PlanEntryStatus::InProgress,
                        arabica_protocol::PlanEntryStatus::Completed => PlanEntryStatus::Completed,
                    };
                    PlanEntry::new(entry.content.clone(), PlanEntryPriority::Medium, status)
                })
                .collect(),
        ))],
        // A denied or cancelled decision is always followed by its own
        // `tool.call.completed{is_error: true}` (the permission gate and
        // cooperative cancellation both guarantee it), which the arm above
        // already turns into a `failed` update, so no separate update is
        // needed for the resolution itself.
        Event::ToolCallPermissionResolved { .. }
        // A person is asked through the separate `session/request_permission`
        // request (`permission.rs`), not a session/update.
        | Event::ToolCallPermissionRequested { .. }
        | Event::SessionCreated { .. }
        | Event::SessionForked { .. }
        | Event::SessionResumed
        | Event::SessionSuspended
        | Event::SessionClosed
        | Event::RunScheduled
        | Event::RunStarted
        | Event::MessageAccepted { .. }
        | Event::ContextRunResolved { .. }
        | Event::ContextRequestExposed { .. }
        | Event::ContextItemUnfolded { .. }
        | Event::ContextCallStarted { .. }
        | Event::ContextCallRejected { .. }
        | Event::ModelRequestPrepared { .. }
        | Event::ModelRouteSelected { .. }
        | Event::ModelRouteExplained { .. }
        | Event::ToolExecutionObserved { .. }
        | Event::ModelCallObserved { .. }
        | Event::ModelResponseCompleted { .. }
        | Event::ModelResponseRejected { .. }
        | Event::ModelResponseNormalized { .. }
        | Event::ToolCallReused { .. }
        | Event::ToolCallLoopBlocked { .. }
        | Event::AgentProgressAdvisory { .. }
        | Event::PlanDelegationObserved { .. }
        | Event::AgentLoopTerminated { .. }
        | Event::TerminalControlTransition { .. }
        | Event::CommandOutput { .. }
        | Event::RunCompleted { .. }
        | Event::RunFailed { .. }
        | Event::RunCancelled
        | Event::ContextRead { .. }
        | Event::ContextSearchResult { .. }
        | Event::ContextUpdated { .. }
        | Event::ContextDeleted { .. }
        | Event::ContextDisclosureSet { .. }
        | Event::Error { .. } => Vec::new(),
    }
}

/// Tool calls a client has seen requested but not completed. When a run ends
/// with calls still open, their outcome is unknown: each is reported as
/// failed with that explanation, so no call stays in progress forever.
#[derive(Default)]
pub(super) struct OpenToolCalls(Vec<(Option<arabica_protocol::RunId>, String)>);

impl OpenToolCalls {
    pub(super) fn track(
        &mut self,
        event: &Event,
        run_id: &Option<arabica_protocol::RunId>,
    ) -> Vec<SessionUpdate> {
        let reason = match event {
            Event::ToolCallRequested { call_id, .. } => {
                self.0.push((run_id.clone(), call_id.clone()));
                return Vec::new();
            }
            Event::ToolCallCompleted { call_id, .. } => {
                self.0
                    .retain(|(open_run, open_call)| open_run != run_id || open_call != call_id);
                return Vec::new();
            }
            Event::RunFailed { .. } | Event::RunCompleted { .. } => {
                "The run ended before this tool call reported a result; its outcome is unknown."
            }
            Event::RunCancelled => {
                "The run was cancelled before this tool call reported a result; it may still have taken effect."
            }
            _ => return Vec::new(),
        };
        let (ended, open): (Vec<_>, Vec<_>) = std::mem::take(&mut self.0)
            .into_iter()
            .partition(|(open_run, _)| open_run == run_id);
        self.0 = open;
        ended
            .into_iter()
            .map(|(_, call_id)| {
                SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
                    acp_tool_call_id(run_id, &call_id),
                    ToolCallUpdateFields::new()
                        .status(ToolCallStatus::Failed)
                        .content(vec![ToolCallContent::from(reason)]),
                ))
            })
            .collect()
    }
}

fn in_progress(run_id: &Option<arabica_protocol::RunId>, call_id: &str) -> SessionUpdate {
    SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
        acp_tool_call_id(run_id, call_id),
        ToolCallUpdateFields::new().status(ToolCallStatus::InProgress),
    ))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn accepted_images_are_replayed_after_their_text() {
        let image = arabica_model::ImageInput {
            media_type: "image/png".to_owned(),
            data_base64: "aGVsbG8=".to_owned(),
        };
        let event = Event::MessageAccepted {
            content: "describe".to_owned(),
            images: vec![image.clone()],
        };
        let updates = replay_updates_for(&event, &None, Path::new("/workspace"));
        let blocks: Vec<_> = updates
            .iter()
            .map(|update| match update {
                SessionUpdate::UserMessageChunk(chunk) => &chunk.content,
                other => panic!("expected user chunks, got {other:?}"),
            })
            .collect();
        assert!(matches!(blocks[0], ContentBlock::Text(text) if text.text == "describe"));
        assert!(matches!(
            blocks[1],
            ContentBlock::Image(img) if img.data == image.data_base64 && img.mime_type == image.media_type
        ));

        // An image-only prompt replays no empty text chunk.
        let image_only = Event::MessageAccepted {
            content: String::new(),
            images: vec![image],
        };
        let updates = replay_updates_for(&image_only, &None, Path::new("/workspace"));
        assert_eq!(updates.len(), 1);
    }

    #[test]
    fn accepted_messages_are_replayed_without_echoing_live_prompts() {
        let content = "First line\n\nSecond line: cafรฉ โ˜•";
        let event = Event::MessageAccepted {
            content: content.to_owned(),
            images: Vec::new(),
        };
        let updates = replay_updates_for(&event, &None, Path::new("/workspace"));
        assert_eq!(updates.len(), 1);
        let SessionUpdate::UserMessageChunk(chunk) = &updates[0] else {
            panic!("expected a user message chunk");
        };
        let ContentBlock::Text(text) = &chunk.content else {
            panic!("expected text content");
        };
        assert_eq!(text.text, content);
        assert!(updates_for(&event, &None, Path::new("/workspace")).is_empty());
    }

    #[test]
    fn calls_left_open_when_a_run_ends_are_reported_failed() {
        let run = Some(arabica_protocol::RunId::new("run-1"));
        let other = Some(arabica_protocol::RunId::new("run-2"));
        let requested = |call_id: &str| Event::ToolCallRequested {
            call_id: call_id.to_owned(),
            name: "mcp__agentnexus__echo".to_owned(),
            arguments: serde_json::json!({}),
            provider_state: None,
        };
        let mut open = OpenToolCalls::default();
        assert!(open.track(&requested("done"), &run).is_empty());
        assert!(open.track(&requested("dangling"), &run).is_empty());
        assert!(open.track(&requested("elsewhere"), &other).is_empty());
        let completed = Event::ToolCallCompleted {
            call_id: "done".to_owned(),
            name: "mcp__agentnexus__echo".to_owned(),
            result: "ok".to_owned(),
            is_error: false,
        };
        assert!(open.track(&completed, &run).is_empty());
        let settled = open.track(
            &Event::RunFailed {
                message: "outcome unknown".to_owned(),
            },
            &run,
        );
        assert_eq!(settled.len(), 1);
        let SessionUpdate::ToolCallUpdate(update) = &settled[0] else {
            panic!("expected a tool call update, got {settled:?}");
        };
        assert_eq!(update.tool_call_id, acp_tool_call_id(&run, "dangling"));
        assert_eq!(update.fields.status, Some(ToolCallStatus::Failed));
        // The other run's call is untouched until that run ends.
        let cancelled = open.track(&Event::RunCancelled, &other);
        assert_eq!(cancelled.len(), 1);
        assert!(open.track(&Event::RunCancelled, &run).is_empty());
    }

    #[test]
    fn tool_kind_matches_the_plans_categories() {
        assert_eq!(tool_kind("read_file"), ToolKind::Read);
        assert_eq!(tool_kind("list_dir"), ToolKind::Read);
        assert_eq!(tool_kind("grep"), ToolKind::Search);
        assert_eq!(tool_kind("find_files"), ToolKind::Search);
        assert_eq!(tool_kind("write_file"), ToolKind::Edit);
        assert_eq!(tool_kind("edit_files"), ToolKind::Edit);
        assert_eq!(tool_kind("delete_file"), ToolKind::Delete);
        assert_eq!(tool_kind("shell"), ToolKind::Execute);
        assert_eq!(tool_kind("unknown_future_tool"), ToolKind::Other);
    }

    #[test]
    fn a_tool_call_requested_event_becomes_a_pending_tool_call() {
        let run_id = Some(arabica_protocol::RunId::new("run-1"));
        let updates = updates_for(
            &Event::ToolCallRequested {
                call_id: "call-1".to_owned(),
                name: "read_file".to_owned(),
                arguments: serde_json::json!({"path": "src/main.rs"}),
                provider_state: None,
            },
            &run_id,
            Path::new("/workspace"),
        );
        assert_eq!(updates.len(), 1);
        let SessionUpdate::ToolCall(call) = &updates[0] else {
            panic!("expected a ToolCall update");
        };
        assert_eq!(call.tool_call_id, ToolCallId::new("run-1:call-1"));
        assert_eq!(call.title, "Read src/main.rs");
        assert_eq!(call.kind, ToolKind::Read);
        assert_eq!(call.status, ToolCallStatus::Pending);
        assert_eq!(
            call.locations,
            vec![ToolCallLocation::new("/workspace/src/main.rs")]
        );
    }

    #[test]
    fn a_write_file_request_carries_a_diff_with_no_old_text() {
        let updates = updates_for(
            &Event::ToolCallRequested {
                call_id: "call-1".to_owned(),
                name: "write_file".to_owned(),
                arguments: serde_json::json!({"path": "a.txt", "content": "hello"}),
                provider_state: None,
            },
            &Some(arabica_protocol::RunId::new("run-1")),
            Path::new("/ws"),
        );
        let SessionUpdate::ToolCall(call) = &updates[0] else {
            panic!("expected a ToolCall update");
        };
        assert_eq!(call.content.len(), 1);
        let ToolCallContent::Diff(diff) = &call.content[0] else {
            panic!("expected a Diff content block");
        };
        assert_eq!(diff.path, PathBuf::from("/ws/a.txt"));
        assert_eq!(diff.old_text, None);
        assert_eq!(diff.new_text, "hello");
    }

    #[test]
    fn an_edit_files_request_carries_one_diff_per_edit() {
        let updates = updates_for(
            &Event::ToolCallRequested {
                call_id: "call-1".to_owned(),
                name: "edit_files".to_owned(),
                arguments: serde_json::json!({"edits": [
                    {"path": "a.txt", "old_string": "old", "new_string": "new"},
                    {"path": "b.txt", "old_string": "x", "new_string": "y"},
                ]}),
                provider_state: None,
            },
            &Some(arabica_protocol::RunId::new("run-1")),
            Path::new("/ws"),
        );
        let SessionUpdate::ToolCall(call) = &updates[0] else {
            panic!("expected a ToolCall update");
        };
        assert_eq!(call.content.len(), 2);
    }

    #[test]
    fn classified_and_allowed_both_report_in_progress() {
        let run_id = Some(arabica_protocol::RunId::new("run-1"));
        for event in [
            Event::ToolCallClassified {
                call_id: "call-1".to_owned(),
                kind: arabica_protocol::ToolInteractionKind::Inspection,
            },
            Event::ToolCallPermissionResolved {
                call_id: "call-1".to_owned(),
                outcome: arabica_protocol::ToolPermissionOutcome::Allowed,
                scope: arabica_protocol::ToolPermissionScope::Once,
                source: arabica_protocol::ToolPermissionSource::Policy,
            },
        ] {
            let updates = updates_for(&event, &run_id, Path::new("/ws"));
            assert_eq!(updates.len(), 1);
            let SessionUpdate::ToolCallUpdate(update) = &updates[0] else {
                panic!("expected a ToolCallUpdate");
            };
            assert_eq!(update.tool_call_id, ToolCallId::new("run-1:call-1"));
            assert_eq!(update.fields.status, Some(ToolCallStatus::InProgress));
        }
    }

    #[test]
    fn a_denied_permission_resolution_alone_produces_no_update() {
        // The completion event that always follows carries the failure.
        let updates = updates_for(
            &Event::ToolCallPermissionResolved {
                call_id: "call-1".to_owned(),
                outcome: arabica_protocol::ToolPermissionOutcome::Denied,
                scope: arabica_protocol::ToolPermissionScope::Once,
                source: arabica_protocol::ToolPermissionSource::Policy,
            },
            &Some(arabica_protocol::RunId::new("run-1")),
            Path::new("/ws"),
        );
        assert!(updates.is_empty());
    }

    #[test]
    fn a_completed_call_reports_success_and_an_errored_one_reports_failure() {
        let run_id = Some(arabica_protocol::RunId::new("run-1"));
        let ok = updates_for(
            &Event::ToolCallCompleted {
                call_id: "call-1".to_owned(),
                name: "read_file".to_owned(),
                result: "file contents".to_owned(),
                is_error: false,
            },
            &run_id,
            Path::new("/ws"),
        );
        let SessionUpdate::ToolCallUpdate(update) = &ok[0] else {
            panic!("expected a ToolCallUpdate");
        };
        assert_eq!(update.fields.status, Some(ToolCallStatus::Completed));

        let failed = updates_for(
            &Event::ToolCallCompleted {
                call_id: "call-2".to_owned(),
                name: "shell".to_owned(),
                result: "permission denied".to_owned(),
                is_error: true,
            },
            &run_id,
            Path::new("/ws"),
        );
        let SessionUpdate::ToolCallUpdate(update) = &failed[0] else {
            panic!("expected a ToolCallUpdate");
        };
        assert_eq!(update.fields.status, Some(ToolCallStatus::Failed));
    }

    #[test]
    fn assistant_text_becomes_an_agent_message_chunk_but_a_tool_result_item_is_ignored() {
        let assistant_message = updates_for(
            &Event::ModelResponseItem {
                model_step: 1,
                item_index: 0,
                item: RuntimeItem::Message(arabica_model::MessageItem {
                    id: Some("msg-1".to_owned()),
                    role: RuntimeRole::Assistant,
                    content: vec![arabica_model::ContentBlock::Text {
                        text: "hello".to_owned(),
                    }],
                    provider_state: None,
                }),
            },
            &Some(arabica_protocol::RunId::new("run-1")),
            Path::new("/ws"),
        );
        assert_eq!(assistant_message.len(), 1);
        assert!(matches!(
            assistant_message[0],
            SessionUpdate::AgentMessageChunk(_)
        ));

        let tool_result_item = updates_for(
            &Event::ModelResponseItem {
                model_step: 1,
                item_index: 1,
                item: RuntimeItem::ToolResult(arabica_model::ToolResultItem {
                    id: None,
                    call_id: "call-1".to_owned(),
                    name: Some("read_file".to_owned()),
                    content: vec![arabica_model::ContentBlock::Text {
                        text: "dup".to_owned(),
                    }],
                    is_error: false,
                }),
            },
            &Some(arabica_protocol::RunId::new("run-1")),
            Path::new("/ws"),
        );
        assert!(tool_result_item.is_empty());
    }
}