Skip to main content

rigspark_cli/
gui_launcher.rs

1use std::{
2    fmt,
3    future::{Future, pending, ready},
4    io::{self, Write},
5    path::{Path, PathBuf},
6    process::{ExitStatus, Stdio},
7    time::Duration,
8};
9use tokio::{
10    io::{AsyncRead, AsyncReadExt},
11    process::{Child, Command},
12    time::timeout,
13};
14
15const STARTUP_TIMEOUT: Duration = Duration::from_secs(10);
16const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(3);
17const PRESENTATION_TIMEOUT: Duration = Duration::from_secs(5);
18const READINESS_LIMIT: usize = 128;
19
20#[derive(Clone, Debug, PartialEq, Eq)]
21pub struct GuiOptions {
22    port: u16,
23    no_open: bool,
24    harness: Option<String>,
25    json: bool,
26}
27
28impl GuiOptions {
29    pub fn new(port: Option<&str>, no_open: bool) -> Result<Self, GuiLaunchError> {
30        let port = port.unwrap_or("4000");
31        if port.is_empty() || !port.bytes().all(|byte| byte.is_ascii_digit()) {
32            return Err(GuiLaunchError::InvalidPort);
33        }
34        let port = port
35            .parse::<u16>()
36            .ok()
37            .filter(|port| *port != 0)
38            .ok_or(GuiLaunchError::InvalidPort)?;
39        Ok(Self {
40            port,
41            no_open,
42            harness: None,
43            json: false,
44        })
45    }
46
47    pub fn with_harness(mut self, harness: Option<&str>) -> Result<Self, GuiLaunchError> {
48        self.harness = harness
49            .map(|name| {
50                let name = name.trim();
51                if !valid_harness(name) {
52                    return Err(GuiLaunchError::InvalidHarness);
53                }
54                Ok(name.to_owned())
55            })
56            .transpose()?;
57        Ok(self)
58    }
59
60    pub fn with_json(mut self, json: bool) -> Self {
61        self.json = json;
62        self
63    }
64}
65
66fn valid_harness(name: &str) -> bool {
67    ["local", "claude", "openai", "openai-compatible", "opencode"].contains(&name)
68}
69
70#[derive(Clone, Debug, PartialEq, Eq)]
71pub struct LaunchSpec {
72    executable: PathBuf,
73    args: Vec<String>,
74    origin: String,
75    port: u16,
76    harness: Option<String>,
77    open_browser: bool,
78}
79
80impl LaunchSpec {
81    pub fn new(current_exe: &Path, options: GuiOptions) -> Result<Self, GuiLaunchError> {
82        let parent = current_exe
83            .parent()
84            .filter(|_| current_exe.is_absolute() && current_exe.file_name().is_some())
85            .ok_or(GuiLaunchError::ExecutableLocation)?;
86        let mut args = vec![
87            "--port".into(),
88            options.port.to_string(),
89            "--startup-json".into(),
90        ];
91        if let Some(harness) = &options.harness {
92            args.extend(["--harness".into(), harness.clone()]);
93        }
94        Ok(Self {
95            executable: parent.join(if cfg!(windows) {
96                "rigspark-gui.exe"
97            } else {
98                "rigspark-gui"
99            }),
100            args,
101            origin: format!("http://127.0.0.1:{}", options.port),
102            port: options.port,
103            harness: options.harness,
104            open_browser: !options.no_open && !options.json,
105        })
106    }
107
108    pub fn executable(&self) -> &Path {
109        &self.executable
110    }
111    pub fn args(&self) -> &[String] {
112        &self.args
113    }
114    pub fn origin(&self) -> &str {
115        &self.origin
116    }
117    pub fn open_browser(&self) -> bool {
118        self.open_browser
119    }
120}
121
122#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
123#[serde(deny_unknown_fields)]
124pub struct GuiReady {
125    url: String,
126    harness: String,
127    port: u16,
128}
129
130impl GuiReady {
131    pub fn url(&self) -> &str {
132        &self.url
133    }
134
135    pub fn write_startup(&self, writer: &mut impl Write, json: bool) -> io::Result<()> {
136        if json {
137            serde_json::to_writer(&mut *writer, self)?;
138            writeln!(writer)?;
139        } else {
140            writeln!(writer, "rigspark GUI listening at {}", self.url)?;
141        }
142        writer.flush()
143    }
144}
145
146#[derive(Clone, Copy, Debug, PartialEq, Eq)]
147pub enum GuiLaunchError {
148    InvalidPort,
149    InvalidHarness,
150    ExecutableLocation,
151    MissingExecutable,
152    Spawn,
153    Wait,
154    Shutdown,
155    Signals,
156    StartupTimeout,
157    ExitedBeforeReady,
158    InvalidReadiness,
159    Presentation,
160}
161
162impl GuiLaunchError {
163    pub fn message(&self) -> &'static str {
164        match self {
165            Self::InvalidPort => "invalid --port (expected an integer in 1..65535)",
166            Self::InvalidHarness => {
167                "invalid --harness (expected local, claude, openai, openai-compatible, or opencode)"
168            }
169            Self::ExecutableLocation => "cannot locate the installed CLI executable",
170            Self::MissingExecutable => {
171                "installed rigspark-gui executable is missing; reinstall the complete native distribution"
172            }
173            Self::Spawn => {
174                "cannot execute the installed rigspark-gui binary; check the native installation and executable permissions"
175            }
176            Self::Wait => "cannot observe the GUI process",
177            Self::Shutdown => "GUI shutdown failed or timed out",
178            Self::Signals => "cannot monitor shutdown signals",
179            Self::StartupTimeout => "GUI startup timed out",
180            Self::ExitedBeforeReady => "GUI exited before reporting readiness",
181            Self::InvalidReadiness => "GUI reported an invalid startup record",
182            Self::Presentation => "cannot present the GUI address",
183        }
184    }
185}
186
187impl fmt::Display for GuiLaunchError {
188    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
189        write!(formatter, "gui: {}", self.message())
190    }
191}
192
193impl std::error::Error for GuiLaunchError {}
194
195#[derive(Clone, Copy, Debug, PartialEq, Eq)]
196pub enum GuiSignal {
197    Interrupt,
198    Terminate,
199    Hangup,
200}
201
202impl GuiSignal {
203    pub fn exit_code(self) -> i32 {
204        match self {
205            Self::Interrupt => 130,
206            Self::Terminate => 143,
207            Self::Hangup => 129,
208        }
209    }
210}
211
212pub async fn run_gui(options: GuiOptions) -> Result<i32, GuiLaunchError> {
213    #[cfg(unix)]
214    let shutdown = {
215        use tokio::signal::unix::{SignalKind, signal};
216        let mut interrupt = signal(SignalKind::interrupt()).map_err(|_| GuiLaunchError::Signals)?;
217        let mut terminate = signal(SignalKind::terminate()).map_err(|_| GuiLaunchError::Signals)?;
218        let mut hangup = signal(SignalKind::hangup()).map_err(|_| GuiLaunchError::Signals)?;
219        async move {
220            let signal = tokio::select! {
221                event = interrupt.recv() => event.map(|()| GuiSignal::Interrupt),
222                event = terminate.recv() => event.map(|()| GuiSignal::Terminate),
223                event = hangup.recv() => event.map(|()| GuiSignal::Hangup),
224            };
225            signal.ok_or_else(|| io::Error::other("signal stream closed"))
226        }
227    };
228    #[cfg(not(unix))]
229    let shutdown = async {
230        tokio::signal::ctrl_c().await?;
231        Ok(GuiSignal::Interrupt)
232    };
233    let executable = std::env::current_exe().map_err(|_| GuiLaunchError::ExecutableLocation)?;
234    let json = options.json;
235    let spec = LaunchSpec::new(&executable, options)?;
236    let mut presented = false;
237    let code = launch_with(&spec, shutdown, |ready, open| {
238        let ready = ready.clone();
239        let presented = &mut presented;
240        async move {
241            ready.write_startup(&mut io::stdout(), json)?;
242            *presented = true;
243            if open && !open_browser(ready.url()).await {
244                let _ = writeln!(
245                    io::stderr(),
246                    "gui: could not open the browser automatically"
247                );
248            }
249            Ok(())
250        }
251    })
252    .await?;
253    if !presented && ![0, 129, 130, 143].contains(&code) {
254        writeln!(io::stderr(), "{}", GuiLaunchError::ExitedBeforeReady)
255            .map_err(|_| GuiLaunchError::Presentation)?;
256    }
257    if presented && [0, 130, 143].contains(&code) {
258        writeln!(io::stdout(), "Stopped.").map_err(|_| GuiLaunchError::Presentation)?;
259    }
260    Ok(code)
261}
262
263pub async fn launch_with<Shutdown, Present, Presentation>(
264    spec: &LaunchSpec,
265    shutdown: Shutdown,
266    present: Present,
267) -> Result<i32, GuiLaunchError>
268where
269    Shutdown: Future<Output = io::Result<GuiSignal>>,
270    Present: FnOnce(&GuiReady, bool) -> Presentation,
271    Presentation: Future<Output = io::Result<()>>,
272{
273    tokio::pin!(shutdown);
274    tokio::select! {
275        biased;
276        signal = &mut shutdown => return signal.map(GuiSignal::exit_code).map_err(|_| GuiLaunchError::Signals),
277        () = ready(()) => (),
278    }
279    let metadata = tokio::fs::symlink_metadata(spec.executable())
280        .await
281        .map_err(|error| {
282            if error.kind() == io::ErrorKind::NotFound {
283                GuiLaunchError::MissingExecutable
284            } else {
285                GuiLaunchError::Spawn
286            }
287        })?;
288    if !metadata.is_file() {
289        return Err(GuiLaunchError::Spawn);
290    }
291    let mut command = Command::new(spec.executable());
292    command
293        .args(spec.args())
294        .stdin(Stdio::null())
295        .stdout(Stdio::piped())
296        .stderr(Stdio::null())
297        .kill_on_drop(true);
298    #[cfg(unix)]
299    command.process_group(0);
300    let mut child = command.spawn().map_err(|_| GuiLaunchError::Spawn)?;
301    let stdout = child.stdout.take().ok_or(GuiLaunchError::Wait)?;
302    let result = tokio::select! {
303        biased;
304        signal = &mut shutdown => signal.map(GuiSignal::exit_code).map_err(|_| GuiLaunchError::Signals),
305        result = supervise(&mut child, stdout, spec, present) => result,
306    };
307    stop(&mut child).await?;
308    result
309}
310
311async fn supervise<Present, Presentation>(
312    child: &mut Child,
313    mut stdout: tokio::process::ChildStdout,
314    spec: &LaunchSpec,
315    present: Present,
316) -> Result<i32, GuiLaunchError>
317where
318    Present: FnOnce(&GuiReady, bool) -> Presentation,
319    Presentation: Future<Output = io::Result<()>>,
320{
321    let readiness = tokio::select! {
322        biased;
323        status = child.wait() => return before_ready(status),
324        result = timeout(STARTUP_TIMEOUT, read_readiness(&mut stdout, spec)) => result.map_err(|_| GuiLaunchError::StartupTimeout)?,
325    };
326    if readiness == Err(GuiLaunchError::ExitedBeforeReady) {
327        return before_ready(
328            timeout(STARTUP_TIMEOUT, child.wait())
329                .await
330                .map_err(|_| GuiLaunchError::StartupTimeout)?,
331        );
332    }
333    let readiness = readiness?;
334    let output = async {
335        timeout(
336            PRESENTATION_TIMEOUT,
337            present(&readiness, spec.open_browser()),
338        )
339        .await
340        .map_err(|_| GuiLaunchError::Presentation)?
341        .map_err(|_| GuiLaunchError::Presentation)?;
342        tokio::io::copy(&mut stdout, &mut tokio::io::sink())
343            .await
344            .map_err(|_| GuiLaunchError::Wait)?;
345        pending::<Result<i32, GuiLaunchError>>().await
346    };
347    tokio::select! {
348        result = output => result,
349        status = child.wait() => status.map(exit_code).map_err(|_| GuiLaunchError::Wait),
350    }
351}
352
353async fn read_readiness(
354    reader: &mut (impl AsyncRead + Unpin),
355    spec: &LaunchSpec,
356) -> Result<GuiReady, GuiLaunchError> {
357    let mut line = Vec::with_capacity(READINESS_LIMIT);
358    for _ in 0..READINESS_LIMIT {
359        let mut byte = [0];
360        if reader
361            .read(&mut byte)
362            .await
363            .map_err(|_| GuiLaunchError::Wait)?
364            == 0
365        {
366            return Err(if line.is_empty() {
367                GuiLaunchError::ExitedBeforeReady
368            } else {
369                GuiLaunchError::InvalidReadiness
370            });
371        }
372        if byte[0] == b'\n' {
373            if line.last() == Some(&b'\r') {
374                line.pop();
375            }
376            let ready: GuiReady =
377                serde_json::from_slice(&line).map_err(|_| GuiLaunchError::InvalidReadiness)?;
378            if ready.url != spec.origin()
379                || ready.port != spec.port
380                || !valid_harness(&ready.harness)
381                || spec
382                    .harness
383                    .as_ref()
384                    .is_some_and(|harness| harness != &ready.harness)
385            {
386                return Err(GuiLaunchError::InvalidReadiness);
387            }
388            return Ok(ready);
389        }
390        line.push(byte[0]);
391    }
392    Err(GuiLaunchError::InvalidReadiness)
393}
394
395fn before_ready(status: io::Result<ExitStatus>) -> Result<i32, GuiLaunchError> {
396    let code = status.map(exit_code).map_err(|_| GuiLaunchError::Wait)?;
397    if code == 0 {
398        Err(GuiLaunchError::ExitedBeforeReady)
399    } else {
400        Ok(code)
401    }
402}
403
404fn exit_code(status: ExitStatus) -> i32 {
405    if let Some(code) = status.code() {
406        return code;
407    }
408    #[cfg(unix)]
409    {
410        use std::os::unix::process::ExitStatusExt;
411        if let Some(signal) = status.signal() {
412            return 128 + signal;
413        }
414    }
415    1
416}
417
418async fn stop(child: &mut Child) -> Result<(), GuiLaunchError> {
419    if child
420        .try_wait()
421        .map_err(|_| GuiLaunchError::Shutdown)?
422        .is_some()
423    {
424        return Ok(());
425    }
426    #[cfg(unix)]
427    if let Some(pid) = child.id() {
428        let mut signal = Command::new("/bin/kill");
429        signal
430            .args(["-s", "INT", &pid.to_string()])
431            .stdin(Stdio::null())
432            .stdout(Stdio::null())
433            .stderr(Stdio::null())
434            .kill_on_drop(true);
435        if matches!(timeout(Duration::from_secs(1), signal.status()).await, Ok(Ok(status)) if status.success())
436            && let Ok(result) = timeout(SHUTDOWN_TIMEOUT, child.wait()).await
437        {
438            return result.map(|_| ()).map_err(|_| GuiLaunchError::Shutdown);
439        }
440    }
441    child.start_kill().map_err(|_| GuiLaunchError::Shutdown)?;
442    timeout(SHUTDOWN_TIMEOUT, child.wait())
443        .await
444        .map_err(|_| GuiLaunchError::Shutdown)?
445        .map(|_| ())
446        .map_err(|_| GuiLaunchError::Shutdown)
447}
448
449async fn open_browser(origin: &str) -> bool {
450    #[cfg(target_os = "macos")]
451    let mut command = Command::new("/usr/bin/open");
452    #[cfg(all(unix, not(target_os = "macos")))]
453    let mut command = Command::new("/usr/bin/xdg-open");
454    #[cfg(windows)]
455    let mut command = {
456        let Some(root) = std::env::var_os("SystemRoot")
457            .map(PathBuf::from)
458            .filter(|root| root.is_absolute())
459        else {
460            return false;
461        };
462        let mut command = Command::new(root.join("System32/rundll32.exe"));
463        command.arg("url.dll,FileProtocolHandler");
464        command
465    };
466    #[cfg(not(any(unix, windows)))]
467    {
468        let _ = origin;
469        false
470    }
471    #[cfg(any(unix, windows))]
472    {
473        let Ok(mut child) = command
474            .arg(origin)
475            .stdin(Stdio::null())
476            .stdout(Stdio::null())
477            .stderr(Stdio::null())
478            .kill_on_drop(true)
479            .spawn()
480        else {
481            return false;
482        };
483        match timeout(Duration::from_secs(2), child.wait()).await {
484            Ok(Ok(status)) => status.success(),
485            _ => {
486                let _ = child.start_kill();
487                let _ = timeout(Duration::from_secs(1), child.wait()).await;
488                false
489            }
490        }
491    }
492}