bunnyquery 1.21.4 → 1.21.12

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/bunnyquery.js CHANGED
@@ -68,6 +68,13 @@
68
68
  function skipDuplicateFilesFrom(data) {
69
69
  return data ? normalizeSkipDuplicateFiles(data.skip_duplicate_files) : DEFAULT_SKIP_DUPLICATE_FILES;
70
70
  }
71
+ var DEFAULT_SHARE_IDENTICAL_FILES = true;
72
+ function normalizeShareIdenticalFiles(value) {
73
+ return value !== false;
74
+ }
75
+ function shareIdenticalFilesFrom(data) {
76
+ return data ? normalizeShareIdenticalFiles(data.share_identical_files) : DEFAULT_SHARE_IDENTICAL_FILES;
77
+ }
71
78
  var DEFAULT_ANSWER_MODE = "standard";
72
79
  function normalizeAnswerMode(value) {
73
80
  return value === "fast" || value === "thorough" ? value : DEFAULT_ANSWER_MODE;
@@ -151,6 +158,9 @@
151
158
  function projectChatGreeting(service) {
152
159
  return chatGreetingFrom(cachedProjectSettings(service));
153
160
  }
161
+ function projectShareIdenticalFiles(service) {
162
+ return shareIdenticalFilesFrom(cachedProjectSettings(service));
163
+ }
154
164
 
155
165
  // src/engine/config.ts
156
166
  var _config = null;
@@ -996,10 +1006,12 @@ Extracted content of attached office files (read inline below; do NOT fetch thei
996
1006
  const webAccess = params.webAccess === true;
997
1007
  const g = params.indexAccessGroup;
998
1008
  const indexGroupLiteral = typeof g === "number" ? String(g) : g === "public" || g === "private" || g === "authorized" || g === "admin" ? `"${g}"` : '"authorized"';
1009
+ const reindexHint = canUpload === false ? `asking the project's owner to re-index that file` : `re-indexing that file (attach the same file again and choose to reindex it)`;
999
1010
  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.
1000
1011
  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`}.
1012
+ 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 ONLY when the value could be a spreadsheet cell or a row, and then with ONE filtered getRecords on that value, never by paging through a whole table), keep the answer short. The text read from photos, scans and other images IS in the page text searchText covered, so a code, serial or phrase asked about a photo needs no records read: 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.
1001
1013
  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.
1002
- 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.`;
1014
+ 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.`;
1003
1015
  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.`;
1004
1016
  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.
1005
1017
  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.`;
@@ -1016,6 +1028,7 @@ NUMBERS FROM A SPREADSHEET are computed from the ROWS, never from one page and n
1016
1028
  ${documentRules}
1017
1029
  ${accessGroupRule}
1018
1030
  COMPLETE ANSWERS: ONE file is routinely SPLIT ACROSS SEVERAL TABLES (a summary row in one, its page or row content in another, its extracted pictures in "__MEDIA__"), so for anything not scoped to a single file run the query in EVERY table that could hold the answer and combine the results. For any request that counts, sums, totals, lists every match, compares across records, finds which one, or asks whether something is present or ABSENT (for example "how many", "total spent", "which card", "is there any", "\uC5C6\uC5B4?", "\uD558\uB098\uB3C4 \uC5C6\uB098?"), read the COMPLETE matching set across every such table and file before answering. Never assert absence ("there is no X", "none", "not found", "\uC544\uB2C8\uC694, \uC5C6\uC2B5\uB2C8\uB2E4") until a complete scan has come back empty: a confident "no" that later turns out wrong is worse than telling the user you are still checking. If you answered from one table and then find another holds more, re-run the sweep and give the complete answer instead of only apologising.
1031
+ LINKED COPIES: files with the same content are indexed once. A file a tool reports as a linked copy (linked_copy, or listed in a hit's also_at) has no rows or pages of its own: its content is the original's, stored and tagged under the original's name. Cite the original file and say that the copy is the same file; never count the two as two documents.
1019
1032
  Embedded values: a search term is often stored inside a larger string (a merchant "BAKSA" as "DNH*BAKSA#4070277042", a card as "5860****5173"), which no index or tag filter matches. When the value may be embedded, fetch the full set with fetch_all and match the substring yourself.
1020
1033
  File attachments: an "Attached files:" section with markdown links in a user message points at short-lived signed URLs in this project's storage. Image files (.jpg, .jpeg, .png, .gif, .webp) are ALREADY in the message as image blocks: look at them directly. Every other attached file (office documents such as .docx/.xlsx/.pptx/.hwp/.hwpx/.ods, PDFs, email (.eml), text/data/code files such as .csv/.tsv/.json/.xml/.txt/.md) is ALREADY INDEXED: it was read end to end when it was uploaded, before this message reached you, so answer from its records (reference "src::<the storage path from the attachment link>"), and for its exact wording use searchText or readFileContent on that same path (see DOCUMENTS). Some turns instead carry the file text between "BEGIN FILE CONTENT" / "END FILE CONTENT" markers: read that block directly; a "[skapi: ...]" note inside it means that file could not be extracted. ${webAccess ? `Never web_fetch an attachment link (the picture is already in the message, everything else is in the database); a file the user gives as an outside web address may be fetched under the web rule above.` : `This chat has no web tool: never try to download or fetch an attachment link.`}
1021
1034
  Stored files: a file already in this project's storage was read end to end at upload time, so its records come first. For its exact wording find the page with searchText (DOCUMENTS); readFileContent re-reads the raw file (an older file without page text, a data file), and you read it to the end before concluding anything is absent there. If its pictures do not reach you, say so plainly and fall back to the indexed records; never call a file unreadable when its content is in the database.
@@ -1067,7 +1080,7 @@ Project description: """${serviceDescription}"""`;
1067
1080
  - 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.
1068
1081
  - 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).
1069
1082
  - 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.
1070
- - 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).
1083
+ - 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.
1071
1084
  - 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.
1072
1085
  - 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.
1073
1086
  - 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.
