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
use anyhow::Result;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use crate::agent::checkpoint::CheckpointManager;
use crate::agent::context::ConversationContext;
use crate::agent::hooks::HooksConfig;
use crate::agent::r#loop::AgentEvent;
use crate::agent::session::SessionStore;
use crate::api::provider::OpenAiCompatibleProvider;
use crate::config::Config;
use crate::repo_map::RepoMap;
use crate::trust::TrustLevel;
use crate::tui::event::{self};
use crate::tui::goodbye::{self, ExitSummary};
use crate::tui::state::UiState;
use crate::tui::terminal::{self};
pub struct App {
config: Config,
client: OpenAiCompatibleProvider,
context: Option<ConversationContext>,
/// Backup of last known good context (kept while agent is running).
last_context_backup: Option<ConversationContext>,
state: UiState,
working_dir: String,
repo_map: RepoMap,
/// Cancellation token for the currently running agent task.
cancel_token: Option<CancellationToken>,
/// Input history for arrow-key navigation.
input_history: Vec<String>,
/// Current position in input history.
history_index: Option<usize>,
/// Saved current input when navigating history.
saved_input: String,
/// Whether repo map needs rebuilding (files were modified).
repo_map_dirty: bool,
/// Receiver for the background repo map initial build.
/// `None` once the build is complete and the map has been applied.
repo_map_receiver: Option<tokio::sync::oneshot::Receiver<crate::repo_map::RepoMap>>,
/// Receiver for a background incremental repo map rebuild triggered at submit time.
/// Polled each frame; applied as soon as it's ready (before or after agent starts).
repo_map_rebuild_rx: Option<tokio::sync::oneshot::Receiver<crate::repo_map::RepoMap>>,
/// Receiver for a background `git diff` spawned on sidebar file click.
/// Polled each frame; when ready, opens the diff popup without blocking the UI.
pending_diff_rx: Option<(String, tokio::sync::oneshot::Receiver<Option<String>>)>,
/// Session store for persistence.
session_store: SessionStore,
/// Current session ID.
session_id: String,
/// Whether auto model routing is enabled.
auto_route: bool,
/// Post-edit hooks configuration.
hooks_config: HooksConfig,
/// Files modified during current agent run (accumulated from FileModified events).
modified_files: Vec<String>,
/// File checkpoint manager for /rewind support.
checkpoint_mgr: CheckpointManager,
/// Current agent index for Tab/Shift+Tab switching.
current_agent_index: usize,
/// Whether first Esc was pressed (waiting for second Esc to cancel).
esc_pending: bool,
/// When the first Esc was pressed (for timeout).
esc_pending_at: Option<std::time::Instant>,
/// When the current agent task started (for real-time elapsed display).
agent_busy_since: Option<std::time::Instant>,
/// Message deferred while the ModeApproval popup is shown.
pending_mode_approval_msg: Option<String>,
/// Per-dispatch collaboration mode set by Arbor auto-routing.
/// Takes priority over session_collab_mode for one dispatch, then resets.
arbor_dispatch_mode: Option<crate::agent::swarm::config::CollaborationMode>,
/// Queue of messages waiting to be processed after current agent finishes.
message_queue: std::collections::VecDeque<String>,
/// Set to true when the user explicitly cancels a running agent.
was_cancelled: bool,
/// Task text of the currently running agent (set at submit time).
current_task: String,
/// Cumulative token snapshot taken when the current task started.
task_start_tokens_in: u64,
task_start_tokens_out: u64,
task_start_api_calls: u32,
/// tool_log length snapshot taken when the current task started.
task_start_tool_count: usize,
/// Compaction count snapshot taken when the current task started.
task_start_compactions: usize,
/// LSP manager for code quality integration.
lsp_manager: crate::lsp::manager::LspManager,
/// Trust level for the current project directory.
trust_level: TrustLevel,
/// If true, open the session resume popup immediately on startup.
pub open_resume_popup: bool,
/// Per-session collaboration mode override (None = use config default, not persisted).
session_collab_mode: Option<crate::agent::swarm::config::CollaborationMode>,
/// Process metrics collector for debug mode (None when debug_mode is off).
metrics_collector: Option<crate::util::process_metrics::MetricsCollector>,
/// Cached MCP child process PIDs (received via AgentEvent::McpPids).
mcp_pids: Vec<u32>,
/// Hidden prompt to send to LLM instead of the visible user input.
/// Used by /init and similar commands to hide verbose prompts from the UI.
hidden_prompt: Option<String>,
/// Pending input deferred by PII warning popup (input, event_tx).
pending_pii_input: Option<(String, tokio::sync::mpsc::UnboundedSender<AgentEvent>)>,
/// Queue of missing LSP servers to prompt installation for, one at a time.
/// Each entry: (language_id, server_command, install_hint).
pending_lsp_installs: Vec<(String, String, String)>,
/// Whether the auto-optimizer has already fired this session (ctx≥40% trigger).
optimizer_auto_triggered: bool,
/// Shared approval mode for tool execution (runtime-switchable via Alt+Y).
approve_mode: crate::agent::approval::SharedApproveMode,
/// Number of auto-continuation rounds completed for the current task.
continuation_count: u32,
/// Session-scoped approval cache shared across all agents (main + hive).
session_approvals: crate::agent::approval::SessionApprovals,
/// Receiver end of the approval request channel (kept alive while agent runs).
approval_req_rx:
Option<tokio::sync::mpsc::UnboundedReceiver<crate::agent::approval::ApprovalRequest>>,
/// Pending approval response channel — set when a ToolApproval popup is shown.
pending_approval_tx:
Option<tokio::sync::oneshot::Sender<crate::agent::approval::ApprovalResponse>>,
/// Timestamp of last Tab press for double-tap detection.
last_tab_at: Option<std::time::Instant>,
/// Smooth-scroll target (scroll_offset animates toward this each frame).
scroll_target: u16,
/// Queued SwarmDone result from a background Hive/Flock coordinator.
/// When `SwarmWorkersDispatched` fires, the user is released to interact.
/// If `SwarmDone` arrives while the user started a new task, it's stored here
/// and reported after the current task finishes.
pending_swarm_result: Option<PendingSwarmResult>,
/// Handle to the active swarm's SharedKnowledge for worker control.
/// Set when a swarm is dispatched, cleared on SwarmDone.
swarm_knowledge: Option<crate::agent::swarm::knowledge::SharedKnowledge>,
/// Dispatch args stashed while a background repo map rebuild is in flight.
/// Fired by event_loop once repo_map_rebuild_rx delivers the rebuilt map.
pub(super) pending_dispatch: Option<PendingDispatch>,
/// Shared MCP manager — initialized once in App::run(), reused every prompt.
cached_mcp: Option<std::sync::Arc<crate::mcp::manager::McpManager>>,
/// Shared skill registry — discovered once, reused every prompt.
cached_skills: Option<std::sync::Arc<crate::skills::SkillRegistry>>,
/// Shared BM25 tool index — built once from cached_mcp+skills, reused every prompt.
cached_tool_index: Option<std::sync::Arc<crate::tools::tool_index::ToolIndex>>,
/// Lightweight session metadata for /resume popup (id, timestamp, completed).
/// Full snapshots are loaded on demand to avoid startup memory bloat.
session_snapshot_ids: Vec<(String, String, bool)>,
}
/// All arguments needed to dispatch an agent task, stashed when a repo map
/// rebuild is in progress so the dispatch can fire after the rebuild completes.
pub struct PendingDispatch {
pub context: crate::agent::context::ConversationContext,
pub augmented_input: String,
pub event_tx: tokio::sync::mpsc::UnboundedSender<crate::agent::r#loop::AgentEvent>,
pub effective_mode: crate::agent::swarm::config::CollaborationMode,
pub agent_name: String,
pub additional_agents: Vec<String>,
pub client: crate::api::provider::OpenAiCompatibleProvider,
pub config: crate::config::Config,
pub working_dir: String,
pub lsp_manager: crate::lsp::manager::LspManager,
pub trust_level: crate::trust::TrustLevel,
pub cancel: tokio_util::sync::CancellationToken,
pub approval_gate: crate::agent::approval::ApprovalGate,
pub approval_req_tx_swarm:
tokio::sync::mpsc::UnboundedSender<crate::agent::approval::ApprovalRequest>,
pub images: Vec<crate::api::ImageData>,
pub shared_mcp: Option<std::sync::Arc<crate::mcp::manager::McpManager>>,
pub shared_skills: Option<std::sync::Arc<crate::skills::SkillRegistry>>,
pub shared_tool_index: Option<std::sync::Arc<crate::tools::tool_index::ToolIndex>>,
}
/// Stores a deferred SwarmDone until the user's current task completes.
pub struct PendingSwarmResult {
merged_response: String,
agent_count: usize,
total_tool_calls: u32,
conflicts_resolved: usize,
}
mod agent;
mod autocomplete;
mod event_loop;
mod input;
mod plan;
mod session;
mod utils;
use utils::{build_system_prompt, detect_available_lsp, detect_missing_lsp};
impl App {
pub fn new(config: Config, client: OpenAiCompatibleProvider) -> Result<Self> {
Self::new_with_progress(config, client, &|_| {})
}
/// Same as `new`, but calls `progress(label)` at each boot phase so a
/// splash screen (or test harness) can display real-time load status.
pub fn new_with_progress(
mut config: Config,
client: OpenAiCompatibleProvider,
progress: &dyn Fn(&str),
) -> Result<Self> {
let working_dir = std::env::current_dir()?.to_string_lossy().to_string();
// Start global project cache background tasks for cross-mode sharing.
crate::project_cache::global().ensure_background_tasks();
// Build the repo map in a background thread — TUI becomes interactive immediately.
// The repo map receiver is polled on each event-loop tick and applied when ready.
progress("Charting the codebase");
let repo_map = RepoMap::new(std::path::Path::new(&working_dir));
let system_prompt = build_system_prompt(&repo_map, None);
let (repo_map_tx, repo_map_rx) = tokio::sync::oneshot::channel::<RepoMap>();
let repo_map_root = working_dir.clone();
tokio::task::spawn_blocking(move || {
let mut rm = RepoMap::new(std::path::Path::new(&repo_map_root));
let re_parsed = rm.rebuild();
tracing::info!(
"Repo map built: {} files, {} symbols, {} re-parsed",
rm.file_count(),
rm.symbol_count(),
re_parsed,
);
let _ = repo_map_tx.send(rm);
});
progress("Opening session vault");
let session_store = SessionStore::new(&working_dir);
let session_id = uuid::Uuid::new_v4().to_string();
let auto_route = config.auto_route;
progress("Loading automation hooks");
let hooks_config = HooksConfig::from_config(&config);
if hooks_config.has_any() {
tracing::info!(
auto_commit = hooks_config.auto_commit,
lint_cmd = ?hooks_config.lint_cmd,
test_cmd = ?hooks_config.test_cmd,
"Post-edit hooks configured",
);
}
progress("Preparing checkpoints");
let checkpoint_mgr = CheckpointManager::new(&working_dir);
progress("Waking up language servers");
let lsp_manager = crate::lsp::manager::LspManager::new(working_dir.clone());
// Check project trust level — prompt user if first visit
progress("Verifying project trust");
let trust_level = crate::trust::load_trust(&working_dir)
.unwrap_or_else(|| crate::trust::prompt_trust(&working_dir));
let ctx_max = config.context_max_tokens;
let compact_thresh = config.compaction_threshold;
let adaptive_compaction = config.adaptive_compaction;
let debug_mode = config.debug_mode;
let mut state = UiState::new();
// Sync model_name, provider_name, and agent_mode from agents[0] (the default agent).
// config.model may differ from agents[0].model when user edits agent files.
if let Some(first_agent) = config.agents.first() {
state.model_name = first_agent.model.clone();
state.agent_mode = first_agent.name.clone();
} else {
state.model_name = config.model.clone();
}
// Resolve provider_name from config file for the active model.
// Also initialize config.cli/cli_args if the first agent uses a CLI provider.
{
let active_model = state.model_name.as_str();
if let Ok(file) = crate::config::load_config_file() {
if let Some(entry) = file
.providers
.iter()
.find(|pe| pe.all_models().contains(&active_model))
{
state.provider_name = entry.name.clone();
if entry.is_cli() {
config.cli = entry.cli.clone();
config.cli_args = entry.cli_args.clone();
}
} else if let Some(first_agent) = config.agents.first().cloned() {
// Try resolving via the agent's explicit provider list.
let resolved = first_agent.providers.iter().find_map(|entry_name| {
crate::config::resolve_provider(entry_name)
.map(|(p, _)| (entry_name.clone(), p))
});
if let Some((pname, entry)) = resolved {
state.provider_name = pname.split('/').next().unwrap_or(&pname).to_string();
if entry.is_cli() {
config.cli = entry.cli.clone();
config.cli_args = entry.cli_args.clone();
}
}
}
}
}
progress("Scanning code intelligence");
state.installed_lsp = detect_available_lsp(&working_dir);
// Collect missing LSP servers — will be shown as sequential popups after startup.
let missing_lsp = detect_missing_lsp(&working_dir);
progress("Connecting MCP tools");
state.mcp_servers = crate::mcp::config::load_mcp_status(&working_dir);
state.set_theme(&config.theme);
state.context_max_tokens = ctx_max;
state.debug_mode = config.debug_mode;
state.debug_targets = config.debug_targets.clone();
let yolo_mode = config.yolo;
state.approve_mode = if yolo_mode { "yolo" } else { "auto" }.to_string();
Ok(Self {
config,
client,
context: Some({
let mut ctx =
ConversationContext::with_budget(system_prompt, ctx_max, compact_thresh);
ctx.set_adaptive_compaction(adaptive_compaction);
ctx
}),
last_context_backup: None,
state,
working_dir,
repo_map,
cancel_token: None,
input_history: Vec::new(),
history_index: None,
saved_input: String::new(),
repo_map_dirty: false,
repo_map_receiver: Some(repo_map_rx),
repo_map_rebuild_rx: None,
pending_diff_rx: None,
session_store,
session_id,
auto_route,
hooks_config,
modified_files: Vec::new(),
checkpoint_mgr,
current_agent_index: 0,
esc_pending: false,
esc_pending_at: None,
agent_busy_since: None,
pending_mode_approval_msg: None,
arbor_dispatch_mode: None,
message_queue: std::collections::VecDeque::new(),
was_cancelled: false,
current_task: String::new(),
task_start_tokens_in: 0,
task_start_tokens_out: 0,
task_start_api_calls: 0,
task_start_tool_count: 0,
task_start_compactions: 0,
lsp_manager,
trust_level,
open_resume_popup: false,
session_collab_mode: None,
metrics_collector: if debug_mode {
Some(crate::util::process_metrics::MetricsCollector::new())
} else {
None
},
hidden_prompt: None,
pending_pii_input: None,
pending_lsp_installs: missing_lsp,
optimizer_auto_triggered: false,
mcp_pids: Vec::new(),
approve_mode: crate::agent::approval::SharedApproveMode::new(if yolo_mode {
crate::agent::approval::ApproveMode::Yolo
} else {
crate::agent::approval::ApproveMode::Auto
}),
continuation_count: 0,
session_approvals: crate::agent::approval::SessionApprovals::new(),
approval_req_rx: None,
pending_approval_tx: None,
last_tab_at: None,
scroll_target: 0,
pending_swarm_result: None,
swarm_knowledge: None,
pending_dispatch: None,
cached_mcp: None,
cached_skills: None,
cached_tool_index: None,
session_snapshot_ids: Vec::new(),
})
}
/// Show the next pending LSP install popup, if any.
///
/// Call this after dismissing a popup (Install or Skip) to chain through
/// all languages that need an LSP server.
fn show_next_lsp_install_popup(&mut self) {
if self.state.popup.is_some() {
return; // Another popup is already visible.
}
if let Some((lang, server, hint)) = self.pending_lsp_installs.first().cloned() {
self.pending_lsp_installs.remove(0);
self.state.popup = Some(crate::tui::state::PopupState {
title: format!(" LSP: {lang} "),
content: String::new(),
scroll: 0,
kind: crate::tui::state::PopupKind::LspInstall {
language: lang,
server,
install_cmd: hint,
selected: 0,
},
saved_theme: None,
select_prefix: None,
search: String::new(),
});
}
}
pub async fn run(&mut self) -> Result<()> {
// Spawn MCP + skill init as a background task so it runs concurrently with
// session resume and session list loading, reducing total blocking time.
let mcp_task = if self.cached_mcp.is_none() {
tracing::info!("Initializing shared MCP manager (background)");
let working_dir = self.working_dir.clone();
let agents = self.config.agents.clone();
Some(tokio::spawn(async move {
let mcp = crate::mcp::manager::McpManager::connect_all(&working_dir).await;
let skills =
crate::skills::SkillRegistry::discover(std::path::Path::new(&working_dir));
let mut idx = crate::tools::tool_index::ToolIndex::new();
idx.reindex_mcp_tools(&mcp);
idx.reindex_skills(&skills);
idx.reindex_agents(&agents);
(
std::sync::Arc::new(mcp),
std::sync::Arc::new(skills),
std::sync::Arc::new(idx),
)
}))
} else {
None
};
// Check for incomplete session before starting TUI
// Skip if session was already restored via --continue/--resume
if self.context.is_none() {
self.try_resume_session().await;
}
// Apply MCP results (task ran concurrently with session resume above).
if let Some(task) = mcp_task
&& let Ok((mcp, skills, idx)) = task.await
{
self.cached_mcp = Some(mcp);
self.cached_skills = Some(skills);
self.cached_tool_index = Some(idx);
}
// Defer session snapshot loading to when user opens /resume popup.
// Previously loaded 15 full snapshots (each containing full message
// history) at startup, wasting 10-50MB of heap. Now we only store
// lightweight metadata from list() and load full snapshots on demand.
self.session_snapshot_ids = {
let sessions = self.session_store.list().await;
sessions.into_iter().take(15).collect()
};
// If requested (--resume flag), open the session picker popup immediately.
if self.open_resume_popup {
self.open_session_resume_popup();
}
// Show first missing LSP popup (if any), unless another popup is already up.
self.show_next_lsp_install_popup();
let mut tui = terminal::init()?;
let (event_tx, mut event_rx) = mpsc::unbounded_channel::<AgentEvent>();
// Spawn dedicated OS thread for crossterm event reading.
// This prevents blocking syscalls (poll/select) from stalling the
// tokio runtime and causing TUI freezes during agent streaming.
let mut key_rx = event::spawn_crossterm_thread();
let result = self
.main_loop(&mut tui, &event_tx, &mut event_rx, &mut key_rx)
.await;
// Save session on exit — mark as incomplete so it can be resumed.
// Only mark completed if there are no user messages (nothing to resume).
let has_conversation = self
.context
.as_ref()
.map(|ctx| ctx.messages().iter().any(|m| m.role == "user"))
.or_else(|| {
self.last_context_backup
.as_ref()
.map(|ctx| ctx.messages().iter().any(|m| m.role == "user"))
})
.unwrap_or(false);
self.save_session(!has_conversation).await;
// Shut down all LSP servers before restoring the terminal to prevent
// zombie language-server processes (rust-analyzer, pyright, etc.).
if let Err(e) = self.lsp_manager.shutdown_all().await {
tracing::warn!("LSP shutdown error: {e}");
}
terminal::restore()?;
// Print exit summary (gemini-cli style)
let tool_success = self.state.tool_log.iter().filter(|e| e.success).count();
let tool_failure = self.state.tool_log.len() - tool_success;
goodbye::print_goodbye(&ExitSummary {
session_id: self.session_id.clone(),
tool_total: self.state.tool_log.len(),
tool_success,
tool_failure,
wall_secs: self.state.elapsed_secs,
total_tokens: self.state.token_stats.total_tokens(),
api_calls: self.state.token_stats.api_calls,
model_name: self.state.model_name.clone(),
theme: self.state.theme.clone(),
});
result
}
}