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
85 pub workflow_permit: Option<tokio::sync::OwnedSemaphorePermit>,
90}
91
92impl Session {
93 pub fn new() -> (Self, mpsc::UnboundedReceiver<TuiMessage>) {
98 let (workflow_tx, workflow_rx) = mpsc::unbounded_channel();
99 let session = Self {
100 input: String::new(),
101 output_lines: Vec::new(),
102 workflow_tx,
103 workflow_state: WorkflowState::Idle,
104 config_toml: None,
105 secrets: None,
106 build_info: None,
107 resume_info: None,
108 backup_resume_info: None,
109 todo_lines: Vec::new(),
110 cancel_token: CancellationToken::new(),
111 pending_command: None,
112 handoff_pending: false,
113 pending_tool_lines: Vec::new(),
114 current_context_tokens: 0,
115 auto_handoff: AutoHandoffConfig::default(),
116 mcp_servers: Vec::new(),
117 should_quit: false,
118 auto_scroll: true,
119 agent_name: "trustee".to_string(),
120 token_store: None,
121 project_id: None,
122 project_name: None,
123 session_id: None,
124 session_name: None,
125 workflow_permit: None,
126 };
127 (session, workflow_rx)
128 }
129
130 pub fn parse_auto_handoff_config(&mut self) {
132 if let Some(ref config_toml) = self.config_toml {
133 self.auto_handoff = crate::config::parse_auto_handoff_config(config_toml);
134 }
135 }
136
137 pub fn handle_workflow_message(&mut self, msg: TuiMessage) {
142 match msg {
143 TuiMessage::WorkflowCancelled => {
144 self.output_lines.push("⏹ Workflow cancelled".to_string());
145 self.output_lines.push("".to_string());
146 self.workflow_state = WorkflowState::Cancelling;
147 }
148 TuiMessage::OutputLine(line) => {
149 self.output_lines.push(line);
150 }
151 TuiMessage::StreamDelta(delta) => {
152 if let Some(last) = self.output_lines.last_mut() {
153 last.push_str(&delta);
154 } else {
155 self.output_lines.push(delta);
156 }
157 }
158 TuiMessage::ReasoningDelta(delta) => {
159 if let Some(last) = self.output_lines.last_mut() {
160 if !last.starts_with('\x01') {
161 last.insert(0, '\x01');
162 }
163 last.push_str(&delta);
164 } else {
165 self.output_lines.push(format!("\x01{}", delta));
166 }
167 }
168 TuiMessage::WorkflowCompleted => {
169 self.output_lines.push("✓ Workflow completed".to_string());
170 self.output_lines.push("".to_string());
171 if self.workflow_state == WorkflowState::Running {
172 self.workflow_state = WorkflowState::Cancelling;
173 }
174 }
175 TuiMessage::WorkflowError(err) => {
176 self.output_lines.push(format!("✗ Error: {}", err));
177 self.output_lines.push("".to_string());
178 if self.workflow_state == WorkflowState::Running {
179 self.workflow_state = WorkflowState::Cancelling;
180 }
181 }
182 TuiMessage::TodoUpdate(content) => {
183 self.todo_lines = content.lines().map(|l| l.to_string()).collect();
184 }
185 TuiMessage::ToolPending { tool_name, hint } => {
186 let label = match &hint {
187 Some(h) => format!("⠋ {} {}", tool_name, h),
188 None => format!("⠋ {}", tool_name),
189 };
190 let idx = self.output_lines.len();
191 self.output_lines.push(label);
192 self.pending_tool_lines.push((tool_name, idx, hint));
193 }
194 TuiMessage::ToolDone { tool_name, success, hint } => {
195 let status = if success { "✓" } else { "✗" };
196 if let Some(pos) = self.pending_tool_lines.iter().position(|(n, _, _)| *n == tool_name) {
197 let (_, idx, pending_hint) = self.pending_tool_lines.remove(pos);
198 let h = hint.or(pending_hint);
199 let label = match &h {
200 Some(h) => format!("{} {} {}", status, tool_name, h),
201 None => format!("{} {}", status, tool_name),
202 };
203 if idx < self.output_lines.len() {
204 self.output_lines[idx] = label;
205 return;
206 }
207 self.output_lines.push(label);
208 } else {
209 let label = match &hint {
210 Some(h) => format!("{} {} {}", status, tool_name, h),
211 None => format!("{} {}", status, tool_name),
212 };
213 self.output_lines.push(label);
214 }
215 }
216 TuiMessage::ResumeInfo(info) => {
217 if self.workflow_state == WorkflowState::Cancelling && info.is_none() {
218 self.resume_info = self.backup_resume_info.take();
219 } else if info.is_some() {
220 self.resume_info = info;
226 self.backup_resume_info = None;
227 }
228 if self.workflow_state == WorkflowState::Cancelling {
230 self.workflow_state = WorkflowState::Idle;
231 self.workflow_permit = None;
233 }
234 if self.resume_info.is_some() {
235 if std::env::var("RUST_LOG")
236 .map(|v| v.to_lowercase().contains("debug"))
237 .unwrap_or(false)
238 {
239 self.output_lines.push("🔄 Session preserved — next command will continue this session".to_string());
240 }
241 }
242 if self.workflow_state == WorkflowState::Idle && self.handoff_pending {
243 self.handoff_pending = false;
244 self.trigger_handoff(String::new());
245 } else if let Some(cmd) = self.pending_command.take() {
246 self.input = cmd;
247 self.execute_command();
248 }
249 }
250 TuiMessage::ContextTokensUpdated(count) => {
251 self.current_context_tokens = count;
252 if self.auto_handoff.enabled
253 && count >= self.auto_handoff.context_threshold
254 && self.workflow_state == WorkflowState::Running
255 && !self.handoff_pending
256 && self.resume_info.is_some()
257 {
258 self.handoff_pending = true;
259 self.cancel_token.cancel();
260 self.workflow_state = WorkflowState::Cancelling;
261 self.output_lines.push(format!(
262 "🔄 Auto-handoff: cancelling workflow, context tokens ({}) ≥ threshold ({})",
263 count, self.auto_handoff.context_threshold
264 ));
265 }
266 }
267 TuiMessage::McpServerStatus { name, connected, tool_count, error } => {
268 let status = if connected { McpServerStatus::Connected } else { McpServerStatus::Failed };
269 if let Some(existing) = self.mcp_servers.iter_mut().find(|s| s.name == name) {
270 existing.status = status;
271 existing.tool_count = tool_count;
272 existing.error = error;
273 } else {
274 self.mcp_servers.push(McpServerInfo { name, status, tool_count, error });
275 }
276 }
277 TuiMessage::HandoffReady(briefing) => {
278 self.workflow_state = WorkflowState::Idle;
279 self.resume_info = None;
280 self.input = briefing;
281 self.execute_command();
282 }
283 }
284 if self.auto_scroll {
285 }
288 }
289
290 pub fn execute_command(&mut self) {
295 let command = self.input.trim().to_string();
296
297 if self.workflow_state != WorkflowState::Idle {
298 self.pending_command = Some(command);
299 self.output_lines.push("⏳ Previous workflow finishing — command queued".to_string());
300 self.input.clear();
301 return;
302 }
303
304 let is_continuation = self.resume_info.is_some();
305
306 if !is_continuation {
307 self.output_lines.clear();
308 if self.session_name.is_none() {
311 let derived = if command.len() > 80 {
312 format!("{}...", &command[..77])
313 } else {
314 command.clone()
315 };
316 self.session_name = Some(derived);
317 }
318 }
319
320 self.output_lines.push(format!("> {}", command));
321
322 let config_toml = match &self.config_toml {
323 Some(c) => c.clone(),
324 None => {
325 self.output_lines.push("✗ Error: Configuration not loaded".to_string());
326 self.output_lines.push("".to_string());
327 return;
328 }
329 };
330
331 let secrets = self.secrets.clone().unwrap_or_default();
332 let build_info = self.build_info.clone();
333 let tx = self.workflow_tx.clone();
334
335 let agent_name = self.agent_name.clone();
336 let token_store = self.token_store.clone();
337 let project_id = self.project_id.clone();
338 let project_name = self.project_name.clone();
339 let session_id = self.session_id.clone();
340 let session_name = self.session_name.clone();
341
342 self.backup_resume_info = self.resume_info.clone();
343 let resume_info = self.resume_info.take();
344
345 self.workflow_state = WorkflowState::Running;
346 self.auto_scroll = true;
347
348 self.cancel_token = CancellationToken::new();
349 let child_token = self.cancel_token.clone();
350
351 let (resume_tx, mut resume_rx) = mpsc::unbounded_channel();
352
353 let resume_forward_tx = tx.clone();
354 tokio::spawn(async move {
355 while let Some(info) = resume_rx.recv().await {
356 resume_forward_tx.send(TuiMessage::ResumeInfo(info)).ok();
357 }
358 });
359
360 tokio::spawn(async move {
361 let tui_sink: abk::orchestration::output::SharedSink =
362 Arc::new(crate::session::TuiForwardSink::new(tx.clone()));
363
364 let mut run_ctx = RunContext::new()
366 .with_agent_name(agent_name.clone());
367
368 if project_id.is_some() || project_name.is_some() {
370 run_ctx = run_ctx.with_project(abk::context::ProjectIdentity {
371 id: project_id.unwrap_or_else(|| "default".to_string()),
372 name: project_name,
373 });
374 }
375
376 if session_id.is_some() || session_name.is_some() {
378 run_ctx = run_ctx.with_session(abk::context::SessionIdentity {
379 id: session_id.unwrap_or_else(|| "default".to_string()),
380 name: session_name,
381 });
382 }
383
384 #[cfg(feature = "registry-mcp-token")]
385 {
386 if let Some(ref ts) = token_store {
387 run_ctx = run_ctx.with_token_store(ts.clone());
388 }
389 }
390
391 let result = abk::observability::with_tui_mode(true, async {
395 abk::cli::run_task_from_raw_config(
396 &config_toml,
397 secrets,
398 build_info,
399 &command,
400 Some(tui_sink),
401 resume_info,
402 Some(resume_tx),
403 Some(child_token),
404 Some(&run_ctx),
405 )
406 .await
407 })
408 .await;
409
410 let task_result = result.unwrap_or_else(|e| abk::cli::TaskResult {
411 success: false,
412 error: Some(e.to_string()),
413 resume_info: None,
418 });
419
420 let msg = if task_result.success {
421 TuiMessage::WorkflowCompleted
422 } else {
423 TuiMessage::WorkflowError(task_result.error.unwrap_or_default())
424 };
425 tx.send(msg).ok();
426 tx.send(TuiMessage::ResumeInfo(task_result.resume_info)).ok();
427 });
428
429 self.input.clear();
430 }
431
432 pub fn trigger_handoff(&mut self, hint: String) {
437 if self.resume_info.is_none() {
438 self.output_lines.push("ℹ Nothing to hand off — run a task first".to_string());
439 return;
440 }
441
442 let config_toml = match &self.config_toml {
443 Some(c) => c.clone(),
444 None => {
445 self.output_lines.push("✗ Error: Configuration not loaded".to_string());
446 return;
447 }
448 };
449
450 let secrets = self.secrets.clone().unwrap_or_default();
451 let build_info = self.build_info.clone();
452 let tx = self.workflow_tx.clone();
453
454 let agent_name = self.agent_name.clone();
455 let token_store = self.token_store.clone();
456
457 let resume_info = self.resume_info.take();
458
459 self.workflow_state = WorkflowState::Running;
460 self.auto_scroll = true;
461 self.cancel_token = CancellationToken::new();
462 let child_token = self.cancel_token.clone();
463
464 self.output_lines.push("🔀 Generating session handoff briefing...".to_string());
465
466 tokio::spawn(async move {
467 let (cap_tx, mut cap_rx) = mpsc::unbounded_channel::<CapturedText>();
468 let cap_sink: abk::orchestration::output::SharedSink =
469 Arc::new(HandoffCaptureSink::new(cap_tx, child_token.clone()));
470
471 let base = "Output a session handoff briefing in at most 300 lines. \
472 Do NOT use any tools. Include: the FULL ABSOLUTE PATH of every \
473 project/repository being worked on (e.g. /Projects/Foo/bar — never \
474 omit the leading path), all project/task/workstream UUIDs referenced, \
475 every file created or modified with its full absolute path, all \
476 commands run and their outcomes, the current state of the work, any \
477 blockers, and the exact next action to take. \
478 Output ONLY the briefing text — no preamble, headers, or closing remarks.";
479 let prompt = if hint.is_empty() {
480 base.to_string()
481 } else {
482 format!("{base}\n\nIn the briefing also consider: {hint}")
483 };
484
485 let (dummy_tx, _dummy_rx) = mpsc::unbounded_channel();
486
487 let run_ctx = RunContext::new()
489 .with_agent_name(agent_name.clone());
490 #[cfg(feature = "registry-mcp-token")]
491 {
492 }
495
496 let _res = abk::observability::with_tui_mode(true, async {
498 abk::cli::run_task_from_raw_config(
499 &config_toml,
500 secrets,
501 build_info,
502 &prompt,
503 Some(cap_sink),
504 resume_info,
505 Some(dummy_tx),
506 Some(child_token),
507 Some(&run_ctx),
508 )
509 .await
510 })
511 .await;
512
513 let mut text_parts = String::new();
514 let mut reasoning_parts = String::new();
515 while let Ok(captured) = cap_rx.try_recv() {
516 match captured {
517 CapturedText::Text(s) => text_parts.push_str(&s),
518 CapturedText::Reasoning(s) => reasoning_parts.push_str(&s),
519 }
520 }
521
522 let briefing = if !text_parts.trim().is_empty() {
523 text_parts.trim().to_string()
524 } else if !reasoning_parts.trim().is_empty() {
525 reasoning_parts.trim().to_string()
526 } else {
527 "Session handoff: briefing unavailable — continue from previous context.".to_string()
528 };
529
530 tx.send(TuiMessage::HandoffReady(briefing)).ok();
531 });
532 }
533}
534
535impl Default for Session {
536 fn default() -> Self {
537 Self::new().0
538 }
539}
540
541pub struct TuiForwardSink {
547 tx: mpsc::UnboundedSender<TuiMessage>,
548 stream_state: AtomicU8,
549}
550
551const STREAM_IDLE: u8 = 0;
553const STREAM_REASONING: u8 = 1;
554const STREAM_CONTENT: u8 = 2;
555
556impl TuiForwardSink {
557 pub fn new(tx: mpsc::UnboundedSender<TuiMessage>) -> Self {
558 Self {
559 tx,
560 stream_state: AtomicU8::new(STREAM_IDLE),
561 }
562 }
563}
564
565impl abk::orchestration::output::OutputSink for TuiForwardSink {
566 fn emit(&self, event: abk::orchestration::output::OutputEvent) {
567 use abk::orchestration::output::OutputEvent;
568
569 let msg = match event {
570 OutputEvent::StreamingChunk { delta } => {
571 if delta.is_empty() {
572 return;
573 }
574 let prev = self.stream_state.swap(STREAM_CONTENT, Ordering::Relaxed);
575 if prev != STREAM_CONTENT {
576 let _ = self.tx.send(TuiMessage::OutputLine(String::new()));
577 }
578 let _ = self.tx.send(TuiMessage::StreamDelta(delta));
579 return;
580 }
581
582 OutputEvent::LlmResponse { text, model } => {
583 TuiMessage::OutputLine(format!("[{}] {}", model, text))
584 }
585
586 OutputEvent::Info { message } => {
587 if message.contains("API call completed successfully") {
589 return;
590 }
591 TuiMessage::OutputLine(message)
592 }
593
594 OutputEvent::WorkflowStarted { task_description } => {
595 TuiMessage::OutputLine(format!("🚀 Workflow started: {}", task_description))
596 }
597
598 OutputEvent::WorkflowCompleted { reason, iterations } => {
599 TuiMessage::OutputLine(format!(
600 "✅ Workflow completed after {} iterations: {}",
601 iterations, reason
602 ))
603 }
604
605 OutputEvent::IterationStarted { iteration, context_tokens } => {
606 let _ = self.tx.send(TuiMessage::ContextTokensUpdated(context_tokens));
607 TuiMessage::OutputLine(format!(
608 "📡 Iteration {} | Context = {} tokens",
609 iteration, context_tokens
610 ))
611 }
612
613 OutputEvent::ApiCallStarted {
614 call_number,
615 model,
616 tool_count,
617 streaming,
618 context_tokens,
619 tool_tokens,
620 } => {
621 let mode = if streaming { "Streaming" } else { "Non-streaming" };
622 let total = context_tokens + tool_tokens;
623 let _ = self.tx.send(TuiMessage::ContextTokensUpdated(total));
624 let _ = self.tx.send(TuiMessage::OutputLine(String::new()));
626 TuiMessage::OutputLine(format!(
627 "🔥 API Call {} | Ctx={}({}+{}) | {} | Model: {} | Tools: {}",
628 call_number, total, context_tokens, tool_tokens, mode, model, tool_count
629 ))
630 }
631
632 OutputEvent::ToolsExecuting { tool_names, hints } => {
633 for (name, hint) in tool_names.into_iter().zip(hints.into_iter()) {
634 let _ = self.tx.send(TuiMessage::ToolPending { tool_name: name, hint });
635 }
636 self.stream_state.store(STREAM_IDLE, Ordering::Relaxed);
637 return;
638 }
639
640 OutputEvent::ToolCompleted {
641 tool_name,
642 success,
643 content,
644 description,
645 } => {
646 if tool_name == "todowrite" && success {
647 let _ = self.tx.send(TuiMessage::TodoUpdate(content.clone()));
648 }
649 let hint = description;
650 let _ = self.tx.send(TuiMessage::ToolDone { tool_name, success, hint });
651 self.stream_state.store(STREAM_IDLE, Ordering::Relaxed);
652 return;
653 }
654
655 OutputEvent::Error { message, context } => {
656 if let Some(ctx) = context {
657 TuiMessage::OutputLine(format!("❌ Error: {} — {}", message, ctx))
658 } else {
659 TuiMessage::OutputLine(format!("❌ Error: {}", message))
660 }
661 }
662
663 OutputEvent::ReasoningChunk { delta } => {
664 if delta.is_empty() {
665 return;
666 }
667 let prev = self.stream_state.swap(STREAM_REASONING, Ordering::Relaxed);
668 if prev != STREAM_REASONING {
669 let _ = self.tx.send(TuiMessage::OutputLine(String::new()));
670 }
671 let _ = self.tx.send(TuiMessage::ReasoningDelta(delta));
672 return;
673 }
674
675 OutputEvent::McpServerStatus { name, connected, tool_count, error } => {
676 let _ = self.tx.send(TuiMessage::McpServerStatus {
677 name,
678 connected,
679 tool_count,
680 error,
681 });
682 return;
683 }
684 };
685
686 self.stream_state.store(STREAM_IDLE, Ordering::Relaxed);
687 let _ = self.tx.send(msg);
688 }
689}