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