forked from OpenCoven/coven-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.rs
More file actions
8198 lines (7671 loc) · 336 KB
/
Copy pathapp.rs
File metadata and controls
8198 lines (7671 loc) · 336 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
// app.rs — App state struct and main event loop.
use crate::bridge_state::BridgeConnectionState;
use crate::context_viz::ContextVizState;
use crate::dialog_select::{DialogSelectState, SelectItem};
use crate::dialogs::McpApprovalDialogState;
use crate::dialogs::PermissionRequest;
use crate::diff_viewer::{build_turn_diff, DiffViewerState};
use crate::export_dialog::{ExportDialogState, ExportFormat};
use crate::import_config_dialog::ImportConfigDialogState;
use crate::mcp_view::{McpServerView, McpToolView, McpViewState, McpViewStatus};
use crate::model_picker::{EffortLevel, ModelPickerState};
use crate::notifications::{NotificationKind, NotificationQueue};
use crate::overlays::{
GlobalSearchState, HelpEntry, HelpOverlay, HistorySearchOverlay, MessageSelectorOverlay,
RewindFlowOverlay, SelectorMessage,
};
use crate::plugin_views::PluginHintBanner;
use crate::prompt_input::{InputMode, PromptInputState, VimMode};
use crate::render;
use crate::session_browser::SessionBrowserState;
use crate::settings_screen::SettingsScreen;
use crate::stats_dialog::StatsDialogState;
use crate::tasks_overlay::TasksOverlay;
use crate::theme_screen::ThemeScreen;
use crate::{
agents_view::{AgentInfo, AgentStatus, AgentsMenuState, AgentsRoute},
diff_viewer::DiffPane,
};
use claurst_core::config::{Config, Settings, Theme};
use claurst_core::cost::CostTracker;
use claurst_core::file_history::FileHistory;
use claurst_core::keybindings::{
KeyContext, KeybindingResolver, KeybindingResult, ParsedKeystroke, UserKeybindings,
};
use claurst_core::types::{ContentBlock, Message, Role};
use claurst_core::{sample_completion_verb, sample_spinner_verb};
use claurst_query::QueryEvent;
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers, MouseEvent, MouseEventKind};
use ratatui::backend::CrosstermBackend;
use ratatui::style::Color;
use ratatui::Terminal;
use std::cell::{Cell, RefCell};
use std::io::Stdout;
use std::sync::{Arc, Mutex};
use tracing::debug;
/// Pairs of (name, one-line description) shown by the slash-command
/// autocompletion, /help overlay, and the command palette. Must stay in
/// sync with the non-hidden entries returned by
/// `claurst_commands::all_commands()`; the
/// `prompt_slash_commands_covers_registry` test in `claurst-commands`
/// enforces that.
pub const PROMPT_SLASH_COMMANDS: &[(&str, &str)] = &[
(
"accounts",
"List stored accounts; `dedupe` collapses duplicate profiles",
),
(
"attach",
"Save and manage file attachments in the structured stash",
),
("chrome", "Browser automation via Chrome DevTools Protocol"),
("clear", "Clear the conversation transcript"),
(
"commit",
"Stage and commit changes (model drafts the message)",
),
("compact", "Compact the conversation context"),
(
"config",
"Open settings (theme, keybindings, advisor, import, UI)",
),
("connect", "Connect an AI provider"),
(
"coven",
"Drive the local Coven daemon (sessions, harness runs, rituals)",
),
("diff", "Inspect the current git diff"),
(
"effort",
"Set effort level (low/normal/high) or toggle fast mode",
),
("exit", "Quit Coven Code"),
("export", "Export, copy, or share the conversation"),
(
"familiar",
"Your familiar & agents — switch persona, inspect, and manage",
),
("feedback", "Open session feedback survey"),
(
"handoff",
"Hand off current session context to a Coven familiar",
),
("help", "Show help"),
("hooks", "Browse configured hooks (read-only)"),
(
"incant",
"Cast a speech incantation (caveman, rocky) or lift it with off",
),
("init", "Initialize AGENTS.md for this project"),
(
"learn",
"Codify the script/workflow we just built into a reusable skill",
),
("link", "Save and manage links in the structured stash"),
("login", "Log in, switch accounts, or refresh provider auth"),
("logout", "Log out of Coven Code"),
("mcp", "Browse configured MCP servers"),
("memory", "Browse and open AGENTS.md memory files"),
("model", "Change the AI model"),
("permissions", "Manage tool permission rules"),
("plan", "Enter plan mode (read-only)"),
(
"plugin",
"Manage plugins (list/info/enable/disable/install/reload)",
),
("providers", "List available AI providers and their status"),
("quit", "Exit Coven Code"),
("resume", "Resume a previous session"),
(
"review",
"Review changes (security/ultra variants, PR comments)",
),
(
"rewind",
"Rewind the conversation or roll back file changes",
),
("sandbox", "Toggle sandboxed shell execution"),
("search", "Search the codebase by natural language or regex"),
(
"splash",
"Show, hide, or toggle the empty-session splash screen",
),
("session", "Browse, rename, fork, branch, and tag sessions"),
(
"settings",
"Open settings (theme, keybindings, advisor, import, UI)",
),
("skills", "List and manage skills"),
(
"status",
"Show session status or run diagnostics (/status doctor)",
),
#[cfg(feature = "steer")]
(
"steer",
"Queue a steering message for the running turn (or send it now if idle)",
),
("survey", "Open session feedback survey"),
("tasks", "Manage tracked background tasks"),
(
"thinking",
"Configure extended thinking or view past thinking traces",
),
(
"update",
"Check for updates and upgrade to the latest version",
),
("release-notes", "Show recent Coven Code highlights"),
("usage", "Detailed per-call token usage breakdown"),
("version", "Display the current Coven Code version"),
(
"whisper",
"Whisper a side question to your familiar (not kept in history)",
),
];
/// Canonical category for a slash command. Single source of truth shared by
/// the F1 help overlay, the command palette, and the `/help` text output in
/// `claurst-commands` (which delegates here) so every surface groups
/// commands the same way.
pub fn slash_command_category(name: &str) -> &'static str {
match name {
"clear" | "compact" | "rewind" | "undo" | "revert" | "export" | "branch" | "fork" => {
"Conversation"
}
"model" | "config" | "settings" | "theme" | "color" | "vim" | "fast" | "effort"
| "voice" | "statusline" | "output-style" | "keybindings" | "splash" | "sandbox" => {
"Settings"
}
"cost" | "usage" | "context" | "stats" => "Usage & Cost",
"status" | "doctor" | "terminal-setup" | "version" | "update" | "upgrade" => "System",
"login" | "logout" | "switch" | "refresh" | "permissions" | "connect" | "providers" => {
"Auth & Permissions"
}
"memory" | "diff" | "init" | "commit" | "review" | "import-config" | "security-review" => {
"Project"
}
"mcp" | "hooks" | "chrome" => "Integrations",
"session" | "resume" | "search" | "share" | "rename" => "Sessions & Remote",
"help" | "exit" | "quit" | "feedback" | "survey" | "bug" => "General",
"think-back" | "thinking" | "plan" | "goal" | "tasks" | "advisor" => "AI & Thinking",
"copy" | "skills" | "learn" | "plugin" | "reload-plugins" | "whisper" | "incant" => {
"Tools & Extras"
}
"coven" | "familiar" | "familiars" | "handoff" => "Coven",
_ => "Other",
}
}
fn help_overlay_entries() -> Vec<HelpEntry> {
PROMPT_SLASH_COMMANDS
.iter()
.map(|(name, description)| HelpEntry {
name: (*name).to_string(),
aliases: String::new(),
description: (*description).to_string(),
category: slash_command_category(name).to_string(),
})
.collect()
}
// ---------------------------------------------------------------------------
// Voice mode bootstrap
// ---------------------------------------------------------------------------
/// `true` when the launcher should treat voice mode as opted out for this
/// run regardless of what `ui-settings.json` says. Set
/// `COVEN_CODE_VOICE=0` (or `false`) to disable voice without editing the
/// stored UI settings — useful when the persistent flag has been turned on
/// and the user wants a one-shot launch where slash-command keystrokes
/// aren't routed through the voice pipeline.
pub(crate) fn voice_explicitly_disabled() -> bool {
matches!(
std::env::var("COVEN_CODE_VOICE").as_deref(),
Ok("0") | Ok("false")
)
}
/// Resolve the voice recorder Arc for this `App` instance.
///
/// Returns `Some(recorder)` only when voice mode is opted in via:
/// * `COVEN_CODE_VOICE_ENABLED=1` (per-launch override), OR
/// * `voice_enabled: true` in `~/.coven-code/ui-settings.json`
///
/// `COVEN_CODE_VOICE=0` (or `=false`) hard-overrides the persistent
/// setting and forces the recorder to `None` for the launch.
fn voice_recorder_from_env_and_settings(
) -> Option<std::sync::Arc<std::sync::Mutex<claurst_core::voice::VoiceRecorder>>> {
if voice_explicitly_disabled() {
return None;
}
let voice_on = std::env::var("COVEN_CODE_VOICE_ENABLED")
.map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
.unwrap_or(false)
|| {
let path = claurst_core::config::Settings::config_dir().join("ui-settings.json");
std::fs::read_to_string(&path)
.ok()
.and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
.and_then(|v| v["voice_enabled"].as_bool())
.unwrap_or(false)
};
if !voice_on {
return None;
}
let recorder = claurst_core::voice::global_voice_recorder();
if let Ok(mut r) = recorder.lock() {
r.set_enabled(true);
}
Some(recorder)
}
#[cfg(test)]
pub(crate) mod test_env {
use std::path::{Path, PathBuf};
use std::sync::{Mutex, MutexGuard};
static ENV_LOCK: Mutex<()> = Mutex::new(());
pub(crate) struct EnvGuard {
old_home: Option<String>,
old_coven_home: Option<String>,
old_anthropic_config_dir: Option<String>,
old_anthropic_api_key: Option<String>,
old_oauth_client_id: Option<String>,
old_claude_bin: Option<String>,
old_user: Option<String>,
old_username: Option<String>,
_lock: MutexGuard<'static, ()>,
}
impl EnvGuard {
pub(crate) fn set(home: &Path, coven_home: &Path) -> Self {
Self::set_with_user(home, coven_home, None)
}
pub(crate) fn set_with_user(home: &Path, coven_home: &Path, user: Option<&str>) -> Self {
let lock = ENV_LOCK.lock().unwrap_or_else(|err| err.into_inner());
let guard = Self {
old_home: std::env::var("HOME").ok(),
old_coven_home: std::env::var("COVEN_HOME").ok(),
old_anthropic_config_dir: std::env::var("ANTHROPIC_CONFIG_DIR").ok(),
old_anthropic_api_key: std::env::var("ANTHROPIC_API_KEY").ok(),
old_oauth_client_id: std::env::var(claurst_core::oauth::CLIENT_ID_ENV).ok(),
old_claude_bin: std::env::var(claurst_api::providers::claude_cli::CLAUDE_BIN_ENV)
.ok(),
old_user: std::env::var("USER").ok(),
old_username: std::env::var("USERNAME").ok(),
_lock: lock,
};
std::env::set_var("HOME", PathBuf::from(home));
std::env::set_var("COVEN_HOME", PathBuf::from(coven_home));
std::env::remove_var("ANTHROPIC_CONFIG_DIR");
std::env::remove_var("ANTHROPIC_API_KEY");
std::env::remove_var(claurst_core::oauth::CLIENT_ID_ENV);
std::env::remove_var(claurst_api::providers::claude_cli::CLAUDE_BIN_ENV);
match user {
Some(value) => std::env::set_var("USER", value),
None => std::env::remove_var("USER"),
}
std::env::remove_var("USERNAME");
// COVEN_HOME changed — drop any roster cached from the old home.
crate::coven_status::invalidate_roster_cache();
guard
}
}
impl Drop for EnvGuard {
fn drop(&mut self) {
match &self.old_home {
Some(value) => std::env::set_var("HOME", value),
None => std::env::remove_var("HOME"),
}
match &self.old_coven_home {
Some(value) => std::env::set_var("COVEN_HOME", value),
None => std::env::remove_var("COVEN_HOME"),
}
match &self.old_anthropic_config_dir {
Some(value) => std::env::set_var("ANTHROPIC_CONFIG_DIR", value),
None => std::env::remove_var("ANTHROPIC_CONFIG_DIR"),
}
match &self.old_anthropic_api_key {
Some(value) => std::env::set_var("ANTHROPIC_API_KEY", value),
None => std::env::remove_var("ANTHROPIC_API_KEY"),
}
match &self.old_oauth_client_id {
Some(value) => std::env::set_var(claurst_core::oauth::CLIENT_ID_ENV, value),
None => std::env::remove_var(claurst_core::oauth::CLIENT_ID_ENV),
}
match &self.old_claude_bin {
Some(value) => {
std::env::set_var(claurst_api::providers::claude_cli::CLAUDE_BIN_ENV, value)
}
None => std::env::remove_var(claurst_api::providers::claude_cli::CLAUDE_BIN_ENV),
}
match &self.old_user {
Some(value) => std::env::set_var("USER", value),
None => std::env::remove_var("USER"),
}
match &self.old_username {
Some(value) => std::env::set_var("USERNAME", value),
None => std::env::remove_var("USERNAME"),
}
// COVEN_HOME restored — drop any roster cached from the temp home.
crate::coven_status::invalidate_roster_cache();
}
}
}
// ---------------------------------------------------------------------------
// Provider connection helpers
// ---------------------------------------------------------------------------
/// Return the environment variable name for a given provider ID.
#[allow(dead_code)]
fn get_env_var_for_provider(id: &str) -> &'static str {
match id {
"anthropic" => "ANTHROPIC_API_KEY",
_ => "API_KEY",
}
}
/// Return a URL hint for obtaining an API key from a given provider.
#[allow(dead_code)]
fn get_url_for_provider(id: &str) -> &'static str {
match id {
"anthropic" => "console.anthropic.com",
_ => "the provider's website",
}
}
fn import_config_picker_items() -> Vec<SelectItem> {
vec![
SelectItem {
id: "claude-md".into(),
title: "CLAUDE.md".into(),
description: "Import ~/.claude/CLAUDE.md".into(),
category: "Import".into(),
badge: None,
},
SelectItem {
id: "settings".into(),
title: "settings.json".into(),
description: "Import ~/.claude/settings.json".into(),
category: "Import".into(),
badge: None,
},
SelectItem {
id: "both".into(),
title: "Both".into(),
description: "Import both CLAUDE.md and settings.json".into(),
category: "Import".into(),
badge: None,
},
]
}
fn provider_picker_items() -> Vec<SelectItem> {
let has_claude_cli = claurst_api::providers::claude_cli::resolve_claude_binary().is_some();
vec![
SelectItem {
id: "anthropic-cli".into(),
title: "Claude CLI".into(),
description: "Run turns through the local claude binary; auth stays in Claude Code"
.into(),
category: "Claude".into(),
badge: has_claude_cli.then(|| "LOCAL".into()),
},
SelectItem {
id: "openai-codex".into(),
title: "Codex CLI".into(),
description: "Sign in with Codex CLI login".into(),
category: "Codex".into(),
badge: None,
},
]
}
// ---------------------------------------------------------------------------
// Supporting types
// ---------------------------------------------------------------------------
/// Visual style for inline system messages in the conversation pane.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SystemMessageStyle {
Info,
Warning,
/// Compact / auto-compact boundary marker.
Compact,
}
/// A synthetic system annotation inserted between conversation messages.
/// `after_index` is the index in `App::messages` after which this annotation
/// should appear (0 = before all messages, 1 = after message 0, etc.).
#[derive(Debug, Clone)]
pub struct SystemAnnotation {
pub after_index: usize,
pub text: String,
pub style: SystemMessageStyle,
}
/// A displayable item in the conversation pane — either a real message or
/// a synthetic system annotation (e.g. compact boundary).
/// Used only by `render.rs`; constructed on the fly from `messages` +
/// `system_annotations`.
#[derive(Debug, Clone)]
pub enum DisplayMessage {
/// A real conversation turn.
Conversation(Message),
/// An injected system notice (e.g. compact boundary).
System {
text: String,
style: SystemMessageStyle,
},
}
/// Context menu state: position and currently selected item index.
#[derive(Debug, Clone, Copy)]
pub struct ContextMenuState {
/// X coordinate of the menu (column).
pub x: u16,
/// Y coordinate of the menu (row).
pub y: u16,
/// Currently selected menu item index (0-based).
pub selected_index: usize,
/// What the context menu is acting on.
pub kind: ContextMenuKind,
}
/// What content the context menu is currently targeting.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContextMenuKind {
/// A specific transcript message.
Message { message_index: usize },
/// The current text selection anywhere in the frame.
Selection,
}
/// Available context menu items.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContextMenuItem {
Copy,
Fork,
}
/// State for the Go to Line dialog (Ctrl+G in message pane).
#[derive(Debug, Clone)]
pub struct GoToLineDialog {
/// Input field for line number.
pub input: String,
/// Whether the dialog is currently active.
pub active: bool,
/// Total number of lines (for validation feedback).
pub total_lines: usize,
}
impl GoToLineDialog {
pub fn new() -> Self {
Self {
input: String::new(),
active: false,
total_lines: 0,
}
}
pub fn open(&mut self, total_lines: usize) {
self.input.clear();
self.active = true;
self.total_lines = total_lines;
}
pub fn close(&mut self) {
self.active = false;
self.input.clear();
}
/// Parse the input as a line number (1-indexed).
/// Returns None if invalid or out of range.
pub fn parse_line_number(&self) -> Option<usize> {
let line_num: usize = self.input.trim().parse().ok()?;
if line_num >= 1 && line_num <= self.total_lines {
Some(line_num)
} else {
None
}
}
}
impl Default for GoToLineDialog {
fn default() -> Self {
Self::new()
}
}
/// Status of an active or completed tool call.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolStatus {
Running,
Done,
Error,
}
/// Represents an active or completed tool invocation visible in the UI.
#[derive(Debug, Clone)]
pub struct ToolUseBlock {
pub id: String,
pub name: String,
pub turn_index: Option<usize>,
pub status: ToolStatus,
pub output_preview: Option<String>,
/// JSON-serialised input for the tool call (populated from the API stream).
pub input_json: String,
}
#[derive(Debug, Clone, Default)]
pub struct TurnMetadata {
pub submitted_at: Option<String>,
pub model_name: Option<String>,
pub agent_mode: Option<String>,
pub duration: Option<String>,
pub interrupted: bool,
}
/// Attempt to copy text to the system clipboard using trusted platform clipboard helpers.
/// Returns true if successful.
pub fn try_copy_to_clipboard(text: &str) -> bool {
crate::image_paste::write_clipboard_text(text)
}
/// Map a character to its QWERTY Latin keyboard-position equivalent.
///
/// When a modifier key (Ctrl, Alt) is held together with a non-ASCII character
/// (e.g. Cyrillic С on a Ukrainian/Russian layout), the char produced by
/// crossterm is the non-Latin glyph rather than the Latin letter that occupies
/// the same physical key. Keybinding strings are always written as Latin
/// letters (`ctrl+c`, `alt+b`, …), so the lookup fails.
///
/// This function converts the reported character to the Latin letter that sits
/// at the same physical QWERTY position, covering the standard Russian JCUKEN
/// and Ukrainian layouts which share the same physical-key→Latin mapping.
/// For characters outside any known mapping the original (lowercased) char is
/// returned unchanged — this is always safe since unrecognised chars just
/// produce no keybinding match.
fn layout_to_latin(c: char) -> String {
// Standard Russian/Ukrainian JCUKEN → QWERTY position mapping.
// Both upper- and lower-case Cyrillic variants are covered by
// converting to lowercase first.
let lower = c.to_lowercase().next().unwrap_or(c);
let mapped: Option<char> = match lower {
// Row 1
'й' => Some('q'),
'ц' => Some('w'),
'у' => Some('e'),
'к' => Some('r'),
'е' => Some('t'),
'н' => Some('y'),
'г' => Some('u'),
'ш' => Some('i'),
'щ' => Some('o'),
'з' => Some('p'),
// Row 2
'ф' => Some('a'),
'ы' => Some('s'),
'в' => Some('d'),
'а' => Some('f'),
'п' => Some('g'),
'р' => Some('h'),
'о' => Some('j'),
'л' => Some('k'),
'д' => Some('l'),
// Row 3
'я' => Some('z'),
'ч' => Some('x'),
'с' => Some('c'),
'м' => Some('v'),
'и' => Some('b'),
'т' => Some('n'),
'ь' => Some('m'),
// Ukrainian-specific letters on standard positions
'і' => Some('s'),
'ї' => Some(']'),
'є' => Some('\''),
_ => None,
};
mapped.unwrap_or(lower).to_string()
}
/// Apply shift transformation to a character based on standard US QWERTY layout.
/// Handles both ASCII lowercase letters and number/symbol keys.
///
/// **Why this exists**: Terminals that support the kitty keyboard protocol send
/// unshifted characters with modifier flags instead of pre-shifted characters
/// (e.g., Shift+1 arrives as '1' + SHIFT instead of '!'). This function normalizes
/// them to the expected shifted characters.
///
/// **Keyboard layout limitation**: This only works correctly for US QWERTY keyboards.
/// Other layouts (AZERTY, QWERTZ, etc.) have different shift mappings. For non-US
/// layouts, we rely on the terminal to send the correctly shifted character, which
/// most modern terminals do (especially with kitty protocol enabled).
fn normalize_char_with_shift(c: char, modifiers: KeyModifiers) -> char {
if !modifiers.contains(KeyModifiers::SHIFT) {
return c;
}
if c.is_ascii_lowercase() {
return c.to_ascii_uppercase();
}
// Map unshifted number/symbol keys to their shifted equivalents (US QWERTY)
match c {
'1' => '!',
'2' => '@',
'3' => '#',
'4' => '$',
'5' => '%',
'6' => '^',
'7' => '&',
'8' => '*',
'9' => '(',
'0' => ')',
'-' => '_',
'=' => '+',
'[' => '{',
']' => '}',
';' => ':',
'\'' => '"',
',' => '<',
'.' => '>',
'/' => '?',
'\\' => '|',
'`' => '~',
_ => c,
}
}
fn key_event_to_keystroke(key: &KeyEvent) -> Option<ParsedKeystroke> {
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
let alt = key.modifiers.contains(KeyModifiers::ALT);
let normalized_key = match key.code {
KeyCode::Backspace => "backspace".to_string(),
KeyCode::Delete => "delete".to_string(),
KeyCode::Down => "down".to_string(),
KeyCode::End => "end".to_string(),
KeyCode::Enter => "enter".to_string(),
KeyCode::Esc => "escape".to_string(),
KeyCode::Home => "home".to_string(),
KeyCode::Left => "left".to_string(),
KeyCode::PageDown => "pagedown".to_string(),
KeyCode::PageUp => "pageup".to_string(),
KeyCode::Right => "right".to_string(),
KeyCode::Tab => "tab".to_string(),
KeyCode::Up => "up".to_string(),
KeyCode::BackTab => "tab".to_string(),
KeyCode::Char(' ') => "space".to_string(),
KeyCode::Char(c) => {
// For modifier-key combos (Ctrl/Alt + letter), normalize to the
// ASCII Latin key at the same physical QWERTY position. This
// makes shortcuts like Ctrl+C work regardless of the active
// keyboard layout (Ukrainian, Russian, Greek, …).
if (ctrl || alt) && !c.is_ascii() {
layout_to_latin(c)
} else {
c.to_lowercase().to_string()
}
}
_ => return None,
};
Some(ParsedKeystroke {
key: normalized_key,
ctrl,
alt,
shift: key.modifiers.contains(KeyModifiers::SHIFT),
meta: key.modifiers.contains(KeyModifiers::SUPER),
})
}
// ---------------------------------------------------------------------------
// Focus target
// ---------------------------------------------------------------------------
/// Which area of the TUI currently has keyboard focus.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FocusTarget {
/// Keyboard input goes to the prompt editor.
Input,
/// Keyboard input goes to the transcript/message pane (scroll, etc.).
Transcript,
}
// ---------------------------------------------------------------------------
// App struct
// ---------------------------------------------------------------------------
/// The top-level TUI application.
pub struct App {
// Core state
pub config: Config,
pub cost_tracker: Arc<CostTracker>,
pub messages: Vec<Message>,
/// Combined display list kept in sync with `messages`: real conversation turns
/// plus injected system annotations. Used by the renderer so it can iterate
/// a single sequence instead of merging two lists on every frame.
pub display_messages: Vec<DisplayMessage>,
/// Synthetic system annotations interleaved between real messages at render time.
pub system_annotations: Vec<SystemAnnotation>,
pub input: String,
pub prompt_input: PromptInputState,
pub input_history: Vec<String>,
pub history_index: Option<usize>,
pub scroll_offset: usize,
pub is_streaming: bool,
pub streaming_text: String,
pub streaming_thinking: String,
pub status_message: Option<String>,
/// Randomly chosen thinking verb shown next to the spinner while streaming.
pub spinner_verb: Option<String>,
pub should_exit: bool,
// Extended state
pub tool_use_blocks: Vec<ToolUseBlock>,
pub permission_request: Option<PermissionRequest>,
pub frame_count: u64,
pub token_count: u32,
/// Maximum token budget (from env var or model context window) — P2 feature flag
pub token_budget: Option<u32>,
pub cost_usd: f64,
pub model_name: String,
/// Whether the app has valid API credentials configured.
/// False = show the in-TUI provider setup dialog on startup.
pub has_credentials: bool,
/// Current effort level (controls extended-thinking budget_tokens).
pub effort_level: EffortLevel,
/// Whether the user has explicitly chosen an effort level (via the model
/// picker, the `/effort` dialog, or the `/effort` command). When false the
/// query layer leaves effort unset so the model uses its own default; when
/// true `effort_level` is the single source of truth and is forwarded to
/// every turn. Without this flag, picker/dialog selections were silently
/// dropped — only the `/effort` command reached the API.
pub effort_is_set: bool,
/// Whether fast mode is currently active (model locked to FAST_MODE_MODEL).
pub fast_mode: bool,
/// Active speech mode: None = normal, Some("caveman") / Some("rocky").
pub speech_mode: Option<String>,
/// Speech mode intensity: "lite", "full", "ultra".
pub speech_level: String,
/// Current agent mode name: "build", "plan", "explore", etc.
pub agent_mode: Option<String>,
/// Accent color derived from the current agent mode.
/// Build = pink, Plan = blue, Explore = amber.
pub accent_color: Color,
/// Set by `cycle_agent_mode` so the main loop can update the query config
/// and tool list to match the newly-selected agent.
pub agent_mode_changed: bool,
pub agent_status: Vec<(String, String)>,
pub keybindings: KeybindingResolver,
// Cursor position within input (byte offset)
pub cursor_pos: usize,
// ---- Scrollback / auto-scroll -----------------------------------------
/// When `true`, the message pane follows the latest messages automatically.
pub auto_scroll: bool,
/// Count of messages that arrived while the user was scrolled up.
pub new_messages_while_scrolled: usize,
// ---- Token warning tracking -------------------------------------------
/// Which threshold (0 = none, 80, 95, 100) was last notified so we only
/// show each banner once.
pub token_warning_threshold_shown: u8,
// ---- Session timing ---------------------------------------------------
/// Instant the session started (used for elapsed-time in the status bar).
pub session_start: std::time::Instant,
/// Current familiar pose for rendering. `Static` when idle; `Loading {
/// frame }` while streaming has stalled long enough to surface a spinner.
/// The glyph itself never walks or blinks.
pub companion_current_pose: crate::mascot::CompanionPose,
/// Instant the current turn's streaming began (reset each time streaming starts).
pub turn_start: Option<std::time::Instant>,
/// Elapsed time string for the last completed turn, e.g. "2m 5s".
pub last_turn_elapsed: Option<String>,
/// Past-tense verb shown after turn completes, e.g. "Worked" / "Baked".
pub last_turn_verb: Option<&'static str>,
/// Per-user turn snapshots used by the transcript renderer.
pub turn_metadata: Vec<TurnMetadata>,
/// Incremented whenever transcript-visible state changes so rendering can
/// reuse cached layout between keystrokes.
pub transcript_version: Cell<u64>,
// ---- New overlay / notification fields --------------------------------
/// Full-screen help overlay (? / F1).
pub help_overlay: HelpOverlay,
/// Ctrl+R history search overlay.
pub history_search_overlay: HistorySearchOverlay,
/// Global ripgrep search / quick-open overlay.
pub global_search: GlobalSearchState,
/// Message selector used by /rewind.
pub message_selector: MessageSelectorOverlay,
/// Multi-step rewind flow overlay.
pub rewind_flow: RewindFlowOverlay,
/// Bridge connection state.
pub bridge_state: BridgeConnectionState,
/// Active notification queue.
pub notifications: NotificationQueue,
/// Scroll offset for error modal text (in lines).
pub error_modal_scroll_offset: usize,
/// Interactive rate-limit recovery modal (auto-retry countdown, one-key
/// tier switch, duplicate-account cleanup).
pub rate_limit_recovery: crate::rate_limit_recovery::RateLimitRecoveryState,
/// Plugin hint banners.
pub plugin_hints: Vec<PluginHintBanner>,
/// Optional session title shown in the status bar.
pub session_title: Option<String>,
/// Remote session URL (set when bridge connects; readable by commands).
pub remote_session_url: Option<String>,
/// Live MCP manager snapshot source when available.
pub mcp_manager: Option<Arc<claurst_mcp::McpManager>>,
/// Queued request for a real MCP reconnect from the interactive loop.
pub pending_mcp_reconnect: bool,
/// Pending MCP panel-auth request for the interactive loop.
pub pending_mcp_panel_auth: Option<String>,
/// Shared file-history service used for turn diff reconstruction.
pub file_history: Option<Arc<parking_lot::Mutex<FileHistory>>>,
/// Shared query-loop turn counter for turn-local diff reconstruction.
pub current_turn: Option<Arc<std::sync::atomic::AtomicUsize>>,
// ---- Visual mode indicators -------------------------------------------
/// Plan mode — input border turns blue, [PLAN] shown in status bar.
pub plan_mode: bool,
/// "While you were away" summary text shown on the welcome screen.
pub away_summary: Option<String>,
/// When streaming stalled (used to turn the spinner red after 3 s).
pub stall_start: Option<std::time::Instant>,
// ---- Settings / theme / privacy screens --------------------------------
/// Full-screen tabbed settings screen (/config, /settings).
pub settings_screen: SettingsScreen,
/// Theme picker overlay (/theme).
pub theme_screen: ThemeScreen,
/// Token/cost analytics dialog.
pub stats_dialog: StatsDialogState,
/// MCP server browser and tool detail view.
pub mcp_view: McpViewState,
/// Agent definitions and active agent status overlay.
pub agents_menu: AgentsMenuState,
/// Diff viewer overlay.
pub diff_viewer: DiffViewerState,
/// Session-quality feedback survey overlay.
pub feedback_survey: crate::feedback_survey::FeedbackSurveyState,
/// Memory file selector overlay (AGENTS.md browser).
pub memory_file_selector: crate::memory_file_selector::MemoryFileSelectorState,
/// Read-only hooks configuration browser.
pub hooks_config_menu: crate::hooks_config_menu::HooksConfigMenuState,
/// Overage credit upsell banner.
pub overage_upsell: crate::overage_upsell::OverageCreditUpsellState,
/// Voice mode availability notice.
pub voice_mode_notice: crate::voice_mode_notice::VoiceModeNoticeState,
/// Startup error dialog for malformed settings.json or AGENTS.md.
pub invalid_config_dialog: crate::invalid_config_dialog::InvalidConfigDialogState,
/// Memory update notification banner.
pub memory_update_notification:
crate::memory_update_notification::MemoryUpdateNotificationState,
/// MCP elicitation dialog (form requested by an MCP server).
pub elicitation: crate::elicitation_dialog::ElicitationDialogState,
/// Model picker overlay (/model command).
pub model_picker: ModelPickerState,
/// Session browser overlay (/session, /resume, /rename, /export).
pub session_browser: SessionBrowserState,
/// Session branching overlay (Ctrl+B) — create and switch branches.
pub session_branching: crate::session_branching::SessionBranchingState,
/// Task progress overlay (Ctrl+T) — shows task status with toggle capability.
pub tasks_overlay: TasksOverlay,
/// Export format picker dialog (/export).
pub export_dialog: ExportDialogState,
/// Context window / rate limit visualization overlay (/context).
pub context_viz: ContextVizState,
/// MCP server approval dialog.
pub mcp_approval: McpApprovalDialogState,
/// Go to Line dialog (Ctrl+G in message pane).
pub go_to_line_dialog: GoToLineDialog,
/// Bypass-permissions startup confirmation dialog.
/// Shown at startup when --dangerously-skip-permissions was passed.
/// User must explicitly accept or the session exits.
pub bypass_permissions_dialog: crate::bypass_permissions_dialog::BypassPermissionsDialogState,
/// Whether the bypass-permissions dialog has been shown this session.
pub bypass_permissions_dialog_shown: bool,
/// File injection warning dialog.
/// Shown when oversized or binary files are detected in @refs.
pub file_injection_dialog: crate::file_injection_dialog::FileInjectionDialogState,
/// When true, the next file injection size check uses limit 0 (no limit),
/// letting files that were "allowed" through the warning dialog be injected.
pub file_injection_force: bool,
/// First-launch onboarding welcome dialog.
pub onboarding_dialog: crate::onboarding_dialog::OnboardingDialogState,
/// Effort-level picker (/effort with no args).
pub effort_picker: crate::effort_picker::EffortPickerState,
/// Interactive skills picker (/skills).
pub skills_picker: crate::skills_picker::SkillsPickerState,
/// API key input dialog (opened from /connect for key-based providers).
pub key_input_dialog: crate::key_input_dialog::KeyInputDialogState,
/// Device code / browser auth dialog (Claude OAuth, Codex login).
pub device_auth_dialog: crate::device_auth_dialog::DeviceAuthDialogState,
/// When set, the main loop should spawn the async auth task for this provider.
pub device_auth_pending: Option<String>,
/// When true, the main loop should rebuild the provider runtime from disk
/// (same as `/refresh`) so newly-established credentials take effect live.
pub pending_provider_refresh: bool,
/// Shared provider registry for dynamic model fetching.
pub provider_registry: Option<std::sync::Arc<claurst_api::ProviderRegistry>>,
/// Model registry populated from models.dev — single source of truth for
/// all provider models shown in the `/model` picker.
pub model_registry: claurst_api::ModelRegistry,
/// When `true`, the main event loop should spawn an async task to fetch
/// the model list from the current provider's `list_models()` API.
pub model_picker_fetch_pending: bool,
/// The provider ID that the model picker was opened for (used when the
/// fetch is triggered from /connect before the provider is activated).
pub model_picker_provider_id: Option<String>,
/// When `true`, the main event loop should spawn an async task to load
/// the session list from disk and populate the session browser.
pub session_list_pending: bool,
/// Receiver for background session-list results.
pub session_list_rx:
Option<tokio::sync::mpsc::Receiver<Vec<crate::session_browser::SessionEntry>>>,
/// Credential store for provider API keys and OAuth tokens.
pub auth_store: claurst_core::AuthStore,
/// Messages typed by the user while a query was streaming. They will be
/// auto-submitted in order once the current turn completes (issue #149).
pub queued_messages: std::collections::VecDeque<String>,
/// When `true`, the main loop will inject a synthetic Enter event on the
/// next iteration to dequeue and submit the next queued message.
pub pending_auto_submit: bool,
/// Connect-a-provider dialog (/connect command).
pub connect_dialog: DialogSelectState,
/// Import-config source picker (/import-config command).
pub import_config_picker: DialogSelectState,
/// Import-config preview and confirmation dialog.
pub import_config_dialog: ImportConfigDialogState,
/// Ctrl+K command palette overlay.
pub command_palette: DialogSelectState,
/// Whether Coven Code was launched from the user's home directory.
/// Shown as a startup notice: "Note: You have launched Coven Code in your home directory…"
pub home_dir_warning: bool,
/// Output style: "auto" | "stream" | "verbose".
pub output_style: String,
/// PR number for the current branch (None if not in a PR context).