Skip to main content

infinity_agent_cli/
daemon_client.rs

1//! Daemon client mode — connects to the infinity daemon over a unix socket
2//! (or in-memory channels) and bridges the protocol messages to the terminal.
3
4use std::collections::HashMap;
5
6use bytes::Bytes;
7use futures_util::{SinkExt, StreamExt};
8use infinity_protocol::{
9    ClientMessage, DaemonMessage, ModelRef, SessionInfo, TokenUsage, length_delimited_codec,
10};
11use std::path::PathBuf;
12use tokio::io::AsyncBufReadExt;
13use tokio::net::UnixStream;
14use tokio::sync::mpsc;
15use tokio_util::codec::{Framed, LengthDelimitedCodec};
16
17use crate::display::DisplayEvent;
18use crate::term_io::{EventSource, TermOut};
19use crate::terminal::{DetachResult, SessionChanged};
20
21type BoxError = Box<dyn std::error::Error + Send + Sync>;
22
23/// Convert the daemon's token-usage report into the usage shape the
24/// terminal's context indicator consumes.
25fn convert_token_usage(u: &TokenUsage) -> infinity_provider_protocol::Usage {
26    let input = u.input_tokens.unwrap_or(0);
27    let output = u.output_tokens.unwrap_or(0);
28    infinity_provider_protocol::Usage {
29        input_tokens: input,
30        output_tokens: output,
31        total_tokens: u.total_tokens.unwrap_or(input + output),
32        cached_input_tokens: 0,
33    }
34}
35
36/// Convert a DaemonMessage into a (thread_id, DisplayEvent) tuple.
37/// Returns None for messages that are handled separately (Connected, Welcome, etc.).
38fn daemon_msg_to_display(msg: DaemonMessage) -> Option<(Option<String>, DisplayEvent)> {
39    Some(match msg {
40        DaemonMessage::StartOutput { thread_id } => (thread_id, DisplayEvent::StartOutput),
41        DaemonMessage::TextChunk { thread_id, chunk } => {
42            (thread_id, DisplayEvent::TextChunk { chunk })
43        }
44        DaemonMessage::ToolCall {
45            name,
46            args,
47            thread_id,
48            display_as,
49        } => (
50            thread_id,
51            DisplayEvent::ToolCall {
52                name,
53                args: serde_json::from_str(&args)
54                    .expect("bug: tool call args should be valid JSON"),
55                display_as,
56            },
57        ),
58        DaemonMessage::ToolResult {
59            segments,
60            thread_id,
61        } => (thread_id, DisplayEvent::ToolResult { segments }),
62        DaemonMessage::Info { thread_id, text } => (thread_id, DisplayEvent::Info(text)),
63        DaemonMessage::ResponseDone {
64            thread_id,
65            token_usage,
66        } => (
67            thread_id,
68            DisplayEvent::ResponseDone(token_usage.as_ref().map(convert_token_usage)),
69        ),
70        DaemonMessage::UserInputEcho { thread_id, text } => {
71            (thread_id, DisplayEvent::UserInput(text))
72        }
73        DaemonMessage::SubscriptionEvent {
74            name,
75            text,
76            thread_id,
77        } => (thread_id, DisplayEvent::SubscriptionEvent { name, text }),
78        DaemonMessage::OAuthRequired {
79            thread_id,
80            auth_url,
81        } => (thread_id, DisplayEvent::OAuthRequired { auth_url }),
82        DaemonMessage::UserChoiceRequired {
83            thread_id,
84            id,
85            prompt,
86            choices,
87            default,
88        } => (
89            thread_id,
90            DisplayEvent::UserChoiceRequired {
91                id,
92                prompt,
93                choices,
94                default,
95                response_url: String::new(),
96            },
97        ),
98        DaemonMessage::UserChoiceComplete { choice_id } => {
99            (None, DisplayEvent::UserChoiceComplete { choice_id })
100        }
101        DaemonMessage::ThinkingStart { thread_id } => (thread_id, DisplayEvent::ThinkingStart),
102        DaemonMessage::ThinkingEnd { thread_id } => (thread_id, DisplayEvent::ThinkingEnd),
103        DaemonMessage::ThinkingChunk { thread_id, chunk } => {
104            (thread_id, DisplayEvent::ThinkingChunk { chunk })
105        }
106        DaemonMessage::CompactionApplied { thread_id } => {
107            (thread_id, DisplayEvent::CompactionApplied)
108        }
109        DaemonMessage::Error { thread_id, text } => {
110            (thread_id, DisplayEvent::Info(format!("Error: {text}")))
111        }
112        DaemonMessage::Connected { .. }
113        | DaemonMessage::Welcome { .. }
114        | DaemonMessage::Replay { .. }
115        | DaemonMessage::SessionsUpdated { .. }
116        | DaemonMessage::ModelSwitched { .. }
117        | DaemonMessage::DisconnectNotIdle
118        | DaemonMessage::DetachedIdle
119        | DaemonMessage::EmigrateResult { .. }
120        | DaemonMessage::MigrateStarted { .. }
121        | DaemonMessage::MigrateComplete { .. }
122        | DaemonMessage::MigrateError { .. }
123        | DaemonMessage::ImportComplete { .. }
124        | DaemonMessage::RapServersBooted { .. }
125        | DaemonMessage::RemotesUpdated { .. }
126        | DaemonMessage::ViewUpdate { .. }
127        | DaemonMessage::DirectoryListing { .. } => return None,
128    })
129}
130
131pub async fn ensure_daemon_running() -> Result<UnixStream, BoxError> {
132    if let Ok(stream) = UnixStream::connect(&infinity_protocol::socket_path()).await {
133        return Ok(stream);
134    }
135    launch_daemon().await?;
136    // The daemon binds its socket before announcing readiness, so a single
137    // connect attempt suffices.
138    UnixStream::connect(&infinity_protocol::socket_path())
139        .await
140        .map_err(|e| {
141            format!("daemon reported ready but connecting to its socket failed: {e}").into()
142        })
143}
144
145/// Returns the pid of the running daemon, or `None` if it is not running.
146/// Probes the pid recorded in the pid file with signal 0: only `ESRCH` (no
147/// such process) is treated as not running, so a stale pid file (e.g. left
148/// behind by a crash) is detected while an unsignalable-but-alive process
149/// (`EPERM`) is not misreported as stopped. Pid reuse is an accepted risk:
150/// the daemon removes its pid file on clean shutdown, and both the file and
151/// the daemon are per-user.
152pub fn running_daemon_pid() -> Option<i32> {
153    let pid_str = std::fs::read_to_string(infinity_protocol::pid_path()).ok()?;
154    let pid: i32 = pid_str.trim().parse().ok()?;
155    match nix::sys::signal::kill(nix::unistd::Pid::from_raw(pid), None) {
156        Err(nix::errno::Errno::ESRCH) => None,
157        _ => Some(pid),
158    }
159}
160
161/// Stop the running daemon: send SIGTERM and wait for the process to fully
162/// exit (so its shutdown cleanup of the socket and pid files completes).
163/// Returns `Ok(Some(pid))` if a daemon was stopped, `Ok(None)` if no daemon
164/// is running.
165pub async fn stop_daemon() -> Result<Option<i32>, BoxError> {
166    let Some(pid) = running_daemon_pid() else {
167        return Ok(None);
168    };
169    nix::sys::signal::kill(
170        nix::unistd::Pid::from_raw(pid),
171        nix::sys::signal::Signal::SIGTERM,
172    )
173    .map_err(|e| format!("failed to send SIGTERM to daemon (pid {pid}): {e}"))?;
174    println!("stopping daemon (pid {pid})...");
175    wait_for_daemon_exit(pid).await?;
176    Ok(Some(pid))
177}
178
179/// How long to wait for the daemon to exit after SIGTERM. Generous because
180/// shutdown cleans up all active sessions.
181const DAEMON_SHUTDOWN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
182
183/// Restart the daemon: stop the running instance (if any), then launch a
184/// fresh one.
185pub async fn restart_daemon() -> Result<(), BoxError> {
186    if stop_daemon().await?.is_none() {
187        println!("daemon is not running — starting a fresh one");
188    }
189    launch_daemon().await?;
190    println!("daemon started");
191    Ok(())
192}
193
194/// Wait until the given pid no longer exists, or error out after
195/// [`DAEMON_SHUTDOWN_TIMEOUT`].
196async fn wait_for_daemon_exit(pid: i32) -> Result<(), BoxError> {
197    let deadline = tokio::time::Instant::now() + DAEMON_SHUTDOWN_TIMEOUT;
198    // Signal 0 probes liveness without delivering a signal; only ESRCH means
199    // the process is gone (see `running_daemon_pid`).
200    while !matches!(
201        nix::sys::signal::kill(nix::unistd::Pid::from_raw(pid), None),
202        Err(nix::errno::Errno::ESRCH)
203    ) {
204        if tokio::time::Instant::now() >= deadline {
205            return Err(format!(
206                "daemon (pid {pid}) did not exit within {}s after SIGTERM",
207                DAEMON_SHUTDOWN_TIMEOUT.as_secs()
208            )
209            .into());
210        }
211        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
212    }
213    Ok(())
214}
215
216/// How long to wait for a launched daemon to either report readiness or
217/// exit. Generous because daemon startup spawns model provider processes.
218const DAEMON_STARTUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
219
220/// Path to the CLI binary to spawn as the daemon. Usually the current
221/// executable, but after a self-update `/proc/self/exe` on Linux points at
222/// the replaced (deleted) inode and its path ends with " (deleted)" — strip
223/// that marker so we spawn the freshly installed binary at the original path.
224fn daemon_exe_path() -> Result<PathBuf, BoxError> {
225    let exe = std::env::current_exe()?;
226    if let Some(s) = exe.to_str()
227        && let Some(stripped) = s.strip_suffix(" (deleted)")
228    {
229        return Ok(PathBuf::from(stripped));
230    }
231    Ok(exe)
232}
233
234/// Launch the daemon as a background process and wait until it prints its
235/// ready line on stdout. If the daemon exits first (e.g. a configuration
236/// error), the error includes everything it printed to stdout/stderr, which
237/// would otherwise be invisible for a detached process.
238pub async fn launch_daemon() -> Result<(), BoxError> {
239    let current_exe = daemon_exe_path()?;
240    let mut child = tokio::process::Command::new(&current_exe)
241        .arg("daemon")
242        .env(
243            "RUST_LOG",
244            std::env::var_os("RUST_LOG").unwrap_or("debug".into()),
245        )
246        .stdin(std::process::Stdio::null())
247        .stdout(std::process::Stdio::piped())
248        .stderr(std::process::Stdio::piped())
249        .spawn()?;
250
251    let stdout = child
252        .stdout
253        .take()
254        .expect("bug: piped child stdout missing");
255    let stderr = child
256        .stderr
257        .take()
258        .expect("bug: piped child stderr missing");
259    let mut stdout_lines = tokio::io::BufReader::new(stdout).lines();
260
261    // Accumulate stderr in the background for the failure report.
262    let stderr_task = tokio::task::spawn(async move {
263        use tokio::io::AsyncReadExt;
264        let mut out = String::new();
265        let mut reader = tokio::io::BufReader::new(stderr);
266        let _ = reader.read_to_string(&mut out).await;
267        out
268    });
269
270    let timeout = tokio::time::sleep(DAEMON_STARTUP_TIMEOUT);
271    tokio::pin!(timeout);
272
273    // Race the ready line against the daemon exiting.
274    let mut stdout_so_far = String::new();
275    let exit_status = loop {
276        tokio::select! {
277            line = stdout_lines.next_line() => match line {
278                Ok(Some(line)) if line == infinity_daemon::DAEMON_READY_LINE => {
279                    // Leave the daemon running detached; dropping the child
280                    // handle and pipes does not kill it.
281                    stderr_task.abort();
282                    return Ok(());
283                }
284                Ok(Some(line)) => {
285                    stdout_so_far.push_str(&line);
286                    stdout_so_far.push('\n');
287                }
288                // stdout closed without the ready line: the daemon is
289                // exiting; reap it below (with a timeout in case it
290                // lingers with closed pipes).
291                Ok(None) | Err(_) => {
292                    match tokio::time::timeout(std::time::Duration::from_secs(5), child.wait())
293                        .await
294                    {
295                        Ok(status) => break status?,
296                        Err(_) => {
297                            let _ = child.start_kill();
298                            break child.wait().await?;
299                        }
300                    }
301                }
302            },
303            status = child.wait() => break status?,
304            _ = &mut timeout => {
305                // Still booting: leave it running (it may just be slow) but
306                // stop waiting.
307                return Err(format!(
308                    "daemon did not report ready within {}s; check ~/.infinity/daemon.log",
309                    DAEMON_STARTUP_TIMEOUT.as_secs()
310                ).into());
311            }
312        }
313    };
314
315    // Drain anything still buffered on stdout, then collect stderr.
316    while let Ok(Some(line)) = stdout_lines.next_line().await {
317        stdout_so_far.push_str(&line);
318        stdout_so_far.push('\n');
319    }
320    let stderr_so_far = stderr_task.await.unwrap_or_default();
321
322    let mut report = format!("daemon exited during startup ({exit_status})");
323    if !stdout_so_far.trim().is_empty() {
324        report.push_str(&format!(
325            "\n--- daemon stdout ---\n{}",
326            stdout_so_far.trim_end()
327        ));
328    }
329    if !stderr_so_far.trim().is_empty() {
330        report.push_str(&format!(
331            "\n--- daemon stderr ---\n{}",
332            stderr_so_far.trim_end()
333        ));
334    }
335    Err(report.into())
336}
337
338/// Send a task to the daemon and exit without opening the TUI.
339pub async fn run_headless(message: String) -> Result<(), BoxError> {
340    let stream = ensure_daemon_running().await?;
341    let mut framed = Framed::new(stream, length_delimited_codec());
342
343    /// Receive the next DaemonMessage from the framed socket.
344    async fn recv(
345        framed: &mut Framed<UnixStream, LengthDelimitedCodec>,
346    ) -> Result<DaemonMessage, BoxError> {
347        match framed.next().await {
348            Some(Ok(bytes)) => Ok(serde_json::from_slice::<DaemonMessage>(&bytes)
349                .expect("bug: failed to deserialize daemon message")),
350            _ => Err("daemon disconnected".into()),
351        }
352    }
353
354    // Read Welcome (must be first message).
355    match recv(&mut framed).await? {
356        DaemonMessage::Welcome { .. } => {}
357        DaemonMessage::Error { text, .. } => return Err(text.into()),
358        _ => return Err("expected Welcome from daemon".into()),
359    }
360
361    let cwd = std::env::current_dir()?;
362
363    // Create a new session.
364    let msg = ClientMessage::CreateSession {
365        cwd,
366        location: None,
367        model: None,
368        keeps_session_alive: true,
369    };
370    framed.send(Bytes::from(serde_json::to_vec(&msg)?)).await?;
371
372    // Wait for Connected to get the session ID.
373    let session_id = loop {
374        match recv(&mut framed).await? {
375            DaemonMessage::Connected { session_id, .. } => break session_id,
376            DaemonMessage::Error { text, .. } => return Err(text.into()),
377            _ => continue, // skip SessionsUpdated, etc.
378        }
379    };
380
381    // Send the user's message.
382    let msg = ClientMessage::UserInput {
383        session_id: session_id.clone(),
384        text: message,
385    };
386    framed.send(Bytes::from(serde_json::to_vec(&msg)?)).await?;
387
388    // Wait for the agent to start processing before disconnecting,
389    // so the session isn't killed by the idle check. Also surface any
390    // initialization errors.
391    loop {
392        match recv(&mut framed).await? {
393            DaemonMessage::StartOutput { .. } => break,
394            DaemonMessage::Error { text, .. } => return Err(text.into()),
395            _ => continue,
396        }
397    }
398
399    // Disconnect (agent keeps running in the background).
400    let msg = ClientMessage::Disconnect;
401    framed.send(Bytes::from(serde_json::to_vec(&msg)?)).await?;
402
403    println!("Session {session_id} created — agent is running in the background.");
404    println!("To connect: infinity --session '{session_id}'");
405
406    Ok(())
407}
408
409/// Connect to the daemon over a unix socket (serialized framing).
410pub async fn run_with_daemon(
411    initial_message: Option<String>,
412    session: Option<String>,
413) -> Result<(), BoxError> {
414    let stream = ensure_daemon_running().await?;
415    let mut framed = Framed::new(stream, length_delimited_codec());
416
417    let (to_daemon_tx, mut to_daemon_rx) = mpsc::unbounded_channel::<ClientMessage>();
418    let (from_daemon_tx, from_daemon_rx) = mpsc::unbounded_channel::<DaemonMessage>();
419
420    tokio::pin! {
421        let client_fut = run_client(
422            crate::term_io::CrosstermTerm::new(),
423            crate::term_io::CrosstermEvents,
424            std::env::current_dir().unwrap_or_default(),
425            from_daemon_rx,
426            to_daemon_tx,
427            initial_message,
428            session,
429            None,
430        );
431    }
432
433    loop {
434        tokio::select! {
435            msg = to_daemon_rx.recv() => {
436                let Some(msg) = msg else { // intentional shut down, terminal disconnecting from daemon
437                    drop(from_daemon_tx);
438                    return client_fut.await;
439                };
440                let bytes = Bytes::from(serde_json::to_vec(&msg).expect("bug: failed to serialize daemon message"));
441                if framed.send(bytes).await.is_err() {
442                    tracing::error!("failed to send message to daemon, it may have disconnected");
443                    drop(from_daemon_tx);
444                    return client_fut.await;
445                }
446            }
447            client_res = &mut client_fut => {
448                #[expect(clippy::let_underscore_future, reason = "dropping completed future")]
449                let _ = client_fut;
450                // TODO(shadaj): maybe use join to simplify the state management?
451                // Drain any remaining messages (e.g. Disconnect) before closing the socket.
452                while let Some(msg) = to_daemon_rx.recv().await {
453                    let bytes = Bytes::from(serde_json::to_vec(&msg).expect("bug: failed to serialize daemon message"));
454                    let _ = framed.send(bytes).await;
455                }
456                return client_res;
457            }
458            frame = framed.next() => {
459                match frame {
460                    Some(Ok(bytes)) => {
461                        let msg = serde_json::from_slice::<DaemonMessage>(&bytes).expect("bug: failed to deserialize daemon message");
462                        let _ = from_daemon_tx.send(msg);
463                    }
464                    Some(Err(e)) => {
465                        tracing::error!("error reading from daemon socket: {e}");
466                        drop(from_daemon_tx);
467                        return client_fut.await;
468                    }
469                    None => {
470                        // Daemon closed the socket — drop from_daemon_tx so
471                        // run_client sees the channel close.
472                        tracing::error!("Daemon closed the connection unexpectedly");
473                        drop(from_daemon_tx);
474                        return client_fut.await;
475                    }
476                }
477            }
478        }
479    }
480}
481
482/// Run in-memory mode — no serialization, direct channel passing.
483pub async fn run_in_memory(
484    from_daemon_rx: mpsc::UnboundedReceiver<DaemonMessage>,
485    to_daemon_tx: mpsc::UnboundedSender<ClientMessage>,
486    initial_message: Option<String>,
487    session: Option<String>,
488    startup_info: Option<String>,
489) -> Result<(), BoxError> {
490    run_client(
491        crate::term_io::CrosstermTerm::new(),
492        crate::term_io::CrosstermEvents,
493        std::env::current_dir().unwrap_or_default(),
494        from_daemon_rx,
495        to_daemon_tx,
496        initial_message,
497        session,
498        startup_info,
499    )
500    .await
501}
502
503/// Core client logic — works with channels regardless of transport, and any
504/// terminal implementation. Production wrappers pass the crossterm-backed
505/// terminal and the process cwd; tests substitute a virtual terminal,
506/// scripted events, and a temp cwd.
507#[expect(clippy::too_many_arguments, reason = "explicit client wiring")]
508pub async fn run_client<T, E>(
509    term: T,
510    events: E,
511    cwd: PathBuf,
512    mut from_daemon: mpsc::UnboundedReceiver<DaemonMessage>,
513    to_daemon: mpsc::UnboundedSender<ClientMessage>,
514    initial_message: Option<String>,
515    session: Option<String>,
516    startup_info: Option<String>,
517) -> Result<(), BoxError>
518where
519    T: TermOut + 'static,
520    E: EventSource + 'static,
521{
522    // Read Welcome
523    let welcome = from_daemon.recv().await.ok_or("daemon disconnected")?;
524    let (model_name, context_window, sessions, available_models, provider_name) = match welcome {
525        DaemonMessage::Welcome {
526            default_model_name,
527            default_context_window,
528            sessions,
529            available_models,
530            provider_name,
531            ..
532        } => (
533            default_model_name,
534            default_context_window,
535            sessions,
536            available_models,
537            provider_name,
538        ),
539        DaemonMessage::Error { text, .. } => return Err(text.into()),
540        _ => return Err("expected Welcome from daemon".into()),
541    };
542
543    let (display_tx, display_rx) = mpsc::unbounded_channel::<(Option<String>, DisplayEvent)>();
544    let (input_tx, input_rx) = mpsc::unbounded_channel::<String>();
545    let (load_session_tx, load_session_rx) = mpsc::unbounded_channel::<(Option<String>, bool)>();
546    let (model_switch_tx, model_switch_rx) = mpsc::unbounded_channel::<usize>();
547    let (session_tx, session_rx) = mpsc::unbounded_channel::<SessionChanged>();
548    let (model_switched_tx, model_switched_rx) =
549        mpsc::unbounded_channel::<crate::terminal::ModelSwitched>();
550    let (sessions_updated_tx, sessions_updated_rx) =
551        mpsc::unbounded_channel::<HashMap<String, SessionInfo>>();
552    let (soft_detach_tx, soft_detach_rx) = mpsc::unbounded_channel::<()>();
553    let (detach_result_tx, detach_result_rx) = mpsc::unbounded_channel::<DetachResult>();
554    let (choice_answered_tx, choice_answered_rx) = mpsc::unbounded_channel::<(String, usize)>();
555
556    if let Some(info) = startup_info {
557        let _ = display_tx.send((None, DisplayEvent::Info(info)));
558    }
559
560    // If --session was provided, connect to it immediately (supports prefix matching).
561    if let Some(ref session_id) = session {
562        let matches: Vec<&String> = sessions
563            .keys()
564            .filter(|k| k.starts_with(session_id.as_str()))
565            .collect();
566        let resolved = match matches.len() {
567            0 => return Err(format!("no session found matching prefix '{session_id}'").into()),
568            1 => matches[0].clone(),
569            _ => {
570                return Err(format!(
571                    "ambiguous session prefix '{session_id}' — matches: {}",
572                    matches
573                        .iter()
574                        .map(|s| s.as_str())
575                        .collect::<Vec<_>>()
576                        .join(", ")
577                )
578                .into());
579            }
580        };
581        to_daemon.send(ClientMessage::Connect {
582            session_id: resolved,
583            thread_id: None,
584            keeps_session_alive: true,
585        })?;
586    }
587
588    let models_for_switch = available_models.clone();
589
590    let mut terminal_handle = tokio::task::spawn_local(crate::terminal::run(
591        term,
592        events,
593        input_tx,
594        display_rx,
595        model_name,
596        provider_name,
597        context_window,
598        sessions,
599        load_session_tx,
600        model_switch_tx,
601        available_models,
602        initial_message,
603        session_rx,
604        model_switched_rx,
605        sessions_updated_rx,
606        soft_detach_tx,
607        detach_result_rx,
608        choice_answered_tx,
609    ));
610
611    let mut active_session: Option<String> = None;
612    let mut pending_input: Vec<String> = Vec::new();
613    // The model most recently selected via the model picker. Stored locally so
614    // it can be passed when creating new sessions, even if no session is active.
615    let mut selected_model: Option<ModelRef> = None;
616    let mut terminal_result: Option<Result<Result<bool, BoxError>, tokio::task::JoinError>> = None;
617    let mut pending_soft_detach = false;
618
619    {
620        // move into a local scope so they drop when the loop exits
621        let mut input_rx = input_rx;
622        let display_tx = display_tx;
623        let mut load_session_rx = load_session_rx;
624        let mut model_switch_rx = model_switch_rx;
625        let session_tx = session_tx;
626        let sessions_updated_tx = sessions_updated_tx;
627        let mut soft_detach_rx = soft_detach_rx;
628        let detach_result_tx = detach_result_tx;
629        let mut choice_answered_rx = choice_answered_rx;
630
631        loop {
632            tokio::select! {
633                biased;
634
635                msg = from_daemon.recv() => {
636                    let Some(msg) = msg else {
637                        break;
638                    };
639                    match msg {
640                        DaemonMessage::Connected { session_id, title, total_tokens_used, model_name, context_window, provider_id, .. } => {
641                            active_session = Some(session_id.clone());
642                            let _ = session_tx.send(SessionChanged { session_id, title, total_tokens_used, model_name, context_window, provider_id });
643                            for text in pending_input.drain(..) {
644                                let sid = active_session.as_ref().expect("bug: active_session should be set after Connected").clone();
645                                let _ = to_daemon.send(ClientMessage::UserInput { session_id: sid, text });
646                            }
647                        }
648                        DaemonMessage::ModelSwitched { thread_id, model_name, context_window, provider_id } => {
649                            let _ = model_switched_tx.send(crate::terminal::ModelSwitched {
650                                thread_id, model_name, provider_id, context_window,
651                            });
652                        }
653                        DaemonMessage::Replay { history, pending_choices, in_progress, .. } => {
654                            for m in history {
655                                if let Some(evt) = daemon_msg_to_display(m) {
656                                    let _ = display_tx.send(evt);
657                                }
658                            }
659                            // End-of-replay marker: closes any open stream/spinner
660                            // state. Deliberately carries no usage info so it does
661                            // not clobber the total from the Connected message.
662                            // Skipped when the response is still in progress — the
663                            // spinner state implied by the end of the history (e.g.
664                            // mid-thinking) is live, and more events will follow.
665                            if !in_progress {
666                                let _ = display_tx.send((None, DisplayEvent::ResponseDone(None)));
667                            }
668                            for m in pending_choices {
669                                if let Some(evt) = daemon_msg_to_display(m) {
670                                    let _ = display_tx.send(evt);
671                                }
672                            }
673                        }
674                        DaemonMessage::SessionsUpdated { sessions } => {
675                            let _ = sessions_updated_tx.send(sessions);
676                        }
677                        DaemonMessage::DisconnectNotIdle => {
678                            if pending_soft_detach {
679                                pending_soft_detach = false;
680                                let _ = detach_result_tx.send(DetachResult::NotIdle);
681                            }
682                        }
683                        DaemonMessage::DetachedIdle => {
684                            if pending_soft_detach {
685                                pending_soft_detach = false;
686                                active_session = None;
687                                let _ = detach_result_tx.send(DetachResult::Idle);
688                            }
689                        }
690                        msg => {
691                            if let Some(evt) = daemon_msg_to_display(msg) {
692                                let _ = display_tx.send(evt);
693                            }
694                        }
695                    }
696                }
697
698                msg = soft_detach_rx.recv() => {
699                    let Some(()) = msg else { break };
700                    if let Some(ref sid) = active_session {
701                        pending_soft_detach = true;
702                        let _ = to_daemon.send(ClientMessage::SoftDetach { session_id: sid.clone() });
703                    }
704                }
705
706                maybe_target = load_session_rx.recv() => {
707                    let Some((maybe_target, shut_down_old)) = maybe_target else { break };
708                    if let Some(ref sid) = active_session {
709                        if shut_down_old {
710                            let _ = to_daemon.send(ClientMessage::ShutdownSession { session_id: sid.clone() });
711                        } else {
712                            let _ = to_daemon.send(ClientMessage::Disconnect);
713                        }
714                    }
715
716                    if shut_down_old && maybe_target.is_none() {
717                        // When stopping (shut_down_old=true) with no target, keep active_session
718                        // so the next user input resumes the same session.
719                    } else {
720                        active_session = None;
721                    }
722
723                    if let Some(target) = maybe_target {
724                        let _ = to_daemon.send(ClientMessage::Connect { session_id: target, thread_id: None, keeps_session_alive: true });
725                    } // if none, will be created on next user input
726                }
727
728                idx = model_switch_rx.recv() => {
729                    let Some(idx) = idx else { break };
730                    if let Some(entry) = models_for_switch.get(idx) {
731                        let model = ModelRef {
732                            provider_id: entry.provider_id.clone(),
733                            model_id: entry.model_id.clone(),
734                        };
735                        // Remember the selection locally so new sessions use it.
736                        selected_model = Some(model.clone());
737                        if let Some(sid) = &active_session {
738                            let _ = to_daemon.send(ClientMessage::SwitchModel {
739                                session_id: sid.clone(), model,
740                            });
741                        }
742                    }
743                }
744
745                answered = choice_answered_rx.recv() => {
746                    let Some((choice_id, selected)) = answered else { break; };
747                    let _ = to_daemon.send(ClientMessage::UserChoiceAnswered { choice_id, selected });
748                }
749
750                res = &mut terminal_handle => {
751                    terminal_result = Some(res);
752                    break;
753                }
754
755                text = input_rx.recv() => {
756                    let Some(text) = text else { break };
757                    if let Some(ref sid) = active_session {
758                        if text == "__compact__" {
759                            let _ = to_daemon.send(ClientMessage::TriggerCompaction { session_id: sid.clone() });
760                        } else if text == "__archive__" {
761                            let _ = to_daemon.send(ClientMessage::ArchiveSession { session_id: sid.clone() });
762                            active_session = None;
763                        } else {
764                            let _ = to_daemon.send(ClientMessage::UserInput { session_id: sid.clone(), text });
765                        }
766                    } else {
767                        pending_input.push(text);
768                        let _ = to_daemon.send(ClientMessage::CreateSession { cwd: cwd.clone(), location: None, model: selected_model.clone(), keeps_session_alive: true });
769                    }
770                }
771            }
772        }
773    }
774
775    let result = match terminal_result {
776        Some(r) => r,
777        None => terminal_handle.await,
778    };
779    if let Err(ref e) = result {
780        if e.is_panic() {
781            tracing::error!("terminal task panicked: {e}");
782        } else {
783            tracing::warn!("terminal task cancelled: {e}");
784        }
785    }
786    let keep_running = matches!(result, Ok(Ok(true)));
787
788    if let Some(sid) = active_session {
789        if keep_running {
790            let _ = to_daemon.send(ClientMessage::Disconnect);
791        } else {
792            let _ = to_daemon.send(ClientMessage::ShutdownSession { session_id: sid });
793        }
794    }
795
796    Ok(())
797}