Skip to content

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

Rust

fix(daemon): transfer session trees as flat nodes (#553)

Sebastian Müller4f097f629eb7
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index 2eff5466d2..dbca510aa8 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -2,6 +2,8 @@
## [Unreleased]
+- Fixed `/tree` overflowing the daemon serializer on very deep sessions by transferring a flat session tree.
+
- Added starting a new session directly from the agents view with `ctrl+n`.
- Added queueing a reply as a follow-up with `alt+enter` in the agents-view reply composer; plain Enter now steers a streaming agent.
- Added session-owned slash commands (`/compact`, `/refine`, `/goal`, `/autonomous`) with autocomplete to the agents-view reply composer; other built-in commands are rejected with guidance instead of being sent as prompt text.
diff --git a/packages/coding-agent/src/core/session-manager.ts b/packages/coding-agent/src/core/session-manager.ts
index ba23f1fdcb..d1436f3846 100644
--- a/packages/coding-agent/src/core/session-manager.ts
+++ b/packages/coding-agent/src/core/session-manager.ts
@@ -261,15 +261,18 @@ export type SessionEntry =
export type FileEntry = SessionHeader | SessionEntry;
/** Tree node for getTree() - defensive copy of session structure */
-export interface SessionTreeNode {
+export interface SessionTreeFlatNode {
entry: SessionEntry;
- children: SessionTreeNode[];
/** Resolved label for this entry, if any */
label?: string;
/** Timestamp of the latest label change for this entry, if any */
labelTimestamp?: string;
}
+export interface SessionTreeNode extends SessionTreeFlatNode {
+ children: SessionTreeNode[];
+}
+
export interface SessionContext {
messages: AgentMessage[];
thinkingLevel: string;
@@ -1797,20 +1800,27 @@ export class SessionManager {
* A well-formed session has exactly one root (first entry with parentId === null).
* Orphaned entries (broken parent chain) are also returned as roots.
*/
+ getFlatTree(): SessionTreeFlatNode[] {
+ return this.getEntries().map((entry) => ({
+ entry,
+ label: this.labelsById.get(entry.id),
+ labelTimestamp: this.labelTimestampsById.get(entry.id),
+ }));
+ }
+
getTree(): SessionTreeNode[] {
- const entries = this.getEntries();
+ const entries = this.getFlatTree();
const nodeMap = new Map<string, SessionTreeNode>();
const roots: SessionTreeNode[] = [];
// Create nodes with resolved labels
- for (const entry of entries) {
- const label = this.labelsById.get(entry.id);
- const labelTimestamp = this.labelTimestampsById.get(entry.id);
- nodeMap.set(entry.id, { entry, children: [], label, labelTimestamp });
+ for (const flatNode of entries) {
+ nodeMap.set(flatNode.entry.id, { ...flatNode, children: [] });
}
// Build tree
- for (const entry of entries) {
+ for (const flatNode of entries) {
+ const entry = flatNode.entry;
const node = nodeMap.get(entry.id)!;
if (entry.parentId === null || entry.parentId === entry.id) {
roots.push(node);
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.ts
index 041405aee9..1aa3c82462 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
@@ -72,6 +72,7 @@ import type {
AgentConnectionSessionContext,
AgentConnectionSessionHeader,
AgentConnectionSessionListCallbacks,
+ AgentConnectionSessionTreeFlatNode,
AgentConnectionSessionTreeNode,
AgentConnectionSessionWatcher,
AgentConnectionSideQuestionEvent,
@@ -178,6 +179,31 @@ export interface DaemonAgentConnectionOptions {
* InteractiveMode depends only on AgentConnection; local socket ownership and
* daemon command details stay inside this adapter.
*/
+export function buildSessionTreeFromFlatNodes(
+ flatNodes: readonly AgentConnectionSessionTreeFlatNode[],
+): AgentConnectionSessionTreeNode[] {
+ const byId = new Map<string, AgentConnectionSessionTreeNode>();
+ const roots: AgentConnectionSessionTreeNode[] = [];
+ for (const flatNode of flatNodes) {
+ byId.set(flatNode.entry.id, { ...flatNode, children: [] });
+ }
+ for (const flatNode of flatNodes) {
+ const entry = flatNode.entry;
+ const node = byId.get(entry.id)!;
+ const parent = entry.parentId === null || entry.parentId === entry.id ? undefined : byId.get(entry.parentId);
+ if (parent) parent.children.push(node);
+ else roots.push(node);
+ }
+ // Match SessionManager.getTree() ordering without recursively walking deep
+ // chains: every node is already indexed, so sort each sibling array directly.
+ for (const node of byId.values()) {
+ node.children.sort(
+ (left, right) => new Date(left.entry.timestamp).getTime() - new Date(right.entry.timestamp).getTime(),
+ );
+ }
+ return roots;
+}
+
export class DaemonAgentConnection implements AgentConnection {
private readonly listeners = new Set<AgentConnectionEventListener>();
private readonly unsubscribeDaemonMessages: () => void;
@@ -479,10 +505,14 @@ export class DaemonAgentConnection implements AgentConnection {
if (this.latestSnapshotIsFresh && this.latestSnapshot?.sessionTree) {
return this.latestSnapshot.sessionTree;
}
- return this.requestData<{ tree: AgentConnectionSessionTreeNode[]; leafId: string | null }>({
+ const data = await this.requestData<{
+ flatNodes: AgentConnectionSessionTreeFlatNode[];
+ leafId: string | null;
+ }>({
type: "get_session_tree",
activeSessionId: this.activeSessionId,
});
+ return { tree: buildSessionTreeFromFlatNodes(data.flatNodes), leafId: data.leafId };
}
async listSavedSessions(
diff --git a/packages/coding-agent/src/modes/agent-connection/types.ts b/packages/coding-agent/src/modes/agent-connection/types.ts
index dda657cffd..cf885c21b7 100644
--- a/packages/coding-agent/src/modes/agent-connection/types.ts
+++ b/packages/coding-agent/src/modes/agent-connection/types.ts
@@ -248,13 +248,16 @@ export type AgentConnectionSessionEntry =
| AgentConnectionAgentStatusEntry
| AgentConnectionGitStateEntry;
-export interface AgentConnectionSessionTreeNode {
+export interface AgentConnectionSessionTreeFlatNode {
entry: AgentConnectionSessionEntry;
- children: AgentConnectionSessionTreeNode[];
label?: string;
labelTimestamp?: string;
}
+export interface AgentConnectionSessionTreeNode extends AgentConnectionSessionTreeFlatNode {
+ children: AgentConnectionSessionTreeNode[];
+}
+
export interface AgentConnectionSessionContext {
messages: AgentMessage[];
thinkingLevel: string;
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index d465c267f5..a284cb39c6 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -3746,7 +3746,7 @@ export class AgentDaemon {
case "get_session_tree": {
const state = this.getSessionState(command.activeSessionId);
return success(command.id, "get_session_tree", {
- tree: state.runtime.session.sessionManager.getTree(),
+ flatNodes: state.runtime.session.sessionManager.getFlatTree(),
leafId: state.runtime.session.sessionManager.getLeafId(),
});
}
diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
index bf84adf971..304a1f29f2 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
@@ -48,11 +48,12 @@ import type { SessionSummary } from "./daemon-session-list.js";
*/
export const DAEMON_PROTOCOL_NAME = "prime-agent.daemon";
-export const DAEMON_PROTOCOL_VERSION = 5;
+export const DAEMON_PROTOCOL_VERSION = 6;
export const DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION = 2;
// Revision 6 combines prompt-admission cancellation with side-question transcripts and transient bash.
-export const DAEMON_SCHEMA_REVISION = 6;
-export const DAEMON_SCHEMA_ID = "protocol-5-schema-6-48a562b9bffe";
+// Revision 7 makes get_session_tree return flatNodes instead of a recursively nested tree.
+export const DAEMON_SCHEMA_REVISION = 7;
+export const DAEMON_SCHEMA_ID = "protocol-6-schema-7-48a562b9bffe";
export type DaemonProtocolName = typeof DAEMON_PROTOCOL_NAME;
export type DaemonProtocolVersion = number;
@@ -625,6 +626,7 @@ const CLIENT_OWNED_DAEMON_COMMAND = {
minProtocol: 4,
capability: "client_owned_sessions",
} as const;
+const FLAT_SESSION_TREE_COMMAND = { minProtocol: 6 } as const;
export const DAEMON_COMMAND_COMPATIBILITY = {
ack_result: LEGACY_DAEMON_COMMAND,
@@ -709,7 +711,7 @@ export const DAEMON_COMMAND_COMPATIBILITY = {
rename_saved_session: LEGACY_DAEMON_COMMAND,
delete_saved_session: LEGACY_DAEMON_COMMAND,
get_session_context: LEGACY_DAEMON_COMMAND,
- get_session_tree: LEGACY_DAEMON_COMMAND,
+ get_session_tree: FLAT_SESSION_TREE_COMMAND,
get_user_messages_for_forking: LEGACY_DAEMON_COMMAND,
get_last_assistant_text: LEGACY_DAEMON_COMMAND,
get_system_prompt: LEGACY_DAEMON_COMMAND,
diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
index f66e3fa585..096eea28f5 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
@@ -42,6 +42,7 @@ import { deserializeDaemonError, serializeDaemonError } from "./daemon-errors.js
import {
collectDaemonClientEnv,
createDaemonEventMeta,
+ DAEMON_COMMAND_COMPATIBILITY,
DAEMON_DEFAULT_CLIENT_CAPABILITIES,
DAEMON_DEFAULT_SERVER_CAPABILITIES,
DAEMON_PROTOCOL_INFO,
@@ -1015,12 +1016,12 @@ export class DaemonSupervisor {
): {
command: DaemonCommand;
envelopeClientId?: string;
+ protocolVersion: number;
admission?: SupervisorPromptAdmission;
} {
const parsed = JSON.parse(line) as unknown;
- const command = (
- isDaemonCommandEnvelope(parsed) ? { ...parsed.command, id: parsed.id } : parsed
- ) as DaemonCommand;
+ const envelope = isDaemonCommandEnvelope(parsed) ? parsed : undefined;
+ const command = (envelope ? { ...envelope.command, id: envelope.id } : parsed) as DaemonCommand;
let admission: SupervisorPromptAdmission | undefined;
if ((command.type === "prompt" || command.type === "prompt_and_wait") && command.admissionId !== undefined) {
if (typeof command.activeSessionId !== "string" || typeof command.admissionId !== "string") {
@@ -1044,7 +1045,8 @@ export class DaemonSupervisor {
}
return {
command,
- envelopeClientId: isDaemonCommandEnvelope(parsed) ? (parsed.clientId ?? client.id) : undefined,
+ envelopeClientId: envelope ? (envelope.clientId ?? client.id) : undefined,
+ protocolVersion: envelope?.protocol.version ?? 1,
admission,
};
}
@@ -1088,6 +1090,20 @@ export class DaemonSupervisor {
this.write(client, failure(command.id, command.type, `Unknown daemon command: ${command.type}`));
return;
}
+ if (
+ command.type === "get_session_tree" &&
+ preParsed.protocolVersion < DAEMON_COMMAND_COMPATIBILITY.get_session_tree.minProtocol
+ ) {
+ this.write(
+ client,
+ failure(
+ command.id,
+ command.type,
+ `get_session_tree requires client protocol ${DAEMON_COMMAND_COMPATIBILITY.get_session_tree.minProtocol} or newer`,
+ ),
+ );
+ return;
+ }
try {
await waitForPromptAdmission(this.assertCurrentOwnership(), parsedAdmission?.controller.signal);
diff --git a/packages/coding-agent/test/agent-connection-daemon.test.ts b/packages/coding-agent/test/agent-connection-daemon.test.ts
index b27f6adecb..9a7d81f130 100644
--- a/packages/coding-agent/test/agent-connection-daemon.test.ts
+++ b/packages/coding-agent/test/agent-connection-daemon.test.ts
@@ -217,7 +217,7 @@ class FakeDaemonClient {
command: command.type,
success: true,
data: {
- tree: [
+ flatNodes: [
{
entry: {
type: "message",
@@ -226,7 +226,6 @@ class FakeDaemonClient {
timestamp: "2026-01-01T00:00:00.000Z",
message: { role: "user", content: "hello", timestamp: 1 },
},
- children: [],
},
],
leafId: "user-1",
diff --git a/packages/coding-agent/test/daemon-client.test.ts b/packages/coding-agent/test/daemon-client.test.ts
index 862e6b7140..f7d6cc8c1e 100644
--- a/packages/coding-agent/test/daemon-client.test.ts
+++ b/packages/coding-agent/test/daemon-client.test.ts
@@ -215,6 +215,21 @@ describe("DaemonClient", () => {
client.close();
});
+ it("rejects flat session-tree requests to an old daemon", async () => {
+ const client = new DaemonClient("/tmp/prime-agent.sock");
+ const connect = client.connect();
+ const socket = netMock.sockets[0]!;
+ socket.emit("connect");
+ await connect;
+ emitHello(socket, 5);
+
+ await expect(client.request({ type: "get_session_tree", activeSessionId: "active-1" })).rejects.toThrow(
+ "does not support get_session_tree",
+ );
+ expect(socket.writes).toEqual([]);
+ client.close();
+ });
+
it("rejects session input admission clearly when an old daemon lacks the capability", async () => {
const client = new DaemonClient("/tmp/prime-agent.sock");
const connect = client.connect();
diff --git a/packages/coding-agent/test/daemon-protocol.test.ts b/packages/coding-agent/test/daemon-protocol.test.ts
index 8509ec7426..677f667f20 100644
--- a/packages/coding-agent/test/daemon-protocol.test.ts
+++ b/packages/coding-agent/test/daemon-protocol.test.ts
@@ -36,7 +36,7 @@ describe("daemon protocol helpers", () => {
});
it("requires compatibility metadata for the heartbeat protocol surface", () => {
- expect(DAEMON_PROTOCOL_VERSION).toBe(5);
+ expect(DAEMON_PROTOCOL_VERSION).toBe(6);
expect(DAEMON_SCHEMA_ID).toContain(`protocol-${DAEMON_PROTOCOL_VERSION}`);
expect(DAEMON_COMMAND_COMPATIBILITY.heartbeats_list).toEqual({
minProtocol: 3,
diff --git a/packages/coding-agent/test/daemon-supervisor-side-question.test.ts b/packages/coding-agent/test/daemon-supervisor-side-question.test.ts
index 3e4d3cb6fc..fc717d66bc 100644
--- a/packages/coding-agent/test/daemon-supervisor-side-question.test.ts
+++ b/packages/coding-agent/test/daemon-supervisor-side-question.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, it, vi } from "vitest";
import type { DaemonSocketClient } from "../src/modes/daemon/active-session-state.js";
-import type { DaemonCommand, DaemonResponse } from "../src/modes/daemon/daemon-protocol.js";
+import {
+ createDaemonCommandEnvelope,
+ DAEMON_COMMAND_COMPATIBILITY,
+ type DaemonCommand,
+ type DaemonResponse,
+} from "../src/modes/daemon/daemon-protocol.js";
import { DaemonSupervisor } from "../src/modes/daemon/daemon-supervisor.js";
import { MutationDrainLatch } from "../src/modes/daemon/mutation-drain-latch.js";
@@ -57,4 +62,45 @@ describe("daemon supervisor side-question routing", () => {
expect.objectContaining({ command: "abort_side_question", success: true }),
]);
});
+ it("rejects flat session-tree requests from an old client", async () => {
+ const handleCommand = vi.fn();
+ const write = vi.fn();
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ ready: Promise.resolve(),
+ ownership: { assertCurrent: vi.fn(async () => undefined) },
+ workers: new Map(),
+ clients: new Set(),
+ protocolClientIds: new WeakMap(),
+ mutationDrain: new MutationDrainLatch(),
+ cancelOwnedWorkerCleanup: vi.fn(),
+ handleCommand,
+ write,
+ log: vi.fn(),
+ }) as SupervisorHarness;
+ const client = { id: "old-client" } as DaemonSocketClient;
+ const command = { type: "get_session_tree", activeSessionId: "active-1" } as const;
+
+ await supervisor.handleLine(
+ client,
+ JSON.stringify(
+ createDaemonCommandEnvelope(
+ command,
+ "tree-1",
+ undefined,
+ DAEMON_COMMAND_COMPATIBILITY.get_session_tree.minProtocol - 1,
+ ),
+ ),
+ );
+
+ expect(handleCommand).not.toHaveBeenCalled();
+ expect(write).toHaveBeenCalledWith(
+ client,
+ expect.objectContaining({
+ id: "tree-1",
+ command: "get_session_tree",
+ success: false,
+ error: expect.stringContaining("requires client protocol 6"),
+ }),
+ );
+ });
});