Skip to content

Commit 8323b12

Browse files
committed
fix(tui): keep failed attachments visible beside replies
1 parent 6e6a0e5 commit 8323b12

6 files changed

Lines changed: 287 additions & 31 deletions

File tree

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3843,7 +3843,7 @@ src/tui/gateway-chat.ts 2
38433843
src/tui/tui-autocomplete.ts 1
38443844
src/tui/tui-command-handlers.ts 5
38453845
src/tui/tui-event-handlers.ts 5
3846-
src/tui/tui-formatters.ts 5
3846+
src/tui/tui-formatters.ts 4
38473847
src/tui/tui-session-actions.ts 5
38483848
src/tui/tui-session-events.ts 1
38493849
src/tui/tui-session-projection.ts 2

‎docs/web/tui.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,7 @@ Tips:
230230
- On connect, the TUI loads the latest history (default 200 messages).
231231
- Reconnect and event-gap recovery reconcile active runs with history, retaining concurrent and newly observed runs without reviving runs that exact history has excluded.
232232
- Streaming responses update in place until finalized.
233+
- Failed assistant attachments show an actionable warning alongside any reply text. Attachment summaries use generic media kinds without exposing filenames or source URLs.
233234
- Messages sent to the same session from another client appear automatically.
234235
- The TUI also listens to agent tool events for richer tool cards.
235236

