bunnyquery 1.18.0 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bunnyquery",
3
- "version": "1.18.0",
3
+ "version": "1.19.0",
4
4
  "description": "Embeddable BunnyQuery AI chat widget + its framework-agnostic chat engine",
5
5
  "main": "bunnyquery.js",
6
6
  "exports": {
@@ -12,14 +12,11 @@
12
12
  * `poll: 0` to get the early ack + a manual `.poll()` handle (needed for queued-
13
13
  * send cancel). So the request builders include `poll` only when it is set.
14
14
  *
15
- * THE TRANSPORT HAS TWO SPELLINGS, and a host may inject either. skapi-js renamed
16
- * clientSecretRequest and its companions to the forwardRequest family, and kept
17
- * every old name working. So this config accepts both families of keys, prefers
18
- * the new one, and every call goes through the resolveForwardRequest* functions
19
- * below, which are the only code in the engine that knows there are two. The old
20
- * keys are not a courtesy: this package is pinned with a caret range, so a host
21
- * written against an earlier release takes this one on its next install with
22
- * nothing but the old keys injected, and it has to keep working unchanged.
15
+ * THE TRANSPORT IS THE forwardRequest FAMILY ONLY (owner, 2026-11-20: clientSecretRequest
16
+ * is being deprecated). The old `clientSecretRequest*` keys are no longer read: a host
17
+ * injects `forwardRequest`, `forwardRequestHistory` and, to stream,
18
+ * `forwardRequestFinalize` and `forwardRequestStream`, all from skapi-js 2.1.0 or newer.
19
+ * Every call goes through the resolveForwardRequest* functions below.
23
20
  */
24
21
 
25
22
  import { type AttachmentParser, registerAttachmentParser } from './attachment_parsers';
@@ -110,35 +107,13 @@ export interface ChatEngineConfig {
110
107
  * is given the embedder's) decides by a companion only the new SDK has,
111
108
  * `forwardRequestHistory`, and never by this method's presence.
112
109
  *
113
- * This or the deprecated `clientSecretRequest` is required; with both, this
114
- * one is used. See resolveForwardRequest.
110
+ * Required. See resolveForwardRequest.
115
111
  */
116
112
  forwardRequest?: (form: any, opts: any) => Promise<any>;
117
113
  /**
118
- * skapi.forwardRequestHistory, bound to the consumer's skapi instance. This or
119
- * the deprecated `clientSecretRequestHistory` is required; with both, this one
120
- * is used. Same arguments either way.
114
+ * skapi.forwardRequestHistory, bound to the consumer's skapi instance. Required.
121
115
  */
122
116
  forwardRequestHistory?: (params: any, fetchOptions: any) => Promise<any>;
123
- /**
124
- * @deprecated Inject `forwardRequest` instead.
125
- *
126
- * skapi.clientSecretRequest, bound to the consumer's skapi instance. Still
127
- * accepted as a COMPATIBILITY CONTRACT, not a leftover: a host that injects
128
- * only the old keys must keep working on this release. Used only when
129
- * `forwardRequest` is absent, and handed the engine's request with `secretName`
130
- * moved back to `clientSecretName`, which is exactly the request it was handed
131
- * before the rename (see resolveForwardRequest).
132
- */
133
- clientSecretRequest?: (opts: any) => Promise<any>;
134
- /**
135
- * @deprecated Inject `forwardRequestHistory` instead.
136
- *
137
- * skapi.clientSecretRequestHistory, bound to the consumer's skapi instance.
138
- * Kept for the same compatibility contract as `clientSecretRequest`, and used
139
- * only when `forwardRequestHistory` is absent.
140
- */
141
- clientSecretRequestHistory?: (params: any, fetchOptions: any) => Promise<any>;
142
117
  /** MCP server base URL (prod vs dev resolved by the consumer). */
143
118
  mcpBaseUrl: string;
144
119
  /**
@@ -263,20 +238,10 @@ export interface ChatEngineConfig {
263
238
  * sends the ASSEMBLED provider body, so history reads it exactly as it reads
264
239
  * a buffered turn) and releases that request's chunks. Optional: a host
265
240
  * without it can still stream, it just leaves the chunks and an empty row.
266
- * Takes precedence over the deprecated `clientSecretRequestFinalize`.
267
241
  */
268
242
  forwardRequestFinalize?: ForwardRequestFinalizeFn;
269
243
  /**
270
- * @deprecated Inject `forwardRequestFinalize` instead.
271
- *
272
- * skapi.clientSecretRequestFinalize, the same call under its old name. Kept
273
- * for the compatibility contract `clientSecretRequest` describes, and used
274
- * only when `forwardRequestFinalize` is absent.
275
- */
276
- clientSecretRequestFinalize?: ForwardRequestFinalizeFn;
277
- /**
278
- * skapi.forwardRequestStream, bound to the consumer's skapi instance. Takes
279
- * precedence over the deprecated `clientSecretRequestStream`.
244
+ * skapi.forwardRequestStream, bound to the consumer's skapi instance.
280
245
  *
281
246
  * THE SECOND HALF OF THE DURABILITY GUARANTEE, and without it a streamed turn
282
247
  * is only as durable as the tab that started it. A streamed row settles with a
@@ -304,15 +269,6 @@ export interface ChatEngineConfig {
304
269
  * streamRecoveryEnabled() below for why the two decisions are separate.
305
270
  */
306
271
  forwardRequestStream?: ForwardRequestStreamFn;
307
- /**
308
- * @deprecated Inject `forwardRequestStream` instead.
309
- *
310
- * skapi.clientSecretRequestStream, the same call under its old name. Kept for
311
- * the compatibility contract `clientSecretRequest` describes, and used only
312
- * when `forwardRequestStream` is absent. It arms recovery exactly as the new
313
- * key does.
314
- */
315
- clientSecretRequestStream?: ForwardRequestStreamFn;
316
272
  /**
317
273
  * Observation hook for a live-streaming turn, called at most once per paint
318
274
  * (about once a second) plus once when the turn settles.
@@ -332,8 +288,7 @@ export interface ChatEngineConfig {
332
288
  * reader is injected.
333
289
  *
334
290
  * There is no need to set it to turn recovery ON: injecting
335
- * `forwardRequestStream` (or its deprecated name, `clientSecretRequestStream`)
336
- * is what arms it (see streamRecoveryEnabled).
291
+ * `forwardRequestStream` is what arms it (see streamRecoveryEnabled).
337
292
  * This exists only as the way back out for a host that wants byte-for-byte the
338
293
  * pre-recovery rendering of a terminal-but-empty row - no bubble, no marker, no
339
294
  * chunk read - while keeping the reader available for its own use. Omit it and
@@ -349,6 +304,30 @@ export interface ChatEngineConfig {
349
304
  * without it, stubs keep their server-extracted heads.
350
305
  */
351
306
  csrHistoryItemLookup?: (fullId: string, service: string, owner: string) => Promise<any>;
307
+ /**
308
+ * Read a document's page progress: the `data` of its "prog::<storagePath>" record
309
+ * ({ pages_saved, pages_total }), which the MCP keeps while the document's pages are
310
+ * saved, or null when there is none. Optional: without it a row shows passes only.
311
+ * Asked by the 10-second queue check for files still being indexed.
312
+ */
313
+ readIndexProgress?: (service: string, storagePath: string) => Promise<{ pages_saved?: number; pages_total?: number | null } | null>;
314
+ /**
315
+ * Save one search finding (findings.ts): where a hard search found its answer, as a
316
+ * record in table "search_findings" with the given unique_id, tags and data, reference
317
+ * "src::<storagePath>" and the ACCESS GROUP OF THAT FILE (read it; skip the save when
318
+ * the file has no record). When the unique_id is taken, add the new tags to the existing
319
+ * record instead. Best effort: never throw into the engine. Optional: without it nothing
320
+ * is saved.
321
+ */
322
+ saveSearchFinding?: (finding: import('./findings').SearchFinding & { service: string; owner?: string }) => Promise<any> | void;
323
+ /**
324
+ * The request ids of one file's indexing passes: the unique ids "pass::<storagePath>#<id>"
325
+ * the worker writes as each pass starts (getUniqueId, prefix "pass::<storagePath>#", every
326
+ * page), answered as the ids after "#" in any order. With it (and csrHistoryItemLookup) the
327
+ * chat history fetches the CONVERSATION only and a file's row loads its passes when opened
328
+ * (ChatSession.loadRunPasses). Without it the history pages the indexing queue as before.
329
+ */
330
+ listIndexPasses?: (service: string, storagePath: string) => Promise<string[]>;
352
331
  }
353
332
 
354
333
  let _config: ChatEngineConfig | null = null;
@@ -369,43 +348,30 @@ export function chatEngineConfig(): ChatEngineConfig {
369
348
  return _config;
370
349
  }
371
350
 
372
- /* ---- the transport, resolved from whichever family the host injected ------------
351
+ /* ---- the transport ------------------------------------------------------------------
373
352
  *
374
- * One resolver per operation, and nothing else in the engine reads the transport
375
- * keys. Each prefers the forwardRequest key and falls back to the deprecated
376
- * clientSecretRequest one, and each reads the config at CALL time rather than
377
- * caching: a host may inject through a getter (agent.vue's finalize and stream hooks
378
- * are getters, so its capability probe runs on first use) or re-configure, and the
379
- * request has to go through whatever is there when it leaves.
353
+ * One resolver per operation, and nothing else in the engine reads the transport keys.
354
+ * Each reads the config at CALL time rather than caching: a host may inject through a
355
+ * getter (agent.vue's finalize and stream hooks are getters, so its capability probe runs
356
+ * on first use) or re-configure, and the request has to go through whatever is there when
357
+ * it leaves. A key counts only when it holds a FUNCTION.
380
358
  *
381
- * A key counts only when it holds a FUNCTION. `forwardRequestFinalize: undefined`
382
- * beside a working old key is a host saying "not this one", and the old key answers.
359
+ * Only the forwardRequest family is read (owner, 2026-11-20). A host that still injects
360
+ * the removed `clientSecretRequest*` keys gets the "No request transport" error below,
361
+ * which names the keys to inject instead.
383
362
  */
384
363
 
385
364
  /**
386
- * Sends one request the engine built, through whichever family the host injected.
387
- *
388
- * Every builder in requests.ts produces the NEW spelling, `secretName`, and hands the
389
- * options here. A host that injected `forwardRequest` gets `forwardRequest(null,
390
- * opts)`: null because the engine never has a form, the whole body is already in
391
- * `opts.data`. A host that injected only the deprecated `clientSecretRequest` gets it
392
- * with `secretName` moved back to `clientSecretName` and placed first, which is key
393
- * for key, in the same order, the request it was handed before the rename. Nothing
394
- * else about the options is touched on either path: `service`, `owner`, `queue`,
395
- * `poll`, the stream flags, `headers` and `data` pass through as the builder made them.
396
- *
397
- * THE RENAME LIVES HERE AND NOWHERE ELSE. Done at each call site it is six copies of
398
- * one translation, and the copy that drifts sends a request naming no secret at all.
399
- * The old SDK refuses that; the new one, where the secret is optional, forwards it
400
- * WITHOUT resolving anything, so the provider receives a literal "$CLIENT_SECRET" as
401
- * its api key and the turn fails at the far end with nothing here to say why.
365
+ * Sends one request the engine built: `forwardRequest(null, opts)`, null because the
366
+ * engine never has a form, the whole body is already in `opts.data`. The options pass
367
+ * through exactly as the builder in requests.ts made them (`secretName`, `service`,
368
+ * `owner`, `queue`, `poll`, the stream flags, `headers`, `data`).
402
369
  *
403
370
  * Called as a method of the config, as the engine always called the transport, so a
404
371
  * host that relied on `this` sees what it saw before.
405
372
  *
406
- * Throws when the host injected neither, with a message that names the fix. The
407
- * builders that call this are async, so it reaches the caller as a rejected request,
408
- * which is the shape the old "is not a function" TypeError had.
373
+ * Throws when the host injected no forwardRequest. The builders that call this are
374
+ * async, so it reaches the caller as a rejected request.
409
375
  */
410
376
  export function resolveForwardRequest(): (opts: any) => Promise<any> {
411
377
  const cfg = chatEngineConfig();
@@ -413,62 +379,43 @@ export function resolveForwardRequest(): (opts: any) => Promise<any> {
413
379
  if (typeof fwd === 'function') {
414
380
  return (opts: any) => fwd.call(cfg, null, opts);
415
381
  }
416
- const legacy = cfg.clientSecretRequest;
417
- if (typeof legacy === 'function') {
418
- return (opts: any) => {
419
- if (!opts || typeof opts !== 'object' || !('secretName' in opts)) return legacy.call(cfg, opts);
420
- const { secretName, ...rest } = opts;
421
- return legacy.call(cfg, Object.assign({ clientSecretName: secretName }, rest));
422
- };
423
- }
424
382
  throw new Error(
425
- '[chat-engine] No request transport: configureChatEngine() needs forwardRequest '
426
- + '(or the deprecated clientSecretRequest), bound to a skapi instance.',
383
+ '[chat-engine] No request transport: configureChatEngine() needs forwardRequest, '
384
+ + 'bound to a skapi instance (skapi-js 2.1.0 or newer). The clientSecretRequest key is no longer read.',
427
385
  );
428
386
  }
429
387
 
430
- /**
431
- * Lists chat history through whichever family the host injected. The two names take
432
- * the same arguments and return the same thing, so this is a pure preference with no
433
- * translation. Throws, like resolveForwardRequest, when the host injected neither.
434
- */
388
+ /** Lists chat history. Throws, like resolveForwardRequest, when the host injected none. */
435
389
  export function resolveForwardRequestHistory(): (params: any, fetchOptions: any) => Promise<any> {
436
390
  const cfg = chatEngineConfig();
437
- const hist = typeof cfg.forwardRequestHistory === 'function'
438
- ? cfg.forwardRequestHistory
439
- : cfg.clientSecretRequestHistory;
391
+ const hist = cfg.forwardRequestHistory;
440
392
  if (typeof hist === 'function') {
441
393
  return (params: any, fetchOptions: any) => hist.call(cfg, params, fetchOptions);
442
394
  }
443
395
  throw new Error(
444
- '[chat-engine] No history transport: configureChatEngine() needs forwardRequestHistory '
445
- + '(or the deprecated clientSecretRequestHistory), bound to a skapi instance.',
396
+ '[chat-engine] No history transport: configureChatEngine() needs forwardRequestHistory, '
397
+ + 'bound to a skapi instance (skapi-js 2.1.0 or newer). The clientSecretRequestHistory key is no longer read.',
446
398
  );
447
399
  }
448
400
 
449
401
  /**
450
- * The finalize hook, from whichever family the host injected, or undefined when it
451
- * injected neither. Optional by design (a host without it still streams, it just
452
- * leaves the chunks), so absence is an answer here and not an error. Returned
453
- * unbound, because the engine has always called it as a plain function.
402
+ * The finalize hook, or undefined when the host injected none. Optional by design (a host
403
+ * without it still streams, it just leaves the chunks), so absence is an answer here and
404
+ * not an error. Returned unbound, because the engine has always called it as a plain
405
+ * function.
454
406
  */
455
407
  export function resolveForwardRequestFinalize(): ForwardRequestFinalizeFn | undefined {
456
408
  const cfg = chatEngineConfig();
457
- if (typeof cfg.forwardRequestFinalize === 'function') return cfg.forwardRequestFinalize;
458
- if (typeof cfg.clientSecretRequestFinalize === 'function') return cfg.clientSecretRequestFinalize;
459
- return undefined;
409
+ return typeof cfg.forwardRequestFinalize === 'function' ? cfg.forwardRequestFinalize : undefined;
460
410
  }
461
411
 
462
412
  /**
463
- * The chunk reader, from whichever family the host injected, or undefined when it
464
- * injected neither. Optional, and its presence is what arms recovery (see
465
- * streamRecoveryEnabled), so both spellings arm it alike. Returned unbound, as above.
413
+ * The chunk reader, or undefined when the host injected none. Optional, and its presence
414
+ * is what arms recovery (see streamRecoveryEnabled). Returned unbound, as above.
466
415
  */
467
416
  export function resolveForwardRequestStream(): ForwardRequestStreamFn | undefined {
468
417
  const cfg = chatEngineConfig();
469
- if (typeof cfg.forwardRequestStream === 'function') return cfg.forwardRequestStream;
470
- if (typeof cfg.clientSecretRequestStream === 'function') return cfg.clientSecretRequestStream;
471
- return undefined;
418
+ return typeof cfg.forwardRequestStream === 'function' ? cfg.forwardRequestStream : undefined;
472
419
  }
473
420
 
474
421
  /** True when the consumer has opted in to server-driven windowed indexing. */
@@ -593,11 +540,7 @@ export function resolveSkipDuplicateFiles(service?: string): Promise<boolean> {
593
540
  * bubble is dropped, and the list looks exactly as it did before. Set
594
541
  * `streamRecovery: false` to opt out of even that.
595
542
  *
596
- * The reader is asked for through resolveForwardRequestStream, so either spelling of
597
- * it arms recovery: `forwardRequestStream`, or the deprecated
598
- * `clientSecretRequestStream` a host written before the rename still injects. Asked
599
- * for the new key alone, this would quietly disarm recovery for every such host on
600
- * its next install, which is the stranding described above arriving by a rename.
543
+ * The reader is asked for through resolveForwardRequestStream: `forwardRequestStream`.
601
544
  */
602
545
  export function streamRecoveryEnabled(): boolean {
603
546
  // Unconfigured is "no reader", never a throw: this is asked on render paths.
@@ -616,8 +559,8 @@ export function streamRecoveryEnabled(): boolean {
616
559
  * into the chunk table) and the DESTINATION's own field inside `data`, which
617
560
  * BunnyQuery is the party that sets, because skapi relays bytes and knows no
618
561
  * vendor. skapi validates the request's params against a schema and KEEPS ONLY
619
- * THE KEYS IN THAT SCHEMA, so an skapi-js predating the feature (whose only door
620
- * was clientSecretRequest) does not reject `stream` - it silently DROPS it. What
562
+ * THE KEYS IN THAT SCHEMA, so an skapi-js predating the feature does not reject
563
+ * `stream` - it silently DROPS it. What
621
564
  * ships is then the exact split
622
565
  * chatStreamWiring exists to make impossible: the destination is asked to answer in
623
566
  * SSE frames, skapi waits and stores the whole transcript on the row, and
@@ -645,18 +588,11 @@ export function streamRecoveryEnabled(): boolean {
645
588
  * learn that `stream` was dropped is to send a real request and read an empty
646
589
  * answer, which is the bug itself.
647
590
  *
648
- * EITHER SPELLING OF THE PAIR ANSWERS YES, and it has to be a whole pair. skapi-js
649
- * renamed the two to forwardRequestStream and forwardRequestFinalize and kept the old
650
- * names as aliases, so three SDKs are out there: the renamed one carries both pairs,
651
- * one from the streaming release up to the rename carries only the old pair, and one
652
- * that predates streaming carries neither. Accepting the old pair is what keeps an
653
- * embed page pinned between the two releases streaming; accepting the new pair is
654
- * what keeps this answering yes once the old aliases are finally removed. The
655
- * reasoning above holds for both: each pair shipped in the same change as, or after,
656
- * the `stream` key, and each IS the capability rather than a proxy for it. A mixed
657
- * half of each is not a pair and is refused, because no real SDK has that shape and
658
- * the engine would still be missing one half of the protocol under the name it asks
659
- * for.
591
+ * ONLY THE NEW PAIR ANSWERS YES (owner, 2026-11-20). forwardRequestStream and
592
+ * forwardRequestFinalize shipped with the forwardRequest rename (skapi-js 2.1.0), after
593
+ * the `stream` key, so each IS the capability. The old clientSecretRequestStream /
594
+ * clientSecretRequestFinalize pair is no longer accepted: the engine no longer reads the
595
+ * old transport keys at all, so an SDK with only that pair could not be wired anyway.
660
596
  *
661
597
  * A presence probe is safe for these two names in a way it is NOT for forwardRequest
662
598
  * itself: no skapi-js ever shipped a forwardRequestStream or forwardRequestFinalize
@@ -666,10 +602,8 @@ export function streamRecoveryEnabled(): boolean {
666
602
  */
667
603
  export function skapiSupportsStreaming(sk: any): boolean {
668
604
  if (!sk) return false;
669
- return (typeof sk.forwardRequestStream === 'function'
670
- && typeof sk.forwardRequestFinalize === 'function')
671
- || (typeof sk.clientSecretRequestStream === 'function'
672
- && typeof sk.clientSecretRequestFinalize === 'function');
605
+ return typeof sk.forwardRequestStream === 'function'
606
+ && typeof sk.forwardRequestFinalize === 'function';
673
607
  }
674
608
 
675
609
  /** Spread helper: `{ ...pollOpt() }` adds `poll` only when configured. */
@@ -3,7 +3,8 @@
3
3
  * yes 2026-10-12): "has the signed-in user already uploaded THIS file to this
4
4
  * project?", answered from the file records the upload path already writes.
5
5
  *
6
- * WHAT COUNTS AS THE SAME FILE. Same name, same size in bytes, same uploader.
6
+ * WHAT COUNTS AS THE SAME FILE. Same name, same size in bytes, same uploader, and a
7
+ * stored copy that finished indexing or is still being indexed (see findDuplicateUpload).
7
8
  * Every upload creates a `src::<storagePath>` record (table `file_summaries`)
8
9
  * whose `data.size_bytes` is the byte count and whose `user_id` is the
9
10
  * uploader, so a lookup by name narrowed by those two fields finds a file
@@ -29,6 +30,8 @@
29
30
  * does not wire the hook and uploads as before.
30
31
  */
31
32
 
33
+ import { RUN_RECORD_WORKING_STALE_MS } from './indexing_groups';
34
+
32
35
  /** The record found, with the storage path the stored file lives at. */
33
36
  export type DuplicateUploadMatch = {
34
37
  /** The stored file's db storage path (the record id without `src::`). */
@@ -37,6 +40,8 @@ export type DuplicateUploadMatch = {
37
40
  uniqueId: string;
38
41
  /** The file record as read. */
39
42
  record: any;
43
+ /** Why it is skipped: the stored copy finished indexing, or is being indexed. */
44
+ indexing?: StoredCopyIndexing;
40
45
  };
41
46
 
42
47
  export type DuplicateUploadFile = {
@@ -66,50 +71,124 @@ function listOf(res: any): any[] {
66
71
  return Array.isArray(res.list) ? res.list : [];
67
72
  }
68
73
 
74
+ /** How long one check may take. A slower lookup answers "not a duplicate": upload as usual. */
75
+ export const DUPLICATE_LOOKUP_TIMEOUT_MS = 15_000;
76
+ /** Most ids the ends-with listing fetches. */
77
+ export const DUPLICATE_LOOKUP_LIMIT = 500;
78
+
79
+ /** The stored copy's indexing state, read from its `done::` and `run::` markers. */
80
+ export type StoredCopyIndexing = 'done' | 'running' | 'other';
81
+
82
+ /** NFC, the form storage paths are written in, so a composed name matches its record. */
83
+ function nfc(text: string): string {
84
+ try {
85
+ return String(text || '').normalize('NFC');
86
+ } catch {
87
+ return String(text || '');
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Is the stored copy indexed, being indexed, or neither? `done::<path>` exists: done. Its
93
+ * `run::<path>` record says 'working' and started less than RUN_RECORD_WORKING_STALE_MS ago
94
+ * (the window the file browser uses for "still indexing"): running. Anything else, a failed
95
+ * or cancelled run, a run that died without closing its record, no record, or a lookup that
96
+ * failed: other.
97
+ */
98
+ async function storedCopyIndexing(skapi: any, storagePath: string, service: { service?: string }): Promise<StoredCopyIndexing> {
99
+ const doneId = 'done::' + storagePath;
100
+ try {
101
+ const done = listOf(await skapi.getUniqueId(Object.assign({ unique_id: doneId }, service), { fetchMore: false, limit: 1 }));
102
+ if (done.some(function (it: any) { return (it && typeof it === 'object' ? it.unique_id : it) === doneId; })) return 'done';
103
+ } catch {
104
+ /* no marker, or the lookup failed: read the run record */
105
+ }
106
+ try {
107
+ const run = listOf(await skapi.getRecords(Object.assign({ unique_id: 'run::' + storagePath }, service)))[0];
108
+ const data = run && run.data && typeof run.data === 'object' ? run.data : null;
109
+ if (data && data.status === 'working' && typeof data.started === 'number'
110
+ && Date.now() - data.started < RUN_RECORD_WORKING_STALE_MS) return 'running';
111
+ } catch {
112
+ /* no run record (NOT_EXISTS) or unreadable: not running */
113
+ }
114
+ return 'other';
115
+ }
116
+
69
117
  /**
70
- * The first `src::` record for `file.name` whose `data.size_bytes` equals
71
- * `file.size` and whose `user_id` is `userId`, or null. `opts.service` is passed
72
- * through to both skapi calls when given (the widget names the project on every
73
- * call); otherwise the instance's own project is queried.
118
+ * This user's stored copy of `file`, when the upload should be SKIPPED, or null to upload as
119
+ * usual. One implementation for the widget and the site (www's duplicates.ts wraps it).
120
+ *
121
+ * THE RULE (owner, 2026-11-20). A `src::` record for `file.name` (root or any folder) whose
122
+ * `data.size_bytes` equals `file.size` and whose `user_id` is `userId`, AND whose stored copy
123
+ * finished indexing or is still being indexed (storedCopyIndexing). A copy whose indexing
124
+ * failed or was cancelled is NOT a duplicate: the upload goes on and reaches the host's usual
125
+ * "already exists: Skip / Reindex / Overwrite" question, instead of being skipped silently
126
+ * with no way to index it again.
127
+ *
128
+ * NEVER THROWS and never takes longer than `opts.timeoutMs` (DUPLICATE_LOOKUP_TIMEOUT_MS): a
129
+ * failed, refused or slow lookup answers null. `opts.service` is passed through to every skapi
130
+ * call when given (the widget and the site name the project on every call).
74
131
  */
75
132
  export async function findDuplicateUpload(
76
133
  skapi: any,
77
134
  file: DuplicateUploadFile,
78
135
  userId: string,
79
- opts?: { service?: string },
136
+ opts?: { service?: string; timeoutMs?: number },
80
137
  ): Promise<DuplicateUploadMatch | null> {
138
+ const timeoutMs = opts && typeof opts.timeoutMs === 'number' && opts.timeoutMs >= 0 ? opts.timeoutMs : DUPLICATE_LOOKUP_TIMEOUT_MS;
139
+ let timer: ReturnType<typeof setTimeout> | undefined;
140
+ const deadline = new Promise<null>(function (resolve) {
141
+ timer = setTimeout(function () { resolve(null); }, timeoutMs);
142
+ });
81
143
  try {
82
- if (!skapi || typeof skapi.getUniqueId !== 'function' || typeof skapi.getRecords !== 'function') return null;
83
- const name = file && typeof file.name === 'string' ? file.name : '';
84
- const size = file && typeof file.size === 'number' ? file.size : NaN;
85
- if (!name || !(size >= 0) || !userId) return null;
86
- const service = opts && opts.service ? { service: opts.service } : {};
144
+ return await Promise.race([lookupDuplicate(skapi, file, userId, opts), deadline]);
145
+ } catch {
146
+ return null;
147
+ } finally {
148
+ if (timer !== undefined) clearTimeout(timer);
149
+ }
150
+ }
87
151
 
88
- const found = listOf(await skapi.getUniqueId(Object.assign({ unique_id: name, condition: '<=' }, service)));
89
- const ids: string[] = [];
90
- for (const item of found) {
91
- const id = item && typeof item === 'object' ? item.unique_id : item;
92
- if (isDuplicateCandidateId(id, name) && ids.indexOf(id) === -1) ids.push(id);
93
- if (ids.length >= DUPLICATE_LOOKUP_MAX_CANDIDATES) break;
94
- }
152
+ async function lookupDuplicate(
153
+ skapi: any,
154
+ file: DuplicateUploadFile,
155
+ userId: string,
156
+ opts?: { service?: string },
157
+ ): Promise<DuplicateUploadMatch | null> {
158
+ if (!skapi || typeof skapi.getUniqueId !== 'function' || typeof skapi.getRecords !== 'function') return null;
159
+ const name = nfc(file && typeof file.name === 'string' ? file.name.split('/').pop() || '' : '');
160
+ const size = file && typeof file.size === 'number' ? file.size : NaN;
161
+ if (!name || !(size >= 0) || !userId) return null;
162
+ const service = opts && opts.service ? { service: opts.service } : {};
95
163
 
96
- for (const uniqueId of ids) {
97
- let record: any = null;
98
- try {
99
- record = listOf(await skapi.getRecords(Object.assign({ unique_id: uniqueId }, service)))[0] || null;
100
- } catch {
101
- // One unreadable candidate (another group, a deleted record) is not
102
- // the answer; the next one may be.
103
- continue;
104
- }
105
- if (!record || typeof record !== 'object') continue;
106
- const data = record.data && typeof record.data === 'object' ? record.data : null;
107
- if (!data || data.size_bytes !== size) continue;
108
- if (record.user_id !== userId) continue;
109
- return { storagePath: uniqueId.slice(SRC_PREFIX.length), uniqueId, record };
164
+ const found = listOf(await skapi.getUniqueId(
165
+ Object.assign({ unique_id: name, condition: '<=' }, service),
166
+ { fetchMore: false, limit: DUPLICATE_LOOKUP_LIMIT },
167
+ ));
168
+ const ids: string[] = [];
169
+ for (const item of found) {
170
+ const id = item && typeof item === 'object' ? item.unique_id : item;
171
+ if (isDuplicateCandidateId(id, name) && ids.indexOf(id) === -1) ids.push(id);
172
+ if (ids.length >= DUPLICATE_LOOKUP_MAX_CANDIDATES) break;
173
+ }
174
+
175
+ for (const uniqueId of ids) {
176
+ let record: any = null;
177
+ try {
178
+ record = listOf(await skapi.getRecords(Object.assign({ unique_id: uniqueId }, service)))[0] || null;
179
+ } catch {
180
+ // One unreadable candidate (another group, a deleted record) is not
181
+ // the answer; the next one may be.
182
+ continue;
110
183
  }
111
- return null;
112
- } catch {
113
- return null;
184
+ if (!record || typeof record !== 'object') continue;
185
+ const data = record.data && typeof record.data === 'object' ? record.data : null;
186
+ if (!data || data.size_bytes !== size) continue;
187
+ if (record.user_id !== userId) continue;
188
+ const storagePath = uniqueId.slice(SRC_PREFIX.length);
189
+ const indexing = await storedCopyIndexing(skapi, storagePath, service);
190
+ if (indexing === 'other') continue;
191
+ return { storagePath, uniqueId, record, indexing };
114
192
  }
193
+ return null;
115
194
  }