bunnyquery 1.21.4 → 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
  }
@@ -3203,6 +3205,16 @@ function formatDuration(ms) {
3203
3205
  out.push(s + "s");
3204
3206
  return out.join(" ");
3205
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
+ }
3206
3218
  function requestIdTimeMs(rid) {
3207
3219
  if (typeof rid !== "string") return 0;
3208
3220
  var stamp = rid.split(":")[0] || "";
@@ -3301,6 +3313,46 @@ function overlayRunRecordVerdict(grp, rec, liveIndexKeys) {
3301
3313
  grp.resolving = false;
3302
3314
  grp.resolvingReason = void 0;
3303
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
+ }
3304
3356
  function buildChatDisplayList(messages, opts) {
3305
3357
  var list = Array.isArray(messages) ? messages : [];
3306
3358
  var liveIndexKeys = opts && opts.liveIndexKeys || {};
@@ -3656,7 +3708,9 @@ function buildChatDisplayList(messages, opts) {
3656
3708
  resolvingReason: reason,
3657
3709
  stub: true,
3658
3710
  queued: waitingStub || live && !!runningKeys && !runningKeys[sp] && !runningKeys[canonIndexKey(sp)] && !runningKeys[fname] ? true : void 0,
3659
- 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
3660
3714
  };
3661
3715
  stubList.push({ started: typeof rec.started === "number" ? rec.started : Infinity, group: sg });
3662
3716
  }
@@ -3675,6 +3729,7 @@ function buildChatDisplayList(messages, opts) {
3675
3729
  tg.runKey = "run:" + (tg.path || tg.key) + "#" + trec.started;
3676
3730
  stubList.push({ started: trec.started, group: tg });
3677
3731
  overlayRunRecordVerdict(tg, trec, liveIndexKeys);
3732
+ tg.durationMs = runRecordGroupDurationMs(tg, trec);
3678
3733
  }
3679
3734
  }
