Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

fix(managed-apps): one-click install died, and installed apps read as "not installed", under systemd

antinrml79aad1bbcfa2
diff --git a/CLAUDE.md b/CLAUDE.md
index 4a4d651b..b40d7e26 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -207,13 +207,20 @@ to `resources/` (rr) and drive any project from one manifest:
in THIS repo** (it used to live untracked under `~/.openclaw/workspace/`, so a fresh
clone could not start the Browser at all and the `-nopw` → `-rfbauth` hardening had no
version control). The script refuses to start without a VNC password file. Two further
- host-side facts the repo cannot carry, and the feature dies quietly without either: (1) `loginctl enable-linger rahman`, or the unit stops at
- logout and never starts at boot; (2) the drop-in
- `/etc/systemd/system/mso.service.d/user-bus.conf` setting
- `Environment=XDG_RUNTIME_DIR=/run/user/1001` — a system unit running as `User=rahman`
- gets NO user-bus address, so without it every `systemctl --user` call fails with
- "Failed to connect to bus: No medium found". `lib/camoufox/service.ts` reports that
- as an error rather than as "not installed", so the panel tells you which one it is.
+ host-side facts that `scripts/install.sh` NOW CARRIES ITSELF, and that the feature dies
+ quietly without: (1) `loginctl enable-linger <user>`, or the unit stops at
+ logout and never starts at boot; (2) `Environment=XDG_RUNTIME_DIR=/run/user/%U` in
+ mso.service — a system unit running as `User=` gets NO user-bus address, so without it
+ every `systemctl --user` call fails with "Failed to connect to bus: No medium found".
+ `lib/camoufox/service.ts` reports that as an error rather than as "not installed", so the
+ panel tells you which one it is.
+ Treating these as un-carryable host lore was itself the bug: a host set up by
+ `scripts/install.sh` alone had neither, so the Browser app looked uninstalled and every
+ managed-app install died at the step that registers its user service. The installer sets
+ both now, and `lib/managed-apps/user-bus.ts` re-derives the bus address at call time so a
+ cockpit installed BEFORE this change is not left broken until someone re-runs the
+ installer. An existing host still needs the linger (`sudo loginctl enable-linger <user>`);
+ re-running `scripts/install.sh` applies the rest.
(3) The unit is deliberately left **`disabled`** with `Restart=no` + `RuntimeMaxSec=2h`:
the UI toggle is plain `start`/`stop` and must NEVER go back to `enable --now`, or every
click re-arms boot autostart — that is how it once ran 26 h with zero viewers. Ship
diff --git a/docs/MANAGED-APPS.md b/docs/MANAGED-APPS.md
index 02400b1a..7140874b 100644
--- a/docs/MANAGED-APPS.md
+++ b/docs/MANAGED-APPS.md
@@ -418,6 +418,43 @@ leave a broken install; so files created since the snapshot stay, and the result
## 7. Operations
+### The user bus, and why an installed app can read as "not installed"
+
+Both apps run as systemd **USER** units, so everything in §3 goes through
+`systemctl --user`. That command finds the user's systemd instance through
+`XDG_RUNTIME_DIR` — and **a systemd SYSTEM unit with `User=` does not have one**, because
+it inherits no login session. Inside such a cockpit every `systemctl --user` answers:
+
+```
+Failed to connect to bus: No medium found
+```
+
+Two failures fall out of that single gap, and neither one names it:
+
+| Symptom | Actually happening |
+|---|---|
+| One-click install always fails, `exited with code 1` | `scripts/managed-app-install` reached `systemctl --user daemon-reload` and died under `set -e` — *after* the upstream installer had finished. The unit file is written but never enabled |
+| An installed, running app shows as **not installed**, with an Install button that fails the same way forever | `detect()` discarded the `--user` answer, found nothing system-scope, then fell through to `which <cmd>` — which also missed, because a unit's PATH has no `~/.local/bin`, where both CLIs install their launcher |
+
+Handled in three places, deliberately overlapping so that no single one has to be right:
+
+- `lib/managed-apps/user-bus.ts` re-derives `XDG_RUNTIME_DIR=/run/user/<uid>` **at call
+ time**, whenever the current value has no bus socket behind it. This is what repairs a
+ cockpit that was installed before the fix, without re-running the installer, and it also
+ covers the boot race where mso.service starts before logind creates the directory.
+- `lib/managed-apps/runner.ts` → `resolveCommand()` falls back to `~/.local/bin` and
+ `~/.bun/bin` when PATH misses — the same lesson `hermes_cmd()` in
+ `scripts/managed-app-install` had already learned the hard way.
+- `scripts/install.sh` writes `Environment=XDG_RUNTIME_DIR=/run/user/%U` plus a PATH that
+ includes those directories, and runs `loginctl enable-linger`. **Linger is not optional**:
+ without it `/run/user/<uid>` is destroyed at logout and the variable points at nothing.
+
+`scripts/managed-app-install` preflights the bus *before* doing ~20 minutes of work, and
+when it cannot reach one it prints the exact host commands to fix it rather than failing at
+the last step. When detection is only *guessing* that an app is absent, `ManagedAppView.diagnostic`
+says so and the install screen shows it — the mistake `lib/camoufox/service.ts` already refuses
+to make, and which its test *"does not disguise an unreachable user bus as 'not installed'"* pins.
+
| Var | Read at | Notes |
|---|---|---|
| `NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE` | **build** (client) + runtime (server, middleware) | e.g. `{id}.mso.rahmanef.com`. Presence of `{id}` is what turns split mode on |
diff --git a/frontend/slices/managed-apps/update-panel.tsx b/frontend/slices/managed-apps/update-panel.tsx
index ea246fbb..9b7e1ef0 100644
--- a/frontend/slices/managed-apps/update-panel.tsx
+++ b/frontend/slices/managed-apps/update-panel.tsx
@@ -134,6 +134,16 @@ export function InstallSurface({ app, icon, onChanged }: { app: ManagedAppView;
const centre = useUpdateCentre(app.id, onChanged);
return (
<Hero icon={icon} title={app.name} description={app.description}>
+ {/* "Absent" is sometimes a guess rather than a fact — see ManagedAppView.diagnostic.
+ Shown ABOVE the Install button because it is the reason that button is about to
+ fail: with no user bus, the install job dies at the step that registers the app's
+ service, every time, after doing all of its other work. */}
+ {app.diagnostic && (
+ <div className="rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-300">
+ <p className="font-medium">This reading may be wrong</p>
+ <p className="mt-1 text-amber-300/85">{app.diagnostic}</p>
+ </div>
+ )}
<InstallPanel appId={app.id} command={centre.status?.capabilities?.installCommand} centre={centre} />
<JobPanel job={centre.job} onDismiss={centre.dismiss} onCancel={centre.cancel} />
</Hero>
diff --git a/lib/managed-apps/install.test.ts b/lib/managed-apps/install.test.ts
index ad93b6b9..1745a69f 100644
--- a/lib/managed-apps/install.test.ts
+++ b/lib/managed-apps/install.test.ts
@@ -26,6 +26,7 @@ const view = (installed: boolean): ManagedAppView =>
healthy: null,
version: null,
dashboardAvailable: false,
+ diagnostic: null,
supportedActions: [],
}) as ManagedAppView;
diff --git a/lib/managed-apps/manager.test.ts b/lib/managed-apps/manager.test.ts
index 4a531d4a..ab473393 100644
--- a/lib/managed-apps/manager.test.ts
+++ b/lib/managed-apps/manager.test.ts
@@ -10,10 +10,17 @@ vi.mock("server-only", () => ({}));
vi.mock("./runner", () => ({
runProgram: vi.fn(),
commandExists: vi.fn().mockResolvedValue(false),
+ resolveCommand: vi.fn().mockResolvedValue(null),
requireProgram: vi.fn(),
}));
+// Stubbed so these tests describe MSO's behaviour rather than whether the machine
+// running them happens to have a user bus.
+vi.mock("./user-bus", () => ({
+ userBusEnv: vi.fn(() => ({ XDG_RUNTIME_DIR: "/run/user/1000" })),
+ userBusUnavailable: vi.fn(() => false),
+}));
-const { runProgram } = await import("./runner");
+const { runProgram, commandExists, resolveCommand } = await import("./runner");
const { getManagedApp, performManagedAppAction } = await import("./manager");
const ok = (stdout: string) => ({ code: 0, stdout, stderr: "" });
@@ -68,6 +75,66 @@ describe("systemd detection tells a stopped unit from one that does not exist",
});
});
+describe("detection survives the environment a systemd system unit actually gets", () => {
+ // Both cases below were live in a shipped build, on a host where Hermes was
+ // installed, enabled and serving. The panel said "not installed" and offered an
+ // Install button whose job died at the same spot every time.
+
+ it("hands the --user probe the bus address the unit never provides", async () => {
+ // mso.service runs system-scope with User=, so it inherits no login session
+ // and no XDG_RUNTIME_DIR. Without one, `systemctl --user` answers "Failed to
+ // connect to bus: No medium found" and the entire user scope is skipped.
+ systemctl({ "hermes-dashboard.service": ACTIVE });
+ await getManagedApp("hermes");
+
+ const userProbe = vi
+ .mocked(runProgram)
+ .mock.calls.find((call) => call[0] === "systemctl" && (call[1] as string[])[0] === "--user");
+ expect(userProbe).toBeDefined();
+ expect(userProbe![3]).toEqual({ XDG_RUNTIME_DIR: "/run/user/1000" });
+ });
+
+ it("finds a CLI that PATH misses instead of declaring the app absent", async () => {
+ // The second half of the same production failure: with the user bus
+ // unreachable, detection falls through to the CLI probe — and a systemd unit's
+ // PATH has no ~/.local/bin, which is exactly where both upstream installers
+ // put their launcher. resolveCommand looks there before giving up.
+ vi.mocked(runProgram).mockImplementation(async (command: string, args: readonly string[]) => {
+ if (command === "systemctl" && args[0] === "--user") {
+ return { code: 1, stdout: "", stderr: "Failed to connect to bus: No medium found" };
+ }
+ if (command === "systemctl") return NOT_FOUND;
+ return ok("");
+ });
+ vi.mocked(commandExists).mockImplementation(async (command: string) => command === "hermes");
+ vi.mocked(resolveCommand).mockResolvedValue("/home/someone/.local/bin/hermes");
+
+ const view = await getManagedApp("hermes");
+ expect(view.installed).toBe(true);
+ expect(view.installationType).toBe("package");
+ });
+
+ it("runs --version by resolved path, never by bare name", async () => {
+ // version() memoises per app id for 60 s, and earlier tests in this file
+ // already primed hermes. Step past the TTL so this asserts a real call rather
+ // than silently passing on a cache hit.
+ vi.useFakeTimers();
+ try {
+ vi.setSystemTime(new Date(Date.now() + 120_000));
+ systemctl({});
+ vi.mocked(resolveCommand).mockResolvedValue("/home/someone/.local/bin/hermes");
+ await getManagedApp("hermes");
+
+ const versionCall = vi
+ .mocked(runProgram)
+ .mock.calls.find((call) => (call[1] as string[])[0] === "--version");
+ expect(versionCall?.[0]).toBe("/home/someone/.local/bin/hermes");
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
describe("backup copies a real install instead of refusing it", () => {
let home: string;
diff --git a/lib/managed-apps/manager.ts b/lib/managed-apps/manager.ts
index 6023ab31..b74c7e14 100644
--- a/lib/managed-apps/manager.ts
+++ b/lib/managed-apps/manager.ts
@@ -3,7 +3,8 @@ import { createBackup } from "./backups";
import { getManagedAppDefinition, listManagedAppDefinitions } from "./catalog";
import { acquireOperation, activeOperation, releaseOperation } from "./lock";
import { redact } from "./redact";
-import { commandExists, requireProgram, runProgram } from "./runner";
+import { commandExists, requireProgram, resolveCommand, runProgram } from "./runner";
+import { userBusEnv, userBusUnavailable } from "./user-bus";
import type { ManagedAppAction, ManagedAppDefinition, ManagedAppId, ManagedAppLogs, ManagedAppView } from "./types";
interface Installation {
@@ -21,7 +22,13 @@ interface Installation {
// call returns both facts.
async function systemdState(service: string): Promise<"active" | "inactive" | "missing"> {
for (const scope of [["--user"], []]) {
- const result = await runProgram("systemctl", [...scope, "show", "-p", "LoadState", "-p", "ActiveState", service], 10_000);
+ // The user scope needs a bus address. mso.service is a SYSTEM unit with
+ // `User=`, which inherits no login session and therefore no
+ // XDG_RUNTIME_DIR, so without this every `--user` probe below answered
+ // "Failed to connect to bus: No medium found" and the whole scope was
+ // silently skipped — the app then looked absent no matter what was running.
+ const env = scope.length ? userBusEnv() : undefined;
+ const result = await runProgram("systemctl", [...scope, "show", "-p", "LoadState", "-p", "ActiveState", service], 10_000, env);
// Non-zero here is no systemctl at all, or no user bus — not an answer about
// the unit, so try the next scope rather than concluding anything.
if (result.code !== 0) continue;
@@ -75,8 +82,11 @@ async function version(definition: ManagedAppDefinition): Promise<string | null>
const hit = versionCache.get(definition.id);
if (hit && Date.now() - hit.at < VERSION_TTL_MS) return hit.value;
let value: string | null = null;
- if (await commandExists(definition.command)) {
- const result = await runProgram(definition.command, ["--version"], 10_000);
+ // Resolved to a path, not spawned by bare name: under systemd the unit's PATH
+ // does not contain ~/.local/bin, where both upstream CLIs install themselves.
+ const program = await resolveCommand(definition.command);
+ if (program) {
+ const result = await runProgram(program, ["--version"], 10_000);
value = result.code === 0 ? result.stdout.trim().split(/\r?\n/)[0]?.slice(0, 160) || null : null;
}
versionCache.set(definition.id, { value, at: Date.now() });
@@ -115,6 +125,12 @@ export async function getManagedApp(id: ManagedAppId): Promise<ManagedAppView> {
version: await version(definition),
dashboardAvailable: isRunning && isHealthy !== false,
supportedActions: actionsFor(installation),
+ // Only ever attached to a NEGATIVE reading. An app detected as present has
+ // been seen, and nothing about the bus can make that observation wrong.
+ diagnostic:
+ installation.type === "not-installed" && userBusUnavailable()
+ ? "MSO cannot reach this user's systemd bus, so it cannot see user services — this app may in fact be installed. Run `loginctl enable-linger` for the user, and set XDG_RUNTIME_DIR=/run/user/%U in mso.service (a drop-in under /etc/systemd/system/mso.service.d/)."
+ : null,
};
}
@@ -126,10 +142,17 @@ export async function listManagedApps(): Promise<ManagedAppView[]> {
async function runLifecycle(installation: Installation, action: "start" | "stop" | "restart"): Promise<void> {
if (installation.type === "systemd" && installation.serviceName) {
+ let lastError = "";
for (const args of [["--user", action, installation.serviceName], [action, installation.serviceName]]) {
- const result = await runProgram("systemctl", args, 30_000);
+ const result = await runProgram("systemctl", args, 30_000, args[0] === "--user" ? userBusEnv() : undefined);
if (result.code === 0) return;
+ lastError = result.stderr.trim() || result.stdout.trim() || `systemctl exited ${result.code}`;
}
+ // Falling through to the generic throw below reported every one of these as
+ // "operation unsupported for detected installation type" — served as a 409,
+ // and flatly untrue: the installation type was detected fine, systemctl just
+ // refused. An unreachable user bus surfaced as a category error about the app.
+ throw new Error(`systemctl ${action} ${installation.serviceName} failed: ${lastError.slice(0, 300)}`);
}
if (installation.type === "docker" && installation.containerName) {
await requireProgram("docker", [action, installation.containerName], 30_000);
diff --git a/lib/managed-apps/restore.ts b/lib/managed-apps/restore.ts
index 7405fbf8..05d99649 100644
--- a/lib/managed-apps/restore.ts
+++ b/lib/managed-apps/restore.ts
@@ -46,6 +46,14 @@ const message = (error: unknown): string => (error instanceof Error ? error.mess
async function assertStopped(id: ManagedAppId): Promise<void> {
const view = await getManagedApp(id);
+ // This gate decides whether it is safe to overwrite the app's state directory,
+ // so it must fail CLOSED. "not-installed" is not in the blocking set below —
+ // correctly, because restoring into an absent app is the case this feature
+ // exists for — but that answer is only safe when it is a FACT. When MSO cannot
+ // reach the user bus it cannot see user services at all, and an app that is
+ // running right now reads exactly like one that was never installed. Restoring
+ // then would copy a snapshot over the live state of a running application.
+ if (view.diagnostic) throw new Error(`cannot confirm ${view.name} is stopped — refusing to restore. ${view.diagnostic}`);
if (RESTORE_BLOCKING_STATES.has(view.state)) throw new Error(`${view.name} is ${view.state}; stop it before restoring a backup`);
}
diff --git a/lib/managed-apps/runner.test.ts b/lib/managed-apps/runner.test.ts
new file mode 100644
index 00000000..11930b0c
--- /dev/null
+++ b/lib/managed-apps/runner.test.ts
@@ -0,0 +1,83 @@
+// The defect this covers shipped: on a host where `hermes` worked fine in a
+// terminal, MSO reported it as not installed. MSO runs as a systemd unit, whose
+// PATH is /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin — and both managed-app
+// CLIs install themselves into ~/.local/bin, which is not on it. `which` missed
+// them, and detection concluded the app was absent.
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
+
+let home: string;
+
+vi.mock("node:os", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("node:os")>();
+ return { ...actual, default: { ...actual, homedir: () => home }, homedir: () => home };
+});
+
+const { resolveCommand, commandExists } = await import("./runner");
+
+/** A name no real PATH can satisfy, so only the fallback can find it. */
+const CLI = "mso-fixture-cli";
+
+beforeEach(async () => {
+ home = await fs.mkdtemp(path.join(os.tmpdir(), "mso-runner-"));
+});
+
+afterEach(async () => {
+ await fs.rm(home, { recursive: true, force: true });
+ vi.restoreAllMocks();
+});
+
+async function install(dir: string, name = CLI): Promise<string> {
+ const binDir = path.join(home, dir);
+ await fs.mkdir(binDir, { recursive: true });
+ const file = path.join(binDir, name);
+ await fs.writeFile(file, "#!/bin/sh\necho fixture\n");
+ await fs.chmod(file, 0o755);
+ return file;
+}
+
+describe("resolveCommand looks where these CLIs actually install themselves", () => {
+ it("finds a CLI in ~/.local/bin that PATH does not carry", async () => {
+ const expected = await install(".local/bin");
+ expect(await resolveCommand(CLI)).toBe(expected);
+ });
+
+ it("also covers ~/.bun/bin", async () => {
+ const expected = await install(".bun/bin");
+ expect(await resolveCommand(CLI)).toBe(expected);
+ });
+
+ it("returns null when the command genuinely is not installed", async () => {
+ expect(await resolveCommand(CLI)).toBeNull();
+ expect(await commandExists(CLI)).toBe(false);
+ });
+
+ it("ignores a match that is present but not executable", async () => {
+ // A stray file of the same name must not be reported as an installed CLI —
+ // spawning it would fail with EACCES long after detection claimed success.
+ const binDir = path.join(home, ".local/bin");
+ await fs.mkdir(binDir, { recursive: true });
+ await fs.writeFile(path.join(binDir, CLI), "not executable");
+ await fs.chmod(path.join(binDir, CLI), 0o644);
+ expect(await resolveCommand(CLI)).toBeNull();
+ });
+
+ it("still prefers PATH when PATH can answer", async () => {
+ // The fallback is a safety net, not a redirect: a command PATH resolves must
+ // keep resolving to the PATH copy.
+ // Not pinned to a literal: /bin/sh and /usr/bin/sh are both correct depending
+ // on whether the distro has merged /usr.
+ const resolved = await resolveCommand("sh");
+ expect(resolved).toMatch(/^\/(usr\/)?bin\/sh$/);
+ });
+
+ it("accepts an absolute path as itself, and rejects one that is absent", async () => {
+ const file = await install(".local/bin", "direct");
+ expect(await resolveCommand(file)).toBe(file);
+ expect(await resolveCommand(path.join(home, "nope", "missing"))).toBeNull();
+ });
+});
diff --git a/lib/managed-apps/runner.ts b/lib/managed-apps/runner.ts
index 2327522b..67f7f8f5 100644
--- a/lib/managed-apps/runner.ts
+++ b/lib/managed-apps/runner.ts
@@ -1,5 +1,8 @@
import "server-only";
import { execFile } from "node:child_process";
+import { accessSync, constants } from "node:fs";
+import { homedir } from "node:os";
+import { isAbsolute, join } from "node:path";
const MAX_OUTPUT = 128 * 1024;
@@ -9,12 +12,29 @@ export interface ProgramResult {
stderr: string;
}
-export function runProgram(command: string, args: readonly string[], timeout = 30_000): Promise<ProgramResult> {
+/**
+ * @param env extra variables merged over this process's environment. Used to hand
+ * a child the user-bus address a systemd system unit never inherits
+ * (see `user-bus.ts`); `undefined` leaves the environment untouched.
+ */
+export function runProgram(
+ command: string,
+ args: readonly string[],
+ timeout = 30_000,
+ env?: Record<string, string>,
+): Promise<ProgramResult> {
return new Promise((resolve) => {
execFile(
command,
[...args],
- { timeout, maxBuffer: MAX_OUTPUT, windowsHide: true, shell: false },
+ {
+ timeout,
+ maxBuffer: MAX_OUTPUT,
+ windowsHide: true,
+ shell: false,
+ // Merge, never replace: the child still needs PATH, HOME and the locale.
+ ...(env ? { env: { ...process.env, ...env } } : {}),
+ },
(error, stdout, stderr) => {
const code = typeof error?.code === "number" ? error.code : error ? 1 : 0;
resolve({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
@@ -23,9 +43,54 @@ export function runProgram(command: string, args: readonly string[], timeout = 3
});
}
+/**
+ * Directories that hold per-user CLIs but are absent from a systemd unit's PATH.
+ *
+ * Both upstream installers put their launcher in `~/.local/bin` — Hermes' own
+ * installer even prints "`/home/<user>/.local/bin` is not on your PATH" while
+ * doing it. systemd gives a unit
+ * `/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin` and nothing else, so `which
+ * hermes` inside mso.service fails on a host where `hermes` plainly works in a
+ * terminal. Detection then reported an installed app as absent.
+ */
+const FALLBACK_BIN_DIRS = [".local/bin", ".bun/bin"] as const;
+
+const isExecutable = (candidate: string): boolean => {
+ try {
+ accessSync(candidate, constants.X_OK);
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+/**
+ * Absolute path of a CLI, or `null` when it genuinely is not installed.
+ *
+ * Resolving to a path rather than trusting PATH means the binary that gets
+ * *detected* is the same one that later gets *run*, and that a unit's narrow PATH
+ * cannot make an installed app look missing.
+ */
+export async function resolveCommand(command: string): Promise<string | null> {
+ // Already a path: nothing to search for.
+ if (command.includes("/")) return isExecutable(command) ? command : null;
+
+ const probe = process.platform === "win32" ? "where" : "which";
+ const result = await runProgram(probe, [command], 5_000);
+ const first = result.stdout.split(/\r?\n/).map((line) => line.trim()).find(Boolean);
+ if (result.code === 0 && first && isAbsolute(first)) return first;
+
+ // PATH missed it — look where these CLIs actually install themselves before
+ // concluding the app is absent.
+ for (const dir of FALLBACK_BIN_DIRS) {
+ const candidate = join(homedir(), dir, command);
+ if (isExecutable(candidate)) return candidate;
+ }
+ return null;
+}
+
export async function commandExists(command: string): Promise<boolean> {
- const probe = process.platform === "win32" ? ["where", [command]] as const : ["which", [command]] as const;
- return (await runProgram(probe[0], probe[1], 5_000)).code === 0;
+ return (await resolveCommand(command)) !== null;
}
export async function requireProgram(command: string, args: readonly string[], timeout?: number): Promise<void> {
diff --git a/lib/managed-apps/types.ts b/lib/managed-apps/types.ts
index ecf9bc75..0de0122e 100644
--- a/lib/managed-apps/types.ts
+++ b/lib/managed-apps/types.ts
@@ -37,6 +37,15 @@ export interface ManagedAppView {
version: string | null;
dashboardAvailable: boolean;
supportedActions: ManagedAppAction[];
+ /** Why this reading may be wrong, when MSO knows that it might be.
+ *
+ * "not-installed" is normally a fact. It is a GUESS when MSO cannot reach the
+ * user's systemd bus, because both apps run as systemd USER units and that is
+ * the only place their presence is visible. Saying "not installed" flatly then
+ * sends the operator to an Install button whose job fails at the same step
+ * every time — which is exactly what happened in production. `null` when the
+ * reading is trustworthy. */
+ diagnostic: string | null;
}
export interface ManagedAppLogs {
diff --git a/lib/managed-apps/user-bus.ts b/lib/managed-apps/user-bus.ts
new file mode 100644
index 00000000..8ff4fc46
--- /dev/null
+++ b/lib/managed-apps/user-bus.ts
@@ -0,0 +1,79 @@
+import "server-only";
+import { existsSync } from "node:fs";
+
+/** Where a user's systemd instance keeps its bus socket. */
+const runtimeDirFor = (uid: number): string => `/run/user/${uid}`;
+
+/**
+ * The environment `systemctl --user` needs, when the current process has not been
+ * given one.
+ *
+ * `systemctl --user` reaches the calling user's systemd instance through
+ * XDG_RUNTIME_DIR. A login shell always has it. A systemd SYSTEM unit with
+ * `User=` never does — units start from a clean environment with no login
+ * session — so inside the packaged `mso.service` every `systemctl --user …`
+ * answers:
+ *
+ * Failed to connect to bus: No medium found
+ *
+ * At the call site that is a non-zero exit with no structure to it, which is
+ * indistinguishable from "no such unit". One missing variable therefore broke two
+ * separate user-visible things:
+ *
+ * 1. `scripts/managed-app-install` died at `systemctl --user daemon-reload`,
+ * after writing the app's unit file but before enabling it. The install had
+ * done all of its real work; it reported failure and left a unit on disk
+ * that nothing had ever started.
+ * 2. `detect()` in manager.ts discarded the `--user` answer, found nothing in
+ * the system scope, and concluded an app that was installed and running was
+ * "not installed".
+ *
+ * Resolved HERE, per call, rather than demanded from the unit file, because the
+ * same code runs two ways: under `bun run dev` from a terminal, where the
+ * variable is already set and must be left exactly as it is, and under systemd,
+ * where it never is. Patching only the generated unit would leave every cockpit
+ * that is already installed broken until its owner happened to re-run the
+ * installer.
+ *
+ * @returns env overrides to merge into the child, or `undefined` when there is
+ * nothing to add — either the caller already has a runtime dir, or no usable
+ * bus exists and no guess would help.
+ */
+export function userBusEnv(): Record<string, string> | undefined {
+ // Judged by whether a bus is actually reachable, NOT by whether the variable
+ // is merely set. Both matter:
+ //
+ // - Set and usable (a terminal, `machinectl shell`, an operator pointing at
+ // a non-default runtime dir on purpose): leave it completely alone.
+ // - Set but with nothing behind it: the unit hard-codes
+ // `XDG_RUNTIME_DIR=/run/user/%U`, which is a static string evaluated when
+ // the service starts. At boot mso.service can win the race against
+ // systemd-logind creating that directory. Trusting the variable's mere
+ // presence would disable this fallback exactly when it is needed.
+ const current = process.env.XDG_RUNTIME_DIR;
+ if (current && existsSync(`${current}/bus`)) return undefined;
+
+ const uid = typeof process.getuid === "function" ? process.getuid() : null;
+ if (uid === null) return undefined; // not POSIX; there is no user bus to find
+
+ const dir = runtimeDirFor(uid);
+ // Only claim the path when the socket is really there. `loginctl enable-linger`
+ // is what keeps `/run/user/<uid>` alive between logins; without linger it is
+ // torn down with the last session, and naming a directory that does not exist
+ // would trade one confusing failure for another one.
+ if (!existsSync(`${dir}/bus`)) return undefined;
+ return { XDG_RUNTIME_DIR: dir };
+}
+
+/**
+ * True when this process cannot talk to a user systemd instance at all.
+ *
+ * Used to tell an operator *why* an app looks absent, instead of asserting the
+ * false conclusion that it is not installed — the mistake
+ * `lib/camoufox/service.ts` already refuses to make.
+ */
+export function userBusUnavailable(): boolean {
+ const current = process.env.XDG_RUNTIME_DIR;
+ if (current && existsSync(`${current}/bus`)) return false;
+ return userBusEnv() === undefined;
+}
diff --git a/lib/os-api/http-adapter.test.ts b/lib/os-api/http-adapter.test.ts
index 58bf677b..228c6bd4 100644
--- a/lib/os-api/http-adapter.test.ts
+++ b/lib/os-api/http-adapter.test.ts
@@ -33,6 +33,7 @@ const view = (id: string, state: string) => ({
healthy: state === "running",
version: null,
dashboardAvailable: state === "running",
+ diagnostic: null,
supportedActions: ["start", "stop", "restart", "backup"],
});
diff --git a/scripts/install.sh b/scripts/install.sh
index 5d4eeb1e..95e1b0e9 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -249,6 +249,19 @@ WorkingDirectory=$DIR
EnvironmentFile=$DIR/.env.local
Environment=PORT=$PORT
Environment=HOSTNAME=$BIND
+# A system unit with User= inherits no login session, so it gets no user-bus
+# address and every \`systemctl --user\` it runs answers "Failed to connect to bus:
+# No medium found". That silently broke the managed-app installs (which create
+# systemd USER units) and made installed apps read as "not installed". %U is the
+# UID of User= above, so this stays correct if the account is renamed. Paired with
+# the \`loginctl enable-linger\` below, without which /run/user/<uid> is destroyed
+# at logout.
+Environment=XDG_RUNTIME_DIR=/run/user/%U
+# systemd would otherwise give this unit only
+# /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin. Both managed-app CLIs install
+# themselves into ~/.local/bin, so without this \`which hermes\` fails inside the
+# service on a host where it plainly works in a terminal.
+Environment=PATH=$HOME/.local/bin:$HOME/.bun/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
ExecStart=$NPM_BIN run start -- --hostname $BIND --port $PORT
Restart=always
RestartSec=5
@@ -272,6 +285,14 @@ EOF
prev_build="$(curl -fsS --max-time 3 "http://$HEALTH_HOST:$PORT/api/health" 2>/dev/null \
| sed -n 's/.*"buildId":"\([^"]*\)".*/\1/p' || true)"
+ # Makes /run/user/<uid> — where the user bus lives — exist without a login
+ # session and survive logout. The XDG_RUNTIME_DIR above names that directory, so
+ # without linger it would point at nothing after the installing shell exits.
+ # Idempotent; failure is not fatal, it only means managed-app installs will say
+ # so plainly when they preflight the bus.
+ sudo_do loginctl enable-linger "$(id -un)" >/dev/null 2>&1 \
+ || warn "could not enable linger for $(id -un) — managed-app installs may not be able to create user services"
+
sudo_do systemctl daemon-reload
sudo_do systemctl enable "$SERVICE"
# restart, NOT `enable --now`. `--now` only *starts*, and a start on a unit
diff --git a/scripts/managed-app-install b/scripts/managed-app-install
index ca0d491e..eacbee83 100755
--- a/scripts/managed-app-install
+++ b/scripts/managed-app-install
@@ -42,6 +42,61 @@ hermes | openclaw) ;;
;;
esac
+# Both apps are installed as systemd USER units, and `systemctl --user` finds the
+# user's systemd instance through XDG_RUNTIME_DIR. MSO may be running as a systemd
+# SYSTEM unit with `User=`, which inherits no login session and therefore no such
+# variable; every `systemctl --user` then answers
+#
+# Failed to connect to bus: No medium found
+#
+# and, under `set -e`, kills this script outright.
+#
+# That is not hypothetical. It aborted real installs inside
+# install_hermes_dashboard() — AFTER the upstream installer had already fetched
+# uv, a Python, the git checkout and 80 skills — leaving a unit file on disk that
+# nothing had ever enabled, and reporting only "exited with code 1".
+ensure_user_bus() {
+ [ -n "${XDG_RUNTIME_DIR:-}" ] && [ -S "${XDG_RUNTIME_DIR}/bus" ] && return 0
+ # Linger is what keeps /run/user/<uid> alive without a login session — and
+ # enabling it CREATES that directory here and now. A user may enable their own
+ # linger without root.
+ loginctl enable-linger "$(id -un)" >/dev/null 2>&1 || true
+ local uid
+ uid="$(id -u)"
+ if [ -S "/run/user/${uid}/bus" ]; then
+ export XDG_RUNTIME_DIR="/run/user/${uid}"
+ return 0
+ fi
+ return 1
+}
+
+# Checked HERE, before ~20 minutes of downloading and compiling, because the last
+# step is the most expensive place to discover a missing environment variable.
+if command -v systemctl >/dev/null 2>&1; then
+ if ensure_user_bus; then
+ log "user systemd bus: ${XDG_RUNTIME_DIR}/bus"
+ else
+ cat >&2 <<MSG
+cannot reach the systemd user bus for $(id -un), so $APP's service could not be
+installed even if everything else succeeded. Nothing has been changed.
+
+MSO is probably running as a systemd system unit, which gets no login session and
+therefore no XDG_RUNTIME_DIR. Fix it once, on the host:
+
+ sudo loginctl enable-linger $(id -un)
+ sudo mkdir -p /etc/systemd/system/mso.service.d
+ printf '[Service]\nEnvironment=XDG_RUNTIME_DIR=/run/user/%%U\n' \\
+ | sudo tee /etc/systemd/system/mso.service.d/10-user-bus.conf
+ sudo systemctl daemon-reload && sudo systemctl restart mso
+
+Then start this install again.
+MSG
+ exit 1
+ fi
+else
+ echo "no systemctl on this host — $APP will be installed without a service" >&2
+fi
+
# ---------------------------------------------------------------- hermes ----
install_hermes() {
local tmp
@@ -114,8 +169,15 @@ WantedBy=default.target
UNIT
# Without linger a user unit dies with the last session, so the dashboard would
- # vanish on logout and never return after a reboot. Idempotent, needs no sudo.
- loginctl enable-linger "$USER" >/dev/null 2>&1 || true
+ # vanish on logout and never return after a reboot. ensure_user_bus enables it
+ # and exports XDG_RUNTIME_DIR; both are idempotent and need no sudo. It ran in
+ # preflight already — repeated here so this function is correct on its own, and
+ # because `$USER` (which this used to read) is not guaranteed to be set in a
+ # systemd child, while `id -un` always is.
+ ensure_user_bus || {
+ echo "cannot reach the user systemd bus — see the preflight message above" >&2
+ return 1
+ }
systemctl --user daemon-reload
systemctl --user enable --now hermes-dashboard.service
@@ -130,7 +192,24 @@ UNIT
fi
sleep 2
done
- echo "dashboard did not answer within 180s — still building? check: systemctl --user status hermes-dashboard" >&2
+
+ # Falling out of this loop used to return 0 — the exit status of the `echo`
+ # below — so the job was recorded as SUCCEEDED with nothing listening on 9119.
+ # That is precisely the failure this function was written to prevent ("an
+ # install that reports success while the iframe is still refused"), reintroduced
+ # through the back door by a missing return.
+ #
+ # "Timed out" is still two different outcomes, so ask which one before deciding:
+ # a first start compiles the web UI with vite and can genuinely outrun 180 s on a
+ # small VPS, and failing that install would be just as wrong as passing a dead one.
+ if systemctl --user is-active --quiet hermes-dashboard.service; then
+ echo "dashboard has not answered within 180s but its service is running — it is still building." >&2
+ echo "watch it with: journalctl --user -u hermes-dashboard -f" >&2
+ return 0
+ fi
+ echo "dashboard service is not running after install: $(systemctl --user is-active hermes-dashboard.service 2>&1)" >&2
+ echo "diagnose with: systemctl --user status hermes-dashboard --no-pager" >&2
+ return 1
}
# Sets HERMES_CMD. An ARRAY, because the last candidate is two words.