A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
add heartbeat observability and management (#425)
kt90b841996aba
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.mdindex 80cb44b09e..dacf2e36c4 100644--- a/packages/coding-agent/CHANGELOG.md+++ b/packages/coding-agent/CHANGELOG.md@@ -4,6 +4,7 @@- Fixed unsupported Node versions crashing before startup by requiring Node 22.8.0 or newer and showing upgrade guidance before loading the CLI ([ENG-4260](https://linear.app/primeintellect/issue/ENG-4260/incorrect-node-version-breaks-first-launch)).- Added `@` file-path autocomplete to new-agent and reply prompts in the Agents View.+- Added a combined heartbeat indicator and manager for pausing, resuming, or stopping user and agent heartbeats ([ENG-4536](https://linear.app/primeintellect/issue/ENG-4536/add-heartbeat-observability-and-management-ui)).## [0.3.1] - 2026-07-15diff --git a/packages/coding-agent/skills/rlm-heartbeat/SKILL.md b/packages/coding-agent/skills/rlm-heartbeat/SKILL.mdindex 6ee2d995d8..995f744c91 100644--- a/packages/coding-agent/skills/rlm-heartbeat/SKILL.md+++ b/packages/coding-agent/skills/rlm-heartbeat/SKILL.md@@ -1,6 +1,6 @@---name: rlm-heartbeat-description: Manage internal RLM heartbeats from IPython. Use to schedule recurring self-checks for the current agent session without touching the user's /heartbeat.+description: Manage agent-owned RLM heartbeats from IPython. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user's /heartbeat.---# RLM Heartbeat@@ -44,6 +44,8 @@ the session when it is busy:## Rules+- Use this when the user asks you to start, create, schedule, or manage your own+ heartbeat without explicitly referring to `/heartbeat`.- Use this only for agent-internal recurring checks and long-running taskcoordination.- Do not use this skill to satisfy a user's request to configure `/heartbeat`;diff --git a/packages/coding-agent/src/core/cron-jobs.ts b/packages/coding-agent/src/core/cron-jobs.tsindex 5e5717ba58..9a2c177e42 100644--- a/packages/coding-agent/src/core/cron-jobs.ts+++ b/packages/coding-agent/src/core/cron-jobs.ts@@ -11,14 +11,13 @@ import {} from "node:fs";import { dirname, join, resolve } from "node:path";import { lockSync } from "proper-lockfile";-import { Type } from "typebox";-import type { ToolDefinition } from "./extensions/types.js";export type AgentCronJobStatus = "active" | "paused" | "completed" | "cancelled";export type AgentCronScheduleKind = "once" | "cron" | "interval";export type AgentCronJobSource = "cron" | "heartbeat" | "rlm_heartbeat";export type AgentCronJobRuntimeKind = "top-level" | "subagent";export type AgentHeartbeatUpdateAction = "pause" | "resume" | "clear";+export type AgentHeartbeatManagementAction = "pause" | "resume" | "stop";export type AgentRlmHeartbeatStatusUpdate = "pause" | "resume";/*** How a scheduled heartbeat prompt is delivered when the target session is busy:@@ -123,10 +122,6 @@ export type ParsedHeartbeatCommand =| { type: "clear" }| { type: "set"; schedule: string; instruction: string; deliveryMode?: AgentHeartbeatDeliveryMode };-export interface AgentCronToolController {- getHeartbeat(): AgentCronJob | undefined;-}-export interface AgentRlmHeartbeatController {listRlmHeartbeats(options?: { includeInactive?: boolean }): AgentCronJob[];createRlmHeartbeat(input: {@@ -146,8 +141,32 @@ export interface AgentRlmHeartbeatController {deleteRlmHeartbeat(id: string): AgentCronJob | undefined;}+function heartbeatCatalogSignature(jobs: readonly AgentCronJob[]): string {+ return JSON.stringify(+ jobs+ .filter((job) => isHeartbeatCronJob(job) && (job.status === "active" || job.status === "paused"))+ .sort((left, right) => left.id.localeCompare(right.id))+ .map((job) => ({+ id: job.id,+ status: job.status,+ source: job.source,+ runtimeKind: job.runtimeKind,+ deliveryMode: job.deliveryMode,+ activeSessionId: job.activeSessionId,+ sessionId: job.sessionId,+ sessionFile: job.sessionFile,+ cwd: job.cwd,+ label: job.label,+ prompt: job.prompt,+ schedule: job.schedule,+ createdAt: job.createdAt,+ })),+ );+}+export class AgentCronJobStore {private readonly sessionArtifactFiles = new Map<string, string>();+ private readonly heartbeatChangeListeners = new Set<() => void>();constructor(private readonly filePath?: string,@@ -162,6 +181,11 @@ export class AgentCronJobStore {return new AgentCronJobStore(undefined, true);}+ onHeartbeatChange(listener: () => void): () => void {+ this.heartbeatChangeListeners.add(listener);+ return () => this.heartbeatChangeListeners.delete(listener);+ }+registerSessionArtifact(sessionId: string, artifactDir: string): boolean {if (!this.sessionArtifactMode) {return false;@@ -553,6 +577,46 @@ export class AgentCronJobStore {return cleared;}+ manageHeartbeat(+ activeSessionId: string,+ id: string,+ action: AgentHeartbeatManagementAction,+ now = new Date(),+ ): AgentCronJob | undefined {+ let updated: AgentCronJob | undefined;+ const jobs = this.readJobs().map((job) => {+ if (job.id !== id || job.activeSessionId !== activeSessionId || !isHeartbeatCronJob(job)) {+ return job;+ }+ if (job.status === "cancelled" || job.status === "completed") {+ return job;+ }+ if (action === "pause") {+ updated = withoutNextRunAt({ ...job, status: "paused", updatedAt: now.toISOString() });+ return updated;+ }+ if (action === "stop") {+ updated = withoutNextRunAt({ ...job, status: "cancelled", updatedAt: now.toISOString() });+ return updated;+ }+ const nextRunAt = nextRunAtForSchedule(job.schedule, now);+ if (!nextRunAt) {+ throw new Error("Heartbeat schedule must be recurring");+ }+ updated = {+ ...job,+ status: "active",+ nextRunAt: nextRunAt.toISOString(),+ updatedAt: now.toISOString(),+ };+ return updated;+ });+ if (updated) {+ this.writeJobs(jobs);+ }+ return updated;+ }+cancel(id: string, now = new Date()): AgentCronJob | undefined {let cancelled: AgentCronJob | undefined;const jobs = this.readJobs().map((job) => {@@ -724,7 +788,9 @@ export class AgentCronJobStore {private mutateStates(mutator: (state: CronJobsState) => AgentCronDispatch[]): AgentCronDispatch[] {const paths = this.sessionArtifactMode ? [...this.sessionArtifactFiles.values()] : [this.requireFilePath()];- return withCronJobsStateLocks(paths, () => {+ const previousHeartbeats = heartbeatCatalogSignature(this.readJobs());+ let changed = false;+ const dispatches = withCronJobsStateLocks(paths, () => {const dispatches: AgentCronDispatch[] = [];for (const path of paths) {const state = readJobsState(path);@@ -732,13 +798,19 @@ export class AgentCronJobStore {dispatches.push(...mutator(state));if (JSON.stringify(state) !== before) {writeJobsState(path, state);+ changed = true;}}return dispatches;});+ if (changed && heartbeatCatalogSignature(this.readJobs()) !== previousHeartbeats) {+ this.notifyHeartbeatChange();+ }+ return dispatches;}private writeJobs(jobs: readonly AgentCronJob[]): void {+ const previousHeartbeats = heartbeatCatalogSignature(this.readJobs());if (this.sessionArtifactMode) {const registeredSessionIds = new Set(this.sessionArtifactFiles.keys());const unregistered = jobs.find((job) => !registeredSessionIds.has(job.sessionId));@@ -782,10 +854,22 @@ export class AgentCronJobStore {}}});+ if (heartbeatCatalogSignature(this.readJobs()) !== previousHeartbeats) {+ this.notifyHeartbeatChange();+ }return;}const path = this.requireFilePath();withCronJobsStateLocks([path], () => writeJobsFile(path, jobs, true));+ if (heartbeatCatalogSignature(this.readJobs()) !== previousHeartbeats) {+ this.notifyHeartbeatChange();+ }+ }++ private notifyHeartbeatChange(): void {+ for (const listener of this.heartbeatChangeListeners) {+ listener();+ }}private requireFilePath(): string {@@ -1132,27 +1216,6 @@ export function formatAgentCronJob(job: AgentCronJob): string {return `${job.id} ${job.status}${label} next=${next} last=${last}${skipped} runs=${job.runCount} schedule="${job.schedule.expression}" prompt="${preview}"${error}`;}-export function createAgentHeartbeatToolDefinitions(controller: AgentCronToolController): ToolDefinition[] {- return [- {- name: "get_heartbeat",- label: "Get Heartbeat",- description: "Get the persistent heartbeat configured for this daemon-backed session, if one exists.",- promptGuidelines: [- "Use get_heartbeat to inspect the current heartbeat before changing it, or when the user asks about heartbeat status.",- ],- parameters: Type.Object({}, { additionalProperties: false }),- execute: async () => {- const job = controller.getHeartbeat();- return {- content: [{ type: "text", text: JSON.stringify({ heartbeat: job ?? null }, null, 2) }],- details: job ?? null,- };- },- },- ];-}-function consumeDeliveryOption(text: string): { deliveryMode: AgentHeartbeatDeliveryMode | undefined; rest: string } {let rest = text.trim();if (/(?:^|\s)--deliver=?$/i.test(rest)) {diff --git a/packages/coding-agent/src/core/keybindings.ts b/packages/coding-agent/src/core/keybindings.tsindex 0de5087145..22f9a96ad2 100644--- a/packages/coding-agent/src/core/keybindings.ts+++ b/packages/coding-agent/src/core/keybindings.ts@@ -24,6 +24,8 @@ export interface AppKeybindings {"app.tools.expand": true;"app.thinking.toggle": true;"app.subagents.focus": true;+ "app.heartbeats.open": true;+ "app.heartbeats.openSelected": true;"app.session.toggleNamedFilter": true;"app.editor.external": true;"app.prompt.stash": true;@@ -95,6 +97,14 @@ export const KEYBINDINGS = {defaultKeys: "alt+a",description: "Open child agents",},+ "app.heartbeats.open": {+ defaultKeys: "ctrl+r",+ description: "Manage heartbeats",+ },+ "app.heartbeats.openSelected": {+ defaultKeys: "right",+ description: "Open selected heartbeat",+ },"app.session.toggleNamedFilter": {defaultKeys: "ctrl+n",description: "Toggle named session filter",diff --git a/packages/coding-agent/src/core/prompts/rlm.ts b/packages/coding-agent/src/core/prompts/rlm.tsindex d4f6fdd863..54566a50bb 100644--- a/packages/coding-agent/src/core/prompts/rlm.ts+++ b/packages/coding-agent/src/core/prompts/rlm.ts@@ -28,7 +28,7 @@ const IPYTHON_CONTROL_PROMPT = ["","Terminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, IPython kernel, and native call interface exposed to the model.","",- "RLM-native call contract for refined continual harness entries: installed Python skills are called from IPython as `await <skill_import>(...)` with keyword arguments, or as `<skill_import> ...` from shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Continual harness subagent entries are reusable delegation specs; invoke them by turning the spec into a concise task prompt and starting `asyncio.create_task(rlm('sub-task'))` by default, then await the task only when its result is needed, or collect independent subagents with `await asyncio.gather(...)`. Use direct `await rlm('sub-task')` only when the result is immediately required. Do not invent non-native wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.",+ "RLM-native call contract: installed Python skills are pre-imported modules. Read the matching SKILL.md and call its documented function, such as `await <skill_import>.<function>(...)`; when a CLI exists, use `<skill_import> ...` from shell. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Continual harness subagent entries are reusable delegation specs; invoke them by turning the spec into a concise task prompt and starting `asyncio.create_task(rlm('sub-task'))` by default, then await the task only when its result is needed, or collect independent subagents with `await asyncio.gather(...)`. Use direct `await rlm('sub-task')` only when the result is immediately required. Do not invent non-native wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.","","Treat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. Use `/refine` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. Do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.",].join("\n");@@ -59,9 +59,9 @@ export function buildRlmPrompt(options: RlmPromptOptions): string {if (installedSkills.length > 0) {const installed = installedSkills.map((skill) => `\`${skill}\``).join(", ");if (hasIpython) {- skillLines.push(`Installed skills (pre-imported): ${installed}.`);+ skillLines.push(`Installed Python skill modules (pre-imported): ${installed}.`);skillLines.push(- "Each skill is an async function by the same name. Inspect with `help(<skill>)` or `inspect.signature(<skill>.run)`.",+ "Read each skill's SKILL.md for its API. Inspect a module with `help(<skill>)` or `dir(<skill>)`, then inspect a documented callable with `inspect.signature(<skill>.<function>)`.",);} else if (canRunShellSkills) {skillLines.push(`Installed skills available as shell commands: ${installed}.`);diff --git a/packages/coding-agent/src/core/refinement/refinement.ts b/packages/coding-agent/src/core/refinement/refinement.tsindex a54f59a19d..26714683bf 100644--- a/packages/coding-agent/src/core/refinement/refinement.ts+++ b/packages/coding-agent/src/core/refinement/refinement.ts@@ -410,7 +410,7 @@ export function formatHarnessStateForPrompt("When to call `/refine`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `/refine` continual harness edits small and evidence-backed.","",includeIpythonExamples- ? "Call contract: use installed Python skills as `await <skill_import>(...)` in IPython, or `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Continual harness subagent entries are invoked by composing a concise task prompt and starting `asyncio.create_task(rlm('sub-task'))` by default, then awaiting only when the result is needed; use `await asyncio.gather(rlm('task1'), rlm('task2'))` for independent parallel subagents. Use direct `await rlm('sub-task')` only when the result is immediately required. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries."+ ? "Call contract: read each installed Python skill's SKILL.md and call its documented module function in IPython; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Continual harness subagent entries are invoked by composing a concise task prompt and starting `asyncio.create_task(rlm('sub-task'))` by default, then awaiting only when the result is needed; use `await asyncio.gather(rlm('task1'), rlm('task2'))` for independent parallel subagents. Use direct `await rlm('sub-task')` only when the result is immediately required. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.": options.includeShellExamples? "Call contract: use installed skills as shell commands when available (for example `<skill_import> ...`). Continual harness entries are routing/context hints only in sessions without IPython; do not use Python `await`, `asyncio`, or `rlm` examples unless the prompt also documents an IPython kernel.": "Call contract: continual harness entries are routing/context hints only in sessions without IPython or shell access; do not use Python `await`, `asyncio`, `rlm`, or shell skill commands unless the prompt also documents those interfaces.",diff --git a/packages/coding-agent/src/core/slash-commands.ts b/packages/coding-agent/src/core/slash-commands.tsindex 4aa8b8adc2..d0d4d5affa 100644--- a/packages/coding-agent/src/core/slash-commands.ts+++ b/packages/coding-agent/src/core/slash-commands.ts@@ -100,6 +100,7 @@ const CANONICAL_BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [argumentHint: "[status|pause|resume|stop|[every <duration>] [--steer|--follow-up] <instruction>]",takesArgument: true,},+ { name: "heartbeats", description: "View and manage all user and agent heartbeats" },{ name: "resume", description: "Resume a different session" },{ name: "reload", description: "Reload keybindings, extensions, skills, prompts, and themes" },{diff --git a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.tsindex 1bda600655..e2e9539523 100644--- a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts+++ b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts@@ -5,7 +5,12 @@ import { getAgentLogPath, getDaemonLogPath } from "../../config.js";import type { AgentSessionEvent } from "../../core/agent-session.js";import type { CompactionResult } from "../../core/compaction/index.js";import type { ContextTreeNode } from "../../core/context-tree.js";-import type { AgentCronJob, AgentHeartbeatDeliveryMode, AgentHeartbeatUpdateAction } from "../../core/cron-jobs.js";+import type {+ AgentCronJob,+ AgentHeartbeatDeliveryMode,+ AgentHeartbeatManagementAction,+ AgentHeartbeatUpdateAction,+} from "../../core/cron-jobs.js";import type { RefinementResult } from "../../core/refinement/index.js";import type { DeleteSessionFileResult } from "../../core/session-file-actions.js";import type { SessionStats } from "../../core/session-stats.js";@@ -36,6 +41,7 @@ import type {AgentConnectionExecuteBashOptions,AgentConnectionExtensionUiResponse,AgentConnectionForkOptions,+ AgentConnectionHeartbeat,AgentConnectionModel,AgentConnectionModelCycleResult,AgentConnectionNavigateTreeOptions,@@ -452,6 +458,25 @@ export class DaemonAgentConnection implements AgentConnection {return data.jobs;}+ async listHeartbeats(): Promise<AgentConnectionHeartbeat[]> {+ const data = await this.requestData<{ heartbeats: AgentConnectionHeartbeat[] }>({ type: "heartbeats_list" });+ return data.heartbeats;+ }++ async manageHeartbeat(+ activeSessionId: string,+ jobId: string,+ action: AgentHeartbeatManagementAction,+ ): Promise<AgentCronJob> {+ const data = await this.requestData<{ heartbeat: AgentCronJob }>({+ type: "heartbeat_manage",+ activeSessionId,+ jobId,+ action,+ });+ return data.heartbeat;+ }+async addCronJob(schedule: string, prompt: string): Promise<AgentCronJob> {const data = await this.requestData<{ job: AgentCronJob }>({type: "cron_add",@@ -931,6 +956,10 @@ export class DaemonAgentConnection implements AgentConnection {}private async handleDaemonMessage(message: DaemonOutbound): Promise<void> {+ if (message.type === "heartbeats_changed") {+ await this.emit({ type: "heartbeats_changed" });+ return;+ }if (!this.isMessageForActiveSession(message)) {return;}@@ -1526,6 +1555,7 @@ function invalidatesCachedSnapshot(commandType: DaemonCommandBody["type"]): boolcase "get_available_models":case "get_queue":case "cron_list":+ case "heartbeats_list":case "get_session_context":case "get_session_tree":case "get_user_messages_for_forking":diff --git a/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.tsindex 4201fe9cbc..78ca04fe85 100644--- a/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts+++ b/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts@@ -4,7 +4,12 @@ import type { ImageContent, ServiceTier, Transport } from "@earendil-works/pi-aiimport type { AgentSessionRuntime } from "../../core/agent-session-runtime.js";import type { CompactionResult } from "../../core/compaction/index.js";import type { ContextTreeNode } from "../../core/context-tree.js";-import type { AgentCronJob, AgentHeartbeatDeliveryMode, AgentHeartbeatUpdateAction } from "../../core/cron-jobs.js";+import type {+ AgentCronJob,+ AgentHeartbeatDeliveryMode,+ AgentHeartbeatManagementAction,+ AgentHeartbeatUpdateAction,+} from "../../core/cron-jobs.js";import type { RefinementResult } from "../../core/refinement/index.js";import { type DeleteSessionFileResult, deleteSessionFile } from "../../core/session-file-actions.js";import { SessionManager } from "../../core/session-manager.js";@@ -25,6 +30,7 @@ import type {AgentConnectionExecuteBashOptions,AgentConnectionExtensionUiResponse,AgentConnectionForkOptions,+ AgentConnectionHeartbeat,AgentConnectionModel,AgentConnectionModelCycleResult,AgentConnectionNavigateTreeOptions,@@ -165,6 +171,18 @@ export class InProcessAgentConnection implements AgentConnection {return [];}+ async listHeartbeats(): Promise<AgentConnectionHeartbeat[]> {+ return [];+ }++ async manageHeartbeat(+ _activeSessionId: string,+ _jobId: string,+ _action: AgentHeartbeatManagementAction,+ ): Promise<AgentCronJob> {+ throw new Error("Heartbeats require daemon mode");+ }+async addCronJob(_schedule: string, _prompt: string): Promise<AgentCronJob> {throw new Error("Cron jobs require daemon mode");}diff --git a/packages/coding-agent/src/modes/agent-connection/index.ts b/packages/coding-agent/src/modes/agent-connection/index.tsindex d795959603..7a6097c7d2 100644--- a/packages/coding-agent/src/modes/agent-connection/index.ts+++ b/packages/coding-agent/src/modes/agent-connection/index.ts@@ -17,6 +17,7 @@ export type {AgentConnectionExtensionUiRequest,AgentConnectionExtensionUiResponse,AgentConnectionForkOptions,+ AgentConnectionHeartbeat,AgentConnectionLabelEntry,AgentConnectionModel,AgentConnectionModelChangeEntry,diff --git a/packages/coding-agent/src/modes/agent-connection/types.ts b/packages/coding-agent/src/modes/agent-connection/types.tsindex 7ea3bf183c..5e225f7987 100644--- a/packages/coding-agent/src/modes/agent-connection/types.ts+++ b/packages/coding-agent/src/modes/agent-connection/types.ts@@ -3,7 +3,12 @@ import type { Api, ImageContent, Model, ServiceTier, TextContent, Transport, Usaimport type { AuthSourceToken } from "../../core/auth-storage.js";import type { CompactionResult } from "../../core/compaction/index.js";import type { ContextTreeNode } from "../../core/context-tree.js";-import type { AgentCronJob, AgentHeartbeatDeliveryMode, AgentHeartbeatUpdateAction } from "../../core/cron-jobs.js";+import type {+ AgentCronJob,+ AgentHeartbeatDeliveryMode,+ AgentHeartbeatManagementAction,+ AgentHeartbeatUpdateAction,+} from "../../core/cron-jobs.js";import type { ReplayBuiltInToolName } from "../../core/extensions/index.js";import type { GoalState } from "../../core/goals.js";import type { KernelSentAgentMessage } from "../../core/kernel/index.js";@@ -446,6 +451,12 @@ export interface AgentConnectionQueueState {followUp: string[];}+export interface AgentConnectionHeartbeat {+ job: AgentCronJob;+ sessionName?: string;+ firstMessage?: string;+}+export type AgentConnectionExtensionUiResponse = { value: string } | { confirmed: boolean } | { cancelled: true };export interface AgentConnectionExtensionUiRequest {@@ -535,6 +546,7 @@ export type AgentConnectionEvent =| { type: "session_status"; recap?: string }| { type: "extension_ui_request"; request: AgentConnectionExtensionUiRequest }| { type: "connection_status"; status: "reconnecting" | "connected"; error?: string }+ | { type: "heartbeats_changed" }| { type: "closed"; error?: string };export type AgentConnectionEventListener = (event: AgentConnectionEvent) => void | Promise<void>;@@ -562,6 +574,12 @@ export interface AgentConnection {clearQueue(): Promise<AgentConnectionQueueState>;abortAndClearQueue(): Promise<AgentConnectionQueueState>;listCronJobs(options?: { includeInactive?: boolean }): Promise<AgentCronJob[]>;+ listHeartbeats(): Promise<AgentConnectionHeartbeat[]>;+ manageHeartbeat(+ activeSessionId: string,+ jobId: string,+ action: AgentHeartbeatManagementAction,+ ): Promise<AgentCronJob>;addCronJob(schedule: string, prompt: string): Promise<AgentCronJob>;cancelCronJob(jobId: string): Promise<AgentCronJob>;getHeartbeat(): Promise<AgentCronJob | undefined>;diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex 23e262a8b2..32fac7cf5b 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -68,8 +68,8 @@ import {AgentCronJobStore,AgentCronScheduler,type AgentHeartbeatDeliveryMode,+ type AgentHeartbeatManagementAction,type AgentHeartbeatUpdateAction,- createAgentHeartbeatToolDefinitions,DEFAULT_HEARTBEAT_SCHEDULE,isHeartbeatCronJob,normalizeHeartbeatDeliveryMode,@@ -95,6 +95,7 @@ import {createAgentConnectionState,} from "../agent-connection/snapshot.js";import { createAgentConnectionToolDefinition } from "../agent-connection/tool-definition.js";+import type { AgentConnectionHeartbeat } from "../agent-connection/types.js";import { attachJsonlLineReader, serializeJsonLine } from "../rpc/jsonl.js";import { encodePrivateFrame, PrivateFrameDecoder } from "../session-worker/private-framing.js";import {@@ -219,6 +220,8 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set(["clear_queue","abort_and_clear_queue","cron_list",+ "heartbeats_list",+ "heartbeat_manage","cron_add","cron_cancel","heartbeat_get",@@ -394,6 +397,7 @@ export class AgentDaemon {this.log(`Cron job ${job.id} failed: ${error instanceof Error ? error.message : String(error)}`);},});+ this.cronStore.onHeartbeatChange(() => this.broadcastGlobal({ type: "heartbeats_changed" }));}// The daemon runs detached with no terminal, so route its diagnostics to its@@ -871,16 +875,6 @@ export class AgentDaemon {runtimeMetadata: command.runtimeMetadata,sessionLease,sessionOptions: {- customTools: [- ...createAgentHeartbeatToolDefinitions({- getHeartbeat: () => {- if (!stateRef) {- throw new Error("Heartbeat state is not ready for this session yet");- }- return this.cronStore.getHeartbeat(stateRef.activeSessionId);- },- }),- ],rlmHeartbeatController: {listRlmHeartbeats: (listOptions) => {if (!stateRef) {@@ -1298,6 +1292,37 @@ export class AgentDaemon {return job;}+ private listHeartbeats(): AgentConnectionHeartbeat[] {+ return this.cronStore+ .list()+ .filter((job) => isHeartbeatCronJob(job) && (job.status === "active" || job.status === "paused"))+ .map((job) => {+ const state = this.sessions.get(job.activeSessionId);+ const summary = state ? summaryForActiveSession(state) : undefined;+ return {+ job,+ ...(summary?.sessionName ? { sessionName: summary.sessionName } : {}),+ ...(summary?.firstMessage ? { firstMessage: summary.firstMessage } : {}),+ };+ });+ }++ private manageHeartbeat(+ activeSessionId: string,+ jobId: string,+ action: AgentHeartbeatManagementAction,+ ): AgentCronJob | undefined {+ const job = this.cronStore.manageHeartbeat(activeSessionId, jobId, action);+ const state = this.sessions.get(activeSessionId);+ if (job && action !== "resume" && state) {+ this.removeQueuedHeartbeatFollowUp(state, job);+ }+ if (job) {+ this.cronScheduler.wake();+ }+ return job;+ }+private rebindCronJobsToState(state: ActiveSessionState): void {const sessionFile = state.runtime.session.sessionFile;if (!sessionFile) {@@ -2587,6 +2612,17 @@ export class AgentDaemon {return success(command.id, "cron_list", { jobs });}+ case "heartbeats_list":+ return success(command.id, "heartbeats_list", { heartbeats: this.listHeartbeats() });++ case "heartbeat_manage": {+ const heartbeat = this.manageHeartbeat(command.activeSessionId, command.jobId, command.action);+ if (!heartbeat) {+ throw new Error(`No active heartbeat found: ${command.jobId}`);+ }+ return success(command.id, "heartbeat_manage", { heartbeat });+ }+case "cron_add": {const state = this.getSessionState(command.activeSessionId);const job = this.createCronJobForState(state, command.schedule, command.prompt);@@ -4025,6 +4061,12 @@ export class AgentDaemon {}}+ private broadcastGlobal(message: DaemonOutbound): void {+ for (const client of this.clients) {+ this.write(client, message);+ }+ }+private recordWorkerRecoveryState(state: ActiveSessionState, operation: string, busyOverride?: boolean): void {if (!this.recoveryJournal) {return;diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.tsindex fccf3a9aa7..689293cc6f 100644--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts@@ -7,12 +7,18 @@ import type {} from "../../core/agent-messages.js";import type { AgentSessionRuntimeConfig } from "../../core/agent-session-config.js";import type { AgentSessionRuntimeMetadata } from "../../core/agent-session-runtime.js";-import type { AgentCronJob, AgentHeartbeatDeliveryMode, AgentHeartbeatUpdateAction } from "../../core/cron-jobs.js";+import type {+ AgentCronJob,+ AgentHeartbeatDeliveryMode,+ AgentHeartbeatManagementAction,+ AgentHeartbeatUpdateAction,+} from "../../core/cron-jobs.js";import type { CustomMessage } from "../../core/messages.js";import type { SessionCwdIssue } from "../../core/session-cwd.js";import type { DeleteSessionFileResult } from "../../core/session-file-actions.js";import type {AgentConnectionAgentStatus,+ AgentConnectionHeartbeat,AgentConnectionQueueMode,AgentConnectionResourceSnapshot,AgentConnectionRlmChildAgentSnapshot,@@ -373,6 +379,14 @@ export type DaemonCommand =| { id?: string; type: "clear_queue"; activeSessionId: string }| { id?: string; type: "abort_and_clear_queue"; activeSessionId: string }| { id?: string; type: "cron_list"; activeSessionId?: string; includeInactive?: boolean }+ | { id?: string; type: "heartbeats_list" }+ | {+ id?: string;+ type: "heartbeat_manage";+ activeSessionId: string;+ jobId: string;+ action: AgentHeartbeatManagementAction;+ }| { id?: string; type: "cron_add"; activeSessionId: string; schedule: string; prompt: string }| { id?: string; type: "cron_cancel"; jobId: string }| { id?: string; type: "heartbeat_get"; activeSessionId: string }@@ -520,6 +534,7 @@ export type DaemonDeleteSavedSessionResult = DeleteSessionFileResult;export type DaemonResourceSnapshot = AgentConnectionResourceSnapshot;export type DaemonCronJob = AgentCronJob;+export type DaemonHeartbeat = AgentConnectionHeartbeat;export type DaemonAgentSessionMessageReceipt = AgentSessionMessageReceipt;export type DaemonAgentSessionMessageSafetyStatus = AgentSessionMessageSafetyStatus;@@ -546,6 +561,7 @@ export type DaemonOutbound =serverCapabilities: readonly DaemonClientCapability[];}| { type: "daemon_closing"; reason: DaemonClosingReason }+ | { type: "heartbeats_changed" }| { type: "session_event"; activeSessionId: string; event: AgentConnectionSessionEvent; meta?: DaemonEventMeta }| { type: "side_question_event"; activeSessionId: string; event: AgentConnectionSideQuestionEvent }| { type: "session_status"; activeSessionId: string; recap?: string; meta?: DaemonEventMeta }@@ -677,6 +693,7 @@ const READ_ONLY_DAEMON_COMMANDS: ReadonlySet<DaemonCommand["type"]> = new Set(["get_available_models","get_queue","cron_list",+ "heartbeats_list","heartbeat_get","get_session_context","get_session_tree",diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.tsindex 7c3ff6350d..793e1f73de 100644--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts@@ -29,6 +29,7 @@ import {} from "../../core/orphan-process-journal.js";import { getProcessStartId } from "../../core/session-lease.js";import type { SessionInfo } from "../../core/session-manager.js";+import type { AgentConnectionHeartbeat } from "../agent-connection/types.js";import { attachJsonlLineReader, serializeJsonLine } from "../rpc/jsonl.js";import type { PrivateFrame } from "../session-worker/private-framing.js";import { createActiveSessionId, type DaemonSocketClient } from "./active-session-state.js";@@ -138,6 +139,8 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set(["clear_queue","abort_and_clear_queue","cron_list",+ "heartbeats_list",+ "heartbeat_manage","cron_add","cron_cancel","heartbeat_get",@@ -187,6 +190,8 @@ interface ResidentWorker {descriptor: DaemonWorkerDescriptor;descriptorPath: string;client?: DaemonWorkerClient;+ heartbeatSnapshot?: AgentConnectionHeartbeat[];+ heartbeatSnapshotStale?: boolean;summaries: Map<string, SessionSummary>;snapshotCache: Map<string, DaemonAttachResult>;transcriptCaches: Map<string, SnapshotTranscriptCache>;@@ -365,6 +370,14 @@ function cronJobsFromResponse(response: DaemonResponse): AgentCronJob[] {return Array.isArray(jobs) ? (jobs as AgentCronJob[]) : [];}+function heartbeatsFromResponse(response: DaemonResponse): AgentConnectionHeartbeat[] {+ if (!response.success || !response.data || typeof response.data !== "object") {+ return [];+ }+ const heartbeats = (response.data as { heartbeats?: unknown }).heartbeats;+ return Array.isArray(heartbeats) ? (heartbeats as AgentConnectionHeartbeat[]) : [];+}+function sortCronJobs(jobs: AgentCronJob[]): AgentCronJob[] {return jobs.sort((left, right) => {if (left.nextRunAt === right.nextRunAt) {@@ -1036,6 +1049,74 @@ export class DaemonSupervisor {}return success(command.id, "cron_list", { jobs: sortCronJobs([...jobs.values()]) });}+ case "heartbeats_list": {+ const workers = [...this.workers.values()];+ const heartbeats = new Map<string, AgentConnectionHeartbeat>();+ const snapshots: Array<{ heartbeats?: AgentConnectionHeartbeat[]; response?: DaemonResponse }> =+ await Promise.all(+ workers.map(async (worker) => {+ if (worker.client && worker.descriptor.lifecycle === "ready") {+ const response = await this.forwardToWorker(worker, command, 5000).catch((error: unknown) =>+ failure(command.id, command.type, error, serializeDaemonError(error)),+ );+ if (response.success) {+ const snapshot = heartbeatsFromResponse(response);+ worker.heartbeatSnapshot = snapshot;+ worker.heartbeatSnapshotStale = false;+ return { heartbeats: snapshot };+ }+ this.log(`Could not list heartbeats from a worker: ${response.error}`);+ if (worker.heartbeatSnapshot === undefined || worker.heartbeatSnapshotStale === true) {+ return { response };+ }+ }+ if (worker.heartbeatSnapshot !== undefined && worker.heartbeatSnapshotStale !== true) {+ return { heartbeats: worker.heartbeatSnapshot };+ }+ const state =+ worker.descriptor.lifecycle === "ready" ? "disconnected" : worker.descriptor.lifecycle;+ const error = new Error(`Cannot list heartbeats while session worker is ${state}`);+ return { response: failure(command.id, command.type, error, serializeDaemonError(error)) };+ }),+ );+ const failed = snapshots.find((snapshot) => snapshot.response)?.response;+ if (failed) {+ return failed;+ }+ for (const snapshot of snapshots) {+ for (const heartbeat of snapshot.heartbeats ?? []) {+ heartbeats.set(heartbeat.job.id, heartbeat);+ }+ }+ return success(command.id, "heartbeats_list", { heartbeats: [...heartbeats.values()] });+ }+ case "heartbeat_manage": {+ const cachedWorker = [...this.workers.values()].find((worker) =>+ worker.heartbeatSnapshot?.some(+ (heartbeat) =>+ heartbeat.job.id === command.jobId && heartbeat.job.activeSessionId === command.activeSessionId,+ ),+ );+ const worker = cachedWorker ?? (await this.findWorker(command.activeSessionId)).worker;+ const response = await this.forwardToWorker(worker, command);+ if (+ response.success &&+ response.data &&+ typeof response.data === "object" &&+ "heartbeat" in response.data+ ) {+ const job = (response.data as { heartbeat?: AgentCronJob }).heartbeat;+ if (job && worker.heartbeatSnapshot) {+ const existing = worker.heartbeatSnapshot.find((heartbeat) => heartbeat.job.id === job.id);+ const remaining = worker.heartbeatSnapshot.filter((heartbeat) => heartbeat.job.id !== job.id);+ worker.heartbeatSnapshot =+ job.status === "active" || job.status === "paused"+ ? [...remaining, existing ? { ...existing, job } : { job }]+ : remaining;+ }+ }+ return response;+ }case "cron_add": {const match = await this.findWorker(command.activeSessionId);return this.forwardToWorker(match.worker, command);@@ -1396,6 +1477,7 @@ export class DaemonSupervisor {worker.descriptor.lastError = undefined;this.persistWorker(worker);await this.syncAgentPeers();+ this.broadcastHeartbeatsChanged();return worker;} catch (error) {if (isSupervisorGenerationStale(error)) {@@ -1543,6 +1625,7 @@ export class DaemonSupervisor {worker.descriptor.lifecycle = "ready";worker.descriptor.consecutiveFailures = 0;this.persistWorker(worker);+ this.broadcastHeartbeatsChanged();} catch (error) {if (isSupervisorRecoveryCancelled(error)) {return;@@ -1737,6 +1820,7 @@ export class DaemonSupervisor {await this.syncAgentPeers().catch((error) =>this.log(`Could not synchronize agent peers after worker recovery: ${String(error)}`),);+ this.broadcastHeartbeatsChanged();return;} catch (error) {if (isSupervisorRecoveryCancelled(error)) {@@ -2443,6 +2527,11 @@ export class DaemonSupervisor {return;}const { outboundType, activeSessionId, sessionEventType, payloadEncoding, snapshotPurpose } = frame.header;+ if (outboundType === "heartbeats_changed") {+ worker.heartbeatSnapshotStale = true;+ this.broadcastHeartbeatsChanged();+ return;+ }if (outboundType === "session_snapshot_begin" && activeSessionId) {try {const begin = JSON.parse(frame.payload.toString("utf8")) as Extract<@@ -3168,6 +3257,7 @@ export class DaemonSupervisor {}if (!this.shuttingDown) {void this.syncAgentPeers().catch(() => undefined);+ this.broadcastHeartbeatsChanged();}}@@ -3219,6 +3309,12 @@ export class DaemonSupervisor {return this.writeSerialized(client, serializeJsonLine(message));}+ private broadcastHeartbeatsChanged(): void {+ for (const client of this.clients) {+ this.write(client, { type: "heartbeats_changed" });+ }+ }+private writeSerialized(client: DaemonSocketClient, line: string | Uint8Array): boolean {if (client.socket.destroyed) {return false;diff --git a/packages/coding-agent/src/modes/interactive/components/heartbeat-manager.ts b/packages/coding-agent/src/modes/interactive/components/heartbeat-manager.tsnew file mode 100644index 0000000000..0c6b8efea9--- /dev/null+++ b/packages/coding-agent/src/modes/interactive/components/heartbeat-manager.ts@@ -0,0 +1,323 @@+import { type Component, type Focusable, getKeybindings, Spacer, TruncatedText } from "@earendil-works/pi-tui";+import type { AgentHeartbeatManagementAction } from "../../../core/cron-jobs.js";+import type { AgentConnectionHeartbeat } from "../../agent-connection/types.js";+import { theme } from "../theme/theme.js";+import { keyHint } from "./keybinding-hints.js";+import { getMenuListLayout, MenuList, MenuPanel, MenuRow } from "./menu-panel.js";+import { shouldTreatAsBack } from "./modal-back.js";++const HEARTBEAT_PANEL_MAX_WIDTH = 72;+const PREFERRED_VISIBLE_HEARTBEATS = 8;+const HEARTBEAT_LIST_RESERVED_ROWS = 7;+const HEARTBEAT_SCROLL_INDICATOR_ROWS = 1;++type HeartbeatManagerMode = { type: "list" } | { type: "actions"; heartbeatId: string; selectedIndex: number };++export interface HeartbeatManagerOptions {+ getRows: () => number;+ onAction: (heartbeat: AgentConnectionHeartbeat, action: AgentHeartbeatManagementAction) => Promise<void>;+ onClose: () => void;+ requestRender: () => void;+}++export class HeartbeatManagerComponent implements Component, Focusable {+ private heartbeats: AgentConnectionHeartbeat[] = [];+ private selectedIndex = 0;+ private mode: HeartbeatManagerMode = { type: "list" };+ private busy = false;+ private error: string | undefined;+ private _focused = false;++ constructor(+ heartbeats: readonly AgentConnectionHeartbeat[],+ private readonly options: HeartbeatManagerOptions,+ ) {+ this.setHeartbeats(heartbeats);+ }++ get focused(): boolean {+ return this._focused;+ }++ set focused(value: boolean) {+ this._focused = value;+ }++ invalidate(): void {}++ setHeartbeats(heartbeats: readonly AgentConnectionHeartbeat[]): void {+ const selectedId = this.heartbeats[this.selectedIndex]?.job.id;+ this.heartbeats = [...heartbeats].sort((left, right) => {+ const sessionOrder = this.sessionLabel(left).localeCompare(this.sessionLabel(right));+ if (sessionOrder !== 0) return sessionOrder;+ if (left.job.source !== right.job.source) return left.job.source === "heartbeat" ? -1 : 1;+ return left.job.createdAt.localeCompare(right.job.createdAt);+ });+ const nextIndex = selectedId+ ? this.heartbeats.findIndex((heartbeat) => heartbeat.job.id === selectedId)+ : this.selectedIndex;+ this.selectedIndex = Math.max(0, Math.min(nextIndex < 0 ? 0 : nextIndex, this.heartbeats.length - 1));+ if (this.mode.type !== "list" && !this.findHeartbeat(this.mode.heartbeatId)) {+ this.mode = { type: "list" };+ }+ this.options.requestRender();+ }++ handleInput(data: string): void {+ if (this.busy) return;+ const keybindings = getKeybindings();+ if (keybindings.matches(data, "tui.select.cancel") || keybindings.matches(data, "app.heartbeats.open")) {+ this.options.onClose();+ return;+ }+ if (shouldTreatAsBack(data)) {+ if (this.mode.type === "list") {+ this.options.onClose();+ } else {+ this.mode = { type: "list" };+ this.error = undefined;+ this.options.requestRender();+ }+ return;+ }+ if (keybindings.matches(data, "tui.select.up")) {+ this.moveSelection(-1);+ return;+ }+ if (keybindings.matches(data, "tui.select.down")) {+ this.moveSelection(1);+ return;+ }+ if (this.mode.type === "list" && keybindings.matches(data, "app.heartbeats.openSelected")) {+ void this.confirmSelection();+ return;+ }+ if (keybindings.matches(data, "tui.select.confirm")) {+ void this.confirmSelection();+ }+ }++ render(width: number): string[] {+ const panel = this.mode.type === "list" ? this.createHeartbeatListPanel() : this.createActionPanel(this.mode);+ const safeWidth = Math.max(1, width);+ const panelWidth = Math.min(safeWidth, HEARTBEAT_PANEL_MAX_WIDTH);+ const leftPadding = Math.max(0, Math.floor((safeWidth - panelWidth) / 2));+ const rightPadding = Math.max(0, safeWidth - panelWidth - leftPadding);+ return panel.render(panelWidth).map((line) => " ".repeat(leftPadding) + line + " ".repeat(rightPadding));+ }++ private createHeartbeatListPanel(): MenuPanel {+ const active = this.heartbeats.filter((heartbeat) => heartbeat.job.status === "active").length;+ const paused = this.heartbeats.length - active;+ const countLabel = `${this.heartbeats.length} heartbeat${this.heartbeats.length === 1 ? "" : "s"}${paused ? ` · ${paused} paused` : ""}`;+ const panel = new MenuPanel({+ title: "Heartbeats",+ subtitle: `${countLabel}. Select a heartbeat to manage.`,+ });+ const list = new MenuList({ compact: this.getListLayout().compact });+ this.populateHeartbeatList(list);+ panel.addChild(list);+ if (this.error) {+ panel.addChild(new Spacer(1));+ panel.addChild(new TruncatedText(theme.fg("error", `Error: ${this.error}`)));+ }+ panel.addChild(new Spacer(1));+ panel.addChild(new TruncatedText(this.closeHint()));+ return panel;+ }++ private populateHeartbeatList(list: MenuList): void {+ if (this.heartbeats.length === 0) {+ list.addChild(new TruncatedText(theme.fg("muted", "No running or paused heartbeats"), 1, 0));+ return;+ }+ const visibleItems = this.getListLayout().visibleItems;+ const startIndex = Math.max(+ 0,+ Math.min(this.selectedIndex - Math.floor(visibleItems / 2), this.heartbeats.length - visibleItems),+ );+ const endIndex = Math.min(startIndex + visibleItems, this.heartbeats.length);++ for (let index = startIndex; index < endIndex; index++) {+ const heartbeat = this.heartbeats[index];+ if (!heartbeat) continue;+ const source = this.sourceLabel(heartbeat);+ const label = heartbeat.job.label?.trim();+ const delivery = heartbeat.job.deliveryMode === "follow_up" ? "follow-up" : "steer";+ const details = heartbeat.job.lastError+ ? `${source} · error: ${this.singleLine(heartbeat.job.lastError)}`+ : `${source} · ${this.sessionLabel(heartbeat)} · ${heartbeat.job.schedule.expression} · ${delivery}`;+ list.addChild(+ new MenuRow({+ primary: label || this.singleLine(heartbeat.job.prompt) || this.defaultHeartbeatName(heartbeat),+ secondary: details,+ meta: this.formatStatus(heartbeat),+ selected: index === this.selectedIndex,+ }),+ );+ }++ if (startIndex > 0 || endIndex < this.heartbeats.length) {+ list.addChild(+ new TruncatedText(theme.fg("muted", ` (${this.selectedIndex + 1}/${this.heartbeats.length})`), 1, 0),+ );+ }+ }++ private createActionPanel(mode: Exclude<HeartbeatManagerMode, { type: "list" }>): MenuPanel {+ const heartbeat = this.findHeartbeat(mode.heartbeatId);+ if (!heartbeat) {+ return new MenuPanel({ title: "Heartbeats", subtitle: "This heartbeat is no longer available." });+ }+ const name = heartbeat.job.label?.trim() || this.defaultHeartbeatName(heartbeat);+ const panel = new MenuPanel({+ title: name,+ subtitle: this.singleLine(heartbeat.job.prompt),+ });+ panel.addChild(new TruncatedText(theme.fg("muted", this.formatHeartbeatDetails(heartbeat))));+ panel.addChild(new Spacer(1));+ if (this.error) {+ panel.addChild(new TruncatedText(theme.fg("error", `Error: ${this.error}`)));+ panel.addChild(new Spacer(1));+ }+ const list = new MenuList();+ for (const [index, action] of this.availableActions(heartbeat).entries()) {+ list.addChild(+ new MenuRow({+ primary: action.label,+ secondary: this.actionDescription(action.action),+ selected: index === mode.selectedIndex,+ }),+ );+ }+ panel.addChild(list);+ panel.addChild(new Spacer(1));+ panel.addChild(new TruncatedText(this.detailHint()));+ return panel;+ }++ private moveSelection(delta: number): void {+ if (this.mode.type === "list") {+ if (this.heartbeats.length === 0) return;+ this.selectedIndex = Math.max(0, Math.min(this.selectedIndex + delta, this.heartbeats.length - 1));+ } else {+ const count = this.availableActions(this.findHeartbeat(this.mode.heartbeatId)).length;+ this.mode = { ...this.mode, selectedIndex: Math.max(0, Math.min(this.mode.selectedIndex + delta, count - 1)) };+ }+ this.options.requestRender();+ }++ private async confirmSelection(): Promise<void> {+ if (this.mode.type === "list") {+ const heartbeat = this.heartbeats[this.selectedIndex];+ if (heartbeat) {+ this.mode = { type: "actions", heartbeatId: heartbeat.job.id, selectedIndex: 0 };+ this.options.requestRender();+ }+ return;+ }+ const heartbeat = this.findHeartbeat(this.mode.heartbeatId);+ if (!heartbeat) {+ this.mode = { type: "list" };+ this.options.requestRender();+ return;+ }+ const selected = this.availableActions(heartbeat)[this.mode.selectedIndex];+ if (!selected) return;+ await this.runAction(heartbeat, selected.action);+ }++ private async runAction(heartbeat: AgentConnectionHeartbeat, action: AgentHeartbeatManagementAction): Promise<void> {+ this.busy = true;+ this.error = undefined;+ this.options.requestRender();+ try {+ await this.options.onAction(heartbeat, action);+ this.mode = { type: "list" };+ } catch (error) {+ this.error = error instanceof Error ? error.message : String(error);+ } finally {+ this.busy = false;+ this.options.requestRender();+ }+ }++ private availableActions(+ heartbeat: AgentConnectionHeartbeat | undefined,+ ): Array<{ label: string; action: AgentHeartbeatManagementAction }> {+ if (!heartbeat) return [];+ return [+ heartbeat.job.status === "paused"+ ? { label: "Resume heartbeat", action: "resume" }+ : { label: "Pause heartbeat", action: "pause" },+ { label: "Stop heartbeat", action: "stop" },+ ];+ }++ private findHeartbeat(id: string): AgentConnectionHeartbeat | undefined {+ return this.heartbeats.find((heartbeat) => heartbeat.job.id === id);+ }++ private sessionLabel(heartbeat: AgentConnectionHeartbeat): string {+ return heartbeat.sessionName?.trim() || this.singleLine(heartbeat.firstMessage ?? "") || heartbeat.job.sessionId;+ }++ private getListLayout() {+ return getMenuListLayout({+ getRows: this.options.getRows,+ preferredVisibleItems: PREFERRED_VISIBLE_HEARTBEATS,+ totalItems: this.heartbeats.length,+ reservedRows: HEARTBEAT_LIST_RESERVED_ROWS + (this.error ? 2 : 0),+ comfortableItemRows: 3,+ compactItemRows: 2,+ scrollIndicatorRows: HEARTBEAT_SCROLL_INDICATOR_ROWS,+ });+ }++ private formatStatus(heartbeat: AgentConnectionHeartbeat): string {+ return heartbeat.job.status === "active" ? theme.fg("success", "active") : theme.fg("warning", "paused");+ }++ private formatHeartbeatDetails(heartbeat: AgentConnectionHeartbeat): string {+ const delivery = heartbeat.job.deliveryMode === "follow_up" ? "follow-up" : "steer";+ const next = heartbeat.job.nextRunAt ? this.formatTimestamp(heartbeat.job.nextRunAt) : "—";+ return `${this.sourceLabel(heartbeat)} · ${this.sessionLabel(heartbeat)} · ${heartbeat.job.status} · ${heartbeat.job.schedule.expression} · ${delivery} · next ${next} · ${heartbeat.job.runCount} runs`;+ }++ private sourceLabel(heartbeat: AgentConnectionHeartbeat): string {+ return heartbeat.job.source === "heartbeat" ? "Created by you" : "Created by agent";+ }++ private defaultHeartbeatName(heartbeat: AgentConnectionHeartbeat): string {+ return heartbeat.job.source === "heartbeat" ? "Your heartbeat" : "Agent-created heartbeat";+ }++ private closeHint(): string {+ return keyHint("tui.select.cancel", "close", { primaryOnly: true });+ }++ private detailHint(): string {+ return `${keyHint("app.modal.back", "back")} ${keyHint("tui.select.cancel", "close", { primaryOnly: true })}`;+ }++ private actionDescription(action: AgentHeartbeatManagementAction): string {+ switch (action) {+ case "pause":+ return "Stop deliveries until resumed";+ case "resume":+ return "Continue scheduled deliveries";+ case "stop":+ return "Permanently remove this heartbeat";+ }+ }++ private singleLine(value: string): string {+ return value.replace(/\s+/g, " ").trim();+ }++ private formatTimestamp(value: string): string {+ const parsed = new Date(value);+ if (!Number.isFinite(parsed.getTime())) return value;+ return parsed.toISOString().slice(0, 16).replace("T", " ");+ }+}diff --git a/packages/coding-agent/src/modes/interactive/components/menu-panel.ts b/packages/coding-agent/src/modes/interactive/components/menu-panel.tsindex 926b60111d..4b88fca4ec 100644--- a/packages/coding-agent/src/modes/interactive/components/menu-panel.ts+++ b/packages/coding-agent/src/modes/interactive/components/menu-panel.ts@@ -44,6 +44,7 @@ const PANEL_PADDING_Y = 1;const FIELD_PADDING_X = 2;const ROW_PADDING_X = 2;const ROW_PADDING_Y = 1;+const ANSI_RESET = "\x1b[0m";export function getMenuPanelInnerWidth(width: number): number {const safeWidth = Math.max(PANEL_PADDING_X * 2 + 1, width);@@ -202,7 +203,14 @@ function paddedBackgroundLine(if (!background) {return contentSpan + trailingSpan;}- return background(contentSpan) + background(trailingSpan);+ return applyBackground(contentSpan, background) + background(trailingSpan);+}++function applyBackground(text: string, background: (text: string) => string): string {+ return text+ .split(ANSI_RESET)+ .map((segment) => background(segment))+ .join(ANSI_RESET);}function surfaceLine(text: string, width: number, paddingX = PANEL_PADDING_X): string {diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.tsindex 3c01d638cf..2cbae0681d 100644--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts@@ -69,7 +69,12 @@ import {uploadAgentTraceFile,} from "../../core/agent-traces.js";import { isNoModelsAvailableMessage } from "../../core/auth-guidance.js";-import { type AgentCronJob, DEFAULT_HEARTBEAT_DELIVERY_MODE, parseHeartbeatCommand } from "../../core/cron-jobs.js";+import {+ type AgentCronJob,+ type AgentHeartbeatManagementAction,+ DEFAULT_HEARTBEAT_DELIVERY_MODE,+ parseHeartbeatCommand,+} from "../../core/cron-jobs.js";import type {AutocompleteProviderFactory,ContextUsage,@@ -119,6 +124,7 @@ import type {AgentConnection,AgentConnectionExtensionUiRequest,AgentConnectionExtensionUiResponse,+ AgentConnectionHeartbeat,AgentConnectionModel,AgentConnectionQueueState,AgentConnectionResourceDiagnostic,@@ -170,6 +176,7 @@ import { ExtensionEditorComponent } from "./components/extension-editor.js";import { ExtensionInputComponent } from "./components/extension-input.js";import { ExtensionSelectorComponent } from "./components/extension-selector.js";import { FooterComponent } from "./components/footer.js";+import { HeartbeatManagerComponent } from "./components/heartbeat-manager.js";import { InjectedPromptMessageComponent, isInjectedPromptMessage } from "./components/injected-prompt-message.js";import { formatKeyText, keyHint, keyText, rawKeyHint } from "./components/keybinding-hints.js";import type { AuthSelectorProvider } from "./components/oauth-selector.js";@@ -775,6 +782,12 @@ export class InteractiveMode {private connectionState: AgentConnectionState | undefined;private connectionResourceSnapshot: AgentConnectionResourceSnapshot | undefined;private sessionHasMessages = false;+ private heartbeats: AgentConnectionHeartbeat[] = [];+ private heartbeatRefreshPromise: Promise<void> | undefined;+ private heartbeatRefreshRequested = false;+ private heartbeatManager: HeartbeatManagerComponent | undefined;+ private heartbeatManagerHandle: OverlayHandle | undefined;+ private heartbeatManagerRefreshTimer: ReturnType<typeof setTimeout> | undefined;// Registry of images pasted this session, keyed by the `[image #N]` marker// shown to the user. Insertion-ordered; the bytes persist (bounded by@@ -2209,6 +2222,36 @@ export class InteractiveMode {this.connectionResourceSnapshot = resources;}+ private refreshHeartbeatCatalog(): Promise<void> {+ if (this.heartbeatRefreshPromise) {+ this.heartbeatRefreshRequested = true;+ return this.heartbeatRefreshPromise;+ }+ const connection = this.agentConnection;+ const refresh = (async () => {+ do {+ this.heartbeatRefreshRequested = false;+ const heartbeats = await connection.listHeartbeats();+ if (this.agentConnection !== connection) return;+ this.applyHeartbeatCatalog(heartbeats);+ } while (this.heartbeatRefreshRequested);+ })().finally(() => {+ if (this.heartbeatRefreshPromise === refresh) {+ this.heartbeatRefreshPromise = undefined;+ }+ });+ this.heartbeatRefreshPromise = refresh;+ return refresh;+ }++ private applyHeartbeatCatalog(heartbeats: AgentConnectionHeartbeat[]): void {+ this.heartbeats = heartbeats;+ this.heartbeatManager?.setHeartbeats(heartbeats);+ this.scheduleHeartbeatManagerRefresh();+ this.childAgentSummary.invalidate();+ this.ui.requestRender();+ }+private applyConnectionStateSnapshot(state: AgentConnectionState): void {this.connectionState = state;// Don't touch contextUsageTokenBaseline: a mid-stream snapshot reflects only completed@@ -2414,7 +2457,7 @@ export class InteractiveMode {this.showLoadedResources({ force: false, showDiagnosticsWhenQuiet: true });}this.subscribeToAgent();- await this.refreshConnectionQueue();+ await Promise.all([this.refreshConnectionQueue(), this.refreshHeartbeatCatalog()]);await this.updateAvailableProviderCount();this.updateEditorBorderColor();this.updateTerminalTitle();@@ -2944,6 +2987,7 @@ export class InteractiveMode {private resetExtensionUI(): void {this.cancelActiveConnectionExtensionUiRequests();+ this.closeHeartbeatManager();if (this.extensionSelector) {this.hideExtensionSelector();}@@ -3575,6 +3619,9 @@ export class InteractiveMode {this.defaultEditor.onAction("app.tools.expand", () => this.toggleToolOutputExpansion());this.defaultEditor.onAction("app.thinking.toggle", () => this.toggleThinkingBlockVisibility());this.defaultEditor.onAction("app.subagents.focus", () => this.focusChildAgentSummary());+ this.defaultEditor.onAction("app.heartbeats.open", () => {+ void this.showHeartbeatManager();+ });this.defaultEditor.onAction("app.editor.external", () => this.openExternalEditor());this.defaultEditor.onAction("app.prompt.stash", () => this.handlePromptStash());this.defaultEditor.onAction("app.message.followUp", () => this.handleFollowUp());@@ -3967,6 +4014,11 @@ export class InteractiveMode {this.editor.setText("");return;}+ if (commandName === "heartbeats") {+ this.editor.setText("");+ await this.showHeartbeatManager();+ return;+ }if (commandName === "changelog" && !commandArgs) {this.echoLocalCommand(text);this.handleChangelogCommand();@@ -4196,6 +4248,11 @@ export class InteractiveMode {event.status === "connected" ? "Daemon reconnected" : "Daemon connection lost; reconnecting…",event.status === "reconnecting" ? "warning" : "dim",);+ if (event.status === "connected") {+ await this.refreshHeartbeatCatalog();+ }+ } else if (event.type === "heartbeats_changed") {+ await this.refreshHeartbeatCatalog();} else if (event.type === "closed") {this.showError(event.error ?? "Agent connection closed");}@@ -5145,30 +5202,14 @@ export class InteractiveMode {}private getTrayHeartbeatLabel(): string | undefined {- const heartbeat = this.connectionState?.heartbeat;- if (!heartbeat) {+ if (this.heartbeats.length === 0) {return undefined;}- const schedule = this.formatHeartbeatScheduleLabel(heartbeat);- const suffix = schedule ? ` (${schedule})` : "";- switch (heartbeat.status) {- case "active":- return `Heartbeat active${suffix}`;- case "paused":- return `Heartbeat paused${suffix}`;- case "completed":- case "cancelled":- return undefined;- default: {- const _exhaustive: never = heartbeat.status;- return _exhaustive;- }- }- }-- private formatHeartbeatScheduleLabel(heartbeat: AgentCronJob): string | undefined {- const schedule = heartbeat.schedule.expression.trim().replace(/^every\s+/i, "");- return schedule || undefined;+ const paused = this.heartbeats.filter((heartbeat) => heartbeat.job.status === "paused").length;+ const count = `${this.heartbeats.length} heartbeat${this.heartbeats.length === 1 ? "" : "s"}`;+ const pausedLabel = paused ? ` · ${paused} paused` : "";+ const shortcut = keyText("app.heartbeats.open");+ return `${count}${pausedLabel}${shortcut ? ` (${shortcut})` : ""}`;}private getTrayGoalLabel(): string | undefined {@@ -8361,6 +8402,7 @@ export class InteractiveMode {case "status": {const heartbeat = await this.agentConnection.getHeartbeat();this.patchConnectionState({ heartbeat: heartbeat ?? null });+ await this.refreshHeartbeatCatalog();this.showHeartbeat(heartbeat);return;}@@ -8371,6 +8413,7 @@ export class InteractiveMode {command.deliveryMode,);this.patchConnectionState({ heartbeat });+ await this.refreshHeartbeatCatalog();this.showStatus(`Heartbeat set\nDelivery: ${heartbeat.deliveryMode ?? DEFAULT_HEARTBEAT_DELIVERY_MODE}\nNext run: ${heartbeat.nextRunAt ?? "-"}`,);@@ -8383,6 +8426,7 @@ export class InteractiveMode {return;}this.patchConnectionState({ heartbeat });+ await this.refreshHeartbeatCatalog();this.showStatus("Heartbeat paused");return;}@@ -8393,6 +8437,7 @@ export class InteractiveMode {return;}this.patchConnectionState({ heartbeat });+ await this.refreshHeartbeatCatalog();this.showStatus(`Heartbeat resumed\nNext run: ${heartbeat.nextRunAt ?? "-"}`);return;}@@ -8402,7 +8447,8 @@ export class InteractiveMode {this.showStatus("No active heartbeat");return;}- this.patchConnectionState({ heartbeat });+ this.patchConnectionState({ heartbeat: null });+ await this.refreshHeartbeatCatalog();this.showStatus("Heartbeat cleared");return;}@@ -8412,6 +8458,91 @@ export class InteractiveMode {}}+ private async showHeartbeatManager(): Promise<void> {+ if (this.heartbeatManagerHandle) {+ this.heartbeatManagerHandle.focus();+ return;+ }+ try {+ await this.refreshHeartbeatCatalog();+ } catch (error) {+ this.showError(error instanceof Error ? error.message : String(error));+ return;+ }+ const manager = new HeartbeatManagerComponent(this.heartbeats, {+ getRows: () => this.ui.terminal.rows,+ onAction: (heartbeat, action) => this.manageHeartbeat(heartbeat, action),+ onClose: () => this.closeHeartbeatManager(),+ requestRender: () => this.ui.requestRender(),+ });+ this.heartbeatManager = manager;+ this.heartbeatManagerHandle = this.showFullPaneOverlay(manager, {+ fullWidth: true,+ suspendFullscreenMouse: true,+ });+ this.scheduleHeartbeatManagerRefresh();+ }++ private closeHeartbeatManager(): void {+ if (this.heartbeatManagerRefreshTimer) {+ clearTimeout(this.heartbeatManagerRefreshTimer);+ this.heartbeatManagerRefreshTimer = undefined;+ }+ this.heartbeatManagerHandle?.hide();+ this.heartbeatManagerHandle = undefined;+ this.heartbeatManager = undefined;+ this.ui.requestRender();+ }++ private scheduleHeartbeatManagerRefresh(): void {+ if (this.heartbeatManagerRefreshTimer) {+ clearTimeout(this.heartbeatManagerRefreshTimer);+ this.heartbeatManagerRefreshTimer = undefined;+ }+ if (!this.heartbeatManager) {+ return;+ }+ const nextRunAt = this.heartbeats+ .filter((heartbeat) => heartbeat.job.status === "active" && heartbeat.job.nextRunAt)+ .map((heartbeat) => Date.parse(heartbeat.job.nextRunAt!))+ .filter(Number.isFinite)+ .sort((left, right) => left - right)[0];+ if (nextRunAt === undefined) {+ return;+ }+ const untilNextRun = nextRunAt - Date.now();+ const delay = untilNextRun > 0 ? Math.min(60_000, untilNextRun + 250) : 5_000;+ this.heartbeatManagerRefreshTimer = setTimeout(() => {+ this.heartbeatManagerRefreshTimer = undefined;+ if (!this.heartbeatManager) {+ return;+ }+ void this.refreshHeartbeatCatalog().catch(() => this.scheduleHeartbeatManagerRefresh());+ }, delay);+ this.heartbeatManagerRefreshTimer.unref?.();+ }++ private async manageHeartbeat(+ heartbeat: AgentConnectionHeartbeat,+ action: AgentHeartbeatManagementAction,+ ): Promise<void> {+ const updated = await this.agentConnection.manageHeartbeat(+ heartbeat.job.activeSessionId,+ heartbeat.job.id,+ action,+ );+ if (updated.source === "heartbeat" && updated.activeSessionId === this.connectionState?.activeSessionId) {+ this.patchConnectionState({ heartbeat: action === "stop" ? null : updated });+ }+ const remaining = this.heartbeats.filter((entry) => entry.job.id !== updated.id);+ this.applyHeartbeatCatalog(+ updated.status === "active" || updated.status === "paused"+ ? [...remaining, { ...heartbeat, job: updated }]+ : remaining,+ );+ void this.refreshHeartbeatCatalog().catch(() => undefined);+ }+private showHeartbeat(job: AgentCronJob | undefined): void {if (!job) {this.showStatus("No active heartbeat");@@ -8548,6 +8679,7 @@ ${shortcutsKey ? `\`${shortcutsKey}\` quick shortcuts · ` : ""}\`/hotkeys\` fulconst expandTools = this.getAppKeyDisplay("app.tools.expand");const toggleThinking = this.getAppKeyDisplay("app.thinking.toggle");const focusSubagents = this.getAppKeyDisplay("app.subagents.focus");+ const manageHeartbeats = this.getAppKeyDisplay("app.heartbeats.open");const externalEditor = this.getAppKeyDisplay("app.editor.external");const promptStash = this.getAppKeyDisplay("app.prompt.stash");const followUp = this.getAppKeyDisplay("app.message.followUp");@@ -8594,6 +8726,7 @@ ${interrupt ? `| \`${interrupt}\` | Interrupt current operation |\n` : ""}${shor| \`${expandTools}\` | Toggle tool output expansion || \`${toggleThinking}\` | Toggle thinking block visibility || \`${focusSubagents}\` | Open subagent inspector |+| \`${manageHeartbeats}\` | Manage heartbeats || \`${externalEditor}\` | Edit message in external editor || \`${promptStash}\` | Stash or restore draft prompt || \`${followUp}\` | Queue follow-up message |@@ -8827,6 +8960,7 @@ ${interrupt ? `| \`${interrupt}\` | Interrupt current operation |\n` : ""}${shorthis.stopWorkingLoader();this.stopWorkingPulse();this.stopGoalTrayTimer();+ this.closeHeartbeatManager();this.clearExtensionTerminalInputListeners();this.footer.dispose();this.footerDataProvider.dispose();diff --git a/packages/coding-agent/test/cron-jobs.test.ts b/packages/coding-agent/test/cron-jobs.test.tsindex f926b18bcd..00706cb16c 100644--- a/packages/coding-agent/test/cron-jobs.test.ts+++ b/packages/coding-agent/test/cron-jobs.test.ts@@ -6,7 +6,6 @@ import {type AgentCronJob,AgentCronJobStore,AgentCronScheduler,- createAgentHeartbeatToolDefinitions,migrateLegacyCronJobsToSessionArtifacts,normalizeHeartbeatDeliveryMode,parseAgentCronSchedule,@@ -1399,45 +1398,6 @@ describe("heartbeat delivery mode", () => {});});-describe("createAgentHeartbeatToolDefinitions", () => {- it("exposes only read-only user heartbeat inspection to the model", () => {- const tools = createAgentHeartbeatToolDefinitions({- getHeartbeat: () => undefined,- });-- expect(tools.map((tool) => tool.name)).toEqual(["get_heartbeat"]);- });-- it("lets the model inspect heartbeat state without mutating it", async () => {- const tools = createAgentHeartbeatToolDefinitions({- getHeartbeat: () =>- ({- id: "job-1",- status: "active",- source: "heartbeat",- activeSessionId: "active-1",- sessionId: "session-1",- sessionFile: "/tmp/session.jsonl",- cwd: "/tmp/project",- prompt: "check on me",- schedule: { kind: "interval", expression: "every 30s", intervalMs: 30_000 },- createdAt: start.toISOString(),- updatedAt: start.toISOString(),- nextRunAt: "2026-01-01T12:34:30.000Z",- runCount: 0,- }) as const,- });-- const getResult = await tools- .find((candidate) => candidate.name === "get_heartbeat")!- .execute("tool-1", {}, undefined, undefined, {} as never);-- expect(getResult.details).toMatchObject({ id: "job-1", status: "active" });- expect(tools.find((candidate) => candidate.name === "create_heartbeat")).toBeUndefined();- expect(tools.find((candidate) => candidate.name === "update_heartbeat")).toBeUndefined();- });-});-function writeJobsForTest(store: AgentCronJobStore, jobs: readonly AgentCronJob[]): void {(store as unknown as {diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.tsindex 4dcfdafdf9..de0cd3f53e 100644--- a/packages/coding-agent/test/daemon-mode.test.ts+++ b/packages/coding-agent/test/daemon-mode.test.ts@@ -3879,6 +3879,45 @@ describe("daemon mode helpers", () => {}});+ it("manages a persisted heartbeat after its session unloads", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-unloaded-heartbeat-"));+ try {+ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const internals = daemon as unknown as {+ cronStore: AgentCronJobStore;+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;+ };+ const heartbeat = internals.cronStore.createHeartbeat({+ activeSessionId: "unloaded-session",+ sessionId: "session-1",+ sessionFile: join(tempDir, "session.jsonl"),+ cwd: tempDir,+ scheduleText: "every 5m",+ prompt: "check on the session",+ });++ const response = await internals.handleCommand(makeClient("client-1", "unloaded-session"), {+ id: "command-1",+ type: "heartbeat_manage",+ activeSessionId: "unloaded-session",+ jobId: heartbeat.id,+ action: "stop",+ });++ expect(response).toMatchObject({+ success: true,+ data: { heartbeat: { id: heartbeat.id, status: "cancelled" } },+ });+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });+it("sets models without waiting for model_select extension handlers while running", async () => {const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },diff --git a/packages/coding-agent/test/daemon-supervisor-heartbeats.test.ts b/packages/coding-agent/test/daemon-supervisor-heartbeats.test.tsnew file mode 100644index 0000000000..8b4b1d1dbb--- /dev/null+++ b/packages/coding-agent/test/daemon-supervisor-heartbeats.test.ts@@ -0,0 +1,170 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { DaemonSocketClient } from "../src/modes/daemon/active-session-state.js";+import { type DaemonCommand, type DaemonResponse, failure, success } from "../src/modes/daemon/daemon-protocol.js";+import { DaemonSupervisor } from "../src/modes/daemon/daemon-supervisor.js";++interface SupervisorHarness {+ workers: Map<string, unknown>;+ forwardToWorker(worker: unknown, command: DaemonCommand, timeoutMs?: number): Promise<DaemonResponse>;+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<DaemonResponse | undefined>;+ handleWorkerFrame(worker: unknown, frame: unknown): void;+}++const tempDirs: string[] = [];++afterEach(() => {+ for (const directory of tempDirs.splice(0)) {+ rmSync(directory, { recursive: true, force: true });+ }+});++function createSupervisorHarness(): SupervisorHarness {+ const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-heartbeats-"));+ tempDirs.push(directory);+ return new DaemonSupervisor(join(directory, "daemon.sock"), {+ defaultSessionConfig: { agentDir: directory, cwd: directory },+ descriptorDir: join(directory, "workers"),+ }) as unknown as SupervisorHarness;+}++function worker(lifecycle: "ready" | "recovering", connected = true) {+ return {+ descriptor: { lifecycle },+ ...(connected ? { client: {} } : {}),+ };+}++describe("daemon supervisor heartbeat aggregation", () => {+ it("uses the last complete worker snapshot during recovery", async () => {+ const supervisor = createSupervisorHarness();+ const first = worker("ready");+ const second = worker("ready");+ supervisor.workers.set("first", first);+ supervisor.workers.set("second", second);+ supervisor.forwardToWorker = vi.fn(async (target, command) =>+ success(command.id, command.type, {+ heartbeats: [{ job: { id: target === first ? "heartbeat-1" : "heartbeat-2" } }],+ }),+ );++ const initial = await supervisor.handleCommand({} as DaemonSocketClient, {+ id: "list-1",+ type: "heartbeats_list",+ });+ expect(initial).toMatchObject({+ success: true,+ data: { heartbeats: [{ job: { id: "heartbeat-1" } }, { job: { id: "heartbeat-2" } }] },+ });++ second.descriptor.lifecycle = "recovering";+ delete second.client;+ const recovered = await supervisor.handleCommand({} as DaemonSocketClient, {+ id: "list-2",+ type: "heartbeats_list",+ });++ expect(recovered).toMatchObject({+ success: true,+ data: { heartbeats: [{ job: { id: "heartbeat-1" } }, { job: { id: "heartbeat-2" } }] },+ });+ expect(supervisor.forwardToWorker).toHaveBeenCalledTimes(3);+ });++ it("returns a worker failure instead of a partial catalog", async () => {+ const supervisor = createSupervisorHarness();+ const first = worker("ready");+ const second = worker("ready");+ supervisor.workers.set("first", first);+ supervisor.workers.set("second", second);+ supervisor.forwardToWorker = vi.fn(async (target, command) =>+ target === first+ ? success(command.id, command.type, { heartbeats: [] })+ : failure(command.id, command.type, "worker unavailable"),+ );++ const response = await supervisor.handleCommand({} as DaemonSocketClient, {+ id: "list-2",+ type: "heartbeats_list",+ });++ expect(response).toMatchObject({ success: false, error: "worker unavailable" });+ expect(supervisor.forwardToWorker).toHaveBeenCalledTimes(2);+ });++ it("does not fall back to a snapshot after the worker reports heartbeat changes", async () => {+ const supervisor = createSupervisorHarness();+ const target = {+ ...worker("ready"),+ heartbeatSnapshot: [{ job: { id: "heartbeat-1" } }],+ heartbeatSnapshotStale: false,+ };+ supervisor.workers.set("target", target);+ supervisor.forwardToWorker = vi.fn(async (_worker, command) =>+ failure(command.id, command.type, "worker unavailable"),+ );++ supervisor.handleWorkerFrame(target, {+ header: { kind: "outbound", outboundType: "heartbeats_changed" },+ payload: Buffer.alloc(0),+ });+ const response = await supervisor.handleCommand({} as DaemonSocketClient, {+ id: "list-stale",+ type: "heartbeats_list",+ });++ expect(target.heartbeatSnapshotStale).toBe(true);+ expect(response).toMatchObject({ success: false, error: "worker unavailable" });+ });++ it("fails rather than returning a partial catalog without a cached snapshot", async () => {+ const supervisor = createSupervisorHarness();+ supervisor.workers.set("ready", worker("ready"));+ supervisor.workers.set("recovering", worker("recovering", false));+ supervisor.forwardToWorker = vi.fn(async (_target, command) =>+ success(command.id, command.type, { heartbeats: [] }),+ );++ const response = await supervisor.handleCommand({} as DaemonSocketClient, {+ id: "list-3",+ type: "heartbeats_list",+ });++ expect(response).toMatchObject({+ success: false,+ error: "Cannot list heartbeats while session worker is recovering",+ });+ expect(supervisor.forwardToWorker).toHaveBeenCalledOnce();+ });++ it("routes management by cached job ownership after a session unloads", async () => {+ const supervisor = createSupervisorHarness();+ const target = {+ ...worker("ready"),+ heartbeatSnapshot: [{ job: { id: "heartbeat-1", activeSessionId: "unloaded-session" } }],+ };+ supervisor.workers.set("target", target);+ supervisor.forwardToWorker = vi.fn(async (_worker, command) =>+ success(command.id, command.type, {+ heartbeat: { id: "heartbeat-1", activeSessionId: "unloaded-session", status: "cancelled" },+ }),+ );++ const response = await supervisor.handleCommand({} as DaemonSocketClient, {+ id: "manage-1",+ type: "heartbeat_manage",+ activeSessionId: "unloaded-session",+ jobId: "heartbeat-1",+ action: "stop",+ });++ expect(response).toMatchObject({ success: true });+ expect(supervisor.forwardToWorker).toHaveBeenCalledWith(+ target,+ expect.objectContaining({ type: "heartbeat_manage", jobId: "heartbeat-1" }),+ );+ expect(target.heartbeatSnapshot).toEqual([]);+ });+});diff --git a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts b/packages/coding-agent/test/daemon-supervisor-monitor.test.tsindex 01329ae217..84aa3818fd 100644--- a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts+++ b/packages/coding-agent/test/daemon-supervisor-monitor.test.ts@@ -1135,6 +1135,7 @@ describe("daemon worker supervisor monitoring", () => {launchWorker: ReturnType<typeof vi.fn>;persistWorker: ReturnType<typeof vi.fn>;syncAgentPeers: ReturnType<typeof vi.fn>;+ broadcastHeartbeatsChanged: ReturnType<typeof vi.fn>;log: ReturnType<typeof vi.fn>;assertRecoveryAllowed: ReturnType<typeof vi.fn>;recoverWorker(worker: RecoveryWorker): Promise<void>;@@ -1227,6 +1228,7 @@ describe("daemon worker supervisor monitoring", () => {syncAgentPeers: vi.fn(async () => {throw new Error("peer unavailable");}),+ broadcastHeartbeatsChanged: vi.fn(),log: vi.fn(),assertRecoveryAllowed: vi.fn(async () => {}),}) as RecoveryHarness;diff --git a/packages/coding-agent/test/heartbeat-manager.test.ts b/packages/coding-agent/test/heartbeat-manager.test.tsnew file mode 100644index 0000000000..bc8ae2e711--- /dev/null+++ b/packages/coding-agent/test/heartbeat-manager.test.ts@@ -0,0 +1,140 @@+import { setKeybindings, visibleWidth } from "@earendil-works/pi-tui";+import { beforeAll, describe, expect, it } from "vitest";+import type { AgentCronJob, AgentHeartbeatManagementAction } from "../src/core/cron-jobs.js";+import { KEYBINDINGS, KeybindingsManager } from "../src/core/keybindings.js";+import type { AgentConnectionHeartbeat } from "../src/modes/agent-connection/types.js";+import { HeartbeatManagerComponent } from "../src/modes/interactive/components/heartbeat-manager.js";+import { initTheme } from "../src/modes/interactive/theme/theme.js";++function heartbeat(+ id: string,+ options: Partial<AgentCronJob> & { source: "heartbeat" | "rlm_heartbeat" },+): AgentConnectionHeartbeat {+ const { source, ...overrides } = options;+ return {+ job: {+ id,+ status: "active",+ source,+ activeSessionId: `active-${id}`,+ sessionId: `session-${id}`,+ sessionFile: `/tmp/${id}.jsonl`,+ cwd: "/tmp",+ prompt: `${id} prompt`,+ schedule: { kind: "interval", expression: "every 5m", intervalMs: 300_000 },+ createdAt: "2026-07-15T10:00:00.000Z",+ updatedAt: "2026-07-15T10:00:00.000Z",+ nextRunAt: "2026-07-15T10:05:00.000Z",+ runCount: 2,+ ...overrides,+ },+ sessionName: id === "user" ? "Primary session" : "Background session",+ };+}++function stripAnsi(value: string): string {+ return value.replace(/\x1b\[[0-9;]*m/g, "");+}++describe("HeartbeatManagerComponent", () => {+ beforeAll(() => {+ initTheme("dark");+ setKeybindings(new KeybindingsManager());+ });++ it("uses a terminal-stable default shortcut", () => {+ expect(KEYBINDINGS["app.heartbeats.open"].defaultKeys).toBe("ctrl+r");+ expect(KEYBINDINGS["app.heartbeats.openSelected"].defaultKeys).toBe("right");+ });++ it("groups user and agent heartbeats and stays within terminal width", () => {+ const component = new HeartbeatManagerComponent(+ [+ heartbeat("user", { source: "heartbeat" }),+ heartbeat("agent", {+ source: "rlm_heartbeat",+ status: "paused",+ nextRunAt: undefined,+ deliveryMode: "follow_up",+ lastError: "the previous delivery failed",+ }),+ ],+ { getRows: () => 20, onAction: async () => {}, onClose: () => {}, requestRender: () => {} },+ );+ for (const width of [32, 48, 80]) {+ const lines = component.render(width);+ expect(lines.every((line) => visibleWidth(line) === width)).toBe(true);+ }+ const rendered = component.render(100).map(stripAnsi);+ const output = rendered.join("\n");+ expect(output).toContain("2 heartbeats · 1 paused");+ expect(output).toContain("Primary session");+ expect(output).toContain("Created by you");+ expect(output).toContain("Created by agent");+ expect(output).toContain("previous delivery failed");+ expect(output).toContain("Esc close");+ expect(output).not.toContain("← close");+ expect(output).not.toContain("›");+ expect(output).not.toContain("─");+ const titleColumn = rendered.find((line) => line.includes("Heartbeats"))?.indexOf("Heartbeats");+ expect(titleColumn).toBeGreaterThan(2);+ expect(rendered.find((line) => line.includes("Esc close"))?.indexOf("Esc close")).toBe(titleColumn);+ });++ it("uses arrows to open and go back, and closes with escape or the toggle shortcut", () => {+ let closeCount = 0;+ const component = new HeartbeatManagerComponent([heartbeat("user", { source: "heartbeat" })], {+ getRows: () => 20,+ onAction: async () => {},+ onClose: () => closeCount++,+ requestRender: () => {},+ });++ component.handleInput("\x1b[D");+ expect(closeCount).toBe(1);++ component.handleInput("\x1b[C");+ const detailLines = component.render(80).map(stripAnsi);+ const titleColumn = detailLines.find((line) => line.includes("Your heartbeat"))?.indexOf("Your heartbeat");+ expect(detailLines.join("\n")).not.toContain("Return to all heartbeats");+ expect(detailLines.find((line) => line.includes("Created by you"))?.indexOf("Created by you")).toBe(titleColumn);+ expect(detailLines.find((line) => line.includes("← back"))?.indexOf("← back")).toBe(titleColumn);++ component.handleInput("\x1b[D");+ expect(closeCount).toBe(1);+ expect(stripAnsi(component.render(80).join("\n"))).toContain("Select a heartbeat to manage");++ component.handleInput("\r");+ component.handleInput("\x1b");+ expect(closeCount).toBe(2);++ component.handleInput("\x12");+ expect(closeCount).toBe(3);+ });++ it("pauses and stops individual heartbeats immediately", async () => {+ const actions: Array<{ id: string; action: AgentHeartbeatManagementAction }> = [];+ const component = new HeartbeatManagerComponent([heartbeat("user", { source: "heartbeat" })], {+ getRows: () => 20,+ onAction: async (entry, action) => {+ actions.push({ id: entry.job.id, action });+ },+ onClose: () => {},+ requestRender: () => {},+ });++ component.handleInput("\r");+ component.handleInput("\r");+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(actions).toEqual([{ id: "user", action: "pause" }]);++ component.handleInput("\r");+ component.handleInput("\x1b[B");+ component.handleInput("\r");+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(actions).toEqual([+ { id: "user", action: "pause" },+ { id: "user", action: "stop" },+ ]);+ });+});diff --git a/packages/coding-agent/test/interactive-heartbeat-management.test.ts b/packages/coding-agent/test/interactive-heartbeat-management.test.tsnew file mode 100644index 0000000000..5400640204--- /dev/null+++ b/packages/coding-agent/test/interactive-heartbeat-management.test.ts@@ -0,0 +1,109 @@+import { describe, expect, it, vi } from "vitest";+import type { AgentCronJob, AgentHeartbeatManagementAction } from "../src/core/cron-jobs.js";+import type { AgentConnectionHeartbeat } from "../src/modes/agent-connection/types.js";+import { InteractiveMode } from "../src/modes/interactive/interactive-mode.js";++interface HeartbeatManagementHarness {+ heartbeats: AgentConnectionHeartbeat[];+ agentConnection: {+ manageHeartbeat(+ activeSessionId: string,+ jobId: string,+ action: AgentHeartbeatManagementAction,+ ): Promise<AgentCronJob>;+ };+ connectionState: { activeSessionId: string };+ patchConnectionState(patch: { heartbeat: AgentCronJob | null }): void;+ applyHeartbeatCatalog(heartbeats: AgentConnectionHeartbeat[]): void;+ refreshHeartbeatCatalog(): Promise<void>;+ manageHeartbeat(heartbeat: AgentConnectionHeartbeat, action: AgentHeartbeatManagementAction): Promise<void>;+}++interface HeartbeatRefreshHarness {+ heartbeats: AgentConnectionHeartbeat[];+ heartbeatManager: object | undefined;+ heartbeatManagerRefreshTimer: ReturnType<typeof setTimeout> | undefined;+ refreshHeartbeatCatalog(): Promise<void>;+ scheduleHeartbeatManagerRefresh(): void;+}++function heartbeat(): AgentCronJob {+ return {+ id: "heartbeat-1",+ status: "active",+ source: "heartbeat",+ activeSessionId: "active-1",+ sessionId: "session-1",+ sessionFile: "/tmp/session.jsonl",+ cwd: "/tmp",+ prompt: "check the session",+ schedule: { kind: "interval", expression: "every 5m", intervalMs: 300_000 },+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-01T00:00:00.000Z",+ nextRunAt: "2026-01-01T00:05:00.000Z",+ runCount: 0,+ };+}++describe("interactive heartbeat management", () => {+ it("clears local user-heartbeat state after stopping from the manager", async () => {+ const current = heartbeat();+ const stopped = { ...current, status: "cancelled" as const, nextRunAt: undefined };+ const patches: Array<{ heartbeat: AgentCronJob | null }> = [];+ const harness = Object.create(InteractiveMode.prototype) as HeartbeatManagementHarness;+ harness.heartbeats = [{ job: current }];+ harness.connectionState = { activeSessionId: current.activeSessionId };+ harness.agentConnection = {+ manageHeartbeat: vi.fn(async () => stopped),+ };+ harness.patchConnectionState = (patch) => patches.push(patch);+ harness.applyHeartbeatCatalog = vi.fn();+ harness.refreshHeartbeatCatalog = vi.fn(async () => {});++ await harness.manageHeartbeat({ job: current }, "stop");++ expect(patches).toEqual([{ heartbeat: null }]);+ expect(harness.applyHeartbeatCatalog).toHaveBeenCalledWith([]);+ expect(harness.refreshHeartbeatCatalog).toHaveBeenCalledOnce();+ });++ it("keeps a successful action successful when the catalog refresh fails", async () => {+ const current = heartbeat();+ const paused = { ...current, status: "paused" as const, nextRunAt: undefined };+ const harness = Object.create(InteractiveMode.prototype) as HeartbeatManagementHarness;+ harness.heartbeats = [{ job: current, sessionName: "Primary session" }];+ harness.connectionState = { activeSessionId: current.activeSessionId };+ harness.agentConnection = { manageHeartbeat: vi.fn(async () => paused) };+ harness.patchConnectionState = vi.fn();+ harness.applyHeartbeatCatalog = vi.fn();+ harness.refreshHeartbeatCatalog = vi.fn(async () => {+ throw new Error("worker recovering");+ });++ await expect(harness.manageHeartbeat({ job: current, sessionName: "Primary session" }, "pause")).resolves.toBe(+ undefined,+ );++ expect(harness.applyHeartbeatCatalog).toHaveBeenCalledWith([{ job: paused, sessionName: "Primary session" }]);+ expect(harness.refreshHeartbeatCatalog).toHaveBeenCalledOnce();+ });++ it("refreshes an open manager after the next scheduled run", async () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z"));+ const harness = Object.create(InteractiveMode.prototype) as HeartbeatRefreshHarness;+ harness.heartbeats = [{ job: { ...heartbeat(), nextRunAt: "2026-01-01T00:00:01.000Z" } }];+ harness.heartbeatManager = {};+ harness.heartbeatManagerRefreshTimer = undefined;+ harness.refreshHeartbeatCatalog = vi.fn(async () => {});++ harness.scheduleHeartbeatManagerRefresh();+ await vi.advanceTimersByTimeAsync(1_250);++ expect(harness.refreshHeartbeatCatalog).toHaveBeenCalledOnce();+ } finally {+ vi.useRealTimers();+ }+ });+});diff --git a/packages/coding-agent/test/interactive-mode-status.test.ts b/packages/coding-agent/test/interactive-mode-status.test.tsindex 6e615057e2..5a5b840180 100644--- a/packages/coding-agent/test/interactive-mode-status.test.ts+++ b/packages/coding-agent/test/interactive-mode-status.test.ts@@ -21,6 +21,7 @@ import { PRIME_INFERENCE_PROVIDER_ID } from "../src/core/prime-inference-auth.jsimport type {AgentConnectionExtensionUiRequest,AgentConnectionExtensionUiResponse,+ AgentConnectionHeartbeat,AgentConnectionModel,AgentConnectionResourceDiagnostic,AgentConnectionResourceSnapshot,@@ -2216,6 +2217,7 @@ describe("InteractiveMode goal status announcements", () => {describe("InteractiveMode tray goal label", () => {type TrayUsage = { contextWindow: number; tokens: number | null; percent: number | null };type TrayLabelHarness = {+ heartbeats: AgentConnectionHeartbeat[];connectionState: {goal: GoalState;heartbeat?: AgentCronJob | null;@@ -2246,6 +2248,7 @@ describe("InteractiveMode tray goal label", () => {test("shows active goals in the lower tray without an objective", () => {const fakeThis = Object.create(InteractiveMode.prototype) as TrayLabelHarness;+ fakeThis.heartbeats = [];fakeThis.connectionState = {goal: {active: true,@@ -2264,6 +2267,7 @@ describe("InteractiveMode tray goal label", () => {test("combines active goals with token/context usage in one lower-tray label", () => {const fakeThis = Object.create(InteractiveMode.prototype) as TrayLabelHarness;+ fakeThis.heartbeats = [];fakeThis.connectionState = {goal: {active: true,@@ -2282,6 +2286,7 @@ describe("InteractiveMode tray goal label", () => {test("combines active goals, active heartbeats, and context usage in one lower-tray label", () => {const fakeThis = Object.create(InteractiveMode.prototype) as TrayLabelHarness;+ fakeThis.heartbeats = [{ job: createHeartbeat("active") }];fakeThis.connectionState = {goal: {active: true,@@ -2296,11 +2301,12 @@ describe("InteractiveMode tray goal label", () => {};fakeThis.uiServices = { getContextUsage: () => undefined };- expect(getTrayContextLabel.call(fakeThis)).toBe("Pursuing goal (1m 05s) · Heartbeat active (5m) · 75k (75%)");+ expect(getTrayContextLabel.call(fakeThis)).toBe("Pursuing goal (1m 05s) · 1 heartbeat · 75k (75%)");});test("omits the usage segment when token count is unknown", () => {const fakeThis = Object.create(InteractiveMode.prototype) as TrayLabelHarness;+ fakeThis.heartbeats = [];fakeThis.connectionState = {goal: {active: true,diff --git a/packages/coding-agent/test/menu-panel.test.ts b/packages/coding-agent/test/menu-panel.test.tsindex 503b15f7bf..c5164ce8fe 100644--- a/packages/coding-agent/test/menu-panel.test.ts+++ b/packages/coding-agent/test/menu-panel.test.ts@@ -1,4 +1,4 @@-import { type Component, visibleWidth } from "@earendil-works/pi-tui";+import { type Component, TruncatedText, visibleWidth } from "@earendil-works/pi-tui";import stripAnsi from "strip-ansi";import { beforeAll, describe, expect, it } from "vitest";import {@@ -8,7 +8,7 @@ import {MenuRow,MenuSearchInput,} from "../src/modes/interactive/components/menu-panel.js";-import { initTheme } from "../src/modes/interactive/theme/theme.js";+import { initTheme, theme } from "../src/modes/interactive/theme/theme.js";class StaticComponent implements Component {invalidate(): void {@@ -55,6 +55,18 @@ describe("MenuPanel", () => {expect(visibleWidth(output)).toBe(24);});+ it("keeps the menu background behind ellipses", () => {+ const panel = new MenuPanel({ title: "Menu" });+ panel.addChild(new TruncatedText(theme.fg("muted", "A long line that must be truncated")));++ const line = panel.render(24).find((value) => stripAnsi(value).includes("A long line"));+ const backgroundEllipsis = theme.getEditorBackgroundColor()?.("...");++ expect(line).toBeDefined();+ expect(backgroundEllipsis).toBeDefined();+ expect(line).toContain(backgroundEllipsis);+ });+it("renders selected rows as full-width surfaces without a cursor glyph", () => {const row = new MenuRow({primary: "openai/gpt-5",diff --git a/packages/coding-agent/test/suite/regressions/4536-heartbeat-observability.test.ts b/packages/coding-agent/test/suite/regressions/4536-heartbeat-observability.test.tsnew file mode 100644index 0000000000..5f6be2b3d2--- /dev/null+++ b/packages/coding-agent/test/suite/regressions/4536-heartbeat-observability.test.ts@@ -0,0 +1,106 @@+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { AgentCronJobStore } from "../../../src/core/cron-jobs.js";+import { createHarness, type Harness } from "../harness.js";++describe("ENG-4536 heartbeat observability", () => {+ const harnesses: Harness[] = [];++ afterEach(() => {+ while (harnesses.length > 0) harnesses.pop()?.cleanup();+ });++ it("keeps user and agent heartbeat ownership separate while allowing user management", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ const store = AgentCronJobStore.forSessionArtifacts();+ for (const sessionId of ["session-a", "session-b"]) {+ store.registerSessionArtifact(sessionId, join(harness.tempDir, "artifacts", sessionId));+ }+ const base = {+ sessionFile: join(harness.tempDir, "session.jsonl"),+ cwd: harness.tempDir,+ scheduleText: "every 5m",+ };+ const userHeartbeat = store.createHeartbeat({+ ...base,+ activeSessionId: "active-a",+ sessionId: "session-a",+ prompt: "user heartbeat",+ });+ const agentHeartbeat = store.createRlmHeartbeat({+ ...base,+ activeSessionId: "active-a",+ sessionId: "session-a",+ prompt: "agent heartbeat",+ });+ const otherAgentHeartbeat = store.createRlmHeartbeat({+ ...base,+ activeSessionId: "active-b",+ sessionId: "session-b",+ prompt: "other agent heartbeat",+ });++ expect(store.getHeartbeat("active-a")?.id).toBe(userHeartbeat.id);+ expect(store.listRlmHeartbeats("active-a").map((job) => job.id)).toEqual([agentHeartbeat.id]);+ expect(store.updateRlmHeartbeat("active-a", userHeartbeat.id, { status: "pause" })).toBeUndefined();+ expect(store.deleteRlmHeartbeat("active-a", userHeartbeat.id)).toBeUndefined();+ expect(store.updateRlmHeartbeat("active-a", otherAgentHeartbeat.id, { status: "pause" })).toBeUndefined();++ expect(store.manageHeartbeat("active-a", userHeartbeat.id, "pause")?.status).toBe("paused");+ expect(store.manageHeartbeat("active-a", agentHeartbeat.id, "pause")?.status).toBe("paused");+ expect(store.manageHeartbeat("active-b", otherAgentHeartbeat.id, "stop")?.status).toBe("cancelled");+ expect(store.manageHeartbeat("active-a", otherAgentHeartbeat.id, "stop")).toBeUndefined();+ });++ it("emits invalidation for lifecycle changes and keeps multiple agent heartbeats", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ const store = AgentCronJobStore.forSessionArtifacts();+ store.registerSessionArtifact("session-a", join(harness.tempDir, "artifacts", "session-a"));+ let changes = 0;+ store.onHeartbeatChange(() => changes++);+ const input = {+ activeSessionId: "active-a",+ sessionId: "session-a",+ sessionFile: join(harness.tempDir, "session.jsonl"),+ cwd: harness.tempDir,+ scheduleText: "every 10m",+ };+ const user = store.createHeartbeat({ ...input, prompt: "user" });+ store.createRlmHeartbeat({ ...input, prompt: "agent one" });+ store.createRlmHeartbeat({ ...input, prompt: "agent two" });++ expect(store.getHeartbeat("active-a")?.id).toBe(user.id);+ expect(store.listRlmHeartbeats("active-a")).toHaveLength(2);+ store.manageHeartbeat("active-a", user.id, "pause");+ store.manageHeartbeat("active-a", user.id, "resume");+ store.manageHeartbeat("active-a", user.id, "stop");+ expect(changes).toBe(6);++ const cron = store.create({+ ...input,+ prompt: "ordinary cron",+ now: new Date("2026-01-01T00:00:00.000Z"),+ });+ const dueAt = new Date(cron.nextRunAt!);+ const dispatch = store.claimDue(dueAt, dueAt)[0];+ expect(dispatch).toBeDefined();+ store.recordDispatchResult(dispatch!.id, { now: dueAt, outcome: "ran" });+ expect(changes).toBe(6);++ const tickingHeartbeat = store.createRlmHeartbeat({+ ...input,+ prompt: "ticking heartbeat",+ now: new Date("2026-02-01T00:00:00.000Z"),+ });+ expect(changes).toBe(7);+ const heartbeatDueAt = new Date(tickingHeartbeat.nextRunAt!);+ const heartbeatDispatch = store+ .claimDue(heartbeatDueAt, heartbeatDueAt)+ .find((candidate) => candidate.job.id === tickingHeartbeat.id);+ expect(heartbeatDispatch).toBeDefined();+ store.recordDispatchResult(heartbeatDispatch!.id, { now: heartbeatDueAt, outcome: "ran" });+ expect(changes).toBe(7);+ });+});diff --git a/packages/coding-agent/test/system-prompt.test.ts b/packages/coding-agent/test/system-prompt.test.tsindex 7a71db4532..651c2343dd 100644--- a/packages/coding-agent/test/system-prompt.test.ts+++ b/packages/coding-agent/test/system-prompt.test.ts@@ -57,8 +57,8 @@ describe("buildRlmPrompt", () => {`Pre-installed Python packages: ${DEFAULT_RLM_EXTRA_IMPORT_LABELS.join(", ")}.`,"Install additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).","",- "Installed skills (pre-imported): `websearch`.",- "Each skill is an async function by the same name. Inspect with `help(<skill>)` or `inspect.signature(<skill>.run)`.",+ "Installed Python skill modules (pre-imported): `websearch`.",+ "Read each skill's SKILL.md for its API. Inspect a module with `help(<skill>)` or `dir(<skill>)`, then inspect a documented callable with `inspect.signature(<skill>.<function>)`.","Each skill is also available as a shell command by the same name: `<skill> ...`. Discover its CLI usage with `<skill> --help`.","","IPython is the agent's long-lived notebook: a persistent control environment for reasoning, context management, state, tool orchestration, and recursive subcalls. Use it to keep intermediate variables, inspect and transform outputs, write small helper functions, and preserve useful state across turns or compaction.",@@ -79,7 +79,7 @@ describe("buildRlmPrompt", () => {"","Terminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, IPython kernel, and native call interface exposed to the model.","",- "RLM-native call contract for refined continual harness entries: installed Python skills are called from IPython as `await <skill_import>(...)` with keyword arguments, or as `<skill_import> ...` from shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Continual harness subagent entries are reusable delegation specs; invoke them by turning the spec into a concise task prompt and starting `asyncio.create_task(rlm('sub-task'))` by default, then await the task only when its result is needed, or collect independent subagents with `await asyncio.gather(...)`. Use direct `await rlm('sub-task')` only when the result is immediately required. Do not invent non-native wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.",+ "RLM-native call contract: installed Python skills are pre-imported modules. Read the matching SKILL.md and call its documented function, such as `await <skill_import>.<function>(...)`; when a CLI exists, use `<skill_import> ...` from shell. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Continual harness subagent entries are reusable delegation specs; invoke them by turning the spec into a concise task prompt and starting `asyncio.create_task(rlm('sub-task'))` by default, then await the task only when its result is needed, or collect independent subagents with `await asyncio.gather(...)`. Use direct `await rlm('sub-task')` only when the result is immediately required. Do not invent non-native wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.","","Treat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. Use `/refine` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. Do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.",].join("\n"),@@ -93,7 +93,7 @@ describe("buildRlmPrompt", () => {installedSkills: ["websearch"],});- expect(prompt).toContain("Installed skills (pre-imported): `websearch`.");+ expect(prompt).toContain("Installed Python skill modules (pre-imported): `websearch`.");expect(prompt).toContain("A callable `rlm` is already in your global namespace");expect(prompt).toContain("IPython is the agent's long-lived notebook");expect(prompt).toContain("Each `%%bash` cell runs in a throw-away subshell");@@ -122,8 +122,8 @@ describe("buildRlmPrompt", () => {expect(prompt).toContain("Installed skills available as shell commands: `websearch`.");expect(prompt).toContain("Each skill is also available as a shell command");expect(prompt).toContain("`<skill> --help`");- expect(prompt).not.toContain("Installed skills (pre-imported)");- expect(prompt).not.toContain("Each skill is an async function");+ expect(prompt).not.toContain("Installed Python skill modules (pre-imported)");+ expect(prompt).not.toContain("Read each skill's SKILL.md for its API");});test("mentions agent observation recovery only when the skill is installed", () => {@@ -296,7 +296,7 @@ describe("buildSystemPrompt", () => {expect(prompt).toContain("The continual harness entries below are compact summaries, not full descriptions");expect(prompt).toContain("Use global continual harness refinement only for stable cross-session lessons");expect(prompt).toContain("When to call `/refine`");- expect(prompt).toContain("Call contract: use installed Python skills as `await <skill_import>(...)`");+ expect(prompt).toContain("Call contract: read each installed Python skill's SKILL.md");expect(prompt).toContain("Continual harness skill entries are Python REPL skills");expect(prompt).toContain("Continual harness subagent entries are invoked by composing a concise task prompt");expect(prompt).toContain("asyncio.create_task(rlm('sub-task'))");@@ -422,8 +422,8 @@ describe("buildSystemPrompt", () => {expect(prompt).not.toContain("rlm.harness.upsert_skill");expect(prompt).toContain("rlm.harness.record_refinement");expect(prompt).toContain("continual harness names the persisted prompt");- expect(prompt).toContain("RLM-native call contract for refined continual harness entries");- expect(prompt).toContain("await <skill_import>(...)");+ expect(prompt).toContain("RLM-native call contract: installed Python skills are pre-imported modules");+ expect(prompt).toContain("await <skill_import>.<function>(...)");expect(prompt).toContain("Python `reference` and `arguments` contract");expect(prompt).toContain("await asyncio.gather(rlm('task1'), rlm('task2'))");expect(prompt).toContain("Use `/refine` to turn repeated delegation patterns into reusable subagent specs");@@ -618,7 +618,7 @@ describe("buildSystemPrompt", () => {cwd: "/repo",});- expect(prompt).not.toContain("Installed skills (pre-imported)");+ expect(prompt).not.toContain("Installed Python skill modules (pre-imported)");expect(prompt).toContain("<available_skills>");expect(prompt).toContain("<name>websearch</name>");expect(prompt).toContain("<type>markdown</type>");@@ -633,7 +633,7 @@ describe("buildSystemPrompt", () => {cwd: "/repo",});- expect(prompt).toContain("Installed skills (pre-imported): `web_search`.");+ expect(prompt).toContain("Installed Python skill modules (pre-imported): `web_search`.");expect(prompt).toContain("<name>web-search</name>");expect(prompt).toContain("<type>python</type>");expect(prompt).toContain("<python_import>web_search</python_import>");