Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(github): conditional heartbeat skips the issue scan when nothing changed

review8905c8e86a9f
diff --git a/src/core/github/client.test.ts b/src/core/github/client.test.ts
index 6071ad0e1..397f0abf5 100644
--- a/src/core/github/client.test.ts
+++ b/src/core/github/client.test.ts
@@ -191,4 +191,47 @@ describe('GitHubIssuesClient', () => {
expect(JSON.parse(String((request as unknown as { init: RequestInit }).init.body)))
.toEqual({ state: 'closed', labels: ['bug', 'status:done'] })
})
+ describe('issuesHeartbeat', () => {
+ it('asks for the single most recently updated item, conditionally on the stored ETag', async () => {
+ const calls: Array<{ url: string; headers: Headers }> = []
+ const client = new GitHubIssuesClient({
+ token: 'secret',
+ fetch: async (url, init) => {
+ calls.push({ url: String(url), headers: new Headers(init?.headers) })
+ return new Response(null, { status: 304, headers: { etag: '"strong"' } })
+ }
+ })
+ expect(await client.issuesHeartbeat('nodeterm/nodeterm', 'W/"stored"'))
+ .toEqual({ notModified: true, etag: 'W/"stored"' })
+ // state=all + sort=updated covers issues AND pull requests: the same endpoint and the same
+ // `updated_at` the incremental `since` scan filters on, so the heartbeat can never miss a
+ // change that scan would have picked up.
+ expect(calls[0].url).toBe(
+ 'https://api.github.com/repos/nodeterm/nodeterm/issues?state=all&sort=updated&direction=desc&per_page=1'
+ )
+ expect(calls[0].headers.get('if-none-match')).toBe('W/"stored"')
+ })
+
+ it('returns the fresh ETag of a changed repository without decoding the item', async () => {
+ const client = new GitHubIssuesClient({
+ token: 'secret',
+ fetch: async () => response([{ anything: 'the body is not the point' }], {
+ headers: { etag: 'W/"fresh"' }
+ })
+ })
+ expect(await client.issuesHeartbeat('nodeterm/nodeterm')).toEqual({
+ notModified: false, etag: 'W/"fresh"'
+ })
+ })
+
+ it('sends no condition when there is no stored ETag', async () => {
+ let headers: Headers | undefined
+ const client = new GitHubIssuesClient({
+ token: 'secret',
+ fetch: async (_url, init) => { headers = new Headers(init?.headers); return response([]) }
+ })
+ await client.issuesHeartbeat('nodeterm/nodeterm')
+ expect(headers?.has('if-none-match')).toBe(false)
+ })
+ })
})
diff --git a/src/core/github/client.ts b/src/core/github/client.ts
index 9896f08c2..ba83d5d68 100644
--- a/src/core/github/client.ts
+++ b/src/core/github/client.ts
@@ -5,6 +5,7 @@ import type {
GitHubIssueUser,
GitHubPullMeta,
GitHubRepositoryLabel,
+ IssueHeartbeatResult,
IssuePageResult,
LabelPageResult,
ListIssueOptions,
@@ -254,6 +255,32 @@ export class GitHubIssuesClient {
}
}
+ /**
+ * One conditional request that answers "did anything in this repository change since `etag`?".
+ *
+ * It asks for the single most recently updated item with `If-None-Match`. GitHub answers an
+ * unchanged repository with 304, and a 304 does not count against the rate limit (measured
+ * 2026-09-28: twenty 304s moved `x-ratelimit-used` by zero, one 200 moved it by one). The
+ * incremental scan cannot do this on its own: its `since` moves every pass, so its URL — and
+ * therefore any ETag it could present — never repeats.
+ *
+ * `state=all` + `sort=updated` is the same endpoint and the same `updated_at` the `since` scan
+ * filters on, pull requests included, so any change the scan would pick up moves the top item
+ * and with it this ETag. The body is drained but not decoded: only the validator matters.
+ */
+ async issuesHeartbeat(repository: string, etag?: string): Promise<IssueHeartbeatResult> {
+ safeRepository(repository)
+ if (etag !== undefined && !string(etag, 512)) throw new GitHubClientError('invalid-request')
+ const response = await this.request(
+ `/repos/${repository}/issues?state=all&sort=updated&direction=desc&per_page=1`,
+ { method: 'GET', ...(etag ? { headers: { 'if-none-match': etag } } : {}) }
+ )
+ if (response.status === 304) return { notModified: true, ...(etag ? { etag } : {}) }
+ await this.json(response)
+ const fresh = response.headers.get('etag')
+ return { notModified: false, ...(fresh && string(fresh, 512) ? { etag: fresh } : {}) }
+ }
+
async getIssue(repository: string, issueNumber: number): Promise<GitHubIssue> {
safeRepository(repository)
if (!positiveInteger(issueNumber, Number.MAX_SAFE_INTEGER)) throw new GitHubClientError('invalid-request')
diff --git a/src/core/github/host.test.ts b/src/core/github/host.test.ts
index 1705410a2..e19de2d9b 100644
--- a/src/core/github/host.test.ts
+++ b/src/core/github/host.test.ts
@@ -88,6 +88,7 @@ function fixture() {
}
const client = {
listIssues: vi.fn(),
+ issuesHeartbeat: vi.fn(),
getIssue: vi.fn(),
updateIssue: vi.fn(),
listRepositoryLabels: vi.fn(),
diff --git a/src/core/github/service.test.ts b/src/core/github/service.test.ts
index 18570cf1b..ba8200265 100644
--- a/src/core/github/service.test.ts
+++ b/src/core/github/service.test.ts
@@ -14,6 +14,7 @@ import {
import { GitHubRequestCoordinator } from './request-coordinator'
import type {
GitHubIssue,
+ IssueHeartbeatResult,
IssuePageResult,
ListIssueOptions,
NormalisedProjectKanbanGitHub
@@ -59,10 +60,26 @@ class FixtureClient implements GitHubIssuesClientLike {
for (const item of issues) this.issues.set(item.number, item)
}
+ heartbeats: Array<string | undefined> = []
+
async listIssues(_repository: string, _options: ListIssueOptions): Promise<IssuePageResult> {
return { items: [...this.issues.values()] }
}
+ /** Honest stand-in for GitHub's conditional heartbeat: the validator is derived from the most
+ * recently updated item, exactly what the real endpoint's body (and so its ETag) depends on. */
+ currentHeartbeatEtag(): string {
+ const top = [...this.issues.values()]
+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || b.number - a.number)[0]
+ return top ? `W/"${top.number}@${top.updatedAt}"` : 'W/"empty"'
+ }
+
+ async issuesHeartbeat(_repository: string, etag?: string): Promise<IssueHeartbeatResult> {
+ this.heartbeats.push(etag)
+ const current = this.currentHeartbeatEtag()
+ return etag === current ? { notModified: true, etag } : { notModified: false, etag: current }
+ }
+
async getIssue(_repository: string, number: number) {
return structuredClone(this.issues.get(number)!)
}
@@ -833,17 +850,20 @@ describe('GitHubIssueService', () => {
await service.refresh({ projectId: 'project-1' })
expect(listed).toBe(1)
+ expect(client.heartbeats).toHaveLength(1)
const afterFirst = resolutions
clock += 1_000
await service.refresh({ projectId: 'project-1' })
- expect(listed).toBe(1)
+ expect(client.heartbeats).toHaveLength(1)
// The throttle must run BEFORE the credential resolution, or the expensive half still happens.
expect(resolutions).toBe(afterFirst)
clock += REFRESH_MIN_INTERVAL_MS
await service.refresh({ projectId: 'project-1' })
- expect(listed).toBe(2)
+ // Admitted again. Nothing changed upstream, so it stops at the (free) conditional heartbeat.
+ expect(client.heartbeats).toHaveLength(2)
+ expect(listed).toBe(1)
})
it('lets a full refresh through its own longer interval, not the incremental one', async () => {
@@ -944,3 +964,129 @@ describe('GitHubIssueService', () => {
expect(client.updates).toEqual([])
})
})
+
+describe('GitHubIssueService heartbeat', () => {
+ function counting(client: FixtureClient) {
+ const scans: ListIssueOptions[] = []
+ const list = client.listIssues.bind(client)
+ client.listIssues = async (repository, options) => {
+ scans.push(structuredClone(options))
+ return list(repository, options)
+ }
+ return scans
+ }
+
+ async function seeded(issues: GitHubIssue[], etags: Record<string, string>, over: {
+ lastFullReconciliationAt?: number
+ } = {}) {
+ const cache = new GitHubIssueCache(userDataDir)
+ await cache.bind('local-1', 'project-1', 'o/r', 'user-1')
+ await cache.saveComplete('user-1', 'o/r', {
+ issues, etags, lastSuccessfulRefreshAt: 5_000,
+ lastFullReconciliationAt: over.lastFullReconciliationAt ?? 5_000
+ })
+ return cache
+ }
+
+ it('skips the whole scan when the heartbeat answers 304', async () => {
+ const client = new FixtureClient([issue(1), issue(2)])
+ const scans = counting(client)
+ const cache = await seeded([issue(1), issue(2)], { heartbeat: client.currentHeartbeatEtag() })
+ const deltas: number[][] = []
+ const service = new GitHubIssueService({
+ cache, coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(client),
+ now: () => 10_000,
+ onDelta: (_uiId, _projectId, numbers) => deltas.push(numbers)
+ })
+
+ await service.refresh({ projectId: 'project-1' })
+
+ expect(client.heartbeats).toEqual([client.currentHeartbeatEtag()])
+ expect(scans).toEqual([])
+ expect(deltas).toEqual([])
+ })
+
+ it('runs the incremental since scan when the heartbeat reports a change, and persists the new ETag', async () => {
+ const client = new FixtureClient([issue(1)])
+ const scans = counting(client)
+ const cache = await seeded([issue(1)], { heartbeat: client.currentHeartbeatEtag() })
+ client.issues.set(2, issue(2))
+ const service = new GitHubIssueService({
+ cache, coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(client),
+ now: () => 10_000
+ })
+
+ await service.refresh({ projectId: 'project-1' })
+
+ expect(scans).toHaveLength(1)
+ expect(scans[0].since).toBe(new Date(3_000).toISOString())
+ expect((await cache.load('user-1', 'o/r')).lastComplete?.etags)
+ .toEqual({ heartbeat: client.currentHeartbeatEtag() })
+ expect((await service.query({ projectId: 'project-1', columnId: null, pageSize: 50 })).items
+ .map((item) => item.number)).toEqual([2, 1])
+ })
+
+ it('reuses the persisted ETag after a restart instead of paying for a scan', async () => {
+ const client = new FixtureClient([issue(1)])
+ const cache = await seeded([], {})
+ const first = new GitHubIssueService({
+ cache, coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(client), now: () => 10_000
+ })
+ await first.refresh({ projectId: 'project-1' })
+
+ // A fresh service over the same on-disk cache is what an app restart looks like.
+ const scans = counting(client)
+ const restarted = new GitHubIssueService({
+ cache, coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(client), now: () => 20_000
+ })
+ await restarted.refresh({ projectId: 'project-1' })
+
+ expect(client.heartbeats.at(-1)).toBe(client.currentHeartbeatEtag())
+ expect(scans).toEqual([])
+ })
+
+ it('still scans on a full reconciliation even when the heartbeat answers 304', async () => {
+ const client = new FixtureClient([issue(1)])
+ const scans = counting(client)
+ const cache = await seeded([issue(1), issue(9)], { heartbeat: client.currentHeartbeatEtag() })
+ const service = new GitHubIssueService({
+ cache, coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(client), now: () => 10_000
+ })
+
+ // A deletion or a transfer out of the repository does not move the top item, so the daily
+ // reconciliation is the only thing that can notice one — the heartbeat must never skip it.
+ await service.refresh({ projectId: 'project-1', full: true })
+
+ expect(scans).toHaveLength(1)
+ expect(scans[0].since).toBeUndefined()
+ expect((await service.query({ projectId: 'project-1', columnId: null, pageSize: 50 })).items
+ .map((item) => item.number)).toEqual([1])
+ })
+
+ it('stores the validator read BEFORE the scan, so a change during the scan is seen next time', async () => {
+ const client = new FixtureClient([issue(1)])
+ const cache = await seeded([issue(1)], {})
+ const list = client.listIssues.bind(client)
+ client.listIssues = async (repository, options) => {
+ const page = await list(repository, options)
+ // An edit lands on GitHub after the scan read its page but before the snapshot is saved.
+ client.issues.set(3, issue(3))
+ return page
+ }
+ const service = new GitHubIssueService({
+ cache, coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(client), now: () => 10_000
+ })
+
+ await service.refresh({ projectId: 'project-1' })
+
+ const stored = (await cache.load('user-1', 'o/r')).lastComplete?.etags.heartbeat
+ expect(stored).toBe('W/"1@2026-08-09T10:00:01Z"')
+ expect(stored).not.toBe(client.currentHeartbeatEtag())
+ })
+})
diff --git a/src/core/github/service.ts b/src/core/github/service.ts
index c90fa4022..29ebb8e7a 100644
--- a/src/core/github/service.ts
+++ b/src/core/github/service.ts
@@ -7,6 +7,7 @@ import type {
GitHubIssueQuery,
GitHubMutationResult,
GitHubRepositoryLabel,
+ IssueHeartbeatResult,
IssuePageResult,
LabelPageResult,
ListIssueOptions,
@@ -25,6 +26,9 @@ const MAX_ISSUES = 10_000
const MAX_CACHE_BYTES = 64 * 1024 * 1024
const FULL_REFRESH_AGE = 24 * 60 * 60_000
const POLL_MS = 60_000
+/** Where the heartbeat's validator lives inside the snapshot's (long-existing, previously always
+ * empty) `etags` map, so it is persisted with the issues it vouches for and survives a restart. */
+export const HEARTBEAT_ETAG_KEY = 'heartbeat'
/** Floor between two caller-driven refreshes of one project, and the longer floor for a FULL
* reconciliation. `refresh` is reachable from the renderer AND — for a shared project — from a
@@ -38,6 +42,7 @@ export const FULL_REFRESH_MIN_INTERVAL_MS = 120_000
export interface GitHubIssuesClientLike {
listIssues(repository: string, options: ListIssueOptions): Promise<IssuePageResult>
+ issuesHeartbeat(repository: string, etag?: string): Promise<IssueHeartbeatResult>
getIssue(repository: string, issueNumber: number): Promise<GitHubIssue>
updateIssue(repository: string, issueNumber: number, input: UpdateIssueInput): Promise<GitHubIssue>
listRepositoryLabels(
@@ -751,8 +756,21 @@ export class GitHubIssueService {
// never re-fetches what was dropped — so the claim survives until a full reconciliation
// re-reads the repository and can honestly clear it.
let pullsTruncated = !full && !!previous?.pullsTruncated
+ // The heartbeat runs BEFORE the scan, and it is its validator — not one read afterwards — that
+ // gets stored: a change landing while the scan pages is then still "new" to the next heartbeat.
+ // A 304 skips the scan outright. It never skips a full reconciliation (deletions and transfers
+ // do not move the top item, so that pass is the only thing that can see them), and never an
+ // incomplete repository, which a 304 would otherwise freeze read only.
+ const storedEtag = previous?.etags[HEARTBEAT_ETAG_KEY]
+ const beat = await this.readWithEpoch(captured, () =>
+ captured.client.issuesHeartbeat(captured.repository, storedEtag))
+ .catch((error: unknown) =>
+ error instanceof ConfigurationChangedError ? null : Promise.reject(error))
+ if (!beat) return
+ if (beat.notModified && !full && previous && !state.incomplete) return
+ const heartbeatEtag = beat.etag
+ const etags: Record<string, string> = heartbeatEtag ? { [HEARTBEAT_ETAG_KEY]: heartbeatEtag } : {}
let page = 1
- const etags: Record<string, string> = {}
while (true) {
if (!this.repositoryWriteAllowed(captured.repository, operationId, repositoryGeneration) ||
cacheGeneration !== state.cacheGeneration ||
diff --git a/src/shared/github-issues.ts b/src/shared/github-issues.ts
index 65acb1a33..6625fd864 100644
--- a/src/shared/github-issues.ts
+++ b/src/shared/github-issues.ts
@@ -133,6 +133,13 @@ export interface IssuePageResult {
notModified?: boolean
}
+/** `notModified` = GitHub answered 304 to the stored validator: nothing in the repository changed.
+ * `etag` is the validator to store for the next heartbeat (the one sent, on a 304). */
+export interface IssueHeartbeatResult {
+ notModified: boolean
+ etag?: string
+}
+
export interface UpdateIssueInput {
state?: 'open' | 'closed'
labels?: string[]