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(gateway): close lifecycle review gaps

Rahmana7c4f0c52367
diff --git a/README.md b/README.md
index dd7fb3ca..9a351187 100644
--- a/README.md
+++ b/README.md
@@ -175,7 +175,7 @@ If it explicitly says the current shell cannot see the user launcher yet, run th
**WSL2:** the CLI is supported even when systemd is not active. In that case the installer now
finishes the CLI instead of failing in `systemctl`, but it skips `mso.service`. `mso onboard` and
`mso web` can start the already-built production runtime detached on `127.0.0.1` and track ownership
-under private state; `mso update` can update/verify/build without a running API. For the full
+under private state; `mso update` can update/verify/build without a running API and safely quiesces/restores a gateway-owned fallback runtime instead of rebuilding `.next` underneath it. For the full
background service, enable systemd in `/etc/wsl.conf`, exit all WSL sessions from Windows, reopen
the distro, then re-run the installer with `--onboard`.
diff --git a/bin/mso b/bin/mso
index 14ae5b41..eb9a73f6 100755
--- a/bin/mso
+++ b/bin/mso
@@ -831,7 +831,7 @@ case "$cmd" in
# The same self-update Settings → About drives, so both surfaces get the same
# preflight and the same transient-unit handoff (a build spawned from the service
# would be killed by the restart it performs).
- update) MSO_UPDATE_ROOT="$ROOT" "$ROOT/scripts/mso-update" "$@" ;;
+ update) local_url="$(gateway_local_url)"; MSO_UPDATE_ROOT="$ROOT" MSO_UPDATE_LOCAL_URL="$local_url" "$ROOT/scripts/mso-update" "$@" ;;
# ── editor-document CRUD (one pattern, all editor features) ──────────────
crud)
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index ba1adada..4eea085c 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -224,7 +224,7 @@ out-of-tree production build), pushes the exact commit, then hands the in-place
build/restart/final verification to the owner user manager when launched through MSO/MCP.
A successful finalizer ends `~/.mso/self-update.log` with `UPDATE OK`.
-For operator updates use Settings → About or `mso update run`; use `--rebuild` for the
+For operator updates use Settings → About or `mso update`; use `--rebuild` for the
supported recovery rebuild. See `docs/INSTALL.md`, `docs/DEVELOPMENT.md` and
`docs/TROUBLESHOOTING.md`.
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 382ebf70..1dcecc59 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -13,6 +13,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Fixed**
+- `gateway` close lifecycle review gaps
- `security` harden gateway scanner fixtures
- `install` survive Bun bin metadata corruption
- `install` keep bootstrap guard shellcheck-clean
diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md
index be35a910..e03210fe 100644
--- a/docs/DEVELOPMENT.md
+++ b/docs/DEVELOPMENT.md
@@ -105,7 +105,7 @@ no host access, forced mock data), served on `:4006` via its own systemd unit. F
non-destructive static check, `bun run typecheck && bun run lint` is the cheap gate.
Recovery if a chunk mismatch is live: wait for any active self-update finalizer to
-finish, then run `mso update run --rebuild` and re-run the post-deploy smoke check.
+finish, then run `mso update --rebuild` and re-run the post-deploy smoke check.
## Package manager: bun installs, Node runs
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index 362b6395..5ac704b1 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -164,8 +164,7 @@ never changes the application bind to `0.0.0.0`. The tool cache is user-local an
with Cloudflare auto-update disabled. The tunnel process also receives a scrubbed environment rather
than inheriting MSO login/session/BYOK secrets from the application shell. If systemd is unavailable (common on WSL), it may start the
already-built Next production runtime itself, still on `127.0.0.1`, and records whether that process
-is gateway-owned. `gateway stop` only terminates a recorded process after its live command line
-matches the expected MSO/cloudflared identity. Private state and logs are owner-only.
+is gateway-owned. `gateway stop` terminates only recorded identities: Cloudflared is matched by PID/start-time/executable/exact argv, while the Next fallback uses PID/start-time/Node executable plus a random runtime-instance nonce echoed by `/api/health` so Next's mutable process title cannot confuse ownership. Private state and logs are owner-only.
This is intentionally labeled **temporary preview**. The random `trycloudflare.com` URL changes on
restart, and Cloudflare Quick Tunnels do not support Server-Sent Events; MSO Terminal's live output
@@ -432,9 +431,12 @@ mso update log
The updater verifies the incoming checkout/build before replacing the service. With an active
`mso.service` it runs outside that service cgroup so the updater survives the restart. With no active
service (including WSL without systemd), it performs the clean fast-forward/dependency/verify/build
-path locally and finishes by telling you to run `mso web`. Interactive CLI commands also show a
-throttled update notice when cached `origin/main` is ahead; the notice never depends on port 4005.
-A successful service finalizer log ends with `UPDATE OK`.
+path locally. If `mso web`/gateway owns the detached Next runtime, update first quiesces only that
+verified runtime, leaves an active tunnel identity intact, rebuilds, then restores the runtime. A
+private deployment receipt and restart marker mean a dependency/build failure after Git already
+reached `origin/main` is retried by the next ordinary `mso update` instead of being mislabeled
+"already up to date". Interactive CLI commands also show a throttled Git-backed update notice;
+the notice never depends on port 4005. A successful service finalizer log ends with `UPDATE OK`.
If the installed source is correct but the production build tree is inconsistent, use:
diff --git a/docs/MCP.md b/docs/MCP.md
index 8c8f556b..f504f3c9 100644
--- a/docs/MCP.md
+++ b/docs/MCP.md
@@ -27,7 +27,7 @@ OS_MCP_MAX_SCOPE=read # read | write | exec; default ceiling is exec
```
After changing deployment environment, use the normal MSO update/rebuild path (Settings →
-About or `mso update run --rebuild`). A Git push or editing `.env.local` does not change the
+About or `mso update --rebuild`). A Git push or editing `.env.local` does not change the
running service by itself.
## Connect an MCP client
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index f5b8da43..c3e1a8b5 100644
--- a/docs/TROUBLESHOOTING.md
+++ b/docs/TROUBLESHOOTING.md
@@ -32,8 +32,11 @@ existing device role still requires the explicit `mso device role` command.
### How do I update when the web UI / port 4005 is down?
Run `mso update`. The CLI updater reads/fetches `origin/main` directly and does not need the MSO API.
-On WSL without an active service it verifies and builds the clean updated checkout, then tells you to
-run `mso web`. Use `mso update status` to see the incoming CLI version/commits and `mso update log`
+On WSL without an active service it verifies and builds the clean updated checkout. If the fallback
+runtime is gateway-owned, it is quiesced before `.next` changes and restored afterward while an
+active tunnel identity is preserved. A private deployment receipt/restart marker survives partial
+failures, so rerunning the same `mso update` retries dependency/build/restart work even when Git HEAD
+already equals `origin/main`. Use `mso update status` for source/deployment state and `mso update log`
for the service-updater transcript.
### `mso gateway start` cannot install or verify cloudflared
diff --git a/scripts/lib/gateway-common.sh b/scripts/lib/gateway-common.sh
index 788d849f..94dffdb1 100644
--- a/scripts/lib/gateway-common.sh
+++ b/scripts/lib/gateway-common.sh
@@ -174,44 +174,3 @@ gateway_wait_health() {
for i in $(seq 1 40); do gateway_health_url_ok "$LOCAL_URL" "$expected_instance" && return 0; sleep 0.25; done
return 1
}
-
-gateway_lock_owner_valid() {
- local owner="$LOCK_DIR/owner" pid ticks live
- [ -f "$owner" ] && [ ! -L "$owner" ] || return 1
- read -r pid ticks <"$owner" || return 1
- [[ "$pid" =~ ^[0-9]+$ && "$ticks" =~ ^[0-9]+$ ]] || return 1
- live="$(gateway_proc_start_ticks "$pid" 2>/dev/null || true)"
- [ -n "$live" ] && [ "$live" = "$ticks" ]
-}
-
-gateway_lock_acquire() {
- local self_ticks candidate stale i
- self_ticks="$(gateway_proc_start_ticks $$)" || gateway_fail "cannot identify gateway process"
- for i in $(seq 1 240); do
- candidate="$STATE_ROOT/.lifecycle-lock.$$.$RANDOM"
- mkdir -m 700 -- "$candidate"
- printf '%s %s\n' "$$" "$self_ticks" >"$candidate/owner"; chmod 600 "$candidate/owner"
- if mv -T -- "$candidate" "$LOCK_DIR" 2>/dev/null; then LOCK_HELD=1; return 0; fi
- rm -rf -- "$candidate"
- if [ -d "$LOCK_DIR" ] && [ ! -L "$LOCK_DIR" ] && ! gateway_lock_owner_valid; then
- stale="$STATE_ROOT/.lifecycle-stale.$$.$RANDOM"
- mv -T -- "$LOCK_DIR" "$stale" 2>/dev/null && rm -rf -- "$stale" || true
- fi
- sleep 0.05
- done
- gateway_fail "another gateway lifecycle operation is still running"
-}
-
-gateway_lock_release() {
- [ "${LOCK_HELD:-0}" = 1 ] || return 0
- if gateway_lock_owner_valid; then rm -f -- "$LOCK_DIR/owner"; rmdir -- "$LOCK_DIR" 2>/dev/null || true; fi
- LOCK_HELD=0
-}
-
-gateway_with_lock() {
- gateway_lock_acquire
- trap gateway_lock_release EXIT
- "$@"
- gateway_lock_release
- trap - EXIT
-}
diff --git a/scripts/lib/gateway-lock.sh b/scripts/lib/gateway-lock.sh
new file mode 100755
index 00000000..b97d3c61
--- /dev/null
+++ b/scripts/lib/gateway-lock.sh
@@ -0,0 +1,59 @@
+#!/usr/bin/env bash
+# Owner-only lifecycle lock and signal-safe pending-child cleanup.
+
+gateway_lock_owner_valid() {
+ local owner="$LOCK_DIR/owner" pid ticks live
+ [ -f "$owner" ] && [ ! -L "$owner" ] || return 1
+ read -r pid ticks <"$owner" || return 1
+ [[ "$pid" =~ ^[0-9]+$ && "$ticks" =~ ^[0-9]+$ ]] || return 1
+ live="$(gateway_proc_start_ticks "$pid" 2>/dev/null || true)"
+ [ -n "$live" ] && [ "$live" = "$ticks" ]
+}
+
+gateway_lock_acquire() {
+ local self_ticks candidate stale i
+ self_ticks="$(gateway_proc_start_ticks $$)" || gateway_fail "cannot identify gateway process"
+ for i in $(seq 1 240); do
+ candidate="$STATE_ROOT/.lifecycle-lock.$$.$RANDOM"
+ mkdir -m 700 -- "$candidate"
+ printf '%s %s\n' "$$" "$self_ticks" >"$candidate/owner"; chmod 600 "$candidate/owner"
+ if mv -T -- "$candidate" "$LOCK_DIR" 2>/dev/null; then LOCK_HELD=1; return 0; fi
+ rm -rf -- "$candidate"
+ if [ -d "$LOCK_DIR" ] && [ ! -L "$LOCK_DIR" ] && ! gateway_lock_owner_valid; then
+ stale="$STATE_ROOT/.lifecycle-stale.$$.$RANDOM"
+ mv -T -- "$LOCK_DIR" "$stale" 2>/dev/null && rm -rf -- "$stale" || true
+ fi
+ sleep 0.05
+ done
+ gateway_fail "another gateway lifecycle operation is still running"
+}
+
+gateway_lock_release() {
+ [ "${LOCK_HELD:-0}" = 1 ] || return 0
+ if gateway_lock_owner_valid; then rm -f -- "$LOCK_DIR/owner"; rmdir -- "$LOCK_DIR" 2>/dev/null || true; fi
+ LOCK_HELD=0
+}
+
+GATEWAY_PENDING_CLEANUP=0
+
+gateway_operation_cleanup() {
+ [ "${GATEWAY_PENDING_CLEANUP:-0}" = 1 ] || return 0
+ if declare -F gateway_cleanup_failed_start >/dev/null 2>&1; then
+ gateway_cleanup_failed_start || true
+ fi
+ GATEWAY_PENDING_CLEANUP=0
+}
+
+gateway_with_lock() {
+ gateway_lock_acquire
+ # HUP/INT/TERM become ordinary non-zero exits. EXIT then rolls back any
+ # pre-persistence child processes before releasing the lifecycle lock.
+ trap 'gateway_operation_cleanup; gateway_lock_release' EXIT
+ trap 'exit 129' HUP
+ trap 'exit 130' INT
+ trap 'exit 143' TERM
+ "$@"
+ gateway_operation_cleanup
+ gateway_lock_release
+ trap - EXIT HUP INT TERM
+}
diff --git a/scripts/lib/gateway-runtime.sh b/scripts/lib/gateway-runtime.sh
index c44cbf0b..156f8618 100644
--- a/scripts/lib/gateway-runtime.sh
+++ b/scripts/lib/gateway-runtime.sh
@@ -57,6 +57,7 @@ gateway_start_runtime_if_needed() {
gateway_fail "runtime did not become this launch's MSO health instance; see $RUNTIME_LOG"
fi
RUNTIME_IDENTITY="$identity"; RUNTIME_INSTANCE_ID="$instance"; RUNTIME_OWNED=true; RUNTIME_STARTED_NOW=true
+ GATEWAY_PENDING_CLEANUP=1
}
gateway_write_state() {
@@ -78,19 +79,52 @@ gateway_active_state() {
}
gateway_cmd_local_start_locked() {
- local state
+ local state tunnel provider mode url
state="$(gateway_state_read)"
gateway_runtime_from_state "$state"
gateway_start_runtime_if_needed
+ tunnel="$(jq -c '.tunnelIdentity // null' <<<"$state")"
+ if [ "$tunnel" != null ] && gateway_identity_matches_retry "$tunnel"; then
+ provider="$(jq -r '.provider // "cloudflare-quick"' <<<"$state")"
+ mode="$(jq -r '.mode // "temporary"' <<<"$state")"
+ url="$(jq -r --arg local "$LOCAL_URL" '.url // $local' <<<"$state")"
+ else
+ tunnel=null; provider=local; mode=local; url="$LOCAL_URL"
+ fi
if [ "$RUNTIME_STARTED_NOW" = true ] || [ "$RUNTIME_OWNED" = true ]; then
- if ! gateway_write_state local local "$LOCAL_URL" null; then
+ if ! gateway_write_state "$provider" "$mode" "$url" "$tunnel"; then
[ "$RUNTIME_STARTED_NOW" = true ] && gateway_stop_identity "$RUNTIME_IDENTITY"
gateway_fail "could not persist local runtime state; newly started runtime was rolled back"
fi
+ GATEWAY_PENDING_CLEANUP=0
fi
gateway_info "runtime: healthy MSO at $LOCAL_URL"
}
+gateway_cmd_runtime_stop_locked() {
+ local state tunnel runtime owned provider mode url
+ state="$(gateway_state_read)"
+ tunnel="$(jq -c '.tunnelIdentity // null' <<<"$state")"
+ runtime="$(jq -c '.runtimeIdentity // null' <<<"$state")"
+ owned="$(jq -r '.runtimeOwned // false' <<<"$state")"
+ if [ "$owned" = true ] && [ "$runtime" != null ]; then
+ gateway_runtime_from_state "$state"
+ [ "$RUNTIME_OWNED" = true ] || gateway_fail "recorded runtime ownership no longer matches a live MSO instance; refusing offline rebuild"
+ gateway_stop_identity "$runtime"
+ provider="$(jq -r '.provider // "local"' <<<"$state")"
+ mode="$(jq -r '.mode // "local"' <<<"$state")"
+ url="$(jq -r --arg local "$LOCAL_URL" '.url // $local' <<<"$state")"
+ RUNTIME_IDENTITY=null; RUNTIME_INSTANCE_ID=''; RUNTIME_OWNED=false; RUNTIME_STARTED_NOW=false
+ gateway_write_state "$provider" "$mode" "$url" "$tunnel" || gateway_fail "could not persist quiesced runtime state"
+ gateway_info "runtime: stopped-owned"
+ return 0
+ fi
+ if gateway_health_ok; then
+ gateway_fail "a loopback MSO runtime is active but is not gateway-owned; stop it before an offline update"
+ fi
+ gateway_info "runtime: already-down"
+}
+
gateway_cmd_stop_locked() {
local state tunnel runtime owned
state="$(gateway_state_read)"
diff --git a/scripts/lib/gateway-tunnel.sh b/scripts/lib/gateway-tunnel.sh
index daa4f0a5..5438aab7 100644
--- a/scripts/lib/gateway-tunnel.sh
+++ b/scripts/lib/gateway-tunnel.sh
@@ -78,6 +78,7 @@ gateway_spawn_tunnel() {
fi
[ -n "$identity" ] || { kill "$pid" 2>/dev/null || true; return 1; }
TUNNEL_IDENTITY="$identity"
+ GATEWAY_PENDING_CLEANUP=1
}
gateway_discover_quick_url() {
@@ -175,6 +176,7 @@ gateway_cmd_start_locked() {
gateway_cleanup_failed_start
gateway_fail "could not persist gateway state; newly launched processes were rolled back"
fi
+ GATEWAY_PENDING_CLEANUP=0
gateway_info "gateway started"
gateway_info "public: $GATEWAY_PUBLIC_URL"
diff --git a/scripts/mso-gateway b/scripts/mso-gateway
index 6b36217d..b81c4608 100755
--- a/scripts/mso-gateway
+++ b/scripts/mso-gateway
@@ -45,6 +45,8 @@ LOCK_HELD=0
. "$ROOT/scripts/lib/gateway-network.sh"
# shellcheck source=scripts/lib/gateway-tool.sh
. "$ROOT/scripts/lib/gateway-tool.sh"
+# shellcheck source=scripts/lib/gateway-lock.sh
+. "$ROOT/scripts/lib/gateway-lock.sh"
# shellcheck source=scripts/lib/gateway-runtime.sh
. "$ROOT/scripts/lib/gateway-runtime.sh"
# shellcheck source=scripts/lib/gateway-tunnel.sh
@@ -58,6 +60,7 @@ case "${1:-status}" in
install) gateway_cmd_install_tool ;;
domain) shift; gateway_cmd_domain "$@" ;;
web) gateway_cmd_web "$@" ;;
- local-start) gateway_with_lock gateway_cmd_local_start_locked ;; # internal: onboard/web WSL fallback
+ local-start) gateway_with_lock gateway_cmd_local_start_locked ;; # internal: onboard/web/update fallback
+ runtime-stop) gateway_with_lock gateway_cmd_runtime_stop_locked ;; # internal: quiesce owned runtime before offline build
*) gateway_fail "usage: mso gateway start|stop|status|url|doctor|install|domain ..." ;;
esac
diff --git a/scripts/mso-gateway-lifecycle.test.ts b/scripts/mso-gateway-lifecycle.test.ts
index 65c8dce8..78bcad92 100644
--- a/scripts/mso-gateway-lifecycle.test.ts
+++ b/scripts/mso-gateway-lifecycle.test.ts
@@ -107,6 +107,49 @@ exec /bin/mv "$@"
expect(alive(child.pid!)).toBe(false);
});
+
+ it("rolls back an unpersisted tunnel when the launcher is terminated during readiness", async () => {
+ const f = fixture();
+ const curl = path.join(f.dir, "bin", "curl-wait");
+ fs.writeFileSync(curl, `#!/bin/sh
+case "$*" in
+ *127.0.0.1:4005/api/health*) printf '%s\n' '{"status":"ok","buildId":"fixture","runtimeInstanceId":"fixture","version":"${VERSION}"}' ;;
+ *) exit 22 ;;
+esac
+`, { mode: 0o700 });
+ const env = { ...f.env, MSO_GATEWAY_CURL: curl, MSO_GATEWAY_SKIP_PUBLIC_PROBE: "0", MSO_GATEWAY_PUBLIC_READY_SECONDS: "10" };
+ const child = spawn(GATEWAY, ["start"], { env, stdio: ["ignore", "pipe", "pipe"] });
+ for (let i = 0; i < 100 && !fs.existsSync(f.startFile); i++) await new Promise((r) => setTimeout(r, 20));
+ expect(fs.existsSync(f.startFile)).toBe(true);
+ const tunnelPid = Number(fs.readFileSync(f.startFile, "utf8").trim().split(/\n+/).at(-1));
+ pids.add(tunnelPid);
+ child.kill("SIGTERM");
+ await new Promise<void>((resolve) => child.once("close", () => resolve()));
+ for (let i = 0; i < 50 && alive(tunnelPid); i++) await new Promise((r) => setTimeout(r, 20));
+ expect(alive(tunnelPid)).toBe(false);
+ expect(fs.existsSync(path.join(f.state, "state.json"))).toBe(false);
+ });
+
+ it("local-start preserves an active tunnel while retaining an owned runtime", async () => {
+ const f = fixture();
+ const tunnel = spawn(f.cloudflared, ["tunnel", "--no-autoupdate", "--url", "http://127.0.0.1:4005"], { env: f.env });
+ const runtime = spawn(process.execPath, ["-e", "process.title='next-server (fixture)';process.on('SIGTERM',()=>process.exit(0));setInterval(()=>{},1000)"]);
+ await new Promise((r) => setTimeout(r, 150));
+ pids.add(tunnel.pid!); pids.add(runtime.pid!);
+ const tid = identity(tunnel.pid!);
+ const rid = { ...identity(runtime.pid!), cmdHash: null, instanceId: "fixture" };
+ writeState(f.state, { provider: "cloudflare-quick", mode: "temporary", url: "https://life-fixture.trycloudflare.com",
+ localUrl: "http://127.0.0.1:4005", tunnelIdentity: tid, runtimeIdentity: rid, runtimeOwned: true, startedAt: "2026-01-01T00:00:00Z" });
+ run(["local-start"], f.env);
+ const state = JSON.parse(fs.readFileSync(path.join(f.state, "state.json"), "utf8"));
+ expect(state.tunnelIdentity).toEqual(tid);
+ expect(state.runtimeIdentity).toEqual(rid);
+ expect(alive(tunnel.pid!)).toBe(true);
+ run(["stop"], f.env);
+ for (let i = 0; i < 50 && (alive(tunnel.pid!) || alive(runtime.pid!)); i++) await new Promise((r) => setTimeout(r, 20));
+ expect(alive(tunnel.pid!)).toBe(false); expect(alive(runtime.pid!)).toBe(false);
+ });
+
it("serializes concurrent starts so only one public tunnel is spawned", async () => {
const f = fixture(), startFile = f.startFile, env = f.env;
const [a, b] = await Promise.all([asyncStart(env), asyncStart(env)]);
diff --git a/scripts/mso-gateway.test.ts b/scripts/mso-gateway.test.ts
index 5e929ff4..ec1a569e 100644
--- a/scripts/mso-gateway.test.ts
+++ b/scripts/mso-gateway.test.ts
@@ -163,6 +163,27 @@ esac
expect(out.trim()).toBe("http://[::1]:4556");
});
+
+ it("opens the Windows browser from WSL with the URL passed as data, not PowerShell code", async () => {
+ const f = fixture();
+ const capture = path.join(f.dir, "powershell-argv");
+ const powershell = path.join(f.bin, "powershell.exe");
+ fs.writeFileSync(powershell, `#!/bin/sh
+printf '%s\n' "$@" > "${capture}"
+`, { mode: 0o700 });
+ const out = execFileSync(CLI, ["--base", "http://127.0.0.1:4555", "web", "--local"], {
+ encoding: "utf8",
+ env: { ...process.env, HOME: f.dir, PATH: `${f.bin}:${process.env.PATH}`, MSO_ENV: "/dev/null",
+ MSO_GATEWAY_STATE_DIR: f.state, MSO_GATEWAY_CURL: f.curl, MSO_GATEWAY_CLOUDFLARED: f.cloudflared },
+ });
+ expect(out).toContain("opened http://127.0.0.1:4555");
+ for (let i = 0; i < 50 && !fs.existsSync(capture); i++) await new Promise((r) => setTimeout(r, 10));
+ const argv = fs.readFileSync(capture, "utf8").trim().split(/\n/);
+ expect(argv).toContain("Start-Process $args[0]");
+ expect(argv.at(-1)).toBe("http://127.0.0.1:4555");
+ expect(argv.filter((v) => v.includes("http://127.0.0.1:4555"))).toHaveLength(1);
+ });
+
it("mso web follows an explicit loopback --base including a non-default port", () => {
const f = fixture();
const out = execFileSync(CLI, ["--base", "http://127.0.0.1:4555", "web", "--local", "--print"], {
diff --git a/scripts/mso-update b/scripts/mso-update
index 47b0e859..d79c2869 100755
--- a/scripts/mso-update
+++ b/scripts/mso-update
@@ -5,6 +5,12 @@ umask 077
ROOT="${MSO_UPDATE_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
LOG="${MSO_UPDATE_LOG:-$HOME/.mso/self-update.log}"
NOTICE_DIR="${MSO_UPDATE_NOTICE_DIR:-$HOME/.mso/private/update-notice}"
+UPDATE_STATE_DIR_REQUESTED="${MSO_UPDATE_STATE_DIR:-$HOME/.mso/private/update-state}"
+LOCAL_URL="${MSO_UPDATE_LOCAL_URL:-${MSO_GATEWAY_LOCAL_URL:-http://127.0.0.1:${MSO_PORT:-4005}}}"
+GATEWAY="$ROOT/scripts/mso-gateway"
+UPDATE_STATE_DIR=''
+DEPLOY_RECEIPT=''
+RESTART_MARKER=''
# shellcheck source=scripts/lib/private-state.sh
. "$ROOT/scripts/lib/private-state.sh"
@@ -22,14 +28,71 @@ require_checkout() {
fetch_main() { git -C "$ROOT" fetch --quiet origin main || fail "could not reach origin/main"; }
+init_update_state() {
+ [ -n "$UPDATE_STATE_DIR" ] && return 0
+ UPDATE_STATE_DIR="$(mso_private_state_dir "$UPDATE_STATE_DIR_REQUESTED")" || fail "unsafe update state directory"
+ DEPLOY_RECEIPT="$UPDATE_STATE_DIR/deployed-sha"
+ RESTART_MARKER="$UPDATE_STATE_DIR/restart-runtime"
+}
+
+read_receipt() {
+ init_update_state
+ if [ ! -e "$DEPLOY_RECEIPT" ] && [ ! -L "$DEPLOY_RECEIPT" ]; then return 1; fi
+ mso_private_state_validate_file "$DEPLOY_RECEIPT" >/dev/null || fail "unsafe deployed-sha receipt"
+ local sha; sha="$(cat "$DEPLOY_RECEIPT")"
+ [[ "$sha" =~ ^[0-9a-f]{40}$ ]] || fail "invalid deployed-sha receipt"
+ printf '%s' "$sha"
+}
+
+write_receipt() {
+ init_update_state
+ git -C "$ROOT" rev-parse HEAD | mso_private_state_atomic_write "$DEPLOY_RECEIPT" >/dev/null
+}
+
+restart_pending() {
+ init_update_state
+ if [ ! -e "$RESTART_MARKER" ] && [ ! -L "$RESTART_MARKER" ]; then return 1; fi
+ mso_private_state_validate_file "$RESTART_MARKER" >/dev/null || fail "unsafe runtime restart marker"
+ [ "$(cat "$RESTART_MARKER")" = 1 ] || fail "invalid runtime restart marker"
+}
+
+mark_restart_pending() { printf '1\n' | mso_private_state_atomic_write "$RESTART_MARKER" >/dev/null; }
+clear_restart_pending() { mso_private_state_remove_file "$RESTART_MARKER" >/dev/null 2>&1 || true; }
+
+quiesce_offline_runtime() {
+ local out
+ [ -x "$GATEWAY" ] || return 0
+ out="$(MSO_GATEWAY_ROOT="$ROOT" MSO_GATEWAY_ENV="$ROOT/.env.local" MSO_GATEWAY_LOCAL_URL="$LOCAL_URL" "$GATEWAY" runtime-stop)" \
+ || fail "could not safely quiesce the local MSO runtime before rebuilding"
+ case "$out" in *'runtime: stopped-owned'*) mark_restart_pending ;; esac
+}
+
+restore_offline_runtime() {
+ restart_pending || return 0
+ MSO_GATEWAY_ROOT="$ROOT" MSO_GATEWAY_ENV="$ROOT/.env.local" MSO_GATEWAY_LOCAL_URL="$LOCAL_URL" "$GATEWAY" local-start >/dev/null \
+ || fail "build succeeded but the previously-owned local MSO runtime could not be restored"
+ clear_restart_pending
+}
+
print_status() {
- local n local_v remote_v
- require_checkout; fetch_main; n="$(behind)"; local_v="$(current_version)"; remote_v="$(remote_version)"
+ local n local_v remote_v head receipt=''
+ require_checkout; fetch_main; n="$(behind)"; local_v="$(current_version)"; remote_v="$(remote_version)"; head="$(git -C "$ROOT" rev-parse HEAD)"
if [ "$n" -gt 0 ]; then
printf 'update available: mso %s -> %s (%s commit%s)\n' "${local_v:-unknown}" "${remote_v:-newer}" "$n" "$([ "$n" = 1 ] || printf s)"
git -C "$ROOT" log --format=' %h %s' -5 HEAD..origin/main
printf 'run: mso update\n'
- else printf 'mso %s is up to date (%s)\n' "${local_v:-unknown}" "$(git -C "$ROOT" rev-parse --short HEAD)"; fi
+ return
+ fi
+ if command -v systemctl >/dev/null 2>&1 && systemctl is-active --quiet mso.service; then
+ printf 'mso %s is up to date (%s)\n' "${local_v:-unknown}" "${head:0:7}"
+ return
+ fi
+ if [ -e "$DEPLOY_RECEIPT" ] || [ -L "$DEPLOY_RECEIPT" ]; then receipt="$(read_receipt)"; fi
+ if [ "$receipt" != "$head" ] || restart_pending; then
+ printf 'source is current at %s, but offline deployment verification/restart is pending. run: mso update\n' "${head:0:7}"
+ else
+ printf 'mso %s is up to date (%s)\n' "${local_v:-unknown}" "${head:0:7}"
+ fi
}
notice() {
@@ -48,15 +111,30 @@ notice() {
}
offline_build() {
- local rebuild_only="$1"
+ local rebuild_only="$1" n head receipt=''
+ init_update_state
if [ "$rebuild_only" != 1 ]; then
fetch_main
- [ "$(behind)" -gt 0 ] || { printf 'MSO is already up to date.\n'; return 0; }
- git -C "$ROOT" merge --ff-only origin/main || fail "cannot fast-forward to origin/main"
- (cd "$ROOT" && bun install) || fail "dependency install failed"
+ n="$(behind)"
+ [ "$n" -eq 0 ] || git -C "$ROOT" merge --ff-only origin/main || fail "cannot fast-forward to origin/main"
fi
+ head="$(git -C "$ROOT" rev-parse HEAD)"
+ if [ -e "$DEPLOY_RECEIPT" ] || [ -L "$DEPLOY_RECEIPT" ]; then receipt="$(read_receipt)"; fi
+ if [ "$rebuild_only" != 1 ] && [ "$receipt" = "$head" ] && ! restart_pending; then
+ printf 'MSO is already up to date and the offline deployment receipt matches.\n'
+ return 0
+ fi
+
+ # Never mutate .next under a gateway-owned detached Next process. If an earlier
+ # attempt failed after quiescing it, the private restart marker survives and the
+ # next ordinary `mso update` finishes the deployment instead of trusting HEAD.
+ quiesce_offline_runtime
+ (cd "$ROOT" && bun install) || fail "dependency install failed"
(cd "$ROOT" && bash scripts/verify-build.sh) || fail "candidate build verification failed"
(cd "$ROOT" && node node_modules/next/dist/bin/next build) || fail "production build failed"
+ restore_offline_runtime
+ write_receipt
+ if restart_pending; then fail "runtime restart marker remained after restore"; fi
printf 'updated to %s. No system service was active; run: mso web\n' "$(git -C "$ROOT" rev-parse --short HEAD)"
}
diff --git a/scripts/mso-update.test.ts b/scripts/mso-update.test.ts
index 99294d2e..d7bd06d7 100644
--- a/scripts/mso-update.test.ts
+++ b/scripts/mso-update.test.ts
@@ -9,12 +9,16 @@ const PRIVATE = path.join(process.cwd(), "scripts/lib/private-state.sh");
const roots: string[] = [];
function git(cwd: string, ...args: string[]) { return execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); }
-function fixture() {
+function fixture(options: { failInstallOnce?: boolean } = {}) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "mso-update-")); roots.push(root);
const repo = path.join(root, "repo"), remote = path.join(root, "remote.git"), bin = path.join(root, "bin"), capture = path.join(root, "capture");
fs.mkdirSync(path.join(repo, "scripts/lib"), { recursive: true }); fs.mkdirSync(path.join(repo, "bin")); fs.mkdirSync(bin);
fs.copyFileSync(PRIVATE, path.join(repo, "scripts/lib/private-state.sh"));
fs.writeFileSync(path.join(repo, "scripts/verify-build.sh"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
+ fs.writeFileSync(path.join(repo, "scripts/mso-gateway"), `#!/bin/sh
+printf 'gateway %s\\n' "$*" >> "${capture}"
+case "$1" in runtime-stop) echo 'runtime: stopped-owned' ;; local-start) echo 'runtime: healthy MSO at fixture' ;; *) exit 2 ;; esac
+`, { mode: 0o755 });
fs.writeFileSync(path.join(repo, "bin/mso"), '#!/bin/sh\nVERSION="1.3.0"\n', { mode: 0o755 });
fs.mkdirSync(path.join(repo, "node_modules/next/dist/bin"), { recursive: true });
fs.writeFileSync(path.join(repo, "node_modules/next/dist/bin/next"), "fixture\n");
@@ -25,10 +29,15 @@ function fixture() {
git(repo, "add", "bin/mso"); git(repo, "commit", "-q", "-m", "new cli"); const newer = git(repo, "rev-parse", "HEAD"); git(repo, "push", "-q", "origin", "main");
git(repo, "reset", "--hard", "-q", old);
fs.writeFileSync(path.join(bin, "systemctl"), "#!/bin/sh\nexit 3\n", { mode: 0o755 });
- fs.writeFileSync(path.join(bin, "bun"), `#!/bin/sh\nprintf 'bun %s\\n' "$*" >> "${capture}"\n`, { mode: 0o755 });
+ const failOnce = path.join(root, "fail-install-once");
+ fs.writeFileSync(path.join(bin, "bun"), `#!/bin/sh
+printf 'bun %s\\n' "$*" >> "${capture}"
+if [ "${options.failInstallOnce ? "1" : "0"}" = 1 ] && [ "$1" = install ] && [ ! -f "${failOnce}" ]; then touch "${failOnce}"; exit 23; fi
+`, { mode: 0o755 });
fs.writeFileSync(path.join(bin, "node"), `#!/bin/sh\nprintf 'node %s\\n' "$*" >> "${capture}"\n`, { mode: 0o755 });
const env = { ...process.env, HOME: path.join(root, "home"), PATH: `${bin}:${process.env.PATH}`, MSO_UPDATE_ROOT: repo,
- MSO_UPDATE_NOTICE_DIR: path.join(root, "notice") };
+ MSO_UPDATE_NOTICE_DIR: path.join(root, "notice"), MSO_UPDATE_STATE_DIR: path.join(root, "update-state"),
+ MSO_UPDATE_LOCAL_URL: "http://127.0.0.1:4555" };
return { root, repo, old, newer, capture, env };
}
@@ -47,6 +56,24 @@ describe("mso update without a running web API", () => {
expect(git(f.repo, "rev-parse", "HEAD")).toBe(f.newer);
const calls = fs.readFileSync(f.capture, "utf8"); expect(calls).toContain("bun install");
expect(calls).toContain("node node_modules/next/dist/bin/next build");
+ expect(calls).toContain("gateway runtime-stop");
+ expect(calls).toContain("gateway local-start");
+ });
+
+ it("retries an incomplete offline deployment even after HEAD already reached origin/main", () => {
+ const f = fixture({ failInstallOnce: true });
+ const first = require("node:child_process").spawnSync(SCRIPT, [], { env: f.env, encoding: "utf8" });
+ expect(first.status).not.toBe(0);
+ expect(first.stderr).toContain("dependency install failed");
+ expect(git(f.repo, "rev-parse", "HEAD")).toBe(f.newer);
+
+ const second = execFileSync(SCRIPT, [], { env: f.env, encoding: "utf8" });
+ expect(second).toContain("No system service was active");
+ const calls = fs.readFileSync(f.capture, "utf8");
+ expect(calls.match(/bun install/g)?.length).toBe(2);
+ expect(calls).toContain("gateway local-start");
+ const receipt = fs.readFileSync(path.join(f.root, "update-state", "deployed-sha"), "utf8").trim();
+ expect(receipt).toBe(f.newer);
});
it("prints an update notice from cached Git state without touching the web API", () => {