Skip to content
Prev Previous commit
Next Next commit
refactor(heartbeat): address code-review findings
- /status now does the live githubStatus() check first (the cached heartbeat
  can be up to ~60s stale after a revoke), restoring the on-demand authority
  that the cache-first ordering had turned into dead code.
- isCopilotTokenValid delegates to probeGithubAuth — one token-exchange path.
- Share SIGNED_OUT_DETAIL so /doctor and the HUD show the same "run /login"
  hint for the signed-out state (they had diverged).
- start() is now idempotent (guard against leaking a second timer).
- Comments on probeGithubAuth / nextGithubStatus now state the real
  limitations instead of over-promising: the transient stickiness is
  UNBOUNDED (a sustained non-401/403 fault never surfaces), 403 is treated as
  definitive despite GitHub using it for some rate-limits, and a boot-time
  transient leaves the badge pending/absent.

Full suite green (379), build clean.

Co-Authored-By: Claude <noreply@anthropic.com>
  • Loading branch information
wangcansunking and claude committed Jun 28, 2026
commit 9cfc68420f6a765d5828465072e60bc6c671f047
20 changes: 13 additions & 7 deletions src/providers/copilot/token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,24 +32,30 @@ export class CopilotTokenStore {
}
}

// True if the stored GitHub token still exchanges for a Copilot token.
// True if the stored GitHub token still exchanges for a Copilot token. A thin wrapper over
// probeGithubAuth so the token-exchange logic lives in exactly one place.
export async function isCopilotTokenValid(ghToken: string, fetchFn: typeof fetch = fetch): Promise<boolean> {
try { await new CopilotTokenStore(ghToken, fetchFn).get(); return true; }
catch { return false; }
return (await probeGithubAuth(ghToken, fetchFn)).ok;
}

