Skip to content

πŸ™Œ OpenHands: AI-Driven Development

test: cover draft persistence (#17334)

aivong-openhands7e2c893e33a9
diff --git a/__tests__/hooks/use-draft-persistence.test.tsx b/__tests__/hooks/use-draft-persistence.test.tsx
index 63836ec4b4..21f9a6c24c 100644
--- a/__tests__/hooks/use-draft-persistence.test.tsx
+++ b/__tests__/hooks/use-draft-persistence.test.tsx
@@ -1,7 +1,11 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { renderHook, act } from "@testing-library/react";
-import { useDraftPersistence } from "#/hooks/chat/use-draft-persistence";
+import {
+ HOME_PROMPT_DRAFT_KEY,
+ useDraftPersistence,
+} from "#/hooks/chat/use-draft-persistence";
import * as conversationLocalStorage from "#/utils/conversation-local-storage";
+import * as chatInputUtils from "#/components/features/chat/utils/chat-input.utils";
// Mock the entire module
vi.mock("#/utils/conversation-local-storage", () => ({
@@ -35,11 +39,14 @@ describe("useDraftPersistence", () => {
vi.clearAllMocks();
vi.useFakeTimers();
localStorage.clear();
+ sessionStorage.clear();
mockSetDraftMessage = vi.fn<(message: string | null) => void>();
// Default mock for useConversationLocalStorageState
- vi.mocked(conversationLocalStorage.useConversationLocalStorageState).mockReturnValue({
+ vi.mocked(
+ conversationLocalStorage.useConversationLocalStorageState,
+ ).mockReturnValue({
state: {
selectedTab: "files",
unpinnedTabs: [],
@@ -71,6 +78,7 @@ describe("useDraftPersistence", () => {
afterEach(() => {
vi.useRealTimers();
+ vi.restoreAllMocks();
vi.clearAllMocks();
});
@@ -142,6 +150,7 @@ describe("useDraftPersistence", () => {
// Assert - content should be cleared since there's no draft
expect(chatInputRef.current?.textContent).toBe("");
+ expect(chatInputUtils.focusContentEditableAtEnd).not.toHaveBeenCalled();
});
});
@@ -215,7 +224,9 @@ describe("useDraftPersistence", () => {
const existingDraft = "Existing draft";
const chatInputRef = createMockChatInputRef(existingDraft);
- vi.mocked(conversationLocalStorage.useConversationLocalStorageState).mockReturnValue({
+ vi.mocked(
+ conversationLocalStorage.useConversationLocalStorageState,
+ ).mockReturnValue({
state: {
selectedTab: "files",
unpinnedTabs: [],
@@ -259,6 +270,21 @@ describe("useDraftPersistence", () => {
// Assert - should not save since content is the same
expect(mockSetDraftMessage).not.toHaveBeenCalled();
});
+
+ it("saves new draft text when no persisted draft exists", () => {
+ const chatInputRef = createMockChatInputRef("Stryker was here!");
+ const { result } = renderHook(() =>
+ useDraftPersistence("conv-new-draft", chatInputRef),
+ );
+ chatInputRef.current!.textContent = "Stryker was here!";
+
+ act(() => {
+ result.current.saveDraft();
+ vi.advanceTimersByTime(500);
+ });
+
+ expect(mockSetDraftMessage).toHaveBeenCalledWith("Stryker was here!");
+ });
});
describe("clearDraft", () => {
@@ -419,12 +445,90 @@ describe("useDraftPersistence", () => {
// Assert - the save should NOT have happened because conversation changed
expect(mockSetDraftMessage).not.toHaveBeenCalled();
});
+
+ it("switches from the home page to a real conversation safely", () => {
+ const chatInputRef = createMockChatInputRef();
+ const { rerender } = renderHook(
+ ({ conversationId }: { conversationId: string | undefined }) =>
+ useDraftPersistence(conversationId, chatInputRef),
+ {
+ initialProps: {
+ conversationId: undefined as string | undefined,
+ },
+ },
+ );
+
+ expect(() => rerender({ conversationId: "conv-real" })).not.toThrow();
+ });
+
+ it("uses the current conversation setter after rerendering", () => {
+ const setDraftForA = vi.fn();
+ const setDraftForB = vi.fn();
+ vi.mocked(
+ conversationLocalStorage.useConversationLocalStorageState,
+ ).mockImplementation((conversationId) => ({
+ state: {
+ selectedTab: "files",
+ unpinnedTabs: [],
+ conversationMode: "code",
+ subConversationTaskId: null,
+ draftMessage: null,
+ filesTabDiffView: null,
+ filesTabContentViewMode: "rich",
+ },
+ setSelectedTab: vi.fn(),
+ setUnpinnedTabs: vi.fn(),
+ setConversationMode: vi.fn(),
+ setDraftMessage:
+ conversationId === "conv-A" ? setDraftForA : setDraftForB,
+ setFilesTabDiffView: vi.fn(),
+ setFilesTabContentViewMode: vi.fn(),
+ }));
+ const chatInputRef = createMockChatInputRef();
+ const { result, rerender } = renderHook(
+ ({ conversationId }) =>
+ useDraftPersistence(conversationId, chatInputRef),
+ { initialProps: { conversationId: "conv-A" } },
+ );
+
+ rerender({ conversationId: "conv-B" });
+ chatInputRef.current.textContent = "draft for B";
+ act(() => {
+ result.current.saveDraft();
+ vi.advanceTimersByTime(500);
+ });
+
+ expect(setDraftForA).not.toHaveBeenCalled();
+ expect(setDraftForB).toHaveBeenCalledWith("draft for B");
+ });
+
+ it("clears the current conversation after leaving the home page", () => {
+ sessionStorage.setItem(HOME_PROMPT_DRAFT_KEY, "home prompt");
+ const chatInputRef = createMockChatInputRef();
+ const { result, rerender } = renderHook(
+ ({ conversationId }: { conversationId: string | undefined }) =>
+ useDraftPersistence(conversationId, chatInputRef),
+ {
+ initialProps: {
+ conversationId: undefined as string | undefined,
+ },
+ },
+ );
+
+ rerender({ conversationId: "conv-real" });
+ act(() => result.current.clearDraft());
+
+ expect(mockSetDraftMessage).toHaveBeenCalledWith(null);
+ expect(sessionStorage.getItem(HOME_PROMPT_DRAFT_KEY)).toBe("home prompt");
+ });
});
describe("task ID to real conversation ID transition", () => {
it("transfers draft from task ID to real conversation ID during transition", () => {
// Arrange
- const chatInputRef = createMockChatInputRef("Draft typed during init");
+ const chatInputRef = createMockChatInputRef(
+ " Draft typed during init ",
+ );
vi.mocked(conversationLocalStorage.getConversationState).mockReturnValue({
selectedTab: "files",
@@ -436,26 +540,30 @@ describe("useDraftPersistence", () => {
filesTabContentViewMode: "rich",
});
- const { rerender } = renderHook(
+ const { result, rerender } = renderHook(
({ conversationId }) =>
useDraftPersistence(conversationId, chatInputRef),
{ initialProps: { conversationId: "task-abc-123" } },
);
// Simulate user typing during task initialization
- chatInputRef.current!.textContent = "Draft typed during init";
+ chatInputRef.current!.textContent = " Draft typed during init ";
// Act - transition to real conversation ID
rerender({ conversationId: "conv-real-123" });
// Assert - draft should be saved to the new real conversation ID
- expect(conversationLocalStorage.setConversationState).toHaveBeenCalledWith(
- "conv-real-123",
- { draftMessage: "Draft typed during init" },
- );
+ expect(
+ conversationLocalStorage.setConversationState,
+ ).toHaveBeenCalledWith("conv-real-123", {
+ draftMessage: "Draft typed during init",
+ });
// And the draft should remain visible in the input
- expect(chatInputRef.current?.textContent).toBe("Draft typed during init");
+ expect(chatInputRef.current?.textContent).toBe(
+ " Draft typed during init ",
+ );
+ expect(result.current.isRestored).toBe(true);
});
it("does not transfer empty draft during task-to-real transition", () => {
@@ -483,7 +591,9 @@ describe("useDraftPersistence", () => {
// Assert - no draft should be saved (input is cleared, checked by hook)
// The setConversationState should not be called with draftMessage
- expect(conversationLocalStorage.setConversationState).not.toHaveBeenCalled();
+ expect(
+ conversationLocalStorage.setConversationState,
+ ).not.toHaveBeenCalled();
});
it("does not transfer draft for non-task ID transitions", () => {
@@ -511,7 +621,9 @@ describe("useDraftPersistence", () => {
// Assert - should not use setConversationState directly
// (the normal path uses setDraftMessage from the hook)
- expect(conversationLocalStorage.setConversationState).not.toHaveBeenCalled();
+ expect(
+ conversationLocalStorage.setConversationState,
+ ).not.toHaveBeenCalled();
});
});
@@ -521,7 +633,9 @@ describe("useDraftPersistence", () => {
const conversationId = "conv-has-draft";
const chatInputRef = createMockChatInputRef();
- vi.mocked(conversationLocalStorage.useConversationLocalStorageState).mockReturnValue({
+ vi.mocked(
+ conversationLocalStorage.useConversationLocalStorageState,
+ ).mockReturnValue({
state: {
selectedTab: "files",
unpinnedTabs: [],
@@ -587,7 +701,339 @@ describe("useDraftPersistence", () => {
});
});
+ describe("home-page session draft", () => {
+ it("restores and preserves a saved home prompt", () => {
+ sessionStorage.setItem(HOME_PROMPT_DRAFT_KEY, " saved home prompt ");
+ const chatInputRef = createMockChatInputRef();
+
+ const { result, unmount } = renderHook(() =>
+ useDraftPersistence(undefined, chatInputRef),
+ );
+
+ expect(
+ conversationLocalStorage.useConversationLocalStorageState,
+ ).toHaveBeenCalledWith("");
+ expect(chatInputRef.current.textContent).toBe(" saved home prompt ");
+ expect(result.current.isRestored).toBe(true);
+
+ unmount();
+ expect(sessionStorage.getItem(HOME_PROMPT_DRAFT_KEY)).toBe(
+ " saved home prompt ",
+ );
+ });
+
+ it("does not overwrite existing home input with a stored prompt", () => {
+ sessionStorage.setItem(HOME_PROMPT_DRAFT_KEY, "stored prompt");
+ const chatInputRef = createMockChatInputRef("current prompt");
+
+ const { unmount } = renderHook(() =>
+ useDraftPersistence(null, chatInputRef),
+ );
+
+ expect(chatInputRef.current.textContent).toBe("current prompt");
+ unmount();
+ expect(sessionStorage.getItem(HOME_PROMPT_DRAFT_KEY)).toBeNull();
+ });
+
+ it("restores safely when the browser has no Selection object", () => {
+ sessionStorage.setItem(HOME_PROMPT_DRAFT_KEY, "saved prompt");
+ vi.spyOn(window, "getSelection").mockReturnValue(null);
+ const chatInputRef = createMockChatInputRef();
+
+ const { result, unmount } = renderHook(() =>
+ useDraftPersistence(undefined, chatInputRef),
+ );
+
+ expect(chatInputRef.current.textContent).toBe("saved prompt");
+ expect(result.current.isRestored).toBe(true);
+ unmount();
+ expect(sessionStorage.getItem(HOME_PROMPT_DRAFT_KEY)).toBe(
+ "saved prompt",
+ );
+ });
+
+ it("restores over whitespace-only home input and places the caret at the end", () => {
+ sessionStorage.setItem(HOME_PROMPT_DRAFT_KEY, "saved prompt");
+ const chatInputRef = createMockChatInputRef(" ");
+ document.body.appendChild(chatInputRef.current);
+
+ renderHook(() => useDraftPersistence(undefined, chatInputRef));
+
+ expect(chatInputRef.current.textContent).toBe("saved prompt");
+ const selection = window.getSelection();
+ expect(selection?.rangeCount).toBe(1);
+ const caret = selection!.getRangeAt(0);
+ expect(caret.collapsed).toBe(true);
+ expect(caret.startOffset).toBe(chatInputRef.current.childNodes.length);
+ chatInputRef.current.remove();
+ });
+
+ it("finishes restoration when session storage is unavailable", () => {
+ vi.spyOn(Storage.prototype, "getItem").mockImplementation(() => {
+ throw new Error("storage disabled");
+ });
+ const chatInputRef = createMockChatInputRef();
+
+ const { result } = renderHook(() =>
+ useDraftPersistence(undefined, chatInputRef),
+ );
+
+ expect(chatInputRef.current.textContent).toBe("");
+ expect(result.current.isRestored).toBe(true);
+ });
+
+ it("writes non-empty input synchronously and removes an empty input", () => {
+ const chatInputRef = createMockChatInputRef(" new home prompt ");
+ const { result } = renderHook(() =>
+ useDraftPersistence(undefined, chatInputRef),
+ );
+
+ act(() => result.current.saveDraft());
+ expect(sessionStorage.getItem(HOME_PROMPT_DRAFT_KEY)).toBe(
+ "new home prompt",
+ );
+
+ chatInputRef.current.textContent = " ";
+ act(() => result.current.saveDraft());
+ expect(sessionStorage.getItem(HOME_PROMPT_DRAFT_KEY)).toBeNull();
+ });
+
+ it("does nothing when saving without a mounted input", () => {
+ sessionStorage.setItem(HOME_PROMPT_DRAFT_KEY, "existing prompt");
+ const chatInputRef = { current: null };
+ const { result } = renderHook(() =>
+ useDraftPersistence(undefined, chatInputRef),
+ );
+
+ act(() => result.current.saveDraft());
+
+ expect(sessionStorage.getItem(HOME_PROMPT_DRAFT_KEY)).toBe(
+ "existing prompt",
+ );
+ expect(result.current.isRestored).toBe(false);
+ });
+
+ it("tolerates storage failures while saving and clearing", () => {
+ const chatInputRef = createMockChatInputRef("home prompt");
+ const { result } = renderHook(() =>
+ useDraftPersistence(undefined, chatInputRef),
+ );
+ vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {
+ throw new Error("storage disabled");
+ });
+
+ expect(() => act(() => result.current.saveDraft())).not.toThrow();
+
+ vi.restoreAllMocks();
+ vi.spyOn(Storage.prototype, "removeItem").mockImplementation(() => {
+ throw new Error("storage disabled");
+ });
+ expect(() => act(() => result.current.clearDraft())).not.toThrow();
+ });
+
+ it("flushes the latest tracked prompt once storage recovers", () => {
+ sessionStorage.setItem(HOME_PROMPT_DRAFT_KEY, "older home prompt");
+ const chatInputRef: { current: HTMLDivElement | null } =
+ createMockChatInputRef();
+ const { result, unmount } = renderHook(() =>
+ useDraftPersistence(undefined, chatInputRef),
+ );
+
+ chatInputRef.current!.textContent = "newer home prompt";
+ vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {
+ throw new Error("storage disabled");
+ });
+ act(() => result.current.saveDraft());
+ vi.restoreAllMocks();
+
+ expect(sessionStorage.getItem(HOME_PROMPT_DRAFT_KEY)).toBe(
+ "older home prompt",
+ );
+
+ chatInputRef.current = null;
+ unmount();
+
+ expect(sessionStorage.getItem(HOME_PROMPT_DRAFT_KEY)).toBe(
+ "newer home prompt",
+ );
+ });
+
+ it("clears the persisted home prompt", () => {
+ sessionStorage.setItem(HOME_PROMPT_DRAFT_KEY, "home prompt");
+ const chatInputRef = createMockChatInputRef("home prompt");
+ const { result } = renderHook(() =>
+ useDraftPersistence(undefined, chatInputRef),
+ );
+
+ act(() => result.current.clearDraft());
+
+ expect(sessionStorage.getItem(HOME_PROMPT_DRAFT_KEY)).toBeNull();
+ });
+
+ it("does not resurrect a prompt deliberately removed before unmount", () => {
+ const chatInputRef = createMockChatInputRef("home prompt");
+ const { result, unmount } = renderHook(() =>
+ useDraftPersistence(undefined, chatInputRef),
+ );
+ act(() => result.current.saveDraft());
+ sessionStorage.removeItem(HOME_PROMPT_DRAFT_KEY);
+
+ unmount();
+
+ expect(sessionStorage.getItem(HOME_PROMPT_DRAFT_KEY)).toBeNull();
+ });
+
+ it("removes an empty tracked prompt during unmount cleanup", () => {
+ sessionStorage.setItem(HOME_PROMPT_DRAFT_KEY, "stale prompt");
+ const chatInputRef = createMockChatInputRef(" ");
+ const { result, unmount } = renderHook(() =>
+ useDraftPersistence(undefined, chatInputRef),
+ );
+ chatInputRef.current.textContent = " ";
+ act(() => result.current.saveDraft());
+
+ unmount();
+
+ expect(sessionStorage.getItem(HOME_PROMPT_DRAFT_KEY)).toBeNull();
+ });
+
+ it("tolerates storage failure during unmount cleanup", () => {
+ const chatInputRef = createMockChatInputRef("home prompt");
+ const { result, unmount } = renderHook(() =>
+ useDraftPersistence(undefined, chatInputRef),
+ );
+ act(() => result.current.saveDraft());
+ vi.spyOn(Storage.prototype, "getItem").mockImplementation(() => {
+ throw new Error("storage disabled");
+ });
+
+ expect(unmount).not.toThrow();
+ });
+ });
+
+ describe("debounce race handling", () => {
+ it("initializes safely when a conversation input is not mounted", () => {
+ const chatInputRef = { current: null };
+
+ const { result } = renderHook(() =>
+ useDraftPersistence("conv-without-input", chatInputRef),
+ );
+
+ expect(result.current.isRestored).toBe(false);
+ expect(
+ conversationLocalStorage.getConversationState,
+ ).not.toHaveBeenCalled();
+ });
+
+ it("ignores a stale timer callback after the conversation changes", () => {
+ const chatInputRef = createMockChatInputRef();
+ const { result, rerender } = renderHook(
+ ({ conversationId }) =>
+ useDraftPersistence(conversationId, chatInputRef),
+ { initialProps: { conversationId: "conv-A" } },
+ );
+ chatInputRef.current.textContent = "draft for A";
+ act(() => result.current.saveDraft());
+ vi.spyOn(globalThis, "clearTimeout").mockImplementation(() => undefined);
+
+ rerender({ conversationId: "conv-B" });
+ chatInputRef.current.textContent = "draft for B";
+ act(() => vi.advanceTimersByTime(500));
+
+ expect(mockSetDraftMessage).not.toHaveBeenCalled();
+ });
+
+ it("does not save when the input disappears before debounce completes", () => {
+ vi.mocked(
+ conversationLocalStorage.useConversationLocalStorageState,
+ ).mockReturnValue({
+ state: {
+ selectedTab: "files",
+ unpinnedTabs: [],
+ conversationMode: "code",
+ subConversationTaskId: null,
+ draftMessage: "existing draft",
+ filesTabDiffView: null,
+ filesTabContentViewMode: "rich",
+ },
+ setSelectedTab: vi.fn(),
+ setUnpinnedTabs: vi.fn(),
+ setConversationMode: vi.fn(),
+ setDraftMessage: mockSetDraftMessage,
+ setFilesTabDiffView: vi.fn(),
+ setFilesTabContentViewMode: vi.fn(),
+ });
+ const chatInputRef: { current: HTMLDivElement | null } =
+ createMockChatInputRef("draft");
+ const { result } = renderHook(() =>
+ useDraftPersistence("conv-disappearing", chatInputRef),
+ );
+ chatInputRef.current!.textContent = "new draft";
+ act(() => result.current.saveDraft());
+ chatInputRef.current = null;
+
+ act(() => vi.advanceTimersByTime(500));
+
+ expect(mockSetDraftMessage).not.toHaveBeenCalled();
+ });
+
+ it("saves an emptied conversation draft as null", () => {
+ vi.mocked(
+ conversationLocalStorage.useConversationLocalStorageState,
+ ).mockReturnValue({
+ state: {
+ selectedTab: "files",
+ unpinnedTabs: [],
+ conversationMode: "code",
+ subConversationTaskId: null,
+ draftMessage: "old draft",
+ filesTabDiffView: null,
+ filesTabContentViewMode: "rich",
+ },
+ setSelectedTab: vi.fn(),
+ setUnpinnedTabs: vi.fn(),
+ setConversationMode: vi.fn(),
+ setDraftMessage: mockSetDraftMessage,
+ setFilesTabDiffView: vi.fn(),
+ setFilesTabContentViewMode: vi.fn(),
+ });
+ vi.mocked(conversationLocalStorage.getConversationState).mockReturnValue({
+ selectedTab: "files",
+ unpinnedTabs: [],
+ conversationMode: "code",
+ subConversationTaskId: null,
+ draftMessage: "old draft",
+ filesTabDiffView: null,
+ filesTabContentViewMode: "rich",
+ });
+ const chatInputRef = createMockChatInputRef();
+ const { result } = renderHook(() =>
+ useDraftPersistence("conv-empty", chatInputRef),
+ );
+ chatInputRef.current.textContent = " ";
+
+ act(() => {
+ result.current.saveDraft();
+ vi.advanceTimersByTime(500);
+ });
+
+ expect(mockSetDraftMessage).toHaveBeenCalledWith(null);
+ });
+ });
+
describe("cleanup on unmount", () => {
+ it("does not change the home prompt when unmounting a conversation", () => {
+ sessionStorage.setItem(HOME_PROMPT_DRAFT_KEY, "home prompt");
+ const chatInputRef = createMockChatInputRef();
+
+ const { unmount } = renderHook(() =>
+ useDraftPersistence("conv-unmount", chatInputRef),
+ );
+ unmount();
+
+ expect(sessionStorage.getItem(HOME_PROMPT_DRAFT_KEY)).toBe("home prompt");
+ });
+
it("clears pending timeout on unmount", () => {
// Arrange
const conversationId = "conv-unmount";
@@ -615,4 +1061,11 @@ describe("useDraftPersistence", () => {
expect(mockSetDraftMessage).not.toHaveBeenCalled();
});
});
+
+ it("keeps the home prompt storage key stable across module reloads", async () => {
+ vi.resetModules();
+ const freshModule = await import("#/hooks/chat/use-draft-persistence");
+
+ expect(freshModule.HOME_PROMPT_DRAFT_KEY).toBe("oh:home-prompt-draft");
+ });
});