Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(heartbeat): use internal run to hide heartbeat from chat history
Jiang Bohanc49ab1fee442
diff --git a/packages/core/src/agent/async-agent.ts b/packages/core/src/agent/async-agent.tsindex ce11f17ac6..e7ff1957ba 100644--- a/packages/core/src/agent/async-agent.ts+++ b/packages/core/src/agent/async-agent.ts@@ -149,6 +149,33 @@ export class AsyncAgent {});}+ /**+ * Run an internal prompt and return the result.+ * Serialized through the write queue. Messages are persisted with+ * `internal: true` and rolled back from in-memory state, so they+ * won't appear in UI history or `getMessages()`.+ */+ runInternalForResult(content: string): Promise<{ text: string; error?: string }> {+ if (this._closed) return Promise.resolve({ text: "", error: "Agent is closed" });+ return new Promise((resolve) => {+ this.queue = this.queue+ .then(async () => {+ if (this._closed) {+ resolve({ text: "", error: "Agent is closed" });+ return;+ }+ const result = await this.agent.runInternal(content);+ await this.agent.flushSession();+ resolve({ text: result.text, error: result.error });+ })+ .catch((err) => {+ const message = err instanceof Error ? err.message : String(err);+ console.error(`[AsyncAgent] runInternalForResult failed: ${message}`);+ resolve({ text: "", error: message });+ });+ });+ }+/** Continuously read channel stream (AgentEvent + error Messages) */read(): AsyncIterable<ChannelItem> {return this.channel;diff --git a/packages/core/src/heartbeat/runner.test.ts b/packages/core/src/heartbeat/runner.test.tsindex 1a04bc5ff2..f6691a5cbb 100644--- a/packages/core/src/heartbeat/runner.test.ts+++ b/packages/core/src/heartbeat/runner.test.ts@@ -8,9 +8,7 @@ type StubAgent = {closed: boolean;sessionId: string;ensureInitialized: () => Promise<void>;- getMessages: () => Array<any>;- write: (content: string, options?: { injectTimestamp?: boolean }) => void;- waitForIdle: () => Promise<void>;+ runInternalForResult: (content: string) => Promise<{ text: string; error?: string }>;getHeartbeatConfig: () => { prompt?: string; ackMaxChars?: number; enabled?: boolean };getPendingWrites: () => number;getProfileDir: () => string | undefined;@@ -21,19 +19,13 @@ function createStubAgent(opts?: {replyText?: string;heartbeatEnabled?: boolean;}): StubAgent {- const messages: Array<any> = [];const replyText = opts?.replyText ?? "HEARTBEAT_OK";return {closed: false,sessionId: "test-session",ensureInitialized: async () => {},- getMessages: () => messages,- write: (content: string) => {- messages.push({ role: "user", content });- messages.push({ role: "assistant", content: [{ type: "text", text: replyText }] });- },- waitForIdle: async () => {},+ runInternalForResult: async () => ({ text: replyText }),getHeartbeatConfig: () =>typeof opts?.heartbeatEnabled === "boolean"? { enabled: opts.heartbeatEnabled }@@ -84,18 +76,18 @@ describe("heartbeat runner", () => {expect(result.status).toBe("ran");});- it("disables timestamp injection for heartbeat prompt writes", async () => {- const writes: Array<{ content: string; options?: { injectTimestamp?: boolean } }> = [];+ it("uses runInternalForResult for heartbeat execution", async () => {+ const calls: string[] = [];const agent = createStubAgent({ replyText: "HEARTBEAT_OK" });- const originalWrite = agent.write;- agent.write = (content, options) => {- writes.push(options ? { content, options } : { content });- originalWrite(content, options);+ agent.runInternalForResult = async (content: string) => {+ calls.push(content);+ return { text: "HEARTBEAT_OK" };};await runHeartbeatOnce({ agent: agent as any, reason: "manual" });- expect(writes.length).toBeGreaterThan(0);- expect(writes[0]?.options?.injectTimestamp).toBe(false);+ expect(calls.length).toBeGreaterThan(0);+ // The prompt should contain heartbeat instructions+ expect(calls[0]).toContain("heartbeat");});});diff --git a/packages/core/src/heartbeat/runner.ts b/packages/core/src/heartbeat/runner.tsindex 7e6dab5368..3ca4d7a0a8 100644--- a/packages/core/src/heartbeat/runner.ts+++ b/packages/core/src/heartbeat/runner.ts@@ -1,6 +1,5 @@import fs from "node:fs/promises";import path from "node:path";-import type { AgentMessage } from "@mariozechner/pi-agent-core";import type { AsyncAgent } from "../agent/async-agent.js";import {DEFAULT_HEARTBEAT_ACK_MAX_CHARS,@@ -73,22 +72,6 @@ function resolveDurationMs(raw: string | undefined): number | null {return null;}-function extractMessageText(message: AgentMessage | undefined): string {- if (!message) return "";- const raw = (message as { content?: unknown }).content;- if (typeof raw === "string") return raw;- if (!Array.isArray(raw)) return "";-- const parts: string[] = [];- for (const block of raw) {- if (!block || typeof block !== "object") continue;- const text = (block as { text?: unknown }).text;- if (typeof text === "string" && text.trim()) {- parts.push(text);- }- }- return parts.join("\n").trim();-}function getHeartbeatConfig(agent: AsyncAgent | null): HeartbeatConfig {const cfg = agent?.getHeartbeatConfig();@@ -167,7 +150,6 @@ export async function runHeartbeatOnce(opts: {}await agent.ensureInitialized();- const beforeMessages = agent.getMessages();const sessionKey = resolveSessionKey(agent);const pendingEvents = drainSystemEvents(sessionKey);@@ -176,15 +158,11 @@ export async function runHeartbeatOnce(opts: {? `${basePrompt}\n\nSystem events:\n${pendingEvents.map((line) => `- ${line}`).join("\n")}`: basePrompt;- agent.write(prompt, { injectTimestamp: false });- await agent.waitForIdle();-- const afterMessages = agent.getMessages();- const appended = afterMessages.slice(beforeMessages.length);- const assistant = [...appended]- .reverse()- .find((msg) => msg.role === "assistant");- const text = extractMessageText(assistant);+ const result = await agent.runInternalForResult(prompt);+ if (result.error) {+ throw new Error(result.error);+ }+ const text = result.text;if (!text.trim()) {const okEmptyEvent: Omit<HeartbeatEventPayload, "ts"> = {