A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix(coding-agent): catch up only skipped daemon events (#430)
Sebastian Müller3065f5a07b94
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.mdindex 4169c52fcf..b36ed19c68 100644--- a/packages/coding-agent/CHANGELOG.md+++ b/packages/coding-agent/CHANGELOG.md@@ -2,6 +2,7 @@## [Unreleased]+- Fixed daemon backpressure triggering redundant catch-up snapshots for events already queued by the socket.- Fixed incompatible daemon builds crashing startup or respawning after shutdown, with capability negotiation, verified provenance, and convergent force shutdown ([ENG-4687](https://linear.app/primeintellect/issue/ENG-4687/make-daemon-version-mismatches-self-healing)).- Changed top-level CLI help to show concise common options and commands without loading runtime resources ([ENG-4688](https://linear.app/primeintellect/issue/ENG-4688/help-command-is-obscenely-verbose)).- Fixed completed subagents cancelling their RLM heartbeats before the first run ([ENG-4652](https://linear.app/primeintellect/issue/ENG-4652/subagent-heartbeats-dont-work)).diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex 385e47e6cf..d4d7b860a1 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -4534,15 +4534,11 @@ export class AgentDaemon {activeSessionId: state.activeSessionId,});const snapshotId = `${state.activeSessionId}-${state.eventGeneration}-${state.lastEventSequence}`;- const accepted = this.write(client, {+ this.write(client, {...sequencedMessage,messages: [],snapshotFollows: true,});- if (!accepted) {- this.queueClientCatchup(client, state.activeSessionId, "replacement");- continue;- }const snapshotSignal = markClientSnapshotStreaming(client, state.activeSessionId);let transcript: SnapshotTranscriptChunkSource;try {@@ -4585,32 +4581,20 @@ export class AgentDaemon {} catch (error) {this.log(`could not prepare replacement snapshot: ${String(error)}`);// Continue below with the complete replacement event.- let accepted: boolean;if (client.transport === "private-framed") {- accepted = this.write(client, sequencedMessage);+ this.write(client, sequencedMessage);} else {serialized ??= serializeJsonLine(sequencedMessage);- accepted = this.writeSerialized(client, serialized, sequencedMessage);- }- if (!accepted) {- this.queueClientCatchup(client, state.activeSessionId, "replacement");+ this.writeSerialized(client, serialized, sequencedMessage);}}continue;}- let accepted: boolean;if (client.transport === "private-framed") {- accepted = this.write(client, sequencedMessage);+ this.write(client, sequencedMessage);} else {serialized ??= serializeJsonLine(sequencedMessage);- accepted = this.writeSerialized(client, serialized, sequencedMessage);- }- if (!accepted) {- this.queueClientCatchup(- client,- state.activeSessionId,- sequencedMessage.type === "session_replaced" ? "replacement" : "resync",- );+ this.writeSerialized(client, serialized, sequencedMessage);}}}diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.tsindex 46da081dce..f6f8d749de 100644--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts@@ -3110,9 +3110,7 @@ export class DaemonSupervisor {this.queueCatchup(client, activeSessionId, outboundType === "session_replaced" ? "replacement" : "resync");continue;}- if (!this.writeSerialized(client, publicPayload)) {- this.queueCatchup(client, activeSessionId, outboundType === "session_replaced" ? "replacement" : "resync");- }+ this.writeSerialized(client, publicPayload);}if (outboundType === "session_replaced" || outboundType === "session_closed") {void this.refreshWorkerSummaries(worker)diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.tsindex 249f504010..868a870870 100644--- a/packages/coding-agent/test/daemon-mode.test.ts+++ b/packages/coding-agent/test/daemon-mode.test.ts@@ -1,3 +1,4 @@+import { EventEmitter } from "node:events";import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import type { Socket } from "node:net";import { tmpdir } from "node:os";@@ -2884,6 +2885,89 @@ describe("daemon mode helpers", () => {expect(client.catchupActiveSessionIds).not.toContain(state.activeSessionId);});+ it("catches up on drain only after events are skipped behind a backpressured write", async () => {+ const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const state = makeState("active");+ state.eventGeneration = "generation-1";+ const writes: string[] = [];+ const write = vi.fn((data: unknown) => {+ writes.push(String(data));+ return writes.length === 1;+ });+ const socket = Object.assign(new EventEmitter(), { destroyed: false, write }) as unknown as Socket;+ const internals = daemon as unknown as {+ clients: Set<DaemonSocketClient>;+ sessions: Map<string, ActiveSessionState>;+ handleConnection(socket: Socket): void;+ createAttachResult(client: DaemonSocketClient, state: ActiveSessionState): DaemonAttachResult;+ broadcastToSession(+ state: ActiveSessionState,+ message: {+ type: "extension_error";+ activeSessionId: string;+ extensionPath: string;+ event: string;+ error: string;+ },+ ): void;+ };+ internals.handleConnection(socket);+ const client = [...internals.clients][0]!;+ client.attachedActiveSessionIds.add(state.activeSessionId);+ state.clients.add(client);+ internals.sessions.set(state.activeSessionId, state);+ internals.createAttachResult = () =>+ ({+ activeSessionId: state.activeSessionId,+ snapshot: { lastEventSequence: state.lastEventSequence },+ lastEventSequence: state.lastEventSequence,+ }) as unknown as DaemonAttachResult;++ internals.broadcastToSession(state, {+ type: "extension_error",+ activeSessionId: state.activeSessionId,+ extensionPath: "x".repeat(1024 * 1024),+ event: "load",+ error: "first",+ });++ expect(client.backpressured).toBe(true);+ expect(client.catchupActiveSessionIds).toEqual(new Set());+ expect(writes).toHaveLength(2);+ expect(writes[1]).toContain('"error":"first"');++ internals.broadcastToSession(state, {+ type: "extension_error",+ activeSessionId: state.activeSessionId,+ extensionPath: "/tmp/extension.ts",+ event: "load",+ error: "skipped",+ });++ expect(writes).toHaveLength(2);+ expect(client.catchupActiveSessionIds).toEqual(new Set([state.activeSessionId]));++ write.mockImplementation((data: unknown) => {+ writes.push(String(data));+ return true;+ });+ socket.emit("drain");+ await vi.waitFor(() => expect(writes).toHaveLength(3));++ expect(JSON.parse(writes[2] ?? "{}")).toMatchObject({+ type: "session_resynced",+ activeSessionId: state.activeSessionId,+ meta: { sequence: 2, cursor: { generation: "generation-1", sequence: 2 } },+ snapshot: { lastEventSequence: 2 },+ });+ expect(client.catchupActiveSessionIds).toEqual(new Set());+ });+it("marks a chunked attach as snapshotting before deferred streaming", async () => {const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-snapshot-order-"));try {diff --git a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts b/packages/coding-agent/test/daemon-supervisor-monitor.test.tsindex 84aa3818fd..3ea552acb4 100644--- a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts+++ b/packages/coding-agent/test/daemon-supervisor-monitor.test.ts@@ -4,12 +4,17 @@ import { tmpdir } from "node:os";import { join } from "node:path";import type { AgentMessage } from "@earendil-works/pi-agent-core";import { afterEach, describe, expect, it, vi } from "vitest";+import type { DaemonSocketClient } from "../src/modes/daemon/active-session-state.js";import { AgentDaemon } from "../src/modes/daemon/daemon-mode.js";import type { DaemonAttachResult } from "../src/modes/daemon/daemon-protocol.js";import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";import { DaemonSupervisor } from "../src/modes/daemon/daemon-supervisor.js";-import { DAEMON_WORKER_STARTUP_GATE_COMMIT } from "../src/modes/daemon/daemon-worker-protocol.js";+import {+ DAEMON_WORKER_STARTUP_GATE_COMMIT,+ type DaemonWorkerFrameHeader,+} from "../src/modes/daemon/daemon-worker-protocol.js";import { WorkerRecoveryJournal } from "../src/modes/daemon/worker-recovery-journal.js";+import type { PrivateFrame } from "../src/modes/session-worker/private-framing.js";const workerLaunchTestState = vi.hoisted(() => ({capture: false,@@ -1349,6 +1354,59 @@ describe("daemon worker supervisor monitoring", () => {expect(seed).toHaveBeenCalledWith(activeSessionId, streamingMessage);});+ it("catches up only after worker events are skipped behind a backpressured write", async () => {+ const activeSessionId = "active-backpressure";+ const writes: string[] = [];+ const write = vi.fn((data: unknown) => {+ writes.push(String(data));+ return false;+ });+ const client = {+ id: "client-1",+ socket: { destroyed: false, write },+ attachedActiveSessionIds: new Set([activeSessionId]),+ catchupActiveSessionIds: new Set<string>(),+ backpressured: false,+ supportsExtensionUi: false,+ capabilities: new Set(),+ } as unknown as DaemonSocketClient;+ const worker = {+ snapshotCache: new Map(),+ transcriptCaches: new Map(),+ incomingTranscriptActiveSessionIds: new Set(),+ duplicateIncomingTranscriptChunkIndexes: new Map(),+ snapshotTransferFrames: new Map(),+ };+ const catchUpClient = vi.fn(async () => undefined);+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {+ clients: new Set([client]),+ streamReconstructor: { observe: vi.fn() },+ catchUpClient,+ invalidateWorkerSnapshot: vi.fn(),+ }) as {+ handleWorkerFrame(residentWorker: typeof worker, frame: PrivateFrame<DaemonWorkerFrameHeader>): void;+ };+ const frame = (error: string, extensionPath: string): PrivateFrame<DaemonWorkerFrameHeader> => ({+ header: { kind: "outbound", outboundType: "extension_error", activeSessionId },+ payload: Buffer.from(+ `${JSON.stringify({ type: "extension_error", activeSessionId, extensionPath, event: "load", error })}\n`,+ ),+ });++ supervisor.handleWorkerFrame(worker, frame("first", "x".repeat(1024 * 1024)));++ expect(client.backpressured).toBe(true);+ expect(client.catchupActiveSessionIds).toEqual(new Set());+ expect(writes).toHaveLength(1);+ expect(writes[0]).toContain('"error":"first"');++ supervisor.handleWorkerFrame(worker, frame("skipped", "/tmp/extension.ts"));++ expect(writes).toHaveLength(1);+ expect(client.catchupActiveSessionIds).toEqual(new Set([activeSessionId]));+ expect(catchUpClient).not.toHaveBeenCalled();+ });+it("subscribes to worker updates with chunked snapshots", async () => {type SubscriptionWorker = {client: { requestWorker: (command: unknown) => Promise<{ success: boolean }> };