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
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
import { act, cleanup, renderHook } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ImageResults, SearchEntry, TextResults } from "@/modules/history";
import {
  getChatMessagesForQuery,
  getLatestLlmResponseForEntry,
  setCurrentSearchRunId,
} from "@/modules/history";
import {
  chatGenerationStatePubSub,
  chatMessagesPubSub,
  getChatSession,
  getLlmTextSearchResults,
  getPageContents,
  getSuppressNextFollowUp,
  imageSearchResultsPubSub,
  imageSearchStatePubSub,
  isRestoringFromHistoryPubSub,
  textSearchResultsPubSub,
  updateImageSearchResults,
  updateLlmTextSearchResults,
  updatePageContents,
  updateSuppressNextFollowUp,
  updateTextSearchResults,
} from "@/modules/pubSub";
import type { TextSearchResults } from "@/modules/types";
import { useHistoryRestore } from "./useHistoryRestore";

/** A chat turn as history stores it: never a system message. */
type StoredTurn = { role: "user" | "assistant"; content: string };

const [updateChatGenerationState] = chatGenerationStatePubSub;
const [updateChatMessages, subscribeToChatMessages, getChatMessages] =
  chatMessagesPubSub;

vi.mock("wouter", () => ({
  useLocation: () => ["/", vi.fn()],
}));

vi.mock("@/modules/logEntries", () => ({ addLogEntry: vi.fn() }));

vi.mock("@/modules/config", () => ({
  getConfig: vi.fn().mockResolvedValue({
    parentWindowOrigins: ["https://huggingface.co"],
  }),
}));

vi.mock("@/modules/history", async (importOriginal) => ({
  ...(await importOriginal<typeof import("@/modules/history")>()),
  getLatestLlmResponseForEntry: vi.fn().mockResolvedValue(null),
  getChatMessagesForQuery: vi.fn().mockResolvedValue([]),
}));

const textResults: TextResults = {
  type: "text",
  items: [
    {
      title: "Saved text",
      snippet: "Saved snippet",
      url: "https://example.com/text",
    },
  ],
};

const imageResults: ImageResults = {
  type: "image",
  items: [
    {
      title: "Saved image",
      url: "https://example.com/image.png",
      thumbnail: "https://example.com/thumbnail.png",
      sourceUrl: "https://example.com/source",
    },
    {
      title: "Image without a source",
      url: "https://example.com/other.png",
      thumbnail: "https://example.com/other-thumbnail.png",
    },
  ],
};

const expectedImages = [
  [
    "Saved image",
    "https://example.com/image.png",
    "https://example.com/thumbnail.png",
    "https://example.com/source",
  ],
  [
    "Image without a source",
    "https://example.com/other.png",
    "https://example.com/other-thumbnail.png",
    "",
  ],
];

beforeEach(() => {
  vi.useFakeTimers();
  vi.mocked(getLatestLlmResponseForEntry).mockResolvedValue(null);
  vi.mocked(getChatMessagesForQuery).mockReset().mockResolvedValue([]);
  updateSuppressNextFollowUp(false);
  updateChatMessages([]);
  updateChatGenerationState({
    isGeneratingResponse: false,
    isGeneratingFollowUpQuestion: false,
  });
  updateImageSearchResults([
    ["Previous image", "old.png", "old-thumb.png", ""],
  ]);
});

afterEach(() => {
  cleanup();
  vi.runOnlyPendingTimers();
  vi.useRealTimers();
});

async function restoreEntry(payload: Partial<SearchEntry>) {
  const { result } = renderHook(() => useHistoryRestore(vi.fn()));
  await act(async () => {
    await result.current.restoreSearch({
      query: "saved search",
      timestamp: 1,
      ...payload,
    });
  });
}

