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