Skip to content

Commit 554e811

Browse files
committed
fix(ui): keep queued message removals exact
1 parent 7e09412 commit 554e811

5 files changed

Lines changed: 255 additions & 9 deletions

File tree

‎ui/src/e2e/chat-flow.queue-edit.e2e.test.ts‎

Lines changed: 229 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
import { expect, it } from "vitest";
2-
import { createChatFlowE2eSuite, installMockGateway } from "./chat-flow.test-support.ts";
2+
import {
3+
createChatFlowE2eSuite,
4+
expectRequestCountStable,
5+
installMockGateway,
6+
requireRecord,
7+
requireString,
8+
waitForRequests,
9+
} from "./chat-flow.test-support.ts";
310

411
const suite = createChatFlowE2eSuite();
512

@@ -116,4 +123,225 @@ suite.define(() => {
116123
await suite.closeBrowserContext(context);
117124
}
118125
});
126+
127+
it("keeps edit, remove, and reorder outcomes exact through reconnect", async () => {
128+
const artifactDir = process.env.OPENCLAW_UI_E2E_ARTIFACT_DIR?.trim();
129+
const context = await suite.newBrowserContext({
130+
locale: "en-US",
131+
...(artifactDir
132+
? { recordVideo: { dir: artifactDir, size: { height: 900, width: 1280 } } }
133+
: {}),
134+
serviceWorkers: "block",
135+
viewport: { height: 900, width: 1280 },
136+
});
137+
const page = await context.newPage();
138+
const gateway = await installMockGateway(page, {
139+
methodResponses: {
140+
"chat.history": {
141+
messages: [],
142+
sessionId: "control-ui-e2e-session",
143+
sessionInfo: { hasActiveRun: false, status: "done" },
144+
thinkingLevel: null,
145+
},
146+
},
147+
});
148+
149+
try {
150+
await page.goto(`${suite.server.baseUrl}settings/appearance`);
151+
await page.locator("[data-settings-follow-up-mode]").selectOption("queue");
152+
await page.goto(`${suite.server.baseUrl}chat?session=main`);
153+
const composer = page.locator(".agent-chat__composer-combobox textarea");
154+
await composer.waitFor({ state: "visible", timeout: 15_000 });
155+
await composer.fill("keep the first run active");
156+
await page.getByRole("button", { name: "Send message" }).click();
157+
const active = requireRecord((await gateway.waitForRequest("chat.send")).params);
158+
const activeRunId = requireString(active.idempotencyKey, "active run idempotency key");
159+
await page.getByRole("button", { name: "Stop generating" }).waitFor({ timeout: 10_000 });
160+
161+
for (const message of ["send first", "edit before send", "remove me", "send last"]) {
162+
await composer.fill(message);
163+
await page.getByRole("button", { name: "Queue message" }).click();
164+
await page.locator(".chat-queue__item", { hasText: message }).waitFor({ timeout: 10_000 });
165+
}
166+
await gateway.setOnline(false);
167+
await gateway.closeLatest();
168+
await page.locator(".agent-chat__offline-hint").waitFor({ timeout: 10_000 });
169+
170+
await page.locator(".chat-queue__item", { hasText: "edit before send" }).dblclick();
171+
await expect.poll(() => composer.inputValue()).toBe("edit before send");
172+
await composer.fill("edited before send");
173+
await composer.press("Enter");
174+
await page.locator(".chat-queue__item", { hasText: "edited before send" }).waitFor();
175+
176+
const lastGrip = page
177+
.locator(".chat-queue__item", { hasText: "send last" })
178+
.locator(".chat-queue__grip");
179+
await lastGrip.focus();
180+
for (const expected of [
181+
["send first", "edited before send", "send last", "remove me"],
182+
["send first", "send last", "edited before send", "remove me"],
183+
["send last", "send first", "edited before send", "remove me"],
184+
]) {
185+
await page.keyboard.press("ArrowUp");
186+
await expect
187+
.poll(() => page.locator(".chat-queue__item .chat-queue__text").allTextContents())
188+
.toEqual(expected);
189+
}
190+
191+
const row = page.locator(".chat-queue__item", {
192+
hasText: "remove me",
193+
});
194+
195+
await page.evaluate(() => {
196+
const descriptor = Object.getOwnPropertyDescriptor(Storage.prototype, "setItem");
197+
if (!descriptor || typeof descriptor.value !== "function") {
198+
throw new Error("Storage.setItem is unavailable");
199+
}
200+
const original = descriptor.value as (this: Storage, key: string, value: string) => void;
201+
Object.defineProperty(window, "restoreQueueStorage", {
202+
configurable: true,
203+
value: () => {
204+
Object.defineProperty(Storage.prototype, "setItem", descriptor);
205+
delete (window as Window & { restoreQueueStorage?: () => void }).restoreQueueStorage;
206+
},
207+
});
208+
Object.defineProperty(Storage.prototype, "setItem", {
209+
...descriptor,
210+
value(this: Storage, ...args: [string, string]) {
211+
if (this === window.sessionStorage) {
212+
throw new DOMException("exceeded the quota", "QuotaExceededError");
213+
}
214+
return Reflect.apply(original, this, args);
215+
},
216+
});
217+
});
218+
await row.locator(".chat-queue__remove").click();
219+
220+
await page
221+
.getByRole("alert")
222+
.getByText("Could not store this message for reconnect.", { exact: false })
223+
.waitFor({ timeout: 10_000 });
224+
await row.waitFor();
225+
expect(await gateway.getRequests("chat.send")).toHaveLength(1);
226+
if (artifactDir) {
227+
await page.waitForTimeout(100);
228+
await page.screenshot({ path: `${artifactDir}/01-remove-rejected.png`, fullPage: true });
229+
}
230+
231+
await page.evaluate(() => {
232+
(window as Window & { restoreQueueStorage?: () => void }).restoreQueueStorage?.();
233+
});
234+
await page.evaluate(() => {
235+
const trace: Array<{ detail: number; rowText?: string }> = [];
236+
Object.defineProperty(window, "queueRemovalEventTrace", {
237+
configurable: true,
238+
value: trace,
239+
});
240+
document.addEventListener(
241+
"click",
242+
(event) => {
243+
const target = event.target instanceof Element ? event.target : null;
244+
trace.push({
245+
detail: (event as MouseEvent).detail,
246+
rowText: target?.closest(".chat-queue__item")?.querySelector(".chat-queue__text")
247+
?.textContent,
248+
});
249+
},
250+
{ capture: true },
251+
);
252+
});
253+
await row.locator(".chat-queue__remove").dblclick();
254+
expect(
255+
await page.evaluate(
256+
() =>
257+
(
258+
window as Window & {
259+
queueRemovalEventTrace?: Array<{ detail: number; rowText?: string }>;
260+
}
261+
).queueRemovalEventTrace,
262+
),
263+
).toEqual([
264+
{ detail: 1, rowText: "remove me" },
265+
{ detail: 2, rowText: "edited before send" },
266+
]);
267+
await row.waitFor({ state: "detached", timeout: 10_000 });
268+
await page.getByRole("alert").waitFor({ state: "detached", timeout: 10_000 });
269+
await expect
270+
.poll(() => page.locator(".chat-queue__item .chat-queue__text").allTextContents())
271+
.toEqual(["send last", "send first", "edited before send"]);
272+
expect(await gateway.getRequests("chat.send")).toHaveLength(1);
273+
274+
const queueDisposable = async (text: string) => {
275+
await composer.fill(text);
276+
await composer.press("Enter");
277+
const disposable = page.locator(".chat-queue__item", { hasText: text });
278+
await disposable.waitFor({ timeout: 10_000 });
279+
return disposable;
280+
};
281+
const singleClickRow = await queueDisposable("single-click removal");
282+
await singleClickRow.locator(".chat-queue__remove").click();
283+
await singleClickRow.waitFor({ state: "detached", timeout: 10_000 });
284+
const keyboardRow = await queueDisposable("keyboard removal");
285+
await keyboardRow.locator(".chat-queue__remove").focus();
286+
await page.keyboard.press("Enter");
287+
await keyboardRow.waitFor({ state: "detached", timeout: 10_000 });
288+
const programmaticRow = await queueDisposable("programmatic removal");
289+
await programmaticRow
290+
.locator(".chat-queue__remove")
291+
.evaluate((button: HTMLElement) => button.click());
292+
await programmaticRow.waitFor({ state: "detached", timeout: 10_000 });
293+
await page.getByRole("alert").waitFor({ state: "detached", timeout: 10_000 });
294+
expect(await gateway.getRequests("chat.send")).toHaveLength(1);
295+
if (artifactDir) {
296+
await page.screenshot({ path: `${artifactDir}/02-duplicate-noop.png`, fullPage: true });
297+
}
298+
299+
await gateway.deferNext("chat.send");
300+
await gateway.setOnline(true);
301+
await page
302+
.locator(".agent-chat__offline-hint")
303+
.waitFor({ state: "detached", timeout: 10_000 });
304+
await gateway.emitChatFinal({ runId: activeRunId, text: "Initial run completed." });
305+
await gateway.emitGatewayEvent("sessions.changed", {
306+
activeRunIds: [],
307+
agentId: "main",
308+
hasActiveRun: false,
309+
key: "global",
310+
status: "done",
311+
});
312+
313+
const first = requireRecord((await waitForRequests(gateway, "chat.send", 2))[1]?.params);
314+
expect(first.message).toBe("send last");
315+
const firstRunId = requireString(first.idempotencyKey, "first queued send idempotency key");
316+
await gateway.resolveDeferred("chat.send", { runId: firstRunId, status: "started" });
317+
await gateway.emitChatFinal({ runId: firstRunId, text: "First queued turn completed." });
318+
319+
const second = requireRecord((await waitForRequests(gateway, "chat.send", 3))[2]?.params);
320+
const secondRunId = requireString(
321+
second.idempotencyKey,
322+
"second queued send idempotency key",
323+
);
324+
await gateway.emitChatFinal({ runId: secondRunId, text: "Second queued turn completed." });
325+
326+
const sends = await waitForRequests(gateway, "chat.send", 4);
327+
const third = requireRecord(sends[3]?.params);
328+
const thirdRunId = requireString(third.idempotencyKey, "third queued send idempotency key");
329+
await gateway.emitChatFinal({ runId: thirdRunId, text: "Third queued turn completed." });
330+
const params = sends.map((request) => requireRecord(request.params));
331+
expect(params.map((entry) => entry.message)).toEqual([
332+
"keep the first run active",
333+
"send last",
334+
"send first",
335+
"edited before send",
336+
]);
337+
expect(new Set(params.map((entry) => entry.idempotencyKey)).size).toBe(4);
338+
await expectRequestCountStable(gateway, "chat.send", 4);
339+
await page.locator(".chat-queue").waitFor({ state: "detached", timeout: 10_000 });
340+
if (artifactDir) {
341+
await page.screenshot({ path: `${artifactDir}/03-exact-drain.png`, fullPage: true });
342+
}
343+
} finally {
344+
await suite.closeBrowserContext(context);
345+
}
346+
});
119347
});

