Skip to content

Commit eeba5a3

Browse files
steipeteMarnie0415fluffyxenia
authored
fix(tui): prevent unsafe errors and out-of-order streamed replies (#114869)
* fix(tui): redact and sanitize terminal errors Co-authored-by: Marnie0415 <[email protected]> * fix(tui): keep streamed answers and tools chronological Co-authored-by: Foxy6670 <[email protected]> * fix(tui): keep revised answers after tool calls Co-authored-by: Foxy6670 <[email protected]> * fix(tui): discard retracted streamed assistant rows Co-authored-by: Foxy6670 <[email protected]> --------- Co-authored-by: Marnie0415 <[email protected]> Co-authored-by: Foxy6670 <[email protected]>
1 parent 577a064 commit eeba5a3

13 files changed

Lines changed: 445 additions & 46 deletions

‎src/tui/components/chat-log.test.ts‎

Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,197 @@ describe("ChatLog", () => {
7575
expect(chatLog.children.length).toBe(1);
7676
});
7777

78+
it("keeps cumulative assistant text in chronological order around a tool call", () => {
79+
const chatLog = new ChatLog(40);
80+
81+
chatLog.updateAssistant("Before the tool.", "run-1");
82+
chatLog.startTool("tool-1", "read_file", { path: "a.txt" });
83+
chatLog.updateAssistant("Before the tool.\n\nAfter the tool.", "run-1");
84+
85+
const rendered = normalizeTestText(chatLog.render(120).join("\n"));
86+
expect(chatLog.children.map((component) => component.constructor.name)).toEqual([
87+
"AssistantMessageComponent",
88+
"ToolExecutionComponent",
89+
"AssistantMessageComponent",
90+
]);
91+
expect(rendered.indexOf("Before the tool.")).toBeLessThan(rendered.indexOf("Read File"));
92+
expect(rendered.indexOf("Read File")).toBeLessThan(rendered.indexOf("After the tool."));
93+
});
94+
95+
it("does not repeat cumulative text across multiple tool calls", () => {
96+
const chatLog = new ChatLog(40);
97+
98+
chatLog.updateAssistant("First segment.", "run-1");
99+
chatLog.startTool("tool-1", "read_file", { path: "a.txt" });
100+
chatLog.updateAssistant("First segment.\n\nSecond segment.", "run-1");
101+
chatLog.startTool("tool-2", "read_file", { path: "b.txt" });
102+
chatLog.updateAssistant("First segment.\n\nSecond segment.\n\nThird segment.", "run-1");
103+
104+
const rendered = normalizeTestText(chatLog.render(120).join("\n"));
105+
for (const text of ["First segment.", "Second segment.", "Third segment."]) {
106+
expect(rendered.split(text)).toHaveLength(2);
107+
}
108+
expect(chatLog.children.map((component) => component.constructor.name)).toEqual([
109+
"AssistantMessageComponent",
110+
"ToolExecutionComponent",
111+
"AssistantMessageComponent",
112+
"ToolExecutionComponent",
113+
"AssistantMessageComponent",
114+
]);
115+
});
116+
117+
it("reconciles revised assistant snapshots without repeating stale frozen text", () => {
118+
const chatLog = new ChatLog(40);
119+
120+
chatLog.updateAssistant("Hello before the tool.", "run-1");
121+
chatLog.startTool("tool-1", "read_file", { path: "a.txt" });
122+
chatLog.updateAssistant("Hallo before the tool.\n\nRevised answer.", "run-1");
123+
124+
const rendered = normalizeTestText(chatLog.render(120).join("\n"));
125+
expect(rendered).not.toContain("Hello before the tool.");
126+
expect(rendered.split("Hallo before the tool.")).toHaveLength(2);
127+
expect(rendered.split("Revised answer.")).toHaveLength(2);
128+
expect(chatLog.children.map((component) => component.constructor.name)).toEqual([
129+
"ToolExecutionComponent",
130+
"AssistantMessageComponent",
131+
]);
132+
expect(rendered.indexOf("Read File")).toBeLessThan(rendered.indexOf("Revised answer."));
133+
134+
chatLog.updateAssistant("Hallo before the tool.\n\nRevised answer.\n\nNext segment.", "run-1");
135+
136+
const continued = normalizeTestText(chatLog.render(120).join("\n"));
137+
expect(continued.indexOf("Read File")).toBeLessThan(continued.indexOf("Next segment."));
138+
expect(continued.split("Revised answer.")).toHaveLength(2);
139+
});
140+
141+
it("reconciles a revised final snapshot after multiple frozen tool calls", () => {
142+
const chatLog = new ChatLog(40);
143+
144+
chatLog.updateAssistant("First segment.", "run-1");
145+
chatLog.startTool("tool-1", "read_file", { path: "a.txt" });
146+
chatLog.updateAssistant("First segment.\n\nSecond segment.", "run-1");
147+
chatLog.startTool("tool-2", "read_file", { path: "b.txt" });
148+
chatLog.finalizeAssistant("Revised first segment.\n\nFinal answer.", "run-1");
149+
150+
const rendered = normalizeTestText(chatLog.render(120).join("\n"));
151+
expect(rendered.split("Revised first segment.")).toHaveLength(2);
152+
expect(rendered.split("Final answer.")).toHaveLength(2);
153+
expect(rendered).not.toContain("Second segment.");
154+
expect(chatLog.children.map((component) => component.constructor.name)).toEqual([
155+
"ToolExecutionComponent",
156+
"ToolExecutionComponent",
157+
"AssistantMessageComponent",
158+
]);
159+
expect(rendered.lastIndexOf("Read File")).toBeLessThan(rendered.indexOf("Final answer."));
160+
});
161+
162+
it("removes frozen provisional text when the final snapshot retracts it", () => {
163+
const chatLog = new ChatLog(40);
164+
165+
chatLog.updateAssistant("Retracted provisional answer.", "run-1");
166+
chatLog.startTool("tool-1", "read_file", { path: "a.txt" });
167+
chatLog.finalizeAssistant("", "run-1");
168+
169+
expect(normalizeTestText(chatLog.render(120).join("\n"))).not.toContain(
170+
"Retracted provisional answer.",
171+
);
172+
expect(chatLog.children.map((component) => component.constructor.name)).toEqual([
173+
"ToolExecutionComponent",
174+
]);
175+
});
176+
177+
it("removes an empty post-tool component when its final snapshot is retracted", () => {
178+
const chatLog = new ChatLog(40);
179+
180+
chatLog.updateAssistant("Before the tool.", "run-1");
181+
chatLog.startTool("tool-1", "read_file", { path: "a.txt" });
182+
chatLog.updateAssistant("Before the tool.\n\nRetracted answer.", "run-1");
183+
chatLog.finalizeAssistant("Before the tool.", "run-1");
184+
185+
expect(chatLog.children.map((component) => component.constructor.name)).toEqual([
186+
"AssistantMessageComponent",
187+
"ToolExecutionComponent",
188+
]);
189+
expect(normalizeTestText(chatLog.render(120).join("\n"))).not.toContain("Retracted answer.");
190+
});
191+
192+
it("preserves indentation in assistant text that follows a tool call", () => {
193+
const chatLog = new ChatLog(40);
194+
195+
chatLog.updateAssistant("I ran it:", "run-1");
196+
chatLog.startTool("tool-1", "read_file", { path: "a.txt" });
197+
chatLog.updateAssistant("I ran it:\n\n command output", "run-1");
198+
199+
const segment = chatLog.children.at(-1);
200+
expect(segment?.constructor.name).toBe("AssistantMessageComponent");
201+
const rendered = normalizeTestText(segment?.render(120).join("\n") ?? "");
202+
expect(rendered).toContain("```");
203+
expect(rendered).toMatch(/\n {2}command output/);
204+
});
205+
206+
it("finalizes only assistant text that follows an intervening tool call", () => {
207+
const chatLog = new ChatLog(40);
208+
209+
chatLog.updateAssistant("Before the tool.", "run-1");
210+
chatLog.startTool("tool-1", "read_file", { path: "a.txt" });
211+
chatLog.finalizeAssistant("Before the tool.\n\nFinal answer.", "run-1");
212+
213+
const rendered = normalizeTestText(chatLog.render(120).join("\n"));
214+
expect(rendered.split("Before the tool.")).toHaveLength(2);
215+
expect(rendered.indexOf("Read File")).toBeLessThan(rendered.indexOf("Final answer."));
216+
});
217+
218+
it("does not add an empty final assistant segment after a tool call", () => {
219+
const chatLog = new ChatLog(40);
220+
221+
chatLog.updateAssistant("Complete before the tool.", "run-1");
222+
chatLog.startTool("tool-1", "read_file", { path: "a.txt" });
223+
chatLog.finalizeAssistant("Complete before the tool.", "run-1");
224+
225+
expect(chatLog.children.map((component) => component.constructor.name)).toEqual([
226+
"AssistantMessageComponent",
227+
"ToolExecutionComponent",
228+
]);
229+
});
230+
231+
it("clears frozen assistant segments when the chat history is rebuilt", () => {
232+
const chatLog = new ChatLog(40);
233+
234+
chatLog.updateAssistant("Before the tool.", "run-1");
235+
chatLog.startTool("tool-1", "read_file", { path: "a.txt" });
236+
chatLog.clearAll();
237+
chatLog.updateAssistant("Before the tool.\n\nNew history.", "run-1");
238+
239+
const rendered = normalizeTestText(chatLog.render(120).join("\n"));
240+
expect(rendered).toContain("Before the tool.");
241+
expect(rendered).toContain("New history.");
242+
expect(chatLog.children).toHaveLength(1);
243+
});
244+
245+
it("removes every frozen assistant segment when a tool-using run is dropped", () => {
246+
const chatLog = new ChatLog(40);
247+
248+
chatLog.updateAssistant("First segment.", "run-1");
249+
chatLog.startTool("tool-1", "read_file", { path: "a.txt" });
250+
chatLog.updateAssistant("First segment.\n\nSecond segment.", "run-1");
251+
chatLog.startTool("tool-2", "read_file", { path: "b.txt" });
252+
chatLog.updateAssistant("First segment.\n\nSecond segment.\n\nThird segment.", "run-1");
253+
254+
chatLog.dropAssistant("run-1");
255+
256+
expect(chatLog.children.map((component) => component.constructor.name)).toEqual([
257+
"ToolExecutionComponent",
258+
"ToolExecutionComponent",
259+
]);
260+
const rendered = normalizeTestText(chatLog.render(120).join("\n"));
261+
expect(rendered).not.toContain("First segment.");
262+
expect(rendered).not.toContain("Second segment.");
263+
expect(rendered).not.toContain("Third segment.");
264+
265+
chatLog.updateAssistant("Fresh run.", "run-1");
266+
expect(normalizeTestText(chatLog.render(120).join("\n"))).toContain("Fresh run.");
267+
});
268+
78269
it("reserves assistant position without clearing existing streamed text", () => {
79270
const chatLog = new ChatLog(40);
80271
chatLog.startAssistant("partial", "run-active");

‎src/tui/components/chat-log.ts‎

Lines changed: 85 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@ export class ChatLog extends Container {
2222
private readonly maxComponents: number;
2323
private toolById = new Map<string, ToolExecutionComponent>();
2424
private streamingRuns = new Map<string, AssistantMessageComponent>();
25+
private frozenAssistants = new Map<string, Set<AssistantMessageComponent>>();
26+
private committedAssistantText = new Map<string, string>();
27+
private latestAssistantText = new Map<string, string>();
2528
private pendingUsers = new Map<
2629
string,
2730
{
@@ -52,6 +55,14 @@ export class ChatLog extends Container {
5255
this.streamingRuns.delete(runId);
5356
}
5457
}
58+
if (component instanceof AssistantMessageComponent) {
59+
for (const [runId, messages] of this.frozenAssistants.entries()) {
60+
messages.delete(component);
61+
if (messages.size === 0) {
62+
this.frozenAssistants.delete(runId);
63+
}
64+
}
65+
}
5566
for (const [runId, entry] of this.pendingUsers.entries()) {
5667
if (entry.component === component) {
5768
this.pendingUsers.delete(runId);
@@ -95,6 +106,9 @@ export class ChatLog extends Container {
95106
this.clear();
96107
this.toolById.clear();
97108
this.streamingRuns.clear();
109+
this.frozenAssistants.clear();
110+
this.committedAssistantText.clear();
111+
this.latestAssistantText.clear();
98112
this.pendingSystemNotices.clear();
99113
this.btwMessage = null;
100114
this.repeatableSystemMessage = null;
@@ -270,14 +284,58 @@ export class ChatLog extends Container {
270284
return runId ?? "default";
271285
}
272286

287+
private resolveAssistantSegment(runId: string, text: string) {
288+
const committed = this.committedAssistantText.get(runId);
289+
if (!committed) {
290+
return text;
291+
}
292+
if (text.startsWith(committed)) {
293+
return text.slice(committed.length).replace(/^(?:\r?\n)+/u, "");
294+
}
295+
296+
// A revised provider snapshot cannot be split at an obsolete tool boundary.
297+
// Drop obsolete segments so the authoritative replacement lands after the tools.
298+
const frozen = this.frozenAssistants.get(runId);
299+
if (!frozen?.size) {
300+
return text;
301+
}
302+
for (const component of frozen) {
303+
this.removeChild(component);
304+
}
305+
this.frozenAssistants.delete(runId);
306+
const streaming = this.streamingRuns.get(runId);
307+
if (streaming) {
308+
this.removeChild(streaming);
309+
this.streamingRuns.delete(runId);
310+
}
311+
this.committedAssistantText.delete(runId);
312+
return text;
313+
}
314+
315+
// Tool rows freeze earlier cumulative text so later deltas render below the tool.
316+
private freezeStreamingAssistants() {
317+
for (const [runId, component] of this.streamingRuns) {
318+
let frozen = this.frozenAssistants.get(runId);
319+
if (!frozen) {
320+
frozen = new Set();
321+
this.frozenAssistants.set(runId, frozen);
322+
}
323+
frozen.add(component);
324+
this.committedAssistantText.set(runId, this.latestAssistantText.get(runId) ?? "");
325+
}
326+
this.streamingRuns.clear();
327+
}
328+
273329
startAssistant(text: string, runId?: string) {
274330
const effectiveRunId = this.resolveRunId(runId);
331+
this.latestAssistantText.set(effectiveRunId, text);
332+
const segmentText = this.resolveAssistantSegment(effectiveRunId, text);
275333
const existing = this.streamingRuns.get(effectiveRunId);
276334
if (existing) {
277-
existing.setText(text);
335+
existing.setText(segmentText);
278336
return existing;
279337
}
280-
const component = new AssistantMessageComponent(text);
338+
const component = new AssistantMessageComponent(segmentText);
281339
this.streamingRuns.set(effectiveRunId, component);
282340
this.appendNonSystem(component);
283341
return component;
@@ -294,27 +352,48 @@ export class ChatLog extends Container {
294352

295353
updateAssistant(text: string, runId?: string) {
296354
const effectiveRunId = this.resolveRunId(runId);
355+
this.latestAssistantText.set(effectiveRunId, text);
356+
const segmentText = this.resolveAssistantSegment(effectiveRunId, text);
297357
const existing = this.streamingRuns.get(effectiveRunId);
298358
if (!existing) {
359+
if (!segmentText && this.committedAssistantText.has(effectiveRunId)) {
360+
return;
361+
}
299362
this.startAssistant(text, runId);
300363
return;
301364
}
302-
existing.setText(text);
365+
existing.setText(segmentText);
303366
}
304367

305368
finalizeAssistant(text: string, runId?: string) {
306369
const effectiveRunId = this.resolveRunId(runId);
370+
const segmentText = this.resolveAssistantSegment(effectiveRunId, text);
307371
const existing = this.streamingRuns.get(effectiveRunId);
372+
this.frozenAssistants.delete(effectiveRunId);
373+
this.committedAssistantText.delete(effectiveRunId);
374+
this.latestAssistantText.delete(effectiveRunId);
308375
if (existing) {
309-
existing.setText(text);
376+
if (segmentText) {
377+
existing.setText(segmentText);
378+
} else {
379+
this.removeChild(existing);
380+
}
310381
this.streamingRuns.delete(effectiveRunId);
311382
return;
312383
}
313-
this.appendNonSystem(new AssistantMessageComponent(text));
384+
if (segmentText) {
385+
this.appendNonSystem(new AssistantMessageComponent(segmentText));
386+
}
314387
}
315388

316389
dropAssistant(runId?: string) {
317390
const effectiveRunId = this.resolveRunId(runId);
391+
for (const component of this.frozenAssistants.get(effectiveRunId) ?? []) {
392+
this.removeChild(component);
393+
}
394+
this.frozenAssistants.delete(effectiveRunId);
395+
this.committedAssistantText.delete(effectiveRunId);
396+
this.latestAssistantText.delete(effectiveRunId);
318397
const existing = this.streamingRuns.get(effectiveRunId);
319398
if (!existing) {
320399
return;
@@ -356,6 +435,7 @@ export class ChatLog extends Container {
356435
existing.setArgs(args);
357436
return existing;
358437
}
438+
this.freezeStreamingAssistants();
359439
const component = new ToolExecutionComponent(toolName, args);
360440
component.setExpanded(this.toolsExpanded);
361441
this.toolById.set(toolCallId, component);

‎src/tui/embedded-backend.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1007,7 +1007,7 @@ describe("EmbeddedTuiBackend", () => {
10071007
await expect(backend.loadHistory({ sessionKey: "agent:main:main" })).resolves.toMatchObject({
10081008
sessionKey: "agent:main:main",
10091009
messages: [],
1010-
runtimePluginsPrewarm: { status: "failed", error: "Error: runtime unavailable" },
1010+
runtimePluginsPrewarm: { status: "failed", error: "runtime unavailable" },
10111011
});
10121012
});
10131013

‎src/tui/embedded-backend.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ import type {
112112
TuiSessionList,
113113
TuiSessionCreateOptions,
114114
} from "./tui-backend.js";
115+
import { formatTuiErrorMessage } from "./tui-formatters.js";
115116

116117
type LocalRunState = {
117118
sessionKey: string;
@@ -203,7 +204,7 @@ function ensureEmbeddedHistoryRuntimePluginsLoaded(params: {
203204
});
204205
return { status: "warmed" };
205206
} catch (err) {
206-
return { status: "failed", error: String(err) };
207+
return { status: "failed", error: formatTuiErrorMessage(err) };
207208
}
208209
}
209210

0 commit comments

Comments
 (0)