bunnyquery 1.21.3 → 1.21.7

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/dist/engine.cjs CHANGED
@@ -1063,10 +1063,12 @@ function buildChatSystemPrompt(params) {
1063
1063
  const webAccess = params.webAccess === true;
1064
1064
  const g = params.indexAccessGroup;
1065
1065
  const indexGroupLiteral = typeof g === "number" ? String(g) : g === "public" || g === "private" || g === "authorized" || g === "admin" ? `"${g}"` : '"authorized"';
1066
+ const reindexHint = canUpload === false ? `asking the project's owner to re-index that file` : client === "console" ? `re-indexing that file (select it on the Files page and choose Reindex)` : `re-indexing that file (attach the same file again and choose to reindex it)`;
1066
1067
  const groundingRules = `ANSWER ONLY FROM THE DATA. Every fact you state about this project's data - a name, a number, a date, a status, what a document says, whether something exists - must come from one of four places: a tool result returned in THIS conversation, a file or image attached to it (including one you read through its attachment link), the project description at the end of this prompt, or what the user told you themselves in this chat. Your general knowledge, the open internet and a plausible guess are NOT sources. Never use them to answer a question about the user's data, to fill a gap in it, or to complete a record that came back partial. A value that is not in what you retrieved is unknown: say it is not in the data instead of supplying a likely one.
1067
1068
  WHEN THE DATA DOES NOT HAVE IT, SAY SO. Once you have searched the way these rules require and nothing answers the question, tell the user plainly, in their language, that this project's data does not contain it, and say what you searched (the tables, files or terms) so they can tell missing data from a missed search. Do not answer from memory instead, and do not turn a missing answer into a general explanation of the topic. Offer what would let you answer it: ${canUpload === false ? `another name or file to look under, or asking the project's owner to add it` : `the document to upload, or another name or file to look under`}.
1069
+ A CODE, NUMBER OR PHRASE THAT searchText DID NOT FIND: when it answers search_complete with no hit, and what its message says was NOT searched has been checked as it says (the skipped_without_page_text files, the records when the value could be in a table), keep the answer short: say plainly that it was not found, name what was searched (the file, and its pages when you searched only some of them, or files_searched files and total_pages_searched pages), and when a recently uploaded file or a photo should hold it, suggest ${reindexHint}, since small or handwritten characters can be misread at indexing. Never present a different file as the match, and never guess the value.
1068
1070
  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.
1069
- 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.`;
1071
+ These 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.`;
1070
1072
  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.`;
1071
1073
  const documentRules = `DOCUMENTS (a contract, a report, a manual, a letter, any uploaded file the user asks about the content of): when the user NAMED a file (its file name; a document title, a quote or a code they mention is NOT a file name: searchText finds those inside the files), first find its storage path by its "src::" record (see WHERE INDEXED CONTENT LIVES) using the name the user used, then find the page with searchText and that path. A spreadsheet's sheets are page text too: a hit names its sheet and rows, and the row itself is a record (its unique_id is the hit's row_id_prefix plus the row number); a spreadsheet indexed before 2026-11-25 has no page text, so read its rows instead (readFileContent, or its records). When they did not name a file, your FIRST call is searchText without a path: no table list, no file lookup before it. Never list or look up files (getUniqueId on "src::") to find out whether a document, quote or title exists before searching: searchText's hits name the file, and a search that finds nothing says what it could not cover. Either way follow searchText's description 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"), or for a hit with "sheet" THE FILE AND THE SHEET ("quote.xlsx, sheet \uCD1D\uAD04"), never a sheet page's number; never present a paraphrase as a quote. A file with no page text is read with readFileContent instead and cited by its file name. In a long file (a manual, a book), when a search of the whole file gives too many hits or none that fit, call getFileOutline 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.