‎ui/src/pages/chat/chat-queue.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -361,10 +361,12 @@ export function excludeComposerAttachments(
361361
}
362362

363363
export function removeQueuedMessage(host: ChatQueueScopedSessionHost, id: string) {
364-
const removed = removeQueuedMessageWithoutReleasing(host, id);
364+
const item = readQueuedMessageById(host, id);
365+
const removed = item ? removeQueuedMessageWithoutReleasing(host, id) : null;
365366
if (removed) {
366367
releaseChatAttachmentPayloads(excludeComposerAttachments(host, removed.attachments));
367368
}
369+
return removed ? ("removed" as const) : item ? ("rejected" as const) : ("absent" as const);
368370
}
369371

370372
export function removeDeliveredQueuedChatSendForRun(

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

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9380,7 +9380,7 @@ describe("handleSendChat", () => {
93809380
]);
93819381
});
93829382

9383-
it("releases queued attachment payloads when the queued item is removed", () => {
9383+
it("releases queued attachment payloads once across duplicate removal", () => {
93849384
const revokeObjectURL = vi.fn();
93859385
vi.stubGlobal(
93869386
"URL",
@@ -9401,12 +9401,16 @@ describe("handleSendChat", () => {
94019401
file,
94029402
});
94039403
const host = makeChatHost({
9404-
chatQueue: [{ id: "queued", text: "later", createdAt: 1, attachments: [attachment] }],
9404+
chatQueue: [
9405+
{ id: "queued", text: "later", createdAt: 1, attachments: [attachment] },
9406+
{ id: "sibling", text: "keep me", createdAt: 2 },
9407+
],
94059408
});
94069409

9407-
removeQueuedMessage(host, "queued");
9410+
expect(removeQueuedMessage(host, "queued")).toBe("removed");
9411+
expect(removeQueuedMessage(host, "queued")).toBe("absent");
94089412

9409-
expect(host.chatQueue).toStrictEqual([]);
9413+
expect(host.chatQueue).toEqual([expect.objectContaining({ id: "sibling" })]);
94109414
expect(getChatAttachmentDataUrl(attachment)).toBeNull();
94119415
expect(revokeObjectURL).toHaveBeenCalledWith("blob:queued");
94129416
});

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

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ import {
5252
normalizeSidebarLayout,
5353
openSlot,
5454
} from "./sidebar-layout.ts";
55+
import { OFFLINE_QUEUE_STORAGE_ERROR } from "./steer-lifecycle.ts";
5556
import { resetToolStream } from "./tool-stream.ts";
5657

5758
type ChatPageElement = {
@@ -309,8 +310,13 @@ export function createPageState(
309310
renderLifecycle.invalidate();
310311
};
311312
state.removeQueuedMessage = (id) => {
312-
removeQueuedMessage(state, id);
313-
void resumeStoredChatOutboxes(state);
313+
const outcome = removeQueuedMessage(state, id);
314+
if (outcome === "removed") {
315+
setChatError(state, null);
316+
void resumeStoredChatOutboxes(state);
317+
} else if (outcome === "rejected") {
318+
setChatError(state, OFFLINE_QUEUE_STORAGE_ERROR);
319+
}
314320
renderLifecycle.invalidate();
315321
};
316322
state.retryQueuedChatMessage = async (id) => {

‎ui/src/pages/chat/components/chat-composer-queue.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,13 @@ function renderChatQueueItem(
267267
type="button"
268268
?disabled=${editing}
269269
aria-label=${t("chat.queue.removeQueuedMessage")}
270-
@click=${() => props.onQueueRemove(item.id)}
270+
@click=${(event: MouseEvent) => {
271+
// Chromium retargets click 2 after row removal; detail still owns the gesture.
272+
if (event.detail <= 1) {
273+
props.onQueueRemove(item.id);
274+
}
275+
}}
276+
@dblclick=${(event: MouseEvent) => event.stopPropagation()}
271277
>
272278
${icons.x}
273279
</button>

0 commit comments

Comments
 (0)