Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix(chat): flush conversation drafts before navigation (#17968)

Long Jin1172ca0470b5
diff --git a/__tests__/hooks/use-draft-persistence.test.tsx b/__tests__/hooks/use-draft-persistence.test.tsx
index 21f9a6c24c..479c364ce6 100644
--- a/__tests__/hooks/use-draft-persistence.test.tsx
+++ b/__tests__/hooks/use-draft-persistence.test.tsx
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { renderHook, act } from "@testing-library/react";
+import { useRef } from "react";
+import { renderHook, render, fireEvent, act } from "@testing-library/react";
import {
HOME_PROMPT_DRAFT_KEY,
useDraftPersistence,
@@ -1057,11 +1058,273 @@ describe("useDraftPersistence", () => {
vi.advanceTimersByTime(500);
});
- // Assert - save should not have been called after unmount
+ // Assert - cleanup flushes once without running the debounced setter later.
+ expect(
+ conversationLocalStorage.setConversationState,
+ ).toHaveBeenCalledWith(conversationId, { draftMessage: "Draft" });
expect(mockSetDraftMessage).not.toHaveBeenCalled();
});
});
+ describe("conversation draft persistence across navigation", () => {
+ beforeEach(async () => {
+ const actual = await vi.importActual<typeof conversationLocalStorage>(
+ "#/utils/conversation-local-storage",
+ );
+ vi.mocked(
+ conversationLocalStorage.useConversationLocalStorageState,
+ ).mockImplementation(actual.useConversationLocalStorageState);
+ vi.mocked(
+ conversationLocalStorage.getConversationState,
+ ).mockImplementation(actual.getConversationState);
+ vi.mocked(
+ conversationLocalStorage.setConversationState,
+ ).mockImplementation(actual.setConversationState);
+ });
+
+ afterEach(() => {
+ vi.mocked(conversationLocalStorage.setConversationState).mockReset();
+ });
+
+ it("restores the latest input after leaving before the debounce completes", () => {
+ // Arrange
+ const conversationId = "conv-leave-early";
+ conversationLocalStorage.setConversationState(conversationId, {
+ draftMessage: "Older saved draft",
+ });
+ sessionStorage.setItem(HOME_PROMPT_DRAFT_KEY, "Home prompt");
+ const chatInputRef: { current: HTMLDivElement | null } =
+ createMockChatInputRef();
+ const { result, unmount } = renderHook(() =>
+ useDraftPersistence(conversationId, chatInputRef),
+ );
+
+ // Act: multiple inputs followed by navigation within 500ms of the last input.
+ chatInputRef.current!.textContent = "First input";
+ act(() => result.current.saveDraft());
+ act(() => vi.advanceTimersByTime(200));
+ chatInputRef.current!.textContent = " Latest input ";
+ act(() => result.current.saveDraft());
+ act(() => vi.advanceTimersByTime(100));
+ expect(
+ conversationLocalStorage.getConversationState(conversationId)
+ .draftMessage,
+ ).toBe("Older saved draft");
+ // React clears DOM refs before passive unmount cleanup runs.
+ chatInputRef.current = null;
+ unmount();
+
+ const restoredInputRef = createMockChatInputRef();
+ renderHook(() => useDraftPersistence(conversationId, restoredInputRef));
+
+ // Assert: the real store survives remount, without a stale timer overwrite.
+ expect(restoredInputRef.current.textContent).toBe("Latest input");
+ act(() => vi.advanceTimersByTime(500));
+ expect(
+ conversationLocalStorage.getConversationState(conversationId)
+ .draftMessage,
+ ).toBe("Latest input");
+ expect(sessionStorage.getItem(HOME_PROMPT_DRAFT_KEY)).toBe("Home prompt");
+ });
+
+ it("keeps pending drafts with their owning conversation when switching", () => {
+ // Arrange
+ conversationLocalStorage.setConversationState("conv-B", {
+ draftMessage: "Saved draft for B",
+ });
+ const chatInputRef = createMockChatInputRef();
+ const { result, rerender } = renderHook(
+ ({ conversationId }) =>
+ useDraftPersistence(conversationId, chatInputRef),
+ { initialProps: { conversationId: "conv-A" } },
+ );
+
+ // Act
+ chatInputRef.current.textContent = "Latest draft for A";
+ act(() => result.current.saveDraft());
+ act(() => vi.advanceTimersByTime(100));
+ rerender({ conversationId: "conv-B" });
+
+ // Assert: A is saved before the input restores B, and B is untouched.
+ expect(
+ conversationLocalStorage.getConversationState("conv-A").draftMessage,
+ ).toBe("Latest draft for A");
+ expect(chatInputRef.current.textContent).toBe("Saved draft for B");
+
+ chatInputRef.current.textContent = "Latest draft for B";
+ act(() => result.current.saveDraft());
+ act(() => vi.advanceTimersByTime(100));
+ rerender({ conversationId: "conv-A" });
+ act(() => vi.advanceTimersByTime(500));
+
+ expect(chatInputRef.current.textContent).toBe("Latest draft for A");
+ expect(
+ conversationLocalStorage.getConversationState("conv-B").draftMessage,
+ ).toBe("Latest draft for B");
+ });
+
+ it("does not revive a draft cleared after confirmed delivery", () => {
+ // Arrange
+ const conversationId = "conv-delivered";
+ conversationLocalStorage.setConversationState(conversationId, {
+ draftMessage: "Previously saved draft",
+ });
+ const chatInputRef = createMockChatInputRef();
+ const { result, unmount } = renderHook(() =>
+ useDraftPersistence(conversationId, chatInputRef),
+ );
+
+ // Act
+ chatInputRef.current.textContent = "Delivered message";
+ act(() => result.current.saveDraft());
+ act(() => vi.advanceTimersByTime(100));
+ act(() => result.current.clearDraft());
+ unmount();
+ act(() => vi.advanceTimersByTime(500));
+ const restoredInputRef = createMockChatInputRef();
+ renderHook(() => useDraftPersistence(conversationId, restoredInputRef));
+
+ // Assert
+ expect(restoredInputRef.current.textContent).toBe("");
+ expect(
+ conversationLocalStorage.getConversationState(conversationId)
+ .draftMessage,
+ ).toBeNull();
+ });
+
+ it("flushes a pending conversation draft when switching to the home page", () => {
+ // Arrange
+ sessionStorage.setItem(HOME_PROMPT_DRAFT_KEY, "Home prompt");
+ const chatInputRef = createMockChatInputRef();
+ const { result, rerender } = renderHook(
+ ({ conversationId }: { conversationId: string | undefined }) =>
+ useDraftPersistence(conversationId, chatInputRef),
+ {
+ initialProps: {
+ conversationId: "conv-to-home" as string | undefined,
+ },
+ },
+ );
+
+ // Act
+ chatInputRef.current.textContent = "Conversation draft";
+ act(() => result.current.saveDraft());
+ rerender({ conversationId: undefined });
+
+ // Assert
+ expect(
+ conversationLocalStorage.getConversationState("conv-to-home")
+ .draftMessage,
+ ).toBe("Conversation draft");
+ expect(sessionStorage.getItem(HOME_PROMPT_DRAFT_KEY)).toBe("Home prompt");
+ });
+
+ it("does not revive text cleared by submission and its delivery event", () => {
+ // Arrange
+ const conversationId = "conv-submitted";
+ const chatInputRef: { current: HTMLDivElement | null } =
+ createMockChatInputRef();
+ const { result, unmount } = renderHook(() =>
+ useDraftPersistence(conversationId, chatInputRef),
+ );
+
+ // Act: submission clears the DOM; delivery clears the store directly.
+ chatInputRef.current!.textContent = "Submitted message";
+ act(() => result.current.saveDraft());
+ act(() => vi.advanceTimersByTime(100));
+ chatInputRef.current!.textContent = "";
+ act(() =>
+ conversationLocalStorage.setConversationState(conversationId, {
+ draftMessage: null,
+ }),
+ );
+ chatInputRef.current = null;
+ unmount();
+ act(() => vi.advanceTimersByTime(500));
+ const restoredInputRef = createMockChatInputRef();
+ renderHook(() => useDraftPersistence(conversationId, restoredInputRef));
+
+ // Assert
+ expect(restoredInputRef.current.textContent).toBe("");
+ expect(
+ conversationLocalStorage.getConversationState(conversationId)
+ .draftMessage,
+ ).toBeNull();
+ });
+
+ it("persists only the latest input after the usual 500ms debounce", () => {
+ // Arrange
+ const conversationId = "conv-normal-debounce";
+ const chatInputRef = createMockChatInputRef();
+ const { result } = renderHook(() =>
+ useDraftPersistence(conversationId, chatInputRef),
+ );
+
+ // Act
+ chatInputRef.current.textContent = "First input";
+ act(() => result.current.saveDraft());
+ act(() => vi.advanceTimersByTime(200));
+ chatInputRef.current.textContent = "Latest input";
+ act(() => result.current.saveDraft());
+ act(() => vi.advanceTimersByTime(499));
+
+ // Assert
+ expect(
+ conversationLocalStorage.getConversationState(conversationId)
+ .draftMessage,
+ ).toBeNull();
+ act(() => vi.advanceTimersByTime(1));
+ expect(
+ conversationLocalStorage.getConversationState(conversationId)
+ .draftMessage,
+ ).toBe("Latest input");
+ });
+
+ it("flushes multiline input before React detaches its DOM node", () => {
+ // Arrange: the component owns both the hook and the actual React ref.
+ const conversationId = "conv-multiline-unmount";
+ function DraftInput() {
+ const inputRef = useRef<HTMLDivElement>(null);
+ const { saveDraft } = useDraftPersistence(conversationId, inputRef);
+ return (
+ <div
+ ref={inputRef}
+ contentEditable
+ onInput={saveDraft}
+ data-testid="draft-input"
+ />
+ );
+ }
+ const { getByTestId, unmount } = render(<DraftInput />);
+ const input = getByTestId("draft-input");
+ input.innerHTML = "<div>First line</div><div>Second line</div>";
+ const connectionStates: boolean[] = [];
+ // jsdom omits innerText. Model the browser's rendered block line breaks,
+ // which become concatenated textContent once the node is detached.
+ vi.mocked(chatInputUtils.getTextContent).mockImplementation((element) => {
+ connectionStates.push(!!element?.isConnected);
+ return element?.isConnected
+ ? "First line\nSecond line"
+ : element?.textContent || "";
+ });
+
+ // Act
+ fireEvent.input(input);
+ act(() => vi.advanceTimersByTime(100));
+ unmount();
+ vi.mocked(chatInputUtils.getTextContent).mockImplementation(
+ (element) => element?.textContent || "",
+ );
+
+ // Assert: cleanup reads the real node while its rendered text is available.
+ expect(connectionStates).toEqual([true]);
+ expect(
+ conversationLocalStorage.getConversationState(conversationId)
+ .draftMessage,
+ ).toBe("First line\nSecond line");
+ });
+ });
+
it("keeps the home prompt storage key stable across module reloads", async () => {
vi.resetModules();
const freshModule = await import("#/hooks/chat/use-draft-persistence");
diff --git a/src/hooks/chat/use-draft-persistence.ts b/src/hooks/chat/use-draft-persistence.ts
index 0a71524006..0f7119333f 100644
--- a/src/hooks/chat/use-draft-persistence.ts
+++ b/src/hooks/chat/use-draft-persistence.ts
@@ -1,4 +1,10 @@
-import { useEffect, useRef, useCallback, useState } from "react";
+import {
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useCallback,
+ useState,
+} from "react";
import {
useConversationLocalStorageState,
getConversationState,
@@ -43,6 +49,12 @@ export const useDraftPersistence = (
conversationId ?? "",
);
const saveTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ // Retain the owning input so cleanup can read it after React clears the ref,
+ // including any programmatic clear performed by message submission.
+ const pendingDraftRef = useRef<{
+ conversationId: string;
+ element: HTMLDivElement;
+ } | null>(null);
const hasRestoredRef = useRef(false);
const [isRestored, setIsRestored] = useState(false);
@@ -50,18 +62,37 @@ export const useDraftPersistence = (
const currentConversationIdRef = useRef(conversationId);
// Track if this is the first mount to handle initial cleanup
const isFirstMountRef = useRef(true);
- // Tracks the latest home-page text so the unmount flush can use it safely.
- // chatInputRef.current is null by the time async useEffect cleanup runs in
- // React 18 (refs are cleared during the synchronous commit phase, before
- // passive effects fire), so we can't read from the DOM there.
+ // Tracks the latest home-page text without relying on a mounted input.
const lastHomeTextRef = useRef<string>("");
+ const flushPendingDraft = useCallback(() => {
+ if (saveTimeoutRef.current) {
+ clearTimeout(saveTimeoutRef.current);
+ saveTimeoutRef.current = null;
+ }
+ const pendingDraft = pendingDraftRef.current;
+ pendingDraftRef.current = null;
+ if (pendingDraft) {
+ const text = getTextContent(pendingDraft.element).trim();
+ const { draftMessage } = getConversationState(
+ pendingDraft.conversationId,
+ );
+ if (text !== (draftMessage || "")) {
+ setConversationState(pendingDraft.conversationId, {
+ draftMessage: text || null,
+ });
+ }
+ }
+ }, []);
+
// IMPORTANT: This effect must run FIRST when conversation changes.
// It handles three concerns:
- // 1. Cleanup: Cancel pending saves from previous conversation
+ // 1. Cleanup: Flush pending saves from previous conversation
// 2. Task-to-real transition: Preserve draft typed during initialization
// 3. DOM reset: Clear stale content before restoration effect runs
useEffect(() => {
+ // Read the previous input before clearing or restoring a different draft.
+ flushPendingDraft();
if (!conversationId) {
return;
}
@@ -70,13 +101,6 @@ export const useDraftPersistence = (
currentConversationIdRef.current = conversationId;
isFirstMountRef.current = false;
- // --- 1. Cancel pending saves from previous conversation ---
- // Prevents draft from being saved to wrong conversation if user switched quickly
- if (saveTimeoutRef.current) {
- clearTimeout(saveTimeoutRef.current);
- saveTimeoutRef.current = null;
- }
-
const element = chatInputRef.current;
// --- 2. Handle task-to-real ID transition (preserve draft during initialization) ---
@@ -117,7 +141,7 @@ export const useDraftPersistence = (
// Reset restoration flag so the restoration effect will run for new conversation
hasRestoredRef.current = false;
setIsRestored(false);
- }, [conversationId, chatInputRef]);
+ }, [conversationId, chatInputRef, flushPendingDraft]);
// Restore draft on mount - uses sessionStorage for the home page (no conversationId)
// and localStorage for active conversations.
@@ -196,13 +220,23 @@ export const useDraftPersistence = (
return;
}
- // Capture the conversationId at the time of input
+ const element = chatInputRef.current;
+ if (!element) {
+ return;
+ }
+
+ // Capture the input and its owner before navigation can replace either.
const capturedConversationId = conversationId;
+ const pendingDraft = { conversationId: capturedConversationId, element };
+ pendingDraftRef.current = pendingDraft;
saveTimeoutRef.current = setTimeout(() => {
// Verify we're still on the same conversation before saving
// This prevents saving draft to wrong conversation if user switched quickly
- if (capturedConversationId !== currentConversationIdRef.current) {
+ if (
+ capturedConversationId !== currentConversationIdRef.current ||
+ pendingDraftRef.current !== pendingDraft
+ ) {
return;
}
@@ -211,6 +245,8 @@ export const useDraftPersistence = (
return;
}
+ pendingDraftRef.current = null;
+ saveTimeoutRef.current = null;
const text = getTextContent(element).trim();
// Only save if content has changed
if (text !== (state.draftMessage || "")) {
@@ -226,6 +262,7 @@ export const useDraftPersistence = (
clearTimeout(saveTimeoutRef.current);
saveTimeoutRef.current = null;
}
+ pendingDraftRef.current = null;
if (!conversationId) {
// Home page: clear sessionStorage
try {
@@ -238,22 +275,18 @@ export const useDraftPersistence = (
setDraftMessage(null);
}, [conversationId, setDraftMessage]);
- // Cleanup on unmount: cancel any pending debounce timer and, for the home
- // page, flush the last-tracked text to sessionStorage. We read from
- // lastHomeTextRef rather than chatInputRef because React clears ref.current
- // during the synchronous commit phase β€” before async useEffect cleanups run
- // β€” so the DOM ref is null by the time this function executes.
+ // Flush the conversation input while it is still attached: reading innerText
+ // after detachment loses line breaks between contentEditable block elements.
+ // The home page continues to flush its last-tracked text to sessionStorage.
//
// We only write text back if the key already exists in sessionStorage.
// saveDraft writes synchronously on every keystroke, so the key is present
// whenever there is unsaved text. If the key is absent it was intentionally
// removed β€” most importantly by HomeChatLauncher.onSuccess after a
// successful conversation start β€” and we must not restore it here.
- useEffect(
+ useLayoutEffect(
() => () => {
- if (saveTimeoutRef.current) {
- clearTimeout(saveTimeoutRef.current);
- }
+ flushPendingDraft();
if (!currentConversationIdRef.current) {
const text = lastHomeTextRef.current;
try {
@@ -269,7 +302,7 @@ export const useDraftPersistence = (
}
}
},
- [],
+ [flushPendingDraft],
);
return {