system HF Staff commited on
Commit
c0e51f5
ยท
verified ยท
1 Parent(s): d19ab4e

Sync from felladrin/MiniSearch@43edeee (part 2)

Browse files
server/configEndpointServerHook.test.ts CHANGED
@@ -27,6 +27,7 @@ async function requestConfig() {
27
  );
28
  return JSON.parse(end.mock.calls[0][0] as string) as {
29
  accessKeysEnabled: boolean;
 
30
  };
31
  }
32
 
@@ -45,4 +46,27 @@ describe("configEndpointServerHook", () => {
45
  vi.stubEnv("ACCESS_KEYS", " , ,");
46
  expect((await requestConfig()).accessKeysEnabled).toBe(false);
47
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  });
 
27
  );
28
  return JSON.parse(end.mock.calls[0][0] as string) as {
29
  accessKeysEnabled: boolean;
30
+ parentWindowOrigins: string[];
31
  };
32
  }
33
 
 
46
  vi.stubEnv("ACCESS_KEYS", " , ,");
47
  expect((await requestConfig()).accessKeysEnabled).toBe(false);
48
  });
49
+
50
+ it("serves the configured parent window origins as a list", async () => {
51
+ vi.stubEnv(
52
+ "PARENT_WINDOW_ORIGINS",
53
+ "https://huggingface.co, https://example.com,",
54
+ );
55
+ expect((await requestConfig()).parentWindowOrigins).toEqual([
56
+ "https://huggingface.co",
57
+ "https://example.com",
58
+ ]);
59
+ });
60
+
61
+ it("serves Hugging Face as the parent window origin when the variable is unset", async () => {
62
+ vi.stubEnv("PARENT_WINDOW_ORIGINS", undefined);
63
+ expect((await requestConfig()).parentWindowOrigins).toEqual([
64
+ "https://huggingface.co",
65
+ ]);
66
+ });
67
+
68
+ it("serves no parent window origin when the variable is empty", async () => {
69
+ vi.stubEnv("PARENT_WINDOW_ORIGINS", "");
70
+ expect((await requestConfig()).parentWindowOrigins).toEqual([]);
71
+ });
72
  });
server/configEndpointServerHook.ts CHANGED
@@ -2,6 +2,7 @@ import type { PreviewServer, ViteDevServer } from "vite";
2
  import {
3
  DEFAULT_INFERENCE_TYPE,
4
  DEFAULT_INTERNAL_API_NAME,
 
5
  DEFAULT_WLLAMA_GPU_MODEL_ID,
6
  DEFAULT_WLLAMA_MODEL_ID,
7
  type ServerConfig,
@@ -43,6 +44,12 @@ export function configEndpointServerHook<
43
  // gets the token of the server answering it, and a reload is enough to
44
  // pick up a new one.
45
  searchToken: getSearchToken(),
 
 
 
 
 
 
46
  };
47
 
48
  res.setHeader("Content-Type", "application/json");
 
2
  import {
3
  DEFAULT_INFERENCE_TYPE,
4
  DEFAULT_INTERNAL_API_NAME,
5
+ DEFAULT_PARENT_WINDOW_ORIGINS,
6
  DEFAULT_WLLAMA_GPU_MODEL_ID,
7
  DEFAULT_WLLAMA_MODEL_ID,
8
  type ServerConfig,
 
44
  // gets the token of the server answering it, and a reload is enough to
45
  // pick up a new one.
46
  searchToken: getSearchToken(),
47
+ // Only an unset variable gets the default: an empty one is how a
48
+ // deployment stops posting the query to any embedding page.
49
+ parentWindowOrigins:
50
+ process.env.PARENT_WINDOW_ORIGINS === undefined
51
+ ? DEFAULT_PARENT_WINDOW_ORIGINS
52
+ : parseCommaSeparatedList(process.env.PARENT_WINDOW_ORIGINS),
53
  };
54
 
55
  res.setHeader("Content-Type", "application/json");
server/fallbackSearchService.test.ts CHANGED
@@ -86,6 +86,10 @@ function youcomDocumentWith(web: unknown[]): string {
86
  return toolReply({ results: { web } });
87
  }
88
 
 
 
 
 
89
  const PARALLEL_URL = "https://search.parallel.ai/mcp";
90
  const YOUCOM_KEYLESS_URL = "https://api.you.com/mcp?profile=free";
91
  const YOUCOM_AUTHENTICATED_URL = "https://api.you.com/mcp";
@@ -1303,8 +1307,9 @@ function listProviders(value: string | undefined) {
1303
  else process.env[PROVIDERS_VARIABLE] = value;
1304
  }
1305
 
1306
- // Fisher-Yates over the two built-in providers draws once: 0 swaps them,
1307
- // anything near 1 keeps the table's order.
 
1308
  function orderYoucomFirst() {
1309
  return vi.spyOn(Math, "random").mockReturnValue(0);
1310
  }
@@ -1337,11 +1342,12 @@ describe("configuration", () => {
1337
  orderParallelFirst();
1338
  mockExchange(documentWith([]));
1339
  mockYoucom([]);
 
1340
 
1341
  await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);
1342
 
1343
  expect(new Set(requestUrls())).toEqual(
1344
- new Set([PARALLEL_URL, YOUCOM_KEYLESS_URL]),
1345
  );
1346
  });
1347
 
@@ -1431,24 +1437,28 @@ describe("configuration", () => {
1431
  orderParallelFirst();
1432
  mockExchange(documentWith([]));
1433
  mockYoucom([]);
 
1434
 
1435
  await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);
1436
 
1437
- // Parallel's three requests carry its key; You.com, with no key of its
1438
- // own, stays on the keyless profile and is never sent Parallel's.
 
1439
  expect(requestUrls()).toEqual([
1440
  PARALLEL_URL,
1441
  PARALLEL_URL,
1442
  PARALLEL_URL,
1443
  YOUCOM_KEYLESS_URL,
1444
  YOUCOM_KEYLESS_URL,
 
 
1445
  ]);
1446
  for (const index of [0, 1, 2]) {
1447
  expect(requestHeaders(index).Authorization).toBe(
1448
  "Bearer parallel-test-value",
1449
  );
1450
  }
1451
- for (const index of [3, 4]) {
1452
  expect(requestHeaders(index).Authorization).toBeUndefined();
1453
  }
1454
  });
