Skip to content

Commit 0bd50cc

Browse files
fix(ui): preserve delayed final turn order (#123560)
1 parent 703c681 commit 0bd50cc

3 files changed

Lines changed: 233 additions & 3 deletions

File tree

‎ui/src/e2e/chat-flow.messaging.e2e.test.ts‎

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,122 @@ suite.define(() => {
136136
});
137137
});
138138

139+
it("keeps a previous final above a newer active turn when events arrive late", async () => {
140+
await withChatPage(async (page) => {
141+
const gateway = await installMockGateway(page, { historyMessages: [] });
142+
const previousRunId = "previous-run";
143+
const previousPrompt = "What are groups?";
144+
const previousFinal = "Groups organize conversations.";
145+
const currentPrompt = "Why were my sessions missing?";
146+
const currentPartial = "Checking external sessions...";
147+
148+
await page.goto(`${suite.server.baseUrl}chat`);
149+
await gateway.waitForRequest("chat.startup");
150+
await gateway.emitGatewayEvent("session.message", {
151+
activeRunIds: [],
152+
clientRunId: previousRunId,
153+
hasActiveRun: false,
154+
message: {
155+
content: [{ text: previousPrompt, type: "text" }],
156+
role: "user",
157+
timestamp: Date.now(),
158+
},
159+
messageId: "previous-user",
160+
messageSeq: 1,
161+
session: {
162+
activeRunIds: [],
163+
hasActiveRun: false,
164+
key: "main",
165+
kind: "direct",
166+
status: "done",
167+
updatedAt: Date.now(),
168+
},
169+
sessionKey: "main",
170+
});
171+
172+
await page.locator(".agent-chat__composer-combobox textarea").fill(currentPrompt);
173+
await page.getByRole("button", { name: "Send message" }).click();
174+
const sendRequest = await gateway.waitForRequest("chat.send");
175+
const currentRunId = requireString(
176+
requireRecord(sendRequest.params).idempotencyKey,
177+
"current chat run id",
178+
);
179+
await gateway.emitGatewayEvent("session.message", {
180+
activeRunIds: [currentRunId],
181+
clientRunId: currentRunId,
182+
hasActiveRun: true,
183+
message: {
184+
content: [{ text: currentPrompt, type: "text" }],
185+
role: "user",
186+
timestamp: Date.now(),
187+
},
188+
messageId: "current-user",
189+
messageSeq: 3,
190+
session: {
191+
activeRunIds: [currentRunId],
192+
hasActiveRun: true,
193+
key: "main",
194+
kind: "direct",
195+
status: "running",
196+
updatedAt: Date.now(),
197+
},
198+
sessionKey: "main",
199+
});
200+
await gateway.emitGatewayEvent("chat", {
201+
deltaText: currentPartial,
202+
message: {
203+
content: [{ text: currentPartial, type: "text" }],
204+
role: "assistant",
205+
timestamp: Date.now(),
206+
},
207+
runId: currentRunId,
208+
seq: 1,
209+
sessionKey: "main",
210+
state: "delta",
211+
});
212+
await gateway.emitGatewayEvent("session.message", {
213+
activeRunIds: [currentRunId],
214+
clientRunId: previousRunId,
215+
hasActiveRun: true,
216+
message: {
217+
content: [{ text: previousFinal, type: "text" }],
218+
role: "assistant",
219+
timestamp: Date.now(),
220+
},
221+
messageId: "previous-final",
222+
messageSeq: 2,
223+
session: {
224+
activeRunIds: [currentRunId],
225+
hasActiveRun: true,
226+
key: "main",
227+
kind: "direct",
228+
status: "running",
229+
updatedAt: Date.now(),
230+
},
231+
sessionKey: "main",
232+
});
233+
234+
const visibleTexts = [previousPrompt, previousFinal, currentPrompt, currentPartial];
235+
const expectVisibleOrder = async () => {
236+
await expect
237+
.poll(() =>
238+
page.locator(".chat-thread-inner").evaluate((thread, texts) => {
239+
const rows = Array.from(thread.querySelectorAll(".chat-bubble"));
240+
return texts.map((text) => rows.findIndex((row) => row.textContent?.includes(text)));
241+
}, visibleTexts),
242+
)
243+
.toEqual([0, 1, 2, 3]);
244+
};
245+
await expectVisibleOrder();
246+
247+
await gateway.emitChatFinal({ runId: previousRunId, text: previousFinal });
248+
await expectVisibleOrder();
249+
await expect
250+
.poll(() => page.locator(".chat-group.assistant", { hasText: previousFinal }).count())
251+
.toBe(1);
252+
});
253+
});
254+
139255
it("preserves distinct same-text peer messages through conflicting envelopes and stale history", async () => {
140256
await withChatPage(async (page) => {
141257
const gateway = await installMockGateway(page, { historyMessages: [] });

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

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ function sessionMessageMatchesChat(
6565
return chatScopedEventSessionMatches(state, event.key, event.agentId ?? undefined);
6666
}
6767

68-
function applyLiveUserMessage(
68+
function applyLiveSessionMessage(
6969
state: ChatPageHost,
7070
payload: unknown,
7171
runActive: boolean | undefined,
@@ -81,7 +81,17 @@ function applyLiveUserMessage(
8181
};
8282
const sourceMessage = event.message;
8383
const incoming = readSessionMessageIdentity(sourceMessage, event);
84-
if (incoming?.role !== "user") {
84+
if (!incoming) {
85+
return;
86+
}
87+
const isPreviousRunAssistant = Boolean(
88+
incoming.role === "assistant" &&
89+
incoming.sequence !== null &&
90+
incoming.runId &&
91+
state.chatRunId &&
92+
incoming.runId !== state.chatRunId,
93+
);
94+
if (incoming.role !== "user" && !isPreviousRunAssistant) {
8595
return;
8696
}
8797
// Partial import provenance cannot turn an envelope position into durable
@@ -183,7 +193,10 @@ function handleSessionMessageEvent(state: ChatPageHost, payload: unknown) {
183193
}
184194
const matchesChat = sessionMessageMatchesChat(state, event);
185195
if (matchesChat) {
186-
applyLiveUserMessage(state, payload, event.hasActiveRun ?? undefined);
196+
// A previous run can persist its final after the next local run starts.
197+
// Admit that sequenced row now so the later unsequenced chat.final replay
198+
// replaces it in place instead of appending below the newer user turn.
199+
applyLiveSessionMessage(state, payload, event.hasActiveRun ?? undefined);
187200
void loadChatBranches(state);
188201
}
189202
if (matchesChat && event.archived !== null) {

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

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,107 @@ describe("canonical session message recovery", () => {
107107
});
108108
});
109109

110+
it("keeps a previous run final before a newer active user turn", () => {
111+
const previousUser = {
112+
role: "user",
113+
content: [{ type: "text", text: "What are groups?" }],
114+
__openclaw: { id: "previous-user", idempotencyKey: "previous-run:user", seq: 1 },
115+
};
116+
const currentUser = {
117+
role: "user",
118+
content: [{ type: "text", text: "Why were my sessions missing?" }],
119+
__openclaw: { id: "current-user", idempotencyKey: "current-run:user", seq: 3 },
120+
};
121+
const persistedFinal = {
122+
role: "assistant",
123+
content: [{ type: "text", text: "Groups organize conversations." }],
124+
__openclaw: { id: "previous-final", seq: 2 },
125+
};
126+
const { state } = createSessionEventState({
127+
chatMessages: [previousUser, currentUser],
128+
chatRunId: "current-run",
129+
chatStream: "Checking external sessions...",
130+
});
131+
132+
handlePageGatewayEvent(state, {
133+
type: "event",
134+
event: "session.message",
135+
payload: {
136+
sessionKey: state.sessionKey,
137+
clientRunId: "previous-run",
138+
hasActiveRun: true,
139+
messageId: "previous-final",
140+
messageSeq: 2,
141+
message: persistedFinal,
142+
},
143+
});
144+
145+
expect(state.chatMessages.map((message) => (message as { role?: string }).role)).toEqual([
146+
"user",
147+
"assistant",
148+
"user",
149+
]);
150+
expect(state.chatMessages[1]).toMatchObject({
151+
content: persistedFinal.content,
152+
__openclaw: { id: "previous-final", seq: 2 },
153+
});
154+
155+
handlePageGatewayEvent(state, {
156+
type: "event",
157+
event: "chat",
158+
payload: {
159+
sessionKey: state.sessionKey,
160+
runId: "previous-run",
161+
state: "final",
162+
message: {
163+
role: "assistant",
164+
content: [{ type: "text", text: "Groups organize conversations." }],
165+
},
166+
},
167+
});
168+
169+
expect(state.chatMessages.map((message) => (message as { role?: string }).role)).toEqual([
170+
"user",
171+
"assistant",
172+
"user",
173+
]);
174+
expect(state.chatRunId).toBe("current-run");
175+
expect(state.chatStream).toBe("Checking external sessions...");
176+
});
177+
178+
it("leaves the active run assistant message on the terminal stream path", () => {
179+
const currentUser = {
180+
role: "user",
181+
content: [{ type: "text", text: "Current prompt" }],
182+
__openclaw: { id: "current-user", idempotencyKey: "current-run:user", seq: 1 },
183+
};
184+
const { state } = createSessionEventState({
185+
chatMessages: [currentUser],
186+
chatRunId: "current-run",
187+
chatStream: "Current partial reply",
188+
});
189+
190+
handlePageGatewayEvent(state, {
191+
type: "event",
192+
event: "session.message",
193+
payload: {
194+
sessionKey: state.sessionKey,
195+
clientRunId: "current-run",
196+
hasActiveRun: true,
197+
messageId: "current-final",
198+
messageSeq: 2,
199+
message: {
200+
role: "assistant",
201+
content: [{ type: "text", text: "Current final reply" }],
202+
__openclaw: { id: "current-final", seq: 2 },
203+
},
204+
},
205+
});
206+
207+
expect(state.chatMessages).toEqual([currentUser]);
208+
expect(state.chatStream).toBe("Current partial reply");
209+
});
210+
110211
it("renders distinct live peers immediately and coalesces their stale history", async () => {
111212
let resolveHistory!: (result: {
112213
messages: unknown[];

0 commit comments

Comments
 (0)