describe("useHistoryRestore", () => {
  it("restores both text and images from the same search", async () => {
    await restoreEntry({ results: textResults, textResults, imageResults });

    expect(imageSearchResultsPubSub[2]()).toEqual(expectedImages);
    const expectedText = [
      ["Saved text", "Saved snippet", "https://example.com/text"],
    ];
    expect(textSearchResultsPubSub[2]()).toEqual(expectedText);
    expect(getLlmTextSearchResults()).toEqual(expectedText);
    expect(imageSearchStatePubSub[2]()).toBe("completed");
  });

  it.each([
    { searchRunId: "live-run", generating: true, keepsGrounding: true },
    { searchRunId: "other-run", generating: true, keepsGrounding: false },
    { searchRunId: "live-run", generating: false, keepsGrounding: false },
  ])(
    "restores text grounding for $searchRunId with generating=$generating",
    async ({ searchRunId, generating, keepsGrounding }) => {
      const savedText: TextSearchResults = [
        ["Saved text", "Saved snippet", "https://example.com/text"],
      ];
      const liveText: TextSearchResults = [
        ...savedText,
        ["Follow-up result", "Fresh snippet", "https://example.com/follow-up"],
      ];
      const excerpts = {
        "https://example.com/text": "First excerpt",
        "https://example.com/follow-up": "Fresh excerpt",
      };
      setCurrentSearchRunId("live-run");
      updateChatGenerationState({
        isGeneratingResponse: generating,
        isGeneratingFollowUpQuestion: false,
      });
      updateTextSearchResults(liveText);
      updateLlmTextSearchResults(liveText);
      updatePageContents(excerpts);
      vi.mocked(getLatestLlmResponseForEntry).mockResolvedValueOnce(
        "Saved AI answer.",
      );

      await restoreEntry({ searchRunId, textResults });

      const expectedText = keepsGrounding ? liveText : savedText;
      expect(textSearchResultsPubSub[2]()).toEqual(expectedText);
      expect(getLlmTextSearchResults()).toEqual(expectedText);
      expect(getPageContents()).toEqual(keepsGrounding ? excerpts : {});
    },
  );

  it.each([
    { name: "image-only entry", payload: { imageResults } },
    { name: "legacy image-only entry", payload: { results: imageResults } },
    {
      name: "legacy images alongside newer text results",
      payload: { textResults, results: imageResults },
    },
    {
      name: "newer images alongside an empty legacy image payload",
      payload: {
        imageResults,
        results: { type: "image", items: [] } as ImageResults,
      },
    },
  ])("restores $name", async ({ payload }) => {
    await restoreEntry(payload);

    expect(imageSearchResultsPubSub[2]()).toEqual(expectedImages);
    expect(imageSearchStatePubSub[2]()).toBe("completed");
  });

  it("clears previous images when the saved search has none", async () => {
    await restoreEntry({ textResults });

    expect(imageSearchResultsPubSub[2]()).toEqual([]);
    expect(imageSearchStatePubSub[2]()).toBe("completed");
  });

  it("restores one picture saved twice from two pages as one image", async () => {
    const picture = {
      title: "Same picture",
      thumbnail: "https://cdn.example.com/thumbnail.png",
      sourceUrl: "https://cdn.example.com/picture.png",
    };
    await restoreEntry({
      imageResults: {
        type: "image",
        items: [
          { ...picture, url: "https://first.example.com/gallery" },
          { ...picture, url: "https://second.example.com/gallery" },
        ],
      },
    });

    expect(imageSearchResultsPubSub[2]()).toEqual([
      [
        "Same picture",
        "https://first.example.com/gallery",
        "https://cdn.example.com/thumbnail.png",
        "https://cdn.example.com/picture.png",
      ],
    ]);
  });

  it("leaves suppressNextFollowUp false when the restored entry has no saved response", async () => {
    await restoreEntry({ textResults });

    expect(getSuppressNextFollowUp()).toBe(false);
  });

  it("sets suppressNextFollowUp true when the restored entry has a saved response", async () => {
    vi.mocked(getLatestLlmResponseForEntry).mockResolvedValueOnce(
      "Saved AI answer.",
    );

    await restoreEntry({ textResults });

    expect(getSuppressNextFollowUp()).toBe(true);
  });

  it("finishes the restore when embedded after a cross-origin frame", async () => {
    const parentWindow = {
      0: {
        get location(): Location {
          throw new DOMException("Blocked a frame", "SecurityError");
        },
      },
      postMessage: vi.fn(),
    };
    vi.stubGlobal("parent", parentWindow);

    try {
      await restoreEntry({ textResults });
      act(() => {
        vi.runOnlyPendingTimers();
      });

      expect(isRestoringFromHistoryPubSub[2]()).toBe(false);
      expect(parentWindow.postMessage).toHaveBeenCalledWith(
        { queryString: "q=saved%20search", hash: "" },
        "https://huggingface.co",
      );
    } finally {
      vi.unstubAllGlobals();
    }
  });

  describe("chat of the search being restored", () => {
    const savedTurns: StoredTurn[] = [
      { role: "user", content: "First follow-up?" },
      { role: "assistant", content: "First answer." },
    ];
    const landedTurns: StoredTurn[] = [
      ...savedTurns,
      { role: "user", content: "Second follow-up?" },
      { role: "assistant", content: "Second answer." },
    ];

    /**
     * Restores `searchRunId` while the stored chat read is held open, and runs
     * `whileReading` before it returns `storedTurns`, the list as it was
     * before the chat's last write. Records every list the restore publishes.
     */
    async function restoreWhileChatReadIsOpen(
      searchRunId: string,
      storedTurns: StoredTurn[],
      whileReading: () => void,
    ) {
      vi.mocked(getLatestLlmResponseForEntry).mockResolvedValue(
        "Saved AI answer.",
      );
      let returnStoredTurns: (turns: StoredTurn[]) => void = () => undefined;
      vi.mocked(getChatMessagesForQuery).mockReturnValue(
        new Promise((resolve) => {
          returnStoredTurns = resolve;
        }),
      );
      const published: StoredTurn[][] = [];
      const unsubscribe = subscribeToChatMessages((messages) => {
        published.push(messages);
      });
      const { result } = renderHook(() => useHistoryRestore(vi.fn()));

      try {
        await act(async () => {
          const restoring = result.current.restoreSearch({
            query: "saved search",
            timestamp: 1,
            searchRunId,
          });
          // Let the restore reach the chat read, as far as it goes.
          for (let i = 0; i < 10; i++) await Promise.resolve();
          whileReading();
          returnStoredTurns(storedTurns);
          await restoring;
        });
      } finally {
        unsubscribe();
      }
      return published;
    }

    /** What ChatInterface's `commitMessages` publishes when an answer lands. */
    function landFollowUpAnswer() {
      updateChatMessages(landedTurns);
      updateChatGenerationState({
        isGeneratingResponse: false,
        isGeneratingFollowUpQuestion: false,
      });
    }

    it("keeps a follow-up answer that lands while the same search is restored", async () => {
      setCurrentSearchRunId("run-1");
      updateChatMessages(savedTurns);
      updateChatGenerationState({
        isGeneratingResponse: true,
        isGeneratingFollowUpQuestion: false,
      });

      const published = await restoreWhileChatReadIsOpen(
        "run-1",
        savedTurns,
        landFollowUpAnswer,
      );

      expect(getChatMessages()).toEqual(landedTurns);
      // Only the chat's own write: the restore never blanked the list or put
      // the older one back over it.
      expect(published).toEqual([landedTurns]);
    });

    it("replaces the chat with the stored one when another search is restored", async () => {
      setCurrentSearchRunId("run-1");
      updateChatMessages(landedTurns);
      updateChatGenerationState({
        isGeneratingResponse: true,
        isGeneratingFollowUpQuestion: false,
      });

      await restoreWhileChatReadIsOpen("run-2", savedTurns, () => undefined);

      expect(getChatMessagesForQuery).toHaveBeenCalledWith("run-2");
      expect(getChatMessages()).toEqual(savedTurns);
    });

    it("reloads the stored chat when the same search is restored with nothing generating", async () => {
      setCurrentSearchRunId("run-1");
      updateChatMessages([]);

      await restoreWhileChatReadIsOpen("run-1", savedTurns, () => undefined);

      expect(getChatMessagesForQuery).toHaveBeenCalledWith("run-1");
      expect(getChatMessages()).toEqual(savedTurns);
    });
  });

  it.each([
    { searchRunId: "run-2", startsNewChat: true },
    { searchRunId: "run-1", startsNewChat: false },
  ])(
    "starts a new chat session only when another search is restored ($searchRunId)",
    async ({ searchRunId, startsNewChat }) => {
      setCurrentSearchRunId("run-1");
      updateChatGenerationState({
        isGeneratingResponse: true,
        isGeneratingFollowUpQuestion: false,
      });
      const sessionBefore = getChatSession();

      await restoreEntry({ searchRunId });

      expect(getChatSession()).toBe(
        startsNewChat ? sessionBefore + 1 : sessionBefore,
      );
    },
  );
});