Skip to content

Commit 7f75fe5

Browse files
committed
fix(ui): keep acknowledged sends pending during stale history
1 parent 1fab280 commit 7f75fe5

3 files changed

Lines changed: 191 additions & 3 deletions

File tree

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

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@ import {
1717
type ChatCommandResetOptions,
1818
} from "./chat-commands.ts";
1919
import { loadChatHistory, type ChatHistoryResult } from "./chat-history.ts";
20+
import { chatOutboxOwner } from "./chat-outbox-owner.ts";
2021
import {
22+
anyChatOutboxPaneMatches,
2123
excludeComposerAttachments,
2224
readQueuedMessageById,
2325
removeQueuedMessageWithoutReleasing,
@@ -91,6 +93,7 @@ type StoredChatOutboxClientState = {
9193
retryTimers: Map<string, ReturnType<typeof setTimeout>>;
9294
};
9395

96+
const STORED_OUTBOX_CONFIRMATION_GRACE_MS = 5_000;
9497
const STORED_OUTBOX_RETRY_DEFAULT_MS = 500;
9598
const STORED_OUTBOX_RETRY_MIN_MS = 100;
9699
const STORED_OUTBOX_RETRY_MAX_MS = 30_000;
@@ -106,7 +109,10 @@ function getStoredChatOutboxClientState(client: GatewayBrowserClient): StoredCha
106109
if (existing) {
107110
return existing;
108111
}
109-
const created = { lanes: new Map(), retryTimers: new Map() };
112+
const created: StoredChatOutboxClientState = {
113+
lanes: new Map(),
114+
retryTimers: new Map(),
115+
};
110116
storedChatOutboxClients.set(client, created);
111117
return created;
112118
}
@@ -164,6 +170,10 @@ function sameQueuedDeliveryVersion(left: ChatQueueItem, right: ChatQueueItem): b
164170
);
165171
}
166172

