Skip to content

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

Rust

fix(coding-agent): keep restored transcripts visible when render steps fail (ENG-4742) (#2214)

Seth Kartendbd29e948af4
diff --git a/packages/coding-agent/.changes/eng-4742-transcript-survives-render-failures.md b/packages/coding-agent/.changes/eng-4742-transcript-survives-render-failures.md
new file mode 100644
index 0000000000..b7bd9e46ed
--- /dev/null
+++ b/packages/coding-agent/.changes/eng-4742-transcript-survives-render-failures.md
@@ -0,0 +1,2 @@
+- Fixed re-opened sessions rendering an empty transcript until the next message when a transient control-plane failure interrupted the initial render.
+- Fixed one unrenderable message aborting the whole transcript rebuild during a session resync.
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index ee9d749fc8..f055fd335c 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -578,6 +578,9 @@ const DEAD_TERMINAL_ERROR_CODES = new Set(["EIO", "EPIPE", "ENOTCONN"]);
// evicted past the cap to keep a long session bounded.
const MAX_PASTED_IMAGE_BYTES = 64 * 1024 * 1024;
const INITIAL_TRANSCRIPT_RENDER_MESSAGE_LIMIT = 400;
+// Coalesce at most this many heartbeats_changed refreshes into one refresh
+// promise; sustained churn must not hold rebindCurrentSession in a drain loop.
+const HEARTBEAT_REFRESH_DRAIN_LIMIT = 25;
function initialRenderMessages(messages: AgentMessage[]): AgentMessage[] {
if (messages.length <= INITIAL_TRANSCRIPT_RENDER_MESSAGE_LIMIT) {
@@ -2582,15 +2585,24 @@ export class InteractiveMode {
}
const connection = this.agentConnection;
const refresh = (async () => {
- do {
+ // Bound the drain loop: sustained heartbeats_changed churn must not
+ // starve an awaiting rebind (and its transcript render) indefinitely.
+ for (let drain = 0; drain <= HEARTBEAT_REFRESH_DRAIN_LIMIT; drain++) {
this.heartbeatRefreshRequested = false;
const heartbeats = await connection.listHeartbeats();
if (this.agentConnection !== connection) return;
this.applyHeartbeatCatalog(heartbeats);
- } while (this.heartbeatRefreshRequested);
+ if (!this.heartbeatRefreshRequested) return;
+ }
})().finally(() => {
if (this.heartbeatRefreshPromise === refresh) {
this.heartbeatRefreshPromise = undefined;
+ // The drain bound was hit with a newer heartbeats_changed
+ // pending: schedule the follow-up refresh so the catalog
+ // converges instead of staying stale until the next event.
+ if (this.heartbeatRefreshRequested) {
+ void this.refreshHeartbeatCatalog().catch(() => undefined);
+ }
}
});
this.heartbeatRefreshPromise = refresh;
@@ -2842,13 +2854,27 @@ export class InteractiveMode {
await this.bindCurrentSessionExtensions();
} else {
setRegisteredThemes(this.uiServices.getThemes());
- await this.refreshConnectionCatalog();
+ // Best-effort: the catalog enriches the composer (commands, models,
+ // resources). A transient control-plane failure must not abort the
+ // rebind and leave the transcript unrendered.
+ try {
+ await this.refreshConnectionCatalog();
+ } catch {
+ // Keep the previous catalog; reconnects re-fetch it.
+ }
this.setupAutocompleteProvider();
}
this.subscribeToAgent();
await this.subscribeToRosterBar();
// A session_action_update in the unsubscribed gap above is lost; re-sync the queue post-subscription.
- this.patchConnectionState({ sessionActions: (await this.agentConnection.getState()).sessionActions });
+ // Best-effort: a transient control-plane failure must not abort the
+ // rebind and leave the transcript unrendered.
+ try {
+ this.patchConnectionState({ sessionActions: (await this.agentConnection.getState()).sessionActions });
+ } catch {
+ // Keep the attached snapshot's session actions; the next connection
+ // state update re-syncs them.
+ }
this.refreshQueueSelectionFromState();
this.updatePendingMessagesDisplay();
await this.refreshHeartbeatCatalog().catch(() => undefined);
@@ -6417,12 +6443,27 @@ export class InteractiveMode {
}
}
}
- await this.preloadToolDefinitions(toolNames);
+ // Tool definitions only enrich rendering: components fall back to
+ // cached or missing definitions. A transient control-plane failure here
+ // must not abort the render (a resync render aborts into an empty chat).
+ let toolDefinitionWarning: string | undefined;
+ try {
+ await this.preloadToolDefinitions(toolNames);
+ } catch (error) {
+ toolDefinitionWarning = `Could not load tool definitions: ${
+ error instanceof Error ? error.message : String(error)
+ }`;
+ }
if (options.clearChat) {
this.chatContainer.clear();
}
+ // Shown after clearChat so rebuild/resync renders keep the warning.
+ if (toolDefinitionWarning) {
+ this.showWarning(toolDefinitionWarning);
+ }
+
if (options.updateFooter) {
this.footer.invalidate();
this.updateEditorBorderColor();
@@ -6451,61 +6492,81 @@ export class InteractiveMode {
}
for (const message of messagesToRender) {
- // Assistant messages need special handling for tool calls
- if (message.role === "assistant") {
- this.addMessageToChat(message);
- // Render tool call components
- for (const content of message.content) {
- if (content.type === "toolCall") {
- const spacing = createConversationSpacing(this.chatContainer.children);
- const component = new ToolExecutionComponent(
- content.name,
- content.id,
- content.arguments,
- {
- showImages: this.settingsManager.getShowImages(),
- includeImageDimensions: false,
- shouldAddLeadingSpace: () => spacing.shouldAddLeadingSpace(true),
- },
- this.getCachedToolDefinition(content.name),
- this.ui,
- this.getCurrentCwd(),
- );
- component.setExpanded(this.toolOutputExpanded);
- component.setEditDiffsExpanded(this.editDiffsExpanded);
- selectLatestToolExpandHint(this.chatContainer.children, component);
- this.chatContainer.addChild(component);
- this.registerIpythonToolComponent(content.name, content.id, component);
-
- if (message.stopReason === "aborted" || message.stopReason === "error") {
- let errorMessage: string;
- if (message.stopReason === "aborted") {
- const retryAttempt = this.getRetryAttempt();
- errorMessage =
- retryAttempt > 0
- ? `Aborted after ${retryAttempt} retry attempt${retryAttempt > 1 ? "s" : ""}`
- : message.errorMessage && message.errorMessage !== "Request was aborted"
- ? message.errorMessage
- : "Operation aborted";
+ // One unrenderable message must not abort the whole transcript:
+ // the chat container may already be cleared for this render.
+ try {
+ // Assistant messages need special handling for tool calls
+ if (message.role === "assistant") {
+ this.addMessageToChat(message);
+ // Render tool call components
+ for (const content of message.content) {
+ if (content.type === "toolCall") {
+ const spacing = createConversationSpacing(this.chatContainer.children);
+ const component = new ToolExecutionComponent(
+ content.name,
+ content.id,
+ content.arguments,
+ {
+ showImages: this.settingsManager.getShowImages(),
+ includeImageDimensions: false,
+ shouldAddLeadingSpace: () => spacing.shouldAddLeadingSpace(true),
+ },
+ this.getCachedToolDefinition(content.name),
+ this.ui,
+ this.getCurrentCwd(),
+ );
+ component.setExpanded(this.toolOutputExpanded);
+ component.setEditDiffsExpanded(this.editDiffsExpanded);
+ selectLatestToolExpandHint(this.chatContainer.children, component);
+ this.chatContainer.addChild(component);
+ this.registerIpythonToolComponent(content.name, content.id, component);
+
+ if (message.stopReason === "aborted" || message.stopReason === "error") {
+ let errorMessage: string;
+ if (message.stopReason === "aborted") {
+ const retryAttempt = this.getRetryAttempt();
+ errorMessage =
+ retryAttempt > 0
+ ? `Aborted after ${retryAttempt} retry attempt${retryAttempt > 1 ? "s" : ""}`
+ : message.errorMessage && message.errorMessage !== "Request was aborted"
+ ? message.errorMessage
+ : "Operation aborted";
+ } else {
+ errorMessage = message.errorMessage || "Error";
+ }
+ component.updateResult({ content: [{ type: "text", text: errorMessage }], isError: true });
} else {
- errorMessage = message.errorMessage || "Error";
+ renderedPendingTools.set(content.id, component);
}
- component.updateResult({ content: [{ type: "text", text: errorMessage }], isError: true });
- } else {
- renderedPendingTools.set(content.id, component);
}
}
+ } else if (message.role === "toolResult") {
+ // Match tool results to pending tool components
+ const component = renderedPendingTools.get(message.toolCallId);
+ if (component) {
+ // Delete first: a throwing updateResult must not leave the
+ // completed result reported as still pending.
+ renderedPendingTools.delete(message.toolCallId);
+ component.updateResult(message);
+ }
+ } else {
+ // All other messages use standard rendering
+ this.addMessageToChat(message, renderOptions);
}
- } else if (message.role === "toolResult") {
- // Match tool results to pending tool components
- const component = renderedPendingTools.get(message.toolCallId);
- if (component) {
- component.updateResult(message);
- renderedPendingTools.delete(message.toolCallId);
- }
- } else {
- // All other messages use standard rendering
- this.addMessageToChat(message, renderOptions);
+ } catch (error) {
+ // Render an inline placeholder instead of losing the transcript.
+ this.chatContainer.addChild(
+ new Text(
+ theme.fg(
+ "warning",
+ `Failed to render a ${message.role} message: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ ),
+ 1,
+ 0,
+ ),
+ );
}
}
diff --git a/packages/coding-agent/test/interactive-mode-status.test.ts b/packages/coding-agent/test/interactive-mode-status.test.ts
index a07e3f3dc1..0ad6020037 100644
--- a/packages/coding-agent/test/interactive-mode-status.test.ts
+++ b/packages/coding-agent/test/interactive-mode-status.test.ts
@@ -224,6 +224,7 @@ type RenderSessionContextHarness = {
getRetryAttempt: () => number;
ui: { requestRender: () => void };
addMessageToChat: (message: AgentMessage, options?: { populateHistory?: boolean }) => void;
+ showWarning: (warningMessage: string) => void;
connectionState?: AgentConnectionState;
};
@@ -272,6 +273,7 @@ function createRenderSessionContextHarness(overrides: Partial<RenderSessionConte
getRetryAttempt: () => 0,
ui: { requestRender: vi.fn() },
addMessageToChat,
+ showWarning: vi.fn(),
...overrides,
};
Object.setPrototypeOf(harness, InteractiveMode.prototype);
@@ -484,6 +486,43 @@ describe("InteractiveMode.renderSessionContext", () => {
expect(renderAll(chatContainer)).not.toContain("for faster open");
});
+ test("still renders the transcript when tool definition preloading fails", async () => {
+ const showWarning = vi.fn();
+ const { harness, chatContainer, addMessageToChat } = createRenderSessionContextHarness({
+ preloadToolDefinitions: vi.fn(async () => {
+ throw new Error("daemon transport unavailable");
+ }),
+ showWarning,
+ });
+ const messages = [userMessage("message 0", 0), userMessage("message 1", 1)];
+
+ await renderMessages(harness, messages, { clearChat: true });
+
+ expect(showWarning).toHaveBeenCalledWith(expect.stringContaining("daemon transport unavailable"));
+ expect(addMessageToChat).toHaveBeenCalledTimes(2);
+ expect(chatContainer.children).toHaveLength(2);
+ });
+
+ test("keeps rendering later messages when one message fails to render", async () => {
+ const chatContainer = new Container();
+ const addMessageToChat = vi.fn((message: AgentMessage) => {
+ if (message.role === "user" && message.content === "broken") {
+ throw new Error("render boom");
+ }
+ chatContainer.addChild({ render: () => ["assistant"], invalidate: () => {} });
+ });
+ const { harness } = createRenderSessionContextHarness({ chatContainer, addMessageToChat });
+
+ await renderMessages(harness, [userMessage("first", 0), userMessage("broken", 1), userMessage("last", 2)], {
+ clearChat: true,
+ });
+
+ expect(addMessageToChat).toHaveBeenCalledTimes(3);
+ // Two rendered messages plus the inline failure placeholder.
+ expect(chatContainer.children).toHaveLength(3);
+ expect(renderAll(chatContainer)).toContain("Failed to render a user message");
+ });
+
test("populates editor history from the full transcript when initial rendering is capped", async () => {
const { harness, addMessageToChat, addToHistory } = createRenderSessionContextHarness();
const messages = Array.from({ length: 405 }, (_, index) => userMessage(`message ${index}`, index));