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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
mod event_handler;
mod popup_types;
mod swarm;
pub use popup_types::*;
pub use swarm::*;
use std::cell::RefCell;
use ratatui::layout::Rect;
use ratatui::prelude::{Color, Line};
use crate::agent::r#loop::AgentEvent;
use crate::api::Content;
/// Maximum chat messages retained in TUI (oldest are dropped).
pub(super) const MAX_MESSAGES: usize = 500;
/// Maximum tool log entries retained.
pub(super) const MAX_TOOL_LOG: usize = 200;
/// Maximum changed file entries in sidebar.
pub(super) const MAX_CHANGED_FILES: usize = 100;
/// Push an item to a Vec, dropping the oldest if capacity is exceeded.
pub(super) fn push_bounded<T>(vec: &mut Vec<T>, item: T, max: usize) {
if vec.len() >= max {
vec.drain(..vec.len() - max + 1);
}
vec.push(item);
}
use crate::agent::session::SessionSnapshot;
use crate::tui::spinner::Spinner;
use crate::tui::theme::Theme;
/// Cached render output for all finalized messages (not including streaming_buffer).
///
/// Stored in `UiState` alongside `messages`. Invalidated when terminal width or theme
/// changes. Incrementally extended when new messages are appended.
pub struct MessagesRenderCache {
/// Terminal inner-width (area.width - 2) this cache was computed for.
pub width: u16,
/// Theme bg color used as a lightweight change-detection signature.
pub theme_bg: Color,
/// Provider name used when rendering assistant headers (cache key).
pub provider_name: String,
/// Model name used when rendering assistant headers (cache key).
pub model_name: String,
/// Swarm agent names at render time (cache key).
pub swarm_names: Vec<String>,
/// Session collaboration mode label at render time (cache key).
pub collab_mode_label: String,
/// Number of messages covered by this cache (== `messages.len()` when fully valid).
pub message_count: usize,
/// Pre-rendered ratatui lines for all cached messages.
pub lines: Vec<Line<'static>>,
/// Line ranges `(start, end)` for user message boxes (used for bg fill).
pub user_box_ranges: Vec<(usize, usize)>,
/// Diff / file-write click regions with absolute line indices into `lines`.
pub click_regions: Vec<DiffClickRegion>,
/// Value of `prev_is_user` after the last cached message (for incremental extension).
pub last_was_user: bool,
/// Cached per-line visual heights (avoids O(n) char-width scan every frame).
/// Invalidated when `lines` or `width` changes.
pub line_heights: Vec<u16>,
}
/// A clickable region in the output panel that expands a truncated diff.
#[derive(Debug, Clone)]
pub struct DiffClickRegion {
/// Visual line index within the output widget's line array.
pub line_index: usize,
/// Popup title (e.g. "file_edit ✎ path/to/file").
pub title: String,
/// Full diff content to show in the popup.
pub content: String,
}
/// Cumulative token usage statistics.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct TokenStats {
pub prompt_tokens: u64,
pub completion_tokens: u64,
pub api_calls: u32,
}
impl TokenStats {
pub fn total_tokens(&self) -> u64 {
self.prompt_tokens + self.completion_tokens
}
pub fn record(&mut self, prompt: u64, completion: u64) {
self.prompt_tokens += prompt;
self.completion_tokens += completion;
self.api_calls += 1;
}
}
/// Kind of an autocomplete candidate.
#[derive(Debug, Clone, PartialEq)]
pub enum AcKind {
Agent,
File,
Dir,
Command,
Skill,
}
/// A single autocomplete candidate.
#[derive(Debug, Clone)]
pub struct AcCandidate {
/// Display label (e.g., "architect", "architect.md/").
pub label: String,
/// Kind of candidate.
pub kind: AcKind,
}
/// Active @-mention autocomplete state.
#[derive(Debug, Clone)]
pub struct MentionAc {
/// The prefix after `@` currently being typed.
pub prefix: String,
/// Matching candidates.
pub candidates: Vec<AcCandidate>,
/// Selected candidate index.
pub selected: usize,
}
impl MentionAc {
pub fn selected_candidate(&self) -> Option<&AcCandidate> {
self.candidates.get(self.selected)
}
}
/// Represents a message in the chat view.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ChatMessage {
pub role: MessageRole,
pub content: Content,
}
impl ChatMessage {
/// Create a text-only message
pub fn text(role: MessageRole, content: impl Into<String>) -> Self {
Self {
role,
content: Content::text(content),
}
}
/// Create a multipart message with images
pub fn with_images(
role: MessageRole,
text: String,
images: Vec<crate::api::ImageData>,
) -> Self {
Self {
role,
content: Content::multipart(text, images),
}
}
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum MessageRole {
User,
Assistant,
Tool {
name: String,
success: bool,
args_summary: String,
},
System,
/// Message queued while the agent is busy — shown like a compact user bubble.
Queued,
}
/// A single configurable value shown in the /config popup.
#[derive(Debug, Clone)]
pub enum ConfigValue {
/// Toggleable boolean.
Bool(bool),
/// Cyclic choice from a fixed option list.
Choice { value: String, options: Vec<String> },
/// Read-only text display (edit via config.toml or env var).
Text(String),
}
impl ConfigValue {
/// Advance to the next value (toggle or cycle). Text values are read-only.
pub fn cycle(&mut self) {
match self {
ConfigValue::Bool(b) => *b = !*b,
ConfigValue::Choice { value, options } => {
if let Some(idx) = options.iter().position(|o| o == value.as_str()) {
*value = options[(idx + 1) % options.len()].clone();
}
}
ConfigValue::Text(_) => {}
}
}
pub fn display(&self) -> &str {
match self {
ConfigValue::Bool(true) => "true",
ConfigValue::Bool(false) => "false",
ConfigValue::Choice { value, .. } => value.as_str(),
ConfigValue::Text(s) => s.as_str(),
}
}
}
/// A row in the /config popup.
#[derive(Debug, Clone)]
pub struct ConfigItem {
/// Human-readable label shown in left column.
pub label: String,
/// Internal key used to apply changes back to Config.
pub key: String,
pub value: ConfigValue,
/// Optional warning hint shown when value exceeds this threshold.
/// Only meaningful for numeric Choice values.
pub warn_above: Option<String>,
}
/// The complete UI state.
pub struct UiState {
/// Chat history.
pub messages: Vec<ChatMessage>,
/// Current streaming buffer (assistant is typing).
pub streaming_buffer: String,
/// Is the agent currently working?
pub agent_busy: bool,
/// User input buffer.
pub input: String,
/// Dim hint text shown after cursor (e.g. subcommand args placeholder).
pub input_hint: Option<String>,
/// Input cursor position.
pub cursor: usize,
/// Scroll offset for output panel.
pub scroll_offset: u16,
/// Current iteration.
pub iteration: u32,
/// Elapsed seconds.
pub elapsed_secs: u64,
/// Tool log entries.
pub tool_log: Vec<ToolLogEntry>,
/// Should the app quit?
pub should_quit: bool,
/// Status message.
pub status_msg: String,
/// Pending session snapshot for /resume command.
pub pending_resume: Option<SessionSnapshot>,
/// Cumulative token usage statistics.
pub token_stats: TokenStats,
/// Current agent mode label ("code", "ask", "architect").
pub agent_mode: String,
/// Number of available checkpoints.
pub checkpoint_count: usize,
/// Current provider name (e.g., "zai-coding"). Empty if unknown.
pub provider_name: String,
/// Current model name (e.g., "glm-4.7").
pub model_name: String,
/// LSP servers installed on the system (detected at startup).
pub installed_lsp: Vec<String>,
/// LSP servers currently running (spawned on demand).
pub running_lsp: Vec<String>,
/// Context window max tokens for budget bar.
pub context_max_tokens: usize,
/// Context window used tokens (estimated).
pub context_used_tokens: usize,
/// Prompt cache hit rate (0.0 - 1.0).
pub cache_hit_rate: f64,
/// Prompt cache tokens saved.
pub cache_tokens_saved: usize,
/// Number of compaction events.
pub compaction_count: usize,
/// Active @-mention autocomplete popup (None = hidden).
pub mention_ac: Option<MentionAc>,
/// Active slash-command autocomplete popup (None = hidden).
pub command_ac: Option<MentionAc>,
/// Animated spinner for thinking/working states.
pub spinner: Spinner,
/// Active color theme.
pub theme: Theme,
/// Pending architect plan awaiting user approval.
pub pending_plan: Option<PendingPlan>,
/// Swarm mode status (None when hive mode is off).
pub swarm_status: Option<SwarmUiStatus>,
/// Active popup overlay (title, content, scroll offset).
pub popup: Option<PopupState>,
/// Scroll offset for the right sidebar tool activity section.
pub sidebar_scroll: u16,
/// Pre-aggregated changed files for sidebar (path → (additions, deletions)).
pub changed_files: Vec<ChangedFileEntry>,
/// Current stream retry attempt (0 = no retry yet).
pub stream_retry: u32,
/// Max allowed stream retries (from config).
pub stream_max_retries: u32,
/// Debug mode enabled (shows process monitor in sidebar).
pub debug_mode: bool,
/// Real-time process metrics for debug monitor.
pub debug_monitor: DebugMonitor,
/// Performance target thresholds (from config) for debug highlight.
pub debug_targets: crate::config::DebugTargets,
/// MCP server status for sidebar display (loaded at startup).
pub mcp_servers: Vec<crate::mcp::config::McpServerUi>,
/// MCP server currently in use (extracted from `mcp__{server}__` tool name prefix).
pub active_mcp_server: Option<String>,
/// Timestamp when active_mcp_server was last set, for minimum display duration.
active_mcp_server_set_at: Option<std::time::Instant>,
/// Hidden paste buffer — when a large paste is abbreviated in `input`, the full
/// text is stored here and spliced back on Submit.
pub paste_buffer: Option<String>,
/// Pending images to be sent with the next message (from clipboard paste).
pub pending_images: Vec<PendingImage>,
/// Clickable "expand" regions populated during output render (interior mutability).
pub diff_click_regions: RefCell<Vec<DiffClickRegion>>,
/// Cached render output for finalized messages — avoids re-wrapping on every frame.
pub messages_render_cache: RefCell<Option<MessagesRenderCache>>,
/// Cached render output for the streaming buffer — avoids O(n) re-parse every frame.
/// Tuple: (cached_buf_len, cached_width, cached_lines).
pub streaming_render_cache: RefCell<Option<(usize, u16, Vec<ratatui::text::Line<'static>>)>>,
/// Output panel area from the last render frame (for click coordinate mapping).
pub last_output_area: RefCell<Rect>,
/// Cumulative visual row offsets from the last render (line_index → cumulative row).
pub last_line_cum_heights: RefCell<Vec<u16>>,
/// Scroll value used in the last render frame.
pub last_render_scroll: RefCell<u16>,
/// Current tool approval mode label for status line display.
pub approve_mode: String,
/// Current session collaboration mode ("none", "fork", "hive", "flock").
pub collab_mode_label: String,
/// Terminal row where the Changed Files list starts in the sidebar (set each frame).
pub sidebar_files_start_row: std::cell::Cell<u16>,
/// Terminal row where the swarm agent list starts in the sidebar (set each frame).
pub sidebar_swarm_agents_start_row: std::cell::Cell<u16>,
/// Sidebar panel area from the last render frame (for click coordinate mapping).
pub last_sidebar_area: RefCell<Rect>,
/// Ephemeral soul reflection message — fades out after a few seconds.
/// `(message, shown_at)` — rendered with decreasing opacity over time.
pub soul_toast: Option<(String, std::time::Instant)>,
/// Current view mode (main chat vs attached worker).
pub view_mode: ViewMode,
/// Full streaming buffers per worker agent_id — accumulated regardless of attach state.
pub worker_streams: std::collections::HashMap<String, WorkerDetailState>,
/// Shell mode: when true, the prompt indicator shows "!" instead of ">"
/// and the status bar uses warning color. Entered by typing "!" on an
/// empty prompt; exited by backspace when input is empty.
pub shell_mode: bool,
/// Fast mode: skip sidebar rendering, swarm coordination, soul reflection.
pub fast_mode: bool,
/// Current project name (folder name of working directory) for status bar display.
pub project_name: String,
}
impl UiState {
pub fn new() -> Self {
Self {
messages: vec![ChatMessage::text(MessageRole::System, "##WELCOME##")],
streaming_buffer: String::new(),
agent_busy: false,
input: String::new(),
input_hint: None,
cursor: 0,
scroll_offset: 0,
iteration: 0,
elapsed_secs: 0,
tool_log: Vec::new(),
should_quit: false,
status_msg: "Ready".to_string(),
pending_resume: None,
token_stats: TokenStats::default(),
agent_mode: "arbor".to_string(),
checkpoint_count: 0,
provider_name: String::new(),
model_name: String::new(),
installed_lsp: Vec::new(),
running_lsp: Vec::new(),
context_max_tokens: 120_000,
context_used_tokens: 0,
cache_hit_rate: 0.0,
cache_tokens_saved: 0,
compaction_count: 0,
mention_ac: None,
command_ac: None,
spinner: Spinner::new(),
theme: Theme::default_theme(),
pending_plan: None,
swarm_status: None,
popup: None,
sidebar_scroll: 0,
changed_files: Vec::new(),
stream_retry: 0,
stream_max_retries: 5,
debug_mode: false,
debug_monitor: DebugMonitor::default(),
debug_targets: crate::config::DebugTargets::default(),
mcp_servers: Vec::new(),
active_mcp_server: None,
active_mcp_server_set_at: None,
paste_buffer: None,
pending_images: Vec::new(),
diff_click_regions: RefCell::new(Vec::new()),
messages_render_cache: RefCell::new(None),
streaming_render_cache: RefCell::new(None),
last_output_area: RefCell::new(Rect::default()),
last_line_cum_heights: RefCell::new(Vec::new()),
last_render_scroll: RefCell::new(0),
approve_mode: "auto".to_string(),
collab_mode_label: "none".to_string(),
sidebar_files_start_row: std::cell::Cell::new(0),
sidebar_swarm_agents_start_row: std::cell::Cell::new(0),
last_sidebar_area: RefCell::new(Rect::default()),
soul_toast: None,
view_mode: ViewMode::default(),
worker_streams: std::collections::HashMap::new(),
shell_mode: false,
fast_mode: false,
project_name: String::new(),
}
}
/// Process an agent event and update state.
pub fn handle_agent_event(&mut self, event: AgentEvent) {
match event {
AgentEvent::Token(token) => self.ev_token(token),
AgentEvent::Response(_text) => self.ev_response(),
AgentEvent::ToolCall {
name,
args,
call_id,
} => self.ev_tool_call(name, args, call_id),
AgentEvent::ToolResult {
name,
result,
success,
call_id,
} => self.ev_tool_result(name, result, success, call_id),
AgentEvent::ImageNotice {
notice,
install_hint,
} => self.ev_image_notice(notice, install_hint),
AgentEvent::SoulReflecting { agent_name } => self.ev_soul_reflecting(agent_name),
AgentEvent::Done { .. }
| AgentEvent::FileModified { .. }
| AgentEvent::PlanReady { .. }
| AgentEvent::SwarmDone { .. }
| AgentEvent::LspInstalled { .. }
| AgentEvent::McpPids { .. }
| AgentEvent::ApprovalRequired { .. }
| AgentEvent::ApprovalDenied { .. }
| AgentEvent::Evolution(_)
| AgentEvent::ShellOutput { .. }
| AgentEvent::ToolBatchProgress { .. }
| AgentEvent::StreamWaiting { .. }
| AgentEvent::CompactionStarted { .. }
| AgentEvent::CompactionDone { .. }
| AgentEvent::ToolResultTruncated { .. } => {
// These events must be intercepted and handled by app/event_loop.rs
// before reaching this function. Log an error if they slip through
// (e.g. due to a future refactor) rather than crashing.
tracing::error!(
event = ?std::mem::discriminant(&event),
"BUG: protected event reached state.handle_agent_event() — \
should have been intercepted by app/event_loop.rs"
);
}
AgentEvent::SwarmAgentStarted {
agent_id,
agent_name,
task_preview,
} => self.ev_swarm_agent_started(agent_id, agent_name, task_preview),
AgentEvent::SwarmAgentProgress {
agent_id,
iteration,
status,
..
} => self.ev_swarm_agent_progress(agent_id, iteration, status),
AgentEvent::SwarmAgentDone {
agent_id,
success,
modified_files,
tool_calls,
input_tokens,
output_tokens,
response,
..
} => self.ev_swarm_agent_done(
agent_id,
success,
modified_files,
tool_calls,
input_tokens,
output_tokens,
response,
),
AgentEvent::SwarmModeSwitch { label } => self.ev_swarm_mode_switch(label),
AgentEvent::SwarmWorkersDispatched => self.ev_swarm_workers_dispatched(),
AgentEvent::SwarmWorkerPaused { agent_id } => self.ev_swarm_worker_paused(&agent_id),
AgentEvent::SwarmWorkerResumed { agent_id } => self.ev_swarm_worker_resumed(&agent_id),
AgentEvent::SwarmResolvedToSingle { agent_label } => {
self.ev_swarm_resolved_to_single(agent_label)
}
AgentEvent::SwarmWorkerApproaching {
agent_id,
task_preview,
remaining,
} => self.ev_swarm_worker_approaching(agent_id, task_preview, remaining),
AgentEvent::SwarmConflict { conflicts } => self.ev_swarm_conflict(conflicts),
AgentEvent::Error(msg) => self.ev_error(msg),
AgentEvent::GuardStop(msg) => self.ev_guard_stop(msg),
AgentEvent::StreamRetry {
attempt,
max,
message,
} => self.ev_stream_retry(attempt, max, message),
AgentEvent::PhaseChange { label } => self.ev_phase_change(label),
AgentEvent::Status {
iteration,
elapsed_secs,
prompt_tokens,
completion_tokens,
cached_tokens,
context_tokens,
} => self.ev_status(
iteration,
elapsed_secs,
prompt_tokens,
completion_tokens,
cached_tokens,
context_tokens,
),
AgentEvent::PerformanceUpdate {
tool_latency_avg_ms,
tool_latency_max_ms,
api_latency_avg_ms,
api_latency_max_ms,
tool_success_count,
tool_failure_count,
total_iterations,
total_tokens_used,
total_tool_calls_made,
top_tools,
} => self.ev_performance_update(
tool_latency_avg_ms,
tool_latency_max_ms,
api_latency_avg_ms,
api_latency_max_ms,
tool_success_count,
tool_failure_count,
total_iterations,
total_tokens_used,
total_tool_calls_made,
top_tools,
),
AgentEvent::SwarmAgentToolCall {
agent_id,
name,
args,
..
} => self.ev_swarm_agent_tool_call(&agent_id, &name, &args),
AgentEvent::SwarmAgentToolResult {
agent_id,
name,
result,
success,
..
} => self.ev_swarm_agent_tool_result(&agent_id, &name, &result, success),
AgentEvent::SwarmAgentToken { agent_id, text } => {
self.ev_swarm_agent_token(&agent_id, &text)
}
AgentEvent::SwarmAgentResponse { agent_id, text } => {
self.ev_swarm_agent_response(&agent_id, &text)
}
}
}
/// Handle agent completion (called from app.rs after extracting context).
pub fn handle_done(&mut self) {
if !self.streaming_buffer.is_empty() {
let text: String = self.streaming_buffer.drain(..).collect();
push_bounded(
&mut self.messages,
ChatMessage::text(MessageRole::Assistant, text),
MAX_MESSAGES,
);
}
// Invalidate streaming render cache so next frame doesn't render stale lines.
*self.streaming_render_cache.borrow_mut() = None;
self.agent_busy = false;
self.status_msg = "Ready".to_string();
self.spinner.reset();
self.stream_retry = 0;
self.swarm_status = None;
// Deactivate LSP display (processes stay alive for reuse).
self.running_lsp.clear();
self.active_mcp_server = None;
self.active_mcp_server_set_at = None;
// Reset worker attach state
self.view_mode = ViewMode::Main;
self.worker_streams.clear();
}
/// Attach to a swarm worker by ID (switches view mode).
pub fn attach_worker(&mut self, agent_id: &str) {
self.view_mode = ViewMode::WorkerAttached {
agent_id: agent_id.to_string(),
};
// Reset scroll for the worker detail
if let Some(detail) = self.worker_streams.get_mut(agent_id) {
detail.auto_scroll = true;
detail.scroll_offset = 0;
}
}
/// Detach from worker view (returns to main chat).
pub fn detach_worker(&mut self) {
self.view_mode = ViewMode::Main;
}
/// Get the currently attached worker's detail state (if any).
pub fn attached_worker_detail(&self) -> Option<(&str, &WorkerDetailState)> {
if let ViewMode::WorkerAttached { ref agent_id } = self.view_mode {
self.worker_streams
.get(agent_id.as_str())
.map(|d| (agent_id.as_str(), d))
} else {
None
}
}
/// Get the currently attached worker's detail state mutably.
pub fn attached_worker_detail_mut(&mut self) -> Option<&mut WorkerDetailState> {
if let ViewMode::WorkerAttached { ref agent_id } = self.view_mode {
let id = agent_id.clone();
self.worker_streams.get_mut(id.as_str())
} else {
None
}
}
/// Set the color theme by name.
pub fn set_theme(&mut self, name: &str) {
self.theme = Theme::from_name(name);
}
/// Advance the spinner animation (called on Tick events).
pub fn tick_spinner(&mut self) {
if self.agent_busy {
self.spinner.tick();
// Auto-restore from compact animation after ~2 seconds (20 frames × 100ms)
if self.spinner.is_compact() && self.spinner.frame_count() > 20 {
self.spinner.set_default();
}
}
// Clear soul toast after 4 seconds
if let Some((_, shown_at)) = &self.soul_toast
&& shown_at.elapsed() >= std::time::Duration::from_secs(4)
{
self.soul_toast = None;
}
// Clear stale MCP server highlight after minimum display duration (2s)
if self.active_mcp_server.is_some() {
let expired = self
.active_mcp_server_set_at
.map(|t| t.elapsed() >= std::time::Duration::from_secs(2) && !self.agent_busy)
.unwrap_or(true);
if expired {
self.active_mcp_server = None;
self.active_mcp_server_set_at = None;
}
}
}
/// Maximum input buffer size in bytes (100 KB).
const MAX_INPUT_LEN: usize = 100_000;
/// Insert a character at cursor position.
pub fn insert_char(&mut self, c: char) {
if self.input.len() + c.len_utf8() > Self::MAX_INPUT_LEN {
return; // silently reject to prevent unbounded growth
}
self.input.insert(self.cursor, c);
self.cursor += c.len_utf8();
}
/// Delete character before cursor.
pub fn backspace(&mut self) {
if self.cursor > 0 {
let prev = self.input[..self.cursor]
.chars()
.last()
.map(|c| c.len_utf8())
.unwrap_or(0);
self.cursor -= prev;
self.input.remove(self.cursor);
}
}
/// Take the current input (clearing the buffer).
pub fn take_input(&mut self) -> String {
self.cursor = 0;
self.input_hint = None;
// If a large paste was abbreviated in the input, return the full content instead.
if let Some(full) = self.paste_buffer.take() {
self.input.clear();
full
} else {
std::mem::take(&mut self.input)
}
}
// ── Cursor movement ─────────────────────────────────────────────────
/// Move cursor one character left.
pub fn cursor_left(&mut self) {
if self.cursor > 0 {
let prev = self.input[..self.cursor]
.chars()
.last()
.map(|c| c.len_utf8())
.unwrap_or(0);
self.cursor -= prev;
}
}
/// Move cursor one character right.
pub fn cursor_right(&mut self) {
if self.cursor < self.input.len() {
let next = self.input[self.cursor..]
.chars()
.next()
.map(|c| c.len_utf8())
.unwrap_or(0);
self.cursor += next;
}
}
/// Move cursor to start of previous word (Option+Left / Ctrl+Left / Alt+B).
pub fn cursor_word_left(&mut self) {
// Collect (byte_offset, char) pairs so we always move on char boundaries,
// not raw bytes — CJK and other multi-byte chars are 2-3 bytes wide.
let chars: Vec<(usize, char)> = self.input[..self.cursor].char_indices().collect();
let mut i = chars.len();
// Skip whitespace backward
while i > 0 && chars[i - 1].1.is_whitespace() {
i -= 1;
}
// Skip word chars backward
while i > 0 && !chars[i - 1].1.is_whitespace() {
i -= 1;
}
self.cursor = chars.get(i).map(|(b, _)| *b).unwrap_or(0);
}
/// Move cursor to end of next word (Option+Right / Ctrl+Right / Alt+F).
pub fn cursor_word_right(&mut self) {
// Same char-boundary-safe approach as cursor_word_left.
let after = &self.input[self.cursor..];
let chars: Vec<(usize, char)> = after.char_indices().collect();
let mut i = 0;
// Skip word chars forward
while i < chars.len() && !chars[i].1.is_whitespace() {
i += 1;
}
// Skip whitespace forward
while i < chars.len() && chars[i].1.is_whitespace() {
i += 1;
}
self.cursor += chars.get(i).map(|(b, _)| *b).unwrap_or(after.len());
}
/// Move cursor to start of current line (Home / Ctrl+A).
pub fn cursor_line_start(&mut self) {
if let Some(nl) = self.input[..self.cursor].rfind('\n') {
self.cursor = nl + 1;
} else {
self.cursor = 0;
}
}
/// Move cursor to end of current line (End / Ctrl+E).
pub fn cursor_line_end(&mut self) {
if let Some(nl) = self.input[self.cursor..].find('\n') {
self.cursor += nl;
} else {
self.cursor = self.input.len();
}
}
/// Returns true if the cursor is NOT on the first logical line.
pub fn cursor_has_line_above(&self) -> bool {
self.input[..self.cursor].contains('\n')
}
/// Returns true if there is at least one more logical line below the cursor.
pub fn cursor_has_line_below(&self) -> bool {
self.input[self.cursor..].contains('\n')
}
/// Move cursor up one logical line, preserving column position.
pub fn cursor_line_up(&mut self) {
let before = &self.input[..self.cursor];
let line_start = before.rfind('\n').map(|p| p + 1).unwrap_or(0);
// Use char count for column so multi-byte chars (CJK, etc.) don't
// land the cursor on an invalid byte boundary in the target line.
let col_chars = before[line_start..].chars().count();
if line_start == 0 {
return; // already on first line
}
let prev_end = line_start - 1; // byte index of the preceding '\n'
let prev_start = self.input[..prev_end]
.rfind('\n')
.map(|p| p + 1)
.unwrap_or(0);
let prev_line = &self.input[prev_start..prev_end];
let byte_offset = prev_line
.char_indices()
.nth(col_chars)
.map(|(i, _)| i)
.unwrap_or(prev_line.len());
self.cursor = prev_start + byte_offset;
}
/// Move cursor down one logical line, preserving column position.
pub fn cursor_line_down(&mut self) {
let before = &self.input[..self.cursor];
let line_start = before.rfind('\n').map(|p| p + 1).unwrap_or(0);
// Use char count for column so multi-byte chars (CJK, etc.) don't
// land the cursor on an invalid byte boundary in the target line.
let col_chars = before[line_start..].chars().count();
let after = &self.input[self.cursor..];
let next_nl_offset = match after.find('\n') {
Some(p) => p,
None => return, // already on last line
};
let next_start = self.cursor + next_nl_offset + 1;
let next_end = self.input[next_start..]
.find('\n')
.map(|p| next_start + p)
.unwrap_or(self.input.len());
let next_line = &self.input[next_start..next_end];
let byte_offset = next_line
.char_indices()
.nth(col_chars)
.map(|(i, _)| i)
.unwrap_or(next_line.len());
self.cursor = next_start + byte_offset;
}
// ── Deletion ────────────────────────────────────────────────────────
/// Delete character at cursor (Delete key).
pub fn delete_forward(&mut self) {
if self.cursor < self.input.len() {
let next = self.input[self.cursor..]
.chars()
.next()
.map(|c| c.len_utf8())
.unwrap_or(0);
self.input.drain(self.cursor..self.cursor + next);
}
}
/// Delete previous word (Ctrl+W).
pub fn delete_word_back(&mut self) {
let old = self.cursor;
self.cursor_word_left();
if self.cursor < old {
self.input.drain(self.cursor..old);
}
}
/// Delete from cursor to line start (Ctrl+U).
pub fn delete_to_line_start(&mut self) {
let start = if let Some(nl) = self.input[..self.cursor].rfind('\n') {
nl + 1
} else {
0
};
self.input.drain(start..self.cursor);
self.cursor = start;
}
/// Delete from cursor to line end (Ctrl+K).
pub fn delete_to_line_end(&mut self) {
let end = if let Some(nl) = self.input[self.cursor..].find('\n') {
self.cursor + nl
} else {
self.input.len()
};
self.input.drain(self.cursor..end);
}
// ── Image management ────────────────────────────────────────────────────
/// Add an image to pending images (called from clipboard paste handler).
pub fn add_pending_image(&mut self, image: crate::api::ImageData) {
self.pending_images.push(PendingImage { data: image });
}
/// Clear all pending images (called on cancel, Esc, and DeleteToLineStart).
pub fn clear_pending_images(&mut self) {
self.pending_images.clear();
}
/// Take all pending images (consumes them)
pub fn take_pending_images(&mut self) -> Vec<PendingImage> {
std::mem::take(&mut self.pending_images)
}
/// Get display text for input (including image count), used by the input bar renderer.
pub fn input_display(&self) -> String {
if self.pending_images.is_empty() {
self.input.clone()
} else {
format!("{} [{} image(s)]", self.input, self.pending_images.len())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_token_stats_default() {
let stats = TokenStats::default();
assert_eq!(stats.prompt_tokens, 0);
assert_eq!(stats.completion_tokens, 0);
assert_eq!(stats.api_calls, 0);
assert_eq!(stats.total_tokens(), 0);
}
#[test]
fn test_token_stats_record() {
let mut stats = TokenStats::default();
stats.record(100, 50);
assert_eq!(stats.prompt_tokens, 100);
assert_eq!(stats.completion_tokens, 50);
assert_eq!(stats.total_tokens(), 150);
assert_eq!(stats.api_calls, 1);
stats.record(200, 100);
assert_eq!(stats.total_tokens(), 450);
assert_eq!(stats.api_calls, 2);
}
#[test]
fn test_ui_state_new() {
let state = UiState::new();
assert!(!state.agent_busy);
assert!(!state.should_quit);
assert_eq!(state.cursor, 0);
assert_eq!(state.iteration, 0);
assert_eq!(state.agent_mode, "arbor");
assert_eq!(state.checkpoint_count, 0);
assert_eq!(state.messages.len(), 1); // welcome message
assert!(state.model_name.is_empty());
assert!(state.installed_lsp.is_empty());
assert!(state.running_lsp.is_empty());
assert_eq!(state.context_max_tokens, 120_000);
assert_eq!(state.context_used_tokens, 0);
assert_eq!(state.cache_hit_rate, 0.0);
}
#[test]
fn test_insert_char() {
let mut state = UiState::new();
state.insert_char('h');
state.insert_char('i');
assert_eq!(state.input, "hi");
assert_eq!(state.cursor, 2);
}
#[test]
fn test_insert_char_unicode() {
let mut state = UiState::new();
state.insert_char('한');
assert_eq!(state.input, "한");
assert_eq!(state.cursor, 3); // UTF-8 length
}
#[test]
fn test_backspace() {
let mut state = UiState::new();
state.insert_char('a');
state.insert_char('b');
state.insert_char('c');
state.backspace();
assert_eq!(state.input, "ab");
assert_eq!(state.cursor, 2);
}
#[test]
fn test_backspace_empty() {
let mut state = UiState::new();
state.backspace(); // should not panic
assert_eq!(state.input, "");
assert_eq!(state.cursor, 0);
}
#[test]
fn test_take_input() {
let mut state = UiState::new();
state.insert_char('h');
state.insert_char('i');
let input = state.take_input();
assert_eq!(input, "hi");
assert_eq!(state.input, "");
assert_eq!(state.cursor, 0);
}
#[test]
fn test_handle_token_event() {
let mut state = UiState::new();
state.handle_agent_event(AgentEvent::Token("hello ".to_string()));
state.handle_agent_event(AgentEvent::Token("world".to_string()));
assert_eq!(state.streaming_buffer, "hello world");
}
#[test]
fn test_handle_response_event() {
let mut state = UiState::new();
state.streaming_buffer = "streamed content".to_string();
state.handle_agent_event(AgentEvent::Response("streamed content".to_string()));
assert!(state.streaming_buffer.is_empty());
assert_eq!(state.messages.last().unwrap().role, MessageRole::Assistant);
}
#[test]
fn test_handle_tool_call_event() {
let mut state = UiState::new();
state.handle_agent_event(AgentEvent::ToolCall {
name: "bash".to_string(),
args: r#"{"command": "ls"}"#.to_string(),
call_id: None,
});
assert_eq!(state.tool_log.len(), 1);
assert_eq!(state.tool_log[0].name, "bash");
assert!(state.status_msg.contains("bash"));
}
#[test]
fn test_handle_error_event() {
let mut state = UiState::new();
state.agent_busy = true;
state.handle_agent_event(AgentEvent::Error("API timeout".to_string()));
assert!(!state.agent_busy);
assert!(
state
.messages
.last()
.unwrap()
.content
.text_content()
.contains("API timeout")
);
}
#[test]
fn test_handle_guard_stop() {
let mut state = UiState::new();
state.agent_busy = true;
state.handle_agent_event(AgentEvent::GuardStop("Iteration limit".to_string()));
assert!(!state.agent_busy);
assert_eq!(state.status_msg, "Guard stop");
}
#[test]
fn test_handle_status_event() {
let mut state = UiState::new();
state.handle_agent_event(AgentEvent::Status {
iteration: 5,
elapsed_secs: 30,
prompt_tokens: 100,
completion_tokens: 50,
cached_tokens: 0,
context_tokens: 5000,
});
assert_eq!(state.iteration, 5);
// elapsed_secs is tracked by the UI-side timer, not set from Status event
}
#[test]
fn test_cursor_word_left_multibyte() {
let mut state = UiState::new();
// Reproduces the panic: cursor inside '웹' (3 bytes) after word-left on CJK input
state.input = "웹 관리자 대시보드 구현\n- 토큰, 암호 등 설정 관리, 정책 관리 ".to_string();
// Place cursor at end of first line (after '현', before '\n')
let first_line = "웹 관리자 대시보드 구현";
state.cursor = first_line.len(); // valid char boundary
// cursor_word_left must not panic and must land on a char boundary
state.cursor_word_left();
assert!(state.input.is_char_boundary(state.cursor));
state.cursor_word_left();
assert!(state.input.is_char_boundary(state.cursor));
// Keep going to start — must never panic
while state.cursor > 0 {
state.cursor_word_left();
assert!(state.input.is_char_boundary(state.cursor));
}
}
#[test]
fn test_cursor_word_right_multibyte() {
let mut state = UiState::new();
state.input = "웹 관리자 대시보드 구현".to_string();
state.cursor = 0;
// cursor_word_right must not panic and must land on a char boundary
while state.cursor < state.input.len() {
state.cursor_word_right();
assert!(state.input.is_char_boundary(state.cursor));
}
}
#[test]
fn test_handle_done() {
let mut state = UiState::new();
state.agent_busy = true;
state.streaming_buffer = "final response".to_string();
state.handle_done();
assert!(!state.agent_busy);
assert_eq!(state.status_msg, "Ready");
assert!(state.streaming_buffer.is_empty());
assert_eq!(state.messages.last().unwrap().role, MessageRole::Assistant);
}
}