Skip to main content

rbnx/cmd/
chat.rs

1// SPDX-License-Identifier: MulanPSL-2.0
2// cmd/chat.rs — TUI chat client (connects to robonix-liaison via SrvLiaison).
3//
4// Modalities (one TUI, one stream type per turn):
5//
6//   ┌────────────────┐ Enter ─────────► SrvLiaison.Stream(Task)
7//   │ rbnx chat TUI  │                 (text → PilotEvent stream)
8//   └────────────────┘ F2 ────────► SrvLiaison.StartVoiceSession(req)
9//                                       (voice → VoiceEvent stream which
10//                                        wraps PilotEvent in `pilot` field)
11//
12// Liaison handles user-id assignment, voice mic/ASR/voiceprint/TTS/speaker
13// orchestration, and forwarding to Pilot. The TUI just renders events.
14
15use anyhow::{Context, Result};
16use crossterm::{
17    ExecutableCommand,
18    event::{self, Event, KeyCode, KeyModifiers},
19    terminal::{self, EnterAlternateScreen, LeaveAlternateScreen},
20};
21use ratatui::{
22    Terminal,
23    backend::CrosstermBackend,
24    layout::{Constraint, Layout},
25    style::{Color, Modifier, Style},
26    text::{Line, Span},
27    widgets::{Block, Borders, Paragraph, Wrap},
28};
29use robonix_atlas::client::AtlasClient;
30use robonix_atlas::pb as atlas_pb;
31use robonix_scribe::{info, warn};
32use std::cell::RefCell;
33use std::collections::HashMap;
34use std::io;
35use std::rc::Rc;
36use tokio_stream::StreamExt;
37use uuid::Uuid;
38
39const CONSUMER_ID: &str = "rbnx-cli/chat";
40// Liaison was split into two contracts (submit + voice). chat only needs
41// to find one of them in atlas to know liaison is up; submit is the
42// always-present one (voice is optional / mode-gated), so wait on it.
43const LIAISON_CONTRACT_ID: &str = "robonix/system/liaison/submit";
44
45/// Atlas contract ids for the audio primitives that have user-visible
46/// device choices on a multi-provider host (e.g. local ALSA driver vs
47/// the macOS bridge). asr/tts are software backends with one provider
48/// per box, so we don't prompt for them.
49const MIC_CONTRACT: &str = "robonix/primitive/audio/mic";
50const SPEAKER_CONTRACT: &str = "robonix/primitive/audio/speaker";
51
52struct ChatMessage {
53    role: Role,
54    text: String,
55}
56
57enum Role {
58    User,
59    Agent,
60    ToolCall,
61    Status,
62    Voice,
63}
64
65/// Live RTDL forest state for the right-side panel. Fed by `PilotEvent`
66/// task_state / plan / node_state / batch_result events; rendered every frame.
67#[derive(Default)]
68struct ForestView {
69    goal: String,
70    success_criterion: String,
71    status: String,
72    /// Every task of the session; empty from a Pilot older than task lists,
73    /// which sends only the goal above.
74    tasks: Vec<crate::pb::pilot::TaskSummary>,
75    /// In-dispatch order; each is one RTDL tree of the current turn.
76    plans: Vec<PlanView>,
77}
78
79struct PlanView {
80    plan_id: String,
81    plan: crate::pb::pilot::Plan,
82    /// node_index → executor state (2=ok 3=fail 4=cancel …). Absent = pending.
83    node_states: HashMap<u32, u32>,
84    done: bool,
85    any_failed: bool,
86}
87
88impl ForestView {
89    /// Reset for a brand-new top-level turn (a fresh user message, not a
90    /// steer). A Pilot with task lists keeps its tasks and their trees across
91    /// turns and resends them, so they stay on the panel.
92    fn begin_turn(&mut self) {
93        self.goal.clear();
94        self.success_criterion.clear();
95        self.status.clear();
96        if self.tasks.is_empty() {
97            self.plans.clear();
98        }
99    }
100
101    fn plan_mut(&mut self, plan_id: &str) -> Option<&mut PlanView> {
102        self.plans.iter_mut().find(|p| p.plan_id == plan_id)
103    }
104}
105
106/// The standard LLM-facing capability name, exactly as pilot presents it to
107/// the model and as the model emits it in `do.cap`: `provider_id.<area>_<leaf>`
108/// — e.g. `front_camera.camera_snapshot`, `explore.explore_status`,
109/// `executor.builtin_read_file`. The `<area>_<leaf>`
110/// part mirrors `robonix_pilot::discovery::llm_name` (kept in sync here since
111/// rbnx-cli doesn't depend on the pilot crate); the `<area>` prefix is what
112/// disambiguates the shared `snapshot` / `status` leaves across providers.
113fn cap_short_name(provider_id: &str, contract_id: &str) -> String {
114    let mut segs = contract_id.rsplit('/');
115    let leaf = segs.next().unwrap_or(contract_id);
116    let area = segs.next().unwrap_or("");
117    let llm_name = if area.is_empty() {
118        leaf.to_string()
119    } else {
120        format!("{area}_{leaf}")
121    };
122    if provider_id.is_empty() {
123        llm_name
124    } else {
125        format!("{provider_id}.{llm_name}")
126    }
127}
128
129/// Compact one-line label for a `do` node: `provider.leaf(short args)`.
130/// Collapses whitespace/newlines (run_command args are whole shell scripts)
131/// and elides past ~48 chars so the tree stays readable in both the log and
132/// the panel.
133fn compact_call_label(provider_id: &str, contract_id: &str, args_json: &str) -> String {
134    let name = cap_short_name(provider_id, contract_id);
135    let flat = args_json.split_whitespace().collect::<Vec<_>>().join(" ");
136    const MAX: usize = 48;
137    let total = flat.chars().count();
138    let shown = if total > MAX {
139        let head: String = flat.chars().take(MAX).collect();
140        format!("{head}… (+{} chars)", total - MAX)
141    } else {
142        flat
143    };
144    format!("{name}({shown})")
145}
146
147/// Glyph + style for one node given its executor state (None = pending).
148fn node_state_glyph(state: Option<u32>) -> (&'static str, Style) {
149    match state {
150        Some(1) => (
151            "▸",
152            Style::default()
153                .fg(Color::Yellow)
154                .add_modifier(Modifier::BOLD),
155        ),
156        Some(2) => ("✓", Style::default().fg(Color::Green)),
157        Some(3) => ("✗", Style::default().fg(Color::Red)),
158        Some(4) => ("⊘", Style::default().fg(Color::Magenta)),
159        Some(5) => ("⏱", Style::default().fg(Color::Red)),
160        Some(6) => ("⏸", Style::default().fg(Color::Blue)),
161        _ => ("·", Style::default().fg(Color::DarkGray)),
162    }
163}
164
165/// Render the whole forest panel (goal + status + every tree with per-node
166/// live state) as styled lines.
167fn forest_panel_lines(forest: &ForestView) -> Vec<Line<'static>> {
168    let header = |s: &str| {
169        Line::from(Span::styled(
170            s.to_string(),
171            Style::default()
172                .fg(Color::Cyan)
173                .add_modifier(Modifier::BOLD),
174        ))
175    };
176    let status_style = |status: &str| match status {
177        "done" => Style::default().fg(Color::Green),
178        "failed" => Style::default().fg(Color::Red),
179        "in_progress" => Style::default().fg(Color::Yellow),
180        _ => Style::default().fg(Color::DarkGray),
181    };
182    let dim = Style::default().fg(Color::DarkGray);
183    let mut lines: Vec<Line<'static>> = Vec::new();
184    if forest.tasks.is_empty() {
185        lines.push(header("Goal"));
186        lines.push(Line::from(if forest.goal.is_empty() {
187            "(none yet)".to_string()
188        } else {
189            forest.goal.clone()
190        }));
191        if !forest.success_criterion.is_empty() {
192            lines.push(Line::from(Span::styled(
193                format!("done when: {}", forest.success_criterion),
194                dim,
195            )));
196        }
197        let status = if forest.status.is_empty() {
198            "—"
199        } else {
200            forest.status.as_str()
201        };
202        lines.push(Line::from(vec![
203            Span::raw("status: "),
204            Span::styled(status.to_string(), status_style(status)),
205        ]));
206    } else {
207        // Each task with its own trees under it, so which tree serves which
208        // task reads straight off the panel.
209        lines.push(header("Tasks"));
210        for task in &forest.tasks {
211            lines.push(Line::from(vec![
212                Span::styled(
213                    format!("{} ", task.task_id),
214                    Style::default().add_modifier(Modifier::BOLD),
215                ),
216                Span::styled(format!("[{}] ", task.status), status_style(&task.status)),
217                Span::raw(if task.goal.is_empty() {
218                    "(goal not stated yet)".to_string()
219                } else {
220                    task.goal.clone()
221                }),
222            ]));
223            if task.status == "in_progress" && !task.success_criterion.is_empty() {
224                lines.push(Line::from(Span::styled(
225                    format!("   done when: {}", task.success_criterion),
226                    dim,
227                )));
228            }
229            if !task.status_reason.is_empty() {
230                lines.push(Line::from(Span::styled(
231                    format!("   {}", task.status_reason),
232                    dim,
233                )));
234            }
235            for plan_id in &task.plan_ids {
236                match forest.plans.iter().find(|pv| &pv.plan_id == plan_id) {
237                    Some(pv) => tree_lines(pv, "   ", &mut lines),
238                    None => lines.push(Line::from(Span::styled(format!("   plan {plan_id}"), dim))),
239                }
240            }
241        }
242        let unfiled: Vec<&PlanView> = forest
243            .plans
244            .iter()
245            .filter(|pv| {
246                !forest
247                    .tasks
248                    .iter()
249                    .any(|t| t.plan_ids.contains(&pv.plan_id))
250            })
251            .collect();
252        if !unfiled.is_empty() {
253            lines.push(Line::from(""));
254            lines.push(header("Unfiled trees"));
255            for pv in unfiled {
256                tree_lines(pv, "", &mut lines);
257            }
258        }
259        return lines;
260    }
261    lines.push(Line::from(""));
262    lines.push(header("Forest"));
263    if forest.plans.is_empty() {
264        lines.push(Line::from(Span::styled(
265            "(no trees yet)".to_string(),
266            Style::default().fg(Color::DarkGray),
267        )));
268    }
269    for pv in &forest.plans {
270        tree_lines(pv, "", &mut lines);
271    }
272    lines
273}
274
275/// One tree: a header with its state, then its nodes, all indented by `indent`.
276fn tree_lines(pv: &PlanView, indent: &str, out: &mut Vec<Line<'static>>) {
277    let (marker, state, style) = match (pv.done, pv.any_failed) {
278        (true, true) => ("✗", "failed", Style::default().fg(Color::Red)),
279        (true, false) => ("✓", "succeeded", Style::default().fg(Color::Green)),
280        _ => (
281            "▸",
282            "running",
283            Style::default()
284                .fg(Color::Yellow)
285                .add_modifier(Modifier::BOLD),
286        ),
287    };
288    out.push(Line::from(vec![
289        Span::raw(indent.to_string()),
290        Span::styled(format!("{marker} plan {} · {state}", pv.plan_id), style),
291    ]));
292    let mut nodes = Vec::new();
293    forest_node_lines(pv, pv.plan.root_index as usize, "", true, true, &mut nodes);
294    for line in nodes {
295        let mut spans = vec![Span::raw(format!("{indent}  "))];
296        spans.extend(line.spans);
297        out.push(Line::from(spans));
298    }
299}
300
301fn forest_node_lines(
302    pv: &PlanView,
303    idx: usize,
304    prefix: &str,
305    is_root: bool,
306    is_last: bool,
307    out: &mut Vec<Line<'static>>,
308) {
309    if idx >= pv.plan.nodes.len() {
310        return;
311    }
312    let node = &pv.plan.nodes[idx];
313    let (glyph, style) = node_state_glyph(pv.node_states.get(&(idx as u32)).copied());
314    // Panel is a simple schematic: capability name only (no args), and bare
315    // operator labels. The full args live in the left-hand log tree.
316    let label = match node.node_kind {
317        0 => "sequence".to_string(),
318        1 => "parallel".to_string(),
319        _ => match node.call.as_ref() {
320            Some(c) => cap_short_name(&c.provider_id, &c.contract_id),
321            None => node.description.clone(),
322        },
323    };
324    let branch = if is_root {
325        String::new()
326    } else if is_last {
327        format!("{prefix}└─ ")
328    } else {
329        format!("{prefix}├─ ")
330    };
331    out.push(Line::from(vec![
332        Span::raw(branch),
333        Span::styled(format!("{glyph} "), style),
334        Span::styled(label, style),
335    ]));
336    let n = node.children.len();
337    for (i, child) in node.children.iter().enumerate() {
338        let child_prefix = if is_root {
339            String::new()
340        } else if is_last {
341            format!("{prefix}   ")
342        } else {
343            format!("{prefix}│  ")
344        };
345        forest_node_lines(pv, *child as usize, &child_prefix, false, i + 1 == n, out);
346    }
347}
348
349const DEFAULT_LIAISON_FALLBACK: &str = "http://127.0.0.1:50081";
350
351/// Persisted user choices for `rbnx chat`, written to ~/.robonix/chat.yaml.
352///
353/// Two layers per audio side:
354///   *_cap_id      → which audio impl provider in atlas (e.g. .alsa vs .macos)
355///   *_device_id   → which OS-level device that impl should drive (impl-
356///                   specific id from ListAudioDevices; "" = OS default)
357///
358/// Hot-swap-able: Ctrl+A in chat re-runs the picker. Initial run reads
359/// this file; missing fields trigger a picker prompt.
360#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
361struct ChatConfig {
362    #[serde(default, skip_serializing_if = "Option::is_none")]
363    mic_cap_id: Option<String>,
364    #[serde(default, skip_serializing_if = "Option::is_none")]
365    mic_device_id: Option<String>,
366    #[serde(default, skip_serializing_if = "Option::is_none")]
367    speaker_cap_id: Option<String>,
368    #[serde(default, skip_serializing_if = "Option::is_none")]
369    speaker_device_id: Option<String>,
370}
371
372fn chat_config_path() -> Option<std::path::PathBuf> {
373    dirs::home_dir().map(|h| h.join(".robonix").join("chat.yaml"))
374}
375
376fn load_chat_config() -> ChatConfig {
377    let Some(p) = chat_config_path() else {
378        return ChatConfig::default();
379    };
380    let Ok(text) = std::fs::read_to_string(&p) else {
381        return ChatConfig::default();
382    };
383    serde_yaml::from_str(&text).unwrap_or_default()
384}
385
386fn save_chat_config(cfg: &ChatConfig) -> Result<()> {
387    let p = chat_config_path().context("no home dir")?;
388    if let Some(parent) = p.parent() {
389        std::fs::create_dir_all(parent)?;
390    }
391    std::fs::write(&p, serde_yaml::to_string(cfg)?)?;
392    Ok(())
393}
394
395pub async fn execute(server: &str) -> Result<()> {
396    let atlas_endpoint = if server.starts_with("http") {
397        server.to_string()
398    } else {
399        format!("http://{server}")
400    };
401
402    let liaison_endpoint = if let Ok(ep) = std::env::var("ROBONIX_LIAISON_ENDPOINT") {
403        info!("using ROBONIX_LIAISON_ENDPOINT={ep}");
404        if ep.starts_with("http") {
405            ep
406        } else {
407            format!("http://{ep}")
408        }
409    } else {
410        discover_liaison(&atlas_endpoint).await.unwrap_or_else(|e| {
411            warn!(
412                "liaison discovery timed out ({e:#}), falling back to {DEFAULT_LIAISON_FALLBACK}"
413            );
414            DEFAULT_LIAISON_FALLBACK.to_string()
415        })
416    };
417    let liaison_endpoint = localhost_to_ipv4_loopback(&liaison_endpoint);
418
419    let mut stdout = io::stdout();
420    stdout.execute(EnterAlternateScreen)?;
421    terminal::enable_raw_mode()?;
422
423    let backend = CrosstermBackend::new(stdout);
424    let mut terminal = Terminal::new(backend)?;
425
426    // ensure_audio_devices is best-effort: if atlas is unreachable, no
427    // audio providers are registered, or the user skips with Esc, we
428    // surface the reason as a warning in the chat history and continue
429    // — text chat works without any audio path. Hard errors here would
430    // mean a single-user typo at audio-pick time kills the whole TUI.
431    let (chat_cfg, audio_warnings) =
432        match ensure_audio_devices(&atlas_endpoint, &mut terminal).await {
433            Ok(v) => v,
434            Err(e) => {
435                terminal::disable_raw_mode()?;
436                terminal.backend_mut().execute(LeaveAlternateScreen)?;
437                return Err(e);
438            }
439        };
440
441    let result = run_tui(
442        &mut terminal,
443        &atlas_endpoint,
444        &liaison_endpoint,
445        chat_cfg,
446        &audio_warnings,
447    )
448    .await;
449
450    terminal::disable_raw_mode()?;
451    terminal.backend_mut().execute(LeaveAlternateScreen)?;
452
453    result
454}
455
456/// Try to discover Liaison via Atlas, retrying for up to `timeout_secs`.
457async fn discover_liaison(atlas_endpoint: &str) -> Result<String> {
458    const RETRY_INTERVAL_MS: u64 = 2_000;
459    const TIMEOUT_SECS: u64 = 60;
460
461    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(TIMEOUT_SECS);
462    let mut attempt = 0u32;
463
464    loop {
465        attempt += 1;
466        match try_discover_once(atlas_endpoint, LIAISON_CONTRACT_ID).await {
467            Ok(ep) => return Ok(ep),
468            Err(e) => {
469                if std::time::Instant::now() >= deadline {
470                    anyhow::bail!("liaison not found in Atlas after {TIMEOUT_SECS}s: {e:#}");
471                }
472                if attempt == 1 {
473                    eprintln!("[chat] waiting for Liaison to register in Atlas ({e:#})…");
474                }
475                tokio::time::sleep(std::time::Duration::from_millis(RETRY_INTERVAL_MS)).await;
476            }
477        }
478    }
479}
480
481async fn try_discover_once(atlas_endpoint: &str, contract_id: &str) -> Result<String> {
482    let mut atlas = AtlasClient::connect(atlas_endpoint).await?;
483    let transport = atlas_pb::Transport::Grpc;
484    let providers = atlas.query_capabilities("", contract_id, transport).await?;
485    for provider in &providers {
486        let has = provider
487            .capabilities
488            .iter()
489            .any(|i| i.contract_id == contract_id && i.transport == transport as i32);
490        if !has {
491            continue;
492        }
493        let (_, endpoint, _) = atlas
494            .connect_capability(CONSUMER_ID, &provider.id, contract_id, transport)
495            .await?;
496        if endpoint.is_empty() {
497            continue;
498        }
499        let uri = if endpoint.starts_with("http") {
500            endpoint
501        } else {
502            format!("http://{endpoint}")
503        };
504        return Ok(localhost_to_ipv4_loopback(&uri));
505    }
506    anyhow::bail!("no {contract_id} capability found in Atlas registry")
507}
508
509// ── Audio-device first-run picker ───────────────────────────────────────────
510//
511// Resolution order for mic/speaker capability_ids when starting a voice
512// session is: ROBONIX_CHAT_*_NODE env (highest, overrides everything) →
513// chat.yaml on disk → first-run TUI picker. The picker only fires when
514// neither env nor config supplies the provider_id; once chosen it's saved
515// to ~/.robonix/chat.yaml so future sessions don't ask again. To
516// re-pick: delete that file (or just edit it), re-run rbnx chat.
517//
518// Why this lives here and not in liaison: the user choice is per-client
519// preference (which physical box's audio do I want when sitting at this
520// terminal), not a per-deployment server setting.
521
522/// Pick mode for the legacy modal picker chain (FirstRun only — the
523/// Ctrl+A path now uses the dashboard via `run_audio_settings_page`).
524/// `Reconfigure` is kept so the older code paths that still take a
525/// PickMode parameter compile cleanly even though nothing constructs it.
526#[derive(Clone, Copy)]
527#[allow(dead_code)]
528enum PickMode {
529    FirstRun,
530    Reconfigure,
531}
532
533/// Best-effort audio device discovery. Anything that goes wrong here
534/// (atlas unreachable, no providers registered, user pressed Esc) is
535/// downgraded to a chat-history warning — text mode keeps working.
536async fn ensure_audio_devices(
537    atlas_endpoint: &str,
538    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
539) -> Result<(ChatConfig, Vec<String>)> {
540    pick_audio_settings(atlas_endpoint, terminal, PickMode::FirstRun).await
541}
542
543async fn pick_audio_settings(
544    atlas_endpoint: &str,
545    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
546    mode: PickMode,
547) -> Result<(ChatConfig, Vec<String>)> {
548    let mut cfg = load_chat_config();
549    let mut warnings: Vec<String> = Vec::new();
550
551    let env_set = |key: &str| std::env::var(key).ok().filter(|s| !s.is_empty()).is_some();
552    let always = matches!(mode, PickMode::Reconfigure);
553    let mut need_mic = always || (!env_set("ROBONIX_CHAT_MIC_NODE") && cfg.mic_cap_id.is_none());
554    let mut need_speaker =
555        always || (!env_set("ROBONIX_CHAT_SPEAKER_NODE") && cfg.speaker_cap_id.is_none());
556
557    let mut atlas = match AtlasClient::connect(atlas_endpoint).await {
558        Ok(c) => c,
559        Err(e) => {
560            warnings.push(format!(
561                "audio device pick skipped — atlas unreachable at {atlas_endpoint}: {e:#}. \
562                 Text mode still works; voice (F2) will fail until atlas is up."
563            ));
564            return Ok((cfg, warnings));
565        }
566    };
567
568    // Validate stored pins against current atlas state. A pin pointing at a
569    // provider that's not in this deploy (e.g. config saved from an earlier
570    // deploy where the audio provider was named differently) would silently break
571    // voice — re-prompt instead.
572    if !need_mic
573        && let Some(pin) = cfg.mic_cap_id.as_deref()
574        && !pin_exists_in_atlas(&mut atlas, pin, MIC_CONTRACT).await
575    {
576        warnings.push(format!(
577            "mic pin '{pin}' not in atlas (stale config) — re-prompting"
578        ));
579        cfg.mic_cap_id = None;
580        cfg.mic_device_id = None;
581        need_mic = true;
582    }
583    if !need_speaker
584        && let Some(pin) = cfg.speaker_cap_id.as_deref()
585        && !pin_exists_in_atlas(&mut atlas, pin, SPEAKER_CONTRACT).await
586    {
587        warnings.push(format!(
588            "speaker pin '{pin}' not in atlas (stale config) — re-prompting"
589        ));
590        cfg.speaker_cap_id = None;
591        cfg.speaker_device_id = None;
592        need_speaker = true;
593    }
594    if !need_mic && !need_speaker {
595        return Ok((cfg, warnings));
596    }
597
598    if need_mic {
599        let saved_cap = cfg.mic_cap_id.clone();
600        let saved_dev = cfg.mic_device_id.clone();
601        match try_pick(
602            &mut atlas,
603            terminal,
604            "mic",
605            MIC_CONTRACT,
606            "input",
607            saved_cap.as_deref(),
608            saved_dev.as_deref(),
609            mode,
610        )
611        .await
612        {
613            Ok(Some((provider_id, device_id))) => {
614                cfg.mic_cap_id = Some(provider_id);
615                cfg.mic_device_id = Some(device_id);
616            }
617            Ok(None) => warnings.push(
618                "no mic provider in atlas — voice input disabled (text mode unaffected)".into(),
619            ),
620            Err(e) => warnings.push(format!("mic pick: {e:#}")),
621        }
622    }
623    if need_speaker {
624        let saved_cap = cfg.speaker_cap_id.clone();
625        let saved_dev = cfg.speaker_device_id.clone();
626        match try_pick(
627            &mut atlas,
628            terminal,
629            "speaker",
630            SPEAKER_CONTRACT,
631            "output",
632            saved_cap.as_deref(),
633            saved_dev.as_deref(),
634            mode,
635        )
636        .await
637        {
638            Ok(Some((provider_id, device_id))) => {
639                cfg.speaker_cap_id = Some(provider_id);
640                cfg.speaker_device_id = Some(device_id);
641            }
642            Ok(None) => warnings.push(
643                "no speaker provider in atlas — voice playback disabled (text mode unaffected)"
644                    .into(),
645            ),
646            Err(e) => warnings.push(format!("speaker pick: {e:#}")),
647        }
648    }
649    if let Err(e) = save_chat_config(&cfg) {
650        warn!("could not save chat config: {e:#}");
651    }
652    Ok((cfg, warnings))
653}
654
655/// True iff atlas currently has a provider whose id (or namespace) matches the
656/// pin AND it provides `contract` over GRPC. Used at chat startup to detect
657/// stale pins from a prior deploy whose audio provider has since been renamed
658/// or removed — caller drops the pin and re-prompts the picker instead of
659/// silently letting voice fail with "no provider".
660async fn pin_exists_in_atlas(atlas: &mut AtlasClient, pin: &str, contract: &str) -> bool {
661    let Ok(providers) = atlas
662        .query_capabilities("", contract, atlas_pb::Transport::Grpc)
663        .await
664    else {
665        // Atlas unreachable — don't drop the pin on a transient failure;
666        // the outer caller already warned and degraded.
667        return true;
668    };
669    providers.iter().any(|r| r.id == pin || r.namespace == pin)
670}
671
672/// `Ok(Some((provider_id, device_id)))` = picked both layers; device_id may be ""
673/// when the impl returned UNIMPLEMENTED on list_devices.
674/// `Ok(None)` = no providers in atlas.
675#[allow(clippy::too_many_arguments)]
676async fn try_pick(
677    atlas: &mut AtlasClient,
678    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
679    label: &str,
680    contract: &str,
681    kind: &str,
682    saved_cap_id: Option<&str>,
683    saved_device_id: Option<&str>,
684    mode: PickMode,
685) -> Result<Option<(String, String)>> {
686    let providers = atlas
687        .query_capabilities("", contract, atlas_pb::Transport::Grpc)
688        .await?;
689    if providers.is_empty() {
690        return Ok(None);
691    }
692
693    // Layer A — provider (provider_id). FirstRun honours the saved choice
694    // when it's still in atlas, or auto-picks the lone provider with a
695    // 400 ms flash. Reconfigure (Ctrl+A) ALWAYS shows the TUI even
696    // for a single entry — auto-pick on Ctrl+A looks identical to
697    // "Ctrl+A did nothing", which is what the user just hit.
698    let provider_id = match (mode, saved_cap_id) {
699        (PickMode::FirstRun, Some(s)) if providers.iter().any(|p| p.id == s) => s.to_string(),
700        (PickMode::FirstRun, _) if providers.len() == 1 => {
701            let id = providers[0].id.clone();
702            flash_picker_message(terminal, &format!("auto-selected {label}: {id}"))?;
703            id
704        }
705        _ => match pick_tui(terminal, label, contract, &providers)? {
706            Some(s) => s,
707            None => return Ok(None),
708        },
709    };
710
711    // Layer B — device id within the chosen impl. Connect to its
712    // list_devices contract (UNIMPLEMENTED is OK — fall through with "").
713    let device_id = pick_device_for_cap(
714        atlas,
715        terminal,
716        &provider_id,
717        label,
718        kind,
719        saved_device_id,
720        mode,
721    )
722    .await?;
723
724    // Tell the impl which device to use. Best-effort; ignore failures.
725    if !device_id.is_empty()
726        && let Err(e) = call_select_device(atlas, &provider_id, kind, &device_id).await
727    {
728        warn!("SelectAudioDevice on {provider_id} ({kind}={device_id}) failed: {e:#}");
729    }
730
731    Ok(Some((provider_id, device_id)))
732}
733
734/// Connect to `provider_id`'s list_devices capability, ask for the device
735/// list, run a picker on the entries that match `kind` (input/output)
736/// + duplex. Returns "" when the impl doesn't expose the contract.
737async fn pick_device_for_cap(
738    atlas: &mut AtlasClient,
739    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
740    provider_id: &str,
741    label: &str,
742    kind: &str,
743    saved_device_id: Option<&str>,
744    mode: PickMode,
745) -> Result<String> {
746    use crate::pb::contracts::robonix_primitive_audio_list_devices_client::RobonixPrimitiveAudioListDevicesClient;
747
748    const LIST_CONTRACT: &str = "robonix/primitive/audio/list_devices";
749    // Reconfigure mode shows visible feedback for every silent path
750    // below; FirstRun stays quiet so a missing list_devices contract
751    // doesn't litter chat history with a non-actionable message.
752    let reconf = matches!(mode, PickMode::Reconfigure);
753
754    let endpoint = match atlas
755        .connect_capability(
756            CONSUMER_ID,
757            provider_id,
758            LIST_CONTRACT,
759            atlas_pb::Transport::Grpc,
760        )
761        .await
762    {
763        Ok((_, ep, _)) => {
764            if ep.starts_with("http") {
765                ep
766            } else {
767                format!("http://{ep}")
768            }
769        }
770        Err(_) => {
771            if reconf {
772                flash_picker_message(
773                    terminal,
774                    &format!(
775                        "{provider_id} doesn't expose list_devices — \
776                         using OS default device. Rebuild the package \
777                         (bash scripts/build.sh) to pick up the new contract."
778                    ),
779                )?;
780            }
781            return Ok(String::new());
782        }
783    };
784
785    let mut client = match RobonixPrimitiveAudioListDevicesClient::connect(endpoint.clone()).await {
786        Ok(c) => c,
787        Err(e) => {
788            if reconf {
789                flash_picker_message(
790                    terminal,
791                    &format!("connect list_devices on {provider_id}: {e}"),
792                )?;
793            }
794            return Ok(String::new());
795        }
796    };
797    let resp = match client
798        .list_audio_devices(crate::pb::audio::ListAudioDevicesRequest {})
799        .await
800    {
801        Ok(r) => r.into_inner(),
802        Err(e) => {
803            if reconf {
804                flash_picker_message(terminal, &format!("ListAudioDevices on {provider_id}: {e}"))?;
805            }
806            return Ok(String::new());
807        }
808    };
809
810    let usable: Vec<crate::pb::audio::AudioDevice> = resp
811        .devices
812        .into_iter()
813        .filter(|d| d.kind == kind || d.kind == "duplex")
814        .collect();
815    if usable.is_empty() {
816        if reconf {
817            flash_picker_message(
818                terminal,
819                &format!("{provider_id} reports no {kind} devices — using OS default"),
820            )?;
821        }
822        return Ok(String::new());
823    }
824
825    // FirstRun: honour saved device when still listed; auto-pick a lone
826    // device with a flash. Reconfigure: always show the TUI so Ctrl+A
827    // gives the user a real page they can interact with.
828    if matches!(mode, PickMode::FirstRun) {
829        if let Some(saved) = saved_device_id
830            && usable.iter().any(|d| d.id == saved)
831        {
832            return Ok(saved.to_string());
833        }
834        if usable.len() == 1 {
835            let id = usable[0].id.clone();
836            flash_picker_message(
837                terminal,
838                &format!("auto-selected {label} device: {}", usable[0].name),
839            )?;
840            return Ok(id);
841        }
842    }
843
844    let chosen = pick_device_tui(terminal, label, &usable)?;
845    // pick_device_tui returns "" on Esc/q — preserve any previously-saved
846    // device id so a Reconfigure-then-skip doesn't accidentally clear it.
847    if chosen.is_empty()
848        && let Some(saved) = saved_device_id
849    {
850        return Ok(saved.to_string());
851    }
852    Ok(chosen)
853}
854
855async fn call_select_device(
856    atlas: &mut AtlasClient,
857    provider_id: &str,
858    kind: &str,
859    device_id: &str,
860) -> Result<()> {
861    use crate::pb::contracts::robonix_primitive_audio_select_device_client::RobonixPrimitiveAudioSelectDeviceClient;
862    const SELECT_CONTRACT: &str = "robonix/primitive/audio/select_device";
863
864    let (_, ep, _) = atlas
865        .connect_capability(
866            CONSUMER_ID,
867            provider_id,
868            SELECT_CONTRACT,
869            atlas_pb::Transport::Grpc,
870        )
871        .await?;
872    let endpoint = if ep.starts_with("http") {
873        ep
874    } else {
875        format!("http://{ep}")
876    };
877    let mut client = RobonixPrimitiveAudioSelectDeviceClient::connect(endpoint).await?;
878    let resp = client
879        .select_audio_device(crate::pb::audio::SelectAudioDeviceRequest {
880            kind: kind.to_string(),
881            id: device_id.to_string(),
882        })
883        .await?
884        .into_inner();
885    if !resp.ok {
886        anyhow::bail!("impl rejected: {}", resp.error);
887    }
888    Ok(())
889}
890
891fn pick_device_tui(
892    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
893    label: &str,
894    devices: &[crate::pb::audio::AudioDevice],
895) -> Result<String> {
896    let mut idx = 0usize;
897    loop {
898        terminal.draw(|f| {
899            let area = f.area();
900            let lines: Vec<Line> = devices
901                .iter()
902                .enumerate()
903                .map(|(i, d)| {
904                    let mark = if i == idx { "▶ " } else { "  " };
905                    let style = if i == idx {
906                        Style::default()
907                            .fg(Color::Black)
908                            .bg(Color::Cyan)
909                            .add_modifier(Modifier::BOLD)
910                    } else {
911                        Style::default()
912                    };
913                    let mut tags = Vec::new();
914                    if d.is_default {
915                        tags.push("default".to_string());
916                    }
917                    if !d.note.is_empty() {
918                        tags.push(format!("⚠ {}", d.note));
919                    }
920                    let suffix = if tags.is_empty() {
921                        String::new()
922                    } else {
923                        format!("  ({})", tags.join(", "))
924                    };
925                    Line::from(vec![Span::styled(
926                        format!("{mark}#{} {}{}", d.id, d.name, suffix),
927                        style,
928                    )])
929                })
930                .collect();
931            let body = Paragraph::new(lines)
932                .block(Block::default().borders(Borders::ALL).title(format!(
933                    " choose {label} device — ↑↓ select · Enter confirm · Esc skip "
934                )))
935                .wrap(Wrap { trim: false });
936            f.render_widget(body, area);
937        })?;
938        if event::poll(std::time::Duration::from_millis(200))?
939            && let Event::Key(key) = event::read()?
940        {
941            match key.code {
942                KeyCode::Up | KeyCode::Char('k') => idx = idx.saturating_sub(1),
943                KeyCode::Down | KeyCode::Char('j') if idx + 1 < devices.len() => idx += 1,
944                KeyCode::Enter => return Ok(devices[idx].id.clone()),
945                KeyCode::Char('q') | KeyCode::Esc => return Ok(String::new()),
946                _ => {}
947            }
948        }
949    }
950}
951
952fn pick_tui(
953    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
954    label: &str,
955    contract: &str,
956    providers: &[atlas_pb::CapabilityProvider],
957) -> Result<Option<String>> {
958    let mut idx = 0usize;
959    loop {
960        terminal.draw(|f| {
961            let area = f.area();
962            let lines: Vec<Line> = providers
963                .iter()
964                .enumerate()
965                .map(|(i, r)| {
966                    let mark = if i == idx { "▶ " } else { "  " };
967                    let style = if i == idx {
968                        Style::default()
969                            .fg(Color::Black)
970                            .bg(Color::Cyan)
971                            .add_modifier(Modifier::BOLD)
972                    } else {
973                        Style::default()
974                    };
975                    let detail = if r.state_detail.is_empty() {
976                        String::new()
977                    } else {
978                        format!("  ({})", r.state_detail)
979                    };
980                    Line::from(vec![Span::styled(format!("{mark}{}{detail}", r.id), style)])
981                })
982                .collect();
983            let body = Paragraph::new(lines)
984                .block(Block::default().borders(Borders::ALL).title(format!(
985                    " choose {label} provider ({contract}) — ↑↓ select · Enter confirm · Esc skip "
986                )))
987                .wrap(Wrap { trim: false });
988            f.render_widget(body, area);
989        })?;
990        if event::poll(std::time::Duration::from_millis(200))?
991            && let Event::Key(key) = event::read()?
992        {
993            match key.code {
994                KeyCode::Up | KeyCode::Char('k') => idx = idx.saturating_sub(1),
995                KeyCode::Down | KeyCode::Char('j') if idx + 1 < providers.len() => {
996                    idx += 1;
997                }
998                KeyCode::Enter => return Ok(Some(providers[idx].id.clone())),
999                KeyCode::Char('q') | KeyCode::Esc => return Ok(None),
1000                _ => {}
1001            }
1002        }
1003    }
1004}
1005
1006// ── Audio settings dashboard (btop-style, single page) ─────────────────────
1007//
1008// Replacement for the old sequential modal pickers. One screen, four
1009// sections (mic provider / mic device / speaker provider / speaker
1010// device), Tab cycles section, ↑↓ moves cursor within section, Enter
1011// picks the highlighted item (and reloads device list when picking a
1012// new provider, or calls SelectAudioDevice when picking a device),
1013// Esc / Ctrl+A / q saves and closes.
1014
1015#[derive(Clone, Copy, PartialEq, Eq)]
1016enum AudioSection {
1017    MicProvider,
1018    MicDevice,
1019    SpeakerProvider,
1020    SpeakerDevice,
1021}
1022
1023struct AudioSettingsPage {
1024    mic_providers: Vec<atlas_pb::CapabilityProvider>,
1025    speaker_providers: Vec<atlas_pb::CapabilityProvider>,
1026    mic_devices: Vec<crate::pb::audio::AudioDevice>,
1027    speaker_devices: Vec<crate::pb::audio::AudioDevice>,
1028
1029    mic_cap_id: String,
1030    mic_device_id: String,
1031    speaker_cap_id: String,
1032    speaker_device_id: String,
1033
1034    section: AudioSection,
1035    cursor_mp: usize,
1036    cursor_md: usize,
1037    cursor_sp: usize,
1038    cursor_sd: usize,
1039
1040    status: String,
1041}
1042
1043async fn fetch_devices_filtered(
1044    atlas: &mut AtlasClient,
1045    provider_id: &str,
1046    kind: &str,
1047) -> Vec<crate::pb::audio::AudioDevice> {
1048    use crate::pb::contracts::robonix_primitive_audio_list_devices_client::RobonixPrimitiveAudioListDevicesClient;
1049    const LIST_CONTRACT: &str = "robonix/primitive/audio/list_devices";
1050    if provider_id.is_empty() {
1051        return Vec::new();
1052    }
1053    let endpoint = match atlas
1054        .connect_capability(
1055            CONSUMER_ID,
1056            provider_id,
1057            LIST_CONTRACT,
1058            atlas_pb::Transport::Grpc,
1059        )
1060        .await
1061    {
1062        Ok((_, ep, _)) if ep.starts_with("http") => ep,
1063        Ok((_, ep, _)) => format!("http://{ep}"),
1064        Err(_) => return Vec::new(),
1065    };
1066    let mut client = match RobonixPrimitiveAudioListDevicesClient::connect(endpoint).await {
1067        Ok(c) => c,
1068        Err(_) => return Vec::new(),
1069    };
1070    let resp = match client
1071        .list_audio_devices(crate::pb::audio::ListAudioDevicesRequest {})
1072        .await
1073    {
1074        Ok(r) => r.into_inner(),
1075        Err(_) => return Vec::new(),
1076    };
1077    resp.devices
1078        .into_iter()
1079        .filter(|d| d.kind == kind || d.kind == "duplex")
1080        .collect()
1081}
1082
1083impl AudioSettingsPage {
1084    async fn load(atlas: &mut AtlasClient, cfg: &ChatConfig) -> Self {
1085        let mic_providers = atlas
1086            .query_capabilities("", MIC_CONTRACT, atlas_pb::Transport::Grpc)
1087            .await
1088            .unwrap_or_default();
1089        let speaker_providers = atlas
1090            .query_capabilities("", SPEAKER_CONTRACT, atlas_pb::Transport::Grpc)
1091            .await
1092            .unwrap_or_default();
1093
1094        let mic_cap_id = cfg.mic_cap_id.clone().unwrap_or_else(|| {
1095            mic_providers
1096                .first()
1097                .map(|p| p.id.clone())
1098                .unwrap_or_default()
1099        });
1100        let speaker_cap_id = cfg.speaker_cap_id.clone().unwrap_or_else(|| {
1101            speaker_providers
1102                .first()
1103                .map(|p| p.id.clone())
1104                .unwrap_or_default()
1105        });
1106
1107        let mic_devices = fetch_devices_filtered(atlas, &mic_cap_id, "input").await;
1108        let speaker_devices = fetch_devices_filtered(atlas, &speaker_cap_id, "output").await;
1109
1110        let mic_device_id = cfg.mic_device_id.clone().unwrap_or_default();
1111        let speaker_device_id = cfg.speaker_device_id.clone().unwrap_or_default();
1112
1113        // Position cursors at the currently-selected entry so the user
1114        // sees what's active rather than always landing at row 0.
1115        let cursor_mp = mic_providers
1116            .iter()
1117            .position(|p| p.id == mic_cap_id)
1118            .unwrap_or(0);
1119        let cursor_sp = speaker_providers
1120            .iter()
1121            .position(|p| p.id == speaker_cap_id)
1122            .unwrap_or(0);
1123        let cursor_md = mic_devices
1124            .iter()
1125            .position(|d| d.id == mic_device_id)
1126            .unwrap_or(0);
1127        let cursor_sd = speaker_devices
1128            .iter()
1129            .position(|d| d.id == speaker_device_id)
1130            .unwrap_or(0);
1131
1132        let mut status = String::new();
1133        if mic_providers.is_empty() && speaker_providers.is_empty() {
1134            status.push_str("no audio providers in atlas — boot the audio package first");
1135        }
1136
1137        Self {
1138            mic_providers,
1139            speaker_providers,
1140            mic_devices,
1141            speaker_devices,
1142            mic_cap_id,
1143            mic_device_id,
1144            speaker_cap_id,
1145            speaker_device_id,
1146            section: AudioSection::MicProvider,
1147            cursor_mp,
1148            cursor_md,
1149            cursor_sp,
1150            cursor_sd,
1151            status,
1152        }
1153    }
1154
1155    fn current_len(&self) -> usize {
1156        match self.section {
1157            AudioSection::MicProvider => self.mic_providers.len(),
1158            AudioSection::MicDevice => self.mic_devices.len(),
1159            AudioSection::SpeakerProvider => self.speaker_providers.len(),
1160            AudioSection::SpeakerDevice => self.speaker_devices.len(),
1161        }
1162    }
1163    fn current_cursor(&self) -> usize {
1164        match self.section {
1165            AudioSection::MicProvider => self.cursor_mp,
1166            AudioSection::MicDevice => self.cursor_md,
1167            AudioSection::SpeakerProvider => self.cursor_sp,
1168            AudioSection::SpeakerDevice => self.cursor_sd,
1169        }
1170    }
1171    fn current_cursor_mut(&mut self) -> &mut usize {
1172        match self.section {
1173            AudioSection::MicProvider => &mut self.cursor_mp,
1174            AudioSection::MicDevice => &mut self.cursor_md,
1175            AudioSection::SpeakerProvider => &mut self.cursor_sp,
1176            AudioSection::SpeakerDevice => &mut self.cursor_sd,
1177        }
1178    }
1179    fn cursor_up(&mut self) {
1180        let c = self.current_cursor_mut();
1181        if *c > 0 {
1182            *c -= 1;
1183        }
1184    }
1185    fn cursor_down(&mut self) {
1186        let n = self.current_len();
1187        let c = self.current_cursor_mut();
1188        if *c + 1 < n {
1189            *c += 1;
1190        }
1191    }
1192    fn next_section(&mut self) {
1193        self.section = match self.section {
1194            AudioSection::MicProvider => AudioSection::MicDevice,
1195            AudioSection::MicDevice => AudioSection::SpeakerProvider,
1196            AudioSection::SpeakerProvider => AudioSection::SpeakerDevice,
1197            AudioSection::SpeakerDevice => AudioSection::MicProvider,
1198        };
1199    }
1200    fn prev_section(&mut self) {
1201        self.section = match self.section {
1202            AudioSection::MicProvider => AudioSection::SpeakerDevice,
1203            AudioSection::MicDevice => AudioSection::MicProvider,
1204            AudioSection::SpeakerProvider => AudioSection::MicDevice,
1205            AudioSection::SpeakerDevice => AudioSection::SpeakerProvider,
1206        };
1207    }
1208
1209    async fn enter(&mut self, atlas: &mut AtlasClient) {
1210        let i = self.current_cursor();
1211        match self.section {
1212            AudioSection::MicProvider => {
1213                if let Some(p) = self.mic_providers.get(i) {
1214                    let new_cap = p.id.clone();
1215                    if new_cap != self.mic_cap_id {
1216                        self.mic_cap_id = new_cap.clone();
1217                        self.mic_devices = fetch_devices_filtered(atlas, &new_cap, "input").await;
1218                        self.mic_device_id.clear();
1219                        self.cursor_md = 0;
1220                    }
1221                    self.status = format!("mic provider → {new_cap}");
1222                }
1223            }
1224            AudioSection::MicDevice => {
1225                if let Some(d) = self.mic_devices.get(i) {
1226                    let id = d.id.clone();
1227                    let name = d.name.clone();
1228                    self.mic_device_id = id.clone();
1229                    match call_select_device(atlas, &self.mic_cap_id, "input", &id).await {
1230                        Ok(()) => self.status = format!("mic device → {name} ({id})"),
1231                        Err(e) => self.status = format!("mic device → {id} (warn: {e:#})"),
1232                    }
1233                }
1234            }
1235            AudioSection::SpeakerProvider => {
1236                if let Some(p) = self.speaker_providers.get(i) {
1237                    let new_cap = p.id.clone();
1238                    if new_cap != self.speaker_cap_id {
1239                        self.speaker_cap_id = new_cap.clone();
1240                        self.speaker_devices =
1241                            fetch_devices_filtered(atlas, &new_cap, "output").await;
1242                        self.speaker_device_id.clear();
1243                        self.cursor_sd = 0;
1244                    }
1245                    self.status = format!("speaker provider → {new_cap}");
1246                }
1247            }
1248            AudioSection::SpeakerDevice => {
1249                if let Some(d) = self.speaker_devices.get(i) {
1250                    let id = d.id.clone();
1251                    let name = d.name.clone();
1252                    self.speaker_device_id = id.clone();
1253                    match call_select_device(atlas, &self.speaker_cap_id, "output", &id).await {
1254                        Ok(()) => self.status = format!("speaker device → {name} ({id})"),
1255                        Err(e) => self.status = format!("speaker device → {id} (warn: {e:#})"),
1256                    }
1257                }
1258            }
1259        }
1260    }
1261
1262    async fn refresh(&mut self, atlas: &mut AtlasClient) {
1263        *self = Self::load(
1264            atlas,
1265            &ChatConfig {
1266                mic_cap_id: (!self.mic_cap_id.is_empty()).then(|| self.mic_cap_id.clone()),
1267                mic_device_id: (!self.mic_device_id.is_empty()).then(|| self.mic_device_id.clone()),
1268                speaker_cap_id: (!self.speaker_cap_id.is_empty())
1269                    .then(|| self.speaker_cap_id.clone()),
1270                speaker_device_id: (!self.speaker_device_id.is_empty())
1271                    .then(|| self.speaker_device_id.clone()),
1272            },
1273        )
1274        .await;
1275        self.status = "refreshed".into();
1276    }
1277
1278    fn draw(&self, frame: &mut ratatui::Frame) {
1279        let mut lines: Vec<Line> = Vec::with_capacity(64);
1280        let dim = Style::default().fg(Color::DarkGray);
1281        let normal = Style::default();
1282        let selected_style = Style::default()
1283            .fg(Color::Green)
1284            .add_modifier(Modifier::BOLD);
1285        let cursor_style = Style::default()
1286            .fg(Color::Black)
1287            .bg(Color::Cyan)
1288            .add_modifier(Modifier::BOLD);
1289
1290        let render_provider_row = |i: usize,
1291                                   p: &atlas_pb::CapabilityProvider,
1292                                   sel: &str,
1293                                   in_section: bool,
1294                                   cursor: usize|
1295         -> Line {
1296            let is_cursor = in_section && i == cursor;
1297            let is_selected = p.id == sel;
1298            let mark_left = if is_cursor { "▶" } else { " " };
1299            let bullet = if is_selected { "●" } else { "○" };
1300            let prefix = format!(" {mark_left} {bullet} ");
1301            let style = if is_cursor {
1302                cursor_style
1303            } else if is_selected {
1304                selected_style
1305            } else {
1306                normal
1307            };
1308            Line::from(vec![Span::styled(format!("{prefix}{}", p.id), style)])
1309        };
1310
1311        let render_device_row = |i: usize,
1312                                 d: &crate::pb::audio::AudioDevice,
1313                                 sel: &str,
1314                                 in_section: bool,
1315                                 cursor: usize|
1316         -> Line {
1317            let is_cursor = in_section && i == cursor;
1318            let is_selected = d.id == sel;
1319            let mark_left = if is_cursor { "▶" } else { " " };
1320            let bullet = if is_selected { "●" } else { "○" };
1321            let mut tags: Vec<String> = Vec::new();
1322            if d.is_default {
1323                tags.push("default".into());
1324            }
1325            if !d.note.is_empty() {
1326                tags.push(format!("⚠ {}", d.note));
1327            }
1328            let suffix = if tags.is_empty() {
1329                String::new()
1330            } else {
1331                format!("   [{}]", tags.join(", "))
1332            };
1333            let body = format!(" {mark_left} {bullet} {:<10}  {}{}", d.id, d.name, suffix);
1334            let style = if is_cursor {
1335                cursor_style
1336            } else if is_selected {
1337                selected_style
1338            } else {
1339                normal
1340            };
1341            Line::from(vec![Span::styled(body, style)])
1342        };
1343
1344        let section_title = |title: &str, active: bool| -> Line {
1345            let bar = "━".repeat(8);
1346            let prefix = if active { "▼" } else { " " };
1347            let style = if active {
1348                Style::default()
1349                    .fg(Color::Cyan)
1350                    .add_modifier(Modifier::BOLD)
1351            } else {
1352                Style::default()
1353                    .fg(Color::Gray)
1354                    .add_modifier(Modifier::BOLD)
1355            };
1356            Line::from(vec![Span::styled(
1357                format!("{prefix} {bar} {title} {bar}"),
1358                style,
1359            )])
1360        };
1361
1362        // ─── MICROPHONE ───
1363        lines.push(Line::from(""));
1364        lines.push(Line::from(vec![Span::styled(
1365            "  MICROPHONE",
1366            Style::default()
1367                .fg(Color::Yellow)
1368                .add_modifier(Modifier::BOLD),
1369        )]));
1370        lines.push(section_title(
1371            "Cap (robonix handle)",
1372            self.section == AudioSection::MicProvider,
1373        ));
1374        if self.mic_providers.is_empty() {
1375            lines.push(Line::from(vec![Span::styled(
1376                "    (no providers — rbnx boot first)",
1377                dim,
1378            )]));
1379        } else {
1380            for (i, p) in self.mic_providers.iter().enumerate() {
1381                lines.push(render_provider_row(
1382                    i,
1383                    p,
1384                    &self.mic_cap_id,
1385                    self.section == AudioSection::MicProvider,
1386                    self.cursor_mp,
1387                ));
1388            }
1389        }
1390        lines.push(section_title(
1391            "Driver-internal device",
1392            self.section == AudioSection::MicDevice,
1393        ));
1394        if self.mic_devices.is_empty() {
1395            lines.push(Line::from(vec![Span::styled(
1396                "    (no devices — impl missing list_devices, or rebuild package)",
1397                dim,
1398            )]));
1399        } else {
1400            for (i, d) in self.mic_devices.iter().enumerate() {
1401                lines.push(render_device_row(
1402                    i,
1403                    d,
1404                    &self.mic_device_id,
1405                    self.section == AudioSection::MicDevice,
1406                    self.cursor_md,
1407                ));
1408            }
1409        }
1410
1411        // ─── SPEAKER ───
1412        lines.push(Line::from(""));
1413        lines.push(Line::from(vec![Span::styled(
1414            "  SPEAKER",
1415            Style::default()
1416                .fg(Color::Yellow)
1417                .add_modifier(Modifier::BOLD),
1418        )]));
1419        lines.push(section_title(
1420            "Cap (robonix handle)",
1421            self.section == AudioSection::SpeakerProvider,
1422        ));
1423        if self.speaker_providers.is_empty() {
1424            lines.push(Line::from(vec![Span::styled(
1425                "    (no providers — rbnx boot first)",
1426                dim,
1427            )]));
1428        } else {
1429            for (i, p) in self.speaker_providers.iter().enumerate() {
1430                lines.push(render_provider_row(
1431                    i,
1432                    p,
1433                    &self.speaker_cap_id,
1434                    self.section == AudioSection::SpeakerProvider,
1435                    self.cursor_sp,
1436                ));
1437            }
1438        }
1439        lines.push(section_title(
1440            "Driver-internal device",
1441            self.section == AudioSection::SpeakerDevice,
1442        ));
1443        if self.speaker_devices.is_empty() {
1444            lines.push(Line::from(vec![Span::styled(
1445                "    (no devices — impl missing list_devices, or rebuild package)",
1446                dim,
1447            )]));
1448        } else {
1449            for (i, d) in self.speaker_devices.iter().enumerate() {
1450                lines.push(render_device_row(
1451                    i,
1452                    d,
1453                    &self.speaker_device_id,
1454                    self.section == AudioSection::SpeakerDevice,
1455                    self.cursor_sd,
1456                ));
1457            }
1458        }
1459
1460        lines.push(Line::from(""));
1461
1462        let area = frame.area();
1463        let chunks = Layout::vertical([
1464            Constraint::Min(0),
1465            Constraint::Length(1),
1466            Constraint::Length(1),
1467        ])
1468        .split(area);
1469
1470        let body = Paragraph::new(lines)
1471            .block(Block::default().borders(Borders::ALL).title(
1472                " Audio Settings — Cap = robonix handle · Driver-internal device = optional, multi-device drivers only ",
1473            ))
1474            .wrap(Wrap { trim: false });
1475        frame.render_widget(body, chunks[0]);
1476
1477        let status_line = if self.status.is_empty() {
1478            String::from(" ")
1479        } else {
1480            format!(" {}", self.status)
1481        };
1482        let status = Paragraph::new(status_line).style(Style::default().fg(Color::Cyan));
1483        frame.render_widget(status, chunks[1]);
1484
1485        let help = Paragraph::new(
1486            " Tab/Shift+Tab: section · ↑↓ jk: item · Enter/Space: pick · r: refresh · Esc/Ctrl+A: close",
1487        )
1488        .style(dim);
1489        frame.render_widget(help, chunks[2]);
1490    }
1491}
1492
1493async fn run_audio_settings_page(
1494    atlas_endpoint: &str,
1495    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
1496    cfg: ChatConfig,
1497) -> Result<ChatConfig> {
1498    let mut atlas = AtlasClient::connect(atlas_endpoint)
1499        .await
1500        .with_context(|| format!("connect to atlas at '{atlas_endpoint}' for audio settings"))?;
1501    let mut page = AudioSettingsPage::load(&mut atlas, &cfg).await;
1502
1503    loop {
1504        terminal.draw(|f| page.draw(f))?;
1505        if event::poll(std::time::Duration::from_millis(150))?
1506            && let Event::Key(key) = event::read()?
1507        {
1508            match (key.modifiers, key.code) {
1509                (_, KeyCode::Tab) => page.next_section(),
1510                (_, KeyCode::BackTab) => page.prev_section(),
1511                (_, KeyCode::Up) | (_, KeyCode::Char('k')) => page.cursor_up(),
1512                (_, KeyCode::Down) | (_, KeyCode::Char('j')) => page.cursor_down(),
1513                (_, KeyCode::Enter) | (_, KeyCode::Char(' ')) => page.enter(&mut atlas).await,
1514                (_, KeyCode::Char('r')) => page.refresh(&mut atlas).await,
1515                (KeyModifiers::CONTROL, KeyCode::Char('a'))
1516                | (_, KeyCode::Esc)
1517                | (_, KeyCode::Char('q')) => break,
1518                _ => {}
1519            }
1520        }
1521    }
1522
1523    let new_cfg = ChatConfig {
1524        mic_cap_id: (!page.mic_cap_id.is_empty()).then_some(page.mic_cap_id),
1525        mic_device_id: (!page.mic_device_id.is_empty()).then_some(page.mic_device_id),
1526        speaker_cap_id: (!page.speaker_cap_id.is_empty()).then_some(page.speaker_cap_id),
1527        speaker_device_id: (!page.speaker_device_id.is_empty()).then_some(page.speaker_device_id),
1528    };
1529    if let Err(e) = save_chat_config(&new_cfg) {
1530        warn!("could not save chat config: {e:#}");
1531    }
1532    Ok(new_cfg)
1533}
1534
1535/// Render a single-line status page and pause briefly so the user can
1536/// read it before the next picker step (or the chat) takes over the
1537/// screen. Long messages now sit for 1.4 s — the previous 400 ms felt
1538/// like "the page just flashed and disappeared."
1539fn flash_picker_message(
1540    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
1541    msg: &str,
1542) -> Result<()> {
1543    terminal.draw(|f| {
1544        let body = Paragraph::new(msg)
1545            .block(
1546                Block::default()
1547                    .borders(Borders::ALL)
1548                    .title(" rbnx chat — audio "),
1549            )
1550            .wrap(Wrap { trim: false });
1551        f.render_widget(body, f.area());
1552    })?;
1553    std::thread::sleep(std::time::Duration::from_millis(1400));
1554    Ok(())
1555}
1556
1557async fn run_tui(
1558    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
1559    atlas_endpoint: &str,
1560    liaison_endpoint: &str,
1561    mut chat_cfg: ChatConfig,
1562    audio_warnings: &[String],
1563) -> Result<()> {
1564    let local_user = format!("local:{}", whoami_username());
1565    let mut initial: Vec<ChatMessage> = Vec::with_capacity(1 + audio_warnings.len());
1566    initial.push(ChatMessage {
1567        role: Role::Status,
1568        text: format!(
1569            "Connected to Liaison at {liaison_endpoint} as {local_user}. \
1570             Enter = send · F2 = voice (auto end on silence) · Ctrl+A = audio settings · Esc = abort turn · Ctrl+C = quit."
1571        ),
1572    });
1573    for w in audio_warnings {
1574        initial.push(ChatMessage {
1575            role: Role::Status,
1576            text: w.clone(),
1577        });
1578    }
1579    let messages: Rc<RefCell<Vec<ChatMessage>>> = Rc::new(RefCell::new(initial));
1580    let forest: Rc<RefCell<ForestView>> = Rc::new(RefCell::new(ForestView::default()));
1581    let mut input = String::new();
1582    let mut scroll: u16 = 0;
1583    let mut busy = false;
1584    let session_id = Uuid::new_v4().to_string();
1585
1586    loop {
1587        draw(
1588            terminal,
1589            &messages.borrow(),
1590            &forest.borrow(),
1591            &input,
1592            scroll,
1593            busy,
1594        )?;
1595
1596        if event::poll(std::time::Duration::from_millis(50))?
1597            && let Event::Key(key) = event::read()?
1598        {
1599            if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
1600                let _ = notify_session_end(liaison_endpoint, &session_id, &local_user).await;
1601                break;
1602            }
1603
1604            // Ctrl+A → btop-style single-page audio settings dashboard.
1605            // All four sections (mic provider, mic device, speaker
1606            // provider, speaker device) visible at once, Tab to cycle,
1607            // ↑↓ to move within a section, Enter to pick. Esc to close.
1608            if !busy
1609                && key.modifiers.contains(KeyModifiers::CONTROL)
1610                && key.code == KeyCode::Char('a')
1611            {
1612                match run_audio_settings_page(atlas_endpoint, terminal, chat_cfg.clone()).await {
1613                    Ok(new_cfg) => {
1614                        chat_cfg = new_cfg;
1615                        messages.borrow_mut().push(ChatMessage {
1616                            role: Role::Status,
1617                            text: format!(
1618                                "audio settings updated: mic={}/{} · speaker={}/{}",
1619                                chat_cfg.mic_cap_id.as_deref().unwrap_or("(unset)"),
1620                                chat_cfg.mic_device_id.as_deref().unwrap_or("default"),
1621                                chat_cfg.speaker_cap_id.as_deref().unwrap_or("(unset)"),
1622                                chat_cfg.speaker_device_id.as_deref().unwrap_or("default"),
1623                            ),
1624                        });
1625                    }
1626                    Err(e) => messages.borrow_mut().push(ChatMessage {
1627                        role: Role::Status,
1628                        text: format!("audio settings: {e:#}"),
1629                    }),
1630                }
1631                continue;
1632            }
1633
1634            // F2 → push-to-talk voice session (auto-ends on silence).
1635            if !busy && key.code == KeyCode::F(2) {
1636                busy = true;
1637                messages.borrow_mut().push(ChatMessage {
1638                    role: Role::Status,
1639                    text: "F2 — starting voice session…".to_string(),
1640                });
1641                draw(
1642                    terminal,
1643                    &messages.borrow(),
1644                    &forest.borrow(),
1645                    &input,
1646                    scroll,
1647                    busy,
1648                )?;
1649                if let Err(e) = run_voice_session_with_esc_abort(
1650                    liaison_endpoint,
1651                    &session_id,
1652                    &local_user,
1653                    Rc::clone(&messages),
1654                    &forest,
1655                    terminal,
1656                    &input,
1657                    &mut scroll,
1658                    &chat_cfg,
1659                )
1660                .await
1661                {
1662                    messages.borrow_mut().push(ChatMessage {
1663                        role: Role::Status,
1664                        text: format!("Voice error: {e:#}"),
1665                    });
1666                }
1667                busy = false;
1668                continue;
1669            }
1670
1671            if busy {
1672                match key.code {
1673                    KeyCode::PageUp => scroll = scroll.saturating_add(5),
1674                    KeyCode::PageDown => scroll = scroll.saturating_sub(5),
1675                    _ => {}
1676                }
1677                continue;
1678            }
1679            match key.code {
1680                KeyCode::Enter => {
1681                    let msg = input.trim().to_string();
1682                    input.clear();
1683                    scroll = 0;
1684                    if msg.is_empty() {
1685                        continue;
1686                    }
1687                    if msg == "quit" || msg == "exit" {
1688                        let _ =
1689                            notify_session_end(liaison_endpoint, &session_id, &local_user).await;
1690                        break;
1691                    }
1692                    messages.borrow_mut().push(ChatMessage {
1693                        role: Role::User,
1694                        text: msg.clone(),
1695                    });
1696                    // Fresh top-level task: reset the live forest panel.
1697                    forest.borrow_mut().begin_turn();
1698                    busy = true;
1699                    draw(
1700                        terminal,
1701                        &messages.borrow(),
1702                        &forest.borrow(),
1703                        &input,
1704                        scroll,
1705                        busy,
1706                    )?;
1707
1708                    match run_text_intent_with_esc_abort(
1709                        liaison_endpoint,
1710                        &session_id,
1711                        &local_user,
1712                        &msg,
1713                        Rc::clone(&messages),
1714                        &forest,
1715                        terminal,
1716                        &input,
1717                        &mut scroll,
1718                    )
1719                    .await
1720                    {
1721                        Ok(()) => {}
1722                        Err(e) => {
1723                            messages.borrow_mut().push(ChatMessage {
1724                                role: Role::Status,
1725                                text: format!("Error: {e:#}"),
1726                            });
1727                        }
1728                    }
1729                    busy = false;
1730                }
1731                KeyCode::Char(c) => input.push(c),
1732                KeyCode::Backspace => {
1733                    input.pop();
1734                }
1735                KeyCode::PageUp => scroll = scroll.saturating_add(5),
1736                KeyCode::PageDown => scroll = scroll.saturating_sub(5),
1737                // Idle Esc: clear the draft input. During a turn,
1738                // run_text_intent_with_esc_abort handles Esc differently
1739                // (sends abort_turn). The header line says "Esc = abort
1740                // turn" which is true mid-turn; idle Esc is a vim-style
1741                // "clear what I typed" affordance.
1742                KeyCode::Esc if !input.is_empty() => {
1743                    input.clear();
1744                }
1745                _ => {}
1746            }
1747        }
1748    }
1749    Ok(())
1750}
1751
1752// ── Liaison gRPC helpers ─────────────────────────────────────────────────────
1753
1754fn build_text_task(session_id: &str, user_id: &str, text: &str) -> crate::pb::pilot::Task {
1755    use crate::pb::pilot::Task;
1756    const INTENT_SOURCE_TEXT: u32 = 0;
1757    Task {
1758        task_id: Uuid::new_v4().to_string(),
1759        session_id: session_id.to_string(),
1760        source: INTENT_SOURCE_TEXT,
1761        text: text.to_string(),
1762        audio_data: vec![],
1763        context_json: serde_json::json!({"user_id": user_id, "modality": "text"}).to_string(),
1764        timestamp_ms: now_ms(),
1765    }
1766}
1767
1768fn build_control_task(
1769    session_id: &str,
1770    user_id: &str,
1771    extra_context_json: &str,
1772) -> crate::pb::pilot::Task {
1773    use crate::pb::pilot::Task;
1774    const INTENT_SOURCE_TEXT: u32 = 0;
1775    let mut ctx: serde_json::Value =
1776        serde_json::from_str(extra_context_json.trim()).unwrap_or_else(|_| serde_json::json!({}));
1777    if let Some(obj) = ctx.as_object_mut() {
1778        obj.entry("user_id").or_insert(serde_json::json!(user_id));
1779    }
1780    Task {
1781        task_id: Uuid::new_v4().to_string(),
1782        session_id: session_id.to_string(),
1783        source: INTENT_SOURCE_TEXT,
1784        text: String::new(),
1785        audio_data: vec![],
1786        context_json: ctx.to_string(),
1787        timestamp_ms: now_ms(),
1788    }
1789}
1790
1791async fn notify_session_end(liaison_endpoint: &str, session_id: &str, user_id: &str) -> Result<()> {
1792    use crate::pb::contracts::robonix_system_liaison_submit_client::RobonixSystemLiaisonSubmitClient;
1793
1794    let mut client = RobonixSystemLiaisonSubmitClient::connect(liaison_endpoint.to_string())
1795        .await
1796        .context("failed to connect to Liaison for session_end")?;
1797
1798    let task = build_control_task(session_id, user_id, r#"{"session_end":true}"#);
1799    let mut stream = client
1800        .submit_task(tonic::Request::new(task))
1801        .await
1802        .context("Liaison Stream session_end failed")?
1803        .into_inner();
1804    while stream.next().await.is_some() {}
1805    Ok(())
1806}
1807
1808async fn abort_session(liaison_endpoint: &str, session_id: &str, user_id: &str) -> Result<()> {
1809    use crate::pb::contracts::robonix_system_liaison_submit_client::RobonixSystemLiaisonSubmitClient;
1810
1811    let mut client = RobonixSystemLiaisonSubmitClient::connect(liaison_endpoint.to_string())
1812        .await
1813        .context("failed to connect to Liaison for abort_turn")?;
1814
1815    let task = build_control_task(session_id, user_id, r#"{"abort_turn":true}"#);
1816    let _ = client
1817        .submit_task(tonic::Request::new(task))
1818        .await
1819        .context("Liaison abort_turn Stream failed")?;
1820    Ok(())
1821}
1822
1823/// Fire-and-forget a mid-turn VOICE steer (Ctrl+V during a running turn):
1824/// record + ASR another utterance via a fresh voice session and let its
1825/// transcript submit — Pilot steers it into the active turn. TTS is disabled
1826/// here (the per-segment playback rides the main turn's stream); we just drain
1827/// this session's events on a spawned task.
1828fn spawn_voice_steer(
1829    liaison_endpoint: &str,
1830    session_id: &str,
1831    user_id: &str,
1832    chat_cfg: &ChatConfig,
1833) {
1834    use crate::pb::contracts::robonix_system_liaison_voice_client::RobonixSystemLiaisonVoiceClient;
1835    use crate::pb::liaison::StartVoiceSessionRequest;
1836    let ep = liaison_endpoint.to_string();
1837    let req = StartVoiceSessionRequest {
1838        session_id: session_id.to_string(),
1839        client_user_id: user_id.to_string(),
1840        record_seconds: voice_record_seconds(),
1841        language: voice_language(),
1842        tts_enabled: false,
1843        mic_node_id: voice_node_with_cfg("ROBONIX_CHAT_MIC_NODE", chat_cfg.mic_cap_id.as_deref()),
1844        asr_node_id: voice_node("ROBONIX_CHAT_ASR_NODE"),
1845        voiceprint_node_id: String::new(),
1846        tts_node_id: voice_node("ROBONIX_CHAT_TTS_NODE"),
1847        speaker_node_id: voice_node_with_cfg(
1848            "ROBONIX_CHAT_SPEAKER_NODE",
1849            chat_cfg.speaker_cap_id.as_deref(),
1850        ),
1851        context_json: String::new(),
1852    };
1853    tokio::spawn(async move {
1854        if let Ok(mut client) = RobonixSystemLiaisonVoiceClient::connect(ep).await
1855            && let Ok(resp) = client.start_voice_session(tonic::Request::new(req)).await
1856        {
1857            let mut s = resp.into_inner();
1858            while s.next().await.is_some() {}
1859        }
1860    });
1861}
1862
1863// ── Text turn ────────────────────────────────────────────────────────────────
1864
1865#[allow(clippy::too_many_arguments)]
1866async fn run_text_intent_with_esc_abort(
1867    liaison_endpoint: &str,
1868    session_id: &str,
1869    user_id: &str,
1870    user_msg: &str,
1871    messages: Rc<RefCell<Vec<ChatMessage>>>,
1872    forest: &Rc<RefCell<ForestView>>,
1873    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
1874    input: &str,
1875    scroll: &mut u16,
1876) -> Result<()> {
1877    use crate::pb::pilot::PilotEvent;
1878    use tonic::Status;
1879
1880    let (tx, mut rx) = tokio::sync::mpsc::channel::<Result<PilotEvent, Status>>(64);
1881    let liaison_ep = liaison_endpoint.to_string();
1882    let task = build_text_task(session_id, user_id, user_msg);
1883
1884    // Steers forward into the same channel; the turn ends when the first
1885    // message's stream and every steer's stream have closed.
1886    let steers = tx.downgrade();
1887    tokio::spawn(forward_submit(liaison_ep.clone(), task, tx));
1888
1889    // Mid-task input: the user can keep typing while the turn runs. Enter sends
1890    // the text as a steer (a new Task on the same session); pilot routes it to
1891    // the running turn instead of starting a second one. The local buffer is
1892    // separate from the idle-draft `input` so the two never collide.
1893    let _ = input;
1894    let mut steer_input = String::new();
1895
1896    loop {
1897        tokio::select! {
1898            biased;
1899            item = rx.recv() => {
1900                match item {
1901                    None => break,
1902                    Some(Ok(event)) => {
1903                        apply_pilot_event(&messages, forest, &event)?;
1904                        draw(terminal, &messages.borrow(), &forest.borrow(), &steer_input, 0, true)?;
1905                    }
1906                    // A failed stream ends by itself; the others keep the turn going.
1907                    Some(Err(e)) => {
1908                        messages.borrow_mut().push(ChatMessage {
1909                            role: Role::Status,
1910                            text: format!("Liaison stream error: {e}"),
1911                        });
1912                        draw(terminal, &messages.borrow(), &forest.borrow(), &steer_input, 0, true)?;
1913                    }
1914                }
1915            }
1916            _ = tokio::time::sleep(std::time::Duration::from_millis(25)) => {
1917                if event::poll(std::time::Duration::ZERO)?
1918                    && let Event::Key(key) = event::read()? {
1919                        match key.code {
1920                            KeyCode::Esc => {
1921                                let _ = abort_session(liaison_endpoint, session_id, user_id).await;
1922                                messages.borrow_mut().push(ChatMessage {
1923                                    role: Role::Status,
1924                                    text: "Esc — abort_turn sent (in-flight turn should stop)."
1925                                        .to_string(),
1926                                });
1927                                draw(terminal, &messages.borrow(), &forest.borrow(), &steer_input, *scroll, true)?;
1928                            }
1929                            KeyCode::Enter => {
1930                                let steer = steer_input.trim().to_string();
1931                                steer_input.clear();
1932                                if !steer.is_empty() {
1933                                    messages.borrow_mut().push(ChatMessage {
1934                                        role: Role::User,
1935                                        text: format!("(steer) {steer}"),
1936                                    });
1937                                    // The steer's own stream carries what Pilot
1938                                    // does for it: read it here, never block on it.
1939                                    if let Some(tx) = steers.upgrade() {
1940                                        let task = build_text_task(session_id, user_id, &steer);
1941                                        tokio::spawn(forward_submit(liaison_ep.clone(), task, tx));
1942                                    }
1943                                    *scroll = 0;
1944                                    draw(terminal, &messages.borrow(), &forest.borrow(), &steer_input, *scroll, true)?;
1945                                }
1946                            }
1947                            KeyCode::Char(c) => {
1948                                steer_input.push(c);
1949                                draw(terminal, &messages.borrow(), &forest.borrow(), &steer_input, *scroll, true)?;
1950                            }
1951                            KeyCode::Backspace => {
1952                                steer_input.pop();
1953                                draw(terminal, &messages.borrow(), &forest.borrow(), &steer_input, *scroll, true)?;
1954                            }
1955                            KeyCode::PageUp => {
1956                                *scroll = scroll.saturating_add(5);
1957                                draw(terminal, &messages.borrow(), &forest.borrow(), &steer_input, *scroll, true)?;
1958                            }
1959                            KeyCode::PageDown => {
1960                                *scroll = scroll.saturating_sub(5);
1961                                draw(terminal, &messages.borrow(), &forest.borrow(), &steer_input, *scroll, true)?;
1962                            }
1963                            _ => {}
1964                        }
1965                    }
1966            }
1967        }
1968    }
1969    Ok(())
1970}
1971
1972/// Submit a task to Liaison and forward its event stream into `tx`.
1973async fn forward_submit(
1974    liaison_ep: String,
1975    task: crate::pb::pilot::Task,
1976    tx: tokio::sync::mpsc::Sender<Result<crate::pb::pilot::PilotEvent, tonic::Status>>,
1977) {
1978    use crate::pb::contracts::robonix_system_liaison_submit_client::RobonixSystemLiaisonSubmitClient;
1979    let mut client = match RobonixSystemLiaisonSubmitClient::connect(liaison_ep).await {
1980        Ok(c) => c,
1981        Err(e) => {
1982            let _ = tx
1983                .send(Err(tonic::Status::unavailable(e.to_string())))
1984                .await;
1985            return;
1986        }
1987    };
1988    let mut stream = match client.submit_task(tonic::Request::new(task)).await {
1989        Ok(r) => r.into_inner(),
1990        Err(e) => {
1991            let _ = tx.send(Err(e)).await;
1992            return;
1993        }
1994    };
1995    while let Some(item) = stream.next().await {
1996        if tx.send(item).await.is_err() {
1997            break;
1998        }
1999    }
2000}
2001
2002/// Submit `text` as a mid-task steer on an already-running session. Pilot routes
2003/// it to the live turn's steer queue and returns an empty stream, which we drain.
2004async fn send_steer(
2005    liaison_endpoint: &str,
2006    session_id: &str,
2007    user_id: &str,
2008    text: &str,
2009) -> Result<()> {
2010    use crate::pb::contracts::robonix_system_liaison_submit_client::RobonixSystemLiaisonSubmitClient;
2011
2012    let mut client = RobonixSystemLiaisonSubmitClient::connect(liaison_endpoint.to_string())
2013        .await
2014        .context("failed to connect to Liaison for steer")?;
2015    let task = build_text_task(session_id, user_id, text);
2016    let mut stream = client
2017        .submit_task(tonic::Request::new(task))
2018        .await
2019        .context("Liaison steer submit failed")?
2020        .into_inner();
2021    while stream.next().await.is_some() {}
2022    Ok(())
2023}
2024
2025// ── Voice turn ───────────────────────────────────────────────────────────────
2026
2027#[allow(clippy::too_many_arguments)]
2028async fn run_voice_session_with_esc_abort(
2029    liaison_endpoint: &str,
2030    session_id: &str,
2031    user_id: &str,
2032    messages: Rc<RefCell<Vec<ChatMessage>>>,
2033    forest: &Rc<RefCell<ForestView>>,
2034    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
2035    input: &str,
2036    scroll: &mut u16,
2037    chat_cfg: &ChatConfig,
2038) -> Result<()> {
2039    use crate::pb::contracts::robonix_system_liaison_voice_client::RobonixSystemLiaisonVoiceClient;
2040    use crate::pb::liaison::{StartVoiceSessionRequest, VoiceEvent};
2041    use tonic::Status;
2042
2043    let req = StartVoiceSessionRequest {
2044        session_id: session_id.to_string(),
2045        client_user_id: user_id.to_string(),
2046        record_seconds: voice_record_seconds(),
2047        language: voice_language(),
2048        tts_enabled: voice_tts_enabled(),
2049        mic_node_id: voice_node_with_cfg("ROBONIX_CHAT_MIC_NODE", chat_cfg.mic_cap_id.as_deref()),
2050        asr_node_id: voice_node("ROBONIX_CHAT_ASR_NODE"),
2051        voiceprint_node_id: String::new(),
2052        tts_node_id: voice_node("ROBONIX_CHAT_TTS_NODE"),
2053        speaker_node_id: voice_node_with_cfg(
2054            "ROBONIX_CHAT_SPEAKER_NODE",
2055            chat_cfg.speaker_cap_id.as_deref(),
2056        ),
2057        context_json: String::new(),
2058    };
2059
2060    let (tx, mut rx) = tokio::sync::mpsc::channel::<Result<VoiceEvent, Status>>(64);
2061    let liaison_ep = liaison_endpoint.to_string();
2062
2063    let _stream_task = tokio::spawn(async move {
2064        let mut client = match RobonixSystemLiaisonVoiceClient::connect(liaison_ep.clone()).await {
2065            Ok(c) => c,
2066            Err(e) => {
2067                let _ = tx.send(Err(Status::unavailable(e.to_string()))).await;
2068                return;
2069            }
2070        };
2071        let stream = match client.start_voice_session(tonic::Request::new(req)).await {
2072            Ok(r) => r.into_inner(),
2073            Err(e) => {
2074                let _ = tx.send(Err(e)).await;
2075                return;
2076            }
2077        };
2078        let mut stream = stream;
2079        while let Some(item) = stream.next().await {
2080            if tx.send(item).await.is_err() {
2081                break;
2082            }
2083        }
2084    });
2085
2086    // Mid-task steer during a voice turn (mirrors the text turn): type + Enter
2087    // sends a text steer; Ctrl+V records another utterance as a voice steer.
2088    // Pilot routes either into the running turn instead of starting a new one.
2089    let _ = input;
2090    let mut steer_input = String::new();
2091
2092    loop {
2093        tokio::select! {
2094            biased;
2095            item = rx.recv() => {
2096                match item {
2097                    None => break,
2098                    Some(Ok(event)) => {
2099                        apply_voice_event(&messages, forest, &event)?;
2100                        draw(terminal, &messages.borrow(), &forest.borrow(), &steer_input, 0, true)?;
2101                    }
2102                    Some(Err(e)) => {
2103                        messages.borrow_mut().push(ChatMessage {
2104                            role: Role::Status,
2105                            text: format!("Voice stream error: {e}"),
2106                        });
2107                        draw(terminal, &messages.borrow(), &forest.borrow(), &steer_input, 0, true)?;
2108                        break;
2109                    }
2110                }
2111            }
2112            _ = tokio::time::sleep(std::time::Duration::from_millis(25)) => {
2113                if event::poll(std::time::Duration::ZERO)?
2114                    && let Event::Key(key) = event::read()? {
2115                        if key.code == KeyCode::Char('v')
2116                            && key.modifiers.contains(KeyModifiers::CONTROL)
2117                        {
2118                            messages.borrow_mut().push(ChatMessage {
2119                                role: Role::Voice,
2120                                text: "Ctrl+V — voice steer: speak your addition…".to_string(),
2121                            });
2122                            spawn_voice_steer(liaison_endpoint, session_id, user_id, chat_cfg);
2123                            draw(terminal, &messages.borrow(), &forest.borrow(), &steer_input, *scroll, true)?;
2124                        } else {
2125                            match key.code {
2126                                KeyCode::Esc => {
2127                                    let _ = abort_session(liaison_endpoint, session_id, user_id).await;
2128                                    messages.borrow_mut().push(ChatMessage {
2129                                        role: Role::Status,
2130                                        text: "Esc — abort_turn sent (Pilot stops; voice playback may still finish).".to_string(),
2131                                    });
2132                                    draw(terminal, &messages.borrow(), &forest.borrow(), &steer_input, *scroll, true)?;
2133                                }
2134                                KeyCode::Enter => {
2135                                    let steer = steer_input.trim().to_string();
2136                                    steer_input.clear();
2137                                    if !steer.is_empty() {
2138                                        messages.borrow_mut().push(ChatMessage {
2139                                            role: Role::User,
2140                                            text: format!("(steer) {steer}"),
2141                                        });
2142                                        if let Err(e) =
2143                                            send_steer(liaison_endpoint, session_id, user_id, &steer).await
2144                                        {
2145                                            messages.borrow_mut().push(ChatMessage {
2146                                                role: Role::Status,
2147                                                text: format!("steer failed: {e:#}"),
2148                                            });
2149                                        }
2150                                        *scroll = 0;
2151                                    }
2152                                    draw(terminal, &messages.borrow(), &forest.borrow(), &steer_input, *scroll, true)?;
2153                                }
2154                                KeyCode::Char(c) => {
2155                                    steer_input.push(c);
2156                                    draw(terminal, &messages.borrow(), &forest.borrow(), &steer_input, *scroll, true)?;
2157                                }
2158                                KeyCode::Backspace => {
2159                                    steer_input.pop();
2160                                    draw(terminal, &messages.borrow(), &forest.borrow(), &steer_input, *scroll, true)?;
2161                                }
2162                                KeyCode::PageUp => {
2163                                    *scroll = scroll.saturating_add(5);
2164                                    draw(terminal, &messages.borrow(), &forest.borrow(), &steer_input, *scroll, true)?;
2165                                }
2166                                KeyCode::PageDown => {
2167                                    *scroll = scroll.saturating_sub(5);
2168                                    draw(terminal, &messages.borrow(), &forest.borrow(), &steer_input, *scroll, true)?;
2169                                }
2170                                _ => {}
2171                            }
2172                        }
2173                    }
2174            }
2175        }
2176    }
2177    Ok(())
2178}
2179
2180fn voice_record_seconds() -> u32 {
2181    std::env::var("ROBONIX_CHAT_VOICE_SECONDS")
2182        .ok()
2183        .and_then(|s| s.parse().ok())
2184        .unwrap_or(0) // 0 → server default (5s)
2185}
2186
2187fn voice_language() -> String {
2188    std::env::var("ROBONIX_CHAT_VOICE_LANG").unwrap_or_default()
2189}
2190
2191fn voice_tts_enabled() -> bool {
2192    !matches!(
2193        std::env::var("ROBONIX_CHAT_VOICE_TTS").as_deref(),
2194        Ok("0") | Ok("false") | Ok("no") | Ok("off")
2195    )
2196}
2197
2198fn voice_node(env_key: &str) -> String {
2199    std::env::var(env_key).unwrap_or_default()
2200}
2201
2202/// Same as `voice_node` but falls back to `cfg_value` (from chat.yaml)
2203/// when the env var is unset / empty. Empty result still means "let
2204/// liaison auto-pick from atlas".
2205fn voice_node_with_cfg(env_key: &str, cfg_value: Option<&str>) -> String {
2206    if let Ok(v) = std::env::var(env_key)
2207        && !v.is_empty()
2208    {
2209        return v;
2210    }
2211    cfg_value.unwrap_or("").to_string()
2212}
2213
2214// ── Event → ChatMessage rendering ────────────────────────────────────────────
2215
2216fn apply_pilot_event(
2217    messages: &Rc<RefCell<Vec<ChatMessage>>>,
2218    forest: &Rc<RefCell<ForestView>>,
2219    event: &crate::pb::pilot::PilotEvent,
2220) -> Result<()> {
2221    // event_kind discriminants — see PilotEvent.msg.
2222    const EVT_TEXT_CHUNK: u32 = 0;
2223    const EVT_PLAN: u32 = 1;
2224    const EVT_BATCH_RESULT: u32 = 2;
2225    const EVT_FINAL_TEXT: u32 = 4;
2226    const EVT_NODE_STATE: u32 = 5;
2227    const EVT_TASK_STATE: u32 = 6;
2228
2229    let mut m = messages.borrow_mut();
2230    match event.event_kind {
2231        EVT_TEXT_CHUNK => {
2232            let t = event.text_chunk.clone();
2233            if let Some(last) = m.last_mut() {
2234                if matches!(last.role, Role::Agent) {
2235                    last.text.push_str(&t);
2236                } else {
2237                    m.push(ChatMessage {
2238                        role: Role::Agent,
2239                        text: t,
2240                    });
2241                }
2242            } else {
2243                m.push(ChatMessage {
2244                    role: Role::Agent,
2245                    text: t,
2246                });
2247            }
2248        }
2249        EVT_FINAL_TEXT => {
2250            let t = event.final_text.clone();
2251            // Skip only a repeat of the narration just shown: with several
2252            // tasks, the final answer can follow another task's narration.
2253            let repeat = m
2254                .last()
2255                .is_some_and(|x| matches!(x.role, Role::Agent) && x.text == t);
2256            if !repeat && !t.is_empty() {
2257                m.push(ChatMessage {
2258                    role: Role::Agent,
2259                    text: t,
2260                });
2261            }
2262        }
2263        EVT_PLAN => {
2264            // Log the dispatched RTDL tree as ASCII (historical record) and add
2265            // it to the live forest panel.
2266            if let Some(ref p) = event.plan {
2267                m.push(ChatMessage {
2268                    role: Role::ToolCall,
2269                    text: render_plan_tree(p),
2270                });
2271                let mut f = forest.borrow_mut();
2272                if f.plan_mut(&p.plan_id).is_none() {
2273                    f.plans.push(PlanView {
2274                        plan_id: p.plan_id.clone(),
2275                        plan: p.clone(),
2276                        node_states: HashMap::new(),
2277                        done: false,
2278                        any_failed: false,
2279                    });
2280                }
2281            }
2282        }
2283        EVT_NODE_STATE => {
2284            if let Some(ref ns) = event.node_state {
2285                let mut f = forest.borrow_mut();
2286                if let Some(pv) = f.plan_mut(&ns.plan_id) {
2287                    pv.node_states.insert(ns.node_index, ns.state);
2288                }
2289            }
2290        }
2291        EVT_BATCH_RESULT => {
2292            if let Some(ref b) = event.batch_result {
2293                let mut f = forest.borrow_mut();
2294                if let Some(pv) = f.plan_mut(&b.plan_id) {
2295                    pv.done = true;
2296                    pv.any_failed = b.any_failed;
2297                }
2298            }
2299        }
2300        EVT_TASK_STATE => {
2301            if let Some(ref ts) = event.task_state {
2302                let mut f = forest.borrow_mut();
2303                f.goal = ts.goal.clone();
2304                f.success_criterion = ts.success_criterion.clone();
2305                f.tasks = ts.tasks.clone();
2306                f.status = ts.status.clone();
2307            }
2308        }
2309        _ => {}
2310    }
2311    Ok(())
2312}
2313
2314/// Render a `Plan` arena as an ASCII tree, e.g.
2315/// ```text
2316/// [plan 1]
2317/// sequence: fetch water
2318/// ├─ navigate(kitchen)
2319/// └─ grasp(water cup)
2320/// ```
2321fn render_plan_tree(plan: &crate::pb::pilot::Plan) -> String {
2322    let mut lines = vec![format!("[plan {}]", plan.plan_id)];
2323    if (plan.root_index as usize) < plan.nodes.len() {
2324        render_plan_node(plan, plan.root_index as usize, "", true, true, &mut lines);
2325    }
2326    lines.join("\n")
2327}
2328
2329fn render_plan_node(
2330    plan: &crate::pb::pilot::Plan,
2331    idx: usize,
2332    prefix: &str,
2333    is_root: bool,
2334    is_last: bool,
2335    out: &mut Vec<String>,
2336) {
2337    let node = &plan.nodes[idx];
2338    let label = match node.node_kind {
2339        0 => format!("sequence: {}", node.description),
2340        1 => format!("parallel: {}", node.description),
2341        _ => match node.call.as_ref() {
2342            Some(c) => compact_call_label(&c.provider_id, &c.contract_id, &c.args_json),
2343            None => node.description.clone(),
2344        },
2345    };
2346    if is_root {
2347        out.push(label);
2348    } else {
2349        let branch = if is_last { "└─ " } else { "├─ " };
2350        out.push(format!("{prefix}{branch}{label}"));
2351    }
2352    let n = node.children.len();
2353    for (i, child) in node.children.iter().enumerate() {
2354        let child_prefix = if is_root {
2355            String::new()
2356        } else if is_last {
2357            format!("{prefix}   ")
2358        } else {
2359            format!("{prefix}│  ")
2360        };
2361        render_plan_node(plan, *child as usize, &child_prefix, false, i + 1 == n, out);
2362    }
2363}
2364
2365fn apply_voice_event(
2366    messages: &Rc<RefCell<Vec<ChatMessage>>>,
2367    forest: &Rc<RefCell<ForestView>>,
2368    event: &crate::pb::liaison::VoiceEvent,
2369) -> Result<()> {
2370    // Mirror the kinds in voice.rs / VoiceEvent.msg
2371    const KIND_SESSION_STARTED: u32 = 0;
2372    const KIND_RECORDING_STARTED: u32 = 1;
2373    const KIND_RECORDING_DONE: u32 = 2;
2374    const KIND_ASR_PARTIAL: u32 = 3;
2375    const KIND_ASR_FINAL: u32 = 4;
2376    const KIND_USER_IDENTIFIED: u32 = 5;
2377    const KIND_PILOT: u32 = 6;
2378    const KIND_TTS_STARTED: u32 = 7;
2379    const KIND_TTS_DONE: u32 = 8;
2380    const KIND_SESSION_DONE: u32 = 9;
2381    const KIND_ERROR: u32 = 10;
2382
2383    match event.event_kind {
2384        KIND_SESSION_STARTED | KIND_RECORDING_STARTED | KIND_RECORDING_DONE => {
2385            messages.borrow_mut().push(ChatMessage {
2386                role: Role::Voice,
2387                text: format!("voice · {}", event.status_message),
2388            });
2389        }
2390        KIND_ASR_PARTIAL => {
2391            messages.borrow_mut().push(ChatMessage {
2392                role: Role::Voice,
2393                text: format!("asr (partial, {:.2}): {}", event.confidence, event.text),
2394            });
2395        }
2396        KIND_ASR_FINAL => {
2397            messages.borrow_mut().push(ChatMessage {
2398                role: Role::User,
2399                text: format!("(voice) {}", event.text),
2400            });
2401        }
2402        KIND_USER_IDENTIFIED => {
2403            let label = if event.status_message.is_empty() {
2404                format!("identified user → {}", event.user_id)
2405            } else {
2406                format!(
2407                    "identified user → {} · {}",
2408                    event.user_id, event.status_message
2409                )
2410            };
2411            messages.borrow_mut().push(ChatMessage {
2412                role: Role::Voice,
2413                text: label,
2414            });
2415        }
2416        KIND_PILOT => {
2417            if let Some(ref pe) = event.pilot {
2418                apply_pilot_event(messages, forest, pe)?;
2419            }
2420        }
2421        KIND_TTS_STARTED => {
2422            messages.borrow_mut().push(ChatMessage {
2423                role: Role::Voice,
2424                text: format!("tts · {}", event.status_message),
2425            });
2426        }
2427        KIND_TTS_DONE => {
2428            messages.borrow_mut().push(ChatMessage {
2429                role: Role::Voice,
2430                text: format!("tts done · {}", event.status_message),
2431            });
2432        }
2433        KIND_SESSION_DONE => {
2434            messages.borrow_mut().push(ChatMessage {
2435                role: Role::Status,
2436                text: "voice session done".to_string(),
2437            });
2438        }
2439        KIND_ERROR => {
2440            messages.borrow_mut().push(ChatMessage {
2441                role: Role::Status,
2442                text: format!("voice error: {}", event.error),
2443            });
2444        }
2445        _ => {
2446            messages.borrow_mut().push(ChatMessage {
2447                role: Role::Voice,
2448                text: format!("voice (kind={}) {}", event.event_kind, event.status_message),
2449            });
2450        }
2451    }
2452    Ok(())
2453}
2454
2455fn draw(
2456    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
2457    messages: &[ChatMessage],
2458    forest: &ForestView,
2459    input: &str,
2460    scroll: u16,
2461    busy: bool,
2462) -> Result<()> {
2463    terminal.draw(|f| {
2464        let area = f.area();
2465        let chunks = Layout::vertical([Constraint::Min(3), Constraint::Length(3)]).split(area);
2466        // Split the body into chat (left) + live RTDL forest panel (right).
2467        // The panel takes two fifths of a wide terminal, so a task's goal and
2468        // its trees fit; never narrower than it used to be.
2469        let panel_w = (chunks[0].width * 2 / 5).max(46);
2470        let body =
2471            Layout::horizontal([Constraint::Min(24), Constraint::Length(panel_w)]).split(chunks[0]);
2472
2473        let mut lines: Vec<Line> = Vec::new();
2474        for msg in messages {
2475            let (prefix, indent, style) = match msg.role {
2476                Role::User => (
2477                    "You:   ",
2478                    "       ",
2479                    Style::default()
2480                        .fg(Color::Cyan)
2481                        .add_modifier(Modifier::BOLD),
2482                ),
2483                // "Robonix:" — the user-facing system name. The reply
2484                // went through Liaison → Pilot → tools → Liaison → here,
2485                // so naming it after one internal crate ("Pilot") leaks
2486                // an architectural detail that the user has no reason
2487                // to know or care about.
2488                Role::Agent => ("Robonix: ", "         ", Style::default().fg(Color::Green)),
2489                Role::ToolCall => (">      ", "       ", Style::default().fg(Color::Yellow)),
2490                Role::Status => (
2491                    "",
2492                    "",
2493                    Style::default()
2494                        .fg(Color::Magenta)
2495                        .add_modifier(Modifier::ITALIC),
2496                ),
2497                Role::Voice => (
2498                    "[v]    ",
2499                    "       ",
2500                    Style::default()
2501                        .fg(Color::Blue)
2502                        .add_modifier(Modifier::ITALIC),
2503                ),
2504            };
2505            for (i, text_line) in msg.text.lines().enumerate() {
2506                let lead = if i == 0 { prefix } else { indent };
2507                lines.push(Line::from(vec![
2508                    Span::styled(lead, style),
2509                    Span::styled(text_line.to_string(), style),
2510                ]));
2511            }
2512        }
2513
2514        let status = if busy { " [thinking...]" } else { "" };
2515        let block = Block::default()
2516            .borders(Borders::ALL)
2517            .title(format!(" Robonix{status} "));
2518        let inner = block.inner(body[0]);
2519
2520        let text_only = Paragraph::new(lines.clone()).wrap(Wrap { trim: false });
2521        let total_lines = text_only.line_count(inner.width) as u16;
2522        let visible = inner.height;
2523        let auto_scroll = if scroll == 0 {
2524            total_lines.saturating_sub(visible)
2525        } else {
2526            total_lines.saturating_sub(visible).saturating_sub(scroll)
2527        };
2528
2529        let history = Paragraph::new(lines)
2530            .block(block)
2531            .wrap(Wrap { trim: false })
2532            .scroll((auto_scroll, 0));
2533        f.render_widget(history, body[0]);
2534
2535        // Right: live task + RTDL forest. Auto-scrolls to the bottom so the
2536        // freshest trees stay visible.
2537        let panel_block = Block::default()
2538            .borders(Borders::ALL)
2539            .title(" Task / Forest ");
2540        let panel_inner_h = panel_block.inner(body[1]).height;
2541        let panel_lines = forest_panel_lines(forest);
2542        let panel_scroll = (panel_lines.len() as u16).saturating_sub(panel_inner_h);
2543        let panel = Paragraph::new(panel_lines)
2544            .block(panel_block)
2545            .wrap(Wrap { trim: false })
2546            .scroll((panel_scroll, 0));
2547        f.render_widget(panel, body[1]);
2548
2549        let input_widget = Paragraph::new(input.to_string()).block(
2550            Block::default()
2551                .borders(Borders::ALL)
2552                .title(" > Enter = send · F2 = voice (auto end) · Esc = abort · Ctrl+C = quit "),
2553        );
2554        f.render_widget(input_widget, chunks[1]);
2555    })?;
2556    Ok(())
2557}
2558
2559fn now_ms() -> u64 {
2560    std::time::SystemTime::now()
2561        .duration_since(std::time::UNIX_EPOCH)
2562        .unwrap_or_default()
2563        .as_millis() as u64
2564}
2565
2566/// Pilot/Liaison bind IPv4 (`0.0.0.0`). Resolving `localhost` often prefers
2567/// `::1`, so the gRPC client hits IPv6 and gets connection refused — force IPv4 loopback.
2568fn localhost_to_ipv4_loopback(url: &str) -> String {
2569    url.replace("localhost", "127.0.0.1")
2570}
2571
2572/// Tiny username probe — avoids pulling in `whoami` for the CLI by reading
2573/// $USER/$USERNAME with a "user" fallback. Liaison uses the real `whoami`
2574/// crate when it stamps the canonical `local:<user>` identity.
2575fn whoami_username() -> String {
2576    std::env::var("USER")
2577        .or_else(|_| std::env::var("USERNAME"))
2578        .unwrap_or_else(|_| "user".to_string())
2579}
浙ICP备2023005800号-2 浙公网安备33010902005384号