bunnyquery 1.19.2 → 1.20.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.
@@ -45,7 +45,7 @@ import {
45
45
  type BgTaskEntry,
46
46
  } from './requests';
47
47
  import { isPagedReadFile, isImageVisionFile, isWindowedReadFile } from './office';
48
- import { windowedIndexingEnabled, liveStreamingEnabled, streamRecoveryEnabled, chatEngineConfig, resolveForwardRequestFinalize, resolveForwardRequestStream, resolveSkipDuplicateFiles } from './config';
48
+ import { windowedIndexingEnabled, liveStreamingEnabled, streamRecoveryEnabled, chatEngineConfig, resolveForwardRequestFinalize, resolveForwardRequestStream, resolveSkipDuplicateFiles, statusPushEnabled, statusPushLive } from './config';
49
49
  // The wire-format knowledge. skapi relays the provider's bytes without reading them,
50
50
  // so the session hands them straight to this parser and never inspects a frame itself.
51
51
  import { createSseParser, type SseParser } from './sse';
@@ -53,6 +53,7 @@ import { isErrorResponseBody, isAuthExpiredError, isNonRetryableRequestError, ge
53
53
  import { buildBoundedChatMessages } from './budget';
54
54
  import { extractRetrievalNote, type RetrievalNote } from './retrieval_memory';
55
55
  import { findingsForTurn } from './findings';
56
+ import { retrievalNoteOfAnswer, answerUsedNoDataTool } from './citations';
56
57
  import { createInlineLinkRegex, sanitizeAttachmentLinksForHistory } from './links';
57
58
  import { markImagePreviewStale } from './image_preview';
58
59
  import { chatCacheKey, indexScopeKey, mapHistoryListToMessages, extractLastUserTextFromRequest, isIndexingRequestText, parseIndexingRequestText, probeBgQueue, BG_PROBE_TTL_MS, getSplitChatHistory, shouldRescueInFlightMessage, adoptLocalAnswerIntoPage } from './history';
@@ -99,6 +100,15 @@ const RECENT_INDEX_PASS_EVIDENCE_MS = 10 * 60 * 1000;
99
100
  // it ended (3.5 min on a 110-page PDF, nine passes done meanwhile). One look is the two
100
101
  // status queries (running, pending); it stops by itself when nothing is tracked.
101
102
  const ADOPT_TICK_MS = 10 * 1000;
103
+ /** The queue check's interval while request status frames are arriving (statusPush). */
104
+ const STATUS_PUSH_ADOPT_TICK_MS = 60 * 1000;
105
+ /** Several reasons to catch up at once (tab shown, socket back, network back) run one. */
106
+ const CATCH_UP_MIN_GAP_MS = 2000;
107
+ /** The return watch: how often it looks, and the gap that means the computer slept. */
108
+ const RETURN_WATCH_MS = 15 * 1000;
109
+ const RETURN_WATCH_SLEEP_GAP_MS = 45 * 1000;
110
+ /** Frame-driven queue checks run at most this often (status push). */
111
+ const STATUS_NUDGE_MIN_GAP_MS = 2000;
102
112
 
103
113
  // awaitIndexingDrained: how often it re-asks the background-indexing queue, and
104
114
  // how many consecutive empty answers it needs before believing the chains are
@@ -579,6 +589,23 @@ export function requestIdTimeMs(rid: string): number {
579
589
  return Math.floor(v / 2 / 1e6);
580
590
  }
581
591
 
592
+ /** The visible message the "Wrong answer?" button sends. The chat prompt's WRONG ANSWER rule reacts to it. */
593
+ export var WRONG_ANSWER_MESSAGE = 'This answer seems wrong. Please check it again against the documents.';
594
+ /** The button's label, shared so the two clients word it the same. */
595
+ export var WRONG_ANSWER_LABEL = 'Wrong answer?';
596
+
597
+ /**
598
+ * True when a bubble gets the "Wrong answer?" button: a settled chat answer that
599
+ * read project data (a retrieval note that is not the no-source mark). Both
600
+ * clients gate through ChatSession.canReportWrongAnswer, which also keeps it to
601
+ * the latest answer, and
602
+ * ChatSession.wrongAnswerReported says whether it was used.
603
+ */
604
+ export function canReportWrongAnswer(msg: ChatMessage | null | undefined): boolean {
605
+ var note = retrievalNoteOfAnswer(msg);
606
+ return !!note && !answerUsedNoDataTool(note) && !(msg as any).isCancelled;
607
+ }
608
+
582
609
  export class ChatSession {
583
610
  host: ChatHost;
584
611
  state: ChatState;
@@ -622,6 +649,9 @@ export class ChatSession {
622
649
  * settleDeadStagedMessages). Today the cache dies with the page too and every
623
650
  * restored stage is live; this stays correct if that ever changes. */
624
651
  private _liveStages: { [stageId: string]: boolean };
652
+ /** Answers whose "Wrong answer?" was already sent, by server id (else local id),
653
+ * so a history refetch that rebuilds the bubble does not offer it again. */
654
+ private _wrongReported: { [msgKey: string]: boolean };
625
655
  /** Files the SERVER currently has unresolved indexing work for, by the same key
626
656
  * a collapsed row uses (storage path, else filename), and whether we have asked
627
657
  * even once for this chat.
@@ -689,6 +719,7 @@ export class ChatSession {
689
719
  this.historyItemPolls = new Map();
690
720
  this._pauseReasons = new Set();
691
721
  this._resuming = false;
722
+ this._wrongReported = {};
692
723
  this._lidSeq = 0;
693
724
  this._stageSeq = 0;
694
725
  this._uploadBatches = 0;
@@ -2502,13 +2533,12 @@ export class ChatSession {
2502
2533
  return Promise.resolve()
2503
2534
  .then(function () {
2504
2535
  self.drainBgTaskQueue();
2505
- // History is loaded ONCE (owner, 2026-11-20): coming back to the tab does not
2506
- // refetch it. What changed while away arrives the way it would have live:
2507
- // replies through their polls (foreground polls never paused), indexing
2508
- // passes through the queue check that drainBgTaskQueue restarts. Only a
2509
- // waiting bubble left with nothing to settle it needs the first page again.
2510
- if (self.needsHistoryRefetch()) return self.loadHistory(false, self.state.gateRefreshToken);
2511
- self.refreshLiveIndexState();
2536
+ // EVERY return re-reads the first page (owner, 2026-11-23: "when the user is
2537
+ // away and comes back it should always have all the chat, no missing"). This
2538
+ // replaces the 2026-11-20 rule that loaded history once and relied on polls
2539
+ // alone: a poll that was stopped, throttled or lost while the tab slept had
2540
+ // nothing behind it. See catchUpHistory.
2541
+ return self.catchUpHistory();
2512
2542
  })
2513
2543
  .catch(function (e: any) { console.error('[chat-engine] resume polling failed', e); })
2514
2544
  .then(function () { self._resuming = false; });
@@ -4003,6 +4033,63 @@ export class ChatSession {
4003
4033
  });
4004
4034
  }
4005
4035
 
4036
+ /** The button's label and the message it sends, read off the session so the
4037
+ * clients need no extra import. */
4038
+ readonly wrongAnswerLabel: string = WRONG_ANSWER_LABEL;
4039
+ readonly wrongAnswerMessage: string = WRONG_ANSWER_MESSAGE;
4040
+
4041
+ /**
4042
+ * Does this bubble get the "Wrong answer?" button: the free function's gate,
4043
+ * and only on the latest answer, because the message it sends names no answer
4044
+ * and the model reads it right after the last one. An answer already reported
4045
+ * keeps its (disabled) button after the complaint turn lands below it.
4046
+ */
4047
+ canReportWrongAnswer(msg: ChatMessage): boolean {
4048
+ if (!canReportWrongAnswer(msg)) return false;
4049
+ return this.wrongAnswerReported(msg) || this._isLatestAnswer(msg);
4050
+ }
4051
+
4052
+ /** True when no chat turn follows `msg` in state.messages. Indexing rows and
4053
+ * cancelled turns do not count (neither reaches the model's history). Matched
4054
+ * by identity or by item id, since agent.vue hands in reactive proxies. */
4055
+ private _isLatestAnswer(msg: ChatMessage): boolean {
4056
+ var list = this.state.messages || [];
4057
+ var sid = msg._serverItemId, lid = msg._localId;
4058
+ for (var i = list.length - 1; i >= 0; i--) {
4059
+ var m = list[i];
4060
+ if (!m) continue;
4061
+ if (m === msg || (m.role === 'assistant' && ((sid && m._serverItemId === sid) || (lid && m._localId === lid)))) return true;
4062
+ if (m.isBackgroundTask || m.isCancelled) continue;
4063
+ return false;
4064
+ }
4065
+ return false;
4066
+ }
4067
+
4068
+ /** True once this answer's "Wrong answer?" was sent (one click per answer). */
4069
+ wrongAnswerReported(msg: ChatMessage): boolean {
4070
+ if (!msg) return false;
4071
+ if ((msg as any)._wrongReported) return true;
4072
+ var key = msg._serverItemId || msg._localId;
4073
+ return !!key && !!this._wrongReported[key];
4074
+ }
4075
+
4076
+ /**
4077
+ * The "Wrong answer?" button: sends WRONG_ANSWER_MESSAGE as an ordinary visible
4078
+ * user turn through dispatchComposedMessage, so it reads the same after a reload
4079
+ * and both clients behave alike. The answer is marked first, so the button goes
4080
+ * disabled at once. False when the bubble does not qualify or was already used.
4081
+ * `pinned` is the caller's usual pinned identity and prompt (agent.vue pins them).
4082
+ */
4083
+ reportWrongAnswer(msg: ChatMessage, pinned?: PinnedDispatchContext): boolean {
4084
+ if (this.wrongAnswerReported(msg) || !this.canReportWrongAnswer(msg)) return false;
4085
+ (msg as any)._wrongReported = true;
4086
+ var key = msg._serverItemId || msg._localId;
4087
+ if (key) this._wrongReported[key] = true;
4088
+ this.host.notify();
4089
+ this.dispatchComposedMessage(WRONG_ANSWER_MESSAGE, false, undefined, undefined, undefined, pinned);
4090
+ return true;
4091
+ }
4092
+
4006
4093
  /**
4007
4094
  * Stop waiting for the reply to the chat turn that is running now, and move on.
4008
4095
  *
@@ -5061,6 +5148,168 @@ export class ChatSession {
5061
5148
  /** Start the ADOPT_TICK_MS follow-up if this page is tracking live indexing work and
5062
5149
  * is visible. Idempotent; each tick re-checks and stops when the work is gone, the tab
5063
5150
  * is hidden (resume restarts it through refreshLiveIndexState) or the view closed. */
5151
+ // ── RETURN CATCH-UP + REQUEST STATUS PUSH (owner, 2026-11-23) ──────────────
5152
+ // The rule: when the user comes back to the chat (the tab shown again, the computer
5153
+ // awake again, the network or the websocket back), the chat is re-read from the
5154
+ // server, so nothing that happened while they were away is missing. The re-read is
5155
+ // loadHistory's own first-page refresh, the one every mount runs: it keeps older pages
5156
+ // the user loaded, keeps a send still in flight, never lets an empty answer replace a
5157
+ // known one, re-attaches polls to whatever is still waiting, and reads back a streamed
5158
+ // answer nobody finalized. Status frames (statusPush) only make things faster; they
5159
+ // never decide anything on screen.
5160
+
5161
+ private _catchUpAt = 0;
5162
+ private _catchUpTimer: any = null;
5163
+ private _returnWatchTimer: any = null;
5164
+ private _returnWatchAt = 0;
5165
+ private _returnListeners = false;
5166
+ private _statusUnsub: (() => void) | null = null;
5167
+ private _statusNudgeTimer: any = null;
5168
+ private _statusNudgeAt = 0;
5169
+ private _statusSeenConnect = false;
5170
+
5171
+ /**
5172
+ * Re-read the chat from the server now (see the rule above). Safe to call from any
5173
+ * number of triggers at once: calls within CATCH_UP_MIN_GAP_MS of the last one run
5174
+ * once, at the end of the gap. Nothing happens while no chat view is mounted (the
5175
+ * mount loads the chat anyway) or while background polling is paused (the tab is
5176
+ * hidden: showing it calls this again).
5177
+ */
5178
+ catchUpHistory(): Promise<void> {
5179
+ var self = this;
5180
+ var id = this.host.getIdentity();
5181
+ if (!id.projectId || id.platform === 'none') return Promise.resolve();
5182
+ if (!this.host.isViewMounted || !this.host.isViewMounted() || this.isPollingPaused()) return Promise.resolve();
5183
+ this._ensureReturnWatch();
5184
+ var wait = this._catchUpAt + CATCH_UP_MIN_GAP_MS - Date.now();
5185
+ if (wait > 0) {
5186
+ if (!this._catchUpTimer) {
5187
+ this._catchUpTimer = setTimeout(function () {
5188
+ self._catchUpTimer = null;
5189
+ self.catchUpHistory();
5190
+ }, wait);
5191
+ }
5192
+ return Promise.resolve();
5193
+ }
5194
+ this._catchUpAt = Date.now();
5195
+ // loadHistory's first-page path ends with refreshLiveIndexState, so indexing rows
5196
+ // are re-asked as well.
5197
+ return this.loadHistory(false, this.state.gateRefreshToken).catch(function (e: any) {
5198
+ console.error('[chat-engine] catch-up failed', e);
5199
+ });
5200
+ }
5201
+
5202
+ /**
5203
+ * Watch for the moments the user comes back without the tab being hidden first: the
5204
+ * computer waking from sleep (the timer finds a gap far longer than its interval),
5205
+ * the network coming back, a page restored from the back-forward cache. Also starts
5206
+ * the status push listener. Runs while a chat view is mounted and stops itself when
5207
+ * none is.
5208
+ */
5209
+ private _ensureReturnWatch(): void {
5210
+ var self = this;
5211
+ if (typeof window === 'undefined') return;
5212
+ if (!this._returnListeners) {
5213
+ this._returnListeners = true;
5214
+ var onBack = function () {
5215
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return;
5216
+ self.catchUpHistory();
5217
+ };
5218
+ window.addEventListener('online', onBack);
5219
+ window.addEventListener('pageshow', function (ev: any) { if (ev && ev.persisted) onBack(); });
5220
+ }
5221
+ this._startStatusPush();
5222
+ if (this._returnWatchTimer) return;
5223
+ this._returnWatchAt = Date.now();
5224
+ var look = function () {
5225
+ self._returnWatchTimer = null;
5226
+ if (!self.host.isViewMounted || !self.host.isViewMounted()) {
5227
+ self._stopStatusPush();
5228
+ return;
5229
+ }
5230
+ var now = Date.now();
5231
+ var gap = now - self._returnWatchAt;
5232
+ self._returnWatchAt = now;
5233
+ // A hidden tab's timers are slowed too, so only a gap seen while VISIBLE is a
5234
+ // wake from sleep; a hidden tab catches up when it is shown (resumePolling).
5235
+ if (gap > RETURN_WATCH_SLEEP_GAP_MS && (typeof document === 'undefined' || document.visibilityState !== 'hidden')) {
5236
+ self.catchUpHistory();
5237
+ }
5238
+ self._returnWatchTimer = setTimeout(look, RETURN_WATCH_MS);
5239
+ };
5240
+ this._returnWatchTimer = setTimeout(look, RETURN_WATCH_MS);
5241
+ }
5242
+
5243
+ /** Listen to request status frames while a chat view is mounted (statusPush on). */
5244
+ private _startStatusPush(): void {
5245
+ if (this._statusUnsub || !statusPushEnabled()) return;
5246
+ var self = this;
5247
+ // The first 'connected' is the socket this subscription found or opened, right
5248
+ // after the view loaded the chat itself: nothing can have been missed yet.
5249
+ this._statusSeenConnect = false;
5250
+ try {
5251
+ var unsub = chatEngineConfig().onRequestStatus!(function (ev: any) { self._onRequestStatus(ev); });
5252
+ this._statusUnsub = typeof unsub === 'function' ? unsub : function () { };
5253
+ } catch (e) {
5254
+ this._statusUnsub = null;
5255
+ }
5256
+ }
5257
+
5258
+ private _stopStatusPush(): void {
5259
+ var unsub = this._statusUnsub;
5260
+ this._statusUnsub = null;
5261
+ if (this._statusNudgeTimer) { clearTimeout(this._statusNudgeTimer); this._statusNudgeTimer = null; }
5262
+ if (unsub) {
5263
+ try { unsub(); } catch (e) { /* best effort */ }
5264
+ }
5265
+ }
5266
+
5267
+ /**
5268
+ * One status frame event. 'connected' (first connection, and every reconnect after a
5269
+ * drop, a sleep or the planned renewal) catches up, because frames sent while the
5270
+ * socket was down are lost. A status change of an indexing pass this page does not
5271
+ * poll runs the queue check now instead of at its next heartbeat; a pass that IS polled
5272
+ * was already woken by skapi-js itself. Chat turns are left to their own polls.
5273
+ */
5274
+ private _onRequestStatus(ev: any): void {
5275
+ if (!ev || !this.host.isViewMounted()) return;
5276
+ if (ev.type === 'connected') {
5277
+ if (!this._statusSeenConnect) { this._statusSeenConnect = true; return; }
5278
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return;
5279
+ this.catchUpHistory();
5280
+ return;
5281
+ }
5282
+ if (ev.type !== 'status' || typeof ev.id !== 'string') return;
5283
+ if (!ev.queue || !isBgIndexingQueue(ev.queue)) return;
5284
+ if (this.historyItemPolls.has(ev.id)) return;
5285
+ var tracked = false;
5286
+ for (var i = 0; i < this.bgTaskQueue.length; i++) {
5287
+ var e = this.bgTaskQueue[i];
5288
+ if (e && e.id === ev.id) { tracked = !e.byListing; break; }
5289
+ }
5290
+ if (tracked) return;
5291
+ this._nudgeQueueCheck();
5292
+ }
5293
+
5294
+ /** Run the queue check (adopt, settle by listing, page progress) now, at most once per
5295
+ * STATUS_NUDGE_MIN_GAP_MS, then let the heartbeat carry on. */
5296
+ private _nudgeQueueCheck(): void {
5297
+ var self = this;
5298
+ if (this._statusNudgeTimer) return;
5299
+ var wait = Math.max(0, this._statusNudgeAt + STATUS_NUDGE_MIN_GAP_MS - Date.now());
5300
+ this._statusNudgeTimer = setTimeout(function () {
5301
+ self._statusNudgeTimer = null;
5302
+ self._statusNudgeAt = Date.now();
5303
+ var id = self.host.getIdentity();
5304
+ if (!id.projectId || (id.platform !== 'claude' && id.platform !== 'openai')) return;
5305
+ if (self.isPollingPaused() || !self.host.isViewMounted()) return;
5306
+ self._adoptWorkerIndexingPasses(0, false, true);
5307
+ self._settleByListing();
5308
+ self._refreshPageProgress();
5309
+ self._ensureAdoptTick();
5310
+ }, wait);
5311
+ }
5312
+
5064
5313
  private _ensureAdoptTick(): void {
5065
5314
  if (this._adoptTickTimer) return;
5066
5315
  var self = this;
@@ -5078,7 +5327,9 @@ export class ChatSession {
5078
5327
  self._settleByListing();
5079
5328
  self._refreshPageProgress();
5080
5329
  self._ensureAdoptTick();
5081
- }, ADOPT_TICK_MS);
5330
+ // While status frames are arriving the queue check is a heartbeat only: a frame
5331
+ // about a pass this page does not follow yet runs it at once (_onRequestStatus).
5332
+ }, statusPushLive() ? STATUS_PUSH_ADOPT_TICK_MS : ADOPT_TICK_MS);
5082
5333
  }
