Switchyard lets LLM applications route traffic across models and providers while preserving native OpenAI and Anthropic API compatibility - enabling flexible model selection, benchmarking, and cost/performance optimization.
Rust
feat(desktop): add the terminal app shell and Overview server status (#1087)
Elyas Mehtabuddinbe225b4f79f3
diff --git a/crates/switchyard-desktop/src/controller.rs b/crates/switchyard-desktop/src/controller.rsnew file mode 100644index 000000000..5cf09c55d--- /dev/null+++ b/crates/switchyard-desktop/src/controller.rs@@ -0,0 +1,129 @@+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+// SPDX-License-Identifier: Apache-2.0++//! The terminal controller reloads settings and combines usage and server health into snapshots.+//! It retains the log reader and health probe across refreshes.++use crate::{config::Config, rollup};+use serde::Serialize;+use serde_json::{Value, json};+use std::path::PathBuf;++/// Snapshot holds the terminal app's usage, server health, errors, and refresh interval.+#[derive(Clone, Default, Serialize)]+pub struct Snapshot {+ pub data_state: DataState,+ pub metrics: Metrics,+ pub errors: Vec<String>,+ pub refresh_seconds: u64,+}++#[derive(Clone, Default, Serialize)]+pub struct DataState {+ pub usage: Source,+ /// This field holds the `/health` result with `state`, `reason`, `checked_at`, and `url`.+ pub health: Value,+}++/// Source records whether the app could read one data file.+#[derive(Clone, Default, Serialize)]+pub struct Source {+ pub state: Availability,+ pub checked_at: String,+ pub path: PathBuf,+}++/// The default is unavailable, so a data file that the app has not read shows no usage.+#[derive(Clone, Copy, Default, PartialEq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum Availability {+ Available,+ #[default]+ Unavailable,+}++#[derive(Clone, Default, Serialize)]+pub struct Metrics {+ pub server_url: String,+ pub running: bool,+ pub today: Counts,+ pub week: Counts,+}++#[derive(Clone, Default, Serialize)]+pub struct Counts {+ pub requests: u64,+ pub tokens: u64,+}++pub struct Controller {+ settings: PathBuf,+ config: Config,+ reader: rollup::Reader,+ health_probe: crate::health::Probe,+}+impl Controller {+ pub fn new(config: Config, settings: PathBuf) -> Self {+ Self {+ config,+ settings,+ reader: rollup::Reader::default(),+ health_probe: crate::health::Probe::default(),+ }+ }+ fn reload(&mut self) -> Result<(), String> {+ self.config = Config::load(&self.settings)?;+ Ok(())+ }+ pub fn snapshot(&mut self) -> Result<Snapshot, String> {+ self.reload()?;+ let mut errors = Vec::new();+ // One local date keeps the daily and weekly usage totals aligned across midnight.+ let today = chrono::Local::now().date_naive();+ let mut usage_state = Availability::Available;+ let usage = self+ .reader+ .read(&self.config.routing_log, today)+ .unwrap_or_else(|error| {+ usage_state = Availability::Unavailable;+ errors.push(format!("Could not read usage: {error}"));+ rollup::Usage::default()+ });+ let checked_at = chrono::Utc::now().to_rfc3339();+ let mut health = self.health_probe.details(&self.config.server_url);+ health["checked_at"] = json!(checked_at);+ health["url"] = json!(self.config.server_url);+ let server_status = if health["state"] == "running" {+ crate::health::ServerStatus::Running+ } else {+ crate::health::ServerStatus::Stopped+ };+ let server_url = self.config.server_url.clone();+ let routing_log = self.config.routing_log.clone();+ let refresh_seconds = self.config.refresh_seconds;+ Ok(Snapshot {+ data_state: DataState {+ usage: Source {+ state: usage_state,+ checked_at: checked_at.clone(),+ path: routing_log.clone(),+ },+ health,+ },+ metrics: Metrics {+ server_url: server_url.clone(),+ running: server_status == crate::health::ServerStatus::Running,+ today: Counts {+ requests: usage.today.requests(),+ tokens: usage.today.tokens(),+ },+ week: Counts {+ requests: usage.week.requests(),+ tokens: usage.week.tokens(),+ },+ },+ errors,+ refresh_seconds: refresh_seconds.max(1),+ })+ }+}diff --git a/crates/switchyard-desktop/src/main.rs b/crates/switchyard-desktop/src/main.rsindex acc6182c7..b4e46e9e0 100644--- a/crates/switchyard-desktop/src/main.rs+++ b/crates/switchyard-desktop/src/main.rs@@ -1,18 +1,21 @@// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.// SPDX-License-Identifier: Apache-2.0-//! The desktop app reports a local Switchyard server's recorded usage.+//! The desktop app shows a local Switchyard server's status and recorded usage.//!-//! The printed summary shows recorded traffic and compares list-price estimates with the-//! configured baseline model.+//! The printed summary compares list-price estimates with the configured baseline model.#![cfg_attr(windows, windows_subsystem = "windows")]use switchyard_desktop::{config, health, rollup};+mod controller;#[cfg(any(target_os = "macos", windows))]mod gui;mod pricing;mod summary;+mod tui;+#[cfg(windows)]+mod windows;use std::path::PathBuf;use std::process::ExitCode;@@ -20,11 +23,13 @@ use std::process::ExitCode;use config::Config;const USAGE: &str = "\-Usage: switchyard-desktop [--print | --validate-toml] [FILE]+Usage: switchyard-desktop [--tui | --print | --validate-toml] [FILE]-This app opens the desktop window. Use --print for a usage summary.+This app opens the desktop window on macOS and Windows.+Use --tui for the terminal app or --print for a usage summary.FILE The app reads settings from FILE.+ --tui Run the terminal app.--print Print the current summary and exit.--validate-toml Parse FILE as TOML and exit.@@ -41,18 +46,14 @@ Savings compare spending on all calls with the cost of the answers atbaseline_model's bundled rates or the table selected by pricing_file.Recorded spending remains visible when savings are unknown.";-/// The command checks TOML syntax or opens the desktop window.+/// The command selects the graphical app, terminal app, printed summary, or TOML validation.fn main() -> ExitCode {- // A desktop launch may have no parent console, so attachment failure does not stop the app.#[cfg(windows)]- let _ = unsafe {- windows_sys::Win32::System::Console::AttachConsole(- windows_sys::Win32::System::Console::ATTACH_PARENT_PROCESS,- )- };+ windows::attach_console();let mut settings = None;- let mut validate_toml = false;let mut print_only = false;+ let mut validate_toml = false;+ let mut terminal = false;for arg in std::env::args().skip(1) {match arg.as_str() {"-h" | "--help" => {@@ -60,6 +61,7 @@ fn main() -> ExitCode {return ExitCode::SUCCESS;}"--print" => print_only = true,+ "--tui" => terminal = true,"--validate-toml" => validate_toml = true,_ if arg.starts_with('-') => {eprintln!("switchyard-desktop: unknown option {arg}\n\n{USAGE}");@@ -73,6 +75,11 @@ fn main() -> ExitCode {}}+ if terminal && (print_only || validate_toml) {+ eprintln!("{USAGE}");+ return ExitCode::FAILURE;+ }+if validate_toml {let Some(path) = settings else {eprintln!("switchyard-desktop: --validate-toml requires a file path");@@ -92,7 +99,7 @@ fn main() -> ExitCode {return ExitCode::FAILURE;}};- if !print_only {+ if !terminal && !print_only {#[cfg(any(target_os = "macos", windows))]return match gui::run(settings) {Ok(()) => ExitCode::SUCCESS,@@ -103,9 +110,7 @@ fn main() -> ExitCode {};#[cfg(not(any(target_os = "macos", windows)))]{- eprintln!(- "The desktop window supports macOS and Windows. Use --print for a usage summary."- );+ eprintln!("The desktop window supports macOS and Windows. Use --print or --tui.");return ExitCode::FAILURE;}}@@ -114,31 +119,51 @@ fn main() -> ExitCode {Ok(config) => config,Err(error) => {eprintln!("switchyard-desktop: {error}");- return ExitCode::FAILURE;- }- };- let usage = match rollup::Reader::default()- .read(&config.routing_log, chrono::Local::now().date_naive())- {- Ok(usage) => usage,- Err(error) => {- eprintln!(- "Usage unavailable. Could not read {}: {error}",- config.routing_log.display()- );- return ExitCode::FAILURE;+ if !terminal {+ return ExitCode::FAILURE;+ }+ match Config::defaults_for(&settings) {+ Ok(config) => config,+ Err(error) => {+ eprintln!("switchyard-desktop: {error}");+ return ExitCode::FAILURE;+ }+ }}};- let rates = match pricing::load(config.prices_file.as_deref()) {- Ok(rates) => rates,- Err(error) => {- eprintln!("switchyard-desktop: {error}");- return ExitCode::FAILURE;+ if print_only {+ let usage = match rollup::Reader::default()+ .read(&config.routing_log, chrono::Local::now().date_naive())+ {+ Ok(usage) => usage,+ Err(error) => {+ eprintln!(+ "Usage unavailable. Could not read {}: {error}",+ config.routing_log.display()+ );+ return ExitCode::FAILURE;+ }+ };+ let rates = match pricing::load(config.prices_file.as_deref()) {+ Ok(rates) => rates,+ Err(error) => {+ eprintln!("switchyard-desktop: {error}");+ return ExitCode::FAILURE;+ }+ };+ let status = health::Probe::default().probe(&config.server_url);+ for row in summary::build(status, &usage, &config, &rates) {+ println!("{row}");}- };- let status = health::Probe::default().probe(&config.server_url);- for row in summary::build(status, &usage, &config, &rates) {- println!("{row}");+ return ExitCode::SUCCESS;+ }++ let controller = controller::Controller::new(config, settings);+ #[cfg(windows)]+ windows::allocate_console();+ if let Err(error) = tui::run(controller) {+ eprintln!("switchyard-desktop: {error}");+ return ExitCode::FAILURE;}ExitCode::SUCCESS}diff --git a/crates/switchyard-desktop/src/tui.rs b/crates/switchyard-desktop/src/tui.rsnew file mode 100644index 000000000..22abf1264--- /dev/null+++ b/crates/switchyard-desktop/src/tui.rs@@ -0,0 +1,559 @@+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+// SPDX-License-Identifier: Apache-2.0++//! The terminal app shows recorded usage and server status on the Overview page.+//!+//! One worker thread owns the controller and refreshes its snapshots while the UI thread+//! draws and reads input.++use crate::controller::{Availability, Controller, Snapshot};+use ratatui::{+ Frame,+ crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers},+ layout::{Constraint, Layout, Rect},+ style::{Color, Modifier, Style},+ text::{Line, Span},+ widgets::{Block, BorderType, Padding, Paragraph, Tabs, Wrap},+};+use std::{+ sync::mpsc,+ thread,+ time::{Duration, Instant},+};++/// Smaller terminals show a resize message instead of clipped panels.+const MIN_WIDTH: u16 = 60;+const MIN_HEIGHT: u16 = 16;+const TOAST_TIME: Duration = Duration::from_secs(4);+const SPINNER: [char; 8] = ['⣷', '⣯', '⣟', '⡿', '⢿', '⣻', '⣽', '⣾'];++/// Each entry holds a key, its status-bar label, and a longer description.+type Key = (&'static str, &'static str, &'static str);+const GLOBAL_KEYS: &[Key] = &[+ (+ "1",+ "page",+ "Show Overview. Tab, Shift-Tab, ← and → also select Overview.",+ ),+ (+ "r",+ "refresh",+ "Reload usage and server health now. F5 also refreshes.",+ ),+ (+ "q",+ "quit",+ "Quit the app. The server keeps running. Ctrl-C also quits.",+ ),+];++/// Theme maps each kind of text to one style. NO_COLOR keeps the text modifiers.+#[derive(Clone, Copy)]+struct Theme {+ muted: Style,+ key: Style,+ ok: Style,+ error: Style,+ selected: Style,+ border: Style,+}+impl Theme {+ fn new(color: bool) -> Self {+ let plain = Style::new();+ if !color {+ return Self {+ muted: plain.add_modifier(Modifier::DIM),+ key: plain.add_modifier(Modifier::BOLD),+ ok: plain,+ error: plain.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),+ selected: plain.add_modifier(Modifier::REVERSED),+ border: plain,+ };+ }+ // Named ANSI colors follow the terminal's palette, so they work on light and dark themes.+ Self {+ muted: plain.fg(Color::DarkGray),+ key: plain.fg(Color::Cyan).add_modifier(Modifier::BOLD),+ ok: plain.fg(Color::Green),+ error: plain.fg(Color::Red),+ // A fixed foreground keeps dim cells readable on the selected row.+ selected: plain.fg(Color::Black).bg(Color::Cyan),+ border: plain.fg(Color::DarkGray),+ }+ }+}+/// This function follows https://no-color.org: any non-empty NO_COLOR value turns color off.+fn color_enabled() -> bool {+ std::env::var_os("NO_COLOR").is_none_or(|value| value.is_empty())+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum Tab {+ Overview,+}+const TABS: [Tab; 1] = [Tab::Overview];+impl Tab {+ fn name(self) -> &'static str {+ match self {+ Tab::Overview => "Overview",+ }+ }+ fn index(self) -> usize {+ self as usize+ }+}++enum Job {+ Refresh,+}+enum Done {+ Finished {+ /// The box keeps this message small; a snapshot holds every model and route total.+ snapshot: Result<Box<Snapshot>, String>,+ },+}+/// Request is a job for the worker plus the label that the status bar shows while it runs.+struct Request {+ job: Job,+ label: &'static str,+}+impl Request {+ fn refresh() -> Self {+ Self {+ job: Job::Refresh,+ label: "Refreshing",+ }+ }+}+struct Busy {+ label: &'static str,+ started: Instant,+}+struct Toast {+ text: String,+ error: bool,+ shown: Instant,+}++struct App {+ theme: Theme,+ data: Snapshot,+ tab: Tab,+ toast: Option<Toast>,+ busy: Option<Busy>,+ /// A quit request waits for the active refresh to finish.+ quit: bool,+ refreshed: Option<Instant>,+ last_refresh: Instant,+ width: u16,+}++impl App {+ fn new(theme: Theme) -> Self {+ Self {+ theme,+ data: Snapshot::default(),+ tab: Tab::Overview,+ toast: None,+ busy: None,+ quit: false,+ refreshed: None,+ last_refresh: Instant::now(),+ width: 80,+ }+ }++ /// Messages appear in the status bar.+ fn notify(&mut self, text: String, error: bool) {+ if !text.is_empty() {+ self.toast = Some(Toast {+ text,+ error,+ shown: Instant::now(),+ });+ }+ }++ fn finish(&mut self, snapshot: Result<Box<Snapshot>, String>) {+ self.busy = None;+ match snapshot {+ Ok(data) => {+ self.data = *data;+ self.refreshed = Some(Instant::now());+ }+ Err(error) => {+ // Overview keeps the error after the status message is dismissed.+ self.data.errors = vec![error.clone()];+ self.notify(error, true);+ }+ }+ }++ fn poll_results(&mut self, results: &mpsc::Receiver<Done>) -> Result<(), String> {+ loop {+ match results.try_recv() {+ Ok(Done::Finished { snapshot }) => self.finish(snapshot),+ Err(mpsc::TryRecvError::Empty) => return Ok(()),+ Err(mpsc::TryRecvError::Disconnected) => {+ return Err("The terminal operation worker stopped unexpectedly.".into());+ }+ }+ }+ }++ fn refresh_due(&self) -> bool {+ // The initial snapshot has no interval, so refreshes use 30 seconds until one succeeds.+ let seconds = match self.data.refresh_seconds {+ 0 => 30,+ seconds => seconds,+ };+ self.busy.is_none() && self.last_refresh.elapsed() >= Duration::from_secs(seconds)+ }++ fn start(&mut self, jobs: &mpsc::Sender<Job>, request: Request) -> Result<(), String> {+ if let Some(busy) = &self.busy {+ let text = format!("Wait for \"{}\" to finish.", busy.label);+ self.notify(text, true);+ return Ok(());+ }+ self.last_refresh = Instant::now();+ jobs.send(request.job).map_err(|error| error.to_string())?;+ self.busy = Some(Busy {+ label: request.label,+ started: Instant::now(),+ });+ Ok(())+ }++ fn keys(&self) -> &'static [Key] {+ &[]+ }++ fn key(&mut self, key: KeyEvent) -> Option<Request> {+ if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {+ self.quit = true;+ return None;+ }+ match key.code {+ KeyCode::Char('q') => self.quit = true,+ KeyCode::Char(digit @ '1'..='1') => {+ self.tab = TABS[digit as usize - '1' as usize];+ }+ KeyCode::Tab | KeyCode::Right => self.tab = TABS[(self.tab.index() + 1) % TABS.len()],+ KeyCode::BackTab | KeyCode::Left => {+ self.tab = TABS[(self.tab.index() + TABS.len() - 1) % TABS.len()];+ }+ KeyCode::Char('r') | KeyCode::F(5) => return Some(Request::refresh()),+ KeyCode::Esc => self.toast = None,+ _ => {}+ }+ None+ }+}++fn server_state(theme: Theme, running: bool) -> [Span<'static>; 2] {+ [+ Span::styled("● ", if running { theme.ok } else { theme.error }),+ Span::raw(if running { "running" } else { "not responding" }),+ ]+}++fn block(theme: Theme, title: &str) -> Block<'static> {+ Block::bordered()+ .border_type(BorderType::Rounded)+ .border_style(theme.border)+ .title(Span::styled(format!(" {title} "), Modifier::BOLD))+}++fn draw(frame: &mut Frame, app: &mut App) {+ // This exhaustive destructuring requires an update when Snapshot gains a field.+ let Snapshot {+ data_state: _,+ metrics: _,+ errors: _,+ refresh_seconds: _,+ } = &app.data;+ let area = frame.area();+ app.width = area.width;+ if area.width < MIN_WIDTH || area.height < MIN_HEIGHT {+ draw_too_small(frame, app.theme, area);+ return;+ }+ let [header, body, status] = Layout::vertical([+ Constraint::Length(1),+ Constraint::Fill(1),+ Constraint::Length(1),+ ])+ .areas(area);+ draw_header(frame, app, header);+ match app.tab {+ Tab::Overview => draw_overview(frame, app, body),+ }+ draw_status(frame, app, status);+}++fn draw_too_small(frame: &mut Frame, theme: Theme, area: Rect) {+ let size = |value: u16, needed: u16| {+ let style = if value < needed {+ theme.error+ } else {+ theme.ok+ };+ Span::styled(value.to_string(), style)+ };+ let text = vec![+ Line::from("Terminal too small"),+ Line::from(vec![+ size(area.width, MIN_WIDTH),+ Span::raw(" × "),+ size(area.height, MIN_HEIGHT),+ ]),+ Line::styled(format!("Needs {MIN_WIDTH} × {MIN_HEIGHT}"), theme.muted),+ ];+ let height = text.len() as u16;+ frame.render_widget(+ Paragraph::new(text).centered(),+ area.centered_vertically(Constraint::Length(height)),+ );+}++fn draw_header(frame: &mut Frame, app: &App, area: Rect) {+ let theme = app.theme;+ let titles = TABS.map(|tab| {+ Line::from(vec![+ Span::styled(format!("{} ", tab.index() + 1), theme.key),+ Span::raw(tab.name()),+ ])+ });+ // Tabs pads each title by one space on both sides and puts a divider between titles.+ let tabs_width: usize = titles.iter().map(|title| title.width() + 3).sum();+ let running = app.data.metrics.running;+ let mut status = server_state(theme, running).to_vec();+ let updated = match app.refreshed {+ Some(time) => format!(" · updated {}s ago ", time.elapsed().as_secs()),+ None => " · no data yet ".into(),+ };+ let url = format!(" · {}", app.data.metrics.server_url);+ // Narrow terminals drop the URL first, then the update time, so the tabs stay readable.+ let room = usize::from(area.width).saturating_sub(tabs_width);+ let base = status.iter().map(Span::width).sum::<usize>();+ if base > room {+ status[1] = Span::raw(if running { "up" } else { "down" });+ }+ if !app.data.metrics.server_url.is_empty()+ && base + url.chars().count() + updated.chars().count() <= room+ {+ status.push(Span::styled(url, theme.muted));+ }+ if base + updated.chars().count() <= room {+ status.push(Span::styled(updated, theme.muted));+ }+ let status = Line::from(status).right_aligned();+ let [tabs, status_area] = Layout::horizontal([+ Constraint::Fill(1),+ Constraint::Length(status.width() as u16),+ ])+ .areas(area);+ frame.render_widget(+ Tabs::new(titles)+ .select(app.tab.index())+ .highlight_style(theme.selected)+ .divider(Span::styled("│", theme.border)),+ tabs,+ );+ frame.render_widget(Paragraph::new(status), status_area);+}++fn draw_overview(frame: &mut Frame, app: &App, area: Rect) {+ let theme = app.theme;+ let data = &app.data;+ let mut server = vec![+ Line::from(server_state(theme, data.metrics.running).to_vec()),+ Line::styled(data.metrics.server_url.as_str(), theme.muted),+ ];+ if let Some(reason) = data.data_state.health["reason"].as_str() {+ server.push(Line::styled(reason.to_string(), theme.muted));+ }+ for error in &data.errors {+ server.push(Line::styled(error.as_str(), theme.error));+ }+ if data.data_state.usage.state == Availability::Available {+ server.push(Line::from(format!(+ "Today: {} calls · {} tokens",+ data.metrics.today.requests, data.metrics.today.tokens+ )));+ server.push(Line::from(format!(+ "Past 7 days: {} calls · {} tokens",+ data.metrics.week.requests, data.metrics.week.tokens+ )));+ }+ frame.render_widget(+ Paragraph::new(server)+ .wrap(Wrap { trim: false })+ .block(block(theme, "Server").padding(Padding::horizontal(1))),+ area,+ );+}++fn draw_status(frame: &mut Frame, app: &App, area: Rect) {+ let theme = app.theme;+ let left = if let Some(busy) = &app.busy {+ let frame_index = busy.started.elapsed().as_millis() / 100 % SPINNER.len() as u128;+ let mut spans = vec![+ Span::styled(format!(" {} ", SPINNER[frame_index as usize]), theme.key),+ Span::raw(format!("{}…", busy.label)),+ ];+ if app.quit {+ spans.push(Span::styled(" quitting when done", theme.muted));+ }+ Line::from(spans)+ } else if let Some(toast) = &app.toast {+ let style = if toast.error { theme.error } else { theme.ok };+ Line::from(vec![+ Span::styled(if toast.error { " ✗ " } else { " ✓ " }, style),+ Span::styled(toast.text.clone(), style),+ ])+ } else {+ Line::default()+ };+ let room = usize::from(area.width).saturating_sub(left.width() + 2);+ let global = true;+ let hints = fit_keys(theme, app.keys(), global, room);+ let [left_area, right_area] =+ Layout::horizontal([Constraint::Length(left.width() as u16), Constraint::Fill(1)])+ .areas(area);+ frame.render_widget(Paragraph::new(left), left_area);+ frame.render_widget(Paragraph::new(hints.right_aligned()), right_area);+}++/// This function lists the page's keys, then the global keys, and stops before a hint would be+/// cut.+fn fit_keys(theme: Theme, keys: &[Key], global: bool, room: usize) -> Line<'static> {+ let hint = |key: &'static str, label: &str| {+ [+ Span::styled(key, theme.key),+ Span::styled(format!(" {label} "), theme.muted),+ ]+ };+ let mut spans = Vec::new();+ let mut used = 0;+ let globals = if global { GLOBAL_KEYS } else { &[] };+ for (key, label, _) in keys.iter().chain(globals) {+ let width = key.chars().count() + label.chars().count() + 3;+ if used + width > room {+ break;+ }+ used += width;+ spans.extend(hint(key, label));+ }+ Line::from(spans)+}++struct PasteMode;+impl Drop for PasteMode {+ fn drop(&mut self) {+ let _ = ratatui::crossterm::execute!(std::io::stdout(), event::DisableBracketedPaste);+ }+}++pub fn run(mut controller: Controller) -> Result<(), String> {+ let mut app = App::new(Theme::new(color_enabled()));+ ratatui::crossterm::execute!(std::io::stdout(), event::EnableBracketedPaste)+ .map_err(|e| e.to_string())?;+ let _paste_mode = PasteMode;+ let (jobs, inbox) = mpsc::channel::<Job>();+ let (done, results) = mpsc::channel::<Done>();+ // One worker owns the controller while the terminal continues to draw and read input.+ let worker = thread::spawn(move || {+ while let Ok(Job::Refresh) = inbox.recv() {+ let finished = Done::Finished {+ snapshot: controller.snapshot().map(Box::new),+ };+ if done.send(finished).is_err() {+ break;+ }+ }+ });+ let result = ratatui::run(|terminal| -> Result<(), String> {+ // The initial refresh starts after terminal setup so a blocked read cannot delay drawing.+ app.start(&jobs, Request::refresh())?;+ loop {+ app.poll_results(&results)?;+ if app.quit && app.busy.is_none() {+ return Ok(());+ }+ if app+ .toast+ .as_ref()+ .is_some_and(|toast| !toast.error && toast.shown.elapsed() > TOAST_TIME)+ {+ app.toast = None;+ }+ terminal+ .draw(|frame| draw(frame, &mut app))+ .map_err(|e| e.to_string())?;+ // The spinner needs a faster redraw only while a job runs.+ let wait = Duration::from_millis(if app.busy.is_some() { 100 } else { 250 });+ if event::poll(wait).map_err(|e| e.to_string())? {+ match event::read().map_err(|e| e.to_string())? {+ Event::Key(key) if key.kind == KeyEventKind::Press => {+ if let Some(request) = app.key(key) {+ app.start(&jobs, request)?;+ }+ }+ _ => {}+ }+ }+ if !app.quit && app.refresh_due() {+ app.start(&jobs, Request::refresh())?;+ }+ }+ });+ drop(jobs);+ worker+ .join()+ .map_err(|_| "The terminal operation worker stopped unexpectedly.".to_string())?;+ if result.is_err() {+ let _ = ratatui::try_restore();+ }+ result+}++#[cfg(test)]+mod tests {+ use super::{App, KeyCode, KeyEvent, KeyModifiers, Request, Theme, draw, mpsc};+ use ratatui::{Terminal, backend::TestBackend};++ // Esc dismisses the status message while Overview keeps the refresh error.+ #[test]+ fn refresh_errors_remain_in_overview_after_dismissing_the_toast() {+ let mut app = App::new(Theme::new(false));+ app.finish(Err("Could not read settings.".into()));+ app.key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));+ let mut terminal = Terminal::new(TestBackend::new(80, 24)).expect("terminal");+ terminal.draw(|frame| draw(frame, &mut app)).expect("draw");+ let text: String = terminal+ .backend()+ .buffer()+ .content+ .iter()+ .map(|cell| cell.symbol())+ .collect();+ assert!(text.contains("Could not read settings."), "{text}");+ }++ // An empty queue can still receive a result; a disconnected queue cannot finish the refresh.+ #[test]+ fn worker_disconnect_returns_an_error_with_a_refresh_in_flight() {+ let mut app = App::new(Theme::new(false));+ let (jobs, _inbox) = mpsc::channel();+ app.start(&jobs, Request::refresh()).expect("refresh");+ let (done, results) = mpsc::channel();+ assert!(app.poll_results(&results).is_ok());+ drop(done);+ assert_eq!(+ app.poll_results(&results),+ Err("The terminal operation worker stopped unexpectedly.".into())+ );+ }+}diff --git a/crates/switchyard-desktop/src/windows.rs b/crates/switchyard-desktop/src/windows.rsnew file mode 100644index 000000000..f939f3a16--- /dev/null+++ b/crates/switchyard-desktop/src/windows.rs@@ -0,0 +1,30 @@+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+// SPDX-License-Identifier: Apache-2.0++pub fn attach_console() {+ unsafe {+ windows_console(false);+ }+}+pub fn allocate_console() {+ unsafe {+ windows_console(true);+ }+}+unsafe fn windows_console(allocate: bool) {+ unsafe extern "system" {+ fn AllocConsole() -> i32;+ fn FreeConsole() -> i32;+ fn AttachConsole(pid: u32) -> i32;+ }+ unsafe {+ if allocate {+ // The app detaches first because AllocConsole fails while a console is attached.+ // A separate console keeps the parent shell from reading the terminal app's input.+ FreeConsole();+ AllocConsole();+ } else {+ AttachConsole(u32::MAX);+ }+ }+}