1072
1074
  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 (for a sheet hit, the rows: by its row_id_prefix, never readFileContent on a sheet page) 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.`;
@@ -1135,7 +1137,7 @@ function buildIndexingSystemPrompt(params) {
1135
1137
  - PDFs (scanned or not): you do NOT read a PDF with a tool or a URL. Its pages are RENDERED and embedded directly in the user message as IMAGE blocks, a WINDOW of pages at a time. LOOK at the embedded page images and datafy every one. The note beside them tells you whether MORE pages remain: if so, save this window's records and stop (a follow-up pass shows the next window automatically); only when the note says it was the LAST window is the PDF fully seen. Do NOT call readFileContent or web_fetch for a PDF.
1136
1138
  - VISION: when the message (a readFileContent window, an embedded PDF page, or an inline attachment) includes IMAGES - scanned/rendered PDF pages, or photos embedded in a spreadsheet next to a row/block - LOOK at them and capture what they show as record data (the reading/values in a scanned table, the part/defect/condition visible in a photo). The image IS part of the data; correlate each photo with its labelled block ("PHOTO A3" markers tie a photo to that grid row).
1137
1139
  - TRANSCRIBE, DO NOT DESCRIBE. When an image contains ANY text - a label, tag, stamp, form field, serial/part number, handwriting - your FIRST job is to read the characters out and store them VERBATIM, not to describe the scene. A record saying "a red inspection tag with handwritten markings" is worthless: it is unsearchable and every such photo produces the same sentence. Put the characters you can actually read into these EXACT fields, not variations of them: "printed_text" (the pre-printed wording), "handwritten_text" (what a person wrote by hand), and, when you can resolve one, "part_no", "serial_no", "tag_id" and "date". Every identifier you read (a serial number, a part number, a tag id, a model code) ALSO goes into "printed_text" or "handwritten_text", exactly as it appears, because those two fields are the image's searchable text. Text can appear at ANY angle (sideways, upside down, mirrored, along a curve): read it in its own orientation, and never call text unreadable only because it is turned. When it is upside down or sideways, watch the look-alikes (6 and 9, 0 and O, 1 and I, Latin and Cyrillic letters of the same shape). Same reason as the fixed table names: a field called photo_text in one pass and visible_text_notes in the next cannot be queried together. Read PARTIAL values rather than skipping: "500.7402.5[?][?]" beats nothing. Write [?] for each character that is genuinely unreadable and copy handwriting character for character - do NOT invent a character, and do NOT replace the whole transcription with a description of what the object looks like. A scene description is a nice extra AFTER the text, never instead of it.
1138
- - IMAGE FILES uploaded as the file itself: if ANY readable character appears ANYWHERE in the image (a label, a stamp, a sign in the background) it counts as an image WITH text - transcribe it per the rule above, and also capture the layout (what appears where) and every entity named. Only a truly text-free image gets description first: a one-line caption, then the objects present with their attributes (type, color, count, condition, position). Either way, save what you extract onto the file's "src::" record with updateRecords, TAG every entity and identifier visible, and INDEX the one number the image offers (a measured value, an amount, a count). On that same record ALSO set "text_rotation" and "text_legibility". "text_rotation" is the CLOCKWISE turn, 0, 90, 180 or 270, that would make the image's main text upright AS THE IMAGE IS SHOWN TO YOU: 0 when it already reads normally; 180 when it is upside down; 90 when its lines run from bottom to top (the tops of the letters face left); 270 when its lines run from top to bottom (the tops of the letters face right). "text_legibility" is "clear", "partial" or "unreadable" ("none" when there is no text).
1140
+ - IMAGE FILES uploaded as the file itself: if ANY readable character appears ANYWHERE in the image (a label, a stamp, a sign in the background) it counts as an image WITH text - transcribe it per the rule above, and also capture the layout (what appears where) and every entity named. Only a truly text-free image gets description first: a one-line caption, then the objects present with their attributes (type, color, count, condition, position). Either way, save what you extract onto the file's "src::" record with updateRecords, TAG every entity and identifier visible, and INDEX the one number the image offers (a measured value, an amount, a count). On that same record ALSO set "text_rotation" and "text_legibility". "text_rotation" is the CLOCKWISE turn, 0, 90, 180 or 270, that would make the image's main text upright AS THE IMAGE IS SHOWN TO YOU: 0 when it already reads normally; 180 when it is upside down; 90 when its lines run from bottom to top (the tops of the letters face left); 270 when its lines run from top to bottom (the tops of the letters face right). "text_legibility" is "clear", "partial" or "unreadable" ("none" when there is no text). ALSO set "text_regions" on that record: a list of up to 4 boxes [left, top, right, bottom], each a fraction from 0 to 1 of the image AS IT IS SHOWN TO YOU (not turned upright), drawn tightly around a label, plate or handwritten area whose characters matter (a serial number, a part number, a tag id); [] when there is none. Where a label names a value (a form field, a plate line), write the value right after its label in "printed_text" or "handwritten_text", as "<label>: <value>" (the label's own words, then the characters written beside it), so the label and its value are found together.
1139
1141
  - Whatever the file type, this file's identity is "src::" + its storage path (the "storage path" metadata line) - never the inline content or a temporary URL. That record ALREADY EXISTS: the upload pipeline creates it in table "file_summaries" (access group "${accessGroup}") before indexing starts, so posting it again is rejected as a duplicate unique_id. Reference it from every record you write, and add what you learn to it with updateRecords. If that update unexpectedly reports the record does not exist, post it yourself ONCE with that exact "src::" unique_id (table "file_summaries", access group "${accessGroup}") and carry on; this is the ONE exception to the do-NOT-post-the-file-record rules elsewhere in these instructions, because the source identity must never be dropped just because an update failed.
1140
1142
  - ACCESS GROUP (hard rule): every record you write for this file - the file record, per-row records, chapters, summaries, intermediates - MUST be posted with access group "${accessGroup}". Pass it explicitly on every postRecords call; do not leave it out and do not vary it between passes of the same file. An access group is part of a record's table key, so records saved under a different group than the file are in a different table and will not come back with the rest of it: a "public" file whose rows were saved as "authorized" is one an anonymous visitor can see the name of and none of the contents of, and a re-index cannot find the strays to clean them up. The one exception is the EXTRACTED MEDIA records in "__MEDIA__", which the pipeline creates for you - leave their group alone and only enrich them.
1141
1143
  - REACHABILITY (hard rule): every record you write while indexing this file MUST be reachable from the file's "src::<storage path>" record by following reference - either reference that record directly, or reference something that already reaches it. A record with no reference, or one pointing outside this file's chain, is an ORPHAN: deleting or re-indexing the file removes the reachable records and leaves the orphan behind forever, where it keeps turning up in later answers as stale data. If you create an intermediate record that OTHER records reference (a page record that rows hang off, a sheet or section record), set source.can_remove_referencing_records to true on it; the delete cascade passes a delete through a record only when that record carries the flag OR a unique_id starting "src::" (the file record cascades because its unique_id starts with "src::"; the intermediates you create carry no "src::" id, so they need the flag), and it cascades ONE LEVEL AT A TIME, so EVERY intermediate record in a chain needs its own marker - an unmarked link stops the cascade there and everything below it survives as orphans. When in doubt, reference the file record directly and keep the chain flat.
@@ -1212,7 +1214,7 @@ Read this file with the readFileContent tool, using the storage path above - do
1212
1214
  return head + `- temporary URL: ${attachment.url}
1213
1215
  ` + (options.imageFile === "attached" ? `
1214
1216
  This is an IMAGE file, attached to this message as an image: read it there, not from the URL. ` : `
