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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
import { act, cleanup, renderHook } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import * as historyModule from "@/modules/history";
import {
  addSearchToHistory,
  historyDatabase,
  type SearchEntry,
  type TextResults,
} from "@/modules/history";
import { getSettings } from "@/modules/pubSub";
import * as stringFormatters from "@/modules/stringFormatters";
import {
  FILTER_DEBOUNCE_MS,
  REFRESH_INTERVAL_MS,
  useSearchHistory,
} from "./useSearchHistory";

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

// Pin auto-cleanup off so seeding is deterministic and pubSub's module-level
// localStorage reads stay out of the test.
vi.mock("@/modules/pubSub", () => ({
  getSettings: vi.fn(() => ({
    historyAutoCleanup: false,
    historyRetentionDays: 30,
    historyMaxEntries: 500,
    historyGroupByDate: false,
  })),
}));

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

// "weather in lisbon" is the narrowing-trap entry: "wet" matches nothing,
// "weth" gains an insertion variant that matches it.
const SEEDED_QUERIES = [
  "weather in lisbon",
  "best pizza porto",
  "rust async tutorial",
];

const queriesOf = (entries: SearchEntry[]) => entries.map((e) => e.query);

/**
 * Fake timers exclude setImmediate/clearImmediate so fake-indexeddb keeps its
 * real scheduling and DB reads resolve on the real event loop, while the
 * debounce and the 30s interval run on the fake clock.
 */
beforeEach(async () => {
  vi.useFakeTimers({
    toFake: [
      "setTimeout",
      "clearTimeout",
      "setInterval",
      "clearInterval",
      "Date",
    ],
  });

  await historyDatabase.searches.clear();
  await historyDatabase.llmResponses.clear();
  await historyDatabase.chatHistory.clear();
  for (const query of SEEDED_QUERIES) {
    await addSearchToHistory(query, textResults);
    // Distinct, deterministic timestamps so the orderBy(timestamp).reverse()
    // read order never falls back to a tie resolved by Dexie internals.
    vi.advanceTimersByTime(1000);
  }
});

afterEach(async () => {
  cleanup();
  await act(async () => {});
  vi.useRealTimers();
  vi.restoreAllMocks();
});

async function settle() {
  await act(async () => {
    await vi.advanceTimersByTimeAsync(FILTER_DEBOUNCE_MS + 50);
  });
}

/**
 * Waits for the hook's read to finish. With includeAllPinned the read also
 * queries the `pinnedAt` index, which takes fake-indexeddb more turns of
 * the real event loop than `settle` alone gives it. setImmediate is left real
 * by the fake timers above, so each await yields one real turn; `vi.waitFor`
 * would not, since under fake timers it polls by advancing fake time.
 */
async function untilLoaded(result: {
  current: ReturnType<typeof useSearchHistory>;
}) {
  for (let turn = 0; turn < 500 && result.current.isLoading; turn++) {
    await act(async () => {
      await new Promise((resolve) => setImmediate(resolve));
    });
  }
  expect(result.current.isLoading).toBe(false);
}

/** Pins the oldest seeded entry, "weather in lisbon". */
async function pinOldestEntry() {
  const [oldest] = await historyDatabase.searches
    .orderBy("timestamp")
    .limit(1)
    .toArray();
  await historyDatabase.searches.update(oldest.id as number, {
    pinned: true,
    pinnedAt: oldest.timestamp,
  });
}

/** Adds newer searches, so the pinned entry falls out of the recent window. */
async function addNewerSearches(count: number) {
  for (let i = 1; i <= count; i++) {
    await addSearchToHistory(`newer search ${i}`, textResults);
    vi.advanceTimersByTime(1000);
  }
}

/** Renders the pinned-aware two-entry window and waits for the first load. */
async function renderPinnedAwareHistory() {
  const { result } = renderHook(() =>
    useSearchHistory({ limit: 2, includeAllPinned: true }),
  );
  await settle();
  await untilLoaded(result);
  return result;
}

