Skip to main content

trustee_core/
session.rs

1//! Session state — core agent session without any UI concerns.
2//!
3//! This struct holds all the state shared between frontends (TUI, API, Web):
4//! output lines, input, workflow state, config, resume info, MCP servers, etc.
5
6use 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, McpServerInfo, McpServerStatus,
19    TuiMessage, WorkflowState,
20};
21
22/// Truncate a first-command string into a display session name.
23///
24/// Never slices by raw byte index: non-ASCII scripts (Persian, Arabic, CJK,
25/// emoji, …) are multi-byte in UTF-8 and a fixed byte cut can land mid-
26/// character, which PANICS ("byte index is not a char boundary") inside the
27/// tokio worker and poisons the session mutex (nghr 811ed903).
28///
29/// Semantics: ≤ 80 CHARS → returned unchanged (pure-ASCII behavior is
30/// byte-for-byte identical to the original implementation); > 80 chars →
31/// truncated at the last char boundary at or before byte 77, plus "...".
32pub fn truncate_session_name(command: &str) -> String {
33    if command.chars().count() <= 80 {
34        command.to_string()
35    } else {
36        let end = command
37            .char_indices()
38            .map(|(i, _)| i)
39            .take_while(|&i| i <= 77)
40            .last()
41            .unwrap_or(0);
42        format!("{}...", &command[..end])
43    }
44}
45
46/// Core session state for the Trustee agent.
47///
48/// Holds all state that is independent of the presentation layer (TUI, API, Web).
49/// Frontend crates compose this struct and add their own UI-specific fields.
50pub struct Session {
51    /// Input buffer for user commands
52    pub input: String,
53    /// Output log lines
54    pub output_lines: Vec<String>,
55    /// Sender for messages from async workflows (clone and pass to workflow runners)
56    pub workflow_tx: mpsc::UnboundedSender<TuiMessage>,
57    /// Current workflow lifecycle state
58    pub workflow_state: WorkflowState,
59    /// Configuration TOML for ABK workflows
60    pub config_toml: Option<String>,
61    /// Secrets for ABK workflows
62    pub secrets: Option<HashMap<String, String>>,
63    /// Build info for ABK workflows
64    pub build_info: Option<BuildInfo>,
65    /// Resume info from the last completed task for session continuity
66    pub resume_info: Option<ResumeInfo>,
67    /// Saved resume_info before execute_command consumes it; restored if task
68    /// is cancelled before producing a real checkpoint (mistake-ENTER recovery).
69    pub backup_resume_info: Option<ResumeInfo>,
70    /// Latest todo list from LLM todowrite tool
71    pub todo_lines: Vec<String>,
72    /// Cancellation token for aborting the current workflow
73    pub cancel_token: CancellationToken,
74    /// Command buffered by user during cancellation wind-down.
75    pub pending_command: Option<String>,
76    /// Whether a session handoff (Ctrl+H) should fire once the current workflow cancels.
77    pub handoff_pending: bool,
78    /// In-flight spinner entries: (tool_name, output_lines_index, hint).
79    pub pending_tool_lines: Vec<(String, usize, Option<String>)>,
80    /// Current context token count (updated from ApiCallStarted events).
81    pub current_context_tokens: usize,
82    /// Auto-handoff configuration parsed from [tui.auto_handoff].
83    pub auto_handoff: AutoHandoffConfig,
84    /// MCP server statuses received from agent init
85    pub mcp_servers: Vec<McpServerInfo>,
86    /// Whether the session should quit
87    pub should_quit: bool,
88    /// Whether auto-scroll is enabled (follows new output)
89    pub auto_scroll: bool,
90
91    // --- TMU Phase 1: Stateless Core ---
92    /// Agent name for checkpoint/token paths (replaces ABK_AGENT_NAME env var).
93    /// Defaults to "trustee". Set from config at startup.
94    pub agent_name: String,
95    /// Per-session token store (None = FileTokenStore fallback).
96    /// When set, MCP credential flows use this instead of file-based storage.
97    pub token_store: Option<Arc<dyn pep::token_store::TokenStore>>,
98
99    // --- Project/Session Identity (backward compatible, all None = old behavior) ---
100    /// Storage partition key (replaces path hash). None = hash(working_dir)
101    pub project_id: Option<String>,
102    /// Human-readable project name. None = directory name
103    pub project_name: Option<String>,
104    /// Storage directory name (replaces timestamp slug). None = auto-generate
105    pub session_id: Option<String>,
106    /// Human-readable session name. None = no description
107    pub session_name: Option<String>,
108    /// Per-user home directory for checkpoint storage. None = default ~/.{agent_name}/
109    /// Set to ~/.trustee/users/{user_hash}/ for per-user isolation in web mode.
110    pub home_dir: Option<std::path::PathBuf>,
111
112    /// Concurrency permit — held while a workflow is running.
113    /// When the workflow completes (state → Idle), this is dropped,
114    /// releasing the permit back to the global semaphore.
115    /// None when no workflow is running or when concurrency limiting is disabled.
116    pub workflow_permit: Option<tokio::sync::OwnedSemaphorePermit>,
117
118    /// Optional agent identity content (e.g. fetched from Fame).
119    /// When set, prepended to `lifecycle.system_template` in the config
120    /// clone inside `execute_command()` and `trigger_handoff()`.
121    /// None = use the config's default system template.
122    pub identity: Option<String>,
123
124    /// Optional model override for the next command.
125    /// When set, `[llm.providers.{model}]` from the config TOML is injected
126    /// into `[llm.provider]` before creating the agent, switching the LLM
127    /// for that command. Consumed per-command (cleared after injection).
128    /// None = use the default `[llm.provider]`.
129    pub model: Option<String>,
130
131    // --- Handoff rotation (post 0.9.16 bugs) ---
132    /// Set to true immediately before the post-handoff briefing execute, so
133    /// `execute_command` treats that run as a rotation rather than a fresh
134    /// session: it derives a new chain identity but does NOT clear the
135    /// visible transcript (Bug 2). Cleared once the rotation is handled.
136    pub rotating_from_handoff: bool,
137    /// True while the current chain identity was born from a handoff briefing
138    /// and no user command has run in it yet (Bug 4). While true, handoff is
139    /// blocked entirely (manual + auto) to prevent briefing-of-briefing loops.
140    /// Cleared on the first user-initiated command.
141    pub briefing_born: bool,
142    /// Monotonic count of handoff rotations this session has performed.
143    /// Surfaced in live-session listings so the UI can show lineage
144    /// (Bug 5: "name rotated silently" → "name · ↻2").
145    pub handoff_count: u32,
146}
147
148impl Session {
149    /// Create a new Session with default state and a fresh message channel.
150    ///
151    /// Returns `(Session, Receiver)` so the caller can own the receiver
152    /// without locking the session (prevents deadlock in async drain loops).
153    pub fn new() -> (Self, mpsc::UnboundedReceiver<TuiMessage>) {
154        let (workflow_tx, workflow_rx) = mpsc::unbounded_channel();
155        let session = Self {
156            input: String::new(),
157            output_lines: Vec::new(),
158            workflow_tx,
159            workflow_state: WorkflowState::Idle,
160            config_toml: None,
161            secrets: None,
162            build_info: None,
163            resume_info: None,
164            backup_resume_info: None,
165            todo_lines: Vec::new(),
166            cancel_token: CancellationToken::new(),
167            pending_command: None,
168            handoff_pending: false,
169            pending_tool_lines: Vec::new(),
170            current_context_tokens: 0,
171            auto_handoff: AutoHandoffConfig::default(),
172            mcp_servers: Vec::new(),
173            should_quit: false,
174            auto_scroll: true,
175            agent_name: "trustee".to_string(),
176            token_store: None,
177            project_id: None,
178            project_name: None,
179            session_id: None,
180            session_name: None,
181            home_dir: None,
182            workflow_permit: None,
183            identity: None,
184            model: None,
185            rotating_from_handoff: false,
186            briefing_born: false,
187            handoff_count: 0,
188        };
189        (session, workflow_rx)
190    }
191
192    /// Parse auto-handoff configuration from the stored config TOML.
193    pub fn parse_auto_handoff_config(&mut self) {
194        if let Some(ref config_toml) = self.config_toml {
195            self.auto_handoff = crate::config::parse_auto_handoff_config(config_toml);
196        }
197    }
198
199    /// Handle messages from async workflows.
200    ///
201    /// This processes all workflow lifecycle events, output updates, and state transitions.
202    /// Returns `true` if the caller should check for pending commands/handoffs after.
203    pub fn handle_workflow_message(&mut self, msg: TuiMessage) {
204        match msg {
205            TuiMessage::WorkflowCancelled => {
206                self.output_lines.push("⏹ Workflow cancelled".to_string());
207                self.output_lines.push("".to_string());
208                self.workflow_state = WorkflowState::Cancelling;
209            }
210            TuiMessage::OutputLine(line) => {
211                self.output_lines.push(line);
212            }
213            TuiMessage::StreamDelta(delta) => {
214                if let Some(last) = self.output_lines.last_mut() {
215                    last.push_str(&delta);
216                } else {
217                    self.output_lines.push(delta);
218                }
219            }
220            TuiMessage::ReasoningDelta(delta) => {
221                if let Some(last) = self.output_lines.last_mut() {
222                    if !last.starts_with('\x01') {
223                        last.insert(0, '\x01');
224                    }
225                    last.push_str(&delta);
226                } else {
227                    self.output_lines.push(format!("\x01{}", delta));
228                }
229            }
230            TuiMessage::WorkflowCompleted => {
231                self.output_lines.push("✓ Workflow completed".to_string());
232                self.output_lines.push("".to_string());
233                if self.workflow_state == WorkflowState::Running {
234                    self.workflow_state = WorkflowState::Cancelling;
235                }
236            }
237            TuiMessage::WorkflowError(err) => {
238                self.output_lines.push(format!("✗ Error: {}", err));
239                self.output_lines.push("".to_string());
240                if self.workflow_state == WorkflowState::Running {
241                    self.workflow_state = WorkflowState::Cancelling;
242                }
243            }
244            TuiMessage::TodoUpdate(content) => {
245                self.todo_lines = content.lines().map(|l| l.to_string()).collect();
246            }
247            TuiMessage::ToolPending { tool_name, hint } => {
248                let label = match &hint {
249                    Some(h) => format!("⠋ {} {}", tool_name, h),
250                    None => format!("⠋ {}", tool_name),
251                };
252                let idx = self.output_lines.len();
253                self.output_lines.push(label);
254                self.pending_tool_lines.push((tool_name, idx, hint));
255            }
256            TuiMessage::ToolDone { tool_name, success, hint } => {
257                let status = if success { "✓" } else { "✗" };
258                if let Some(pos) = self.pending_tool_lines.iter().position(|(n, _, _)| *n == tool_name) {
259                    let (_, idx, pending_hint) = self.pending_tool_lines.remove(pos);
260                    let h = hint.or(pending_hint);
261                    let label = match &h {
262                        Some(h) => format!("{} {} {}", status, tool_name, h),
263                        None => format!("{} {}", status, tool_name),
264                    };
265                    if idx < self.output_lines.len() {
266                        self.output_lines[idx] = label;
267                        return;
268                    }
269                    self.output_lines.push(label);
270                } else {
271                    let label = match &hint {
272                        Some(h) => format!("{} {} {}", status, tool_name, h),
273                        None => format!("{} {}", status, tool_name),
274                    };
275                    self.output_lines.push(label);
276                }
277            }
278            TuiMessage::ResumeInfo(info) => {
279                if self.workflow_state == WorkflowState::Cancelling && info.is_none() {
280                    self.resume_info = self.backup_resume_info.take();
281                } else if info.is_some() {
282                    // Only overwrite with a valid resume_info.
283                    // Don't let ResumeInfo(None) clobber a valid Some that was
284                    // set by an earlier incremental checkpoint message — this
285                    // happens when the error/cancel path fails to create a
286                    // final checkpoint but earlier checkpoints exist.
287                    self.resume_info = info;
288                    self.backup_resume_info = None;
289                }
290                // If info is None and we're not cancelling, keep existing resume_info.
291
292                // Capture session_id from resume_info so it persists for the
293                // lifetime of this conversation. This is immutable — once ABK
294                // assigns it, we never change it.
295                if let Some(ref ri) = self.resume_info {
296                    if self.session_id.is_none() {
297                        self.session_id = Some(ri.session_id.clone());
298                    }
299                }
300
301                if self.workflow_state == WorkflowState::Cancelling {
302                    self.workflow_state = WorkflowState::Idle;
303                    // Release the concurrency permit when the workflow finishes.
304                    self.workflow_permit = None;
305                }
306                if self.resume_info.is_some() {
307                    if std::env::var("RUST_LOG")
308                        .map(|v| v.to_lowercase().contains("debug"))
309                        .unwrap_or(false)
310                    {
311                        self.output_lines.push("🔄 Session preserved — next command will continue this session".to_string());
312                    }
313                }
314                if self.workflow_state == WorkflowState::Idle && self.handoff_pending {
315                    self.handoff_pending = false;
316                    self.trigger_handoff(String::new());
317                } else if let Some(cmd) = self.pending_command.take() {
318                    self.input = cmd;
319                    self.execute_command();
320                }
321            }
322            TuiMessage::ContextTokensUpdated(count) => {
323                self.current_context_tokens = count;
324                if self.auto_handoff.enabled
325                    && count >= self.auto_handoff.context_threshold
326                    && self.workflow_state == WorkflowState::Running
327                    && !self.handoff_pending
328                    && self.resume_info.is_some()
329                    // Bug 4: never auto-handoff a briefing-born chain — a large
330                    // briefing inflating the context would chain handoffs into a
331                    // briefing-of-briefing loop. Auto-handoff only re-arms after
332                    // a real user command has run in this chain.
333                    && !self.briefing_born
334                {
335                    self.handoff_pending = true;
336                    self.cancel_token.cancel();
337                    self.workflow_state = WorkflowState::Cancelling;
338                    self.output_lines.push(format!(
339                        "🔄 Auto-handoff: cancelling workflow, context tokens ({}) ≥ threshold ({})",
340                        count, self.auto_handoff.context_threshold
341                    ));
342                }
343            }
344            TuiMessage::McpServerStatus { name, connected, tool_count, error } => {
345                let status = if connected { McpServerStatus::Connected } else { McpServerStatus::Failed };
346                if let Some(existing) = self.mcp_servers.iter_mut().find(|s| s.name == name) {
347                    existing.status = status;
348                    existing.tool_count = tool_count;
349                    existing.error = error;
350                } else {
351                    self.mcp_servers.push(McpServerInfo { name, status, tool_count, error });
352                }
353            }
354            TuiMessage::HandoffReady(briefing) => {
355                self.workflow_state = WorkflowState::Idle;
356                self.resume_info = None;
357                // Capture the pre-rotation chain id so the rotation event can
358                // tell clients exactly which chain was replaced (Bug 1).
359                let old_session_id = self.session_id.clone();
360                // Clear session identity so execute_command generates fresh
361                // session_id/session_name for the new post-handoff session.
362                self.session_id = None;
363                self.session_name = None;
364                // Rotation markers (Bugs 2/4): preserve the transcript across
365                // the identity switch, and mark the new chain as briefing-born
366                // so it can't immediately hand off again (briefing-of-briefing
367                // loop) until a real user command runs in it.
368                self.rotating_from_handoff = true;
369                self.briefing_born = true;
370                self.handoff_count += 1;
371                self.input = briefing;
372                self.execute_command();
373                // execute_command derives the new chain id synchronously —
374                // broadcast the explicit rotation event so clients adopt the
375                // new identity without inferring it from ResumeInfo (Bug 1).
376                let _ = self.workflow_tx.send(TuiMessage::SessionRotated {
377                    old: old_session_id,
378                    new: self.session_id.clone(),
379                });
380            }
381            TuiMessage::SessionRotated { .. } => {
382                // Identity rotation already applied in-place by the
383                // HandoffReady handler. This event is for external clients
384                // (web/torpi consoles) — nothing to do in session state.
385            }
386            TuiMessage::HandoffFailed => {
387                // Briefing unavailable — session continuity was already restored
388                // by the ResumeInfo(Some) that precedes this message. Return to
389                // Idle so the user can retry or continue manually (Bug 5/8).
390                self.workflow_state = WorkflowState::Idle;
391                self.output_lines.push(
392                    "✗ Handoff briefing unavailable — session preserved, try again.".to_string(),
393                );
394                self.output_lines.push("".to_string());
395            }
396            TuiMessage::SessionTitleUpdated(title) => {
397                // LLM-generated title has arrived — update the session name.
398                self.session_name = Some(title);
399            }
400        }
401        if self.auto_scroll {
402            // Signal to frontend that it should scroll to bottom.
403            // Frontend reads auto_scroll flag directly.
404        }
405    }
406
407    /// Execute the current command in the input buffer.
408    ///
409    /// Spawns an async ABK workflow task, clears the input buffer, and sets
410    /// workflow_state to Running.
411    pub fn execute_command(&mut self) {
412        let command = self.input.trim().to_string();
413
414        if self.workflow_state != WorkflowState::Idle {
415            self.pending_command = Some(command);
416            self.output_lines.push("⏳ Previous workflow finishing — command queued".to_string());
417            self.input.clear();
418            return;
419        }
420
421        let is_continuation = self.resume_info.is_some();
422
423        // Rotation gate (Bug 2): the post-handoff briefing execute is a
424        // "fresh chain" run (resume_info == None) but NOT a fresh session —
425        // the user's visible transcript must survive the identity switch.
426        // Take the flag so it applies exactly once, to this run.
427        let rotating_from_handoff = self.rotating_from_handoff;
428        self.rotating_from_handoff = false;
429
430        // Bug 4: the first command that is NOT the briefing run itself is a
431        // real user command — the briefing-born lock lifts and handoff
432        // (manual and auto) re-arms for this chain.
433        if !rotating_from_handoff {
434            self.briefing_born = false;
435        }
436
437// Transcript gate (Bug 2): never wipe the visible transcript for a
438        // session that has rotated its chain identity. This covers the
439        // briefing run itself (rotating_from_handoff) AND any later command
440        // that lands on the non-continuation path (e.g. after a failed
441        // checkpoint) — a rotated session is one logical conversation, not a
442        // fresh one.
443        if !is_continuation && !rotating_from_handoff && self.handoff_count == 0 {
444            self.output_lines.clear();
445        }
446        // Identity derivation: applies to EVERY non-continuation run (fresh
447        // session OR handoff rotation) — a rotated session must get its new
448        // chain id immediately so the SessionRotated event can carry it.
449        if !is_continuation {
450            // Auto-derive session_id and session_name from the first command
451            // if not explicitly set. The session_id uses timestamp + UUID suffix
452            // (session_YYYY_MM_DD_HH_MM_{uuid8}) for uniqueness across all
453            // interfaces. The session_name is a human-readable display name
454            // (truncated command text).
455            if self.session_id.is_none() {
456                let timestamp = chrono::Utc::now().format("%Y_%m_%d_%H_%M");
457                let uuid_suffix = uuid::Uuid::new_v4().simple().to_string();
458                let uuid8 = &uuid_suffix[..8];
459                self.session_id = Some(format!("session_{}_{}", timestamp, uuid8));
460            }
461            if self.session_name.is_none() {
462                self.session_name = Some(truncate_session_name(&command));
463            }
464        }
465
466        self.output_lines.push(format!("> {}", command));
467
468        let config_toml = match &self.config_toml {
469            Some(c) => c.clone(),
470            None => {
471                self.output_lines.push("✗ Error: Configuration not loaded".to_string());
472                self.output_lines.push("".to_string());
473                return;
474            }
475        };
476
477        // Inject identity into the config clone if present.
478        let config_toml = inject_identity(config_toml, &self.identity);
479
480        // Inject model override (select from [llm.providers.{model}]) if present.
481        let model_override = self.model.take();
482        let config_toml = inject_model(config_toml, model_override);
483
484        let secrets = self.secrets.clone().unwrap_or_default();
485        // Clone secrets for post-completion title generation (secrets are moved into run_task below)
486        let title_secrets = secrets.clone();
487        let build_info = self.build_info.clone();
488        let tx = self.workflow_tx.clone();
489
490        let agent_name = self.agent_name.clone();
491        let token_store = self.token_store.clone();
492        let project_id = self.project_id.clone();
493        let project_name = self.project_name.clone();
494        let session_id = self.session_id.clone();
495        let session_name = self.session_name.clone();
496        let home_dir = self.home_dir.clone();
497
498        self.backup_resume_info = self.resume_info.clone();
499        let resume_info = self.resume_info.take();
500
501        self.workflow_state = WorkflowState::Running;
502        self.auto_scroll = true;
503
504        self.cancel_token = CancellationToken::new();
505        let child_token = self.cancel_token.clone();
506
507        let (resume_tx, mut resume_rx) = mpsc::unbounded_channel();
508
509        let resume_forward_tx = tx.clone();
510        tokio::spawn(async move {
511            while let Some(info) = resume_rx.recv().await {
512                resume_forward_tx.send(TuiMessage::ResumeInfo(info)).ok();
513            }
514        });
515
516        tokio::spawn(async move {
517            let tui_sink: abk::orchestration::output::SharedSink =
518                Arc::new(crate::session::TuiForwardSink::new(tx.clone()));
519
520            // Build RunContext from session fields for stateless operation
521            let mut run_ctx = RunContext::new()
522                .with_agent_name(agent_name.clone());
523
524            // Set home_dir for per-user isolation if provided
525            if let Some(ref dir) = home_dir {
526                run_ctx = run_ctx.with_home_dir(dir.clone());
527            }
528
529            // Set project identity if any field is provided
530            if project_id.is_some() || project_name.is_some() {
531                run_ctx = run_ctx.with_project(abk::context::ProjectIdentity {
532                    id: project_id.unwrap_or_else(|| "default".to_string()),
533                    name: project_name,
534                });
535            }
536
537            // Set session identity if any field is provided
538            if session_id.is_some() || session_name.is_some() {
539                run_ctx = run_ctx.with_session(abk::context::SessionIdentity {
540                    id: session_id.unwrap_or_else(|| "default".to_string()),
541                    name: session_name,
542                });
543            }
544
545            #[cfg(feature = "registry-mcp-token")]
546            {
547                if let Some(ref ts) = token_store {
548                    run_ctx = run_ctx.with_token_store(ts.clone());
549                }
550            }
551
552            // Run the entire workflow inside a TUI-mode scope and a
553            // per-task logger scope. This replaces the old process-global
554            // set_tui_mode()/init_global_logger() mutations with task-local
555            // scopes, enabling safe concurrent multi-user operation.
556            let scope_logger = {
557                abk::observability::Logger::with_agent_name(
558                    None::<&std::path::Path>,
559                    Some("INFO"),
560                    Some(&agent_name),
561                ).unwrap_or_else(|_| abk::observability::Logger::new(None, Some("INFO")).unwrap())
562            };
563
564            let result = abk::observability::with_logger(scope_logger, async {
565                abk::observability::with_tui_mode(true, async {
566                    abk::cli::run_task_from_raw_config(
567                        &config_toml,
568                        secrets,
569                        build_info,
570                        &command,
571                        Some(tui_sink),
572                        resume_info,
573                        Some(resume_tx),
574                        Some(child_token),
575                        Some(&run_ctx),
576                    )
577                    .await
578                })
579                .await
580            })
581            .await;
582
583            let task_result = result.unwrap_or_else(|e| abk::cli::TaskResult {
584                success: false,
585                error: Some(e.to_string()),
586                // resume_info will be None here, but the on_checkpoint channel
587                // may have already delivered a valid ResumeInfo via TuiMessage.
588                // The ResumeInfo handler now ignores None when a valid Some exists,
589                // so this None won't clobber the earlier incremental checkpoint.
590                resume_info: None,
591            });
592
593            let msg = if task_result.success {
594                TuiMessage::WorkflowCompleted
595            } else {
596                TuiMessage::WorkflowError(task_result.error.unwrap_or_default())
597            };
598
599            // Capture session_id from resume_info before it's moved into the channel
600            let title_session_id = task_result.resume_info
601                .as_ref()
602                .map(|ri| ri.session_id.clone());
603
604            tx.send(msg).ok();
605            tx.send(TuiMessage::ResumeInfo(task_result.resume_info)).ok();
606
607            // Solution B: After successful completion, spawn a lightweight LLM call
608            // to generate a descriptive session title. The title is:
609            // 1. Persisted to session_metadata.json on disk via persist_session_title
610            // 2. Sent via SessionTitleUpdated message (updates in-memory session_name)
611            // Only fires if the title hasn't been LLM-set yet.
612            // Fire-and-forget — errors don't affect the session.
613            if task_result.success {
614                let title_tx = tx.clone();
615                let title_config = config_toml.clone();
616                let title_command = command.clone();
617                let title_ctx = run_ctx.clone();
618
619                tokio::spawn(async move {
620                    // Only generate titles for truly fresh sessions.
621                    // Check the disk: if session already has checkpoints from prior
622                    // runs, or description is already set, skip.
623                    if let Some(ref sid) = title_session_id {
624                        if !abk::cli::should_generate_title(&title_ctx, sid, &title_command).await {
625                            return;
626                        }
627                    } else {
628                        return; // No session ID — can't safely persist
629                    }
630
631                    // Small delay to ensure checkpoint metadata writes complete first
632                    tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
633
634                    // Re-check after delay (checkpoint may have written metadata)
635                    if let Some(ref sid) = title_session_id {
636                        if !abk::cli::should_generate_title(&title_ctx, sid, &title_command).await {
637                            return;
638                        }
639                    }
640
641                    match abk::cli::generate_session_title(
642                        &title_config,
643                        title_secrets,
644                        &title_command,
645                    )
646                    .await
647                    {
648                        Ok(Some(title)) => {
649                            // Persist to disk + remote
650                            if let Some(ref sid) = title_session_id {
651                                if let Err(e) = abk::cli::persist_session_title(
652                                    &title_ctx,
653                                    &title_config,
654                                    sid,
655                                    &title,
656                                ).await {
657                                    let _ = e; // non-fatal
658                                }
659                            }
660                            // Update in-memory session name for live WS clients
661                            title_tx.send(TuiMessage::SessionTitleUpdated(title)).ok();
662                        }
663                        Ok(None) => {}
664                        Err(e) => { let _ = e; }
665                    }
666                });
667            }
668        });
669
670        self.input.clear();
671    }
672
673    /// Request a session handoff through the safe state-machine entry point.
674    ///
675    /// Mirrors the TUI Ctrl+H behavior:
676    /// - Idle → trigger the handoff immediately
677    /// - Running → cancel the workflow, fire handoff once it stops
678    /// - Cancelling → queue handoff for when it stops
679    ///
680    /// This prevents any caller (web button, API, future MCP tool) from
681    /// spawning a briefing task concurrently with a running workflow
682    /// (Bugs 1/2/5).
683    pub fn request_handoff(&mut self, hint: String) {
684        // Bug 4: a session born from a handoff briefing cannot hand off again
685        // before a user command has run in it. Manual double-triggers during
686        // handoff investigation spawned two extra chains in 3 minutes; the
687        // second briefing was literally about the first briefing. Explicit
688        // user action may re-arm it only after real work has happened.
689        if self.briefing_born {
690            self.workflow_tx
691                .send(TuiMessage::OutputLine(
692                    "ℹ Handoff unavailable — this session started from a handoff briefing. Run a command first.".to_string(),
693                ))
694                .ok();
695            return;
696        }
697        match self.workflow_state {
698            WorkflowState::Idle => self.trigger_handoff(hint),
699            WorkflowState::Running => {
700                self.cancel_token.cancel();
701                self.workflow_state = WorkflowState::Cancelling;
702                self.handoff_pending = true;
703                // Broadcast via the message channel so live UI (web/TUI) sees
704                // the status immediately. A direct output_lines.push() would
705                // only appear after a page refresh (output_lines is served via
706                // the /api/v1/session poll, not pushed over WebSocket).
707                self.workflow_tx
708                    .send(TuiMessage::OutputLine("⏹ Cancelling before handoff...".to_string()))
709                    .ok();
710            }
711            WorkflowState::Cancelling => {
712                self.handoff_pending = true;
713            }
714        }
715    }
716
717    /// Trigger a session handoff.
718    ///
719    /// Runs a single LLM call using the current session's resume_info to generate
720    /// a briefing. On completion, sends `TuiMessage::HandoffReady(briefing)`.
721    ///
722    /// This is the internal Idle-only entry point. Callers that may be invoked
723    /// while a workflow is running should use [`Session::request_handoff`].
724    pub fn trigger_handoff(&mut self, hint: String) {
725        // Belt-and-braces guard: never run a briefing concurrently with a
726        // workflow (Bug 1). request_handoff handles the Running/Cancelling
727        // states; direct callers must be Idle.
728        if self.workflow_state != WorkflowState::Idle {
729            self.output_lines
730                .push("⏳ Workflow still running — handoff will fire after it stops".to_string());
731            return;
732        }
733        // Bug 4 (defense in depth): request_handoff already rejects this, but
734        // trigger_handoff is also reachable from the handoff_pending path —
735        // never hand off a chain that hasn't seen a user command yet.
736        if self.briefing_born {
737            self.output_lines
738                .push("ℹ Handoff unavailable — this session started from a handoff briefing. Run a command first.".to_string());
739            return;
740        }
741        if self.resume_info.is_none() {
742            self.output_lines.push("ℹ Nothing to hand off — run a task first".to_string());
743            return;
744        }
745
746        let config_toml = match &self.config_toml {
747            Some(c) => c.clone(),
748            None => {
749                self.output_lines.push("✗ Error: Configuration not loaded".to_string());
750                return;
751            }
752        };
753
754        // Inject identity into the config clone if present.
755        let config_toml = inject_identity(config_toml, &self.identity);
756
757        // Inject model override for handoff briefing (use same model as the session).
758        let model_override = self.model.clone();
759        let config_toml = inject_model(config_toml, model_override);
760
761        let tx = self.workflow_tx.clone();
762        let agent_name = self.agent_name.clone();
763        let project_id = self.project_id.clone();
764        let project_name = self.project_name.clone();
765        let session_id = self.session_id.clone();
766        let session_name = self.session_name.clone();
767        let home_dir = self.home_dir.clone();
768
769        // Preserve resume_info so a failed briefing can restore the session
770        // instead of losing all continuity (Bug 4/8).
771        let backup_resume_info = self.resume_info.clone();
772        let resume_info = match self.resume_info.take() {
773            Some(ri) => ri,
774            None => {
775                // Already checked is_none() above — defensive only.
776                self.output_lines.push("ℹ Nothing to hand off — run a task first".to_string());
777                return;
778            }
779        };
780
781        self.workflow_state = WorkflowState::Running;
782        self.auto_scroll = true;
783        self.cancel_token = CancellationToken::new();
784
785        // Broadcast via the message channel so live UI (web/TUI) sees the
786        // status line immediately. A direct output_lines.push() would only
787        // appear after a page refresh (output_lines is served via the
788        // /api/v1/session poll, not pushed over WebSocket). The drain task
789        // pushes this line to output_lines (via handle_workflow_message) AND
790        // broadcasts StateChanged(Running) + OutputLine to WS clients.
791        self.workflow_tx
792            .send(TuiMessage::OutputLine("🔀 Generating session handoff briefing...".to_string()))
793            .ok();
794
795        tokio::spawn(async move {
796            let base = "Output a session handoff briefing in at most 300 lines. \
797                 Do NOT use any tools. The FIRST line must be exactly: \
798                 \"Session Title: <a concise descriptive title of this work, maximum 50 characters>\" \
799                 — nothing else on that line. The rest of the briefing must include: \
800                 the FULL ABSOLUTE PATH of every \
801                 project/repository being worked on (e.g. /Projects/Foo/bar — never \
802                 omit the leading path), all project/task/workstream UUIDs referenced, \
803                 every file created or modified with its full absolute path, all \
804                 commands run and their outcomes, the current state of the work, any \
805                 blockers, and the exact next action to take. \
806                 Output ONLY the briefing text — the title line first, then the body, \
807                 with no other headers, preamble, or closing remarks.";
808            let prompt = if hint.is_empty() {
809                base.to_string()
810            } else {
811                format!("{base}\n\nIn the briefing also consider: {hint}")
812            };
813
814            // Build RunContext for stateless operation — same fields as execute_command
815            let mut run_ctx = RunContext::new()
816                .with_agent_name(agent_name.clone());
817
818            // Set home_dir for per-user isolation
819            if let Some(ref dir) = home_dir {
820                run_ctx = run_ctx.with_home_dir(dir.clone());
821            }
822
823            // Set project identity if any field is provided
824            if project_id.is_some() || project_name.is_some() {
825                run_ctx = run_ctx.with_project(abk::context::ProjectIdentity {
826                    id: project_id.unwrap_or_else(|| "default".to_string()),
827                    name: project_name,
828                });
829            }
830
831            // Set session identity if any field is provided
832            if session_id.is_some() || session_name.is_some() {
833                run_ctx = run_ctx.with_session(abk::context::SessionIdentity {
834                    id: session_id.unwrap_or_else(|| "default".to_string()),
835                    name: session_name,
836                });
837            }
838
839            // Run inside per-task logger + TUI-mode scope (task-local, not process-global)
840            let scope_logger = abk::observability::Logger::with_agent_name(
841                None,
842                Some("INFO"),
843                Some(&agent_name),
844            ).unwrap_or_else(|_| abk::observability::Logger::new(None, Some("INFO")).unwrap());
845
846            // Single direct LLM call — no agentic workflow loop. This is the fix
847            // for the session-bricking bug: the full workflow ran tools, looped
848            // on the large history, and never completed.
849            let result = abk::observability::with_logger(scope_logger, async {
850                abk::observability::with_tui_mode(true, async {
851                    abk::cli::generate_handoff_briefing(
852                        &config_toml,
853                        &run_ctx,
854                        &resume_info,
855                        &prompt,
856                    )
857                    .await
858                })
859                .await
860            })
861            .await;
862
863            match result {
864                Ok(briefing) if !briefing.trim().is_empty() => {
865                    tx.send(TuiMessage::HandoffReady(briefing)).ok();
866                }
867                _ => {
868                    // Briefing unavailable (LLM failure, truncation, cancel).
869                    // Restore session continuity and surface the failure —
870                    // NEVER auto-execute a garbage fallback string (Bug 8).
871                    tx.send(TuiMessage::ResumeInfo(backup_resume_info)).ok();
872                    tx.send(TuiMessage::HandoffFailed).ok();
873                }
874            }
875        });
876    }
877}
878
879impl Default for Session {
880    fn default() -> Self {
881        Self::new().0
882    }
883}
884
885/// Prepend agent identity to `lifecycle.system_template` in the config TOML.
886///
887/// If `identity` is `None` or empty, returns the config unchanged.
888/// On parse/serialize failure, returns the config unchanged (best-effort).
889fn inject_identity(config_toml: String, identity: &Option<String>) -> String {
890    let Some(identity) = identity.as_ref().filter(|s| !s.is_empty()) else {
891        return config_toml;
892    };
893
894    let Ok(mut table) = config_toml.parse::<toml::Value>() else {
895        return config_toml;
896    };
897
898    let lifecycle = table
899        .get_mut("lifecycle")
900        .and_then(|v| v.as_table_mut());
901
902    if let Some(lifecycle) = lifecycle {
903        let existing = lifecycle
904            .get("system_template")
905            .and_then(|v| v.as_str())
906            .unwrap_or("");
907        let combined = format!("{}\n\n{}", identity, existing);
908        lifecycle.insert(
909            "system_template".to_string(),
910            toml::Value::String(combined),
911        );
912    } else {
913        // No [lifecycle] section — create one with just the identity as template.
914        let mut ltable = toml::value::Table::new();
915        ltable.insert(
916            "system_template".to_string(),
917            toml::Value::String(identity.clone()),
918        );
919        if let Some(table) = table.as_table_mut() {
920            table.insert("lifecycle".to_string(), toml::Value::Table(ltable));
921        }
922    }
923
924    toml::to_string(&table).unwrap_or(config_toml)
925}
926
927/// Override the model for the next command.
928///
929/// `model` is a LITERAL model string (e.g. "GLM-4.7-Flash", "gpt-4o"),
930/// not necessarily a provider key. Resolution order:
931///
932/// 1. If it matches a KEY in `[llm.providers.*]` → swap to that provider,
933///    use its default model.
934/// 2. Else if it appears in some named provider's `models` list (or equals
935///    its `model`) → swap to that provider AND set that model on it.
936/// 3. Else — set it as the `model` on the current provider. This lets users
937///    pass any model name their endpoint accepts even if unlisted.
938///
939/// If `model` is `None`, the config is returned unchanged.
940fn inject_model(config_toml: String, model: Option<String>) -> String {
941    let Some(model_name) = model.as_ref().filter(|s| !s.is_empty()) else {
942        return config_toml;
943    };
944
945    let Ok(mut table) = config_toml.parse::<toml::Value>() else {
946        return config_toml;
947    };
948
949    let llm = match table.get_mut("llm").and_then(|v| v.as_table_mut()) {
950        Some(l) => l,
951        None => return config_toml,
952    };
953
954    // Helper: is this named-provider entry a real provider (vs ambiguous)?
955    let looks_like_provider = |v: &toml::Value| -> bool {
956        v.as_table()
957            .map(|t| {
958                t.contains_key("base_url")
959                    || t.contains_key("api_key")
960                    || t.contains_key("models")
961            })
962            .unwrap_or(false)
963    };
964    // Helper: does this entry offer this model?
965    let offers_model = |v: &toml::Value| -> bool {
966        v.get("models")
967            .and_then(|m| m.as_array())
968            .map(|arr| arr.iter().any(|m| m.as_str() == Some(model_name)))
969            .unwrap_or(false)
970            || v.get("model").and_then(|m| m.as_str()) == Some(model_name.as_str())
971    };
972
973    let providers = llm.get("providers").cloned();
974
975    // Case 1: model_name is a provider KEY → swap, keep provider's default model.
976    if let Some(ref ps) = providers {
977        if let Some(selected) = ps.get(model_name.as_str()) {
978            if looks_like_provider(selected) {
979                let mut selected = selected.clone();
980                if let Some(st) = selected.as_table_mut() {
981                    st.entry("provider_type".to_string())
982                        .or_insert_with(|| toml::Value::String("openai".to_string()));
983                }
984                llm.insert("provider".to_string(), selected);
985                return toml::to_string(&table).unwrap_or(config_toml);
986            }
987        }
988    }
989
990    // Case 2: model_name is OFFERED by some named provider → swap + set model.
991    if let Some(ref ps) = providers {
992        if let Some(ptable) = ps.as_table() {
993            for (_key, entry) in ptable {
994                if looks_like_provider(entry) && offers_model(entry) {
995                    let mut selected = entry.clone();
996                    if let Some(st) = selected.as_table_mut() {
997                        st.insert(
998                            "model".to_string(),
999                            toml::Value::String(model_name.clone()),
1000                        );
1001                        st.entry("provider_type".to_string())
1002                            .or_insert_with(|| toml::Value::String("openai".to_string()));
1003                    }
1004                    llm.insert("provider".to_string(), selected);
1005                    return toml::to_string(&table).unwrap_or(config_toml);
1006                }
1007            }
1008        }
1009    }
1010
1011    // Case 3: literal model string — set it on the current provider.
1012    if let Some(provider) = llm.get_mut("provider").and_then(|p| p.as_table_mut()) {
1013        provider.insert(
1014            "model".to_string(),
1015            toml::Value::String(model_name.clone()),
1016        );
1017    }
1018
1019    toml::to_string(&table).unwrap_or(config_toml)
1020}
1021///
1022/// Includes a 3-state atomic state machine (IDLE/REASONING/CONTENT) that
1023/// inserts blank separator lines when transitioning between reasoning and
1024/// content streams, so the frontend can distinguish them visually.
1025pub struct TuiForwardSink {
1026    tx: mpsc::UnboundedSender<TuiMessage>,
1027    stream_state: AtomicU8,
1028}
1029
1030/// Stream state machine constants.
1031const STREAM_IDLE: u8 = 0;
1032const STREAM_REASONING: u8 = 1;
1033const STREAM_CONTENT: u8 = 2;
1034
1035impl TuiForwardSink {
1036    pub fn new(tx: mpsc::UnboundedSender<TuiMessage>) -> Self {
1037        Self {
1038            tx,
1039            stream_state: AtomicU8::new(STREAM_IDLE),
1040        }
1041    }
1042}
1043
1044impl abk::orchestration::output::OutputSink for TuiForwardSink {
1045    fn emit(&self, event: abk::orchestration::output::OutputEvent) {
1046        use abk::orchestration::output::OutputEvent;
1047
1048        let msg = match event {
1049            OutputEvent::StreamingChunk { delta } => {
1050                if delta.is_empty() {
1051                    return;
1052                }
1053                let prev = self.stream_state.swap(STREAM_CONTENT, Ordering::Relaxed);
1054                if prev != STREAM_CONTENT {
1055                    let _ = self.tx.send(TuiMessage::OutputLine(String::new()));
1056                }
1057                let _ = self.tx.send(TuiMessage::StreamDelta(delta));
1058                return;
1059            }
1060
1061            OutputEvent::LlmResponse { text, model } => {
1062                TuiMessage::OutputLine(format!("[{}] {}", model, text))
1063            }
1064
1065            OutputEvent::Info { message } => {
1066                // Suppress noisy/no-value messages from ABK
1067                if message.contains("API call completed successfully") {
1068                    return;
1069                }
1070                TuiMessage::OutputLine(message)
1071            }
1072
1073            OutputEvent::WorkflowStarted { task_description } => {
1074                TuiMessage::OutputLine(format!("🚀 Workflow started: {}", task_description))
1075            }
1076
1077            OutputEvent::WorkflowCompleted { reason, iterations } => {
1078                TuiMessage::OutputLine(format!(
1079                    "✅ Workflow completed after {} iterations: {}",
1080                    iterations, reason
1081                ))
1082            }
1083
1084            OutputEvent::IterationStarted { iteration, context_tokens } => {
1085                let _ = self.tx.send(TuiMessage::ContextTokensUpdated(context_tokens));
1086                TuiMessage::OutputLine(format!(
1087                    "📡 Iteration {} | Context = {} tokens",
1088                    iteration, context_tokens
1089                ))
1090            }
1091
1092            OutputEvent::ApiCallStarted {
1093                call_number,
1094                model,
1095                tool_count,
1096                streaming,
1097                context_tokens,
1098                tool_tokens,
1099            } => {
1100                let mode = if streaming { "Streaming" } else { "Non-streaming" };
1101                let total = context_tokens + tool_tokens;
1102                let _ = self.tx.send(TuiMessage::ContextTokensUpdated(total));
1103                // Blank line separator before each API call for readability
1104                let _ = self.tx.send(TuiMessage::OutputLine(String::new()));
1105                TuiMessage::OutputLine(format!(
1106                    "🔥 API Call {} | Ctx={}({}+{}) | {} | Model: {} | Tools: {}",
1107                    call_number, total, context_tokens, tool_tokens, mode, model, tool_count
1108                ))
1109            }
1110
1111            OutputEvent::ToolsExecuting { tool_names, hints } => {
1112                for (name, hint) in tool_names.into_iter().zip(hints.into_iter()) {
1113                    let _ = self.tx.send(TuiMessage::ToolPending { tool_name: name, hint });
1114                }
1115                self.stream_state.store(STREAM_IDLE, Ordering::Relaxed);
1116                return;
1117            }
1118
1119            OutputEvent::ToolCompleted {
1120                tool_name,
1121                success,
1122                content,
1123                description,
1124            } => {
1125                if tool_name == "todowrite" && success {
1126                    let _ = self.tx.send(TuiMessage::TodoUpdate(content.clone()));
1127                }
1128                let hint = description;
1129                let _ = self.tx.send(TuiMessage::ToolDone { tool_name, success, hint });
1130                self.stream_state.store(STREAM_IDLE, Ordering::Relaxed);
1131                return;
1132            }
1133
1134            OutputEvent::Error { message, context } => {
1135                if let Some(ctx) = context {
1136                    TuiMessage::OutputLine(format!("❌ Error: {} — {}", message, ctx))
1137                } else {
1138                    TuiMessage::OutputLine(format!("❌ Error: {}", message))
1139                }
1140            }
1141
1142            OutputEvent::ReasoningChunk { delta } => {
1143                if delta.is_empty() {
1144                    return;
1145                }
1146                let prev = self.stream_state.swap(STREAM_REASONING, Ordering::Relaxed);
1147                if prev != STREAM_REASONING {
1148                    let _ = self.tx.send(TuiMessage::OutputLine(String::new()));
1149                }
1150                let _ = self.tx.send(TuiMessage::ReasoningDelta(delta));
1151                return;
1152            }
1153
1154            OutputEvent::McpServerStatus { name, connected, tool_count, error } => {
1155                let _ = self.tx.send(TuiMessage::McpServerStatus {
1156                    name,
1157                    connected,
1158                    tool_count,
1159                    error,
1160                });
1161                return;
1162            }
1163        };
1164
1165        self.stream_state.store(STREAM_IDLE, Ordering::Relaxed);
1166        let _ = self.tx.send(msg);
1167    }
1168}