-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp_runner.rs
More file actions
1455 lines (1306 loc) · 52.5 KB
/
app_runner.rs
File metadata and controls
1455 lines (1306 loc) · 52.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! High-level application runner for Cortex TUI.
//!
//! This module provides `AppRunner`, the main entry point for running the
//! cortex-tui application. It handles terminal initialization, session
//! management, event loop execution, and cleanup.
//!
//! # Example
//!
//! ```rust,ignore
//! use cortex_tui::runner::AppRunner;
//! use cortex_engine::Config;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//! let config = Config::load_sync(Default::default())?;
//! let exit_info = AppRunner::new(config)
//! .with_initial_prompt("Hello!")
//! .run()
//! .await?;
//!
//! println!("Exited with: {:?}", exit_info.exit_reason);
//! Ok(())
//! }
//! ```
//!
//! # Architecture
//!
//! The `AppRunner` orchestrates the following components:
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────┐
//! │ AppRunner │
//! │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
//! │ │ CortexTerminal │ │ SessionBridge │ │ EventLoop │ │
//! │ │ (Terminal I/O) │ │ (Backend Comm) │ │ (Main Loop) │ │
//! │ └────────┬────────┘ └────────┬────────┘ └────────┬────────┘ │
//! │ │ │ │ │
//! │ └────────────────────┴────────────────────┘ │
//! │ │ │
//! └──────────────────────────────┼───────────────────────────────────┘
//! │
//! ▼
//! AppExitInfo
//! ```
use crate::app::AppState;
use crate::bridge::SessionBridge;
use crate::providers::ProviderManager;
use crate::runner::event_loop::EventLoop;
use crate::runner::terminal::{CortexTerminal, TerminalOptions};
use crate::session::CortexSession;
use anyhow::Result;
use cortex_engine::Config;
use cortex_login::{CredentialsStoreMode, load_auth, logout_with_fallback};
use cortex_protocol::ConversationId;
use std::path::PathBuf;
use tracing;
// ============================================================================
// Authentication Status
// ============================================================================
/// Authentication status for startup check.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AuthStatus {
/// User is authenticated.
Authenticated,
/// Session has expired.
Expired,
/// User is not authenticated.
NotAuthenticated,
}
// ============================================================================
// Exit Information
// ============================================================================
/// The reason the application exited.
///
/// This enum captures the different ways the TUI can terminate, which is
/// useful for downstream handling (e.g., displaying appropriate messages,
/// setting exit codes, or cleaning up resources).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExitReason {
/// User quit normally (e.g., via quit command or Ctrl+Q).
Normal,
/// User interrupted the application (e.g., via Ctrl+C).
Interrupted,
/// An error occurred during execution.
Error,
/// The session ended (e.g., backend disconnected).
SessionEnded,
}
impl Default for ExitReason {
fn default() -> Self {
Self::Normal
}
}
impl std::fmt::Display for ExitReason {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ExitReason::Normal => write!(f, "normal exit"),
ExitReason::Interrupted => write!(f, "interrupted"),
ExitReason::Error => write!(f, "error"),
ExitReason::SessionEnded => write!(f, "session ended"),
}
}
}
/// Information about how the application exited.
///
/// This struct is returned by `AppRunner::run()` and contains details about
/// the exit, including the conversation ID (for session resumption) and
/// the reason for termination.
///
/// # Example
///
/// ```rust,ignore
/// let exit_info = runner.run().await?;
/// if let Some(id) = exit_info.conversation_id {
/// println!("Session ID: {} - can be resumed later", id);
/// }
/// match exit_info.exit_reason {
/// ExitReason::Normal => println!("Goodbye!"),
/// ExitReason::Interrupted => println!("Session interrupted"),
/// ExitReason::Error => eprintln!("An error occurred"),
/// ExitReason::SessionEnded => println!("Session ended"),
/// }
/// ```
#[derive(Debug, Clone)]
pub struct AppExitInfo {
/// The conversation ID (if a session was active).
///
/// This can be used to resume the session later using
/// `AppRunner::with_conversation_id()`.
pub conversation_id: Option<ConversationId>,
/// The reason for exit.
pub exit_reason: ExitReason,
/// Message to print after exit (e.g., logout confirmation).
pub exit_message: Option<String>,
}
impl Default for AppExitInfo {
fn default() -> Self {
Self {
conversation_id: None,
exit_reason: ExitReason::Normal,
exit_message: None,
}
}
}
impl AppExitInfo {
/// Create a new exit info with a conversation ID.
pub fn with_conversation_id(mut self, id: ConversationId) -> Self {
self.conversation_id = Some(id);
self
}
/// Create a new exit info with an exit reason.
pub fn with_exit_reason(mut self, reason: ExitReason) -> Self {
self.exit_reason = reason;
self
}
/// Create a new exit info with an exit message.
pub fn with_exit_message(mut self, message: impl Into<String>) -> Self {
self.exit_message = Some(message.into());
self
}
/// Returns true if the exit was due to an error.
pub fn is_error(&self) -> bool {
self.exit_reason == ExitReason::Error
}
/// Returns true if the exit was normal.
pub fn is_normal(&self) -> bool {
self.exit_reason == ExitReason::Normal
}
}
// ============================================================================
// AppRunner
// ============================================================================
/// High-level application runner for Cortex TUI.
///
/// This is the main entry point for running the TUI application. It handles:
/// - Terminal initialization and cleanup
/// - Session creation or resumption
/// - Event loop execution
/// - Graceful shutdown and error handling
///
/// # Example
///
/// ```rust,ignore
/// use cortex_tui::runner::AppRunner;
/// use cortex_engine::Config;
///
/// // Basic usage
/// let config = Config::load_sync(Default::default())?;
/// let mut runner = AppRunner::new(config);
/// runner.run().await?;
///
/// // With builder pattern
/// let exit_info = AppRunner::new(config)
/// .with_initial_prompt("Explain this codebase")
/// .inline()
/// .run()
/// .await?;
/// ```
///
/// # Lifecycle
///
/// 1. **Initialization**: Terminal is set up with the configured options
/// 2. **Session**: A new session is created or an existing one is resumed
/// 3. **Event Loop**: The main loop processes events until exit
/// 4. **Cleanup**: Terminal is restored and resources are released
pub struct AppRunner {
/// The cortex-core configuration.
config: Config,
/// Initial prompt to send on startup (optional).
initial_prompt: Option<String>,
/// Conversation ID to resume (optional).
conversation_id: Option<ConversationId>,
/// Cortex session ID to resume (optional).
cortex_session_id: Option<String>,
/// Terminal configuration options.
terminal_options: TerminalOptions,
/// Whether to use direct provider mode (bypasses backend).
use_direct_provider: bool,
}
impl AppRunner {
// ========================================================================
// Constructor
// ========================================================================
/// Create a new app runner with the given configuration.
///
/// This creates a runner with default terminal options (full-screen mode
/// with alternate screen, mouse capture, etc.).
///
/// # Arguments
///
/// * `config` - The cortex-core configuration for the session
///
/// # Example
///
/// ```rust,ignore
/// let config = Config::load_sync(Default::default())?;
/// let runner = AppRunner::new(config);
/// ```
pub fn new(config: Config) -> Self {
Self {
config,
initial_prompt: None,
conversation_id: None,
cortex_session_id: None,
terminal_options: TerminalOptions::default(),
use_direct_provider: true, // Default to direct provider mode
}
}
// ========================================================================
// Builder Methods
// ========================================================================
/// Set an initial prompt to send on startup.
///
/// When set, this prompt will be automatically sent to the session
/// after initialization completes. This is useful for CLI workflows
/// where the user provides input via command-line arguments.
///
/// # Arguments
///
/// * `prompt` - The initial message to send
///
/// # Example
///
/// ```rust,ignore
/// let runner = AppRunner::new(config)
/// .with_initial_prompt("What files are in this directory?");
/// ```
pub fn with_initial_prompt(mut self, prompt: impl Into<String>) -> Self {
self.initial_prompt = Some(prompt.into());
self
}
/// Resume an existing conversation (legacy backend mode).
///
/// When set, the runner will attempt to resume the specified conversation
/// instead of creating a new one. The conversation history will be
/// restored from the rollout file.
///
/// # Arguments
///
/// * `id` - The conversation ID to resume
///
/// # Example
///
/// ```rust,ignore
/// let conversation_id = ConversationId::from_str("abc-123")?;
/// let runner = AppRunner::new(config)
/// .with_conversation_id(conversation_id);
/// ```
pub fn with_conversation_id(mut self, id: ConversationId) -> Self {
self.conversation_id = Some(id);
self.use_direct_provider = false; // Use legacy mode when resuming backend sessions
self
}
/// Resume an existing Cortex session.
///
/// When set, the runner will load the specified Cortex session from local storage.
///
/// # Arguments
///
/// * `id` - The Cortex session ID to resume
///
/// # Example
///
/// ```rust,ignore
/// let runner = AppRunner::new(config)
/// .with_cortex_session_id("abc-123");
/// ```
pub fn with_cortex_session_id(mut self, id: impl Into<String>) -> Self {
self.cortex_session_id = Some(id.into());
self
}
/// Use direct provider mode (bypasses backend session bridge).
///
/// This is the default mode. Direct provider mode uses the ProviderManager
/// to communicate directly with AI providers and stores sessions locally.
///
/// # Example
///
/// ```rust,ignore
/// let runner = AppRunner::new(config).direct_provider(true);
/// ```
pub fn direct_provider(mut self, enabled: bool) -> Self {
self.use_direct_provider = enabled;
self
}
/// Use legacy backend mode (requires running cortex server).
///
/// This mode uses the SessionBridge to communicate with a cortex-core backend.
///
/// # Example
///
/// ```rust,ignore
/// let runner = AppRunner::new(config).legacy_backend();
/// ```
pub fn legacy_backend(mut self) -> Self {
self.use_direct_provider = false;
self
}
/// Use custom terminal options.
///
/// This allows fine-grained control over terminal initialization,
/// including alternate screen usage, mouse capture, and more.
///
/// # Arguments
///
/// * `options` - The terminal configuration options
///
/// # Example
///
/// ```rust,ignore
/// let options = TerminalOptions::new()
/// .alternate_screen(true)
/// .mouse_capture(false);
/// let runner = AppRunner::new(config)
/// .with_terminal_options(options);
/// ```
pub fn with_terminal_options(mut self, options: TerminalOptions) -> Self {
self.terminal_options = options;
self
}
/// Use inline mode (preserves scrollback).
///
/// Inline mode runs the TUI without using the alternate screen buffer,
/// which preserves the terminal scrollback and allows output to remain
/// visible after the TUI exits. This is useful for non-fullscreen
/// workflows or when you want to see the conversation history in the
/// terminal after exiting.
///
/// # Example
///
/// ```rust,ignore
/// let runner = AppRunner::new(config).inline();
/// ```
pub fn inline(mut self) -> Self {
self.terminal_options = TerminalOptions::inline();
self
}
// ========================================================================
// Configuration Helpers
// ========================================================================
/// Get the effective model name.
///
/// Returns the model from the configuration, or a sensible default
/// if none is configured.
pub fn model(&self) -> &str {
&self.config.model
}
/// Get the effective provider name.
///
/// Returns the provider from the configuration, or a sensible default
/// if none is configured.
pub fn provider(&self) -> &str {
&self.config.model_provider_id
}
/// Get a reference to the configuration.
pub fn config(&self) -> &Config {
&self.config
}
// ========================================================================
// Run Methods
// ========================================================================
/// Run the application.
///
/// This is the main entry point that:
/// 1. Initializes the terminal with the configured options
/// 2. Creates or resumes a session (direct provider or legacy bridge)
/// 3. Sets up the application state
/// 4. Runs the event loop until exit
/// 5. Cleans up and returns exit information
///
/// # Returns
///
/// Returns `AppExitInfo` containing the conversation ID and exit reason.
///
/// # Errors
///
/// Returns an error if:
/// - Terminal initialization fails
/// - Session creation/resumption fails
/// - The event loop encounters a fatal error
///
/// # Example
///
/// ```rust,ignore
/// let exit_info = AppRunner::new(config).run().await?;
/// println!("Exited: {:?}", exit_info.exit_reason);
/// ```
pub async fn run(self) -> Result<AppExitInfo> {
tracing::info!("Starting Cortex TUI");
// Use direct provider mode if enabled
if self.use_direct_provider {
return self.run_direct_provider().await;
}
// Legacy mode: use SessionBridge
self.run_legacy_bridge().await
}
/// Run using direct provider mode (new architecture).
///
/// ## Performance Optimizations
///
/// This function is optimized for fast TUI startup by:
/// 1. **Deferring non-critical HTTP requests**: Session validation, model fetching,
/// and user info are fetched in the background after the terminal is initialized
/// 2. **Parallel I/O operations**: Session history loading runs concurrently with
/// other startup tasks using `tokio::spawn`
/// 3. **Non-blocking validation**: Server-side session validation happens
/// asynchronously and doesn't block the TUI from appearing
///
/// The TUI should appear almost instantly after trust verification and auth check.
async fn run_direct_provider(self) -> Result<AppExitInfo> {
// Trust verification before anything else
let workspace = std::env::current_dir()?;
if !is_workspace_trusted(&workspace) {
use super::trust_screen::{TrustResult, TrustScreen};
let mut trust_screen = TrustScreen::new(workspace.clone());
match trust_screen.run().await? {
TrustResult::Trusted => {
mark_workspace_trusted(&workspace)?;
}
TrustResult::Rejected => {
return Ok(AppExitInfo {
exit_reason: ExitReason::Normal,
..Default::default()
});
}
}
}
// Check authentication before starting (fast local check)
let cortex_home = dirs::home_dir()
.map(|h| h.join(".cortex"))
.unwrap_or_else(|| PathBuf::from(".cortex"));
// Load provider manager first to check for API keys
let mut provider_manager = ProviderManager::load().unwrap_or_else(|e| {
tracing::warn!("Failed to load provider config, using defaults: {}", e);
ProviderManager::new(Default::default())
});
// Try to load auth token from keyring and set it on the provider manager
if let Some(token) = cortex_login::get_auth_token() {
tracing::debug!("Loaded auth token from keyring");
provider_manager.set_auth_token(token);
}
// Check if user is authenticated (OAuth/API key login) or has API keys configured
// This is a fast local check - no network calls
let mut auth_status = match load_auth(&cortex_home, CredentialsStoreMode::default()) {
Ok(Some(auth)) if !auth.is_expired() => {
tracing::info!("User authenticated via {}", auth.mode);
AuthStatus::Authenticated
}
Ok(Some(_)) => {
// Token expired - delete stale credentials so user doesn't appear as "logged in"
tracing::info!("Token expired, removing stale credentials");
if let Err(e) = logout_with_fallback(&cortex_home) {
tracing::warn!("Failed to remove expired credentials: {}", e);
}
AuthStatus::Expired
}
Ok(None) => {
// No OAuth credentials - check if API keys are configured
if provider_manager.is_available() {
tracing::info!("Using API key authentication");
AuthStatus::Authenticated
} else if std::env::var("CORTEX_API_KEY").is_ok() {
tracing::info!("Using CORTEX_API_KEY environment variable");
AuthStatus::Authenticated
} else {
AuthStatus::NotAuthenticated
}
}
Err(e) => {
tracing::warn!("Failed to load auth: {}", e);
// Continue anyway if API keys are available
if provider_manager.is_available() || std::env::var("CORTEX_API_KEY").is_ok() {
AuthStatus::Authenticated
} else {
AuthStatus::NotAuthenticated
}
}
};
// If not authenticated, show the login screen TUI
// (We skip server validation here and do it in the background later)
if auth_status != AuthStatus::Authenticated {
use super::login_screen::{LoginResult, LoginScreen};
let message = match auth_status {
AuthStatus::Expired => Some("Your session has expired.".to_string()),
AuthStatus::NotAuthenticated => None,
_ => None,
};
let mut login_screen = LoginScreen::new(cortex_home.clone(), message);
match login_screen.run().await? {
LoginResult::LoggedIn => {
tracing::info!("User logged in successfully");
// Reload auth token after login - this is critical!
if let Some(token) = cortex_login::get_auth_token() {
tracing::info!("Loaded fresh auth token from keyring after login");
provider_manager.set_auth_token(token);
} else {
tracing::warn!("Login succeeded but could not load token from keyring");
}
auth_status = AuthStatus::Authenticated;
}
LoginResult::ContinueWithApiKey => {
// Show API key setup instructions and exit
println!();
println!("\x1b[1;36m API Key Authentication\x1b[0m");
println!();
println!(" To use Cortex with an API key, set the environment variable:");
println!();
println!(" \x1b[32mexport CORTEX_API_KEY=ctx-xxxxxxxxxxxxxxxx\x1b[0m");
println!();
println!(" On Windows (PowerShell):");
println!();
println!(" \x1b[32m$env:CORTEX_API_KEY = \"ctx-xxxxxxxxxxxxxxxx\"\x1b[0m");
println!();
println!(" Then run \x1b[1mcortex\x1b[0m again to start.");
println!();
return Ok(AppExitInfo::default().with_exit_reason(ExitReason::Normal));
}
LoginResult::Exit => {
println!();
println!("\x1b[33m Login cancelled.\x1b[0m");
println!();
return Ok(AppExitInfo::default().with_exit_reason(ExitReason::Normal));
}
LoginResult::Failed(e) => {
tracing::error!("Login failed: {}", e);
return Ok(AppExitInfo::default().with_exit_reason(ExitReason::Error));
}
}
}
// ====================================================================
// Fetch user info BEFORE showing TUI to avoid "User" placeholder
// ====================================================================
let mut user_name: Option<String> = None;
let mut user_email: Option<String> = None;
let mut org_name: Option<String> = None;
// Fetch user info from /me API - wait for this before showing TUI
if let Some(token) = cortex_login::get_auth_token() {
tracing::debug!("Fetching user info from /me API...");
if let Ok(client) = cortex_engine::create_default_client() {
match client
.get("https://api.cortex.foundation/auth/me")
.bearer_auth(&token)
.timeout(std::time::Duration::from_secs(5))
.send()
.await
{
Ok(resp) if resp.status().is_success() => {
if let Ok(json) = resp.json::<serde_json::Value>().await {
if let Some(name) = json.get("name").and_then(|v| v.as_str()) {
user_name = Some(name.to_string());
tracing::info!("User info loaded: {}", name);
}
if let Some(email) = json.get("email").and_then(|v| v.as_str()) {
user_email = Some(email.to_string());
}
if let Some(orgs) = json.get("organizations").and_then(|v| v.as_array())
{
if let Some(first_org) = orgs.first() {
if let Some(org) =
first_org.get("org_name").and_then(|v| v.as_str())
{
org_name = Some(org.to_string());
}
}
}
}
}
Ok(resp) => {
tracing::warn!("Failed to fetch user info: HTTP {}", resp.status());
}
Err(e) => {
tracing::warn!("Failed to fetch user info: {}", e);
}
}
}
}
// ====================================================================
// Now initialize TUI after we have user info
// ====================================================================
let mut terminal = CortexTerminal::with_options(self.terminal_options)?;
terminal.set_title("Cortex")?;
// Get terminal size for app state
let (width, height) = terminal.size()?;
tracing::debug!("Terminal size: {}x{}", width, height);
tracing::info!("Using direct provider mode");
let provider = provider_manager.current_provider().to_string();
let model = provider_manager.current_model().to_string();
tracing::info!("Provider: {}, Model: {}", provider, model);
// Create or resume Cortex session
let cortex_session = if let Some(ref session_id) = self.cortex_session_id {
tracing::info!("Resuming Cortex session: {}", session_id);
CortexSession::load(session_id)?
} else {
tracing::info!("Creating new Cortex session");
CortexSession::new(&provider, &model)?
};
let _session_id = cortex_session.id().to_string();
// Create app state with user info already loaded
let mut app_state = AppState::new()
.with_model(model.clone())
.with_provider(provider.clone())
.with_terminal_size(width, height);
// Set user info from pre-fetched data
app_state.user_name = user_name;
app_state.user_email = user_email;
app_state.org_name = org_name;
// ====================================================================
// BACKGROUND TASKS: Spawn non-blocking operations in parallel
// ====================================================================
// 1. Session history loading (file I/O) - spawn in background
let session_history_task =
tokio::task::spawn_blocking(|| CortexSession::list_recent(50).ok());
// 3. Models prefetch and session validation - spawn in background
// We use a channel to receive results and update provider_manager later
let models_and_validation_task = {
let api_url = provider_manager.api_url().to_string();
let token = cortex_login::get_auth_token();
let cortex_home_clone = cortex_home.clone();
tokio::spawn(async move {
let mut validation_failed = false;
let mut models: Option<Vec<cortex_engine::client::CortexModel>> = None;
if let Some(token) = token {
// Create a client with timeout for faster failure on network issues
if let Ok(client) = cortex_engine::create_client_builder()
.connect_timeout(std::time::Duration::from_secs(3))
.timeout(std::time::Duration::from_secs(10))
.build()
{
// Session validation (lightweight)
tracing::debug!("Background: validating session with server...");
if let Ok(resp) = client
.get(format!("{}/v1/models", api_url))
.header("Authorization", format!("Bearer {}", token))
.send()
.await
{
let status = resp.status();
if status == reqwest::StatusCode::UNAUTHORIZED
|| status == reqwest::StatusCode::FORBIDDEN
{
tracing::warn!(
"Background: session validation failed ({})",
status
);
// Delete invalidated credentials
if let Err(e) = logout_with_fallback(&cortex_home_clone) {
tracing::warn!(
"Failed to remove invalidated credentials: {}",
e
);
}
validation_failed = true;
} else if status.is_success() {
// Parse models from the same response to avoid another request
if let Ok(json) = resp.json::<serde_json::Value>().await {
if let Some(data) = json.get("data").and_then(|d| d.as_array())
{
let parsed: Vec<cortex_engine::client::CortexModel> = data
.iter()
.filter_map(|m| serde_json::from_value(m.clone()).ok())
.collect();
if !parsed.is_empty() {
tracing::info!(
"Background: loaded {} models from API",
parsed.len()
);
models = Some(parsed);
}
}
}
}
}
}
}
(validation_failed, models)
})
};
// ====================================================================
// Collect background task results (with timeout to not block forever)
// ====================================================================
// Wait for session history (file I/O should be fast)
if let Ok(Some(sessions)) = session_history_task.await {
use crate::app::SessionSummary;
for session in sessions {
if let Ok(session_uuid) = uuid::Uuid::parse_str(&session.id) {
let summary = SessionSummary::new(session_uuid, session.title)
.with_message_count(session.message_count as usize)
.with_timestamp(session.updated_at);
app_state.session_history.push(summary);
}
}
tracing::debug!(
"Loaded {} Cortex session(s) from history",
app_state.session_history.len()
);
}
// Check validation result (with short timeout - don't block TUI)
// We'll handle models update after event loop is created
let validation_result = tokio::time::timeout(
std::time::Duration::from_millis(500),
models_and_validation_task,
)
.await;
// If validation failed in background, update auth status
// (This would show a toast in the TUI asking user to re-login)
if let Ok(Ok((true, _))) = &validation_result {
tracing::warn!("Session was invalidated by server - user should re-login");
// The credentials are already deleted in the background task
// We continue with the TUI but the user will get auth errors on API calls
}
// Extract and apply models if we got them from background task
if let Ok(Ok((_, Some(models)))) = validation_result {
provider_manager.set_cached_models(models);
}
// Create unified tool executor for Task and Batch tools
// This requires an API key for the subagent's model client
let unified_executor = {
use cortex_engine::tools::{ExecutorConfig, UnifiedToolExecutor};
use std::sync::Arc;
// Get auth token using the centralized auth module
// This properly handles: instance token → env var → keyring
// Previous bug: only checked CORTEX_AUTH_TOKEN env var, missing keyring auth
let api_key = cortex_engine::auth_token::get_auth_token(None).ok();
let base_url = provider_manager.config().get_base_url(&provider);
match api_key {
Some(api_key) if !api_key.is_empty() => {
tracing::debug!(
"Using API key for UnifiedToolExecutor (length: {})",
api_key.len()
);
let mut config = ExecutorConfig::new(&provider, &model, &api_key)
.with_working_dir(std::env::current_dir().unwrap_or_default());
// Add base URL if configured
if let Some(url) = base_url {
config = config.with_base_url(url);
}
match UnifiedToolExecutor::new(config) {
Ok(executor) => {
tracing::info!(
"UnifiedToolExecutor initialized - Task and Batch tools enabled"
);
Some(Arc::new(executor))
}
Err(e) => {
tracing::warn!(
"Failed to create UnifiedToolExecutor: {} - Task/Batch will use fallback",
e
);
None
}
}
}
Some(_) => {
// Empty API key - treat same as None
tracing::warn!(
"Empty API key for provider '{}' - Task/Batch tools will use fallback",
provider
);
None
}
None => {
tracing::warn!(
"No API key configured for provider '{}' - Task/Batch tools will use fallback",
provider
);
None
}
}
};
// Create tool registry for executing tools
let tool_registry = {
use cortex_engine::tools::ToolRegistry;
use std::sync::Arc;
let registry = ToolRegistry::new();
tracing::info!("Initialized ToolRegistry");
Arc::new(registry)
};
// Create event loop with provider manager, cortex session, and tool registry
let mut event_loop = EventLoop::new(app_state)
.with_provider_manager(provider_manager)
.with_cortex_session(cortex_session)
.with_tool_registry(tool_registry);
// Add unified executor if available
if let Some(executor) = unified_executor {
event_loop = event_loop.with_unified_executor(executor);
}
// Load persisted MCP server configurations
event_loop.load_mcp_servers();
// Handle initial prompt if provided
if let Some(prompt) = self.initial_prompt {
tracing::debug!("Initial prompt queued: {}", prompt);
// TODO: Send initial prompt after session is ready
}
// Run the main event loop
let result = event_loop.run(&mut terminal).await;
// Capture logout message before cleanup
let logout_message = event_loop.app_state.logout_message.take();
// Cleanup
terminal.show_cursor()?;
drop(terminal);
match result {
Ok(()) => {
tracing::info!("Cortex TUI exited normally");
let mut exit_info = AppExitInfo {
conversation_id: None, // Cortex sessions use string IDs
exit_reason: ExitReason::Normal,
exit_message: None,
};
if let Some(msg) = logout_message {
exit_info = exit_info.with_exit_message(msg);
}
Ok(exit_info)
}
Err(e) => {
tracing::error!("Cortex TUI error: {}", e);
Err(e)
}
}
}
/// Run using legacy SessionBridge mode.
async fn run_legacy_bridge(self) -> Result<AppExitInfo> {
// Initialize terminal
let mut terminal = CortexTerminal::with_options(self.terminal_options)?;
terminal.set_title("Cortex")?;
// Get terminal size for app state
let (width, height) = terminal.size()?;
tracing::debug!("Terminal size: {}x{}", width, height);
tracing::info!("Using legacy SessionBridge mode");
// Create or resume session via bridge
let session_bridge = if let Some(id) = self.conversation_id {
tracing::info!("Resuming session: {}", id);
SessionBridge::resume(self.config.clone(), id).await?
} else {
tracing::info!("Creating new session");
SessionBridge::new(self.config.clone()).await?
};
let conversation_id = session_bridge.conversation_id().clone();
// Create app state with configuration
let mut app_state = AppState::new()
.with_model(self.config.model.clone())
.with_provider(self.config.model_provider_id.clone())
.with_terminal_size(width, height);
// Load session history from cortex-core
if let Ok(sessions) = cortex_engine::list_sessions(&self.config.cortex_home) {
use crate::app::SessionSummary;
for session in sessions.into_iter().take(50) {
let timestamp = chrono::DateTime::parse_from_rfc3339(&session.timestamp)
.map(|dt| dt.with_timezone(&chrono::Utc))
.unwrap_or_else(|_| chrono::Utc::now());
let title = session.model.clone().unwrap_or_else(|| {
session
.cwd
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_else(|| "Session".to_string())
});
if let Ok(session_uuid) = uuid::Uuid::parse_str(&session.id) {
let summary = SessionSummary::new(session_uuid, title)
.with_message_count(session.message_count)
.with_timestamp(timestamp);
app_state.session_history.push(summary);
}
}
tracing::debug!(
"Loaded {} session(s) from history",
app_state.session_history.len()
);
}
// Create tool registry for executing tools
let tool_registry = {
use cortex_engine::tools::ToolRegistry;