Lines changed: 248 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,248 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
import { stripAnsi } from "../../packages/terminal-core/src/ansi.js";
3+
import { ChatLog } from "./components/chat-log.js";
4+
import { createEventHandlers } from "./tui-event-handlers.js";
5+
import { extractTextFromMessage, extractTuiAbortedText } from "./tui-formatters.js";
6+
import { getTuiSessionProjection, reduceTuiSessionProjection } from "./tui-session-projection.js";
7+
import { TuiStreamAssembler } from "./tui-stream-assembler.js";
8+
import type { TuiStateAccess } from "./tui-types.js";
9+
10+
const audioFailure = {
11+
type: "attachment_error",
12+
attachment: { code: "delivery-failed", kind: "audio", label: "Generated audio 1" },
13+
};
14+
const audioReceipt = "⚠️ audio attachment: Delivery failed. Try sending this file again.";
15+
const caption = { type: "text", text: "Your recording" };
16+
const image = { type: "image", url: "file:///private/image.png" };
17+
const assistant = (content: unknown[]) => ({ role: "assistant", content });
18+
19+
function createDisplayHarness() {
20+
const state: TuiStateAccess = {
21+
agentDefaultId: "main",
22+
sessionMainKey: "main",
23+
sessionScope: "per-sender",
24+
agents: [],
25+
currentAgentId: "main",
26+
currentSessionKey: "agent:main:main",
27+
currentSessionId: "session-1",
28+
activeChatRunId: null,
29+
pendingSubmit: null,
30+
historyLoaded: true,
31+
sessionInfo: {},
32+
initialSessionApplied: true,
33+
isConnected: true,
34+
autoMessageSent: false,
35+
toolsExpanded: false,
36+
showThinking: false,
37+
connectionStatus: "connected",
38+
activityStatus: "idle",
39+
statusTimeout: null,
40+
lastCtrlCAt: 0,
41+
};
42+
const chatLog = new ChatLog();
43+
const handlers = createEventHandlers({
44+
state,
45+
chatLog,
46+
tui: { requestRender: vi.fn() },
47+
btw: { clear: vi.fn(), showResult: vi.fn() },
48+
setActivityStatus: (value) => {
49+
state.activityStatus = value;
50+
},
51+
streamingWatchdogMs: 0,
52+
});
53+
return {
54+
state,
55+
chatLog,
56+
...handlers,
57+
visible: () =>
58+
chatLog
59+
.render(160)
60+
.map((line) => stripAnsi(line).trimEnd())
61+
.join("\n")
62+
.trim(),
63+
};
64+
}
65+
66+
describe("TUI attachment failure presentation", () => {
67+
it.each([
68+
{ name: "failure only", content: [audioFailure], expected: audioReceipt },
69+
{
70+
name: "caption and failure",
71+
content: [caption, audioFailure],
72+
expected: `Your recording\n${audioReceipt}`,
73+
},
74+
{
75+
name: "success and failure",
76+
content: [image, audioFailure],
77+
expected: `Attached image\n${audioReceipt}`,
78+
},
79+
{
80+
name: "caption, success and failure",
81+
content: [caption, image, audioFailure],
82+
expected: `Your recording\n${audioReceipt}`,
83+
},
84+
{
85+
name: "multiple failures",
86+
content: [audioFailure, audioFailure],
87+
expected: `${audioReceipt}\n${audioReceipt}`,
88+
},
89+
])("keeps $name in history and final output", ({ content, expected }) => {
90+
const message = assistant(content);
91+
expect(extractTextFromMessage(message)).toBe(expected);
92+
expect(new TuiStreamAssembler().finalize("run-1", message, false)).toBe(expected);
93+
});
94+
95+
it.each([
96+
{
97+
kind: "image",
98+
code: "file-not-found",
99+
expected: "⚠️ image attachment: File not found. Check the path and try again.",
100+
},
101+
{
102+
kind: "video",
103+
code: "unsupported-format",
104+
expected:
105+
"⚠️ video attachment: Rejected by the local attachment allowlist. Send a supported file type.",
106+
},
107+
{
108+
kind: "document",
109+
code: "delivery-failed",
110+
expected: "⚠️ file attachment: Delivery failed. Try sending this file again.",
111+
},
112+
])(
113+
"renders actionable $kind/$code receipts without source metadata",
114+
({ kind, code, expected }) => {
115+
const message = assistant([
116+
{
117+
type: "attachment_error",
118+
attachment: {
119+
kind,
120+
code,
121+
label: "\x1b]52;c;private-clipboard\x07file:///private/name",
122+
url: "https://private.invalid/file?ticket=private",
123+
mimeType: "private/type",
124+
},
125+
},
126+
]);
127+
expect(extractTextFromMessage(message)).toBe(expected);
128+
expect(new TuiStreamAssembler().finalize("run-1", message, false)).toBe(expected);
129+
},
130+
);
131+
132+
it.each([false, true])(
133+
"retains streamed captions and thinking visibility (%s) before a failure-only final",
134+
(showThinking) => {
135+
const assembler = new TuiStreamAssembler();
136+
assembler.ingestDelta(
137+
"run-1",
138+
assistant([caption, { type: "thinking", thinking: "Preparing" }]),
139+
showThinking,
140+
);
141+
expect(assembler.finalize("run-1", assistant([audioFailure]), showThinking)).toBe(
142+
`${showThinking ? "[thinking]\nPreparing\n\n" : ""}Your recording\n${audioReceipt}`,
143+
);
144+
},
145+
);
146+
147+
it("keeps genuine errors ahead of success fallback while appending the failure receipt", () => {
148+
const message = {
149+
...assistant([image, audioFailure]),
150+
stopReason: "error",
151+
errorMessage: "generation stopped",
152+
};
153+
expect(extractTextFromMessage(message)).toBe(`generation stopped\n${audioReceipt}`);
154+
expect(
155+
new TuiStreamAssembler().finalize(
156+
"run-1",
157+
assistant([image, audioFailure]),
158+
false,
159+
"generation stopped",
160+
),
161+
).toBe(`generation stopped\n${audioReceipt}`);
162+
});
163+
164+
it.each([
165+
{ name: "failure only", content: [audioFailure], streamed: false, expected: audioReceipt },
166+
{
167+
name: "mixed attachments",
168+
content: [image, audioFailure],
169+
streamed: false,
170+
expected: `Attached image\n${audioReceipt}`,
171+
},
172+
{
173+
name: "streamed caption",
174+
content: [image, audioFailure],
175+
streamed: true,
176+
expected: `Your recording\n${audioReceipt}`,
177+
},
178+
])(
179+
"renders one receipt through optimistic and authoritative history: $name",
180+
({ content, streamed, expected }) => {
181+
const harness = createDisplayHarness();
182+
const event = { runId: "run-1", sessionKey: harness.state.currentSessionKey };
183+
try {
184+
if (streamed) {
185+
harness.handleChatEvent({ ...event, state: "delta", message: assistant([caption]) });
186+
expect(harness.visible()).toBe("Your recording");
187+
}
188+
const message = assistant(content);
189+
harness.handleChatEvent({ ...event, state: "final", message });
190+
expect(harness.visible()).toBe(expected);
191+
expect(harness.state.activityStatus).toBe("idle");
192+
193+
for (const messages of [
194+
[],
195+
[
196+
{
197+
...assistant(streamed ? [caption, ...content] : content),
198+
__openclaw: { id: "assistant-1", seq: 1, runId: event.runId },
199+
},
200+
],
201+
]) {
202+
const projection = reduceTuiSessionProjection(harness.state, {
203+
type: "snapshotLoaded",
204+
messages,
205+
});
206+
expect(projection.messages).toHaveLength(1);
207+
harness.chatLog.clearAll();
208+
for (const row of projection.messages) {
209+
harness.chatLog.finalizeAssistant(extractTextFromMessage(row));
210+
}
211+
expect(harness.visible()).toBe(expected);
212+
}
213+
} finally {
214+
harness.dispose();
215+
}
216+
},
217+
);
218+
219+
it("keeps failure-only aborts diagnostic and ignores a late attachment final", () => {
220+
const harness = createDisplayHarness();
221+
const event = {
222+
runId: "run-1",
223+
sessionKey: harness.state.currentSessionKey,
224+
message: assistant([audioFailure]),
225+
};
226+
try {
227+
expect(extractTuiAbortedText(event.message, false)).toBe("");
228+
harness.handleChatEvent({ ...event, state: "aborted" });
229+
harness.handleChatEvent({ ...event, state: "final" });
230+
expect(harness.visible()).toBe("run aborted");
231+
expect(getTuiSessionProjection(harness.state).messages).toHaveLength(0);
232+
} finally {
233+
harness.dispose();
234+
}
235+
});
236+
237+
it("does not invent failure output for empty or unsupported blocks", () => {
238+
for (const content of [
239+
[],
240+
[{ type: "tool_use", name: "search" }],
241+
[{ type: "attachment_error", attachment: { code: "unknown", kind: "audio" } }],
242+
]) {
243+
const message = assistant(content);
244+
expect(extractTextFromMessage(message)).toBe("");
245+
expect(new TuiStreamAssembler().finalize("run-1", message, false)).toBe("(no output)");
246+
}
247+
});
248+
});