3680
3735
  stubList.sort(function(a, b) {
@@ -4113,6 +4168,22 @@ var IMAGE_PREVIEWS_PER_MESSAGE = 8;
4113
4168
  var INLINE_LINK_GLYPH = "\u2197";
4114
4169
  var INLINE_LINK_UNAVAILABLE_GLYPH = "\u2715";
4115
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
+ }
4116
4187
  function renderInlineLinkHtml(link, opts) {
4117
4188
  var o = opts || {};
4118
4189
  var unavailable = !!o.unavailable;
@@ -4125,7 +4196,16 @@ function renderInlineLinkHtml(link, opts) {
4125
4196
  if (unavailable) cls.push("is-unavailable");
4126
4197
  if (preview) cls.push("is-image-preview");
4127
4198
  var glyphHtml = '<span class="bq-link-glyph" translate="no">' + (unavailable ? INLINE_LINK_UNAVAILABLE_GLYPH : INLINE_LINK_GLYPH) + "</span>";
4128
- 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
+ }
4129
4209
  var attrs = ['class="' + cls.join(" ") + '"'];
4130
4210
  if (unavailable) attrs.push('aria-disabled="true"', 'data-bq-unavailable="1"');
4131
4211
  else attrs.push('href="' + escapeInlineHtml(link.href) + '"', 'target="_blank"', 'rel="noopener noreferrer"');
@@ -5853,6 +5933,10 @@ function canReportWrongAnswer(msg) {
5853
5933
  var note = retrievalNoteOfAnswer(msg);
5854
5934
  return !!note && !answerUsedNoDataTool(note) && !msg.isCancelled;
5855
5935
  }
5936
+ var UPLOAD_CANCELLED_MESSAGE = "Upload cancelled";
5937
+ function isUploadCancelledError(err) {
5938
+ return !!err && (err.code === "CANCELLED" || err.message === UPLOAD_CANCELLED_MESSAGE);
5939
+ }
5856
5940
  var _ChatSession = class _ChatSession {
5857
5941
  constructor(host) {
5858
5942
  // --- live streaming ----------------------------------------------------
@@ -13018,6 +13102,29 @@ var _ChatSession = class _ChatSession {
13018
13102
  });
13019
13103
  }
13020
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
+ }
13021
13128
  // Upload one attachment (a file = 1 member, a folder = N) to db storage and
13022
13129
  // queue indexing per member. The bytes I/O + chip rendering go through host
13023
13130
  // hooks; the overwrite/reindex flow, status lifecycle, and indexing live here.
@@ -13040,6 +13147,17 @@ var _ChatSession = class _ChatSession {
13040
13147
  var anyIndexFailed = false;
13041
13148
  var reusedCount = 0;
13042
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
+ };
13043
13161
  delete att.duplicates;
13044
13162
  var chain = Promise.resolve();
13045
13163
  var findDuplicate = function(member) {
@@ -13056,10 +13174,12 @@ var _ChatSession = class _ChatSession {
13056
13174
  };
13057
13175
  members.forEach(function(member, idx) {
13058
13176
  chain = chain.then(function() {
13177
+ checkCancel();
13059
13178
  var hadExists = false;
13060
13179
  var skipped = false;
13061
13180
  var duplicateOf = null;
13062
13181
  var existedBefore = false;
13182
+ var madeRecord = false;
13063
13183
  var onProg = function(p) {
13064
13184
  if (p && p.total) {
13065
13185
  att.progress = Math.floor((idx + p.loaded / p.total) / total * 100);
@@ -13067,14 +13187,33 @@ var _ChatSession = class _ChatSession {
13067
13187
  }
13068
13188
  };
13069
13189
  var doMemberUpload = function(checkExistence) {
13190
+ checkCancel();
13070
13191
  return self.host.uploadFile({
13071
13192
  file: member.file,
13072
13193
  storagePath: member.storagePath,
13073
13194
  checkExistence,
13074
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.
13075
13200
  setAbort: function(abort) {
13076
13201
  att._abort = abort;
13202
+ if (att._cancelled) {
13203
+ try {
13204
+ abort();
13205
+ } catch (e) {
13206
+ }
13207
+ }
13077
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;
13078
13217
  });
13079
13218
  };
13080
13219
  if (isIndexRetry) {
@@ -13108,12 +13247,14 @@ var _ChatSession = class _ChatSession {
13108
13247
  existedBefore = true;
13109
13248
  });
13110
13249
  }).then(function() {
13250
+ checkCancel();
13111
13251
  if (skipped) return;
13112
13252
  return Promise.resolve(self.host.getTemporaryUrl(duplicateOf || member.storagePath)).catch(function(err) {
13113
13253
  var ecode = err && (err.code || err.body && err.body.code);
13114
13254
  var emsg = String(err && (err.message || err.body && err.body.message) || err || "");
13115
13255
  var refused = /no access to this file/i.test(emsg) || ecode === "INVALID_REQUEST" && /access/i.test(emsg);
13116
13256
  if (duplicateOf || !refused || typeof self.host.ensureFileIndexRecord !== "function") throw err;
13257
+ madeRecord = !existedBefore;
13117
13258
  return Promise.resolve(self.host.ensureFileIndexRecord(member.storagePath, {
13118
13259
  name: member.file.name,
13119
13260
  mime: member.file.type || self.host.getMimeType(member.file.name),
@@ -13123,6 +13264,13 @@ var _ChatSession = class _ChatSession {
13123
13264
  });
13124
13265
  });
13125
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
+ }
13126
13274
  if (skipped) return;
13127
13275
  if (duplicateOf) {
13128
13276
  urls.push({ name: member.relPath, url, storagePath: duplicateOf });
@@ -13151,13 +13299,14 @@ var _ChatSession = class _ChatSession {
13151
13299
  var mime = member.file.type || self.host.getMimeType(member.file.name);
13152
13300
  var alreadyIndexing = false;
13153
13301
  var existingGroup = null;
13302
+ var clearedOld = false;
13154
13303
  var preIndex = self.claimIndexRun(member.storagePath).then(function(claimed) {
13155
13304
  alreadyIndexing = !claimed;
13156
13305
  if (alreadyIndexing) {
13157
13306
  console.log("[chat-engine] skipping a duplicate index request for", member.storagePath);
13158
13307
  return;
13159
13308
  }
13160
- if (!existedBefore) return;
13309
+ if (!existedBefore || att._cancelled) return;
13161
13310
  var readGroup = typeof self.host.readFileAccessGroup === "function" ? Promise.resolve(self.host.readFileAccessGroup(member.storagePath)).then(function(g) {
13162
13311
  existingGroup = g || null;
13163
13312
  }, function(err) {
@@ -13165,7 +13314,9 @@ var _ChatSession = class _ChatSession {
13165
13314
  throw err;
13166
13315
  }) : Promise.resolve();
13167
13316
  return readGroup.then(function() {
13317
+ if (att._cancelled) return;
13168
13318
  if (typeof self.host.deleteExistingFileRecord === "function") {
13319
+ clearedOld = true;
13169
13320
  return Promise.resolve(self.host.deleteExistingFileRecord(member.storagePath)).catch(function() {
13170
13321
  });
13171
13322
  }
@@ -13173,7 +13324,9 @@ var _ChatSession = class _ChatSession {
13173
13324
  });
13174
13325
  preIndex = preIndex.then(function() {
13175
13326
  if (alreadyIndexing) return;
13327
+ if (att._cancelled && !clearedOld) return;
13176
13328
  if (typeof self.host.ensureFileIndexRecord !== "function") return;
13329
+ if (!existedBefore) madeRecord = true;
13177
13330
  return Promise.resolve(self.host.ensureFileIndexRecord(member.storagePath, {
13178
13331
  name: member.file.name,
13179
13332
  mime: mime || void 0,
@@ -13194,10 +13347,28 @@ var _ChatSession = class _ChatSession {
13194
13347
  }).catch(function() {
13195
13348
  });
13196
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
+ };
13197
13359
  return preIndex.then(function() {
13360
+ return abandonIfCancelled();
13361
+ }).then(function() {
13198
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
+ });
13199
13367
  }).then(function(parsedContent) {
13200
13368
  if (alreadyIndexing) return;
13369
+ att._indexQueuedCount = (att._indexQueuedCount || 0) + 1;
13370
+ if (att.kind !== "folder") att._indexQueued = true;
13371
+ self.host.renderAttachmentChips();
13201
13372
  return self.trackIndexDispatch(notifyAgentSaveAttachment({
13202
13373
  platform: id.platform,
13203
13374
  model: id.model,
@@ -13253,6 +13424,7 @@ var _ChatSession = class _ChatSession {
13253
13424
  });
13254
13425
  });
13255
13426
  return chain.then(function() {
13427
+ checkCancel();
13256
13428
  att._abort = null;
13257
13429
  att.progress = 100;
13258
13430
  if (att.kind === "folder") att.uploadedUrls = urls.map(function(u) {
@@ -13313,12 +13485,20 @@ var _ChatSession = class _ChatSession {
13313
13485
  return a.id === att.id;
13314
13486
  });
13315
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
+ }
13316
13494
  if (removed || aborted) return;
13317
13495
  att.status = "error";
13318
13496
  att.errorMessage = "File upload has failed";
13319
13497
  att.errorCode = err && (err.code || err.body && err.body.code) || "";
13320
13498
  att.errorDetail = err && (err.message || err.body && err.body.message) || (typeof err === "string" ? err : "");
13321
13499
  self.host.renderAttachmentChips();
13500
+ }).then(function() {
13501
+ att._settledBatch = att._batchId || true;
13322
13502
  });
13323
13503
  });
13324
13504
  });
@@ -13433,6 +13613,7 @@ exports.UPLOAD_ACCESS_GROUPS = UPLOAD_ACCESS_GROUPS;
13433
13613
  exports.UPLOAD_ACCESS_HINTS = UPLOAD_ACCESS_HINTS;
13434
13614
  exports.UPLOAD_ACCESS_LABELS = UPLOAD_ACCESS_LABELS;
13435
13615
  exports.UPLOAD_ACCESS_OPTIONS = UPLOAD_ACCESS_OPTIONS;
13616
+ exports.UPLOAD_CANCELLED_MESSAGE = UPLOAD_CANCELLED_MESSAGE;
13436
13617
  exports.XML_EXTS = XML_EXTS;
13437
13618
  exports.__resetSplitHistoryState = __resetSplitHistoryState;
13438
13619
  exports.accessSettingFrom = accessSettingFrom;
@@ -13505,6 +13686,7 @@ exports.findAttachmentParser = findAttachmentParser;
13505
13686
  exports.findDuplicateUpload = findDuplicateUpload;
13506
13687
  exports.formatChatTimestamp = formatChatTimestamp;
13507
13688
  exports.formatDuration = formatDuration;
13689
+ exports.formatIndexDuration = formatIndexDuration;
13508
13690
  exports.formatRetrievalNote = formatRetrievalNote;
13509
13691
  exports.getAttachmentParsers = getAttachmentParsers;
13510
13692
  exports.getChatHistory = getChatHistory;
@@ -13521,6 +13703,7 @@ exports.groupAttachmentFailures = groupAttachmentFailures;
13521
13703
  exports.hasBom = hasBom;
13522
13704
  exports.hydrateImagePreviews = hydrateImagePreviews;
13523
13705
  exports.indexDoneUniqueId = indexDoneUniqueId;
13706
+ exports.indexGroupDurationLabel = indexGroupDurationLabel;
13524
13707
  exports.indexScopeKey = indexScopeKey;
13525
13708
  exports.indexingAccessGroup = indexingAccessGroup;
13526
13709
  exports.isAuthExpiredError = isAuthExpiredError;
@@ -13545,6 +13728,7 @@ exports.isReturnTrigger = isReturnTrigger;
13545
13728
  exports.isServerExtractable = isServerExtractable;
13546
13729
  exports.isServiceDbAttachmentHref = isServiceDbAttachmentHref;
13547
13730
  exports.isTransportFailure = isTransportFailure;
13731
+ exports.isUploadCancelledError = isUploadCancelledError;
13548
13732
  exports.isWindowedReadFile = isWindowedReadFile;
13549
13733
  exports.linkUnavailableKeyForHref = linkUnavailableKeyForHref;
13550
13734
  exports.linkUnavailableKeyForPath = linkUnavailableKeyForPath;
@@ -13614,6 +13798,7 @@ exports.resolveWebAccess = resolveWebAccess;
13614
13798
  exports.retrievalNoteFromText = retrievalNoteFromText;
13615
13799
  exports.retrievalNoteOfAnswer = retrievalNoteOfAnswer;
13616
13800
  exports.runIndexUniqueId = runIndexUniqueId;
13801
+ exports.runRecordDurationMs = runRecordDurationMs;
13617
13802
  exports.runSettleSideEffect = runSettleSideEffect;
13618
13803
  exports.safeDecodeURIComponent = safeDecodeURIComponent;
13619
13804
  exports.sanitizeAttachmentLinksForHistory = sanitizeAttachmentLinksForHistory;
@@ -13624,6 +13809,7 @@ exports.sideEffectDone = sideEffectDone;
13624
13809
  exports.skapiSupportsStreaming = skapiSupportsStreaming;
13625
13810
  exports.skipDuplicateFilesEnabled = skipDuplicateFilesEnabled;
13626
13811
  exports.skipDuplicateFilesFrom = skipDuplicateFilesFrom;
13812
+ exports.splitLabelForFit = splitLabelForFit;
13627
13813
  exports.statusPushEnabled = statusPushEnabled;
13628
13814
  exports.statusPushLive = statusPushLive;
13629
13815
  exports.streamRecoveryEnabled = streamRecoveryEnabled;