5083
5334
 
5084
5335
  /** The last COMPLETE running+pending look at this user's bg queue: which pass ids were
@@ -5780,6 +6031,8 @@ export class ChatSession {
5780
6031
  var id = this.host.getIdentity();
5781
6032
  var svcId = id.projectId, plat = id.platform;
5782
6033
  if (!svcId || plat === 'none' || !this.host.isViewMounted()) return;
6034
+ // A chat view is up: watch for the user coming back (see catchUpHistory).
6035
+ this._ensureReturnWatch();
5783
6036
  // Before anything is surfaced: drop continuations of files the user stopped
5784
6037
  // (and let a fresh first pass lift the stop), then cancel any worker-queued
5785
6038
  // pass of a stopped file that reached the chat through history.
@@ -5916,6 +6169,11 @@ export class ChatSession {
5916
6169
  var executedAt: number | undefined;
5917
6170
  var bp = entry.poll({
5918
6171
  latency: POLL_INTERVAL,
6172
+ // Status push (statusPushEnabled): a pass adopted from a listing is polled
6173
+ // slowly while frames arrive, like one this page dispatched. A dispatch
6174
+ // reply's poll decides that from the server's acknowledgement and
6175
+ // ignores this key.
6176
+ notify: statusPushEnabled(),
5919
6177
  onResponse: function (_res: any, meta: any) {
5920
6178
  if (meta && typeof meta.executed === 'number' && meta.executed > 0) executedAt = meta.executed;
5921
6179
  },
@@ -6780,7 +7038,7 @@ export class ChatSession {
6780
7038
  },
6781
7039
  };
6782
7040
  var pp = isBg
6783
- ? item.poll(Object.assign({ latency: POLL_INTERVAL }, pollOpts))
7041
+ ? item.poll(Object.assign({ latency: POLL_INTERVAL, notify: statusPushEnabled() }, pollOpts))
6784
7042
  // Pinned to the chat this LOAD is for, snapshotted at its start
6785
7043
  // (loadKey/platform/projectId/owner), never a live read: a load can
6786
7044
  // still be attaching polls after the user has moved on, and a stream
package/styles/chat.css CHANGED
@@ -180,6 +180,27 @@
180
180
  color: var(--bq-muted);
181
181
  clear: both;
182
182
  }
183
+ /* "Wrong answer?" under an answer that read data: a small muted text button, no
184
+ box and no hover colour (the hover is an underline). Disabled once sent. */
185
+ .bq-wrong-answer-btn {
186
+ display: block;
187
+ margin-top: 0.3rem;
188
+ padding: 0;
189
+ min-height: 0;
190
+ border: 0;
191
+ background: transparent;
192
+ color: var(--bq-muted);
193
+ font: inherit;
194
+ font-size: 0.68rem;
195
+ line-height: 1.3;
196
+ text-align: left;
197
+ cursor: pointer;
198
+ box-shadow: none;
199
+ border-radius: 0;
200
+ clear: both;
201
+ }
202
+ .bq-wrong-answer-btn:hover:not(:disabled) { text-decoration: underline; }
203
+ .bq-wrong-answer-btn:disabled { cursor: default; opacity: 0.6; }
183
204
  /* Timestamp under a settled bubble (created for a user turn, response time for an
184
205
  assistant turn). Muted and small so it never competes with the message. */
185
206
  .bq-msg-time {