‎src/tui/tui-formatters.ts‎

Lines changed: 34 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1+
import { asOptionalObjectRecord as asMessageRecord } from "@openclaw/normalization-core/record-coerce";
12
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
23
// Formats terminal-safe strings for TUI messages and status surfaces.
34
import { stripAnsi } from "../../packages/terminal-core/src/ansi.js";
45
import { splitTrailingAuthProfile } from "../agents/model-ref-profile.js";
6+
import { appendReplyMediaFailures, type ReplyMediaFailure } from "../auto-reply/reply-payload.js";
57
import { stripLeadingInboundMetadata } from "../auto-reply/reply/strip-inbound-meta.js";
68
import type { SessionGoal } from "../config/sessions/types.js";
79
import { formatErrorMessage } from "../infra/errors.js";
@@ -316,25 +318,12 @@ export function resolveFinalAssistantText(params: {
316318
finalText?: string | null;
317319
streamedText?: string | null;
318320
errorMessage?: string | null;
319-
attachmentText?: string | null;
321+
message?: unknown;
320322
}) {
321-
const finalText = params.finalText ?? "";
322-
if (finalText.trim()) {
323-
return finalText;
324-
}
325-
const streamedText = params.streamedText ?? "";
326-
if (streamedText.trim()) {
327-
return streamedText;
328-
}
329-
const errorMessage = params.errorMessage ?? "";
330-
if (errorMessage.trim()) {
331-
return formatRawAssistantErrorForUi(errorMessage);
332-
}
333-
const attachmentText = params.attachmentText ?? "";
334-
if (attachmentText.trim()) {
335-
return attachmentText;
336-
}
337-
return "(no output)";
323+
const contentText =
324+
[params.finalText, params.streamedText].find((text) => text?.trim()) ??
325+
(params.errorMessage?.trim() ? formatRawAssistantErrorForUi(params.errorMessage) : "");
326+
return formatTuiAssistantContent(params.message, contentText) || "(no output)";
338327
}
339328

