bunnyquery 1.15.0 → 1.15.2

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.
@@ -42,7 +42,7 @@ import {
42
42
  type BgTaskEntry,
43
43
  } from './requests';
44
44
  import { isPagedReadFile, isImageVisionFile, isWindowedReadFile } from './office';
45
- import { windowedIndexingEnabled, liveStreamingEnabled, streamRecoveryEnabled, chatEngineConfig, resolveForwardRequestFinalize, resolveForwardRequestStream } from './config';
45
+ import { windowedIndexingEnabled, liveStreamingEnabled, streamRecoveryEnabled, chatEngineConfig, resolveForwardRequestFinalize, resolveForwardRequestStream, resolveSkipDuplicateFiles } from './config';
46
46
  // The wire-format knowledge. skapi relays the provider's bytes without reading them,
47
47
  // so the session hands them straight to this parser and never inspects a frame itself.
48
48
  import { createSseParser, type SseParser } from './sse';
@@ -611,6 +611,17 @@ export class ChatSession {
611
611
  /** Files this client has an index dispatch in flight for, by scoped path ->
612
612
  * wall clock. See claimIndexRun. */
613
613
  private _indexClaims: { [scopedPath: string]: number };
614
+ /** bgTaskQueue by the SAME scoped path the claims use -> how many entries
615
+ * name that file. Derived from the array, never written to directly: see
616
+ * _bgQueueIndex for when it is rebuilt and why that is exact. */
617
+ private _bgQueueByFile: { [scopedPath: string]: number } | null;
618
+ /** What _bgQueueByFile was built from: the array itself, its length and its
619
+ * first and last entries. Equal stamp = equal contents (see _bgQueueIndex). */
620
+ private _bgQueueStamp: { arr: BgTaskEntry[] | null; length: number; first: any; last: any };
621
+ /** How many times the index was rebuilt. Diagnostics and tests only: a
622
+ * 3,000-file batch should build it a few thousand times at most (once per
623
+ * push or settle), never once per claim. */
624
+ _bgQueueIndexRebuilds: number;
614
625
 
615
626
  constructor(host: ChatHost) {
616
627
  this.host = host;
@@ -651,6 +662,9 @@ export class ChatSession {
651
662
  this._liveIndexKey = '';
652
663
  this._liveIndexAt = 0;
653
664
  this._indexClaims = {};
665
+ this._bgQueueByFile = null;
666
+ this._bgQueueStamp = { arr: null, length: 0, first: undefined, last: undefined };
667
+ this._bgQueueIndexRebuilds = 0;
654
668
  }
655
669
 
656
670
  /** What the display layer needs to decide whether a run is finished. `keys` holds
@@ -699,13 +713,14 @@ export class ChatSession {
699
713
  // of truth says "not indexing", and a second dispatch in that window is
700
714
  // exactly the duplicate this guard exists to stop. Observed live: two first
701
715
  // passes four seconds apart, two collapsed rows.
702
- var claimed = this._indexClaims[this._indexClaimKey(storagePath)];
716
+ var scoped = this._indexClaimKey(storagePath);
717
+ var claimed = this._indexClaims[scoped];
703
718
  if (claimed && nowMs() - claimed < INDEX_DISPATCH_CLAIM_MS) return true;
704
- var id = this.host.getIdentity();
705
- for (var i = 0; i < this.bgTaskQueue.length; i++) {
706
- var e = this.bgTaskQueue[i];
707
- if (e && e.storagePath === storagePath && e.projectId === id.projectId && e.platform === id.platform) return true;
708
- }
719
+ // The queue, looked up by the same scoped path instead of scanned. A batch
720
+ // claims once per file, and the queue holds one entry per file already
721
+ // dispatched, so the scan was O(n) per claim and O(n^2) over a 3,000-file
722
+ // batch. The index is rebuilt only when the array changes (_bgQueueIndex).
723
+ if (this._bgQueueIndex()[scoped] > 0) return true;
709
724
  return this.state.messages.some(function (m) {
710
725
  if (!m.isBackgroundTask || m.role !== 'user' || m.isCancelled) return false;
711
726
  if (!(m.isPendingQueued || m.isPendingInProcess || m.isSendingToServer)) return false;
@@ -720,6 +735,48 @@ export class ChatSession {
720
735
  return indexScopeKey(id.projectId, id.platform) + '|' + storagePath;
721
736
  }
722
737
 
738
+ /**
739
+ * bgTaskQueue as a map: scoped path (indexScopeKey(projectId, platform) +
740
+ * '|' + storagePath, the key the claims and the stops use) -> entries.
741
+ *
742
+ * The array stays the source of truth because the engine does not own every
743
+ * write to it: both hosts hand in their own array (the dashboard a Vue
744
+ * reactive one it pushes to from the Files page and splices from its
745
+ * fallback poller), and tests push to it directly. So the map is DERIVED, and
746
+ * rebuilt when a cheap stamp says the array changed: its identity, its length,
747
+ * its first and its last entry.
748
+ *
749
+ * Why that stamp is exact for this array: every write to bgTaskQueue is either
750
+ * a push of a NEW entry object or a splice that removes one (nothing inserts
751
+ * in the middle, replaces in place or re-pushes a removed entry). Under those
752
+ * two operations, same length plus same last entry means the same contents:
753
+ * a push changes the last entry unless that same push is removed again, and a
754
+ * removal changes the length unless a push restores it, which changes the
755
+ * last entry. The first entry is in the stamp as margin. A rebuild is one
756
+ * pass over the array, paid once per change instead of once per claim.
757
+ */
758
+ private _bgQueueIndex(): { [scopedPath: string]: number } {
759
+ var q = this.bgTaskQueue;
760
+ var n = q ? q.length : 0;
761
+ var first = n ? q[0] : undefined;
762
+ var last = n ? q[n - 1] : undefined;
763
+ var st = this._bgQueueStamp;
764
+ if (this._bgQueueByFile && st.arr === q && st.length === n && st.first === first && st.last === last) {
765
+ return this._bgQueueByFile;
766
+ }
767
+ var idx: { [scopedPath: string]: number } = {};
768
+ for (var i = 0; i < n; i++) {
769
+ var e = q[i];
770
+ if (!e || !e.storagePath) continue;
771
+ var k = indexScopeKey(e.projectId, e.platform) + '|' + e.storagePath;
772
+ idx[k] = (idx[k] || 0) + 1;
773
+ }
774
+ this._bgQueueByFile = idx;
775
+ this._bgQueueStamp = { arr: q, length: n, first: first, last: last };
776
+ this._bgQueueIndexRebuilds++;
777
+ return idx;
778
+ }
779
+
723
780
  /**
724
781
  * Take this file's indexing slot, or report that someone already has it.
725
782
  *
@@ -5955,11 +6012,35 @@ export class ChatSession {
5955
6012
  if (!total) return Promise.reject(new Error('Empty attachment'));
5956
6013
  var urls: Array<{ name: string; url: string; storagePath: string }> = [];
5957
6014
  var anyIndexFailed = false;
6015
+ // Members answered by a file the user already has here (see findDuplicate
6016
+ // below). Counted so a folder chip can say how many it reused.
6017
+ var reusedCount = 0;
6018
+ att.reused = false;
5958
6019
  var chain: Promise<any> = Promise.resolve();
6020
+ // "Already uploaded by this user, same name and size" -> the stored copy's
6021
+ // storage path, else null. Asked only while the skip-duplicates switch
6022
+ // resolves ON (the project's setting is the ceiling, the host may only
6023
+ // restrict), and only of a host that wired the hook. Every failure is null,
6024
+ // so this can save an upload and an indexing run but never block one.
6025
+ var findDuplicate = function (member: any): Promise<string | null> {
6026
+ if (typeof self.host.findDuplicateUpload !== 'function') return Promise.resolve(null);
6027
+ var storedName = String(member.storagePath || '').split('/').filter(Boolean).pop() || member.file.name;
6028
+ return resolveSkipDuplicateFiles(id.projectId).then(function (on) {
6029
+ if (!on) return null;
6030
+ return Promise.resolve(self.host.findDuplicateUpload!({ name: storedName, size: member.file.size }))
6031
+ .then(function (hit: any) {
6032
+ return hit && typeof hit.storagePath === 'string' && hit.storagePath ? hit.storagePath : null;
6033
+ });
6034
+ }).catch(function () { return null; });
6035
+ };
5959
6036
  members.forEach(function (member: any, idx: number) {
5960
6037
  chain = chain.then(function () {
5961
6038
  var hadExists = false;
5962
6039
  var skipped = false;
6040
+ // The storage path of the file this member DUPLICATES, when the user
6041
+ // already has it here: nothing is uploaded or indexed for it, and the
6042
+ // turn takes the stored copy's url instead.
6043
+ var duplicateOf: string | null = null;
5963
6044
  // True when the file already existed and we are re-indexing over it
5964
6045
  // (user chose Reindex, OR Overwrite replaced the bytes). Drives the
5965
6046
  // delete-then-repost of the stale "src::" record below. Kept separate
@@ -5978,7 +6059,14 @@ export class ChatSession {
5978
6059
  onProgress: onProg, setAbort: function (abort) { att._abort = abort; },
5979
6060
  });
5980
6061
  };
5981
- return doMemberUpload(true).catch(function (err: any) {
6062
+ return findDuplicate(member).then(function (dup) {
6063
+ if (dup) {
6064
+ duplicateOf = dup;
6065
+ console.log('[chat-engine] skipping an upload the user already has:', member.storagePath, '->', dup);
6066
+ return;
6067
+ }
6068
+ return doMemberUpload(true);
6069
+ }).catch(function (err: any) {
5982
6070
  var code = err && (err.code || (err.body && err.body.code));
5983
6071
  var msg = err && (err.message || (err.body && err.body.message) || (typeof err === 'string' ? err : ''));
5984
6072
  var isExists = code === 'EXISTS' || (msg && /exist/i.test(msg));
@@ -5999,9 +6087,20 @@ export class ChatSession {
5999
6087
  });
6000
6088
  }).then(function () {
6001
6089
  if (skipped) return; // user skipped this member — no url, no index request
6002
- return self.host.getTemporaryUrl(member.storagePath);
6090
+ // A duplicate takes the STORED copy's url: the same reuse an EXISTS
6091
+ // answer gets when the user keeps the file, minus the prompt and
6092
+ // minus the re-index.
6093
+ return self.host.getTemporaryUrl(duplicateOf || member.storagePath);
6003
6094
  }).then(function (url: string) {
6004
6095
  if (skipped) return; // guard the indexing branch for a skipped member
6096
+ if (duplicateOf) {
6097
+ urls.push({ name: member.relPath, url: url, storagePath: duplicateOf });
6098
+ reusedCount += 1;
6099
+ if (att.kind !== 'folder') { att.uploadedUrl = url; att.storagePath = duplicateOf; att.reused = true; }
6100
+ else att.reusedCount = reusedCount;
6101
+ self.host.renderAttachmentChips();
6102
+ return; // not indexed: the stored copy already is
6103
+ }
6005
6104
  urls.push({ name: member.relPath, url: url, storagePath: member.storagePath });
6006
6105
  if (att.kind !== 'folder') { att.uploadedUrl = url; att.storagePath = member.storagePath; }
6007
6106
  var mime = member.file.type || self.host.getMimeType(member.file.name);