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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
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 * as conversationLocalStorage from "#/utils/conversation-local-storage";

// Mock the entire module
vi.mock("#/utils/conversation-local-storage", () => ({
  useConversationLocalStorageState: vi.fn(),
  getConversationState: vi.fn(),
  setConversationState: vi.fn(),
}));

// Mock the chat-input utilities. The hook uses both `getTextContent`
// (to read the current contentEditable text) and `focusContentEditableAtEnd`
// (to place the caret at the end of the input after restoring a draft).
// Both need to be mocked here so the hook doesn't crash on
// `focusContentEditableAtEnd is not a function`.
vi.mock("#/components/features/chat/utils/chat-input.utils", () => ({
  getTextContent: vi.fn((el: HTMLDivElement | null) => el?.textContent || ""),
  focusContentEditableAtEnd: vi.fn(),
}));

describe("useDraftPersistence", () => {
  let mockSetDraftMessage: (message: string | null) => void;

  // Create a mock ref to contentEditable div
  const createMockChatInputRef = (initialContent = "") => {
    const div = document.createElement("div");
    div.setAttribute("contenteditable", "true");
    div.textContent = initialContent;
    return { current: div };
  };

  beforeEach(() => {
    vi.clearAllMocks();
    vi.useFakeTimers();
    localStorage.clear();

    mockSetDraftMessage = vi.fn<(message: string | null) => void>();

    // Default mock for useConversationLocalStorageState
    vi.mocked(conversationLocalStorage.useConversationLocalStorageState).mockReturnValue({
      state: {
        selectedTab: "files",
        unpinnedTabs: [],
        conversationMode: "code",
        subConversationTaskId: null,
        draftMessage: null,
        filesTabDiffView: null,
        filesTabContentViewMode: "rich",
      },
      setSelectedTab: vi.fn(),
      setUnpinnedTabs: vi.fn(),
      setConversationMode: vi.fn(),
      setDraftMessage: mockSetDraftMessage,
      setFilesTabDiffView: vi.fn(),
      setFilesTabContentViewMode: vi.fn(),
    });

    // Default mock for getConversationState
    vi.mocked(conversationLocalStorage.getConversationState).mockReturnValue({
      selectedTab: "files",
      unpinnedTabs: [],
      conversationMode: "code",
      subConversationTaskId: null,
      draftMessage: null,
      filesTabDiffView: null,
      filesTabContentViewMode: "rich",
    });
  });

  afterEach(() => {
    vi.useRealTimers();
    vi.clearAllMocks();
  });

  describe("draft restoration on mount", () => {
    it("restores draft from localStorage when mounting with existing draft", () => {
      // Arrange
      const conversationId = "conv-restore-1";
      const savedDraft = "Previously saved draft message";
      const chatInputRef = createMockChatInputRef();

      vi.mocked(conversationLocalStorage.getConversationState).mockReturnValue({
        selectedTab: "files",
        unpinnedTabs: [],
        conversationMode: "code",
        subConversationTaskId: null,
        draftMessage: savedDraft,
        filesTabDiffView: null,
        filesTabContentViewMode: "rich",
      });

      // Act
      renderHook(() => useDraftPersistence(conversationId, chatInputRef));

      // Assert - draft should be restored to the DOM element
      expect(chatInputRef.current?.textContent).toBe(savedDraft);
    });

    it("clears input on mount then restores draft if exists", () => {
      // Arrange
      const conversationId = "conv-restore-2";
      const existingContent = "Stale content from previous conversation";
      const savedDraft = "Saved draft";
      const chatInputRef = createMockChatInputRef(existingContent);

      vi.mocked(conversationLocalStorage.getConversationState).mockReturnValue({
        selectedTab: "files",
        unpinnedTabs: [],
        conversationMode: "code",
        subConversationTaskId: null,
        draftMessage: savedDraft,
        filesTabDiffView: null,
        filesTabContentViewMode: "rich",
      });

      // Act
      renderHook(() => useDraftPersistence(conversationId, chatInputRef));

      // Assert - input cleared then draft restored
      expect(chatInputRef.current?.textContent).toBe(savedDraft);
    });

    it("clears input when no draft exists for conversation", () => {
      // Arrange
      const conversationId = "conv-no-draft";
      const chatInputRef = createMockChatInputRef("Some stale content");

      vi.mocked(conversationLocalStorage.getConversationState).mockReturnValue({
        selectedTab: "files",
        unpinnedTabs: [],
        conversationMode: "code",
        subConversationTaskId: null,
        draftMessage: null,
        filesTabDiffView: null,
        filesTabContentViewMode: "rich",
      });

      // Act
      renderHook(() => useDraftPersistence(conversationId, chatInputRef));

      // Assert - content should be cleared since there's no draft
      expect(chatInputRef.current?.textContent).toBe("");
    });
  });

  describe("debounced saving", () => {
    it("saves draft after debounce period", () => {
      // Arrange
      const conversationId = "conv-debounce-1";
      const chatInputRef = createMockChatInputRef();

      const { result } = renderHook(() =>
        useDraftPersistence(conversationId, chatInputRef),
      );

      // Act - simulate user typing
      chatInputRef.current!.textContent = "New draft content";
      act(() => {
        result.current.saveDraft();
      });

      // Assert - should not save immediately
      expect(mockSetDraftMessage).not.toHaveBeenCalled();

      // Fast forward past debounce period (500ms)
      act(() => {
        vi.advanceTimersByTime(500);
      });

      // Assert - should save after debounce
      expect(mockSetDraftMessage).toHaveBeenCalledWith("New draft content");
    });

    it("cancels pending save when new input arrives before debounce", () => {
      // Arrange
      const conversationId = "conv-debounce-2";
      const chatInputRef = createMockChatInputRef();

      const { result } = renderHook(() =>
        useDraftPersistence(conversationId, chatInputRef),
      );

      // Act - first input
      chatInputRef.current!.textContent = "First";
      act(() => {
        result.current.saveDraft();
      });

      // Wait 200ms (less than debounce)
      act(() => {
        vi.advanceTimersByTime(200);
      });

      // Second input before debounce completes
      chatInputRef.current!.textContent = "First Second";
      act(() => {
        result.current.saveDraft();
      });

      // Complete the second debounce
      act(() => {
        vi.advanceTimersByTime(500);
      });

      // Assert - should only save the final value once
      expect(mockSetDraftMessage).toHaveBeenCalledTimes(1);
      expect(mockSetDraftMessage).toHaveBeenCalledWith("First Second");
    });

    it("does not save if content matches existing draft", () => {
      // Arrange
      const conversationId = "conv-no-change";
      const existingDraft = "Existing draft";
      const chatInputRef = createMockChatInputRef(existingDraft);

      vi.mocked(conversationLocalStorage.useConversationLocalStorageState).mockReturnValue({
        state: {
          selectedTab: "files",
          unpinnedTabs: [],
          conversationMode: "code",
          subConversationTaskId: null,
          draftMessage: existingDraft,
          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: existingDraft,
        filesTabDiffView: null,
        filesTabContentViewMode: "rich",
      });

      const { result } = renderHook(() =>
        useDraftPersistence(conversationId, chatInputRef),
      );

      // Act - try to save same content
      act(() => {
        result.current.saveDraft();
      });

      act(() => {
        vi.advanceTimersByTime(500);
      });

      // Assert - should not save since content is the same
      expect(mockSetDraftMessage).not.toHaveBeenCalled();
    });
  });

  describe("clearDraft", () => {
    it("clears the draft from localStorage", () => {
      // Arrange
      const conversationId = "conv-clear-1";
      const chatInputRef = createMockChatInputRef("Some content");

      const { result } = renderHook(() =>
        useDraftPersistence(conversationId, chatInputRef),
      );

      // Act
      act(() => {
        result.current.clearDraft();
      });

      // Assert
      expect(mockSetDraftMessage).toHaveBeenCalledWith(null);
    });

    it("cancels any pending debounced save when clearing", () => {
      // Arrange
      const conversationId = "conv-clear-2";
      const chatInputRef = createMockChatInputRef();

      const { result } = renderHook(() =>
        useDraftPersistence(conversationId, chatInputRef),
      );

      // Start a save
      chatInputRef.current!.textContent = "Pending draft";
      act(() => {
        result.current.saveDraft();
      });

      // Clear before debounce completes
      act(() => {
        vi.advanceTimersByTime(200);
        result.current.clearDraft();
      });

      // Complete the original debounce period
      act(() => {
        vi.advanceTimersByTime(500);
      });

      // Assert - only the clear should have been called (the pending save should be cancelled)
      expect(mockSetDraftMessage).toHaveBeenCalledTimes(1);
      expect(mockSetDraftMessage).toHaveBeenCalledWith(null);
    });
  });

  describe("conversation switching", () => {
    it("clears input when switching to a new conversation without a draft", () => {
      // Arrange
      const chatInputRef = createMockChatInputRef("Draft from conv A");

      // First conversation has a draft
      vi.mocked(conversationLocalStorage.getConversationState)
        .mockReturnValueOnce({
          selectedTab: "files",
          unpinnedTabs: [],
          conversationMode: "code",
          subConversationTaskId: null,
          draftMessage: "Draft from conv A",
          filesTabDiffView: null,
          filesTabContentViewMode: "rich",
        })
        .mockReturnValue({
          selectedTab: "files",
          unpinnedTabs: [],
          conversationMode: "code",
          subConversationTaskId: null,
          draftMessage: null,
          filesTabDiffView: null,
          filesTabContentViewMode: "rich",
        });

      const { rerender } = renderHook(
        ({ conversationId }) =>
          useDraftPersistence(conversationId, chatInputRef),
        { initialProps: { conversationId: "conv-A" } },
      );

      // Act - switch to conversation B
      rerender({ conversationId: "conv-B" });

      // Assert - input should be cleared (no draft for conv-B)
      expect(chatInputRef.current?.textContent).toBe("");
    });

    it("restores draft when switching to a conversation with an existing draft", () => {
      // Arrange
      const chatInputRef = createMockChatInputRef();
      const draftForConvB = "Saved draft for conversation B";

      vi.mocked(conversationLocalStorage.getConversationState)
        .mockReturnValueOnce({
          selectedTab: "files",
          unpinnedTabs: [],
          conversationMode: "code",
          subConversationTaskId: null,
          draftMessage: null,
          filesTabDiffView: null,
          filesTabContentViewMode: "rich",
        })
        .mockReturnValue({
          selectedTab: "files",
          unpinnedTabs: [],
          conversationMode: "code",
          subConversationTaskId: null,
          draftMessage: draftForConvB,
          filesTabDiffView: null,
          filesTabContentViewMode: "rich",
        });

      const { rerender } = renderHook(
        ({ conversationId }) =>
          useDraftPersistence(conversationId, chatInputRef),
        { initialProps: { conversationId: "conv-A" } },
      );

      // Act - switch to conversation B
      rerender({ conversationId: "conv-B" });

      // Assert - draft for conv-B should be restored
      expect(chatInputRef.current?.textContent).toBe(draftForConvB);
    });

    it("cancels pending save when switching conversations", () => {
      // Arrange
      const chatInputRef = createMockChatInputRef();

      const { result, rerender } = renderHook(
        ({ conversationId }) =>
          useDraftPersistence(conversationId, chatInputRef),
        { initialProps: { conversationId: "conv-A" } },
      );

      // Start typing in conv-A
      chatInputRef.current!.textContent = "Draft for conv-A";
      act(() => {
        result.current.saveDraft();
      });

      // Switch conversation before debounce completes
      act(() => {
        vi.advanceTimersByTime(200);
      });
      rerender({ conversationId: "conv-B" });

      // Complete the debounce period
      act(() => {
        vi.advanceTimersByTime(500);
      });

      // Assert - the save should NOT have happened because conversation changed
      expect(mockSetDraftMessage).not.toHaveBeenCalled();
    });
  });

  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");

      vi.mocked(conversationLocalStorage.getConversationState).mockReturnValue({
        selectedTab: "files",
        unpinnedTabs: [],
        conversationMode: "code",
        subConversationTaskId: null,
        draftMessage: null,
        filesTabDiffView: null,
        filesTabContentViewMode: "rich",
      });

      const { rerender } = renderHook(
        ({ conversationId }) =>
          useDraftPersistence(conversationId, chatInputRef),
        { initialProps: { conversationId: "task-abc-123" } },
      );

      // Simulate user typing during task initialization
      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" },
      );

      // And the draft should remain visible in the input
      expect(chatInputRef.current?.textContent).toBe("Draft typed during init");
    });

    it("does not transfer empty draft during task-to-real transition", () => {
      // Arrange
      const chatInputRef = createMockChatInputRef("");

      vi.mocked(conversationLocalStorage.getConversationState).mockReturnValue({
        selectedTab: "files",
        unpinnedTabs: [],
        conversationMode: "code",
        subConversationTaskId: null,
        draftMessage: null,
        filesTabDiffView: null,
        filesTabContentViewMode: "rich",
      });

      const { rerender } = renderHook(
        ({ conversationId }) =>
          useDraftPersistence(conversationId, chatInputRef),
        { initialProps: { conversationId: "task-abc-123" } },
      );

      // Act - transition to real conversation ID with empty input
      rerender({ conversationId: "conv-real-123" });

      // 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();
    });

    it("does not transfer draft for non-task ID transitions", () => {
      // Arrange
      const chatInputRef = createMockChatInputRef("Some draft");

      vi.mocked(conversationLocalStorage.getConversationState).mockReturnValue({
        selectedTab: "files",
        unpinnedTabs: [],
        conversationMode: "code",
        subConversationTaskId: null,
        draftMessage: null,
        filesTabDiffView: null,
        filesTabContentViewMode: "rich",
      });

      const { rerender } = renderHook(
        ({ conversationId }) =>
          useDraftPersistence(conversationId, chatInputRef),
        { initialProps: { conversationId: "conv-A" } },
      );

      // Act - normal conversation switch (not task-to-real)
      rerender({ conversationId: "conv-B" });

      // Assert - should not use setConversationState directly
      // (the normal path uses setDraftMessage from the hook)
      expect(conversationLocalStorage.setConversationState).not.toHaveBeenCalled();
    });
  });

  describe("hasDraft and isRestored state", () => {
    it("returns hasDraft true when draft exists in hook state", () => {
      // Arrange
      const conversationId = "conv-has-draft";
      const chatInputRef = createMockChatInputRef();

      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(),
      });

      // Act
      const { result } = renderHook(() =>
        useDraftPersistence(conversationId, chatInputRef),
      );

      // Assert
      expect(result.current.hasDraft).toBe(true);
    });

    it("returns hasDraft false when no draft exists", () => {
      // Arrange
      const conversationId = "conv-no-draft";
      const chatInputRef = createMockChatInputRef();

      // Act
      const { result } = renderHook(() =>
        useDraftPersistence(conversationId, chatInputRef),
      );

      // Assert
      expect(result.current.hasDraft).toBe(false);
    });

    it("sets isRestored to true after restoration completes", () => {
      // Arrange
      const conversationId = "conv-restored";
      const chatInputRef = createMockChatInputRef();

      vi.mocked(conversationLocalStorage.getConversationState).mockReturnValue({
        selectedTab: "files",
        unpinnedTabs: [],
        conversationMode: "code",
        subConversationTaskId: null,
        draftMessage: "Draft to restore",
        filesTabDiffView: null,
        filesTabContentViewMode: "rich",
      });

      // Act
      const { result } = renderHook(() =>
        useDraftPersistence(conversationId, chatInputRef),
      );

      // Assert
      expect(result.current.isRestored).toBe(true);
    });
  });

  describe("cleanup on unmount", () => {
    it("clears pending timeout on unmount", () => {
      // Arrange
      const conversationId = "conv-unmount";
      const chatInputRef = createMockChatInputRef();

      const { result, unmount } = renderHook(() =>
        useDraftPersistence(conversationId, chatInputRef),
      );

      // Start a save
      chatInputRef.current!.textContent = "Draft";
      act(() => {
        result.current.saveDraft();
      });

      // Unmount before debounce completes
      unmount();

      // Complete the debounce period
      act(() => {
        vi.advanceTimersByTime(500);
      });

      // Assert - save should not have been called after unmount
      expect(mockSetDraftMessage).not.toHaveBeenCalled();
    });
  });
});