Skip to content

Commit 3bd3b27

Browse files
fix(ui): recover when the managed CLI is missing (#131974)
* fix(linux): recover when managed CLI is missing * fix(linux): clear stale gateway during CLI recovery
1 parent 5b605da commit 3bd3b27

4 files changed

Lines changed: 206 additions & 19 deletions

File tree

‎apps/linux/src-tauri/src/cli.rs‎

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,14 @@ use std::ffi::OsString;
44
use std::fmt;
55
use std::path::PathBuf;
66
use std::process::{Command, Output, Stdio};
7+
use std::sync::atomic::{AtomicBool, Ordering};
8+
use std::sync::Arc;
79

810
#[derive(Clone, Debug)]
911
pub struct OpenClawCli {
1012
executable: PathBuf,
1113
openclaw_home: PathBuf,
14+
available: Arc<AtomicBool>,
1215
}
1316

1417
#[derive(Debug)]
@@ -61,9 +64,14 @@ impl OpenClawCli {
6164
Self {
6265
executable,
6366
openclaw_home,
67+
available: Arc::new(AtomicBool::new(true)),
6468
}
6569
}
6670

71+
pub fn is_available(&self) -> bool {
72+
self.available.load(Ordering::Acquire)
73+
}
74+
6775
fn verify(&self) -> Result<(), CliError> {
6876
let output = self.output(["--version"])?;
6977
if output.status.success() {
@@ -92,9 +100,15 @@ impl OpenClawCli {
92100
I: IntoIterator<Item = S>,
93101
S: AsRef<std::ffi::OsStr>,
94102
{
95-
self.command(args)?
96-
.output()
97-
.map_err(|error| CliError::Spawn(format!("Failed to run OpenClaw CLI: {error}")))
103+
let mut command = self.command(args)?;
104+
command.stdout(Stdio::piped()).stderr(Stdio::piped());
105+
let child = command.spawn().map_err(|error| {
106+
self.available.store(false, Ordering::Release);
107+
CliError::Spawn(format!("Failed to run OpenClaw CLI: {error}"))
108+
})?;
109+
child.wait_with_output().map_err(|error| {
110+
CliError::Spawn(format!("Failed to read OpenClaw CLI output: {error}"))
111+
})
98112
}
99113

100114
pub fn json<T, I, S>(&self, args: I) -> Result<(T, Output), CliError>
@@ -159,7 +173,8 @@ pub fn openclaw_home() -> Result<PathBuf, CliError> {
159173

160174
#[cfg(test)]
161175
mod tests {
162-
use super::output_tail;
176+
use super::{output_tail, OpenClawCli};
177+
use std::path::PathBuf;
163178

164179
#[test]
165180
fn output_tail_keeps_the_last_twelve_nonempty_lines() {
@@ -175,4 +190,16 @@ mod tests {
175190
assert_eq!(output_tail(output.as_bytes()), Some(expected));
176191
assert_eq!(output_tail(b"\n \n"), None);
177192
}
193+
194+
#[test]
195+
fn missing_executable_invalidates_the_cached_cli() {
196+
let cli = OpenClawCli::new(
197+
PathBuf::from("openclaw-test-executable-that-does-not-exist"),
198+
PathBuf::new(),
199+
);
200+
201+
assert!(cli.is_available());
202+
assert!(cli.output(["--version"]).is_err());
203+
assert!(!cli.is_available());
204+
}
178205
}

‎apps/linux/src-tauri/src/main.rs‎

Lines changed: 72 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -459,11 +459,7 @@ impl DesktopState {
459459
let cli = match self.resolve_cli() {
460460
Ok(cli) => cli,
461461
Err(CliError::Missing) => {
462-
app.state::<gateway_ws::GatewayClient>()
463-
.clear_configuration(app);
464-
let snapshot = GatewaySnapshot::missing_cli();
465-
self.update_tray(&snapshot);
466-
return Ok(snapshot);
462+
return self.show_missing_cli(app, explicit_local, None);
467463
}
468464
Err(error) => return Err(error.to_string()),
469465
};
@@ -485,7 +481,7 @@ impl DesktopState {
485481
let navigated = self.navigate_local(app, &ready.dashboard_url, false, None, true, true)?;
486482
self.update_tray(&ready.snapshot);
487483
if navigated {
488-
self.start_watchdog(app.clone());
484+
self.start_watchdog(app.clone(), cli);
489485
}
490486
Ok(ready.snapshot)
491487
}
@@ -547,7 +543,7 @@ impl DesktopState {
547543
})?;
548544
self.update_tray(&ready.snapshot);
549545
if navigated {
550-
self.start_watchdog(app.clone());
546+
self.start_watchdog(app.clone(), cli);
551547
}
552548
Ok(ready.snapshot)
553549
}
@@ -581,7 +577,7 @@ impl DesktopState {
581577
let navigated = self.navigate_local(app, &ready.dashboard_url, false, None, true, true)?;
582578
self.update_tray(&ready.snapshot);
583579
if navigated {
584-
self.start_watchdog(app.clone());
580+
self.start_watchdog(app.clone(), cli);
585581
}
586582
Ok(ready.snapshot)
587583
}
@@ -746,7 +742,14 @@ impl DesktopState {
746742
}
747743

748744
pub(crate) fn resolve_cli(&self) -> Result<OpenClawCli, CliError> {
749-
if let Some(cli) = self.inner.cli.lock().expect("CLI mutex poisoned").clone() {
745+
if let Some(cli) = self
746+
.inner
747+
.cli
748+
.lock()
749+
.expect("CLI mutex poisoned")
750+
.clone()
751+
.filter(OpenClawCli::is_available)
752+
{
750753
return Ok(cli);
751754
}
752755
let cli = OpenClawCli::discover()?;
@@ -777,6 +780,35 @@ impl DesktopState {
777780
}
778781
}
779782

783+
fn show_missing_cli(
784+
&self,
785+
app: &AppHandle,
786+
force: bool,
787+
expected_generation: Option<u64>,
788+
) -> Result<GatewaySnapshot, String> {
789+
let snapshot = GatewaySnapshot::missing_cli();
790+
let navigation = self.show_local(app, "missingCli", force, expected_generation);
791+
if !local_recovery_owns_gateway(&navigation) {
792+
return Ok(snapshot);
793+
}
794+
app.state::<gateway_ws::GatewayClient>()
795+
.clear_configuration(app);
796+
self.update_tray(&snapshot);
797+
navigation.map(|_| snapshot)
798+
}
799+
800+
fn show_cli_recovery_error(&self, app: &AppHandle, generation: u64, error: CliError) {
801+
let mut snapshot = GatewaySnapshot::missing_cli();
802+
snapshot.status = "CLI unavailable".to_string();
803+
snapshot.detail = Some(error.to_string());
804+
let navigation = self.show_local(app, "error", false, Some(generation));
805+
if local_recovery_owns_gateway(&navigation) {
806+
app.state::<gateway_ws::GatewayClient>()
807+
.clear_configuration(app);
808+
self.update_tray(&snapshot);
809+
}
810+
}
811+
780812
fn poll_pending_approvals(&self, app: &AppHandle, cli: &OpenClawCli, generation: u64) {
781813
let pending = match pending_approvals::fetch(cli) {
782814
Ok(pending) => pending,
@@ -902,7 +934,7 @@ impl DesktopState {
902934
.is_ok_and(|navigation| navigation.watchdog_is_current(generation))
903935
}
904936

905-
fn start_watchdog(&self, app: AppHandle) {
937+
fn start_watchdog(&self, app: AppHandle, mut cli: OpenClawCli) {
906938
let generation = {
907939
let Ok(mut navigation) = self.inner.navigation.lock() else {
908940
return;
@@ -921,9 +953,6 @@ impl DesktopState {
921953
let Ok(_operation) = state.inner.operation.try_lock() else {
922954
continue;
923955
};
924-
let Ok(cli) = state.resolve_cli() else {
925-
continue;
926-
};
927956
let snapshot = match gateway::status(&cli) {
928957
Ok(snapshot) => snapshot,
929958
Err(error) => GatewaySnapshot::reconnecting(error),
@@ -958,6 +987,19 @@ impl DesktopState {
958987
return;
959988
}
960989
if let Ok(_operation) = state.inner.operation.try_lock() {
990+
if !cli.is_available() {
991+
match state.resolve_cli() {
992+
Ok(discovered) => cli = discovered,
993+
Err(error) => {
994+
if matches!(error, CliError::Missing) {
995+
let _ = state.show_missing_cli(&app, false, Some(generation));
996+
} else {
997+
state.show_cli_recovery_error(&app, generation, error);
998+
}
999+
return;
1000+
}
1001+
}
1002+
}
9611003
let snapshot = match gateway::status(&cli) {
9621004
Ok(snapshot) => snapshot,
9631005
Err(error) => GatewaySnapshot::reconnecting(error),
@@ -1011,9 +1053,16 @@ fn local_mode(snapshot: &GatewaySnapshot) -> &'static str {
10111053
}
10121054
}
10131055

1056+
fn local_recovery_owns_gateway(navigation: &Result<bool, String>) -> bool {
1057+
!matches!(navigation, Ok(false))
1058+
}
1059+
10141060
#[cfg(test)]
10151061
mod navigation_tests {
1016-
use super::{is_active_onboarding_url, is_release_version, NavigationState, Url};
1062+
use super::{
1063+
is_active_onboarding_url, is_release_version, local_recovery_owns_gateway, NavigationState,
1064+
Url,
1065+
};
10171066

10181067
#[test]
10191068
fn only_active_onboarding_preserves_the_dashboard_during_reconnect() {
@@ -1097,6 +1146,15 @@ mod navigation_tests {
10971146
assert!(navigation.remote_dashboard);
10981147
}
10991148

1149+
#[test]
1150+
fn local_recovery_clears_retained_gateway_unless_remote_navigation_won() {
1151+
assert!(local_recovery_owns_gateway(&Ok(true)));
1152+
assert!(local_recovery_owns_gateway(&Err(
1153+
"local navigation failed".to_string()
1154+
)));
1155+
assert!(!local_recovery_owns_gateway(&Ok(false)));
1156+
}
1157+
11001158
#[test]
11011159
fn first_run_url_preserves_gateway_base_path_query_and_auth_fragment() {
11021160
let mut navigation = NavigationState::default();

‎apps/linux/ui/main.js‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -593,7 +593,15 @@ void refreshGateways();
593593
window.setInterval(() => void refreshGateways(), 2000);
594594

595595
const mode = new URLSearchParams(window.location.search).get("mode");
596-
if (mode === "reconnecting") {
596+
if (mode === "missingCli") {
597+
render({
598+
description: "Install the OpenClaw CLI to connect to a local Gateway.",
599+
dot: "idle",
600+
eyebrow: "CLI REQUIRED",
601+
showInstall: true,
602+
title: "OpenClaw needs the CLI",
603+
});
604+
} else if (mode === "reconnecting") {
597605
render({
598606
activity: "Retrying every few seconds…",
599607
description: "The gateway connection dropped. OpenClaw will restore the dashboard automatically.",
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import assert from "node:assert/strict";
2+
import { readFileSync } from "node:fs";
3+
import vm from "node:vm";
4+
import { test } from "vitest";
5+
6+
const dashboardSource = readFileSync(new URL("../apps/linux/ui/main.js", import.meta.url), "utf8");
7+
8+
function fakeElement() {
9+
const classes = new Set(["hidden"]);
10+
return {
11+
className: "",
12+
classList: {
13+
contains: (name: string) => classes.has(name),
14+
toggle(name: string, force?: boolean) {
15+
const enabled = force ?? !classes.has(name);
16+
if (enabled) classes.add(name);
17+
else classes.delete(name);
18+
},
19+
},
20+
disabled: false,
21+
textContent: "",
22+
value: "stable",
23+
addEventListener() {},
24+
append() {},
25+
removeAttribute() {},
26+
replaceChildren() {},
27+
setAttribute() {},
28+
};
29+
}
30+
31+
test("missing CLI mode offers installation without retrying bootstrap", async () => {
32+
const elements = new Map<string, ReturnType<typeof fakeElement>>();
33+
const invoked: string[] = [];
34+
const document = {
35+
createElement: fakeElement,
36+
querySelector(selector: string) {
37+
if (!elements.has(selector)) elements.set(selector, fakeElement());
38+
return elements.get(selector);
39+
},
40+
};
41+
const window = {
42+
__TAURI__: {
43+
core: {
44+
invoke(command: string) {
45+
invoked.push(command);
46+
if (command === "discover_gateways") return Promise.resolve([]);
47+
return Promise.resolve({ phase: "connected" });
48+
},
49+
},
50+
event: { listen: async () => () => {} },
51+
},
52+
location: { search: "?mode=missingCli" },
53+
setInterval() {},
54+
};
55+
56+
await vm.runInNewContext(`(async () => { ${dashboardSource}\n})()`, {
57+
document,
58+
URLSearchParams,
59+
window,
60+
});
61+
62+
assert.equal(elements.get("#title")?.textContent, "OpenClaw needs the CLI");
63+
assert.equal(elements.get("#install-controls")?.classList.contains("hidden"), false);
64+
assert.equal(invoked.includes("bootstrap"), false);
65+
});
66+
67+
test("CLI recovery errors offer both retry and reinstall", async () => {
68+
const elements = new Map<string, ReturnType<typeof fakeElement>>();
69+
const document = {
70+
createElement: fakeElement,
71+
querySelector(selector: string) {
72+
if (!elements.has(selector)) elements.set(selector, fakeElement());
73+
return elements.get(selector);
74+
},
75+
};
76+
const window = {
77+
__TAURI__: {
78+
core: { invoke: () => Promise.resolve([]) },
79+
event: { listen: async () => () => {} },
80+
},
81+
location: { search: "?mode=error" },
82+
setInterval() {},
83+
};
84+
85+
await vm.runInNewContext(`(async () => { ${dashboardSource}\n})()`, {
86+
document,
87+
URLSearchParams,
88+
window,
89+
});
90+
91+
assert.equal(elements.get("#primary-action")?.textContent, "Try again");
92+
assert.equal(elements.get("#action-controls")?.classList.contains("hidden"), false);
93+
assert.equal(elements.get("#install-controls")?.classList.contains("hidden"), false);
94+
});

0 commit comments

Comments
 (0)