1use std::collections::HashMap;
7use std::sync::Arc;
8
9use tokio::sync::mpsc;
10use tokio_util::sync::CancellationToken;
11
12use abk::cli::ResumeInfo;
13use abk::context::RunContext;
14
15use std::sync::atomic::{AtomicU8, Ordering};
16
17use crate::types::{
18 AutoHandoffConfig, BuildInfo, CapturedText, HandoffCaptureSink, McpServerInfo, McpServerStatus,
19 TuiMessage, WorkflowState,
20};
21
22pub struct Session {
27 pub input: String,
29 pub output_lines: Vec<String>,
31 pub workflow_tx: mpsc::UnboundedSender<TuiMessage>,
33 pub workflow_state: WorkflowState,
35 pub config_toml: Option<String>,
37 pub secrets: Option<HashMap<String, String>>,
39 pub build_info: Option<BuildInfo>,
41 pub resume_info: Option<ResumeInfo>,
43 pub backup_resume_info: Option<ResumeInfo>,
46 pub todo_lines: Vec<String>,
48 pub cancel_token: CancellationToken,
50 pub pending_command: Option<String>,
52 pub handoff_pending: bool,
54 pub pending_tool_lines: Vec<(String, usize, Option<String>)>,
56 pub current_context_tokens: usize,
58 pub auto_handoff: AutoHandoffConfig,
60 pub mcp_servers: Vec<McpServerInfo>,
62 pub should_quit: bool,
64 pub auto_scroll: bool,
66
67 pub agent_name: String,
71 pub token_store: Option<Arc<dyn pep::token_store::TokenStore>>,
74
75 pub project_id: Option<String>,
78 pub project_name: Option<String>,
80 pub session_id: Option<String>,
82 pub session_name: Option<String>,
84 pub home_dir: Option<std::path::PathBuf>,
87
88 pub workflow_permit: Option<tokio::sync::OwnedSemaphorePermit>,
93}
94
95impl Session {
96 pub fn new() -> (Self, mpsc::UnboundedReceiver<TuiMessage>) {
101 let (workflow_tx, workflow_rx) = mpsc::unbounded_channel();
102 let session = Self {
103 input: String::new(),
104 output_lines: Vec::new(),
105 workflow_tx,
106 workflow_state: WorkflowState::Idle,
107 config_toml: None,
108 secrets: None,
109 build_info: None,
110 resume_info: None,
111 backup_resume_info: None,
112 todo_lines: Vec::new(),
113 cancel_token: CancellationToken::new(),
114 pending_command: None,
115 handoff_pending: false,
116 pending_tool_lines: Vec::new(),
117 current_context_tokens: 0,
118 auto_handoff: AutoHandoffConfig::default(),
119 mcp_servers: Vec::new(),
120 should_quit: false,
121 auto_scroll: true,
122 agent_name: "trustee".to_string(),
123 token_store: None,
124 project_id: None,
125 project_name: None,
126 session_id: None,
127 session_name: None,
128 home_dir: None,
129 workflow_permit: None,
130 };
131 (session, workflow_rx)
132 }
133
134 pub fn parse_auto_handoff_config(&mut self) {
136 if let Some(ref config_toml) = self.config_toml {
137 self.auto_handoff = crate::config::parse_auto_handoff_config(config_toml);
138 }
139 }
140
141 pub fn handle_workflow_message(&mut self, msg: TuiMessage) {
146 match msg {
147 TuiMessage::WorkflowCancelled => {
148 self.output_lines.push("⏹ Workflow cancelled".to_string());
149 self.output_lines.push("".to_string());
150 self.workflow_state = WorkflowState::Cancelling;
151 }
152 TuiMessage::OutputLine(line) => {
153 self.output_lines.push(line);
154 }
155 TuiMessage::StreamDelta(delta) => {
156 if let Some(last) = self.output_lines.last_mut() {
157 last.push_str(&delta);
158 } else {
159 self.output_lines.push(delta);
160 }
161 }
162 TuiMessage::ReasoningDelta(delta) => {
163 if let Some(last) = self.output_lines.last_mut() {
164 if !last.starts_with('\x01') {
165 last.insert(0, '\x01');
166 }
167 last.push_str(&delta);
168 } else {
169 self.output_lines.push(format!("\x01{}", delta));
170 }
171 }
172 TuiMessage::WorkflowCompleted => {
173 self.output_lines.push("✓ Workflow completed".to_string());
174 self.output_lines.push("".to_string());
175 if self.workflow_state == WorkflowState::Running {
176 self.workflow_state = WorkflowState::Cancelling;
177 }
178 }
179 TuiMessage::WorkflowError(err) => {
180 self.output_lines.push(format!("✗ Error: {}", err));
181 self.output_lines.push("".to_string());
182 if self.workflow_state == WorkflowState::Running {
183 self.workflow_state = WorkflowState::Cancelling;
184 }
185 }
186 TuiMessage::TodoUpdate(content) => {
187 self.todo_lines = content.lines().map(|l| l.to_string()).collect();
188 }
189 TuiMessage::ToolPending { tool_name, hint } => {
190 let label = match &hint {
191 Some(h) => format!("⠋ {} {}", tool_name, h),
192 None => format!("⠋ {}", tool_name),
193 };
194 let idx = self.output_lines.len();
195 self.output_lines.push(label);
196 self.pending_tool_lines.push((tool_name, idx, hint));
197 }
198 TuiMessage::ToolDone { tool_name, success, hint } => {
199 let status = if success { "✓" } else { "✗" };
200 if let Some(pos) = self.pending_tool_lines.iter().position(|(n, _, _)| *n == tool_name) {
201 let (_, idx, pending_hint) = self.pending_tool_lines.remove(pos);
202 let h = hint.or(pending_hint);
203 let label = match &h {
204 Some(h) => format!("{} {} {}", status, tool_name, h),
205 None => format!("{} {}", status, tool_name),
206 };
207 if idx < self.output_lines.len() {
208 self.output_lines[idx] = label;
209 return;
210 }
211 self.output_lines.push(label);
212 } else {
213 let label = match &hint {
214 Some(h) => format!("{} {} {}", status, tool_name, h),
215 None => format!("{} {}", status, tool_name),
216 };
217 self.output_lines.push(label);
218 }
219 }
220 TuiMessage::ResumeInfo(info) => {
221 if self.workflow_state == WorkflowState::Cancelling && info.is_none() {
222 self.resume_info = self.backup_resume_info.take();
223 } else if info.is_some() {
224 self.resume_info = info;
230 self.backup_resume_info = None;
231 }
232 if let Some(ref ri) = self.resume_info {
238 if self.session_id.is_none() {
239 self.session_id = Some(ri.session_id.clone());
240 }
241 }
242
243 if self.workflow_state == WorkflowState::Cancelling {
244 self.workflow_state = WorkflowState::Idle;
245 self.workflow_permit = None;
247 }
248 if self.resume_info.is_some() {
249 if std::env::var("RUST_LOG")
250 .map(|v| v.to_lowercase().contains("debug"))
251 .unwrap_or(false)
252 {
253 self.output_lines.push("🔄 Session preserved — next command will continue this session".to_string());
254 }
255 }
256 if self.workflow_state == WorkflowState::Idle && self.handoff_pending {
257 self.handoff_pending = false;
258 self.trigger_handoff(String::new());
259 } else if let Some(cmd) = self.pending_command.take() {
260 self.input = cmd;
261 self.execute_command();
262 }
263 }
264 TuiMessage::ContextTokensUpdated(count) => {
265 self.current_context_tokens = count;
266 if self.auto_handoff.enabled
267 && count >= self.auto_handoff.context_threshold
268 && self.workflow_state == WorkflowState::Running
269 && !self.handoff_pending
270 && self.resume_info.is_some()
271 {
272 self.handoff_pending = true;
273 self.cancel_token.cancel();
274 self.workflow_state = WorkflowState::Cancelling;
275 self.output_lines.push(format!(
276 "🔄 Auto-handoff: cancelling workflow, context tokens ({}) ≥ threshold ({})",
277 count, self.auto_handoff.context_threshold
278 ));
279 }
280 }
281 TuiMessage::McpServerStatus { name, connected, tool_count, error } => {
282 let status = if connected { McpServerStatus::Connected } else { McpServerStatus::Failed };
283 if let Some(existing) = self.mcp_servers.iter_mut().find(|s| s.name == name) {
284 existing.status = status;
285 existing.tool_count = tool_count;
286 existing.error = error;
287 } else {
288 self.mcp_servers.push(McpServerInfo { name, status, tool_count, error });
289 }
290 }
291 TuiMessage::HandoffReady(briefing) => {
292 self.workflow_state = WorkflowState::Idle;
293 self.resume_info = None;
294 self.session_id = None;
297 self.session_name = None;
298 self.input = briefing;
299 self.execute_command();
300 }
301 TuiMessage::SessionTitleUpdated(title) => {
302 self.session_name = Some(title);
304 }
305 }
306 if self.auto_scroll {
307 }
310 }
311
312 pub fn execute_command(&mut self) {
317 let command = self.input.trim().to_string();
318
319 if self.workflow_state != WorkflowState::Idle {
320 self.pending_command = Some(command);
321 self.output_lines.push("⏳ Previous workflow finishing — command queued".to_string());
322 self.input.clear();
323 return;
324 }
325
326 let is_continuation = self.resume_info.is_some();
327
328 if !is_continuation {
329 self.output_lines.clear();
330 if self.session_id.is_none() {
336 let timestamp = chrono::Utc::now().format("%Y_%m_%d_%H_%M");
337 let uuid_suffix = uuid::Uuid::new_v4().simple().to_string();
338 let uuid8 = &uuid_suffix[..8];
339 self.session_id = Some(format!("session_{}_{}", timestamp, uuid8));
340 }
341 if self.session_name.is_none() {
342 let derived = if command.len() > 80 {
343 format!("{}...", &command[..77])
344 } else {
345 command.clone()
346 };
347 self.session_name = Some(derived);
348 }
349 }
350
351 self.output_lines.push(format!("> {}", command));
352
353 let config_toml = match &self.config_toml {
354 Some(c) => c.clone(),
355 None => {
356 self.output_lines.push("✗ Error: Configuration not loaded".to_string());
357 self.output_lines.push("".to_string());
358 return;
359 }
360 };
361
362 let secrets = self.secrets.clone().unwrap_or_default();
363 let title_secrets = secrets.clone();
365 let build_info = self.build_info.clone();
366 let tx = self.workflow_tx.clone();
367
368 let agent_name = self.agent_name.clone();
369 let token_store = self.token_store.clone();
370 let project_id = self.project_id.clone();
371 let project_name = self.project_name.clone();
372 let session_id = self.session_id.clone();
373 let session_name = self.session_name.clone();
374 let home_dir = self.home_dir.clone();
375
376 self.backup_resume_info = self.resume_info.clone();
377 let resume_info = self.resume_info.take();
378
379 self.workflow_state = WorkflowState::Running;
380 self.auto_scroll = true;
381
382 self.cancel_token = CancellationToken::new();
383 let child_token = self.cancel_token.clone();
384
385 let (resume_tx, mut resume_rx) = mpsc::unbounded_channel();
386
387 let resume_forward_tx = tx.clone();
388 tokio::spawn(async move {
389 while let Some(info) = resume_rx.recv().await {
390 resume_forward_tx.send(TuiMessage::ResumeInfo(info)).ok();
391 }
392 });
393
394 tokio::spawn(async move {
395 let tui_sink: abk::orchestration::output::SharedSink =
396 Arc::new(crate::session::TuiForwardSink::new(tx.clone()));
397
398 let mut run_ctx = RunContext::new()
400 .with_agent_name(agent_name.clone());
401
402 if let Some(ref dir) = home_dir {
404 run_ctx = run_ctx.with_home_dir(dir.clone());
405 }
406
407 if project_id.is_some() || project_name.is_some() {
409 run_ctx = run_ctx.with_project(abk::context::ProjectIdentity {
410 id: project_id.unwrap_or_else(|| "default".to_string()),
411 name: project_name,
412 });
413 }
414
415 if session_id.is_some() || session_name.is_some() {
417 run_ctx = run_ctx.with_session(abk::context::SessionIdentity {
418 id: session_id.unwrap_or_else(|| "default".to_string()),
419 name: session_name,
420 });
421 }
422
423 #[cfg(feature = "registry-mcp-token")]
424 {
425 if let Some(ref ts) = token_store {
426 run_ctx = run_ctx.with_token_store(ts.clone());
427 }
428 }
429
430 let scope_logger = {
435 abk::observability::Logger::with_agent_name(
436 None::<&std::path::Path>,
437 Some("INFO"),
438 Some(&agent_name),
439 ).unwrap_or_else(|_| abk::observability::Logger::new(None, Some("INFO")).unwrap())
440 };
441
442 let result = abk::observability::with_logger(scope_logger, async {
443 abk::observability::with_tui_mode(true, async {
444 abk::cli::run_task_from_raw_config(
445 &config_toml,
446 secrets,
447 build_info,
448 &command,
449 Some(tui_sink),
450 resume_info,
451 Some(resume_tx),
452 Some(child_token),
453 Some(&run_ctx),
454 )
455 .await
456 })
457 .await
458 })
459 .await;
460
461 let task_result = result.unwrap_or_else(|e| abk::cli::TaskResult {
462 success: false,
463 error: Some(e.to_string()),
464 resume_info: None,
469 });
470
471 let msg = if task_result.success {
472 TuiMessage::WorkflowCompleted
473 } else {
474 TuiMessage::WorkflowError(task_result.error.unwrap_or_default())
475 };
476
477 let title_session_id = task_result.resume_info
479 .as_ref()
480 .map(|ri| ri.session_id.clone());
481
482 tx.send(msg).ok();
483 tx.send(TuiMessage::ResumeInfo(task_result.resume_info)).ok();
484
485 if task_result.success {
492 let title_tx = tx.clone();
493 let title_config = config_toml.clone();
494 let title_command = command.clone();
495 let title_ctx = run_ctx.clone();
496
497 tokio::spawn(async move {
498 if let Some(ref sid) = title_session_id {
502 if !abk::cli::should_generate_title(&title_ctx, sid, &title_command).await {
503 return;
504 }
505 } else {
506 return; }
508
509 tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
511
512 if let Some(ref sid) = title_session_id {
514 if !abk::cli::should_generate_title(&title_ctx, sid, &title_command).await {
515 return;
516 }
517 }
518
519 match abk::cli::generate_session_title(
520 &title_config,
521 title_secrets,
522 &title_command,
523 )
524 .await
525 {
526 Ok(Some(title)) => {
527 if let Some(ref sid) = title_session_id {
529 if let Err(e) = abk::cli::persist_session_title(
530 &title_ctx,
531 &title_config,
532 sid,
533 &title,
534 ).await {
535 let _ = e; }
537 }
538 title_tx.send(TuiMessage::SessionTitleUpdated(title)).ok();
540 }
541 Ok(None) => {}
542 Err(e) => { let _ = e; }
543 }
544 });
545 }
546 });
547
548 self.input.clear();
549 }
550
551 pub fn trigger_handoff(&mut self, hint: String) {
556 if self.resume_info.is_none() {
557 self.output_lines.push("ℹ Nothing to hand off — run a task first".to_string());
558 return;
559 }
560
561 let config_toml = match &self.config_toml {
562 Some(c) => c.clone(),
563 None => {
564 self.output_lines.push("✗ Error: Configuration not loaded".to_string());
565 return;
566 }
567 };
568
569 let secrets = self.secrets.clone().unwrap_or_default();
570 let build_info = self.build_info.clone();
571 let tx = self.workflow_tx.clone();
572
573 let agent_name = self.agent_name.clone();
574 let token_store = self.token_store.clone();
575 let project_id = self.project_id.clone();
576 let project_name = self.project_name.clone();
577 let session_id = self.session_id.clone();
578 let session_name = self.session_name.clone();
579 let home_dir = self.home_dir.clone();
580
581 let resume_info = self.resume_info.take();
582
583 self.workflow_state = WorkflowState::Running;
584 self.auto_scroll = true;
585 self.cancel_token = CancellationToken::new();
586 let child_token = self.cancel_token.clone();
587
588 self.output_lines.push("🔀 Generating session handoff briefing...".to_string());
589
590 tokio::spawn(async move {
591 let (cap_tx, mut cap_rx) = mpsc::unbounded_channel::<CapturedText>();
592 let cap_sink: abk::orchestration::output::SharedSink =
593 Arc::new(HandoffCaptureSink::new(cap_tx, child_token.clone()));
594
595 let base = "Output a session handoff briefing in at most 300 lines. \
596 Do NOT use any tools. Include: the FULL ABSOLUTE PATH of every \
597 project/repository being worked on (e.g. /Projects/Foo/bar — never \
598 omit the leading path), all project/task/workstream UUIDs referenced, \
599 every file created or modified with its full absolute path, all \
600 commands run and their outcomes, the current state of the work, any \
601 blockers, and the exact next action to take. \
602 Output ONLY the briefing text — no preamble, headers, or closing remarks.";
603 let prompt = if hint.is_empty() {
604 base.to_string()
605 } else {
606 format!("{base}\n\nIn the briefing also consider: {hint}")
607 };
608
609 let (dummy_tx, _dummy_rx) = mpsc::unbounded_channel();
610
611 let mut run_ctx = RunContext::new()
613 .with_agent_name(agent_name.clone());
614
615 if let Some(ref dir) = home_dir {
617 run_ctx = run_ctx.with_home_dir(dir.clone());
618 }
619
620 if project_id.is_some() || project_name.is_some() {
622 run_ctx = run_ctx.with_project(abk::context::ProjectIdentity {
623 id: project_id.unwrap_or_else(|| "default".to_string()),
624 name: project_name,
625 });
626 }
627
628 if session_id.is_some() || session_name.is_some() {
630 run_ctx = run_ctx.with_session(abk::context::SessionIdentity {
631 id: session_id.unwrap_or_else(|| "default".to_string()),
632 name: session_name,
633 });
634 }
635 #[cfg(feature = "registry-mcp-token")]
636 {
637 }
640
641 let scope_logger = abk::observability::Logger::with_agent_name(
643 None,
644 Some("INFO"),
645 Some(&agent_name),
646 ).unwrap_or_else(|_| abk::observability::Logger::new(None, Some("INFO")).unwrap());
647
648 let _res = abk::observability::with_logger(scope_logger, async {
649 abk::observability::with_tui_mode(true, async {
650 abk::cli::run_task_from_raw_config(
651 &config_toml,
652 secrets,
653 build_info,
654 &prompt,
655 Some(cap_sink),
656 resume_info,
657 Some(dummy_tx),
658 Some(child_token),
659 Some(&run_ctx),
660 )
661 .await
662 })
663 .await
664 })
665 .await;
666
667 let mut text_parts = String::new();
668 let mut reasoning_parts = String::new();
669 while let Ok(captured) = cap_rx.try_recv() {
670 match captured {
671 CapturedText::Text(s) => text_parts.push_str(&s),
672 CapturedText::Reasoning(s) => reasoning_parts.push_str(&s),
673 }
674 }
675
676 let briefing = if !text_parts.trim().is_empty() {
677 text_parts.trim().to_string()
678 } else if !reasoning_parts.trim().is_empty() {
679 reasoning_parts.trim().to_string()
680 } else {
681 "Session handoff: briefing unavailable — continue from previous context.".to_string()
682 };
683
684 tx.send(TuiMessage::HandoffReady(briefing)).ok();
685 });
686 }
687}
688
689impl Default for Session {
690 fn default() -> Self {
691 Self::new().0
692 }
693}
694
695pub struct TuiForwardSink {
701 tx: mpsc::UnboundedSender<TuiMessage>,
702 stream_state: AtomicU8,
703}
704
705const STREAM_IDLE: u8 = 0;
707const STREAM_REASONING: u8 = 1;
708const STREAM_CONTENT: u8 = 2;
709
710impl TuiForwardSink {
711 pub fn new(tx: mpsc::UnboundedSender<TuiMessage>) -> Self {
712 Self {
713 tx,
714 stream_state: AtomicU8::new(STREAM_IDLE),
715 }
716 }
717}
718
719impl abk::orchestration::output::OutputSink for TuiForwardSink {
720 fn emit(&self, event: abk::orchestration::output::OutputEvent) {
721 use abk::orchestration::output::OutputEvent;
722
723 let msg = match event {
724 OutputEvent::StreamingChunk { delta } => {
725 if delta.is_empty() {
726 return;
727 }
728 let prev = self.stream_state.swap(STREAM_CONTENT, Ordering::Relaxed);
729 if prev != STREAM_CONTENT {
730 let _ = self.tx.send(TuiMessage::OutputLine(String::new()));
731 }
732 let _ = self.tx.send(TuiMessage::StreamDelta(delta));
733 return;
734 }
735
736 OutputEvent::LlmResponse { text, model } => {
737 TuiMessage::OutputLine(format!("[{}] {}", model, text))
738 }
739
740 OutputEvent::Info { message } => {
741 if message.contains("API call completed successfully") {
743 return;
744 }
745 TuiMessage::OutputLine(message)
746 }
747
748 OutputEvent::WorkflowStarted { task_description } => {
749 TuiMessage::OutputLine(format!("🚀 Workflow started: {}", task_description))
750 }
751
752 OutputEvent::WorkflowCompleted { reason, iterations } => {
753 TuiMessage::OutputLine(format!(
754 "✅ Workflow completed after {} iterations: {}",
755 iterations, reason
756 ))
757 }
758
759 OutputEvent::IterationStarted { iteration, context_tokens } => {
760 let _ = self.tx.send(TuiMessage::ContextTokensUpdated(context_tokens));
761 TuiMessage::OutputLine(format!(
762 "📡 Iteration {} | Context = {} tokens",
763 iteration, context_tokens
764 ))
765 }
766
767 OutputEvent::ApiCallStarted {
768 call_number,
769 model,
770 tool_count,
771 streaming,
772 context_tokens,
773 tool_tokens,
774 } => {
775 let mode = if streaming { "Streaming" } else { "Non-streaming" };
776 let total = context_tokens + tool_tokens;
777 let _ = self.tx.send(TuiMessage::ContextTokensUpdated(total));
778 let _ = self.tx.send(TuiMessage::OutputLine(String::new()));
780 TuiMessage::OutputLine(format!(
781 "🔥 API Call {} | Ctx={}({}+{}) | {} | Model: {} | Tools: {}",
782 call_number, total, context_tokens, tool_tokens, mode, model, tool_count
783 ))
784 }
785
786 OutputEvent::ToolsExecuting { tool_names, hints } => {
787 for (name, hint) in tool_names.into_iter().zip(hints.into_iter()) {
788 let _ = self.tx.send(TuiMessage::ToolPending { tool_name: name, hint });
789 }
790 self.stream_state.store(STREAM_IDLE, Ordering::Relaxed);
791 return;
792 }
793
794 OutputEvent::ToolCompleted {
795 tool_name,
796 success,
797 content,
798 description,
799 } => {
800 if tool_name == "todowrite" && success {
801 let _ = self.tx.send(TuiMessage::TodoUpdate(content.clone()));
802 }
803 let hint = description;
804 let _ = self.tx.send(TuiMessage::ToolDone { tool_name, success, hint });
805 self.stream_state.store(STREAM_IDLE, Ordering::Relaxed);
806 return;
807 }
808
809 OutputEvent::Error { message, context } => {
810 if let Some(ctx) = context {
811 TuiMessage::OutputLine(format!("❌ Error: {} — {}", message, ctx))
812 } else {
813 TuiMessage::OutputLine(format!("❌ Error: {}", message))
814 }
815 }
816
817 OutputEvent::ReasoningChunk { delta } => {
818 if delta.is_empty() {
819 return;
820 }
821 let prev = self.stream_state.swap(STREAM_REASONING, Ordering::Relaxed);
822 if prev != STREAM_REASONING {
823 let _ = self.tx.send(TuiMessage::OutputLine(String::new()));
824 }
825 let _ = self.tx.send(TuiMessage::ReasoningDelta(delta));
826 return;
827 }
828
829 OutputEvent::McpServerStatus { name, connected, tool_count, error } => {
830 let _ = self.tx.send(TuiMessage::McpServerStatus {
831 name,
832 connected,
833 tool_count,
834 error,
835 });
836 return;
837 }
838 };
839
840 self.stream_state.store(STREAM_IDLE, Ordering::Relaxed);
841 let _ = self.tx.send(msg);
842 }
843}