describe("useSearchHistory with includeAllPinned", () => {
  it("keeps a pinned search older than the whole recent window", async () => {
    await pinOldestEntry();
    // limit 2 reads the newest 4: the pinned entry is the 7th newest.
    await addNewerSearches(4);

    const result = await renderPinnedAwareHistory();

    expect(queriesOf(result.current.filteredSearches)).toEqual([
      "newer search 4",
      "newer search 3",
      "weather in lisbon",
    ]);
  });

  it("keeps a pinned search inside the window but past the limit", async () => {
    await pinOldestEntry();

    const result = await renderPinnedAwareHistory();

    expect(queriesOf(result.current.filteredSearches)).toEqual([
      "rust async tutorial",
      "best pizza porto",
      "weather in lisbon",
    ]);
  });

  it("lets the filter find a pinned search outside the recent window", async () => {
    await pinOldestEntry();
    await addNewerSearches(4);

    const result = await renderPinnedAwareHistory();
    act(() => result.current.searchHistory("lisbon"));
    await settle();

    expect(queriesOf(result.current.filteredSearches)).toEqual([
      "weather in lisbon",
    ]);
  });

  it("still reads IndexedDB only on load, never while typing", async () => {
    await pinOldestEntry();
    const pinnedReadSpy = vi.spyOn(historyModule, "getPinnedSearches");

    const result = await renderPinnedAwareHistory();
    expect(pinnedReadSpy).toHaveBeenCalledTimes(1);

    for (const query of ["w", "we", "wea"]) {
      act(() => result.current.searchHistory(query));
      await settle();
    }

    expect(pinnedReadSpy).toHaveBeenCalledTimes(1);
  });

  it("leaves the recent window as it is without the option", async () => {
    await pinOldestEntry();
    await addNewerSearches(4);

    const { result } = renderHook(() => useSearchHistory({ limit: 2 }));
    await settle();
    await untilLoaded(result);

    expect(queriesOf(result.current.filteredSearches)).toEqual([
      "newer search 4",
      "newer search 3",
    ]);
  });
  it("pins and unpins through both fields, so the index agrees with the flag", async () => {
    const [oldest] = await historyDatabase.searches
      .orderBy("timestamp")
      .limit(1)
      .toArray();
    const id = oldest.id as number;

    const { result } = renderHook(() =>
      useSearchHistory({ limit: 2, includeAllPinned: true }),
    );
    await untilLoaded(result);

    await act(async () => {
      await result.current.togglePin(id);
    });
    const pinned = await historyDatabase.searches.get(id);
    expect(pinned?.pinned).toBe(true);
    expect(pinned?.pinnedAt).toBe(Date.now());
    expect(queriesOf(await historyModule.getPinnedSearches())).toEqual([
      "weather in lisbon",
    ]);

    await act(async () => {
      await result.current.togglePin(id);
    });
    const unpinned = await historyDatabase.searches.get(id);
    expect(unpinned?.pinned).toBe(false);
    expect(unpinned && "pinnedAt" in unpinned).toBe(false);
    expect(await historyModule.getPinnedSearches()).toEqual([]);
  });
});

