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