340329
export function composeThinkingAndContent(params: {
@@ -356,13 +345,6 @@ export function composeThinkingAndContent(params: {
356345
return parts.join("\n\n").trim();
357346
}
358347

359-
function asMessageRecord(message: unknown): Record<string, unknown> | undefined {
360-
if (!message || typeof message !== "object") {
361-
return undefined;
362-
}
363-
return message as Record<string, unknown>;
364-
}
365-
366348
type TuiAttachmentKind = "image" | "audio" | "video" | "file" | "media";
367349

368350
const TUI_ATTACHMENT_BLOCK_KINDS: Readonly<Record<string, TuiAttachmentKind>> = {
@@ -416,7 +398,7 @@ function resolvePersistedTuiAttachmentKind(
416398
}
417399

418400
/** Render assistant attachments without exposing their sources or capability URLs. */
419-
export function extractAssistantAttachmentText(message: unknown): string {
401+
function extractAssistantAttachmentText(message: unknown): string {
420402
const record = asMessageRecord(message);
421403
if (!record) {
422404
return "";
@@ -448,6 +430,29 @@ export function extractAssistantAttachmentText(message: unknown): string {
448430
return legacyMedia.map(() => "Attached media").join("\n");
449431
}
450432

433+
function formatTuiAssistantContent(message: unknown, contentText: string): string {
434+
const content = asMessageRecord(message)?.content;
435+
const failures: ReplyMediaFailure[] = [];
436+
for (const block of Array.isArray(content) ? content : []) {
437+
const entry = asMessageRecord(block);
438+
const attachment =
439+
entry?.type === "attachment_error" ? asMessageRecord(entry.attachment) : undefined;
440+
const code = attachment?.code;
441+
const kind = attachment?.kind;
442+
if (
443+
(code === "file-not-found" || code === "unsupported-format" || code === "delivery-failed") &&
444+
(kind === "image" || kind === "audio" || kind === "video" || kind === "document")
445+
) {
446+
// Assistant attachment labels can contain private paths or capability URLs.
447+
// Reuse the actionable receipt wording, but keep the TUI's generic labels.
448+
failures.push({ code, kind, label: `${kind === "document" ? "file" : kind} attachment` });
449+
}
450+
}
451+
return (
452+
appendReplyMediaFailures(contentText || extractAssistantAttachmentText(message), failures) ?? ""
453+
);
454+
}
455+
451456
function resolveMessageRecord(
452457
message: unknown,
453458
): { record: Record<string, unknown>; content: unknown } | undefined {
@@ -651,8 +656,9 @@ export function extractTextFromMessage(
651656
return composeThinkingAndContent({
652657
thinkingText: extractThinkingFromMessage(record),
653658
contentText:
654-
contentText ||
655-
(opts?.includeAttachments !== false ? extractAssistantAttachmentText(record) : ""),
659+
opts?.includeAttachments !== false
660+
? formatTuiAssistantContent(record, contentText)
661+
: contentText,
656662
showThinking: opts?.includeThinking ?? false,
657663
});
658664
}

‎src/tui/tui-session-projection.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,8 @@ export function projectTuiSessionFinal(
157157
event.message && typeof event.message === "object" && !Array.isArray(event.message)
158158
? (event.message as Record<string, unknown>)
159159
: {};
160+
// Failure receipts are already in finalText; retain only successful blocks
161+
// so a history rebuild cannot append the same failure a second time.
160162
const attachments = Array.isArray(source.content)
161163
? source.content.filter(isTuiAssistantAttachmentBlock)
162164
: [];

‎src/tui/tui-stream-assembler.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
// Assembles streamed backend events into TUI-visible messages.
22
import {
33
composeThinkingAndContent,
4-
extractAssistantAttachmentText,
54
extractContentFromMessage,
65
extractThinkingFromMessage,
76
resolveFinalAssistantText,
@@ -232,7 +231,7 @@ export class TuiStreamAssembler {
232231
finalText: shouldKeepStreamedText ? streamedContentText : state.contentText,
233232
streamedText: streamedContentText,
234233
errorMessage,
235-
attachmentText: extractAssistantAttachmentText(message),
234+
message,
236235
});
237236
// Thinking is optional presentation around the selected response content;
238237
// it must not hide errors or attachments when the final has no text.

0 commit comments

Comments
 (0)