bunnyquery 1.19.3 → 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.
package/README.md CHANGED
@@ -28,7 +28,16 @@ release-by-release changelog is [HISTORY.md](HISTORY.md).
28
28
  - **Grounded answers**: the agent answers only from the project's data, says so when
29
29
  the data does not have it, and names the file and page an answer came from as
30
30
  citation chips under the reply. The open web is off unless the project's owner
31
- turns it on (`webAccess`).
31
+ turns it on (`webAccess`). A long file (a manual, a book) is searched by chapter
32
+ from its contents list, and for a signed-in user the question goes along with the
33
+ search so the server learns which page answered it.
34
+ - **"Wrong answer?"**: the latest answer that read data carries a small button that
35
+ sends "This answer seems wrong. Please check it again against the documents." as
36
+ an ordinary message, once per answer. The agent re-reads the cited pages and
37
+ searches again, then corrects the answer, or corrects it and records the right
38
+ page with an exact quote that proves it (signed-in users only), or keeps it and
39
+ quotes the supporting text. A user's word alone never changes what search has
40
+ learned.
32
41
  - **Authentication**: email/password login, optional signup, password change,
33
42
  email verification, account recovery, and "Sign in with Google".
34
43
  - **Conversation history**: paginated, with "Fetching history…" indicators on
