1#![expect(
2 clippy::print_stdout,
3 reason = "`orch ui` writes the address it opens to the terminal"
4)]
5
6use std::process::Command;
9use std::sync::Arc;
10use std::time::Duration;
11
12use tokio::time::Instant;
13
14use futures::StreamExt;
15use tokio::sync::broadcast;
16use tokio::{signal, time};
17use tokio_tungstenite::connect_async;
18use tokio_tungstenite::tungstenite::Message;
19
20use crate::cli;
21use crate::cli::service;
22use crate::engine::tasks::events::{TaskEvent, read_ws_credentials};
23use crate::ui;
24
25const RELAY_RETRY: Duration = Duration::from_secs(3);
26const SERVICE_WAIT: Duration = Duration::from_secs(30);
27
28pub async fn open(print: bool, dev: bool) -> anyhow::Result<()> {
29 if dev {
30 return serve_dev(print).await;
31 }
32
33 if let Some(endpoint) = ui::endpoint().await {
34 return launch(&endpoint, print).await;
35 }
36
37 println!("Starting the orch service");
39 service::start()?;
40 let deadline = Instant::now() + SERVICE_WAIT;
41 while Instant::now() < deadline {
42 if let Some(endpoint) = ui::endpoint().await {
43 return launch(&endpoint, print).await;
44 }
45
46 time::sleep(Duration::from_millis(500)).await;
47 }
48
49 anyhow::bail!("the orch service did not start its web UI. Check `orch log`")
50}
51
52async fn sign_in_url(endpoint: &ui::Endpoint) -> anyhow::Result<String> {
54 let url = format!("http://127.0.0.1:{}/", endpoint.port);
55 let code: serde_json::Value = reqwest::Client::new()
56 .post(format!("{url}login-code"))
57 .bearer_auth(&endpoint.token)
58 .send()
59 .await?
60 .error_for_status()?
61 .json()
62 .await?;
63 let code = code
64 .get("code")
65 .and_then(|c| c.as_str())
66 .ok_or_else(|| anyhow::anyhow!("the orch service sent no sign-in code"))?;
67 Ok(format!("{url}?code={code}"))
68}
69
70async fn launch(endpoint: &ui::Endpoint, print: bool) -> anyhow::Result<()> {
71 let url = format!("http://127.0.0.1:{}/", endpoint.port);
72 let login = sign_in_url(endpoint).await?;
73 if print {
74 println!("{login}");
75 return Ok(());
76 }
77
78 let opener = if cfg!(target_os = "macos") {
79 "open"
80 } else {
81 "xdg-open"
82 };
83 let status = Command::new(opener).arg(&login).status()?;
84 if !status.success() {
85 anyhow::bail!("{opener} failed, run `orch ui --print` and open the address yourself");
86 }
87
88 println!("Opened {url}");
89 Ok(())
90}
91
92async fn serve_dev(print: bool) -> anyhow::Result<()> {
94 let store = Arc::new(cli::init_store().await?);
95 let (tx, _) = broadcast::channel(256);
96 tokio::spawn(relay_events(tx.clone()));
97 let endpoint = ui::serve_on(store, tx).await?;
98 launch(&endpoint, print).await?;
99 println!("Serving the web UI from this build. Ctrl+C to stop");
100 signal::ctrl_c().await?;
101 Ok(())
102}
103
104async fn relay_events(tx: broadcast::Sender<TaskEvent>) {
105 loop {
106 if let Ok((port, token)) = read_ws_credentials() {
107 let url = format!(
108 "ws://127.0.0.1:{port}/events?token={}",
109 urlencoding::encode(&token)
110 );
111 if let Ok((ws, _)) = connect_async(&url).await {
112 let (_write, mut read) = ws.split();
113 while let Some(Ok(msg)) = read.next().await {
114 if let Message::Text(text) = msg
115 && let Ok(event) = serde_json::from_str::<TaskEvent>(&text)
116 {
117 let _ = tx.send(event);
118 }
119 }
120 }
121 }
122
123 time::sleep(RELAY_RETRY).await;
124 }
125}