@@ -1541,6 +1551,7 @@ describe("the cascade", () => {
1541
  orderParallelFirst();
1542
  fetchMock.mockResolvedValueOnce(createMockResponse("", { status: 500 }));
1543
  fetchMock.mockResolvedValueOnce(createMockResponse("", { status: 503 }));
 
1544
 
1545
  const error = (await fetchFallbackTextResults(
1546
  QUERY,
@@ -1549,7 +1560,7 @@ describe("the cascade", () => {
1549
  ).catch((thrown: unknown) => thrown)) as Error;
1550
 
1551
  expect(error.message).toBe(
1552
- "Every fallback search provider failed (parallel: The fallback search endpoint did not answer the initialize request (status 500); youcom: The fallback search endpoint did not answer the initialize request (status 503))",
1553
  );
1554
  expect(error.message).not.toContain(QUERY);
1555
  });
@@ -1591,6 +1602,7 @@ describe("the cascade", () => {
1591
  it("gives each attempt an equal share of what is left of the budget", async () => {
1592
  vi.useFakeTimers({ toFake: ["Date"] });
1593
  vi.setSystemTime(1_000_000);
 
1594
  orderParallelFirst();
1595
  const timeoutSpy = vi.spyOn(AbortSignal, "timeout");
1596
  // The first provider spends a second before it fails, so the second one
@@ -1608,6 +1620,7 @@ describe("the cascade", () => {
1608
 
1609
  it("splits the module's own cap when the caller offers more", async () => {
1610
  vi.useFakeTimers({ toFake: ["Date"] });
 
1611
  orderParallelFirst();
1612
  const timeoutSpy = vi.spyOn(AbortSignal, "timeout");
1613
  mockExchange(
@@ -1631,7 +1644,7 @@ describe("the cascade", () => {
1631
  });
1632
 
1633
  await expect(fetchFallbackTextResults(QUERY, 10, 3_000)).rejects.toThrow(
1634
- "No fallback search provider served the search (parallel: Network failure; not tried, the time budget ran out: youcom)",
1635
  );
1636
  expect(fetchMock).toHaveBeenCalledTimes(1);
1637
  });
@@ -1777,14 +1790,15 @@ describe("pausing a rate-limited provider", () => {
1777
  throw new Error("Network failure");
1778
  });
1779
  fetchMock.mockResolvedValueOnce(rateLimited({ "retry-after": "3600" }));
 
1780
 
1781
  await expect(
1782
  fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),
1783
  ).rejects.toThrow(
1784
- "Every fallback search provider failed (parallel: Network failure)",
1785
  );
1786
 
1787
- expect(fetchMock).toHaveBeenCalledTimes(2);
1788
  expect(getFallbackProviderStats().youcom).toMatchObject({
1789
  rateLimited: 1,
1790
  skippedWhilePaused: 1,
@@ -1814,7 +1828,7 @@ describe("pausing a rate-limited provider", () => {
1814
  listProviders("youcom");
1815
  await hitRateLimit();
1816
 
1817
- listProviders(undefined);
1818
  orderParallelFirst();
1819
  const timeoutSpy = vi.spyOn(AbortSignal, "timeout");
1820
  mockExchange(
@@ -1885,6 +1899,7 @@ describe("pausing a rate-limited provider", () => {
1885
  orderParallelFirst();
1886
  fetchMock.mockResolvedValueOnce(rateLimited());
1887
  fetchMock.mockResolvedValueOnce(rateLimited());
 
1888
  await expect(
1889
  fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),
1890
  ).rejects.toThrow("Every fallback search provider failed");
@@ -1917,27 +1932,28 @@ describe("getFallbackProviderStats", () => {
1917
 
1918
  describe("Keenable", () => {
1919
  const KEENABLE_KEY_VARIABLE = "SEARCH_FALLBACK_KEENABLE_API_KEY";
1920
- const keenableDocumentWith = (results: unknown[]) =>
1921
- toolReply({ query: QUERY, mode: "pro", results });
1922
  const runKeenable = async (results: unknown[], limit = 10) => {
1923
  process.env.SEARCH_FALLBACK_PROVIDERS = "keenable";
1924
  mockExchange(keenableDocumentWith(results), { initializeSession: null });
1925
  return fetchFallbackTextResults(QUERY, limit, FULL_BUDGET_MS);
1926
  };
1927
 
1928
- it("is left out of the default list while it has no key", async () => {
1929
  delete process.env.SEARCH_FALLBACK_PROVIDERS;
1930
  vi.spyOn(Math, "random").mockReturnValue(0.99);
1931
  mockExchange(documentWith([]));
1932
  mockExchange(youcomDocumentWith([]), { initializeSession: null });
 
1933
 
1934
  await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);
1935
 
1936
  const urls = fetchMock.mock.calls.map(([requestUrl]) => String(requestUrl));
1937
- expect(new Set(urls)).toEqual(new Set([PARALLEL_URL, YOUCOM_KEYLESS_URL]));
 
 
1938
  });
1939
 
1940
- it("joins the default list when its key is set", async () => {
1941
  delete process.env.SEARCH_FALLBACK_PROVIDERS;
1942
  process.env[KEENABLE_KEY_VARIABLE] = "keenable-test-value";
1943
  vi.spyOn(Math, "random").mockReturnValue(0.99);
 
86
  return toolReply({ results: { web } });
87
  }
88
 
89
+ function keenableDocumentWith(results: unknown[]): string {
90
+ return toolReply({ query: QUERY, mode: "pro", results });
91
+ }
92
+
93
  const PARALLEL_URL = "https://search.parallel.ai/mcp";
94
  const YOUCOM_KEYLESS_URL = "https://api.you.com/mcp?profile=free";
95
  const YOUCOM_AUTHENTICATED_URL = "https://api.you.com/mcp";
 
1307
  else process.env[PROVIDERS_VARIABLE] = value;
1308
  }
1309
 
1310
+ // Fisher-Yates over the three built-in providers draws twice: 0 rotates the
1311
+ // last item to the front (You.com), anything near 1 keeps the table's order
1312
+ // (Parallel).
1313
  function orderYoucomFirst() {
1314
  return vi.spyOn(Math, "random").mockReturnValue(0);
1315
  }
 
1342
  orderParallelFirst();
1343
  mockExchange(documentWith([]));
1344
  mockYoucom([]);
1345
+ mockExchange(keenableDocumentWith([]), { initializeSession: null });
1346
 
1347
  await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);
1348
 
1349
  expect(new Set(requestUrls())).toEqual(
1350
+ new Set([PARALLEL_URL, YOUCOM_KEYLESS_URL, KEENABLE_KEYLESS_URL]),
1351
  );
1352
  });
1353
 
 
1437
  orderParallelFirst();
1438
  mockExchange(documentWith([]));
1439
  mockYoucom([]);
1440
+ mockExchange(keenableDocumentWith([]), { initializeSession: null });
1441
 
1442
  await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);
1443
 
1444
+ // Parallel's three requests carry its key; You.com and Keenable, with no
1445
+ // key of their own, stay on their keyless endpoints and are never sent
1446
+ // Parallel's.
1447
  expect(requestUrls()).toEqual([
1448
  PARALLEL_URL,
1449
  PARALLEL_URL,
1450
  PARALLEL_URL,
1451
  YOUCOM_KEYLESS_URL,
1452
  YOUCOM_KEYLESS_URL,
1453
+ KEENABLE_KEYLESS_URL,
1454
+ KEENABLE_KEYLESS_URL,
1455
  ]);
1456
  for (const index of [0, 1, 2]) {
1457
  expect(requestHeaders(index).Authorization).toBe(
1458
  "Bearer parallel-test-value",
1459
  );
1460
  }
1461
+ for (const index of [3, 4, 5, 6]) {
1462
  expect(requestHeaders(index).Authorization).toBeUndefined();
1463
  }
1464
  });
 
1551
  orderParallelFirst();
1552
  fetchMock.mockResolvedValueOnce(createMockResponse("", { status: 500 }));
1553
  fetchMock.mockResolvedValueOnce(createMockResponse("", { status: 503 }));
1554
+ fetchMock.mockResolvedValueOnce(createMockResponse("", { status: 502 }));
1555
 
1556
  const error = (await fetchFallbackTextResults(
1557
  QUERY,
 
1560
  ).catch((thrown: unknown) => thrown)) as Error;
1561
 
1562
  expect(error.message).toBe(
1563
+ "Every fallback search provider failed (parallel: The fallback search endpoint did not answer the initialize request (status 500); youcom: The fallback search endpoint did not answer the initialize request (status 503); keenable: The fallback search endpoint did not answer the initialize request (status 502))",
1564
  );
1565
  expect(error.message).not.toContain(QUERY);
1566
  });
 
1602
  it("gives each attempt an equal share of what is left of the budget", async () => {
1603
  vi.useFakeTimers({ toFake: ["Date"] });
1604
  vi.setSystemTime(1_000_000);
1605
+ listProviders("parallel,youcom");
1606
  orderParallelFirst();
1607
  const timeoutSpy = vi.spyOn(AbortSignal, "timeout");
1608
  // The first provider spends a second before it fails, so the second one
 
1620
 
1621
  it("splits the module's own cap when the caller offers more", async () => {
1622
  vi.useFakeTimers({ toFake: ["Date"] });
1623
+ listProviders("parallel,youcom");
1624
  orderParallelFirst();
1625
  const timeoutSpy = vi.spyOn(AbortSignal, "timeout");
1626
  mockExchange(
 
1644
  });
1645
 
1646
  await expect(fetchFallbackTextResults(QUERY, 10, 3_000)).rejects.toThrow(
1647
+ "No fallback search provider served the search (parallel: Network failure; not tried, the time budget ran out: youcom, keenable)",
1648
  );
1649
  expect(fetchMock).toHaveBeenCalledTimes(1);
1650
  });
 
1790
  throw new Error("Network failure");
1791
  });
1792
  fetchMock.mockResolvedValueOnce(rateLimited({ "retry-after": "3600" }));
1793
+ fetchMock.mockResolvedValueOnce(createMockResponse("", { status: 502 }));
1794
 
1795
  await expect(
1796
  fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),
1797
  ).rejects.toThrow(
1798
+ "Every fallback search provider failed (parallel: Network failure; keenable: The fallback search endpoint did not answer the initialize request (status 502))",
1799
  );
1800
 
1801
+ expect(fetchMock).toHaveBeenCalledTimes(3);
1802
  expect(getFallbackProviderStats().youcom).toMatchObject({
1803
  rateLimited: 1,
1804
  skippedWhilePaused: 1,
 
1828
  listProviders("youcom");
1829
  await hitRateLimit();
1830
 
1831
+ listProviders("parallel,youcom");
1832
  orderParallelFirst();
1833
  const timeoutSpy = vi.spyOn(AbortSignal, "timeout");
1834
  mockExchange(
 
1899
  orderParallelFirst();
1900
  fetchMock.mockResolvedValueOnce(rateLimited());
1901
  fetchMock.mockResolvedValueOnce(rateLimited());
1902
+ fetchMock.mockResolvedValueOnce(rateLimited());
1903
  await expect(
1904
  fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS),
1905
  ).rejects.toThrow("Every fallback search provider failed");
 
1932
 
1933
  describe("Keenable", () => {
1934
  const KEENABLE_KEY_VARIABLE = "SEARCH_FALLBACK_KEENABLE_API_KEY";
 
 
1935
  const runKeenable = async (results: unknown[], limit = 10) => {
1936
  process.env.SEARCH_FALLBACK_PROVIDERS = "keenable";
1937
  mockExchange(keenableDocumentWith(results), { initializeSession: null });
1938
  return fetchFallbackTextResults(QUERY, limit, FULL_BUDGET_MS);
1939
  };
1940
 
1941
+ it("joins the default list on the keyless endpoint when it has no key", async () => {
1942
  delete process.env.SEARCH_FALLBACK_PROVIDERS;
1943
  vi.spyOn(Math, "random").mockReturnValue(0.99);
1944
  mockExchange(documentWith([]));
1945
  mockExchange(youcomDocumentWith([]), { initializeSession: null });
1946
+ mockExchange(keenableDocumentWith([]), { initializeSession: null });
1947
 
1948
  await fetchFallbackTextResults(QUERY, 10, FULL_BUDGET_MS);
1949
 
1950
  const urls = fetchMock.mock.calls.map(([requestUrl]) => String(requestUrl));
1951
+ expect(new Set(urls)).toEqual(
1952
+ new Set([PARALLEL_URL, YOUCOM_KEYLESS_URL, KEENABLE_KEYLESS_URL]),
1953
+ );
1954
  });
1955
 
1956
+ it("uses the authenticated endpoint when its key is set", async () => {
1957
  delete process.env.SEARCH_FALLBACK_PROVIDERS;
1958
  process.env[KEENABLE_KEY_VARIABLE] = "keenable-test-value";
1959
  vi.spyOn(Math, "random").mockReturnValue(0.99);
server/fallbackSearchService.ts CHANGED
@@ -1,6 +1,7 @@
1
  import { randomUUID } from "node:crypto";
2
  import { basename } from "node:path";
3
  import debug from "debug";
 
4
  import { rememberSearchExcerpts } from "./searchExcerptStore.ts";
5
  import { isOpenableUrl } from "./utils/openableUrl.ts";
6
 
@@ -87,12 +88,6 @@ interface MappedResults {
87
  interface FallbackProvider {
88
  name: ProviderName;
89
  apiKeyVariable: string;
90
- /**
91
- * Left out of the default list: tried only when SEARCH_FALLBACK_PROVIDERS
92
- * names it or its key is set, so adding it changes nothing for an instance
93
- * that already runs the fallback.
94
- */
95
- optIn?: boolean;
96
  endpointUrl: (apiKey: string) => string;
97
  /** The headers that carry the key, and any the provider needs on every request. Bearer when absent. */
98
  headers?: (apiKey: string) => Record<string, string>;
@@ -138,7 +133,6 @@ const PROVIDERS: readonly FallbackProvider[] = [
138
  {
139
  name: "keenable",
140
  apiKeyVariable: "SEARCH_FALLBACK_KEENABLE_API_KEY",
141
- optIn: true,
142
  endpointUrl: (apiKey) =>
143
  apiKey
144
  ? "https://api.keenable.ai/mcp"
@@ -256,12 +250,7 @@ function readConfiguredProviders(): FallbackProvider[] {
256
  }
257
 
258
  const value = process.env.SEARCH_FALLBACK_PROVIDERS ?? "";
259
- if (value.trim() === "") {
260
- return PROVIDERS.filter(
261
- ({ optIn, apiKeyVariable }) =>
262
- !optIn || (process.env[apiKeyVariable] ?? "").trim() !== "",
263
- );
264
- }
265
 
266
  const names = value
267
  .split(",")
@@ -424,14 +413,6 @@ function countFor(name: ProviderName): ProviderCounters {
424
  return providerCounters.get(name) as ProviderCounters;
425
  }
426
 
427
- function shuffle<Item>(items: Item[]): Item[] {
428
- for (let index = items.length - 1; index > 0; index--) {
429
- const swapIndex = Math.floor(Math.random() * (index + 1));
430
- [items[index], items[swapIndex]] = [items[swapIndex], items[index]];
431
- }
432
- return items;
433
- }
434
-
435
  // RFC 9110's IMF-fixdate. Date.parse alone is too lenient: V8 turns strings
436
  // such as "1.5" or "-1" into dates in 2001, which would clamp to the minimum
437
  // pause instead of the default an unreadable value gets. The two obsolete
 
1
  import { randomUUID } from "node:crypto";
2
  import { basename } from "node:path";
3
  import debug from "debug";
4
+ import { shuffle } from "../shared/shuffle.ts";
5
  import { rememberSearchExcerpts } from "./searchExcerptStore.ts";
6
  import { isOpenableUrl } from "./utils/openableUrl.ts";
7
 
 
88
  interface FallbackProvider {
89
  name: ProviderName;
90
  apiKeyVariable: string;
 
 
 
 
 
 
91
  endpointUrl: (apiKey: string) => string;
92
  /** The headers that carry the key, and any the provider needs on every request. Bearer when absent. */
93
  headers?: (apiKey: string) => Record<string, string>;
 
133
  {
134
  name: "keenable",
135
  apiKeyVariable: "SEARCH_FALLBACK_KEENABLE_API_KEY",
 
136
  endpointUrl: (apiKey) =>
137
  apiKey
138
  ? "https://api.keenable.ai/mcp"
 
250
  }
251
 
252
  const value = process.env.SEARCH_FALLBACK_PROVIDERS ?? "";
253
+ if (value.trim() === "") return [...PROVIDERS];
 
 
 
 
 
254
 
255
  const names = value
256
  .split(",")
 
413
  return providerCounters.get(name) as ProviderCounters;
414
  }
415
 
 
 
 
 
 
 
 
 
416
  // RFC 9110's IMF-fixdate. Date.parse alone is too lenient: V8 turns strings
417
  // such as "1.5" or "-1" into dates in 2001, which would clamp to the minimum
418
  // pause instead of the default an unreadable value gets. The two obsolete
server/inferencesSinceLastRestart.test.ts ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+
3
+ // The counters are module state that lasts for the process, and these cases
4
+ // assert absolute values, so each one starts from a freshly imported module.
5
+ async function loadCounters() {
6
+ vi.resetModules();
7
+ return import("./inferencesSinceLastRestart.ts");
8
+ }
9
+
10
+ describe("byModel stats", () => {
11
+ beforeEach(() => {
12
+ vi.resetModules();
13
+ });
14
+
15
+ it("publishes the counters as an array in the configured model order, zero-filling models that were never tried", async () => {
16
+ const counters = await loadCounters();
17
+ counters.recordModelAttempt("second");
18
+ counters.recordModelStreamed("second");
19
+
20
+ const stats = counters.getInferenceStats(["first", "second"]);
21
+
22
+ expect(stats.byModel).toEqual([
23
+ { attempted: 0, streamed: 0, failed: 0, abandoned: 0 },
24
+ { attempted: 1, streamed: 1, failed: 0, abandoned: 0 },
25
+ ]);
26
+ });
27
+
28
+ it("publishes no model names, only the four counters per entry", async () => {
29
+ const counters = await loadCounters();
30
+ counters.recordModelAttempt("secret-model");
31
+
32
+ const stats = counters.getInferenceStats();
33
+
34
+ expect(stats.byModel).toHaveLength(1);
35
+ expect(Object.keys(stats.byModel[0]).sort()).toEqual([
36
+ "abandoned",
37
+ "attempted",
38
+ "failed",
39
+ "streamed",
40
+ ]);
41
+ });
42
+
43
+ it("keeps counters for a model outside the configured list instead of dropping them", async () => {
44
+ const counters = await loadCounters();
45
+ counters.recordModelAttempt("listed");
46
+ counters.recordModelAttempt("unlisted");
47
+ counters.recordModelAttempt("unlisted");
48
+
49
+ const stats = counters.getInferenceStats(["listed"]);
50
+
51
+ expect(stats.byModel).toEqual([
52
+ { attempted: 1, streamed: 0, failed: 0, abandoned: 0 },
53
+ { attempted: 2, streamed: 0, failed: 0, abandoned: 0 },
54
+ ]);
55
+ });
56
+
57
+ it("lists a model named twice in the configured list once", async () => {
58
+ const counters = await loadCounters();
59
+ counters.recordModelAttempt("dup");
60
+
61
+ const stats = counters.getInferenceStats(["dup", "dup"]);
62
+
63
+ expect(stats.byModel).toHaveLength(1);
64
+ expect(stats.byModel[0].attempted).toBe(1);
65
+ });
66
+
67
+ it("falls back to first-seen order when no configured order is given", async () => {
68
+ const counters = await loadCounters();
69
+ counters.recordModelAttempt("beta");
70
+ counters.recordModelAttempt("alpha");
71
+ counters.recordModelStreamed("beta");
72
+
73
+ const stats = counters.getInferenceStats();
74
+
75
+ expect(stats.byModel).toEqual([
76
+ { attempted: 1, streamed: 1, failed: 0, abandoned: 0 },
77
+ { attempted: 1, streamed: 0, failed: 0, abandoned: 0 },
78
+ ]);
79
+ });
80
+ });
server/inferencesSinceLastRestart.ts CHANGED
@@ -2,8 +2,11 @@
2
  * Counts and durations only. The obvious thing to record about an inference is
3
  * the conversation, and that is the whole of what the user typed, so none of it
4
  * is kept: no prompt, no message, no answer, no token, and no timestamp per
5
- * request. Model ids are configuration rather than user data, and the endpoint
6
- * already sends them to the browser in every chunk, so those are named.
 
 
 
7
  */
8
 
9
  /**
@@ -63,6 +66,10 @@ function countsFor(model: string): ModelCounts {
63
  return created;
64
  }
65
 
 
 
 
 
66
  export function recordModelAttempt(model: string): void {
67
  countsFor(model).attempted++;
68
  }
@@ -150,13 +157,33 @@ export function recordInference({
150
  }
151
  }
152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  /**
154
  * Every outcome sums to `requests`, so a request that stops being recorded
155
  * shows up as a gap rather than being lost silently. `outcomes.unclassified` is
156
  * that gap made visible: it should always be zero, and a non-zero value means
157
  * a path through the handler no longer reports what it did.
158
  */
159
- export function getInferenceStats() {
160
  const { streamed, ...failed } = outcomes;
161
  const requests = Object.values(outcomes).reduce(
162
  (total, count) => total + count,
@@ -182,8 +209,6 @@ export function getInferenceStats() {
182
  streamsEndedWithoutFinish,
183
  attemptFailures: { ...attemptFailures },
184
  failed,
185
- byModel: Object.fromEntries(
186
- [...byModel].map(([model, counts]) => [model, { ...counts }]),
187
- ),
188
  };
189
  }
 
2
  * Counts and durations only. The obvious thing to record about an inference is
3
  * the conversation, and that is the whole of what the user typed, so none of it
4
  * is kept: no prompt, no message, no answer, no token, and no timestamp per
5
+ * request. Model ids are not published either: `/status` needs no token, and
6
+ * naming the internal pool would hand whoever probes it the list of upstream
7
+ * models to target, which with a random-model pool is the upstream's whole
8
+ * catalog. The per-model counters come out as an array in the configured
9
+ * order instead, so the operator can still map each entry to a model.
10
  */
11
 
12
  /**
 
66
  return created;
67
  }
68
 
69
+ function zeroCounts(): ModelCounts {
70
+ return { attempted: 0, streamed: 0, failed: 0, abandoned: 0 };
71
+ }
72
+
73
  export function recordModelAttempt(model: string): void {
74
  countsFor(model).attempted++;
75
  }
 
157
  }
158
  }
159
 
160
+ /**
161
+ * The per-model counters as an array, never keyed by model name: `/status`
162
+ * needs no token. With the configured list given, entry *i* is the model at
163
+ * position *i* of that list (duplicates listed once), zero-filled when that
164
+ * model has not been tried, so an operator who knows their own list can still
165
+ * read a dead member of the pool out of it. Counters for a model outside the
166
+ * list are appended after it rather than dropped. With no list (the random
167
+ * pool), the entries follow first-seen order, stable for the process.
168
+ */
169
+ function byModelArray(modelOrder: string[]): ModelCounts[] {
170
+ const listed = new Set(modelOrder);
171
+ const entries = [...listed].map((model) => ({
172
+ ...(byModel.get(model) ?? zeroCounts()),
173
+ }));
174
+ for (const [model, counts] of byModel) {
175
+ if (!listed.has(model)) entries.push({ ...counts });
176
+ }
177
+ return entries;
178
+ }
179
+
180
  /**
181
  * Every outcome sums to `requests`, so a request that stops being recorded
182
  * shows up as a gap rather than being lost silently. `outcomes.unclassified` is
183
  * that gap made visible: it should always be zero, and a non-zero value means
184
  * a path through the handler no longer reports what it did.
185
  */
186
+ export function getInferenceStats(modelOrder: string[] = []) {
187
  const { streamed, ...failed } = outcomes;
188
  const requests = Object.values(outcomes).reduce(
189
  (total, count) => total + count,
 
209
  streamsEndedWithoutFinish,
210
  attemptFailures: { ...attemptFailures },
211
  failed,
212
+ byModel: byModelArray(modelOrder),
 
 
213
  };
214
  }
server/internalApiEndpointServerHook.test.ts CHANGED
@@ -1310,7 +1310,7 @@ describe("internalApiEndpointServerHook", () => {
1310
  });
1311
 
1312
  it("counts a finished answer under its model", async () => {
1313
- const before = getInferenceStats();
1314
  vi.mocked(streamText).mockImplementation(
1315
  () =>
1316
  streamOf([
@@ -1321,15 +1321,15 @@ describe("internalApiEndpointServerHook", () => {
1321
 
1322
  await callInference();
1323
 
1324
- const after = getInferenceStats();
1325
  expect(after.streamed).toBe(before.streamed + 1);
1326
  expect(after.requests).toBe(before.requests + 1);
1327
  expect(after.averageAttempts).toBeGreaterThan(0);
1328
- expect(after.byModel["test-model"].attempted).toBe(
1329
- (before.byModel["test-model"]?.attempted ?? 0) + 1,
1330
  );
1331
- expect(after.byModel["test-model"].streamed).toBe(
1332
- (before.byModel["test-model"]?.streamed ?? 0) + 1,
1333
  );
1334
  });
1335
 
@@ -1356,7 +1356,7 @@ describe("internalApiEndpointServerHook", () => {
1356
  });
1357
 
1358
  it("counts an attempt the client walked away from mid-answer", async () => {
1359
- const before = getInferenceStats();
1360
  const response = createResponse();
1361
  const mutable = response as {
1362
  writableEnded: boolean;
@@ -1379,25 +1379,23 @@ describe("internalApiEndpointServerHook", () => {
1379
 
1380
  await callInference(response);
1381
 
1382
- const after = getInferenceStats();
1383
  expect(after.failed.abandoned).toBe(before.failed.abandoned + 1);
1384
- const model = after.byModel["test-model"];
1385
- expect(model.abandoned).toBe(
1386
- (before.byModel["test-model"]?.abandoned ?? 0) + 1,
1387
- );
1388
  expect(model.attempted).toBe(
1389
  model.streamed + model.failed + model.abandoned,
1390
  );
1391
  });
1392
 
1393
  it("counts an exhausted ladder as a failure before the first token", async () => {
1394
- const before = getInferenceStats();
1395
  vi.mocked(streamText).mockImplementation(() => streamOf([]) as never);
1396
 
1397
  const response = await callInference();
1398
 
1399
  expect(response.statusCode).toBe(503);
1400
- const after = getInferenceStats();
1401
  expect(after.failed.failedBeforeFirstToken).toBe(
1402
  before.failed.failedBeforeFirstToken + 1,
1403
  );
@@ -1405,8 +1403,8 @@ describe("internalApiEndpointServerHook", () => {
1405
  expect(after.streamsEndedWithoutFinish).toBe(
1406
  before.streamsEndedWithoutFinish + 2,
1407
  );
1408
- expect(after.byModel["test-model"].failed).toBe(
1409
- (before.byModel["test-model"]?.failed ?? 0) + 2,
1410
  );
1411
  // A retry of the same model is not a move to another model.
1412
  expect(after.modelFallbacks).toBe(before.modelFallbacks);
@@ -1468,7 +1466,7 @@ describe("internalApiEndpointServerHook", () => {
1468
  });
1469
 
1470
  it("counts a fallback to another model", async () => {
1471
- const before = getInferenceStats();
1472
  vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);
1473
  vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([
1474
  { id: "model-a" },
@@ -1504,13 +1502,13 @@ describe("internalApiEndpointServerHook", () => {
1504
  vi.useRealTimers();
1505
  }
1506
 
1507
- const after = getInferenceStats();
1508
  expect(after.modelFallbacks).toBe(before.modelFallbacks + 1);
1509
- expect(after.byModel["model-a"].failed).toBe(
1510
- (before.byModel["model-a"]?.failed ?? 0) + 1,
1511
  );
1512
- expect(after.byModel["model-b"].streamed).toBe(
1513
- (before.byModel["model-b"]?.streamed ?? 0) + 1,
1514
  );
1515
  expect(after.streamed).toBe(before.streamed + 1);
1516
  });
 
1310
  });
1311
 
1312
  it("counts a finished answer under its model", async () => {
1313
+ const before = getInferenceStats(["test-model"]);
1314
  vi.mocked(streamText).mockImplementation(
1315
  () =>
1316
  streamOf([
 
1321
 
1322
  await callInference();
1323
 
1324
+ const after = getInferenceStats(["test-model"]);
1325
  expect(after.streamed).toBe(before.streamed + 1);
1326
  expect(after.requests).toBe(before.requests + 1);
1327
  expect(after.averageAttempts).toBeGreaterThan(0);
1328
+ expect(after.byModel[0].attempted).toBe(
1329
+ (before.byModel[0]?.attempted ?? 0) + 1,
1330
  );
1331
+ expect(after.byModel[0].streamed).toBe(
1332
+ (before.byModel[0]?.streamed ?? 0) + 1,
1333
  );
1334
  });
1335
 
 
1356
  });
1357
 
1358
  it("counts an attempt the client walked away from mid-answer", async () => {
1359
+ const before = getInferenceStats(["test-model"]);
1360
  const response = createResponse();
1361
  const mutable = response as {
1362
  writableEnded: boolean;
 
1379
 
1380
  await callInference(response);
1381
 
1382
+ const after = getInferenceStats(["test-model"]);
1383
  expect(after.failed.abandoned).toBe(before.failed.abandoned + 1);
1384
+ const model = after.byModel[0];
1385
+ expect(model.abandoned).toBe((before.byModel[0]?.abandoned ?? 0) + 1);
 
 
1386
  expect(model.attempted).toBe(
1387
  model.streamed + model.failed + model.abandoned,
1388
  );
1389
  });
1390
 
1391
  it("counts an exhausted ladder as a failure before the first token", async () => {
1392
+ const before = getInferenceStats(["test-model"]);
1393
  vi.mocked(streamText).mockImplementation(() => streamOf([]) as never);
1394
 
1395
  const response = await callInference();
1396
 
1397
  expect(response.statusCode).toBe(503);
1398
+ const after = getInferenceStats(["test-model"]);
1399
  expect(after.failed.failedBeforeFirstToken).toBe(
1400
  before.failed.failedBeforeFirstToken + 1,
1401
  );
 
1403
  expect(after.streamsEndedWithoutFinish).toBe(
1404
  before.streamsEndedWithoutFinish + 2,
1405
  );
1406
+ expect(after.byModel[0].failed).toBe(
1407
+ (before.byModel[0]?.failed ?? 0) + 2,
1408
  );
1409
  // A retry of the same model is not a move to another model.
1410
  expect(after.modelFallbacks).toBe(before.modelFallbacks);
 
1466
  });
1467
 
1468
  it("counts a fallback to another model", async () => {
1469
+ const before = getInferenceStats(["model-a", "model-b"]);
1470
  vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);
1471
  vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([
1472
  { id: "model-a" },
 
1502
  vi.useRealTimers();
1503
  }
1504
 
1505
+ const after = getInferenceStats(["model-a", "model-b"]);
1506
  expect(after.modelFallbacks).toBe(before.modelFallbacks + 1);
1507
+ expect(after.byModel[0].failed).toBe(
1508
+ (before.byModel[0]?.failed ?? 0) + 1,
1509
  );
1510
+ expect(after.byModel[1].streamed).toBe(
1511
+ (before.byModel[1]?.streamed ?? 0) + 1,
1512
  );
1513
  expect(after.streamed).toBe(before.streamed + 1);
1514
  });
server/pageContentService.test.ts CHANGED
@@ -7,12 +7,20 @@ vi.mock("./biEncoderService.ts", () => ({ scorePassages: scorePassagesMock }));
7
  const lookupMock = vi.hoisted(() => vi.fn());
8
  const pdfGetTextMock = vi.hoisted(() => vi.fn());
9
  const pdfDestroyMock = vi.hoisted(() => vi.fn());
 
10
 
11
  vi.mock("node:dns/promises", () => ({
12
  default: { lookup: lookupMock },
13
  lookup: lookupMock,
14
  }));
15
 
 
 
 
 
 
 
 
16
  vi.mock("pdf-parse", () => ({
17
  PDFParse: class {
18
  getText = pdfGetTextMock;
@@ -1526,3 +1534,91 @@ describe("dense passage fusion", () => {
1526
  },
1527
  );
1528
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  const lookupMock = vi.hoisted(() => vi.fn());
8
  const pdfGetTextMock = vi.hoisted(() => vi.fn());
9
  const pdfDestroyMock = vi.hoisted(() => vi.fn());
10
+ const htmlToTextConvertMock = vi.hoisted(() => vi.fn());
11
 
12
  vi.mock("node:dns/promises", () => ({
13
  default: { lookup: lookupMock },
14
  lookup: lookupMock,
15
  }));
16
 
17
+ // Runs the real converter unless a case makes it throw once.
18
+ vi.mock("html-to-text", async (importOriginal) => {
19
+ const actual = await importOriginal<typeof import("html-to-text")>();
20
+ htmlToTextConvertMock.mockImplementation(actual.convert);
21
+ return { ...actual, convert: htmlToTextConvertMock };
22
+ });
23
+
24
  vi.mock("pdf-parse", () => ({
25
  PDFParse: class {
26
  getText = pdfGetTextMock;
 
1534
  },
1535
  );
1536
  });
1537
+
1538
+ describe("pages that arrive but cannot be parsed", () => {
1539
+ const pdfResponse = () =>
1540
+ new Response("%PDF-1.7\n%%EOF", {
1541
+ status: 200,
1542
+ headers: { "content-type": "application/pdf" },
1543
+ });
1544
+
1545
+ it("counts a PDF whose text extraction rejects as unparsable, not failed", async () => {
1546
+ pdfGetTextMock.mockRejectedValue(new Error("No password given"));
1547
+ fetchMock.mockImplementation(async () => pdfResponse());
1548
+
1549
+ expect(
1550
+ (await countOutcomes("https://example.com/locked.pdf")).skipped,
1551
+ ).toEqual({ unparsable: 1 });
1552
+ expect(pdfDestroyMock).toHaveBeenCalledTimes(1);
1553
+ });
1554
+
1555
+ it("does not box a host over documents it served and the parser could not read", async () => {
1556
+ const breaker = new PageReadHostBreaker({ failureThreshold: 3 });
1557
+ pdfGetTextMock.mockRejectedValue(new Error("Invalid PDF structure"));
1558
+ fetchMock.mockImplementation(async () => pdfResponse());
1559
+
1560
+ for (const name of ["a", "b", "c"]) {
1561
+ expect(
1562
+ (await countOutcomes(`https://docs.example.com/${name}.pdf`, breaker))
1563
+ .skipped,
1564
+ ).toEqual({ unparsable: 1 });
1565
+ }
1566
+ expect(breaker.getOpens()).toBe(0);
1567
+
1568
+ // The host's good pages are still read.
1569
+ fetchMock.mockImplementation(
1570
+ async () =>
1571
+ new Response(articlePage, {
1572
+ status: 200,
1573
+ headers: { "content-type": "text/html; charset=utf-8" },
1574
+ }),
1575
+ );
1576
+ expect(
1577
+ (await countOutcomes("https://docs.example.com/article", breaker)).read,
1578
+ ).toBe(1);
1579
+ });
1580
+
1581
+ it("counts an HTML page whose extraction throws as unparsable", async () => {
1582
+ respondWithHtml(articlePage);
1583
+ htmlToTextConvertMock.mockImplementationOnce(() => {
1584
+ throw new Error("unexpected markup");
1585
+ });
1586
+
1587
+ expect(
1588
+ (await countOutcomes("https://example.com/broken-markup")).skipped,
1589
+ ).toEqual({ unparsable: 1 });
1590
+ });
1591
+
1592
+ it("keeps a rejected fetch and a body that errors mid-stream as failed, and they still box the host", async () => {
1593
+ const breaker = new PageReadHostBreaker({ failureThreshold: 3 });
1594
+
1595
+ fetchMock.mockRejectedValue(new TypeError("fetch failed"));
1596
+ expect(
1597
+ (await countOutcomes("https://flaky.example.com/a", breaker)).skipped,
1598
+ ).toEqual({ failed: 1 });
1599
+
1600
+ fetchMock.mockImplementation(
1601
+ async () =>
1602
+ new Response(
1603
+ new ReadableStream({
1604
+ pull(controller) {
1605
+ controller.error(new TypeError("terminated"));
1606
+ },
1607
+ }),
1608
+ { status: 200, headers: { "content-type": "text/html" } },
1609
+ ),
1610
+ );
1611
+ expect(
1612
+ (await countOutcomes("https://flaky.example.com/b", breaker)).skipped,
1613
+ ).toEqual({ failed: 1 });
1614
+ expect(
1615
+ (await countOutcomes("https://flaky.example.com/c", breaker)).skipped,
1616
+ ).toEqual({ failed: 1 });
1617
+
1618
+ respondWithHtml(articlePage);
1619
+ expect(
1620
+ (await countOutcomes("https://flaky.example.com/d", breaker)).skipped,
1621
+ ).toEqual({ skippedByBreaker: 1 });
1622
+ expect(breaker.getOpens()).toBe(1);
1623
+ });
1624
+ });
server/pageContentService.ts CHANGED
@@ -527,26 +527,37 @@ async function readHop(url: URL, deadline: AbortSignal): Promise<HopResult> {
527
  }
528
  }
529
 
 
 
530
  try {
531
- const { bytes, truncated } = await readCappedBytes(
532
  response,
533
  MAX_RESPONSE_BYTES,
534
- );
535
- if (contentType.trim().toLowerCase().startsWith("application/pdf")) {
 
 
 
 
 
 
 
 
536
  return {
537
  outcome: "ok",
538
  text: await extractPdfText(bytes),
539
  bodyTruncated: truncated,
540
  };
 
 
541
  }
542
- return {
543
- outcome: "ok",
544
- html: decodeDocument(bytes, contentType),
545
- bodyTruncated: truncated,
546
- };
547
- } catch (error) {
548
- return { outcome: isTimeout(error) ? "timedOut" : "failed" };
549
  }
 
 
 
 
 
 
550
  }
551
 
552
  /**
@@ -1201,8 +1212,10 @@ async function fetchPageContent(
1201
  contextTerms,
1202
  };
1203
  } catch {
 
 
1204
  recordPageRead({
1205
- outcome: "failed",
1206
  durationMs: performance.now() - startedAt,
1207
  bodyTruncated,
1208
  });
 
527
  }
528
  }
529
 
530
+ let bytes: Uint8Array;
531
+ let truncated: boolean;
532
  try {
533
+ ({ bytes, truncated } = await readCappedBytes(
534
  response,
535
  MAX_RESPONSE_BYTES,
536
+ ));
537
+ } catch (error) {
538
+ return { outcome: isTimeout(error) ? "timedOut" : "failed" };
539
+ }
540
+
541
+ if (contentType.trim().toLowerCase().startsWith("application/pdf")) {
542
+ // The host delivered the file. A parser that rejects it (a password, a
543
+ // damaged structure) says something about the document, not the host, so
544
+ // it must not read as a dropped connection and count toward boxing.
545
+ try {
546
  return {
547
  outcome: "ok",
548
  text: await extractPdfText(bytes),
549
  bodyTruncated: truncated,
550
  };
551
+ } catch {
552
+ return { outcome: "unparsable" };
553
  }
 
 
 
 
 
 
 
554
  }
555
+
556
+ return {
557
+ outcome: "ok",
558
+ html: decodeDocument(bytes, contentType),
559
+ bodyTruncated: truncated,
560
+ };
561
  }
562
 
563
  /**
 
1212
  contextTerms,
1213
  };
1214
  } catch {
1215
+ // The page arrived and its text could not be extracted: not a connection
1216
+ // failure.
1217
  recordPageRead({
1218
+ outcome: "unparsable",
1219
  durationMs: performance.now() - startedAt,
1220
  bodyTruncated,
1221
  });
server/pageReadHostBreaker.ts CHANGED
@@ -9,9 +9,10 @@ import {
9
  * bot wall or rate limit (`httpForbidden`), any other non-ok status, a read
10
  * that hit the deadline, and a connection that was refused or dropped. A dead
11
  * link (`httpNotFound`) is the host answering, a page with too little text is
12
- * the page's fault, and `blocked` never reached the host at all, so none of
13
- * those count, and each of them resets the run of refusals the way a read
14
- * that worked does.
 
15
  */
16
  const HOST_REFUSALS: ReadonlySet<string> = new Set<PageReadOutcome>([
17
  "httpForbidden",
 
9
  * bot wall or rate limit (`httpForbidden`), any other non-ok status, a read
10
  * that hit the deadline, and a connection that was refused or dropped. A dead
11
  * link (`httpNotFound`) is the host answering, a page with too little text is
12
+ * the page's fault, a document the host served but that could not be parsed
13
+ * (`unparsable`) is the document's, and `blocked` never reached the host at
14
+ * all, so none of those count, and each of them resets the run of refusals the
15
+ * way a read that worked does.
16
  */
17
  const HOST_REFUSALS: ReadonlySet<string> = new Set<PageReadOutcome>([
18
  "httpForbidden",
server/pageReadsSinceLastRestart.test.ts CHANGED
@@ -46,9 +46,10 @@ describe("recordPageRead", () => {
46
  recordPageRead({ outcome: "timedOut", durationMs: 6000 });
47
  recordPageRead({ outcome: "tooLittleText", durationMs: 7 });
48
  recordPageRead({ outcome: "failed", durationMs: 8 });
 
49
  });
50
 
51
- expect(counted.requested).toBe(10);
52
  expect(counted.read).toBe(0);
53
  expect(counted.skipped).toEqual({
54
  blocked: 1,
@@ -61,6 +62,7 @@ describe("recordPageRead", () => {
61
  timedOut: 1,
62
  tooLittleText: 1,
63
  failed: 1,
 
64
  });
65
  });
66
 
 
46
  recordPageRead({ outcome: "timedOut", durationMs: 6000 });
47
  recordPageRead({ outcome: "tooLittleText", durationMs: 7 });
48
  recordPageRead({ outcome: "failed", durationMs: 8 });
49
+ recordPageRead({ outcome: "unparsable", durationMs: 9 });
50
  });
51
 
52
+ expect(counted.requested).toBe(11);
53
  expect(counted.read).toBe(0);
54
  expect(counted.skipped).toEqual({
55
  blocked: 1,
 
62
  timedOut: 1,
63
  tooLittleText: 1,
64
  failed: 1,
65
+ unparsable: 1,
66
  });
67
  });
68
 
server/pageReadsSinceLastRestart.ts CHANGED
@@ -3,6 +3,9 @@
3
  * contributed nothing to the prompt and its result kept only its snippet.
4
  * `skippedByBreaker` is a read that never left the server: its host had
5
  * refused enough recent reads that `pageReadHostBreaker` boxed it.
 
 
 
6
  */
7
  export type PageReadOutcome =
8
  | "read"
@@ -15,6 +18,7 @@ export type PageReadOutcome =
15
  | "redirectLimit"
16
  | "timedOut"
17
  | "tooLittleText"
 
18
  | "failed";
19
 
20
  /**
@@ -39,6 +43,7 @@ const outcomes: Record<PageReadOutcome, number> = {
39
  redirectLimit: 0,
40
  timedOut: 0,
41
  tooLittleText: 0,
 
42
  failed: 0,
43
  };
44
 
 
3
  * contributed nothing to the prompt and its result kept only its snippet.
4
  * `skippedByBreaker` is a read that never left the server: its host had
5
  * refused enough recent reads that `pageReadHostBreaker` boxed it.
6
+ * `unparsable` is a page that arrived but whose content could not be read: a
7
+ * PDF the parser rejected (password-protected, malformed) or markup the
8
+ * extractor threw on. The host answered, so it never counts toward the breaker.
9
  */
10
  export type PageReadOutcome =
11
  | "read"
 
18
  | "redirectLimit"
19
  | "timedOut"
20
  | "tooLittleText"
21
+ | "unparsable"
22
  | "failed";
23
 
24
  /**
 
43
  redirectLimit: 0,
44
  timedOut: 0,
45
  tooLittleText: 0,
46
+ unparsable: 0,
47
  failed: 0,
48
  };
49
 
server/searchEndpointServerHook.test.ts CHANGED
@@ -136,6 +136,59 @@ describe("searchEndpointServerHook", () => {
136
  expect(fetchSearXNG).not.toHaveBeenCalled();
137
  });
138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
  it("responds 400 when the query parameter is missing", async () => {
140
  const handler = getRegisteredHandler();
141
  const response = createResponse();
 
136
  expect(fetchSearXNG).not.toHaveBeenCalled();
137
  });
138
 
139
+ it.each([
140
+ "/search/",
141
+ "/search/foo",
142
+ "/search/textual",
143
+ "/search/text/",
144
+ "/search/text/x",
145
+ "/search/images2",
146
+ ])("answers 404 to %s without running a search", async (path) => {
147
+ const handler = getRegisteredHandler();
148
+ const response = createResponse();
149
+ const next = vi.fn();
150
+
151
+ await handler(createRequest(`${path}?q=cats&token=abc`), response, next);
152
+
153
+ expect(response.statusCode).toBe(404);
154
+ expect(response.setHeader).toHaveBeenCalledWith(
155
+ "Content-Type",
156
+ "application/json",
157
+ );
158
+ expect(response.end).toHaveBeenCalledWith(
159
+ JSON.stringify({ error: "Not found" }),
160
+ );
161
+ // Nothing was authorized or searched, so nothing is verified, ranked or
162
+ // counted.
163
+ expect(handleTokenVerification).not.toHaveBeenCalled();
164
+ expect(fetchSearXNG).not.toHaveBeenCalled();
165
+ expect(recordSearchDuration).not.toHaveBeenCalled();
166
+ expect(incrementTextualSearchesSinceLastRestart).not.toHaveBeenCalled();
167
+ expect(incrementGraphicalSearchesSinceLastRestart).not.toHaveBeenCalled();
168
+ expect(next).not.toHaveBeenCalled();
169
+ });
170
+
171
+ it("takes the search type from the path alone", async () => {
172
+ vi.mocked(fetchSearXNG).mockResolvedValue([]);
173
+ const handler = getRegisteredHandler();
174
+ const unknown = createResponse();
175
+
176
+ await handler(
177
+ createRequest("/search/foo?q=cats&token=abc&next=/search/text"),
178
+ unknown,
179
+ vi.fn(),
180
+ );
181
+ await handler(
182
+ createRequest("/search/images?q=cats&token=abc&next=/search/text"),
183
+ createResponse(),
184
+ vi.fn(),
185
+ );
186
+
187
+ expect(unknown.statusCode).toBe(404);
188
+ expect(fetchSearXNG).toHaveBeenCalledTimes(1);
189
+ expect(fetchSearXNG).toHaveBeenCalledWith("cats", "images", 30);
190
+ });
191
+
192
  it("responds 400 when the query parameter is missing", async () => {
193
  const handler = getRegisteredHandler();
194
  const response = createResponse();
server/searchEndpointServerHook.ts CHANGED
@@ -55,6 +55,14 @@ const OFFICIAL_LANE_RESERVED_MS = 5_000;
55
  // slower than the page it was meant to improve.
56
  const MAX_OFFICIAL_LANE_TIMEOUT_MS = 8_000;
57
 
 
 
 
 
 
 
 
 
58
  const searchParamsSchema = z.object({
59
  query: z
60
  .string({ error: "Missing query parameter" })
@@ -187,6 +195,14 @@ export function searchEndpointServerHook<
187
  return;
188
  }
189
 
 
 
 
 
 
 
 
 
190
  // Verified before the parameters are read, matching `/page-content`: a
191
  // malformed query from an unauthenticated caller has to cost the caller a
192
  // rate-limit point, and it has to be counted, rather than leaving on a 400
@@ -212,8 +228,7 @@ export function searchEndpointServerHook<
212
  const { query, limit } = parsedParams.data;
213
 
214
  try {
215
- const isTextSearch = request.url?.startsWith("/search/text");
216
- const searchType = isTextSearch ? "text" : "images";
217
 
218
  let searchResults: TextResult[] | ImageResult[] | null;
219
  let servedBySearXNG = false;
 
55
  // slower than the page it was meant to improve.
56
  const MAX_OFFICIAL_LANE_TIMEOUT_MS = 8_000;
57
 
58
+ // The hook claims every path under `/search/`, so the type comes from the exact
59
+ // pathname: a prefix test would run a search for `/search/foo` and for
60
+ // `/search/textual`.
61
+ const SEARCH_TYPES = new Map<string, SearchType>([
62
+ ["/search/text", "text"],
63
+ ["/search/images", "images"],
64
+ ]);
65
+
66
  const searchParamsSchema = z.object({
67
  query: z
68
  .string({ error: "Missing query parameter" })
 
195
  return;
196
  }
197
 
198
+ // Answered before the token is checked: an unknown path starts no search,
199
+ // so it has nothing to authorize and costs the caller no rate-limit point.
200
+ const searchType = SEARCH_TYPES.get(url.pathname);
201
+ if (!searchType) {
202
+ sendJsonError(response, 404, { error: "Not found" });
203
+ return;
204
+ }
205
+
206
  // Verified before the parameters are read, matching `/page-content`: a
207
  // malformed query from an unauthenticated caller has to cost the caller a
208
  // rate-limit point, and it has to be counted, rather than leaving on a 400
 
228
  const { query, limit } = parsedParams.data;
229
 
230
  try {
231
+ const isTextSearch = searchType === "text";
 
232
 
233
  let searchResults: TextResult[] | ImageResult[] | null;
234
  let servedBySearXNG = false;
server/searchesSinceLastRestart.test.ts ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+
3
+ // The counters are module state that lasts for the process, and these cases
4
+ // assert absolute values, so each one starts from a freshly imported module.
5
+ async function loadCounters() {
6
+ vi.resetModules();
7
+ return import("./searchesSinceLastRestart.ts");
8
+ }
9
+
10
+ describe("getSearchStats", () => {
11
+ beforeEach(() => {
12
+ vi.resetModules();
13
+ });
14
+
15
+ it("reports 0, not NaN, before any search was timed", async () => {
16
+ const counters = await loadCounters();
17
+
18
+ expect(counters.getSearchStats()).toEqual({
19
+ averageTextualMs: 0,
20
+ averageGraphicalMs: 0,
21
+ });
22
+ });
23
+
24
+ it("averages over the timed text searches, not every text search served", async () => {
25
+ const counters = await loadCounters();
26
+
27
+ // One search SearXNG answered in 1000 ms, and one the fallback served,
28
+ // which has no SearXNG duration to record.
29
+ counters.recordSearchDuration("text", 1000);
30
+ counters.incrementTextualSearchesSinceLastRestart();
31
+ counters.incrementTextualSearchesSinceLastRestart();
32
+
33
+ expect(counters.getSearchStats().averageTextualMs).toBe(1000);
34
+ expect(counters.getTextualSearchesSinceLastRestart()).toBe(2);
35
+ });
36
+
37
+ it("averages over the timed image searches, not every image search served", async () => {
38
+ const counters = await loadCounters();
39
+
40
+ counters.recordSearchDuration("images", 1000);
41
+ counters.incrementGraphicalSearchesSinceLastRestart();
42
+ counters.incrementGraphicalSearchesSinceLastRestart();
43
+
44
+ expect(counters.getSearchStats().averageGraphicalMs).toBe(1000);
45
+ expect(counters.getGraphicalSearchesSinceLastRestart()).toBe(2);
46
+ });
47
+
48
+ it("keeps the text and image averages apart", async () => {
49
+ const counters = await loadCounters();
50
+
51
+ counters.recordSearchDuration("text", 2000);
52
+ counters.recordSearchDuration("text", 4000);
53
+ counters.recordSearchDuration("images", 500);
54
+
55
+ expect(counters.getSearchStats()).toEqual({
56
+ averageTextualMs: 3000,
57
+ averageGraphicalMs: 500,
58
+ });
59
+ });
60
+
61
+ it("does not let outages pull the average toward 0", async () => {
62
+ const counters = await loadCounters();
63
+
64
+ // SearXNG answers 10 searches at 2000 ms, then the fallback serves 30.
65
+ for (let i = 0; i < 10; i++) counters.recordSearchDuration("text", 2000);
66
+ for (let i = 0; i < 40; i++)
67
+ counters.incrementTextualSearchesSinceLastRestart();
68
+
69
+ expect(counters.getSearchStats().averageTextualMs).toBe(2000);
70
+ });
71
+ });
server/searchesSinceLastRestart.ts CHANGED
@@ -184,6 +184,11 @@ export function getUnresponsiveEngineStats() {
184
 
185
  let textualSearchMs = 0;
186
  let graphicalSearchMs = 0;
 
 
 
 
 
187
  let thumbnailsRequested = 0;
188
  let thumbnailsDropped = 0;
189
  let thumbnailsBlocked = 0;
@@ -193,8 +198,13 @@ export function recordSearchDuration(
193
  searchType: SearchType,
194
  durationMs: number,
195
  ): void {
196
- if (searchType === "text") textualSearchMs += durationMs;
197
- else graphicalSearchMs += durationMs;
 
 
 
 
 
198
  }
199
 
200
  export function recordThumbnailRequested(): void {
@@ -217,11 +227,9 @@ export function recordThumbnailBlocked(): void {
217
 
218
  export function getSearchStats() {
219
  return {
220
- averageTextualMs: Math.round(
221
- textualSearchMs / textualSearchesSinceLastRestart || 0,
222
- ),
223
  averageGraphicalMs: Math.round(
224
- graphicalSearchMs / graphicalSearchesSinceLastRestart || 0,
225
  ),
226
  };
227
  }
 
184
 
185
  let textualSearchMs = 0;
186
  let graphicalSearchMs = 0;
187
+ // The searches behind those sums. Not the "searches served" counters above:
188
+ // those also count a search the fallback served, which has no SearXNG duration,
189
+ // so dividing by them made the average sink during an outage.
190
+ let textualSearchesTimed = 0;
191
+ let graphicalSearchesTimed = 0;
192
  let thumbnailsRequested = 0;
193
  let thumbnailsDropped = 0;
194
  let thumbnailsBlocked = 0;
 
198
  searchType: SearchType,
199
  durationMs: number,
200
  ): void {
201
+ if (searchType === "text") {
202
+ textualSearchMs += durationMs;
203
+ textualSearchesTimed++;
204
+ } else {
205
+ graphicalSearchMs += durationMs;
206
+ graphicalSearchesTimed++;
207
+ }
208
  }
209
 
210
  export function recordThumbnailRequested(): void {
 
227
 
228
  export function getSearchStats() {
229
  return {
230
+ averageTextualMs: Math.round(textualSearchMs / textualSearchesTimed || 0),
 
 
231
  averageGraphicalMs: Math.round(
232
+ graphicalSearchMs / graphicalSearchesTimed || 0,
233
  ),
234
  };
235
  }
server/statusEndpointServerHook.test.ts CHANGED
@@ -1,6 +1,7 @@
1
  import type { IncomingMessage, ServerResponse } from "node:http";
2
  import { describe, expect, it, vi } from "vitest";
3
  import { getFallbackProviderStats } from "./fallbackSearchService.ts";
 
4
  import {
5
  incrementSearchesFailedOnFallback,
6
  incrementSearchesServedByFallback,
@@ -59,6 +60,21 @@ function callStatus(): Promise<Record<string, unknown>> {
59
  }
60
 
61
  describe("statusEndpointServerHook", () => {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  it.each(["/statuses", "/statusX?token=abc", "/status/extra"])(
63
  "passes through %s, which is not the /status route",
64
  async (url) => {
 
1
  import type { IncomingMessage, ServerResponse } from "node:http";
2
  import { describe, expect, it, vi } from "vitest";
3
  import { getFallbackProviderStats } from "./fallbackSearchService.ts";
4
+ import { recordModelAttempt } from "./inferencesSinceLastRestart.ts";
5
  import {
6
  incrementSearchesFailedOnFallback,
7
  incrementSearchesServedByFallback,
 
60
  }
61
 
62
  describe("statusEndpointServerHook", () => {
63
+ it("serves inference.byModel as an array in the configured model order", async () => {
64
+ vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", "slot-one, slot-two");
65
+ try {
66
+ recordModelAttempt("slot-two");
67
+ const status = await callStatus();
68
+ const inference = status.inference as { byModel: unknown[] };
69
+ expect(inference.byModel).toEqual([
70
+ { attempted: 0, streamed: 0, failed: 0, abandoned: 0 },
71
+ { attempted: 1, streamed: 0, failed: 0, abandoned: 0 },
72
+ ]);
73
+ } finally {
74
+ vi.unstubAllEnvs();
75
+ }
76
+ });
77
+
78
  it.each(["/statuses", "/statusX?token=abc", "/status/extra"])(
79
  "passes through %s, which is not the /status route",
80
  async (url) => {
server/statusEndpointServerHook.ts CHANGED
@@ -6,6 +6,7 @@ import { getFallbackProviderStats } from "./fallbackSearchService.ts";
6
  import { getInferenceStats } from "./inferencesSinceLastRestart.ts";
7
  import { getPageReadCircuitStats } from "./pageReadHostBreaker.ts";
8
  import { getPageReadStats } from "./pageReadsSinceLastRestart.ts";
 
9
  import { getRerankerStatus } from "./rerankerService.ts";
10
  import { getRerankingStats } from "./rerankingSinceLastRestart.ts";
11
  import {
@@ -108,7 +109,14 @@ export function statusEndpointServerHook<
108
  ...getPageReadCircuitStats(),
109
  },
110
  authorization: getAuthorizationStats(),
111
- inference: getInferenceStats(),
 
 
 
 
 
 
 
112
  activeSessions: getActiveSessionsAmount(),
113
  searches: {
114
  ...getSearchStats(),
 
6
  import { getInferenceStats } from "./inferencesSinceLastRestart.ts";
7
  import { getPageReadCircuitStats } from "./pageReadHostBreaker.ts";
8
  import { getPageReadStats } from "./pageReadsSinceLastRestart.ts";
9
+ import { parseCommaSeparatedList } from "./parseCommaSeparatedList.ts";
10
  import { getRerankerStatus } from "./rerankerService.ts";
11
  import { getRerankingStats } from "./rerankingSinceLastRestart.ts";
12
  import {
 
109
  ...getPageReadCircuitStats(),
110
  },
111
  authorization: getAuthorizationStats(),
112
+ // The per-model counters go out as an array in the configured order,
113
+ // never keyed by model name: `/status` needs no token. Same parse the
114
+ // inference hook uses for its ladder.
115
+ inference: getInferenceStats(
116
+ parseCommaSeparatedList(
117
+ process.env.INTERNAL_OPENAI_COMPATIBLE_API_MODEL,
118
+ ),
119
+ ),
120
  activeSessions: getActiveSessionsAmount(),
121
  searches: {
122
  ...getSearchStats(),
shared/openaiModels.test.ts ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+ import { listOpenAiCompatibleModels } from "./openaiModels";
3
+
4
+ const fetchMock = vi.fn();
5
+ vi.stubGlobal("fetch", fetchMock);
6
+
7
+ afterEach(() => {
8
+ fetchMock.mockReset();
9
+ vi.restoreAllMocks();
10
+ });
11
+
12
+ describe("listOpenAiCompatibleModels", () => {
13
+ it("skips entries without a usable id", async () => {
14
+ fetchMock.mockResolvedValue(
15
+ new Response(
16
+ JSON.stringify({
17
+ data: [{ id: "a" }, { object: "model" }, { id: "" }, null, { id: 7 }],
18
+ }),
19
+ ),
20
+ );
21
+
22
+ await expect(listOpenAiCompatibleModels("http://x/v1/")).resolves.toEqual([
23
+ { id: "a" },
24
+ ]);
25
+ expect(fetchMock.mock.calls[0][0]).toBe("http://x/v1/models");
26
+ });
27
+
28
+ it("aborts with the caller's signal", async () => {
29
+ fetchMock.mockResolvedValue(new Response(JSON.stringify({ data: [] })));
30
+ const controller = new AbortController();
31
+
32
+ await listOpenAiCompatibleModels("http://x", undefined, controller.signal);
33
+ const signal: AbortSignal = fetchMock.mock.calls[0][1].signal;
34
+ expect(signal.aborted).toBe(false);
35
+ controller.abort();
36
+ expect(signal.aborted).toBe(true);
37
+ });
38
+
39
+ it("gives up on a server that never answers after 10 seconds", async () => {
40
+ const timeout = new AbortController();
41
+ const spy = vi
42
+ .spyOn(AbortSignal, "timeout")
43
+ .mockReturnValue(timeout.signal);
44
+ fetchMock.mockImplementation(
45
+ (_url: string, init: RequestInit) =>
46
+ new Promise((_resolve, reject) =>
47
+ init.signal?.addEventListener("abort", () =>
48
+ reject(init.signal?.reason),
49
+ ),
50
+ ),
51
+ );
52
+
53
+ const listing = listOpenAiCompatibleModels("http://black-hole");
54
+ expect(spy).toHaveBeenCalledWith(10_000);
55
+ timeout.abort(new DOMException("Timed out", "TimeoutError"));
56
+ await expect(listing).rejects.toMatchObject({ name: "TimeoutError" });
57
+ });
58
+ });
shared/openaiModels.ts CHANGED
@@ -1,3 +1,5 @@
 
 
1
  type OpenAIModel = { id: string };
2
 
3
  export function selectRandomModel(
@@ -18,15 +20,25 @@ function makeOpenAIHeaders(apiKey?: string): Record<string, string> {
18
  };
19
  }
20
 
 
 
 
 
 
 
 
 
21
  export async function listOpenAiCompatibleModels(
22
  baseUrl: string,
23
  apiKey?: string,
 
24
  ): Promise<OpenAIModel[]> {
25
  if (!baseUrl) throw new Error("Base URL is required to list models");
26
 
27
  const normalizedBase = baseUrl.replace(/\/$/, "");
28
  const response = await fetch(`${normalizedBase}/models`, {
29
  headers: makeOpenAIHeaders(apiKey),
 
30
  });
31
 
32
  if (!response.ok) {
@@ -36,6 +48,11 @@ export async function listOpenAiCompatibleModels(
36
  }
37
 
38
  const data = await response.json();
39
- const models: OpenAIModel[] = Array.isArray(data?.data) ? data.data : [];
40
- return models;
 
 
 
 
 
41
  }
 
1
+ import { withTimeout } from "./withTimeout";
2
+
3
  type OpenAIModel = { id: string };
4
 
5
  export function selectRandomModel(
 
20
  };
21
  }
22
 
23
+ /** How long a `/models` request may take before it gives up. */
24
+ const LIST_MODELS_TIMEOUT_MS = 10_000;
25
+
26
+ /**
27
+ * Lists the models of an OpenAI-compatible server. Gives up after
28
+ * `LIST_MODELS_TIMEOUT_MS`, or earlier when `signal` aborts, so a server that
29
+ * never answers cannot leave the caller waiting.
30
+ */
31
  export async function listOpenAiCompatibleModels(
32
  baseUrl: string,
33
  apiKey?: string,
34
+ signal?: AbortSignal,
35
  ): Promise<OpenAIModel[]> {
36
  if (!baseUrl) throw new Error("Base URL is required to list models");
37
 
38
  const normalizedBase = baseUrl.replace(/\/$/, "");
39
  const response = await fetch(`${normalizedBase}/models`, {
40
  headers: makeOpenAIHeaders(apiKey),
41
+ signal: withTimeout(signal, LIST_MODELS_TIMEOUT_MS),
42
  });
43
 
44
  if (!response.ok) {
 
48
  }
49
 
50
  const data = await response.json();
51
+ const items: unknown[] = Array.isArray(data?.data) ? data.data : [];
52
+ // A non-conforming server may list entries without a usable id; skip them.
53
+ return items.filter(
54
+ (m): m is OpenAIModel =>
55
+ typeof (m as OpenAIModel | null)?.id === "string" &&
56
+ (m as OpenAIModel).id !== "",
57
+ );
58
  }
shared/serverConfig.ts CHANGED
@@ -10,6 +10,12 @@ export interface ServerConfig {
10
  defaultInferenceType: string;
11
  /** The CSRF token to hash into the `?token=` of every request to this server. */
12
  searchToken: string;
 
 
 
 
 
 
13
  }
14
 
15
  /**
@@ -21,3 +27,4 @@ export const DEFAULT_WLLAMA_MODEL_ID = "littlelamb-290m";
21
  export const DEFAULT_WLLAMA_GPU_MODEL_ID = "gemma-3-4b";
22
  export const DEFAULT_INFERENCE_TYPE = "browser";
23
  export const DEFAULT_INTERNAL_API_NAME = "Internal API";
 
 
10
  defaultInferenceType: string;
11
  /** The CSRF token to hash into the `?token=` of every request to this server. */
12
  searchToken: string;
13
+ /**
14
+ * Origins allowed to receive the query when MiniSearch is embedded in an
15
+ * iframe. The post goes to each one and the browser drops it unless the
16
+ * embedding page is on that origin.
17
+ */
18
+ parentWindowOrigins: string[];
19
  }
20
 
21
  /**
 
27
  export const DEFAULT_WLLAMA_GPU_MODEL_ID = "gemma-3-4b";
28
  export const DEFAULT_INFERENCE_TYPE = "browser";
29
  export const DEFAULT_INTERNAL_API_NAME = "Internal API";
30
+ export const DEFAULT_PARENT_WINDOW_ORIGINS = ["https://huggingface.co"];
shared/shuffle.test.ts ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+ import { shuffle } from "./shuffle";
3
+
4
+ /** A seeded generator (mulberry32), so the distribution check is reproducible. */
5
+ function seededRandom(seed: number) {
6
+ let state = seed;
7
+ return () => {
8
+ state = (state + 0x6d2b79f5) | 0;
9
+ let mixed = Math.imul(state ^ (state >>> 15), 1 | state);
10
+ mixed = (mixed + Math.imul(mixed ^ (mixed >>> 7), 61 | mixed)) ^ mixed;
11
+ return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296;
12
+ };
13
+ }
14
+
15
+ describe("shuffle", () => {
16
+ afterEach(() => {
17
+ vi.restoreAllMocks();
18
+ });
19
+
20
+ it("returns the same array, holding the same items", () => {
21
+ const items = [1, 2, 3, 4, 5];
22
+
23
+ const result = shuffle(items);
24
+
25
+ expect(result).toBe(items);
26
+ expect([...result].sort()).toEqual([1, 2, 3, 4, 5]);
27
+ });
28
+
29
+ it("leaves an empty list and a single item as they are", () => {
30
+ expect(shuffle([])).toEqual([]);
31
+ expect(shuffle(["only"])).toEqual(["only"]);
32
+ });
33
+
34
+ it("puts every item in every position about equally often", () => {
35
+ vi.spyOn(Math, "random").mockImplementation(seededRandom(20261124));
36
+ const items = ["a", "b", "c", "d"];
37
+ const runs = 40_000;
38
+ const counts = items.map(() => items.map(() => 0));
39
+
40
+ for (let run = 0; run < runs; run++) {
41
+ shuffle([...items]).forEach((item, position) => {
42
+ counts[items.indexOf(item)][position]++;
43
+ });
44
+ }
45
+
46
+ for (const itemCounts of counts) {
47
+ for (const count of itemCounts) {
48
+ expect(count / runs).toBeGreaterThan(0.23);
49
+ expect(count / runs).toBeLessThan(0.27);
50
+ }
51
+ }
52
+ });
53
+ });
shared/shuffle.ts ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ /** Shuffles `items` in place with Fisher-Yates and returns it; every order is equally likely. */
2
+ export function shuffle<Item>(items: Item[]): Item[] {
3
+ for (let index = items.length - 1; index > 0; index--) {
4
+ const swapIndex = Math.floor(Math.random() * (index + 1));
5
+ [items[index], items[swapIndex]] = [items[swapIndex], items[index]];
6
+ }
7
+ return items;
8
+ }
shared/withTimeout.ts ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ /** Aborts when `signal` does, or after `ms` milliseconds, whichever comes first. */
2
+ export function withTimeout(
3
+ signal: AbortSignal | undefined,
4
+ ms: number,
5
+ ): AbortSignal {
6
+ const timeout = AbortSignal.timeout(ms);
7
+ return signal ? AbortSignal.any([signal, timeout]) : timeout;
8
+ }