@@ -161,6 +170,7 @@ Mounts the widget. Returns the `BunnyQuery` object.
161
170
  | `skipDuplicateFiles` | `boolean` | `null` | Whether a chat attachment the signed-in user **already uploaded** to this project (same stored file name, same size in bytes, same uploader, found from the file's `src::` record, and a stored copy that finished indexing or is still being indexed) is skipped: it is neither uploaded nor indexed again, the chip reads "already uploaded", and the message uses the stored copy's url. The project's **Skip duplicate files** setting (the `skip_duplicate_files` key of `bq::settings`, **on** unless the owner turned it off) is the **ceiling**, and this option may only restrict below it: `effective = projectSetting && skipDuplicateFiles !== false`. `null` or `true` follows the project; `false` lets this page re-upload duplicates; a value above the project setting has no effect. A stored copy whose indexing failed or was cancelled is not a duplicate, so the file uploads as usual. The check never blocks an upload: a failed lookup, or one slower than 15 seconds, uploads as usual. |
162
171
  | `reuseMcpToolList` | `boolean` | `false` | OpenAI chat turns only: reuse the MCP tool listing OpenAI returned on an earlier turn of this page, so OpenAI does not fetch it again (about 0.6 s per turn). Off unless `true`. Each reused turn's request and stored history row is about 31 to 34 KB larger. See `reuseMcpToolList` under `configureChatEngine`. |
163
172
  | `liveStreaming` | `boolean` | `false` | Deliver the streamed reply over skapi's websocket as well as the poll, so each piece lands the moment the server relays it instead of on the next one-second poll tick. Streaming itself is not an option: the widget streams every reply whenever the page's `skapi-js` can carry skapi's half of the stream flag (it checks for `forwardRequestStream` and `forwardRequestFinalize`), and otherwise warns once and buffers. Off unless you ask for it: skapi's `joinRealtime` **replaces** the connection's group, so for the length of a turn it takes the room out from under whatever else your app uses realtime for. Purely an accelerator; with it off the reply still streams, on the poll's cadence. Before 1.16.0 this key meant "stream at all" and the socket was `liveStreamingRealtime`; that name is now ignored. |
173
+ | `statusPush` | `boolean` | `false` | Indexing status over skapi's websocket: each indexing pass asks the server for status messages, its poll then reads once a minute while they arrive and at once when one names it, and the chat re-reads its history when the socket reconnects. Off unless you ask for it, because it keeps a websocket open on your page's skapi instance (your own realtime callback never sees these messages). Needs skapi-js 2.5.0 or newer; with an older one it stays off. Purely an accelerator: every status on screen still comes from reading the request. |
164
174
 
165
175
  ### Rebranding the widget
166
176
 
@@ -369,7 +379,9 @@ Uploading over a file that already exists prompts for skip, "reindex only", or
369
379
  overwrite. Choosing either of the latter two deletes the file's existing
370
380
  `src::<path>` index record first, and the skapi backend cascades that delete to
371
381
  the record's reference-linked children, so re-indexing **replaces** the file's
372
- knowledge rather than duplicating it.
382
+ knowledge rather than duplicating it. That includes the file's contents list, its
383
+ search glossary and everything search has learned about it from people's
384
+ questions and corrections, which the dialog says.
373
385
 
374
386
  ### Filenames
375
387
 
@@ -529,6 +541,9 @@ helpers. See the `.d.ts` shipped with `bunnyquery/engine`.
529
541
  | `forwardRequestStream` | `function?` | `skapi.forwardRequestStream`, bound to your Skapi instance. The **second half of the durability guarantee**: a row that settles while no poll is attached (closed tab, discarded background tab, slept device) is never finalized, so its answer stays in the chunk store and its history row is terminal and empty. Given the request id this drains that turn's chunks in one pass; the engine parses them exactly as it parses a live stream and finalizes what it read, so each row is recovered at most once. Without it the engine mints no recovery marker at all, and without the pair the engine does not stream. |
530
542
  | `onLiveStreamUpdate` | `function?` | Observation hook for a streaming turn (`{ serverItemId, ownerKey, phase, text, thinkingText, toolNames, complete, errored }`). The engine already paints the answer text itself, so this is only for affordances it does not decide the presentation of. Never throw from it. |
531
543
  | `liveStreaming` | `boolean?` | Deliver streamed chunks over skapi's websocket as well. Off by default: `joinRealtime` replaces the connection's group for the length of a turn, so only a host that owns its skapi instance should opt in. Streaming itself has no key: the engine streams every chat turn whenever `forwardRequestFinalize` and `forwardRequestStream` are both handed over (`liveStreamingEnabled()`), and a host that wants buffered replies hands over neither. Before 1.16.0 this key meant "stream at all"; `liveStreamingRealtime` is now ignored. |
544
+ | `statusPush` | `boolean?` | Request status push (skapi-js 2.5.0+, with `onRequestStatus` below). Indexing passes are dispatched with `notify: true`, their polls idle at a once-a-minute heartbeat while status messages arrive, a message about a pass the page does not follow runs the queue check, and a reconnect runs `catchUpHistory()`. Off by default: it keeps a websocket open on the host's skapi instance. |
545
+ | `onRequestStatus` | `function?` | `skapi.onRequestStatus`, bound to the host's skapi instance (skapi-js 2.5.0+). Required for `statusPush`. |
546
+ | `isRequestStatusLive` | `function?` | `skapi.isRequestStatusLive`, bound to the host's skapi instance (skapi-js 2.5.0+). |
532
547
  | `streamRecovery` | `boolean?` | Set `false` to force the read-back of already-streamed turns **off**, even though the chunk reader is injected. There is no need to set it to turn recovery on: injecting `forwardRequestStream` is what arms it. |
533
548
  | `mintIndexDoneMarker` | `function?` | Write the durable "indexing finished" marker (`done::<path>`, reference `src::<path>`, table `__INDEXING__`) for the runs this client knows are complete. Best-effort, must never throw. Without it the engine falls back to inference. |
534
549
  | `upsertIndexRunRecord` | `function?` | Create-or-update the per-file run record (`run::<path>`, reference `src::<path>`, table `__INDEXING__`), which is what lets chat rows and files-page badges paint without scanning background history. You implement the upsert (the records API has none) and the status precedence: `'working'` must never overwrite a terminal status. Without it the engine uses the legacy scan/probe path. |
@@ -599,6 +614,12 @@ widget rather than approximately:
599
614
  handed the pending assistant bubble, it cancels the running request on the
600
615
  server, marks the question cancelled and promotes the next queued message.
601
616
  `cancelQueuedMessage` does the same for a message still in the queue.
617
+ - **`ChatSession.canReportWrongAnswer(msg)` / `reportWrongAnswer(msg, pinned?)`**
618
+ are the "Wrong answer?" button. The gate is a settled answer with a retrieval
619
+ note (not the no-source mark), not cancelled, and the latest answer; one that
620
+ was already reported keeps a disabled button (`wrongAnswerReported(msg)`).
621
+ `reportWrongAnswer` sends `wrongAnswerMessage` through `dispatchComposedMessage`,
622
+ so it is a normal visible turn; `wrongAnswerLabel` is the button's text.
602
623
  - **`resetFileIndexOnServer({ service, owner?, storagePath })`** clears a file's index on the MCP (`/internal/index-reset`: the file record and everything that cascades from it, the agent's per-window records, and the `done::`, `run::` and `prog::` markers) before a Reindex or an Overwrite, through the host's `forwardRequest` with `$ACCESS_TOKEN`. Resolves to the server's answer (including the old record's `access_group`), or `null` when the MCP could not be reached, in which case the caller clears the index itself.
603
624
  - **`findDuplicateUpload`** and the `configureProjectSettings` reader back the
604
625
  `skipDuplicateFiles` and `webAccess` switches; see the `configureChatEngine`
package/bunnyquery.css CHANGED
@@ -1289,6 +1289,27 @@
1289
1289
  color: var(--bq-muted);
1290
1290
  clear: both;
1291
1291
  }
1292
+ /* "Wrong answer?" under an answer that read data: a small muted text button, no
1293
+ box and no hover colour (the hover is an underline). Disabled once sent. */
1294
+ .bq-wrong-answer-btn {
1295
+ display: block;
1296
+ margin-top: 0.3rem;
1297
+ padding: 0;
1298
+ min-height: 0;
1299
+ border: 0;
1300
+ background: transparent;
1301
+ color: var(--bq-muted);
1302
+ font: inherit;
1303
+ font-size: 0.68rem;
1304
+ line-height: 1.3;
1305
+ text-align: left;
1306
+ cursor: pointer;
1307
+ box-shadow: none;
1308
+ border-radius: 0;
1309
+ clear: both;
1310
+ }
1311
+ .bq-wrong-answer-btn:hover:not(:disabled) { text-decoration: underline; }
1312
+ .bq-wrong-answer-btn:disabled { cursor: default; opacity: 0.6; }
1292
1313
  /* Timestamp under a settled bubble (created for a user turn, response time for an
1293
1314
  assistant turn). Muted and small so it never competes with the message. */
