bunnyquery 1.19.3 → 1.20.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.
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 = `
@@ -786,7 +798,6 @@ Scope: Only answer questions about this project and its data. Do not answer ques
786
798
  Knowledge lookup: before saying you don't know, or that something isn't in the chat history, ALWAYS search this project's data with the tools: the project's data lives in its database, not in the earlier messages of this chat.
787
799
  ${groundingRules}
788
800
  ${webRule}
789
- SAVED FINDINGS FIRST: where an earlier search found an answer is saved in table "search_findings" (one record per file page; its tags are the key words of the question that led there and of the search terms, stored lowercase without spaces). Before any other search, call getRecords with table_name "search_findings", access_group ${indexGroupLiteral} and tags set to ONE specific key word of the question (a name or a term, in the user's words; when nothing comes back, try one more word, or the word in the documents' language). A finding gives data.path and data.page: read THAT page (searchText with that path and the question's words) and answer from the page itself, quoting and citing it as usual. A finding is only a pointer, never the answer: when its page does not answer the question, or nothing is found, search as below.
790
801
  FINDING THE DATA: the database is the way in, for every kind of file. Follow the search path in getTables' description, with one exception for this project: when getTables' one page is the whole list (end_of_list true), skip its table-name search even when no name fits: you already see every table, and a table is never named after a company, a person or a single fact, so when no table fits, the answer is in a document's text: use searchText (DOCUMENTS below). Pick EVERY table that could hold the answer, not the first that fits. Read getIndexes and getTags one page each, never with fetch_all: name and tag lists can be millions of characters long and are never read whole, so when the name is not on that page, search for it with the user's words as their descriptions say. Never call getTags with neither table_name nor tag: that lists every tag of every table. Then getRecords in that table and group with the selector that matched (an index, one exact tag, or none for the whole table), always with fetch_all true. WHERE INDEXED CONTENT LIVES: a document's extracted content (PDF, Word, slides, scans) is in table "document_entries", one record per row / entry / section, with its page in "page"; spreadsheet rows are in "spreadsheet_rows". Files indexed before 2026-11-20 may still hold theirs in other tables, so a file's records are found wherever they are with getRecords reference "src::<path>" (see the access group rule below); every later mention of a file's records means this call. Every stored file has a record whose unique_id is "src::<its storage path>", so getUniqueId with unique_id "src::" and condition "gte" lists every file across every table (add the start of a path to narrow it; condition "lte" with a file name alone finds it in any folder).
791
802
  NUMBERS FROM A SPREADSHEET are computed from the ROWS, never from one page and never from a guess. Each row of each sheet is one record in its table: reference "src::<path>", unique_id "row::<path>#<sheet>#R<n>", the cells by header name, plus "_sheet", "_row", "_grain" ("detail" or "summary") and, on a total or preamble row, "_row_type". Its tags carry the file name, the sheet, the grain and up to four key values of the row (a name, a code), so getRecords with one exact tag selects every row about that thing across all the files in the table. Workbooks state the same money more than once: a detail sheet, then per-song, per-album and per-artist sheets that re-total it, plus a summary. Use rows whose "_grain" is "detail" and whose "_row_type" is not "total", pick ONE sheet per file and say which, and never add a sheet to its summary. Fetch the COMPLETE matching set, keep only the rows whose column or tag names what was asked, then add them up carefully, in groups, and check that the group sums agree with the grand total. A FILE TOTAL IS NOT A ROW'S TOTAL: the biggest number on a summary sheet is the whole file, not the thing asked about, so check every figure is scoped to what the question named (filter by the column that identifies it). Quote the row count, the sheet(s) and the file(s) the figure was made from and label it as calculated.
792
803
  ${documentRules}
@@ -2516,6 +2527,9 @@ Index the REMAINING windows - one record per row/item, looking at any page image
2516
2527
  service,
2517
2528
  owner,
2518
2529
  ...pollOpt(),
2530
+ // Status push for this pass and the continuations the worker queues from it
2531
+ // (see ChatEngineConfig.statusPush). Absent unless the host turned it on.
2532
+ ...statusPushEnabled() ? { notify: true } : {},
2519
2533
  url: OPENAI_RESPONSES_API_URL,
2520
2534
  method: "POST",
2521
2535
  headers: {
@@ -2560,6 +2574,9 @@ Index the REMAINING windows - one record per row/item, looking at any page image
2560
2574
  service,
2561
2575
  owner,
2562
2576
  ...pollOpt(),
2577
+ // Status push for this pass and the continuations the worker queues from it
2578
+ // (see ChatEngineConfig.statusPush). Absent unless the host turned it on.
2579
+ ...statusPushEnabled() ? { notify: true } : {},
2563
2580
  url: ANTHROPIC_MESSAGES_API_URL,
2564
2581
  method: "POST",
2565
2582
  headers: {
@@ -5122,6 +5139,11 @@ Index the REMAINING windows - one record per row/item, looking at any page image
5122
5139
  var WORKER_PASS_ADOPT_ATTEMPTS = [0, 2e3, 6e3];
5123
5140
  var RECENT_INDEX_PASS_EVIDENCE_MS = 10 * 60 * 1e3;
5124
5141
  var ADOPT_TICK_MS = 10 * 1e3;
5142
+ var STATUS_PUSH_ADOPT_TICK_MS = 60 * 1e3;
5143
+ var CATCH_UP_MIN_GAP_MS = 2e3;
5144
+ var RETURN_WATCH_MS = 15 * 1e3;
5145
+ var RETURN_WATCH_SLEEP_GAP_MS = 45 * 1e3;
5146
+ var STATUS_NUDGE_MIN_GAP_MS = 2e3;
5125
5147
  var EARLY_PROBE_SCHEDULE_MS = [400, 900, 1700];
5126
5148
  var INDEXING_DRAIN_BUSY_POLL_MS = 8e3;
5127
5149
  var INDEXING_DRAIN_CONFIRM_POLL_MS = 3e3;
@@ -5263,6 +5285,12 @@ Index the REMAINING windows - one record per row/item, looking at any page image
5263
5285
  }
5264
5286
  return Math.floor(v / 2 / 1e6);
5265
5287
  }
5288
+ var WRONG_ANSWER_MESSAGE = "This answer seems wrong. Please check it again against the documents.";
5289
+ var WRONG_ANSWER_LABEL = "Wrong answer?";
5290
+ function canReportWrongAnswer(msg) {
5291
+ var note = retrievalNoteOfAnswer(msg);
5292
+ return !!note && !answerUsedNoDataTool(note) && !msg.isCancelled;
5293
+ }
5266
5294
  var _ChatSession = class _ChatSession {
5267
5295
  constructor(host) {
5268
5296
  // --- live streaming ----------------------------------------------------
@@ -5312,6 +5340,10 @@ Index the REMAINING windows - one record per row/item, looking at any page image
5312
5340
  // bubble can never silently revert to its 200-char head.
5313
5341
  this._hydratedBodies = {};
5314
5342
  this._hydratingItems = {};
5343
+ /** The button's label and the message it sends, read off the session so the
5344
+ * clients need no extra import. */
5345
+ this.wrongAnswerLabel = WRONG_ANSWER_LABEL;
5346
+ this.wrongAnswerMessage = WRONG_ANSWER_MESSAGE;
5315
5347
  this.typewriterQueue = Promise.resolve();
5316
5348
  /**
5317
5349
  * Pick up indexing passes the WORKER minted, which no client ever dispatched.
@@ -5348,6 +5380,27 @@ Index the REMAINING windows - one record per row/item, looking at any page image
5348
5380
  * a reload starts without it and asks once, as before. */
5349
5381
  this._idleVerdictAt = {};
5350
5382
  this._adoptTickTimer = null;
5383
+ /** Start the ADOPT_TICK_MS follow-up if this page is tracking live indexing work and
5384
+ * is visible. Idempotent; each tick re-checks and stops when the work is gone, the tab
5385
+ * is hidden (resume restarts it through refreshLiveIndexState) or the view closed. */
5386
+ // ── RETURN CATCH-UP + REQUEST STATUS PUSH (owner, 2026-11-23) ──────────────
5387
+ // The rule: when the user comes back to the chat (the tab shown again, the computer
5388
+ // awake again, the network or the websocket back), the chat is re-read from the
5389
+ // server, so nothing that happened while they were away is missing. The re-read is
5390
+ // loadHistory's own first-page refresh, the one every mount runs: it keeps older pages
5391
+ // the user loaded, keeps a send still in flight, never lets an empty answer replace a
5392
+ // known one, re-attaches polls to whatever is still waiting, and reads back a streamed
5393
+ // answer nobody finalized. Status frames (statusPush) only make things faster; they
5394
+ // never decide anything on screen.
5395
+ this._catchUpAt = 0;
5396
+ this._catchUpTimer = null;
5397
+ this._returnWatchTimer = null;
5398
+ this._returnWatchAt = 0;
5399
+ this._returnListeners = false;
5400
+ this._statusUnsub = null;
5401
+ this._statusNudgeTimer = null;
5402
+ this._statusNudgeAt = 0;
5403
+ this._statusSeenConnect = false;
5351
5404
  /** The last COMPLETE running+pending look at this user's bg queue: which pass ids were
5352
5405
  * live. Complete means both lists came back shorter than their limit, so a tracked pass
5353
5406
  * missing from it really has left the queue. */
@@ -5392,6 +5445,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
5392
5445
  this.historyItemPolls = /* @__PURE__ */ new Map();
5393
5446
  this._pauseReasons = /* @__PURE__ */ new Set();
5394
5447
  this._resuming = false;
5448
+ this._wrongReported = {};
5395
5449
  this._lidSeq = 0;
5396
5450
  this._stageSeq = 0;
5397
5451
  this._uploadBatches = 0;
@@ -6786,8 +6840,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
6786
6840
  this._resuming = true;
6787
6841
  return Promise.resolve().then(function() {
6788
6842
  self.drainBgTaskQueue();
6789
- if (self.needsHistoryRefetch()) return self.loadHistory(false, self.state.gateRefreshToken);
6790
- self.refreshLiveIndexState();
6843
+ return self.catchUpHistory();
6791
6844
  }).catch(function(e) {
6792
6845
  console.error("[chat-engine] resume polling failed", e);
6793
6846
  }).then(function() {
@@ -8018,6 +8071,54 @@ Index the REMAINING windows - one record per row/item, looking at any page image
8018
8071
  }
8019
8072
  });
8020
8073
  }
8074
+ /**
8075
+ * Does this bubble get the "Wrong answer?" button: the free function's gate,
8076
+ * and only on the latest answer, because the message it sends names no answer
8077
+ * and the model reads it right after the last one. An answer already reported
8078
+ * keeps its (disabled) button after the complaint turn lands below it.
8079
+ */
8080
+ canReportWrongAnswer(msg) {
8081
+ if (!canReportWrongAnswer(msg)) return false;
8082
+ return this.wrongAnswerReported(msg) || this._isLatestAnswer(msg);
8083
+ }
8084
+ /** True when no chat turn follows `msg` in state.messages. Indexing rows and
8085
+ * cancelled turns do not count (neither reaches the model's history). Matched
8086
+ * by identity or by item id, since agent.vue hands in reactive proxies. */
8087
+ _isLatestAnswer(msg) {
8088
+ var list = this.state.messages || [];
8089
+ var sid = msg._serverItemId, lid = msg._localId;
8090
+ for (var i = list.length - 1; i >= 0; i--) {
8091
+ var m = list[i];
8092
+ if (!m) continue;
8093
+ if (m === msg || m.role === "assistant" && (sid && m._serverItemId === sid || lid && m._localId === lid)) return true;
8094
+ if (m.isBackgroundTask || m.isCancelled) continue;
8095
+ return false;
8096
+ }
8097
+ return false;
8098
+ }
8099
+ /** True once this answer's "Wrong answer?" was sent (one click per answer). */
8100
+ wrongAnswerReported(msg) {
8101
+ if (!msg) return false;
8102
+ if (msg._wrongReported) return true;
8103
+ var key = msg._serverItemId || msg._localId;
8104
+ return !!key && !!this._wrongReported[key];
8105
+ }
8106
+ /**
8107
+ * The "Wrong answer?" button: sends WRONG_ANSWER_MESSAGE as an ordinary visible
8108
+ * user turn through dispatchComposedMessage, so it reads the same after a reload
8109
+ * and both clients behave alike. The answer is marked first, so the button goes
8110
+ * disabled at once. False when the bubble does not qualify or was already used.
8111
+ * `pinned` is the caller's usual pinned identity and prompt (agent.vue pins them).
8112
+ */
8113
+ reportWrongAnswer(msg, pinned) {
8114
+ if (this.wrongAnswerReported(msg) || !this.canReportWrongAnswer(msg)) return false;
8115
+ msg._wrongReported = true;
8116
+ var key = msg._serverItemId || msg._localId;
8117
+ if (key) this._wrongReported[key] = true;
8118
+ this.host.notify();
8119
+ this.dispatchComposedMessage(WRONG_ANSWER_MESSAGE, false, void 0, void 0, void 0, pinned);
8120
+ return true;
8121
+ }
8021
8122
  /**
8022
8123
  * Stop waiting for the reply to the chat turn that is running now, and move on.
8023
8124
  *
@@ -8858,9 +8959,153 @@ Index the REMAINING windows - one record per row/item, looking at any page image
8858
8959
  });
8859
8960
  return found;
8860
8961
  }
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. */
8962
+ /**
8963
+ * Re-read the chat from the server now (see the rule above). Safe to call from any
8964
+ * number of triggers at once: calls within CATCH_UP_MIN_GAP_MS of the last one run
8965
+ * once, at the end of the gap. Nothing happens while no chat view is mounted (the
8966
+ * mount loads the chat anyway) or while background polling is paused (the tab is
8967
+ * hidden: showing it calls this again).
8968
+ */
8969
+ catchUpHistory() {
8970
+ var self = this;
8971
+ var id = this.host.getIdentity();
8972
+ if (!id.projectId || id.platform === "none") return Promise.resolve();
8973
+ if (!this.host.isViewMounted || !this.host.isViewMounted() || this.isPollingPaused()) return Promise.resolve();
8974
+ this._ensureReturnWatch();
8975
+ var wait = this._catchUpAt + CATCH_UP_MIN_GAP_MS - Date.now();
8976
+ if (wait > 0) {
8977
+ if (!this._catchUpTimer) {
8978
+ this._catchUpTimer = setTimeout(function() {
8979
+ self._catchUpTimer = null;
8980
+ self.catchUpHistory();
8981
+ }, wait);
8982
+ }
8983
+ return Promise.resolve();
8984
+ }
8985
+ this._catchUpAt = Date.now();
8986
+ return this.loadHistory(false, this.state.gateRefreshToken).catch(function(e) {
8987
+ console.error("[chat-engine] catch-up failed", e);
8988
+ });
8989
+ }
8990
+ /**
8991
+ * Watch for the moments the user comes back without the tab being hidden first: the
8992
+ * computer waking from sleep (the timer finds a gap far longer than its interval),
8993
+ * the network coming back, a page restored from the back-forward cache. Also starts
8994
+ * the status push listener. Runs while a chat view is mounted and stops itself when
8995
+ * none is.
8996
+ */
8997
+ _ensureReturnWatch() {
8998
+ var self = this;
8999
+ if (typeof window === "undefined") return;
9000
+ if (!this._returnListeners) {
9001
+ this._returnListeners = true;
9002
+ var onBack = function() {
9003
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") return;
9004
+ self.catchUpHistory();
9005
+ };
9006
+ window.addEventListener("online", onBack);
9007
+ window.addEventListener("pageshow", function(ev) {
9008
+ if (ev && ev.persisted) onBack();
9009
+ });
9010
+ }
9011
+ this._startStatusPush();
9012
+ if (this._returnWatchTimer) return;
9013
+ this._returnWatchAt = Date.now();
9014
+ var look = function() {
9015
+ self._returnWatchTimer = null;
9016
+ if (!self.host.isViewMounted || !self.host.isViewMounted()) {
9017
+ self._stopStatusPush();
9018
+ return;
9019
+ }
9020
+ var now = Date.now();
9021
+ var gap = now - self._returnWatchAt;
9022
+ self._returnWatchAt = now;
9023
+ if (gap > RETURN_WATCH_SLEEP_GAP_MS && (typeof document === "undefined" || document.visibilityState !== "hidden")) {
9024
+ self.catchUpHistory();
9025
+ }
9026
+ self._returnWatchTimer = setTimeout(look, RETURN_WATCH_MS);
9027
+ };
9028
+ this._returnWatchTimer = setTimeout(look, RETURN_WATCH_MS);
9029
+ }
9030
+ /** Listen to request status frames while a chat view is mounted (statusPush on). */
9031
+ _startStatusPush() {
9032
+ if (this._statusUnsub || !statusPushEnabled()) return;
9033
+ var self = this;
9034
+ this._statusSeenConnect = false;
9035
+ try {
9036
+ var unsub = chatEngineConfig().onRequestStatus(function(ev) {
9037
+ self._onRequestStatus(ev);
9038
+ });
9039
+ this._statusUnsub = typeof unsub === "function" ? unsub : function() {
9040
+ };
9041
+ } catch (e) {
9042
+ this._statusUnsub = null;
9043
+ }
9044
+ }
9045
+ _stopStatusPush() {
9046
+ var unsub = this._statusUnsub;
9047
+ this._statusUnsub = null;
9048
+ if (this._statusNudgeTimer) {
9049
+ clearTimeout(this._statusNudgeTimer);
9050
+ this._statusNudgeTimer = null;
9051
+ }
9052
+ if (unsub) {
9053
+ try {
9054
+ unsub();
9055
+ } catch (e) {
9056
+ }
9057
+ }
9058
+ }
9059
+ /**
9060
+ * One status frame event. 'connected' (first connection, and every reconnect after a
9061
+ * drop, a sleep or the planned renewal) catches up, because frames sent while the
9062
+ * socket was down are lost. A status change of an indexing pass this page does not
9063
+ * poll runs the queue check now instead of at its next heartbeat; a pass that IS polled
9064
+ * was already woken by skapi-js itself. Chat turns are left to their own polls.
9065
+ */
9066
+ _onRequestStatus(ev) {
9067
+ if (!ev || !this.host.isViewMounted()) return;
9068
+ if (ev.type === "connected") {
9069
+ if (!this._statusSeenConnect) {
9070
+ this._statusSeenConnect = true;
9071
+ return;
9072
+ }
9073
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") return;
9074
+ this.catchUpHistory();
9075
+ return;
9076
+ }
9077
+ if (ev.type !== "status" || typeof ev.id !== "string") return;
9078
+ if (!ev.queue || !isBgIndexingQueue(ev.queue)) return;
9079
+ if (this.historyItemPolls.has(ev.id)) return;
9080
+ var tracked = false;
9081
+ for (var i = 0; i < this.bgTaskQueue.length; i++) {
9082
+ var e = this.bgTaskQueue[i];
9083
+ if (e && e.id === ev.id) {
9084
+ tracked = !e.byListing;
9085
+ break;
9086
+ }
9087
+ }
9088
+ if (tracked) return;
9089
+ this._nudgeQueueCheck();
9090
+ }
9091
+ /** Run the queue check (adopt, settle by listing, page progress) now, at most once per
9092
+ * STATUS_NUDGE_MIN_GAP_MS, then let the heartbeat carry on. */
9093
+ _nudgeQueueCheck() {
9094
+ var self = this;
9095
+ if (this._statusNudgeTimer) return;
9096
+ var wait = Math.max(0, this._statusNudgeAt + STATUS_NUDGE_MIN_GAP_MS - Date.now());
9097
+ this._statusNudgeTimer = setTimeout(function() {
9098
+ self._statusNudgeTimer = null;
9099
+ self._statusNudgeAt = Date.now();
9100
+ var id = self.host.getIdentity();
9101
+ if (!id.projectId || id.platform !== "claude" && id.platform !== "openai") return;
9102
+ if (self.isPollingPaused() || !self.host.isViewMounted()) return;
9103
+ self._adoptWorkerIndexingPasses(0, false, true);
9104
+ self._settleByListing();
9105
+ self._refreshPageProgress();
9106
+ self._ensureAdoptTick();
9107
+ }, wait);
9108
+ }
8864
9109
  _ensureAdoptTick() {
8865
9110
  if (this._adoptTickTimer) return;
8866
9111
  var self = this;
@@ -8881,7 +9126,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
8881
9126
  self._settleByListing();
8882
9127
  self._refreshPageProgress();
8883
9128
  self._ensureAdoptTick();
8884
- }, ADOPT_TICK_MS);
9129
+ }, statusPushLive() ? STATUS_PUSH_ADOPT_TICK_MS : ADOPT_TICK_MS);
8885
9130
  }
8886
9131
  /**
8887
9132
  * Follow an indexing pass found in a loaded history page through the queue check
@@ -8963,12 +9208,8 @@ Index the REMAINING windows - one record per row/item, looking at any page image
8963
9208
  this.state.messages.splice(idx + 1, 0, placeholder);
8964
9209
  return true;
8965
9210
  }
8966
- /**
8967
- * Save where a hard search found its answer (findings.ts), through the host's
8968
- * saveSearchFinding hook. Never for an indexing pass, never twice for one turn, never
8969
- * throws, never waited on.
8970
- */
8971
9211
  _saveFindings(itemId, body, answer, note) {
9212
+ if (!_ChatSession.SAVE_SEARCH_FINDINGS) return;
8972
9213
  try {
8973
9214
  var save = chatEngineConfig().saveSearchFinding;
8974
9215
  if (typeof save !== "function" || !note || !body) return;
@@ -9497,6 +9738,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
9497
9738
  var id = this.host.getIdentity();
9498
9739
  var svcId = id.projectId, plat = id.platform;
9499
9740
  if (!svcId || plat === "none" || !this.host.isViewMounted()) return;
9741
+ this._ensureReturnWatch();
9500
9742
  this._applyIndexCancellations();
9501
9743
  this._sweepCancelledIndexing();
9502
9744
  this._ensureAdoptTick();
@@ -9565,6 +9807,11 @@ Index the REMAINING windows - one record per row/item, looking at any page image
9565
9807
  var executedAt;
9566
9808
  var bp = entry2.poll({
9567
9809
  latency: POLL_INTERVAL,
9810
+ // Status push (statusPushEnabled): a pass adopted from a listing is polled
9811
+ // slowly while frames arrive, like one this page dispatched. A dispatch
9812
+ // reply's poll decides that from the server's acknowledgement and
9813
+ // ignores this key.
9814
+ notify: statusPushEnabled(),
9568
9815
  onResponse: function(_res, meta) {
9569
9816
  if (meta && typeof meta.executed === "number" && meta.executed > 0) executedAt = meta.executed;
9570
9817
  }
@@ -10213,7 +10460,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
10213
10460
  }
10214
10461
  }
10215
10462
  };
10216
- var pp = isBg ? item.poll(Object.assign({ latency: POLL_INTERVAL }, pollOpts)) : self._fgPollWithEarlyProbe(item, capturedId, pollOpts, {
10463
+ var pp = isBg ? item.poll(Object.assign({ latency: POLL_INTERVAL, notify: statusPushEnabled() }, pollOpts)) : self._fgPollWithEarlyProbe(item, capturedId, pollOpts, {
10217
10464
  platform,
10218
10465
  projectId,
10219
10466
  owner,
@@ -10560,6 +10807,17 @@ Index the REMAINING windows - one record per row/item, looking at any page image
10560
10807
  this.state.gateRefreshToken += 1;
10561
10808
  }
10562
10809
  };
10810
+ /**
10811
+ * Save where a hard search found its answer (findings.ts), through the host's
10812
+ * saveSearchFinding hook. Never for an indexing pass, never twice for one turn, never
10813
+ * throws, never waited on.
10814
+ *
10815
+ * OFF since 1.20.1 (owner, 2026-11-24): the MCP's searchText now learns which page answered
10816
+ * a question by itself (learned links, read first by every search), so the chat no longer
10817
+ * reads "search_findings" first (that read cost 7 to 8 s at the start of every turn in
10818
+ * production) and nothing is saved here. SAVE_SEARCH_FINDINGS turns it back on.
10819
+ */
10820
+ _ChatSession.SAVE_SEARCH_FINDINGS = false;
10563
10821
  /** How many passes one "Load more" brings into a file's row. */
10564
10822
  _ChatSession.RUN_PASS_PAGE = 10;
10565
10823
  var ChatSession = _ChatSession;
@@ -10568,7 +10826,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
10568
10826
  (function() {
10569
10827
  var MCP_PROD = "https://mcp.skapi.com";
10570
10828
  var MCP_DEV = "https://mcp-dev.broadwayinc.computer";
10571
- var BQ_VERSION = "1.19.3" ;
10829
+ var BQ_VERSION = "1.20.1" ;
10572
10830
  var ATTACHMENT_URL_EXPIRES_SECONDS = 600;
10573
10831
  var GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";
10574
10832
  var GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
@@ -14162,6 +14420,19 @@ Index the REMAINING windows - one record per row/item, looking at any page image
14162
14420
  bubble.appendChild(citeRow);
14163
14421
  }
14164
14422
  if (answerUsedNoDataTool(citeNote)) bubble.appendChild(h("span", { class: "bq-no-source-note", text: NO_DATA_TOOL_MARK }));
14423
+ if (session.canReportWrongAnswer(msg)) {
14424
+ var wrongSent = session.wrongAnswerReported(msg);
14425
+ var wrongBtn = h("button", { class: "bq-wrong-answer-btn", type: "button", text: session.wrongAnswerLabel });
14426
+ if (wrongSent) wrongBtn.disabled = true;
14427
+ else wrongBtn.addEventListener("click", function(e) {
14428
+ e.stopPropagation();
14429
+ wrongBtn.disabled = true;
14430
+ readyProjectSettings(S.projectId).then(function() {
14431
+ session.reportWrongAnswer(msg);
14432
+ });
14433
+ });
14434
+ bubble.appendChild(wrongBtn);
14435
+ }
14165
14436
  }
14166
14437
  if (msg.isUploadingAttachments) bubble.appendChild(h("span", { class: "bq-pending-note", text: "(Uploading files...)" }));
14167
14438
  else if (msg.isAwaitingIndexing) bubble.appendChild(h("span", { class: "bq-pending-note", text: "(Indexing files...)" }));
@@ -15298,6 +15569,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
15298
15569
  { class: "bq-modal-desc" },
15299
15570
  "A file named \u201C" + filename + "\u201D already exists. Skip it, keep the existing file and just reindex it, or overwrite it completely?"
15300
15571
  ),
15572
+ 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
15573
  applyLabel,
15302
15574
  h(
15303
15575
  "div",
@@ -15367,7 +15639,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
15367
15639
  )
15368
15640
  )
15369
15641
  ));
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.' }));
15642
+ 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
15643
  reindexBtn = h("button", { class: "btn", type: "button", onclick: function() {
15372
15644
  if (reindexing) return;
15373
15645
  reindexing = true;
@@ -15598,7 +15870,14 @@ Index the REMAINING windows - one record per row/item, looking at any page image
15598
15870
  // skapi-js can (see canStream in init) and buffers, with a warning, when it
15599
15871
  // cannot. Before 1.16.0 this key meant "stream at all" and the socket was
15600
15872
  // `liveStreamingRealtime`; that name is now ignored.
15601
- liveStreaming: false
15873
+ liveStreaming: false,
15874
+ // Request STATUS PUSH (engine ChatEngineConfig.statusPush): indexing passes are
15875
+ // dispatched with `notify`, their polls slow down to a heartbeat while status
15876
+ // frames arrive on skapi's websocket, and the chat catches up when the socket
15877
+ // comes back. OFF unless the embedder asks, for the same reason as
15878
+ // `liveStreaming`: it keeps a websocket open on the host page's skapi instance.
15879
+ // Needs skapi-js 2.5.0 or newer on the page; an older one leaves it off.
15880
+ statusPush: false
15602
15881
  }, opts || {});
15603
15882
  S.mountEl = mountEl;
15604
15883
  clear(mountEl);
@@ -15735,7 +16014,13 @@ Index the REMAINING windows - one record per row/item, looking at any page image
15735
16014
  // canStream. What the embedder chooses is the socket: `liveStreaming` here
15736
16015
  // is the engine's socket-delivery key. ANDed with canStream so a page whose
15737
16016
  // SDK cannot stream never asks for a socket on a buffered reply.
15738
- liveStreaming: canStream && S.opts.liveStreaming === true
16017
+ liveStreaming: canStream && S.opts.liveStreaming === true,
16018
+ // ---- request status push (mirrored in agent.vue's ai_agent.ts) ----
16019
+ // Only an explicit true, and only when the page's skapi-js has the hooks
16020
+ // (2.5.0 or newer); the engine then does nothing different without them.
16021
+ statusPush: S.opts.statusPush === true && !!S.skapi && typeof S.skapi.onRequestStatus === "function",
16022
+ onRequestStatus: S.skapi && typeof S.skapi.onRequestStatus === "function" ? S.skapi.onRequestStatus.bind(S.skapi) : void 0,
16023
+ isRequestStatusLive: S.skapi && typeof S.skapi.isRequestStatusLive === "function" ? S.skapi.isRequestStatusLive.bind(S.skapi) : void 0
15739
16024
  // The transport: dispatch and history, plus the finalize hook that stores
15740
16025
  // a streamed turn's kept version and the chunk reader that is the second
15741
16026
  // half of the durability guarantee. The two optional hooks are handed