173+
function queuedDeliveryVersion(item: ChatQueueItem): string {
174+
return `${item.id}\u0000${item.sendRunId ?? ""}\u0000${item.sendAttempts ?? 0}`;
175+
}
176+
167177
async function readCurrentStoredChatHistory(
168178
host: ChatHost,
169179
outbox: StoredChatOutbox,
@@ -282,21 +292,54 @@ async function reconcileStoredChatOutboxHead(
282292
return "blocked";
283293
}
284294
}
295+
const outboxOwner = chatOutboxOwner(host);
296+
const clearConfirmationGrace = () => outboxOwner.clearConfirmationGrace(outbox, item.id);
285297
const historyArgs = [host, outbox, item, client, connectionEpoch, dependencies] as const;
286298
const history = await readCurrentStoredChatHistory(...historyArgs);
287299
// Keyed unknown sends reach history only for exact proof; absence stays blocked.
288300
if (history === "blocked" || history === "continue" || item.sendState === "unconfirmed") {
301+
clearConfirmationGrace();
289302
return history === "continue" ? "continue" : "blocked";
290303
}
291304
if (visibleSessionMatches(host, outbox.sessionKey, outbox.agentId) && isChatBusy(host)) {
305+
clearConfirmationGrace();
292306
return "blocked";
293307
}
294308
if ((item.sendAttempts ?? 0) > 0) {
295309
// History and run metadata are non-atomic; verify idle before parking unknown.
296310
const verifiedHistory = await readCurrentStoredChatHistory(...historyArgs);
297311
if (verifiedHistory === "blocked" || verifiedHistory === "continue") {
312+
clearConfirmationGrace();
298313
return verifiedHistory;
299314
}
315+
const liveSendCurrent = anyChatOutboxPaneMatches(host, (pane) => {
316+
const liveItem = pane.chatQueue.find((entry) => entry.id === item.id);
317+
return (
318+
liveItem?.sendState === "sending" &&
319+
sameQueuedDeliveryVersion(liveItem, { ...item, sendState: "sending" })
320+
);
321+
});
322+
if (liveSendCurrent) {
323+
// Start the bound only after idle is verified; a valid run can outlive the send request.
324+
const now = Date.now();
325+
const deadlineMs = outboxOwner.confirmationDeadline(
326+
outbox,
327+
item.id,
328+
queuedDeliveryVersion(item),
329+
now,
330+
STORED_OUTBOX_CONFIRMATION_GRACE_MS,
331+
);
332+
if (deadlineMs !== null && now < deadlineMs) {
333+
scheduleStoredChatOutboxRetry(
334+
host,
335+
outbox,
336+
Math.min(STORED_OUTBOX_RETRY_DEFAULT_MS, deadlineMs - now),
337+
dependencies,
338+
);
339+
return "blocked";
340+
}
341+
}
342+
clearConfirmationGrace();
300343
const parked = updateQueuedMessageForSession(host, outbox.sessionKey, item.id, (entry) => ({
301344
...entry,
302345
sendError: UNCONFIRMED_CHAT_SEND_ERROR,

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

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,11 @@ type HostProjection = {
1515
durableSeen: Set<string>;
1616
retryable: Set<string>;
1717
};
18-
type LiveProjection = { item: ChatQueueItem; owner: Host };
18+
type LiveProjection = {
19+
confirmationGrace?: { deadlineMs: number; deliveryVersion: string };
20+
item: ChatQueueItem;
21+
owner: Host;
22+
};
1923
const LIVE_VERSION_KEYS = ["sendRunId", "sendAttempts", "sendState", "sendError"] as const;
2024
const routePresentation = new WeakSet<ChatQueueItem>();
2125
const storageIds = new WeakMap<Storage, number>();
@@ -233,6 +237,30 @@ class ChatOutboxGatewayOwner {
233237
hasVolatile(host: Host, id: string): boolean {
234238
return this.hosts.get(host)?.retryable.has(id) ?? false;
235239
}
240+
confirmationDeadline(
241+
scope: Scope,
242+
itemId: string,
243+
deliveryVersion: string,
244+
now: number,
245+
graceMs: number,
246+
): number | null {
247+
const live = this.live.get(storedChatOutboxScopeKey(scope))?.get(itemId);
248+
if (!live) {
249+
return null;
250+
}
251+
if (live.confirmationGrace?.deliveryVersion === deliveryVersion) {
252+
return live.confirmationGrace.deadlineMs;
253+
}
254+
const deadlineMs = now + graceMs;
255+
live.confirmationGrace = { deadlineMs, deliveryVersion };
256+
return deadlineMs;
257+
}
258+
clearConfirmationGrace(scope: Scope, itemId: string): void {
259+
const live = this.live.get(storedChatOutboxScopeKey(scope))?.get(itemId);
260+
if (live) {
261+
delete live.confirmationGrace;
262+
}
263+
}
236264
// Panes share this outbox and its drain while composer state stays per pane, so
237265
// a pane-local fact that blocks delivery has to be answerable from any of them.
238266
anyPane(matches: (host: Host) => boolean): boolean {
@@ -257,7 +285,7 @@ class ChatOutboxGatewayOwner {
257285
const key = storedChatOutboxScopeKey(scope);
258286
const live = this.live.get(key) ?? new Map<string, LiveProjection>();
259287
if (item) {
260-
live.set(id, { item, owner: host });
288+
live.set(id, { confirmationGrace: live.get(id)?.confirmationGrace, item, owner: host });
261289
this.live.set(key, live);
262290
} else {
263291
live.delete(id);

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

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import { refreshChatAvatar } from "./chat-avatar.ts";
3232
import * as chatCommandExecutor from "./chat-command-executor.ts";
3333
import type { executeSlashCommand } from "./chat-command-executor.ts";
3434
import { makeChatHost, makeRequestMock } from "./chat-host.test-support.ts";
35+
import { UNCONFIRMED_CHAT_SEND_ERROR } from "./chat-outbox-drain.ts";
3536
import { renderChatPaneComposerControls } from "./chat-pane-session-controls.ts";
3637
import type { ChatHost } from "./chat-send-contract.ts";
3738
import {
@@ -149,6 +150,7 @@ let loadChatHistory: typeof import("./chat-history.ts").loadChatHistory;
149150
let clearPendingQueueItemsForRun: typeof import("./chat-queue.ts").clearPendingQueueItemsForRun;
150151
let admitQueuedMessageForSession: typeof import("./chat-queue.ts").admitQueuedMessageForSession;
151152
let removeQueuedMessage: typeof import("./chat-queue.ts").removeQueuedMessage;
153+
let setTransientQueuedMessageProjection: typeof import("./chat-queue.ts").setTransientQueuedMessageProjection;
152154
let removeDeliveredQueuedChatSendForRun: typeof import("./chat-queue.ts").removeDeliveredQueuedChatSendForRun;
153155
let removeVisibleOrScopedQueuedMessageWithoutReleasing: typeof import("./chat-queue.ts").removeVisibleOrScopedQueuedMessageWithoutReleasing;
154156
let markQueuedChatSendsWaitingForReconnect: typeof import("./chat-queue.ts").markQueuedChatSendsWaitingForReconnect;
@@ -182,6 +184,7 @@ async function loadChatHelpers(): Promise<void> {
182184
clearPendingQueueItemsForRun,
183185
removeDeliveredQueuedChatSendForRun,
184186
removeQueuedMessage,
187+
setTransientQueuedMessageProjection,
185188
markQueuedChatSendsWaitingForReconnect,
186189
removeVisibleOrScopedQueuedMessageWithoutReleasing,
187190
readChatQueueForScope,
@@ -5604,6 +5607,120 @@ describe("handleSendChat", () => {
56045607
expect(host.chatMessages).toStrictEqual([]);
56055608
});
56065609

5610+
it("keeps an acknowledged live send pending while durable history is briefly stale", async () => {
5611+
let historyRequests = 0;
5612+
let runId: string | undefined;
5613+
const host = makeChatHost({
5614+
requestHandlers: {
5615+
"chat.history": () => {
5616+
historyRequests += 1;
5617+
return Promise.resolve({
5618+
messages:
5619+
historyRequests > 2
5620+
? [{ role: "user", __openclaw: { idempotencyKey: `${runId}:user` } }]
5621+
: [],
5622+
sessionInfo: row("agent:main", { hasActiveRun: false, status: "done" }),
5623+
});
5624+
},
5625+
"chat.send": (params: unknown) => {
5626+
const payload = requireRecord(params, "live send payload");
5627+
runId = String(payload.idempotencyKey);
5628+
return Promise.resolve({ runId, status: "started" });
5629+
},
5630+
},
5631+
});
5632+
5633+
await handleSendChat(host, "history will catch up");
5634+
expect(host.chatQueue).toEqual([
5635+
expect.objectContaining({ sendState: "sending", text: "history will catch up" }),
5636+
]);
5637+
expect(loadChatComposerSnapshot(host, host.sessionKey)?.queue).toEqual([
5638+
expect.objectContaining({ sendAttempts: 1, sendState: "waiting-reconnect" }),
5639+
]);
5640+
5641+
host.chatRunId = null;
5642+
await flushChatQueueForEvent(host);
5643+
5644+
expect(host.chatQueue[0]?.sendState).toBe("sending");
5645+
expect(host.lastError).toBeNull();
5646+
await waitForFast(() => expect(listStoredChatOutboxes(host)).toStrictEqual([]), {
5647+
timeout: 1_000,
5648+
});
5649+
expect(historyRequests).toBeGreaterThanOrEqual(3);
5650+
expect(host.chatQueue).toStrictEqual([]);
5651+
expect(host.lastError).toBeNull();
5652+
});
5653+
5654+
it("marks an acknowledged live send unconfirmed after history stays missing", async () => {
5655+
let now = 1_000;
5656+
vi.spyOn(Date, "now").mockImplementation(() => now);
5657+
const host = makeChatHost({
5658+
requestHandlers: {
5659+
"chat.history": () => idleChatHistory(),
5660+
"chat.send": (params: unknown) => {
5661+
const payload = requireRecord(params, "live send payload");
5662+
const runId = String(payload.idempotencyKey);
5663+
return Promise.resolve({ runId, status: "started" });
5664+
},
5665+
},
5666+
});
5667+
5668+
await handleSendChat(host, "history never catches up");
5669+
host.chatRunId = null;
5670+
await flushChatQueueForEvent(host);
5671+
5672+
expect(host.chatQueue[0]?.sendState).toBe("sending");
5673+
expect(host.lastError).toBeNull();
5674+
5675+
now += 5_001;
5676+
await flushChatQueueForEvent(host);
5677+
5678+
expect(host.chatQueue[0]).toMatchObject({
5679+
sendError: UNCONFIRMED_CHAT_SEND_ERROR,
5680+
sendState: "unconfirmed",
5681+
text: "history never catches up",
5682+
});
5683+
expect(host.lastError).toBe(UNCONFIRMED_CHAT_SEND_ERROR);
5684+
});
5685+
5686+
it("starts a fresh confirmation grace after the prior outbox scope is removed", async () => {
5687+
let now = 1_000;
5688+
vi.spyOn(Date, "now").mockImplementation(() => now);
5689+
const host = makeChatHost({
5690+
requestHandlers: {
5691+
"chat.history": () => idleChatHistory(),
5692+
"chat.send": (params: unknown) => {
5693+
const payload = requireRecord(params, "live send payload");
5694+
const runId = String(payload.idempotencyKey);
5695+
return Promise.resolve({ runId, status: "started" });
5696+
},
5697+
},
5698+
});
5699+
5700+
await handleSendChat(host, "reuse this delivery version");
5701+
host.chatRunId = null;
5702+
await flushChatQueueForEvent(host);
5703+
5704+
const item = expectDefined(host.chatQueue[0], "queued live send");
5705+
const sessionKey = expectDefined(item.sessionKey, "queued session key");
5706+
expect(removeQueuedMessage(host, item.id)).toBe("removed");
5707+
5708+
now = 5_500;
5709+
expect(admitQueuedMessageForSession(host, sessionKey, item)).toBe(true);
5710+
expect(setTransientQueuedMessageProjection(host, sessionKey, item)).toBe(true);
5711+
await flushChatQueueForEvent(host);
5712+
5713+
now = 6_001;
5714+
await flushChatQueueForEvent(host);
5715+
5716+
expect(host.chatQueue[0]).toMatchObject({
5717+
id: item.id,
5718+
sendState: "sending",
5719+
text: "reuse this delivery version",
5720+
});
5721+
expect(host.lastError).toBeNull();
5722+
});
5723+
56075724
it("coalesces duplicate queued local commands while the first command is running", async () => {
56085725
const command = createDeferred<{ content: string }>();
56095726
executeSlashCommandMock.mockImplementation(() => command.promise);

0 commit comments

Comments
 (0)