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

+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;
}