From 4b3c8f213ae56e99bb76d4d147a276781e92d9fd Mon Sep 17 00:00:00 2001
From: Dasemu
Date: Mon, 19 Oct 2026 05:45:25 +0200
Subject: [PATCH 1/3] feat: add a panel button to update the manager itself
The manager clones SELF_UPDATE_REPO_URL, builds a new image in the shared build queue and
hands over to a short-lived updater container (new image) that swaps the manager container,
health-checks it and rolls back on failure. Exposed as GET/POST /api/system behind requireAuth;
installation changes answer 409 while an update runs. Session cookie is now SameSite=Lax.
Co-Authored-By: Claude Sonnet 5.5
---
.env.example | 7 +
CLAUDE.md | 3 +
Dockerfile | 2 +
README.md | 6 +
apps/server/src/api/installations.ts | 11 +
apps/server/src/api/system.ts | 17 ++
apps/server/src/config/env.ts | 4 +
apps/server/src/index.ts | 8 +
apps/server/src/service/buildQueue.ts | 6 +
apps/server/src/service/orchestrator.ts | 6 +-
apps/server/src/system/containerSpec.test.ts | 42 ++++
apps/server/src/system/containerSpec.ts | 40 ++++
apps/server/src/system/dockerLogs.test.ts | 27 +++
apps/server/src/system/dockerLogs.ts | 11 +
apps/server/src/system/selfUpdate.ts | 211 +++++++++++++++++++
apps/server/src/system/selfUpdateHelper.ts | 109 ++++++++++
apps/server/src/system/version.ts | 14 ++
apps/web/src/api/client.ts | 15 ++
apps/web/src/components/ManagerCard.tsx | 123 +++++++++++
apps/web/src/pages/InstallationList.tsx | 3 +
docker-compose.yml | 2 +
docs/architecture.md | 7 +
docs/operations.md | 36 ++++
23 files changed, 705 insertions(+), 5 deletions(-)
create mode 100644 apps/server/src/api/system.ts
create mode 100644 apps/server/src/service/buildQueue.ts
create mode 100644 apps/server/src/system/containerSpec.test.ts
create mode 100644 apps/server/src/system/containerSpec.ts
create mode 100644 apps/server/src/system/dockerLogs.test.ts
create mode 100644 apps/server/src/system/dockerLogs.ts
create mode 100644 apps/server/src/system/selfUpdate.ts
create mode 100644 apps/server/src/system/selfUpdateHelper.ts
create mode 100644 apps/server/src/system/version.ts
create mode 100644 apps/web/src/components/ManagerCard.tsx
diff --git a/.env.example b/.env.example
index ce13f74..d4c26a4 100644
--- a/.env.example
+++ b/.env.example
@@ -40,6 +40,13 @@ MAX_PROXY_REQUESTS=100
# The manager exits (and is restarted by compose) when its heap + external memory passes this. 0 disables.
MANAGER_MEMORY_LIMIT_MB=512
+# Enables the panel's "Update manager" button: the manager clones this repo at SELF_UPDATE_REF,
+# builds a new image and replaces its own container (rolls back if the new one isn't healthy).
+# Operator-set only, never taken from a request. Leave empty to disable the button.
+# Needs SSH_DIR below if the URL is ssh://. See docs/operations.md.
+SELF_UPDATE_REPO_URL=
+SELF_UPDATE_REF=master
+
# Absolute path to an SSH dir (key + known_hosts) with clone access to the repos you'll
# install, mounted read-only into the manager container so `git clone ssh://...` works for
# private repos. Required only if you install from private/SSH repo URLs.
diff --git a/CLAUDE.md b/CLAUDE.md
index 2f6c4f8..5655328 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -40,3 +40,6 @@ authenticated requests to it. See `README.md` for the full flow and `docs/` for
- Local Node 24 cannot compile `better-sqlite3@11`, so `npm test` fails on the host: run the suite in a
`node:20` container (`podman run ... docker.io/library/node:20-slim`, repo copied without `node_modules`).
- `.gitea/workflows/ci.yml` only runs if this repo's Gitea instance has Actions enabled with a runner.
+- Self-update (panel button) needs `SELF_UPDATE_REPO_URL` and only works when the manager runs in a
+ container; the swap is done by a helper container (`system/selfUpdateHelper.ts`), not by the
+ manager itself. Keep the helper standalone (no config/db imports). See `docs/operations.md`.
diff --git a/Dockerfile b/Dockerfile
index a88dd6b..fa1f840 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -38,6 +38,8 @@ RUN npm ci --omit=dev --workspace apps/server
COPY --from=build /repo/apps/server/dist apps/server/dist
COPY --from=build /repo/apps/web/dist apps/web/dist
+# Shown in the panel next to the self-update button.
+COPY VERSION VERSION
WORKDIR /repo/apps/server
ENV NODE_ENV=production
diff --git a/README.md b/README.md
index f1d407c..6bdf86b 100644
--- a/README.md
+++ b/README.md
@@ -14,6 +14,12 @@ docker compose up -d --build
Put your own reverse proxy (nginx, etc.) in front of port 3000 for TLS and your public domain.
+## Updating
+
+Set `SELF_UPDATE_REPO_URL` (and optionally `SELF_UPDATE_REF`) in `.env` and use the **Update manager**
+button in the panel: it builds the latest source and swaps the manager's container, rolling back
+if the new one isn't healthy. Details in [docs/operations.md](docs/operations.md).
+
## Local development (Podman)
Requires `nixpacks` and a `docker` CLI pointed at your Podman socket (e.g. via the
diff --git a/apps/server/src/api/installations.ts b/apps/server/src/api/installations.ts
index 207e6bc..cfecd7a 100644
--- a/apps/server/src/api/installations.ts
+++ b/apps/server/src/api/installations.ts
@@ -21,9 +21,20 @@ import {
import { buildLogPath } from "../build/nixpacks.js";
import { generateBearerToken } from "../crypto/secrets.js";
import fs from "node:fs";
+import { isSelfUpdateInProgress } from "../system/selfUpdate.js";
export const installationsRouter = Router();
+// An update swaps the manager's own container; an installation build or start in flight would be
+// killed by it, so changes wait until the update is over.
+installationsRouter.use((req, res, next) => {
+ if (req.method !== "GET" && isSelfUpdateInProgress()) {
+ res.status(409).json({ error: "the manager is updating itself; try again in a minute" });
+ return;
+ }
+ next();
+});
+
// Not masked: this API sits behind single-operator session auth (requireAuth), and the
// operator is the same person who owns these secrets — editing them requires seeing them.
function toPublicJson(installation: Installation) {
diff --git a/apps/server/src/api/system.ts b/apps/server/src/api/system.ts
new file mode 100644
index 0000000..f4a791f
--- /dev/null
+++ b/apps/server/src/api/system.ts
@@ -0,0 +1,17 @@
+import { Router } from "express";
+import { getSystemInfo, startSelfUpdate, SelfUpdateError } from "../system/selfUpdate.js";
+
+export const systemRouter = Router();
+
+systemRouter.get("/", async (_req, res) => {
+ res.json(await getSystemInfo());
+});
+
+systemRouter.post("/update", async (_req, res) => {
+ try {
+ await startSelfUpdate();
+ res.status(202).json({ ok: true });
+ } catch (err) {
+ res.status(err instanceof SelfUpdateError ? err.status : 500).json({ error: (err as Error).message });
+ }
+});
diff --git a/apps/server/src/config/env.ts b/apps/server/src/config/env.ts
index e7589ee..8d70e6a 100644
--- a/apps/server/src/config/env.ts
+++ b/apps/server/src/config/env.ts
@@ -25,4 +25,8 @@ export const config = {
// The manager exits (and the container restart policy brings it back) once its own
// heap + external memory exceeds this. 0 disables the guard.
memoryLimitMb: Number(process.env.MANAGER_MEMORY_LIMIT_MB ?? 512),
+ // Self-update: git repo/ref the manager rebuilds itself from. Operator-set only (never taken
+ // from a request); without a repo URL the panel's "Update manager" button is disabled.
+ selfUpdateRepoUrl: process.env.SELF_UPDATE_REPO_URL || undefined,
+ selfUpdateRef: process.env.SELF_UPDATE_REF || "master",
};
diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts
index 8240b54..adf15d1 100644
--- a/apps/server/src/index.ts
+++ b/apps/server/src/index.ts
@@ -7,6 +7,8 @@ import { reconcileInterruptedInstallations } from "./db/installations.js";
import { getActiveProxyRequests, handleMcpProxyRequest } from "./proxy/mcpProxy.js";
import { authRouter } from "./api/auth.js";
import { installationsRouter } from "./api/installations.js";
+import { systemRouter } from "./api/system.js";
+import { collectSelfUpdateResult } from "./system/selfUpdate.js";
import { requireAuth } from "./middleware/requireAuth.js";
import { SqliteSessionStore } from "./session/sqliteStore.js";
import { startMemoryGuard } from "./service/memoryGuard.js";
@@ -28,6 +30,8 @@ app.use(
saveUninitialized: false,
cookie: {
httpOnly: true,
+ // Lax: a cross-site form POST must not carry the session (e.g. to trigger a manager update).
+ sameSite: "lax",
// "auto": secure only if the request actually arrived over HTTPS (checks req.secure,
// which respects "trust proxy" + X-Forwarded-Proto). A flat `NODE_ENV === "production"`
// check meant the cookie was never stored at all when the admin panel is reached over
@@ -60,6 +64,7 @@ app.all("/mcp/:slug", handleMcpProxyRequest);
app.use("/api", express.json());
app.use("/api/auth", authRouter);
app.use("/api/installations", requireAuth, installationsRouter);
+app.use("/api/system", requireAuth, systemRouter);
const webDist = path.resolve(import.meta.dirname, "../../web/dist");
app.use(express.static(webDist));
@@ -73,6 +78,9 @@ const server = app.listen(config.port, () => {
console.log(`remote-mcp-manager listening on http://localhost:${config.port}`);
});
+// If an updater container ran just before this boot, pick up its outcome for the panel.
+void collectSelfUpdateResult();
+
function shutdown(code: number): void {
server.close(() => process.exit(code));
server.closeAllConnections();
diff --git a/apps/server/src/service/buildQueue.ts b/apps/server/src/service/buildQueue.ts
new file mode 100644
index 0000000..74b0cf2
--- /dev/null
+++ b/apps/server/src/service/buildQueue.ts
@@ -0,0 +1,6 @@
+import { createSerialQueue } from "../util/serialQueue.js";
+
+// Builds are the heaviest thing the host does (nixpacks + docker build); running several at
+// once on a small host is what pushes it into swap. Serialize them — including the manager's
+// own self-update build.
+export const enqueueBuild = createSerialQueue();
diff --git a/apps/server/src/service/orchestrator.ts b/apps/server/src/service/orchestrator.ts
index a4ab18f..84cf838 100644
--- a/apps/server/src/service/orchestrator.ts
+++ b/apps/server/src/service/orchestrator.ts
@@ -20,11 +20,7 @@ import {
removeImageIfUnused,
} from "../docker/containers.js";
import { generateBearerToken } from "../crypto/secrets.js";
-import { createSerialQueue } from "../util/serialQueue.js";
-
-// Builds are the heaviest thing the host does (nixpacks + docker build); running several at
-// once on a small host is what pushes it into swap. Serialize them.
-const enqueueBuild = createSerialQueue();
+import { enqueueBuild } from "./buildQueue.js";
export interface DraftResult {
installation: Installation;
diff --git a/apps/server/src/system/containerSpec.test.ts b/apps/server/src/system/containerSpec.test.ts
new file mode 100644
index 0000000..53cd75f
--- /dev/null
+++ b/apps/server/src/system/containerSpec.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from "vitest";
+import type { ContainerInspectInfo } from "dockerode";
+import { buildReplacementSpec } from "./containerSpec.js";
+
+const old = {
+ Id: "0123456789abcdef0123",
+ Name: "/remote-mcp-manager-manager-1",
+ Config: {
+ Env: ["PATH=/usr/bin", "NODE_OPTIONS=--old", "ADMIN_PASSWORD=x", "PORT=3000"],
+ Labels: { "com.docker.compose.service": "manager" },
+ ExposedPorts: { "3000/tcp": {} },
+ User: "",
+ Hostname: "0123456789ab",
+ Cmd: ["node", "old.js"],
+ },
+ HostConfig: {
+ NetworkMode: "mcp-net",
+ Binds: ["/var/run/docker.sock:/var/run/docker.sock", "./data:/repo/data"],
+ RestartPolicy: { Name: "unless-stopped" },
+ },
+ NetworkSettings: { Networks: { "mcp-net": { Aliases: ["manager", "0123456789ab"] } } },
+} as unknown as ContainerInspectInfo;
+
+describe("buildReplacementSpec", () => {
+ const spec = buildReplacementSpec(old, ["PATH=/usr/bin", "NODE_OPTIONS=--old"], "mcpmgr-manager:new");
+
+ it("keeps the name, host config and operator-set env, and runs the new image", () => {
+ expect(spec.name).toBe("remote-mcp-manager-manager-1");
+ expect(spec.Image).toBe("mcpmgr-manager:new");
+ expect(spec.HostConfig).toBe(old.HostConfig);
+ expect(spec.Env).toEqual(["ADMIN_PASSWORD=x", "PORT=3000"]);
+ });
+
+ it("does not pin the old image's Cmd or hostname", () => {
+ expect(spec.Cmd).toBeUndefined();
+ expect(spec.Hostname).toBeUndefined();
+ });
+
+ it("keeps network aliases except the old container's own id", () => {
+ expect(spec.NetworkingConfig?.EndpointsConfig?.["mcp-net"]?.Aliases).toEqual(["manager"]);
+ });
+});
diff --git a/apps/server/src/system/containerSpec.ts b/apps/server/src/system/containerSpec.ts
new file mode 100644
index 0000000..c9bbb1d
--- /dev/null
+++ b/apps/server/src/system/containerSpec.ts
@@ -0,0 +1,40 @@
+import type { ContainerCreateOptions, ContainerInspectInfo } from "dockerode";
+
+/**
+ * Builds the create options for a container that replaces `old` but runs `newImage`, keeping
+ * everything the operator configured (name, bind mounts, port bindings, network + aliases,
+ * restart policy, user-supplied env) and nothing the image itself defines.
+ *
+ * `oldImageEnv` is the env baked into the OLD image: those entries are dropped, otherwise a
+ * `docker inspect`'d container pins the old image's ENV and a changed ENV in the new image
+ * (e.g. NODE_OPTIONS) would silently never apply. Cmd/Entrypoint/Hostname are likewise left
+ * out so the new image's defaults and a fresh hostname (= its own container id) apply.
+ */
+export function buildReplacementSpec(
+ old: ContainerInspectInfo,
+ oldImageEnv: string[],
+ newImage: string,
+): ContainerCreateOptions {
+ const networkMode = old.HostConfig.NetworkMode ?? "default";
+ const network = old.NetworkSettings.Networks[networkMode];
+ const shortId = old.Id.slice(0, 12);
+
+ return {
+ name: old.Name.replace(/^\//, ""),
+ Image: newImage,
+ Env: (old.Config.Env ?? []).filter((e) => !oldImageEnv.includes(e)),
+ Labels: old.Config.Labels ?? {},
+ ExposedPorts: old.Config.ExposedPorts,
+ User: old.Config.User || undefined,
+ HostConfig: old.HostConfig,
+ ...(network
+ ? {
+ NetworkingConfig: {
+ EndpointsConfig: {
+ [networkMode]: { Aliases: ((network.Aliases ?? []) as string[]).filter((a) => a !== shortId) },
+ },
+ },
+ }
+ : {}),
+ };
+}
diff --git a/apps/server/src/system/dockerLogs.test.ts b/apps/server/src/system/dockerLogs.test.ts
new file mode 100644
index 0000000..fe900be
--- /dev/null
+++ b/apps/server/src/system/dockerLogs.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from "vitest";
+import { demuxLogs } from "./dockerLogs.js";
+
+function frame(stream: number, text: string): Buffer {
+ const payload = Buffer.from(text);
+ const header = Buffer.alloc(8);
+ header[0] = stream;
+ header.writeUInt32BE(payload.length, 4);
+ return Buffer.concat([header, payload]);
+}
+
+describe("demuxLogs", () => {
+ it("joins stdout and stderr frames in order", () => {
+ const buf = Buffer.concat([frame(1, "hello "), frame(2, "world\n")]);
+ expect(demuxLogs(buf)).toBe("hello world\n");
+ });
+
+ it("returns an empty string for empty or header-only input", () => {
+ expect(demuxLogs(Buffer.alloc(0))).toBe("");
+ expect(demuxLogs(Buffer.alloc(4))).toBe("");
+ });
+
+ it("does not read past a truncated frame", () => {
+ const buf = frame(1, "abcdef").subarray(0, 8 + 3);
+ expect(demuxLogs(buf)).toBe("abc");
+ });
+});
diff --git a/apps/server/src/system/dockerLogs.ts b/apps/server/src/system/dockerLogs.ts
new file mode 100644
index 0000000..9824f17
--- /dev/null
+++ b/apps/server/src/system/dockerLogs.ts
@@ -0,0 +1,11 @@
+/** Demuxes Docker's non-tty log stream (8-byte frame headers) into plain text. */
+export function demuxLogs(buf: Buffer): string {
+ const out: string[] = [];
+ let offset = 0;
+ while (offset + 8 <= buf.length) {
+ const size = buf.readUInt32BE(offset + 4);
+ out.push(buf.subarray(offset + 8, offset + 8 + size).toString("utf8"));
+ offset += 8 + size;
+ }
+ return out.join("");
+}
diff --git a/apps/server/src/system/selfUpdate.ts b/apps/server/src/system/selfUpdate.ts
new file mode 100644
index 0000000..dfbaa73
--- /dev/null
+++ b/apps/server/src/system/selfUpdate.ts
@@ -0,0 +1,211 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { spawn } from "node:child_process";
+import Docker from "dockerode";
+import { config } from "../config/env.js";
+import { listInstallations } from "../db/installations.js";
+import { cloneOrUpdateRepo, repoDir } from "../build/git.js";
+import { enqueueBuild } from "../service/buildQueue.js";
+import { killGroupAfter } from "../util/processTimeout.js";
+import { withTimeout } from "../util/withTimeout.js";
+import { demuxLogs } from "./dockerLogs.js";
+import { readVersion } from "./version.js";
+
+const docker = new Docker({ socketPath: config.dockerSocketPath });
+
+const HELPER_LABEL = "remote-mcp-manager.self-update-helper";
+const BUILD_TIMEOUT_MS = 30 * 60 * 1000;
+// Updater: up to 90 s of health checks plus stop/create/rollback; this is only a backstop.
+const HANDOVER_TIMEOUT_MS = 5 * 60 * 1000;
+// The checkout lives under a name no installation slug can take (slugify strips underscores).
+const CHECKOUT_SLUG = "_manager";
+const BUSY_STATUSES = new Set(["cloning", "building", "starting"]);
+
+type Phase = "idle" | "cloning" | "building" | "handing-over";
+
+const state: { phase: Phase; error?: string; logPath?: string } = { phase: "idle" };
+let lastResult: { finishedAt: string; ok: boolean; log: string } | null = null;
+
+/** The container this process runs in (Docker sets the hostname to the container id), if any. */
+async function inspectSelf() {
+ try {
+ return await withTimeout(docker.getContainer(os.hostname()).inspect(), 10_000, "docker inspect self");
+ } catch {
+ return undefined;
+ }
+}
+
+function tailOfLog(maxLines = 200): string {
+ if (!state.logPath || !fs.existsSync(state.logPath)) return "";
+ return fs.readFileSync(state.logPath, "utf8").split("\n").slice(-maxLines).join("\n");
+}
+
+export async function getSystemInfo() {
+ // The updater is usually still running when the new manager boots, so its result can only be
+ // collected later; polling this endpoint is what picks it up.
+ if (!lastResult && state.phase === "idle") await collectSelfUpdateResult();
+ const self = await inspectSelf();
+ return {
+ version: readVersion(),
+ uptimeSec: Math.round(process.uptime()),
+ canSelfUpdate: Boolean(config.selfUpdateRepoUrl && self),
+ unavailableReason: !config.selfUpdateRepoUrl
+ ? "SELF_UPDATE_REPO_URL is not set"
+ : !self
+ ? "the manager is not running inside a container it can inspect"
+ : null,
+ ref: config.selfUpdateRef,
+ phase: state.phase,
+ error: state.error ?? null,
+ log: state.phase === "idle" && !state.error ? "" : tailOfLog(),
+ lastUpdate: lastResult,
+ };
+}
+
+function runDockerBuild(contextDir: string, image: string, logPath: string): Promise {
+ return new Promise((resolve) => {
+ const logStream = fs.createWriteStream(logPath, { flags: "a" });
+ const child = spawn("docker", ["build", "-t", image, contextDir], { detached: true });
+ killGroupAfter(child, BUILD_TIMEOUT_MS);
+ child.stdout.pipe(logStream, { end: false });
+ child.stderr.pipe(logStream, { end: false });
+ child.on("close", (code) => {
+ logStream.end();
+ resolve(code === 0);
+ });
+ child.on("error", (err) => {
+ logStream.write(`\nfailed to spawn docker: ${err.message}\n`);
+ logStream.end();
+ resolve(false);
+ });
+ });
+}
+
+async function runUpdate(self: Docker.ContainerInspectInfo): Promise {
+ const url = config.selfUpdateRepoUrl!;
+ const image = `mcpmgr-manager:update-${Date.now()}`;
+ const logDir = path.join(config.logsDir, CHECKOUT_SLUG);
+ fs.mkdirSync(logDir, { recursive: true });
+ state.logPath = path.join(logDir, `${Date.now()}.log`);
+ const note = (msg: string) => fs.appendFileSync(state.logPath!, `[self-update] ${msg}\n`);
+
+ try {
+ // Same queue as installation builds: never two heavy builds at once on a small host. The
+ // hand-over below also happens inside it, so no queued build can start while the manager is
+ // about to be swapped out.
+ await enqueueBuild(async () => {
+ state.phase = "cloning";
+ note(`cloning ${url} (${config.selfUpdateRef})`);
+ await cloneOrUpdateRepo(CHECKOUT_SLUG, url, config.selfUpdateRef);
+
+ state.phase = "building";
+ note(`building ${image}`);
+ if (!(await runDockerBuild(repoDir(CHECKOUT_SLUG), image, state.logPath!))) {
+ throw new Error(`image build failed, see ${state.logPath}`);
+ }
+
+ state.phase = "handing-over";
+ const socketBind = (self.HostConfig.Binds ?? []).find((b) => b.split(":")[1] === config.dockerSocketPath);
+ if (!socketBind) throw new Error(`no bind mount for ${config.dockerSocketPath} on the manager container`);
+
+ note("starting the updater container; the manager will restart shortly");
+ const helper = await docker.createContainer({
+ Image: image,
+ Cmd: ["node", "dist/system/selfUpdateHelper.js"],
+ Env: [
+ `OLD_CONTAINER_ID=${self.Id}`,
+ `NEW_IMAGE=${image}`,
+ `DOCKER_SOCKET_PATH=${config.dockerSocketPath}`,
+ ],
+ Labels: { [HELPER_LABEL]: "1" },
+ HostConfig: {
+ Binds: [socketBind],
+ SecurityOpt: self.HostConfig.SecurityOpt ?? undefined,
+ NetworkMode: self.HostConfig.NetworkMode,
+ RestartPolicy: { Name: "no" },
+ },
+ });
+ await helper.start();
+
+ // A successful hand-over kills this process, so getting past this wait means the updater
+ // ended without replacing us (crashed early, rolled back before stopping us) or hung.
+ const exit = (await withTimeout(helper.wait(), HANDOVER_TIMEOUT_MS, "updater container")) as { StatusCode: number };
+ await collectSelfUpdateResult();
+ throw new Error(
+ exit.StatusCode === 0
+ ? "the updater finished but this manager is still running"
+ : `the updater exited with code ${exit.StatusCode}${lastResult ? `:\n${lastResult.log.split("\n").slice(-15).join("\n")}` : ""}`,
+ );
+ });
+ } catch (err) {
+ state.phase = "idle";
+ state.error = (err as Error).message;
+ note(`failed: ${state.error}`);
+ }
+}
+
+/** True from the moment an update is requested until it fails; a successful one ends this process. */
+export function isSelfUpdateInProgress(): boolean {
+ return state.phase !== "idle";
+}
+
+export class SelfUpdateError extends Error {
+ constructor(
+ message: string,
+ readonly status: number,
+ ) {
+ super(message);
+ }
+}
+
+/** Validates preconditions and starts the update in the background. Throws SelfUpdateError if it can't. */
+export async function startSelfUpdate(): Promise {
+ if (!config.selfUpdateRepoUrl) throw new SelfUpdateError("SELF_UPDATE_REPO_URL is not set", 400);
+ if (state.phase !== "idle") throw new SelfUpdateError("an update is already in progress", 409);
+ if (listInstallations().some((i) => BUSY_STATUSES.has(i.status))) {
+ throw new SelfUpdateError("an installation is building or starting; wait for it to finish", 409);
+ }
+
+ // Claimed before the first await so two concurrent requests can't both start an update.
+ state.phase = "cloning";
+ state.error = undefined;
+ const self = await inspectSelf();
+ if (!self) {
+ state.phase = "idle";
+ throw new SelfUpdateError("the manager is not running inside a container it can inspect", 400);
+ }
+ void runUpdate(self);
+}
+
+/**
+ * Called once at boot: if an updater container left a result behind (this process is either the
+ * freshly updated manager or the one the updater rolled back to), record its log and clean it up.
+ */
+export async function collectSelfUpdateResult(): Promise {
+ try {
+ const helpers = await withTimeout(
+ docker.listContainers({ all: true, filters: { label: [HELPER_LABEL] } }),
+ 10_000,
+ "docker list updater",
+ );
+ for (const h of helpers) {
+ if (h.State === "running") continue;
+ const container = docker.getContainer(h.Id);
+ const info = await withTimeout(container.inspect(), 10_000, "docker inspect updater");
+ const logs = (await withTimeout(
+ container.logs({ stdout: true, stderr: true }),
+ 10_000,
+ "docker logs updater",
+ )) as unknown as Buffer;
+ lastResult = {
+ finishedAt: info.State.FinishedAt,
+ ok: info.State.ExitCode === 0,
+ log: demuxLogs(Buffer.from(logs)),
+ };
+ await withTimeout(container.remove({ force: true }), 10_000, "docker rm updater");
+ }
+ } catch {
+ // Best effort: no Docker access (e.g. local dev) just means there is nothing to report.
+ }
+}
diff --git a/apps/server/src/system/selfUpdateHelper.ts b/apps/server/src/system/selfUpdateHelper.ts
new file mode 100644
index 0000000..5051d5d
--- /dev/null
+++ b/apps/server/src/system/selfUpdateHelper.ts
@@ -0,0 +1,109 @@
+// Entry point of the short-lived "updater" container (the NEW image run with this script).
+// The manager can't replace itself — stopping its own container kills the code doing it — so it
+// hands over to this process, which swaps the manager container for one running NEW_IMAGE and
+// rolls back to the old container if the new one never becomes healthy.
+// Standalone on purpose: it doesn't import the app's config/db modules.
+import http from "node:http";
+import Docker from "dockerode";
+import { buildReplacementSpec } from "./containerSpec.js";
+
+const socketPath = process.env.DOCKER_SOCKET_PATH ?? "/var/run/docker.sock";
+const oldId = process.env.OLD_CONTAINER_ID;
+const newImage = process.env.NEW_IMAGE;
+const HEALTH_TIMEOUT_MS = 90_000;
+
+const docker = new Docker({ socketPath });
+const log = (msg: string) => console.log(`[self-update] ${msg}`);
+
+function checkHealth(ip: string, port: number): Promise {
+ return new Promise((resolve) => {
+ const req = http.get({ host: ip, port, path: "/health", timeout: 2_000 }, (res) => {
+ res.resume();
+ resolve(res.statusCode === 200);
+ });
+ req.on("error", () => resolve(false));
+ req.on("timeout", () => {
+ req.destroy();
+ resolve(false);
+ });
+ });
+}
+
+async function waitUntilHealthy(containerId: string, network: string, port: number): Promise {
+ const deadline = Date.now() + HEALTH_TIMEOUT_MS;
+ while (Date.now() < deadline) {
+ const info = await docker.getContainer(containerId).inspect();
+ if (!info.State.Running && info.State.Status !== "restarting") return false;
+ const ip = info.NetworkSettings.Networks[network]?.IPAddress;
+ if (ip && (await checkHealth(ip, port))) return true;
+ await new Promise((r) => setTimeout(r, 2_000));
+ }
+ return false;
+}
+
+async function main(): Promise {
+ if (!oldId || !newImage) throw new Error("OLD_CONTAINER_ID and NEW_IMAGE are required");
+
+ const oldContainer = docker.getContainer(oldId);
+ const old = await oldContainer.inspect();
+ const name = old.Name.replace(/^\//, "");
+ const oldImageEnv = (await docker.getImage(old.Image).inspect()).Config.Env ?? [];
+ const spec = buildReplacementSpec(old, oldImageEnv, newImage);
+ const network = old.HostConfig.NetworkMode ?? "default";
+ const port = Number(old.Config.Env?.find((e) => e.startsWith("PORT="))?.slice(5) ?? 3000);
+
+ // The old container holds the name and the published port, so it has to go first. It is only
+ // renamed and stopped (not removed) so it can be started again if the new one fails. Renaming
+ // comes first, while it is still running: if that fails, nothing has been touched yet.
+ const backupName = `${name}-pre-update`;
+ await docker.getContainer(backupName).remove({ force: true }).catch(() => {});
+ await oldContainer.rename({ name: backupName });
+ log(`stopping ${name} (${old.Id.slice(0, 12)})`);
+ try {
+ await oldContainer.stop({ t: 15 });
+ } catch (err) {
+ if ((err as { statusCode?: number }).statusCode !== 304) {
+ await oldContainer.rename({ name }).catch(() => {});
+ throw err;
+ }
+ }
+
+ let created: Docker.Container | undefined;
+ let healthy = false;
+ try {
+ log(`starting new container from ${newImage}`);
+ created = await docker.createContainer(spec);
+ await created.start();
+ healthy = await waitUntilHealthy(created.id, network, port);
+ if (!healthy) log(`new manager did not become healthy within ${HEALTH_TIMEOUT_MS / 1000}s`);
+ } catch (err) {
+ log(`failed to start the new container: ${(err as Error).message}`);
+ }
+
+ if (healthy) {
+ // The update has succeeded; failing to tidy up must not undo it.
+ log("new manager is healthy, removing the old container");
+ await oldContainer.remove({ force: true }).catch((err) => log(`could not remove the old container: ${err.message}`));
+ await docker.getImage(old.Image).remove({ force: false }).catch(() => {});
+ log("update complete");
+ return 0;
+ }
+
+ // Every rollback step is attempted on its own: the old container must be started again even if
+ // an earlier step failed.
+ log("rolling back to the previous manager");
+ if (created) await created.remove({ force: true }).catch((err) => log(`could not remove the new container: ${err.message}`));
+ await oldContainer.rename({ name }).catch((err) => log(`could not restore the name: ${err.message}`));
+ await oldContainer.start().catch((err) => log(`could not start the old container: ${err.message}`));
+ await docker.getImage(newImage).remove({ force: false }).catch(() => {});
+ log("rollback complete");
+ return 1;
+}
+
+main().then(
+ (code) => process.exit(code),
+ (err) => {
+ log(`fatal: ${(err as Error).stack ?? err}`);
+ process.exit(2);
+ },
+);
diff --git a/apps/server/src/system/version.ts b/apps/server/src/system/version.ts
new file mode 100644
index 0000000..58ff796
--- /dev/null
+++ b/apps/server/src/system/version.ts
@@ -0,0 +1,14 @@
+import fs from "node:fs";
+import path from "node:path";
+
+// VERSION sits at the repo root, four levels above this file in both the image and a checkout:
+// /apps/server/{src,dist}/system/version.*
+const versionFile = path.resolve(import.meta.dirname, "../../../../VERSION");
+
+export function readVersion(): string {
+ try {
+ return fs.readFileSync(versionFile, "utf8").trim() || "unknown";
+ } catch {
+ return "unknown";
+ }
+}
diff --git a/apps/web/src/api/client.ts b/apps/web/src/api/client.ts
index afca352..5fe54c4 100644
--- a/apps/web/src/api/client.ts
+++ b/apps/web/src/api/client.ts
@@ -19,6 +19,18 @@ export interface Installation {
updatedAt: string;
}
+export interface SystemInfo {
+ version: string;
+ uptimeSec: number;
+ canSelfUpdate: boolean;
+ unavailableReason: string | null;
+ ref: string;
+ phase: "idle" | "cloning" | "building" | "handing-over";
+ error: string | null;
+ log: string;
+ lastUpdate: { finishedAt: string; ok: boolean; log: string } | null;
+}
+
async function request(path: string, init?: RequestInit): Promise {
const res = await fetch(path, {
...init,
@@ -60,4 +72,7 @@ export const api = {
request<{ bearerToken: string }>(`/api/installations/${id}/regenerate-token`, { method: "POST" }),
remove: (id: string) => request(`/api/installations/${id}`, { method: "DELETE" }),
logs: (id: string) => request<{ log: string }>(`/api/installations/${id}/logs`),
+
+ systemInfo: () => request("/api/system"),
+ updateManager: () => request<{ ok: true }>("/api/system/update", { method: "POST" }),
};
diff --git a/apps/web/src/components/ManagerCard.tsx b/apps/web/src/components/ManagerCard.tsx
new file mode 100644
index 0000000..10280fe
--- /dev/null
+++ b/apps/web/src/components/ManagerCard.tsx
@@ -0,0 +1,123 @@
+import { useEffect, useState } from "react";
+import { api, type SystemInfo } from "../api/client";
+
+// Stops waiting for a manager that never comes back (the updater itself gives up well before this).
+const MAX_WAIT_MS = 10 * 60 * 1000;
+
+const PHASE_LABEL: Record = {
+ idle: "",
+ cloning: "Fetching the latest source…",
+ building: "Building the new image…",
+ "handing-over": "Handing over to the new version…",
+};
+
+export function ManagerCard() {
+ const [info, setInfo] = useState(null);
+ const [error, setError] = useState(null);
+ const [requested, setRequested] = useState(false);
+ const [unreachable, setUnreachable] = useState(false);
+ const [startedAt, setStartedAt] = useState(null);
+ const [gaveUp, setGaveUp] = useState(false);
+
+ async function refresh() {
+ try {
+ setInfo(await api.systemInfo());
+ setUnreachable(false);
+ } catch {
+ // Expected while the container is being swapped; keep polling until it answers again.
+ setUnreachable(true);
+ }
+ }
+
+ useEffect(() => {
+ refresh();
+ }, []);
+
+ const updating = !gaveUp && (requested || (info !== null && info.phase !== "idle"));
+
+ useEffect(() => {
+ if (!updating) return;
+ const timer = setInterval(() => {
+ if (startedAt !== null && Date.now() - startedAt > MAX_WAIT_MS) {
+ setGaveUp(true);
+ setRequested(false);
+ return;
+ }
+ refresh();
+ }, 3000);
+ return () => clearInterval(timer);
+ }, [updating, startedAt]);
+
+ // The update is over once the manager answers again with nothing in progress.
+ useEffect(() => {
+ // A restarted manager has a smaller uptime than the time since we asked.
+ const restarted = startedAt !== null && info !== null && info.uptimeSec * 1000 < Date.now() - startedAt;
+ if (requested && info && info.phase === "idle" && !unreachable && (info.lastUpdate || info.error || restarted)) {
+ setRequested(false);
+ }
+ }, [requested, info, unreachable, startedAt]);
+
+ async function update() {
+ if (!info) return;
+ const msg =
+ `Update the manager from ${info.ref}? It builds a new image, then restarts itself ` +
+ "(a few seconds of downtime; MCP clients should reconnect). It rolls back if the new version isn't healthy.";
+ if (!window.confirm(msg)) return;
+ setError(null);
+ try {
+ await api.updateManager();
+ setGaveUp(false);
+ setStartedAt(Date.now());
+ setRequested(true);
+ refresh();
+ } catch (err) {
+ setError((err as Error).message);
+ }
+ }
+
+ if (!info && !unreachable) return null;
+
+ const log = info?.log || info?.lastUpdate?.log || "";
+
+ return (
+
+
+ Manager
+
+ {info ? `Version ${info.version} · ${info.ref}` : "Restarting…"}
+
+
+
+ {updating && (
+
+ {unreachable ? "The manager is restarting, waiting for it to come back…" : PHASE_LABEL[info?.phase ?? "idle"]}
+
+ )}
+ {error &&
{error}
}
+ {gaveUp &&
The manager did not come back in 10 minutes; check the host.
}
+ {info?.error &&
Update failed: {info.error}
}
+ {!updating && info?.lastUpdate && (
+
+ Last update {info.lastUpdate.ok ? "succeeded" : "did not complete (rolled back or failed; see the log)"} ({new Date(info.lastUpdate.finishedAt).toLocaleString()}).
+
+ )}
+ {info && !info.canSelfUpdate && info.unavailableReason && (
+
Self-update unavailable: {info.unavailableReason}.
+ )}
+
+
+
+ {updating ? "Updating…" : "Update manager"}
+
+
+
+ {log &&
{log} }
+
+ );
+}
diff --git a/apps/web/src/pages/InstallationList.tsx b/apps/web/src/pages/InstallationList.tsx
index 9d37fe8..1e5d81f 100644
--- a/apps/web/src/pages/InstallationList.tsx
+++ b/apps/web/src/pages/InstallationList.tsx
@@ -2,6 +2,7 @@ import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { api, type Installation } from "../api/client";
import { InstallWizard } from "./InstallWizard";
+import { ManagerCard } from "../components/ManagerCard";
import { Shell } from "../components/Shell";
import { StatusBadge } from "../components/StatusBadge";
@@ -71,6 +72,8 @@ export function InstallationList({ onLoggedOut }: { onLoggedOut: () => void }) {
)}
+
+
);
}
diff --git a/docker-compose.yml b/docker-compose.yml
index 33b9860..fa325e6 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -18,6 +18,8 @@ services:
PROXY_TIMEOUT_MS: ${PROXY_TIMEOUT_MS:-300000}
MAX_PROXY_REQUESTS: ${MAX_PROXY_REQUESTS:-100}
MANAGER_MEMORY_LIMIT_MB: ${MANAGER_MEMORY_LIMIT_MB:-512}
+ SELF_UPDATE_REPO_URL: ${SELF_UPDATE_REPO_URL:-}
+ SELF_UPDATE_REF: ${SELF_UPDATE_REF:-master}
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- ./data:/repo/data
diff --git a/docs/architecture.md b/docs/architecture.md
index dfaf92f..0f514e5 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -54,3 +54,10 @@ manager can only reach sibling MCP containers (by IP on `mcp-net`) when it is it
attached to that network — running it directly on the host only works for routes that
don't need to reach a sibling container (e.g. `/health`, `/api/auth`). See the README's
"Local development (Podman)" section and `LESSONS.md` for the operational detail.
+
+## Self-update
+
+`system/selfUpdate.ts` (state, clone + build in the shared build queue, hand-over) and
+`system/selfUpdateHelper.ts` (the updater container's entry point: swap, health check, rollback)
+implement the panel's *Update manager* button, exposed as `GET /api/system` and
+`POST /api/system/update` behind `requireAuth`. See `docs/operations.md`.
diff --git a/docs/operations.md b/docs/operations.md
index 545d258..77e5232 100644
--- a/docs/operations.md
+++ b/docs/operations.md
@@ -29,3 +29,39 @@ yourself on hosts that support it.
`activeProxyRequests`. A heap that keeps climbing between restarts, or an
`activeProxyRequests` that stays high with no traffic, points at a leak. A line
`memory guard: ... restarting` in the manager's log means the guard fired.
+
+## Updating the manager from the panel
+
+The **Manager** card on the installations page has an *Update manager* button. It is enabled when
+`SELF_UPDATE_REPO_URL` is set (operator-only env var, never taken from a request) and the manager
+runs in a container whose id it can inspect (production compose; not local `npm run dev`).
+
+Flow:
+
+1. In the serial build queue (so it never overlaps an installation build) the manager clones
+ `SELF_UPDATE_REPO_URL` at `SELF_UPDATE_REF` (default `master`) and runs `docker build` on it.
+ Refused with `409` if an installation is cloning/building/starting.
+2. It starts a short-lived **updater container** from the *new* image
+ (`node dist/system/selfUpdateHelper.js`, label `remote-mcp-manager.self-update-helper`). A
+ manager cannot replace itself: stopping its own container kills the code doing it.
+3. The updater stops the old manager, renames it `-pre-update`, creates a replacement with
+ the same name, bind mounts, port bindings, network aliases, restart policy, labels and operator
+ env (`buildReplacementSpec`), but the new image's own `Cmd` and image `ENV`, and polls
+ `/health` for up to 90 s.
+4. Healthy: the old container and image are removed. Not healthy: the replacement is removed and
+ the old container is renamed back and started (rollback). Exit code 0 = updated, 1 = rolled
+ back, 2 = fatal.
+5. The (new or restored) manager reads the exited updater's logs at the next `GET /api/system`,
+ shows the outcome in the card, and removes the updater container.
+
+Expect a few seconds of downtime while the containers swap; the panel keeps polling and reconnects
+on its own. The sessions live in SQLite under `./data`, so the login survives. Compose still sees
+the replacement as its `manager` service (labels are copied); a later `docker compose up -d --build`
+works as usual. The checkout is kept in `data/repos/_manager` and logs in `data/logs/_manager/`.
+Over `ssh://` the clone uses the mounted `SSH_DIR`, like installations do.
+
+Caveats: installation changes (build, deploy, start, stop...) answer `409` while an update is in
+progress, and the hand-over runs inside the build queue, so no installation build overlaps it. The
+updater removes the old manager image after a successful swap, so before running `docker compose
+up -d --build` on the host again, `git pull` its checkout first or compose will rebuild (and
+deploy) an older version than the one installed from the panel.
From 9a85c3bca00c209cf80359fd5e00799764494ee6 Mon Sep 17 00:00:00 2001
From: Dasemu
Date: Mon, 19 Oct 2026 09:14:35 +0200
Subject: [PATCH 2/3] feat: show the installed commit and how many newer
commits the remote has
The Manager card now shows the commit SHA the image was built from (GIT_SHA build arg, passed
by the panel's self-update and documented for compose) and counts the commits SELF_UPDATE_REF
has beyond it, with their subjects and a "Check for updates" button. The check is a cached,
background, history-only git fetch so GET /api/system never waits on it.
Co-Authored-By: Claude Sonnet 5.5
---
.env.example | 3 +
Dockerfile | 4 +
apps/server/src/api/system.ts | 7 +-
apps/server/src/build/git.ts | 9 +-
apps/server/src/system/commits.test.ts | 29 ++++++
apps/server/src/system/commits.ts | 23 +++++
apps/server/src/system/remoteCheck.test.ts | 75 +++++++++++++++
apps/server/src/system/remoteCheck.ts | 102 +++++++++++++++++++++
apps/server/src/system/selfUpdate.ts | 25 ++++-
apps/server/src/system/version.ts | 24 ++++-
apps/web/src/api/client.ts | 11 +++
apps/web/src/components/ManagerCard.tsx | 73 ++++++++++++++-
docker-compose.yml | 7 +-
docs/architecture.md | 2 +
docs/operations.md | 17 ++++
15 files changed, 400 insertions(+), 11 deletions(-)
create mode 100644 apps/server/src/system/commits.test.ts
create mode 100644 apps/server/src/system/commits.ts
create mode 100644 apps/server/src/system/remoteCheck.test.ts
create mode 100644 apps/server/src/system/remoteCheck.ts
diff --git a/.env.example b/.env.example
index d4c26a4..8f9fbb2 100644
--- a/.env.example
+++ b/.env.example
@@ -46,6 +46,9 @@ MANAGER_MEMORY_LIMIT_MB=512
# Needs SSH_DIR below if the URL is ssh://. See docs/operations.md.
SELF_UPDATE_REPO_URL=
SELF_UPDATE_REF=master
+# Optional, read by docker compose at build time only (not by the app): the commit being built,
+# e.g. GIT_SHA=$(git rev-parse HEAD) docker compose up -d --build
+# GIT_SHA=
# Absolute path to an SSH dir (key + known_hosts) with clone access to the repos you'll
# install, mounted read-only into the manager container so `git clone ssh://...` works for
diff --git a/Dockerfile b/Dockerfile
index fa1f840..ef74720 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -43,6 +43,10 @@ COPY VERSION VERSION
WORKDIR /repo/apps/server
ENV NODE_ENV=production
+# Commit this image was built from, shown in the panel. Passed with --build-arg GIT_SHA=
+# (compose: see docker-compose.yml; the panel's self-update does it itself).
+ARG GIT_SHA=unknown
+ENV GIT_SHA=$GIT_SHA
# Hard V8 heap ceiling, above MANAGER_MEMORY_LIMIT_MB (the soft limit the app enforces itself):
# a leak ends in a crash + restart by the compose restart policy instead of swapping the host.
ENV NODE_OPTIONS=--max-old-space-size=768
diff --git a/apps/server/src/api/system.ts b/apps/server/src/api/system.ts
index f4a791f..4b616a0 100644
--- a/apps/server/src/api/system.ts
+++ b/apps/server/src/api/system.ts
@@ -1,5 +1,5 @@
import { Router } from "express";
-import { getSystemInfo, startSelfUpdate, SelfUpdateError } from "../system/selfUpdate.js";
+import { getSystemInfo, refreshRemoteStatus, startSelfUpdate, SelfUpdateError } from "../system/selfUpdate.js";
export const systemRouter = Router();
@@ -7,6 +7,11 @@ systemRouter.get("/", async (_req, res) => {
res.json(await getSystemInfo());
});
+systemRouter.post("/check", async (_req, res) => {
+ await refreshRemoteStatus();
+ res.json(await getSystemInfo());
+});
+
systemRouter.post("/update", async (_req, res) => {
try {
await startSelfUpdate();
diff --git a/apps/server/src/build/git.ts b/apps/server/src/build/git.ts
index da3e647..5616df8 100644
--- a/apps/server/src/build/git.ts
+++ b/apps/server/src/build/git.ts
@@ -7,7 +7,7 @@ import { killGroupAfter } from "../util/processTimeout.js";
// A clone that never finishes (e.g. ssh waiting on a prompt) would otherwise hang forever.
const GIT_TIMEOUT_MS = 5 * 60 * 1000;
-function run(cmd: string, args: string[], cwd?: string): Promise<{ code: number; output: string }> {
+export function run(cmd: string, args: string[], cwd?: string): Promise<{ code: number; output: string }> {
return new Promise((resolve, reject) => {
const child = spawn(cmd, args, { cwd, detached: true });
killGroupAfter(child, GIT_TIMEOUT_MS);
@@ -39,6 +39,13 @@ export async function cloneOrUpdateRepo(slug: string, repoUrl: string, gitRef?:
return dir;
}
+/** Full SHA of the checkout's HEAD, or undefined if it can't be read. */
+export async function readHeadSha(dir: string): Promise {
+ const { code, output } = await run("git", ["rev-parse", "HEAD"], dir).catch(() => ({ code: 1, output: "" }));
+ const sha = output.trim();
+ return code === 0 && /^[0-9a-f]{40}$/.test(sha) ? sha : undefined;
+}
+
export function readEnvExampleKeys(dir: string): string[] {
const file = path.join(dir, ".env.example");
if (!fs.existsSync(file)) return [];
diff --git a/apps/server/src/system/commits.test.ts b/apps/server/src/system/commits.test.ts
new file mode 100644
index 0000000..9b2e949
--- /dev/null
+++ b/apps/server/src/system/commits.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from "vitest";
+import { normalizeSha, parseCommitLog } from "./commits.js";
+
+describe("normalizeSha", () => {
+ it("accepts hex shas and lowercases them", () => {
+ expect(normalizeSha("ABCDEF1234567")).toBe("abcdef1234567");
+ expect(normalizeSha(" 5fb1d6b\n")).toBe("5fb1d6b");
+ });
+
+ it("rejects unknown, empty, too short and non-hex values", () => {
+ for (const v of [undefined, "", "unknown", "abc12", "zzzzzzzz", "abc123; rm -rf /"]) {
+ expect(normalizeSha(v)).toBeUndefined();
+ }
+ });
+});
+
+describe("parseCommitLog", () => {
+ it("parses sha and subject, keeping tabs inside the subject", () => {
+ const out = "a1b2c3d\tfeat: add thing\ne4f5a6b\tfix: a\tb\n";
+ expect(parseCommitLog(out)).toEqual([
+ { sha: "a1b2c3d", subject: "feat: add thing" },
+ { sha: "e4f5a6b", subject: "fix: a\tb" },
+ ]);
+ });
+
+ it("returns nothing for empty output", () => {
+ expect(parseCommitLog("")).toEqual([]);
+ });
+});
diff --git a/apps/server/src/system/commits.ts b/apps/server/src/system/commits.ts
new file mode 100644
index 0000000..024ab1d
--- /dev/null
+++ b/apps/server/src/system/commits.ts
@@ -0,0 +1,23 @@
+export interface CommitSummary {
+ sha: string;
+ subject: string;
+}
+
+const SHA_RE = /^[0-9a-f]{7,40}$/;
+
+/** Accepts a baked-in/inspected SHA only if it is plain hex; "unknown" and junk become undefined. */
+export function normalizeSha(raw: string | undefined): string | undefined {
+ const sha = raw?.trim().toLowerCase();
+ return sha && SHA_RE.test(sha) ? sha : undefined;
+}
+
+/** Parses `git log --format=%h%x09%s` output. */
+export function parseCommitLog(output: string): CommitSummary[] {
+ return output
+ .split("\n")
+ .filter((line) => line.includes("\t"))
+ .map((line) => {
+ const [sha, ...rest] = line.split("\t");
+ return { sha: sha!.trim(), subject: rest.join("\t").trim() };
+ });
+}
diff --git a/apps/server/src/system/remoteCheck.test.ts b/apps/server/src/system/remoteCheck.test.ts
new file mode 100644
index 0000000..fbd7815
--- /dev/null
+++ b/apps/server/src/system/remoteCheck.test.ts
@@ -0,0 +1,75 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { execFileSync } from "node:child_process";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+
+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "remote-check-"));
+const origin = path.join(tmp, "origin");
+const shas: string[] = [];
+
+function git(cwd: string, ...args: string[]) {
+ return execFileSync("git", args, {
+ cwd,
+ encoding: "utf8",
+ env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" },
+ }).trim();
+}
+
+async function load() {
+ vi.resetModules();
+ vi.stubEnv("DATA_DIR", path.join(tmp, "data"));
+ vi.stubEnv("SELF_UPDATE_REPO_URL", origin);
+ vi.stubEnv("SELF_UPDATE_REF", "main");
+ return import("./remoteCheck.js");
+}
+
+beforeAll(() => {
+ fs.mkdirSync(origin);
+ git(origin, "init", "-q", "-b", "main");
+ for (const n of [1, 2, 3]) {
+ fs.writeFileSync(path.join(origin, "f.txt"), String(n));
+ git(origin, "add", ".");
+ git(origin, "commit", "-q", "-m", `commit ${n}`);
+ shas.push(git(origin, "rev-parse", "HEAD"));
+ }
+});
+
+afterAll(() => {
+ vi.unstubAllEnvs();
+ fs.rmSync(tmp, { recursive: true, force: true });
+});
+
+describe("checkRemote", () => {
+ it("counts the commits the installed sha is missing", async () => {
+ const { checkRemote } = await load();
+ const status = await checkRemote(shas[0], true);
+ expect(status.error).toBeNull();
+ expect(status.remoteSha).toBe(shas[2]);
+ expect(status.behind).toBe(2);
+ expect(status.commits.map((c) => c.subject)).toEqual(["commit 3", "commit 2"]);
+ });
+
+ it("reports 0 when installed is the remote head", async () => {
+ const { checkRemote } = await load();
+ expect((await checkRemote(shas[2], true)).behind).toBe(0);
+ });
+
+ it("reports the remote head only when the installed sha is unknown to it", async () => {
+ const { checkRemote } = await load();
+ const status = await checkRemote("deadbeefdeadbeef", true);
+ expect(status.behind).toBeNull();
+ expect(status.remoteSha).toBe(shas[2]);
+ expect(status.error).toBeNull();
+ });
+
+ it("reports an error instead of throwing when the remote is unreachable", async () => {
+ await load();
+ vi.stubEnv("SELF_UPDATE_REPO_URL", path.join(tmp, "does-not-exist"));
+ vi.resetModules();
+ const mod = await import("./remoteCheck.js");
+ const status = await mod.checkRemote(shas[0], true);
+ expect(status.error).toMatch(/git fetch failed/);
+ expect(status.behind).toBeNull();
+ });
+});
diff --git a/apps/server/src/system/remoteCheck.ts b/apps/server/src/system/remoteCheck.ts
new file mode 100644
index 0000000..5562e0d
--- /dev/null
+++ b/apps/server/src/system/remoteCheck.ts
@@ -0,0 +1,102 @@
+import fs from "node:fs";
+import path from "node:path";
+import { config } from "../config/env.js";
+import { run } from "../build/git.js";
+import { type CommitSummary, parseCommitLog } from "./commits.js";
+
+// A bare repo that only ever holds commit history (no blobs) of the update source, so counting
+// "how far behind" doesn't need a full clone. Name can't collide with an installation slug.
+const CHECK_DIR = "_manager-check";
+const OK_TTL_MS = 10 * 60 * 1000;
+const ERROR_TTL_MS = 60 * 1000;
+const MAX_LISTED = 20;
+
+export interface RemoteStatus {
+ checkedAt: string;
+ remoteSha: string | null;
+ /** Commits on the remote that the installed build doesn't have; null when it can't be told. */
+ behind: number | null;
+ commits: CommitSummary[];
+ error: string | null;
+}
+
+let cached: { status: RemoteStatus; expires: number; forSha: string | undefined } | null = null;
+let inFlight: Promise | null = null;
+
+async function git(cwd: string, args: string[]) {
+ return run("git", args, cwd).catch((err: Error) => ({ code: 1, output: err.message }));
+}
+
+async function compute(installedSha: string | undefined): Promise {
+ const base: RemoteStatus = { checkedAt: new Date().toISOString(), remoteSha: null, behind: null, commits: [], error: null };
+ const url = config.selfUpdateRepoUrl;
+ if (!url) return { ...base, error: "SELF_UPDATE_REPO_URL is not set" };
+
+ const dir = path.join(config.reposDir, CHECK_DIR);
+ fs.mkdirSync(dir, { recursive: true });
+ if (!fs.existsSync(path.join(dir, "HEAD"))) {
+ const init = await git(dir, ["init", "--bare", "--quiet"]);
+ if (init.code !== 0) return { ...base, error: `git init failed: ${init.output.trim()}` };
+ }
+
+ // Blobless fetch where the server supports it; plain fetch otherwise.
+ const fetchArgs = ["fetch", "--quiet", "--no-tags", url, config.selfUpdateRef];
+ let fetched = await git(dir, [fetchArgs[0]!, "--filter=blob:none", ...fetchArgs.slice(1)]);
+ if (fetched.code !== 0) fetched = await git(dir, fetchArgs);
+ if (fetched.code !== 0) return { ...base, error: `git fetch failed: ${fetched.output.trim().slice(-300)}` };
+
+ const head = await git(dir, ["rev-parse", "FETCH_HEAD"]);
+ const remoteSha = head.output.trim();
+ if (head.code !== 0 || !remoteSha) return { ...base, error: "could not read the fetched head" };
+ if (!installedSha) return { ...base, remoteSha };
+ if (remoteSha.startsWith(installedSha)) return { ...base, remoteSha, behind: 0 };
+
+ // The installed commit has to be an ancestor of the remote head to count what is new; if it
+ // isn't (force-push, other branch, local build) we can only report the remote head.
+ const isAncestor = await git(dir, ["merge-base", "--is-ancestor", installedSha, remoteSha]);
+ if (isAncestor.code !== 0) return { ...base, remoteSha };
+
+ const range = `${installedSha}..${remoteSha}`;
+ const count = await git(dir, ["rev-list", "--count", range]);
+ const log = await git(dir, ["log", `-n${MAX_LISTED}`, "--format=%h%x09%s", range]);
+ const behind = Number.parseInt(count.output.trim(), 10);
+ return {
+ ...base,
+ remoteSha,
+ behind: Number.isNaN(behind) ? null : behind,
+ commits: parseCommitLog(log.output),
+ };
+}
+
+/** Cached for a few minutes; concurrent callers share one fetch. `force` skips the cache. */
+export function checkRemote(installedSha: string | undefined, force = false): Promise {
+ if (!force && cached && cached.expires > Date.now() && cached.forSha === installedSha) {
+ return Promise.resolve(cached.status);
+ }
+ if (inFlight) return inFlight;
+ inFlight = compute(installedSha)
+ .catch((err: Error): RemoteStatus => ({
+ checkedAt: new Date().toISOString(),
+ remoteSha: null,
+ behind: null,
+ commits: [],
+ error: err.message,
+ }))
+ .then((status) => {
+ cached = { status, expires: Date.now() + (status.error ? ERROR_TTL_MS : OK_TTL_MS), forSha: installedSha };
+ return status;
+ })
+ .finally(() => {
+ inFlight = null;
+ });
+ return inFlight;
+}
+
+/** Last known result without triggering a fetch (null if none yet). */
+export function cachedRemoteStatus(): RemoteStatus | null {
+ return cached?.status ?? null;
+}
+
+export function isRemoteCheckStale(installedSha: string | undefined): boolean {
+ return !cached || cached.expires <= Date.now() || cached.forSha !== installedSha;
+}
diff --git a/apps/server/src/system/selfUpdate.ts b/apps/server/src/system/selfUpdate.ts
index dfbaa73..98b0382 100644
--- a/apps/server/src/system/selfUpdate.ts
+++ b/apps/server/src/system/selfUpdate.ts
@@ -5,12 +5,13 @@ import { spawn } from "node:child_process";
import Docker from "dockerode";
import { config } from "../config/env.js";
import { listInstallations } from "../db/installations.js";
-import { cloneOrUpdateRepo, repoDir } from "../build/git.js";
+import { cloneOrUpdateRepo, readHeadSha, repoDir } from "../build/git.js";
import { enqueueBuild } from "../service/buildQueue.js";
import { killGroupAfter } from "../util/processTimeout.js";
import { withTimeout } from "../util/withTimeout.js";
import { demuxLogs } from "./dockerLogs.js";
-import { readVersion } from "./version.js";
+import { cachedRemoteStatus, checkRemote, isRemoteCheckStale } from "./remoteCheck.js";
+import { readInstalledSha, readVersion } from "./version.js";
const docker = new Docker({ socketPath: config.dockerSocketPath });
@@ -46,8 +47,15 @@ export async function getSystemInfo() {
// collected later; polling this endpoint is what picks it up.
if (!lastResult && state.phase === "idle") await collectSelfUpdateResult();
const self = await inspectSelf();
+ const installedSha = readInstalledSha();
+ // Refresh in the background so this endpoint never waits on a git fetch.
+ if (config.selfUpdateRepoUrl && state.phase === "idle" && isRemoteCheckStale(installedSha)) {
+ void checkRemote(installedSha);
+ }
return {
version: readVersion(),
+ sha: installedSha ?? null,
+ remote: cachedRemoteStatus(),
uptimeSec: Math.round(process.uptime()),
canSelfUpdate: Boolean(config.selfUpdateRepoUrl && self),
unavailableReason: !config.selfUpdateRepoUrl
@@ -63,10 +71,10 @@ export async function getSystemInfo() {
};
}
-function runDockerBuild(contextDir: string, image: string, logPath: string): Promise {
+function runDockerBuild(contextDir: string, image: string, logPath: string, sha: string | undefined): Promise {
return new Promise((resolve) => {
const logStream = fs.createWriteStream(logPath, { flags: "a" });
- const child = spawn("docker", ["build", "-t", image, contextDir], { detached: true });
+ const child = spawn("docker", ["build", "-t", image, ...(sha ? ["--build-arg", `GIT_SHA=${sha}`] : []), contextDir], { detached: true });
killGroupAfter(child, BUILD_TIMEOUT_MS);
child.stdout.pipe(logStream, { end: false });
child.stderr.pipe(logStream, { end: false });
@@ -101,7 +109,9 @@ async function runUpdate(self: Docker.ContainerInspectInfo): Promise {
state.phase = "building";
note(`building ${image}`);
- if (!(await runDockerBuild(repoDir(CHECKOUT_SLUG), image, state.logPath!))) {
+ const sha = await readHeadSha(repoDir(CHECKOUT_SLUG));
+ note(`building commit ${sha ?? "unknown"}`);
+ if (!(await runDockerBuild(repoDir(CHECKOUT_SLUG), image, state.logPath!, sha))) {
throw new Error(`image build failed, see ${state.logPath}`);
}
@@ -150,6 +160,11 @@ export function isSelfUpdateInProgress(): boolean {
return state.phase !== "idle";
}
+/** Forces a fresh look at the remote (the panel's "Check now"). */
+export function refreshRemoteStatus() {
+ return checkRemote(readInstalledSha(), true);
+}
+
export class SelfUpdateError extends Error {
constructor(
message: string,
diff --git a/apps/server/src/system/version.ts b/apps/server/src/system/version.ts
index 58ff796..c1e2024 100644
--- a/apps/server/src/system/version.ts
+++ b/apps/server/src/system/version.ts
@@ -1,9 +1,12 @@
import fs from "node:fs";
import path from "node:path";
+import { execFileSync } from "node:child_process";
+import { normalizeSha } from "./commits.js";
// VERSION sits at the repo root, four levels above this file in both the image and a checkout:
// /apps/server/{src,dist}/system/version.*
-const versionFile = path.resolve(import.meta.dirname, "../../../../VERSION");
+const repoRoot = path.resolve(import.meta.dirname, "../../../..");
+const versionFile = path.join(repoRoot, "VERSION");
export function readVersion(): string {
try {
@@ -12,3 +15,22 @@ export function readVersion(): string {
return "unknown";
}
}
+
+let sha: string | undefined | null = null;
+
+/**
+ * Commit this build was made from. The image gets it as the GIT_SHA build arg (see the
+ * Dockerfile); in a plain checkout (local dev) it is read from git instead.
+ */
+export function readInstalledSha(): string | undefined {
+ if (sha !== null) return sha;
+ sha = normalizeSha(process.env.GIT_SHA);
+ if (!sha) {
+ try {
+ sha = normalizeSha(execFileSync("git", ["rev-parse", "HEAD"], { cwd: repoRoot, timeout: 3000, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }));
+ } catch {
+ sha = undefined;
+ }
+ }
+ return sha;
+}
diff --git a/apps/web/src/api/client.ts b/apps/web/src/api/client.ts
index 5fe54c4..bddb90a 100644
--- a/apps/web/src/api/client.ts
+++ b/apps/web/src/api/client.ts
@@ -19,8 +19,18 @@ export interface Installation {
updatedAt: string;
}
+export interface RemoteStatus {
+ checkedAt: string;
+ remoteSha: string | null;
+ behind: number | null;
+ commits: { sha: string; subject: string }[];
+ error: string | null;
+}
+
export interface SystemInfo {
version: string;
+ sha: string | null;
+ remote: RemoteStatus | null;
uptimeSec: number;
canSelfUpdate: boolean;
unavailableReason: string | null;
@@ -74,5 +84,6 @@ export const api = {
logs: (id: string) => request<{ log: string }>(`/api/installations/${id}/logs`),
systemInfo: () => request("/api/system"),
+ checkManager: () => request("/api/system/check", { method: "POST" }),
updateManager: () => request<{ ok: true }>("/api/system/update", { method: "POST" }),
};
diff --git a/apps/web/src/components/ManagerCard.tsx b/apps/web/src/components/ManagerCard.tsx
index 10280fe..4d9b3dc 100644
--- a/apps/web/src/components/ManagerCard.tsx
+++ b/apps/web/src/components/ManagerCard.tsx
@@ -18,6 +18,7 @@ export function ManagerCard() {
const [unreachable, setUnreachable] = useState(false);
const [startedAt, setStartedAt] = useState(null);
const [gaveUp, setGaveUp] = useState(false);
+ const [checking, setChecking] = useState(false);
async function refresh() {
try {
@@ -57,6 +58,32 @@ export function ManagerCard() {
}
}, [requested, info, unreachable, startedAt]);
+ const repoConfigured = info !== null && info.unavailableReason !== "SELF_UPDATE_REPO_URL is not set";
+ const waitingForRemote = repoConfigured && info !== null && info.remote === null && info.phase === "idle";
+
+ // The first remote check runs in the background on the server; poll briefly until it lands.
+ useEffect(() => {
+ if (!waitingForRemote) return;
+ let tries = 0;
+ const timer = setInterval(() => {
+ if (++tries > 10) clearInterval(timer);
+ else refresh();
+ }, 3000);
+ return () => clearInterval(timer);
+ }, [waitingForRemote]);
+
+ async function checkNow() {
+ setChecking(true);
+ setError(null);
+ try {
+ setInfo(await api.checkManager());
+ } catch (err) {
+ setError((err as Error).message);
+ } finally {
+ setChecking(false);
+ }
+ }
+
async function update() {
if (!info) return;
const msg =
@@ -84,7 +111,7 @@ export function ManagerCard() {
Manager
- {info ? `Version ${info.version} · ${info.ref}` : "Restarting…"}
+ {info ? `Version ${info.version} · ${info.sha ? info.sha.slice(0, 7) : "unknown commit"}` : "Restarting…"}
@@ -101,11 +128,12 @@ export function ManagerCard() {
Last update {info.lastUpdate.ok ? "succeeded" : "did not complete (rolled back or failed; see the log)"} ({new Date(info.lastUpdate.finishedAt).toLocaleString()}).
)}
+ {!updating && info && repoConfigured && }
{info && !info.canSelfUpdate && info.unavailableReason && (
Self-update unavailable: {info.unavailableReason}.
)}
-
+
{updating ? "Updating…" : "Update manager"}
+ {repoConfigured && (
+
+ {checking ? "Checking…" : "Check for updates"}
+
+ )}
{log &&
{log} }
);
}
+
+function RemoteLine({ info, checking }: { info: SystemInfo; checking: boolean }) {
+ const remote = info.remote;
+ if (!remote) return {checking ? "Checking the remote…" : ""}
;
+ if (remote.error) return Could not check the remote: {remote.error}
;
+
+ const head = remote.remoteSha?.slice(0, 7);
+ const when = new Date(remote.checkedAt).toLocaleTimeString();
+ if (remote.behind === 0) {
+ return Up to date with {info.ref} ({head}) · checked {when}
;
+ }
+ if (remote.behind === null) {
+ return (
+
+ {info.sha
+ ? `The installed commit is not in the history of ${info.ref}; its head is ${head}.`
+ : `The installed commit is unknown; ${info.ref} is at ${head}.`}
+
+ );
+ }
+ return (
+
+
+ {remote.behind} newer commit{remote.behind === 1 ? "" : "s"} on {info.ref} (head {head}) · checked {when}
+
+
+ {remote.commits.map((c) => (
+
+ {c.sha} {c.subject}
+
+ ))}
+ {remote.behind > remote.commits.length && …and {remote.behind - remote.commits.length} more }
+
+
+ );
+}
diff --git a/docker-compose.yml b/docker-compose.yml
index fa325e6..f4b98b9 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -1,6 +1,11 @@
services:
manager:
- build: .
+ build:
+ context: .
+ args:
+ # export GIT_SHA=$(git rev-parse HEAD) before `docker compose up -d --build` so the panel
+ # can show which commit is installed and how far behind the remote it is.
+ GIT_SHA: ${GIT_SHA:-unknown}
restart: unless-stopped
ports:
- "127.0.0.1:3000:3000"
diff --git a/docs/architecture.md b/docs/architecture.md
index 0f514e5..ce7e6f7 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -61,3 +61,5 @@ don't need to reach a sibling container (e.g. `/health`, `/api/auth`). See the R
`system/selfUpdateHelper.ts` (the updater container's entry point: swap, health check, rollback)
implement the panel's *Update manager* button, exposed as `GET /api/system` and
`POST /api/system/update` behind `requireAuth`. See `docs/operations.md`.
+`system/remoteCheck.ts` compares the installed commit (`GIT_SHA`) with the remote head to show how many
+commits behind the manager is.
diff --git a/docs/operations.md b/docs/operations.md
index 77e5232..7554b81 100644
--- a/docs/operations.md
+++ b/docs/operations.md
@@ -65,3 +65,20 @@ progress, and the hand-over runs inside the build queue, so no installation buil
updater removes the old manager image after a successful swap, so before running `docker compose
up -d --build` on the host again, `git pull` its checkout first or compose will rebuild (and
deploy) an older version than the one installed from the panel.
+
+## Installed version and newer commits
+
+The Manager card shows the version (`VERSION`) and the **commit SHA** the running image was built
+from, and how many commits `SELF_UPDATE_REF` has on `SELF_UPDATE_REPO_URL` that it doesn't (with
+the subjects of the latest 20). `Check for updates` forces a refresh; otherwise the result is
+cached for 10 minutes (1 minute after a failure) and refreshed in the background by
+`GET /api/system`, so the endpoint never waits on git.
+
+- **Where the SHA comes from:** the `GIT_SHA` build arg (baked as an image `ENV`). The panel's
+ self-update passes it itself. With compose, build with
+ `GIT_SHA=$(git rev-parse HEAD) docker compose up -d --build`; without it the card says
+ "unknown commit" and can only show the remote head. In local dev it is read with `git rev-parse`.
+- **How it counts:** a history-only (blobless where the server allows it) fetch into the bare repo
+ `data/repos/_manager-check`, then `git rev-list --count ..`. If the
+ installed commit isn't an ancestor of the remote head (force-push, other branch) only the remote
+ head is shown.
From 69e39541a4701776d1fa2ee791f00cd60bc24f48 Mon Sep 17 00:00:00 2001
From: Dasemu
Date: Mon, 19 Oct 2026 09:18:03 +0200
Subject: [PATCH 3/3] fix: harden the remote commit check after review
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Bound the check to 60 s and only retry unfiltered on filter errors, wait for an in-flight fetch
before a forced refresh, resolve annotated tags to their commit, guard git args with `--`, treat
rev-list failures as errors, and stop the card's "Checking…" state after the polling gives up.
Co-Authored-By: Claude Sonnet 5.5
---
apps/server/src/build/git.ts | 9 +++-
apps/server/src/system/remoteCheck.test.ts | 21 ++++++++-
apps/server/src/system/remoteCheck.ts | 52 ++++++++++++++--------
apps/web/src/components/ManagerCard.tsx | 14 ++++--
4 files changed, 70 insertions(+), 26 deletions(-)
diff --git a/apps/server/src/build/git.ts b/apps/server/src/build/git.ts
index 5616df8..b15e844 100644
--- a/apps/server/src/build/git.ts
+++ b/apps/server/src/build/git.ts
@@ -7,10 +7,15 @@ import { killGroupAfter } from "../util/processTimeout.js";
// A clone that never finishes (e.g. ssh waiting on a prompt) would otherwise hang forever.
const GIT_TIMEOUT_MS = 5 * 60 * 1000;
-export function run(cmd: string, args: string[], cwd?: string): Promise<{ code: number; output: string }> {
+export function run(
+ cmd: string,
+ args: string[],
+ cwd?: string,
+ timeoutMs = GIT_TIMEOUT_MS,
+): Promise<{ code: number; output: string }> {
return new Promise((resolve, reject) => {
const child = spawn(cmd, args, { cwd, detached: true });
- killGroupAfter(child, GIT_TIMEOUT_MS);
+ killGroupAfter(child, timeoutMs);
let output = "";
child.stdout.on("data", (d) => (output += d.toString()));
child.stderr.on("data", (d) => (output += d.toString()));
diff --git a/apps/server/src/system/remoteCheck.test.ts b/apps/server/src/system/remoteCheck.test.ts
index fbd7815..77823b6 100644
--- a/apps/server/src/system/remoteCheck.test.ts
+++ b/apps/server/src/system/remoteCheck.test.ts
@@ -16,11 +16,11 @@ function git(cwd: string, ...args: string[]) {
}).trim();
}
-async function load() {
+async function load(ref = "main") {
vi.resetModules();
vi.stubEnv("DATA_DIR", path.join(tmp, "data"));
vi.stubEnv("SELF_UPDATE_REPO_URL", origin);
- vi.stubEnv("SELF_UPDATE_REF", "main");
+ vi.stubEnv("SELF_UPDATE_REF", ref);
return import("./remoteCheck.js");
}
@@ -41,6 +41,23 @@ afterAll(() => {
});
describe("checkRemote", () => {
+ it("resolves an annotated tag to its commit", async () => {
+ git(origin, "tag", "-a", "v1", "-m", "release", shas[2]!);
+ const { checkRemote } = await load("v1");
+ const status = await checkRemote(shas[0], true);
+ expect(status.remoteSha).toBe(shas[2]);
+ expect(status.behind).toBe(2);
+ });
+
+ it("runs a fresh check after a forced refresh requested mid-flight", async () => {
+ const { checkRemote } = await load();
+ const first = checkRemote(shas[0]);
+ const forced = checkRemote(shas[0], true);
+ const [a, b] = await Promise.all([first, forced]);
+ expect(b.checkedAt >= a.checkedAt).toBe(true);
+ expect(b).not.toBe(a);
+ });
+
it("counts the commits the installed sha is missing", async () => {
const { checkRemote } = await load();
const status = await checkRemote(shas[0], true);
diff --git a/apps/server/src/system/remoteCheck.ts b/apps/server/src/system/remoteCheck.ts
index 5562e0d..3cce58d 100644
--- a/apps/server/src/system/remoteCheck.ts
+++ b/apps/server/src/system/remoteCheck.ts
@@ -10,6 +10,8 @@ const CHECK_DIR = "_manager-check";
const OK_TTL_MS = 10 * 60 * 1000;
const ERROR_TTL_MS = 60 * 1000;
const MAX_LISTED = 20;
+// The panel waits on this, so it gets far less than the 5 min installs allow for a clone.
+const GIT_CHECK_TIMEOUT_MS = 60 * 1000;
export interface RemoteStatus {
checkedAt: string;
@@ -22,9 +24,10 @@ export interface RemoteStatus {
let cached: { status: RemoteStatus; expires: number; forSha: string | undefined } | null = null;
let inFlight: Promise | null = null;
+let queuedForce: Promise | null = null;
async function git(cwd: string, args: string[]) {
- return run("git", args, cwd).catch((err: Error) => ({ code: 1, output: err.message }));
+ return run("git", args, cwd, GIT_CHECK_TIMEOUT_MS).catch((err: Error) => ({ code: 1, output: err.message }));
}
async function compute(installedSha: string | undefined): Promise {
@@ -40,12 +43,14 @@ async function compute(installedSha: string | undefined): Promise
}
// Blobless fetch where the server supports it; plain fetch otherwise.
- const fetchArgs = ["fetch", "--quiet", "--no-tags", url, config.selfUpdateRef];
- let fetched = await git(dir, [fetchArgs[0]!, "--filter=blob:none", ...fetchArgs.slice(1)]);
- if (fetched.code !== 0) fetched = await git(dir, fetchArgs);
+ const fetchTail = ["--quiet", "--no-tags", "--", url, config.selfUpdateRef];
+ let fetched = await git(dir, ["fetch", "--filter=blob:none", ...fetchTail]);
+ // Only a server that doesn't do partial clones warrants the retry; an unreachable one would
+ // just make the panel wait twice as long.
+ if (fetched.code !== 0 && /filter/i.test(fetched.output)) fetched = await git(dir, ["fetch", ...fetchTail]);
if (fetched.code !== 0) return { ...base, error: `git fetch failed: ${fetched.output.trim().slice(-300)}` };
- const head = await git(dir, ["rev-parse", "FETCH_HEAD"]);
+ const head = await git(dir, ["rev-parse", "--verify", "FETCH_HEAD^{commit}"]);
const remoteSha = head.output.trim();
if (head.code !== 0 || !remoteSha) return { ...base, error: "could not read the fetched head" };
if (!installedSha) return { ...base, remoteSha };
@@ -58,22 +63,15 @@ async function compute(installedSha: string | undefined): Promise
const range = `${installedSha}..${remoteSha}`;
const count = await git(dir, ["rev-list", "--count", range]);
- const log = await git(dir, ["log", `-n${MAX_LISTED}`, "--format=%h%x09%s", range]);
const behind = Number.parseInt(count.output.trim(), 10);
- return {
- ...base,
- remoteSha,
- behind: Number.isNaN(behind) ? null : behind,
- commits: parseCommitLog(log.output),
- };
+ if (count.code !== 0 || Number.isNaN(behind)) {
+ return { ...base, remoteSha, error: `git rev-list failed: ${count.output.trim().slice(-200)}` };
+ }
+ const log = await git(dir, ["log", `-n${MAX_LISTED}`, "--format=%h%x09%s", range]);
+ return { ...base, remoteSha, behind, commits: log.code === 0 ? parseCommitLog(log.output) : [] };
}
-/** Cached for a few minutes; concurrent callers share one fetch. `force` skips the cache. */
-export function checkRemote(installedSha: string | undefined, force = false): Promise {
- if (!force && cached && cached.expires > Date.now() && cached.forSha === installedSha) {
- return Promise.resolve(cached.status);
- }
- if (inFlight) return inFlight;
+function start(installedSha: string | undefined): Promise {
inFlight = compute(installedSha)
.catch((err: Error): RemoteStatus => ({
checkedAt: new Date().toISOString(),
@@ -92,6 +90,24 @@ export function checkRemote(installedSha: string | undefined, force = false): Pr
return inFlight;
}
+/**
+ * Cached for a few minutes; concurrent callers share one fetch. `force` skips the cache, and if a
+ * fetch is already running (it may have read the refs before a push) waits for it and runs a
+ * fresh one after it — at most one is ever queued.
+ */
+export function checkRemote(installedSha: string | undefined, force = false): Promise {
+ if (!force && cached && cached.expires > Date.now() && cached.forSha === installedSha) {
+ return Promise.resolve(cached.status);
+ }
+ if (!inFlight) return start(installedSha);
+ if (!force) return inFlight;
+ queuedForce ??= inFlight.then(() => {
+ queuedForce = null;
+ return start(installedSha);
+ });
+ return queuedForce;
+}
+
/** Last known result without triggering a fetch (null if none yet). */
export function cachedRemoteStatus(): RemoteStatus | null {
return cached?.status ?? null;
diff --git a/apps/web/src/components/ManagerCard.tsx b/apps/web/src/components/ManagerCard.tsx
index 4d9b3dc..0b88ec0 100644
--- a/apps/web/src/components/ManagerCard.tsx
+++ b/apps/web/src/components/ManagerCard.tsx
@@ -19,6 +19,7 @@ export function ManagerCard() {
const [startedAt, setStartedAt] = useState(null);
const [gaveUp, setGaveUp] = useState(false);
const [checking, setChecking] = useState(false);
+ const [remoteGaveUp, setRemoteGaveUp] = useState(false);
async function refresh() {
try {
@@ -59,21 +60,24 @@ export function ManagerCard() {
}, [requested, info, unreachable, startedAt]);
const repoConfigured = info !== null && info.unavailableReason !== "SELF_UPDATE_REPO_URL is not set";
- const waitingForRemote = repoConfigured && info !== null && info.remote === null && info.phase === "idle";
+ const waitingForRemote = repoConfigured && info !== null && info.remote === null && info.phase === "idle" && !remoteGaveUp;
// The first remote check runs in the background on the server; poll briefly until it lands.
useEffect(() => {
if (!waitingForRemote) return;
let tries = 0;
const timer = setInterval(() => {
- if (++tries > 10) clearInterval(timer);
- else refresh();
+ if (++tries > 10) {
+ clearInterval(timer);
+ setRemoteGaveUp(true);
+ } else refresh();
}, 3000);
return () => clearInterval(timer);
}, [waitingForRemote]);
async function checkNow() {
setChecking(true);
+ setRemoteGaveUp(false);
setError(null);
try {
setInfo(await api.checkManager());
@@ -157,7 +161,9 @@ export function ManagerCard() {
function RemoteLine({ info, checking }: { info: SystemInfo; checking: boolean }) {
const remote = info.remote;
- if (!remote) return {checking ? "Checking the remote…" : ""}
;
+ if (!remote) {
+ return {checking ? "Checking the remote…" : "Not checked yet; use Check for updates."}
;
+ }
if (remote.error) return Could not check the remote: {remote.error}
;
const head = remote.remoteSha?.slice(0, 7);