@@ -1144,7 +1157,7 @@ Read this file with the readFileContent tool, using the storage path above - do
1144
1157
  return head + `- temporary URL: ${attachment.url}
1145
1158
  ` + (options.imageFile === "attached" ? `
1146
1159
  This is an IMAGE file, attached to this message as an image: read it there, not from the URL. ` : `
1147
- 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.`;
1160
+ 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.`;
1148
1161
  }
1149
1162
  return head + `- temporary URL (fetch this to read the file contents): ${attachment.url}`;
1150
1163
  }
@@ -2766,12 +2779,14 @@ Index the REMAINING windows - one record per row/item, looking at any page image
2766
2779
  const singlePass = !visionFile && !windowedRead && !pagedRead && !continuing;
2767
2780
  const imageFile = singlePass && !parsedContent && !serverExtract ? indexingImageFile(attachment) : void 0;
2768
2781
  const fileUrlDetail = imageFile && platform === "openai" ? getOpenAIImageDetail(info.model || DEFAULT_OPENAI_MODEL) : void 0;
2782
+ const shareIdentical = !continuing && info.shareIdentical !== false && (info.shareIdentical === true || projectShareIdenticalFiles(service));
2769
2783
  const skapiFileUrls = attachment.url && attachment.storagePath ? {
2770
2784
  _skapi_file_urls: [{
2771
2785
  path: attachment.storagePath,
2772
2786
  url: attachment.url,
2773
2787
  ...singlePass ? { index_end: true } : {},
2774
- ...fileUrlDetail ? { detail: fileUrlDetail } : {}
2788
+ ...fileUrlDetail ? { detail: fileUrlDetail } : {},
2789
+ ...shareIdentical ? { share_identical: true } : {}
2775
2790
  }]
2776
2791
  } : {};
2777
2792
  const userMessage = visionFile && renderPlaceholder ? buildIndexingRenderMessage(attachment, renderPlaceholder, renderFrom) : windowedRead && windowPlaceholder ? buildIndexingWindowMessage(attachment, windowPlaceholder, false) : continuing ? buildIndexingContinueMessage(attachment) : buildIndexingUserMessage(
@@ -2898,13 +2913,26 @@ Index the REMAINING windows - one record per row/item, looking at any page image
2898
2913
  }
2899
2914
  }));
2900
2915
  }
2916
+ function providerDocument(response) {
2917
+ if (typeof response !== "string") return response;
2918
+ var t = response.trim();
2919
+ if (t.charAt(0) !== "{" || t.charAt(t.length - 1) !== "}") return response;
2920
+ try {
2921
+ var doc = JSON.parse(t);
2922
+ return doc && typeof doc === "object" && !Array.isArray(doc) ? doc : response;
2923
+ } catch (e) {
2924
+ return response;
2925
+ }
2926
+ }
2901
2927
  function extractClaudeText(response) {
2928
+ response = providerDocument(response);
2902
2929
  if (!Array.isArray(response?.content)) {
2903
2930
  return "";
2904
2931
  }
2905
2932
  return response.content.filter((block) => block?.type === "text").map((block) => block.text).join("\n");
2906
2933
  }
2907
2934
  function extractOpenAIText(response) {
2935
+ response = providerDocument(response);
2908
2936
  if (typeof response?.output_text === "string" && response.output_text.length) {
2909
2937
  return response.output_text;
2910
2938
  }
@@ -3051,6 +3079,16 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3051
3079
  out.push(s + "s");
3052
3080
  return out.join(" ");
3053
3081
  }
3082
+ function formatIndexDuration(ms) {
3083
+ if (typeof ms !== "number" || !isFinite(ms) || ms < 1e3) return "";
3084
+ var total = Math.floor(ms / 1e3);
3085
+ var h = Math.floor(total / 3600);
3086
+ var m = Math.floor(total % 3600 / 60);
3087
+ var s = total % 60;
3088
+ if (h) return h + " h" + (m ? " " + m + " min" : "");
3089
+ if (m) return m + " min" + (s ? " " + s + " s" : "");
3090
+ return s + " s";
3091
+ }
3054
3092
  function requestIdTimeMs(rid) {
3055
3093
  if (typeof rid !== "string") return 0;
3056
3094
  var stamp = rid.split(":")[0] || "";
@@ -3071,6 +3109,122 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3071
3109
  return typeof m._ts === "number" && m._ts > 0 ? m._ts : 0;
3072
3110
  }
3073
3111
 
3112
+ // src/engine/identical.ts
3113
+ var LINKED_COPY_TAG = "bq_linked";
3114
+ function linkedMarkerOf(data) {
3115
+ if (!data || typeof data !== "object" || data.linked !== true) return null;
3116
+ var original = typeof data.alias_of === "string" ? data.alias_of : "";
3117
+ if (!original) return null;
3118
+ var at = Number(data.completed_at || data.finished || data.linked_at);
3119
+ return {
3120
+ original,
3121
+ claim: typeof data.alias_claim === "string" && data.alias_claim ? data.alias_claim : void 0,
3122
+ linkedAt: isFinite(at) && at > 0 ? at : void 0,
3123
+ group: data.copy_group !== void 0 ? data.copy_group : void 0,
3124
+ owner: typeof data.copy_owner === "string" ? data.copy_owner : void 0,
3125
+ contentKey: typeof data.content_key === "string" && data.content_key ? data.content_key : void 0
3126
+ };
3127
+ }
3128
+ function fileNameOf(path) {
3129
+ var s = String(path || "");
3130
+ var at = s.lastIndexOf("/");
3131
+ return at === -1 ? s : s.slice(at + 1);
3132
+ }
3133
+ function copiesByOriginal(linked) {
3134
+ var entries = linked instanceof Map ? Array.from(linked.entries()) : Object.keys(linked).map(function(k) {
3135
+ return [k, linked[k]];
3136
+ });
3137
+ entries.sort(function(a, b) {
3138
+ return (a[1].linkedAt || 0) - (b[1].linkedAt || 0) || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
3139
+ });
3140
+ var out = /* @__PURE__ */ new Map();
3141
+ for (var i = 0; i < entries.length; i++) {
3142
+ var o = entries[i][1].original;
3143
+ if (!out.has(o)) out.set(o, []);
3144
+ out.get(o).push(entries[i][0]);
3145
+ }
3146
+ return out;
3147
+ }
3148
+ function formatLinkDuration(ms) {
3149
+ if (typeof ms !== "number" || !isFinite(ms) || ms < 0) return "";
3150
+ if (ms < 1e4) return (Math.max(ms, 100) / 1e3).toFixed(1) + " s";
3151
+ return formatIndexDuration(ms);
3152
+ }
3153
+ function linkedRowLabel(original, ms) {
3154
+ var took = formatLinkDuration(ms);
3155
+ return "Same content as " + fileNameOf(original) + ": linked" + (took ? " in " + took : "") + ", no AI used";
3156
+ }
3157
+ function parseLinkedReply(text) {
3158
+ if (typeof text !== "string" || text.indexOf('[skapi] Same content as "') === -1) return null;
3159
+ var m = /\[skapi\] Same content as "([^"]+)": linked to its index(?: in ([0-9]+(?:\.[0-9]+)?) s)?/.exec(text);
3160
+ if (!m) return null;
3161
+ var secs = m[2] !== void 0 ? Number(m[2]) : NaN;
3162
+ return { original: m[1], ms: isFinite(secs) ? Math.round(secs * 1e3) : void 0 };
3163
+ }
3164
+ function promotableCopies(linked, actor) {
3165
+ var entries = linked instanceof Map ? Array.from(linked.entries()) : Object.keys(linked).map(function(k) {
3166
+ return [k, linked[k]];
3167
+ });
3168
+ var out = /* @__PURE__ */ new Map();
3169
+ for (var i = 0; i < entries.length; i++) {
3170
+ var m = entries[i][1];
3171
+ if (actor.isProjectOwner || !!actor.userId && !!m && m.owner === actor.userId) out.set(entries[i][0], m);
3172
+ }
3173
+ return out;
3174
+ }
3175
+ function copiesToPromote(linked, removed, removedFolders, actor) {
3176
+ if (actor) linked = promotableCopies(linked, actor);
3177
+ var gone = new Set(removed || []);
3178
+ var folders = (removedFolders || []).filter(Boolean).map(function(f) {
3179
+ return f.replace(/\/+$/, "") + "/";
3180
+ });
3181
+ var isGone = function(p) {
3182
+ if (gone.has(p)) return true;
3183
+ for (var i = 0; i < folders.length; i++) if (p.indexOf(folders[i]) === 0) return true;
3184
+ return false;
3185
+ };
3186
+ var out = [];
3187
+ copiesByOriginal(linked).forEach(function(copies, original) {
3188
+ if (!isGone(original)) return;
3189
+ var keep = copies.filter(function(c) {
3190
+ return !isGone(c);
3191
+ });
3192
+ if (keep.length) out.push({ original, copies: keep });
3193
+ });
3194
+ return out;
3195
+ }
3196
+ function listOf(res) {
3197
+ return res && Array.isArray(res.list) ? res.list : [];
3198
+ }
3199
+ async function listLinkedCopies(skapi, service, maxPages = 10) {
3200
+ if (!skapi || typeof skapi.getRecords !== "function" || !service) return null;
3201
+ var out = /* @__PURE__ */ new Map();
3202
+ try {
3203
+ var fetchMore = false;
3204
+ for (var page = 0; page < maxPages; page++) {
3205
+ var res = await skapi.getRecords(
3206
+ { service, table: { name: "__INDEXING__", access_group: "authorized" }, tag: LINKED_COPY_TAG },
3207
+ { limit: 1e3, fetchMore }
3208
+ );
3209
+ var list = listOf(res);
3210
+ for (var i = 0; i < list.length; i++) {
3211
+ var r = list[i] || {};
3212
+ var uid = String(r.unique_id || "");
3213
+ if (uid.indexOf("done::") !== 0) continue;
3214
+ var mk = linkedMarkerOf(r.data);
3215
+ if (mk) out.set(uid.slice(6), mk);
3216
+ }
3217
+ if (!res || res.endOfList !== false) return out;
3218
+ fetchMore = true;
3219
+ }
3220
+ return out;
3221
+ } catch (err) {
3222
+ var msg = String(err && (err.code || err.message) || err || "");
3223
+ if (/NOT_EXISTS|not exist/i.test(msg)) return out;
3224
+ return null;
3225
+ }
3226
+ }
3227
+
3074
3228
  // src/engine/indexing_groups.ts
3075
3229
  function canonIndexKey(s) {
3076
3230
  return typeof s === "string" && s ? s.trim() : "";
@@ -3149,6 +3303,50 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3149
3303
  grp.resolving = false;
3150
3304
  grp.resolvingReason = void 0;
3151
3305
  }
3306
+ function runRecordDurationMs(rec) {
3307
+ if (!rec || rec.status !== "done") return void 0;
3308
+ var a = rec.started;
3309
+ var b = rec.finished;
3310
+ if (typeof a !== "number" || typeof b !== "number" || !isFinite(a) || !isFinite(b) || b < a) return void 0;
3311
+ return b - a;
3312
+ }
3313
+ var RUN_DURATION_CLOCK_SLACK_MS = 6e4;
3314
+ var RUN_DURATION_SERVER_SLACK_MS = 5e3;
3315
+ function runRecordGroupDurationMs(grp, rec) {
3316
+ if (rec.status !== "done" || !grp.members.length) return void 0;
3317
+ var fin = rec.finished;
3318
+ if (typeof fin !== "number" || !isFinite(fin)) return void 0;
3319
+ var firstTs = messageTimeMs(grp.members[0].msg);
3320
+ var lastTs = messageTimeMs(grp.members[grp.members.length - 1].msg);
3321
+ if (!firstTs || !lastTs) return void 0;
3322
+ if (fin < firstTs || fin < lastTs - RUN_DURATION_SERVER_SLACK_MS) return void 0;
3323
+ var firstPassTs = 0;
3324
+ for (var i = 0; i < grp.members.length; i++) {
3325
+ var m = grp.members[i].msg;
3326
+ if (m.role !== "user") continue;
3327
+ var ref = readFileRef(m);
3328
+ if (ref && !ref.continued) firstPassTs = messageTimeMs(m);
3329
+ break;
3330
+ }
3331
+ var st = typeof rec.started === "number" && isFinite(rec.started) ? rec.started : void 0;
3332
+ var start;
3333
+ if (st !== void 0 && st > firstTs + RUN_DURATION_CLOCK_SLACK_MS) return void 0;
3334
+ if (firstPassTs) {
3335
+ start = st !== void 0 && st >= firstPassTs - RUN_DURATION_CLOCK_SLACK_MS ? st : firstPassTs;
3336
+ } else {
3337
+ if (st === void 0) return void 0;
3338
+ start = st;
3339
+ }
3340
+ return fin >= start ? fin - start : void 0;
3341
+ }
3342
+ function indexGroupDurationLabel(group) {
3343
+ if (!group || group.status !== "done" || !group.finished || group.resolving || group.queued) return "";
3344
+ return formatIndexDuration(group.durationMs);
3345
+ }
3346
+ function indexGroupLinkedLabel(group) {
3347
+ if (!group || !group.linked || group.status !== "done") return "";
3348
+ return linkedRowLabel(group.linked.original, group.linked.ms);
3349
+ }
3152
3350
  function buildChatDisplayList(messages, opts) {
3153
3351
  var list = Array.isArray(messages) ? messages : [];
3154
3352
  var liveIndexKeys = opts && opts.liveIndexKeys || {};
@@ -3344,6 +3542,14 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3344
3542
  var vm = grp.members[vi];
3345
3543
  if (vm.msg._indexComplete) sawComplete = true;
3346
3544
  if (!isHiddenPass(vm.msg)) grp.visibleMembers.push(vm);
3545
+ if (vm.msg.role === "assistant" && !vm.msg.isError && !grp.linked) {
3546
+ var linkedReply = parseLinkedReply(vm.msg.content);
3547
+ if (linkedReply) grp.linked = linkedReply;
3548
+ }
3549
+ }
3550
+ if (grp.linked && grp.status !== "active" && grp.status !== "cancelled") {
3551
+ grp.status = "done";
3552
+ sawComplete = true;
3347
3553
  }
3348
3554
  grp.driver = !isPagedReadFile(grp.name, grp.mime) ? "single" : isImageVisionFile(grp.name, grp.mime) ? "worker" : windowedIndexing ? "worker" : "client";
3349
3555
  if (grp.status === "active") {
@@ -3355,7 +3561,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3355
3561
  } else if (grp.driver === "client") {
3356
3562
  grp.finished = sawComplete || grp.status === "error" || grp.passCount >= MAX_INDEXING_RESUME_PASSES;
3357
3563
  } else {
3358
- grp.finished = !newestRunOfKey[order[oi]] || !!doneKeys[grp.key] && !liveIndexKeys[grp.key] || liveIndexChecked && !liveIndexKeys[grp.key];
3564
+ grp.finished = !newestRunOfKey[order[oi]] || !!grp.linked || !!doneKeys[grp.key] && !liveIndexKeys[grp.key] || liveIndexChecked && !liveIndexKeys[grp.key];
3359
3565
  }
3360
3566
  if (grp.status !== "done") {
3361
3567
  grp.resolving = false;
@@ -3504,7 +3710,10 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3504
3710
  resolvingReason: reason,
3505
3711
  stub: true,
3506
3712
  queued: waitingStub || live && !!runningKeys && !runningKeys[sp] && !runningKeys[canonIndexKey(sp)] && !runningKeys[fname] ? true : void 0,
3507
- stubError: rec.error || (st === "error" && !rec.error ? "Indexing did not finish." : void 0)
3713
+ stubError: rec.error || (st === "error" && !rec.error ? "Indexing did not finish." : void 0),
3714
+ // The stub IS the record, so a 'done' record's span is this run's.
3715
+ durationMs: st === "done" ? runRecordDurationMs(rec) : void 0,
3716
+ linked: st === "done" && rec.linked && rec.alias_of ? { original: rec.alias_of, ms: typeof rec.link_ms === "number" ? rec.link_ms : void 0 } : void 0
3508
3717
  };
3509
3718
  stubList.push({ started: typeof rec.started === "number" ? rec.started : Infinity, group: sg });
3510
3719
  }
@@ -3523,6 +3732,10 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3523
3732
  tg.runKey = "run:" + (tg.path || tg.key) + "#" + trec.started;
3524
3733
  stubList.push({ started: trec.started, group: tg });
3525
3734
  overlayRunRecordVerdict(tg, trec, liveIndexKeys);
3735
+ tg.durationMs = runRecordGroupDurationMs(tg, trec);
3736
+ if (trec.linked && trec.alias_of && trec.status === "done") {
3737
+ tg.linked = { original: trec.alias_of, ms: tg.linked && tg.linked.ms !== void 0 ? tg.linked.ms : typeof trec.link_ms === "number" ? trec.link_ms : void 0 };
3738
+ }
3526
3739
  }
3527
3740
  }
3528
3741
  stubList.sort(function(a, b) {
@@ -3564,7 +3777,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3564
3777
  const tail = "/" + name;
3565
3778
  return uniqueId.length > SRC_PREFIX2.length + tail.length && uniqueId.slice(-tail.length) === tail;
3566
3779
  }
3567
- function listOf(res) {
3780
+ function listOf2(res) {
3568
3781
  if (!res) return [];
3569
3782
  if (Array.isArray(res)) return res;
3570
3783
  return Array.isArray(res.list) ? res.list : [];
@@ -3581,14 +3794,14 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3581
3794
  async function storedCopyIndexing(skapi, storagePath, service) {
3582
3795
  const doneId = "done::" + storagePath;
3583
3796
  try {
3584
- const done = listOf(await skapi.getUniqueId(Object.assign({ unique_id: doneId }, service), { fetchMore: false, limit: 1 }));
3797
+ const done = listOf2(await skapi.getUniqueId(Object.assign({ unique_id: doneId }, service), { fetchMore: false, limit: 1 }));
3585
3798
  if (done.some(function(it) {
3586
3799
  return (it && typeof it === "object" ? it.unique_id : it) === doneId;
3587
3800
  })) return "done";
3588
3801
  } catch {
3589
3802
  }
3590
3803
  try {
3591
- const run = listOf(await skapi.getRecords(Object.assign({ unique_id: "run::" + storagePath }, service)))[0];
3804
+ const run = listOf2(await skapi.getRecords(Object.assign({ unique_id: "run::" + storagePath }, service)))[0];
3592
3805
  const data = run && run.data && typeof run.data === "object" ? run.data : null;
3593
3806
  if (data && data.status === "working" && typeof data.started === "number" && Date.now() - data.started < RUN_RECORD_WORKING_STALE_MS) return "running";
3594
3807
  } catch {
@@ -3617,7 +3830,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3617
3830
  const size = file && typeof file.size === "number" ? file.size : NaN;
3618
3831
  if (!name || !(size >= 0) || !userId) return null;
3619
3832
  const service = opts && opts.service ? { service: opts.service } : {};
3620
- const found = listOf(await skapi.getUniqueId(
3833
+ const found = listOf2(await skapi.getUniqueId(
3621
3834
  Object.assign({ unique_id: name, condition: "<=" }, service),
3622
3835
  { fetchMore: false, limit: DUPLICATE_LOOKUP_LIMIT }
3623
3836
  ));
@@ -3630,7 +3843,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3630
3843
  for (const uniqueId of ids) {
3631
3844
  let record = null;
3632
3845
  try {
3633
- record = listOf(await skapi.getRecords(Object.assign({ unique_id: uniqueId }, service)))[0] || null;
3846
+ record = listOf2(await skapi.getRecords(Object.assign({ unique_id: uniqueId }, service)))[0] || null;
3634
3847
  } catch {
3635
3848
  continue;
3636
3849
  }
@@ -3958,6 +4171,22 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3958
4171
  var INLINE_LINK_GLYPH = "\u2197";
3959
4172
  var INLINE_LINK_UNAVAILABLE_GLYPH = "\u2715";
3960
4173
  var INLINE_LINK_UNAVAILABLE_SUFFIX = " (unavailable)";
4174
+ var FIT_LABEL_TAIL_CHARS = 8;
4175
+ function splitLabelForFit(name) {
4176
+ var chars = Array.from(String(name == null ? "" : name));
4177
+ var dot = -1;
4178
+ for (var i = chars.length - 1; i > 0; i--) {
4179
+ if (chars[i] === ".") {
4180
+ dot = i;
4181
+ break;
4182
+ }
4183
+ if (chars[i] === " " || chars[i] === "/" || chars.length - i > 10) break;
4184
+ }
4185
+ var extStart = dot > 0 && dot < chars.length - 1 ? dot : chars.length;
4186
+ var tailStart = Math.max(0, extStart - FIT_LABEL_TAIL_CHARS);
4187
+ if (tailStart < 4) return { stem: chars.join(""), tail: "" };
4188
+ return { stem: chars.slice(0, tailStart).join(""), tail: chars.slice(tailStart).join("") };
4189
+ }
3961
4190
  function renderInlineLinkHtml(link, opts) {
3962
4191
  var o = opts || {};
3963
4192
  var unavailable = !!o.unavailable;
@@ -3970,7 +4199,16 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3970
4199
  if (unavailable) cls.push("is-unavailable");
3971
4200
  if (preview) cls.push("is-image-preview");
3972
4201
  var glyphHtml = '<span class="bq-link-glyph" translate="no">' + (unavailable ? INLINE_LINK_UNAVAILABLE_GLYPH : INLINE_LINK_GLYPH) + "</span>";
3973
- var labelHtml = glyphHtml + escapeInlineHtml(link.label + (unavailable ? INLINE_LINK_UNAVAILABLE_SUFFIX : refreshing ? " (fetching...)" : ""));
4202
+ var stateSuffix = unavailable ? INLINE_LINK_UNAVAILABLE_SUFFIX : refreshing ? " (fetching...)" : "";
4203
+ var fit = !!o.fitLabel && !preview;
4204
+ if (fit) cls.push("bq-link-fit");
4205
+ var labelHtml;
4206
+ if (fit) {
4207
+ var split = splitLabelForFit(full);
4208
+ 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>" : "");
4209
+ } else {
4210
+ labelHtml = glyphHtml + escapeInlineHtml(link.label + stateSuffix);
4211
+ }
3974
4212
  var attrs = ['class="' + cls.join(" ") + '"'];
3975
4213
  if (unavailable) attrs.push('aria-disabled="true"', 'data-bq-unavailable="1"');
3976
4214
  else attrs.push('href="' + escapeInlineHtml(link.href) + '"', 'target="_blank"', 'rel="noopener noreferrer"');
@@ -5674,6 +5912,10 @@ Index the REMAINING windows - one record per row/item, looking at any page image
5674
5912
  var note = retrievalNoteOfAnswer(msg);
5675
5913
  return !!note && !answerUsedNoDataTool(note) && !msg.isCancelled;
5676
5914
  }
5915
+ var UPLOAD_CANCELLED_MESSAGE = "Upload cancelled";
5916
+ function isUploadCancelledError(err) {
5917
+ return !!err && (err.code === "CANCELLED" || err.message === UPLOAD_CANCELLED_MESSAGE);
5918
+ }
5677
5919
  var _ChatSession = class _ChatSession {
5678
5920
  constructor(host) {
5679
5921
  // --- live streaming ----------------------------------------------------
@@ -6095,6 +6337,43 @@ Index the REMAINING windows - one record per row/item, looking at any page image
6095
6337
  return queued;
6096
6338
  });
6097
6339
  }
6340
+ /**
6341
+ * ONE SHARED INDEX FOR IDENTICAL FILES: the linked copies that lose their original when
6342
+ * `removed` files (or every file under `folders`) go away, per original, oldest first
6343
+ * (identical.ts copiesToPromote). Read through host.findLinkedCopies, fresh, and it has
6344
+ * to be read BEFORE the delete or reset: those remove nothing from the copies' markers,
6345
+ * but a later sweep could no longer tell whose copies they were once a new original
6346
+ * exists. Never rejects; [] without the hook or on any failure.
6347
+ */
6348
+ collectLinkedCopies(removed, folders) {
6349
+ if (typeof this.host.findLinkedCopies !== "function") return Promise.resolve([]);
6350
+ var id = this.host.getIdentity();
6351
+ var actor = { userId: id && !id.anonymous ? id.userId : null, isProjectOwner: !!(id && !id.anonymous && id.owner && id.userId === id.owner) };
6352
+ return Promise.resolve(this.host.findLinkedCopies()).then(function(map) {
6353
+ return map ? copiesToPromote(map, removed || [], folders, actor) : [];
6354
+ }).catch(function() {
6355
+ return [];
6356
+ });
6357
+ }
6358
+ /**
6359
+ * Send the copies of a removed or overwritten original again (owner decision
6360
+ * 2026-11-26): each list's oldest copy first, so its first pass claims the content and
6361
+ * is indexed for real (one AI run), then the others, which link to it with no AI call.
6362
+ * The share flag rides on every first pass while the project's switch is on (requests.ts
6363
+ * notifyAgentSaveAttachment). Through reindexStoredFiles, so each copy keeps its access
6364
+ * group and shows as a "Reindexing" row. Resolves to the number of files queued.
6365
+ */
6366
+ promoteLinkedCopies(plan) {
6367
+ var list = [];
6368
+ (plan || []).forEach(function(g) {
6369
+ (g && g.copies || []).forEach(function(c) {
6370
+ if (c) list.push({ storagePath: c });
6371
+ });
6372
+ });
6373
+ if (!list.length) return Promise.resolve(0);
6374
+ console.log("[chat-engine] identical files: sending " + list.length + " linked cop" + (list.length === 1 ? "y" : "ies") + " again, their original is gone:", plan);
6375
+ return this.reindexStoredFiles(list);
6376
+ }
6098
6377
  /**
6099
6378
  * The same question, asked of the SERVER when this page cannot answer it.
6100
6379
  *
@@ -12839,6 +13118,29 @@ Index the REMAINING windows - one record per row/item, looking at any page image
12839
13118
  });
12840
13119
  }
12841
13120
  // --- attachment upload orchestration ---------------------------------
13121
+ /**
13122
+ * The user cancelled this chip's upload (the widget's per-chip x or "Cancel all
13123
+ * uploads"). Stops the bytes now when they are moving (the host's abort), and
13124
+ * leaves a flag every later step of uploadSingleAttachment checks, so a cancel
13125
+ * that lands between steps (the get-signed-url round trip before the bytes, or
13126
+ * the src:: record and the indexing request after them) still stops the file
13127
+ * from being indexed and from being attached to the chat turn. A member whose
13128
+ * indexing request has already gone out is past cancelling: it shows as an
13129
+ * indexing row with its own Stop. Returns false for a chip that is not being
13130
+ * uploaded by this session any more.
13131
+ */
13132
+ cancelAttachmentUpload(att) {
13133
+ if (!att || att._cancelled) return false;
13134
+ if (att.status !== "uploading" && !att._batchId) return false;
13135
+ att._cancelled = true;
13136
+ if (typeof att._abort === "function") {
13137
+ try {
13138
+ att._abort();
13139
+ } catch (e) {
13140
+ }
13141
+ }
13142
+ return true;
13143
+ }
12842
13144
  // Upload one attachment (a file = 1 member, a folder = N) to db storage and
12843
13145
  // queue indexing per member. The bytes I/O + chip rendering go through host
12844
13146
  // hooks; the overwrite/reindex flow, status lifecycle, and indexing live here.
@@ -12861,6 +13163,18 @@ Index the REMAINING windows - one record per row/item, looking at any page image
12861
13163
  var anyIndexFailed = false;
12862
13164
  var reusedCount = 0;
12863
13165
  att.reused = false;
13166
+ att._storedCount = 0;
13167
+ att._indexQueuedCount = 0;
13168
+ att._indexQueued = false;
13169
+ att._landedNew = [];
13170
+ var cancelError = function() {
13171
+ var e = new Error(UPLOAD_CANCELLED_MESSAGE);
13172
+ e.code = "CANCELLED";
13173
+ return e;
13174
+ };
13175
+ var checkCancel = function() {
13176
+ if (att._cancelled) throw cancelError();
13177
+ };
12864
13178
  delete att.duplicates;
12865
13179
  var chain = Promise.resolve();
12866
13180
  var findDuplicate = function(member) {
@@ -12877,25 +13191,54 @@ Index the REMAINING windows - one record per row/item, looking at any page image
12877
13191
  };
12878
13192
  members.forEach(function(member, idx) {
12879
13193
  chain = chain.then(function() {
13194
+ checkCancel();
12880
13195
  var hadExists = false;
12881
13196
  var skipped = false;
13197
+ var promotion = null;
12882
13198
  var duplicateOf = null;
12883
13199
  var existedBefore = false;
13200
+ var madeRecord = false;
13201
+ var sentAll = false;
12884
13202
  var onProg = function(p) {
13203
+ if (p && p.total && p.loaded >= p.total) sentAll = true;
12885
13204
  if (p && p.total) {
12886
13205
  att.progress = Math.floor((idx + p.loaded / p.total) / total * 100);
12887
13206
  self.host.renderAttachmentChips();
12888
13207
  }
12889
13208
  };
12890
13209
  var doMemberUpload = function(checkExistence) {
13210
+ checkCancel();
13211
+ sentAll = false;
12891
13212
  return self.host.uploadFile({
12892
13213
  file: member.file,
12893
13214
  storagePath: member.storagePath,
12894
13215
  checkExistence,
12895
13216
  onProgress: onProg,
13217
+ // The host hands its abort over just before the bytes start. A
13218
+ // cancel made during the get-signed-url round trip had nothing to
13219
+ // abort yet, so it is applied here, before anything is sent: a
13220
+ // storage POST that never completes leaves no object behind.
12896
13221
  setAbort: function(abort) {
12897
13222
  att._abort = abort;
13223
+ if (att._cancelled) {
13224
+ try {
13225
+ abort();
13226
+ } catch (e) {
13227
+ }
13228
+ }
13229
+ }
13230
+ }).then(function(r) {
13231
+ att._abort = null;
13232
+ att._storedCount = (att._storedCount || 0) + 1;
13233
+ if (checkExistence) att._landedNew.push(member.storagePath);
13234
+ return r;
13235
+ }, function(err) {
13236
+ att._abort = null;
13237
+ if (att._cancelled) {
13238
+ if (checkExistence && sentAll) att._landedNew.push(member.storagePath);
13239
+ throw cancelError();
12898
13240
  }
13241
+ throw err;
12899
13242
  });
12900
13243
  };
12901
13244
  if (isIndexRetry) {
@@ -12918,6 +13261,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
12918
13261
  return self.host.promptOverwrite(member.file.name).then(function(choice) {
12919
13262
  if (choice === "overwrite") {
12920
13263
  existedBefore = true;
13264
+ promotion = self.collectLinkedCopies([member.storagePath]);
12921
13265
  markImagePreviewStale(self.host.getIdentity().projectId || "default", member.storagePath);
12922
13266
  return doMemberUpload(false);
12923
13267
  }
@@ -12929,12 +13273,14 @@ Index the REMAINING windows - one record per row/item, looking at any page image
12929
13273
  existedBefore = true;
12930
13274
  });
12931
13275
  }).then(function() {
13276
+ checkCancel();
12932
13277
  if (skipped) return;
12933
13278
  return Promise.resolve(self.host.getTemporaryUrl(duplicateOf || member.storagePath)).catch(function(err) {
12934
13279
  var ecode = err && (err.code || err.body && err.body.code);
12935
13280
  var emsg = String(err && (err.message || err.body && err.body.message) || err || "");
12936
13281
  var refused = /no access to this file/i.test(emsg) || ecode === "INVALID_REQUEST" && /access/i.test(emsg);
12937
13282
  if (duplicateOf || !refused || typeof self.host.ensureFileIndexRecord !== "function") throw err;
13283
+ madeRecord = !existedBefore;
12938
13284
  return Promise.resolve(self.host.ensureFileIndexRecord(member.storagePath, {
12939
13285
  name: member.file.name,
12940
13286
  mime: member.file.type || self.host.getMimeType(member.file.name),
@@ -12944,6 +13290,13 @@ Index the REMAINING windows - one record per row/item, looking at any page image
12944
13290
  });
12945
13291
  });
12946
13292
  }).then(function(url) {
13293
+ if (att._cancelled) {
13294
+ var dropEarly = madeRecord && typeof self.host.deleteExistingFileRecord === "function" ? Promise.resolve(self.host.deleteExistingFileRecord(member.storagePath)).catch(function() {
13295
+ }) : Promise.resolve();
13296
+ return dropEarly.then(function() {
13297
+ throw cancelError();
13298
+ });
13299
+ }
12947
13300
  if (skipped) return;
12948
13301
  if (duplicateOf) {
12949
13302
  urls.push({ name: member.relPath, url, storagePath: duplicateOf });
@@ -12972,13 +13325,14 @@ Index the REMAINING windows - one record per row/item, looking at any page image
12972
13325
  var mime = member.file.type || self.host.getMimeType(member.file.name);
12973
13326
  var alreadyIndexing = false;
12974
13327
  var existingGroup = null;
13328
+ var clearedOld = false;
12975
13329
  var preIndex = self.claimIndexRun(member.storagePath).then(function(claimed) {
12976
13330
  alreadyIndexing = !claimed;
12977
13331
  if (alreadyIndexing) {
12978
13332
  console.log("[chat-engine] skipping a duplicate index request for", member.storagePath);
12979
13333
  return;
12980
13334
  }
12981
- if (!existedBefore) return;
13335
+ if (!existedBefore || att._cancelled) return;
12982
13336
  var readGroup = typeof self.host.readFileAccessGroup === "function" ? Promise.resolve(self.host.readFileAccessGroup(member.storagePath)).then(function(g) {
12983
13337
  existingGroup = g || null;
12984
13338
  }, function(err) {
@@ -12986,7 +13340,9 @@ Index the REMAINING windows - one record per row/item, looking at any page image
12986
13340
  throw err;
12987
13341
  }) : Promise.resolve();
12988
13342
  return readGroup.then(function() {
13343
+ if (att._cancelled) return;
12989
13344
  if (typeof self.host.deleteExistingFileRecord === "function") {
13345
+ clearedOld = true;
12990
13346
  return Promise.resolve(self.host.deleteExistingFileRecord(member.storagePath)).catch(function() {
12991
13347
  });
12992
13348
  }
@@ -12994,7 +13350,9 @@ Index the REMAINING windows - one record per row/item, looking at any page image
12994
13350
  });
12995
13351
  preIndex = preIndex.then(function() {
12996
13352
  if (alreadyIndexing) return;
13353
+ if (att._cancelled && !clearedOld) return;
12997
13354
  if (typeof self.host.ensureFileIndexRecord !== "function") return;
13355
+ if (!existedBefore) madeRecord = true;
12998
13356
  return Promise.resolve(self.host.ensureFileIndexRecord(member.storagePath, {
12999
13357
  name: member.file.name,
13000
13358
  mime: mime || void 0,
@@ -13015,10 +13373,31 @@ Index the REMAINING windows - one record per row/item, looking at any page image
13015
13373
  }).catch(function() {
13016
13374
  });
13017
13375
  });
13376
+ var abandonIfCancelled = function() {
13377
+ if (!att._cancelled) return;
13378
+ if (!alreadyIndexing) self.releaseIndexRun(member.storagePath);
13379
+ var drop = !existedBefore && !alreadyIndexing && madeRecord && typeof self.host.deleteExistingFileRecord === "function" ? Promise.resolve(self.host.deleteExistingFileRecord(member.storagePath)).catch(function() {
13380
+ }) : Promise.resolve();
13381
+ return drop.then(function() {
13382
+ throw cancelError();
13383
+ });
13384
+ };
13018
13385
  return preIndex.then(function() {
13386
+ return abandonIfCancelled();
13387
+ }).then(function() {
13019
13388
  return parseAttachmentContent(member.file, member.file.name, mime || void 0);
13389
+ }).then(function(parsedContent) {
13390
+ return Promise.resolve(abandonIfCancelled()).then(function() {
13391
+ return parsedContent;
13392
+ });
13020
13393
  }).then(function(parsedContent) {
13021
13394
  if (alreadyIndexing) return;
13395
+ att._indexQueuedCount = (att._indexQueuedCount || 0) + 1;
13396
+ if (att.kind !== "folder") att._indexQueued = true;
13397
+ att._landedNew = (att._landedNew || []).filter(function(p) {
13398
+ return p !== member.storagePath;
13399
+ });
13400
+ self.host.renderAttachmentChips();
13022
13401
  return self.trackIndexDispatch(notifyAgentSaveAttachment({
13023
13402
  platform: id.platform,
13024
13403
  model: id.model,
@@ -13059,6 +13438,14 @@ Index the REMAINING windows - one record per row/item, looking at any page image
13059
13438
  });
13060
13439
  self.noteBgQueueChanged();
13061
13440
  self.drainBgTaskQueue();
13441
+ if (promotion) {
13442
+ var plan = promotion;
13443
+ promotion = null;
13444
+ plan.then(function(pl) {
13445
+ return self.promoteLinkedCopies(pl);
13446
+ }).catch(function() {
13447
+ });
13448
+ }
13062
13449
  }
13063
13450
  }, function(e) {
13064
13451
  console.error("[chat-engine] indexing request failed", e);
@@ -13074,6 +13461,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
13074
13461
  });
13075
13462
  });
13076
13463
  return chain.then(function() {
13464
+ checkCancel();
13077
13465
  att._abort = null;
13078
13466
  att.progress = 100;
13079
13467
  if (att.kind === "folder") att.uploadedUrls = urls.map(function(u) {
@@ -13134,12 +13522,26 @@ Index the REMAINING windows - one record per row/item, looking at any page image
13134
13522
  return a.id === att.id;
13135
13523
  });
13136
13524
  var aborted = err && (err.message === "Aborted" || err === "Aborted");
13525
+ if (att._cancelled || isUploadCancelledError(err)) {
13526
+ att.status = "cancelled";
13527
+ att._abort = null;
13528
+ self.host.renderAttachmentChips();
13529
+ if (typeof att._onCancelSettled === "function") {
13530
+ try {
13531
+ att._onCancelSettled((att._landedNew || []).slice());
13532
+ } catch (e) {
13533
+ }
13534
+ }
13535
+ return;
13536
+ }
13137
13537
  if (removed || aborted) return;
13138
13538
  att.status = "error";
13139
13539
  att.errorMessage = "File upload has failed";
13140
13540
  att.errorCode = err && (err.code || err.body && err.body.code) || "";
13141
13541
  att.errorDetail = err && (err.message || err.body && err.body.message) || (typeof err === "string" ? err : "");
13142
13542
  self.host.renderAttachmentChips();
13543
+ }).then(function() {
13544
+ att._settledBatch = att._batchId || true;
13143
13545
  });
13144
13546
  });
13145
13547
  });
@@ -13169,8 +13571,8 @@ Index the REMAINING windows - one record per row/item, looking at any page image
13169
13571
  // src/index.js
13170
13572
  (function() {
13171
13573
  var MCP_PROD = "https://mcp.skapi.com";
13172
- var MCP_DEV = "https://mcp-dev.broadwayinc.computer";
13173
- var BQ_VERSION = "1.21.4" ;
13574
+ var MCP_DEV = "https://mcp.broadwayinc.computer";
13575
+ var BQ_VERSION = "1.21.12" ;
13174
13576
  var ATTACHMENT_URL_EXPIRES_SECONDS = 600;
13175
13577
  var GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";
13176
13578
  var GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
@@ -14961,6 +15363,8 @@ Index the REMAINING windows - one record per row/item, looking at any page image
14961
15363
  attachmentWarning: "",
14962
15364
  attachmentCapNotice: "",
14963
15365
  // informational "N files not added" when an add hit MAX_ATTACHMENT_FILE_COUNT
15366
+ attachmentCancelNotice: "",
15367
+ // "Upload cancelled: <file>." after the user cancelled uploads
14964
15368
  attachmentsRow: null,
14965
15369
  // .bq-attachments DOM node
14966
15370
  attachBtnEl: null,
@@ -15104,6 +15508,12 @@ Index the REMAINING windows - one record per row/item, looking at any page image
15104
15508
  if (!uid) return Promise.resolve(null);
15105
15509
  return findDuplicateUpload(S.skapi, file, uid, { service: S.projectId });
15106
15510
  },
15511
+ // Every linked copy of the project (one shared index for identical files): an
15512
+ // Overwrite of an original sends its copies again (engine collectLinkedCopies).
15513
+ findLinkedCopies: function() {
15514
+ if (!S.skapi || !S.projectId || isAnonymousSession()) return Promise.resolve(null);
15515
+ return listLinkedCopies(S.skapi, S.projectId);
15516
+ },
15107
15517
  storagePathFor: function(relPath) {
15108
15518
  return attachmentStoragePath(relPath);
15109
15519
  },
@@ -15316,6 +15726,10 @@ Index the REMAINING windows - one record per row/item, looking at any page image
15316
15726
  updateComposerControls();
15317
15727
  return;
15318
15728
  }
15729
+ if (CS.attachmentCancelNotice) {
15730
+ CS.attachmentCancelNotice = "";
15731
+ renderAttachmentChips();
15732
+ }
15319
15733
  if (inputEl) {
15320
15734
  inputEl.value = "";
15321
15735
  autoGrowInput(inputEl);
@@ -15424,11 +15838,12 @@ Index the REMAINING windows - one record per row/item, looking at any page image
15424
15838
  function fileToAnchorHtml(filename, href) {
15425
15839
  return '<a class="bq-file-download" href="' + escapeHtml(href) + '" download="' + escapeHtml(filename) + '" target="_blank" rel="noopener noreferrer"><span class="bq-link-glyph" translate="no">\u2197</span>' + escapeHtml(filename) + "</a>";
15426
15840
  }
15427
- function linkToAnchorHtml(link, allowImagePreview) {
15841
+ function linkToAnchorHtml(link, allowImagePreview, fitLabel) {
15428
15842
  return renderInlineLinkHtml(link, {
15429
15843
  refreshing: !!refreshingLinkMap[link.expiredHref || link.href],
15430
15844
  allowImagePreview,
15431
- unavailable: isLinkUnavailable(link, unavailableLinkMap)
15845
+ unavailable: isLinkUnavailable(link, unavailableLinkMap),
15846
+ fitLabel: !!fitLabel
15432
15847
  });
15433
15848
  }
15434
15849
  function citationChipsHtml(note) {
@@ -15468,6 +15883,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
15468
15883
  }
15469
15884
  function parseMsgPartsHtml(content, opts) {
15470
15885
  var noPreviews = !!(opts && opts.imagePreviews === false);
15886
+ var fitLinks = !!(opts && opts.fitLinkLabels);
15471
15887
  var placeholderHtml = [];
15472
15888
  var PH = function(idx) {
15473
15889
  return "\uE000BQ" + idx + "\uE001";
@@ -15503,7 +15919,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
15503
15919
  var built = buildLinkPartFromGroups(full, args[0], args[1], args[2], args[3], args[4], args[5]);
15504
15920
  if (!built) return full;
15505
15921
  var allow = previewsLeft > 0;
15506
- var html2 = linkToAnchorHtml(built.part, allow);
15922
+ var html2 = linkToAnchorHtml(built.part, allow, fitLinks);
15507
15923
  if (allow && built.part.image) previewsLeft--;
15508
15924
  return pushPlaceholder(html2) + (built.tail || "");
15509
15925
  });
@@ -15622,14 +16038,15 @@ Index the REMAINING windows - one record per row/item, looking at any page image
15622
16038
  });
15623
16039
  }
15624
16040
  if (xhr.upload && typeof onProgress === "function") xhr.upload.onprogress = onProgress;
16041
+ touch();
16042
+ xhr.send(form);
15625
16043
  if (typeof setAbort === "function") setAbort(function() {
16044
+ clearIdle();
15626
16045
  try {
15627
16046
  xhr.abort();
15628
16047
  } catch (e) {
15629
16048
  }
15630
16049
  });
15631
- touch();
15632
- xhr.send(form);
15633
16050
  });
15634
16051
  }
15635
16052
  function uploadFileToDb(file, storagePath, onProgress, setAbort, checkExistence) {
@@ -16014,6 +16431,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
16014
16431
  remaining -= count;
16015
16432
  changed = true;
16016
16433
  });
16434
+ CS.attachmentCancelNotice = "";
16017
16435
  CS.attachmentCapNotice = dropped > 0 ? "You can attach up to " + MAX_ATTACHMENT_FILE_COUNT + " files per message. " + dropped + " file" + (dropped === 1 ? " was" : "s were") + " not added." : "";
16018
16436
  if (changed) {
16019
16437
  recomputeAttachmentWarning();
@@ -16111,7 +16529,17 @@ Index the REMAINING windows - one record per row/item, looking at any page image
16111
16529
  ids.forEach(function(id) {
16112
16530
  idset[id] = true;
16113
16531
  });
16532
+ var inFlight = inFlightUploadAttachments().filter(function(a) {
16533
+ return idset[a.id];
16534
+ });
16535
+ if (inFlight.length) {
16536
+ cancelAttachmentUploads(inFlight);
16537
+ inFlight.forEach(function(a) {
16538
+ delete idset[a.id];
16539
+ });
16540
+ }
16114
16541
  CS.attachments = CS.attachments.filter(function(a) {
16542
+ if (idset[a.id] && a._batchId && a.status === "uploading") return true;
16115
16543
  if (idset[a.id]) {
16116
16544
  if (a._abort) {
16117
16545
  try {
@@ -16136,6 +16564,10 @@ Index the REMAINING windows - one record per row/item, looking at any page image
16136
16564
  });
16137
16565
  if (i === -1) return;
16138
16566
  var att = CS.attachments[i];
16567
+ if (isInFlightUpload(att)) {
16568
+ cancelAttachmentUploads([att]);
16569
+ return;
16570
+ }
16139
16571
  if (att._abort) {
16140
16572
  try {
16141
16573
  att._abort();
@@ -16149,6 +16581,144 @@ Index the REMAINING windows - one record per row/item, looking at any page image
16149
16581
  updateComposerControls();
16150
16582
  scheduleAttachmentOverflowRecompute();
16151
16583
  }
16584
+ function isInFlightUpload(a) {
16585
+ if (!a || a._cancelled) return false;
16586
+ if (a.kind !== "folder" && a._indexQueued) return false;
16587
+ if (a.status === "uploading") return true;
16588
+ if (a._settledBatch && a._settledBatch === a._batchId) return false;
16589
+ return !!a._batchId && a.status !== "done" && a.status !== "cancelled";
16590
+ }
16591
+ function inFlightUploadAttachments() {
16592
+ return CS.attachments.filter(isInFlightUpload);
16593
+ }
16594
+ function cancelAttachmentUploads(atts) {
16595
+ var cancelled = (atts || []).filter(isInFlightUpload);
16596
+ if (!cancelled.length) return;
16597
+ var ids = {};
16598
+ var notice = { list: cancelled, text: "" };
16599
+ cancelled.forEach(function(a) {
16600
+ a._onCancelSettled = function(landed) {
16601
+ discardCancelledUploads(a, landed, notice);
16602
+ };
16603
+ if (!session.cancelAttachmentUpload(a)) a._cancelled = true;
16604
+ ids[a.id] = true;
16605
+ });
16606
+ CS.attachments = CS.attachments.filter(function(a) {
16607
+ return !ids[a.id];
16608
+ });
16609
+ notice.text = uploadCancelNotice(cancelled);
16610
+ CS.attachmentCancelNotice = notice.text;
16611
+ CS.attachmentCapNotice = "";
16612
+ CS.visibleAttachmentCount = Infinity;
16613
+ recomputeAttachmentWarning();
16614
+ renderAttachmentChips();
16615
+ updateComposerControls();
16616
+ scheduleAttachmentOverflowRecompute();
16617
+ }
16618
+ function uploadCancelNotice(list) {
16619
+ var names = list.map(function(a) {
16620
+ return a.kind === "folder" ? a.name + "/" : a.name;
16621
+ });
16622
+ var text = list.length === 1 ? "Upload cancelled: " + names[0] + "." : list.length + " uploads cancelled: " + names.slice(0, 3).join(", ") + (names.length > 3 ? " and " + (names.length - 3) + " more." : ".");
16623
+ var queued = 0, checking = 0, removed = 0, kept = 0, reasons = [];
16624
+ list.forEach(function(a) {
16625
+ var q = a._indexQueuedCount || 0;
16626
+ queued += q;
16627
+ var d = a._discard;
16628
+ if (d && d.state === "done") {
16629
+ removed += d.removed;
16630
+ kept += d.kept;
16631
+ if (d.reason && reasons.indexOf(d.reason) === -1) reasons.push(d.reason);
16632
+ return;
16633
+ }
16634
+ if (d && d.state === "pending") {
16635
+ checking += d.count;
16636
+ return;
16637
+ }
16638
+ var landed = Math.max(0, (a._storedCount || 0) - q);
16639
+ if (!landed && a.status === "uploading" && (a.progress || 0) >= 100) landed = 1;
16640
+ checking += landed;
16641
+ });
16642
+ var one = list.length === 1 && !queued;
16643
+ if (queued) {
16644
+ text += " " + queued + (queued === 1 ? " file had" : " files had") + " already gone to indexing; stop " + (queued === 1 ? "it from its row" : "them from their rows") + " in the chat.";
16645
+ }
16646
+ if (checking) {
16647
+ text += " " + (one && checking === 1 ? "Its" : checking === 1 ? "One file's" : checking + " files'") + " bytes had already been sent; removing " + (checking === 1 ? "it" : "them") + " from storage.";
16648
+ }
16649
+ if (removed) {
16650
+ text += " " + (one && removed === 1 && !kept ? "Its bytes had already reached storage and were removed again." : removed === 1 ? "One file had already reached storage and was removed again." : removed + " files had already reached storage and were removed again.");
16651
+ }
16652
+ if (kept) {
16653
+ text += " " + (one && kept === 1 && !removed ? "It" : kept === 1 ? "One file" : kept + " files") + " had already reached storage and could not be removed, but " + (kept === 1 ? "it was" : "they were") + " not indexed or added to the chat." + (reasons.length ? " " + reasons.join(" ") : "");
16654
+ }
16655
+ return text;
16656
+ }
16657
+ function discardCancelledUploads(att, landed, notice) {
16658
+ var paths = (landed || []).filter(function(p, i, all) {
16659
+ return p && all.indexOf(p) === i;
16660
+ });
16661
+ if (!paths.length) {
16662
+ att._discard = { state: "done", removed: 0, kept: 0, reason: "" };
16663
+ refreshCancelNotice(notice);
16664
+ return;
16665
+ }
16666
+ att._discard = { state: "pending", count: paths.length };
16667
+ refreshCancelNotice(notice);
16668
+ var removed = 0, kept = 0, reason = "";
16669
+ paths.reduce(function(p, storagePath) {
16670
+ return p.then(function() {
16671
+ return discardUploadedFile(storagePath).then(function(out) {
16672
+ if (out.removed) removed += 1;
16673
+ else if (!out.gone) {
16674
+ kept += 1;
16675
+ if (!reason && out.message) reason = out.message.replace(/\s*(It|The file) was not removed\.$/, "");
16676
+ }
16677
+ });
16678
+ });
16679
+ }, Promise.resolve()).then(function() {
16680
+ att._discard = { state: "done", removed, kept, reason };
16681
+ refreshCancelNotice(notice);
16682
+ });
16683
+ }
16684
+ function discardUploadedFile(storagePath) {
16685
+ if (!S.skapi || typeof S.skapi.forwardRequest !== "function" || !S.projectId) {
16686
+ return Promise.resolve({ removed: false, message: "This page cannot reach the BunnyQuery server." });
16687
+ }
16688
+ return Promise.resolve(S.skapi.forwardRequest(null, {
16689
+ service: S.projectId,
16690
+ owner: S.owner || void 0,
16691
+ url: mcpBaseUrl() + "/internal/upload-discard",
16692
+ method: "POST",
16693
+ // "$ACCESS_TOKEN" is filled in by skapi with this user's own token: the
16694
+ // server acts for the user it names and nobody else.
16695
+ headers: { "content-type": "application/json", Authorization: "Bearer $ACCESS_TOKEN" },
16696
+ data: { project_id: S.projectId, path: storagePath }
16697
+ })).then(function(res) {
16698
+ var body = res;
16699
+ if (typeof body === "string") {
16700
+ try {
16701
+ body = JSON.parse(body);
16702
+ } catch (e) {
16703
+ body = { message: body };
16704
+ }
16705
+ }
16706
+ if (!body || typeof body !== "object" || typeof body.removed !== "boolean") {
16707
+ return { removed: false, message: "The server gave no answer about the file." };
16708
+ }
16709
+ return { removed: body.removed, gone: body.gone === true, message: typeof body.message === "string" ? body.message : "" };
16710
+ }, function(err) {
16711
+ var msg = err && (err.message || err.body && err.body.message) || (typeof err === "string" ? err : "");
16712
+ return { removed: false, message: msg ? "The server answered: " + String(msg).slice(0, 200).replace(/\.?$/, ".") : "The server could not be reached." };
16713
+ });
16714
+ }
16715
+ function refreshCancelNotice(notice) {
16716
+ if (!notice || CS.attachmentCancelNotice !== notice.text) return;
16717
+ notice.text = uploadCancelNotice(notice.list);
16718
+ CS.attachmentCancelNotice = notice.text;
16719
+ renderAttachmentChips();
16720
+ scheduleAttachmentOverflowRecompute();
16721
+ }
16152
16722
  function clearAttachments() {
16153
16723
  CS.attachments = CS.attachments.filter(function(a) {
16154
16724
  return !!a._batchId;
@@ -16165,6 +16735,8 @@ Index the REMAINING windows - one record per row/item, looking at any page image
16165
16735
  if (a.status !== "error" && a.status !== "indexError") return false;
16166
16736
  a._abort = null;
16167
16737
  delete a._batchId;
16738
+ delete a._indexQueued;
16739
+ delete a._settledBatch;
16168
16740
  return true;
16169
16741
  });
16170
16742
  CS.attachmentCapNotice = "";
@@ -16195,11 +16767,32 @@ Index the REMAINING windows - one record per row/item, looking at any page image
16195
16767
  var row = CS.attachmentsRow;
16196
16768
  if (!row) return;
16197
16769
  row.innerHTML = "";
16198
- if (!CS.attachments.length && !CS.attachmentWarning && !CS.attachmentCapNotice) {
16770
+ if (!CS.attachments.length && !CS.attachmentWarning && !CS.attachmentCapNotice && !CS.attachmentCancelNotice) {
16199
16771
  row.style.display = "none";
16200
16772
  return;
16201
16773
  }
16202
16774
  row.style.display = "";
16775
+ if (CS.attachmentCancelNotice) {
16776
+ var cancelNoticeClose = h("button", {
16777
+ class: "bq-attachment-remove",
16778
+ type: "button",
16779
+ title: "Dismiss",
16780
+ "aria-label": "Dismiss",
16781
+ text: "\xD7"
16782
+ });
16783
+ cancelNoticeClose.addEventListener("click", function(e) {
16784
+ e.stopPropagation();
16785
+ CS.attachmentCancelNotice = "";
16786
+ renderAttachmentChips();
16787
+ scheduleAttachmentOverflowRecompute();
16788
+ });
16789
+ row.appendChild(h(
16790
+ "div",
16791
+ { class: "bq-attachment-warning is-notice", role: "status" },
16792
+ h("span", { text: CS.attachmentCancelNotice }),
16793
+ cancelNoticeClose
16794
+ ));
16795
+ }
16203
16796
  if (CS.attachmentCapNotice) {
16204
16797
  row.appendChild(h("div", { class: "bq-attachment-warning" }, h("span", { text: CS.attachmentCapNotice })));
16205
16798
  }
@@ -16234,7 +16827,20 @@ Index the REMAINING windows - one record per row/item, looking at any page image
16234
16827
  var meta = att.status === "error" ? "(Failed)" : att.status === "indexError" ? "(Error)" : preparing ? "Preparing" : finalizing ? "Finalizing" : att.status === "uploading" ? att.progress + "%" : isFolder ? "(" + (att.files ? att.files.length : 0) + ")" : att.reused ? "already uploaded" : formatBytes(att.file ? att.file.size : att.size);
16235
16828
  chip.appendChild(h("span", { class: "bq-attachment-meta", text: meta }));
16236
16829
  if (clickable) chip.appendChild(h("span", { class: "bq-attachment-arrow", text: "\u2197" }));
16237
- if (att.status !== "uploading" && att.status !== "done") {
16830
+ if (isInFlightUpload(att)) {
16831
+ var cancelBtn = h("button", {
16832
+ class: "bq-attachment-remove",
16833
+ type: "button",
16834
+ title: "Cancel upload",
16835
+ "aria-label": "Cancel upload of " + att.name,
16836
+ text: "\xD7"
16837
+ });
16838
+ cancelBtn.addEventListener("click", function(e) {
16839
+ e.stopPropagation();
16840
+ cancelAttachmentUploads([att]);
16841
+ });
16842
+ chip.appendChild(cancelBtn);
16843
+ } else if (att.status !== "uploading" && att.status !== "done") {
16238
16844
  var rm = h("button", { class: "bq-attachment-remove", type: "button", title: "Remove", text: "\xD7" });
16239
16845
  rm.addEventListener("click", function(e) {
16240
16846
  e.stopPropagation();
@@ -16280,6 +16886,19 @@ Index the REMAINING windows - one record per row/item, looking at any page image
16280
16886
  });
16281
16887
  row.appendChild(removeAll);
16282
16888
  }
16889
+ var inFlight = inFlightUploadAttachments();
16890
+ if (inFlight.length >= 2) {
16891
+ var cancelAll = h("button", {
16892
+ class: "bq-attachment-remove-all",
16893
+ type: "button",
16894
+ title: "Cancel all " + inFlight.length + " uploads"
16895
+ }, "Cancel all uploads \xD7");
16896
+ cancelAll.addEventListener("click", function(e) {
16897
+ e.stopPropagation();
16898
+ cancelAttachmentUploads(inFlightUploadAttachments());
16899
+ });
16900
+ row.appendChild(cancelAll);
16901
+ }
16283
16902
  }
16284
16903
  function uploadsFrozenForUser() {
16285
16904
  if (!S.user) return true;
@@ -16547,7 +17166,9 @@ Index the REMAINING windows - one record per row/item, looking at any page image
16547
17166
  anchor.click();
16548
17167
  return;
16549
17168
  }
16550
- var busy = document.createTextNode(" (fetching...)");
17169
+ var busy = document.createElement("span");
17170
+ busy.className = "bq-link-tail";
17171
+ busy.textContent = " (fetching...)";
16551
17172
  anchor.classList.add("is-refreshing");
16552
17173
  anchor.appendChild(busy);
16553
17174
  var unbusy = function() {
@@ -16856,11 +17477,13 @@ Index the REMAINING windows - one record per row/item, looking at any page image
16856
17477
  return indexGroupVerb(group) + " " + nameLabel;
16857
17478
  }
16858
17479
  function indexGroupCount(group) {
16859
- if (group.stub) return "";
17480
+ var linkedLine = indexGroupLinkedLabel(group);
17481
+ if (linkedLine) return linkedLine;
17482
+ if (group.stub) return indexGroupDurationLabel(group);
16860
17483
  var prog = group.status === "active" && session && session.pageProgressFor ? session.pageProgressFor(group.path || group.key, group.name) : null;
16861
17484
  var pages = prog ? prog.total ? prog.saved + " of " + prog.total + " pages" : prog.saved + " pages" : "";
16862
17485
  var passes = group.passCount <= 1 && !group.mayHaveOlder ? "" : group.passCount + (group.mayHaveOlder ? "+" : "") + " passes";
16863
- return [pages, passes].filter(Boolean).join(" \xB7 ");
17486
+ return [pages, passes, indexGroupDurationLabel(group)].filter(Boolean).join(" \xB7 ");
16864
17487
  }
16865
17488
  var markerSweep = { svc: "", at: 0, gen: 0, done: {}, runs: {}, partial: false, inflight: null };
16866
17489
  var MARKER_SWEEP_TTL_MS = 3e4;
@@ -16905,7 +17528,11 @@ Index the REMAINING windows - one record per row/item, looking at any page image
16905
17528
  finished: typeof d.finished === "number" ? d.finished : void 0,
16906
17529
  error: typeof d.error === "string" ? d.error : void 0,
16907
17530
  platform: d.platform === "claude" || d.platform === "openai" ? d.platform : void 0,
16908
- owner: list[i] && typeof list[i].user_id === "string" ? list[i].user_id : void 0
17531
+ owner: list[i] && typeof list[i].user_id === "string" ? list[i].user_id : void 0,
17532
+ // a run LINKED to an identical file's index (engine identical.ts)
17533
+ linked: d.linked === true ? true : void 0,
17534
+ alias_of: d.linked === true && typeof d.alias_of === "string" ? d.alias_of : void 0,
17535
+ link_ms: d.linked === true && typeof d.link_ms === "number" ? d.link_ms : void 0
16909
17536
  };
16910
17537
  }
16911
17538
  }
@@ -16985,7 +17612,10 @@ Index the REMAINING windows - one record per row/item, looking at any page image
16985
17612
  finished: rr.finished,
16986
17613
  error: rr.error,
16987
17614
  platform: rr.platform,
16988
- owner: rr.owner
17615
+ owner: rr.owner,
17616
+ linked: rr.linked,
17617
+ alias_of: rr.alias_of,
17618
+ link_ms: rr.link_ms
16989
17619
  };
16990
17620
  }
16991
17621
  }
@@ -17241,7 +17871,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
17241
17871
  var label = h(
17242
17872
  "span",
17243
17873
  { class: "bq-index-label" },
17244
- h("span", { class: "bq-md", html: parseMsgPartsHtml(indexGroupLabel(group), { imagePreviews: false }) })
17874
+ h("span", { class: "bq-md", html: parseMsgPartsHtml(indexGroupLabel(group), { imagePreviews: false, fitLinkLabels: true }) })
17245
17875
  );
17246
17876
  label.addEventListener("click", function(e) {
17247
17877
  if (e.target && e.target.closest && e.target.closest("a")) e.stopPropagation();
@@ -17606,6 +18236,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
17606
18236
  CS.uploadingAttachments = false;
17607
18237
  CS.attachmentWarning = "";
17608
18238
  CS.attachmentCapNotice = "";
18239
+ CS.attachmentCancelNotice = "";
17609
18240
  CS.attachmentsRow = null;
17610
18241
  CS.attachBtnEl = null;
17611
18242
  CS.sendBtnEl = null;
@@ -18192,7 +18823,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
18192
18823
  signup: false,
18193
18824
  // include signup (and thus delete/recover account)
18194
18825
  dev: false,
18195
- // use the MCP dev host (mcp-dev.broadwayinc.computer)
18826
+ // use the MCP dev host (mcp.broadwayinc.computer)
18196
18827
  mcpBaseUrl: null,
18197
18828
  // override the MCP OAuth server base entirely
18198
18829
  googleClientId: null,