Skip to content

The agent that grows with you

fix(desktop): local-graph fallback when the update compare API 404s a patched checkout

ibm2024ae37fac2ac69
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 5b983d119f2..9238f2003de 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -430,8 +430,10 @@ import {
compareApiUrl,
describeUpdateCheckFailure,
githubRepoSlug,
+ listLocalCommits,
parseCompare,
- rateLimitFromHeaders
+ rateLimitFromHeaders,
+ resolveBehindLocally
} from './update-api-check'
import { waitForUpdateClearance } from './update-gate'
import { readLiveUpdateMarker, updateHandoffConflict, writeUpdateMarker } from './update-marker'
@@ -3309,7 +3311,7 @@ async function checkUpdates({ force = false }: { force?: boolean } = {}) {
const slug = githubRepoSlug(originUrl)
const status = slug
- ? await checkUpdatesViaApi({ slug, branch, currentSha })
+ ? await checkUpdatesViaApi({ slug, branch, currentSha, updateRoot })
: await checkUpdatesViaLsRemote({ updateRoot, branch, currentSha })
const result = {
@@ -3351,7 +3353,7 @@ function writeUpdateCheckCache(entry) {
// then the compare endpoint only when the tips differ — it yields the exact
// behind count plus the commit list the overlay renders, replacing both
// `rev-list --count` and `git log HEAD..origin/<branch>`.
-async function checkUpdatesViaApi({ slug, branch, currentSha }) {
+async function checkUpdatesViaApi({ slug, branch, currentSha, updateRoot }) {
let targetSha
try {
@@ -3370,9 +3372,14 @@ async function checkUpdatesViaApi({ slug, branch, currentSha }) {
// Compare failure (rate-limited, local-only HEAD 404) keeps the honest
// "update available, count unknown" — never a fabricated number.
+ let compareError = null
const compared = await fetchGitHubApi(compareApiUrl(slug, currentSha, targetSha))
.then(parseCompare)
- .catch(() => null)
+ .catch(error => {
+ compareError = error
+
+ return null
+ })
// ahead_by === 0 with differing tips: the remote tip is reachable from our
// HEAD — a local commit sitting AHEAD, not behind. Flagging that as an update
@@ -3381,6 +3388,26 @@ async function checkUpdatesViaApi({ slug, branch, currentSha }) {
return { behind: 0, updateAvailable: false, targetSha, commits: [] }
}
+ // A local-only HEAD (a patched checkout's merge/rebase commits exist nowhere
+ // upstream) makes the compare endpoint 404 FOREVER — the fallback below then
+ // holds a permanent "update available" no update can ever clear, since every
+ // update re-creates the local-only HEAD. When the already-fetched tip is in
+ // the local object database, answer from the local graph instead — the same
+ // ancestry guard the ls-remote path already applies and the backend's
+ // banner._tips_behind uses. Only a tip we can't see at all stays "unknown".
+ if (compared === null && compareError && updateRoot) {
+ const local = await resolveBehindLocally(runGit, updateRoot, currentSha, targetSha)
+
+ if (local !== null) {
+ return {
+ behind: local,
+ updateAvailable: local > 0,
+ targetSha,
+ commits: local > 0 ? await listLocalCommits(runGit, updateRoot, currentSha, targetSha) : []
+ }
+ }
+ }
+
return {
behind: compared ? compared.behind : null,
updateAvailable: true,
diff --git a/apps/desktop/electron/update-api-check.test.ts b/apps/desktop/electron/update-api-check.test.ts
index 3b9fba232ee..83991b9a7e0 100644
--- a/apps/desktop/electron/update-api-check.test.ts
+++ b/apps/desktop/electron/update-api-check.test.ts
@@ -18,8 +18,10 @@ import {
cacheIsFresh,
describeUpdateCheckFailure,
githubRepoSlug,
+ listLocalCommits,
parseCompare,
rateLimitFromHeaders,
+ resolveBehindLocally,
UPDATE_CHECK_FAILURE_TTL_MS,
UPDATE_CHECK_TTL_MS
} from './update-api-check'
@@ -111,3 +113,71 @@ test('a rate-limited 403 names the shared-IP cause, the reset time and GITHUB_TO
'api.github.com answered HTTP 403.'
)
})
+
+/**
+ * Fake runGit keyed on the subcommand. Records every call so tests can pin
+ * that a stale tip short-circuits before any graph walk.
+ */
+function fakeGit(responses: Record<string, { code: number; stdout?: string }>) {
+ const calls: string[][] = []
+
+ return {
+ calls,
+ runGit: async (args: string[]) => {
+ calls.push(args)
+ const canned = responses[args[0]] ?? { code: 0 }
+
+ return { code: canned.code, stdout: canned.stdout ?? '', stderr: '' }
+ }
+ }
+}
+
+test('resolveBehindLocally: unreachable tip is unknown, reachable tip is ahead, otherwise the real gap', async () => {
+ // A tip missing from the object database (truly stale checkout) stays unknown.
+ const stale = fakeGit({ 'cat-file': { code: 1 } })
+ assert.equal(await resolveBehindLocally(stale.runGit, '/repo', SHA_A, SHA_B), null)
+ assert.deepEqual(stale.calls.map(args => args[0]), ['cat-file'])
+
+ // The remote tip reachable from HEAD is a local commit AHEAD, not an update.
+ const ahead = fakeGit({})
+ assert.equal(await resolveBehindLocally(ahead.runGit, '/repo', SHA_A, SHA_B), 0)
+ assert.deepEqual(ahead.calls.map(args => args[0]), ['cat-file', 'merge-base'])
+
+ // Otherwise the honest local count of HEAD..tip (merge-base must fail first).
+ const behind = fakeGit({ 'merge-base': { code: 1 }, 'rev-list': { code: 0, stdout: '3\n' } })
+ assert.equal(await resolveBehindLocally(behind.runGit, '/repo', SHA_A, SHA_B), 3)
+ assert.deepEqual(behind.calls.map(args => args[0]), ['cat-file', 'merge-base', 'rev-list'])
+
+ // A git failure mid-walk is never silently read as zero.
+ const broken = fakeGit({ 'merge-base': { code: 1 }, 'rev-list': { code: 128 } })
+ assert.equal(await resolveBehindLocally(broken.runGit, '/repo', SHA_A, SHA_B), null)
+})
+
+test('listLocalCommits renders the local gap newest-first in the parseCompare shape', async () => {
+ const OLDEST = '1'.repeat(40)
+ const NEWEST = '2'.repeat(40)
+ const gitLog = fakeGit({
+ log: {
+ code: 0,
+ stdout: [
+ [OLDEST, 'Old Hand', '2026-09-10T00:00:00+00:00', 'fix: older'].join('\x1f'),
+ [NEWEST, 'New Face', '2026-09-11T00:00:00+00:00', 'feat: newer'].join('\x1f'),
+ ''
+ ].join('\n')
+ }
+ })
+
+ const commits = await listLocalCommits(gitLog.runGit, '/repo', SHA_A, SHA_B)
+ assert.deepEqual(
+ commits.map(c => [c.sha, c.summary, c.author]),
+ [
+ [NEWEST, 'feat: newer', 'New Face'],
+ [OLDEST, 'fix: older', 'Old Hand']
+ ]
+ )
+ assert.equal(commits[0].at, Date.parse('2026-09-11T00:00:00+00:00'))
+
+ // A failed log renders as "no listed commits", never a fabricated list.
+ const failed = fakeGit({ log: { code: 128 } })
+ assert.deepEqual(await listLocalCommits(failed.runGit, '/repo', SHA_A, SHA_B), [])
+})
diff --git a/apps/desktop/electron/update-api-check.ts b/apps/desktop/electron/update-api-check.ts
index 0d55876f6f7..61f340ea465 100644
--- a/apps/desktop/electron/update-api-check.ts
+++ b/apps/desktop/electron/update-api-check.ts
@@ -192,3 +192,75 @@ export function describeUpdateCheckFailure(error: UpdateCheckFailure | null | un
return `api.github.com: ${error?.message || String(error)}`
}
+
+/** A git command runner — main.ts injects its runGit; tests inject a fake. */
+export type GitRunner = (args: string[], options?: { cwd?: string }) => Promise<{
+ code: number
+ stdout: string
+ stderr: string
+}>
+
+/**
+ * Answer "how far behind is HEAD?" from the LOCAL object database when the
+ * compare endpoint can't — its 404 on a local-only HEAD (a patched checkout's
+ * merge/rebase commits exist nowhere upstream) or a rate limit. Mirrors the
+ * ls-remote path's ancestry guard and the backend's banner._tips_behind: a
+ * tip reachable from HEAD is a local commit AHEAD, not an update; anything
+ * else counts HEAD..tip. Returns null when the tip isn't in the local
+ * database (a truly stale checkout) so callers keep the honest
+ * "update available, count unknown" state instead of a fabricated number.
+ */
+export async function resolveBehindLocally(
+ runGit: GitRunner,
+ cwd: string,
+ currentSha: string,
+ targetSha: string
+): Promise<number | null> {
+ const known = await runGit(['cat-file', '-e', `${targetSha}^{commit}`], { cwd })
+
+ if (known.code !== 0) {
+ return null
+ }
+
+ if ((await runGit(['merge-base', '--is-ancestor', targetSha, currentSha], { cwd })).code === 0) {
+ return 0
+ }
+
+ const count = await runGit(['rev-list', '--count', `${currentSha}..${targetSha}`], { cwd })
+ const parsed = Number.parseInt(count.stdout.trim(), 10)
+
+ return count.code === 0 && Number.isInteger(parsed) && parsed >= 0 ? parsed : null
+}
+
+/**
+ * Newest-first commit list for resolveBehindLocally's count, in the same
+ * CompareCommit shape as parseCompare so the overlay's "what's changed" list
+ * renders the local answer too.
+ */
+export async function listLocalCommits(
+ runGit: GitRunner,
+ cwd: string,
+ currentSha: string,
+ targetSha: string
+): Promise<CompareCommit[]> {
+ const log = await runGit(
+ ['log', '--reverse', '--date=iso-strict', '--pretty=%H%x1f%an%x1f%ad%x1f%s', `${currentSha}..${targetSha}`],
+ { cwd }
+ )
+
+ if (log.code !== 0) {
+ return []
+ }
+
+ return log.stdout
+ .split('\n')
+ .map(line => line.split('\x1f'))
+ .filter(parts => parts.length === 4 && parts[0])
+ .map(([sha, author, date, summary]) => ({
+ sha,
+ author,
+ summary,
+ at: Number.isFinite(Date.parse(date)) ? Date.parse(date) : 0
+ }))
+ .reverse()
+}