Skip to content

Commit 0f054bb

Browse files
fix(ui): show final replies after interim output (#132197)
* fix(ui): recover missing final replies after interim output * fix(ui): keep polling past final-phase partials
1 parent cff996e commit 0f054bb

4 files changed

Lines changed: 333 additions & 67 deletions

File tree

‎ui/src/e2e/dashboard-final-reply-recovery.e2e.test.ts‎

Lines changed: 68 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ function dashboardPath(): string {
1717
}
1818

1919
suite.define(() => {
20-
it("projects a durable reply when the dashboard terminal event has no message", async () => {
20+
it("projects a distinct durable reply after interim text and a message-less terminal", async () => {
2121
const recordProof = process.env.OPENCLAW_UI_E2E_RECORD === "1";
2222
if (recordProof) {
2323
await mkdir(proofDir, { recursive: true });
@@ -63,6 +63,10 @@ suite.define(() => {
6363
try {
6464
await page.goto(new URL(dashboardPath(), suite.server.baseUrl).href);
6565
const prompt = "Why did Done appear without my reply?";
66+
const interimText = "Checking the dashboard state.";
67+
const updatedInterimText = "Still checking the dashboard state.";
68+
const partialFinalText = "Drafting the durable dashboard reply.";
69+
const stalePartialFinalText = "Drafting more of the durable dashboard reply.";
6670
const finalText = "The durable dashboard reply is visible after Done.";
6771
const composer = page.locator(".agent-chat__composer-combobox textarea");
6872
await composer.fill(prompt);
@@ -72,19 +76,75 @@ suite.define(() => {
7276
const runId = typeof params.idempotencyKey === "string" ? params.idempotencyKey : "";
7377
expect(runId).not.toBe("");
7478

75-
const persistedHistory = [
79+
await gateway.emitGatewayEvent("chat", {
80+
runId,
81+
sessionKey,
82+
seq: 1,
83+
state: "delta",
84+
deltaText: interimText,
85+
message: {
86+
role: "assistant",
87+
phase: "commentary",
88+
content: [{ type: "text", text: interimText }],
89+
timestamp: 1,
90+
},
91+
});
92+
await page.locator(".chat-thread-inner", { hasText: interimText }).waitFor();
93+
await gateway.emitGatewayEvent("chat", {
94+
runId,
95+
sessionKey,
96+
seq: 2,
97+
state: "delta",
98+
deltaText: partialFinalText,
99+
message: {
100+
role: "assistant",
101+
phase: "final_answer",
102+
content: [{ type: "text", text: partialFinalText }],
103+
timestamp: 2,
104+
},
105+
});
106+
await page.locator(".chat-thread-inner", { hasText: partialFinalText }).waitFor();
107+
108+
const persistedInterimHistory = [
76109
{
77110
role: "user",
78111
content: [{ type: "text", text: prompt }],
79112
timestamp: 1,
80113
__openclaw: { id: "dashboard-prompt", idempotencyKey: `${runId}:user`, seq: 1 },
81114
},
115+
{
116+
role: "assistant",
117+
phase: "commentary",
118+
// A stale snapshot can contain newer commentary with producer key
119+
// order and metadata changes; it is still not the terminal reply.
120+
content: [
121+
{ text: updatedInterimText, type: "text", cache_control: { type: "ephemeral" } },
122+
],
123+
timestamp: 2,
124+
__openclaw: { id: "dashboard-interim", runId, seq: 2 },
125+
},
126+
{
127+
role: "assistant",
128+
phase: "final_answer",
129+
content: [
130+
{
131+
text: stalePartialFinalText,
132+
type: "text",
133+
cache_control: { type: "ephemeral" },
134+
},
135+
],
136+
timestamp: 3,
137+
__openclaw: { id: "dashboard-partial-final", runId, seq: 3 },
138+
},
139+
];
140+
const persistedHistory = [
141+
...persistedInterimHistory,
82142
{
83143
role: "assistant",
84144
content: [{ type: "text", text: finalText }],
85145
stopReason: "stop",
86-
timestamp: 2,
87-
__openclaw: { id: "dashboard-final", runId, seq: 2 },
146+
timestamp: 4,
147+
__openclaw: { id: "dashboard-final", runId, seq: 4 },
88148
},
89149
];
90150
const historyCount = (await gateway.getRequests("chat.history")).length;
@@ -97,12 +157,12 @@ suite.define(() => {
97157

98158
const staleRequest = await gateway.waitForRequest("chat.history", { after: historyCount });
99159
expect(staleRequest.params).toMatchObject({ sessionKey, limit: 100 });
100-
// The real Gateway can publish the terminal event before the durable row
101-
// is visible to chat.history. The first recovery snapshot is therefore
102-
// stale; a bounded retry must pick up the later commit without reconnect.
160+
// The first authoritative snapshot can promote the same interim text to
161+
// a durable row before the distinct terminal reply is committed. That
162+
// identity change is not a recovered final; retry until new content lands.
103163
await gateway.setHistoryMessages(persistedHistory);
104164
await gateway.resolveDeferred("chat.history", {
105-
messages: [],
165+
messages: persistedInterimHistory,
106166
sessionId: "control-ui-e2e-session",
107167
thinkingLevel: null,
108168
});

‎ui/src/pages/chat/chat-state-events.ts‎

Lines changed: 82 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,5 @@
1-
import { readSessionMessageIdentity } from "@openclaw/gateway-client/browser";
21
import { asNullableRecord } from "@openclaw/normalization-core/record-coerce";
32
import type { SessionObserverDigest } from "../../../../packages/gateway-protocol/src/schema/sessions.js";
4-
import {
5-
isToolCallContentType,
6-
isToolResultContentType,
7-
} from "../../../../src/chat/tool-content.js";
83
import type { GatewayEventFrame } from "../../api/gateway.ts";
94
import { fireFirstReplyConfetti } from "../../components/confetti.ts";
105
import { isGitHubPullRequestLink } from "../../components/github-link-target.ts";
@@ -45,8 +40,6 @@ import { refreshCurrentChatSessionList } from "./chat-session.ts";
4540
import type { ChatPageHost } from "./chat-state-host.ts";
4641
import { requestChatPageUpdate } from "./chat-state-render.ts";
4742
import { resolveChatAgentId, selectedChatSessionRow } from "./chat-state-route.ts";
48-
import { transcriptRunId } from "./chat-thread-run-identity.ts";
49-
import { safeNormalizeMessage } from "./chat-turn-boundary.ts";
5043
import { handleBackgroundTasksEvent } from "./components/chat-background-tasks.ts";
5144
import {
5245
refreshSessionWorkspace,
@@ -70,10 +63,12 @@ import {
7063
import { applySessionMessagePayload } from "./session-message-apply.ts";
7164
import { isSidebarSlotVisible } from "./sidebar-layout.ts";
7265
import { rememberAuthoritativeTerminal } from "./terminal-message-identity.ts";
66+
import { readTerminalReplyRecoveryState } from "./terminal-reply-recovery.ts";
7367
import { handleAgentEvent, handleSessionOperationEvent } from "./tool-stream.ts";
7468

7569
const BRANCH_TOPOLOGY_REASONS = new Set(["rewind", "branch-switch", "fork", "reset", "new"]);
7670
const MISSING_TERMINAL_HISTORY_RETRY_DELAYS_MS = [100, 400, 1_500, 3_000] as const;
71+
const MAX_REMEMBERED_TERMINAL_RECOVERY_CLAIMS = 64;
7772
type ChatPanePresentation = () => boolean;
7873

7974
function sessionMessageMatchesChat(
@@ -230,43 +225,79 @@ function replayPendingSessionMessageReload(
230225
return true;
231226
}
232227

233-
function hasRecoveredTerminalReply(state: ChatPageHost, runId: string): boolean {
234-
const scope = readChatSessionProjectionScope(state);
235-
const projection = getChatSessionProjection(state, state.chatMessages, scope);
236-
const message =
237-
projection.runs[runId]?.message ??
238-
projection.messages.findLast(
239-
(candidate) =>
240-
readSessionMessageIdentity(candidate)?.role === "assistant" &&
241-
transcriptRunId(candidate) === runId,
242-
);
243-
const text = extractText(message);
244-
if (
245-
typeof text === "string" &&
246-
text.trim().length > 0 &&
247-
!isHiddenAssistantStreamText(text) &&
248-
!shouldHideAssistantChatMessage(message)
249-
) {
250-
return true;
251-
}
252-
if (shouldHideAssistantChatMessage(message)) {
253-
return false;
254-
}
255-
return (safeNormalizeMessage(message)?.content ?? []).some((block) => {
256-
const type = block.type;
257-
return type !== "text" && !isToolCallContentType(type) && !isToolResultContentType(type);
258-
});
259-
}
260-
261228
type TerminalRecoveryOwnership = {
262229
sessionKey: string;
263230
agentId: string;
264231
runId: string;
265232
client: ChatPageHost["client"];
266233
connectionEpoch: number;
267234
runLifecycleGeneration: number;
235+
initialTerminalReplySignatures: ReadonlySet<string>;
268236
};
269237

238+
const terminalRecoveryClaimsByPane = new WeakMap<object, Map<string, ChatPageHost["client"]>>();
239+
240+
function createTerminalRecoveryOwnership(
241+
state: ChatPageHost,
242+
payload: ChatEventPayload,
243+
): TerminalRecoveryOwnership | null {
244+
const runId = payload.runId;
245+
if (!runId) {
246+
return null;
247+
}
248+
return {
249+
sessionKey: payload.sessionKey,
250+
agentId: resolveChatAgentId(state),
251+
runId,
252+
client: state.client,
253+
connectionEpoch: state.connectionEpoch,
254+
runLifecycleGeneration: state.chatRunLifecycleGeneration ?? 0,
255+
initialTerminalReplySignatures: readTerminalReplyRecoveryState(state, runId)
256+
.terminalReplySignatures,
257+
};
258+
}
259+
260+
function claimTerminalRecovery(state: ChatPageHost, ownership: TerminalRecoveryOwnership): boolean {
261+
let claims = terminalRecoveryClaimsByPane.get(state);
262+
if (!claims) {
263+
claims = new Map();
264+
terminalRecoveryClaimsByPane.set(state, claims);
265+
}
266+
const key = [
267+
ownership.connectionEpoch,
268+
ownership.runLifecycleGeneration,
269+
ownership.agentId,
270+
ownership.sessionKey,
271+
ownership.runId,
272+
].join("\0");
273+
if (claims.has(key) && claims.get(key) === ownership.client) {
274+
return false;
275+
}
276+
claims.delete(key);
277+
claims.set(key, ownership.client);
278+
while (claims.size > MAX_REMEMBERED_TERMINAL_RECOVERY_CLAIMS) {
279+
const oldest = claims.keys().next().value;
280+
if (typeof oldest !== "string") {
281+
break;
282+
}
283+
claims.delete(oldest);
284+
}
285+
return true;
286+
}
287+
288+
function hasRecoveredTerminalReply(
289+
state: ChatPageHost,
290+
ownership: TerminalRecoveryOwnership,
291+
): boolean {
292+
const recovery = readTerminalReplyRecoveryState(state, ownership.runId);
293+
return (
294+
recovery.acceptedFinal ||
295+
[...recovery.terminalReplySignatures].some(
296+
(signature) => !ownership.initialTerminalReplySignatures.has(signature),
297+
)
298+
);
299+
}
300+
270301
function terminalRecoveryStillOwned(
271302
state: ChatPageHost,
272303
ownership: TerminalRecoveryOwnership,
@@ -279,28 +310,15 @@ function terminalRecoveryStillOwned(
279310
resolveChatAgentId(state) === ownership.agentId &&
280311
(state.chatRunId === null || state.chatRunId === ownership.runId) &&
281312
(state.chatRunLifecycleGeneration ?? 0) === ownership.runLifecycleGeneration &&
282-
!hasRecoveredTerminalReply(state, ownership.runId)
313+
!hasRecoveredTerminalReply(state, ownership)
283314
);
284315
}
285316

286317
async function recoverMissingTerminalReply(
287318
state: ChatPageHost,
288-
payload: ChatEventPayload,
319+
ownership: TerminalRecoveryOwnership,
289320
presentation: ChatPanePresentation,
290321
): Promise<void> {
291-
const sessionKey = payload.sessionKey;
292-
const runId = payload.runId;
293-
if (!runId) {
294-
return;
295-
}
296-
const ownership: TerminalRecoveryOwnership = {
297-
sessionKey,
298-
agentId: resolveChatAgentId(state),
299-
runId,
300-
client: state.client,
301-
connectionEpoch: state.connectionEpoch,
302-
runLifecycleGeneration: state.chatRunLifecycleGeneration ?? 0,
303-
};
304322
for (let attempt = 0; ; attempt += 1) {
305323
if (!terminalRecoveryStillOwned(state, ownership)) {
306324
return;
@@ -547,10 +565,6 @@ export function handlePageGatewayEvent(
547565
? payload.runId
548566
: null;
549567
const recoveryScope = recoveryRunId ? readChatSessionProjectionScope(state) : null;
550-
const projectedRunBeforeEvent =
551-
recoveryRunId && recoveryScope
552-
? getChatSessionProjection(state, state.chatMessages, recoveryScope).runs[recoveryRunId]
553-
: undefined;
554568
if (
555569
payload?.state === "delta" &&
556570
typeof payload.runId === "string" &&
@@ -605,17 +619,26 @@ export function handlePageGatewayEvent(
605619
const shouldRecoverMissingTerminal = Boolean(
606620
recoveryRunId &&
607621
recoveryScope &&
608-
(projectedRunBeforeEvent === undefined || projectedRunBeforeEvent.status === "streaming") &&
609622
getChatSessionProjection(state, state.chatMessages, recoveryScope).runs[recoveryRunId]
610623
?.status === "completed",
611624
);
612-
if (shouldRecoverMissingTerminal && payload) {
625+
const recoveryOwnership =
626+
shouldRecoverMissingTerminal && payload
627+
? createTerminalRecoveryOwnership(state, payload)
628+
: null;
629+
const recoveryClaimed = recoveryOwnership
630+
? claimTerminalRecovery(state, recoveryOwnership)
631+
: false;
632+
if (recoveryOwnership && recoveryClaimed) {
613633
state.pendingSessionMessageReloadSessionKey = null;
614-
// Only the first owned completion can recover history. Replayed, yielded,
615-
// or background-run terminals must not repeat I/O or disturb the foreground pane.
634+
// The first owned message-less terminal recovers history even when an
635+
// earlier snapshot already marked the run complete. Replays, yielded, or
636+
// background-run terminals must not repeat I/O or disturb the foreground pane.
616637
// Persistence can trail the terminal event, so retry bounded authoritative
617638
// snapshots until the completed run's reply becomes visible.
618-
void recoverMissingTerminalReply(state, payload, isPresented).catch(() => undefined);
639+
void recoverMissingTerminalReply(state, recoveryOwnership, isPresented).catch(
640+
() => undefined,
641+
);
619642
} else {
620643
replayPendingSessionMessageReload(state, payload, isPresented);
621644
}

0 commit comments

Comments
 (0)