1215
- This is an IMAGE file in a format the AI cannot take directly. When an image of it is attached to this message (the server converts it when it can), read it there; when none is attached, index the file from its metadata only and do not guess its contents. `) + `Transcribe every character FIRST, at whatever angle the text is: "printed_text", "handwritten_text", and "part_no" / "serial_no" / "tag_id", with every identifier also written inside "printed_text" or "handwritten_text". Then set "text_rotation" and "text_legibility" on the file's "src::" record, and only then describe what the image shows.`;
1217
+ This is an IMAGE file in a format the AI cannot take directly. When an image of it is attached to this message (the server converts it when it can), read it there; when none is attached, index the file from its metadata only and do not guess its contents. `) + `Transcribe every character FIRST, at whatever angle the text is: "printed_text", "handwritten_text", and "part_no" / "serial_no" / "tag_id", with every identifier also written inside "printed_text" or "handwritten_text". Write each label's value right after its label, as "<label>: <value>" (the label's own words, then the characters written beside it), reading small and handwritten characters closely; use [?] only for a character that is truly unreadable, and never put a guessed character in its place. Then set "text_rotation", "text_legibility" and "text_regions" on the file's "src::" record, and only then describe what the image shows. "text_regions" is a list of up to 4 boxes [left, top, right, bottom], each a fraction from 0 to 1 of the image exactly as it is shown to you here (not turned upright), drawn tightly around a label, plate or handwritten area whose characters matter (a serial number, a part number, a tag); [] when there is none.`;
1216
1218
  }
1217
1219
  return head + `- temporary URL (fetch this to read the file contents): ${attachment.url}`;
1218
1220
  }
@@ -3172,6 +3174,67 @@ function buildHistoryItemFullId(platform, service, itemId) {
3172
3174
  return `[POST]${url.toLowerCase()}#${service}:${itemId}`;
3173
3175
  }
3174
3176
 
3177
+ // src/engine/time.ts
3178
+ function wallClockNow() {
3179
+ return Date.now();
3180
+ }
3181
+ function formatChatTimestamp(ms) {
3182
+ if (typeof ms !== "number" || !isFinite(ms) || ms <= 0) return "";
3183
+ try {
3184
+ return new Date(ms).toLocaleString(void 0, {
3185
+ year: "numeric",
3186
+ month: "short",
3187
+ day: "numeric",
3188
+ hour: "numeric",
3189
+ minute: "2-digit",
3190
+ second: "2-digit"
3191
+ });
3192
+ } catch (e) {
3193
+ return "";
3194
+ }
3195
+ }
3196
+ function formatDuration(ms) {
3197
+ if (typeof ms !== "number" || !isFinite(ms) || ms < 1e3) return "";
3198
+ var total = Math.floor(ms / 1e3);
3199
+ var h = Math.floor(total / 3600);
3200
+ var m = Math.floor(total % 3600 / 60);
3201
+ var s = total % 60;
3202
+ var out = [];
3203
+ if (h) out.push(h + "h");
3204
+ if (m) out.push(m + "m");
3205
+ out.push(s + "s");
3206
+ return out.join(" ");
3207
+ }
3208
+ function formatIndexDuration(ms) {
3209
+ if (typeof ms !== "number" || !isFinite(ms) || ms < 1e3) return "";
3210
+ var total = Math.floor(ms / 1e3);
3211
+ var h = Math.floor(total / 3600);
3212
+ var m = Math.floor(total % 3600 / 60);
3213
+ var s = total % 60;
3214
+ if (h) return h + " h" + (m ? " " + m + " min" : "");
3215
+ if (m) return m + " min" + (s ? " " + s + " s" : "");
3216
+ return s + " s";
3217
+ }
3218
+ function requestIdTimeMs(rid) {
3219
+ if (typeof rid !== "string") return 0;
3220
+ var stamp = rid.split(":")[0] || "";
3221
+ if (stamp.length !== 13) return 0;
3222
+ var alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
3223
+ var v = 0;
3224
+ for (var i = 0; i < stamp.length; i++) {
3225
+ var d = alphabet.indexOf(stamp.charAt(i).toUpperCase());
3226
+ if (d < 0) return 0;
3227
+ v = v * 32 + d;
3228
+ }
3229
+ return Math.floor(v / 2 / 1e6);
3230
+ }
3231
+ function messageTimeMs(m) {
3232
+ if (!m) return 0;
3233
+ var r = typeof m._serverItemId === "string" ? requestIdTimeMs(m._serverItemId) : 0;
3234
+ if (r > 0) return r;
3235
+ return typeof m._ts === "number" && m._ts > 0 ? m._ts : 0;
3236
+ }
3237
+
3175
3238
  // src/engine/indexing_groups.ts
