Skip to content

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

Rust

perf(coding-agent): skip roster re-composition for unchanged sessions (#2393)

Seth Kartene311d6495124
diff --git a/packages/coding-agent/.changes/roster-compose-skip.md b/packages/coding-agent/.changes/roster-compose-skip.md
new file mode 100644
index 0000000000..c84accbb0f
--- /dev/null
+++ b/packages/coding-agent/.changes/roster-compose-skip.md
@@ -0,0 +1 @@
+- Fixed worker CPU growing with session size: roster heartbeat flushes no longer re-walk every message for the latest-activity timestamp, no longer re-compose and re-serialize unchanged session summaries each cycle, and the heartbeats list no longer builds a full session summary per registered job per poll. Unchanged sessions reuse their last composed roster entry; any live-state change (new message, streaming, bash, compaction, verdict, or registration flag) still recomposes and publishes the same wire delta as before.
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index 99a9c79890..e8e751ac0a 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -190,6 +190,7 @@ import {
inactiveLifecycleForSession,
type SessionSummary,
scheduledJobRegistrations,
+ sessionDisplayLabels,
summaryForActiveSession,
} from "./daemon-session-list.js";
import { DaemonSessionSummarizer } from "./daemon-session-summarizer.js";
@@ -615,6 +616,7 @@ export class AgentDaemon {
private readonly recoveryJournal?: WorkerRecoveryJournal;
private readonly rosterReporter: WorkerRosterReporterState = {
lastComposed: new Map(),
+ lastComposedSource: new Map(),
lastComposedJson: new Map(),
queuedChildren: new Map(),
removedAgentIds: new Map(),
@@ -2326,11 +2328,13 @@ export class AgentDaemon {
.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;
+ // Only the session's display labels are needed; a full summary compose
+ // would re-walk the transcript once per heartbeat job on every poll.
+ const labels = state ? sessionDisplayLabels(state) : undefined;
return {
job,
- ...(summary?.sessionName ? { sessionName: summary.sessionName } : {}),
- ...(summary?.firstMessage ? { firstMessage: summary.firstMessage } : {}),
+ ...(labels?.sessionName ? { sessionName: labels.sessionName } : {}),
+ ...(labels?.firstMessage ? { firstMessage: labels.firstMessage } : {}),
};
});
}
@@ -7364,10 +7368,23 @@ export class AgentDaemon {
private flushRoster(): void {
const reporter = this.rosterReporter;
const entries = new Map<string, WorkerRosterEntry>();
+ // Summary objects are memoized per session: an unchanged session composes
+ // to the same summary reference, so its roster entry and serialization can
+ // be reused instead of re-composed and re-stringified on every flush.
+ const composedSources = new Map<string, SessionSummary>();
const scheduledJobs = this.cronStore.list();
for (const summary of buildSessionList([...this.sessions.values()], [], scheduledJobs)) {
- const entry = workerRosterEntryFromSummary(summary);
- entries.set(entry.agentId, entry);
+ const agentId = rosterAgentIdForSummary(summary);
+ if (reporter.lastComposedSource.get(agentId) === summary) {
+ const entry = reporter.lastComposed.get(agentId);
+ if (entry) {
+ entries.set(agentId, entry);
+ composedSources.set(agentId, summary);
+ continue;
+ }
+ }
+ entries.set(agentId, workerRosterEntryFromSummary(summary));
+ composedSources.set(agentId, summary);
}
for (const [agentId, queued] of reporter.queuedChildren) {
if (entries.has(agentId)) {
@@ -7420,12 +7437,18 @@ export class AgentDaemon {
const changed: WorkerRosterEntry[] = [];
const nextJson = new Map<string, string>();
for (const entry of entries.values()) {
- const json = JSON.stringify(entry);
+ // An entry reused from the last flush is unchanged by construction:
+ // skip its serialization and keep the previous json for the delta compare.
+ const json =
+ reporter.lastComposed.get(entry.agentId) === entry
+ ? (reporter.lastComposedJson.get(entry.agentId) ?? JSON.stringify(entry))
+ : JSON.stringify(entry);
nextJson.set(entry.agentId, json);
if (reporter.lastComposedJson.get(entry.agentId) !== json) changed.push(entry);
}
const removedAgentIds = [...reporter.removedAgentIds.keys()];
reporter.lastComposed = new Map(entries);
+ reporter.lastComposedSource = composedSources;
reporter.lastComposedJson = nextJson;
if (!this.hasAuthenticatedSupervisorClient()) {
if (changed.length > 0 || removedAgentIds.length > 0) reporter.snapshotPending = true;
@@ -7913,6 +7936,8 @@ export class AgentDaemon {
interface WorkerRosterReporterState {
lastComposed: Map<string, WorkerRosterEntry>;
+ /** Summary each lastComposed entry was composed from; an unchanged session reuses its entry. */
+ lastComposedSource: Map<string, SessionSummary>;
lastComposedJson: Map<string, string>;
queuedChildren: Map<string, WorkerRosterEntry>;
/** Pending removals: agentId -> removed sessionId; a new incarnation of the id cancels it. */
diff --git a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
index 21e0794e32..73a5c7c398 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
@@ -6,7 +6,7 @@ import { compactRlmText } from "../../core/agent-session.js";
import type { AgentSessionRuntimeDiagnostic } from "../../core/agent-session-services.js";
import { type AgentCronJob, isHeartbeatCronJob } from "../../core/cron-jobs.js";
import type { SessionActionSnapshot } from "../../core/session-action-store.js";
-import type { AgentTaskState, SessionInfo } from "../../core/session-manager.js";
+import type { AgentStatus, AgentTaskState, SessionInfo } from "../../core/session-manager.js";
import type { SessionUsageSummary } from "../../core/usage.js";
import type { AgentConnectionRlmChildAgentSnapshot } from "../agent-connection/types.js";
import type { ActiveSessionState } from "./active-session-state.js";
@@ -216,6 +216,77 @@ export function buildSessionList(
return entries;
}
+// Compose memos, keyed weakly by session state so entries die with the session.
+// Roster flushes re-compose every active session summary on every event; with
+// large sessions that meant a full message walk plus a full compose plus a
+// serialize per session per flush. The activity memo keeps the timestamp scan
+// incremental, and the fingerprint memo returns the last composed summary
+// (same object) whenever every input that feeds it is unchanged.
+const messageActivityMemos = new WeakMap<ActiveSessionState, MessageActivityMemo>();
+const summaryComposeMemos = new WeakMap<
+ ActiveSessionState,
+ { fingerprint: SummaryComposeFingerprint; summary: SessionSummary }
+>();
+
+/**
+ * Cheap snapshot of every summary input; any difference forces a fresh compose.
+ *
+ * Leaf id and message count alone are not a sufficient key: isStreaming,
+ * isBashRunning, isCompacting, attachment counts, the summary verdict, and the
+ * heartbeat/cron flags all change without a single append, and the daemon
+ * schedules roster flushes at exactly those edges. Comparing the full input set
+ * keeps the memoized summary byte-identical to a fresh compose.
+ */
+interface SummaryComposeFingerprint {
+ // Caller inputs: registration flags vary per compose site, and the saved
+ // catalog entry (when present) feeds created/modified/firstMessage/parentSessionPath.
+ hasActiveHeartbeat: boolean;
+ hasRegisteredHeartbeat: boolean;
+ hasRegisteredCronJob: boolean;
+ savedSession: SessionInfo | undefined;
+ // Busy-state bits flip without appends (turn, bash, compaction, tool edges).
+ isStreaming: boolean;
+ isCompacting: boolean;
+ isBashRunning: boolean;
+ pendingToolCallsSize: number;
+ isSessionActive: boolean;
+ hasRunningRlmChildren: boolean;
+ unfinishedActionCount: number;
+ attachedClients: number;
+ directAttachedClients: number;
+ messageCount: number;
+ // References: memoized upstream (usage), replaced on change (model,
+ // summaryState, streamingMessage), or structural (sessionActions,
+ // diagnostics: post-construction changes replace the array or append).
+ usage: SessionUsageSummary | undefined;
+ model: Model<Api> | undefined;
+ thinkingLevel: ThinkingLevel | undefined;
+ streamingMessage: AgentMessage | undefined;
+ summaryState: AgentStatus | undefined;
+ diagnostics: readonly AgentSessionRuntimeDiagnostic[];
+ repliedSinceTask: boolean | undefined;
+ sessionActions: SessionActionSnapshot;
+ // Identity and display inputs: the metadata getter returns a fresh copy on
+ // every read, so its summary-relevant fields compare by value.
+ metadataKind: string;
+ metadataParentActiveSessionId: string | undefined;
+ metadataParentSessionId: string | undefined;
+ metadataParentSessionFile: string | undefined;
+ metadataRlmChildId: string | undefined;
+ metadataRlmParentNodeId: string | undefined;
+ sessionName: string | undefined;
+ sessionId: string;
+ sessionFile: string | undefined;
+ cwd: string;
+ rlmDepth: number | undefined;
+ modelFallbackMessage: string | undefined;
+ // Values computed once per attempt and shared with the compose.
+ headerTimestamp: string | undefined;
+ modified: string | undefined;
+ lastActivityAt: string | undefined;
+ firstMessage: string | undefined;
+}
+
export function summaryForActiveSession(
activeSession: ActiveSessionState,
savedSession?: SessionInfo,
@@ -237,7 +308,71 @@ export function summaryForActiveSession(
const directAttachedClients = [...activeSession.clients].filter(
(client) => client.authenticationRole === "session_client",
).length;
- return {
+ // The activity memo folds only messages appended since the last scan.
+ let activityMemo = messageActivityMemos.get(activeSession);
+ if (activityMemo === undefined) {
+ activityMemo = { source: undefined, scannedLength: 0, tailRef: undefined, latest: undefined };
+ messageActivityMemos.set(activeSession, activityMemo);
+ }
+ const headerTimestamp = session.sessionManager.getHeader?.()?.timestamp;
+ const lastActivityAt = latestMessageActivityAt(session.messages, activityMemo) ?? modified ?? headerTimestamp;
+ // Subagent sessions live in artifact dirs that the saved-session scan
+ // never sees; their spawn prompt is the most identifying title we have.
+ // A freshly created top-level session has neither yet — its jsonl is not
+ // scanned until it flushes — so derive from the live first user message to
+ // avoid titling the chat with its session ID until the file lands.
+ const firstMessage =
+ savedSession?.firstMessage ??
+ (metadata.prompt ? compactRlmText(metadata.prompt, 120) : undefined) ??
+ firstUserMessageText(session);
+
+ const fingerprint: SummaryComposeFingerprint = {
+ hasActiveHeartbeat,
+ hasRegisteredHeartbeat,
+ hasRegisteredCronJob,
+ savedSession,
+ isStreaming: session.isStreaming,
+ isCompacting: session.isCompacting,
+ isBashRunning: session.isBashRunning,
+ pendingToolCallsSize: session.state.pendingToolCalls.size,
+ isSessionActive: session.isSessionActive,
+ hasRunningRlmChildren: session.hasRunningRlmChildren(),
+ unfinishedActionCount: session.unfinishedActionCount,
+ attachedClients: activeSession.clients.size,
+ directAttachedClients,
+ messageCount: session.messages.length,
+ usage: session.getOwnUsageSummary?.(),
+ model: session.model as Model<Api> | undefined,
+ thinkingLevel: session.thinkingLevel,
+ streamingMessage: session.state.streamingMessage,
+ summaryState: activeSession.summaryState,
+ diagnostics: activeSession.runtime.diagnostics,
+ repliedSinceTask: metadata.kind === "subagent" ? session.repliedToParentSinceTask : undefined,
+ sessionActions: session.getSessionActionSnapshot(),
+ metadataKind: metadata.kind,
+ metadataParentActiveSessionId: metadata.parentActiveSessionId,
+ metadataParentSessionId: metadata.parentSessionId,
+ metadataParentSessionFile: metadata.parentSessionFile,
+ metadataRlmChildId: metadata.rlmChildId,
+ metadataRlmParentNodeId: metadata.rlmParentNodeId,
+ sessionName: session.sessionName,
+ sessionId: session.sessionId,
+ sessionFile: session.sessionFile,
+ cwd: session.sessionManager.getCwd(),
+ rlmDepth: session.rlmDepth,
+ modelFallbackMessage: activeSession.runtime.modelFallbackMessage,
+ headerTimestamp,
+ modified,
+ lastActivityAt,
+ firstMessage,
+ };
+
+ const memo = summaryComposeMemos.get(activeSession);
+ if (memo && summaryComposeFingerprintsEqual(memo.fingerprint, fingerprint)) {
+ return memo.summary;
+ }
+
+ const summary: SessionSummary = {
id: activeSession.activeSessionId,
lifecycle: activeLifecycleForSession(activeSession),
activity: activeActivityForSession(activeSession),
@@ -245,8 +380,7 @@ export function summaryForActiveSession(
hasActiveHeartbeat: hasActiveHeartbeat || undefined,
hasRegisteredHeartbeat: hasRegisteredHeartbeat || undefined,
hasRegisteredCronJob: hasRegisteredCronJob || undefined,
- lastActivityAt:
- latestMessageActivityAt(session.messages) ?? modified ?? session.sessionManager.getHeader?.()?.timestamp,
+ lastActivityAt,
runtimeKind: metadata.kind,
rlmDepth: session.rlmDepth,
activeSessionId: activeSession.activeSessionId,
@@ -268,17 +402,9 @@ export function summaryForActiveSession(
unfinishedActionCount: session.unfinishedActionCount,
sessionActions: session.getSessionActionSnapshot(),
streamingMessage: session.state.streamingMessage,
- created: savedSession?.created.toISOString() ?? session.sessionManager.getHeader?.()?.timestamp,
+ created: savedSession?.created.toISOString() ?? headerTimestamp,
modified,
- // Subagent sessions live in artifact dirs that the saved-session scan
- // never sees; their spawn prompt is the most identifying title we have.
- // A freshly created top-level session has neither yet — its jsonl is not
- // scanned until it flushes — so derive from the live first user message to
- // avoid titling the chat with its session ID until the file lands.
- firstMessage:
- savedSession?.firstMessage ??
- (metadata.prompt ? compactRlmText(metadata.prompt, 120) : undefined) ??
- firstUserMessageText(session),
+ firstMessage,
parentActiveSessionId: metadata.parentActiveSessionId,
parentSessionId: metadata.parentSessionId,
parentSessionPath: savedSession?.parentSessionPath ?? metadata.parentSessionFile,
@@ -298,20 +424,169 @@ export function summaryForActiveSession(
summary: activeSession.summaryState?.summary,
...(isSummaryCurrent(activeSession) ? { taskState: activeSession.summaryState?.taskState } : {}),
};
+ summaryComposeMemos.set(activeSession, { fingerprint, summary });
+ return summary;
+}
+
+function summaryComposeFingerprintsEqual(left: SummaryComposeFingerprint, right: SummaryComposeFingerprint): boolean {
+ return (
+ left.hasActiveHeartbeat === right.hasActiveHeartbeat &&
+ left.hasRegisteredHeartbeat === right.hasRegisteredHeartbeat &&
+ left.hasRegisteredCronJob === right.hasRegisteredCronJob &&
+ left.savedSession === right.savedSession &&
+ left.isStreaming === right.isStreaming &&
+ left.isCompacting === right.isCompacting &&
+ left.isBashRunning === right.isBashRunning &&
+ left.pendingToolCallsSize === right.pendingToolCallsSize &&
+ left.isSessionActive === right.isSessionActive &&
+ left.hasRunningRlmChildren === right.hasRunningRlmChildren &&
+ left.unfinishedActionCount === right.unfinishedActionCount &&
+ left.attachedClients === right.attachedClients &&
+ left.directAttachedClients === right.directAttachedClients &&
+ left.messageCount === right.messageCount &&
+ left.usage === right.usage &&
+ left.model === right.model &&
+ left.thinkingLevel === right.thinkingLevel &&
+ left.streamingMessage === right.streamingMessage &&
+ left.summaryState === right.summaryState &&
+ left.repliedSinceTask === right.repliedSinceTask &&
+ left.metadataKind === right.metadataKind &&
+ left.metadataParentActiveSessionId === right.metadataParentActiveSessionId &&
+ left.metadataParentSessionId === right.metadataParentSessionId &&
+ left.metadataParentSessionFile === right.metadataParentSessionFile &&
+ left.metadataRlmChildId === right.metadataRlmChildId &&
+ left.metadataRlmParentNodeId === right.metadataRlmParentNodeId &&
+ left.sessionName === right.sessionName &&
+ left.sessionId === right.sessionId &&
+ left.sessionFile === right.sessionFile &&
+ left.cwd === right.cwd &&
+ left.rlmDepth === right.rlmDepth &&
+ left.modelFallbackMessage === right.modelFallbackMessage &&
+ left.headerTimestamp === right.headerTimestamp &&
+ left.modified === right.modified &&
+ left.lastActivityAt === right.lastActivityAt &&
+ left.firstMessage === right.firstMessage &&
+ diagnosticsEqual(left.diagnostics, right.diagnostics) &&
+ sessionActionSnapshotsEqual(left.sessionActions, right.sessionActions)
+ );
+}
+
+// Runtime diagnostics change by wholesale replacement or by append; a stable
+// length and tail element covers both without a deep compare.
+function diagnosticsEqual(
+ left: readonly AgentSessionRuntimeDiagnostic[],
+ right: readonly AgentSessionRuntimeDiagnostic[],
+): boolean {
+ if (left === right) return true;
+ if (left.length !== right.length) return false;
+ return left.length === 0 || left[left.length - 1] === right[right.length - 1];
+}
+
+function sessionActionSnapshotsEqual(left: SessionActionSnapshot, right: SessionActionSnapshot): boolean {
+ if (left === right) return true;
+ if (left.queuedCount !== right.queuedCount) return false;
+ if (
+ left.active?.kind !== right.active?.kind ||
+ left.active?.phase !== right.active?.phase ||
+ left.active?.label !== right.active?.label
+ ) {
+ return false;
+ }
+ return stringArraysEqual(left.steering, right.steering) && stringArraysEqual(left.followUps, right.followUps);
+}
+
+function stringArraysEqual(left: readonly string[], right: readonly string[]): boolean {
+ if (left === right) return true;
+ if (left.length !== right.length) return false;
+ for (let index = 0; index < left.length; index += 1) {
+ if (left[index] !== right[index]) return false;
+ }
+ return true;
+}
+
+/**
+ * Cheap display labels for callers that need only the session's identity (the
+ * heartbeats list polls once per registered job); avoids the full summary
+ * compose. Mirrors the sessionName/firstMessage fields summaryForActiveSession
+ * produces for a session without a saved catalog entry.
+ */
+export function sessionDisplayLabels(activeSession: ActiveSessionState): {
+ sessionName: string | undefined;
+ firstMessage: string | undefined;
+} {
+ const session = activeSession.runtime.session;
+ const metadata = activeSession.runtime.metadata ?? { kind: "top-level" as const };
+ return {
+ sessionName: session.sessionName,
+ firstMessage:
+ (metadata.prompt ? compactRlmText(metadata.prompt, 120) : undefined) ?? firstUserMessageText(session),
+ };
+}
+
+/**
+ * Incremental max-message-timestamp tracker for one active session.
+ *
+ * Sessions only append to their message array in place (full reassignments
+ * replace the array object), so the memo folds just the messages appended
+ * since the last scan. It falls back to a full walk whenever the array is
+ * replaced, shrinks, or shifts: a mid-array insert changes the element at the
+ * previous scan boundary, which the tail reference detects.
+ */
+export interface MessageActivityMemo {
+ /** Live messages array the memo last scanned; an identity change forces a full walk. */
+ source: readonly AgentMessage[] | undefined;
+ /** Number of leading elements already folded into `latest`. */
+ scannedLength: number;
+ /** Element at `scannedLength - 1` at the last scan; detects mid-array inserts. */
+ tailRef: AgentMessage | undefined;
+ /** Largest valid message timestamp seen so far, or undefined before the first valid one. */
+ latest: number | undefined;
}
-function latestMessageActivityAt(messages: readonly AgentMessage[]): string | undefined {
+function messageActivityTimestamp(message: AgentMessage): number | undefined {
+ // Tool results and custom messages are real session activity too. Looking at
+ // every timestamp also keeps this correct for future AgentMessage variants.
+ if (
+ typeof message.timestamp === "number" &&
+ Number.isFinite(message.timestamp) &&
+ Math.abs(message.timestamp) <= MAX_DATE_TIMESTAMP_MS
+ ) {
+ return message.timestamp;
+ }
+ return undefined;
+}
+
+function foldMessageActivity(
+ messages: readonly AgentMessage[],
+ from: number,
+ latest: number | undefined,
+): number | undefined {
+ for (let index = from; index < messages.length; index += 1) {
+ const timestamp = messageActivityTimestamp(messages[index]!);
+ if (timestamp === undefined) continue;
+ latest = latest === undefined ? timestamp : Math.max(latest, timestamp);
+ }
+ return latest;
+}
+
+export function latestMessageActivityAt(
+ messages: readonly AgentMessage[],
+ memo?: MessageActivityMemo,
+): string | undefined {
let latest: number | undefined;
- for (const message of messages) {
- // Tool results and custom messages are real session activity too. Looking at
- // every timestamp also keeps this correct for future AgentMessage variants.
- if (
- typeof message.timestamp === "number" &&
- Number.isFinite(message.timestamp) &&
- Math.abs(message.timestamp) <= MAX_DATE_TIMESTAMP_MS
- ) {
- latest = latest === undefined ? message.timestamp : Math.max(latest, message.timestamp);
- }
+ if (memo === undefined || memo.source !== messages || messages.length < memo.scannedLength) {
+ latest = foldMessageActivity(messages, 0, undefined);
+ } else if (memo.scannedLength > 0 && messages[memo.scannedLength - 1] !== memo.tailRef) {
+ // A mid-array insert shifted the scanned prefix; rescan everything.
+ latest = foldMessageActivity(messages, 0, undefined);
+ } else {
+ latest = foldMessageActivity(messages, memo.scannedLength, memo.latest);
+ }
+ if (memo !== undefined) {
+ memo.source = messages;
+ memo.scannedLength = messages.length;
+ memo.tailRef = messages.length > 0 ? messages[messages.length - 1] : undefined;
+ memo.latest = latest;
}
return latest === undefined ? undefined : new Date(latest).toISOString();
}
diff --git a/packages/coding-agent/test/daemon-agent-roster.test.ts b/packages/coding-agent/test/daemon-agent-roster.test.ts
index 453d08c8f8..41b6feec25 100644
--- a/packages/coding-agent/test/daemon-agent-roster.test.ts
+++ b/packages/coding-agent/test/daemon-agent-roster.test.ts
@@ -34,6 +34,7 @@ interface WorkerReporterFixture {
flushRoster(): void;
rosterReporter: {
lastComposed: Map<string, WorkerRosterEntry>;
+ lastComposedSource: Map<string, SessionSummary>;
lastComposedJson: Map<string, string>;
queuedChildren: Map<string, WorkerRosterEntry>;
removedAgentIds: Map<string, string | undefined>;
@@ -55,6 +56,7 @@ function makeWorkerReporter(connected = true): WorkerReporterFixture {
acpMcpOwners: new Map(),
rosterReporter: {
lastComposed: new Map<string, WorkerRosterEntry>(),
+ lastComposedSource: new Map<string, SessionSummary>(),
lastComposedJson: new Map<string, string>(),
queuedChildren: new Map<string, WorkerRosterEntry>(),
removedAgentIds: new Map<string, string | undefined>(),
@@ -483,6 +485,69 @@ describe("worker roster reporter", () => {
await new Promise((resolveSettle) => setImmediate(resolveSettle));
expect(internals.rosterReporter.lastComposed.get(agentId)?.summary.model).toMatchObject({ id: "m2" });
});
+
+ it("reuses the composed entry for an unchanged session and recomposes on append", () => {
+ const { daemon, sentDeltas } = makeWorkerReporter();
+ const messages: AgentMessage[] = [];
+ const state = makeState({ activeSessionId: "steady-active", sessionId: "steady-session", messages });
+ daemon.sessions.set(state.activeSessionId, state);
+
+ daemon.flushRoster();
+ expect(sentDeltas).toHaveLength(1);
+ const firstEntry = daemon.rosterReporter.lastComposed.get("steady-session");
+ expect(firstEntry?.summary.messageCount).toBe(0);
+
+ // Nothing changed: no new delta, and the same entry object is reused
+ // instead of being recomposed and re-serialized from the same inputs.
+ daemon.flushRoster();
+ expect(sentDeltas).toHaveLength(1);
+ expect(daemon.rosterReporter.lastComposed.get("steady-session")).toBe(firstEntry);
+
+ // A new message recomposes the row and publishes the updated activity.
+ messages.push({
+ role: "user",
+ content: "next turn",
+ timestamp: Date.parse("2026-05-02T00:00:00.000Z"),
+ } as AgentMessage);
+ daemon.flushRoster();
+ expect(sentDeltas).toHaveLength(2);
+ const secondEntry = daemon.rosterReporter.lastComposed.get("steady-session");
+ expect(secondEntry).not.toBe(firstEntry);
+ expect(secondEntry?.summary).toMatchObject({
+ messageCount: 1,
+ lastActivityAt: "2026-05-02T00:00:00.000Z",
+ });
+
+ // Unchanged again: the recomposed entry is reused across later flushes.
+ daemon.flushRoster();
+ expect(sentDeltas).toHaveLength(2);
+ expect(daemon.rosterReporter.lastComposed.get("steady-session")).toBe(secondEntry);
+ });
+
+ it("republishes busy-state flips that arrive without any append", () => {
+ const { daemon, sentDeltas } = makeWorkerReporter();
+ const state = makeState({ activeSessionId: "busy-active", sessionId: "busy-session", messages: [] });
+ daemon.sessions.set(state.activeSessionId, state);
+
+ daemon.flushRoster();
+ expect(sentDeltas.at(-1)?.entries.some((entry) => entry.summary.isStreaming === false)).toBe(true);
+
+ // turn_start/bash_start/compaction_start schedule flushes with no message
+ // appended: the entry must recompose, not reuse the idle snapshot.
+ const session = state.runtime.session as unknown as { isStreaming: boolean; isSessionActive: boolean };
+ session.isStreaming = true;
+ session.isSessionActive = true;
+ daemon.flushRoster();
+ const delta = sentDeltas.at(-1);
+ expect(delta?.entries).toHaveLength(1);
+ expect(delta?.entries[0]?.summary).toMatchObject({ isStreaming: true, activity: "working" });
+
+ // Back to idle: the row recomposes again even though no append happened.
+ session.isStreaming = false;
+ session.isSessionActive = false;
+ daemon.flushRoster();
+ expect(sentDeltas.at(-1)?.entries[0]?.summary).toMatchObject({ isStreaming: false, activity: "idle" });
+ });
});
// --- Supervisor-side roster ledger ---
diff --git a/packages/coding-agent/test/daemon-session-list.test.ts b/packages/coding-agent/test/daemon-session-list.test.ts
index 708e83a7ee..8e72f66b7a 100644
--- a/packages/coding-agent/test/daemon-session-list.test.ts
+++ b/packages/coding-agent/test/daemon-session-list.test.ts
@@ -3,6 +3,7 @@ import type { AgentMessage } from "@earendil-works/pi-agent-core";
import { describe, expect, it } from "vitest";
import type { RlmChildAgentSnapshot } from "../src/core/agent-session.js";
import type { AgentCronJob } from "../src/core/cron-jobs.js";
+import type { SessionActionSnapshot } from "../src/core/session-action-store.js";
import type { SessionInfo } from "../src/core/session-manager.js";
import type { SessionUsageSummary } from "../src/core/usage.js";
import type { ActiveSessionState, DaemonSocketClient } from "../src/modes/daemon/active-session-state.js";
@@ -10,8 +11,11 @@ import { passivatedWorkerRosterEntry, workerRosterEntryFromSummary } from "../sr
import {
buildRlmChildSnapshots,
buildSessionList,
+ latestMessageActivityAt,
+ type MessageActivityMemo,
resolveAttachModelFallbackMessage,
type SessionSummary,
+ sessionDisplayLabels,
summaryForActiveSession,
} from "../src/modes/daemon/daemon-session-list.js";
@@ -503,6 +507,214 @@ describe("summaryForActiveSession recap currency", () => {
});
});
+describe("summary compose memoization", () => {
+ const messageAt = (iso: string, content = "hello") =>
+ ({ role: "user", content, timestamp: Date.parse(iso) }) as AgentMessage;
+
+ it("returns the same summary object when nothing changed", () => {
+ const state = makeState({ activeSessionId: "steady", messages: [messageAt("2026-05-01T00:00:00.000Z")] });
+ const first = summaryForActiveSession(state);
+ expect(first).toMatchObject({ messageCount: 1, lastActivityAt: "2026-05-01T00:00:00.000Z" });
+ // Roster flushes recompose every session each cycle; an unchanged session
+ // must reuse the previous summary instead of recomposing it.
+ expect(summaryForActiveSession(state)).toBe(first);
+ });
+
+ it("recomposes when a message is appended and folds only the new tail", () => {
+ const messages = [messageAt("2026-05-01T00:00:00.000Z")];
+ const state = makeState({ activeSessionId: "append", messages });
+ const first = summaryForActiveSession(state);
+ messages.push(messageAt("2026-05-02T00:00:00.000Z"));
+ const second = summaryForActiveSession(state);
+ expect(second).not.toBe(first);
+ expect(second).toMatchObject({ messageCount: 2, lastActivityAt: "2026-05-02T00:00:00.000Z" });
+ // A stale appended timestamp must not unseat the existing latest activity.
+ messages.push(messageAt("2026-05-01T12:00:00.000Z"));
+ const third = summaryForActiveSession(state);
+ expect(third).not.toBe(second);
+ expect(third.lastActivityAt).toBe("2026-05-02T00:00:00.000Z");
+ });
+
+ it("recomposes when busy-state bits flip without an append", () => {
+ const state = makeState({ activeSessionId: "busy", messages: [messageAt("2026-05-01T00:00:00.000Z")] });
+ const first = summaryForActiveSession(state);
+ expect(first.isStreaming).toBe(false);
+ (state.runtime.session as unknown as { isStreaming: boolean }).isStreaming = true;
+ (state.runtime.session as unknown as { isSessionActive: boolean }).isSessionActive = true;
+ const second = summaryForActiveSession(state);
+ expect(second).not.toBe(first);
+ expect(second).toMatchObject({ isStreaming: true, activity: "working" });
+ });
+
+ it("recomposes when the summarizer verdict is replaced", () => {
+ const state = makeState({
+ activeSessionId: "verdict",
+ messages: [messageAt("2026-05-01T00:00:00.000Z")],
+ });
+ const first = summaryForActiveSession(state);
+ expect(first.summary).toBeUndefined();
+ (state as unknown as { summaryState?: object }).summaryState = {
+ summary: "Editing the router",
+ taskState: "completed",
+ basedOnMessageCount: 1,
+ };
+ const second = summaryForActiveSession(state);
+ expect(second).not.toBe(first);
+ expect(second).toMatchObject({ summary: "Editing the router", taskState: "completed" });
+ });
+
+ it("recomposes when the visible action snapshot changes", () => {
+ const state = makeState({ activeSessionId: "queued" });
+ const first = summaryForActiveSession(state);
+ expect(first.sessionActions).toMatchObject({ queuedCount: 0 });
+ (
+ state.runtime.session as unknown as {
+ getSessionActionSnapshot: () => SessionActionSnapshot;
+ }
+ ).getSessionActionSnapshot = () => ({
+ queuedCount: 1,
+ steering: ["revised plan"],
+ followUps: [],
+ });
+ const second = summaryForActiveSession(state);
+ expect(second).not.toBe(first);
+ expect(second.sessionActions).toMatchObject({ queuedCount: 1, steering: ["revised plan"] });
+ });
+
+ it("recomposes when heartbeat registration flags differ per call site", () => {
+ const state = makeState({ activeSessionId: "flags" });
+ const unflagged = summaryForActiveSession(state);
+ expect(unflagged.hasActiveHeartbeat).toBeUndefined();
+ const flagged = summaryForActiveSession(state, undefined, true);
+ expect(flagged).not.toBe(unflagged);
+ expect(flagged.hasActiveHeartbeat).toBe(true);
+ expect(summaryForActiveSession(state, undefined, true)).toBe(flagged);
+ });
+});
+
+describe("latestMessageActivityAt memo", () => {
+ const messageAt = (iso: string, content = "hello") =>
+ ({ role: "user", content, timestamp: Date.parse(iso) }) as AgentMessage;
+
+ function countingArray(messages: AgentMessage[]): { reads: number[]; array: AgentMessage[] } {
+ const reads: number[] = [];
+ const array = new Proxy(messages, {
+ get(target, property, receiver) {
+ if (typeof property === "string" && /^\d+$/.test(property)) reads.push(Number(property));
+ return Reflect.get(target, property, receiver);
+ },
+ });
+ return { reads, array };
+ }
+
+ function freshMemo(): MessageActivityMemo {
+ return { source: undefined, scannedLength: 0, tailRef: undefined, latest: undefined };
+ }
+
+ it("scans the whole array once and then only appended messages", () => {
+ // Twenty messages stand in for a large transcript: the memo must never
+ // re-walk the old prefix once it has scanned it.
+ const messages = Array.from({ length: 20 }, (_, index) =>
+ messageAt(new Date(Date.UTC(2026, 4, 1, 0, 0, index)).toISOString()),
+ );
+ const { reads, array } = countingArray(messages);
+ const memo = freshMemo();
+
+ const latestIso = new Date(Date.UTC(2026, 4, 1, 0, 0, 19)).toISOString();
+ expect(latestMessageActivityAt(array, memo)).toBe(latestIso);
+ expect(reads).toContain(0);
+ expect(memo.scannedLength).toBe(20);
+
+ // Unchanged array: O(1) boundary/tail reads only, no message walk.
+ reads.length = 0;
+ expect(latestMessageActivityAt(array, memo)).toBe(latestIso);
+ expect(reads.length).toBeGreaterThan(0);
+ expect(reads.every((index) => index >= 19)).toBe(true);
+
+ // One append: the boundary check plus the new element, nothing older.
+ messages.push(messageAt("2026-06-01T00:00:00.000Z"));
+ reads.length = 0;
+ expect(latestMessageActivityAt(array, memo)).toBe("2026-06-01T00:00:00.000Z");
+ expect(reads.every((index) => index >= 19)).toBe(true);
+ expect(reads).toContain(20);
+ expect(memo.scannedLength).toBe(21);
+ });
+
+ it("rescans everything after a mid-array insert shifts the boundary", () => {
+ const messages = [messageAt("2026-05-01T00:00:00.000Z"), messageAt("2026-05-04T00:00:00.000Z")];
+ const memo = freshMemo();
+ expect(latestMessageActivityAt(messages, memo)).toBe("2026-05-04T00:00:00.000Z");
+ // Insert before the tail: the pre-error splice path in agent-session.
+ messages.splice(1, 0, messageAt("2026-05-03T00:00:00.000Z"));
+ expect(latestMessageActivityAt(messages, memo)).toBe("2026-05-04T00:00:00.000Z");
+ expect(memo.scannedLength).toBe(3);
+ expect(memo.latest).toBe(Date.parse("2026-05-04T00:00:00.000Z"));
+ });
+
+ it("rescans when the array is replaced or shrinks", () => {
+ const messages = [messageAt("2026-05-01T00:00:00.000Z"), messageAt("2026-05-02T00:00:00.000Z")];
+ const memo = freshMemo();
+ expect(latestMessageActivityAt(messages, memo)).toBe("2026-05-02T00:00:00.000Z");
+ // Compaction and filtering reassign the array; the memo must not trust the old scan.
+ const replacement = [...messages];
+ expect(latestMessageActivityAt(replacement, memo)).toBe("2026-05-02T00:00:00.000Z");
+ replacement.pop();
+ expect(latestMessageActivityAt(replacement, memo)).toBe("2026-05-01T00:00:00.000Z");
+ expect(memo.scannedLength).toBe(1);
+ });
+
+ it("keeps ignoring invalid timestamps on appended messages", () => {
+ const messages = [messageAt("2026-05-01T00:00:00.000Z")];
+ const memo = freshMemo();
+ expect(latestMessageActivityAt(messages, memo)).toBe("2026-05-01T00:00:00.000Z");
+ messages.push({
+ role: "assistant",
+ content: "corrupt",
+ timestamp: 8.64e15 + 1,
+ } as unknown as AgentMessage);
+ expect(latestMessageActivityAt(messages, memo)).toBe("2026-05-01T00:00:00.000Z");
+ expect(memo.scannedLength).toBe(2);
+ });
+
+ it("matches a full rescan on every mutation pattern", () => {
+ const build = (count: number) =>
+ Array.from({ length: count }, (_, index) => messageAt(new Date(2026, 4, 1, 0, 0, index).toISOString()));
+ const messages = build(25);
+ const memo = freshMemo();
+ const fullScan = () => latestMessageActivityAt(messages);
+ for (const mutation of [
+ () => messages.push(messageAt("2026-06-01T00:00:00.000Z")),
+ () => messages.splice(10, 0, messageAt("2026-05-15T00:00:00.000Z")),
+ () => messages.pop(),
+ () => messages.push(messageAt("2026-04-01T00:00:00.000Z")),
+ ]) {
+ mutation();
+ expect(latestMessageActivityAt(messages, memo)).toBe(fullScan());
+ }
+ });
+});
+
+describe("sessionDisplayLabels", () => {
+ it("mirrors the summary's session name and first message", () => {
+ const state = makeState({
+ activeSessionId: "labels",
+ messages: [{ role: "user", content: "first prompt" } as AgentMessage],
+ });
+ const labels = sessionDisplayLabels(state);
+ const summary = summaryForActiveSession(state);
+ expect(labels.sessionName).toBe(summary.sessionName);
+ expect(labels.firstMessage).toBe(summary.firstMessage);
+ });
+
+ it("uses the spawn prompt as the subagent title", () => {
+ const state = makeState({
+ activeSessionId: "spawned",
+ metadata: { kind: "subagent", createdAt: 1, prompt: "Audit the retry\nlogic", rlmChildId: "c1" },
+ });
+ expect(sessionDisplayLabels(state).firstMessage).toBe("Audit the retry logic");
+ });
+});
+
describe("buildRlmChildSnapshots", () => {
it("uses the AgentSession projection and adds resident active session ids", () => {
const queued = {
diff --git a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts b/packages/coding-agent/test/daemon-supervisor-monitor.test.ts
index e900df4a4f..be84102de7 100644
--- a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts
+++ b/packages/coding-agent/test/daemon-supervisor-monitor.test.ts
@@ -512,6 +512,7 @@ describe("daemon worker supervisor monitoring", () => {
cronStore: { list: () => [] },
rosterReporter: {
lastComposed: new Map(),
+ lastComposedSource: new Map(),
lastComposedJson: new Map(),
queuedChildren: new Map(),
removedAgentIds: new Map(),