Skip to content

Commit 9327c10

Browse files
feat(ui): edit a queued chat message in place (#121692)
* feat(ui): edit a queued chat message in place The pencil on a queued row, or a double-click, lifts the message and its attachments into the composer. The row stays where it is, marked Editing, so the position the corrected message will take is visible rather than promised. The composer shows an edit banner with an X to cancel. Cancelling touches storage not at all, because the row never left the queue. Sending retires the original and hands its position to the replacement, which lands in the same slot. While an edit is open the drain refuses that row, so a reconnect cannot deliver the text the operator is visibly rewriting; the queue behind it waits, which is the same contract the held position promises. * fix(ui): retire an edited queued row only with its replacement The send retired the source row first and admitted the replacement second, so a rejected store write left the operator with neither: the original gone, the replacement never persisted, and the attachments it dropped already released. Admission now carries the source id and swaps both rows in one store write, so a rejected write changes nothing and the edit stays open on the row that is still there, which is what cancelling already promises. Filtering the source before the cap check also keeps a replacement admissible on a full queue. The edit token recorded only the session key, but an outbox is scoped by session and agent, and a raw global session keeps its key while the selected agent changes underneath it. The token now carries the agent that owned the row and every reader validates the whole scope, so a send after a switch cannot retire a row in the outbox it left behind. * fix(ui): hold an edited queued row across every pane Panes share one outbox and one drain lane while composer state stays per pane, so the hold that keeps a row from being delivered while it is rewritten was invisible to the pane that drained it: a session event in a second split pane resumed every stored outbox, saw no edit, and sent the original text. The hold is now read across every pane subscribed to the outbox, which keeps one source of truth — each pane's own scope-validated edit — and needs no lifecycle of its own, so closing a pane or switching agent releases it by simply no longer being an active edit. The payloads an edit owns now travel with its token. The write that admits the replacement retires the source row and tells every pane synchronously, so by the time the send released the images the replacement had dropped, the row holding them was already gone and nothing was released. That leaked the payload and its object URL for the rest of the browser session. * fix(ui): release attachments from cancelled queue edits
1 parent e4a6ded commit 9327c10

24 files changed

Lines changed: 937 additions & 31 deletions

‎docs/web/control-ui.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -508,6 +508,7 @@ Capability toggles stay disabled until the Gateway, session, and runtime config
508508
- Click **Stop**. Runs with an exact local run ID call `chat.abort`; when selected-session state reports active work but the Control UI has no local run ID, it calls `sessions.abort` instead. For non-global sessions, that selected-session path also discards queued follow-ups so they cannot restart work after the stop.
509509
- While a run is active, normal follow-ups use the Gateway's effective `messages.queue` mode. `steer` injects into the running turn; other modes keep the browser's durable queued delivery. Steering rejection also falls back to that queue. Click **Steer** on a queued message to inject it manually.
510510
- Reorder the queue from the handle on the left of a queued message: drag it, or focus it and press the up and down arrow keys. The position is stored with the message, so it survives a reload and decides delivery order, not just what the list looks like. Rows already handed to a run — sending, steering, running a command, awaiting settings, or waiting on an uncertain delivery — hold their place and split the queue: a message moves only among the rows between two of them, so it can never reach the Gateway ahead of work already handed over.
511+
- Edit a queued message with the pencil on its row, or by double-clicking the row. The message and its attachments move into the composer, the row stays where it is marked **Editing**, and a pencil marker with an X to cancel appears beside the input. Cancelling leaves the queued message exactly as it was. Sending replaces it in the same slot, and if the queue drained in the meantime it simply sends as a normal turn. The queue behind an edited row waits rather than delivering a message you are still rewriting, so that row splits the queue for reordering the same way an in-flight row does. Editing needs an empty composer, and queued slash commands keep the discard-and-retype flow.
511512
- **Settings → Appearance → Chat → Follow-ups while the agent is working** can override that server default for the current browser. The page marks an override explicitly and offers **Reset to server default**. `Steer into the active run` sends follow-ups immediately, while `Queue until the run ends` holds them until the run finishes.
512513
- Type `/stop` (or standalone abort phrases like `stop`, `stop action`, `stop run`, `stop openclaw`, `please stop`) to abort out-of-band.
513514
- `chat.abort` supports `{ sessionKey }` (no `runId`) to abort all active runs for that session. The Control UI uses `sessions.abort` when it has no local run ID.
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
import { expect, it } from "vitest";
2+
import { createChatFlowE2eSuite, installMockGateway } from "./chat-flow.test-support.ts";
3+
4+
const suite = createChatFlowE2eSuite();
5+
6+
const QUEUED = ["review the migration", "then update the docs", "finally run the smoke"] as const;
7+
8+
/** Vertical centre of each control on the composer's input row, in page pixels. */
9+
const COMPOSER_ROW_CONTROLS = [
10+
".agent-chat__input-btn--attach",
11+
".agent-chat__composer-edit",
12+
".agent-chat__composer-combobox textarea",
13+
".agent-chat__composer-actions",
14+
] as const;
15+
16+
suite.define(() => {
17+
it("edits a queued message in the composer and returns it to its place", async () => {
18+
const context = await suite.newBrowserContext({
19+
locale: "en-US",
20+
serviceWorkers: "block",
21+
viewport: { height: 900, width: 1280 },
22+
});
23+
const page = await context.newPage();
24+
const gateway = await installMockGateway(page);
25+
26+
try {
27+
await page.goto(`${suite.server.baseUrl}chat`);
28+
const composer = page.locator(".agent-chat__composer-combobox textarea");
29+
await composer.waitFor({ state: "visible", timeout: 15_000 });
30+
31+
// Offline holds the queue still, so the round-trip stays observable.
32+
await gateway.setOnline(false);
33+
await gateway.closeLatest();
34+
for (const message of QUEUED) {
35+
await composer.fill(message);
36+
await composer.press("Enter");
37+
await page.locator(".chat-queue__item", { hasText: message }).waitFor({ timeout: 10_000 });
38+
}
39+
const queueText = () => page.locator(".chat-queue__item .chat-queue__text").allTextContents();
40+
expect(await queueText()).toEqual([...QUEUED]);
41+
42+
// Double-click is the shortcut; the pencil on the row is the visible path.
43+
await page.locator(".chat-queue__item").nth(1).dblclick();
44+
45+
await expect.poll(() => composer.inputValue(), { timeout: 10_000 }).toBe(QUEUED[1]);
46+
await page.locator(".agent-chat__composer-edit").waitFor({ timeout: 10_000 });
47+
// The row stays where it is, marked as the one being edited.
48+
expect(await queueText()).toEqual([...QUEUED]);
49+
expect(await page.locator(".chat-queue__item--editing").count()).toBe(1);
50+
expect(
51+
await page.locator(".chat-queue__item").nth(1).locator(".chat-queue__badge").textContent(),
52+
).toBe("Editing");
53+
54+
// The marker is a new child of a bottom-aligned row, so prove the row still
55+
// resolves to one axis instead of trusting that it looks right.
56+
const centres = await page.evaluate(
57+
(selectors) => {
58+
const row = document.querySelector(".agent-chat__composer-input-row");
59+
return selectors.map((selector) => {
60+
const box = row?.querySelector(selector)?.getBoundingClientRect();
61+
return box ? box.top + box.height / 2 : Number.NaN;
62+
});
63+
},
64+
COMPOSER_ROW_CONTROLS as unknown as string[],
65+
);
66+
expect(centres.some(Number.isNaN)).toBe(false);
67+
expect(Math.max(...centres) - Math.min(...centres)).toBeLessThanOrEqual(1);
68+
69+
await composer.fill("then update the docs and the changelog");
70+
await composer.press("Enter");
71+
72+
await expect
73+
.poll(queueText, { timeout: 10_000 })
74+
.toEqual([QUEUED[0], "then update the docs and the changelog", QUEUED[2]]);
75+
expect(await page.locator(".agent-chat__composer-edit").count()).toBe(0);
76+
} finally {
77+
await suite.closeBrowserContext(context);
78+
}
79+
});
80+
81+
it("puts the row back untouched when the edit is cancelled", async () => {
82+
const context = await suite.newBrowserContext({
83+
locale: "en-US",
84+
serviceWorkers: "block",
85+
viewport: { height: 900, width: 1280 },
86+
});
87+
const page = await context.newPage();
88+
const gateway = await installMockGateway(page);
89+
90+
try {
91+
await page.goto(`${suite.server.baseUrl}chat`);
92+
const composer = page.locator(".agent-chat__composer-combobox textarea");
93+
await composer.waitFor({ state: "visible", timeout: 15_000 });
94+
await gateway.setOnline(false);
95+
await gateway.closeLatest();
96+
for (const message of QUEUED) {
97+
await composer.fill(message);
98+
await composer.press("Enter");
99+
await page.locator(".chat-queue__item", { hasText: message }).waitFor({ timeout: 10_000 });
100+
}
101+
102+
const row = page.locator(".chat-queue__item").nth(1);
103+
await row.locator(".chat-queue__edit").click();
104+
await page.locator(".agent-chat__composer-edit").waitFor({ timeout: 10_000 });
105+
await composer.fill("a replacement the operator abandons");
106+
107+
await page.locator(".agent-chat__composer-edit-cancel").click();
108+
109+
await expect
110+
.poll(() => page.locator(".chat-queue__item .chat-queue__text").allTextContents(), {
111+
timeout: 10_000,
112+
})
113+
.toEqual([...QUEUED]);
114+
expect(await composer.inputValue()).toBe("");
115+
} finally {
116+
await suite.closeBrowserContext(context);
117+
}
118+
});
119+
});

‎ui/src/i18n/locales/en.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4869,12 +4869,19 @@ export const en: TranslationMap = {
48694869
steerQueuedMessage: "Steer queued message",
48704870
removeQueuedMessage: "Remove queued message",
48714871
reorderQueuedMessage: "Reorder queued message with the arrow keys",
4872+
reorderUnavailable: "This message holds its place and cannot be reordered",
4873+
editQueuedMessage: "Edit queued message",
4874+
editing: "Editing a queued message",
4875+
cancelEdit: "Cancel editing and keep the queued message",
4876+
editNeedsEmptyComposer:
4877+
"Editing needs an empty composer. Send or clear your current message first.",
48724878
states: {
48734879
steering: "Steering",
48744880
applyingSettings: "Applying chat settings",
48754881
waitingForRun: "Waiting for current run",
48764882
runningCommand: "Running command",
48774883
waitingForReconnect: "Waiting for reconnect",
4884+
editing: "Editing",
48784885
needsReview: "Delivery uncertain",
48794886
},
48804887
imageCount: "Image ({count})",

‎ui/src/lib/chat/chat-queue-order.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ type ChatQueuePosition = Pick<ChatQueueItem, "createdAt" | "orderKey">;
66
* Canonical queue position. `orderKey` is the operator-owned position; `createdAt`
77
* is the arrival fact and stays the default so an untouched queue is FIFO.
88
*/
9-
function chatQueueOrderKey(item: ChatQueuePosition): number {
9+
export function chatQueueOrderKey(item: ChatQueuePosition): number {
1010
return item.orderKey ?? item.createdAt;
1111
}
1212

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

Lines changed: 78 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,84 @@ describe("chat composer queue reordering", () => {
120120
expect(container.querySelector(".chat-queue__item")?.getAttribute("draggable")).toBe("false");
121121
});
122122

123+
it("reserves the handle column on every row so the pills never shift", () => {
124+
const container = renderQueue({
125+
queue: [
126+
{ id: "steer", text: "steer", createdAt: 1, kind: "steered", pendingRunId: "run-1" },
127+
waiting("b", 2),
128+
waiting("c", 3),
129+
],
130+
onQueueMove: vi.fn(),
131+
onQueueRemove: vi.fn(),
132+
});
133+
134+
const grips = [...container.querySelectorAll(".chat-queue__item")].map((row) =>
135+
row.querySelector(".chat-queue__grip"),
136+
);
137+
// Every row keeps the column; only the rows that may move keep it live.
138+
expect(grips.every((grip) => grip !== null)).toBe(true);
139+
expect(grips.map((grip) => grip!.hasAttribute("disabled"))).toEqual([true, false, false]);
140+
expect(grips[0]?.getAttribute("aria-label")).toBe(t("chat.queue.reorderUnavailable"));
141+
expect(grips[0]?.hasAttribute("aria-keyshortcuts")).toBe(false);
142+
});
143+
144+
it("holds the column with an inert handle on the row being edited", () => {
145+
const onQueueMove = vi.fn();
146+
const container = renderQueue({
147+
queue: [waiting("a", 1), waiting("b", 2), waiting("c", 3)],
148+
editingId: "b",
149+
onQueueMove,
150+
onQueueRemove: vi.fn(),
151+
});
152+
153+
const rows = [...container.querySelectorAll(".chat-queue__item")];
154+
const grips = rows.map((row) => row.querySelector(".chat-queue__grip"));
155+
expect(grips.every((grip) => grip !== null)).toBe(true);
156+
// The edited row holds the drain, so it splits the queue: neither neighbour
157+
// has anywhere to go, and every handle waits without leaving the column.
158+
expect(grips.map((grip) => grip!.hasAttribute("disabled"))).toEqual([true, true, true]);
159+
expect(rows[1]?.classList.contains("chat-queue__item--editing")).toBe(true);
160+
161+
const event = new KeyboardEvent("keydown", { key: "ArrowUp", bubbles: true, cancelable: true });
162+
grips[1]!.dispatchEvent(event);
163+
164+
expect(onQueueMove).not.toHaveBeenCalled();
165+
expect(event.defaultPrevented).toBe(false);
166+
});
167+
168+
it("holds every action slot inert while one edit is open", () => {
169+
const onQueueEdit = vi.fn();
170+
const onQueueRemove = vi.fn();
171+
const container = renderQueue({
172+
queue: [waiting("a", 1), waiting("b", 2), waiting("c", 3)],
173+
editingId: "b",
174+
onQueueEdit,
175+
onQueueMove: vi.fn(),
176+
onQueueRemove,
177+
});
178+
179+
const rows = [...container.querySelectorAll(".chat-queue__item")];
180+
// Every row keeps both buttons, so no column shifts while the edit is open.
181+
for (const selector of [".chat-queue__edit", ".chat-queue__remove"]) {
182+
const present = rows.map((row) => row.querySelector(selector) !== null);
183+
expect(present).toEqual([true, true, true]);
184+
}
185+
// One edit at a time, so every pencil waits; discarding another row is still
186+
// safe, so only the edited row's X goes inert.
187+
const disabled = (selector: string) =>
188+
rows.map((row) => row.querySelector(selector)!.hasAttribute("disabled"));
189+
expect(disabled(".chat-queue__edit")).toEqual([true, true, true]);
190+
expect(disabled(".chat-queue__remove")).toEqual([false, true, false]);
191+
192+
rows[0]?.querySelector<HTMLButtonElement>(".chat-queue__edit")?.click();
193+
rows[1]?.querySelector<HTMLButtonElement>(".chat-queue__remove")?.click();
194+
expect(onQueueEdit).not.toHaveBeenCalled();
195+
expect(onQueueRemove).not.toHaveBeenCalled();
196+
197+
rows[2]?.querySelector<HTMLButtonElement>(".chat-queue__remove")?.click();
198+
expect(onQueueRemove).toHaveBeenCalledWith("c");
199+
});
200+
123201
it("keeps a row that already joined a run out of the reorder set", () => {
124202
const container = renderQueue({
125203
queue: [
@@ -133,7 +211,6 @@ describe("chat composer queue reordering", () => {
133211

134212
const rows = [...container.querySelectorAll(".chat-queue__item")];
135213
expect(rows.map((row) => row.getAttribute("draggable"))).toEqual(["false", "true", "true"]);
136-
expect(rows[0]?.querySelector(".chat-queue__grip")).toBeNull();
137214
});
138215

139216
it("offers no move to a row alone between locked rows, and refuses a drop from across one", () => {

‎ui/src/pages/chat/chat-outbox-drain.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import {
2727
type StoredChatOutbox,
2828
type StoredChatOutboxScope,
2929
} from "./composer-persistence.ts";
30+
import { isQueuedMessageBeingEdited } from "./queued-message-edit.ts";
3031
import { isChatBusy } from "./run-lifecycle.ts";
3132
import {
3233
chatMessagesContainQueuedSend,
@@ -285,7 +286,11 @@ async function drainStoredChatOutbox(
285286
}
286287
if (
287288
item.sendState === "unconfirmed" ||
288-
(item.sendState === "waiting-model" && !lane.pendingOptions.has(item.id))
289+
(item.sendState === "waiting-model" && !lane.pendingOptions.has(item.id)) ||
290+
// An open edit owns this row: sending the superseded text would deliver a
291+
// message the operator is visibly rewriting. The queue behind it waits,
292+
// which is the same contract the row's held position promises.
293+
isQueuedMessageBeingEdited(host, item.id)
289294
) {
290295
syncVisibleChatQueueProjection(host);
291296
return "blocked";

‎ui/src/pages/chat/chat-outbox-owner.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,16 @@ class ChatOutboxGatewayOwner {
233233
hasVolatile(host: Host, id: string): boolean {
234234
return this.hosts.get(host)?.retryable.has(id) ?? false;
235235
}
236+
// Panes share this outbox and its drain while composer state stays per pane, so
237+
// a pane-local fact that blocks delivery has to be answerable from any of them.
238+
anyPane(matches: (host: Host) => boolean): boolean {
239+
for (const pane of this.panes) {
240+
if (matches(pane)) {
241+
return true;
242+
}
243+
}
244+
return false;
245+
}
236246
mayRemove(host: Host, scope: Scope, id: string): boolean {
237247
const live = this.live.get(storedChatOutboxScopeKey(scope))?.get(id);
238248
const local = host.chatQueue.find((item) => item.id === id);

‎ui/src/pages/chat/chat-pane-render.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ import {
6161
openSessionWorkspaceFile,
6262
revealSessionWorkspaceFile,
6363
} from "./components/chat-session-workspace.ts";
64+
import { activeQueuedMessageEdit } from "./queued-message-edit.ts";
6465
import { hasAbortableSessionRun } from "./run-lifecycle.ts";
6566
import { scheduleChatScroll } from "./scroll.ts";
6667
import {
@@ -549,6 +550,11 @@ export class ChatPane extends ChatPaneBrowserAnnotationRender {
549550
? undefined
550551
: (id) => void state.steerQueuedChatMessage(id),
551552
onQueueMove: sessionParticipationBlocked ? undefined : state.moveQueuedChatMessage,
553+
queuedEdit: {
554+
editingId: activeQueuedMessageEdit(state)?.id ?? null,
555+
onEdit: sessionParticipationBlocked ? undefined : state.editQueuedChatMessage,
556+
onCancel: state.cancelQueuedChatMessageEdit,
557+
},
552558
onGoalCommand: (command) => void state.handleSendChat(command),
553559
onCompanionQuestion: (question) => void this.submitSessionCompanionQuestion(question),
554560
onCompanionPrefill: this.prefillSessionCompanionQuestion,

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

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,24 @@ export function isVolatileQueuedMessage(host: ChatQueueScopedSessionHost, id: st
3636
return chatOutboxOwner(host).hasVolatile(host, id);
3737
}
3838

39+
/** True while the row has a stored copy that would survive a reload. */
40+
export function isDurableQueuedMessage(host: ChatQueueScopedSessionHost, id: string): boolean {
41+
return chatOutboxOwner(host).durable(host, id) !== undefined;
42+
}
43+
44+
/**
45+
* Every pane sharing an outbox also shares its drain, and any of them can own the
46+
* drain lane. A fact one pane records about a row — a delivery hold, say — has to
47+
* be read across all of them, or the pane that drains will not see it. Panes
48+
* registered with an owner are the same kind of chat host as the caller.
49+
*/
50+
export function anyChatOutboxPaneMatches<T extends ChatQueueScopedSessionHost>(
51+
host: T,
52+
matches: (pane: T) => boolean,
53+
): boolean {
54+
return matches(host) || chatOutboxOwner(host).anyPane((pane) => matches(pane as T));
55+
}
56+
3957
export function keepVolatileQueuedMessage(
4058
host: ChatQueueScopedSessionHost,
4159
sessionKey: string,
@@ -259,15 +277,21 @@ export function updateQueuedMessageForSession(
259277
return nextItem;
260278
}
261279

280+
/**
281+
* `replacesId` admits the item as the stored replacement for another row, which
282+
* retires the source in the same write. A rejected write changes nothing, so an
283+
* edited message can never lose both its original and its replacement.
284+
*/
262285
export function admitQueuedMessageForSession(
263286
host: ChatQueueScopedSessionHost,
264287
sessionKey: string,
265288
item: ChatQueueItem,
289+
replacesId?: string,
266290
): boolean {
267291
const owner = chatOutboxOwner(host);
268292
const scope = resolveStoredChatOutboxScope(host, sessionKey, item.agentId);
269293
owner.keep(host, scope, item);
270-
if (!admitStoredChatComposerQueueItem(host, sessionKey, item, item.agentId)) {
294+
if (!admitStoredChatComposerQueueItem(host, sessionKey, item, item.agentId, replacesId)) {
271295
return false;
272296
}
273297
if (item.sendState !== "waiting-model") {

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import type { ChatCommandHost } from "./chat-commands.ts";
88
import type { ChatRunStartupState } from "./chat-run-startup.ts";
99
import type { ChatSendTimingEntry } from "./chat-send-ack.ts";
1010
import type { ChatInputHistoryState } from "./input-history.ts";
11+
import type { QueuedMessageEdit } from "./queued-message-edit.ts";
1112
import type { RenderLifecycle } from "./render-lifecycle.ts";
1213

1314
type ChatAgentsListSnapshot = Partial<Omit<AgentsListResult, "agents">> & {
@@ -23,6 +24,8 @@ export type ChatHost = ChatInputHistoryState &
2324
connectionEpoch?: number;
2425
chatAttachments: ChatAttachment[];
2526
chatQueue: ChatQueueItem[];
27+
/** Set while a queued row is held out of the queue inside the composer. */
28+
chatQueuedEdit?: QueuedMessageEdit | null;
2629
/** Active leaf of the history snapshot currently rendered by this pane. */
2730
chatDisplayedLeafEntryId?: string | null;
2831
chatRunId: string | null;

0 commit comments

Comments
 (0)