3176
3239
  function canonIndexKey(s) {
3177
3240
  return typeof s === "string" && s ? s.trim() : "";
@@ -3250,6 +3313,46 @@ function overlayRunRecordVerdict(grp, rec, liveIndexKeys) {
3250
3313
  grp.resolving = false;
3251
3314
  grp.resolvingReason = void 0;
3252
3315
  }
3316
+ function runRecordDurationMs(rec) {
3317
+ if (!rec || rec.status !== "done") return void 0;
3318
+ var a = rec.started;
3319
+ var b = rec.finished;
3320
+ if (typeof a !== "number" || typeof b !== "number" || !isFinite(a) || !isFinite(b) || b < a) return void 0;
3321
+ return b - a;
3322
+ }
3323
+ var RUN_DURATION_CLOCK_SLACK_MS = 6e4;
3324
+ var RUN_DURATION_SERVER_SLACK_MS = 5e3;
3325
+ function runRecordGroupDurationMs(grp, rec) {
3326
+ if (rec.status !== "done" || !grp.members.length) return void 0;
3327
+ var fin = rec.finished;
3328
+ if (typeof fin !== "number" || !isFinite(fin)) return void 0;
3329
+ var firstTs = messageTimeMs(grp.members[0].msg);
3330
+ var lastTs = messageTimeMs(grp.members[grp.members.length - 1].msg);
3331
+ if (!firstTs || !lastTs) return void 0;
3332
+ if (fin < firstTs || fin < lastTs - RUN_DURATION_SERVER_SLACK_MS) return void 0;
3333
+ var firstPassTs = 0;
3334
+ for (var i = 0; i < grp.members.length; i++) {
3335
+ var m = grp.members[i].msg;
3336
+ if (m.role !== "user") continue;
3337
+ var ref = readFileRef(m);
3338
+ if (ref && !ref.continued) firstPassTs = messageTimeMs(m);
3339
+ break;
3340
+ }
3341
+ var st = typeof rec.started === "number" && isFinite(rec.started) ? rec.started : void 0;
3342
+ var start;
3343
+ if (st !== void 0 && st > firstTs + RUN_DURATION_CLOCK_SLACK_MS) return void 0;
3344
+ if (firstPassTs) {
3345
+ start = st !== void 0 && st >= firstPassTs - RUN_DURATION_CLOCK_SLACK_MS ? st : firstPassTs;
3346
+ } else {
3347
+ if (st === void 0) return void 0;
3348
+ start = st;
3349
+ }
3350
+ return fin >= start ? fin - start : void 0;
3351
+ }
3352
+ function indexGroupDurationLabel(group) {
3353
+ if (!group || group.status !== "done" || !group.finished || group.resolving || group.queued) return "";
3354
+ return formatIndexDuration(group.durationMs);
3355
+ }
3253
3356
  function buildChatDisplayList(messages, opts) {
3254
3357
  var list = Array.isArray(messages) ? messages : [];
3255
3358
  var liveIndexKeys = opts && opts.liveIndexKeys || {};
@@ -3282,8 +3385,9 @@ function buildChatDisplayList(messages, opts) {
3282
3385
  var alreadySeen = !!(msg._serverItemId && runByItemId[msg._serverItemId]);
3283
3386
  var openId = openRunOfKey[key];
3284
3387
  var notLater = false;
3285
- if (openId && typeof msg._ts === "number" && typeof newestTsOfRun[openId] === "number") {
3286
- notLater = msg._ts <= newestTsOfRun[openId];
3388
+ var msgTime = messageTimeMs(msg);
3389
+ if (openId && msgTime > 0 && typeof newestTsOfRun[openId] === "number") {
3390
+ notLater = msgTime <= newestTsOfRun[openId];
3287
3391
  }
3288
3392
  if (!ref.continued && !alreadySeen && !notLater && openRunOfKey[key]) delete openRunOfKey[key];
3289
3393
  runId = openRunOfKey[key];
@@ -3297,9 +3401,10 @@ function buildChatDisplayList(messages, opts) {
3297
3401
  runId = runOfIndex[i - 1];
3298
3402
  }
3299
3403
  if (!runId) continue;
3300
- if (typeof msg._ts === "number") {
3404
+ var memberTime = messageTimeMs(msg);
3405
+ if (memberTime > 0) {
3301
3406
  var prevTs = newestTsOfRun[runId];
3302
- if (typeof prevTs !== "number" || msg._ts > prevTs) newestTsOfRun[runId] = msg._ts;
3407
+ if (typeof prevTs !== "number" || memberTime > prevTs) newestTsOfRun[runId] = memberTime;
3303
3408
  }
3304
3409
  var g = groups[runId];
3305
3410
  if (!g) {
@@ -3603,7 +3708,9 @@ function buildChatDisplayList(messages, opts) {
3603
3708
  resolvingReason: reason,
3604
3709
  stub: true,
3605
3710
  queued: waitingStub || live && !!runningKeys && !runningKeys[sp] && !runningKeys[canonIndexKey(sp)] && !runningKeys[fname] ? true : void 0,
3606
- stubError: rec.error || (st === "error" && !rec.error ? "Indexing did not finish." : void 0)
3711
+ stubError: rec.error || (st === "error" && !rec.error ? "Indexing did not finish." : void 0),
3712
+ // The stub IS the record, so a 'done' record's span is this run's.
3713
+ durationMs: st === "done" ? runRecordDurationMs(rec) : void 0
3607
3714
  };
3608
3715
  stubList.push({ started: typeof rec.started === "number" ? rec.started : Infinity, group: sg });
3609
3716
  }
@@ -3622,6 +3729,7 @@ function buildChatDisplayList(messages, opts) {
3622
3729
  tg.runKey = "run:" + (tg.path || tg.key) + "#" + trec.started;
3623
3730
  stubList.push({ started: trec.started, group: tg });
3624
3731
  overlayRunRecordVerdict(tg, trec, liveIndexKeys);
3732
+ tg.durationMs = runRecordGroupDurationMs(tg, trec);
3625
3733
  }
3626
3734
  }
3627
3735
  stubList.sort(function(a, b) {
@@ -4060,6 +4168,22 @@ var IMAGE_PREVIEWS_PER_MESSAGE = 8;
4060
4168
  var INLINE_LINK_GLYPH = "\u2197";
4061
4169
  var INLINE_LINK_UNAVAILABLE_GLYPH = "\u2715";
4062
4170
  var INLINE_LINK_UNAVAILABLE_SUFFIX = " (unavailable)";
4171
+ var FIT_LABEL_TAIL_CHARS = 8;
4172
+ function splitLabelForFit(name) {
4173
+ var chars = Array.from(String(name == null ? "" : name));
4174
+ var dot = -1;
4175
+ for (var i = chars.length - 1; i > 0; i--) {
4176
+ if (chars[i] === ".") {
4177
+ dot = i;
4178
+ break;
4179
+ }
4180
+ if (chars[i] === " " || chars[i] === "/" || chars.length - i > 10) break;
4181
+ }
4182
+ var extStart = dot > 0 && dot < chars.length - 1 ? dot : chars.length;
4183
+ var tailStart = Math.max(0, extStart - FIT_LABEL_TAIL_CHARS);
4184
+ if (tailStart < 4) return { stem: chars.join(""), tail: "" };
4185
+ return { stem: chars.slice(0, tailStart).join(""), tail: chars.slice(tailStart).join("") };
4186
+ }
4063
4187
  function renderInlineLinkHtml(link, opts) {
4064
4188
  var o = opts || {};
4065
4189
  var unavailable = !!o.unavailable;
@@ -4072,7 +4196,16 @@ function renderInlineLinkHtml(link, opts) {
4072
4196
  if (unavailable) cls.push("is-unavailable");
4073
4197
  if (preview) cls.push("is-image-preview");
4074
4198
  var glyphHtml = '<span class="bq-link-glyph" translate="no">' + (unavailable ? INLINE_LINK_UNAVAILABLE_GLYPH : INLINE_LINK_GLYPH) + "</span>";
4075
- var labelHtml = glyphHtml + escapeInlineHtml(link.label + (unavailable ? INLINE_LINK_UNAVAILABLE_SUFFIX : refreshing ? " (fetching...)" : ""));
4199
+ var stateSuffix = unavailable ? INLINE_LINK_UNAVAILABLE_SUFFIX : refreshing ? " (fetching...)" : "";
4200
+ var fit = !!o.fitLabel && !preview;
4201
+ if (fit) cls.push("bq-link-fit");
4202
+ var labelHtml;
4203
+ if (fit) {
4204
+ var split = splitLabelForFit(full);
4205
+ labelHtml = glyphHtml + '<span class="bq-link-stem">' + escapeInlineHtml(split.stem) + "</span>" + (split.tail ? '<span class="bq-link-tail">' + escapeInlineHtml(split.tail) + "</span>" : "") + (stateSuffix ? '<span class="bq-link-tail">' + escapeInlineHtml(stateSuffix) + "</span>" : "");
4206
+ } else {
4207
+ labelHtml = glyphHtml + escapeInlineHtml(link.label + stateSuffix);
4208
+ }
4076
4209
  var attrs = ['class="' + cls.join(" ") + '"'];
4077
4210
  if (unavailable) attrs.push('aria-disabled="true"', 'data-bq-unavailable="1"');
4078
4211
  else attrs.push('href="' + escapeInlineHtml(link.href) + '"', 'target="_blank"', 'rel="noopener noreferrer"');
@@ -4213,38 +4346,6 @@ function previewLayoutBox(img) {
4213
4346
  return closest.call(img, PREVIEW_LAYOUT_BOX_SELECTOR) || img;
4214
4347
  }
4215
4348
 
4216
- // src/engine/time.ts
4217
- function wallClockNow() {
4218
- return Date.now();
4219
- }
4220
- function formatChatTimestamp(ms) {
4221
- if (typeof ms !== "number" || !isFinite(ms) || ms <= 0) return "";
4222
- try {
4223
- return new Date(ms).toLocaleString(void 0, {
4224
- year: "numeric",
4225
- month: "short",
4226
- day: "numeric",
4227
- hour: "numeric",
4228
- minute: "2-digit",
4229
- second: "2-digit"
4230
- });
4231
- } catch (e) {
4232
- return "";
4233
- }
4234
- }
4235
- function formatDuration(ms) {
4236
- if (typeof ms !== "number" || !isFinite(ms) || ms < 1e3) return "";
4237
- var total = Math.floor(ms / 1e3);
4238
- var h = Math.floor(total / 3600);
4239
- var m = Math.floor(total % 3600 / 60);
4240
- var s = total % 60;
4241
- var out = [];
4242
- if (h) out.push(h + "h");
4243
- if (m) out.push(m + "m");
4244
- out.push(s + "s");
4245
- return out.join(" ");
4246
- }
4247
-
4248
4349
  // src/engine/ai_agent.ts
4249
4350
  function normalizePlatform(raw) {
4250
4351
  var p = (raw || "").trim().toLowerCase();
@@ -5826,25 +5927,16 @@ function streamRecoveryLabels(phase) {
5826
5927
  }
5827
5928
  var LIVE_PAINT_MIN_MS = 250;
5828
5929
  var LIVE_TYPE_MAX_STEP = 1200;
5829
- function requestIdTimeMs(rid) {
5830
- if (typeof rid !== "string") return 0;
5831
- var stamp = rid.split(":")[0] || "";
5832
- if (stamp.length !== 13) return 0;
5833
- var alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
5834
- var v = 0;
5835
- for (var i = 0; i < stamp.length; i++) {
5836
- var d = alphabet.indexOf(stamp.charAt(i).toUpperCase());
5837
- if (d < 0) return 0;
5838
- v = v * 32 + d;
5839
- }
5840
- return Math.floor(v / 2 / 1e6);
5841
- }
5842
5930
  var WRONG_ANSWER_MESSAGE = "This answer seems wrong. Please check it again against the documents.";
5843
5931
  var WRONG_ANSWER_LABEL = "Wrong answer?";
5844
5932
  function canReportWrongAnswer(msg) {
5845
5933
  var note = retrievalNoteOfAnswer(msg);
5846
5934
  return !!note && !answerUsedNoDataTool(note) && !msg.isCancelled;
5847
5935
  }
5936
+ var UPLOAD_CANCELLED_MESSAGE = "Upload cancelled";
5937
+ function isUploadCancelledError(err) {
5938
+ return !!err && (err.code === "CANCELLED" || err.message === UPLOAD_CANCELLED_MESSAGE);
5939
+ }
5848
5940
  var _ChatSession = class _ChatSession {
5849
5941
  constructor(host) {
5850
5942
  // --- live streaming ----------------------------------------------------
@@ -11766,15 +11858,18 @@ var _ChatSession = class _ChatSession {
11766
11858
  self.updateHistoryCache();
11767
11859
  });
11768
11860
  }
11769
- /** Insert bubbles before the first message that is newer than them (by `_ts`); messages
11770
- * without a time are skipped over, and the end of the list takes them otherwise. */
11861
+ /** Insert bubbles before the first message that is newer than them; messages whose time
11862
+ * is unknown are skipped over, and the end of the list takes them otherwise. A message's
11863
+ * time is its `_ts`, else (2026-11-25) the time in its request id: a live worker pass
11864
+ * adopted from the queue carries no `_ts`, and a file's older passes loaded by opening its
11865
+ * row (loadRunPasses) used to land AFTER it, which split one run into two rows. */
11771
11866
  _insertByTime(bubbles) {
11772
- var at = bubbles[0] && bubbles[0]._ts;
11867
+ var at = messageTimeMs(bubbles[0]);
11773
11868
  var idx = this.state.messages.length;
11774
- if (typeof at === "number") {
11869
+ if (at > 0) {
11775
11870
  for (var i = 0; i < this.state.messages.length; i++) {
11776
- var t = this.state.messages[i] && this.state.messages[i]._ts;
11777
- if (typeof t === "number" && t > at) {
11871
+ var t = messageTimeMs(this.state.messages[i]);
11872
+ if (t > 0 && t > at) {
11778
11873
  idx = i;
11779
11874
  break;
11780
11875
  }
@@ -13007,6 +13102,29 @@ var _ChatSession = class _ChatSession {
13007
13102
  });
13008
13103
  }
13009
13104
  // --- attachment upload orchestration ---------------------------------
13105
+ /**
13106
+ * The user cancelled this chip's upload (the widget's per-chip x or "Cancel all
13107
+ * uploads"). Stops the bytes now when they are moving (the host's abort), and
13108
+ * leaves a flag every later step of uploadSingleAttachment checks, so a cancel
13109
+ * that lands between steps (the get-signed-url round trip before the bytes, or
13110
+ * the src:: record and the indexing request after them) still stops the file
13111
+ * from being indexed and from being attached to the chat turn. A member whose
13112
+ * indexing request has already gone out is past cancelling: it shows as an
13113
+ * indexing row with its own Stop. Returns false for a chip that is not being
13114
+ * uploaded by this session any more.
13115
+ */
13116
+ cancelAttachmentUpload(att) {
13117
+ if (!att || att._cancelled) return false;
13118
+ if (att.status !== "uploading" && !att._batchId) return false;
13119
+ att._cancelled = true;
13120
+ if (typeof att._abort === "function") {
13121
+ try {
13122
+ att._abort();
13123
+ } catch (e) {
13124
+ }
13125
+ }
13126
+ return true;
13127
+ }
13010
13128
  // Upload one attachment (a file = 1 member, a folder = N) to db storage and
13011
13129
  // queue indexing per member. The bytes I/O + chip rendering go through host
13012
13130
  // hooks; the overwrite/reindex flow, status lifecycle, and indexing live here.
@@ -13029,6 +13147,17 @@ var _ChatSession = class _ChatSession {
13029
13147
  var anyIndexFailed = false;
13030
13148
  var reusedCount = 0;
13031
13149
  att.reused = false;
13150
+ att._storedCount = 0;
13151
+ att._indexQueuedCount = 0;
13152
+ att._indexQueued = false;
13153
+ var cancelError = function() {
13154
+ var e = new Error(UPLOAD_CANCELLED_MESSAGE);
13155
+ e.code = "CANCELLED";
13156
+ return e;
13157
+ };
13158
+ var checkCancel = function() {
13159
+ if (att._cancelled) throw cancelError();
13160
+ };
13032
13161
  delete att.duplicates;
13033
13162
  var chain = Promise.resolve();
13034
13163
  var findDuplicate = function(member) {
@@ -13045,10 +13174,12 @@ var _ChatSession = class _ChatSession {
13045
13174
  };
13046
13175
  members.forEach(function(member, idx) {
13047
13176
  chain = chain.then(function() {
13177
+ checkCancel();
13048
13178
  var hadExists = false;
13049
13179
  var skipped = false;
13050
13180
  var duplicateOf = null;
13051
13181
  var existedBefore = false;
13182
+ var madeRecord = false;
13052
13183
  var onProg = function(p) {
13053
13184
  if (p && p.total) {
13054
13185
  att.progress = Math.floor((idx + p.loaded / p.total) / total * 100);
@@ -13056,14 +13187,33 @@ var _ChatSession = class _ChatSession {
13056
13187
  }
13057
13188
  };
13058
13189
  var doMemberUpload = function(checkExistence) {
13190
+ checkCancel();
13059
13191
  return self.host.uploadFile({
13060
13192
  file: member.file,
13061
13193
  storagePath: member.storagePath,
13062
13194
  checkExistence,
13063
13195
  onProgress: onProg,
13196
+ // The host hands its abort over just before the bytes start. A
13197
+ // cancel made during the get-signed-url round trip had nothing to
13198
+ // abort yet, so it is applied here, before anything is sent: a
13199
+ // storage POST that never completes leaves no object behind.
13064
13200
  setAbort: function(abort) {
13065
13201
  att._abort = abort;
13202
+ if (att._cancelled) {
13203
+ try {
13204
+ abort();
13205
+ } catch (e) {
13206
+ }
13207
+ }
13066
13208
  }
13209
+ }).then(function(r) {
13210
+ att._abort = null;
13211
+ att._storedCount = (att._storedCount || 0) + 1;
13212
+ return r;
13213
+ }, function(err) {
13214
+ att._abort = null;
13215
+ if (att._cancelled) throw cancelError();
13216
+ throw err;
13067
13217
  });
13068
13218
  };
13069
13219
  if (isIndexRetry) {
@@ -13097,12 +13247,14 @@ var _ChatSession = class _ChatSession {
13097
13247
  existedBefore = true;
13098
13248
  });
13099
13249
  }).then(function() {
13250
+ checkCancel();
13100
13251
  if (skipped) return;
13101
13252
  return Promise.resolve(self.host.getTemporaryUrl(duplicateOf || member.storagePath)).catch(function(err) {
13102
13253
  var ecode = err && (err.code || err.body && err.body.code);
13103
13254
  var emsg = String(err && (err.message || err.body && err.body.message) || err || "");
13104
13255
  var refused = /no access to this file/i.test(emsg) || ecode === "INVALID_REQUEST" && /access/i.test(emsg);
13105
13256
  if (duplicateOf || !refused || typeof self.host.ensureFileIndexRecord !== "function") throw err;
13257
+ madeRecord = !existedBefore;
13106
13258
  return Promise.resolve(self.host.ensureFileIndexRecord(member.storagePath, {
13107
13259
  name: member.file.name,
13108
13260
  mime: member.file.type || self.host.getMimeType(member.file.name),
@@ -13112,6 +13264,13 @@ var _ChatSession = class _ChatSession {
13112
13264
  });
13113
13265
  });
13114
13266
  }).then(function(url) {
13267
+ if (att._cancelled) {
13268
+ var dropEarly = madeRecord && typeof self.host.deleteExistingFileRecord === "function" ? Promise.resolve(self.host.deleteExistingFileRecord(member.storagePath)).catch(function() {
13269
+ }) : Promise.resolve();
13270
+ return dropEarly.then(function() {
13271
+ throw cancelError();
13272
+ });
13273
+ }
13115
13274
  if (skipped) return;
13116
13275
  if (duplicateOf) {
13117
13276
  urls.push({ name: member.relPath, url, storagePath: duplicateOf });
@@ -13140,13 +13299,14 @@ var _ChatSession = class _ChatSession {
13140
13299
  var mime = member.file.type || self.host.getMimeType(member.file.name);
13141
13300
  var alreadyIndexing = false;
13142
13301
  var existingGroup = null;
13302
+ var clearedOld = false;
13143
13303
  var preIndex = self.claimIndexRun(member.storagePath).then(function(claimed) {
13144
13304
  alreadyIndexing = !claimed;
13145
13305
  if (alreadyIndexing) {
13146
13306
  console.log("[chat-engine] skipping a duplicate index request for", member.storagePath);
13147
13307
  return;
13148
13308
  }
13149
- if (!existedBefore) return;
13309
+ if (!existedBefore || att._cancelled) return;
13150
13310
  var readGroup = typeof self.host.readFileAccessGroup === "function" ? Promise.resolve(self.host.readFileAccessGroup(member.storagePath)).then(function(g) {
13151
13311
  existingGroup = g || null;
13152
13312
  }, function(err) {
@@ -13154,7 +13314,9 @@ var _ChatSession = class _ChatSession {
13154
13314
  throw err;
13155
13315
  }) : Promise.resolve();
13156
13316
  return readGroup.then(function() {
13317
+ if (att._cancelled) return;
13157
13318
  if (typeof self.host.deleteExistingFileRecord === "function") {
13319
+ clearedOld = true;
13158
13320
  return Promise.resolve(self.host.deleteExistingFileRecord(member.storagePath)).catch(function() {
13159
13321
  });
13160
13322
  }
@@ -13162,7 +13324,9 @@ var _ChatSession = class _ChatSession {
13162
13324
  });
13163
13325
  preIndex = preIndex.then(function() {
13164
13326
  if (alreadyIndexing) return;
13327
+ if (att._cancelled && !clearedOld) return;
13165
13328
  if (typeof self.host.ensureFileIndexRecord !== "function") return;
13329
+ if (!existedBefore) madeRecord = true;
13166
13330
  return Promise.resolve(self.host.ensureFileIndexRecord(member.storagePath, {
13167
13331
  name: member.file.name,
13168
13332
  mime: mime || void 0,
@@ -13183,10 +13347,28 @@ var _ChatSession = class _ChatSession {
13183
13347
  }).catch(function() {
13184
13348
  });
13185
13349
  });
13350
+ var abandonIfCancelled = function() {
13351
+ if (!att._cancelled) return;
13352
+ if (!alreadyIndexing) self.releaseIndexRun(member.storagePath);
13353
+ var drop = !existedBefore && !alreadyIndexing && madeRecord && typeof self.host.deleteExistingFileRecord === "function" ? Promise.resolve(self.host.deleteExistingFileRecord(member.storagePath)).catch(function() {
13354
+ }) : Promise.resolve();
13355
+ return drop.then(function() {
13356
+ throw cancelError();
13357
+ });
13358
+ };
13186
13359
  return preIndex.then(function() {
13360
+ return abandonIfCancelled();
13361
+ }).then(function() {
13187
13362
  return parseAttachmentContent(member.file, member.file.name, mime || void 0);
13363
+ }).then(function(parsedContent) {
13364
+ return Promise.resolve(abandonIfCancelled()).then(function() {
13365
+ return parsedContent;
13366
+ });
13188
13367
  }).then(function(parsedContent) {
13189
13368
  if (alreadyIndexing) return;
13369
+ att._indexQueuedCount = (att._indexQueuedCount || 0) + 1;
13370
+ if (att.kind !== "folder") att._indexQueued = true;
13371
+ self.host.renderAttachmentChips();
13190
13372
  return self.trackIndexDispatch(notifyAgentSaveAttachment({
13191
13373
  platform: id.platform,
13192
13374
  model: id.model,
@@ -13242,6 +13424,7 @@ var _ChatSession = class _ChatSession {
13242
13424
  });
13243
13425
  });
13244
13426
  return chain.then(function() {
13427
+ checkCancel();
13245
13428
  att._abort = null;
13246
13429
  att.progress = 100;
13247
13430
  if (att.kind === "folder") att.uploadedUrls = urls.map(function(u) {
@@ -13302,12 +13485,20 @@ var _ChatSession = class _ChatSession {
13302
13485
  return a.id === att.id;
13303
13486
  });
13304
13487
  var aborted = err && (err.message === "Aborted" || err === "Aborted");
13488
+ if (att._cancelled || isUploadCancelledError(err)) {
13489
+ att.status = "cancelled";
13490
+ att._abort = null;
13491
+ self.host.renderAttachmentChips();
13492
+ return;
13493
+ }
13305
13494
  if (removed || aborted) return;
13306
13495
  att.status = "error";
13307
13496
  att.errorMessage = "File upload has failed";
13308
13497
  att.errorCode = err && (err.code || err.body && err.body.code) || "";
13309
13498
  att.errorDetail = err && (err.message || err.body && err.body.message) || (typeof err === "string" ? err : "");
13310
13499
  self.host.renderAttachmentChips();
13500
+ }).then(function() {
13501
+ att._settledBatch = att._batchId || true;
13311
13502
  });
13312
13503
  });
13313
13504
  });
@@ -13422,6 +13613,7 @@ exports.UPLOAD_ACCESS_GROUPS = UPLOAD_ACCESS_GROUPS;
13422
13613
  exports.UPLOAD_ACCESS_HINTS = UPLOAD_ACCESS_HINTS;
13423
13614
  exports.UPLOAD_ACCESS_LABELS = UPLOAD_ACCESS_LABELS;
13424
13615
  exports.UPLOAD_ACCESS_OPTIONS = UPLOAD_ACCESS_OPTIONS;
13616
+ exports.UPLOAD_CANCELLED_MESSAGE = UPLOAD_CANCELLED_MESSAGE;
13425
13617
  exports.XML_EXTS = XML_EXTS;
13426
13618
  exports.__resetSplitHistoryState = __resetSplitHistoryState;
13427
13619
  exports.accessSettingFrom = accessSettingFrom;
@@ -13494,6 +13686,7 @@ exports.findAttachmentParser = findAttachmentParser;
13494
13686
  exports.findDuplicateUpload = findDuplicateUpload;
13495
13687
  exports.formatChatTimestamp = formatChatTimestamp;
13496
13688
  exports.formatDuration = formatDuration;
13689
+ exports.formatIndexDuration = formatIndexDuration;
13497
13690
  exports.formatRetrievalNote = formatRetrievalNote;
13498
13691
  exports.getAttachmentParsers = getAttachmentParsers;
13499
13692
  exports.getChatHistory = getChatHistory;
@@ -13510,6 +13703,7 @@ exports.groupAttachmentFailures = groupAttachmentFailures;
13510
13703
  exports.hasBom = hasBom;
13511
13704
  exports.hydrateImagePreviews = hydrateImagePreviews;
13512
13705
  exports.indexDoneUniqueId = indexDoneUniqueId;
13706
+ exports.indexGroupDurationLabel = indexGroupDurationLabel;
13513
13707
  exports.indexScopeKey = indexScopeKey;
13514
13708
  exports.indexingAccessGroup = indexingAccessGroup;
13515
13709
  exports.isAuthExpiredError = isAuthExpiredError;
@@ -13534,6 +13728,7 @@ exports.isReturnTrigger = isReturnTrigger;
13534
13728
  exports.isServerExtractable = isServerExtractable;
13535
13729
  exports.isServiceDbAttachmentHref = isServiceDbAttachmentHref;
13536
13730
  exports.isTransportFailure = isTransportFailure;
13731
+ exports.isUploadCancelledError = isUploadCancelledError;
13537
13732
  exports.isWindowedReadFile = isWindowedReadFile;
13538
13733
  exports.linkUnavailableKeyForHref = linkUnavailableKeyForHref;
13539
13734
  exports.linkUnavailableKeyForPath = linkUnavailableKeyForPath;
@@ -13548,6 +13743,7 @@ exports.makeExtractPlaceholder = makeExtractPlaceholder;
13548
13743
  exports.mapHistoryListToMessages = mapHistoryListToMessages;
13549
13744
  exports.markImagePreviewStale = markImagePreviewStale;
13550
13745
  exports.mayKeepStreamedAnswer = mayKeepStreamedAnswer;
13746
+ exports.messageTimeMs = messageTimeMs;
13551
13747
  exports.mintCacheBustStamp = mintCacheBustStamp;
13552
13748
  exports.needsBomForExt = needsBomForExt;
13553
13749
  exports.newClientRef = newClientRef;
@@ -13593,6 +13789,7 @@ exports.registerModelContextWindows = registerModelContextWindows;
13593
13789
  exports.renderInlineLinkHtml = renderInlineLinkHtml;
13594
13790
  exports.repairUrlEntities = repairUrlEntities;
13595
13791
  exports.repairUrlWhitespace = repairUrlWhitespace;
13792
+ exports.requestIdTimeMs = requestIdTimeMs;
13596
13793
  exports.resetFileIndexOnServer = resetFileIndexOnServer;
13597
13794
  exports.resolveAnswerMode = resolveAnswerMode;
13598
13795
  exports.resolveImagePreviewUrl = resolveImagePreviewUrl;
@@ -13601,6 +13798,7 @@ exports.resolveWebAccess = resolveWebAccess;
13601
13798
  exports.retrievalNoteFromText = retrievalNoteFromText;
13602
13799
  exports.retrievalNoteOfAnswer = retrievalNoteOfAnswer;
13603
13800
  exports.runIndexUniqueId = runIndexUniqueId;
13801
+ exports.runRecordDurationMs = runRecordDurationMs;
13604
13802
  exports.runSettleSideEffect = runSettleSideEffect;
13605
13803
  exports.safeDecodeURIComponent = safeDecodeURIComponent;
13606
13804
  exports.sanitizeAttachmentLinksForHistory = sanitizeAttachmentLinksForHistory;
@@ -13611,6 +13809,7 @@ exports.sideEffectDone = sideEffectDone;
13611
13809
  exports.skapiSupportsStreaming = skapiSupportsStreaming;
13612
13810
  exports.skipDuplicateFilesEnabled = skipDuplicateFilesEnabled;
13613
13811
  exports.skipDuplicateFilesFrom = skipDuplicateFilesFrom;
13812
+ exports.splitLabelForFit = splitLabelForFit;
13614
13813
  exports.statusPushEnabled = statusPushEnabled;
13615
13814
  exports.statusPushLive = statusPushLive;
13616
13815
  exports.streamRecoveryEnabled = streamRecoveryEnabled;