describe("useSearchHistory", () => {
  it("leaves IndexedDB alone while history is turned off", async () => {
    const settingsMock = vi.mocked(getSettings);
    const historyOn = settingsMock.getMockImplementation();
    settingsMock.mockImplementation(
      () =>
        ({
          ...historyOn?.(),
          enableHistory: false,
        }) as ReturnType<typeof getSettings>,
    );
    const readSpy = vi.spyOn(historyModule, "getRecentSearches");

    try {
      const { result } = renderHook(() => useSearchHistory({ limit: 100 }));
      await settle();
      await act(async () => {
        await vi.advanceTimersByTimeAsync(REFRESH_INTERVAL_MS);
      });

      expect(readSpy).not.toHaveBeenCalled();
      expect(result.current.isLoading).toBe(false);
      expect(result.current.recentSearches).toEqual([]);
    } finally {
      if (historyOn) settingsMock.mockImplementation(historyOn);
    }
  });

  it("reads IndexedDB only on load, never while typing", async () => {
    const readSpy = vi.spyOn(historyModule, "getRecentSearches");

    const { result } = renderHook(() => useSearchHistory({ limit: 100 }));
    await settle();

    expect(result.current.isLoading).toBe(false);
    expect(result.current.recentSearches).toHaveLength(SEEDED_QUERIES.length);
    const readsAfterLoad = readSpy.mock.calls.length;
    expect(readsAfterLoad).toBe(1);

    for (const query of ["w", "we", "wet", "weather"]) {
      act(() => result.current.searchHistory(query));
      await settle();
    }

    expect(readSpy).toHaveBeenCalledTimes(readsAfterLoad);
    // The filter did run: the settled query produced matches from memory.
    // "weather" is a stable prefix that always matches, so this test does not
    // depend on the uFuzzy narrowing trap.
    expect(queriesOf(result.current.filteredSearches)).toContain(
      "weather in lisbon",
    );
  });

  it("re-scans all in-memory entries per settled query instead of narrowing", async () => {
    // Assert the uFuzzy premise directly against the seeded entries first, so
    // a future @leeoniya/ufuzzy bump that changes the per-length error rules
    // fails here, pointing at the premise, not at the hook.
    const seeded = await historyDatabase.searches.toArray();
    expect(
      stringFormatters.searchWithFuzzy(seeded, "wet", (entry) => entry.query),
    ).toHaveLength(0);
    expect(
      queriesOf(
        stringFormatters
          .searchWithFuzzy(seeded, "weth", (entry) => entry.query)
          .map((result) => result.item),
      ),
    ).toContain("weather in lisbon");

    const { result } = renderHook(() => useSearchHistory({ limit: 100 }));
    await settle();

    // The trap: under this setup's per-length uFuzzy error rules, "wet"
    // compiles to a pattern that matches nothing.
    act(() => result.current.searchHistory("wet"));
    await settle();
    expect(queriesOf(result.current.filteredSearches)).not.toContain(
      "weather in lisbon",
    );

    // Typing past the prefix gains an insertion variant that matches. A fresh
    // full scan finds it; narrowing from the previous keystroke would have
    // kept it dropped forever.
    act(() => result.current.searchHistory("weth"));
    await settle();
    expect(queriesOf(result.current.filteredSearches)).toContain(
      "weather in lisbon",
    );
  });

  it("runs one fuzzy pass per settled query, not one per keystroke", async () => {
    const fuzzySpy = vi.spyOn(stringFormatters, "searchWithFuzzy");

    const { result } = renderHook(() => useSearchHistory({ limit: 100 }));
    await settle();
    expect(fuzzySpy).not.toHaveBeenCalled();

    act(() => {
      result.current.searchHistory("w");
      result.current.searchHistory("we");
      result.current.searchHistory("wet");
      result.current.searchHistory("weth");
    });
    expect(fuzzySpy).not.toHaveBeenCalled();

    await settle();
    expect(fuzzySpy).toHaveBeenCalledTimes(1);
    expect(fuzzySpy.mock.calls[0][1]).toBe("weth");
  });

  it("keeps the 30s interval alive across keystrokes", async () => {
    const setIntervalSpy = vi.spyOn(globalThis, "setInterval");

    const { result } = renderHook(() => useSearchHistory({ limit: 100 }));
    await settle();

    const intervalsAfterMount = setIntervalSpy.mock.calls.length;
    expect(intervalsAfterMount).toBe(1);

    for (const query of ["w", "we", "wet", "weth"]) {
      act(() => result.current.searchHistory(query));
      await settle();
    }

    expect(setIntervalSpy).toHaveBeenCalledTimes(intervalsAfterMount);
  });

  it("still refreshes from IndexedDB when the 30s interval fires", async () => {
    const readSpy = vi.spyOn(historyModule, "getRecentSearches");

    const { result } = renderHook(() => useSearchHistory({ limit: 100 }));
    await settle();
    expect(readSpy).toHaveBeenCalledTimes(1);

    act(() => result.current.searchHistory("weth"));
    await settle();
    expect(readSpy).toHaveBeenCalledTimes(1);
    expect(result.current.filteredSearches).toHaveLength(1);
    expect(queriesOf(result.current.filteredSearches)).toContain(
      "weather in lisbon",
    );

    await act(async () => {
      await vi.advanceTimersByTimeAsync(REFRESH_INTERVAL_MS + 50);
    });
    expect(readSpy).toHaveBeenCalledTimes(2);
    // The active filter survives the background refresh: still one match,
    // not the full unfiltered list.
    expect(result.current.filteredSearches).toHaveLength(1);
    expect(queriesOf(result.current.filteredSearches)).toContain(
      "weather in lisbon",
    );
  });

  it("clearing the filter settles immediately, without waiting for the debounce", async () => {
    const { result } = renderHook(() => useSearchHistory({ limit: 100 }));
    await settle();

    act(() => result.current.searchHistory("weth"));
    await settle();
    expect(result.current.filteredSearches).toHaveLength(1);

    // The drawer's clear button: the full list must return on the same tick,
    // with no timer advance.
    act(() => result.current.searchHistory(""));
    expect(result.current.filteredSearches).toHaveLength(SEEDED_QUERIES.length);
  });

  it("deletes an entry's answer and chat with it and leaves the other entries' rows", async () => {
    // Seeding shares one search run; give each entry its own, as separate
    // searches have, with an answer and a chat turn stored under it.
    const entries = await historyDatabase.searches.toArray();
    for (const entry of entries) {
      const runId = `run-${entry.id}`;
      await historyDatabase.searches.update(entry.id as number, {
        searchRunId: runId,
      });
      await historyDatabase.llmResponses.add({
        searchRunId: runId,
        searchId: entry.id,
        prompt: entry.query,
        response: "answer",
        model: "m",
        timestamp: Date.now(),
      });
      await historyDatabase.chatHistory.add({
        role: "user",
        content: "chat",
        timestamp: Date.now(),
        conversationId: runId,
      });
    }
    const { result } = renderHook(() => useSearchHistory({ limit: 100 }));
    await settle();

    const [target] = entries;
    await act(async () => {
      await result.current.deleteEntry(target.id as number);
    });

    const targetRun = `run-${target.id}`;
    expect(await historyDatabase.searches.get(target.id as number)).toBe(
      undefined,
    );
    expect(
      await historyDatabase.llmResponses
        .where("searchRunId")
        .equals(targetRun)
        .count(),
    ).toBe(0);
    expect(
      await historyDatabase.chatHistory
        .where("conversationId")
        .equals(targetRun)
        .count(),
    ).toBe(0);
    expect(await historyDatabase.llmResponses.count()).toBe(entries.length - 1);
    expect(await historyDatabase.chatHistory.count()).toBe(entries.length - 1);
  });

  it("paginates from memory: page changes and queries trigger no reads", async () => {
    await addSearchToHistory("wine tasting porto", textResults);
    vi.advanceTimersByTime(1000);
    await addSearchToHistory("waterfall hike madeira", textResults);
    vi.advanceTimersByTime(1000);

    const readSpy = vi.spyOn(historyModule, "getRecentSearches");

    const { result } = renderHook(() =>
      useSearchHistory({ limit: 100, enablePagination: true, pageSize: 2 }),
    );
    await settle();

    expect(result.current.isLoading).toBe(false);
    expect(readSpy).toHaveBeenCalledTimes(1);
    expect(result.current.filteredSearches).toHaveLength(2);
    expect(result.current.totalPages).toBe(3);
    expect(result.current.hasNextPage).toBe(true);

    act(() => result.current.nextPage());
    await settle();
    expect(result.current.currentPage).toBe(1);
    expect(result.current.filteredSearches).toHaveLength(2);
    expect(readSpy).toHaveBeenCalledTimes(1);

    act(() => result.current.goToPage(0));
    await settle();

    act(() => result.current.searchHistory("w"));
    await settle();
    // Three of the five seeded queries fuzzy-match "w"; the page shows the
    // top-ranked two of them, counted over the full match set.
    const wMatches = [
      "weather in lisbon",
      "wine tasting porto",
      "waterfall hike madeira",
    ];
    expect(result.current.totalPages).toBe(2);
    expect(result.current.filteredSearches).toHaveLength(2);
    expect(wMatches).toEqual(
      expect.arrayContaining(queriesOf(result.current.filteredSearches)),
    );
    expect(readSpy).toHaveBeenCalledTimes(1);
  });
});