π OpenHands: AI-Driven Development
fix: preserve newer failed messages when history reloads (#17647)
Alonae5a05c390e39
diff --git a/__tests__/components/chat/chat-interface.test.tsx b/__tests__/components/chat/chat-interface.test.tsxindex 4cd159a818..9c65d743c6 100644--- a/__tests__/components/chat/chat-interface.test.tsx+++ b/__tests__/components/chat/chat-interface.test.tsx@@ -182,9 +182,7 @@ describe("ChatInterface - Chat Suggestions", () => {},});- useOptimisticUserMessageStore.setState({- pendingMessages: [],- });+ useOptimisticUserMessageStore.getState().clearPendingMessages();useErrorMessageStore.setState({errorMessage: null,@@ -313,7 +311,7 @@ describe("ChatInterface - Scroll-up loads older events", () => {defaultOptions: { queries: { retry: false } },});- useOptimisticUserMessageStore.setState({ pendingMessages: [] });+ useOptimisticUserMessageStore.getState().clearPendingMessages();useErrorMessageStore.setState({ errorMessage: null });(useConfig as unknown as ReturnType<typeof vi.fn>).mockReturnValue({@@ -677,7 +675,7 @@ describe("ChatInterface - Pending message queue", () => {queryClient = new QueryClient({defaultOptions: { queries: { retry: false } },});- useOptimisticUserMessageStore.setState({ pendingMessages: [] });+ useOptimisticUserMessageStore.getState().clearPendingMessages();useErrorMessageStore.setState({ errorMessage: null });(useConfig as unknown as ReturnType<typeof vi.fn>).mockReturnValue({data: {},@@ -698,7 +696,7 @@ describe("ChatInterface - Pending message queue", () => {});afterEach(() => {- useOptimisticUserMessageStore.setState({ pendingMessages: [] });+ useOptimisticUserMessageStore.getState().clearPendingMessages();});function submitMessage(text: string) {@@ -785,7 +783,7 @@ describe("ChatInterface - Auto-scroll on submit (issue #817)", () => {queryClient = new QueryClient({defaultOptions: { queries: { retry: false } },});- useOptimisticUserMessageStore.setState({ pendingMessages: [] });+ useOptimisticUserMessageStore.getState().clearPendingMessages();useErrorMessageStore.setState({ errorMessage: null });(useConfig as unknown as ReturnType<typeof vi.fn>).mockReturnValue({data: {},@@ -806,7 +804,7 @@ describe("ChatInterface - Auto-scroll on submit (issue #817)", () => {});afterEach(() => {- useOptimisticUserMessageStore.setState({ pendingMessages: [] });+ useOptimisticUserMessageStore.getState().clearPendingMessages();});it("scrolls to bottom when a new prompt is submitted while the user is scrolled up", async () => {@@ -1031,7 +1029,7 @@ describe("ChatInterface - Tracking", () => {queryClient = new QueryClient({defaultOptions: { queries: { retry: false } },});- useOptimisticUserMessageStore.setState({ pendingMessages: [] });+ useOptimisticUserMessageStore.getState().clearPendingMessages();useErrorMessageStore.setState({ errorMessage: null });(useConfig as unknown as ReturnType<typeof vi.fn>).mockReturnValue({data: {},@@ -1120,7 +1118,7 @@ describe("ChatInterface - Build plan keyboard shortcut", () => {queryClient = new QueryClient({defaultOptions: { queries: { retry: false } },});- useOptimisticUserMessageStore.setState({ pendingMessages: [] });+ useOptimisticUserMessageStore.getState().clearPendingMessages();useErrorMessageStore.setState({ errorMessage: null });(useConfig as unknown as ReturnType<typeof vi.fn>).mockReturnValue({data: {},diff --git a/__tests__/components/chat/message-display-continuity.test.tsx b/__tests__/components/chat/message-display-continuity.test.tsxindex 44f1e0ec16..09f00f4684 100644--- a/__tests__/components/chat/message-display-continuity.test.tsx+++ b/__tests__/components/chat/message-display-continuity.test.tsx@@ -113,7 +113,7 @@ describe("ChatInterface β message display continuity (spec 3.1)", () => {conversationId: "test-conversation-id",});- useOptimisticUserMessageStore.setState({ pendingMessages: [] });+ useOptimisticUserMessageStore.getState().clearPendingMessages();(useConfig as unknown as ReturnType<typeof vi.fn>).mockReturnValue({data: { app_mode: "local" },diff --git a/__tests__/components/features/chat/pending-user-messages.test.tsx b/__tests__/components/features/chat/pending-user-messages.test.tsxindex 8017e7d816..8152bc0500 100644--- a/__tests__/components/features/chat/pending-user-messages.test.tsx+++ b/__tests__/components/features/chat/pending-user-messages.test.tsx@@ -22,7 +22,7 @@ vi.mock("#/hooks/use-conversation-id", () => ({describe("PendingUserMessages", () => {beforeEach(() => {mockSend.mockReset();- useOptimisticUserMessageStore.setState({ pendingMessages: [] });+ useOptimisticUserMessageStore.getState().clearPendingMessages();useConversationStore.setState({messageRestoreIfEmpty: null,messageToSend: null,@@ -30,7 +30,7 @@ describe("PendingUserMessages", () => {});afterEach(() => {- useOptimisticUserMessageStore.setState({ pendingMessages: [] });+ useOptimisticUserMessageStore.getState().clearPendingMessages();});it("renders nothing when the queue is empty", () => {diff --git a/__tests__/components/features/chat/plan-preview.test.tsx b/__tests__/components/features/chat/plan-preview.test.tsxindex c48a09c48d..4f4ecb49e2 100644--- a/__tests__/components/features/chat/plan-preview.test.tsx+++ b/__tests__/components/features/chat/plan-preview.test.tsx@@ -65,9 +65,7 @@ describe("PlanPreview", () => {mockSend.mockResolvedValue({ queued: false });// Reset store stateslocalStorage.clear();- useOptimisticUserMessageStore.setState({- pendingMessages: [],- });+ useOptimisticUserMessageStore.getState().clearPendingMessages();useConversationStore.setState({conversationMode: "plan",selectedTab: null,@@ -82,9 +80,7 @@ describe("PlanPreview", () => {useConversationStore.setState({conversationMode: "code",});- useOptimisticUserMessageStore.setState({- pendingMessages: [],- });+ useOptimisticUserMessageStore.getState().clearPendingMessages();localStorage.clear();});@@ -197,7 +193,7 @@ describe("PlanPreview", () => {it("should enqueue a pending user message when Build button is clicked", async () => {// Arrange- useOptimisticUserMessageStore.setState({ pendingMessages: [] });+ useOptimisticUserMessageStore.getState().clearPendingMessages();const user = userEvent.setup();const expectedPrompt ="Execute the plan based on the .agents_tmp/PLAN.md file.";diff --git a/__tests__/contexts/conversation-websocket-context.test.tsx b/__tests__/contexts/conversation-websocket-context.test.tsxindex 071cf15cbd..dac1c71bc4 100644--- a/__tests__/contexts/conversation-websocket-context.test.tsx+++ b/__tests__/contexts/conversation-websocket-context.test.tsx@@ -150,7 +150,7 @@ describe("ConversationWebSocketProvider β conversation-scoped event store", ()uiEvents: [],loadedConversationId: null,});- useOptimisticUserMessageStore.setState({ pendingMessages: [] });+ useOptimisticUserMessageStore.getState().clearPendingMessages();useBrowserStore.getState().reset();useMetricsStore.getState().resetMetrics();useCommandStore.setState({ commands: [] });diff --git a/__tests__/contexts/conversation-websocket-provider.behavior.test.tsx b/__tests__/contexts/conversation-websocket-provider.behavior.test.tsxindex dc8c0594cc..c88b10333e 100644--- a/__tests__/contexts/conversation-websocket-provider.behavior.test.tsx+++ b/__tests__/contexts/conversation-websocket-provider.behavior.test.tsx@@ -337,7 +337,7 @@ describe("Conversation websocket behavior", () => {loadedConversationId: null,});useErrorMessageStore.getState().removeErrorMessage();- useOptimisticUserMessageStore.setState({ pendingMessages: [] });+ useOptimisticUserMessageStore.getState().clearPendingMessages();useConversationStateStore.getState().reset();useConversationStore.setState({conversationMode: "code",@@ -363,6 +363,26 @@ describe("Conversation websocket behavior", () => {window.localStorage.clear();});+ it("retains a newer failed identical prompt when old history reloads", () => {+ const oldDeliveredMessage = makeMessageEvent("01", "user", ["continue"]);+ useEventStore.getState().clearEventsForConversation("conv-main");+ useEventStore.getState().addEvent(oldDeliveredMessage);+ const store = useOptimisticUserMessageStore.getState();+ const failedId = store.enqueuePendingMessage({+ conversationId: "conv-main",+ text: "continue",+ timestamp: "2026-09-23T12:00:00.000Z",+ });+ store.markPendingMessageError(failedId, "Request rejected before delivery");+ historyCapture.result.data = { events: [oldDeliveredMessage] };++ renderProvider();++ expect(useOptimisticUserMessageStore.getState().pendingMessages).toEqual([+ expect.objectContaining({ id: failedId, status: "error" }),+ ]);+ });+it("returns no websocket API outside the provider", () => {render(<ContextProbe />);@@ -414,6 +434,10 @@ describe("Conversation websocket behavior", () => {expect(consumeMatchingPendingMessage).toHaveBeenCalledWith("conv-main","hello world",+ expect.objectContaining({+ id: expect.any(String),+ timestamp: expect.any(String),+ }),);expect(socketCapture.mainUrl).toContain("/sockets/events/conv-main");// The session key is now passed via the dedicated `sessionApiKey` option@@ -1091,6 +1115,10 @@ describe("Conversation websocket behavior", () => {expect(consumeMatchingPendingMessage).toHaveBeenCalledWith("conv-main","hello world",+ expect.objectContaining({+ id: expect.any(String),+ timestamp: expect.any(String),+ }),);expect(getConversationState("conv-main").draftMessage).toBeNull();@@ -1988,6 +2016,10 @@ describe("Conversation websocket behavior", () => {expect(consumeMatchingPendingMessage).toHaveBeenCalledWith("conv-main","plan this",+ expect.objectContaining({+ id: expect.any(String),+ timestamp: expect.any(String),+ }),);expect(getConversationState("conv-main").draftMessage).toBeNull();diff --git a/__tests__/hooks/query/use-task-polling.test.tsx b/__tests__/hooks/query/use-task-polling.test.tsxindex 1e4a1aa4b0..50a69c78a6 100644--- a/__tests__/hooks/query/use-task-polling.test.tsx+++ b/__tests__/hooks/query/use-task-polling.test.tsx@@ -74,7 +74,7 @@ describe("useTaskPolling", () => {vi.clearAllMocks();localStorage.clear();resetPendingTaskMessageLinkState();- useOptimisticUserMessageStore.setState({ pendingMessages: [] });+ useOptimisticUserMessageStore.getState().clearPendingMessages();});afterEach(() => {diff --git a/__tests__/hooks/use-handle-build-plan-click.test.ts b/__tests__/hooks/use-handle-build-plan-click.test.tsindex 57e49187d3..fbd23b48fb 100644--- a/__tests__/hooks/use-handle-build-plan-click.test.ts+++ b/__tests__/hooks/use-handle-build-plan-click.test.ts@@ -36,9 +36,7 @@ describe("useHandleBuildPlanClick", () => {useConversationStore.setState({conversationMode: "plan",});- useOptimisticUserMessageStore.setState({- pendingMessages: [],- });+ useOptimisticUserMessageStore.getState().clearPendingMessages();// Setup send message hook mock(useSendMessage as unknown as ReturnType<typeof vi.fn>).mockReturnValue({@@ -62,9 +60,7 @@ describe("useHandleBuildPlanClick", () => {useConversationStore.setState({conversationMode: "code",});- useOptimisticUserMessageStore.setState({- pendingMessages: [],- });+ useOptimisticUserMessageStore.getState().clearPendingMessages();});it("should switch conversation mode to code when handleBuildPlanClick is called", () => {@@ -113,7 +109,7 @@ describe("useHandleBuildPlanClick", () => {it("should enqueue a pending user message when handleBuildPlanClick is called", () => {// Arrange- useOptimisticUserMessageStore.setState({ pendingMessages: [] });+ useOptimisticUserMessageStore.getState().clearPendingMessages();const { result } = renderHook(() => useHandleBuildPlanClick());const expectedPrompt ="Execute the plan based on the .agents_tmp/PLAN.md file.";@@ -124,8 +120,7 @@ describe("useHandleBuildPlanClick", () => {});// Assert- const pending =- useOptimisticUserMessageStore.getState().pendingMessages;+ const pending = useOptimisticUserMessageStore.getState().pendingMessages;expect(pending).toHaveLength(1);expect(pending[0].text).toBe(expectedPrompt);expect(pending[0].status).toBe("sending");@@ -152,7 +147,7 @@ describe("useHandleBuildPlanClick", () => {it("should handle call without event parameter", () => {// ArrangeuseConversationStore.setState({ conversationMode: "plan" });- useOptimisticUserMessageStore.setState({ pendingMessages: [] });+ useOptimisticUserMessageStore.getState().clearPendingMessages();const { result } = renderHook(() => useHandleBuildPlanClick());// Act & Assert - should not throw@@ -163,8 +158,7 @@ describe("useHandleBuildPlanClick", () => {// Assert all expected behaviors still occurexpect(useConversationStore.getState().conversationMode).toBe("code");expect(mockSend).toHaveBeenCalledTimes(1);- const pending =- useOptimisticUserMessageStore.getState().pendingMessages;+ const pending = useOptimisticUserMessageStore.getState().pendingMessages;expect(pending).toHaveLength(1);expect(pending[0].text).toBe("Execute the plan based on the .agents_tmp/PLAN.md file.",diff --git a/__tests__/stores/optimistic-user-message-store.test.ts b/__tests__/stores/optimistic-user-message-store.test.tsindex 710d4d1280..5a872de60e 100644--- a/__tests__/stores/optimistic-user-message-store.test.ts+++ b/__tests__/stores/optimistic-user-message-store.test.ts@@ -3,13 +3,35 @@ import {PENDING_MESSAGE_TIMEOUT_MS,useOptimisticUserMessageStore,} from "#/stores/optimistic-user-message-store";+import {+ linkPendingTaskMessages,+ resetPendingTaskMessageLinkState,+} from "#/utils/pending-task-message-link";++import { useEventStore } from "#/stores/use-event-store";const CONVO = "conv-a";+function addServerMessage(id: string, timestamp: string) {+ useEventStore.getState().addEvent({+ id,+ timestamp,+ source: "user",+ llm_message: {+ role: "user",+ content: [{ type: "text", text: "continue" }],+ },+ activated_skills: [],+ extended_content: [],+ });+}+describe("optimistic-user-message-store", () => {beforeEach(() => {vi.useFakeTimers();- useOptimisticUserMessageStore.setState({ pendingMessages: [] });+ useOptimisticUserMessageStore.getState().clearPendingMessages();+ resetPendingTaskMessageLinkState();+ useEventStore.getState().clearEventsForConversation(CONVO);});afterEach(() => {@@ -116,7 +138,10 @@ describe("optimistic-user-message-store", () => {// Echo for "second" arrives before "first" β must pop "second", not the// oldest entry. This is the case the previous FIFO-only implementation// got wrong.- const consumed = store.consumeMatchingPendingMessage(CONVO, "second");+ const consumed = store.consumeMatchingPendingMessage(CONVO, "second", {+ id: "confirmation",+ timestamp: new Date().toISOString(),+ });expect(consumed?.id).toBe(secondId);const remaining = useOptimisticUserMessageStore.getState().pendingMessages;@@ -124,7 +149,7 @@ describe("optimistic-user-message-store", () => {expect(remaining[0].id).toBe(firstId);});- it("consumeMatchingPendingMessage falls back to oldest sending entry when no exact match exists", () => {+ it("consumeMatchingPendingMessage matches trimmed content without consuming unrelated sending entries", () => {const store = useOptimisticUserMessageStore.getState();const firstId = store.enqueuePendingMessage({conversationId: CONVO,@@ -132,12 +157,10 @@ describe("optimistic-user-message-store", () => {});store.enqueuePendingMessage({ conversationId: CONVO, text: "world" });- // Server munged the echo (e.g., trimmed whitespace). FIFO fallback keeps- // the bubble from getting stuck.- const consumed = store.consumeMatchingPendingMessage(- CONVO,- "something else",- );+ const consumed = store.consumeMatchingPendingMessage(CONVO, " hello ", {+ id: "confirmation",+ timestamp: new Date().toISOString(),+ });expect(consumed?.id).toBe(firstId);expect(@@ -157,7 +180,10 @@ describe("optimistic-user-message-store", () => {});store.markPendingMessageError(firstId, "boom");- const consumed = store.consumeMatchingPendingMessage(CONVO, "second");+ const consumed = store.consumeMatchingPendingMessage(CONVO, "second", {+ id: "confirmation",+ timestamp: new Date().toISOString(),+ });expect(consumed?.id).toBe(secondId);const remaining = useOptimisticUserMessageStore.getState().pendingMessages;@@ -174,7 +200,10 @@ describe("optimistic-user-message-store", () => {});store.markPendingMessageError(id, "boom");- const consumed = store.consumeMatchingPendingMessage(CONVO, "unrelated");+ const consumed = store.consumeMatchingPendingMessage(CONVO, "unrelated", {+ id: "confirmation",+ timestamp: new Date().toISOString(),+ });expect(consumed).toBeNull();expect(@@ -194,7 +223,10 @@ describe("optimistic-user-message-store", () => {useOptimisticUserMessageStore.getState().pendingMessages[0].status,).toBe("error");- const consumed = store.consumeMatchingPendingMessage(CONVO, "late echo");+ const consumed = store.consumeMatchingPendingMessage(CONVO, "late echo", {+ id: "confirmation",+ timestamp: new Date().toISOString(),+ });expect(consumed?.id).toBe(id);expect(@@ -202,6 +234,151 @@ describe("optimistic-user-message-store", () => {).toHaveLength(0);});+ it.each(["sending", "error"] as const)(+ "keeps a newer %s message when identical old history arrives",+ (status) => {+ const store = useOptimisticUserMessageStore.getState();+ const oldTimestamp = new Date(Date.now() - 1000).toISOString();+ addServerMessage("old", oldTimestamp);+ const id = store.enqueuePendingMessage({+ conversationId: CONVO,+ text: "continue",+ });+ if (status === "error") store.markPendingMessageError(id, "Rejected");++ store.consumeMatchingPendingMessage(CONVO, "continue", {+ id: "old",+ timestamp: oldTimestamp,+ });++ expect(useOptimisticUserMessageStore.getState().pendingMessages).toEqual([+ expect.objectContaining({ id, status }),+ ]);+ },+ );++ it.each([-60_000, 60_000])(+ "uses server history when the browser clock differs by %d ms",+ (clockOffset) => {+ const serverTime = Date.parse("2026-09-24T12:00:00Z");+ vi.setSystemTime(serverTime + clockOffset);+ addServerMessage("old", new Date(serverTime - 1000).toISOString());+ const store = useOptimisticUserMessageStore.getState();+ const id = store.enqueuePendingMessage({+ conversationId: CONVO,+ text: "continue",+ });++ expect(+ store.consumeMatchingPendingMessage(CONVO, "continue", {+ id: "old",+ timestamp: new Date(serverTime - 1000).toISOString(),+ }),+ ).toBeNull();+ expect(+ store.consumeMatchingPendingMessage(CONVO, "continue", {+ id: "new",+ timestamp: new Date(serverTime).toISOString(),+ })?.id,+ ).toBe(id);+ },+ );++ it("confirms the sending attempt before an older identical failed attempt", () => {+ const store = useOptimisticUserMessageStore.getState();+ const failed = store.enqueuePendingMessage({+ conversationId: CONVO,+ text: "continue",+ });+ store.markPendingMessageError(failed, "Rejected");+ const sending = store.enqueuePendingMessage({+ conversationId: CONVO,+ text: "continue",+ });++ const confirmed = store.consumeMatchingPendingMessage(CONVO, "continue", {+ id: "accepted",+ timestamp: new Date().toISOString(),+ });++ expect(confirmed?.id).toBe(sending);+ expect(useOptimisticUserMessageStore.getState().pendingMessages).toEqual([+ expect.objectContaining({ id: failed, status: "error" }),+ ]);+ });++ it("refreshes the server history boundary when retrying a failed attempt", () => {+ const store = useOptimisticUserMessageStore.getState();+ const id = store.enqueuePendingMessage({+ conversationId: CONVO,+ text: "continue",+ });+ store.markPendingMessageError(id, "Rejected");+ const oldTimestamp = new Date().toISOString();+ addServerMessage("other-attempt", oldTimestamp);++ store.markPendingMessageSending(id);++ expect(+ store.consumeMatchingPendingMessage(CONVO, "continue", {+ id: "other-attempt",+ timestamp: oldTimestamp,+ }),+ ).toBeNull();+ expect(+ store.consumeMatchingPendingMessage(CONVO, "continue", {+ id: "retry-accepted",+ timestamp: new Date(Date.now() + 1000).toISOString(),+ })?.id,+ ).toBe(id);+ });++ it("does not confirm two identical attempts with a replayed event", () => {+ const store = useOptimisticUserMessageStore.getState();+ store.enqueuePendingMessage({ conversationId: CONVO, text: "continue" });+ const failed = store.enqueuePendingMessage({+ conversationId: CONVO,+ text: "continue",+ });+ store.markPendingMessageError(failed, "Rejected");+ const event = { id: "accepted", timestamp: new Date().toISOString() };++ store.consumeMatchingPendingMessage(CONVO, "continue", event);+ store.consumeMatchingPendingMessage(CONVO, "continue", event);++ expect(useOptimisticUserMessageStore.getState().pendingMessages).toEqual([+ expect.objectContaining({ id: failed, status: "error" }),+ ]);+ });++ it("retains a sending message for an unrelated newer confirmation", () => {+ const store = useOptimisticUserMessageStore.getState();+ const id = store.enqueuePendingMessage({+ conversationId: CONVO,+ text: "continue",+ });+ store.consumeMatchingPendingMessage(CONVO, "different message", {+ id: "other",+ timestamp: new Date().toISOString(),+ });+ expect(useOptimisticUserMessageStore.getState().pendingMessages[0].id).toBe(+ id,+ );+ });++ it("confirms a task's first message before the pending route reassignment", () => {+ const store = useOptimisticUserMessageStore.getState();+ store.enqueuePendingMessage({ conversationId: "task-123", text: "hello" });+ linkPendingTaskMessages(CONVO, "task-123");+ store.consumeMatchingPendingMessage(CONVO, "hello", {+ id: "first",+ timestamp: new Date().toISOString().replace("Z", ""),+ });+ expect(useOptimisticUserMessageStore.getState().pendingMessages).toEqual(+ [],+ );+ });+it("consumeMatchingPendingMessage only consumes entries for the given conversation", () => {const store = useOptimisticUserMessageStore.getState();const aId = store.enqueuePendingMessage({@@ -215,7 +392,10 @@ describe("optimistic-user-message-store", () => {// A cross-conversation ack for conv-b β even with identical content,// must not pop conv-a's pending entry.- const consumed = store.consumeMatchingPendingMessage("conv-b", "shared");+ const consumed = store.consumeMatchingPendingMessage("conv-b", "shared", {+ id: "confirmation",+ timestamp: new Date().toISOString(),+ });expect(consumed?.id).toBe(bId);const remaining = useOptimisticUserMessageStore.getState().pendingMessages;@@ -248,7 +428,10 @@ describe("optimistic-user-message-store", () => {const store = useOptimisticUserMessageStore.getState();store.enqueuePendingMessage({ conversationId: CONVO, text: "fast" });- store.consumeMatchingPendingMessage(CONVO, "fast");+ store.consumeMatchingPendingMessage(CONVO, "fast", {+ id: "confirmation",+ timestamp: new Date().toISOString(),+ });vi.advanceTimersByTime(PENDING_MESSAGE_TIMEOUT_MS);expect(diff --git a/src/contexts/conversation-websocket-context.tsx b/src/contexts/conversation-websocket-context.tsxindex 32cd815627..c1057b09bd 100644--- a/src/contexts/conversation-websocket-context.tsx+++ b/src/contexts/conversation-websocket-context.tsx@@ -348,6 +348,7 @@ export function ConversationWebSocketProvider({consumeMatchingPendingMessage(conversationId,extractMessageEventText(event),+ event,);}}@@ -621,15 +622,13 @@ export function ConversationWebSocketProvider({}// Clear optimistic user message when a user message is confirmed.- // We match by the echoed text content (with FIFO fallback inside the- // store), so an echo for "second" pops "second" β not whichever- // pending entry happens to be oldest β protecting against any- // out-of-order delivery between conversations or sub-agents.+ // History and live delivery share the same timestamp/identity checks.if (isUserMessageEvent(event)) {if (conversationId) {consumeMatchingPendingMessage(conversationId,extractMessageEventText(event),+ event,);// Clear draft from localStorage - message was successfully deliveredsetConversationState(conversationId, { draftMessage: null });@@ -863,6 +862,7 @@ export function ConversationWebSocketProvider({consumeMatchingPendingMessage(conversationId,extractMessageEventText(event),+ event,);setConversationState(conversationId, { draftMessage: null });}diff --git a/src/stores/optimistic-user-message-store.ts b/src/stores/optimistic-user-message-store.tsindex 9cb49ab6bf..6e6116ef38 100644--- a/src/stores/optimistic-user-message-store.ts+++ b/src/stores/optimistic-user-message-store.ts@@ -1,4 +1,8 @@import { create } from "zustand";+import { useEventStore } from "#/stores/use-event-store";+import { parseDateAsUTC } from "#/utils/format-time-delta";+import { matchesPendingConversationId } from "#/utils/pending-task-message-link";+import type { BaseEvent } from "#/types/agent-server/core/base/event";export type PendingUserMessageStatus = "sending" | "error";@@ -33,11 +37,13 @@ export interface PendingUserMessage {imageUrls: string[];fileUrls: string[];timestamp: string;+ afterTimestamp?: number;errorMessage?: string;}interface OptimisticUserMessageState {pendingMessages: PendingUserMessage[];+ confirmedEventIds: Set<string>;}export interface EnqueuePendingMessagePayload {@@ -68,21 +74,12 @@ interface OptimisticUserMessageActions {markPendingMessageSending: (id: string) => void;/** Drop a pending message from the queue (e.g., after success/cancellation). */removePendingMessage: (id: string) => void;- /**- * Remove the pending message that matches the given echoed `content` in- * the given conversation. Matching is done by exact content equality on- * messages in either state: an echo with identical text proves the message- * was delivered, so it also clears an entry the watchdog already flipped to- * "error". If no exact match exists we fall back to removing the oldest- * "sending" entry in that conversation so that an echo with a slightly- * munged body (e.g. trailing-whitespace stripped by the server) still- * clears its bubble; the fallback never touches "error" entries. Scoping by- * `conversationId` ensures a stale ack for one conversation never pops a- * pending entry belonging to another.- */+ /** Match conversation (including task links), server history and content once per event.+ * Prefer a sending attempt; an errored attempt may still receive a late echo. */consumeMatchingPendingMessage: (conversationId: string,content: string,+ event: Pick<BaseEvent, "id" | "timestamp">,) => PendingUserMessage | null;/** Wipe all queued messages (e.g., when changing conversations). */clearPendingMessages: () => void;@@ -101,6 +98,7 @@ type OptimisticUserMessageStore = OptimisticUserMessageState &const initialState: OptimisticUserMessageState = {pendingMessages: [],+ confirmedEventIds: new Set(),};// Use a timestamp + random suffix instead of a module-level counter so ids@@ -110,6 +108,28 @@ const initialState: OptimisticUserMessageState = {const generatePendingId = (): string =>`pending-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;+const latestServerTimestamp = (conversationId: string): number | undefined => {+ const { events, loadedConversationId } = useEventStore.getState();+ if (+ !loadedConversationId ||+ !matchesPendingConversationId(loadedConversationId, conversationId)+ )+ return undefined;++ let latest: number | undefined;+ for (const event of events) {+ if (!("timestamp" in event) || !event.timestamp) continue;+ const timestamp = parseDateAsUTC(event.timestamp).getTime();+ if (+ Number.isFinite(timestamp) &&+ (latest === undefined || timestamp > latest)+ ) {+ latest = timestamp;+ }+ }+ return latest;+};+export const useOptimisticUserMessageStore = create<OptimisticUserMessageStore>((set, get) => ({...initialState,@@ -125,6 +145,7 @@ export const useOptimisticUserMessageStore = create<OptimisticUserMessageStore>(imageUrls: payload.imageUrls ?? [],fileUrls: payload.fileUrls ?? [],timestamp: payload.timestamp ?? new Date().toISOString(),+ afterTimestamp: latestServerTimestamp(payload.conversationId),};set((state) => ({pendingMessages: [...state.pendingMessages, message],@@ -156,7 +177,12 @@ export const useOptimisticUserMessageStore = create<OptimisticUserMessageStore>(set((state) => ({pendingMessages: state.pendingMessages.map((message) =>message.id === id- ? { ...message, status: "sending", errorMessage: undefined }+ ? {+ ...message,+ status: "sending",+ errorMessage: undefined,+ afterTimestamp: latestServerTimestamp(message.conversationId),+ }: message,),})),@@ -168,41 +194,42 @@ export const useOptimisticUserMessageStore = create<OptimisticUserMessageStore>(),})),- consumeMatchingPendingMessage: (conversationId, content) => {- // Single atomic `set` so the find + filter can't observe an interleaved- // mutation from another action. We prefer an exact content match (this- // is what makes out-of-order echoes safe: an echo of "world" will pop- // the "world" bubble, not the older "hello" one). The exact match may- // hit an entry already in "error" state: the watchdog flips a bubble to- // "error" on a timer, so a late echo (reconnect replay, slow server-side- // accept, returning from another conversation) proves the message was- // delivered after all and must clear the stale failure. If no exact- // match exists β e.g. the server slightly munged the body β fall back- // to the oldest "sending" entry in this conversation so the user doesn't- // end up with a permanently-stuck bubble in the happy-path- // single-message case. The fallback deliberately skips "error" entries- // so an unrelated echo can never wipe a genuinely failed bubble.+ consumeMatchingPendingMessage: (conversationId, content, event) => {let consumed: PendingUserMessage | null = null;+ const confirmationId = `${conversationId}:${event.id}`;+ const confirmedAt = parseDateAsUTC(event.timestamp).getTime();set((state) => {- const inConversation = state.pendingMessages- .map((m, i) => ({ m, i }))- .filter(({ m }) => m.conversationId === conversationId);- const exact = inConversation.find(({ m }) => m.content === content);- const target =- exact ?? inConversation.find(({ m }) => m.status === "sending");- if (!target) return state;- consumed = target.m;+ if (state.confirmedEventIds.has(confirmationId)) return state;+ // Browser clocks cannot establish ordering against server event history.+ const matches = (message: PendingUserMessage) =>+ matchesPendingConversationId(+ conversationId,+ message.conversationId,+ ) &&+ (message.afterTimestamp === undefined ||+ confirmedAt > message.afterTimestamp) &&+ message.content.trim() === content.trim();+ let target = state.pendingMessages.findIndex(+ (message) => message.status === "sending" && matches(message),+ );+ if (target === -1) target = state.pendingMessages.findIndex(matches);+ if (target === -1) return state;+ consumed = state.pendingMessages[target];return {- pendingMessages: [- ...state.pendingMessages.slice(0, target.i),- ...state.pendingMessages.slice(target.i + 1),- ],+ pendingMessages: state.pendingMessages.filter(+ (_, index) => index !== target,+ ),+ confirmedEventIds: new Set([+ ...state.confirmedEventIds,+ confirmationId,+ ]),};});return consumed;},- clearPendingMessages: () => set(() => ({ ...initialState })),+ clearPendingMessages: () =>+ set(() => ({ pendingMessages: [], confirmedEventIds: new Set() })),reassignPendingMessages: (fromConversationId, toConversationId) =>set((state) => ({diff --git a/src/utils/format-time-delta.ts b/src/utils/format-time-delta.tsindex 1501e8fa92..bf656662ae 100644--- a/src/utils/format-time-delta.ts+++ b/src/utils/format-time-delta.ts@@ -9,7 +9,7 @@* parseDateAsUTC("2025-12-01T11:53:37.273886Z"); // Already has timezone, parsed correctly* parseDateAsUTC("2025-12-01T11:53:37+00:00"); // Already has timezone, parsed correctly*/-const parseDateAsUTC = (dateString: string): Date => {+export const parseDateAsUTC = (dateString: string): Date => {// Check if the string already has a timezone indicator// Look for 'Z' (UTC), '+' (positive offset), or '-' after the time part (negative offset)const hasTimezone =diff --git a/tests/e2e/mock-llm/conversations/mock-llm-message-confirmation.spec.ts b/tests/e2e/mock-llm/conversations/mock-llm-message-confirmation.spec.tsnew file mode 100644index 0000000000..695f49016f--- /dev/null+++ b/tests/e2e/mock-llm/conversations/mock-llm-message-confirmation.spec.ts@@ -0,0 +1,114 @@+import { expect, test, type Page } from "@playwright/test";+import {+ activateTrajectory,+ BACKEND_URL,+ deleteConversation,+ ensureMockLLMProfile,+ getConversationIdFromURL,+ registerTrajectory,+ resetMockLLM,+ seedLocalStorage,+ SESSION_API_KEY,+ setChatInput,+} from "../utils/mock-llm-helpers";++const PROMPT = "Continue with the validation.";+const REPLY = "Message confirmation completed.";++async function sendMessage(page: Page) {+ await setChatInput(page, PROMPT);+ await page.getByTestId("submit-button").click();+}++async function userEventCount(page: Page, conversationId: string) {+ const response = await page.request.get(+ `${BACKEND_URL}/api/conversations/${conversationId}/events/search?limit=100`,+ { headers: { "X-Session-API-Key": SESSION_API_KEY } },+ );+ expect(response.ok()).toBe(true);+ const body = await response.json();+ return body.items.filter(+ (event: { source: string }) => event.source === "user",+ ).length;+}++test.beforeEach(async ({ page, request }) => {+ await seedLocalStorage(page);+ await ensureMockLLMProfile(page, { profileName: "message-confirmation" });+ await registerTrajectory(+ request,+ "message-confirmation",+ Array.from({ length: 8 }, () => ({+ tool_call: { name: "finish", arguments: { message: REPLY } },+ })),+ );+ await activateTrajectory(request, "message-confirmation");+ await page.goto("/");+ await sendMessage(page);+ await page.waitForURL(/\/conversations\/[^/?]+/);+ await expect(page.getByText(REPLY, { exact: true }).last()).toBeVisible();+ await expect(page.getByTestId("chat-message-sending")).toHaveCount(0);+});++test.afterEach(async ({ page, request }) => {+ const match = page.url().match(/\/conversations\/([^/?#]+)/);+ if (match) await deleteConversation(request, decodeURIComponent(match[1]));+ await resetMockLLM(request);+});++test("confirms a real server echo when the browser clock is ahead", async ({+ page,+}) => {+ const conversationId = getConversationIdFromURL(page);+ await page.clock.setFixedTime(new Date(Date.now() + 60_000));++ await sendMessage(page);++ await expect.poll(() => userEventCount(page, conversationId)).toBe(2);+ await expect(page.getByTestId("chat-message-sending")).toHaveCount(0);+ await expect(page.getByTestId("chat-message-retry")).toHaveCount(0);+});++test("preserves the failed attempt through history reload, identical send and retry", async ({+ page,+}) => {+ const conversationId = getConversationIdFromURL(page);+ await page.evaluate(() => {+ const send = WebSocket.prototype.send;+ WebSocket.prototype.send = function (data) {+ if (typeof data === "string" && JSON.parse(data)?.role === "user") {+ WebSocket.prototype.send = send;+ throw new DOMException("Controlled send failure", "NetworkError");+ }+ return send.call(this, data);+ };+ });+ await sendMessage(page);+ await expect(page.getByTestId("chat-message-retry")).toHaveCount(1);++ await page.getByRole("link", { name: "New Chat", exact: true }).click();+ await expect(page.getByTestId("home-chat-launcher")).toBeVisible();+ const history = page.waitForResponse(+ (response) =>+ response+ .url()+ .includes(`/conversations/${conversationId}/events/search`) &&+ response.ok(),+ );+ await page+ .locator(`a[href*="/conversations/${conversationId}"]`)+ .first()+ .click();+ await history;+ await expect(page.getByTestId("chat-message-retry")).toHaveCount(1);++ await sendMessage(page);+ await expect.poll(() => userEventCount(page, conversationId)).toBe(2);+ await expect(page.getByTestId("chat-message-sending")).toHaveCount(0);+ await expect(page.getByTestId("chat-message-retry")).toHaveCount(1);++ await page.getByTestId("chat-message-retry").click();+ await expect.poll(() => userEventCount(page, conversationId)).toBe(3);+ await expect(page.getByTestId("chat-message-retry")).toHaveCount(0);+ await expect(page.getByTestId("chat-message-sending")).toHaveCount(0);+});