fix: harden the remote commit check after review

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 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-10-19 09:18:03 +02:00
1 parent 9a85c3bca0
commit 69e39541a4
4 files changed
+70 -26

No files matched your search

+7 -2
View File
@@ -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. // A clone that never finishes (e.g. ssh waiting on a prompt) would otherwise hang forever.
const GIT_TIMEOUT_MS = 5 * 60 * 1000; 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) => { return new Promise((resolve, reject) => {
const child = spawn(cmd, args, { cwd, detached: true }); const child = spawn(cmd, args, { cwd, detached: true });
killGroupAfter(child, GIT_TIMEOUT_MS); killGroupAfter(child, timeoutMs);
let output = ""; let output = "";
child.stdout.on("data", (d) => (output += d.toString())); child.stdout.on("data", (d) => (output += d.toString()));
child.stderr.on("data", (d) => (output += d.toString())); child.stderr.on("data", (d) => (output += d.toString()));
+19 -2
View File
@@ -16,11 +16,11 @@ function git(cwd: string, ...args: string[]) {
}).trim(); }).trim();
} }
async function load() { async function load(ref = "main") {
vi.resetModules(); vi.resetModules();
vi.stubEnv("DATA_DIR", path.join(tmp, "data")); vi.stubEnv("DATA_DIR", path.join(tmp, "data"));
vi.stubEnv("SELF_UPDATE_REPO_URL", origin); vi.stubEnv("SELF_UPDATE_REPO_URL", origin);
vi.stubEnv("SELF_UPDATE_REF", "main"); vi.stubEnv("SELF_UPDATE_REF", ref);
return import("./remoteCheck.js"); return import("./remoteCheck.js");
} }
@@ -41,6 +41,23 @@ afterAll(() => {
}); });
describe("checkRemote", () => { 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 () => { it("counts the commits the installed sha is missing", async () => {
const { checkRemote } = await load(); const { checkRemote } = await load();
const status = await checkRemote(shas[0], true); const status = await checkRemote(shas[0], true);
+34 -18
View File
@@ -10,6 +10,8 @@ const CHECK_DIR = "_manager-check";
const OK_TTL_MS = 10 * 60 * 1000; const OK_TTL_MS = 10 * 60 * 1000;
const ERROR_TTL_MS = 60 * 1000; const ERROR_TTL_MS = 60 * 1000;
const MAX_LISTED = 20; 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 { export interface RemoteStatus {
checkedAt: string; checkedAt: string;
@@ -22,9 +24,10 @@ export interface RemoteStatus {
let cached: { status: RemoteStatus; expires: number; forSha: string | undefined } | null = null; let cached: { status: RemoteStatus; expires: number; forSha: string | undefined } | null = null;
let inFlight: Promise<RemoteStatus> | null = null; let inFlight: Promise<RemoteStatus> | null = null;
let queuedForce: Promise<RemoteStatus> | null = null;
async function git(cwd: string, args: string[]) { 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<RemoteStatus> { async function compute(installedSha: string | undefined): Promise<RemoteStatus> {
@@ -40,12 +43,14 @@ async function compute(installedSha: string | undefined): Promise<RemoteStatus>
} }
// Blobless fetch where the server supports it; plain fetch otherwise. // Blobless fetch where the server supports it; plain fetch otherwise.
const fetchArgs = ["fetch", "--quiet", "--no-tags", url, config.selfUpdateRef]; const fetchTail = ["--quiet", "--no-tags", "--", url, config.selfUpdateRef];
let fetched = await git(dir, [fetchArgs[0]!, "--filter=blob:none", ...fetchArgs.slice(1)]); let fetched = await git(dir, ["fetch", "--filter=blob:none", ...fetchTail]);
if (fetched.code !== 0) fetched = await git(dir, fetchArgs); // 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)}` }; 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(); const remoteSha = head.output.trim();
if (head.code !== 0 || !remoteSha) return { ...base, error: "could not read the fetched head" }; if (head.code !== 0 || !remoteSha) return { ...base, error: "could not read the fetched head" };
if (!installedSha) return { ...base, remoteSha }; if (!installedSha) return { ...base, remoteSha };
@@ -58,22 +63,15 @@ async function compute(installedSha: string | undefined): Promise<RemoteStatus>
const range = `${installedSha}..${remoteSha}`; const range = `${installedSha}..${remoteSha}`;
const count = await git(dir, ["rev-list", "--count", range]); 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); const behind = Number.parseInt(count.output.trim(), 10);
return { if (count.code !== 0 || Number.isNaN(behind)) {
...base, return { ...base, remoteSha, error: `git rev-list failed: ${count.output.trim().slice(-200)}` };
remoteSha, }
behind: Number.isNaN(behind) ? null : behind, const log = await git(dir, ["log", `-n${MAX_LISTED}`, "--format=%h%x09%s", range]);
commits: parseCommitLog(log.output), 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. */ function start(installedSha: string | undefined): Promise<RemoteStatus> {
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) inFlight = compute(installedSha)
.catch((err: Error): RemoteStatus => ({ .catch((err: Error): RemoteStatus => ({
checkedAt: new Date().toISOString(), checkedAt: new Date().toISOString(),
@@ -92,6 +90,24 @@ export function checkRemote(installedSha: string | undefined, force = false): Pr
return inFlight; 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<RemoteStatus> {
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). */ /** Last known result without triggering a fetch (null if none yet). */
export function cachedRemoteStatus(): RemoteStatus | null { export function cachedRemoteStatus(): RemoteStatus | null {
return cached?.status ?? null; return cached?.status ?? null;
+10 -4
View File
@@ -19,6 +19,7 @@ export function ManagerCard() {
const [startedAt, setStartedAt] = useState<number | null>(null); const [startedAt, setStartedAt] = useState<number | null>(null);
const [gaveUp, setGaveUp] = useState(false); const [gaveUp, setGaveUp] = useState(false);
const [checking, setChecking] = useState(false); const [checking, setChecking] = useState(false);
const [remoteGaveUp, setRemoteGaveUp] = useState(false);
async function refresh() { async function refresh() {
try { try {
@@ -59,21 +60,24 @@ export function ManagerCard() {
}, [requested, info, unreachable, startedAt]); }, [requested, info, unreachable, startedAt]);
const repoConfigured = info !== null && info.unavailableReason !== "SELF_UPDATE_REPO_URL is not set"; 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. // The first remote check runs in the background on the server; poll briefly until it lands.
useEffect(() => { useEffect(() => {
if (!waitingForRemote) return; if (!waitingForRemote) return;
let tries = 0; let tries = 0;
const timer = setInterval(() => { const timer = setInterval(() => {
if (++tries > 10) clearInterval(timer); if (++tries > 10) {
else refresh(); clearInterval(timer);
setRemoteGaveUp(true);
} else refresh();
}, 3000); }, 3000);
return () => clearInterval(timer); return () => clearInterval(timer);
}, [waitingForRemote]); }, [waitingForRemote]);
async function checkNow() { async function checkNow() {
setChecking(true); setChecking(true);
setRemoteGaveUp(false);
setError(null); setError(null);
try { try {
setInfo(await api.checkManager()); setInfo(await api.checkManager());
@@ -157,7 +161,9 @@ export function ManagerCard() {
function RemoteLine({ info, checking }: { info: SystemInfo; checking: boolean }) { function RemoteLine({ info, checking }: { info: SystemInfo; checking: boolean }) {
const remote = info.remote; const remote = info.remote;
if (!remote) return <p className="status-detail">{checking ? "Checking the remote…" : ""}</p>; if (!remote) {
return <p className="status-detail">{checking ? "Checking the remote…" : "Not checked yet; use Check for updates."}</p>;
}
if (remote.error) return <p className="status-detail">Could not check the remote: {remote.error}</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 head = remote.remoteSha?.slice(0, 7);