bunnyquery 1.18.0 → 1.19.1

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.
@@ -48,7 +48,8 @@ import { windowedIndexingEnabled, liveStreamingEnabled, streamRecoveryEnabled, c
48
48
  import { createSseParser, type SseParser } from './sse';
49
49
  import { isErrorResponseBody, isAuthExpiredError, isNonRetryableRequestError, getErrorMessage, isCsrStatusEnvelope } from './errors';
50
50
  import { buildBoundedChatMessages } from './budget';
51
- import { extractRetrievalNote } from './retrieval_memory';
51
+ import { extractRetrievalNote, type RetrievalNote } from './retrieval_memory';
52
+ import { findingsForTurn } from './findings';
52
53
  import { createInlineLinkRegex, sanitizeAttachmentLinksForHistory } from './links';
53
54
  import { markImagePreviewStale } from './image_preview';
54
55
  import { chatCacheKey, indexScopeKey, mapHistoryListToMessages, extractLastUserTextFromRequest, isIndexingRequestText, parseIndexingRequestText, probeBgQueue, BG_PROBE_TTL_MS, getSplitChatHistory, shouldRescueInFlightMessage, adoptLocalAnswerIntoPage } from './history';
@@ -88,6 +89,13 @@ const WORKER_PASS_ADOPT_ATTEMPTS = [0, 2000, 6000];
88
89
  * round trips, while the cost of being too tight is a file that reads "Indexed"
89
90
  * while it is still being read. */
90
91
  const RECENT_INDEX_PASS_EVIDENCE_MS = 10 * 60 * 1000;
92
+ // While this chat is following a worker-driven indexing run and its tab is visible, look
93
+ // for newly minted passes this often (2026-11-20). Adoption used to run only when a pass
94
+ // this client tracked SETTLED, and with parallel windows the one pass the client sent is
95
+ // just one of eight: the other lanes, and everything they finished, stayed invisible until
96
+ // it ended (3.5 min on a 110-page PDF, nine passes done meanwhile). One look is the two
97
+ // status queries (running, pending); it stops by itself when nothing is tracked.
98
+ const ADOPT_TICK_MS = 10 * 1000;
91
99
 
92
100
  // awaitIndexingDrained: how often it re-asks the background-indexing queue, and
93
101
  // how many consecutive empty answers it needs before believing the chains are
@@ -548,6 +556,26 @@ type LiveStreamState = {
548
556
  transport: { socket: number; poll: number };
549
557
  };
550
558
 
559
+ /**
560
+ * Creation time (ms epoch) of a request id "stamp:entropy", whose stamp is a time_ns written
561
+ * as 8 bytes of base32hex without padding (the worker's and the producer's _generate_req_id).
562
+ * 0 when it is not one.
563
+ */
564
+ export function requestIdTimeMs(rid: string): number {
565
+ if (typeof rid !== 'string') return 0;
566
+ var stamp = rid.split(':')[0] || '';
567
+ if (stamp.length !== 13) return 0;
568
+ var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUV';
569
+ var v = 0;
570
+ for (var i = 0; i < stamp.length; i++) {
571
+ var d = alphabet.indexOf(stamp.charAt(i).toUpperCase());
572
+ if (d < 0) return 0;
573
+ v = v * 32 + d;
574
+ }
575
+ // 13 digits are 65 bits for 64 of data: the last bit is padding.
576
+ return Math.floor(v / 2 / 1e6);
577
+ }
578
+
551
579
  export class ChatSession {
552
580
  host: ChatHost;
553
581
  state: ChatState;
@@ -642,7 +670,12 @@ export class ChatSession {
642
670
  historyRequestToken: 0,
643
671
  gateRefreshToken: 0,
644
672
  liveIndexKeys: {},
673
+ indexPageProgress: {},
674
+ passPaging: {},
645
675
  liveIndexChecked: false,
676
+ liveIndexRunning: {},
677
+ liveIndexRunningChecked: false,
678
+ liveIndexSettled: {},
646
679
  stoppedIndexIds: {},
647
680
  };
648
681
  this.bgTaskQueue = [];
@@ -670,8 +703,8 @@ export class ChatSession {
670
703
  /** What the display layer needs to decide whether a run is finished. `keys` holds
671
704
  * every file the server still has indexing work for; `checked` is false until the
672
705
  * first answer for this chat, and false means "we do not know yet". */
673
- getLiveIndexState(): { keys: { [fileKey: string]: boolean }; checked: boolean } {
674
- return { keys: this.state.liveIndexKeys, checked: this.state.liveIndexChecked };
706
+ getLiveIndexState(): { keys: { [fileKey: string]: boolean }; checked: boolean; running: { [fileKey: string]: boolean }; runningChecked: boolean; settled: { [fileKey: string]: boolean } } {
707
+ return { keys: this.state.liveIndexKeys, checked: this.state.liveIndexChecked, running: this.state.liveIndexRunning || {}, runningChecked: !!this.state.liveIndexRunningChecked, settled: this.state.liveIndexSettled || {} };
675
708
  }
676
709
 
677
710
  /** Passes that were on a row when the user stopped it, so the display layer can
@@ -809,6 +842,95 @@ export class ChatSession {
809
842
  if (storagePath) delete this._indexClaims[this._indexClaimKey(storagePath)];
810
843
  }
811
844
 
845
+ /**
846
+ * Index files that are ALREADY STORED again, without uploading anything: the
847
+ * Reindex answer of the "already uploaded" report, offered for the members a send
848
+ * skipped as duplicates (att.duplicates, see uploadSingleAttachment). The same
849
+ * steps the Files page's Reindex takes: claim the file (one already being indexed
850
+ * is left alone), keep its access group (host.readFileAccessGroup, read before the
851
+ * delete), clear the old index, re-create the file record, queue the first pass.
852
+ * Each file appears in the chat as a "Reindexing" row. Never rejects; resolves to
853
+ * the number of files queued.
854
+ */
855
+ reindexStoredFiles(list: Array<{ storagePath: string; name?: string; size?: number; mime?: string }>): Promise<number> {
856
+ var self = this;
857
+ var id = this.host.getIdentity();
858
+ var queued = 0;
859
+ if (!id.projectId || (id.platform !== 'claude' && id.platform !== 'openai')) return Promise.resolve(0);
860
+ var chain: Promise<any> = Promise.resolve();
861
+ (list || []).forEach(function (d) {
862
+ if (!d || !d.storagePath) return;
863
+ var storagePath = d.storagePath;
864
+ var name = d.name || storagePath.split('/').filter(Boolean).pop() || storagePath;
865
+ var mime = d.mime || self.host.getMimeType(name) || undefined;
866
+ chain = chain.then(function () {
867
+ var claimed = false;
868
+ var url = '';
869
+ var group: 'public' | 'authorized' | 'private' | undefined;
870
+ return self.claimIndexRun(storagePath).then(function (ok) {
871
+ claimed = ok;
872
+ if (!ok) return; // already being indexed
873
+ return Promise.resolve(self.host.getTemporaryUrl(storagePath)).then(function (u: any) {
874
+ url = typeof u === 'string' ? u : (u && u.url) || '';
875
+ if (!url) return;
876
+ return typeof self.host.readFileAccessGroup === 'function'
877
+ ? Promise.resolve(self.host.readFileAccessGroup(storagePath)).then(function (g) { group = g || undefined; })
878
+ : undefined;
879
+ }).then(function () {
880
+ if (!url) return;
881
+ if (typeof self.host.deleteExistingFileRecord === 'function') {
882
+ return Promise.resolve(self.host.deleteExistingFileRecord(storagePath)).catch(function () { });
883
+ }
884
+ }).then(function () {
885
+ if (!url) return;
886
+ if (typeof self.host.ensureFileIndexRecord === 'function') {
887
+ return Promise.resolve(self.host.ensureFileIndexRecord(storagePath, { name: name, mime: mime, size: d.size }, group)).catch(function () { });
888
+ }
889
+ }).then(function () {
890
+ if (!url || group || typeof self.host.uploadAccessGroup !== 'function') return;
891
+ // No stored group (the file record was gone): the group the
892
+ // re-created record was just written at.
893
+ return Promise.resolve(self.host.uploadAccessGroup(storagePath)).then(function (g) { group = g || undefined; }).catch(function () { });
894
+ }).then(function () {
895
+ if (!url) { self.releaseIndexRun(storagePath); return; }
896
+ return self.trackIndexDispatch(notifyAgentSaveAttachment({
897
+ platform: id.platform as 'claude' | 'openai',
898
+ model: id.model,
899
+ service: id.projectId,
900
+ publicProjectId: id.publicProjectId,
901
+ owner: id.owner,
902
+ userId: id.userId || id.projectId,
903
+ serviceName: id.serviceName,
904
+ serviceDescription: id.serviceDescription,
905
+ attachment: { name: name, storagePath: storagePath, mime: mime, size: d.size, url: url, accessGroup: group },
906
+ })).then(function (ack: any) {
907
+ if (ack && typeof ack.id === 'string') {
908
+ queued += 1;
909
+ self.bgTaskQueue.push({
910
+ projectId: id.projectId, platform: id.platform as 'claude' | 'openai', id: ack.id,
911
+ filename: name,
912
+ storagePath: storagePath,
913
+ isReindex: true,
914
+ mime: mime,
915
+ size: d.size,
916
+ status: ack.status === 'running' ? 'running' : 'pending',
917
+ poll: ack.poll,
918
+ });
919
+ self.drainBgTaskQueue();
920
+ } else {
921
+ self.releaseIndexRun(storagePath);
922
+ }
923
+ });
924
+ });
925
+ }).catch(function (err: any) {
926
+ console.error('[chat-engine] reindex of a stored file failed', storagePath, err);
927
+ if (claimed) self.releaseIndexRun(storagePath);
928
+ });
929
+ });
930
+ });
931
+ return chain.then(function () { self.drainBgTaskQueue(); return queued; });
932
+ }
933
+
812
934
  /**
813
935
  * The same question, asked of the SERVER when this page cannot answer it.
814
936
  *
@@ -877,11 +999,17 @@ export class ChatSession {
877
999
  */
878
1000
  private _recordLiveIndexKeys(lists: any[]): void {
879
1001
  var next: { [k: string]: boolean } = {};
1002
+ var running: { [k: string]: boolean } = {};
880
1003
  // A page that came back FULL is not a whole-queue answer: the query is capped
881
1004
  // and ordered newest-first, so a bulk upload of 40 files returns the 20 newest
882
1005
  // and omits the 20 about to run. Absence would then read as "finished" for
883
1006
  // exactly the files that have not been touched yet. Report not-knowing instead.
884
1007
  var truncated = false;
1008
+ // The RUNNING half on its own. A file indexes in at most a few parallel lanes, so the
1009
+ // running list practically never fills; the pending one fills on any bulk upload. A
1010
+ // complete running half still proves something when the pending half is cut off: a
1011
+ // file whose run is open and which is not running is waiting its turn.
1012
+ var runningTruncated = false;
885
1013
  // Locally settled already. The adopt path refuses these items for the same
886
1014
  // reason and says why: the status index is eventually consistent, so the pass
887
1015
  // that just finished can still come back as running. Counting it as live work
@@ -895,7 +1023,16 @@ export class ChatSession {
895
1023
  });
896
1024
  for (var li = 0; li < lists.length; li++) {
897
1025
  var list = lists[li] && Array.isArray(lists[li].list) ? lists[li].list : [];
898
- if (list.length >= WORKER_PASS_ADOPT_LIMIT) truncated = true;
1026
+ // Cut off when it came back full OR the server says more exist: a filtered
1027
+ // listing can return fewer rows than asked for and still not be the end, and
1028
+ // reading that page as whole turned every file past it into "Indexed".
1029
+ if (list.length >= WORKER_PASS_ADOPT_LIMIT || (lists[li] && lists[li].endOfList === false)) {
1030
+ truncated = true;
1031
+ // Which half this is, from its items (the callers pass them in either order).
1032
+ for (var si = 0; si < list.length; si++) {
1033
+ if (list[si] && list[si].status === 'running') { runningTruncated = true; break; }
1034
+ }
1035
+ }
899
1036
  for (var i = 0; i < list.length; i++) {
900
1037
  var item = list[i];
901
1038
  if (!item || (item.status !== 'pending' && item.status !== 'running')) continue;
@@ -914,6 +1051,10 @@ export class ChatSession {
914
1051
  // wrong.
915
1052
  if (ref.path) next[ref.path] = true;
916
1053
  if (ref.name) next[ref.name] = true;
1054
+ if (item.status === 'running') {
1055
+ if (ref.path) running[ref.path] = true;
1056
+ if (ref.name) running[ref.name] = true;
1057
+ }
917
1058
  }
918
1059
  }
919
1060
  var nowChecked = !truncated;
@@ -922,7 +1063,25 @@ export class ChatSession {
922
1063
  for (var k in next) if (!was[k]) { changed = true; break; }
923
1064
  if (!changed) for (var k2 in was) if (!next[k2]) { changed = true; break; }
924
1065
  }
1066
+ if (!changed) {
1067
+ var wasRun = this.state.liveIndexRunning || {};
1068
+ for (var r1 in running) if (!wasRun[r1]) { changed = true; break; }
1069
+ if (!changed) for (var r2 in wasRun) if (!running[r2]) { changed = true; break; }
1070
+ }
925
1071
  this.state.liveIndexKeys = next;
1072
+ if (this.state.liveIndexRunningChecked !== !runningTruncated) changed = true;
1073
+ // Files seen to LEAVE the queue: live in the previous look, absent from a complete
1074
+ // one. Kept until the file is live again, so a later look that comes back cut off
1075
+ // (a bulk upload behind it) cannot turn its "Indexed" back into "Indexing".
1076
+ var settledNow = this.state.liveIndexSettled || {};
1077
+ var settledNext: { [k: string]: boolean } = {};
1078
+ for (var sk in settledNow) if (settledNow[sk] && !next[sk]) settledNext[sk] = true;
1079
+ if (nowChecked) {
1080
+ for (var wk in was) if (was[wk] && !next[wk]) { if (!settledNext[wk]) changed = true; settledNext[wk] = true; }
1081
+ }
1082
+ this.state.liveIndexSettled = settledNext;
1083
+ this.state.liveIndexRunning = running;
1084
+ this.state.liveIndexRunningChecked = !runningTruncated;
926
1085
  this.state.liveIndexChecked = nowChecked;
927
1086
  this._liveIndexAt = nowMs();
928
1087
  // Claim the snapshot for the CURRENT chat. Both callers verify identity before
@@ -943,8 +1102,13 @@ export class ChatSession {
943
1102
  * project the user just switched to is unknown until it is asked for again. */
944
1103
  private _resetLiveIndexKeys(): void {
945
1104
  this.state.liveIndexKeys = {};
1105
+ this.state.liveIndexRunning = {};
1106
+ this.state.liveIndexRunningChecked = false;
1107
+ this.state.liveIndexSettled = {};
946
1108
  this.state.liveIndexChecked = false;
947
1109
  this._liveIndexAt = 0;
1110
+ // Steps loaded into rows belong to that chat too.
1111
+ this.state.passPaging = {};
948
1112
  }
949
1113
 
950
1114
  /**
@@ -976,7 +1140,21 @@ export class ChatSession {
976
1140
  // pass-boundary gap the ladder exists for presumes a chain was alive,
977
1141
  // and on an idle tab return the climb was three round trips of asking
978
1142
  // a question whose answer had not changed.
1143
+ //
1144
+ // SKIPPED (2026-11-20) when a look already confirmed the queue idle, no pass on
1145
+ // screen is newer than that, and this page tracks nothing live: then the answer is
1146
+ // known, and every tab return used to ask it again. "Nothing live" is still RECORDED,
1147
+ // as the look would have, so finished rows do not fall back to spinning. A run begun
1148
+ // elsewhere since shows up in the history page this follows (newer `_ts`, or a bg
1149
+ // poll attached to its running item), which is evidence, and the look runs.
1150
+ var sid = this.host.getIdentity().projectId;
1151
+ var idleAt = sid ? this._idleVerdictAt[sid] : 0;
1152
+ if (sid && idleAt && !this._hasLocalLiveIndexWork(sid) && this._newestIndexPassTs() <= idleAt) {
1153
+ this._recordLiveIndexKeys([{ list: [] }, { list: [] }]);
1154
+ return;
1155
+ }
979
1156
  this._adoptWorkerIndexingPasses(0, true);
1157
+ this._ensureAdoptTick();
980
1158
  }
981
1159
 
982
1160
  /** Forget what we know about which files are indexing — but ONLY when the
@@ -2170,6 +2348,7 @@ export class ChatSession {
2170
2348
  if (!isErr) {
2171
2349
  var rNote = extractRetrievalNote(body, text);
2172
2350
  if (rNote) reply._retrieval = rNote;
2351
+ this._saveFindings(itemId, body, text, rNote);
2173
2352
  }
2174
2353
  if (ownerKey && this.getHistoryCacheKey() !== ownerKey) {
2175
2354
  // The reader is in another chat. Settle it where it belongs and touch
@@ -2320,12 +2499,42 @@ export class ChatSession {
2320
2499
  return Promise.resolve()
2321
2500
  .then(function () {
2322
2501
  self.drainBgTaskQueue();
2323
- return self.loadHistory(false, self.state.gateRefreshToken);
2502
+ // History is loaded ONCE (owner, 2026-11-20): coming back to the tab does not
2503
+ // refetch it. What changed while away arrives the way it would have live:
2504
+ // replies through their polls (foreground polls never paused), indexing
2505
+ // passes through the queue check that drainBgTaskQueue restarts. Only a
2506
+ // waiting bubble left with nothing to settle it needs the first page again.
2507
+ if (self.needsHistoryRefetch()) return self.loadHistory(false, self.state.gateRefreshToken);
2508
+ self.refreshLiveIndexState();
2324
2509
  })
2325
2510
  .catch(function (e: any) { console.error('[chat-engine] resume polling failed', e); })
2326
2511
  .then(function () { self._resuming = false; });
2327
2512
  }
2328
2513
 
2514
+ /**
2515
+ * Does the chat on screen need its first history page fetched again to stay right?
2516
+ * Only when a waiting bubble of THIS chat has nothing that will settle it: no live poll
2517
+ * and no entry in bgTaskQueue (whose passes the drain and the queue check follow). Then
2518
+ * the page is the only place its poll handle or its answer can come from (a turn on the
2519
+ * background queue whose poll paused while the tab was hidden, for instance). A bubble
2520
+ * with no server id yet is a send still in flight, which resolves on its own.
2521
+ */
2522
+ needsHistoryRefetch(): boolean {
2523
+ var key = this.getHistoryCacheKey();
2524
+ var tracked: { [id: string]: true } = {};
2525
+ for (var q = 0; q < this.bgTaskQueue.length; q++) if (this.bgTaskQueue[q]) tracked[this.bgTaskQueue[q].id] = true;
2526
+ for (var i = 0; i < this.state.messages.length; i++) {
2527
+ var m = this.state.messages[i];
2528
+ if (!m || !(m.isPending || m.isPendingQueued || m.isPendingInProcess)) continue;
2529
+ if (m._ownerKey !== undefined && m._ownerKey !== key) continue;
2530
+ var sid = m._serverItemId;
2531
+ if (!sid) continue;
2532
+ if (this.historyItemPolls.has(sid) || tracked[sid]) continue;
2533
+ return true;
2534
+ }
2535
+ return false;
2536
+ }
2537
+
2329
2538
  private _newLocalId(): string {
2330
2539
  this._lidSeq += 1;
2331
2540
  return 'lid_' + this._lidSeq;
@@ -2680,7 +2889,7 @@ export class ChatSession {
2680
2889
  answer = (answer || '').trim();
2681
2890
  // Retrieval memory: what this turn read, off the body's tool blocks (a
2682
2891
  // streamed turn's `response` is already the assembled body here).
2683
- return { content: answer || 'No text response received from AI provider.', isError: false, retrieval: extractRetrievalNote(response, answer) };
2892
+ return { content: answer || 'No text response received from AI provider.', isError: false, retrieval: extractRetrievalNote(response, answer), body: response };
2684
2893
  })
2685
2894
  .catch(function (err: any) { return { content: getErrorMessage(err), isError: true }; })
2686
2895
  .then(function (result: any) {
@@ -2700,6 +2909,7 @@ export class ChatSession {
2700
2909
  var reply: ChatMessage = { role: 'assistant', content: result.content, isError: result.isError };
2701
2910
  if (dispatchItemId) reply._serverItemId = dispatchItemId;
2702
2911
  if (result.retrieval) reply._retrieval = result.retrieval;
2912
+ if (!result.isError && result.body) self._saveFindings(dispatchItemId, result.body, result.content, result.retrieval);
2703
2913
 
2704
2914
  // REPLACE the trailing pending "Thinking..." bubble in the cache with
2705
2915
  // the answer, regardless of whether this chat is the currently-visible
@@ -3337,9 +3547,19 @@ export class ChatSession {
3337
3547
  }
3338
3548
 
3339
3549
  promoteNextBgQueuedToRunning(): void {
3340
- if (this.state.messages.some(function (m) { return m.isPending && m.role === 'assistant' && m.isBackgroundTask; })) return;
3550
+ // Passes the queue check follows (byListing) are never promoted by this guess: the
3551
+ // worker runs several at once in any order, so "the next waiting one" is often the
3552
+ // wrong one, and the running listing promotes them by id (_promoteListedRunning).
3553
+ // The guess stays for anything else on the background queue.
3554
+ var listed: { [id: string]: true } = {};
3555
+ for (var q = 0; q < this.bgTaskQueue.length; q++) {
3556
+ var qe = this.bgTaskQueue[q];
3557
+ if (qe && qe.byListing) listed[qe.id] = true;
3558
+ }
3559
+ var guessed = function (m: ChatMessage) { return !(m._serverItemId && listed[m._serverItemId]); };
3560
+ if (this.state.messages.some(function (m) { return m.isPending && m.role === 'assistant' && m.isBackgroundTask && guessed(m); })) return;
3341
3561
  var nextIdx = this.state.messages.findIndex(function (m) {
3342
- return m.isPendingQueued && m.role === 'user' && m.isBackgroundTask;
3562
+ return m.isPendingQueued && m.role === 'user' && m.isBackgroundTask && guessed(m);
3343
3563
  });
3344
3564
  if (nextIdx === -1) return;
3345
3565
  var existing = this.state.messages[nextIdx];
@@ -3538,6 +3758,7 @@ export class ChatSession {
3538
3758
  if (!offReply.isError) {
3539
3759
  var offNote = extractRetrievalNote(response, offReply.content);
3540
3760
  if (offNote) offReply._retrieval = offNote;
3761
+ this._saveFindings(serverId, response, offReply.content, offNote);
3541
3762
  }
3542
3763
  this._applyReplyToCache(ownerKey, offReply, serverId);
3543
3764
  if (serverId) this.cancelledServerIds.delete(serverId);
@@ -3557,6 +3778,7 @@ export class ChatSession {
3557
3778
  // Retrieval memory for this turn, attached to whichever bubble below ends up
3558
3779
  // holding the answer.
3559
3780
  var qNote = extractRetrievalNote(response, answer);
3781
+ this._saveFindings(serverId, response, answer, qNote);
3560
3782
  var lid = this._newLocalId();
3561
3783
  if (targetIdx >= 0 && this.state.messages[targetIdx] && this.state.messages[targetIdx].isPending) {
3562
3784
  // Same resume as the immediate-send path: keep what the stream painted
@@ -4541,6 +4763,7 @@ export class ChatSession {
4541
4763
  // Retrieval memory for a CHAT turn that settled through a re-attached poll.
4542
4764
  // Read once here; the background branches below never use it.
4543
4765
  var hNote = isErr ? null : extractRetrievalNote(response, answer);
4766
+ if (hNote) this._saveFindings(itemId, response, answer, hNote);
4544
4767
  var stripMarker = function (t: string): string {
4545
4768
  return reportedComplete ? t.split(INDEXING_COMPLETE_MARKER).join('').trim() : t;
4546
4769
  };
@@ -4754,7 +4977,502 @@ export class ChatSession {
4754
4977
  * shape that previously looped fetchHistoryPage after an already-DONE index.
4755
4978
  */
4756
4979
  private _adoptingWorkerPasses = false;
4757
- private _adoptWorkerIndexingPasses(attempt: number, passive?: boolean): void {
4980
+ /** Per project: when a look last CONFIRMED the bg queue held nothing pending or running
4981
+ * (2026-11-20). A recent pass older than this is a finished run, not evidence of live
4982
+ * work, so a tab return no longer re-asks for ten minutes after every run. Memory only:
4983
+ * a reload starts without it and asks once, as before. */
4984
+ private _idleVerdictAt: { [svcId: string]: number } = {};
4985
+ private _adoptTickTimer: any = null;
4986
+
4987
+ /** Newest wall-clock `_ts` of any indexing pass on screen, or 0. */
4988
+ private _newestIndexPassTs(): number {
4989
+ var newest = 0;
4990
+ var msgs = this.state.messages;
4991
+ for (var i = 0; i < msgs.length; i++) {
4992
+ var m = msgs[i];
4993
+ if (m && m._indexFile && typeof m._ts === 'number' && m._ts > newest) newest = m._ts;
4994
+ }
4995
+ return newest;
4996
+ }
4997
+
4998
+ /** Live indexing work THIS page is tracking for the project: a queued or adopted pass,
4999
+ * an attached bg poll, or a live key a look recorded. No recency guess. */
5000
+ private _hasLocalLiveIndexWork(svcId: string): boolean {
5001
+ for (var i = 0; i < this.bgTaskQueue.length; i++) {
5002
+ var e = this.bgTaskQueue[i];
5003
+ if (e && e.projectId === svcId) return true;
5004
+ }
5005
+ var keys = this.state.liveIndexKeys || {};
5006
+ for (var k in keys) { if (keys[k]) return true; }
5007
+ var found = false;
5008
+ this.historyItemPolls.forEach(function (h: any) { if (h && h.kind === 'bg') found = true; });
5009
+ return found;
5010
+ }
5011
+
5012
+ /** Start the ADOPT_TICK_MS follow-up if this page is tracking live indexing work and
5013
+ * is visible. Idempotent; each tick re-checks and stops when the work is gone, the tab
5014
+ * is hidden (resume restarts it through refreshLiveIndexState) or the view closed. */
5015
+ private _ensureAdoptTick(): void {
5016
+ if (this._adoptTickTimer) return;
5017
+ var self = this;
5018
+ var id = this.host.getIdentity();
5019
+ if (!id.projectId || (id.platform !== 'claude' && id.platform !== 'openai')) return;
5020
+ if (this.isPollingPaused() || !this.host.isViewMounted()) return;
5021
+ if (!this._hasLocalLiveIndexWork(id.projectId)) return;
5022
+ this._adoptTickTimer = setTimeout(function () {
5023
+ self._adoptTickTimer = null;
5024
+ var now = self.host.getIdentity();
5025
+ if (self.isPollingPaused() || !self.host.isViewMounted()) return;
5026
+ if (now.projectId !== id.projectId) { self._ensureAdoptTick(); return; }
5027
+ if (!self._hasLocalLiveIndexWork(now.projectId)) return;
5028
+ self._adoptWorkerIndexingPasses(0, false, true);
5029
+ self._settleByListing();
5030
+ self._refreshPageProgress();
5031
+ self._ensureAdoptTick();
5032
+ }, ADOPT_TICK_MS);
5033
+ }
5034
+
5035
+ /** The last COMPLETE running+pending look at this user's bg queue: which pass ids were
5036
+ * live. Complete means both lists came back shorter than their limit, so a tracked pass
5037
+ * missing from it really has left the queue. */
5038
+ private _lastLiveLook: { svcId: string; platform: string; at: number; ids: { [id: string]: true } } | null = null;
5039
+ /** By-listing passes whose by-id lookup is in flight, so one tick never reads a pass twice. */
5040
+ private _listingSettling: { [id: string]: true } = {};
5041
+ private _listingLookInflight = false;
5042
+
5043
+ /**
5044
+ * Follow an indexing pass found in a loaded history page through the queue check
5045
+ * instead of polling it (owner, 2026-11-20): polls on one queue run one at a time in
5046
+ * skapi-js, so after a reload mid-run every lane waited behind the first. Only for a
5047
+ * pass the worker drives (a client-driven chain is resumed off its dispatching entry,
5048
+ * whose pass count caps it) and only when the host can read a row by id. True when the
5049
+ * pass is now tracked (the caller then attaches no poll).
5050
+ */
5051
+ trackHistoryIndexPass(item: any): boolean {
5052
+ if (typeof chatEngineConfig().csrHistoryItemLookup !== 'function') return false;
5053
+ if (!item || typeof item.id !== 'string' || !item.id) return false;
5054
+ if (item.status !== 'pending' && item.status !== 'running') return false;
5055
+ for (var q = 0; q < this.bgTaskQueue.length; q++) {
5056
+ if (this.bgTaskQueue[q] && this.bgTaskQueue[q].id === item.id) return !!this.bgTaskQueue[q].byListing;
5057
+ }
5058
+ var id = this.host.getIdentity();
5059
+ var platform = id.platform;
5060
+ if (!id.projectId || (platform !== 'claude' && platform !== 'openai')) return false;
5061
+ var text = typeof item.request_text === 'string' && item.request_text
5062
+ ? item.request_text
5063
+ : extractLastUserTextFromRequest(item.request_body);
5064
+ var ref = parseIndexingRequestText(text);
5065
+ if (!ref || !ref.name) return false;
5066
+ if (!this._isWorkerDrivenIndexing(ref.name, ref.mime)) return false;
5067
+ this.bgTaskQueue.push({
5068
+ projectId: id.projectId,
5069
+ platform: platform,
5070
+ id: item.id,
5071
+ filename: ref.name,
5072
+ storagePath: ref.path,
5073
+ mime: ref.mime,
5074
+ size: ref.size,
5075
+ status: item.status === 'running' ? 'running' : 'pending',
5076
+ poll: typeof item.poll === 'function' ? item.poll : undefined,
5077
+ resumePass: ref.continued ? 1 : 0,
5078
+ byListing: true,
5079
+ adoptedAt: Date.now(),
5080
+ });
5081
+ return true;
5082
+ }
5083
+
5084
+ /**
5085
+ * Show a pass as RUNNING once the queue says it is. A pass this client sent starts out
5086
+ * waiting (the server queues it), and its own poll's running tick used to be what
5087
+ * moved it on. Settled from the listing, it has no poll, so the running listing the
5088
+ * 10-second check already takes does it instead (owner, 2026-11-20).
5089
+ */
5090
+ private _promoteListedRunning(runningRes: any): void {
5091
+ var list = runningRes && Array.isArray(runningRes.list) ? runningRes.list : [];
5092
+ if (!list.length) return;
5093
+ var running: { [id: string]: true } = {};
5094
+ for (var i = 0; i < list.length; i++) if (list[i] && typeof list[i].id === 'string') running[list[i].id] = true;
5095
+ var changed = false;
5096
+ for (var q = 0; q < this.bgTaskQueue.length; q++) {
5097
+ var e = this.bgTaskQueue[q];
5098
+ if (!e || e.status !== 'pending' || !running[e.id]) continue;
5099
+ e.status = 'running';
5100
+ if (this._promoteBgItemToRunning(e.id)) changed = true;
5101
+ }
5102
+ if (changed) {
5103
+ this.host.notify();
5104
+ this.updateHistoryCache();
5105
+ }
5106
+ }
5107
+
5108
+ /** promoteNextBgQueuedToRunning for one named pass: its waiting request bubble becomes
5109
+ * the running one, with a "Thinking..." placeholder under it. False when that pass has
5110
+ * no waiting bubble (already running, settled, or not on screen). */
5111
+ private _promoteBgItemToRunning(itemId: string): boolean {
5112
+ var idx = this.state.messages.findIndex(function (m) {
5113
+ return m.role === 'user' && m.isBackgroundTask && m.isPendingQueued && m._serverItemId === itemId;
5114
+ });
5115
+ if (idx === -1) return false;
5116
+ var existing = this.state.messages[idx];
5117
+ var promoted: ChatMessage = { role: 'user', content: existing.content, isPendingInProcess: true, isBackgroundTask: true, _serverItemId: itemId };
5118
+ if (existing._indexFile) promoted._indexFile = existing._indexFile;
5119
+ if (existing._ts !== undefined) promoted._ts = existing._ts;
5120
+ if (existing._ownerKey !== undefined) promoted._ownerKey = existing._ownerKey;
5121
+ this.state.messages[idx] = promoted;
5122
+ var placeholder: ChatMessage = { role: 'assistant', content: '', isPending: true, isPendingInProcess: true, isBackgroundTask: true, _serverItemId: itemId };
5123
+ if (existing._ownerKey !== undefined) placeholder._ownerKey = existing._ownerKey;
5124
+ this.state.messages.splice(idx + 1, 0, placeholder);
5125
+ return true;
5126
+ }
5127
+
5128
+ /** Turns whose findings were already looked at (a turn can settle by more than one path). */
5129
+ private _findingsDone: { [itemId: string]: true } = {};
5130
+
5131
+ /**
5132
+ * Save where a hard search found its answer (findings.ts), through the host's
5133
+ * saveSearchFinding hook. Never for an indexing pass, never twice for one turn, never
5134
+ * throws, never waited on.
5135
+ */
5136
+ private _saveFindings(itemId: string | undefined, body: any, answer: string | null | undefined, note: RetrievalNote | null | undefined): void {
5137
+ try {
5138
+ var save = chatEngineConfig().saveSearchFinding;
5139
+ if (typeof save !== 'function' || !note || !body) return;
5140
+ if (itemId) {
5141
+ if (this._findingsDone[itemId]) return;
5142
+ this._findingsDone[itemId] = true;
5143
+ }
5144
+ // The question: the user bubble of this turn (same server id), when it is on screen.
5145
+ var question: string | null = null;
5146
+ if (itemId) {
5147
+ for (var i = 0; i < this.state.messages.length; i++) {
5148
+ var m = this.state.messages[i];
5149
+ if (m && m.role === 'user' && m._serverItemId === itemId) {
5150
+ if (m.isBackgroundTask) return; // an indexing pass, not a chat turn
5151
+ question = typeof m.content === 'string' ? m.content : null;
5152
+ break;
5153
+ }
5154
+ }
5155
+ }
5156
+ var found = findingsForTurn({ question: question, body: body, note: note, answer: answer });
5157
+ if (!found.length) return;
5158
+ var id = this.host.getIdentity();
5159
+ if (!id.projectId) return;
5160
+ for (var f = 0; f < found.length; f++) {
5161
+ var payload = Object.assign({ service: id.projectId, owner: id.owner }, found[f]);
5162
+ Promise.resolve(save(payload)).catch(function () { /* best effort */ });
5163
+ }
5164
+ } catch (e) { /* never in the way of the answer */ }
5165
+ }
5166
+
5167
+ /**
5168
+ * Chats-only history (owner, 2026-11-21): on when the host can list a file's passes
5169
+ * (listIndexPasses) and read one by id (csrHistoryItemLookup). The history fetch then
5170
+ * skips the indexing queue, a file's row comes from its run:: record, and opening the
5171
+ * row loads its passes (loadRunPasses), a page at a time.
5172
+ */
5173
+ lazyIndexRowsEnabled(): boolean {
5174
+ var cfg = chatEngineConfig();
5175
+ return typeof cfg.listIndexPasses === 'function' && typeof cfg.csrHistoryItemLookup === 'function';
5176
+ }
5177
+
5178
+ /** How many passes one "Load more" brings into a file's row. */
5179
+ static RUN_PASS_PAGE = 10;
5180
+
5181
+ /** The paging state of a file's passes, or null before its row was first opened. */
5182
+ runPassPaging(storagePath?: string): { ids: string[]; loaded: number; loading: boolean; done: boolean; error?: string } | null {
5183
+ if (!storagePath || !this.state.passPaging) return null;
5184
+ return this.state.passPaging[storagePath] || null;
5185
+ }
5186
+
5187
+ /**
5188
+ * Load the next page of a file's indexing passes into the chat, newest first (owner,
5189
+ * 2026-11-21). The ids come from the file's pass records (listIndexPasses, once), each
5190
+ * pass is read by id (csrHistoryItemLookup) and lands as the same request + reply bubbles
5191
+ * a live pass produces, so its file's row groups it like any other. A pass still running
5192
+ * or waiting is left to the live queue check, which shows it as it settles; one already
5193
+ * in the chat is not read again. Never throws.
5194
+ */
5195
+ loadRunPasses(storagePath: string, fileName?: string): Promise<void> {
5196
+ var self = this;
5197
+ var cfg = chatEngineConfig();
5198
+ var list = cfg.listIndexPasses, lookup = cfg.csrHistoryItemLookup;
5199
+ var id = this.host.getIdentity();
5200
+ var platform = id.platform;
5201
+ if (!storagePath || typeof list !== 'function' || typeof lookup !== 'function') return Promise.resolve();
5202
+ if (!id.projectId || (platform !== 'claude' && platform !== 'openai')) return Promise.resolve();
5203
+ if (!this.state.passPaging) this.state.passPaging = {};
5204
+ var paging = this.state.passPaging[storagePath];
5205
+ if (paging && (paging.loading || paging.done)) return Promise.resolve();
5206
+ if (!paging) {
5207
+ this.state.passPaging[storagePath] = { ids: [], loaded: 0, loading: false, done: false };
5208
+ }
5209
+ // Read back through the state, never the object just stored: a host may hold the state
5210
+ // as a reactive proxy (Vue), and writes to the raw object would never reach the screen.
5211
+ var p = this.state.passPaging[storagePath];
5212
+ p.loading = true;
5213
+ p.error = undefined;
5214
+ this.host.notify();
5215
+ var svcId = id.projectId, owner = id.owner;
5216
+ var name = fileName || storagePath.split('/').pop() || storagePath;
5217
+ var idsReady: Promise<string[]> = p.ids.length
5218
+ ? Promise.resolve(p.ids)
5219
+ : Promise.resolve(list(svcId, storagePath)).then(function (ids) {
5220
+ var clean = (Array.isArray(ids) ? ids : []).filter(function (x) { return typeof x === 'string' && !!x; });
5221
+ // Request ids sort by time ("stamp:entropy", the stamp a time_ns): newest first.
5222
+ clean.sort(function (a, b) { return a < b ? 1 : a > b ? -1 : 0; });
5223
+ p.ids = clean;
5224
+ return clean;
5225
+ });
5226
+ return idsReady.then(function (ids) {
5227
+ var oldest = ids.length ? ids[ids.length - 1] : '';
5228
+ var present: { [rid: string]: true } = {};
5229
+ for (var i = 0; i < self.state.messages.length; i++) {
5230
+ var m = self.state.messages[i];
5231
+ if (m && m._serverItemId) present[m._serverItemId] = true;
5232
+ }
5233
+ // The next RUN_PASS_PAGE steps not already on screen (a step the live check or an
5234
+ // earlier page brought in is passed over, not counted).
5235
+ var page: string[] = [];
5236
+ var next = p.loaded;
5237
+ while (next < ids.length && page.length < ChatSession.RUN_PASS_PAGE) {
5238
+ if (!present[ids[next]]) page.push(ids[next]);
5239
+ next++;
5240
+ }
5241
+ return Promise.all(page.map(function (rid) {
5242
+ return Promise.resolve(lookup!(buildHistoryItemFullId(platform as 'claude' | 'openai', svcId, rid), svcId, owner))
5243
+ .then(function (body: any) { return { rid: rid, body: body, err: null as any }; },
5244
+ function (err: any) { return { rid: rid, body: null, err: err }; });
5245
+ })).then(function (got) {
5246
+ if (self.host.getIdentity().projectId !== svcId) return;
5247
+ var add: ChatMessage[][] = [];
5248
+ for (var g = 0; g < got.length; g++) {
5249
+ var r = got[g];
5250
+ if (!r) continue;
5251
+ var body = r.body;
5252
+ // Live work (running or waiting) is the queue check's to show.
5253
+ if (isCsrStatusEnvelope(body) && (body.status === 'running' || body.status === 'pending')) continue;
5254
+ var notExists = r.err && (r.err.code === 'NOT_EXISTS' || (r.err.body && r.err.body.code === 'NOT_EXISTS'));
5255
+ if (notExists) continue;
5256
+ var continued = r.rid !== oldest;
5257
+ var when = requestIdTimeMs(r.rid);
5258
+ var user: ChatMessage = {
5259
+ role: 'user',
5260
+ content: self.host.formatIndexingLabel(name, undefined, null, storagePath, false, continued),
5261
+ isBackgroundTask: true,
5262
+ _serverItemId: r.rid,
5263
+ _indexFile: { name: name, path: storagePath, isReindex: false, continued: continued },
5264
+ };
5265
+ if (when) user._ts = when;
5266
+ var reply: ChatMessage;
5267
+ if (r.err) {
5268
+ reply = { role: 'assistant', content: getErrorMessage(r.err), isError: true, isBackgroundTask: true, _serverItemId: r.rid };
5269
+ } else if (isCsrStatusEnvelope(body) && body.status === 'cancelled') {
5270
+ user.isCancelled = true;
5271
+ add.push([user]);
5272
+ continue;
5273
+ } else if (isErrorResponseBody(body)) {
5274
+ reply = { role: 'assistant', content: getErrorMessage(body), isError: true, isBackgroundTask: true, _serverItemId: r.rid };
5275
+ } else {
5276
+ var text = ((platform === 'openai' ? extractOpenAIText(body) : extractClaudeText(body)) || '').trim();
5277
+ var complete = text.indexOf(INDEXING_COMPLETE_MARKER) !== -1;
5278
+ if (complete) text = text.split(INDEXING_COMPLETE_MARKER).join('').trim();
5279
+ reply = { role: 'assistant', content: text || EMPTY_INDEXING_REPLY, isBackgroundTask: true, _serverItemId: r.rid };
5280
+ if (complete) reply._indexComplete = true;
5281
+ }
5282
+ if (when) reply._ts = when;
5283
+ add.push([user, reply]);
5284
+ }
5285
+ // Oldest first, each pair at its place in time among the messages.
5286
+ add.sort(function (a, b) { return (a[0]._ts || 0) - (b[0]._ts || 0); });
5287
+ for (var k = 0; k < add.length; k++) self._insertByTime(add[k]);
5288
+ p.loaded = next;
5289
+ p.done = p.loaded >= ids.length;
5290
+ });
5291
+ }).catch(function (err: any) {
5292
+ p.error = getErrorMessage(err) || 'The steps could not be loaded.';
5293
+ }).then(function () {
5294
+ p.loading = false;
5295
+ self.host.notify();
5296
+ self.updateHistoryCache();
5297
+ });
5298
+ }
5299
+
5300
+ /** Insert bubbles before the first message that is newer than them (by `_ts`); messages
5301
+ * without a time are skipped over, and the end of the list takes them otherwise. */
5302
+ private _insertByTime(bubbles: ChatMessage[]): void {
5303
+ var at = bubbles[0] && bubbles[0]._ts;
5304
+ var idx = this.state.messages.length;
5305
+ if (typeof at === 'number') {
5306
+ for (var i = 0; i < this.state.messages.length; i++) {
5307
+ var t = this.state.messages[i] && this.state.messages[i]._ts;
5308
+ if (typeof t === 'number' && t > at) { idx = i; break; }
5309
+ }
5310
+ }
5311
+ Array.prototype.splice.apply(this.state.messages, ([idx, 0] as any[]).concat(bubbles));
5312
+ }
5313
+
5314
+ private _progressInflight = false;
5315
+
5316
+ /**
5317
+ * Refresh the page progress ("175 of 530 pages") of the documents this page is still
5318
+ * tracking passes for, one read per file (config readIndexProgress, the MCP's
5319
+ * prog::<path> record). Runs on the ADOPT_TICK_MS check; a file with nothing tracked is
5320
+ * not asked about. Never throws.
5321
+ */
5322
+ private _refreshPageProgress(): void {
5323
+ var read = chatEngineConfig().readIndexProgress;
5324
+ if (typeof read !== 'function' || this._progressInflight) return;
5325
+ var id = this.host.getIdentity();
5326
+ if (!id.projectId || this.isPollingPaused() || !this.host.isViewMounted()) return;
5327
+ var svcId = id.projectId;
5328
+ var paths: string[] = [];
5329
+ for (var i = 0; i < this.bgTaskQueue.length; i++) {
5330
+ var e = this.bgTaskQueue[i];
5331
+ if (e && e.projectId === svcId && e.storagePath && paths.indexOf(e.storagePath) === -1) paths.push(e.storagePath);
5332
+ }
5333
+ if (!paths.length) return;
5334
+ var self = this;
5335
+ this._progressInflight = true;
5336
+ Promise.all(paths.map(function (path) {
5337
+ return Promise.resolve(read!(svcId, path)).then(function (data) { return { path: path, data: data }; }, function () { return { path: path, data: null }; });
5338
+ })).then(function (rows) {
5339
+ self._progressInflight = false;
5340
+ if (self.host.getIdentity().projectId !== svcId) return;
5341
+ if (!self.state.indexPageProgress) self.state.indexPageProgress = {};
5342
+ var changed = false;
5343
+ for (var r = 0; r < rows.length; r++) {
5344
+ var d: any = rows[r].data;
5345
+ var saved = d && typeof d.pages_saved === 'number' ? d.pages_saved : null;
5346
+ if (saved === null) continue;
5347
+ var total = d && typeof d.pages_total === 'number' && d.pages_total > 0 ? d.pages_total : null;
5348
+ var prev = self.state.indexPageProgress[rows[r].path];
5349
+ if (prev && prev.saved === saved && prev.total === total) continue;
5350
+ self.state.indexPageProgress[rows[r].path] = { saved: saved, total: total, at: Date.now() };
5351
+ changed = true;
5352
+ }
5353
+ if (changed) self.host.notify();
5354
+ }, function () { self._progressInflight = false; });
5355
+ }
5356
+
5357
+ /** The page progress to show for a file's row, or null (see _refreshPageProgress). */
5358
+ pageProgressFor(storagePath?: string, fileName?: string): { saved: number; total: number | null } | null {
5359
+ var map = this.state.indexPageProgress;
5360
+ if (!map) return null;
5361
+ var p = storagePath ? map[storagePath] : undefined;
5362
+ // A row put together from passes the queue check just found can lack its storage
5363
+ // path for a moment (the first of them carries it); the file NAME still finds the
5364
+ // progress then, when exactly one file of that name is being followed.
5365
+ if (!p && fileName) {
5366
+ var hit: string | null = null;
5367
+ for (var k in map) {
5368
+ if (k === fileName || k.slice(-(fileName.length + 1)) === '/' + fileName) {
5369
+ if (hit) { hit = null; break; }
5370
+ hit = k;
5371
+ }
5372
+ }
5373
+ if (hit) p = map[hit];
5374
+ }
5375
+ return p ? { saved: p.saved, total: p.total } : null;
5376
+ }
5377
+
5378
+ private _noteLiveLook(svcId: string, platform: 'claude' | 'openai', results: any[]): void {
5379
+ var ids: { [id: string]: true } = {};
5380
+ var complete = true;
5381
+ for (var r = 0; r < results.length; r++) {
5382
+ var list = results[r] && Array.isArray(results[r].list) ? results[r].list : [];
5383
+ if (list.length >= WORKER_PASS_ADOPT_LIMIT || (results[r] && results[r].endOfList === false)) complete = false;
5384
+ for (var i = 0; i < list.length; i++) if (list[i] && typeof list[i].id === 'string') ids[list[i].id] = true;
5385
+ }
5386
+ this._lastLiveLook = complete ? { svcId: svcId, platform: platform, at: Date.now(), ids: ids } : null;
5387
+ }
5388
+
5389
+ /**
5390
+ * Settle indexing passes from the queue instead of from their own polls (owner,
5391
+ * 2026-11-20): the worker's lanes AND the first passes this client sent. Runs on the
5392
+ * ADOPT_TICK_MS check, beside the adoption look.
5393
+ *
5394
+ * WHY. skapi-js runs every poll on one queue one at a time, each until its request
5395
+ * finishes. The worker runs a document's windows in parallel lanes on that one queue, so
5396
+ * a lane that finished waited behind every pass ahead of it (measured: passes done at
5397
+ * 17:04 shown at 17:06-17:07, one every ~5 s, after a 3-minute first pass).
5398
+ *
5399
+ * HOW. One compact listing each of the queue's `resolved` and `failed` rows (stubs, no
5400
+ * bodies). A tracked pass found there, or one missing from a COMPLETE running+pending look
5401
+ * taken after it was adopted (cancelled, removed), is read ONCE by id through the host's
5402
+ * csrHistoryItemLookup, the same row a poll's last read returns, and settled through
5403
+ * _settleBgOutcome exactly as its poll would have been. A lookup that still says
5404
+ * running/pending (the status index lags the table) leaves the pass for the next tick.
5405
+ */
5406
+ private _settleByListing(): void {
5407
+ var self = this;
5408
+ if (this._listingLookInflight) return;
5409
+ var lookup = chatEngineConfig().csrHistoryItemLookup;
5410
+ if (typeof lookup !== 'function') return;
5411
+ var id = this.host.getIdentity();
5412
+ var platform = id.platform;
5413
+ if (!id.projectId || (platform !== 'claude' && platform !== 'openai')) return;
5414
+ if (this.isPollingPaused() || !this.host.isViewMounted()) return;
5415
+ var svcId = id.projectId, owner = id.owner;
5416
+ var waiting: BgTaskEntry[] = [];
5417
+ for (var i = 0; i < this.bgTaskQueue.length; i++) {
5418
+ var e = this.bgTaskQueue[i];
5419
+ if (e && e.byListing && e.projectId === svcId && e.platform === platform && !this._listingSettling[e.id]) waiting.push(e);
5420
+ }
5421
+ if (!waiting.length) return;
5422
+ var queue = bgIndexingQueueName(id.userId, svcId);
5423
+ var ask = function (status: 'resolved' | 'failed') {
5424
+ return Promise.resolve(getChatHistory(
5425
+ { service: svcId, owner: owner, platform: platform as 'claude' | 'openai', queue: queue, status: status, queue_exact: true, compact: true },
5426
+ { limit: WORKER_PASS_ADOPT_LIMIT, fetchMore: false },
5427
+ )).then(function (res: any) { return res && Array.isArray(res.list) ? res.list : []; })
5428
+ .catch(function () { return []; });
5429
+ };
5430
+ this._listingLookInflight = true;
5431
+ Promise.all([ask('resolved'), ask('failed')]).then(function (lists: any[][]) {
5432
+ self._listingLookInflight = false;
5433
+ var now = self.host.getIdentity();
5434
+ if (now.projectId !== svcId || now.platform !== platform || !self.host.isViewMounted()) return;
5435
+ var finished: { [id: string]: any } = {};
5436
+ for (var l = 0; l < lists.length; l++) {
5437
+ for (var k = 0; k < lists[l].length; k++) {
5438
+ var row = lists[l][k];
5439
+ if (row && typeof row.id === 'string') finished[row.id] = row;
5440
+ }
5441
+ }
5442
+ var look = self._lastLiveLook;
5443
+ var lookUsable = !!look && look.svcId === svcId && look.platform === platform && Date.now() - look.at <= 2 * ADOPT_TICK_MS;
5444
+ for (var w = 0; w < waiting.length; w++) {
5445
+ var entry = waiting[w];
5446
+ if (self.bgTaskQueue.indexOf(entry) === -1) continue; // settled meanwhile (history, cancel)
5447
+ var row2 = finished[entry.id];
5448
+ var leftQueue = !row2 && lookUsable && !look!.ids[entry.id]
5449
+ && typeof entry.adoptedAt === 'number' && entry.adoptedAt < look!.at;
5450
+ if (!row2 && !leftQueue) continue;
5451
+ self._settleListedEntry(entry, platform as 'claude' | 'openai', lookup,
5452
+ row2 && typeof row2.executed === 'number' && row2.executed > 0 ? row2.executed : undefined);
5453
+ }
5454
+ }, function () { self._listingLookInflight = false; });
5455
+ }
5456
+
5457
+ /** One by-id read of a by-listing pass, then the shared settle. */
5458
+ private _settleListedEntry(entry: BgTaskEntry, platform: 'claude' | 'openai', lookup: (fullId: string, service: string, owner: string) => Promise<any>, executedAt: number | undefined): void {
5459
+ var self = this;
5460
+ var id = this.host.getIdentity();
5461
+ this._listingSettling[entry.id] = true;
5462
+ Promise.resolve(lookup(buildHistoryItemFullId(platform, entry.projectId, entry.id), entry.projectId, id.owner)).then(function (body: any) {
5463
+ delete self._listingSettling[entry.id];
5464
+ if (self.bgTaskQueue.indexOf(entry) === -1) return;
5465
+ // Still going by the table's own reading: leave it for the next tick.
5466
+ if (isCsrStatusEnvelope(body) && (body.status === 'running' || body.status === 'pending')) return;
5467
+ self._settleBgOutcome(entry, platform, Promise.resolve(body), function () { return executedAt; });
5468
+ }, function (err: any) {
5469
+ delete self._listingSettling[entry.id];
5470
+ if (self.bgTaskQueue.indexOf(entry) === -1) return;
5471
+ self._settleBgOutcome(entry, platform, Promise.reject(err), function () { return executedAt; });
5472
+ });
5473
+ }
5474
+
5475
+ private _adoptWorkerIndexingPasses(attempt: number, passive?: boolean, single?: boolean): void {
4758
5476
  var self = this;
4759
5477
  // One in flight at a time. The query is queue-WIDE, so a second file's pass
4760
5478
  // settling in the same moment is covered by the query already running.
@@ -4790,13 +5508,35 @@ export class ChatSession {
4790
5508
  // list — harmless there (nothing to adopt) but not here: recording it would
4791
5509
  // publish "the queue holds nothing" on the strength of a request that never
4792
5510
  // answered, which reads as finished. Not knowing is the honest state.
4793
- if (results[0] !== null && results[1] !== null) self._recordLiveIndexKeys(results);
5511
+ if (results[0] !== null && results[1] !== null) {
5512
+ self._recordLiveIndexKeys(results);
5513
+ self._noteLiveLook(svcId, platform as 'claude' | 'openai', results);
5514
+ // A file the queue still works on keeps being looked at until it leaves the
5515
+ // queue, even when this page tracks none of its passes (a reload, or a run
5516
+ // started elsewhere): its row is drawn from the look, and a look nobody
5517
+ // repeats would leave the row "Indexing" after the run had ended.
5518
+ self._ensureAdoptTick();
5519
+ }
5520
+ if (results[0] !== null) self._promoteListedRunning(results[0]);
5521
+ // Both queries answered and both empty: the queue holds nothing for this user.
5522
+ var emptyLook = results[0] !== null && results[1] !== null
5523
+ && !((results[0].list || []).length) && !((results[1].list || []).length);
4794
5524
  var adoptedIds: string[] = [];
5525
+ // OLDEST FIRST, across both lists. A file's row starts at the first pass the
5526
+ // grouping meets: adopted in the queue's own order (running, then pending, each
5527
+ // newest first), a run's "continuing" passes landed before its opening pass, and
5528
+ // the run drew two rows until the opening pass settled. Request ids sort by time.
5529
+ var found: any[] = [];
4795
5530
  for (var ri = 0; ri < results.length; ri++) {
4796
5531
  var list = results[ri] && Array.isArray(results[ri].list) ? results[ri].list : [];
4797
- for (var i = 0; i < list.length; i++) {
4798
- if (self._adoptWorkerIndexingItem(list[i], svcId, platform as 'claude' | 'openai')) adoptedIds.push(list[i].id);
4799
- }
5532
+ for (var i = 0; i < list.length; i++) if (list[i]) found.push(list[i]);
5533
+ }
5534
+ found.sort(function (a: any, b: any) {
5535
+ var x = String(a.id || ''), y = String(b.id || '');
5536
+ return x < y ? -1 : x > y ? 1 : 0;
5537
+ });
5538
+ for (var fi = 0; fi < found.length; fi++) {
5539
+ if (self._adoptWorkerIndexingItem(found[fi], svcId, platform as 'claude' | 'openai')) adoptedIds.push(found[fi].id);
4800
5540
  }
4801
5541
  if (adoptedIds.length) {
4802
5542
  self.drainBgTaskQueue();
@@ -4807,8 +5547,10 @@ export class ChatSession {
4807
5547
  // pass belonging to a file the user stopped is dropped on sight. Both
4808
5548
  // used to read as "found the next pass", which ended the search for a
4809
5549
  // pass that had not been written yet.
4810
- if (self._isTrackingAny(adoptedIds)) return;
5550
+ if (self._isTrackingAny(adoptedIds)) { self._ensureAdoptTick(); return; }
4811
5551
  }
5552
+ // A periodic look (_ensureAdoptTick) never climbs: the next tick is its retry.
5553
+ if (single) return;
4812
5554
  // Nothing yet. The worker writes pass N+1 a few milliseconds AFTER it
4813
5555
  // flips pass N to resolved, so a poll that lands in that gap sees an
4814
5556
  // empty queue for a chain that is very much alive — and with no pass
@@ -4822,8 +5564,12 @@ export class ChatSession {
4822
5564
  // re-asked an unchanged question three more times on every tab return.
4823
5565
  // (No nudge here either: a send waiting on indexing implies local
4824
5566
  // entries, which IS evidence, so the passive stop never starves it.)
4825
- if (passive && !self._hasLiveIndexEvidence(svcId)) return;
5567
+ if (passive && !self._hasLiveIndexEvidence(svcId)) {
5568
+ if (emptyLook) self._idleVerdictAt[svcId] = Date.now();
5569
+ return;
5570
+ }
4826
5571
  if (attempt + 1 >= WORKER_PASS_ADOPT_ATTEMPTS.length) {
5572
+ if (emptyLook) self._idleVerdictAt[svcId] = Date.now();
4827
5573
  // The ladder is the only thing that can tell a worker-driven chain has
4828
5574
  // really ended, and it just did. This is the earliest honest moment to
4829
5575
  // let a turn waiting on these files stop waiting.
@@ -4878,6 +5624,9 @@ export class ChatSession {
4878
5624
  // true for any chat that has ever indexed anything: exactly the always-climb
4879
5625
  // this gate was added to stop.
4880
5626
  var cutoff = Date.now() - RECENT_INDEX_PASS_EVIDENCE_MS;
5627
+ // A pass from before the last confirmed-idle look belongs to a run that is over.
5628
+ var idleAt = this._idleVerdictAt[svcId] || 0;
5629
+ if (idleAt > cutoff) cutoff = idleAt;
4881
5630
  var msgs = this.state.messages;
4882
5631
  for (var mi = msgs.length - 1; mi >= 0; mi--) {
4883
5632
  var m = msgs[mi];
@@ -4949,6 +5698,10 @@ export class ChatSession {
4949
5698
  // _applyIndexCancellations, which must not read a CONTINUE pass as the
4950
5699
  // fresh first pass that lifts a stop.
4951
5700
  resumePass: ref.continued ? 1 : 0,
5701
+ // Settled by the 10-second queue check when the host can look a row up by id
5702
+ // (csrHistoryItemLookup); otherwise polled as before.
5703
+ byListing: typeof chatEngineConfig().csrHistoryItemLookup === 'function',
5704
+ adoptedAt: Date.now(),
4952
5705
  });
4953
5706
  return true;
4954
5707
  }
@@ -4983,6 +5736,8 @@ export class ChatSession {
4983
5736
  // pass of a stopped file that reached the chat through history.
4984
5737
  this._applyIndexCancellations();
4985
5738
  this._sweepCancelledIndexing();
5739
+ // A dispatched or adopted pass is live work: follow the run while the tab shows it.
5740
+ this._ensureAdoptTick();
4986
5741
  // Index messages by _serverItemId ONCE, so the per-entry presence/pending
4987
5742
  // checks below are O(1) instead of a full messages.some() scan each. With a
4988
5743
  // large bg queue (bulk uploads) the old nested scan was O(queue x messages)
@@ -5016,6 +5771,13 @@ export class ChatSession {
5016
5771
  // entry; only the polling is rationed, and an unpolled entry picks up a
5017
5772
  // poll on the drain that follows the next resolution.
5018
5773
  var bgPollBudget = MAX_CONCURRENT_BG_POLLS - this._countBgPolls();
5774
+ // Every indexing pass is settled by the 10-second queue check rather than by its own
5775
+ // poll when the host can read a row by id (owner, 2026-11-20): first passes too, not
5776
+ // only the worker's lanes. skapi-js runs a queue's polls one at a time, so a file's
5777
+ // first pass that finished waited behind another file's (a PDF's first pass runs for
5778
+ // minutes). Decided HERE, the one place polls are attached, so a pass added by any
5779
+ // caller (this engine, agent.vue, the files page) is covered alike.
5780
+ var listingSettles = typeof chatEngineConfig().csrHistoryItemLookup === 'function';
5019
5781
  // Set by the injection branch; drives the single render/cache/scroll below.
5020
5782
  var injectedAny = false;
5021
5783
  this.bgTaskQueue.forEach(function (entry) {
@@ -5085,11 +5847,17 @@ export class ChatSession {
5085
5847
  // are gone.
5086
5848
  injectedAny = true;
5087
5849
  }
5088
- if (bgPollBudget > 0 && !self.isPollingPaused() && !self.historyItemPolls.has(entry.id) && typeof entry.poll === 'function') {
5850
+ if (listingSettles && !entry.byListing) {
5851
+ entry.byListing = true;
5852
+ if (typeof entry.adoptedAt !== 'number') entry.adoptedAt = Date.now();
5853
+ }
5854
+ // A by-listing pass is never polled: the 10-second queue check settles it
5855
+ // (_settleByListing), so it neither waits in skapi-js's per-queue poll line nor
5856
+ // spends this budget.
5857
+ if (!entry.byListing && bgPollBudget > 0 && !self.isPollingPaused() && !self.historyItemPolls.has(entry.id) && typeof entry.poll === 'function') {
5089
5858
  bgPollBudget--;
5090
- var capturedId = entry.id, capturedPlat = plat;
5859
+ var capturedPlat = plat;
5091
5860
  var capturedEntry = entry;
5092
- var wasStopped = false;
5093
5861
  // When the worker BEGAN running this pass. It rides on the poll's status
5094
5862
  // envelope (a running tick), never on the terminal read, which hands back
5095
5863
  // the destination's own body. Captured here so a settled pass can show how
@@ -5104,68 +5872,7 @@ export class ChatSession {
5104
5872
  },
5105
5873
  });
5106
5874
  self._trackPoll(entry.id, 'bg', bp);
5107
- bp.then(function (response: any) {
5108
- // A stopped poll is not a result: leave the bubble and the queue entry
5109
- // exactly as they were so resumePolling can re-attach.
5110
- if (isPollStopped(response)) { wasStopped = true; return; }
5111
- self.handleHistoryItemResolution(capturedId, response, capturedPlat, executedAt);
5112
- self.maybeResumeIndexing(capturedEntry, response, capturedPlat);
5113
- }).catch(function (err: any) {
5114
- self.historyItemPolls.delete(capturedId);
5115
- var isNotExists = err && (err.code === 'NOT_EXISTS' || (err.body && err.body.code === 'NOT_EXISTS'));
5116
- // Settle the REQUEST bubble first, unconditionally. Only a RUNNING
5117
- // pass gets an assistant placeholder, so for a queued one the lookup
5118
- // below finds nothing and every branch was skipped — leaving the
5119
- // request bubble isPendingQueued with its queue entry about to be
5120
- // spliced away, i.e. no poll left to ever clear it. One such bubble
5121
- // pins the whole collapsed row to "active": a spinner and a Stop
5122
- // button against a dead id, until the page is reloaded.
5123
- self._clearPendingUserBubble(capturedId);
5124
- var bi = self.state.messages.findIndex(function (m) { return m.isPending && m._serverItemId === capturedId; });
5125
- if (bi !== -1) {
5126
- if (isNotExists) self.state.messages.splice(bi, 1);
5127
- else self.state.messages[bi] = { role: 'assistant', content: getErrorMessage(err), isError: true, isBackgroundTask: true, _serverItemId: capturedId };
5128
- } else if (!isNotExists) {
5129
- // No placeholder to turn into the error (a queued pass). Put one
5130
- // after the request bubble so the row reports the failure instead
5131
- // of quietly settling to "Indexed".
5132
- var ui = self.state.messages.findIndex(function (m) { return m.role === 'user' && m._serverItemId === capturedId; });
5133
- if (ui !== -1) {
5134
- self.state.messages.splice(ui + 1, 0, { role: 'assistant', content: getErrorMessage(err), isError: true, isBackgroundTask: true, _serverItemId: capturedId });
5135
- }
5136
- }
5137
- self.host.notify(); self.updateHistoryCache();
5138
- // A pass that FAILED dispatches no continuation on any path, so a
5139
- // CLIENT-driven file is finished either way — let a turn waiting on it
5140
- // look now. Not for a worker-driven one: this catch also fires on a
5141
- // dropped poll, and the worker may have resolved that pass and written
5142
- // the next one regardless. Nudging there would pull the two confirming
5143
- // looks into the window where the new pass is not yet in the status
5144
- // index, which is the same way a nudge on work STARTING went wrong.
5145
- if (!self._isWorkerDrivenIndexing(capturedEntry.filename, capturedEntry.mime)) {
5146
- // Also close the run record: for a CLIENT-driven file a failed
5147
- // pass ends the chain on every path, and a removed row reads as
5148
- // a cancel. Worker-driven files are excluded for the same reason
5149
- // as the nudge — this catch fires on dropped polls too, and the
5150
- // worker may be writing the next pass regardless.
5151
- if (isNotExists) self._flipRunRecord(capturedEntry, 'cancelled');
5152
- else self._flipRunRecord(capturedEntry, 'error', self._runErrorText(err));
5153
- self._nudgeIndexingDrain();
5154
- }
5155
- }).then(function () {
5156
- // Keep the queue entry when the poll was merely stopped, or resuming
5157
- // would have nothing left to re-attach to.
5158
- if (wasStopped) return;
5159
- var qi = self.bgTaskQueue.findIndex(function (q) { return q.id === capturedId; });
5160
- if (qi !== -1) self.bgTaskQueue.splice(qi, 1);
5161
- // This resolution freed a slot in the MAX_CONCURRENT_BG_POLLS budget,
5162
- // so hand it to the next-oldest unpolled entry. Load-bearing under the
5163
- // cap: with thousands of entries queued, only the handful holding
5164
- // polls can ever settle, and without this re-drain the remaining
5165
- // entries would sit unpolled forever. Not left to a host-side watcher
5166
- // on bgTaskQueue — agent.vue has one, the widget does not.
5167
- self.drainBgTaskQueue();
5168
- });
5875
+ self._settleBgOutcome(capturedEntry, capturedPlat, bp, function () { return executedAt; });
5169
5876
  }
5170
5877
  });
5171
5878
  // One render, one cache write, one scroll for the whole drain — however many
@@ -5178,6 +5885,83 @@ export class ChatSession {
5178
5885
  this.promoteNextBgQueuedToRunning();
5179
5886
  }
5180
5887
 
5888
+
5889
+ /**
5890
+ * Settle one background pass from the outcome of reading it: its poll (drainBgTaskQueue)
5891
+ * or a single by-id lookup made by the 10-second queue check (_settleByListing). Both
5892
+ * read the same row the same way, so they share this one path: the resolution, the
5893
+ * resume/chain follow-up, the failure bubble and run record, and the queue entry's removal.
5894
+ * A stopped poll (isPollStopped) leaves the bubble and the entry as they were.
5895
+ */
5896
+ private _settleBgOutcome(entry: BgTaskEntry, plat: 'claude' | 'openai', outcome: Promise<any>, getExecutedAt: () => number | undefined): void {
5897
+ var self = this;
5898
+ var capturedId = entry.id, capturedPlat = plat;
5899
+ var capturedEntry = entry;
5900
+ var wasStopped = false;
5901
+ outcome.then(function (response: any) {
5902
+ // A stopped poll is not a result: leave the bubble and the queue entry
5903
+ // exactly as they were so resumePolling can re-attach.
5904
+ if (isPollStopped(response)) { wasStopped = true; return; }
5905
+ self.handleHistoryItemResolution(capturedId, response, capturedPlat, getExecutedAt());
5906
+ self.maybeResumeIndexing(capturedEntry, response, capturedPlat);
5907
+ }).catch(function (err: any) {
5908
+ self.historyItemPolls.delete(capturedId);
5909
+ var isNotExists = err && (err.code === 'NOT_EXISTS' || (err.body && err.body.code === 'NOT_EXISTS'));
5910
+ // Settle the REQUEST bubble first, unconditionally. Only a RUNNING
5911
+ // pass gets an assistant placeholder, so for a queued one the lookup
5912
+ // below finds nothing and every branch was skipped — leaving the
5913
+ // request bubble isPendingQueued with its queue entry about to be
5914
+ // spliced away, i.e. no poll left to ever clear it. One such bubble
5915
+ // pins the whole collapsed row to "active": a spinner and a Stop
5916
+ // button against a dead id, until the page is reloaded.
5917
+ self._clearPendingUserBubble(capturedId);
5918
+ var bi = self.state.messages.findIndex(function (m) { return m.isPending && m._serverItemId === capturedId; });
5919
+ if (bi !== -1) {
5920
+ if (isNotExists) self.state.messages.splice(bi, 1);
5921
+ else self.state.messages[bi] = { role: 'assistant', content: getErrorMessage(err), isError: true, isBackgroundTask: true, _serverItemId: capturedId };
5922
+ } else if (!isNotExists) {
5923
+ // No placeholder to turn into the error (a queued pass). Put one
5924
+ // after the request bubble so the row reports the failure instead
5925
+ // of quietly settling to "Indexed".
5926
+ var ui = self.state.messages.findIndex(function (m) { return m.role === 'user' && m._serverItemId === capturedId; });
5927
+ if (ui !== -1) {
5928
+ self.state.messages.splice(ui + 1, 0, { role: 'assistant', content: getErrorMessage(err), isError: true, isBackgroundTask: true, _serverItemId: capturedId });
5929
+ }
5930
+ }
5931
+ self.host.notify(); self.updateHistoryCache();
5932
+ // A pass that FAILED dispatches no continuation on any path, so a
5933
+ // CLIENT-driven file is finished either way — let a turn waiting on it
5934
+ // look now. Not for a worker-driven one: this catch also fires on a
5935
+ // dropped poll, and the worker may have resolved that pass and written
5936
+ // the next one regardless. Nudging there would pull the two confirming
5937
+ // looks into the window where the new pass is not yet in the status
5938
+ // index, which is the same way a nudge on work STARTING went wrong.
5939
+ if (!self._isWorkerDrivenIndexing(capturedEntry.filename, capturedEntry.mime)) {
5940
+ // Also close the run record: for a CLIENT-driven file a failed
5941
+ // pass ends the chain on every path, and a removed row reads as
5942
+ // a cancel. Worker-driven files are excluded for the same reason
5943
+ // as the nudge — this catch fires on dropped polls too, and the
5944
+ // worker may be writing the next pass regardless.
5945
+ if (isNotExists) self._flipRunRecord(capturedEntry, 'cancelled');
5946
+ else self._flipRunRecord(capturedEntry, 'error', self._runErrorText(err));
5947
+ self._nudgeIndexingDrain();
5948
+ }
5949
+ }).then(function () {
5950
+ // Keep the queue entry when the poll was merely stopped, or resuming
5951
+ // would have nothing left to re-attach to.
5952
+ if (wasStopped) return;
5953
+ var qi = self.bgTaskQueue.findIndex(function (q) { return q.id === capturedId; });
5954
+ if (qi !== -1) self.bgTaskQueue.splice(qi, 1);
5955
+ // This resolution freed a slot in the MAX_CONCURRENT_BG_POLLS budget,
5956
+ // so hand it to the next-oldest unpolled entry. Load-bearing under the
5957
+ // cap: with thousands of entries queued, only the handful holding
5958
+ // polls can ever settle, and without this re-drain the remaining
5959
+ // entries would sit unpolled forever. Not left to a host-side watcher
5960
+ // on bgTaskQueue — agent.vue has one, the widget does not.
5961
+ self.drainBgTaskQueue();
5962
+ });
5963
+ }
5964
+
5181
5965
  // Resume-across-passes: if a background INDEXING task for a paged file (spreadsheet or
5182
5966
  // text) finished WITHOUT the completion marker, the agent ran out of room before reading
5183
5967
  // the whole file - dispatch a CONTINUE pass (up to a cap) that resumes from where the
@@ -5417,6 +6201,8 @@ export class ChatSession {
5417
6201
  this._resetLiveIndexKeys();
5418
6202
  }
5419
6203
  if (fetchMore) this.state.loadingOlderHistory = true;
6204
+ // A first page replaces the messages, and with them any steps loaded into rows.
6205
+ if (!fetchMore) this.state.passPaging = {};
5420
6206
  this.host.notify(); // surface "Fetching history..." while it loads
5421
6207
  var platform = id.platform as 'claude' | 'openai';
5422
6208
  var projectId = id.projectId, owner = id.owner;
@@ -5438,6 +6224,8 @@ export class ChatSession {
5438
6224
  // share. Read this device's own queue instead. See
5439
6225
  // scopeSurfaceToQueue.
5440
6226
  scopeSurfaceToQueue: !!id.anonymous,
6227
+ // Chats only when a file's row can load its own passes (lazyIndexRowsEnabled).
6228
+ skipBg: self.lazyIndexRowsEnabled(),
5441
6229
  }, options);
5442
6230
  };
5443
6231
 
@@ -5867,6 +6655,9 @@ export class ChatSession {
5867
6655
  // poll had since died — with no live poller, leaving a "Thinking..."
5868
6656
  // that never clears even after the server settled everything.
5869
6657
  if (self.historyItemPolls.has(item.id)) return;
6658
+ // An indexing pass the worker drives is followed by the queue check, not
6659
+ // polled (see trackHistoryIndexPass).
6660
+ if (item._isBgTask && self.trackHistoryIndexPass(item)) return;
5870
6661
  // An in-flight immediate dispatch polls its own MAIN-QUEUE item but
5871
6662
  // registers that id in historyItemPolls only AFTER its provider POST
5872
6663
  // returns; in the sliver before that, a remount can surface the item
@@ -5997,6 +6788,12 @@ export class ChatSession {
5997
6788
  uploadSingleAttachment(att: any, stageId?: string): Promise<Array<{ name: string; url: string; storagePath: string }>> {
5998
6789
  var self = this;
5999
6790
  var id = this.host.getIdentity();
6791
+ // Read BEFORE the status is reset below: a chip in "indexError" is one whose
6792
+ // bytes are already stored and only whose indexing failed. Its retry (the next
6793
+ // Send) re-indexes the stored copies through the "file is already there,
6794
+ // reindex it" path: no second upload, no "already exists" question about the
6795
+ // user's own file, no duplicate check (agent.vue isIndexRetry).
6796
+ var isIndexRetry = att.status === 'indexError';
6000
6797
  // progress stays null until the first byte-progress event. Every upload
6001
6798
  // opens with a get-signed-url round trip that reports nothing, so a chip
6002
6799
  // initialised to 0 rendered an empty, motionless bar for the whole
@@ -6016,6 +6813,10 @@ export class ChatSession {
6016
6813
  // below). Counted so a folder chip can say how many it reused.
6017
6814
  var reusedCount = 0;
6018
6815
  att.reused = false;
6816
+ // The members skipped as duplicates, with the STORED copy each one matched, so
6817
+ // the host can report them after the send and offer to reindex the stored
6818
+ // copies (reindexStoredFiles). A retry decides afresh.
6819
+ delete att.duplicates;
6019
6820
  var chain: Promise<any> = Promise.resolve();
6020
6821
  // "Already uploaded by this user, same name and size" -> the stored copy's
6021
6822
  // storage path, else null. Asked only while the skip-duplicates switch
@@ -6059,7 +6860,9 @@ export class ChatSession {
6059
6860
  onProgress: onProg, setAbort: function (abort) { att._abort = abort; },
6060
6861
  });
6061
6862
  };
6062
- return findDuplicate(member).then(function (dup) {
6863
+ if (isIndexRetry) { hadExists = true; existedBefore = true; }
6864
+ return (isIndexRetry ? Promise.resolve(null) : findDuplicate(member)).then(function (dup) {
6865
+ if (isIndexRetry) return;
6063
6866
  if (dup) {
6064
6867
  duplicateOf = dup;
6065
6868
  console.log('[chat-engine] skipping an upload the user already has:', member.storagePath, '->', dup);
@@ -6090,11 +6893,34 @@ export class ChatSession {
6090
6893
  // A duplicate takes the STORED copy's url: the same reuse an EXISTS
6091
6894
  // answer gets when the user keeps the file, minus the prompt and
6092
6895
  // minus the re-index.
6093
- return self.host.getTemporaryUrl(duplicateOf || member.storagePath);
6896
+ return Promise.resolve(self.host.getTemporaryUrl(duplicateOf || member.storagePath)).catch(function (err: any) {
6897
+ // A file nobody has indexed yet is readable by the project OWNER only
6898
+ // (the store's access rule), so for any other uploader the link to the
6899
+ // file they just uploaded is refused ("No access to this file.") and the
6900
+ // file could never be indexed. Its file record makes it a file of the
6901
+ // uploader's chosen group, which they can read: create it now (the step
6902
+ // below would have created the same record a moment later, and a second
6903
+ // create is refused harmlessly) and ask again.
6904
+ var ecode = err && (err.code || (err.body && err.body.code));
6905
+ var emsg = String((err && (err.message || (err.body && err.body.message))) || err || '');
6906
+ var refused = /no access to this file/i.test(emsg) || (ecode === 'INVALID_REQUEST' && /access/i.test(emsg));
6907
+ if (duplicateOf || !refused || typeof self.host.ensureFileIndexRecord !== 'function') throw err;
6908
+ return Promise.resolve(self.host.ensureFileIndexRecord(member.storagePath, {
6909
+ name: member.file.name, mime: member.file.type || self.host.getMimeType(member.file.name), size: member.file.size,
6910
+ })).then(function () { return self.host.getTemporaryUrl(member.storagePath); });
6911
+ });
6094
6912
  }).then(function (url: string) {
6095
6913
  if (skipped) return; // guard the indexing branch for a skipped member
6096
6914
  if (duplicateOf) {
6097
6915
  urls.push({ name: member.relPath, url: url, storagePath: duplicateOf });
6916
+ if (!att.duplicates) att.duplicates = [];
6917
+ att.duplicates.push({
6918
+ label: member.relPath,
6919
+ storagePath: duplicateOf,
6920
+ name: member.file.name,
6921
+ size: member.file.size,
6922
+ mime: member.file.type || self.host.getMimeType(member.file.name) || undefined,
6923
+ });
6098
6924
  reusedCount += 1;
6099
6925
  if (att.kind !== 'folder') { att.uploadedUrl = url; att.storagePath = duplicateOf; att.reused = true; }
6100
6926
  else att.reusedCount = reusedCount;
@@ -6124,15 +6950,31 @@ export class ChatSession {
6124
6950
  // run has already written and then not re-index them. Asked of the
6125
6951
  // QUEUE, not just this page — see isIndexRunLive.
6126
6952
  var alreadyIndexing = false;
6953
+ // The group the file's EXISTING src:: record is at, read BEFORE the
6954
+ // delete below destroys it: a re-index or an overwrite keeps the file's
6955
+ // visibility instead of re-deciding it (host.readFileAccessGroup).
6956
+ var existingGroup: 'public' | 'authorized' | 'private' | null = null;
6127
6957
  var preIndex = self.claimIndexRun(member.storagePath).then(function (claimed) {
6128
6958
  alreadyIndexing = !claimed;
6129
6959
  if (alreadyIndexing) {
6130
6960
  console.log('[chat-engine] skipping a duplicate index request for', member.storagePath);
6131
6961
  return;
6132
6962
  }
6133
- if (existedBefore && typeof self.host.deleteExistingFileRecord === 'function') {
6134
- return Promise.resolve(self.host.deleteExistingFileRecord(member.storagePath)).catch(function () { });
6135
- }
6963
+ if (!existedBefore) return;
6964
+ var readGroup = typeof self.host.readFileAccessGroup === 'function'
6965
+ ? Promise.resolve(self.host.readFileAccessGroup(member.storagePath)).then(function (g) { existingGroup = g || null; }, function (err: any) {
6966
+ // Unknown is not "no group": deleting now would destroy the only
6967
+ // record of it. Fail this member (the chip turns red and can be
6968
+ // retried) and hand the claim back so the retry is not refused.
6969
+ self.releaseIndexRun(member.storagePath);
6970
+ throw err;
6971
+ })
6972
+ : Promise.resolve();
6973
+ return readGroup.then(function () {
6974
+ if (typeof self.host.deleteExistingFileRecord === 'function') {
6975
+ return Promise.resolve(self.host.deleteExistingFileRecord(member.storagePath)).catch(function () { });
6976
+ }
6977
+ });
6136
6978
  });
6137
6979
  preIndex = preIndex.then(function () {
6138
6980
  if (alreadyIndexing) return;
@@ -6141,7 +6983,7 @@ export class ChatSession {
6141
6983
  name: member.file.name,
6142
6984
  mime: mime || undefined,
6143
6985
  size: member.file.size,
6144
- })).catch(function () { });
6986
+ }, existingGroup || undefined)).catch(function () { });
6145
6987
  });
6146
6988
  // The access group the host actually recorded this file at. Read
6147
6989
  // AFTER ensureFileIndexRecord so the value here is the one the
@@ -6149,6 +6991,7 @@ export class ChatSession {
6149
6991
  var accessGroup: 'public' | 'authorized' | 'private' | undefined;
6150
6992
  preIndex = preIndex.then(function () {
6151
6993
  if (alreadyIndexing) return;
6994
+ if (existingGroup) { accessGroup = existingGroup; return; }
6152
6995
  if (typeof self.host.uploadAccessGroup !== 'function') return;
6153
6996
  return Promise.resolve(self.host.uploadAccessGroup(member.storagePath))
6154
6997
  .then(function (g) { accessGroup = g || undefined; })
@@ -6251,7 +7094,9 @@ export class ChatSession {
6251
7094
  snapshot.forEach(function (att: any) {
6252
7095
  chain = chain.then(function () {
6253
7096
  if (!self.state.attachments.some(function (a: any) { return a.id === att.id; })) return; // removed
6254
- if (att.status === 'done' || att.status === 'indexError') {
7097
+ // "indexError" is NOT collected as-is: its upload worked but its indexing
7098
+ // did not, and uploadSingleAttachment retries just the indexing.
7099
+ if (att.status === 'done') {
6255
7100
  if (att.kind === 'folder' && att.uploadedUrls) {
6256
7101
  att.uploadedUrls.forEach(function (u: any) { collected.push({ name: u.path, url: u.url, storagePath: u.storagePath }); });
6257
7102
  return;