-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathui.rs
More file actions
1227 lines (1079 loc) · 44.5 KB
/
ui.rs
File metadata and controls
1227 lines (1079 loc) · 44.5 KB
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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use agent_client_protocol as acp;
use async_trait::async_trait;
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use tokio::sync::{mpsc, oneshot};
use serde_json::{Map as JsonMap, Value as JsonValue};
use crate::acp::types::{fragment_to_content_block, map_tool_kind, map_tool_status};
use crate::ui::{DisplayFragment, UIError, UiEvent, UserInterface};
/// Tracks the last type of content for paragraph breaks after hidden tools
#[derive(Debug, Clone, Copy, PartialEq)]
enum LastContentType {
None,
Text,
Thinking,
}
/// UserInterface implementation that sends session/update notifications via ACP
pub struct ACPUserUI {
session_id: acp::SessionId,
session_update_tx: mpsc::UnboundedSender<(acp::SessionNotification, oneshot::Sender<()>)>,
// Track tool calls for status updates
tool_calls: Arc<Mutex<HashMap<String, ToolCallState>>>,
base_path: Option<PathBuf>,
// Track if we should continue streaming (atomic for lock-free access from sync callbacks)
should_continue: Arc<AtomicBool>,
last_error: Arc<Mutex<Option<String>>>,
// Track last content type for paragraph breaks after hidden tools
last_content_type: Arc<Mutex<LastContentType>>,
// Flag indicating a hidden tool completed and we may need a paragraph break
needs_paragraph_break_after_hidden_tool: Arc<Mutex<bool>>,
}
#[derive(Default, Clone)]
struct ParameterValue {
value: String,
}
impl ParameterValue {
fn append(&mut self, chunk: &str) {
self.value.push_str(chunk);
}
fn replace(&mut self, value: &str) {
self.value.clear();
self.value.push_str(value);
}
}
struct ToolCallState {
id: acp::ToolCallId,
tool_name: Option<String>,
title: Option<String>,
kind: Option<acp::ToolKind>,
status: acp::ToolCallStatus,
parameters: BTreeMap<String, ParameterValue>,
output_stream: Option<String>,
final_output: Option<String>,
status_message: Option<String>,
terminal_id: Option<acp::TerminalId>,
}
impl ToolCallState {
fn new(id: &str) -> Self {
Self {
id: acp::ToolCallId::new(id.to_string()),
tool_name: None,
title: None,
kind: None,
status: acp::ToolCallStatus::Pending,
parameters: BTreeMap::new(),
output_stream: None,
final_output: None,
status_message: None,
terminal_id: None,
}
}
fn set_tool_name(&mut self, name: &str) {
self.tool_name = Some(name.to_string());
self.title.get_or_insert_with(|| name.to_string());
self.kind.get_or_insert_with(|| map_tool_kind(name));
}
fn kind(&self) -> acp::ToolKind {
self.kind.unwrap_or(acp::ToolKind::Other)
}
fn status(&self) -> acp::ToolCallStatus {
self.status
}
fn append_parameter(&mut self, name: &str, value: &str) {
let entry = self.parameters.entry(name.to_string()).or_default();
entry.append(value);
// Update title if we have a template for this tool
if let Some(tool_name) = &self.tool_name {
let tool_name = tool_name.clone(); // Clone to avoid borrow issues
self.update_title_from_template(&tool_name);
}
}
fn replace_parameter(&mut self, name: &str, value: &str) {
let entry = self.parameters.entry(name.to_string()).or_default();
entry.replace(value);
if let Some(tool_name) = &self.tool_name {
let tool_name = tool_name.clone();
self.update_title_from_template(&tool_name);
}
}
fn update_title_from_template(&mut self, tool_name: &str) {
// Convert parameters to HashMap<String, String> for shared title function
let params: std::collections::HashMap<String, String> = self
.parameters
.iter()
.map(|(k, v)| (k.clone(), v.value.clone()))
.collect();
if let Some(new_title) = crate::tools::core::generate_tool_title(tool_name, ¶ms) {
self.title = Some(new_title);
}
}
fn update_status(
&mut self,
status: acp::ToolCallStatus,
message: Option<String>,
output: Option<String>,
) {
self.status = status;
if let Some(message) = message {
if !message.is_empty() {
self.status_message = Some(message);
}
}
if let Some(output) = output {
self.final_output = Some(output);
}
}
fn ensure_completed(&mut self) {
if matches!(
self.status,
acp::ToolCallStatus::Pending | acp::ToolCallStatus::InProgress
) {
self.status = acp::ToolCallStatus::Completed;
}
}
fn append_output_chunk(&mut self, chunk: &str) {
if self.terminal_id.is_some() {
return;
}
if chunk.is_empty() {
return;
}
self.output_stream
.get_or_insert_with(String::new)
.push_str(chunk);
}
fn set_terminal(&mut self, terminal_id: &str) {
if terminal_id.is_empty() {
return;
}
self.terminal_id = Some(acp::TerminalId::new(terminal_id.to_string()));
}
fn raw_input(&self) -> Option<JsonValue> {
if self.parameters.is_empty() {
return None;
}
let mut map = JsonMap::new();
for (key, value) in &self.parameters {
map.insert(key.clone(), parse_parameter_value(&value.value));
}
Some(JsonValue::Object(map))
}
fn output_text(&self) -> Option<String> {
if let Some(final_output) = &self.final_output {
Some(final_output.clone())
} else {
self.output_stream.clone()
}
}
fn raw_output(&self) -> Option<JsonValue> {
self.output_text().map(JsonValue::String)
}
fn diff_content(&self, base_path: Option<&Path>) -> Option<acp::ToolCallContent> {
if !matches!(
self.tool_name.as_deref(),
Some("edit") | Some("write_file") | Some("replace_in_file")
) {
return None;
}
let path = self.parameters.get("path")?.value.trim();
if path.is_empty() {
return None;
}
let new_text = self.parameters.get("new_text")?.value.clone();
let old_text = self.parameters.get("old_text").map(|v| v.value.clone());
let diff = acp::Diff::new(resolve_path(path, base_path), new_text).old_text(old_text);
Some(acp::ToolCallContent::Diff(diff))
}
fn build_content(&self, base_path: Option<&Path>) -> Option<Vec<acp::ToolCallContent>> {
let mut content = Vec::new();
let is_failed = matches!(self.status, acp::ToolCallStatus::Failed);
// Always add terminal content first if present
if let Some(terminal_id) = &self.terminal_id {
content.push(acp::ToolCallContent::Terminal(acp::Terminal::new(
terminal_id.clone(),
)));
}
// For file modification tools (edit, write_file, replace_in_file), use diff content
if let Some(diff_content) = self.diff_content(base_path) {
content.push(diff_content);
} else if self.terminal_id.is_some() && !self.parameters.is_empty() {
// For terminal tools, show parameters (like the command being run)
let mut lines = Vec::new();
for (name, value) in &self.parameters {
lines.push(format!("{name}: {}", value.value));
}
content.push(text_content(lines.join("\n")));
} else {
// For all other tools, put the full output as the primary content
if let Some(output) = self.output_text() {
if !output.is_empty() {
// For spawn_agent, try to render as markdown
if self.tool_name.as_deref() == Some("spawn_agent") {
if let Some(markdown) = render_sub_agent_output_as_markdown(&output) {
content.push(text_content(markdown));
} else {
content.push(text_content(output));
}
} else {
content.push(text_content(output));
}
}
}
}
// Add error messages for failed tools
if is_failed {
if let Some(message) = &self.status_message {
if !message.is_empty() {
// Only add status message if it's different from the output
let should_add_status = self
.output_text()
.map(|output| message.trim() != output.trim())
.unwrap_or(true);
if should_add_status {
content.push(text_content(message.clone()));
}
}
}
}
if content.is_empty() {
None
} else {
Some(content)
}
}
fn build_locations(&self, base_path: Option<&Path>) -> Option<Vec<acp::ToolCallLocation>> {
let path_value = self.parameters.get("path")?.value.trim();
if path_value.is_empty() {
return None;
}
let resolved = resolve_path(path_value, base_path);
let line = self
.parameters
.get("line")
.or_else(|| self.parameters.get("line_number"))
.and_then(|value| value.value.trim().parse::<u32>().ok());
Some(vec![acp::ToolCallLocation::new(resolved).line(line)])
}
fn to_tool_call(&self, base_path: Option<&Path>) -> acp::ToolCall {
let title = self
.title
.clone()
.or_else(|| self.tool_name.clone())
.unwrap_or_default();
acp::ToolCall::new(self.id.clone(), title)
.kind(self.kind())
.status(self.status())
.content(self.build_content(base_path).unwrap_or_default())
.locations(self.build_locations(base_path).unwrap_or_default())
.raw_input(self.raw_input())
.raw_output(self.raw_output())
}
fn to_update(&self, base_path: Option<&Path>) -> acp::ToolCallUpdate {
let fields = acp::ToolCallUpdateFields::new()
.kind(self.kind)
.status(self.status())
.title(self.title.clone())
.content(self.build_content(base_path))
.locations(self.build_locations(base_path))
.raw_input(self.raw_input())
.raw_output(self.raw_output());
acp::ToolCallUpdate::new(self.id.clone(), fields)
}
}
fn parse_parameter_value(raw: &str) -> JsonValue {
if raw.is_empty() {
return JsonValue::String(String::new());
}
let trimmed = raw.trim();
if let Ok(value) = serde_json::from_str::<JsonValue>(trimmed) {
return value;
}
JsonValue::String(raw.to_string())
}
fn text_content(text: String) -> acp::ToolCallContent {
acp::ToolCallContent::Content(acp::Content::new(acp::ContentBlock::Text(
acp::TextContent::new(text),
)))
}
/// Render SubAgentOutput JSON as markdown for ACP display.
/// Returns None if the JSON is not valid SubAgentOutput.
fn render_sub_agent_output_as_markdown(json_str: &str) -> Option<String> {
use crate::agent::sub_agent::{SubAgentOutput, SubAgentToolStatus};
let output: SubAgentOutput = serde_json::from_str(json_str).ok()?;
let mut lines = Vec::new();
// Render tool calls as a bullet list
if !output.tools.is_empty() {
for tool in &output.tools {
// Use title if available, otherwise tool name
let display_text = tool
.title
.as_ref()
.filter(|t| !t.is_empty())
.cloned()
.or_else(|| tool.message.as_ref().filter(|m| !m.is_empty()).cloned())
.unwrap_or_else(|| tool.name.replace('_', " "));
let suffix = match tool.status {
SubAgentToolStatus::Error => " (failed)",
_ => "",
};
lines.push(format!("- {display_text}{suffix}"));
}
}
// Render error if present
if let Some(error) = &output.error {
lines.push(format!("**Error:** {error}"));
}
// Render final response
if let Some(response) = &output.response {
if !response.is_empty() {
if !lines.is_empty() {
lines.push(String::new()); // Blank line before response
}
lines.push(response.clone());
}
}
if lines.is_empty() {
None
} else {
Some(lines.join("\n"))
}
}
fn resolve_path(path: &str, base_path: Option<&Path>) -> PathBuf {
let candidate = PathBuf::from(path);
if candidate.is_absolute() {
candidate
} else if let Some(root) = base_path {
root.join(candidate)
} else {
candidate
}
}
impl ACPUserUI {
pub fn new(
session_id: acp::SessionId,
session_update_tx: mpsc::UnboundedSender<(acp::SessionNotification, oneshot::Sender<()>)>,
base_path: Option<PathBuf>,
) -> Self {
Self {
session_id,
session_update_tx,
tool_calls: Arc::new(Mutex::new(HashMap::new())),
base_path,
should_continue: Arc::new(AtomicBool::new(true)),
last_error: Arc::new(Mutex::new(None)),
last_content_type: Arc::new(Mutex::new(LastContentType::None)),
needs_paragraph_break_after_hidden_tool: Arc::new(Mutex::new(false)),
}
}
/// Signal that the operation should be cancelled
/// This is called by the cancel() method to stop the prompt() loop
pub fn signal_cancel(&self) {
self.should_continue.store(false, Ordering::Relaxed);
}
fn content_chunk(content: acp::ContentBlock) -> acp::ContentChunk {
acp::ContentChunk::new(content)
}
/// Send a session update notification
async fn send_session_update(&self, update: acp::SessionUpdate) -> Result<(), UIError> {
tracing::debug!("ACPUserUI: Sending session update: {:?}", update);
let (tx, rx) = oneshot::channel();
self.session_update_tx
.send((
acp::SessionNotification::new(self.session_id.clone(), update),
tx,
))
.map_err(|_| {
tracing::error!("ACPUserUI: Channel closed when sending update");
UIError::IOError(std::io::Error::other("Channel closed"))
})?;
// Wait for acknowledgment
rx.await.map_err(|_| {
tracing::error!("ACPUserUI: Failed to receive acknowledgment");
UIError::IOError(std::io::Error::other("Failed to receive ack"))
})?;
tracing::debug!("ACPUserUI: Update sent and acknowledged");
Ok(())
}
fn update_tool_call<F>(&self, tool_id: &str, updater: F) -> acp::ToolCallUpdate
where
F: FnOnce(&mut ToolCallState),
{
let tool_id = tool_id.to_string();
let base_path = self.base_path.as_deref();
let update = {
let mut tool_calls = self.tool_calls.lock().unwrap();
let state = tool_calls
.entry(tool_id.clone())
.or_insert_with(|| ToolCallState::new(&tool_id));
updater(state);
state.to_update(base_path)
};
update
}
fn get_tool_call<F>(&self, tool_id: &str, mutator: F) -> acp::ToolCall
where
F: FnOnce(&mut ToolCallState),
{
let tool_id = tool_id.to_string();
let base_path = self.base_path.as_deref();
let tool_call = {
let mut tool_calls = self.tool_calls.lock().unwrap();
let state = tool_calls
.entry(tool_id.clone())
.or_insert_with(|| ToolCallState::new(&tool_id));
mutator(state);
state.to_tool_call(base_path)
};
tool_call
}
fn queue_session_update(&self, update: acp::SessionUpdate) {
let (ack_tx, _ack_rx) = oneshot::channel();
let notification = acp::SessionNotification::new(self.session_id.clone(), update);
if let Err(e) = self.session_update_tx.send((notification, ack_tx)) {
tracing::error!("ACPUserUI: Failed to send queued update: {:?}", e);
} else {
tracing::trace!("ACPUserUI: Queued session update");
}
}
/// Check if we need a paragraph break after a hidden tool and emit it if so
fn maybe_emit_paragraph_break(&self, current_type: LastContentType) -> Result<(), UIError> {
let mut needs_break = self.needs_paragraph_break_after_hidden_tool.lock().unwrap();
if !*needs_break {
return Ok(());
}
// Reset the flag
*needs_break = false;
// Check if the content type matches the last one
let last_type = *self.last_content_type.lock().unwrap();
if last_type == current_type {
// Same type as before the hidden tool - emit paragraph break
let content = acp::ContentBlock::Text(acp::TextContent::new("\n\n"));
let chunk = Self::content_chunk(content);
// Use the appropriate update type based on content type
let update = match current_type {
LastContentType::Thinking => acp::SessionUpdate::AgentThoughtChunk(chunk),
_ => acp::SessionUpdate::AgentMessageChunk(chunk),
};
self.queue_session_update(update);
}
Ok(())
}
pub fn tool_call_update(&self, tool_id: &str) -> Option<acp::ToolCallUpdate> {
let base_path = self.base_path.as_deref();
let tool_calls = self.tool_calls.lock().unwrap();
tool_calls
.get(tool_id)
.map(|state| state.to_update(base_path))
}
pub fn take_last_error(&self) -> Option<String> {
self.last_error
.lock()
.ok()
.and_then(|mut guard| guard.take())
}
}
#[async_trait]
impl UserInterface for ACPUserUI {
async fn send_event(&self, event: UiEvent) -> Result<(), UIError> {
match event {
UiEvent::DisplayUserInput {
content,
attachments,
node_id: _, // ACP doesn't use node_id for branching
} => {
// Send user message content
self.send_session_update(acp::SessionUpdate::UserMessageChunk(
Self::content_chunk(acp::ContentBlock::Text(acp::TextContent::new(content))),
))
.await?;
// Send attachments as additional content blocks
for attachment in attachments {
#[allow(clippy::single_match)]
match attachment {
crate::persistence::DraftAttachment::Image { content, mime_type } => {
self.send_session_update(acp::SessionUpdate::UserMessageChunk(
Self::content_chunk(acp::ContentBlock::Image(
acp::ImageContent::new(content, mime_type),
)),
))
.await?;
}
_ => {} // Ignore other attachment types for now
}
}
}
UiEvent::UpdateToolStatus {
tool_id,
status,
message,
output,
} => {
let tool_status = map_tool_status(status);
let message_clone = message.clone();
let output_clone = output.clone();
let tool_call_update = self.update_tool_call(&tool_id, |state| {
state.update_status(tool_status, message_clone.clone(), output_clone.clone());
});
self.send_session_update(acp::SessionUpdate::ToolCallUpdate(tool_call_update))
.await?;
}
UiEvent::UpdatePlan { plan } => {
let entries = plan
.entries
.into_iter()
.map(|entry| {
let priority = match entry.priority {
crate::types::PlanItemPriority::High => acp::PlanEntryPriority::High,
crate::types::PlanItemPriority::Medium => {
acp::PlanEntryPriority::Medium
}
crate::types::PlanItemPriority::Low => acp::PlanEntryPriority::Low,
};
let status = match entry.status {
crate::types::PlanItemStatus::Pending => acp::PlanEntryStatus::Pending,
crate::types::PlanItemStatus::InProgress => {
acp::PlanEntryStatus::InProgress
}
crate::types::PlanItemStatus::Completed => {
acp::PlanEntryStatus::Completed
}
};
let meta = entry.meta.and_then(|v| v.as_object().cloned());
acp::PlanEntry::new(entry.content, priority, status).meta(meta)
})
.collect();
let plan_meta = plan.meta.and_then(|v| v.as_object().cloned());
let acp_plan = acp::Plan::new(entries).meta(plan_meta);
self.send_session_update(acp::SessionUpdate::Plan(acp_plan))
.await?;
}
UiEvent::AppendToTextBlock { .. }
| UiEvent::AppendToThinkingBlock { .. }
| UiEvent::StartTool { .. } => {
tracing::trace!(
"ACPUserUI: streaming event received via send_event; handled via display_fragment"
);
}
UiEvent::UpdateToolParameter {
tool_id,
name,
value,
} => {
if tool_id.is_empty() {
tracing::warn!("ACPUserUI: UpdateToolParameter with empty tool_id");
} else {
let name = name.clone();
let value = value.clone();
let tool_call_update = self.update_tool_call(&tool_id, |state| {
state.replace_parameter(&name, &value);
});
self.send_session_update(acp::SessionUpdate::ToolCallUpdate(tool_call_update))
.await?;
}
}
UiEvent::EndTool { .. }
| UiEvent::AddImage { .. }
| UiEvent::AppendToolOutput { .. }
| UiEvent::StartReasoningSummaryItem
| UiEvent::AppendReasoningSummaryDelta { .. }
| UiEvent::CompleteReasoning => {
tracing::trace!(
"ACPUserUI: streaming event received via send_event; handled via display_fragment"
);
}
// Resource events - could be used for "follow mode" in ACP
UiEvent::ResourceLoaded { project, path } => {
tracing::trace!(
"ACPUserUI: ResourceLoaded - project: {}, path: {}",
project,
path.display()
);
// TODO: Could emit follow mode updates here
}
UiEvent::ResourceWritten { project, path } => {
tracing::trace!(
"ACPUserUI: ResourceWritten - project: {}, path: {}",
project,
path.display()
);
}
UiEvent::DirectoryListed { project, path } => {
tracing::trace!(
"ACPUserUI: DirectoryListed - project: {}, path: {}",
project,
path.display()
);
}
UiEvent::ResourceDeleted { project, path } => {
tracing::trace!(
"ACPUserUI: ResourceDeleted - project: {}, path: {}",
project,
path.display()
);
}
// Events that don't translate to ACP
UiEvent::SetMessages { .. }
| UiEvent::DisplayCompactionSummary { .. }
| UiEvent::StreamingStarted(_)
| UiEvent::StreamingStopped { .. }
| UiEvent::RefreshChatList
| UiEvent::UpdateChatList { .. }
| UiEvent::ClearMessages
| UiEvent::SendUserMessage { .. }
| UiEvent::UpdateSessionMetadata { .. }
| UiEvent::UpdateSessionActivityState { .. }
| UiEvent::QueueUserMessage { .. }
| UiEvent::RequestPendingMessageEdit { .. }
| UiEvent::UpdatePendingMessage { .. }
| UiEvent::ClearError
| UiEvent::UpdateCurrentModel { .. }
| UiEvent::UpdateSandboxPolicy { .. }
| UiEvent::CancelSubAgent { .. }
| UiEvent::HiddenToolCompleted
| UiEvent::StartMessageEdit { .. }
| UiEvent::SwitchBranch { .. }
| UiEvent::MessageEditReady { .. }
| UiEvent::BranchSwitched { .. }
| UiEvent::UpdateBranchInfo { .. } => {
// These are UI management events, not relevant for ACP
}
UiEvent::DisplayError { message } => {
tracing::error!("ACPUserUI: Received DisplayError event: {}", message);
if let Ok(mut last_error) = self.last_error.lock() {
*last_error = Some(message);
}
}
}
Ok(())
}
fn display_fragment(&self, fragment: &DisplayFragment) -> Result<(), UIError> {
match fragment {
DisplayFragment::PlainText(text) => {
// Check if we need a paragraph break after a hidden tool
self.maybe_emit_paragraph_break(LastContentType::Text)?;
// Track content type for future hidden tool events
*self.last_content_type.lock().unwrap() = LastContentType::Text;
let content = acp::ContentBlock::Text(acp::TextContent::new(text.clone()));
let chunk = Self::content_chunk(content);
self.queue_session_update(acp::SessionUpdate::AgentMessageChunk(chunk));
}
DisplayFragment::Image { .. } => {
let content = fragment_to_content_block(fragment);
let chunk = Self::content_chunk(content);
self.queue_session_update(acp::SessionUpdate::AgentMessageChunk(chunk));
}
DisplayFragment::CompactionDivider { .. } => {
let content = fragment_to_content_block(fragment);
let chunk = Self::content_chunk(content);
self.queue_session_update(acp::SessionUpdate::AgentMessageChunk(chunk));
}
DisplayFragment::ThinkingText(text) => {
// Check if we need a paragraph break after a hidden tool
self.maybe_emit_paragraph_break(LastContentType::Thinking)?;
// Track content type for future hidden tool events
*self.last_content_type.lock().unwrap() = LastContentType::Thinking;
let content = acp::ContentBlock::Text(acp::TextContent::new(text.clone()));
let chunk = Self::content_chunk(content);
self.queue_session_update(acp::SessionUpdate::AgentThoughtChunk(chunk));
}
DisplayFragment::ToolName { name, id } => {
if id.is_empty() {
tracing::warn!(
"ACPUserUI: StreamingProcessor provided empty tool ID for tool '{}'",
name
);
return Err(UIError::IOError(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("Empty tool ID for tool '{name}'"),
)));
}
let tool_call = self.get_tool_call(id, |state| {
state.set_tool_name(name);
});
self.queue_session_update(acp::SessionUpdate::ToolCall(tool_call));
}
DisplayFragment::ToolParameter {
name,
value,
tool_id,
} => {
if tool_id.is_empty() {
tracing::warn!(
"ACPUserUI: StreamingProcessor provided empty tool ID for parameter '{}'",
name
);
return Err(UIError::IOError(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("Empty tool ID for parameter '{name}'"),
)));
}
let name = name.clone();
let value = value.clone();
let tool_call_update = self.update_tool_call(tool_id, |state| {
state.append_parameter(&name, &value);
});
self.queue_session_update(acp::SessionUpdate::ToolCallUpdate(tool_call_update));
}
DisplayFragment::ToolEnd { id } => {
if id.is_empty() {
tracing::warn!(
"ACPUserUI: StreamingProcessor provided empty tool ID for ToolEnd"
);
return Err(UIError::IOError(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"Empty tool ID for ToolEnd".to_string(),
)));
}
let tool_call_update = self.update_tool_call(id, |state| {
state.ensure_completed();
});
self.queue_session_update(acp::SessionUpdate::ToolCallUpdate(tool_call_update));
}
DisplayFragment::ToolOutput { tool_id, chunk } => {
if tool_id.is_empty() {
tracing::warn!(
"ACPUserUI: StreamingProcessor provided empty tool ID for ToolOutput"
);
return Err(UIError::IOError(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"Empty tool ID for ToolOutput".to_string(),
)));
}
let chunk = chunk.clone();
let tool_call_update = self.update_tool_call(tool_id, |state| {
state.append_output_chunk(&chunk);
});
self.queue_session_update(acp::SessionUpdate::ToolCallUpdate(tool_call_update));
}
DisplayFragment::ToolTerminal {
tool_id,
terminal_id,
} => {
if tool_id.is_empty() || terminal_id.is_empty() {
tracing::warn!(
"ACPUserUI: ToolTerminal fragment missing tool_id or terminal_id"
);
return Err(UIError::IOError(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"ToolTerminal fragment missing identifiers".to_string(),
)));
}
let terminal_id = terminal_id.clone();
let tool_call_update = self.update_tool_call(tool_id, |state| {
state.set_terminal(&terminal_id);
});
self.queue_session_update(acp::SessionUpdate::ToolCallUpdate(tool_call_update));
}
DisplayFragment::ReasoningSummaryStart | DisplayFragment::ReasoningComplete => {
// No ACP representation needed
}
DisplayFragment::HiddenToolCompleted => {
// Mark that a hidden tool completed - paragraph break may be needed before next text
*self.needs_paragraph_break_after_hidden_tool.lock().unwrap() = true;
}
DisplayFragment::ReasoningSummaryDelta(delta) => {
// Reasoning summaries are emitted as AgentThoughtChunk, same as ThinkingText
self.queue_session_update(acp::SessionUpdate::AgentThoughtChunk(
Self::content_chunk(acp::ContentBlock::Text(acp::TextContent::new(
delta.clone(),
))),
));
}
}
Ok(())
}
fn should_streaming_continue(&self) -> bool {
self.should_continue.load(Ordering::Relaxed)
}
fn notify_rate_limit(&self, _seconds_remaining: u64) {
// Could send a custom meta field with rate limit info
}
fn clear_rate_limit(&self) {
// No action needed
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::{PlanItem, PlanItemPriority, PlanItemStatus, PlanState};
use serde_json::json;
use tokio::sync::{mpsc, oneshot};
fn create_ui() -> (
ACPUserUI,
mpsc::UnboundedReceiver<(acp::SessionNotification, oneshot::Sender<()>)>,
) {
let (tx, rx) = mpsc::unbounded_channel();
let ui = ACPUserUI::new(acp::SessionId::new("session-1"), tx, None);
(ui, rx)
}
#[test]
fn tool_call_state_includes_terminal_content() {
let mut state = ToolCallState::new("tool-1");
state.set_tool_name("execute_command");
state.append_parameter("command", "npm test");
state.append_output_chunk("running…\n");
state.set_terminal("term-123");
let content = state
.build_content(None)
.expect("content should be emitted");
assert!(matches!(
content.first(),
Some(acp::ToolCallContent::Terminal(terminal))
if terminal.terminal_id.0.as_ref() == "term-123"
));
assert!(content.iter().any(|item| matches!(
item,
acp::ToolCallContent::Content(content)
if matches!(&content.content, acp::ContentBlock::Text(text_content)
if text_content.text.contains("command: npm test"))
)));
}
#[test]
fn tool_output_stops_streaming_after_terminal_attached() {
let mut state = ToolCallState::new("tool-1");
state.append_output_chunk("line one\n");
assert_eq!(state.output_text().as_deref(), Some("line one\n"));
state.set_terminal("term-123");
state.append_output_chunk("line two\n");
assert_eq!(state.output_text().as_deref(), Some("line one\n"));
}
#[test]
fn tool_name_fragment_emits_tool_call_notification() {
let (ui, mut rx) = create_ui();
ui.display_fragment(&DisplayFragment::ToolName {
name: "execute_command".into(),
id: "tool-1".into(),
})
.unwrap();
let (notification, _ack) = rx.try_recv().expect("expected tool call notification");
match notification.update {
acp::SessionUpdate::ToolCall(call) => {
assert_eq!(call.tool_call_id.0.as_ref(), "tool-1");
assert_eq!(call.kind, acp::ToolKind::Execute);
assert_eq!(call.title, "execute_command");
}
other => panic!("unexpected update: {other:?}"),
}
}
#[test]
fn tool_output_fragments_accumulate_raw_output() {
let (ui, mut rx) = create_ui();
ui.display_fragment(&DisplayFragment::ToolName {
name: "read_files".into(),
id: "tool-1".into(),
})
.unwrap();
rx.try_recv().unwrap(); // discard ToolCall notification
ui.display_fragment(&DisplayFragment::ToolOutput {
tool_id: "tool-1".into(),
chunk: "part one".into(),
})
.unwrap();
let (notification, _ack) = rx.try_recv().expect("first tool update");
let update = match notification.update {
acp::SessionUpdate::ToolCallUpdate(update) => update,
other => panic!("unexpected update: {other:?}"),
};
assert_eq!(