Skip to content

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

Rust

fix(coding-agent): avoid repeated transcript downloads (fixes #2260) (#2296)

Florian Brand327139f7a153
diff --git a/packages/coding-agent/.changes/perf-large-chat-open.md b/packages/coding-agent/.changes/perf-large-chat-open.md
new file mode 100644
index 0000000000..e81ffc37d7
--- /dev/null
+++ b/packages/coding-agent/.changes/perf-large-chat-open.md
@@ -0,0 +1 @@
+- Fixed large chats downloading their transcript again after refreshing the model catalog during startup.
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 c9a63b90ba..54e81a8e86 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
@@ -249,6 +249,10 @@ export class DaemonAgentConnection implements AgentConnection {
private childRosterSequence: number | undefined;
private latestSnapshot: AgentConnectionSnapshot | undefined;
private latestSnapshotIsFresh = false;
+ private latestSnapshotStateIsFresh = false;
+ // Bumped whenever a catalog refresh invalidates state freshness so snapshot
+ // reads already in flight cannot mark stale state fresh again.
+ private stateFreshnessGeneration = 0;
private deferredSessionEvents: {
event: AgentSessionEvent;
sequence: number | undefined;
@@ -522,7 +526,7 @@ export class DaemonAgentConnection implements AgentConnection {
}
async getState(): Promise<AgentConnectionState> {
- if (this.latestSnapshotIsFresh && this.latestSnapshot) {
+ if (this.latestSnapshotIsFresh && this.latestSnapshotStateIsFresh && this.latestSnapshot) {
return this.latestSnapshot.state;
}
return this.requestData<AgentConnectionState>({
@@ -533,13 +537,40 @@ export class DaemonAgentConnection implements AgentConnection {
async getInitialSnapshot(options?: { recoverable?: boolean }): Promise<AgentConnectionSnapshot> {
if (this.latestSnapshotIsFresh && this.latestSnapshot) {
- return this.latestSnapshot;
+ if (this.latestSnapshotStateIsFresh) return this.latestSnapshot;
+ const snapshot = this.latestSnapshot;
+ const stateFreshnessGeneration = this.stateFreshnessGeneration;
+ const state = await this.requestData<AgentConnectionState>(
+ { type: "get_connection_state", activeSessionId: this.activeSessionId },
+ undefined,
+ options,
+ );
+ if (this.latestSnapshotIsFresh && this.latestSnapshot?.messages === snapshot.messages) {
+ const recap = this.latestSnapshot.state.recap;
+ this.latestSnapshot = {
+ ...this.latestSnapshot,
+ state: recap !== snapshot.state.recap ? { ...state, recap } : state,
+ ...(snapshot.sessionContext
+ ? {
+ sessionContext: {
+ ...snapshot.sessionContext,
+ thinkingLevel: state.thinkingLevel,
+ serviceTier: state.serviceTier,
+ model: state.model ? { provider: state.model.provider, modelId: state.model.id } : null,
+ },
+ }
+ : {}),
+ };
+ this.latestSnapshotStateIsFresh = stateFreshnessGeneration === this.stateFreshnessGeneration;
+ return this.latestSnapshot;
+ }
}
// The session tree is intentionally not fetched here: it is large on long
// sessions and only needed when the user opens the tree/branch selector.
// getSessionTree() fetches it lazily via get_session_tree on first use.
const snapshotCursor = this.lastEventCursor;
const snapshotSequence = this.lastEventSequence;
+ const stateFreshnessGeneration = this.stateFreshnessGeneration;
const [state, messagesData, sessionContextData] = await Promise.all([
this.requestData<AgentConnectionState>(
{ type: "get_connection_state", activeSessionId: this.activeSessionId },
@@ -576,6 +607,8 @@ export class DaemonAgentConnection implements AgentConnection {
snapshotSequence === this.lastEventSequence &&
snapshotCursor?.generation === this.lastEventCursor?.generation &&
snapshotCursor?.sequence === this.lastEventCursor?.sequence;
+ this.latestSnapshotStateIsFresh =
+ this.latestSnapshotIsFresh && stateFreshnessGeneration === this.stateFreshnessGeneration;
return this.latestSnapshot;
}
@@ -780,7 +813,7 @@ export class DaemonAgentConnection implements AgentConnection {
}
async getSessionContext(): Promise<AgentConnectionSessionContext> {
- if (this.latestSnapshotIsFresh && this.latestSnapshot?.sessionContext) {
+ if (this.latestSnapshotIsFresh && this.latestSnapshotStateIsFresh && this.latestSnapshot?.sessionContext) {
return this.latestSnapshot.sessionContext;
}
const data = await this.requestData<{ context: AgentConnectionSessionContext }>({
@@ -1831,7 +1864,11 @@ export class DaemonAgentConnection implements AgentConnection {
this.definitiveRequestErrors.add(error);
throw error;
}
- if (invalidatesCachedSnapshot(command.type)) {
+ if (command.type === "get_model_catalog" || command.type === "get_available_models") {
+ // Catalog refresh can change model/auth settings, but does not change the transcript.
+ this.stateFreshnessGeneration++;
+ this.latestSnapshotStateIsFresh = false;
+ } else if (invalidatesCachedSnapshot(command.type)) {
this.latestSnapshotIsFresh = false;
}
return response.data as T;
@@ -2281,6 +2318,7 @@ export class DaemonAgentConnection implements AgentConnection {
this.latestSnapshot.lastEventCursor = this.lastEventCursor;
this.childRosterSequence = Array.isArray(snapshot.children) ? snapshot.lastEventSequence : undefined;
this.latestSnapshotIsFresh = true;
+ this.latestSnapshotStateIsFresh = true;
}
private async completeSnapshotAssembly(
diff --git a/packages/coding-agent/test/suite/regressions/2260-model-catalog-snapshot.test.ts b/packages/coding-agent/test/suite/regressions/2260-model-catalog-snapshot.test.ts
new file mode 100644
index 0000000000..9806c84054
--- /dev/null
+++ b/packages/coding-agent/test/suite/regressions/2260-model-catalog-snapshot.test.ts
@@ -0,0 +1,201 @@
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import { getModel } from "@earendil-works/pi-ai";
+import { describe, expect, it, vi } from "vitest";
+import { DaemonAgentConnection } from "../../../src/modes/agent-connection/daemon-agent-connection.js";
+import type { AgentConnectionState } from "../../../src/modes/agent-connection/types.js";
+import type { DaemonClientMessageListener, DaemonTransportClient } from "../../../src/modes/daemon/daemon-client.js";
+import type { DaemonCommand } from "../../../src/modes/daemon/daemon-protocol.js";
+
+async function createConnection(modelCatalog = true, deferSessionEvents = false) {
+ const messages: AgentMessage[] = [{ role: "user", content: "saved transcript", timestamp: 1 }];
+ const updatedMessages: AgentMessage[] = [{ role: "user", content: "updated transcript", timestamp: 2 }];
+ const model = getModel("xai", "grok-4.5");
+ const state = { sessionId: "session", model, thinkingLevel: "high", serviceTier: "default" } as AgentConnectionState;
+ const refreshedState = { ...state, model: { ...model, api: "openai-responses" }, thinkingLevel: "low" };
+ let listener: DaemonClientMessageListener | undefined;
+ let duringStateRead: (() => void) | undefined;
+ const request = vi.fn(async (command: Pick<DaemonCommand, "type">) => {
+ if (command.type === "get_connection_state") duringStateRead?.();
+ const data = {
+ attach: {
+ activeSessionId: "active",
+ snapshot: {
+ state,
+ messages,
+ sessionContext: { messages, thinkingLevel: "high" },
+ summary: { sessionId: "session" },
+ },
+ },
+ get_model_catalog: { models: [model], configuredProviders: ["xai"] },
+ get_available_models: { models: [model] },
+ get_connection_state: refreshedState,
+ get_messages: { messages: updatedMessages },
+ get_session_context: { context: { messages: updatedMessages } },
+ };
+ return { type: "response", command: command.type, success: true, data: data[command.type as keyof typeof data] };
+ });
+ const client = {
+ request,
+ onMessage: (callback: DaemonClientMessageListener) => {
+ listener = callback;
+ return () => {};
+ },
+ onClose: () => () => {},
+ supportsServerCapability: () => modelCatalog,
+ } as unknown as DaemonTransportClient;
+ const connection = new DaemonAgentConnection(client, "active", { deferSessionEvents });
+ await connection.attach();
+ return {
+ connection,
+ request,
+ messages,
+ updatedMessages,
+ refreshedState,
+ setDuringStateRead: (callback: (() => void) | undefined) => {
+ duringStateRead = callback;
+ },
+ emitStatus: (recap: string) => listener?.({ type: "session_status", activeSessionId: "active", recap }),
+ emit: () =>
+ listener?.({
+ type: "session_event",
+ activeSessionId: "active",
+ event: { type: "message_end", message: updatedMessages[0]! },
+ }),
+ };
+}
+
+describe("model catalog refresh preserves the attached transcript", () => {
+ it.each(["catalog", "legacyCatalog", "available"])(
+ "refreshes model state without downloading messages after %s",
+ async (refresh) => {
+ const { connection, request, messages, refreshedState } = await createConnection(refresh !== "legacyCatalog");
+ try {
+ if (refresh === "available") await connection.getAvailableModels();
+ else await connection.getModelCatalog();
+ expect(await connection.getState()).toBe(refreshedState);
+ const snapshot = await connection.getInitialSnapshot();
+ expect(snapshot.state).toBe(refreshedState);
+ expect(snapshot.messages).toBe(messages);
+ expect(snapshot.sessionContext).toMatchObject({
+ messages,
+ thinkingLevel: "low",
+ model: { provider: "xai", modelId: refreshedState.model.id },
+ });
+ expect(request.mock.calls.map(([command]) => command.type)).not.toContain("get_messages");
+ expect(request.mock.calls.map(([command]) => command.type)).not.toContain("get_session_context");
+ request.mockClear();
+ expect(await connection.getInitialSnapshot()).toBe(snapshot);
+ expect(await connection.getState()).toBe(snapshot.state);
+ expect(await connection.getSessionContext()).toBe(snapshot.sessionContext);
+ expect(request).not.toHaveBeenCalled();
+ } finally {
+ await connection.dispose();
+ }
+ },
+ );
+
+ it("still reloads the transcript after a session mutation", async () => {
+ const { connection, request, updatedMessages } = await createConnection();
+ try {
+ await connection.getModelCatalog();
+ await connection.setThinkingLevel("medium");
+ const snapshot = await connection.getInitialSnapshot();
+ expect(snapshot.messages).toBe(updatedMessages);
+ expect(request.mock.calls.map(([command]) => command.type)).toContain("get_messages");
+ request.mockClear();
+ expect(await connection.getInitialSnapshot()).toBe(snapshot);
+ expect(await connection.getState()).toBe(snapshot.state);
+ expect(await connection.getSessionContext()).toBe(snapshot.sessionContext);
+ expect(request).not.toHaveBeenCalled();
+ } finally {
+ await connection.dispose();
+ }
+ });
+
+ it("keeps a concurrent recap update without downloading the transcript", async () => {
+ const { connection, request, messages, emitStatus, setDuringStateRead } = await createConnection();
+ try {
+ await connection.getModelCatalog();
+ setDuringStateRead(() => emitStatus("Updated recap"));
+ request.mockClear();
+ const snapshot = await connection.getInitialSnapshot();
+ expect(snapshot.messages).toBe(messages);
+ expect(snapshot.state.recap).toBe("Updated recap");
+ expect(await connection.getInitialSnapshot()).toBe(snapshot);
+ expect(request.mock.calls.map(([command]) => command.type)).toEqual(["get_connection_state"]);
+ } finally {
+ await connection.dispose();
+ }
+ });
+
+ it("preserves deferred updates and invalidates the transcript when they replay", async () => {
+ const { connection, messages, updatedMessages, emit } = await createConnection(true, true);
+ try {
+ await connection.getModelCatalog();
+ emit();
+ expect((await connection.getInitialSnapshot()).messages).toBe(messages);
+ await connection.flushBufferedSessionEvents();
+ expect((await connection.getInitialSnapshot()).messages).toBe(updatedMessages);
+ } finally {
+ await connection.dispose();
+ }
+ });
+
+ it("reloads if a live event invalidates the transcript during the state refresh", async () => {
+ const { connection, updatedMessages, emit, setDuringStateRead } = await createConnection();
+ try {
+ await connection.getModelCatalog();
+ setDuringStateRead(emit);
+ expect((await connection.getInitialSnapshot()).messages).toBe(updatedMessages);
+ } finally {
+ await connection.dispose();
+ }
+ });
+
+ it("keeps state stale when a catalog refresh lands during the state re-read", async () => {
+ const { connection, request, messages, refreshedState, setDuringStateRead } = await createConnection();
+ try {
+ await connection.getModelCatalog();
+ setDuringStateRead(() => void connection.getAvailableModels());
+ const snapshot = await connection.getInitialSnapshot();
+ expect(snapshot.messages).toBe(messages);
+ // The concurrent catalog refresh must preserve the invalidation: getState()
+ // re-reads state instead of trusting the merged snapshot's state.
+ expect(await connection.getState()).toBe(refreshedState);
+ expect(request.mock.calls.filter(([command]) => command.type === "get_connection_state")).toHaveLength(2);
+ setDuringStateRead(undefined);
+ const merged = await connection.getInitialSnapshot();
+ expect(merged.state).toBe(refreshedState);
+ expect(await connection.getInitialSnapshot()).toBe(merged);
+ expect(await connection.getState()).toBe(merged.state);
+ expect(request.mock.calls.filter(([command]) => command.type === "get_connection_state")).toHaveLength(3);
+ expect(request.mock.calls.filter(([command]) => command.type === "get_messages")).toHaveLength(0);
+ expect(request.mock.calls.filter(([command]) => command.type === "get_session_context")).toHaveLength(0);
+ } finally {
+ await connection.dispose();
+ }
+ });
+
+ it("keeps state stale when a catalog refresh lands during a full snapshot reload", async () => {
+ const { connection, request, updatedMessages, refreshedState, setDuringStateRead } = await createConnection();
+ try {
+ await connection.getModelCatalog();
+ await connection.setThinkingLevel("medium");
+ setDuringStateRead(() => void connection.getAvailableModels());
+ const snapshot = await connection.getInitialSnapshot();
+ expect(snapshot.messages).toBe(updatedMessages);
+ // The concurrent catalog refresh must preserve the invalidation even
+ // though the transcript cursor guard passed: getState() re-reads state.
+ expect(await connection.getState()).toBe(refreshedState);
+ expect(request.mock.calls.filter(([command]) => command.type === "get_connection_state")).toHaveLength(2);
+ setDuringStateRead(undefined);
+ const merged = await connection.getInitialSnapshot();
+ expect(merged.messages).toBe(updatedMessages);
+ expect(await connection.getInitialSnapshot()).toBe(merged);
+ expect(request.mock.calls.filter(([command]) => command.type === "get_messages")).toHaveLength(1);
+ expect(request.mock.calls.filter(([command]) => command.type === "get_session_context")).toHaveLength(1);
+ } finally {
+ await connection.dispose();
+ }
+ });
+});