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 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-10-19 09:14:35 +02:00
1 parent 4b3c8f213a
commit 9a85c3bca0
15 files changed
+400 -11

No files matched your search

+3
View File
@@ -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
+4
View File
@@ -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=<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
+6 -1
View File
@@ -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();
+8 -1
View File
@@ -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<string | undefined> {
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 [];
+29
View File
@@ -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([]);
});
});
+23
View File
@@ -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() };
});
}
@@ -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();
});
});
+102
View File
@@ -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<RemoteStatus> | 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<RemoteStatus> {
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<RemoteStatus> {
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;
}
+20 -5
View File
@@ -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<boolean> {
function runDockerBuild(contextDir: string, image: string, logPath: string, sha: string | undefined): Promise<boolean> {
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<void> {
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,
+23 -1
View File
@@ -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:
// <root>/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;
}
+11
View File
@@ -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<SystemInfo>("/api/system"),
checkManager: () => request<SystemInfo>("/api/system/check", { method: "POST" }),
updateManager: () => request<{ ok: true }>("/api/system/update", { method: "POST" }),
};
+71 -2
View File
@@ -18,6 +18,7 @@ export function ManagerCard() {
const [unreachable, setUnreachable] = useState(false);
const [startedAt, setStartedAt] = useState<number | null>(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() {
<div className="card-header">
<span className="card-title">Manager</span>
<span className="card-hint">
{info ? `Version ${info.version} · ${info.ref}` : "Restarting…"}
{info ? `Version ${info.version} · ${info.sha ? info.sha.slice(0, 7) : "unknown commit"}` : "Restarting…"}
</span>
</div>
@@ -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()}).
</p>
)}
{!updating && info && repoConfigured && <RemoteLine info={info} checking={checking || waitingForRemote} />}
{info && !info.canSelfUpdate && info.unavailableReason && (
<p className="status-detail">Self-update unavailable: {info.unavailableReason}.</p>
)}
<div>
<div style={{ display: "flex", gap: 8 }}>
<button
type="button"
className="btn"
@@ -115,9 +143,50 @@ export function ManagerCard() {
>
{updating ? "Updating…" : "Update manager"}
</button>
{repoConfigured && (
<button type="button" className="btn btn-ghost" disabled={checking || updating} onClick={checkNow}>
{checking ? "Checking…" : "Check for updates"}
</button>
)}
</div>
{log && <pre className="log-pane">{log}</pre>}
</div>
);
}
function RemoteLine({ info, checking }: { info: SystemInfo; checking: boolean }) {
const remote = info.remote;
if (!remote) return <p className="status-detail">{checking ? "Checking the remote…" : ""}</p>;
if (remote.error) return <p className="status-detail">Could not check the remote: {remote.error}</p>;
const head = remote.remoteSha?.slice(0, 7);
const when = new Date(remote.checkedAt).toLocaleTimeString();
if (remote.behind === 0) {
return <p className="status-detail">Up to date with {info.ref} ({head}) · checked {when}</p>;
}
if (remote.behind === null) {
return (
<p className="status-detail">
{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}.`}
</p>
);
}
return (
<div>
<p className="status-detail">
{remote.behind} newer commit{remote.behind === 1 ? "" : "s"} on {info.ref} (head {head}) · checked {when}
</p>
<ul className="status-detail" style={{ margin: "4px 0 8px 18px" }}>
{remote.commits.map((c) => (
<li key={c.sha}>
<code>{c.sha}</code> {c.subject}
</li>
))}
{remote.behind > remote.commits.length && <li>…and {remote.behind - remote.commits.length} more</li>}
</ul>
</div>
);
}
+6 -1
View File
@@ -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"
+2
View File
@@ -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.
+17
View File
@@ -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 <installed>..<remote head>`. If the
installed commit isn't an ancestor of the remote head (force-push, other branch) only the remote
head is shown.