Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t.sh
2,263 linesCodeBlameRaw
1//! The runner in the app: g1t's self-hosted runner, started for the
2//! signed-in person when g1t opens and stopped when it quits, so their
3//! computer runs their workspace's `runs-on: self-hosted` jobs with
4//! nothing to install, register or start by hand
5//! (docs.g1t.sh/guides/desktop/#the-runner).
6//!
7//! - **When.** On by default; settings turn it off ("Run jobs on this
8//! computer while g1t is open"), and Stop in settings or the tray stops
9//! it until Start, or until g1t starts again. It starts a few seconds
10//! after the window, never before.
11//! - **How.** The backend settings choose (backend.rs): Sandboxed, the
12//! default, where nothing a job does reaches this computer; Docker; or
13//! directly on this computer. The two that are not sandboxes are only
14//! ever chosen by the person, and nothing falls back to them. Sandboxed
15//! is `g1t-runner sandbox` (launcher.rs) on every OS: `up` a few seconds
16//! after the window, `status` every few seconds while it runs, `down`
17//! as g1t quits, and `down --drain` when another backend is chosen.
18//! Each kind of job it runs (Linux jobs, Windows jobs) starts and stops
19//! on its own too: settings keep which are on (`runnerCapabilities`),
20//! every `up` names them (`--only`), and stopping one is `down --only`
21//! it, which leaves the other running. One that should run and doesn't
22//! while the other runs is tried again by itself, every few minutes, and
23//! every five while the newest release has no sandbox images.
24//! - **Registering.** The first time, and when the workspace or backend
25//! changes, the app needs a registration token for the workspace. Only
26//! the site can make one, for an owner who is signed in: the app asks
27//! the site's page (`g1t-runner-wanted`), the page asks the server
28//! (`POST /-/desktop/runner-token`) and hands the token to the app
29//! (`runner_register` in bridge.rs), which gives it to `g1t-runner`
30//! once: in its environment, or to the sandbox's first `up`. It is never
31//! shown or written to the log. The registration is kept
32//! (registration.json and the runner's own folder; the sandbox keeps its
33//! own, and sandbox-registration.json says whose it is) and used on
34//! every later start.
35//! - **Up to date.** Soon after it starts and every hour, and when the
36//! person asks ("Check for runner updates"), the app looks for a newer
37//! release on a thread of its own: its manifest only when g1t's release
38//! key signed it (native.rs), its program only when its SHA-256 is the
39//! manifest's. What it finds waits, downloaded, until each kind of job
40//! is idle, and goes in kind by kind, never in the middle of a job: the
41//! sandbox's Linux jobs take its image (`sandbox update`, which drains
42//! them itself) once they have no job; its Windows jobs, whose runner is
43//! the program itself, are drained (`down --only windows --drain`), the
44//! program is replaced, and they start again; a runner in Docker or on
45//! this computer is stopped between jobs and started on the new one.
46//! "Download updates by themselves" off, it looks only when asked.
47//! - **Seen.** What it is doing, and when it is not running why and how to
48//! fix it (diagnosis.rs), is in the title bar's chip, the Runner window
49//! (launcher/runner.html), the tray, a line in settings, and on the
50//! site's Runners page (`g1t-runner-status`), read from what its log says
51//! (log.rs), or for the sandbox from its status. The whole log is kept
52//! in `runner/runner.log`.
53//!
54//! All of it runs on a thread of its own, which owns the runner's process
55//! and is told what happened through one channel.
56
57mod backend;
58pub mod diagnosis;
59mod launcher;
60mod log;
61mod native;
62
63use std::collections::VecDeque;
64use std::fs::{File, OpenOptions};
65use std::io::{BufRead, BufReader, Read, Write};
66use std::path::PathBuf;
67use std::process::{Child, Stdio};
68use std::sync::Mutex;
69use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
70use std::time::{Duration, Instant, SystemTime};
71
72use serde::{Deserialize, Serialize};
73use tauri::{AppHandle, Emitter, EventTarget, Manager};
74use url::Url;
75
76pub use backend::Backend;
77use backend::{Engine, Missing};
78use diagnosis::{Code, Diagnosis, Facts};
79use launcher::{Down, State, Status};
80use native::Fault;
81
82use crate::{config, frame, settings, tray};
83
84/// What settings, the tray and the site listen for: the runner's status changed.
85pub const STATUS_EVENT: &str = "g1t-runner-status";
86/// What the site's page listens for: the app needs a registration token for a workspace.
87pub const WANTED_EVENT: &str = "g1t-runner-wanted";
88
89/// How long after the window the runner starts.
90const AFTER_START: Duration = Duration::from_secs(4);
91/// How often the thread looks at the runner when nothing has happened.
92const TICK: Duration = Duration::from_secs(5);
93/// How long after starting the first look for an update is, then how often.
94const FIRST_UPDATE: Duration = Duration::from_secs(90);
95const UPDATE_EVERY: Duration = Duration::from_secs(60 * 60);
96/// How often a backend that cannot start is looked at again.
97const LOOK_AGAIN: Duration = Duration::from_secs(30);
98/// How long the app waits for the site to hand over a token before asking again.
99const ASK_AGAIN: Duration = Duration::from_secs(60);
100/// The longest the app waits before starting a runner that stopped by itself again.
101const MOST_BACKOFF: Duration = Duration::from_secs(10 * 60);
102/// The runner says when a poll fails, and nothing when one works: this
103/// long without another failure, it is back (its longest wait is 60s).
104const BACK_ONLINE: Duration = Duration::from_secs(75);
105/// The runner's log is started over when it is bigger than this.
106const LOG_LIMIT: u64 = 5 * 1024 * 1024;
107/// The last lines of the log settings show.
108const TAIL: usize = 40;
109
110/// A workspace the site says the person may add runners to: those they own.
111#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
112pub struct Offered {
113 pub slug: String,
114 #[serde(default)]
115 pub name: Option<String>,
116}
117
118/// What the runner is doing, as the thread last said.
119#[derive(Clone, Debug, Default, PartialEq)]
120struct Now {
121 code: Code,
122 detail: Option<String>,
123 exit_code: Option<i32>,
124 wait_seconds: Option<u64>,
125 job: Option<String>,
126 version: Option<String>,
127 /// What the sandbox says to do, for a cause in its own words.
128 fix: Option<String>,
129 /// How the sandbox is, while jobs run sandboxed.
130 sandbox: Option<Status>,
131 /// A sandbox run is up, or on its way.
132 live: bool,
133 /// The kinds of job a launcher command is starting now.
134 starting: Vec<String>,
135 /// How far the sandbox's image has downloaded, while it does.
136 download: Option<launcher::Download>,
137}
138
139/// How the runner's updates stand, as the thread last said.
140#[derive(Clone, Debug, Default, PartialEq)]
141struct Updates {
142 /// When the releases last answered.
143 checked_at: Option<SystemTime>,
144 checking: bool,
145 /// A newer version, downloaded and checked, waiting.
146 ready: Option<String>,
147 /// Its program is still to be put in place.
148 program: bool,
149 /// The sandbox's image is still to take it.
150 image: bool,
151 /// The kinds of job taking it now.
152 installing: Vec<String>,
153}
154
155/// What a look at the releases found.
156struct Found {
157 version: String,
158 /// Newer than the program here.
159 newer: bool,
160 /// Its program, downloaded and checked: None when it isn't newer, or is
161 /// already waiting.
162 program: Option<Vec<u8>>,
163 /// The release has the sandbox's images.
164 images: bool,
165}
166
167/// What the site last said about the person.
168#[derive(Clone, Debug, Default, PartialEq)]
169struct Site {
170 /// Unknown until the site's first page loads.
171 signed_in: Option<bool>,
172 owned: Vec<Offered>,
173 current: Option<String>,
174}
175
176/// What the rest of the app shares with the thread.
177#[derive(Default)]
178pub struct Shared {
179 now: Mutex<Now>,
180 /// The workspace a token is wanted for.
181 wanted: Mutex<Option<String>>,
182 site: Mutex<Site>,
183 /// Stopped by the person until Start, or until g1t starts again.
184 paused: Mutex<bool>,
185 tail: Mutex<VecDeque<String>>,
186 tx: Mutex<Option<Sender<Ask>>>,
187 updates: Mutex<Updates>,
188}
189
190/// What settings, the tray and the site are shown.
191#[derive(Clone, Debug, PartialEq, Serialize)]
192#[serde(rename_all = "camelCase")]
193pub struct View {
194 pub diagnosis: Diagnosis,
195 /// What the site says of this computer once g1t is closed on it.
196 pub closed: Diagnosis,
197 pub running: bool,
198 pub version: Option<String>,
199 pub backend: Backend,
200 pub workspace: Option<String>,
201 /// The workspaces it may run for, from the site.
202 pub workspaces: Vec<Offered>,
203 /// The setting: run jobs while g1t is open.
204 pub enabled: bool,
205 pub paused: bool,
206 /// The workspace's Runners page.
207 pub link: Option<String>,
208 /// This computer's name, which the runner has on g1t.
209 pub machine: String,
210 pub platform: String,
211 /// The last lines of the runner's log.
212 pub log: Vec<String>,
213 /// In a few words, for the title bar's chip.
214 pub chip: diagnosis::Chip,
215}
216
217/// What the thread is told.
218enum Ask {
219 /// Something changed: settings, Start or Stop, Retry.
220 Look,
221 /// A kind of job was started: start what should run now, stopping nothing.
222 Soon,
223 Retry,
224 /// "Check for runner updates": look now, and install what is found
225 /// even with "Download updates by themselves" off.
226 Check,
227 /// What a look at the releases found.
228 Checked(Result<Found, Fault>),
229 Token { workspace: String, token: String },
230 Refused { workspace: String, allowed: bool, why: String },
231 /// A line of the runner's output, or the launcher's; true from its standard output.
232 Line(u64, String, bool),
233 Exited(u64),
234 /// What `sandbox status` said.
235 Sandbox(u64, Result<Box<Status>, String>),
236 Quit(Sender<()>),
237}
238
239/// The registration the app made, besides what the runner keeps itself.
240#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
241struct Registration {
242 server: String,
243 workspace: String,
244 backend: Backend,
245}
246
247/// Whose the sandbox's registration is. The sandbox keeps its own, and
248/// keeps it while another backend runs, so choosing Sandboxed again needs
249/// no new one; this says which workspace it is for.
250#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
251struct SandboxRegistration {
252 server: String,
253 workspace: String,
254 /// False from the `up` that was given a token until it registered.
255 registered: bool,
256}
257
258impl SandboxRegistration {
259 fn path(app: &AppHandle) -> PathBuf {
260 folder(app).join("sandbox-registration.json")
261 }
262 fn load(app: &AppHandle) -> Option<SandboxRegistration> {
263 std::fs::read(Self::path(app)).ok().and_then(|bytes| serde_json::from_slice(&bytes).ok())
264 }
265 fn save(&self, app: &AppHandle) {
266 let _ = std::fs::create_dir_all(folder(app));
267 let _ = std::fs::write(Self::path(app), serde_json::to_vec_pretty(self).unwrap_or_default());
268 }
269 fn clear(app: &AppHandle) {
270 let _ = std::fs::remove_file(Self::path(app));
271 }
272}
273
274/// Where the runner keeps everything: its program, registrations, log and
275/// the sandbox's VM. In the app's local data, which stays on this computer:
276/// roaming data (Windows' %APPDATA%) is copied to a profile server on
277/// networks with roaming profiles, and a VM's disk and a runner's
278/// credential have no business there. A computer whose runner already
279/// lives in roaming data keeps it there: its WSL distribution is
280/// registered at that path, and moving its disk would break it. On macOS
281/// and Linux the two are the same folder.
282fn folder(app: &AppHandle) -> PathBuf {
283 let fallback = || std::env::temp_dir().join("sh.g1t.desktop");
284 let local = app.path().app_local_data_dir().unwrap_or_else(|_| fallback()).join("runner");
285 let roaming = app.path().app_data_dir().unwrap_or_else(|_| fallback()).join("runner");
286 chosen_folder(local, roaming)
287}
288
289/// The local folder, unless the runner was set up in the roaming one before.
290fn chosen_folder(local: PathBuf, roaming: PathBuf) -> PathBuf {
291 if !local.exists() && roaming.exists() { roaming } else { local }
292}
293
294impl Registration {
295 fn path(app: &AppHandle) -> PathBuf {
296 folder(app).join("registration.json")
297 }
298 fn load(app: &AppHandle) -> Option<Registration> {
299 std::fs::read(Self::path(app)).ok().and_then(|bytes| serde_json::from_slice(&bytes).ok())
300 }
301 fn save(&self, app: &AppHandle) {
302 let _ = std::fs::create_dir_all(folder(app));
303 let _ = std::fs::write(Self::path(app), serde_json::to_vec_pretty(self).unwrap_or_default());
304 }
305 fn clear(app: &AppHandle) {
306 let _ = std::fs::remove_file(Self::path(app));
307 }
308}
309
310/// Where a native runner of a backend keeps its configuration.
311fn native_dir(app: &AppHandle, backend: Backend) -> PathBuf {
312 folder(app).join(match backend {
313 Backend::Docker => "docker",
314 Backend::Host => "host",
315 Backend::Sandboxed => launcher::FOLDER,
316 })
317}
318
319/// The workspace the runner is for: the one settings name, else the one it
320/// is registered with, else the one the person is in on the site, else the
321/// first they own.
322fn workspace(app: &AppHandle) -> Option<String> {
323 let settings = config::settings(app);
324 if let Some(chosen) = settings.runner_workspace.filter(|w| !w.is_empty()) {
325 return Some(chosen);
326 }
327 let server = config::server(app).to_string();
328 if let Some(registration) = Registration::load(app).filter(|r| r.server == server) {
329 return Some(registration.workspace);
330 }
331 let site = app.state::<Shared>().site.lock().unwrap().clone();
332 site.current.filter(|slug| site.owned.iter().any(|o| &o.slug == slug)).or_else(|| site.owned.first().map(|o| o.slug.clone()))
333}
334
335/// The kinds of job a sandbox can have.
336const KINDS: [&str; 3] = ["linux", "windows", "macos"];
337
338fn facts(app: &AppHandle, now: &Now) -> Facts {
339 let server = config::server(app);
340 let settings = config::settings(app);
341 let backend = settings.runner_backend;
342 Facts {
343 workspace: workspace(app),
344 backend: backend.label(),
345 machine: backend::machine_name(),
346 job: now.job.clone(),
347 detail: now.detail.clone(),
348 exit_code: now.exit_code,
349 wait_seconds: now.wait_seconds,
350 server: server.host_str().unwrap_or("g1t").to_owned(),
351 site: server.as_str().trim_end_matches('/').to_owned(),
352 platform: std::env::consts::OS.into(),
353 fix: now.fix.clone(),
354 sandbox: now.sandbox.clone().filter(|_| backend == Backend::Sandboxed),
355 off: KINDS.iter().filter(|kind| !settings.runner_capabilities.on(kind)).map(|kind| (*kind).to_owned()).collect(),
356 live: now.live,
357 starting: now.starting.clone(),
358 download: now.download.clone(),
359 held: !settings.runner || *app.state::<Shared>().paused.lock().unwrap(),
360 update: update_facts(app, now, backend),
361 }
362}
363
364/// How the runner's updates stand, for the words: what is still to take a
365/// waiting version. The sandbox's Windows jobs (any kind but Linux) take
366/// its program while they run; a runner with no kinds of job takes it
367/// itself.
368fn update_facts(app: &AppHandle, now: &Now, backend: Backend) -> diagnosis::Update {
369 let updates = app.state::<Shared>().updates.lock().unwrap().clone();
370 let sandbox = now.sandbox.as_ref().filter(|_| backend == Backend::Sandboxed);
371 let mut waiting = Vec::new();
372 if updates.image {
373 waiting.push("linux".to_owned());
374 }
375 if updates.program {
376 match sandbox {
377 Some(status) => waiting.extend(native_kinds(status).into_iter().map(|c| c.id.clone())),
378 None => waiting.push("runner".to_owned()),
379 }
380 }
381 diagnosis::Update {
382 installed: native::installed(&folder(app)),
383 checked_at: updates.checked_at.map(rfc3339),
384 checked_ago: updates.checked_at.and_then(|at| at.elapsed().ok()).map(|ago| ago.as_secs()),
385 checking: updates.checking,
386 ready: updates.ready,
387 waiting,
388 installing: updates.installing,
389 }
390}
391
392/// The kinds of job running on the program itself, which replacing it
393/// stops: the sandbox's Windows jobs (not Linux jobs, which run in its VM).
394fn native_kinds(status: &Status) -> Vec<&launcher::Capability> {
395 status.capabilities.iter().filter(|c| c.id != "linux" && !c.off() && matches!(c.state, State::Running | State::Starting)).collect()
396}
397
398/// A time as RFC 3339, in UTC to the second: `2026-10-12T12:04:05Z`.
399fn rfc3339(at: SystemTime) -> String {
400 let seconds = at.duration_since(SystemTime::UNIX_EPOCH).map_or(0, |since| since.as_secs());
401 let (days, rest) = (seconds / 86_400, seconds % 86_400);
402 // Days since 1970 to a date in the proleptic Gregorian calendar (Howard Hinnant's civil_from_days).
403 let z = days as i64 + 719_468;
404 let era = z.div_euclid(146_097);
405 let day_of_era = z.rem_euclid(146_097);
406 let year_of_era = (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
407 let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
408 let month_index = (5 * day_of_year + 2) / 153;
409 let day = day_of_year - (153 * month_index + 2) / 5 + 1;
410 let month = if month_index < 10 { month_index + 3 } else { month_index - 9 };
411 let year = year_of_era + era * 400 + i64::from(month <= 2);
412 format!("{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z", rest / 3600, rest % 3600 / 60, rest % 60)
413}
414
415pub fn view(app: &AppHandle) -> View {
416 let shared = app.state::<Shared>();
417 let now = shared.now.lock().unwrap().clone();
418 let settings = config::settings(app);
419 let facts = facts(app, &now);
420 let server = config::server(app);
421 let diagnosed = diagnosis::diagnose(now.code, &facts);
422 View {
423 chip: diagnosis::chip(&diagnosed),
424 diagnosis: diagnosed,
425 closed: diagnosis::closed(&facts),
426 running: matches!(now.code, Code::Idle | Code::Busy | Code::Offline) || facts.sandbox.as_ref().is_some_and(Status::running),
427 version: now.version,
428 backend: settings.runner_backend,
429 link: facts.workspace.as_ref().and_then(|w| server.join(&format!("{w}/-/runners")).ok()).map(|u| u.to_string()),
430 workspace: facts.workspace,
431 workspaces: shared.site.lock().unwrap().owned.clone(),
432 enabled: settings.runner,
433 paused: *shared.paused.lock().unwrap(),
434 machine: facts.machine,
435 platform: facts.platform,
436 log: shared.tail.lock().unwrap().iter().cloned().collect(),
437 }
438}
439
440/// Whether the runner is running a job: what restarts g1t waits for it,
441/// since restarting stops the runner and would cut the job short.
442pub fn busy(app: &AppHandle) -> bool {
443 let now = app.state::<Shared>().now.lock().unwrap().clone();
444 now.code == Code::Busy || now.sandbox.as_ref().is_some_and(|status| status.job().is_some())
445}
446
447/// The tray's line: `Runner: Waiting for jobs`, at most 60 characters.
448pub fn headline(view: &View) -> String {
449 let line = format!("Runner: {}", view.diagnosis.title);
450 if line.chars().count() > 60 { line.chars().take(59).collect::<String>() + "…" } else { line }
451}
452
453/// Tells everyone what the runner is doing now.
454fn publish(app: &AppHandle) {
455 let view = view(app);
456 tray::runner_changed(app, &view);
457 let _ = app.emit_to(settings::SETTINGS, STATUS_EVENT, view.clone());
458 let _ = app.emit_to(settings::RUNNER, STATUS_EVENT, view.clone());
459 let _ = app.emit_to(EventTarget::webview(frame::BAR), STATUS_EVENT, view.chip.clone());
460 let _ = app.emit_to(EventTarget::webview(frame::SITE), STATUS_EVENT, view);
461}
462
463fn ask(app: &AppHandle, ask: Ask) {
464 if let Some(tx) = app.state::<Shared>().tx.lock().unwrap().as_ref() {
465 let _ = tx.send(ask);
466 }
467}
468
469/// Starts the thread that keeps the runner, as the app starts.
470pub fn install(app: &AppHandle) {
471 let (tx, rx) = mpsc::channel();
472 *app.state::<Shared>().tx.lock().unwrap() = Some(tx.clone());
473 let handle = app.clone();
474 let spawned = std::thread::Builder::new().name("g1t-runner".into()).spawn(move || Keeper::new(handle, tx).keep(rx));
475 if let Err(error) = spawned {
476 eprintln!("g1t: the runner's thread could not start: {error}");
477 }
478}
479
480/// Settings changed: the thread looks again.
481pub fn settings_changed(app: &AppHandle) {
482 ask(app, Ask::Look);
483 publish(app);
484}
485
486/// Start or Stop, from settings or the tray.
487pub fn set_paused(app: &AppHandle, paused: bool) {
488 *app.state::<Shared>().paused.lock().unwrap() = paused;
489 // Start with the setting off turns the setting on: that is what was asked.
490 if !paused && !config::settings(app).runner {
491 let mut settings = config::settings(app);
492 settings.runner = true;
493 let _ = settings::apply(app, settings);
494 }
495 settings_changed(app);
496}
497
498/// Start or Stop on one kind of job's card: kept in settings, and the
499/// thread starts or stops that kind alone. Starting one with the runner
500/// off or stopped starts the runner too: that is what was asked.
501pub fn set_kind(app: &AppHandle, kind: &str, on: bool) -> Result<(), String> {
502 let mut settings = config::settings(app);
503 if !settings.runner_capabilities.set(kind, on) {
504 return Err(format!("g1t runs no {kind} jobs"));
505 }
506 if on {
507 settings.runner = true;
508 *app.state::<Shared>().paused.lock().unwrap() = false;
509 }
510 settings::apply(app, settings)?;
511 if on {
512 ask(app, Ask::Soon);
513 }
514 settings_changed(app);
515 Ok(())
516}
517
518/// The tray's Start or Stop row.
519pub fn toggle(app: &AppHandle) {
520 let view = view(app);
521 set_paused(app, view.enabled && !view.paused);
522}
523
524/// Retry and Restart: now, rather than when the wait is over.
525pub fn retry(app: &AppHandle) {
526 *app.state::<Shared>().paused.lock().unwrap() = false;
527 ask(app, Ask::Retry);
528}
529
530/// What the site says about the person, on every page: whether they are
531/// signed in, the workspaces they own, and the one they are in.
532pub fn offer(app: &AppHandle, signed_in: bool, owned: Vec<Offered>, current: Option<String>) {
533 let next = Site { signed_in: Some(signed_in), owned, current: current.map(|c| c.to_ascii_lowercase()) };
534 let changed = {
535 let shared = app.state::<Shared>();
536 let mut site = shared.site.lock().unwrap();
537 let changed = *site != next;
538 *site = next;
539 changed
540 };
541 if changed {
542 settings_changed(app);
543 }
544}
545
546/// The site handed over a registration token, or said why it could not:
547/// `allowed` is false when the person may not add runners to the workspace.
548pub fn register(app: &AppHandle, workspace: String, token: Option<String>, allowed: bool, error: Option<String>) {
549 match token {
550 Some(token) if token.starts_with("g1trt_") => ask(app, Ask::Token { workspace, token }),
551 _ => ask(app, Ask::Refused { workspace, allowed, why: error.unwrap_or_else(|| "g1t didn't make a registration token.".into()) }),
552 }
553}
554
555/// A diagnosis's button, or Start and Stop: from the settings window, or
556/// from the site's card for this computer. With a kind of job (`linux`,
557/// `windows`), Start and Stop are that kind's alone.
558pub fn act(app: &AppHandle, action: &str, kind: Option<&str>) -> Result<(), String> {
559 use tauri_plugin_opener::OpenerExt;
560 let browse = |url: &str| app.opener().open_url(url, None::<&str>).map_err(|e| e.to_string());
561 if let ("start" | "stop", Some(kind)) = (action, kind) {
562 return set_kind(app, kind, action == "start");
563 }
564 match action {
565 "start" => {
566 set_paused(app, false);
567 retry(app);
568 }
569 "stop" => set_paused(app, true),
570 "retry" | "restart" => retry(app),
571 "check_updates" => ask(app, Ask::Check),
572 "sign_in" => crate::links::go(app, "/login"),
573 "new_workspace" => crate::links::go(app, "/workspaces/new"),
574 "view_runners" => match workspace(app) {
575 Some(workspace) => crate::links::go(app, &format!("/{workspace}/-/runners")),
576 None => crate::links::go(app, "/"),
577 },
578 // They are chosen in the Runner window.
579 "choose_workspace" | "choose_backend" | "open_runner" => settings::open_runner(app),
580 "view_log" => {
581 let path = log_file(app);
582 if !path.exists() {
583 return Err("The runner hasn't written a log yet.".into());
584 }
585 app.opener().open_path(path.to_string_lossy(), None::<&str>).map_err(|e| e.to_string())?;
586 }
587 "open_docker" => open_docker(app)?,
588 "copy_wsl_install" => copy(launcher::WSL_INSTALL)?,
589 "copy_vfkit_install" => copy(launcher::VFKIT_INSTALL)?,
590 "windows_features" => windows_features()?,
591 "get_docker" => browse("https://docs.docker.com/get-started/get-docker/")?,
592 "install_sysbox" => browse("https://github.com/nestybox/sysbox#installation")?,
593 "learn_more" => browse("https://docs.g1t.sh/guides/desktop/#how-jobs-run")?,
594 "report" => browse(config::server(app).join("support").map_err(|e| e.to_string())?.as_str())?,
595 other => return Err(format!("the runner has no action called {other}")),
596 }
597 Ok(())
598}
599
600/// Starts Docker Desktop, where it is installed in its usual place.
601fn open_docker(app: &AppHandle) -> Result<(), String> {
602 use tauri_plugin_opener::OpenerExt;
603 if cfg!(target_os = "macos") {
604 return app.opener().open_path("/Applications/Docker.app", None::<&str>).map_err(|e| e.to_string());
605 }
606 if cfg!(windows) {
607 let program = std::env::var_os("ProgramFiles").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(r"C:\Program Files"));
608 let desktop = program.join("Docker").join("Docker").join("Docker Desktop.exe");
609 if desktop.exists() {
610 return app.opener().open_path(desktop.to_string_lossy(), None::<&str>).map_err(|e| e.to_string());
611 }
612 return Err("Docker Desktop isn't installed in its usual place. Get Docker to install it.".into());
613 }
614 Err("Start Docker with your system's service manager, such as `sudo systemctl start docker`.".into())
615}
616
617/// Puts a command on the clipboard, for the person to paste where it runs.
618fn copy(text: &str) -> Result<(), String> {
619 let tools: &[(&str, &[&str])] = if cfg!(windows) {
620 &[("clip", &[])]
621 } else if cfg!(target_os = "macos") {
622 &[("pbcopy", &[])]
623 } else {
624 &[("wl-copy", &[]), ("xclip", &["-selection", "clipboard"]), ("xsel", &["--clipboard", "--input"])]
625 };
626 for (program, args) in tools {
627 let Ok(mut child) = backend::quiet(program).args(*args).stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null()).spawn() else { continue };
628 if let Some(mut input) = child.stdin.take() {
629 let _ = input.write_all(text.as_bytes());
630 }
631 if child.wait().is_ok_and(|status| status.success()) {
632 return Ok(());
633 }
634 }
635 Err(format!("It couldn't be copied. The command is: {text}"))
636}
637
638/// Windows' "Turn Windows features on or off", where Windows Sandbox and
639/// Virtual Machine Platform are.
640fn windows_features() -> Result<(), String> {
641 if !cfg!(windows) {
642 return Err("Windows features are only on Windows.".into());
643 }
644 backend::quiet("optionalfeatures.exe").spawn().map(|_| ()).map_err(|e| format!("Windows features couldn't be opened: {e}"))
645}
646
647/// The workspace a token is wanted for now, if one is: the site asks as it loads.
648pub fn wanted(app: &AppHandle) -> Option<String> {
649 app.state::<Shared>().wanted.lock().unwrap().clone()
650}
651
652/// The runner's log, for the settings window to open.
653pub fn log_file(app: &AppHandle) -> PathBuf {
654 folder(app).join("runner.log")
655}
656
657/// Stops the runner as g1t quits or restarts, and waits for it.
658pub fn shutdown(app: &AppHandle) {
659 let tx = app.state::<Shared>().tx.lock().unwrap().take();
660 if let Some(tx) = tx {
661 let (done, wait) = mpsc::channel();
662 if tx.send(Ask::Quit(done)).is_ok() {
663 let _ = wait.recv_timeout(Duration::from_secs(30));
664 }
665 }
666}
667
668/// How the runner is started this time.
669enum Process {
670 /// `g1t-runner`, a child of the app, whose output is the runner's log.
671 Child(Child),
672 /// The sandbox, which runs on its own once `up` is done; the launcher
673 /// command the app is waiting for, while there is one.
674 Sandbox(Option<(Step, Child)>),
675}
676
677/// A launcher command that takes a while.
678#[derive(Clone, Debug, PartialEq, Eq)]
679enum Step {
680 Up,
681 Update,
682 /// `up --only <kind>`: one kind of job, started while the rest run.
683 Start(String),
684 /// `down --only <kind>`: one kind of job, stopped, the rest running on.
685 Stop(String),
686 /// `down --only <kind> --drain`: one kind of job, stopped after its
687 /// job, so the program its runner is can be replaced.
688 Drain(String),
689}
690
691impl Step {
692 fn name(&self) -> &'static str {
693 match self {
694 Step::Up | Step::Start(_) => "up",
695 Step::Update => "update",
696 Step::Stop(_) | Step::Drain(_) => "down",
697 }
698 }
699}
700
701struct Run {
702 generation: u64,
703 engine: Engine,
704 backend: Backend,
705 workspace: String,
706 process: Process,
707 /// Registered and polling.
708 listening: bool,
709 busy: bool,
710 /// When a poll last failed to reach g1t.
711 offline_at: Option<Instant>,
712 /// Started with a registration token, which a container keeps in its configuration until replaced.
713 with_token: bool,
714 forgotten: bool,
715 token_refused: bool,
716 error: Option<String>,
717 /// The status a launcher command is printing, line by line.
718 json: Option<Vec<String>>,
719 /// Asking the sandbox how it is, and when it was last asked.
720 polling: bool,
721 polled_at: Option<Instant>,
722 /// A poll asked before a launcher command ended, whose answer is old.
723 stale: bool,
724}
725
726impl Run {
727 fn new(generation: u64, engine: Engine, backend: Backend, workspace: String, process: Process, with_token: bool) -> Run {
728 Run {
729 generation,
730 engine,
731 backend,
732 workspace,
733 process,
734 listening: false,
735 busy: false,
736 offline_at: None,
737 with_token,
738 forgotten: false,
739 token_refused: false,
740 error: None,
741 json: None,
742 polling: false,
743 polled_at: None,
744 stale: false,
745 }
746 }
747
748 fn step(&self) -> Option<Step> {
749 match &self.process {
750 Process::Sandbox(Some((step, _))) => Some(step.clone()),
751 _ => None,
752 }
753 }
754}
755
756struct Keeper {
757 app: AppHandle,
758 tx: Sender<Ask>,
759 run: Option<Run>,
760 generation: u64,
761 token: Option<(String, String)>,
762 not_before: Instant,
763 failures: u32,
764 next_update: Instant,
765 log: Option<File>,
766 /// Why the last update failed (`UpdateFailed`, or `UpdateRefused` for
767 /// a release g1t didn't sign), said while the runner is idle, until
768 /// the next one works.
769 update_failed: Option<(Code, String)>,
770 /// A newer program, downloaded and checked, waiting for the kinds of
771 /// job that run on it to be idle: its version and its bytes.
772 program: Option<(String, Vec<u8>)>,
773 /// The person asked for this update: it installs with "Download
774 /// updates by themselves" off.
775 asked: bool,
776 /// When g1t last looked, as settings last said it.
777 said_checked: String,
778 /// A kind of job that should run and doesn't, while another runs:
779 /// when it is tried again, and how many times it has been.
780 retry: Vec<(String, Instant, u32)>,
781}
782
783/// What a set of the state carries besides its code.
784#[derive(Default)]
785struct Extra {
786 detail: Option<String>,
787 exit_code: Option<i32>,
788 wait_seconds: Option<u64>,
789 fix: Option<String>,
790}
791
792fn detail(text: impl Into<String>) -> Extra {
793 Extra { detail: Some(text.into()), ..Extra::default() }
794}
795
796impl Keeper {
797 fn new(app: AppHandle, tx: Sender<Ask>) -> Keeper {
798 let now = Instant::now();
799 Keeper {
800 app,
801 tx,
802 run: None,
803 generation: 0,
804 token: None,
805 not_before: now + AFTER_START,
806 failures: 0,
807 next_update: now + FIRST_UPDATE,
808 log: None,
809 update_failed: None,
810 program: None,
811 asked: false,
812 said_checked: String::new(),
813 retry: Vec::new(),
814 }
815 }
816
817 fn keep(mut self, rx: Receiver<Ask>) {
818 self.reap();
819 self.set(Code::Starting, detail("Starting after g1t's window."));
820 loop {
821 match rx.recv_timeout(TICK) {
822 Ok(Ask::Quit(done)) => {
823 self.halt();
824 let _ = done.send(());
825 return;
826 }
827 Ok(ask) => self.handle(ask),
828 Err(RecvTimeoutError::Timeout) => {}
829 Err(RecvTimeoutError::Disconnected) => {
830 self.halt();
831 return;
832 }
833 }
834 self.look();
835 self.said_when();
836 }
837 }
838
839 /// Settings say when g1t last looked for a newer runner, in minutes
840 /// and hours: said again as that changes.
841 fn said_when(&mut self) {
842 let (checked_at, checking) = self.with_updates(|updates| (updates.checked_at, updates.checking));
843 let checked_ago = checked_at.and_then(|at| at.elapsed().ok()).map(|ago| ago.as_secs());
844 let checked = diagnosis::checked(&diagnosis::Update { checked_ago, checking, ..diagnosis::Update::default() });
845 if checked != self.said_checked {
846 self.said_checked = checked;
847 publish(&self.app);
848 }
849 }
850
851 fn with_updates<R>(&self, change: impl FnOnce(&mut Updates) -> R) -> R {
852 change(&mut self.app.state::<Shared>().updates.lock().unwrap())
853 }
854
855 /// What an idle runner shows: why its last update failed, until one works.
856 fn idle(&self, code: Code) -> (Code, Extra) {
857 match (&self.update_failed, code) {
858 (Some((failed, why)), Code::Idle) => (*failed, detail(why.clone())),
859 _ => (code, Extra::default()),
860 }
861 }
862
863 fn set(&mut self, code: Code, extra: Extra) {
864 let changed = {
865 let shared = self.app.state::<Shared>();
866 let mut now = shared.now.lock().unwrap();
867 let job = if code == Code::Busy { now.job.clone() } else { None };
868 let next = Now {
869 code,
870 detail: extra.detail,
871 exit_code: extra.exit_code,
872 wait_seconds: extra.wait_seconds,
873 job,
874 fix: extra.fix,
875 live: self.run.as_ref().is_some_and(|run| run.engine == Engine::Launcher),
876 ..now.clone()
877 };
878 let changed = *now != next;
879 *now = next;
880 changed
881 };
882 if changed {
883 publish(&self.app);
884 }
885 }
886
887 fn code(&self) -> Code {
888 self.app.state::<Shared>().now.lock().unwrap().code
889 }
890
891 fn note(&mut self, job: Option<String>, version: Option<String>) {
892 let shared = self.app.state::<Shared>();
893 let mut now = shared.now.lock().unwrap();
894 if job.is_some() {
895 now.job = job;
896 }
897 if version.is_some() {
898 now.version = version;
899 }
900 }
901
902 /// A line of the runner's log, into the log file and the tail settings show.
903 fn write_log(&mut self, line: &str) {
904 {
905 let shared = self.app.state::<Shared>();
906 let mut tail = shared.tail.lock().unwrap();
907 if tail.len() == TAIL {
908 tail.pop_front();
909 }
910 tail.push_back(line.to_owned());
911 }
912 let path = log_file(&self.app);
913 if self.log.is_none() {
914 let _ = std::fs::create_dir_all(folder(&self.app));
915 if std::fs::metadata(&path).is_ok_and(|m| m.len() > LOG_LIMIT) {
916 let _ = std::fs::rename(&path, path.with_extension("log.old"));
917 }
918 self.log = OpenOptions::new().create(true).append(true).open(&path).ok();
919 }
920 if let Some(file) = self.log.as_mut() {
921 let _ = writeln!(file, "{line}");
922 }
923 }
924
925 fn handle(&mut self, ask: Ask) {
926 match ask {
927 Ask::Look | Ask::Quit(_) => {}
928 Ask::Soon => {
929 self.not_before = Instant::now();
930 for (_, at, _) in &mut self.retry {
931 *at = Instant::now();
932 }
933 }
934 Ask::Retry => {
935 self.not_before = Instant::now();
936 self.failures = 0;
937 // Each kind of job that waits to be tried again is tried now.
938 for (_, at, _) in &mut self.retry {
939 *at = Instant::now();
940 }
941 match self.code() {
942 // The runner is fine: only the update is tried again.
943 Code::UpdateFailed | Code::UpdateRefused if self.run.is_some() => self.check(true),
944 Code::Offline => self.halt(),
945 _ if self.run.as_ref().is_some_and(|run| !run.listening) => self.halt(),
946 _ => {}
947 }
948 }
949 Ask::Check => self.check(true),
950 Ask::Checked(found) => self.checked(found),
951 Ask::Token { workspace, token } => {
952 let shared = self.app.state::<Shared>();
953 let mut wanted = shared.wanted.lock().unwrap();
954 if wanted.as_deref() == Some(workspace.as_str()) {
955 *wanted = None;
956 self.token = Some((workspace, token));
957 self.not_before = Instant::now();
958 }
959 }
960 Ask::Refused { workspace, allowed, why } => {
961 let matched = {
962 let shared = self.app.state::<Shared>();
963 let mut wanted = shared.wanted.lock().unwrap();
964 let matched = wanted.as_deref() == Some(workspace.as_str());
965 if matched {
966 *wanted = None;
967 }
968 matched
969 };
970 if matched {
971 self.not_before = Instant::now() + MOST_BACKOFF;
972 self.set(if allowed { Code::RegisterFailed } else { Code::NotAllowed }, detail(why));
973 }
974 }
975 Ask::Line(generation, line, out) => self.line(generation, &line, out),
976 Ask::Exited(generation) => self.exited(generation),
977 Ask::Sandbox(generation, status) => self.polled(generation, status),
978 }
979 }
980
981 fn line(&mut self, generation: u64, line: &str, out: bool) {
982 let Some(run) = self.run.as_mut().filter(|run| run.generation == generation) else { return };
983 if run.engine == Engine::Launcher {
984 // The launcher's log, then its status, which is read when it ends.
985 if out && (run.json.is_some() || launcher::starts_status(line)) {
986 run.json.get_or_insert_with(Vec::new).push(line.to_owned());
987 } else {
988 if let Some(download) = launcher::download(line) {
989 let changed = {
990 let shared = self.app.state::<Shared>();
991 let mut now = shared.now.lock().unwrap();
992 let changed = now.download.as_ref() != Some(&download);
993 now.download = Some(download);
994 changed
995 };
996 if changed {
997 publish(&self.app);
998 }
999 }
1000 self.write_log(line);
1001 }
1002 return;
1003 }
1004 let mut became = None;
1005 let mut job = None;
1006 let mut version = None;
1007 match log::read(line) {
1008 log::Event::Listening { version: v } => {
1009 run.listening = true;
1010 version = Some(v);
1011 became = Some(Code::Idle);
1012 }
1013 log::Event::Took { name, repo } => {
1014 run.busy = true;
1015 run.offline_at = None;
1016 job = Some(format!("{name} ({repo})"));
1017 became = Some(Code::Busy);
1018 }
1019 log::Event::Ended => {
1020 run.busy = false;
1021 became = Some(Code::Idle);
1022 }
1023 log::Event::Offline => {
1024 run.offline_at = Some(Instant::now());
1025 if !run.busy {
1026 became = Some(Code::Offline);
1027 }
1028 }
1029 log::Event::Forgotten => run.forgotten = true,
1030 log::Event::TokenRefused => run.token_refused = true,
1031 log::Event::Failed(error) => run.error = Some(error),
1032 log::Event::Other => {}
1033 }
1034 let registered = version.is_some().then(|| Registration {
1035 server: config::server(&self.app).to_string(),
1036 workspace: run.workspace.clone(),
1037 backend: run.backend,
1038 });
1039 self.write_log(line);
1040 if let Some(registration) = registered {
1041 registration.save(&self.app);
1042 self.failures = 0;
1043 }
1044 self.note(job, version);
1045 if let Some(code) = became {
1046 let (code, extra) = self.idle(code);
1047 self.set(code, extra);
1048 }
1049 }
1050
1051 fn exited(&mut self, generation: u64) {
1052 if self.run.as_ref().is_none_or(|run| run.generation != generation) {
1053 return;
1054 }
1055 if self.run.as_ref().is_some_and(|run| run.engine == Engine::Launcher) {
1056 return self.launched(generation);
1057 }
1058 let mut run = self.run.take().expect("checked above");
1059 let exit_code = match &mut run.process {
1060 Process::Child(child) => child.wait().ok().and_then(|status| status.code()),
1061 Process::Sandbox(_) => None,
1062 };
1063 self.stop(&mut run, Down::Now);
1064 if run.forgotten || run.token_refused {
1065 // The registration is no more, or was never made: the next start asks for a token.
1066 self.forget();
1067 self.not_before = Instant::now();
1068 return;
1069 }
1070 self.failures += 1;
1071 let wait = Duration::from_secs(15 * 2u64.pow(self.failures.min(6))).min(MOST_BACKOFF);
1072 self.not_before = Instant::now() + wait;
1073 let offline = run.error.as_deref().is_some_and(|e| e.contains("could not reach g1t"));
1074 if offline {
1075 self.set(Code::Offline, Extra::default());
1076 } else if !run.listening && Registration::load(&self.app).is_none() {
1077 self.set(Code::RegisterFailed, Extra { detail: run.error, ..Extra::default() });
1078 } else {
1079 self.set(Code::Crashed, Extra { detail: run.error, exit_code, wait_seconds: Some(wait.as_secs()), ..Extra::default() });
1080 }
1081 }
1082
1083 /// Stops a run's process, the way it was started: the sandbox `how` says.
1084 fn stop(&mut self, run: &mut Run, how: Down) {
1085 match (&mut run.process, run.engine) {
1086 (Process::Sandbox(step), _) => {
1087 // A launcher command still going is ended first, then the sandbox stopped.
1088 if let Some((_, child)) = step.as_mut() {
1089 native::stop(child);
1090 }
1091 let binary = native::binary(&folder(&self.app));
1092 // How it is once stopped, so each kind of job's card says so.
1093 let stopped = match launcher::down(&binary, &native_dir(&self.app, Backend::Sandboxed), how) {
1094 Ok(status) => Some(status),
1095 Err(why) => {
1096 self.write_log(&format!("g1t: the sandbox didn't stop cleanly: {why}"));
1097 None
1098 }
1099 };
1100 let shared = self.app.state::<Shared>();
1101 let mut now = shared.now.lock().unwrap();
1102 now.sandbox = stopped.filter(|_| how != Down::Delete);
1103 now.starting.clear();
1104 now.download = None;
1105 }
1106 (Process::Child(child), Engine::Launcher) => native::stop(child),
1107 (Process::Child(child), Engine::Native { docker }) => {
1108 native::stop(child);
1109 // A job's container outlives the runner killed under it: removed now, not at its next start.
1110 if docker {
1111 native::sweep(&native_dir(&self.app, run.backend));
1112 }
1113 }
1114 }
1115 let _ = std::fs::remove_file(folder(&self.app).join("pid"));
1116 }
1117
1118 /// Stops whatever runs now.
1119 fn halt(&mut self) {
1120 self.halt_as(Down::Now);
1121 }
1122
1123 /// Stops whatever runs: the sandbox now, after its job, or for good.
1124 fn halt_as(&mut self, how: Down) {
1125 self.generation += 1;
1126 if let Some(mut run) = self.run.take() {
1127 self.stop(&mut run, how);
1128 }
1129 }
1130
1131 /// A runner an earlier g1t started and did not stop: it ended without quitting.
1132 fn reap(&self) {
1133 if let Some(pid) = std::fs::read_to_string(folder(&self.app).join("pid")).ok().and_then(|text| text.trim().parse().ok()) {
1134 native::reap(pid);
1135 let _ = std::fs::remove_file(folder(&self.app).join("pid"));
1136 }
1137 }
1138
1139 /// Unregisters the runner the app registered, whatever backend it was.
1140 fn forget(&mut self) {
1141 let app = self.app.clone();
1142 let Some(registration) = Registration::load(&app) else { return };
1143 let binary = native::binary(&folder(&app));
1144 match registration.backend {
1145 // The sandbox keeps its registration for when it is chosen
1146 // again (sandbox-registration.json says whose): it only stops,
1147 // after its job.
1148 Backend::Sandboxed => {
1149 let _ = launcher::down(&binary, &native_dir(&app, Backend::Sandboxed), Down::Drain);
1150 }
1151 backend => native::forget(&binary, &native_dir(&app, backend)),
1152 }
1153 Registration::clear(&app);
1154 }
1155
1156 /// Removes the sandbox and its registration: it was for another
1157 /// workspace, or g1t no longer knows its runners.
1158 fn forget_sandbox(&mut self) {
1159 let binary = native::binary(&folder(&self.app));
1160 if let Err(why) = launcher::down(&binary, &native_dir(&self.app, Backend::Sandboxed), Down::Delete) {
1161 self.write_log(&format!("g1t: the sandbox couldn't be removed: {why}"));
1162 }
1163 SandboxRegistration::clear(&self.app);
1164 if Registration::load(&self.app).is_some_and(|r| r.backend == Backend::Sandboxed) {
1165 Registration::clear(&self.app);
1166 }
1167 }
1168
1169 /// Whether what a native runner keeps of a registration is still here.
1170 fn kept(&self, backend: Backend) -> bool {
1171 native_dir(&self.app, backend).join("config.json").exists()
1172 }
1173
1174 /// Asks the site for a registration token for `workspace`.
1175 fn want(&mut self, workspace: &str) {
1176 *self.app.state::<Shared>().wanted.lock().unwrap() = Some(workspace.to_owned());
1177 let _ = self.app.emit_to(EventTarget::webview(frame::SITE), WANTED_EVENT, workspace.to_owned());
1178 self.not_before = Instant::now() + ASK_AGAIN;
1179 let signed_out = self.app.state::<Shared>().site.lock().unwrap().signed_in == Some(false);
1180 self.set(if signed_out { Code::SignedOut } else { Code::Registering }, Extra::default());
1181 }
1182
1183 /// The thread's look round: what should run, and whether it does.
1184 fn look(&mut self) {
1185 let settings = config::settings(&self.app);
1186 let paused = *self.app.state::<Shared>().paused.lock().unwrap();
1187 if !settings.runner || paused {
1188 if self.run.is_some() {
1189 self.halt();
1190 }
1191 *self.app.state::<Shared>().wanted.lock().unwrap() = None;
1192 self.set(if paused { Code::Stopped } else { Code::Off }, Extra::default());
1193 return;
1194 }
1195 // Looking needs a runner here to compare with; the first comes with the first start.
1196 if Instant::now() >= self.next_update && native::installed(&folder(&self.app)).is_some() {
1197 self.check(false);
1198 }
1199 let workspace = workspace(&self.app);
1200 if let Some(run) = &self.run {
1201 let moved = run.backend != settings.runner_backend || Some(&run.workspace) != workspace.as_ref();
1202 let back = run.offline_at.is_some_and(|at| at.elapsed() >= BACK_ONLINE);
1203 let (busy, stepping) = (run.busy, run.step().is_some());
1204 if back {
1205 if let Some(run) = self.run.as_mut() {
1206 run.offline_at = None;
1207 }
1208 self.set(Code::Idle, Extra::default());
1209 }
1210 // A change of backend or workspace waits for the job to end, as an update does.
1211 if moved && !busy && !stepping {
1212 self.halt_as(Down::Drain);
1213 self.not_before = Instant::now();
1214 } else if !moved && !stepping && !self.install() {
1215 self.kinds(workspace.as_deref());
1216 }
1217 self.poll();
1218 return;
1219 }
1220 if Instant::now() < self.not_before {
1221 return;
1222 }
1223 // Nothing runs: a waiting program goes in before anything starts.
1224 if self.program.is_some()
1225 && self.allowed()
1226 && let Some((version, bytes)) = self.program.take()
1227 {
1228 self.put(version, &bytes);
1229 }
1230 self.start(settings.runner_backend, workspace);
1231 }
1232
1233 fn start(&mut self, backend: Backend, workspace: Option<String>) {
1234 let app = self.app.clone();
1235 let engine = match backend::engine(backend) {
1236 Ok(engine) => engine,
1237 Err(missing) => {
1238 self.not_before = Instant::now() + LOOK_AGAIN;
1239 let code = match missing {
1240 Missing::Docker => Code::NoDocker,
1241 };
1242 self.set(code, Extra::default());
1243 return;
1244 }
1245 };
1246 let Some(workspace) = workspace else {
1247 self.not_before = Instant::now() + LOOK_AGAIN;
1248 let code = match app.state::<Shared>().site.lock().unwrap().signed_in {
1249 Some(false) => Code::SignedOut,
1250 Some(true) => Code::NoWorkspace,
1251 None => Code::Starting,
1252 };
1253 self.set(code, detail("Waiting for g1t to open."));
1254 return;
1255 };
1256 if engine == Engine::Launcher {
1257 return self.start_sandbox(workspace);
1258 }
1259 let server = config::server(&app);
1260 let registration = Registration::load(&app);
1261 let ours = registration.as_ref().is_some_and(|r| r.server == server.as_str() && r.workspace == workspace && r.backend == backend) && self.kept(backend);
1262 let mut token = None;
1263 if !ours {
1264 if registration.is_some() {
1265 self.set(Code::Starting, detail("Removing this computer's earlier registration."));
1266 self.forget();
1267 }
1268 match self.token.take() {
1269 Some((for_workspace, given)) if for_workspace == workspace => token = Some(given),
1270 _ => return self.want(&workspace),
1271 }
1272 }
1273 self.hold_workspace(&workspace);
1274 self.set(Code::Starting, Extra::default());
1275 let envs = environment(&server, backend, token.as_deref());
1276 let generation = self.generation + 1;
1277 self.generation = generation;
1278 let binary = match self.ensure_binary(&server) {
1279 Ok(binary) => binary,
1280 Err(fault) => return self.not_installed(workspace, token, fault),
1281 };
1282 let started = native::spawn(&binary, &native_dir(&app, backend), &envs).map_err(|e| format!("g1t-runner could not start: {e}")).inspect(|child| {
1283 let _ = std::fs::write(folder(&app).join("pid"), child.id().to_string());
1284 });
1285 match started {
1286 Ok(mut child) => {
1287 self.follow(generation, &mut child);
1288 self.run = Some(Run::new(generation, engine, backend, workspace, Process::Child(child), token.is_some()));
1289 self.set(Code::Starting, Extra::default());
1290 }
1291 Err(why) => self.not_started(workspace, token, why),
1292 }
1293 }
1294
1295 /// The runner couldn't be started: the token is kept for the next try,
1296 /// while it lasts, and it is tried again in a while.
1297 fn not_started(&mut self, workspace: String, token: Option<String>, why: String) {
1298 if let Some(given) = token {
1299 self.token = Some((workspace, given));
1300 }
1301 self.failures += 1;
1302 self.not_before = Instant::now() + LOOK_AGAIN;
1303 let offline = why.contains("error sending request") || why.contains("dns") || why.contains("connect");
1304 self.write_log(&format!("g1t: the runner could not start: {why}"));
1305 if offline {
1306 self.set(Code::Offline, Extra::default());
1307 } else {
1308 self.set(Code::Crashed, Extra { detail: Some(why), wait_seconds: Some(LOOK_AGAIN.as_secs()), ..Extra::default() });
1309 }
1310 }
1311
1312 /// The setting names the workspace from now on, so browsing another one never moves the runner.
1313 fn hold_workspace(&self, workspace: &str) {
1314 if config::settings(&self.app).runner_workspace.as_deref() != Some(workspace) {
1315 let mut settings = config::settings(&self.app);
1316 settings.runner_workspace = Some(workspace.to_owned());
1317 let _ = config::set_settings(&self.app, settings);
1318 }
1319 }
1320
1321 /// Reads the child's output, a line at a time, onto the thread's channel.
1322 fn follow(&self, generation: u64, child: &mut Child) {
1323 fn pipe(tx: Sender<Ask>, generation: u64, from: impl Read + Send + 'static, last: bool) {
1324 std::thread::spawn(move || {
1325 for line in BufReader::new(from).lines().map_while(Result::ok) {
1326 if tx.send(Ask::Line(generation, line, last)).is_err() {
1327 return;
1328 }
1329 }
1330 if last {
1331 let _ = tx.send(Ask::Exited(generation));
1332 }
1333 });
1334 }
1335 if let Some(err) = child.stderr.take() {
1336 pipe(self.tx.clone(), generation, err, false);
1337 }
1338 if let Some(out) = child.stdout.take() {
1339 pipe(self.tx.clone(), generation, out, true);
1340 }
1341 }
1342
1343 /// `g1t-runner` installed, from the newest release when it is not:
1344 /// one g1t signed, as every update is.
1345 fn ensure_binary(&mut self, server: &Url) -> Result<PathBuf, Fault> {
1346 let folder = folder(&self.app);
1347 let binary = native::binary(&folder);
1348 if native::installed(&folder).is_some() {
1349 return Ok(binary);
1350 }
1351 self.set(Code::Updating, detail("Downloading g1t-runner."));
1352 let manifest = native::latest(server)?;
1353 let bytes = native::download(server, &manifest).map_err(Fault::Failed)?;
1354 native::put(&folder, &bytes, &manifest.version).map_err(Fault::Failed)?;
1355 self.note(None, Some(manifest.version));
1356 self.with_updates(|updates| updates.checked_at = Some(SystemTime::now()));
1357 Ok(binary)
1358 }
1359
1360 /// There is no `g1t-runner` here, and none could be had: a release g1t
1361 /// didn't sign is refused, and asked for again in a while.
1362 fn not_installed(&mut self, workspace: String, token: Option<String>, fault: Fault) {
1363 match fault {
1364 Fault::Failed(why) => self.not_started(workspace, token, why),
1365 Fault::Unsigned(why) => {
1366 if let Some(given) = token {
1367 self.token = Some((workspace, given));
1368 }
1369 self.write_log(&format!("g1t: g1t-runner wasn't installed: {why}"));
1370 self.not_before = Instant::now() + MOST_BACKOFF;
1371 self.set(Code::UpdateRefused, detail(why));
1372 }
1373 }
1374 }
1375
1376 // --- Updates ------------------------------------------------------------------
1377
1378 /// Looks for a newer release on a thread of its own, so the runner is
1379 /// looked after meanwhile: its signed manifest, and its program when it
1380 /// is newer than the one here. `asked` is the person asking, which
1381 /// works with "Download updates by themselves" off.
1382 fn check(&mut self, asked: bool) {
1383 self.next_update = Instant::now() + UPDATE_EVERY;
1384 if !asked && !config::settings(&self.app).auto_update {
1385 return;
1386 }
1387 if self.with_updates(|updates| std::mem::replace(&mut updates.checking, true)) {
1388 return;
1389 }
1390 self.asked |= asked;
1391 publish(&self.app);
1392 let (server, folder) = (config::server(&self.app), folder(&self.app));
1393 let waiting = self.program.as_ref().map(|(version, _)| version.clone());
1394 let tx = self.tx.clone();
1395 let spawned = std::thread::Builder::new().name("g1t-runner-releases".into()).spawn(move || {
1396 let _ = tx.send(Ask::Checked(look_for_release(&server, &folder, waiting.as_deref())));
1397 });
1398 if spawned.is_err() {
1399 self.with_updates(|updates| updates.checking = false);
1400 }
1401 }
1402
1403 /// What the look found: a newer program waits for its kinds of job to
1404 /// be idle, and so does the sandbox's image when it is older than the
1405 /// release's. A release g1t didn't sign, or one that didn't download,
1406 /// leaves the runner as it is, and is said while it is idle.
1407 fn checked(&mut self, found: Result<Found, Fault>) {
1408 self.with_updates(|updates| updates.checking = false);
1409 let found = match found {
1410 Ok(found) => found,
1411 Err(fault) => {
1412 let failed = match fault {
1413 Fault::Unsigned(why) => (Code::UpdateRefused, why),
1414 Fault::Failed(why) => (Code::UpdateFailed, format!("g1t-runner couldn't be updated: {why}")),
1415 };
1416 self.write_log(&format!("g1t: {}", failed.1));
1417 self.update_failed = Some(failed);
1418 self.asked = false;
1419 if matches!(self.code(), Code::Idle | Code::UpdateFailed | Code::UpdateRefused) {
1420 let (code, extra) = self.idle(Code::Idle);
1421 self.set(code, extra);
1422 }
1423 return publish(&self.app);
1424 }
1425 };
1426 if let Some(bytes) = found.program {
1427 self.program = Some((found.version.clone(), bytes));
1428 }
1429 if !found.newer {
1430 self.program = None;
1431 }
1432 // The sandbox's image is the release's version; one older takes the newest.
1433 let sandbox = self.app.state::<Shared>().now.lock().unwrap().sandbox.clone();
1434 let launcher = self.run.as_ref().is_some_and(|run| run.engine == Engine::Launcher);
1435 let image = launcher
1436 && found.images
1437 && sandbox.is_some_and(|status| status.linux().state != State::Absent && status.image_version.as_deref().is_some_and(|have| native::newer(&found.version, have)));
1438 let program = self.program.is_some();
1439 self.with_updates(|updates| {
1440 updates.checked_at = Some(SystemTime::now());
1441 updates.program = program;
1442 updates.image = image;
1443 updates.ready = (program || image).then(|| found.version.clone());
1444 });
1445 if program || image {
1446 self.write_log(&format!("g1t: g1t-runner {} is ready, and installs as each kind of job is idle.", found.version));
1447 } else {
1448 self.asked = false;
1449 }
1450 // It worked: what the last failure said goes.
1451 if self.update_failed.take().is_some() && matches!(self.code(), Code::UpdateFailed | Code::UpdateRefused) {
1452 self.set(Code::Idle, Extra::default());
1453 }
1454 publish(&self.app);
1455 }
1456
1457 /// Whether a waiting update may go in: "Download updates by
1458 /// themselves" is on, or the person asked for it. Turned off since it
1459 /// downloaded, it no longer waits.
1460 fn allowed(&mut self) -> bool {
1461 if self.asked || config::settings(&self.app).auto_update {
1462 return true;
1463 }
1464 self.program = None;
1465 self.with_updates(|updates| {
1466 updates.program = false;
1467 updates.image = false;
1468 updates.ready = None;
1469 });
1470 false
1471 }
1472
1473 /// Puts a waiting update in, kind by kind, as each kind of job is idle:
1474 /// true when it started something, which is waited for. Never in the
1475 /// middle of a job.
1476 fn install(&mut self) -> bool {
1477 let image = self.with_updates(|updates| updates.image);
1478 if (self.program.is_none() && !image) || !self.allowed() {
1479 return false;
1480 }
1481 let Some((engine, busy, listening)) = self.run.as_ref().map(|run| (run.engine, run.busy, run.listening)) else { return false };
1482 if engine != Engine::Launcher {
1483 // A runner in Docker or on this computer is the program: stopped between jobs, started on the new one.
1484 if busy || !listening {
1485 return false;
1486 }
1487 let Some((version, bytes)) = self.program.take() else { return false };
1488 self.set(Code::Updating, detail(format!("Updating g1t-runner to {version}.")));
1489 self.halt();
1490 self.put(version, &bytes);
1491 self.not_before = Instant::now();
1492 return true;
1493 }
1494 let Some(status) = self.app.state::<Shared>().now.lock().unwrap().sandbox.clone() else { return false };
1495 if self.program.is_some() {
1496 let running = native_kinds(&status);
1497 if running.is_empty() {
1498 // Nothing runs on the program: it is replaced now, and
1499 // kinds() starts what was drained on the new one first,
1500 // before the image, which takes minutes, is updated.
1501 let (version, bytes) = self.program.take().expect("checked above");
1502 self.put(version, &bytes);
1503 return false;
1504 } else if !status.per_kind() {
1505 // A launcher from before kinds of job stopped on their own: the whole sandbox stops between jobs.
1506 if busy {
1507 return false;
1508 }
1509 let (version, bytes) = self.program.take().expect("checked above");
1510 self.set(Code::Updating, detail(format!("Updating g1t-runner to {version}.")));
1511 self.halt_as(Down::Drain);
1512 self.put(version, &bytes);
1513 self.with_updates(|updates| updates.image = true);
1514 self.not_before = Instant::now();
1515 return true;
1516 } else if let Some(idle) = running.iter().find(|kind| kind.job.is_none()) {
1517 // Stopped after any job it takes meanwhile; replaced once it has.
1518 let kind = idle.id.clone();
1519 self.with_updates(|updates| updates.installing = vec![kind.clone()]);
1520 self.kind_step(Step::Drain(kind), None);
1521 return true;
1522 }
1523 }
1524 // Linux jobs take the image once they have no job (`update` drains them itself too).
1525 let image = self.with_updates(|updates| updates.image);
1526 if image && status.linux().job.is_none() {
1527 self.with_updates(|updates| updates.installing.push("linux".into()));
1528 self.sandbox_step(Step::Update);
1529 return true;
1530 }
1531 false
1532 }
1533
1534 /// Puts a downloaded program in place, with nothing running on it.
1535 fn put(&mut self, version: String, bytes: &[u8]) {
1536 match native::put(&folder(&self.app), bytes, &version) {
1537 Ok(()) => {
1538 self.write_log(&format!("g1t: g1t-runner {version} is in place."));
1539 if self.run.as_ref().is_none_or(|run| run.engine != Engine::Launcher) {
1540 self.note(None, Some(version));
1541 }
1542 }
1543 Err(why) => {
1544 let why = format!("g1t-runner {version} couldn't be put in place: {why}");
1545 self.write_log(&format!("g1t: {why}"));
1546 self.update_failed = Some((Code::UpdateFailed, why));
1547 }
1548 }
1549 self.done_with(|updates| {
1550 updates.program = false;
1551 updates.installing.retain(|kind| kind == "linux");
1552 });
1553 }
1554
1555 /// Part of an update is done: what waits is said again.
1556 fn done_with(&mut self, change: impl FnOnce(&mut Updates)) {
1557 let left = self.with_updates(|updates| {
1558 change(updates);
1559 if !updates.program && !updates.image {
1560 updates.ready = None;
1561 }
1562 updates.program || updates.image
1563 });
1564 if !left {
1565 self.asked = false;
1566 }
1567 publish(&self.app);
1568 }
1569
1570 // --- The sandbox (launcher.rs) ------------------------------------------------
1571
1572 /// Starts the sandbox for `workspace`: registered with it the first
1573 /// time, with a token from the site; from its own registration after.
1574 fn start_sandbox(&mut self, workspace: String) {
1575 let app = self.app.clone();
1576 let server = config::server(&app);
1577 let binary = match self.ensure_binary(&server) {
1578 Ok(binary) => binary,
1579 Err(fault) => return self.not_installed(workspace, None, fault),
1580 };
1581 let dir = native_dir(&app, Backend::Sandboxed);
1582 let mut status = match launcher::status(&binary, &dir) {
1583 Ok(status) => status,
1584 Err(why) => return self.no_status(why),
1585 };
1586 self.seen(&status);
1587 // Nothing here can be sandboxed: why, and how to fix it; looked at again in a while.
1588 if !status.anything_available() {
1589 self.not_before = Instant::now() + LOOK_AGAIN;
1590 let (code, extra) = shown(&status);
1591 return self.set(code, extra);
1592 }
1593 // Another backend's registration goes; the sandbox's own is kept for its workspace.
1594 if Registration::load(&app).is_some_and(|r| r.backend != Backend::Sandboxed) {
1595 self.set(Code::Starting, detail("Removing this computer's earlier registration."));
1596 self.forget();
1597 }
1598 let kept = SandboxRegistration::load(&app);
1599 let ours = kept.as_ref().is_some_and(|k| k.server == server.as_str() && k.workspace == workspace);
1600 let made = status.capabilities.iter().any(|c| c.state != State::Absent) || status.state != State::Absent;
1601 if !ours && made && kept.is_none() {
1602 // Made by hand (`g1t-runner sandbox up`), and there is one per computer: it is the person's to remove.
1603 self.not_before = Instant::now() + LOOK_AGAIN;
1604 return self.set(Code::SandboxTaken, Extra::default());
1605 }
1606 if !ours && made {
1607 // The app's sandbox, registered with another workspace or server.
1608 self.set(Code::Starting, detail("Removing this computer's sandbox for another workspace."));
1609 self.forget_sandbox();
1610 status = match launcher::status(&binary, &dir) {
1611 Ok(status) => status,
1612 Err(why) => return self.no_status(why),
1613 };
1614 }
1615 // The kinds of job the person stopped are stopped here too, before
1616 // anything starts (the launcher keeps them off); with every kind
1617 // stopped, nothing starts.
1618 let kinds = config::settings(&app).runner_capabilities;
1619 if status.per_kind() {
1620 let stopping: Vec<String> = status.capabilities.iter().filter(|c| !kinds.on(&c.id) && !c.off()).map(|c| c.id.clone()).collect();
1621 for kind in &stopping {
1622 if let Err(why) = launcher::down_only(&binary, &dir, kind) {
1623 self.write_log(&format!("g1t: {} couldn't be stopped: {why}", diagnosis::kind_label(kind)));
1624 }
1625 }
1626 if !stopping.is_empty() {
1627 status = match launcher::status(&binary, &dir) {
1628 Ok(status) => status,
1629 Err(why) => return self.no_status(why),
1630 };
1631 self.seen(&status);
1632 }
1633 }
1634 let wanted: Vec<String> = status.capabilities.iter().filter(|c| c.available && kinds.on(&c.id)).map(|c| c.id.clone()).collect();
1635 if status.capabilities.iter().any(|c| c.available) && wanted.is_empty() {
1636 self.not_before = Instant::now() + LOOK_AGAIN;
1637 return self.set(Code::KindsStopped, Extra::default());
1638 }
1639 let mut token = None;
1640 if !ours || !kept.as_ref().is_some_and(|k| k.registered) || status.unregistered() {
1641 match self.token.take() {
1642 Some((for_workspace, given)) if for_workspace == workspace => token = Some(given),
1643 _ => return self.want(&workspace),
1644 }
1645 SandboxRegistration { server: server.to_string(), workspace: workspace.clone(), registered: false }.save(&app);
1646 }
1647 self.hold_workspace(&workspace);
1648 let generation = self.generation + 1;
1649 self.generation = generation;
1650 self.run = Some(Run::new(generation, Engine::Launcher, Backend::Sandboxed, workspace.clone(), Process::Sandbox(None), token.is_some()));
1651 // A new release's image first, then the sandbox starts again.
1652 let image = self.with_updates(|updates| std::mem::take(&mut updates.image));
1653 let step = if image && status.linux().state != State::Absent { Step::Update } else { Step::Up };
1654 if step == Step::Update {
1655 self.with_updates(|updates| updates.installing.push("linux".into()));
1656 } else if image {
1657 self.done_with(|_| {});
1658 }
1659 let name = backend::machine_name();
1660 let url = server.as_str().trim_end_matches('/').to_owned();
1661 let up = launcher::Up { url: &url, name: &name, labels: "desktop", token: token.as_deref(), only: wanted.iter().map(String::as_str).collect() };
1662 let (args, starting) = match step {
1663 Step::Update => (launcher::update_args(&dir), vec![]),
1664 _ => (launcher::up_args(&dir, &up), wanted.clone()),
1665 };
1666 if let Err(why) = self.spawn_step(step, args, up.token) {
1667 self.run = None;
1668 return self.not_started(workspace, token, why);
1669 }
1670 self.now_starting(starting);
1671 self.set(Code::Starting, detail(STARTING_SANDBOX));
1672 }
1673
1674 /// Says which kinds of job a launcher command is starting now.
1675 fn now_starting(&self, kinds: Vec<String>) {
1676 let changed = {
1677 let shared = self.app.state::<Shared>();
1678 let mut now = shared.now.lock().unwrap();
1679 let changed = now.starting != kinds;
1680 now.starting = kinds;
1681 changed
1682 };
1683 if changed {
1684 publish(&self.app);
1685 }
1686 }
1687
1688 /// Each kind of job as the person has it: one they stopped is stopped
1689 /// (`down --only`), one they started is started (`up --only`), and one
1690 /// that should run and doesn't while another runs is tried again in a
1691 /// while: every five minutes while the release has no sandbox images.
1692 /// One launcher command at a time, each leaving the others as they are.
1693 fn kinds(&mut self, workspace: Option<&str>) {
1694 if !self.run.as_ref().is_some_and(|run| run.engine == Engine::Launcher) {
1695 return;
1696 }
1697 let Some(status) = self.app.state::<Shared>().now.lock().unwrap().sandbox.clone() else { return };
1698 if !status.per_kind() {
1699 return;
1700 }
1701 let on = config::settings(&self.app).runner_capabilities;
1702 // A kind of job drained for a new program starts on the new one, once it is in.
1703 let replacing = self.program.is_some();
1704 for capability in &status.capabilities {
1705 if !on.on(&capability.id) && !capability.off() {
1706 return self.kind_step(Step::Stop(capability.id.clone()), None);
1707 }
1708 if on.on(&capability.id) && capability.off() && capability.available && !(replacing && capability.id != "linux") {
1709 return self.start_kind(capability, workspace);
1710 }
1711 }
1712 // Nothing runs: the sandbox as a whole starts again (sandbox_stopped).
1713 if !status.running() {
1714 self.retry.clear();
1715 return;
1716 }
1717 let now = Instant::now();
1718 for capability in &status.capabilities {
1719 let id = capability.id.as_str();
1720 let wanting = on.on(id) && !capability.off() && capability.available && matches!(capability.state, State::Error | State::Stopped | State::Absent);
1721 if !wanting {
1722 self.retry.retain(|(kind, _, _)| kind != id);
1723 continue;
1724 }
1725 let images = id == "linux" && status.trouble().is_some_and(|(cause, _)| launcher::why(&cause) == launcher::Why::NoImages);
1726 match self.retry.iter().position(|(kind, _, _)| kind == id) {
1727 // Just seen not running: tried again in a while.
1728 None => self.retry.push((id.to_owned(), now + again(images, 1), 1)),
1729 Some(at) if now >= self.retry[at].1 => {
1730 let tries = self.retry[at].2 + 1;
1731 self.retry[at] = (id.to_owned(), now + again(images, tries), tries);
1732 self.write_log(&format!("g1t: trying {} again.", diagnosis::kind_label(id)));
1733 return self.start_kind(capability, workspace);
1734 }
1735 Some(_) => {}
1736 }
1737 }
1738 }
1739
1740 /// Starts one kind of job; one never registered needs a token from the
1741 /// site first, which is asked for, and it starts once it is here.
1742 fn start_kind(&mut self, capability: &launcher::Capability, workspace: Option<&str>) {
1743 let mut token = None;
1744 if capability.state == State::Absent {
1745 let Some(workspace) = workspace else { return };
1746 match self.token.take() {
1747 Some((for_workspace, given)) if for_workspace == workspace => token = Some(given),
1748 other => {
1749 self.token = other;
1750 if wanted(&self.app).is_none() {
1751 *self.app.state::<Shared>().wanted.lock().unwrap() = Some(workspace.to_owned());
1752 let _ = self.app.emit_to(EventTarget::webview(frame::SITE), WANTED_EVENT, workspace.to_owned());
1753 }
1754 return;
1755 }
1756 }
1757 }
1758 self.kind_step(Step::Start(capability.id.clone()), token);
1759 }
1760
1761 /// `up --only` or `down --only` one kind of job, while the rest run on.
1762 fn kind_step(&mut self, step: Step, token: Option<String>) {
1763 let dir = native_dir(&self.app, Backend::Sandboxed);
1764 let (args, starting, said) = match &step {
1765 Step::Start(kind) => {
1766 let url = config::server(&self.app).as_str().trim_end_matches('/').to_owned();
1767 let name = backend::machine_name();
1768 let up = launcher::Up { url: &url, name: &name, labels: "desktop", token: token.as_deref(), only: vec![kind.as_str()] };
1769 (launcher::up_args(&dir, &up), vec![kind.clone()], format!("starting {}", diagnosis::kind_label(kind)))
1770 }
1771 Step::Stop(kind) => (launcher::down_only_args(&dir, kind), vec![], format!("stopping {}", diagnosis::kind_label(kind))),
1772 Step::Drain(kind) => (launcher::drain_only_args(&dir, kind), vec![], format!("stopping {} after their job, to update g1t-runner", diagnosis::kind_label(kind))),
1773 Step::Up | Step::Update => return,
1774 };
1775 self.write_log(&format!("g1t: {said}."));
1776 match self.spawn_step(step, args, token.as_deref()) {
1777 Ok(()) => self.now_starting(starting),
1778 Err(why) => self.write_log(&format!("g1t: {why}")),
1779 }
1780 }
1781
1782 /// `sandbox status` didn't answer: a `g1t-runner` from before its
1783 /// launcher, which a newer release replaces, or one that failed.
1784 fn no_status(&mut self, why: String) {
1785 self.write_log(&format!("g1t: the sandbox's status: {why}"));
1786 self.failures += 1;
1787 if why.contains("older than its sandbox launcher") {
1788 let (server, folder) = (config::server(&self.app), folder(&self.app));
1789 if let Ok(Found { version, program: Some(bytes), .. }) = look_for_release(&server, &folder, None)
1790 && native::put(&folder, &bytes, &version).is_ok()
1791 {
1792 self.note(None, Some(version));
1793 self.not_before = Instant::now();
1794 return;
1795 }
1796 self.not_before = Instant::now() + MOST_BACKOFF;
1797 return self.set(Code::NoLauncher, detail(why));
1798 }
1799 self.not_before = Instant::now() + LOOK_AGAIN;
1800 self.set(Code::SandboxFailed, Extra { detail: Some(why), wait_seconds: Some(LOOK_AGAIN.as_secs()), ..Extra::default() });
1801 }
1802
1803 /// Runs a launcher command for the sandbox's run, reading its output.
1804 fn spawn_step(&mut self, step: Step, args: Vec<std::ffi::OsString>, token: Option<&str>) -> Result<(), String> {
1805 let binary = native::binary(&folder(&self.app));
1806 let mut command = launcher::command(&binary, args);
1807 launcher::with_token(&mut command, token);
1808 let mut child = command.spawn().map_err(|e| format!("g1t-runner sandbox {} could not start: {e}", step.name()))?;
1809 let _ = std::fs::write(folder(&self.app).join("pid"), child.id().to_string());
1810 let Some(generation) = self.run.as_ref().map(|run| run.generation) else {
1811 native::stop(&mut child);
1812 return Ok(());
1813 };
1814 self.follow(generation, &mut child);
1815 let run = self.run.as_mut().expect("checked above");
1816 run.json = None;
1817 run.process = Process::Sandbox(Some((step, child)));
1818 Ok(())
1819 }
1820
1821 /// `update` on the running sandbox, while it has no job.
1822 fn sandbox_step(&mut self, step: Step) {
1823 if self.run.as_ref().is_none_or(|run| run.step().is_some()) {
1824 return;
1825 }
1826 let dir = native_dir(&self.app, Backend::Sandboxed);
1827 if let Err(why) = self.spawn_step(step, launcher::update_args(&dir), None) {
1828 self.write_log(&format!("g1t: {why}"));
1829 }
1830 }
1831
1832 /// Asks the sandbox how it is, every few seconds, on a thread of its own.
1833 fn poll(&mut self) {
1834 let Some(run) = self.run.as_mut().filter(|run| run.engine == Engine::Launcher) else { return };
1835 if run.polling || run.polled_at.is_some_and(|at| at.elapsed() < launcher::STATUS_EVERY) {
1836 return;
1837 }
1838 run.polling = true;
1839 run.polled_at = Some(Instant::now());
1840 let (tx, generation) = (self.tx.clone(), run.generation);
1841 let binary = native::binary(&folder(&self.app));
1842 let dir = native_dir(&self.app, Backend::Sandboxed);
1843 let spawned = std::thread::Builder::new().name("g1t-sandbox-status".into()).spawn(move || {
1844 let _ = tx.send(Ask::Sandbox(generation, launcher::status(&binary, &dir).map(Box::new)));
1845 });
1846 if spawned.is_err() {
1847 run.polling = false;
1848 }
1849 }
1850
1851 /// What a poll said.
1852 fn polled(&mut self, generation: u64, status: Result<Box<Status>, String>) {
1853 let Some(run) = self.run.as_mut().filter(|run| run.generation == generation) else { return };
1854 run.polling = false;
1855 if std::mem::take(&mut run.stale) {
1856 return;
1857 }
1858 match status {
1859 Ok(status) => self.sandbox_now(*status),
1860 // Once is nothing: the next poll asks again.
1861 Err(why) => self.write_log(&format!("g1t: the sandbox's status: {why}")),
1862 }
1863 }
1864
1865 /// Keeps what a status says for the tray, settings and the site.
1866 fn seen(&mut self, status: &Status) {
1867 let shared = self.app.state::<Shared>();
1868 let mut now = shared.now.lock().unwrap();
1869 now.sandbox = Some(status.clone());
1870 if let Some(version) = status.version() {
1871 now.version = Some(version);
1872 }
1873 now.job = status.job().map(launcher::Job::said);
1874 }
1875
1876 /// The sandbox as it is now, while it is the run.
1877 fn sandbox_now(&mut self, status: Status) {
1878 let had = self.app.state::<Shared>().now.lock().unwrap().job.clone();
1879 let Some(run) = self.run.as_mut() else { return };
1880 let step = run.step();
1881 let job = status.job().map(launcher::Job::said);
1882 let was = had.filter(|_| run.busy);
1883 run.busy = job.is_some();
1884 run.listening = status.running();
1885 let update_failed = self.update_failed.clone();
1886 if was != job {
1887 if let Some(ended) = &was {
1888 self.write_log(&format!("g1t: {ended} ended."));
1889 }
1890 if let Some(took) = &job {
1891 self.write_log(&format!("g1t: Took {took}."));
1892 }
1893 }
1894 self.seen(&status);
1895 match &step {
1896 Some(Step::Up) => return self.set(Code::Starting, detail(STARTING_SANDBOX)),
1897 Some(Step::Update) if status.state == State::Updating => return self.set(Code::Updating, detail("Updating the sandbox to the newest image.")),
1898 _ => {}
1899 }
1900 let (code, extra) = shown(&status);
1901 // Every kind of job stopped by the person: nothing to start again.
1902 if step.is_none() && status.all_off() && !status.running() {
1903 self.run = None;
1904 self.generation += 1;
1905 self.retry.clear();
1906 self.not_before = Instant::now() + LOOK_AGAIN;
1907 return self.set(Code::KindsStopped, Extra::default());
1908 }
1909 if step.is_none() && !status.running() && !matches!(status.state, State::Starting | State::Updating) {
1910 return self.sandbox_stopped(&status, code, extra);
1911 }
1912 match (code, update_failed) {
1913 (Code::Idle, Some((failed, why))) => self.set(failed, detail(why)),
1914 (code, _) => self.set(code, extra),
1915 }
1916 }
1917
1918 /// The sandbox stopped by itself, or never got going: started again,
1919 /// waiting longer each time, or registered again when that is why.
1920 fn sandbox_stopped(&mut self, status: &Status, code: Code, extra: Extra) {
1921 let error = status.error.clone().or_else(|| extra.detail.clone()).unwrap_or_default();
1922 if self.registration_trouble(&error) {
1923 return;
1924 }
1925 self.run = None;
1926 self.generation += 1;
1927 self.failures += 1;
1928 // A release without the sandbox's images is looked at again every few minutes.
1929 let wait = if code == Code::WaitingForImage { launcher::IMAGES_AGAIN } else { again(false, self.failures) };
1930 self.not_before = Instant::now() + wait;
1931 let (code, extra) = match code {
1932 Code::Idle | Code::Busy | Code::Starting | Code::Updating => (Code::SandboxFailed, Extra { detail: status.error.clone().or_else(|| some_text("The sandbox stopped by itself.")), ..Extra::default() }),
1933 code => (code, extra),
1934 };
1935 self.set(code, Extra { wait_seconds: Some(wait.as_secs()), ..extra });
1936 }
1937
1938 /// When the sandbox's trouble is its registration: true when the app
1939 /// has seen to it, and the next start registers again.
1940 fn registration_trouble(&mut self, error: &str) -> bool {
1941 match launcher::why(error) {
1942 launcher::Why::TokenRefused | launcher::Why::Unregistered => {
1943 if let Some(mut kept) = SandboxRegistration::load(&self.app) {
1944 kept.registered = false;
1945 kept.save(&self.app);
1946 }
1947 self.halt();
1948 self.not_before = Instant::now();
1949 true
1950 }
1951 launcher::Why::Forgotten => {
1952 self.halt();
1953 self.forget_sandbox();
1954 self.not_before = Instant::now();
1955 true
1956 }
1957 _ => false,
1958 }
1959 }
1960
1961 /// A launcher command ended: what it printed last is the sandbox's status.
1962 fn launched(&mut self, generation: u64) {
1963 let Some(run) = self.run.as_mut().filter(|run| run.generation == generation) else { return };
1964 let Process::Sandbox(slot) = &mut run.process else { return };
1965 let Some((step, mut child)) = slot.take() else { return };
1966 let worked = child.wait().is_ok_and(|status| status.success());
1967 let _ = std::fs::remove_file(folder(&self.app).join("pid"));
1968 let printed = run.json.take().unwrap_or_default().join("\n");
1969 run.stale = run.polling;
1970 let with_token = run.with_token;
1971 let status = launcher::parse(&printed);
1972 {
1973 let shared = self.app.state::<Shared>();
1974 let mut now = shared.now.lock().unwrap();
1975 now.starting.clear();
1976 now.download = None;
1977 }
1978 let error = match (&status, worked) {
1979 (Ok(status), true) => status.error.clone().filter(|_| !status.running()),
1980 (Ok(status), false) => Some(status.error.clone().unwrap_or_else(|| format!("g1t-runner sandbox {} failed.", step.name()))),
1981 (Err(why), _) => Some(why.clone()),
1982 };
1983 let status = status.ok();
1984 let running = status.as_ref().is_some_and(Status::running);
1985 if let Some(error) = &error {
1986 self.write_log(&format!("g1t: sandbox {}: {error}", step.name()));
1987 }
1988 // Drained for a new program, which goes in on the next look; one
1989 // that didn't stop leaves the update for the next one, rather than
1990 // being asked again and again.
1991 if let (Step::Drain(_), Some(error)) = (&step, &error) {
1992 self.program = None;
1993 self.update_failed = Some((Code::UpdateFailed, format!("g1t-runner couldn't be updated: {error}")));
1994 self.done_with(|updates| {
1995 updates.program = false;
1996 updates.installing.retain(|kind| kind == "linux");
1997 });
1998 }
1999 // One kind of job started or stopped: how the sandbox is now says
2000 // the rest, and one that didn't start is tried again in a while.
2001 if matches!(step, Step::Start(_) | Step::Stop(_) | Step::Drain(_)) {
2002 if let Some(status) = status {
2003 self.sandbox_now(status);
2004 }
2005 return;
2006 }
2007 // Registered: from now on it starts with no token.
2008 if step == Step::Up && with_token && (error.is_none() || running) {
2009 let app = self.app.clone();
2010 if let Some(run) = self.run.as_mut() {
2011 run.with_token = false;
2012 let registration = Registration { server: config::server(&app).to_string(), workspace: run.workspace.clone(), backend: Backend::Sandboxed };
2013 SandboxRegistration { server: registration.server.clone(), workspace: registration.workspace.clone(), registered: true }.save(&app);
2014 registration.save(&app);
2015 }
2016 }
2017 // The image is taken, or failed to be: the next look says whether another waits.
2018 if step == Step::Update {
2019 self.done_with(|updates| {
2020 updates.image = false;
2021 updates.installing.retain(|kind| kind != "linux");
2022 });
2023 }
2024 if let Some(error) = error.clone() {
2025 if self.registration_trouble(&error) {
2026 return;
2027 }
2028 if step == Step::Update {
2029 self.update_failed = Some((Code::UpdateFailed, format!("The sandbox's image couldn't be updated: {error}")));
2030 } else if !running {
2031 // Nothing runs: tidied away, and tried again in a while;
2032 // a release without the sandbox's images every few minutes.
2033 self.halt();
2034 self.failures += 1;
2035 let (code, cause, fix) = status
2036 .as_ref()
2037 .and_then(diagnosis::sandbox_trouble)
2038 .unwrap_or_else(|| (diagnosis::sandbox_code(launcher::why(&error)), error.clone(), None));
2039 let wait = if code == Code::WaitingForImage { launcher::IMAGES_AGAIN } else { again(false, self.failures) };
2040 self.not_before = Instant::now() + wait;
2041 // The cards say why from what `up` said, not from the stopped sandbox.
2042 if let Some(failed) = status {
2043 self.app.state::<Shared>().now.lock().unwrap().sandbox = Some(failed);
2044 }
2045 return self.set(code, Extra { detail: Some(cause), fix, wait_seconds: Some(wait.as_secs()), ..Extra::default() });
2046 }
2047 } else if step == Step::Up {
2048 self.failures = 0;
2049 } else {
2050 self.update_failed = None;
2051 }
2052 if step == Step::Update && !running {
2053 // Updated while stopped: it starts again with the new image.
2054 self.run = None;
2055 self.generation += 1;
2056 self.not_before = Instant::now();
2057 return;
2058 }
2059 if let Some(status) = status {
2060 self.sandbox_now(status);
2061 }
2062 }
2063}
2064
2065/// What the tray says while the sandbox starts.
2066const STARTING_SANDBOX: &str = "Starting the sandbox. The first time, it downloads and checks the sandbox's image, which takes a few minutes.";
2067
2068/// The newest release, signed, and its program when it is newer than the
2069/// one in `folder` and isn't already `waiting`: downloaded and checked
2070/// against its SHA-256. On the update thread, never the runner's.
2071fn look_for_release(server: &Url, folder: &std::path::Path, waiting: Option<&str>) -> Result<Found, Fault> {
2072 let manifest = native::latest(server)?;
2073 let newer = native::installed(folder).is_none_or(|have| native::newer(&manifest.version, &have));
2074 let program = if newer && waiting != Some(manifest.version.as_str()) {
2075 Some(native::download(server, &manifest).map_err(|why| Fault::Failed(format!("{} didn't download: {why}", manifest.version)))?)
2076 } else {
2077 None
2078 };
2079 Ok(Found { images: manifest.has_images(), version: manifest.version, newer, program })
2080}
2081
2082fn some_text(text: &str) -> Option<String> {
2083 Some(text.to_owned())
2084}
2085
2086/// How long before trying again, the `tries`th time: every few minutes
2087/// while the release has no sandbox images, else longer each time.
2088fn again(images: bool, tries: u32) -> Duration {
2089 if images { launcher::IMAGES_AGAIN } else { Duration::from_secs(15 * 2u64.pow(tries.min(6))).min(MOST_BACKOFF) }
2090}
2091
2092/// What the app shows for how the sandbox is, with no launcher command
2093/// running: what its runners do while one runs (each kind of job's card
2094/// says the rest), else what is wrong with Linux jobs.
2095fn shown(status: &Status) -> (Code, Extra) {
2096 if status.job().is_some() {
2097 return (Code::Busy, Extra::default());
2098 }
2099 if status.running() {
2100 return (Code::Idle, Extra::default());
2101 }
2102 if let Some((code, cause, fix)) = diagnosis::sandbox_trouble(status) {
2103 return (code, Extra { detail: Some(cause), fix, ..Extra::default() });
2104 }
2105 match status.linux().state {
2106 State::Starting => (Code::Starting, detail(STARTING_SANDBOX)),
2107 State::Updating => (Code::Updating, detail("Updating the sandbox to the newest image.")),
2108 _ if status.all_off() => (Code::KindsStopped, Extra::default()),
2109 _ => (Code::SandboxFailed, detail("The sandbox isn't running.")),
2110 }
2111}
2112
2113/// What `register-and-run` reads: where g1t is, the runner's name and
2114/// labels, and the token, the first time only. The app updates the runner,
2115/// so the runner does not update itself; registering again takes the
2116/// place of this computer's earlier runner of the same name.
2117fn environment(server: &Url, backend: Backend, token: Option<&str>) -> Vec<(&'static str, String)> {
2118 let mut envs = vec![
2119 ("G1T_RUNNER_URL", server.as_str().trim_end_matches('/').to_owned()),
2120 ("G1T_RUNNER_NAME", backend::machine_name()),
2121 ("G1T_RUNNER_LABELS", "desktop".to_owned()),
2122 ("G1T_RUNNER_REPLACE", "1".to_owned()),
2123 ("G1T_RUNNER_NO_AUTO_UPDATE", "1".to_owned()),
2124 ];
2125 if backend == Backend::Host {
2126 envs.push(("G1T_RUNNER_NO_DOCKER", "1".to_owned()));
2127 }
2128 if let Some(token) = token {
2129 envs.push(("G1T_RUNNER_TOKEN", token.to_owned()));
2130 }
2131 envs
2132}
2133
2134#[cfg(test)]
2135mod tests {
2136 use super::*;
2137
2138 fn view(code: Code, job: Option<&str>) -> View {
2139 let facts = Facts { workspace: Some("acme".into()), backend: "sandboxed", machine: "box".into(), job: job.map(str::to_owned), ..Facts::default() };
2140 let diagnosed = diagnosis::diagnose(code, &facts);
2141 View {
2142 chip: diagnosis::chip(&diagnosed),
2143 diagnosis: diagnosed,
2144 closed: diagnosis::closed(&facts),
2145 running: code == Code::Idle,
2146 version: None,
2147 backend: Backend::Sandboxed,
2148 workspace: Some("acme".into()),
2149 workspaces: vec![],
2150 enabled: true,
2151 paused: false,
2152 link: None,
2153 machine: "box".into(),
2154 platform: "windows".into(),
2155 log: vec![],
2156 }
2157 }
2158
2159 #[test]
2160 fn the_tray_says_what_the_runner_is_doing() {
2161 assert_eq!(headline(&view(Code::Idle, None)), "Runner: Waiting for jobs");
2162 assert_eq!(headline(&view(Code::Busy, Some("Build (acme/web)"))), "Runner: Running Build (acme/web)");
2163 assert_eq!(headline(&view(Code::NoDocker, None)), "Runner: Not running: Docker isn't running");
2164 assert_eq!(headline(&view(Code::Busy, Some(&"x".repeat(200)))).chars().count(), 60);
2165 }
2166
2167 #[test]
2168 fn the_runner_is_told_where_and_who_and_the_token_only_once() {
2169 let server = Url::parse("https://g1t.sh/").unwrap();
2170 let envs = environment(&server, Backend::Host, Some("g1trt_abc"));
2171 let get = |name: &str| envs.iter().find(|(n, _)| *n == name).map(|(_, v)| v.as_str());
2172 assert_eq!(get("G1T_RUNNER_URL"), Some("https://g1t.sh"));
2173 assert_eq!(get("G1T_RUNNER_LABELS"), Some("desktop"));
2174 assert_eq!(get("G1T_RUNNER_NO_DOCKER"), Some("1"));
2175 assert_eq!(get("G1T_RUNNER_NO_AUTO_UPDATE"), Some("1"));
2176 assert_eq!(get("G1T_RUNNER_TOKEN"), Some("g1trt_abc"));
2177 let again = environment(&server, Backend::Docker, None);
2178 assert!(!again.iter().any(|(name, _)| *name == "G1T_RUNNER_TOKEN" || *name == "G1T_RUNNER_NO_DOCKER"));
2179 }
2180
2181 fn status(json: &str) -> Status {
2182 launcher::parse(json).unwrap()
2183 }
2184
2185 #[test]
2186 fn the_sandbox_shows_what_its_runners_do_and_linux_trouble_first() {
2187 let running = status(r#"{"schema":1,"state":"running","capabilities":[{"id":"linux","available":true,"state":"running"},{"id":"windows","available":false,"state":"absent","cause":"Windows Sandbox is not turned on, or this edition of Windows has none (Home does not)."}]}"#);
2188 assert_eq!(shown(&running).0, Code::Idle);
2189 let busy = status(r#"{"schema":1,"state":"running","job":{"kind":"workflow","id":"j","name":"build","repo":"acme/web"}}"#);
2190 assert_eq!(shown(&busy).0, Code::Busy);
2191 let starting = status(r#"{"schema":1,"state":"starting","capabilities":[{"id":"linux","available":true,"state":"starting"}]}"#);
2192 assert_eq!(shown(&starting).0, Code::Starting);
2193 let updating = status(r#"{"schema":1,"state":"updating","capabilities":[{"id":"linux","available":true,"state":"updating"}]}"#);
2194 assert_eq!(shown(&updating).0, Code::Updating);
2195 // Windows jobs run while WSL is missing: the runner waits for jobs,
2196 // and the Linux card says what is wrong (diagnosis.rs).
2197 let no_wsl = status(r#"{"schema":1,"state":"error","error":"WSL is not installed, and the sandbox for Linux jobs is a WSL distribution of its own.","capabilities":[
2198 {"id":"linux","available":false,"state":"error","cause":"WSL is not installed, and the sandbox for Linux jobs is a WSL distribution of its own.","fix":"Open a terminal as administrator and run `wsl --install --no-distribution`."},
2199 {"id":"windows","available":true,"state":"running"}]}"#);
2200 assert_eq!(shown(&no_wsl).0, Code::Idle);
2201 let (code, extra) = shown(&status(r#"{"schema":1,"state":"error","error":"WSL is not installed, and the sandbox for Linux jobs is a WSL distribution of its own.","capabilities":[
2202 {"id":"linux","available":false,"state":"error","cause":"WSL is not installed, and the sandbox for Linux jobs is a WSL distribution of its own."},
2203 {"id":"windows","available":false,"state":"absent"}]}"#));
2204 assert_eq!(code, Code::NoWsl);
2205 assert!(extra.detail.unwrap().starts_with("WSL is not installed"));
2206 // 0.3.0 without its images, on Home: waiting for them, not failing.
2207 let images = status(r#"{"schema":1,"state":"error","error":"release 0.3.0 has no sandbox images","capabilities":[{"id":"linux","available":true,"state":"error","turned_off":false},{"id":"windows","available":false,"state":"absent","turned_off":false}]}"#);
2208 assert_eq!(shown(&images).0, Code::WaitingForImage);
2209 assert_eq!(again(true, 5), launcher::IMAGES_AGAIN);
2210 assert_eq!(again(false, 1), Duration::from_secs(30));
2211 assert_eq!(again(false, 9), MOST_BACKOFF);
2212 // Every kind of job stopped by the person.
2213 let off = status(r#"{"schema":1,"state":"stopped","capabilities":[{"id":"linux","available":true,"state":"stopped","turned_off":true},{"id":"windows","available":true,"state":"stopped","turned_off":true}]}"#);
2214 assert_eq!(shown(&off).0, Code::KindsStopped);
2215 let failed = status(r#"{"schema":1,"state":"error","error":"the sandbox did not start within 180 seconds","capabilities":[{"id":"linux","available":true,"state":"error"}]}"#);
2216 let (code, extra) = shown(&failed);
2217 assert_eq!((code, extra.detail.as_deref()), (Code::SandboxFailed, Some("the sandbox did not start within 180 seconds")));
2218 let stopped = status(r#"{"schema":1,"state":"stopped","capabilities":[{"id":"linux","available":true,"state":"stopped"},{"id":"windows","available":true,"state":"stopped"}]}"#);
2219 assert_eq!(shown(&stopped).0, Code::SandboxFailed);
2220 }
2221
2222 #[test]
2223 fn a_new_runner_lives_in_local_data_and_an_old_one_stays_put() {
2224 let base = std::env::temp_dir().join(format!("g1t-desktop-folders-{}", std::process::id()));
2225 let _ = std::fs::remove_dir_all(&base);
2226 let (local, roaming) = (base.join("local").join("runner"), base.join("roaming").join("runner"));
2227 assert_eq!(chosen_folder(local.clone(), roaming.clone()), local);
2228 std::fs::create_dir_all(&roaming).unwrap();
2229 assert_eq!(chosen_folder(local.clone(), roaming.clone()), roaming);
2230 std::fs::create_dir_all(&local).unwrap();
2231 assert_eq!(chosen_folder(local.clone(), roaming), local);
2232 let _ = std::fs::remove_dir_all(&base);
2233 }
2234
2235 #[test]
2236 fn when_is_said_as_the_site_reads_it() {
2237 let at = |seconds: u64| rfc3339(SystemTime::UNIX_EPOCH + Duration::from_secs(seconds));
2238 assert_eq!(at(0), "1970-01-01T00:00:00Z");
2239 assert_eq!(at(1_791_806_645), "2026-10-12T12:04:05Z");
2240 // The day after February 29th of a leap year.
2241 assert_eq!(at(1_709_251_199 + 1), "2024-03-01T00:00:00Z");
2242 assert_eq!(at(951_782_400), "2000-02-29T00:00:00Z");
2243 }
2244
2245 /// What is running on the program itself, which an update drains first:
2246 /// Windows jobs running or starting, not Linux jobs, nor ones stopped.
2247 #[test]
2248 fn an_update_drains_only_what_runs_on_the_program() {
2249 let kinds = |json: &str| native_kinds(&status(json)).iter().map(|c| c.id.clone()).collect::<Vec<_>>();
2250 assert_eq!(
2251 kinds(r#"{"schema":1,"state":"running","capabilities":[{"id":"linux","available":true,"state":"running","turned_off":false},{"id":"windows","available":true,"state":"running","turned_off":false}]}"#),
2252 ["windows"]
2253 );
2254 assert!(kinds(r#"{"schema":1,"state":"running","capabilities":[{"id":"linux","available":true,"state":"running","turned_off":false},{"id":"windows","available":true,"state":"stopped","turned_off":true}]}"#).is_empty());
2255 assert!(kinds(r#"{"schema":1,"state":"running","capabilities":[{"id":"linux","available":true,"state":"running"},{"id":"windows","available":false,"state":"absent"}]}"#).is_empty());
2256 }
2257
2258 #[test]
2259 fn the_site_names_workspaces_in_its_own_words() {
2260 let offered: Vec<Offered> = serde_json::from_str(r#"[{"slug":"acme","name":"Acme"},{"slug":"solo"}]"#).unwrap();
2261 assert_eq!(offered[1], Offered { slug: "solo".into(), name: None });
2262 }
2263}