// A classified auth check for the heartbeat. Unlike isCopilotTokenValid (a bare boolean), this
// distinguishes a DEFINITIVE auth failure (401/403 — the login was revoked/expired) from a TRANSIENT
// one (timeout / 5xx / network blip). The heartbeat keeps the last-known-good status on transient
// errors so a single GitHub rate-limit or hiccup never flips the UI to "expired".
// distinguishes a DEFINITIVE auth failure (401/403) from a TRANSIENT one (timeout / 5xx / network /
// other). The heartbeat keeps the last-known-good status on transient errors, so a brief blip doesn't
// flip the UI to "expired". Known limitations of this code:
// - The stickiness is UNBOUNDED: a SUSTAINED transient fault (a long GitHub outage, DNS down, a
// persistently malformed body) also never surfaces — a connected badge stays green the whole time.
// Only 401/403 ever flips the UI to "expired".
// - 403 is treated as definitive here, but GitHub also returns 403 for some rate-limits; a rate-
// limited 403 would therefore (incorrectly) read as "expired". (429 is correctly transient.)
export interface AuthProbe { ok: boolean; transient: boolean; detail: string }
export async function probeGithubAuth(ghToken: string, fetchFn: typeof fetch = fetch): Promise<AuthProbe> {
try {
await new CopilotTokenStore(ghToken, fetchFn).get();
return { ok: true, transient: false, detail: "token valid" };
} catch (e) {
// CopilotTokenStore throws CopilotAuthError(status) for any non-ok response, and other errors
// (AbortError on timeout, network failures) for the rest. Only 401/403 is a real auth failure.
// (AbortError on timeout, network failures) for the rest. We treat 401/403 as definitive auth
// failures; everything else is transient. See the limitations noted above.
if (e instanceof CopilotAuthError && (e.status === 401 || e.status === 403)) {
return { ok: false, transient: false, detail: e.message };
}
Expand Down
13 changes: 10 additions & 3 deletions src/supervisor/github-heartbeat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,22 @@ import type { GithubStatus } from "../shared/control-types.js";
export const GITHUB_HEARTBEAT_INTERVAL_MS = 60_000;
export const GITHUB_HEARTBEAT_INITIAL_DELAY_MS = 2_000;

// Shared so /doctor and the heartbeat show the same remediation hint for the signed-out state.
export const SIGNED_OUT_DETAIL = "not logged in — run /login";

// Pure reducer: given the prior cached status, whether a token is on disk, and the latest probe
// result, decide the next cached status. Sticky on transient errors so a single hiccup never flips a
// connected session to "expired".
// result, decide the next cached status. Transient errors are sticky — they keep the prior status —
// so a brief blip doesn't flip a connected session to "expired". Caveat (see probeGithubAuth): the
// stickiness is unbounded, and if the FIRST probe is transient (prev still undefined) the status stays
// undefined / "pending", so /api/status omits `github` and the HUD shows no badge until a non-transient
// result lands.
export function nextGithubStatus(
prev: GithubStatus | undefined,
hasToken: boolean,
probe: AuthProbe | null,
now: number,
): GithubStatus | undefined {
if (!hasToken) return { ok: false, hasToken: false, checkedAt: now, detail: "not logged in — run /login" };
if (!hasToken) return { ok: false, hasToken: false, checkedAt: now, detail: SIGNED_OUT_DETAIL };
if (probe && probe.transient) return prev; // keep last-known-good (or stay pending if none yet)
if (!probe) return prev;
return { ok: probe.ok, hasToken: true, checkedAt: now, detail: probe.detail };
Expand Down Expand Up @@ -60,6 +66,7 @@ export class GithubHeartbeat {
}

start(): void {
if (this.timer) return; // idempotent: don't leak a second timer if start() is called twice
this.stopped = false;
const tick = () => { void this.runOnce(); };
this.timer = setTimeout(() => {
Expand Down
4 changes: 2 additions & 2 deletions src/supervisor/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { defaultConfig } from "../shared/config.js";
import { dataDir, dbPath } from "../shared/paths.js";
import { readGhToken } from "../shared/creds.js";
import { probeGithubAuth } from "../providers/copilot/token.js";
import { GithubHeartbeat } from "./github-heartbeat.js";
import { GithubHeartbeat, SIGNED_OUT_DETAIL } from "./github-heartbeat.js";
import type { WorkerState, DoctorCheck } from "../shared/control-types.js";

export function startSupervisor(): { stop: () => void } {
Expand Down Expand Up @@ -39,7 +39,7 @@ export function startSupervisor(): { stop: () => void } {
const gh = readGhToken(dataDir());
let auth: DoctorCheck;
if (!gh) {
auth = { name: "github-auth", ok: false, detail: "not logged in — restart copilot-reverse to log in" };
auth = { name: "github-auth", ok: false, detail: SIGNED_OUT_DETAIL };
} else {
// Validate the token actually exchanges, not just that it exists on disk. Shares the heartbeat's
// classifier so on-demand /doctor and the periodic probe agree.
Expand Down
5 changes: 3 additions & 2 deletions src/tui/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,9 @@ export function App({
if (t === "/webiq" && enableWebiq) { setScreen({ kind: "webiq-key" }); return; }
if (t === "/status" && (startupStatus || githubStatus || webSearchBackend)) {
// Render the live status overview (same card as startup), then the worker restart history.
// Prefer the heartbeat value the poll already cached; only fall back to a live check if absent.
const ghState = github ?? (githubStatus ? await githubStatus() : (startupStatus?.github ?? "signed-out"));
// /status is an explicit "is my login OK right now?" — do the live check when wired (the cached
// heartbeat can be up to ~60s stale), falling back to the cached/seed value only if it isn't.
const ghState = githubStatus ? await githubStatus() : (github ?? startupStatus?.github ?? "signed-out");
let worker = state, restarts: string[] = [];
try {
const s = await statusSource?.();
Expand Down
19 changes: 19 additions & 0 deletions tests/supervisor/github-heartbeat.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,4 +93,23 @@ describe("GithubHeartbeat", () => {
vi.useRealTimers();
}
});

it("start() is idempotent — a second start() without stop() does not leak a second timer", async () => {
vi.useFakeTimers();
try {
const probe = vi.fn(async () => ok);
const hb = new GithubHeartbeat(() => "gho", probe, () => 1, { intervalMs: 500, initialDelayMs: 100 });
hb.start();
hb.start(); // second call must be a no-op, not a leaked parallel timer
await vi.advanceTimersByTimeAsync(100);
expect(probe).toHaveBeenCalledTimes(1); // one probe, not two
await vi.advanceTimersByTimeAsync(500);
expect(probe).toHaveBeenCalledTimes(2); // single cadence, not doubled
hb.stop();
await vi.advanceTimersByTimeAsync(2000);
expect(probe).toHaveBeenCalledTimes(2); // stop() halts the single timer
} finally {
vi.useRealTimers();
}
});
});
14 changes: 8 additions & 6 deletions tests/tui/app.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,17 +80,19 @@ describe("App", () => {
expect(lastFrame() ?? "").toMatch(/github.*✓/);
});

it("/status uses the cached heartbeat value and does NOT make a redundant githubStatus call", async () => {
const githubStatus = vi.fn(async () => "connected" as const);
const statusSource = async () => ({ workerState: "ready" as const, restarts: [], github: { ok: false, hasToken: true, checkedAt: 1, detail: "expired" } });
it("/status does a live githubStatus() check rather than trusting the cached heartbeat (which can be stale)", async () => {
// Live check says "expired" (token just revoked); the cached heartbeat still reads "connected".
// /status must reflect the fresh live result, not the up-to-60s-stale cache.
const githubStatus = vi.fn(async () => "expired" as const);
const statusSource = async () => ({ workerState: "ready" as const, restarts: [], github: { ok: true, hasToken: true, checkedAt: 1, detail: "token valid" } });
const { stdin, lastFrame } = render(<App registry={reg()} title="m" statusSource={statusSource} githubStatus={githubStatus} startupStatus={{ github: "connected", webSearch: "webiq", worker: "ready", clients: { claude: false, codex: false } } as any} />);
await new Promise((r) => setTimeout(r, 60)); // poll populates the cached 'expired' state
await new Promise((r) => setTimeout(r, 60)); // poll populates the cached 'connected' state
stdin.write("/status");
await new Promise((r) => setTimeout(r, 20));
stdin.write("\r");
await new Promise((r) => setTimeout(r, 80));
const f = lastFrame() ?? "";
expect(f).toMatch(/expired/i); // card reflects the cached heartbeat value, not startup's "connected"
expect(githubStatus).not.toHaveBeenCalled(); // cached → no redundant network check
expect(githubStatus).toHaveBeenCalled(); // /status is authoritative: it runs the live check
expect(f).toMatch(/expired/i); // and reflects the live result, not the stale cache
});
});