1294
1315
  .bq-msg-time {
package/bunnyquery.js CHANGED
@@ -199,6 +199,17 @@
199
199
  function windowedIndexingEnabled() {
200
200
  return _config?.windowedIndexing === true;
201
201
  }
202
+ function statusPushEnabled() {
203
+ return _config?.statusPush === true && typeof _config?.onRequestStatus === "function";
204
+ }
205
+ function statusPushLive() {
206
+ if (!statusPushEnabled() || typeof _config?.isRequestStatusLive !== "function") return false;
207
+ try {
208
+ return !!_config.isRequestStatusLive();
209
+ } catch (e) {
210
+ return false;
211
+ }
212
+ }
202
213
  function liveStreamingSocketEnabled() {
203
214
  return liveStreamingEnabled() && _config?.liveStreaming === true;
204
215
  }
@@ -777,7 +788,8 @@ WHEN THE DATA DOES NOT HAVE IT, SAY SO. Once you have searched the way these rul
777
788
  KEEP WHAT THE DATA SAYS APART FROM WHAT YOU WORKED OUT. A total you computed, a comparison, a trend, an interpretation or a recommendation is yours, not the data's: label it as such ("calculated from...", "this suggests...") and name the rows or files it was made from. Never present an estimate, an assumption or an inference as something the data states.
778
789
  These three rules govern every claim about the project's data. They do not limit the About BunnyQuery section (answer product questions from it), a greeting, or text the user explicitly asks you to write.`;
779
790
  const webRule = webAccess ? `WEB ACCESS IS ON for this project: when the user asks for something that is not in the project's data, you may search the web for it, but every such fact must be marked as coming from the web (name the site), kept apart from what the project's data says, and never used to fill in or complete a document's content or a record. This is the one exception to the four sources named above.` : `This chat has no web tool: the web is never a source here.`;
780
- const documentRules = `DOCUMENTS (a contract, a report, a manual, a letter, any uploaded file the user asks about the content of): FIRST FIND THE FILE, with getFileOutline when you know its storage path, otherwise by its "src::" record (see WHERE INDEXED CONTENT LIVES) using the name the user used. THEN FIND THE PAGE with searchText: with the file's path when the user named a file, without a path when they did not ("find a file that contains X"), and follow its description's steps to the end, including asking the user once, after quick results, before it searches all files. QUOTE THE EXACT TEXT it returned and CITE THE FILE AND THE PAGE ("report.pdf, page 7"); never present a paraphrase as a quote. A file with no page text is read with readFileContent instead and cited by its file name.`;
791
+ const documentRules = `DOCUMENTS (a contract, a report, a manual, a letter, any uploaded file the user asks about the content of): FIRST FIND THE FILE, with getFileOutline when you know its storage path, otherwise by its "src::" record (see WHERE INDEXED CONTENT LIVES) using the name the user used. THEN FIND THE PAGE with searchText: with the file's path when the user named a file, without a path when they did not ("find a file that contains X"), and follow its description's steps to the end, including asking the user once, after quick results, before it searches all files. QUOTE THE EXACT TEXT it returned and CITE THE FILE AND THE PAGE ("report.pdf, page 7"); never present a paraphrase as a quote. A file with no page text is read with readFileContent instead and cited by its file name. For a long file (a manual, a book), call getFileOutline first and search the chapter that fits with searchText page_from and page_to. When the user asks about the content of the documents, pass searchText "question": that question in the user's own words, without names or personal details that are not about the documents. Leave "question" out for anything else.
792
+ WRONG ANSWER: when the user says an answer is wrong (or sends "This answer seems wrong. Please check it again against the documents."), re-read the pages you cited and search again, passing searchText "question" = the user's ORIGINAL question that the disputed answer answered, never the complaint message itself. Then do exactly one of: correct the answer only; correct the answer and call correctSearchLink (when it is among your tools); or keep the answer and quote the text that supports it. Call correctSearchLink only with the page and an exact quote that prove it, and never change data on the user's word alone.`;
781
793
  const groupIsPublic = indexGroupLiteral === '"public"' || indexGroupLiteral === "0";
782
794
  const accessGroupRule = `THIS PROJECT INDEXES AT access_group ${indexGroupLiteral}: pass access_group ${indexGroupLiteral} EXPLICITLY on EVERY query that names a table_name, whether it filters by index, by tag or by nothing, and never rely on a default: a group left off is NOT "all groups", and any user but the project's owner is then answered from access_group 0 (public) alone${groupIsPublic ? "" : `, so a table indexed at ${indexGroupLiteral} would look empty with its records sitting right there`}. Files uploaded before the project's setting changed may sit at another group, so when a table query comes back empty, retry it in the other groups among 0, 1 and "private" before concluding there is nothing. Reference is the exception: reference ALONE spans EVERY table and EVERY access group, so getRecords with reference "src::<the file's storage path>" is the one call that returns a whole file's records wherever the indexer put them; adding table_name narrows it to that table, and access_group WITHOUT table_name fails.`;
783
795
  let systemPrompt = `
@@ -2516,6 +2528,9 @@ Index the REMAINING windows - one record per row/item, looking at any page image
2516
2528
  service,
2517
2529
  owner,
2518
2530
  ...pollOpt(),
2531
+ // Status push for this pass and the continuations the worker queues from it
2532
+ // (see ChatEngineConfig.statusPush). Absent unless the host turned it on.
2533
+ ...statusPushEnabled() ? { notify: true } : {},
2519
2534
  url: OPENAI_RESPONSES_API_URL,
2520
2535
  method: "POST",
2521
2536
  headers: {
@@ -2560,6 +2575,9 @@ Index the REMAINING windows - one record per row/item, looking at any page image
2560
2575
  service,
2561
2576
  owner,
2562
2577
  ...pollOpt(),
2578
+ // Status push for this pass and the continuations the worker queues from it
2579
+ // (see ChatEngineConfig.statusPush). Absent unless the host turned it on.
2580
+ ...statusPushEnabled() ? { notify: true } : {},
2563
2581
  url: ANTHROPIC_MESSAGES_API_URL,
2564
2582
  method: "POST",
2565
2583
  headers: {
@@ -5122,6 +5140,11 @@ Index the REMAINING windows - one record per row/item, looking at any page image
5122
5140
  var WORKER_PASS_ADOPT_ATTEMPTS = [0, 2e3, 6e3];
5123
5141
  var RECENT_INDEX_PASS_EVIDENCE_MS = 10 * 60 * 1e3;
5124
5142
  var ADOPT_TICK_MS = 10 * 1e3;
5143
+ var STATUS_PUSH_ADOPT_TICK_MS = 60 * 1e3;
5144
+ var CATCH_UP_MIN_GAP_MS = 2e3;
5145
+ var RETURN_WATCH_MS = 15 * 1e3;
5146
+ var RETURN_WATCH_SLEEP_GAP_MS = 45 * 1e3;
5147
+ var STATUS_NUDGE_MIN_GAP_MS = 2e3;
5125
5148
  var EARLY_PROBE_SCHEDULE_MS = [400, 900, 1700];
5126
5149
  var INDEXING_DRAIN_BUSY_POLL_MS = 8e3;
5127
5150
  var INDEXING_DRAIN_CONFIRM_POLL_MS = 3e3;
@@ -5263,6 +5286,12 @@ Index the REMAINING windows - one record per row/item, looking at any page image
5263
5286
  }
5264
5287
  return Math.floor(v / 2 / 1e6);
5265
5288
  }
5289
+ var WRONG_ANSWER_MESSAGE = "This answer seems wrong. Please check it again against the documents.";
5290
+ var WRONG_ANSWER_LABEL = "Wrong answer?";
5291
+ function canReportWrongAnswer(msg) {
5292
+ var note = retrievalNoteOfAnswer(msg);
5293
+ return !!note && !answerUsedNoDataTool(note) && !msg.isCancelled;
5294
+ }
5266
5295
  var _ChatSession = class _ChatSession {
5267
5296
  constructor(host) {
5268
5297
  // --- live streaming ----------------------------------------------------
@@ -5312,6 +5341,10 @@ Index the REMAINING windows - one record per row/item, looking at any page image
5312
5341
  // bubble can never silently revert to its 200-char head.
5313
5342
  this._hydratedBodies = {};
5314
5343
  this._hydratingItems = {};
5344
+ /** The button's label and the message it sends, read off the session so the
5345
+ * clients need no extra import. */
5346
+ this.wrongAnswerLabel = WRONG_ANSWER_LABEL;
5347
+ this.wrongAnswerMessage = WRONG_ANSWER_MESSAGE;
5315
5348
  this.typewriterQueue = Promise.resolve();
5316
5349
  /**
5317
5350
  * Pick up indexing passes the WORKER minted, which no client ever dispatched.
@@ -5348,6 +5381,27 @@ Index the REMAINING windows - one record per row/item, looking at any page image
5348
5381
  * a reload starts without it and asks once, as before. */
5349
5382
  this._idleVerdictAt = {};
5350
5383
  this._adoptTickTimer = null;
5384
+ /** Start the ADOPT_TICK_MS follow-up if this page is tracking live indexing work and
5385
+ * is visible. Idempotent; each tick re-checks and stops when the work is gone, the tab
5386
+ * is hidden (resume restarts it through refreshLiveIndexState) or the view closed. */
5387
+ // ── RETURN CATCH-UP + REQUEST STATUS PUSH (owner, 2026-11-23) ──────────────
5388
+ // The rule: when the user comes back to the chat (the tab shown again, the computer
5389
+ // awake again, the network or the websocket back), the chat is re-read from the
5390
+ // server, so nothing that happened while they were away is missing. The re-read is
5391
+ // loadHistory's own first-page refresh, the one every mount runs: it keeps older pages
5392
+ // the user loaded, keeps a send still in flight, never lets an empty answer replace a
5393
+ // known one, re-attaches polls to whatever is still waiting, and reads back a streamed
5394
+ // answer nobody finalized. Status frames (statusPush) only make things faster; they
5395
+ // never decide anything on screen.
5396
+ this._catchUpAt = 0;
5397
+ this._catchUpTimer = null;
5398
+ this._returnWatchTimer = null;
5399
+ this._returnWatchAt = 0;
5400
+ this._returnListeners = false;
5401
+ this._statusUnsub = null;
5402
+ this._statusNudgeTimer = null;
5403
+ this._statusNudgeAt = 0;
5404
+ this._statusSeenConnect = false;
5351
5405
  /** The last COMPLETE running+pending look at this user's bg queue: which pass ids were
5352
5406
  * live. Complete means both lists came back shorter than their limit, so a tracked pass
5353
5407
  * missing from it really has left the queue. */
@@ -5392,6 +5446,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
5392
5446
  this.historyItemPolls = /* @__PURE__ */ new Map();
5393
5447
  this._pauseReasons = /* @__PURE__ */ new Set();
5394
5448
  this._resuming = false;
5449
+ this._wrongReported = {};
5395
5450
  this._lidSeq = 0;
5396
5451
  this._stageSeq = 0;
5397
5452
  this._uploadBatches = 0;
@@ -6786,8 +6841,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
6786
6841
  this._resuming = true;
6787
6842
  return Promise.resolve().then(function() {
6788
6843
  self.drainBgTaskQueue();
6789
- if (self.needsHistoryRefetch()) return self.loadHistory(false, self.state.gateRefreshToken);
6790
- self.refreshLiveIndexState();
6844
+ return self.catchUpHistory();
6791
6845
  }).catch(function(e) {
6792
6846
  console.error("[chat-engine] resume polling failed", e);
6793
6847
  }).then(function() {
@@ -8018,6 +8072,54 @@ Index the REMAINING windows - one record per row/item, looking at any page image
8018
8072
  }
8019
8073
  });
8020
8074
  }
8075
+ /**
8076
+ * Does this bubble get the "Wrong answer?" button: the free function's gate,
8077
+ * and only on the latest answer, because the message it sends names no answer
8078
+ * and the model reads it right after the last one. An answer already reported
8079
+ * keeps its (disabled) button after the complaint turn lands below it.
8080
+ */
8081
+ canReportWrongAnswer(msg) {
8082
+ if (!canReportWrongAnswer(msg)) return false;
8083
+ return this.wrongAnswerReported(msg) || this._isLatestAnswer(msg);
8084
+ }
8085
+ /** True when no chat turn follows `msg` in state.messages. Indexing rows and
8086
+ * cancelled turns do not count (neither reaches the model's history). Matched
8087
+ * by identity or by item id, since agent.vue hands in reactive proxies. */
8088
+ _isLatestAnswer(msg) {
8089
+ var list = this.state.messages || [];
8090
+ var sid = msg._serverItemId, lid = msg._localId;
8091
+ for (var i = list.length - 1; i >= 0; i--) {
8092
+ var m = list[i];
8093
+ if (!m) continue;
8094
+ if (m === msg || m.role === "assistant" && (sid && m._serverItemId === sid || lid && m._localId === lid)) return true;
8095
+ if (m.isBackgroundTask || m.isCancelled) continue;
8096
+ return false;
8097
+ }
8098
+ return false;
8099
+ }
8100
+ /** True once this answer's "Wrong answer?" was sent (one click per answer). */
8101
+ wrongAnswerReported(msg) {
8102
+ if (!msg) return false;
8103
+ if (msg._wrongReported) return true;
8104
+ var key = msg._serverItemId || msg._localId;
8105
+ return !!key && !!this._wrongReported[key];
8106
+ }
8107
+ /**
8108
+ * The "Wrong answer?" button: sends WRONG_ANSWER_MESSAGE as an ordinary visible
8109
+ * user turn through dispatchComposedMessage, so it reads the same after a reload
8110
+ * and both clients behave alike. The answer is marked first, so the button goes
8111
+ * disabled at once. False when the bubble does not qualify or was already used.
8112
+ * `pinned` is the caller's usual pinned identity and prompt (agent.vue pins them).
8113
+ */
8114
+ reportWrongAnswer(msg, pinned) {
8115
+ if (this.wrongAnswerReported(msg) || !this.canReportWrongAnswer(msg)) return false;
8116
+ msg._wrongReported = true;
8117
+ var key = msg._serverItemId || msg._localId;
8118
+ if (key) this._wrongReported[key] = true;
8119
+ this.host.notify();
8120
+ this.dispatchComposedMessage(WRONG_ANSWER_MESSAGE, false, void 0, void 0, void 0, pinned);
8121
+ return true;
8122
+ }
8021
8123
  /**
8022
8124
  * Stop waiting for the reply to the chat turn that is running now, and move on.
8023
8125
  *
@@ -8858,9 +8960,153 @@ Index the REMAINING windows - one record per row/item, looking at any page image
8858
8960
  });
8859
8961
  return found;
8860
8962
  }
8861
- /** Start the ADOPT_TICK_MS follow-up if this page is tracking live indexing work and
8862
- * is visible. Idempotent; each tick re-checks and stops when the work is gone, the tab
8863
- * is hidden (resume restarts it through refreshLiveIndexState) or the view closed. */
8963
+ /**
8964
+ * Re-read the chat from the server now (see the rule above). Safe to call from any
8965
+ * number of triggers at once: calls within CATCH_UP_MIN_GAP_MS of the last one run
8966
+ * once, at the end of the gap. Nothing happens while no chat view is mounted (the
8967
+ * mount loads the chat anyway) or while background polling is paused (the tab is
8968
+ * hidden: showing it calls this again).
8969
+ */
8970
+ catchUpHistory() {
8971
+ var self = this;
8972
+ var id = this.host.getIdentity();
8973
+ if (!id.projectId || id.platform === "none") return Promise.resolve();
8974
+ if (!this.host.isViewMounted || !this.host.isViewMounted() || this.isPollingPaused()) return Promise.resolve();
8975
+ this._ensureReturnWatch();
8976
+ var wait = this._catchUpAt + CATCH_UP_MIN_GAP_MS - Date.now();
8977
+ if (wait > 0) {
8978
+ if (!this._catchUpTimer) {
8979
+ this._catchUpTimer = setTimeout(function() {
8980
+ self._catchUpTimer = null;
8981
+ self.catchUpHistory();
8982
+ }, wait);
8983
+ }
8984
+ return Promise.resolve();
8985
+ }
8986
+ this._catchUpAt = Date.now();
8987
+ return this.loadHistory(false, this.state.gateRefreshToken).catch(function(e) {
8988
+ console.error("[chat-engine] catch-up failed", e);
8989
+ });
8990
+ }
8991
+ /**
8992
+ * Watch for the moments the user comes back without the tab being hidden first: the
8993
+ * computer waking from sleep (the timer finds a gap far longer than its interval),
8994
+ * the network coming back, a page restored from the back-forward cache. Also starts
8995
+ * the status push listener. Runs while a chat view is mounted and stops itself when
8996
+ * none is.
8997
+ */
8998
+ _ensureReturnWatch() {
8999
+ var self = this;
9000
+ if (typeof window === "undefined") return;
9001
+ if (!this._returnListeners) {
9002
+ this._returnListeners = true;
9003
+ var onBack = function() {
9004
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") return;
9005
+ self.catchUpHistory();
9006
+ };
9007
+ window.addEventListener("online", onBack);
9008
+ window.addEventListener("pageshow", function(ev) {
9009
+ if (ev && ev.persisted) onBack();
9010
+ });
9011
+ }
9012
+ this._startStatusPush();
9013
+ if (this._returnWatchTimer) return;
9014
+ this._returnWatchAt = Date.now();
9015
+ var look = function() {
9016
+ self._returnWatchTimer = null;
9017
+ if (!self.host.isViewMounted || !self.host.isViewMounted()) {
9018
+ self._stopStatusPush();
9019
+ return;
9020
+ }
9021
+ var now = Date.now();
9022
+ var gap = now - self._returnWatchAt;
9023
+ self._returnWatchAt = now;
9024
+ if (gap > RETURN_WATCH_SLEEP_GAP_MS && (typeof document === "undefined" || document.visibilityState !== "hidden")) {
9025
+ self.catchUpHistory();
9026
+ }
9027
+ self._returnWatchTimer = setTimeout(look, RETURN_WATCH_MS);
9028
+ };
9029
+ this._returnWatchTimer = setTimeout(look, RETURN_WATCH_MS);
9030
+ }
9031
+ /** Listen to request status frames while a chat view is mounted (statusPush on). */
9032
+ _startStatusPush() {
9033
+ if (this._statusUnsub || !statusPushEnabled()) return;
9034
+ var self = this;
9035
+ this._statusSeenConnect = false;
9036
+ try {
9037
+ var unsub = chatEngineConfig().onRequestStatus(function(ev) {
9038
+ self._onRequestStatus(ev);
9039
+ });
9040
+ this._statusUnsub = typeof unsub === "function" ? unsub : function() {
9041
+ };
9042
+ } catch (e) {
9043
+ this._statusUnsub = null;
9044
+ }
9045
+ }
9046
+ _stopStatusPush() {
9047
+ var unsub = this._statusUnsub;
9048
+ this._statusUnsub = null;
9049
+ if (this._statusNudgeTimer) {
9050
+ clearTimeout(this._statusNudgeTimer);
9051
+ this._statusNudgeTimer = null;
9052
+ }
9053
+ if (unsub) {
9054
+ try {
9055
+ unsub();
9056
+ } catch (e) {
9057
+ }
9058
+ }
9059
+ }
9060
+ /**
9061
+ * One status frame event. 'connected' (first connection, and every reconnect after a
9062
+ * drop, a sleep or the planned renewal) catches up, because frames sent while the
9063
+ * socket was down are lost. A status change of an indexing pass this page does not
9064
+ * poll runs the queue check now instead of at its next heartbeat; a pass that IS polled
9065
+ * was already woken by skapi-js itself. Chat turns are left to their own polls.
9066
+ */
9067
+ _onRequestStatus(ev) {
9068
+ if (!ev || !this.host.isViewMounted()) return;
9069
+ if (ev.type === "connected") {
9070
+ if (!this._statusSeenConnect) {
9071
+ this._statusSeenConnect = true;
9072
+ return;
9073
+ }
9074
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") return;
9075
+ this.catchUpHistory();
9076
+ return;
9077
+ }
9078
+ if (ev.type !== "status" || typeof ev.id !== "string") return;
9079
+ if (!ev.queue || !isBgIndexingQueue(ev.queue)) return;
9080
+ if (this.historyItemPolls.has(ev.id)) return;
9081
+ var tracked = false;
9082
+ for (var i = 0; i < this.bgTaskQueue.length; i++) {
9083
+ var e = this.bgTaskQueue[i];
9084
+ if (e && e.id === ev.id) {
9085
+ tracked = !e.byListing;
9086
+ break;
9087
+ }
9088
+ }
9089
+ if (tracked) return;
9090
+ this._nudgeQueueCheck();
9091
+ }
9092
+ /** Run the queue check (adopt, settle by listing, page progress) now, at most once per
9093
+ * STATUS_NUDGE_MIN_GAP_MS, then let the heartbeat carry on. */
9094
+ _nudgeQueueCheck() {
9095
+ var self = this;
9096
+ if (this._statusNudgeTimer) return;
9097
+ var wait = Math.max(0, this._statusNudgeAt + STATUS_NUDGE_MIN_GAP_MS - Date.now());
9098
+ this._statusNudgeTimer = setTimeout(function() {
9099
+ self._statusNudgeTimer = null;
9100
+ self._statusNudgeAt = Date.now();
9101
+ var id = self.host.getIdentity();
9102
+ if (!id.projectId || id.platform !== "claude" && id.platform !== "openai") return;
9103
+ if (self.isPollingPaused() || !self.host.isViewMounted()) return;
9104
+ self._adoptWorkerIndexingPasses(0, false, true);
9105
+ self._settleByListing();
9106
+ self._refreshPageProgress();
9107
+ self._ensureAdoptTick();
9108
+ }, wait);
9109
+ }
8864
9110
  _ensureAdoptTick() {
8865
9111
  if (this._adoptTickTimer) return;
8866
9112
  var self = this;
@@ -8881,7 +9127,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
8881
9127
  self._settleByListing();
8882
9128
  self._refreshPageProgress();
8883
9129
  self._ensureAdoptTick();
8884
- }, ADOPT_TICK_MS);
9130
+ }, statusPushLive() ? STATUS_PUSH_ADOPT_TICK_MS : ADOPT_TICK_MS);
8885
9131
  }
8886
9132
  /**
8887
9133
  * Follow an indexing pass found in a loaded history page through the queue check
@@ -9497,6 +9743,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
9497
9743
  var id = this.host.getIdentity();
9498
9744
  var svcId = id.projectId, plat = id.platform;
9499
9745
  if (!svcId || plat === "none" || !this.host.isViewMounted()) return;
9746
+ this._ensureReturnWatch();
9500
9747
  this._applyIndexCancellations();
9501
9748
  this._sweepCancelledIndexing();
9502
9749
  this._ensureAdoptTick();
@@ -9565,6 +9812,11 @@ Index the REMAINING windows - one record per row/item, looking at any page image
9565
9812
  var executedAt;
9566
9813
  var bp = entry2.poll({
9567
9814
  latency: POLL_INTERVAL,
9815
+ // Status push (statusPushEnabled): a pass adopted from a listing is polled
9816
+ // slowly while frames arrive, like one this page dispatched. A dispatch
9817
+ // reply's poll decides that from the server's acknowledgement and
9818
+ // ignores this key.
9819
+ notify: statusPushEnabled(),
9568
9820
  onResponse: function(_res, meta) {
9569
9821
  if (meta && typeof meta.executed === "number" && meta.executed > 0) executedAt = meta.executed;
9570
9822
  }
@@ -10213,7 +10465,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
10213
10465
  }
10214
10466
  }
10215
10467
  };
10216
- var pp = isBg ? item.poll(Object.assign({ latency: POLL_INTERVAL }, pollOpts)) : self._fgPollWithEarlyProbe(item, capturedId, pollOpts, {
10468
+ var pp = isBg ? item.poll(Object.assign({ latency: POLL_INTERVAL, notify: statusPushEnabled() }, pollOpts)) : self._fgPollWithEarlyProbe(item, capturedId, pollOpts, {
10217
10469
  platform,
10218
10470
  projectId,
10219
10471
  owner,
@@ -10568,7 +10820,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
10568
10820
  (function() {
10569
10821
  var MCP_PROD = "https://mcp.skapi.com";
10570
10822
  var MCP_DEV = "https://mcp-dev.broadwayinc.computer";
10571
- var BQ_VERSION = "1.19.3" ;
10823
+ var BQ_VERSION = "1.20.0" ;
10572
10824
  var ATTACHMENT_URL_EXPIRES_SECONDS = 600;
10573
10825
  var GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";
10574
10826
  var GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
@@ -14162,6 +14414,19 @@ Index the REMAINING windows - one record per row/item, looking at any page image
14162
14414
  bubble.appendChild(citeRow);
14163
14415
  }
14164
14416
  if (answerUsedNoDataTool(citeNote)) bubble.appendChild(h("span", { class: "bq-no-source-note", text: NO_DATA_TOOL_MARK }));
14417
+ if (session.canReportWrongAnswer(msg)) {
14418
+ var wrongSent = session.wrongAnswerReported(msg);
14419
+ var wrongBtn = h("button", { class: "bq-wrong-answer-btn", type: "button", text: session.wrongAnswerLabel });
14420
+ if (wrongSent) wrongBtn.disabled = true;
14421
+ else wrongBtn.addEventListener("click", function(e) {
14422
+ e.stopPropagation();
14423
+ wrongBtn.disabled = true;
14424
+ readyProjectSettings(S.projectId).then(function() {
14425
+ session.reportWrongAnswer(msg);
14426
+ });
14427
+ });
14428
+ bubble.appendChild(wrongBtn);
14429
+ }
14165
14430
  }
14166
14431
  if (msg.isUploadingAttachments) bubble.appendChild(h("span", { class: "bq-pending-note", text: "(Uploading files...)" }));
14167
14432
  else if (msg.isAwaitingIndexing) bubble.appendChild(h("span", { class: "bq-pending-note", text: "(Indexing files...)" }));
@@ -15298,6 +15563,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
15298
15563
  { class: "bq-modal-desc" },
15299
15564
  "A file named \u201C" + filename + "\u201D already exists. Skip it, keep the existing file and just reindex it, or overwrite it completely?"
15300
15565
  ),
15566
+ h("p", { class: "bq-modal-desc", text: "Re-indexing also removes everything search has learned about this file from people's questions and corrections." }),
15301
15567
  applyLabel,
15302
15568
  h(
15303
15569
  "div",
@@ -15367,7 +15633,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
15367
15633
  )
15368
15634
  )
15369
15635
  ));
15370
- body.push(h("p", { class: "bq-modal-desc", text: 'To index the stored copies again, choose Reindex. To upload such files again instead, turn off "Skip duplicate files" in the project settings.' }));
15636
+ body.push(h("p", { class: "bq-modal-desc", text: `To index the stored copies again, choose Reindex. Re-indexing also removes everything search has learned about this file from people's questions and corrections. To upload such files again instead, turn off "Skip duplicate files" in the project settings.` }));
15371
15637
  reindexBtn = h("button", { class: "btn", type: "button", onclick: function() {
15372
15638
  if (reindexing) return;
15373
15639
  reindexing = true;
@@ -15598,7 +15864,14 @@ Index the REMAINING windows - one record per row/item, looking at any page image
15598
15864
  // skapi-js can (see canStream in init) and buffers, with a warning, when it
15599
15865
  // cannot. Before 1.16.0 this key meant "stream at all" and the socket was
15600
15866
  // `liveStreamingRealtime`; that name is now ignored.
15601
- liveStreaming: false
15867
+ liveStreaming: false,
15868
+ // Request STATUS PUSH (engine ChatEngineConfig.statusPush): indexing passes are
15869
+ // dispatched with `notify`, their polls slow down to a heartbeat while status
15870
+ // frames arrive on skapi's websocket, and the chat catches up when the socket
15871
+ // comes back. OFF unless the embedder asks, for the same reason as
15872
+ // `liveStreaming`: it keeps a websocket open on the host page's skapi instance.
15873
+ // Needs skapi-js 2.5.0 or newer on the page; an older one leaves it off.
15874
+ statusPush: false
15602
15875
  }, opts || {});
15603
15876
  S.mountEl = mountEl;
15604
15877
  clear(mountEl);
@@ -15735,7 +16008,13 @@ Index the REMAINING windows - one record per row/item, looking at any page image
15735
16008
  // canStream. What the embedder chooses is the socket: `liveStreaming` here
15736
16009
  // is the engine's socket-delivery key. ANDed with canStream so a page whose
15737
16010
  // SDK cannot stream never asks for a socket on a buffered reply.
15738
- liveStreaming: canStream && S.opts.liveStreaming === true
16011
+ liveStreaming: canStream && S.opts.liveStreaming === true,
16012
+ // ---- request status push (mirrored in agent.vue's ai_agent.ts) ----
16013
+ // Only an explicit true, and only when the page's skapi-js has the hooks
16014
+ // (2.5.0 or newer); the engine then does nothing different without them.
16015
+ statusPush: S.opts.statusPush === true && !!S.skapi && typeof S.skapi.onRequestStatus === "function",
16016
+ onRequestStatus: S.skapi && typeof S.skapi.onRequestStatus === "function" ? S.skapi.onRequestStatus.bind(S.skapi) : void 0,
16017
+ isRequestStatusLive: S.skapi && typeof S.skapi.isRequestStatusLive === "function" ? S.skapi.isRequestStatusLive.bind(S.skapi) : void 0
15739
16018
  // The transport: dispatch and history, plus the finalize hook that stores
15740
16019
  // a streamed turn's kept version and the chunk reader that is the second
15741
16020
  // half of the durability guarantee. The two optional hooks are handed