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): fail closed on an unreadable bus, and stop a retry eating the live venv

antinrml5be19160a70c
diff --git a/lib/managed-apps/install.ts b/lib/managed-apps/install.ts
index e67a01e2..eac28bd7 100644
--- a/lib/managed-apps/install.ts
+++ b/lib/managed-apps/install.ts
@@ -57,6 +57,15 @@ const BINDS = new Set(["loopback", "lan", "tailnet", "auto"]);
export async function startInstall(id: ManagedAppId, options: InstallOptions = {}): Promise<ManagedAppJob> {
const view = await getManagedApp(id);
if (view.installed) throw new Error(`${getManagedAppDefinition(id).name} is already installed — use Update instead`);
+ // Fail CLOSED on an unreadable reading. This guard's own reason for existing
+ // (above) is that re-running an installer "restarts services under whoever is
+ // using them" — and Hermes' upstream installer recreates the venv that the
+ // RUNNING gateway is executing from. `installed: false` arriving because MSO
+ // cannot see user services is exactly when that is most destructive, so
+ // "I could not check" must not be treated as "it is not there".
+ if (view.diagnostic) {
+ throw new Error(`cannot determine whether ${getManagedAppDefinition(id).name} is installed — refusing to run the installer. ${view.diagnostic}`);
+ }
const env: Record<string, string> = {};
const bind = options.bind ?? "loopback";
diff --git a/lib/managed-apps/job-child.ts b/lib/managed-apps/job-child.ts
index f2f3d812..30f17f5b 100644
--- a/lib/managed-apps/job-child.ts
+++ b/lib/managed-apps/job-child.ts
@@ -2,6 +2,7 @@ import "server-only";
import { spawn, type ChildProcess, type StdioOptions } from "node:child_process";
import { childEnv } from "@/lib/host/child-env";
import type { ManagedAppJobStatus, StartManagedAppJobOptions } from "./types";
+import { userBusEnv } from "./user-bus";
// The child half of the job layer: spawning it, bounding it, and — the part
// that cost a permanently wedged lock to learn — REAPING it. job-runner.ts owns
@@ -82,7 +83,14 @@ export function spawnJobChild(argv: readonly string[], options: StartManagedAppJ
cwd: options.cwd,
// NO_COLOR/TERM: the transcript is stored and rendered as plain text, so
// ANSI would only eat the cap.
- env: { ...(childEnv() as NodeJS.ProcessEnv), NO_COLOR: "1", TERM: "dumb", ...options.env },
+ //
+ // userBusEnv() is ADDED rather than inherited: childEnv() copies this
+ // process's environment minus secret-shaped names, and it can only copy what
+ // is there — under systemd XDG_RUNTIME_DIR is not. Every managed-app install
+ // ends by registering a systemd USER unit, so without this the job's last
+ // step dies with "Failed to connect to bus: No medium found" after doing all
+ // of its work. options.env still wins, so a caller can override it.
+ env: { ...(childEnv() as NodeJS.ProcessEnv), ...userBusEnv(), NO_COLOR: "1", TERM: "dumb", ...options.env },
stdio: JOB_STDIO,
detached: true,
shell: false,
diff --git a/lib/managed-apps/runner.test.ts b/lib/managed-apps/runner.test.ts
index 11930b0c..0ceab5d9 100644
--- a/lib/managed-apps/runner.test.ts
+++ b/lib/managed-apps/runner.test.ts
@@ -11,11 +11,7 @@ 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 realHome = process.env.HOME;
const { resolveCommand, commandExists } = await import("./runner");
@@ -24,9 +20,15 @@ const CLI = "mso-fixture-cli";
beforeEach(async () => {
home = await fs.mkdtemp(path.join(os.tmpdir(), "mso-runner-"));
+ // $HOME, not a mock of node:os — resolveCommand reads the env var first, so
+ // redirecting it is both what the code actually honours and what a caller can
+ // do. A mocked module binding would not be seen through the ESM import.
+ process.env.HOME = home;
});
afterEach(async () => {
+ if (realHome === undefined) delete process.env.HOME;
+ else process.env.HOME = realHome;
await fs.rm(home, { recursive: true, force: true });
vi.restoreAllMocks();
});
diff --git a/lib/managed-apps/runner.ts b/lib/managed-apps/runner.ts
index 67f7f8f5..74f516dd 100644
--- a/lib/managed-apps/runner.ts
+++ b/lib/managed-apps/runner.ts
@@ -6,6 +6,18 @@ import { isAbsolute, join } from "node:path";
const MAX_OUTPUT = 128 * 1024;
+/**
+ * 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.
+ */
+const FALLBACK_BIN_DIRS = [".local/bin", ".bun/bin"] as const;
+
export interface ProgramResult {
code: number;
stdout: string;
@@ -33,6 +45,10 @@ export function runProgram(
windowsHide: true,
shell: false,
// Merge, never replace: the child still needs PATH, HOME and the locale.
+ // NOT widened globally: `runProgram` also spawns systemctl/docker, and
+ // silently adding a user-writable dir to every child's PATH would both
+ // create a shadowing hazard and defeat the PATH-narrowing that
+ // update.test.ts relies on to keep tests off the real CLIs.
...(env ? { env: { ...process.env, ...env } } : {}),
},
(error, stdout, stderr) => {
@@ -43,17 +59,8 @@ export function runProgram(
});
}
-/**
- * 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;
+/** `$HOME` first so a caller (and a test) can redirect it; homedir() is the fallback. */
+const userHome = (): string => process.env.HOME || homedir();
const isExecutable = (candidate: string): boolean => {
try {
@@ -83,7 +90,7 @@ export async function resolveCommand(command: string): Promise<string | null> {
// 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);
+ const candidate = join(userHome(), dir, command);
if (isExecutable(candidate)) return candidate;
}
return null;
diff --git a/lib/managed-apps/update.test.ts b/lib/managed-apps/update.test.ts
index bd5b7575..fb3a636e 100644
--- a/lib/managed-apps/update.test.ts
+++ b/lib/managed-apps/update.test.ts
@@ -25,6 +25,7 @@ import type { ManagedAppJob } from "./types";
let home: string;
let bin: string;
const realPath = process.env.PATH ?? "";
+const realHome = process.env.HOME;
beforeEach(async () => {
home = await fs.mkdtemp(path.join(os.tmpdir(), "mapp-update-"));
@@ -32,6 +33,8 @@ beforeEach(async () => {
await fs.mkdir(bin);
vi.spyOn(os, "homedir").mockReturnValue(home);
process.env.PATH = `${bin}:/usr/bin:/bin`;
+ // HOME too: resolveCommand() falls back to $HOME/.local/bin when PATH misses.
+ process.env.HOME = home;
for (const id of ["hermes", "openclaw"]) await fs.mkdir(path.join(home, `.${id}`), { recursive: true });
await fs.writeFile(path.join(home, ".hermes", "config.yaml"), "state: kept\n");
await fs.writeFile(path.join(home, ".openclaw", "openclaw.json"), "{}");
@@ -39,6 +42,7 @@ beforeEach(async () => {
afterEach(async () => {
process.env.PATH = realPath;
+ if (realHome === undefined) delete process.env.HOME; else process.env.HOME = realHome;
vi.restoreAllMocks();
await fs.rm(home, { recursive: true, force: true });
});
diff --git a/lib/managed-apps/update.ts b/lib/managed-apps/update.ts
index 3aa3fde5..c56fbe98 100644
--- a/lib/managed-apps/update.ts
+++ b/lib/managed-apps/update.ts
@@ -6,7 +6,7 @@ import { getManagedAppDefinition } from "./catalog";
import { startManagedAppJob } from "./jobs";
import { activeOperation } from "./lock";
import { restoreManagedAppBackup } from "./restore";
-import { runProgram } from "./runner";
+import { resolveCommand, runProgram } from "./runner";
import type { ManagedAppDefinition, ManagedAppId, ManagedAppJob } from "./types";
import { assertChannel, updateAdapter, UNINSTALL_PREVIEW_FLAG } from "./update-cli";
import type { ManagedAppBackup, ManagedAppUpdateOptions, ManagedAppUpdateStatus } from "./update-types";
@@ -32,11 +32,13 @@ const cache = new Map<ManagedAppId, ManagedAppUpdateStatus>();
* argv the job records is the exact binary that ran, and a missing CLI fails
* here with a readable message instead of as a child-process ENOENT. */
async function resolveProgram(command: string): Promise<string> {
- 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 || !path.isAbsolute(first)) throw new Error(`${command} is not installed`);
- return first;
+ // Shared with detection (runner.ts) rather than a second `which` of its own:
+ // under systemd the unit's PATH has no ~/.local/bin, so a bare `which` reported
+ // "hermes is not installed" for an installed Hermes and disabled the whole
+ // update centre — the same fault that made the app read as absent.
+ const resolved = await resolveCommand(command);
+ if (!resolved || !path.isAbsolute(resolved)) throw new Error(`${command} is not installed`);
+ return resolved;
}
const message = (error: unknown): string => (error instanceof Error ? error.message : String(error));
diff --git a/scripts/managed-app-install b/scripts/managed-app-install
index eacbee83..f1cf366b 100755
--- a/scripts/managed-app-install
+++ b/scripts/managed-app-install
@@ -110,11 +110,33 @@ install_hermes() {
curl -fsSL --max-time 300 https://hermes-agent.nousresearch.com/install.sh -o "$tmp/install.sh"
printf 'installer: %s bytes, sha256 %s\n' "$(wc -c <"$tmp/install.sh")" "$(sha256sum <"$tmp/install.sh" | cut -c1-16)"
- log "running the installer (non-interactive)"
- # --non-interactive makes it skip every stage that would ask (install.sh:3211).
- # It pulls uv, Python, Node and ffmpeg itself; sudo is used only to apt-get git
- # and degrades to a no-op without it.
- bash "$tmp/install.sh" --non-interactive
+ # The upstream installer is NOT safely re-runnable against a live install: on a
+ # second pass it prints "Virtual environment already exists, recreating…" and
+ # unlinks the interpreter that the RUNNING hermes-gateway.service is executing
+ # from (its ExecStart is …/venv/bin/python). The process survives on deleted
+ # inodes — observed holding 18 `(deleted)` .so mappings, including
+ # cryptography/_rust and nacl/_sodium — until something makes it import a module
+ # it has not already loaded, and then it dies in a way nothing here reported.
+ #
+ # This mattered because a FAILED install invites a retry, and the retry is what
+ # does the damage. So: if a working Hermes is already present, do not re-run the
+ # installer. Everything after it (`setup`, `gateway install`, the dashboard unit)
+ # is idempotent by upstream's own design — "Service already installed … Use
+ # --force", "config.yaml already exists, keeping it" — so the button still works
+ # as a REPAIR for the steps that actually failed.
+ #
+ # Tested by running the launcher, not by stat-ing the venv: a half-built venv
+ # has an executable python and imports nothing.
+ if hermes_cmd 2>/dev/null && "${HERMES_CMD[@]}" --version >/dev/null 2>&1; then
+ log "hermes is already installed and runnable — skipping the upstream installer"
+ printf 'found: %s\n' "$("${HERMES_CMD[@]}" --version 2>/dev/null | head -1)"
+ else
+ log "running the installer (non-interactive)"
+ # --non-interactive makes it skip every stage that would ask (install.sh:3211).
+ # It pulls uv, Python, Node and ffmpeg itself; sudo is used only to apt-get git
+ # and degrades to a no-op without it.
+ bash "$tmp/install.sh" --non-interactive
+ fi
hermes_cmd
log "configuring from the environment"