Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

fix(coding-agent): bound heartbeat view catalog fetch with a 10s deadline (#2342)

Seth Kartenad426c672327
diff --git a/packages/coding-agent/.changes/heartbeat-view-fetch-deadline.md b/packages/coding-agent/.changes/heartbeat-view-fetch-deadline.md
new file mode 100644
index 0000000000..8fc2163e75
--- /dev/null
+++ b/packages/coding-agent/.changes/heartbeat-view-fetch-deadline.md
@@ -0,0 +1 @@
+- Fixed the TUI heartbeat view freezing on busy sessions: catalog fetches now keep the last snapshot after a 10-second deadline and retry on the next heartbeats_changed event, instead of waiting behind an active turn indefinitely. A timed-out fetch still applies its late answer and re-arms a short retry so the open view always converges, and a failed fetch now shows an error in the view instead of silently showing a stale catalog.
diff --git a/packages/coding-agent/src/modes/interactive/components/heartbeat-manager.ts b/packages/coding-agent/src/modes/interactive/components/heartbeat-manager.ts
index 28e9344ec7..ab0dfbb2db 100644
--- a/packages/coding-agent/src/modes/interactive/components/heartbeat-manager.ts
+++ b/packages/coding-agent/src/modes/interactive/components/heartbeat-manager.ts
@@ -15,6 +15,8 @@ type HeartbeatManagerMode = { type: "list" } | { type: "actions"; heartbeatId: s
export interface HeartbeatManagerOptions {
getHeartbeats: () => readonly AgentConnectionHeartbeat[];
+ /** Last catalog fetch failure to surface in the list view, if any. */
+ getFetchError?: () => string | undefined;
getRows: () => number;
onAction: (heartbeat: AgentConnectionHeartbeat, action: AgentHeartbeatManagementAction) => Promise<void>;
onClose: () => void;
@@ -111,6 +113,13 @@ export class HeartbeatManagerComponent implements Component, Focusable {
const list = new MenuList({ compact: this.getListLayout().compact });
this.populateHeartbeatList(list);
panel.addChild(list);
+ const fetchError = this.options.getFetchError?.();
+ if (fetchError) {
+ panel.addChild(new Spacer(1));
+ panel.addChild(
+ new TruncatedText(theme.fg("warning", `Heartbeat refresh failed: ${this.singleLine(fetchError)}`)),
+ );
+ }
if (this.error) {
panel.addChild(new Spacer(1));
panel.addChild(new TruncatedText(theme.fg("error", `Error: ${this.error}`)));
@@ -270,7 +279,7 @@ export class HeartbeatManagerComponent implements Component, Focusable {
getRows: this.options.getRows,
preferredVisibleItems: PREFERRED_VISIBLE_HEARTBEATS,
totalItems: this.heartbeats.length,
- reservedRows: HEARTBEAT_LIST_RESERVED_ROWS + (this.error ? 2 : 0),
+ reservedRows: HEARTBEAT_LIST_RESERVED_ROWS + (this.error || this.options.getFetchError?.() ? 2 : 0),
comfortableItemRows: 3,
compactItemRows: 2,
scrollIndicatorRows: HEARTBEAT_SCROLL_INDICATOR_ROWS,
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index 445dabc4a9..82477c66b3 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -583,6 +583,36 @@ const INITIAL_TRANSCRIPT_RENDER_MESSAGE_LIMIT = 400;
// Coalesce at most this many heartbeats_changed refreshes into one refresh
// promise; sustained churn must not hold rebindCurrentSession in a drain loop.
const HEARTBEAT_REFRESH_DRAIN_LIMIT = 25;
+// A busy daemon can serialize a catalog fetch behind session work or worker
+// recovery for minutes; the TUI waits at most this long before keeping the
+// last catalog and letting the next heartbeats_changed event retry.
+export const HEARTBEAT_REFRESH_FETCH_TIMEOUT_MS = 10_000;
+// After a deadline expiry, retry the open manager's refresh on this short
+// cadence so the view always has a next scheduled retrieval even when no
+// heartbeats_changed event arrives and the catalog has no nextRunAt to
+// schedule from.
+export const HEARTBEAT_REFRESH_RETRY_DELAY_MS = 5_000;
+
+/** Race a catalog fetch against the refresh deadline; resolves undefined on expiry. */
+async function fetchHeartbeatsWithinDeadline(
+ fetch: Promise<AgentConnectionHeartbeat[]>,
+): Promise<AgentConnectionHeartbeat[] | undefined> {
+ // The deadline can settle first; a late failure must not surface as an
+ // unhandled rejection after this refresh has moved on.
+ void fetch.catch(() => undefined);
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race([
+ fetch,
+ new Promise<undefined>((resolve) => {
+ timeout = setTimeout(() => resolve(undefined), HEARTBEAT_REFRESH_FETCH_TIMEOUT_MS);
+ timeout.unref?.();
+ }),
+ ]);
+ } finally {
+ clearTimeout(timeout);
+ }
+}
function initialRenderMessages(messages: AgentMessage[]): AgentMessage[] {
if (messages.length <= INITIAL_TRANSCRIPT_RENDER_MESSAGE_LIMIT) {
@@ -1062,6 +1092,15 @@ export class InteractiveMode {
private heartbeatManagerHandle: OverlayHandle | undefined;
private heartbeatManagerRefreshTimer: ReturnType<typeof setTimeout> | undefined;
private heartbeatManagerRefreshAt: number | undefined;
+ private heartbeatManagerFetchRetryTimer: ReturnType<typeof setTimeout> | undefined;
+ // Last catalog fetch failure surfaced in the open manager view; cleared by
+ // the next successful apply and on manager open.
+ private heartbeatCatalogFetchError: string | undefined;
+ // Monotonic issue-order sequence for catalog writes (fetches and heartbeat
+ // management actions). A fetch write sequenced behind an already-applied
+ // newer one is dropped, so a late/older snapshot cannot revert newer state.
+ private heartbeatCatalogSeq = 0;
+ private heartbeatCatalogAppliedSeq = 0;
// Registry of images pasted this session, keyed by the `[image #N]` marker
// shown to the user. Insertion-ordered; the bytes persist (bounded by
@@ -2657,9 +2696,22 @@ export class InteractiveMode {
// starve an awaiting rebind (and its transcript render) indefinitely.
for (let drain = 0; drain <= HEARTBEAT_REFRESH_DRAIN_LIMIT; drain++) {
this.heartbeatRefreshRequested = false;
- const heartbeats = await connection.listHeartbeats();
+ const fetchSeq = ++this.heartbeatCatalogSeq;
+ const fetch = connection.listHeartbeats();
+ const heartbeats = await fetchHeartbeatsWithinDeadline(fetch);
if (this.isShuttingDown || this.isReturningToAgentsView || this.agentConnection !== connection) return;
- this.applyHeartbeatCatalog(heartbeats);
+ if (heartbeats === undefined) {
+ // The fetch deadline expired: keep the last catalog, retain the
+ // in-flight result so the open view still converges when the
+ // late answer lands, and arm a bounded retry so the open view
+ // always has a next scheduled retrieval even if it never does.
+ // A change event that arrived mid-fetch still re-triggers a
+ // refresh through the follow-up scheduling below.
+ this.retainHeartbeatCatalogFetch(fetch, connection, fetchSeq);
+ this.armHeartbeatManagerFetchRetry();
+ return;
+ }
+ this.applyHeartbeatCatalog(heartbeats, fetchSeq);
if (!this.heartbeatRefreshRequested) return;
}
})().finally(() => {
@@ -2677,8 +2729,15 @@ export class InteractiveMode {
return refresh;
}
- private applyHeartbeatCatalog(heartbeats: AgentConnectionHeartbeat[]): void {
+ private applyHeartbeatCatalog(heartbeats: AgentConnectionHeartbeat[], seq?: number): void {
+ // A sequenced fetch write that lost the race to a newer catalog write
+ // (a later fetch or a management action) must not revert it.
+ if (seq !== undefined) {
+ if (seq < this.heartbeatCatalogAppliedSeq) return;
+ this.heartbeatCatalogAppliedSeq = seq;
+ }
this.heartbeatCatalog = heartbeats;
+ this.heartbeatCatalogFetchError = undefined;
this.scheduleHeartbeatManagerRefresh();
this.updateSubagentSummaryLine();
this.ui.requestRender();
@@ -4183,7 +4242,7 @@ export class InteractiveMode {
this.defaultEditor.onAction("app.tools.expand", () => this.toggleToolOutputExpansion());
this.defaultEditor.onAction("app.subagents.focus", () => this.focusSubagentSummary());
this.defaultEditor.onAction("app.heartbeats.open", () => {
- void this.showHeartbeatManager();
+ this.showHeartbeatManager();
});
this.defaultEditor.onAction("app.editor.external", () => this.openExternalEditor());
this.defaultEditor.onAction("app.prompt.stash", () => this.handlePromptStash());
@@ -9930,19 +9989,22 @@ export class InteractiveMode {
}
}
- private async showHeartbeatManager(): Promise<void> {
+ private showHeartbeatManager(): void {
if (this.heartbeatManagerHandle) {
this.heartbeatManagerHandle.focus();
return;
}
- try {
- await this.refreshHeartbeatCatalog();
- } catch (error) {
- this.showError(error instanceof Error ? error.message : String(error));
- return;
- }
+ // Stale-while-revalidate: open immediately with the cached catalog. A
+ // busy session can take minutes to answer the fetch, and the overlay
+ // must not wait for it; the background refresh updates the open view
+ // when fresh data lands (the component reads the catalog per render).
+ // A failed fetch surfaces inside the view instead of silently showing a
+ // possibly-stale catalog; each open starts with a clean notice state.
+ this.heartbeatCatalogFetchError = undefined;
+ void this.refreshHeartbeatCatalog().catch((error) => this.onHeartbeatCatalogFetchError(error));
const manager = new HeartbeatManagerComponent({
getHeartbeats: () => this.getScopedHeartbeats(),
+ getFetchError: () => this.heartbeatCatalogFetchError,
getRows: () => this.ui.terminal.rows,
onAction: (heartbeat, action) => this.manageHeartbeat(heartbeat, action),
onClose: () => this.closeHeartbeatManager(),
@@ -9958,6 +10020,7 @@ export class InteractiveMode {
private closeHeartbeatManager(): void {
this.clearHeartbeatManagerRefreshTimer();
+ this.clearHeartbeatManagerFetchRetryTimer();
this.heartbeatManagerHandle?.hide();
this.heartbeatManagerHandle = undefined;
this.heartbeatManager = undefined;
@@ -10012,10 +10075,64 @@ export class InteractiveMode {
this.heartbeatManagerRefreshAt = undefined;
}
+ private retainHeartbeatCatalogFetch(
+ fetch: Promise<AgentConnectionHeartbeat[]>,
+ connection: AgentConnection,
+ seq: number,
+ ): void {
+ // The deadline expired while this fetch was still in flight: apply the
+ // late result when it lands so the open view converges even without a
+ // further heartbeats_changed event. Bounded by the same context guards
+ // as the drain loop and by the write sequence, so a superseded result
+ // cannot revert newer catalog state; a late failure is swallowed (the
+ // retry chain owns recovery from it).
+ void fetch
+ .then((heartbeats) => {
+ if (this.isShuttingDown || this.isReturningToAgentsView || this.agentConnection !== connection) {
+ return;
+ }
+ this.applyHeartbeatCatalog(heartbeats, seq);
+ })
+ .catch(() => undefined);
+ }
+
+ private armHeartbeatManagerFetchRetry(): void {
+ // Guarantee the open manager always has a next scheduled retrieval
+ // after a deadline expiry; a still-armed retry keeps the earliest slot.
+ if (!this.heartbeatManager || this.heartbeatManagerFetchRetryTimer) return;
+ this.heartbeatManagerFetchRetryTimer = setTimeout(() => {
+ this.heartbeatManagerFetchRetryTimer = undefined;
+ if (!this.heartbeatManager) return;
+ void this.refreshHeartbeatCatalog().catch((error) => this.onHeartbeatCatalogFetchError(error));
+ }, HEARTBEAT_REFRESH_RETRY_DELAY_MS);
+ this.heartbeatManagerFetchRetryTimer.unref?.();
+ }
+
+ private clearHeartbeatManagerFetchRetryTimer(): void {
+ if (this.heartbeatManagerFetchRetryTimer) {
+ clearTimeout(this.heartbeatManagerFetchRetryTimer);
+ this.heartbeatManagerFetchRetryTimer = undefined;
+ }
+ }
+
+ private onHeartbeatCatalogFetchError(error: unknown): void {
+ // Stale-while-revalidate opens the manager even when the fetch fails;
+ // surface the failure in the view instead of silently showing a stale
+ // catalog, and keep a next retrieval scheduled.
+ this.heartbeatCatalogFetchError = error instanceof Error ? error.message : String(error);
+ this.armHeartbeatManagerFetchRetry();
+ this.scheduleHeartbeatManagerRefresh();
+ this.ui.requestRender();
+ }
+
private async manageHeartbeat(
heartbeat: AgentConnectionHeartbeat,
action: AgentHeartbeatManagementAction,
): Promise<void> {
+ // Sequence the action by issue order so an older in-flight fetch
+ // cannot later revert its result; the action itself is authoritative
+ // and always applies.
+ const actionSeq = ++this.heartbeatCatalogSeq;
const updated = await this.agentConnection.manageHeartbeat(
heartbeat.job.activeSessionId,
heartbeat.job.id,
@@ -10024,6 +10141,7 @@ export class InteractiveMode {
if (updated.source === "heartbeat" && updated.activeSessionId === this.connectionState?.activeSessionId) {
this.patchConnectionState({ heartbeat: action === "stop" ? null : updated });
}
+ this.heartbeatCatalogAppliedSeq = Math.max(this.heartbeatCatalogAppliedSeq, actionSeq);
const remaining = this.heartbeatCatalog.filter((entry) => entry.job.id !== updated.id);
this.applyHeartbeatCatalog(
updated.status === "active" || updated.status === "paused"
diff --git a/packages/coding-agent/test/interactive-heartbeat-management.test.ts b/packages/coding-agent/test/interactive-heartbeat-management.test.ts
index 664779e00e..d891331bd8 100644
--- a/packages/coding-agent/test/interactive-heartbeat-management.test.ts
+++ b/packages/coding-agent/test/interactive-heartbeat-management.test.ts
@@ -1,10 +1,19 @@
-import { describe, expect, it, vi } from "vitest";
+import { setKeybindings } from "@earendil-works/pi-tui";
+import stripAnsi from "strip-ansi";
+import { beforeAll, describe, expect, it, vi } from "vitest";
import type { AgentCronJob, AgentHeartbeatManagementAction } from "../src/core/cron-jobs.js";
+import { KeybindingsManager } from "../src/core/keybindings.js";
import type {
AgentConnectionHeartbeat,
AgentConnectionRlmChildAgentSnapshot,
} from "../src/modes/agent-connection/types.js";
-import { InteractiveMode } from "../src/modes/interactive/interactive-mode.js";
+import type { HeartbeatManagerComponent } from "../src/modes/interactive/components/heartbeat-manager.js";
+import {
+ HEARTBEAT_REFRESH_FETCH_TIMEOUT_MS,
+ HEARTBEAT_REFRESH_RETRY_DELAY_MS,
+ InteractiveMode,
+} from "../src/modes/interactive/interactive-mode.js";
+import { initTheme } from "../src/modes/interactive/theme/theme.js";
interface HeartbeatManagementHarness {
heartbeatCatalog: AgentConnectionHeartbeat[];
@@ -246,3 +255,546 @@ describe("interactive heartbeat management", () => {
}
});
});
+
+interface HeartbeatManagerOpenHarness {
+ heartbeatManager: HeartbeatManagerComponent | undefined;
+ heartbeatManagerHandle: { focus(): void; hide(): void } | undefined;
+ heartbeatCatalog: AgentConnectionHeartbeat[];
+ heartbeatRefreshPromise: Promise<void> | undefined;
+ heartbeatRefreshRequested: boolean;
+ heartbeatManagerFetchRetryTimer: ReturnType<typeof setTimeout> | undefined;
+ heartbeatManagerRefreshTimer: ReturnType<typeof setTimeout> | undefined;
+ heartbeatManagerRefreshAt: number | undefined;
+ heartbeatCatalogSeq: number;
+ heartbeatCatalogAppliedSeq: number;
+ connectionState: { activeSessionId: string; sessionId: string };
+ subagentSnapshots: Map<string, AgentConnectionRlmChildAgentSnapshot>;
+ agentConnection: {
+ listHeartbeats(): Promise<AgentConnectionHeartbeat[]>;
+ manageHeartbeat?(
+ activeSessionId: string,
+ jobId: string,
+ action: AgentHeartbeatManagementAction,
+ ): Promise<AgentCronJob>;
+ };
+ isShuttingDown: boolean;
+ isReturningToAgentsView: boolean;
+ ui: {
+ requestRender(): void;
+ terminal: { rows: number };
+ showOverlay(): { focus(): void; hide(): void };
+ };
+ patchConnectionState(patch: { heartbeat: AgentCronJob | null }): void;
+ scheduleHeartbeatManagerRefresh(): void;
+ updateSubagentSummaryLine(): void;
+ refreshHeartbeatCatalog(): Promise<void>;
+ showHeartbeatManager(): void;
+ manageHeartbeat(heartbeat: AgentConnectionHeartbeat, action: AgentHeartbeatManagementAction): Promise<void>;
+}
+
+interface HeartbeatCommandHarness {
+ defaultEditor: { onSubmit?: (text: string) => Promise<void> };
+ editor: { getText(): string; setText(text: string): void };
+ agentConnection: { prompt(text: string): Promise<unknown> };
+ showError(message: string): void;
+ heartbeatManagerHandle: { focus(): void; hide(): void } | undefined;
+ heartbeatCatalog: AgentConnectionHeartbeat[];
+ refreshHeartbeatCatalog(): Promise<void>;
+ refreshHeartbeatCatalogCalled?: boolean;
+ ui: {
+ requestRender(): void;
+ terminal: { rows: number };
+ showOverlay(): { focus(): void; hide(): void };
+ };
+ [key: string]: unknown;
+}
+
+const setupEditorSubmitHandlerPrototype = (
+ InteractiveMode.prototype as unknown as {
+ setupEditorSubmitHandler(this: unknown): void;
+ }
+).setupEditorSubmitHandler;
+
+describe("interactive heartbeat manager open (stale-while-revalidate)", () => {
+ beforeAll(() => {
+ initTheme("dark");
+ setKeybindings(new KeybindingsManager());
+ });
+
+ const overlayHandle = { focus: vi.fn(), hide: vi.fn() };
+
+ function makeOpenHarness(options?: {
+ listHeartbeats?: () => Promise<AgentConnectionHeartbeat[]>;
+ /** Keep the real nextRunAt poll scheduling instead of a mock. */
+ realSchedule?: boolean;
+ }): {
+ harness: HeartbeatManagerOpenHarness;
+ requestRender: ReturnType<typeof vi.fn>;
+ } {
+ const requestRender = vi.fn();
+ const harness = Object.create(InteractiveMode.prototype) as HeartbeatManagerOpenHarness;
+ harness.heartbeatManager = undefined;
+ harness.heartbeatManagerHandle = undefined;
+ harness.heartbeatCatalog = [{ job: heartbeat() }];
+ harness.heartbeatRefreshPromise = undefined;
+ harness.heartbeatRefreshRequested = false;
+ harness.heartbeatManagerFetchRetryTimer = undefined;
+ harness.heartbeatManagerRefreshTimer = undefined;
+ harness.heartbeatManagerRefreshAt = undefined;
+ // Prototype-only harnesses skip the constructor, so sequence fields
+ // must be seeded explicitly.
+ harness.heartbeatCatalogSeq = 0;
+ harness.heartbeatCatalogAppliedSeq = 0;
+ harness.connectionState = { activeSessionId: "active-1", sessionId: "session-1" };
+ harness.subagentSnapshots = new Map([
+ [
+ "child-1",
+ {
+ id: "child-1",
+ activeSessionId: "active-2",
+ label: "child",
+ status: "running",
+ sessionDir: "/tmp/child-1",
+ },
+ ],
+ ]);
+ harness.agentConnection = {
+ listHeartbeats: options?.listHeartbeats ?? vi.fn(() => new Promise<AgentConnectionHeartbeat[]>(() => {})),
+ };
+ harness.isShuttingDown = false;
+ harness.isReturningToAgentsView = false;
+ harness.ui = {
+ requestRender,
+ terminal: { rows: 24 },
+ showOverlay: vi.fn(() => overlayHandle),
+ };
+ harness.patchConnectionState = vi.fn();
+ if (options?.realSchedule) {
+ harness.scheduleHeartbeatManagerRefresh = (
+ InteractiveMode.prototype as unknown as {
+ scheduleHeartbeatManagerRefresh(this: HeartbeatManagerOpenHarness): void;
+ }
+ ).scheduleHeartbeatManagerRefresh;
+ } else {
+ harness.scheduleHeartbeatManagerRefresh = vi.fn();
+ }
+ harness.updateSubagentSummaryLine = vi.fn();
+ return { harness, requestRender };
+ }
+
+ function renderedManager(manager: NonNullable<HeartbeatManagerOpenHarness["heartbeatManager"]>): string {
+ return stripAnsi(manager.render(100).join("\n"));
+ }
+
+ it("opens immediately with the cached catalog while the fetch hangs, then updates when data lands", async () => {
+ let resolveFetch: (heartbeats: AgentConnectionHeartbeat[]) => void = () => {};
+ const listHeartbeats = vi.fn(
+ () =>
+ new Promise<AgentConnectionHeartbeat[]>((resolve) => {
+ resolveFetch = resolve;
+ }),
+ );
+ const { harness, requestRender } = makeOpenHarness({ listHeartbeats });
+
+ harness.showHeartbeatManager();
+
+ // The overlay must open synchronously with the cached catalog, before the fetch settles.
+ expect(listHeartbeats).toHaveBeenCalledOnce();
+ expect(harness.heartbeatManagerHandle).toBe(overlayHandle);
+ expect(harness.heartbeatManager).toBeDefined();
+ expect(renderedManager(harness.heartbeatManager!)).toContain("1 heartbeat.");
+
+ // Input keeps working while the fetch is still in flight.
+ harness.heartbeatManager!.handleInput("\x1b[B");
+ expect(requestRender).toHaveBeenCalled();
+
+ // Fresh data lands: the still-open view updates through the live catalog getter.
+ resolveFetch([
+ { job: heartbeat() },
+ {
+ job: heartbeat({
+ id: "heartbeat-2",
+ activeSessionId: "active-2",
+ sessionId: "session-2",
+ sessionFile: "/tmp/session-2.jsonl",
+ status: "paused",
+ nextRunAt: undefined,
+ }),
+ },
+ ]);
+ const refreshed = Promise.race([
+ harness.heartbeatRefreshPromise ?? Promise.resolve(),
+ new Promise<never>((_, reject) => setTimeout(() => reject(new Error("refresh deadline")), 1_000)),
+ ]);
+ await expect(refreshed).resolves.toBeUndefined();
+ expect(renderedManager(harness.heartbeatManager!)).toContain("2 heartbeats · 1 paused");
+ });
+
+ it("keeps the stale catalog usable when the fetch deadline expires", { timeout: 10_000 }, async () => {
+ vi.useFakeTimers();
+ try {
+ const { harness } = makeOpenHarness({
+ listHeartbeats: () => new Promise<AgentConnectionHeartbeat[]>(() => {}),
+ });
+
+ harness.showHeartbeatManager();
+ expect(harness.heartbeatManager).toBeDefined();
+ const refresh = harness.heartbeatRefreshPromise;
+ expect(refresh).toBeDefined();
+
+ await vi.advanceTimersByTimeAsync(HEARTBEAT_REFRESH_FETCH_TIMEOUT_MS + 10);
+
+ // The deadline settles the refresh quietly: no rejection, no stale overwrite.
+ await expect(refresh).resolves.toBeUndefined();
+ expect(harness.heartbeatCatalog).toEqual([{ job: heartbeat() }]);
+ expect(harness.updateSubagentSummaryLine).not.toHaveBeenCalled();
+ expect(harness.heartbeatRefreshPromise).toBeUndefined();
+
+ // The open view stays usable with the stale catalog.
+ expect(renderedManager(harness.heartbeatManager!)).toContain("1 heartbeat.");
+ harness.heartbeatManager!.handleInput("\x1b[B");
+ expect(harness.ui.requestRender).toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("retries after the deadline when heartbeats_changed arrived mid-fetch", { timeout: 10_000 }, async () => {
+ vi.useFakeTimers();
+ try {
+ const fresh: AgentConnectionHeartbeat[] = [
+ { job: heartbeat() },
+ {
+ job: heartbeat({
+ id: "heartbeat-2",
+ activeSessionId: "active-2",
+ sessionId: "session-2",
+ sessionFile: "/tmp/session-2.jsonl",
+ status: "paused",
+ nextRunAt: undefined,
+ }),
+ },
+ ];
+ const listHeartbeats = vi.fn(() => new Promise<AgentConnectionHeartbeat[]>(() => {}));
+ listHeartbeats.mockImplementationOnce(() => new Promise<AgentConnectionHeartbeat[]>(() => {}));
+ listHeartbeats.mockImplementationOnce(() => Promise.resolve(fresh));
+ const { harness } = makeOpenHarness({ listHeartbeats });
+
+ const first = harness.refreshHeartbeatCatalog();
+ // A heartbeats_changed event coalesces into the in-flight refresh.
+ const joined = harness.refreshHeartbeatCatalog();
+ await vi.advanceTimersByTimeAsync(HEARTBEAT_REFRESH_FETCH_TIMEOUT_MS + 10);
+ await expect(first).resolves.toBeUndefined();
+ await expect(joined).resolves.toBeUndefined();
+
+ // The drained follow-up refresh fetches again and converges.
+ await vi.advanceTimersByTimeAsync(10);
+ expect(listHeartbeats).toHaveBeenCalledTimes(2);
+ expect(harness.heartbeatCatalog).toEqual(fresh);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("retries a timed-out initial fetch on a short cadence so the open view converges", {
+ timeout: 10_000,
+ }, async () => {
+ vi.useFakeTimers();
+ try {
+ // No heartbeats_changed event arrives and the empty catalog has no
+ // nextRunAt for the poll to schedule from: only the retry chain can
+ // guarantee the open view a next retrieval.
+ const fresh: AgentConnectionHeartbeat[] = [{ job: heartbeat() }];
+ const listHeartbeats = vi.fn(() => Promise.resolve(fresh));
+ listHeartbeats.mockImplementationOnce(() => new Promise<AgentConnectionHeartbeat[]>(() => {}));
+ const { harness } = makeOpenHarness({ listHeartbeats });
+ harness.heartbeatCatalog = [];
+
+ harness.showHeartbeatManager();
+ expect(renderedManager(harness.heartbeatManager!)).toContain("No running or paused heartbeats");
+
+ // The deadline expires quietly: the stale catalog stays, but the
+ // view must not be left without a next scheduled retrieval.
+ await vi.advanceTimersByTimeAsync(HEARTBEAT_REFRESH_FETCH_TIMEOUT_MS + 10);
+ expect(listHeartbeats).toHaveBeenCalledTimes(1);
+ expect(harness.heartbeatManagerFetchRetryTimer).toBeDefined();
+ expect(harness.heartbeatCatalog).toEqual([]);
+
+ // The bounded retry fires and converges the open view.
+ await vi.advanceTimersByTimeAsync(HEARTBEAT_REFRESH_RETRY_DELAY_MS + 10);
+ expect(listHeartbeats).toHaveBeenCalledTimes(2);
+ expect(harness.heartbeatCatalog).toEqual(fresh);
+ expect(renderedManager(harness.heartbeatManager!)).toContain("1 heartbeat.");
+ expect(harness.updateSubagentSummaryLine).toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("applies the late result to the open view after the fetch deadline expired", { timeout: 10_000 }, async () => {
+ vi.useFakeTimers();
+ try {
+ let resolveFetch: (heartbeats: AgentConnectionHeartbeat[]) => void = () => {};
+ const listHeartbeats = vi.fn(
+ () =>
+ new Promise<AgentConnectionHeartbeat[]>((resolve) => {
+ resolveFetch = resolve;
+ }),
+ );
+ const { harness } = makeOpenHarness({ listHeartbeats });
+
+ harness.showHeartbeatManager();
+ const refresh = harness.heartbeatRefreshPromise;
+ expect(refresh).toBeDefined();
+
+ await vi.advanceTimersByTimeAsync(HEARTBEAT_REFRESH_FETCH_TIMEOUT_MS + 10);
+ await expect(refresh).resolves.toBeUndefined();
+ // The deadline kept the stale catalog...
+ expect(harness.heartbeatCatalog).toEqual([{ job: heartbeat() }]);
+ expect(harness.updateSubagentSummaryLine).not.toHaveBeenCalled();
+
+ // ...but the retained fetch must still land in the open view.
+ const fresh: AgentConnectionHeartbeat[] = [
+ { job: heartbeat() },
+ {
+ job: heartbeat({
+ id: "heartbeat-2",
+ activeSessionId: "active-2",
+ sessionId: "session-2",
+ sessionFile: "/tmp/session-2.jsonl",
+ status: "paused",
+ nextRunAt: undefined,
+ }),
+ },
+ ];
+ resolveFetch(fresh);
+ await vi.advanceTimersByTimeAsync(10);
+ await Promise.resolve();
+
+ expect(listHeartbeats).toHaveBeenCalledTimes(1);
+ expect(harness.heartbeatCatalog).toEqual(fresh);
+ expect(harness.updateSubagentSummaryLine).toHaveBeenCalled();
+ expect(renderedManager(harness.heartbeatManager!)).toContain("2 heartbeats · 1 paused");
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("opens with a visible failure state when the initial fetch rejects, then recovers on the retry", {
+ timeout: 10_000,
+ }, async () => {
+ vi.useFakeTimers();
+ try {
+ const fresh: AgentConnectionHeartbeat[] = [{ job: heartbeat() }];
+ const listHeartbeats = vi.fn(() => Promise.resolve(fresh));
+ listHeartbeats.mockImplementationOnce(() => Promise.reject(new Error("worker recovering")));
+ const { harness } = makeOpenHarness({ listHeartbeats });
+
+ harness.showHeartbeatManager();
+ // The manager must still open without waiting for the fetch.
+ expect(harness.heartbeatManagerHandle).toBe(overlayHandle);
+ await vi.advanceTimersByTimeAsync(10);
+
+ // The rejection surfaces in the view instead of a silent stale catalog.
+ const rendered = renderedManager(harness.heartbeatManager!);
+ expect(rendered).toContain("Heartbeat refresh failed: worker recovering");
+ expect(rendered).toContain("1 heartbeat.");
+ // A failed fetch still leaves the open view a next scheduled retrieval.
+ expect(harness.heartbeatManagerFetchRetryTimer).toBeDefined();
+
+ // The retry recovers: fresh data lands and the failure notice clears.
+ await vi.advanceTimersByTimeAsync(HEARTBEAT_REFRESH_RETRY_DELAY_MS + 10);
+ expect(listHeartbeats).toHaveBeenCalledTimes(2);
+ expect(harness.heartbeatCatalog).toEqual(fresh);
+ const recovered = renderedManager(harness.heartbeatManager!);
+ expect(recovered).not.toContain("Heartbeat refresh failed");
+ expect(recovered).toContain("1 heartbeat.");
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("keeps a next retrieval scheduled after a timed-out poll", { timeout: 10_000 }, async () => {
+ vi.useFakeTimers();
+ try {
+ // Overdue heartbeat: the nextRunAt poll falls back to the 5s cadence.
+ vi.setSystemTime(new Date("2026-01-01T00:10:00.000Z"));
+ const listHeartbeats = vi.fn(() => new Promise<AgentConnectionHeartbeat[]>(() => {}));
+ const { harness } = makeOpenHarness({ listHeartbeats, realSchedule: true });
+
+ harness.showHeartbeatManager();
+ expect(listHeartbeats).toHaveBeenCalledTimes(1);
+
+ // The overdue poll fires and joins the in-flight initial fetch.
+ await vi.advanceTimersByTimeAsync(5_250);
+ expect(listHeartbeats).toHaveBeenCalledTimes(1);
+
+ // That fetch times out: the poll is spent and nothing applied, yet
+ // the retry chain keeps a next retrieval armed and the follow-up
+ // refresh issued. The view must never go quiet from here.
+ await vi.advanceTimersByTimeAsync(4_760);
+ expect(listHeartbeats).toHaveBeenCalledTimes(2);
+ expect(harness.heartbeatManagerFetchRetryTimer).toBeDefined();
+
+ await vi.advanceTimersByTimeAsync(10_010);
+ expect(listHeartbeats).toHaveBeenCalledTimes(3);
+ await vi.advanceTimersByTimeAsync(10_010);
+ expect(listHeartbeats).toHaveBeenCalledTimes(4);
+ await vi.advanceTimersByTimeAsync(10_010);
+ expect(listHeartbeats).toHaveBeenCalledTimes(5);
+
+ // All those fetches timed out: the view kept its stale catalog and
+ // still never lacked a next scheduled retrieval.
+ expect(harness.heartbeatCatalog).toEqual([{ job: heartbeat() }]);
+ expect(harness.updateSubagentSummaryLine).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("does not overwrite a newer catalog with a late timed-out fetch result", { timeout: 10_000 }, async () => {
+ vi.useFakeTimers();
+ try {
+ const resolvers: Array<(heartbeats: AgentConnectionHeartbeat[]) => void> = [];
+ const listHeartbeats = vi.fn(
+ () =>
+ new Promise<AgentConnectionHeartbeat[]>((resolve) => {
+ resolvers.push(resolve);
+ }),
+ );
+ const { harness } = makeOpenHarness({ listHeartbeats });
+
+ harness.showHeartbeatManager();
+ // The initial fetch times out and is retained.
+ await vi.advanceTimersByTimeAsync(HEARTBEAT_REFRESH_FETCH_TIMEOUT_MS + 10);
+
+ // The retry fetch lands first with fresh data.
+ await vi.advanceTimersByTimeAsync(HEARTBEAT_REFRESH_RETRY_DELAY_MS + 10);
+ expect(resolvers.length).toBe(2);
+ const fresh: AgentConnectionHeartbeat[] = [{ job: heartbeat({ id: "heartbeat-9" }) }];
+ resolvers[1]?.(fresh);
+ await vi.advanceTimersByTimeAsync(10);
+ await Promise.resolve();
+ expect(harness.heartbeatCatalog).toEqual(fresh);
+
+ // The older timed-out fetch resolves last: it must not overwrite.
+ const stale: AgentConnectionHeartbeat[] = [{ job: heartbeat() }, { job: heartbeat({ id: "heartbeat-8" }) }];
+ resolvers[0]?.(stale);
+ await vi.advanceTimersByTimeAsync(10);
+ await Promise.resolve();
+
+ expect(harness.heartbeatCatalog).toEqual(fresh);
+ expect(harness.updateSubagentSummaryLine).toHaveBeenCalledTimes(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("does not let a late timed-out fetch revert a local heartbeat action", { timeout: 10_000 }, async () => {
+ vi.useFakeTimers();
+ try {
+ const resolvers: Array<(heartbeats: AgentConnectionHeartbeat[]) => void> = [];
+ const listHeartbeats = vi.fn(
+ () =>
+ new Promise<AgentConnectionHeartbeat[]>((resolve) => {
+ resolvers.push(resolve);
+ }),
+ );
+ const current = heartbeat();
+ const paused = { ...current, status: "paused" as const, nextRunAt: undefined };
+ const { harness } = makeOpenHarness({ listHeartbeats });
+ harness.agentConnection = {
+ listHeartbeats,
+ manageHeartbeat: vi.fn(async () => paused),
+ };
+
+ harness.showHeartbeatManager();
+ // The user pauses while the initial fetch is still in flight.
+ await harness.manageHeartbeat({ job: current }, "pause");
+ expect(harness.heartbeatCatalog).toEqual([{ job: paused }]);
+
+ // The initial fetch times out and is retained.
+ await vi.advanceTimersByTimeAsync(HEARTBEAT_REFRESH_FETCH_TIMEOUT_MS + 10);
+
+ // The pre-pause snapshot lands late: it must not revert the pause.
+ resolvers[0]?.([{ job: current }]);
+ await vi.advanceTimersByTimeAsync(10);
+ await Promise.resolve();
+
+ expect(harness.heartbeatCatalog).toEqual([{ job: paused }]);
+ expect(renderedManager(harness.heartbeatManager!)).toContain("1 paused");
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
+describe("interactive /heartbeats command", () => {
+ beforeAll(() => {
+ initTheme("dark");
+ setKeybindings(new KeybindingsManager());
+ });
+
+ it("opens the manager without waiting for the catalog fetch", async () => {
+ const overlayHandle = { focus: vi.fn(), hide: vi.fn() };
+ let editorText = "";
+ const refreshHeartbeatCatalog = vi.fn(() => new Promise<void>(() => {}));
+ const context = Object.create(InteractiveMode.prototype) as HeartbeatCommandHarness;
+ Object.assign(context, {
+ defaultEditor: {} as { onSubmit?: (text: string) => Promise<void> },
+ editor: {
+ getText: () => editorText,
+ setText: (text: string) => {
+ editorText = text;
+ },
+ },
+ agentConnection: { prompt: vi.fn(async () => undefined) },
+ // Only settingsManager is read on the /heartbeats path (telemetry
+ // capture is fire-and-forget), so a minimal uiServices suffices.
+ uiServices: { settingsManager: {} },
+ showError: vi.fn(),
+ showStatus: vi.fn(),
+ echoLocalCommand: vi.fn(),
+ submittedInputBehavior: "steer",
+ inputSubmissionGeneration: 0,
+ inputSubmissionsPending: 0,
+ pendingPromptStashReleases: [],
+ promptStashState: {},
+ pendingSubmittedPromptStash: undefined,
+ snapshotPromptStash: vi.fn(() => ({ text: "" })),
+ promptStash: undefined,
+ promptStashSessionId: "session-1",
+ sessionId: "session-1",
+ clearShortcutGuide: vi.fn(),
+ // Support for the real showHeartbeatManager: a fetch that never settles.
+ heartbeatManager: undefined,
+ heartbeatManagerHandle: undefined,
+ heartbeatCatalog: [{ job: heartbeat() }],
+ heartbeatRefreshPromise: undefined,
+ heartbeatRefreshRequested: false,
+ connectionState: { activeSessionId: "active-1", sessionId: "session-1" },
+ subagentSnapshots: new Map(),
+ refreshHeartbeatCatalog,
+ ui: {
+ requestRender: vi.fn(),
+ terminal: { rows: 24 },
+ showOverlay: vi.fn(() => overlayHandle),
+ },
+ scheduleHeartbeatManagerRefresh: vi.fn(),
+ updateSubagentSummaryLine: vi.fn(),
+ });
+
+ setupEditorSubmitHandlerPrototype.call(context);
+ const submitted = context.defaultEditor.onSubmit?.("/heartbeats");
+ expect(submitted).toBeDefined();
+
+ // The submit handler must settle without the fetch: bound the wait explicitly.
+ const outcome = await Promise.race([
+ submitted!.then(() => "settled" as const),
+ new Promise<"deadline">((resolve) => setTimeout(() => resolve("deadline"), 1_000)),
+ ]);
+ expect(outcome).toBe("settled");
+ expect(context.heartbeatManagerHandle).toBe(overlayHandle);
+ expect(refreshHeartbeatCatalog).toHaveBeenCalledOnce();
+ });
+});