Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(desktop): native loopback probe, 'found but needs upgrade' state
Salman Qureshi5ac8668b511a
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.tomlindex 40bdec50..f68bb228 100644--- a/apps/desktop/src-tauri/Cargo.toml+++ b/apps/desktop/src-tauri/Cargo.toml@@ -32,7 +32,7 @@ tauri-plugin-log = "2.10"# OS keychain for device tokens: Keychain, Credential Manager, Secret Service.keyring = { version = "3", features = ["apple-native", "windows-native", "sync-secret-service", "crypto-rust"] }# Runtime installer: GitHub release download, sha256, web.tar.gz.-reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "http2"] }+reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "http2", "json"] }sha2 = "0.10"flate2 = "1"tar = "0.4"diff --git a/apps/desktop/src-tauri/src/commands/local.rs b/apps/desktop/src-tauri/src/commands/local.rsindex c156ecb1..de8f3a61 100644--- a/apps/desktop/src-tauri/src/commands/local.rs+++ b/apps/desktop/src-tauri/src/commands/local.rs@@ -33,7 +33,7 @@ const DEFAULT_PORT: u16 = 6174;/// Subcommands the app is allowed to run on the user's behalf. Anything/// else is refused; the frontend is not a shell.-const ALLOWED_SUBCOMMANDS: &[&str] = &["service", "start", "stop", "status", "devices", "setup", "--version"];+const ALLOWED_SUBCOMMANDS: &[&str] = &["service", "start", "stop", "status", "devices", "setup", "upgrade", "--version"];pub(crate) fn mercury_home() -> PathBuf {if let Ok(home) = env::var("MERCURY_HOME") {@@ -183,6 +183,28 @@ pub fn detect_local_runtime() -> LocalRuntime {}}+/// `GET /api/health` on loopback, from the native side. The webview cannot+/// ask directly when the runtime predates CORS support (< 1.5.0): the browser+/// hides the answer. From here we see the real thing and can tell the user+/// "found, but needs an upgrade" instead of "not running".+#[tauri::command]+pub async fn probe_local_health(port: u16) -> Result<serde_json::Value, String> {+ let client = reqwest::Client::builder()+ .timeout(std::time::Duration::from_millis(2500))+ .no_proxy()+ .build()+ .map_err(|e| e.to_string())?;+ let res = client+ .get(format!("http://127.0.0.1:{port}/api/health"))+ .send()+ .await+ .map_err(|e| format!("unreachable: {e}"))?;+ if !res.status().is_success() {+ return Err(format!("status {}", res.status()));+ }+ res.json::<serde_json::Value>().await.map_err(|e| e.to_string())+}+/// The runtime's per-boot, owner-only attach token (src/web/auth.ts). The/// app runs as the same user, so reading it is the same trust the CLI has.#[tauri::command]diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex c4437428..d96ccbb3 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -38,6 +38,7 @@ pub fn run() {.invoke_handler(tauri::generate_handler![commands::local::detect_local_runtime,commands::local::read_attach_token,+ commands::local::probe_local_health,commands::local::run_mercury,commands::installer::install_runtime,commands::secrets::secret_get,diff --git a/apps/desktop/src/shell/Onboarding.tsx b/apps/desktop/src/shell/Onboarding.tsxindex 3e4ef473..c853d88e 100644--- a/apps/desktop/src/shell/Onboarding.tsx+++ b/apps/desktop/src/shell/Onboarding.tsx@@ -6,6 +6,7 @@ import { AddRemote } from "./AddRemote";import { InstallRuntime } from "./InstallRuntime";import { desktop, type LocalRuntime } from "./tauri";import { LOCAL_CONNECTION_ID, useConnections } from "./connections";+import { checkCompat, SUPPORTED_API } from "./compat";/*** First run (design v2, board 01): where should Mercury run?@@ -17,6 +18,7 @@ import { LOCAL_CONNECTION_ID, useConnections } from "./connections";type LocalProbe =| { state: "probing" }| { state: "running"; runtime: LocalRuntime; health: HealthInfo }+ | { state: "outdated"; runtime: LocalRuntime; health: HealthInfo }| { state: "installed"; runtime: LocalRuntime }| { state: "missing"; runtime: LocalRuntime };@@ -31,10 +33,15 @@ export function Onboarding({ onDone, canCancel }: { onDone: () => void; canCanceasync function probe() {setLocal({ state: "probing" });const runtime = await desktop.detectLocalRuntime();- const baseUrl = `http://127.0.0.1:${runtime.port}`;try {- const health = await api.health.probe(baseUrl, null, 2500);- setLocal({ state: "running", runtime, health });+ const raw = await desktop.probeLocalHealth(runtime.port);+ const health = raw as unknown as HealthInfo;+ const compat = checkCompat(health.apiVersion);+ if (!compat.ok && compat.reason === "runtime-too-old") {+ setLocal({ state: "outdated", runtime, health });+ } else {+ setLocal({ state: "running", runtime, health });+ }} catch {setLocal(runtime.binaryPath ? { state: "installed", runtime } : { state: "missing", runtime });}@@ -58,6 +65,22 @@ export function Onboarding({ onDone, canCancel }: { onDone: () => void; canCance}}+ async function upgradeLocal() {+ setBusy("upgrade");+ setError(null);+ try {+ const out = await desktop.runMercury(["upgrade"]);+ if (out.code !== 0) throw new Error((out.stderr || out.stdout).trim().split(/\r?\n/)[0] || `mercury upgrade exited with ${out.code}`);+ // The upgrade restarts the daemon; give the listener a moment.+ await new Promise((r) => setTimeout(r, 4000));+ await probe();+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setBusy(null);+ }+ }+async function startLocal() {if (local.state !== "installed") return;setBusy("start");@@ -99,12 +122,12 @@ export function Onboarding({ onDone, canCancel }: { onDone: () => void; canCance<div className="grid w-full grid-cols-1 gap-4 md:grid-cols-3">{/* 1 · Found here */}- <Card highlighted={local.state === "running"} badge={local.state === "running" ? `FOUND ON ${platformLabel.toUpperCase()}` : undefined}>+ <Card highlighted={local.state === "running" || local.state === "outdated"} badge={local.state === "running" || local.state === "outdated" ? `FOUND ON ${platformLabel.toUpperCase()}` : undefined}><CardTitle>Use the Mercury that's here</CardTitle>{local.state === "probing" && <CardBody>Looking for a running Mercury…</CardBody>}{local.state === "running" && (<>- <CardBody>Mercury {local.health.version} is running{local.runtime.serviceInstalled ? " as a service" : ""}. The app attaches to it. Sessions, memory, skills and plugins stay exactly where they are.</CardBody>+ <CardBody>Mercury {local.health.version || local.runtime.binaryVersion || ""} is running{local.runtime.serviceInstalled ? " as a service" : ""}. The app attaches to it. Sessions, memory, skills and plugins stay exactly where they are.</CardBody><Facts rows={[["bin", local.runtime.binaryPath ?? "—"],["daemon", `running · pid ${local.health.pid}`],@@ -115,6 +138,14 @@ export function Onboarding({ onDone, canCancel }: { onDone: () => void; canCance<PrimaryButton onClick={() => void useLocal()} disabled={busy !== null}>{busy === "local" ? "Connecting…" : "Connect"}</PrimaryButton></>)}+ {local.state === "outdated" && (+ <>+ <CardBody>Mercury {local.health.version || local.runtime.binaryVersion || ""} is running here, but it predates the desktop API (needs API v{SUPPORTED_API.min}, Mercury 1.5 or newer). Upgrade it and the app attaches; nothing else changes.</CardBody>+ <Facts rows={[["bin", local.runtime.binaryPath ?? "—"], ["daemon", `running · pid ${local.health.pid}`], ["api", `127.0.0.1:${local.runtime.port} · v${local.health.apiVersion ?? "0"}`]]} />+ <div className="flex-1" />+ <PrimaryButton onClick={() => void upgradeLocal()} disabled={busy !== null}>{busy === "upgrade" ? "Upgrading…" : "Upgrade Mercury"}</PrimaryButton>+ </>+ )}{local.state === "installed" && (<><CardBody>Mercury {local.runtime.binaryVersion ?? ""} is installed but not running. Start it and the app will attach.</CardBody>diff --git a/apps/desktop/src/shell/tauri.ts b/apps/desktop/src/shell/tauri.tsindex 0d896e6c..99ac1418 100644--- a/apps/desktop/src/shell/tauri.ts+++ b/apps/desktop/src/shell/tauri.ts@@ -53,6 +53,19 @@ export const desktop = {return invoke<LocalRuntime>("detect_local_runtime");},+ /**+ * Loopback health from the native side. Works against runtimes that+ * predate CORS (the webview's own fetch would be blinded by the browser).+ */+ async probeLocalHealth(port: number): Promise<Record<string, unknown>> {+ if (!isTauri) {+ const res = await fetch(`http://127.0.0.1:${port}/api/health`);+ if (!res.ok) throw new Error(`status ${res.status}`);+ return (await res.json()) as Record<string, unknown>;+ }+ return invoke<Record<string, unknown>>("probe_local_health", { port });+ },+readAttachToken(): Promise<string | null> {if (!isTauri) return Promise.resolve(null);return invoke<string | null>("read_attach_token");diff --git a/apps/desktop/src/shell/useRuntime.ts b/apps/desktop/src/shell/useRuntime.tsindex 35e86928..2a031cfa 100644--- a/apps/desktop/src/shell/useRuntime.ts+++ b/apps/desktop/src/shell/useRuntime.ts@@ -3,6 +3,7 @@ import api, { type HealthInfo } from "@/lib/api";import { configureApi } from "@/lib/connection";import { checkCompat, type Compat } from "./compat";import { credentialFor, type Connection } from "./connections";+import { desktop } from "./tauri";/*** Bring one connection to life: resolve its credential, point the shared@@ -65,7 +66,12 @@ export function useRuntime(connection: Connection, onUnauthorized: () => void):});try {- const health = await api.health.probe(connection.baseUrl, token);+ // A local runtime is asked from the native side first: that works+ // even when it predates CORS, so an old runtime reads as+ // "incompatible, upgrade" rather than "offline".+ const health: HealthInfo = connection.kind === "local"+ ? ((await desktop.probeLocalHealth(portOf(connection.baseUrl))) as unknown as HealthInfo)+ : await api.health.probe(connection.baseUrl, token);if (cancelled) return;const compat = checkCompat(health.apiVersion);if (!compat.ok) {@@ -94,3 +100,12 @@ export function useRuntime(connection: Connection, onUnauthorized: () => void):return { status, retry };}++function portOf(baseUrl: string): number {+ try {+ const port = Number(new URL(baseUrl).port);+ return Number.isInteger(port) && port > 0 ? port : 6174;+ } catch {+ return 6174;+ }+}diff --git a/src/web/api/status.ts b/src/web/api/status.tsindex e06fd849..f1efbfaf 100644--- a/src/web/api/status.ts+++ b/src/web/api/status.ts@@ -47,7 +47,10 @@ let runtimeVersion = '';function versionString(): string {if (runtimeVersion) return runtimeVersion;try {+ // tsup bakes the version into the bundle (globalThis.__MERCURY_VERSION__);+ // package.json is only reachable when running from source.runtimeVersion = process.env.MERCURY_CHANNEL_VERSION+ || (globalThis as { __MERCURY_VERSION__?: string }).__MERCURY_VERSION__|| JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', 'package.json'), 'utf8')).version|| '';} catch { runtimeVersion = ''; }