Skip to main content

hyprstream_core/cli/
shell_handlers.rs

1//! Shell client handlers.
2//!
3//! Two modes:
4//!
5//! - `handle_shell_tui` — interactive local mode (`hyprstream` no args).
6//!   Connects to TuiService, renders ratatui chrome via `AnsiBackend` to the
7//!   local terminal, and routes input through the `Compositor` state machine.
8//!
9//! - `handle_tui_shell` — embedded mode (`hyprstream tui shell`).
10//!   Sends `SpawnChromeShell` RPC to TuiService so ShellApp runs server-side
11//!   as a `PaneProcess`.  No fork occurs in the client, avoiding the ZMQ
12//!   signaler assertion that fired when forking after ZMQ initialisation.
13// CLI handlers intentionally print to stdout/stderr for user interaction
14#![allow(clippy::print_stdout, clippy::print_stderr)]
15
16use std::collections::HashMap;
17
18use anyhow::{Context, Result};
19use ed25519_dalek::SigningKey;
20use waxterm::backend::AnsiBackend;
21use waxterm::input::InputParser;
22use zeroize::Zeroizing;
23
24use hyprstream_compositor::{
25    Compositor, CompositorInput, CompositorOutput, ConversationKind, ConversationPickerEntry,
26    GenerationDefaults, ModelEntry, PaneSummary, RpcRequest, ToastLevel, WindowSummary,
27};
28
29/// Status update from the model polling background task.
30struct ModelStatusUpdate {
31    model_ref: String,
32    loaded: bool,
33    gen_defaults: GenerationDefaults,
34}
35use hyprstream_compositor::layout::{
36    CellUpdate, CursorState, FrameContent, FrameUpdate, ScrollUpdate,
37};
38use hyprstream_tui::chat_app::{ChatApp, LoadHook, SaveHook};
39use hyprstream_tui::console_app::ConsoleApp;
40use hyprstream_tui::container_app::ContainerTermApp;
41use hyprstream_tui::private_store::{FsBackend, StorageKey};
42use waxterm::app::TerminalApp;
43use waxterm::input::KeyPress;
44
45// ============================================================================
46// ActiveApp — client-owned app variants (ChatApp or ContainerTermApp)
47// ============================================================================
48
49enum ActiveApp {
50    Chat(Box<ChatApp>),
51    Container(Box<ContainerTermApp>),
52}
53
54impl ActiveApp {
55    fn tick(&mut self, delta_ms: u64) -> bool {
56        match self {
57            Self::Chat(a) => a.tick(delta_ms),
58            Self::Container(a) => a.tick(delta_ms),
59        }
60    }
61
62    fn should_quit(&self) -> bool {
63        match self {
64            Self::Chat(a) => a.should_quit(),
65            Self::Container(a) => a.should_quit(),
66        }
67    }
68
69    fn pending_toasts(&mut self) -> Vec<String> {
70        match self {
71            Self::Chat(a) => a.pending_toasts.drain(..).collect(),
72            Self::Container(a) => a.pending_toasts.drain(..).collect(),
73        }
74    }
75
76    fn cols(&self) -> u16 {
77        match self {
78            Self::Chat(a) => a.cols,
79            Self::Container(a) => a.cols,
80        }
81    }
82
83    fn rows(&self) -> u16 {
84        match self {
85            Self::Chat(a) => a.rows,
86            Self::Container(a) => a.rows,
87        }
88    }
89
90    fn render(&self, frame: &mut ratatui::Frame) {
91        match self {
92            Self::Chat(a) => a.render(frame),
93            Self::Container(a) => a.render(frame),
94        }
95    }
96
97    fn handle_input(&mut self, key: KeyPress) -> bool {
98        match self {
99            Self::Chat(a) => a.handle_input(key),
100            Self::Container(a) => a.handle_input(key),
101        }
102    }
103
104    fn as_chat_mut(&mut self) -> Option<&mut ChatApp> {
105        match self {
106            Self::Chat(a) => Some(a),
107            Self::Container(_) => None,
108        }
109    }
110}
111
112use crate::tui::shell_client::{
113    close_window_rpc, focus_window_rpc, spawn_chat_app_rpc, spawn_shell_rpc,
114};
115use hyprstream_rpc_std::tui_client::{
116    ConnectRequest, DisplayMode, ResizeRequest, SendInputRequest, SpawnChromeShellRequest,
117    TuiClient,
118};
119
120// ============================================================================
121// handle_shell_tui — local interactive mode
122// ============================================================================
123
124/// Run ShellClient as a local interactive terminal using the compositor.
125pub async fn handle_shell_tui(
126    signing_key: &SigningKey,
127    models_dir: &std::path::Path,
128) -> Result<()> {
129    use crate::cli::tui_handlers::{
130        create_tui_client, enter_raw_mode, restore_terminal, terminal_size,
131    };
132    use hyprstream_rpc::streaming::StreamPayload;
133
134    let client = create_tui_client(signing_key)?;
135    // Resolve the signal-handler client before raw-mode and background-thread
136    // side effects so a failure returns with the terminal untouched.
137    let resize_client = create_tui_client(signing_key)?;
138    let (cols, rows) = terminal_size();
139    let pane_rows = rows.saturating_sub(4); // status(1) + top border(1) + bottom border(1) + strip(1)
140    let pane_cols = cols.saturating_sub(2); // left + right border
141
142    // Connect to session 0 using Capnp display mode so the frame stream
143    // carries structured TuiFrame messages with pane_id for correct routing.
144    let result = client
145        .connect(&ConnectRequest {
146            session_id: 0,
147            display_mode: DisplayMode::Capnp,
148            cols: pane_cols,
149            rows: pane_rows,
150        })
151        .await
152        .context("Failed to connect to TUI session. Is the TUI service running?")?;
153
154    let session_id = result.session_id;
155    let viewer_id = result.viewer_id;
156
157    // Build initial window list.
158    let windows: Vec<WindowSummary> = result
159        .windows
160        .iter()
161        .map(|w| WindowSummary {
162            id: w.id,
163            name: w.name.clone(),
164            active_pane_id: w.active_pane_id,
165            panes: w
166                .panes
167                .iter()
168                .map(|p| PaneSummary {
169                    id: p.id,
170                    cols: p.cols,
171                    rows: p.rows,
172                    is_private: p.is_private,
173                })
174                .collect(),
175        })
176        .collect();
177
178    // Fetch model list from registry.
179    let models = fetch_models(signing_key, models_dir).await;
180
181    // Model load-status channel (background polling → event loop).
182    let model_client = hyprstream_rpc_std::model_client::ModelClient::from_provider(
183        &hyprstream_discovery::ProductionRpcClientProvider,
184        signing_key.clone(),
185        None,
186    )?;
187    // Worker client for sandbox/container/image management.
188    let worker_client = {
189        hyprstream_rpc_std::worker_client::WorkerClient::from_provider(
190            &hyprstream_discovery::ProductionRpcClientProvider,
191            signing_key.clone(),
192            None,
193        )?
194    };
195    let registry = hyprstream_rpc_std::registry_client::RegistryClient::from_provider(
196        &hyprstream_discovery::ProductionRpcClientProvider,
197        signing_key.clone(),
198        None,
199    )?;
200
201    let (model_status_tx, mut model_status_rx) =
202        tokio::sync::mpsc::channel::<ModelStatusUpdate>(32);
203
204    // Terminal resize channel — SIGWINCH handler → main event loop.
205    let (resize_tx, mut resize_rx) = tokio::sync::mpsc::channel::<(u16, u16)>(4);
206
207    // rows tracks the current terminal height and is updated on SIGWINCH.
208    let mut rows = rows;
209
210    // Build compositor.
211    let mut compositor = Compositor::new(cols, rows, session_id, viewer_id, windows, models);
212
213    // Subscribe to ANSI frame stream.
214    let stdout_stream = result
215        .streams
216        .get(1)
217        .context("TuiService did not return a frame stream")?;
218    let mac_key: [u8; 32] = stdout_stream
219        .mac_key
220        .as_slice()
221        .try_into()
222        .context("mac_key must be 32 bytes")?;
223    let topic = stdout_stream.topic.clone();
224
225    use hyprstream_rpc::moq_stream::MoqStreamHandle;
226
227    let broadcast_path = stdout_stream.broadcast_path.clone();
228    anyhow::ensure!(
229        !broadcast_path.is_empty(),
230        "TUI service did not return a moq broadcast path — server did not initialize moq transport"
231    );
232
233    let (frame_tx, mut frame_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(64);
234
235    // #356: dial the producer's networked reach (the TUI service's bound QUIC
236    // `/moq` endpoint) rather than this process's OWN local moq UDS plane. The
237    // shared `MoqStreamHandle::networked` consumer prefers the StreamInfo's
238    // `announcedAt` reach and falls back to the local UDS only when no dialable
239    // reach is present — mirroring the chat-inference consumer that this fix is
240    // modeled on. (Before the fix this bespoke loop did `connect_uds(moq_uds_path)`,
241    // which timed out because the PTY broadcast lives on the *TUI service's* plane,
242    // a different process from this viewer.)
243    let reach = stdout_stream.announced_at.clone();
244    // #358: a shell stdout attach is a live pipe → direct-first (default
245    // StreamOpt = Retention::Live); selection only reorders advertised reaches.
246    let qos = hyprstream_rpc::stream_info::StreamOpt::default();
247    // #321: the TUI stdout stream is published AEAD-off (the viewer gets only
248    // `mac_key`+`topic` out of band), so the transport enc_key is never exercised
249    // here — derive a stable one from mac_key purely to satisfy the consumer API.
250    let enc_key = *hyprstream_rpc::crypto::StreamKeys::new(topic.clone(), mac_key).enc_key;
251    let mut handle = MoqStreamHandle::networked_with_server_identity(
252        reach,
253        &qos,
254        broadcast_path,
255        mac_key,
256        enc_key,
257        topic,
258        stdout_stream.moql_server_identity.clone(),
259    );
260    let _recv_handle = tokio::spawn(async move {
261        loop {
262            match handle.recv_next().await {
263                Ok(Some(StreamPayload::Data(data))) => {
264                    if frame_tx.send(data).await.is_err() {
265                        return;
266                    }
267                }
268                // A terminal Complete payload or a clean end-of-stream both end
269                // the loop cleanly.
270                Ok(Some(StreamPayload::Complete(_))) | Ok(None) => return,
271                Ok(Some(StreamPayload::Error(msg))) => {
272                    tracing::warn!("moq stream error: {msg}");
273                    return;
274                }
275                // Other payloads (e.g. Tagged) carry no ANSI frame bytes.
276                Ok(Some(_)) => continue,
277                Err(e) => {
278                    tracing::warn!("moq frame recv: {e}");
279                    return;
280                }
281            }
282        }
283    });
284
285    // Stdin reader thread.
286    let (stdin_tx, mut stdin_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(64);
287    std::thread::spawn(move || {
288        use std::io::Read;
289        let mut buf = [0u8; 256];
290        loop {
291            match std::io::stdin().lock().read(&mut buf) {
292                Ok(0) | Err(_) => break,
293                Ok(n) => {
294                    if stdin_tx.blocking_send(buf[..n].to_vec()).is_err() {
295                        break;
296                    }
297                }
298            }
299        }
300    });
301
302    // Set up ratatui terminal.
303    let writer = AnsiWriter(std::io::stdout());
304    let backend = AnsiBackend::new(writer, cols, rows, false);
305    let mut terminal =
306        ratatui::Terminal::new(backend).context("Failed to create ratatui terminal")?;
307    let _ = terminal.hide_cursor();
308    let _ = terminal.clear();
309
310    let input_parser = InputParser::new(vec![]);
311
312    // Redirect tracing to a log file so raw-mode rendering is not corrupted.
313    let log_dir = dirs::data_local_dir()
314        .unwrap_or_else(|| std::path::PathBuf::from("/tmp"))
315        .join("hyprstream");
316    std::fs::create_dir_all(&log_dir).ok();
317    let file_appender = tracing_appender::rolling::never(&log_dir, "hyprstream-tui.log");
318    let (non_blocking, _log_guard) = tracing_appender::non_blocking(file_appender);
319    #[allow(unused_imports)]
320    use tracing_subscriber::util::SubscriberInitExt as _;
321    let _subscriber_guard = tracing_subscriber::fmt()
322        .with_writer(non_blocking)
323        .with_ansi(false)
324        .set_default();
325
326    // Install tui-logger so the Console overlay can display structured logs.
327    let _ = tui_logger::init_logger(log::LevelFilter::Debug);
328    tui_logger::set_default_level(log::LevelFilter::Info);
329
330    let orig = enter_raw_mode()?;
331
332    // Enable SGR mouse tracking.
333    {
334        use std::io::Write;
335        let _ = std::io::stdout().write_all(b"\x1b[?1002h\x1b[?1006h");
336        let _ = std::io::stdout().flush();
337    }
338
339    // Derive storage key for private chat sessions.
340    let storage_key = derive_storage_key(signing_key);
341
342    // Derive VFS subject from the signing key's public key — real identity, not anonymous.
343    let vfs_subject = {
344        let vk = signing_key.verifying_key();
345        let pubkey_hex = hex::encode(vk.as_bytes());
346        hyprstream_rpc::Subject::new(pubkey_hex)
347    };
348
349    // Build VFS namespace for `/path` routing in ChatApps, via the shared
350    // standard-namespace recipe (see `crate::services::namespace_builder`).
351    // The CLI shell has a registry client available, so it mounts
352    // `/srv/registry` (+ `/worktree` alias) — the TUI ChatApp builder does
353    // not currently have one and omits it.
354    let vfs_ns: std::sync::Arc<hyprstream_vfs::Namespace> = {
355        let config = crate::config::HyprConfig::load().unwrap_or_default();
356        let pep = crate::mac::production_vfs_pep(signing_key.clone(), &config.oauth, "vfs-shell")
357            .await
358            .context("construct shell VFS MAC PEP")?;
359        let ns =
360            crate::services::build_standard_namespace(crate::services::StandardNamespaceConfig {
361                subject: vfs_subject.clone(),
362                model_client: model_client.clone(),
363                registry: Some(Clone::clone(&registry)),
364                pep: Some(pep),
365                model_path: "/srv/model".to_owned(),
366                registry_path: "/srv/registry".to_owned(),
367                worktree_path: "/worktree".to_owned(),
368                bin_path: "/bin".to_owned(),
369                env_path: "/env".to_owned(),
370                tcl_path: "/lang/tcl".to_owned(),
371            });
372        std::sync::Arc::new(ns)
373    };
374
375    // Spawn VFS proxy on a dedicated OS thread with its own tokio runtime.
376    // The CLI shell's ChatApps run directly in the LocalSet event loop (not
377    // via spawn_app_process), so the proxy must NOT share the same runtime —
378    // otherwise reply_rx.recv() blocks the runtime and deadlocks the proxy.
379    let vfs_proxy_tx =
380        crate::tui::vfs::spawn_dedicated_vfs_proxy(vfs_ns.clone(), vfs_subject.clone());
381
382    // Console overlay for log viewing (F9 / Ctrl-L).
383    let mut console_app = ConsoleApp::new();
384
385    // Active client-owned apps (ChatApp or ContainerTermApp) keyed by pane_id.
386    let mut active_apps: HashMap<u32, ActiveApp> = HashMap::new();
387    // Local pane ID counter — high bit set to avoid collision with server IDs.
388    let mut next_local_id: u32 = hyprstream_compositor::LOCAL_ID_BIT;
389
390    let mut saw_ctrl_b = false;
391    let mut win_refresh = tokio::time::interval(std::time::Duration::from_secs(2));
392    win_refresh.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
393    let mut bg_tick = tokio::time::interval(std::time::Duration::from_millis(50));
394    bg_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
395    let mut worker_refresh = tokio::time::interval(std::time::Duration::from_secs(5));
396    worker_refresh.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
397
398    // SIGWINCH — forward terminal resize to TuiService and compositor.
399    let resize_tx_sigwinch = resize_tx.clone();
400    let _sigwinch_handle = tokio::spawn(async move {
401        use tokio::signal::unix::{signal, SignalKind};
402        let mut sigwinch = match signal(SignalKind::window_change()) {
403            Ok(s) => s,
404            Err(_) => return,
405        };
406        loop {
407            sigwinch.recv().await;
408            let (c, r) = terminal_size();
409            // Send pane dimensions to server (full rows minus 4 chrome rows, cols minus 2 borders),
410            // matching the initial connect() call which sends pane dimensions not terminal dimensions.
411            let _ = resize_rpc(&resize_client, c.saturating_sub(2), r.saturating_sub(4)).await;
412            // Compositor needs full terminal rows to recalculate layout.
413            let _ = resize_tx_sigwinch.try_send((c, r));
414        }
415    });
416
417    // Initial render.
418    composite_draw(&mut terminal, &compositor, &mut console_app);
419
420    let mut should_exit = false;
421
422    loop {
423        tokio::select! {
424            Some(frame_bytes) = frame_rx.recv() => {
425                // Decode structured TuiFrame (Capnp mode) and route by embedded pane_id.
426                let outputs = match decode_tui_frame(&frame_bytes) {
427                    Ok(mut frame) => {
428                        if frame.pane_id == 0 {
429                            frame.pane_id = compositor.active_pane_id();
430                        }
431                        compositor.handle(CompositorInput::ServerFrameCapnp { frame })
432                    }
433                    Err(_) => {
434                        // Fallback: treat as raw ANSI (shouldn't happen in Capnp mode).
435                        let pane_id = compositor.active_pane_id();
436                        compositor.handle(CompositorInput::ServerFrame { pane_id, ansi: frame_bytes })
437                    }
438                };
439                if dispatch_outputs(
440                    &mut compositor, &client, &model_client, &worker_client,
441                    &model_status_tx, &mut terminal, &mut console_app,
442                    &mut active_apps, &mut next_local_id, &storage_key, signing_key,
443                    &registry, &vfs_ns, &vfs_subject, &vfs_proxy_tx, outputs,
444                ).await { break; }
445            }
446
447            Some(raw) = stdin_rx.recv() => {
448                // Ctrl-B D/Q — detach/quit at event loop level.
449                for &b in &raw {
450                    if saw_ctrl_b && (b == b'd' || b == b'q') {
451                        should_exit = true;
452                        break;
453                    }
454                    saw_ctrl_b = b == 0x02;
455                }
456                if should_exit { break; }
457
458                // SGR mouse click handling.
459                if let Some((col, row)) = parse_sgr_mouse_click(&raw) {
460                    // Close button on windows/modals — handled by compositor.
461                    let close_outputs = compositor.handle(CompositorInput::MouseClick { col, row });
462                    if !close_outputs.is_empty() {
463                        if dispatch_outputs(
464                            &mut compositor, &client, &model_client, &worker_client,
465                            &model_status_tx, &mut terminal, &mut console_app,
466                            &mut active_apps, &mut next_local_id, &storage_key, signing_key,
467                            &registry, &vfs_ns, &vfs_subject, &vfs_proxy_tx, close_outputs,
468                        ).await { break; }
469                        continue;
470                    }
471
472                    // Window strip: [Ctrl-Space] label + tab clicks.
473                    let win_strip_row = rows.saturating_sub(1);
474                    if row == win_strip_row {
475                        const STRIP_LABEL_W: u16 = 14;
476                        if col < STRIP_LABEL_W {
477                            // Click on [Ctrl-Space] label — open start menu.
478                            let outs = compositor.chrome.handle_key(waxterm::input::KeyPress::CtrlSpace);
479                            let mut should_redraw = false;
480                            for co in outs {
481                                if let hyprstream_compositor::ChromeOutput::Redraw = co {
482                                    should_redraw = true;
483                                }
484                            }
485                            if should_redraw {
486                                composite_draw(&mut terminal, &compositor, &mut console_app);
487                            }
488                        } else if let Some(idx) = tab_index_at_col(&compositor.chrome.windows, col - STRIP_LABEL_W) {
489                            compositor.chrome.active_win = idx;
490                            if let Some(w) = compositor.chrome.windows.get(idx) {
491                                let wid = w.id;
492                                let _ = focus_window_rpc(&client, wid).await;
493                            }
494                            composite_draw(&mut terminal, &compositor, &mut console_app);
495                        }
496                        continue;
497                    }
498
499                    // Pass-through clicks in the pane area to the terminal.
500                    let (pane_top, pane_rows) =
501                        if matches!(compositor.chrome.mode, hyprstream_compositor::ShellMode::Fullscreen) {
502                            (0u16, rows)
503                        } else {
504                            (2u16, rows.saturating_sub(4))
505                        };
506                    if row < pane_top || row >= pane_top + pane_rows {
507                        continue;
508                    }
509                }
510
511                let keys = input_parser.parse(&raw);
512                for key in keys {
513                    let outputs = compositor.handle(CompositorInput::KeyPress(key));
514                    if dispatch_outputs(
515                        &mut compositor, &client, &model_client, &worker_client,
516                        &model_status_tx, &mut terminal, &mut console_app,
517                        &mut active_apps, &mut next_local_id, &storage_key, signing_key,
518                        &registry, &vfs_ns, &vfs_subject, &vfs_proxy_tx, outputs,
519                    ).await {
520                        should_exit = true;
521                        break;
522                    }
523                }
524                if should_exit { break; }
525            }
526
527            _ = win_refresh.tick() => {
528                if let Ok(wins) = list_windows_rpc(&client).await {
529                    let outputs = compositor.handle(CompositorInput::WindowList(wins));
530                    if dispatch_outputs(
531                        &mut compositor, &client, &model_client, &worker_client,
532                        &model_status_tx, &mut terminal, &mut console_app,
533                        &mut active_apps, &mut next_local_id, &storage_key, signing_key,
534                        &registry, &vfs_ns, &vfs_subject, &vfs_proxy_tx, outputs,
535                    ).await { break; }
536                }
537            }
538
539            _ = worker_refresh.tick() => {
540                if matches!(compositor.chrome.mode, hyprstream_compositor::ShellMode::WorkerManager { .. }) {
541
542                    // Poll sandboxes + containers
543                    if let Ok(sandbox_infos) = worker_client.sandbox().list(&hyprstream_rpc_std::worker_client::PodSandboxFilter::default()).await {
544                        let mut entries = Vec::new();
545                        for sb in &sandbox_infos {
546                            let short_id = if sb.id.len() > 8 { sb.id[..8].to_owned() } else { sb.id.clone() };
547                            let containers = match worker_client.container().list(&hyprstream_rpc_std::worker_client::ContainerFilter {
548                                pod_sandbox_id: sb.id.clone(),
549                                ..Default::default()
550                            }).await {
551                                Ok(cis) => cis.into_iter().map(|c| {
552                                    let c_short = if c.id.len() > 8 { c.id[..8].to_owned() } else { c.id.clone() };
553                                    hyprstream_compositor::ContainerEntry {
554                                        id: c_short,
555                                        full_id: c.id,
556                                        image: c.image.image,
557                                        state: format!("{:?}", c.state),
558                                        cpu_pct: None,
559                                        mem_mb: None,
560                                    }
561                                }).collect(),
562                                Err(_) => vec![],
563                            };
564                            entries.push(hyprstream_compositor::WorkerEntry {
565                                id: short_id,
566                                full_id: sb.id.clone(),
567                                state: format!("{:?}", sb.state),
568                                backend: sb.runtime_handler.clone(),
569                                cpu_pct: None,
570                                mem_mb: None,
571                                containers,
572                            });
573                        }
574                        let pool_summary = format!("{} sandboxes", entries.len());
575                        let outputs = compositor.handle(CompositorInput::WorkerList { sandboxes: entries, pool_summary });
576                        if dispatch_outputs(
577                            &mut compositor, &client, &model_client, &worker_client,
578                            &model_status_tx, &mut terminal, &mut console_app,
579                            &mut active_apps, &mut next_local_id, &storage_key, signing_key,
580                            &registry, &vfs_ns, &vfs_subject, &vfs_proxy_tx, outputs,
581                        ).await { break; }
582                    }
583                    // Poll images
584                    if let Ok(images) = worker_client.image().list(&hyprstream_rpc_std::worker_client::ImageFilter { image: hyprstream_rpc_std::worker_client::ImageSpec::default() }).await {
585                        let entries: Vec<hyprstream_compositor::ImageEntry> = images.into_iter().map(|img| {
586                            let repo_tag = img.repo_tags.first().cloned().unwrap_or_else(|| "<none>".to_owned());
587                            let id = if img.id.len() > 12 { img.id[..12].to_owned() } else { img.id.clone() };
588                            hyprstream_compositor::ImageEntry {
589                                repo_tag,
590                                id,
591                                size_bytes: img.size,
592                                created: format!("{}s ago", std::time::SystemTime::now()
593                                    .duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs()
594                                    .saturating_sub(img.uid as u64)),
595                            }
596                        }).collect();
597                        let outputs = compositor.handle(CompositorInput::WorkerImageList { images: entries });
598                        if dispatch_outputs(
599                            &mut compositor, &client, &model_client, &worker_client,
600                            &model_status_tx, &mut terminal, &mut console_app,
601                            &mut active_apps, &mut next_local_id, &storage_key, signing_key,
602                            &registry, &vfs_ns, &vfs_subject, &vfs_proxy_tx, outputs,
603                        ).await { break; }
604                    }
605                }
606            }
607
608            _ = bg_tick.tick() => {
609                let bg_dirty = compositor.chrome.tick_bg();
610                let toast_dirty = compositor.chrome.tick_toasts();
611                if bg_dirty || toast_dirty {
612                    composite_draw(&mut terminal, &compositor, &mut console_app);
613                }
614                // Tick active ChatApps and collect frames / quit IDs.
615                // Two-pass to avoid holding &mut active_apps while dispatching.
616                let mut dirty_frames: Vec<(u32, Vec<u8>)> = Vec::new();
617                let mut quit_app_ids: Vec<u32> = Vec::new();
618                let mut pending_ctx_reloads: Vec<(String, usize)> = Vec::new();
619                for (&pane_id, app) in active_apps.iter_mut() {
620                    let dirty = app.tick(50);
621                    // Surface inference errors as compositor toasts.
622                    for msg in app.pending_toasts() {
623                        compositor.chrome.push_toast(msg, ToastLevel::Error);
624                    }
625                    if app.should_quit() {
626                        quit_app_ids.push(pane_id);
627                        continue;
628                    }
629                    // Collect context-window reload requests from settings modal.
630                    if let Some(chat) = app.as_chat_mut() {
631                        if let Some(ctx) = chat.requested_context_window.take() {
632                            pending_ctx_reloads.push((chat.model_name.clone(), ctx));
633                        }
634                    }
635                    if dirty {
636                        dirty_frames.push((pane_id, render_app_to_ansi(app)));
637                    }
638                }
639                // Apply context-window reloads (model will reload with new context size).
640                for (model_ref, ctx_window) in pending_ctx_reloads {
641                    let reload_max_context = if ctx_window == 0 { None } else { Some(ctx_window as u32) };
642                    let ctx_label = if ctx_window == 0 {
643                        "model default".to_owned()
644                    } else {
645                        ctx_window.to_string()
646                    };
647                    compositor.chrome.push_toast(
648                        format!("Reloading {model_ref} with context {ctx_label}…"),
649                        ToastLevel::Info,
650                    );
651                    let _ = model_client.load(&hyprstream_rpc_std::model_client::LoadModelRequest {
652                        model_ref: model_ref.clone(),
653                        max_context: reload_max_context,
654                        kv_quant: None,
655                    }).await;
656                    spawn_model_load_poll(model_client.clone(), model_ref.clone(), model_status_tx.clone());
657                }
658                // Feed dirty frames into compositor.
659                for (pane_id, ansi) in dirty_frames {
660                    let outputs = compositor.handle(CompositorInput::AppFrame { app_id: pane_id, ansi });
661                    if dispatch_outputs(
662                        &mut compositor, &client, &model_client, &worker_client,
663                        &model_status_tx, &mut terminal, &mut console_app,
664                        &mut active_apps, &mut next_local_id, &storage_key, signing_key,
665                        &registry, &vfs_ns, &vfs_subject, &vfs_proxy_tx, outputs,
666                    ).await { should_exit = true; break; }
667                }
668                // Remove quitting apps.
669                for id in quit_app_ids {
670                    // Fire-and-forget detach for container apps.
671                    if let Some(ActiveApp::Container(ref c)) = active_apps.get(&id) {
672                        let cid = c.container_id.clone();
673                        let wc = worker_client.clone();
674                        std::thread::spawn(move || {
675                            let rt = tokio::runtime::Builder::new_current_thread()
676                                .enable_all()
677                                .build();
678                            if let Ok(rt) = rt {
679                                let _ = rt.block_on(wc.container().detach(&cid));
680                            }
681                        });
682                    }
683                    active_apps.remove(&id);
684                    compositor.chrome.private_panes.remove(&id);
685                    let outputs = compositor.handle(CompositorInput::AppExited { app_id: id });
686                    dispatch_outputs(
687                        &mut compositor, &client, &model_client, &worker_client,
688                        &model_status_tx, &mut terminal, &mut console_app,
689                        &mut active_apps, &mut next_local_id, &storage_key, signing_key,
690                        &registry, &vfs_ns, &vfs_subject, &vfs_proxy_tx, outputs,
691                    ).await;
692                }
693                if should_exit { break; }
694            }
695
696            Some(update) = model_status_rx.recv() => {
697                let ModelStatusUpdate { model_ref, loaded, gen_defaults } = update;
698                // Update gen_defaults on the model entry.
699                for entry in compositor.chrome.model_list.items_mut() {
700                    if entry.model_ref == model_ref {
701                        entry.gen_defaults = gen_defaults.clone();
702                    }
703                }
704                let follow_up = compositor.chrome.update_model_status(&model_ref, loaded);
705                if !loaded {
706                    compositor.chrome.push_toast(
707                        format!("Model load timed out: {model_ref}"),
708                        ToastLevel::Error,
709                    );
710                }
711                // Dispatch follow-up RPC (e.g., ListConversations when pending picker resolves).
712                if let Some(rpc_req) = follow_up {
713                    dispatch_outputs(
714                        &mut compositor, &client, &model_client, &worker_client,
715                        &model_status_tx, &mut terminal, &mut console_app,
716                        &mut active_apps, &mut next_local_id, &storage_key, signing_key,
717                        &registry, &vfs_ns, &vfs_subject, &vfs_proxy_tx,
718                        vec![CompositorOutput::Rpc(rpc_req)],
719                    ).await;
720                }
721                composite_draw(&mut terminal, &compositor, &mut console_app);
722            }
723
724            Some((new_cols, new_rows)) = resize_rx.recv() => {
725                rows = new_rows;
726                // Resize the ratatui backend to the new dimensions.
727                terminal.backend_mut().resize(new_cols, new_rows);
728                let _ = terminal.clear();
729                let outputs = compositor.handle(CompositorInput::Resize(new_cols, new_rows));
730                if dispatch_outputs(
731                    &mut compositor, &client, &model_client, &worker_client,
732                    &model_status_tx, &mut terminal, &mut console_app,
733                    &mut active_apps, &mut next_local_id, &storage_key, signing_key,
734                    &registry, &vfs_ns, &vfs_subject, &vfs_proxy_tx, outputs,
735                ).await { break; }
736                composite_draw(&mut terminal, &compositor, &mut console_app);
737            }
738
739            else => break,
740        }
741    }
742
743    // Abort background tasks that would otherwise block shutdown.
744    _sigwinch_handle.abort();
745
746    // Disable mouse tracking.
747    {
748        use std::io::Write;
749        let _ = std::io::stdout().write_all(b"\x1b[?1002l\x1b[?1006l");
750        let _ = std::io::stdout().flush();
751    }
752    let _ = terminal.show_cursor();
753    let _ = terminal.flush();
754    restore_terminal(&orig);
755
756    // Drop RPC clients off-thread to avoid dropping futures inside an async context.
757    tokio::task::spawn_blocking(move || {
758        drop(client);
759        drop(model_client);
760        drop(worker_client);
761    });
762
763    Ok(())
764}
765
766// ============================================================================
767// dispatch_outputs — translate CompositorOutput to RPC calls
768// ============================================================================
769
770// ============================================================================
771// composite_draw — render compositor + optional Console overlay
772// ============================================================================
773
774fn composite_draw(
775    terminal: &mut ratatui::Terminal<AnsiBackend<AnsiWriter>>,
776    compositor: &hyprstream_compositor::Compositor,
777    console_app: &mut ConsoleApp,
778) {
779    let _ = terminal.draw(|f| {
780        compositor.render(f);
781        if matches!(
782            compositor.chrome.mode,
783            hyprstream_compositor::ShellMode::Console
784        ) {
785            use ratatui::layout::{Constraint, Flex, Layout};
786            use ratatui::widgets::Clear;
787            let area = f.area();
788            let pane_area = compositor.pane_block_area(area);
789            let [v] = Layout::vertical([Constraint::Percentage(68)])
790                .flex(Flex::Center)
791                .areas(pane_area);
792            let [popup] = Layout::horizontal([Constraint::Percentage(82)])
793                .flex(Flex::Center)
794                .areas(v);
795            f.render_widget(Clear, popup);
796            let block =
797                hyprstream_compositor::theme::modal_block(ratatui::text::Line::from(" Console "));
798            let inner = block.inner(popup);
799            f.render_widget(block, popup);
800            console_app.draw(f, inner);
801        }
802    });
803}
804
805/// Dispatch compositor outputs to the appropriate RPC calls.
806/// Returns `true` if the session should exit.
807async fn dispatch_outputs(
808    compositor: &mut Compositor,
809    client: &TuiClient,
810    model_client: &hyprstream_rpc_std::model_client::ModelClient,
811    worker_client: &hyprstream_rpc_std::worker_client::WorkerClient,
812    model_status_tx: &tokio::sync::mpsc::Sender<ModelStatusUpdate>,
813    terminal: &mut ratatui::Terminal<AnsiBackend<AnsiWriter>>,
814    console_app: &mut ConsoleApp,
815    active_apps: &mut HashMap<u32, ActiveApp>,
816    next_local_id: &mut u32,
817    storage_key: &StorageKey,
818    signing_key: &SigningKey,
819    registry: &hyprstream_rpc_std::registry_client::RegistryClient,
820    vfs_ns: &std::sync::Arc<hyprstream_vfs::Namespace>,
821    vfs_subject: &hyprstream_rpc::Subject,
822    vfs_proxy_tx: &tokio::sync::mpsc::Sender<hyprstream_vfs::proxy::VfsRequest>,
823    outputs: Vec<CompositorOutput>,
824) -> bool {
825    for output in outputs {
826        match output {
827            CompositorOutput::Redraw => {
828                composite_draw(terminal, compositor, console_app);
829            }
830            CompositorOutput::Quit => return true,
831            CompositorOutput::Rpc(req) => {
832                let feed_back = handle_rpc(
833                    compositor,
834                    client,
835                    model_client,
836                    worker_client,
837                    model_status_tx,
838                    active_apps,
839                    next_local_id,
840                    storage_key,
841                    signing_key,
842                    registry,
843                    vfs_ns,
844                    vfs_subject,
845                    vfs_proxy_tx,
846                    req,
847                )
848                .await;
849                for input in feed_back {
850                    let follow = compositor.handle(input);
851                    for fo in follow {
852                        match fo {
853                            CompositorOutput::Redraw => {
854                                composite_draw(terminal, compositor, console_app);
855                            }
856                            CompositorOutput::Quit => return true,
857                            _ => {}
858                        }
859                    }
860                }
861            }
862            CompositorOutput::RouteInput { app_id, data } => {
863                if let Some(app) = active_apps.get_mut(&app_id) {
864                    let keys: Vec<waxterm::input::KeyPress> = InputParser::new(vec![]).parse(&data);
865                    for key in keys {
866                        if app.handle_input(key) {
867                            let ansi = render_app_to_ansi(app);
868                            let outs =
869                                compositor.handle(CompositorInput::AppFrame { app_id, ansi });
870                            for o in outs {
871                                if let CompositorOutput::Redraw = o {
872                                    composite_draw(terminal, compositor, console_app);
873                                }
874                            }
875                        }
876                    }
877                }
878            }
879        }
880    }
881    false
882}
883
884/// Translate an `RpcRequest` into RPC calls and return `CompositorInput`
885/// events to feed back (e.g. updated window list after create/close).
886async fn handle_rpc(
887    compositor: &mut Compositor,
888    client: &TuiClient,
889    model_client: &hyprstream_rpc_std::model_client::ModelClient,
890    worker_client: &hyprstream_rpc_std::worker_client::WorkerClient,
891    model_status_tx: &tokio::sync::mpsc::Sender<ModelStatusUpdate>,
892    active_apps: &mut HashMap<u32, ActiveApp>,
893    next_local_id: &mut u32,
894    storage_key: &StorageKey,
895    signing_key: &SigningKey,
896    registry: &hyprstream_rpc_std::registry_client::RegistryClient,
897    vfs_ns: &std::sync::Arc<hyprstream_vfs::Namespace>,
898    vfs_subject: &hyprstream_rpc::Subject,
899    vfs_proxy_tx: &tokio::sync::mpsc::Sender<hyprstream_vfs::proxy::VfsRequest>,
900    req: RpcRequest,
901) -> Vec<CompositorInput> {
902    let session_id = compositor.chrome.session_id;
903    match req {
904        RpcRequest::SendInput { viewer_id, data } => {
905            send_input_rpc(client, viewer_id, &data).await;
906            vec![]
907        }
908
909        RpcRequest::CreateWindow { .. } => {
910            // Create window + spawn shell, then advance active_win to the new window.
911            if let Ok(win_info) = client.create_window().await {
912                let new_win_id = win_info.id;
913                let _ = spawn_shell_rpc(client, session_id, win_info.active_pane_id, "").await;
914                let _ = focus_window_rpc(client, new_win_id).await;
915                let wins = list_windows_rpc(client).await.unwrap_or_default();
916                if let Some(idx) = wins.iter().position(|w| w.id == new_win_id) {
917                    compositor.chrome.active_win = idx;
918                }
919                return vec![CompositorInput::WindowList(wins)];
920            }
921            vec![]
922        }
923
924        RpcRequest::CloseWindow { window_id, .. } => {
925            // Collect pane IDs before removing the window.
926            let pane_ids: Vec<u32> = compositor
927                .chrome
928                .windows
929                .iter()
930                .find(|w| w.id == window_id)
931                .map(|w| w.panes.iter().map(|p| p.id).collect())
932                .unwrap_or_default();
933            // Clean up client-owned ChatApps for any private panes in this window.
934            for id in &pane_ids {
935                active_apps.remove(id);
936                compositor.chrome.private_panes.remove(id);
937            }
938            // Remove the window from chrome immediately so the tab disappears
939            // and the background animation resumes without waiting for server confirmation.
940            if let Some(win_idx) = compositor
941                .chrome
942                .windows
943                .iter()
944                .position(|w| w.id == window_id)
945            {
946                compositor.chrome.windows.remove(win_idx);
947                if compositor.chrome.windows.is_empty() {
948                    compositor.chrome.active_win = 0;
949                } else {
950                    compositor.chrome.active_win = compositor
951                        .chrome
952                        .active_win
953                        .min(compositor.chrome.windows.len() - 1);
954                }
955            }
956            let _ = close_window_rpc(client, window_id).await;
957            // Remove each pane's VT buffer from the client-side LayoutTree.
958            for id in pane_ids {
959                compositor.handle(CompositorInput::PaneClosed { pane_id: id });
960            }
961            refresh_windows(client).await
962        }
963
964        RpcRequest::FocusWindow { window_id, .. } => {
965            if focus_window_rpc(client, window_id).await.is_ok() {
966                if let Some(idx) = compositor
967                    .chrome
968                    .windows
969                    .iter()
970                    .position(|w| w.id == window_id)
971                {
972                    compositor.chrome.active_win = idx;
973                }
974            }
975            vec![]
976        }
977
978        RpcRequest::SpawnShell { pane_id, cwd, .. } => {
979            if pane_id == 0 {
980                // pane_id == 0 means "new window" — create one and spawn the shell
981                // in its pane with the requested CWD (same pattern as SpawnServerChat).
982                if let Ok(win_info) = client.create_window().await {
983                    let new_win_id = win_info.id;
984                    let _ = focus_window_rpc(client, new_win_id).await;
985                    let _ =
986                        spawn_shell_rpc(client, session_id, win_info.active_pane_id, &cwd).await;
987                    let wins = list_windows_rpc(client).await.unwrap_or_default();
988                    if let Some(idx) = wins.iter().position(|w| w.id == new_win_id) {
989                        compositor.chrome.active_win = idx;
990                    }
991                    return vec![CompositorInput::WindowList(wins)];
992                }
993                vec![]
994            } else {
995                // pane_id given — spawn shell in the existing pane.
996                let _ = spawn_shell_rpc(client, session_id, pane_id, &cwd).await;
997                refresh_windows(client).await
998            }
999        }
1000
1001        RpcRequest::SpawnServerChat {
1002            model_ref,
1003            cols,
1004            rows,
1005            ..
1006        } => {
1007            // Create a window, spawn chat app in its pane, then advance active_win.
1008            if let Ok(win_info) = client.create_window().await {
1009                let new_win_id = win_info.id;
1010                let _ = focus_window_rpc(client, new_win_id).await;
1011                let _ = spawn_chat_app_rpc(
1012                    client,
1013                    session_id,
1014                    &model_ref,
1015                    cols,
1016                    rows,
1017                    win_info.active_pane_id,
1018                )
1019                .await;
1020                let wins = list_windows_rpc(client).await.unwrap_or_default();
1021                if let Some(idx) = wins.iter().position(|w| w.id == new_win_id) {
1022                    compositor.chrome.active_win = idx;
1023                }
1024                return vec![CompositorInput::WindowList(wins)];
1025            }
1026            vec![]
1027        }
1028
1029        RpcRequest::LoadModel { model_ref } => {
1030            let _ = model_client
1031                .load(&hyprstream_rpc_std::model_client::LoadModelRequest {
1032                    model_ref: model_ref.clone(),
1033                    max_context: None,
1034                    kv_quant: None,
1035                })
1036                .await;
1037            spawn_model_load_poll(model_client.clone(), model_ref, model_status_tx.clone());
1038            vec![]
1039        }
1040
1041        RpcRequest::UnloadModel { model_ref } => {
1042            let ok = model_client
1043                .unload(&hyprstream_rpc_std::model_client::UnloadModelRequest {
1044                    model_ref: model_ref.clone(),
1045                })
1046                .await
1047                .is_ok();
1048            if ok {
1049                compositor.chrome.update_model_status(&model_ref, false);
1050            }
1051            vec![]
1052        }
1053
1054        RpcRequest::LocalPrivateChat {
1055            model_ref,
1056            cols,
1057            rows,
1058            resume_uuid,
1059            gen_defaults,
1060        } => {
1061            let (tool_caller, tool_descriptions, openai_tools) =
1062                match crate::tui::rpc_transport::make_tool_caller(signing_key) {
1063                    Ok(tool_caller) => tool_caller,
1064                    Err(_) => {
1065                        compositor.chrome.push_toast(
1066                            "Private chat unavailable: TUI service credential is required"
1067                                .to_owned(),
1068                            ToastLevel::Error,
1069                        );
1070                        return vec![];
1071                    }
1072                };
1073            // Allocate a local pane ID in the high-bit range to avoid
1074            // collision with server-allocated IDs (which start at 1).
1075            let pane_id = *next_local_id;
1076            *next_local_id = next_local_id.saturating_add(1);
1077
1078            let session_uuid = match &resume_uuid {
1079                Some(s) => uuid::Uuid::parse_str(s).unwrap_or_else(|_| uuid::Uuid::new_v4()),
1080                None => uuid::Uuid::new_v4(),
1081            };
1082            // Shared gen_config Arc — passed to both the spawner and the ChatApp.
1083            // Use model-specific defaults from RPC if available, otherwise fall back.
1084            let chat_gen_cfg = match gen_defaults {
1085                Some(gd) => {
1086                    let d = hyprstream_tui::chat_app::ChatGenConfig::default();
1087                    hyprstream_tui::chat_app::ChatGenConfig {
1088                        max_tokens: gd.max_tokens.unwrap_or(d.max_tokens),
1089                        temperature: gd.temperature.unwrap_or(d.temperature),
1090                        top_p: gd.top_p.unwrap_or(d.top_p),
1091                        top_k: gd.top_k.or(d.top_k),
1092                        context_window: gd.context_window,
1093                    }
1094                }
1095                None => hyprstream_tui::chat_app::ChatGenConfig::default(),
1096            };
1097            let gen_config = std::sync::Arc::new(parking_lot::RwLock::new(chat_gen_cfg));
1098
1099            let storage_dir = private_store_dir();
1100            let app = match FsBackend::new(storage_dir) {
1101                Ok(fs) => {
1102                    let key_bytes: [u8; 32] = **storage_key;
1103                    let fs_store =
1104                        std::sync::Arc::new(hyprstream_tui::private_store::PrivateStore::new(
1105                            fs,
1106                            Zeroizing::new(key_bytes),
1107                        ));
1108                    // Register conversation in manifest (skip if resuming).
1109                    if resume_uuid.is_none() {
1110                        let now = std::time::SystemTime::now()
1111                            .duration_since(std::time::UNIX_EPOCH)
1112                            .unwrap_or_default()
1113                            .as_secs();
1114                        let _ = fs_store.register_conversation(
1115                            hyprstream_tui::private_store::ConversationMeta {
1116                                uuid: session_uuid,
1117                                model_ref: model_ref.clone(),
1118                                created_at: now,
1119                                last_active: now,
1120                                label: Some(format!("Chat: {}", model_ref)),
1121                            },
1122                        );
1123                    }
1124                    let load_store = fs_store.clone();
1125                    let save_store = fs_store;
1126                    let uuid_for_load = session_uuid;
1127                    let uuid_for_save = session_uuid;
1128                    let load_hook: LoadHook = Box::new(move || {
1129                        load_store
1130                            .load::<hyprstream_tui::chat_app::ChatHistoryEntry>(&uuid_for_load)
1131                            .ok()
1132                            .flatten()
1133                    });
1134                    let save_hook: SaveHook = Box::new(move |entries| {
1135                        let _ = save_store.save(&uuid_for_save, entries);
1136                    });
1137                    let spawner = crate::tui::rpc_transport::make_chat_spawner(
1138                        signing_key,
1139                        &model_ref,
1140                        Some(openai_tools.clone()),
1141                        gen_config.clone(),
1142                    );
1143                    ChatApp::new_private(
1144                        model_ref.clone(),
1145                        cols,
1146                        rows,
1147                        spawner,
1148                        session_uuid,
1149                        load_hook,
1150                        save_hook,
1151                    )
1152                    .with_gen_config(gen_config)
1153                    .with_vfs_proxy(
1154                        vfs_ns.clone(),
1155                        vfs_subject.clone(),
1156                        vfs_proxy_tx.clone(),
1157                    )
1158                }
1159                Err(e) => {
1160                    compositor.chrome.push_toast(
1161                        format!("Private store dir unavailable: {e}"),
1162                        ToastLevel::Warn,
1163                    );
1164                    let spawner = crate::tui::rpc_transport::make_chat_spawner(
1165                        signing_key,
1166                        &model_ref,
1167                        Some(openai_tools.clone()),
1168                        gen_config.clone(),
1169                    );
1170                    ChatApp::new(model_ref.clone(), cols, rows, spawner)
1171                        .with_gen_config(gen_config)
1172                        .with_vfs_proxy(vfs_ns.clone(), vfs_subject.clone(), vfs_proxy_tx.clone())
1173                }
1174            };
1175            // Detect tool call format from the model reference name.
1176            let tool_format = {
1177                use crate::api::tools::ToolCallFormat;
1178                match ToolCallFormat::from_model_ref(&model_ref) {
1179                    ToolCallFormat::Qwen3Xml | ToolCallFormat::None => {
1180                        hyprstream_tui::chat_app::ToolCallFormat::Qwen3Xml
1181                    }
1182                    ToolCallFormat::Qwen35XmlParam => {
1183                        hyprstream_tui::chat_app::ToolCallFormat::Qwen35XmlParam
1184                    }
1185                    ToolCallFormat::LlamaJson => {
1186                        hyprstream_tui::chat_app::ToolCallFormat::LlamaJson
1187                    }
1188                    ToolCallFormat::MistralJson => {
1189                        hyprstream_tui::chat_app::ToolCallFormat::MistralJson
1190                    }
1191                }
1192            };
1193            let app = app.with_tool_caller(tool_caller, tool_descriptions, tool_format);
1194            active_apps.insert(pane_id, ActiveApp::Chat(Box::new(app)));
1195            compositor.chrome.private_panes.insert(pane_id);
1196            compositor.layout.get_or_create_private(pane_id);
1197
1198            // Auto-number window names for duplicate models.
1199            let chat_prefix = format!("Chat: {}", model_ref);
1200            let existing_count = compositor
1201                .chrome
1202                .windows
1203                .iter()
1204                .filter(|w| {
1205                    w.name == chat_prefix || w.name.starts_with(&format!("{} (", chat_prefix))
1206                })
1207                .count();
1208            let win_name = if existing_count > 0 {
1209                format!("{} ({})", chat_prefix, existing_count + 1)
1210            } else {
1211                chat_prefix
1212            };
1213
1214            // Insert a phantom local window into chrome (no server round-trip).
1215            let win_summary = WindowSummary {
1216                id: pane_id, // use pane_id as window_id for local windows
1217                name: win_name,
1218                active_pane_id: pane_id,
1219                panes: vec![PaneSummary {
1220                    id: pane_id,
1221                    cols,
1222                    rows,
1223                    is_private: true,
1224                }],
1225            };
1226            compositor.chrome.windows.push(win_summary);
1227            compositor.chrome.active_win = compositor.chrome.windows.len() - 1;
1228
1229            // Render first frame.
1230            if let Some(a) = active_apps.get(&pane_id) {
1231                let ansi = render_app_to_ansi(a);
1232                compositor.handle(CompositorInput::AppFrame {
1233                    app_id: pane_id,
1234                    ansi,
1235                });
1236            }
1237            vec![]
1238        }
1239
1240        RpcRequest::ListConversations { model_ref } => {
1241            let storage_dir = private_store_dir();
1242            let conversations = match FsBackend::new(storage_dir) {
1243                Ok(fs) => {
1244                    let key_bytes: [u8; 32] = **storage_key;
1245                    let store = hyprstream_tui::private_store::PrivateStore::new(
1246                        fs,
1247                        Zeroizing::new(key_bytes),
1248                    );
1249                    store
1250                        .list_conversations(&model_ref)
1251                        .into_iter()
1252                        .map(|meta| ConversationPickerEntry {
1253                            kind: ConversationKind::Resume {
1254                                uuid: meta.uuid.to_string(),
1255                            },
1256                            label: meta
1257                                .label
1258                                .unwrap_or_else(|| format!("Chat: {}", meta.model_ref)),
1259                            last_active: meta.last_active,
1260                        })
1261                        .collect()
1262                }
1263                Err(_) => vec![],
1264            };
1265            compositor
1266                .chrome
1267                .open_conversation_picker(model_ref, conversations);
1268            vec![]
1269        }
1270
1271        RpcRequest::DeleteConversation { uuid, model_ref } => {
1272            let storage_dir = private_store_dir();
1273            if let Ok(fs) = FsBackend::new(storage_dir) {
1274                let key_bytes: [u8; 32] = **storage_key;
1275                let store =
1276                    hyprstream_tui::private_store::PrivateStore::new(fs, Zeroizing::new(key_bytes));
1277                if let Ok(uid) = uuid::Uuid::parse_str(&uuid) {
1278                    let _ = store.delete_conversation(&uid);
1279                }
1280            }
1281            compositor.chrome.push_toast(
1282                format!("Deleted conversation from {}", model_ref),
1283                ToastLevel::Info,
1284            );
1285            vec![]
1286        }
1287
1288        RpcRequest::ServiceStart { name: _ }
1289        | RpcRequest::ServiceStop { name: _ }
1290        | RpcRequest::ServiceRestart { name: _ }
1291        | RpcRequest::ServiceInstall
1292        | RpcRequest::ServiceStopAll
1293        | RpcRequest::ServiceStartAll => {
1294            compositor.chrome.push_toast(
1295                "Service management not yet available".to_owned(),
1296                ToastLevel::Warn,
1297            );
1298            vec![]
1299        }
1300        RpcRequest::WorkerDestroySandbox { sandbox_id } => {
1301            let short = &sandbox_id[..sandbox_id.len().min(8)];
1302            compositor
1303                .chrome
1304                .push_toast(format!("Destroying {short}..."), ToastLevel::Info);
1305            match worker_client.sandbox().stop(&sandbox_id).await {
1306                Ok(()) => {
1307                    let _ = worker_client.sandbox().remove(&sandbox_id).await;
1308                    compositor
1309                        .chrome
1310                        .push_toast(format!("Destroyed {short}"), ToastLevel::Info);
1311                }
1312                Err(e) => {
1313                    compositor
1314                        .chrome
1315                        .push_toast(format!("Destroy failed: {e}"), ToastLevel::Error);
1316                }
1317            }
1318            vec![]
1319        }
1320        RpcRequest::WorkerExecSync {
1321            sandbox_id: _,
1322            container_id,
1323            cmd,
1324        } => {
1325            let short = &container_id[..container_id.len().min(8)];
1326            compositor
1327                .chrome
1328                .push_toast(format!("Exec in {short}: {:?}", cmd), ToastLevel::Info);
1329            match worker_client
1330                .container()
1331                .exec(&hyprstream_rpc_std::worker_client::ExecSyncRequest {
1332                    container_id: container_id.clone(),
1333                    cmd: cmd.clone(),
1334                    timeout: 30,
1335                })
1336                .await
1337            {
1338                Ok(result) => {
1339                    let stdout = String::from_utf8_lossy(&result.stdout);
1340                    let msg = if stdout.len() > 60 {
1341                        format!("{}…", &stdout[..60])
1342                    } else {
1343                        stdout.to_string()
1344                    };
1345                    compositor
1346                        .chrome
1347                        .push_toast(format!("exec: {msg}"), ToastLevel::Info);
1348                }
1349                Err(e) => {
1350                    compositor
1351                        .chrome
1352                        .push_toast(format!("exec failed: {e}"), ToastLevel::Error);
1353                }
1354            }
1355            vec![]
1356        }
1357        RpcRequest::WorkerImageList => {
1358            match worker_client
1359                .image()
1360                .list(&hyprstream_rpc_std::worker_client::ImageFilter {
1361                    image: hyprstream_rpc_std::worker_client::ImageSpec::default(),
1362                })
1363                .await
1364            {
1365                Ok(images) => {
1366                    let entries: Vec<hyprstream_compositor::ImageEntry> = images
1367                        .into_iter()
1368                        .map(|img| {
1369                            let repo_tag = img
1370                                .repo_tags
1371                                .first()
1372                                .cloned()
1373                                .unwrap_or_else(|| "<none>".to_owned());
1374                            let id = if img.id.len() > 12 {
1375                                img.id[..12].to_owned()
1376                            } else {
1377                                img.id.clone()
1378                            };
1379                            hyprstream_compositor::ImageEntry {
1380                                repo_tag,
1381                                id,
1382                                size_bytes: img.size,
1383                                created: format!(
1384                                    "{}s ago",
1385                                    std::time::SystemTime::now()
1386                                        .duration_since(std::time::UNIX_EPOCH)
1387                                        .unwrap_or_default()
1388                                        .as_secs()
1389                                        .saturating_sub(img.uid as u64)
1390                                ),
1391                            }
1392                        })
1393                        .collect();
1394                    vec![CompositorInput::WorkerImageList { images: entries }]
1395                }
1396                Err(e) => {
1397                    compositor
1398                        .chrome
1399                        .push_toast(format!("Image list failed: {e}"), ToastLevel::Warn);
1400                    vec![]
1401                }
1402            }
1403        }
1404        RpcRequest::WorkerImagePull { image } => {
1405            use hyprstream_rpc_std::worker_client::ImageSpec;
1406            compositor
1407                .chrome
1408                .push_toast(format!("Pulling {image}..."), ToastLevel::Info);
1409            let spec = ImageSpec {
1410                image: image.clone(),
1411                annotations: Default::default(),
1412                runtime_handler: Default::default(),
1413            };
1414            match worker_client
1415                .image()
1416                .pull(&hyprstream_rpc_std::worker_client::PullImageRequest {
1417                    image: spec,
1418                    auth: hyprstream_rpc_std::worker_client::AuthConfig::default(),
1419                    sandbox_config: hyprstream_rpc_std::worker_client::PodSandboxConfig::default(),
1420                })
1421                .await
1422            {
1423                Ok(ref_id) => {
1424                    compositor.chrome.push_toast(
1425                        format!("Pulled: {}", &ref_id[..ref_id.len().min(20)]),
1426                        ToastLevel::Info,
1427                    );
1428                }
1429                Err(e) => {
1430                    compositor
1431                        .chrome
1432                        .push_toast(format!("Pull failed: {e}"), ToastLevel::Error);
1433                }
1434            }
1435            vec![]
1436        }
1437        RpcRequest::WorkerImageRemove { image } => {
1438            use hyprstream_rpc_std::worker_client::ImageSpec;
1439            let spec = ImageSpec {
1440                image: image.clone(),
1441                annotations: Default::default(),
1442                runtime_handler: Default::default(),
1443            };
1444            match worker_client.image().remove(&spec).await {
1445                Ok(()) => {
1446                    compositor
1447                        .chrome
1448                        .push_toast(format!("Removed {image}"), ToastLevel::Info);
1449                }
1450                Err(e) => {
1451                    compositor
1452                        .chrome
1453                        .push_toast(format!("Remove failed: {e}"), ToastLevel::Error);
1454                }
1455            }
1456            vec![]
1457        }
1458        RpcRequest::WorkerCreateSandbox {
1459            hostname,
1460            backend,
1461            gpu,
1462        } => {
1463            use hyprstream_rpc_std::worker_client::{KeyValue, PodSandboxConfig};
1464            let mut annotations = vec![];
1465            annotations.push(KeyValue {
1466                key: "io.hyprstream/runtime-handler".to_owned(),
1467                value: backend,
1468            });
1469            if gpu {
1470                annotations.push(KeyValue {
1471                    key: "hyprstream.io/gpu".to_owned(),
1472                    value: "true".to_owned(),
1473                });
1474            }
1475            let config = PodSandboxConfig {
1476                hostname,
1477                annotations,
1478                ..Default::default()
1479            };
1480            match worker_client.sandbox().run(&config).await {
1481                Ok(sandbox_id) => {
1482                    let short = &sandbox_id[..sandbox_id.len().min(8)];
1483                    compositor
1484                        .chrome
1485                        .push_toast(format!("Created sandbox {short}"), ToastLevel::Info);
1486                }
1487                Err(e) => {
1488                    compositor
1489                        .chrome
1490                        .push_toast(format!("Create sandbox failed: {e}"), ToastLevel::Error);
1491                }
1492            }
1493            vec![]
1494        }
1495        RpcRequest::WorkerCreateContainer {
1496            sandbox_id,
1497            image,
1498            cmd,
1499            tty,
1500        } => {
1501            use hyprstream_rpc_std::worker_client::{ContainerConfig, ImageSpec, PodSandboxConfig};
1502            let short_sb = &sandbox_id[..sandbox_id.len().min(8)];
1503            // PodSandboxStatusResponse has no config field — use default
1504            let sandbox_config = PodSandboxConfig::default();
1505            let container_config = ContainerConfig {
1506                image: ImageSpec {
1507                    image: image.clone(),
1508                    annotations: Default::default(),
1509                    runtime_handler: Default::default(),
1510                },
1511                command: cmd,
1512                tty,
1513                ..Default::default()
1514            };
1515            match worker_client
1516                .container()
1517                .create(&hyprstream_rpc_std::worker_client::CreateContainerRequest {
1518                    pod_sandbox_id: sandbox_id.clone(),
1519                    config: container_config,
1520                    sandbox_config,
1521                })
1522                .await
1523            {
1524                Ok(container_id) => {
1525                    let short = &container_id[..container_id.len().min(8)];
1526                    compositor.chrome.push_toast(
1527                        format!("Created container {short} in {short_sb}"),
1528                        ToastLevel::Info,
1529                    );
1530                    // Auto-start
1531                    if let Err(e) = worker_client.container().start(&container_id).await {
1532                        compositor
1533                            .chrome
1534                            .push_toast(format!("Start failed: {e}"), ToastLevel::Error);
1535                    }
1536                }
1537                Err(e) => {
1538                    compositor
1539                        .chrome
1540                        .push_toast(format!("Create container failed: {e}"), ToastLevel::Error);
1541                }
1542            }
1543            vec![]
1544        }
1545        RpcRequest::WorkerStartContainer { container_id } => {
1546            let short = &container_id[..container_id.len().min(8)];
1547            match worker_client.container().start(&container_id).await {
1548                Ok(()) => compositor
1549                    .chrome
1550                    .push_toast(format!("Started {short}"), ToastLevel::Info),
1551                Err(e) => compositor
1552                    .chrome
1553                    .push_toast(format!("Start failed: {e}"), ToastLevel::Error),
1554            }
1555            vec![]
1556        }
1557        RpcRequest::WorkerStopContainer { container_id } => {
1558            let short = &container_id[..container_id.len().min(8)];
1559            match worker_client
1560                .container()
1561                .stop(&hyprstream_rpc_std::worker_client::StopContainerRequest {
1562                    container_id: container_id.clone(),
1563                    timeout: 10,
1564                })
1565                .await
1566            {
1567                Ok(()) => compositor
1568                    .chrome
1569                    .push_toast(format!("Stopped {short}"), ToastLevel::Info),
1570                Err(e) => compositor
1571                    .chrome
1572                    .push_toast(format!("Stop failed: {e}"), ToastLevel::Error),
1573            }
1574            vec![]
1575        }
1576        RpcRequest::WorkerRemoveContainer { container_id } => {
1577            let short = &container_id[..container_id.len().min(8)];
1578            match worker_client.container().remove(&container_id).await {
1579                Ok(()) => compositor
1580                    .chrome
1581                    .push_toast(format!("Removed {short}"), ToastLevel::Info),
1582                Err(e) => compositor
1583                    .chrome
1584                    .push_toast(format!("Remove failed: {e}"), ToastLevel::Error),
1585            }
1586            vec![]
1587        }
1588        RpcRequest::AttachContainer {
1589            sandbox_id,
1590            container_id,
1591            cols,
1592            rows,
1593        } => {
1594            use hyprstream_rpc::streaming::StreamPayload;
1595
1596            let short_c = container_id[..container_id.len().min(8)].to_owned();
1597            let short_s = sandbox_id[..sandbox_id.len().min(8)].to_owned();
1598
1599            // Attach RPC → returns ready-to-use StreamHandle (DH + SUB + HMAC managed internally).
1600            use hyprstream_rpc_std::worker_client::ContainerRpc;
1601            let mut stream_handle = match ContainerRpc::attach(
1602                &worker_client.container(),
1603                &hyprstream_rpc_std::worker_client::AttachRequest {
1604                    container_id: container_id.clone(),
1605                    fds: vec![],
1606                },
1607            )
1608            .await
1609            {
1610                Ok(h) => h,
1611                Err(e) => {
1612                    compositor
1613                        .chrome
1614                        .push_toast(format!("Attach failed: {e}"), ToastLevel::Error);
1615                    return vec![];
1616                }
1617            };
1618
1619            // Channel: stream reader thread → ContainerTermApp VtPane.
1620            let (stdout_tx, stdout_rx) = std::sync::mpsc::sync_channel::<Vec<u8>>(64);
1621
1622            // Spawn a thread with its own Tokio runtime to pump the stream.
1623            std::thread::spawn(move || {
1624                let rt = match tokio::runtime::Builder::new_current_thread()
1625                    .enable_all()
1626                    .build()
1627                {
1628                    Ok(r) => r,
1629                    Err(_) => return,
1630                };
1631                rt.block_on(async move {
1632                    while let Ok(Some(StreamPayload::Data(bytes))) = stream_handle.recv_next().await
1633                    {
1634                        if stdout_tx.send(bytes).is_err() {
1635                            break; // ContainerTermApp dropped
1636                        }
1637                    }
1638                });
1639            });
1640
1641            // Create ContainerTermApp with the stdout channel.
1642            let app = ContainerTermApp::new(
1643                container_id.clone(),
1644                sandbox_id.clone(),
1645                cols,
1646                rows,
1647                stdout_rx,
1648                None, // stdin not wired yet (Phase W-III-b)
1649            );
1650
1651            // Allocate local pane ID.
1652            let pane_id = *next_local_id;
1653            *next_local_id = next_local_id.saturating_add(1);
1654
1655            active_apps.insert(pane_id, ActiveApp::Container(Box::new(app)));
1656            compositor.chrome.private_panes.insert(pane_id);
1657            compositor.layout.get_or_create_private(pane_id);
1658
1659            // Insert phantom window for the container terminal.
1660            let win_name = format!("{short_s}:{short_c}");
1661            let win_summary = WindowSummary {
1662                id: pane_id,
1663                name: win_name,
1664                active_pane_id: pane_id,
1665                panes: vec![PaneSummary {
1666                    id: pane_id,
1667                    cols,
1668                    rows,
1669                    is_private: true,
1670                }],
1671            };
1672            compositor.chrome.windows.push(win_summary);
1673            compositor.chrome.active_win = compositor.chrome.windows.len() - 1;
1674
1675            // Close the worker modal.
1676            compositor.chrome.mode = hyprstream_compositor::chrome::ShellMode::Normal;
1677
1678            // Render initial frame.
1679            if let Some(a) = active_apps.get(&pane_id) {
1680                let ansi = render_app_to_ansi(a);
1681                compositor.handle(CompositorInput::AppFrame {
1682                    app_id: pane_id,
1683                    ansi,
1684                });
1685            }
1686
1687            compositor
1688                .chrome
1689                .push_toast(format!("Attached to {short_c}"), ToastLevel::Info);
1690            vec![]
1691        }
1692        RpcRequest::CloneModel { url, name } => {
1693            use hyprstream_rpc_std::registry_client::CloneRequest;
1694            compositor
1695                .chrome
1696                .push_toast(format!("Cloning {name}…"), ToastLevel::Info);
1697            match registry
1698                .clone(&CloneRequest {
1699                    url,
1700                    name: name.clone(),
1701                    shallow: false,
1702                    depth: 0,
1703                    branch: String::new(),
1704                })
1705                .await
1706            {
1707                Ok(_) => {
1708                    compositor
1709                        .chrome
1710                        .finish_clone(true, format!("Cloned {name}"));
1711                    compositor
1712                        .chrome
1713                        .push_toast(format!("Cloned {name}"), ToastLevel::Info);
1714                }
1715                Err(e) => {
1716                    compositor
1717                        .chrome
1718                        .finish_clone(false, format!("Clone failed: {e}"));
1719                    compositor
1720                        .chrome
1721                        .push_toast(format!("Clone failed: {e}"), ToastLevel::Error);
1722                }
1723            }
1724            vec![]
1725        }
1726
1727        RpcRequest::PullModel { model_ref } => {
1728            use hyprstream_rpc_std::registry_client::UpdateRequest;
1729            let model_name = model_ref.split(':').next().unwrap_or(&model_ref);
1730            let branch = model_ref.split(':').nth(1).unwrap_or("main");
1731            match registry.get_by_name(model_name).await {
1732                Ok(tracked) => {
1733                    let repo_client = registry.repo(&tracked.id);
1734                    match repo_client
1735                        .update(&UpdateRequest {
1736                            refspec: format!("refs/heads/{branch}"),
1737                        })
1738                        .await
1739                    {
1740                        Ok(()) => {
1741                            compositor
1742                                .chrome
1743                                .update_git_op_progress(&format!("Done: Pulled {model_ref}"));
1744                            compositor
1745                                .chrome
1746                                .push_toast(format!("Pulled {model_ref}"), ToastLevel::Info);
1747                        }
1748                        Err(e) => {
1749                            compositor
1750                                .chrome
1751                                .update_git_op_progress(&format!("Error: {e}"));
1752                            compositor
1753                                .chrome
1754                                .push_toast(format!("Pull failed: {e}"), ToastLevel::Error);
1755                        }
1756                    }
1757                }
1758                Err(e) => {
1759                    compositor
1760                        .chrome
1761                        .update_git_op_progress(&format!("Error: {e}"));
1762                    compositor
1763                        .chrome
1764                        .push_toast(format!("Pull failed: {e}"), ToastLevel::Error);
1765                }
1766            }
1767            vec![]
1768        }
1769
1770        RpcRequest::PushModel { model_ref } => {
1771            use hyprstream_rpc_std::registry_client::PushRequest;
1772            let model_name = model_ref.split(':').next().unwrap_or(&model_ref);
1773            let branch = model_ref.split(':').nth(1).unwrap_or("main");
1774            match registry.get_by_name(model_name).await {
1775                Ok(tracked) => {
1776                    let repo_client = registry.repo(&tracked.id);
1777                    let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
1778                    match repo_client
1779                        .push(&PushRequest {
1780                            remote: "origin".to_owned(),
1781                            refspec,
1782                            force: false,
1783                        })
1784                        .await
1785                    {
1786                        Ok(()) => {
1787                            compositor
1788                                .chrome
1789                                .update_git_op_progress(&format!("Done: Pushed {model_ref}"));
1790                            compositor
1791                                .chrome
1792                                .push_toast(format!("Pushed {model_ref}"), ToastLevel::Info);
1793                        }
1794                        Err(e) => {
1795                            compositor
1796                                .chrome
1797                                .update_git_op_progress(&format!("Error: {e}"));
1798                            compositor
1799                                .chrome
1800                                .push_toast(format!("Push failed: {e}"), ToastLevel::Error);
1801                        }
1802                    }
1803                }
1804                Err(e) => {
1805                    compositor
1806                        .chrome
1807                        .update_git_op_progress(&format!("Error: {e}"));
1808                    compositor
1809                        .chrome
1810                        .push_toast(format!("Push failed: {e}"), ToastLevel::Error);
1811                }
1812            }
1813            vec![]
1814        }
1815
1816        RpcRequest::FetchModelStatus => {
1817            // Refresh the model list from registry
1818            vec![]
1819        }
1820
1821        RpcRequest::Quit => vec![],
1822    }
1823}
1824
1825/// Call listWindows and return a `WindowList` compositor input.
1826async fn refresh_windows(client: &TuiClient) -> Vec<CompositorInput> {
1827    match list_windows_rpc(client).await {
1828        Ok(wins) => vec![CompositorInput::WindowList(wins)],
1829        Err(_) => vec![],
1830    }
1831}
1832
1833// ============================================================================
1834// handle_tui_shell — embedded mode (hyprstream tui shell)
1835// ============================================================================
1836
1837/// Spawn ShellApp inside TuiService via SpawnChromeShell RPC.
1838///
1839/// The ShellApp runs server-side as a `PaneProcess` — no fork occurs in this
1840/// process after ZMQ is initialised.  Playwright tests use this path.
1841pub async fn handle_tui_shell(
1842    signing_key: &SigningKey,
1843    models_dir: &std::path::Path,
1844    session_id: u32,
1845) -> Result<()> {
1846    use crate::cli::tui_handlers::{create_tui_client, terminal_size};
1847
1848    let (cols, rows) = terminal_size();
1849    let client = create_tui_client(signing_key)?;
1850
1851    let registry_dir = models_dir.join(".registry").join("models");
1852    let registry_dir = if registry_dir.exists() {
1853        registry_dir
1854    } else {
1855        models_dir.to_path_buf()
1856    };
1857    let registry_str = registry_dir.to_string_lossy().into_owned();
1858
1859    client
1860        .spawn_chrome_shell(&SpawnChromeShellRequest {
1861            session_id,
1862            registry_dir: registry_str,
1863            cols,
1864            rows,
1865            pane_id: 0,
1866        })
1867        .await
1868        .context("spawnChromeShell RPC failed")?;
1869
1870    tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?
1871        .recv()
1872        .await;
1873
1874    Ok(())
1875}
1876
1877// ============================================================================
1878// Helpers — model fetch
1879// ============================================================================
1880
1881async fn fetch_models(signing_key: &SigningKey, models_dir: &std::path::Path) -> Vec<ModelEntry> {
1882    let registry: hyprstream_rpc_std::registry_client::RegistryClient =
1883        match hyprstream_rpc_std::registry_client::RegistryClient::from_provider(
1884            &hyprstream_discovery::ProductionRpcClientProvider,
1885            signing_key.clone(),
1886            None,
1887        ) {
1888            Ok(c) => c,
1889            Err(e) => {
1890                tracing::warn!("Failed to create RegistryClient: {e}");
1891                return Vec::new();
1892            }
1893        };
1894    let model_client_for_status = match hyprstream_rpc_std::model_client::ModelClient::from_provider(
1895        &hyprstream_discovery::ProductionRpcClientProvider,
1896        signing_key.clone(),
1897        None,
1898    ) {
1899        Ok(c) => c,
1900        Err(e) => {
1901            tracing::warn!("Failed to create ModelClient: {e}");
1902            return Vec::new();
1903        }
1904    };
1905    let registry_models_dir = models_dir.to_path_buf();
1906    let status_timeout = std::time::Duration::from_millis(500);
1907
1908    let all_status_req = hyprstream_rpc_std::model_client::StatusRequest {
1909        model_ref: String::new(),
1910    };
1911    let (repos_result, status_result) = tokio::join!(
1912        registry.list(),
1913        tokio::time::timeout(
1914            status_timeout,
1915            model_client_for_status.status(&all_status_req)
1916        ),
1917    );
1918
1919    let status_map: std::collections::HashMap<String, (bool, GenerationDefaults)> =
1920        match status_result {
1921            Ok(Ok(entries)) => entries
1922                .into_iter()
1923                .map(|e| {
1924                    let loaded = e.status == "loaded";
1925                    let gd = wire_gen_defaults_to_compositor(&e.generation_defaults);
1926                    (e.model_ref, (loaded, gd))
1927                })
1928                .collect(),
1929            _ => std::collections::HashMap::new(),
1930        };
1931
1932    match repos_result {
1933        Ok(repos) => repos
1934            .into_iter()
1935            .filter(|r| !r.name.is_empty())
1936            .flat_map(|r| {
1937                let name = r.name.clone();
1938                let rmd = registry_models_dir.clone();
1939                r.worktrees
1940                    .into_iter()
1941                    .map(move |wt| {
1942                        let branch = if wt.branch_name.is_empty() {
1943                            "main".to_owned()
1944                        } else {
1945                            wt.branch_name
1946                        };
1947                        let model_ref = format!("{}:{}", name, branch);
1948                        let path = rmd.join(&name).join("worktrees").join(&branch);
1949                        ModelEntry {
1950                            model_ref,
1951                            path,
1952                            loaded: false,
1953                            loading: false,
1954                            gen_defaults: Default::default(),
1955                        }
1956                    })
1957                    .collect::<Vec<_>>()
1958            })
1959            .map(|mut entry| {
1960                if let Some((loaded, gd)) = status_map.get(&entry.model_ref) {
1961                    entry.loaded = *loaded;
1962                    entry.gen_defaults = gd.clone();
1963                }
1964                entry
1965            })
1966            .collect(),
1967        Err(_) => vec![],
1968    }
1969}
1970
1971// ============================================================================
1972// RPC helpers
1973// ============================================================================
1974
1975async fn list_windows_rpc(client: &TuiClient) -> anyhow::Result<Vec<WindowSummary>> {
1976    let list = client.list_windows(0).await?;
1977    Ok(list
1978        .windows
1979        .iter()
1980        .map(|w| WindowSummary {
1981            id: w.id,
1982            name: w.name.clone(),
1983            active_pane_id: w.active_pane_id,
1984            panes: w
1985                .panes
1986                .iter()
1987                .map(|p| PaneSummary {
1988                    id: p.id,
1989                    cols: p.cols,
1990                    rows: p.rows,
1991                    is_private: p.is_private,
1992                })
1993                .collect(),
1994        })
1995        .collect())
1996}
1997
1998async fn resize_rpc(client: &TuiClient, cols: u16, rows: u16) -> anyhow::Result<()> {
1999    client.resize(&ResizeRequest { cols, rows }).await
2000}
2001
2002async fn send_input_rpc(client: &TuiClient, viewer_id: u32, data: &[u8]) {
2003    if let Err(e) = client
2004        .send_input(&SendInputRequest {
2005            viewer_id,
2006            data: data.to_vec(),
2007        })
2008        .await
2009    {
2010        tracing::debug!("sendInput failed: {e}");
2011    }
2012}
2013
2014// ============================================================================
2015// AnsiWriter newtype
2016// ============================================================================
2017
2018struct AnsiWriter(std::io::Stdout);
2019
2020impl std::io::Write for AnsiWriter {
2021    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
2022        self.0.write(buf)
2023    }
2024    fn flush(&mut self) -> std::io::Result<()> {
2025        self.0.flush()
2026    }
2027}
2028
2029// ============================================================================
2030// Mouse helpers
2031// ============================================================================
2032
2033fn parse_sgr_mouse_click(data: &[u8]) -> Option<(u16, u16)> {
2034    let mut i = 0;
2035    while i + 5 < data.len() {
2036        if data[i] == 0x1b && data[i + 1] == b'[' && data[i + 2] == b'<' {
2037            let rest = &data[i + 3..];
2038            if let Some(end) = rest.iter().position(|&b| b == b'M' || b == b'm') {
2039                let term = rest[end];
2040                let params = std::str::from_utf8(&rest[..end]).ok()?;
2041                let parts: Vec<&str> = params.split(';').collect();
2042                if parts.len() == 3 && term == b'M' {
2043                    let col = parts[1].parse::<u16>().ok()?.saturating_sub(1);
2044                    let row = parts[2].parse::<u16>().ok()?.saturating_sub(1);
2045                    return Some((col, row));
2046                }
2047                i += 3 + end + 1;
2048                continue;
2049            }
2050        }
2051        i += 1;
2052    }
2053    None
2054}
2055
2056fn tab_index_at_col(windows: &[WindowSummary], col: u16) -> Option<usize> {
2057    let mut x = 0u16;
2058    for (i, win) in windows.iter().enumerate() {
2059        let label_width = (win.name.len() as u16) + 2;
2060        let divider = if i + 1 < windows.len() { 1 } else { 0 };
2061        if col >= x && col < x + label_width {
2062            return Some(i);
2063        }
2064        x += label_width + divider;
2065    }
2066    None
2067}
2068
2069/// Convert the wire GenerationDefaults (7 fields) to the compositor's
2070/// GenerationDefaults (5 fields).
2071///
2072/// Intentionally dropped from the wire type:
2073///   - `repeat_penalty`: not exposed in the pre-chat settings modal
2074///   - `stop_tokens`: handled at the engine layer, not user-configurable
2075///   - `do_sample`: inferred from temperature > 0
2076///
2077/// `context_window` is set to `None` because it is a load-time parameter
2078/// configured via `LoadModelRequest.maxContext`, not a generation default.
2079fn wire_gen_defaults_to_compositor(
2080    wire: &hyprstream_rpc_std::model_client::GenerationDefaults,
2081) -> GenerationDefaults {
2082    GenerationDefaults {
2083        temperature: wire.temperature,
2084        top_p: wire.top_p,
2085        top_k: wire.top_k.map(|v| v as usize),
2086        max_tokens: wire.max_tokens.map(|v| v as usize),
2087        context_window: None,
2088    }
2089}
2090
2091/// Spawn a background task that polls model status every 2s until loaded (or timeout).
2092/// Sends a `ModelStatusUpdate` through `tx` when the model loads or after 120s timeout.
2093fn spawn_model_load_poll(
2094    poll_client: hyprstream_rpc_std::model_client::ModelClient,
2095    model_ref: String,
2096    tx: tokio::sync::mpsc::Sender<ModelStatusUpdate>,
2097) {
2098    tokio::spawn(async move {
2099        for _ in 0..60u32 {
2100            tokio::time::sleep(std::time::Duration::from_secs(2)).await;
2101            if let Ok(entries) = poll_client
2102                .status(&hyprstream_rpc_std::model_client::StatusRequest {
2103                    model_ref: model_ref.clone(),
2104                })
2105                .await
2106            {
2107                if let Some(entry) = entries.iter().find(|e| e.status == "loaded") {
2108                    let gd = wire_gen_defaults_to_compositor(&entry.generation_defaults);
2109                    let _ = tx
2110                        .send(ModelStatusUpdate {
2111                            model_ref,
2112                            loaded: true,
2113                            gen_defaults: gd,
2114                        })
2115                        .await;
2116                    return;
2117                }
2118            }
2119        }
2120        let _ = tx
2121            .send(ModelStatusUpdate {
2122                model_ref,
2123                loaded: false,
2124                gen_defaults: GenerationDefaults::default(),
2125            })
2126            .await;
2127    });
2128}
2129
2130/// Derive a 32-byte AES-256 storage key from the Ed25519 signing key seed.
2131///
2132/// Uses Blake3 `derive_key` (same as `hyprstream_rpc::crypto::backend::derive_key`)
2133/// so the key is deterministic and session-independent (rotating the signing key
2134/// invalidates all history — documented V1 limitation).
2135fn derive_storage_key(signing_key: &SigningKey) -> StorageKey {
2136    let seed = signing_key.to_bytes(); // 32-byte seed (pre-SHA-512)
2137    let key =
2138        hyprstream_rpc::crypto::backend::derive_key("hyprstream-storage-session-enc-v1", &seed);
2139    Zeroizing::new(key)
2140}
2141
2142/// Return the native path for private session storage files.
2143/// `$XDG_DATA_HOME/hyprstream/private/v1/` (or `~/.local/share/…` fallback).
2144fn private_store_dir() -> std::path::PathBuf {
2145    let base = std::env::var_os("XDG_DATA_HOME")
2146        .map(std::path::PathBuf::from)
2147        .or_else(|| dirs::home_dir().map(|h| h.join(".local").join("share")))
2148        .unwrap_or_else(|| std::path::PathBuf::from("/tmp"));
2149    base.join("hyprstream").join("private").join("v1")
2150}
2151
2152/// Render an `ActiveApp` off-screen to an ANSI byte buffer.
2153fn render_app_to_ansi(app: &ActiveApp) -> Vec<u8> {
2154    let backend = AnsiBackend::new(Vec::<u8>::new(), app.cols(), app.rows(), false);
2155    let Ok(mut term) = ratatui::Terminal::new(backend) else {
2156        return Vec::new();
2157    };
2158    let _ = term.draw(|f| app.render(f));
2159    term.backend().writer().clone()
2160}
2161
2162// ============================================================================
2163// TuiFrame decoder — Capnp → FrameUpdate
2164// ============================================================================
2165
2166/// Decode a serialized Cap'n Proto TuiFrame into a compositor `FrameUpdate`.
2167///
2168/// Called from the frame_rx arm in the event loop when connected in Capnp mode.
2169/// The resulting `FrameUpdate` is passed to `CompositorInput::ServerFrameCapnp`.
2170fn decode_tui_frame(data: &[u8]) -> anyhow::Result<FrameUpdate> {
2171    use capnp::serialize;
2172    use hyprstream_rpc_std::tui_capnp;
2173
2174    let reader = serialize::read_message_from_flat_slice(
2175        &mut &data[..],
2176        capnp::message::ReaderOptions::default(),
2177    )?;
2178    let frame = reader.get_root::<tui_capnp::tui_frame::Reader<'_>>()?;
2179
2180    let pane_id = frame.get_pane_id();
2181    let generation = frame.get_generation();
2182
2183    let cursor = {
2184        let c = frame.get_cursor()?;
2185        CursorState {
2186            x: c.get_x(),
2187            y: c.get_y(),
2188            visible: c.get_visible(),
2189        }
2190    };
2191
2192    let content = match frame.which()? {
2193        tui_capnp::tui_frame::Which::Full(full_r) => {
2194            let full = full_r?;
2195            let cols = full.get_cols();
2196            let rows = full.get_rows();
2197            let cells = full
2198                .get_cells()?
2199                .iter()
2200                .map(|c| CellUpdate {
2201                    x: c.get_x(),
2202                    y: c.get_y(),
2203                    symbol: c
2204                        .get_symbol()
2205                        .ok()
2206                        .and_then(|r| r.to_str().ok())
2207                        .unwrap_or("")
2208                        .to_owned(),
2209                    fg: unpack_color(c.get_fg()),
2210                    bg: unpack_color(c.get_bg()),
2211                    modifiers: ratatui::style::Modifier::from_bits_truncate(c.get_modifiers()),
2212                })
2213                .collect();
2214            FrameContent::Full { cols, rows, cells }
2215        }
2216        tui_capnp::tui_frame::Which::Incremental(incr_r) => {
2217            let incr = incr_r?;
2218            let scrolls = incr
2219                .get_scrolls()?
2220                .iter()
2221                .map(|s| ScrollUpdate {
2222                    top: s.get_top(),
2223                    bottom: s.get_bottom(),
2224                    amount: s.get_amount(),
2225                })
2226                .collect();
2227            let deltas = incr
2228                .get_deltas()?
2229                .iter()
2230                .map(|c| CellUpdate {
2231                    x: c.get_x(),
2232                    y: c.get_y(),
2233                    symbol: c
2234                        .get_symbol()
2235                        .ok()
2236                        .and_then(|r| r.to_str().ok())
2237                        .unwrap_or("")
2238                        .to_owned(),
2239                    fg: unpack_color(c.get_fg()),
2240                    bg: unpack_color(c.get_bg()),
2241                    modifiers: ratatui::style::Modifier::from_bits_truncate(c.get_modifiers()),
2242                })
2243                .collect();
2244            FrameContent::Incremental { scrolls, deltas }
2245        }
2246    };
2247
2248    Ok(FrameUpdate {
2249        pane_id,
2250        generation,
2251        cursor,
2252        content,
2253    })
2254}
2255
2256/// Unpack a u32 color (as encoded by `diff::pack_color`) into a ratatui Color.
2257fn unpack_color(packed: u32) -> ratatui::style::Color {
2258    use ratatui::style::Color;
2259    if packed & 0x0200_0000 != 0 {
2260        Color::Indexed((packed & 0xFF) as u8)
2261    } else if packed & 0x0100_0000 != 0 {
2262        Color::Rgb(
2263            ((packed >> 16) & 0xFF) as u8,
2264            ((packed >> 8) & 0xFF) as u8,
2265            (packed & 0xFF) as u8,
2266        )
2267    } else {
2268        match packed {
2269            1 => Color::Black,
2270            2 => Color::Red,
2271            3 => Color::Green,
2272            4 => Color::Yellow,
2273            5 => Color::Blue,
2274            6 => Color::Magenta,
2275            7 => Color::Cyan,
2276            8 => Color::Gray,
2277            9 => Color::DarkGray,
2278            10 => Color::LightRed,
2279            11 => Color::LightGreen,
2280            12 => Color::LightYellow,
2281            13 => Color::LightBlue,
2282            14 => Color::LightMagenta,
2283            15 => Color::LightCyan,
2284            16 => Color::White,
2285            _ => Color::Reset,
2286        }
2287    }
2288}
2289
2290// Tool discovery from `.tcl` files (used to populate `/bin` with discovered
2291// tool scripts) now lives in `crate::services::namespace_builder::discover_tools`
2292// as part of the shared standard-namespace recipe (#634).