bunnyquery 1.21.3 → 1.21.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/bunnyquery.css +70 -0
- package/bunnyquery.js +391 -73
- package/dist/engine.cjs +260 -61
- package/dist/engine.cjs.map +1 -1
- package/dist/engine.d.mts +96 -3
- package/dist/engine.d.ts +96 -3
- package/dist/engine.mjs +253 -62
- package/dist/engine.mjs.map +1 -1
- package/package.json +1 -1
- package/src/engine/index.ts +5 -0
- package/src/engine/indexing_groups.ts +96 -4
- package/src/engine/link_markup.ts +51 -2
- package/src/engine/prompts/chat_system_prompt.ts +13 -1
- package/src/engine/prompts/indexing_system_prompt.ts +1 -1
- package/src/engine/prompts/indexing_user_message.ts +6 -1
- package/src/engine/session.ts +149 -31
- package/src/engine/time.ts +57 -0
- package/src/widget.css +10 -0
- package/styles/chat.css +60 -0
package/package.json
CHANGED
package/src/engine/index.ts
CHANGED
|
@@ -253,6 +253,9 @@ export {
|
|
|
253
253
|
// A page that draws indexing state from the queue, with or without a chat view
|
|
254
254
|
// (ChatSession.watchIndexQueue; the answer is in state.indexQueues).
|
|
255
255
|
type IndexQueueIdentity, type IndexQueueWatchOptions, type IndexQueueWatchHandle,
|
|
256
|
+
// A cancelled attachment upload (ChatSession.cancelAttachmentUpload) rejects
|
|
257
|
+
// with this, so a view can tell it from a failed one.
|
|
258
|
+
UPLOAD_CANCELLED_MESSAGE, isUploadCancelledError,
|
|
256
259
|
} from './session';
|
|
257
260
|
export type { ChatHost, ChatIdentity, ChatState, ChatMessage, IndexingFileRef, PinnedDispatchContext, IndexQueueSnapshot } from './host';
|
|
258
261
|
|
|
@@ -261,6 +264,8 @@ export type { ChatHost, ChatIdentity, ChatState, ChatMessage, IndexingFileRef, P
|
|
|
261
264
|
export {
|
|
262
265
|
buildChatDisplayList,
|
|
263
266
|
parseIndexingLabel,
|
|
267
|
+
indexGroupDurationLabel,
|
|
268
|
+
runRecordDurationMs,
|
|
264
269
|
type DisplayEntry,
|
|
265
270
|
type IndexingGroup,
|
|
266
271
|
type IndexingGroupStatus,
|
|
@@ -67,6 +67,7 @@ import type { ChatMessage, IndexingFileRef } from './host';
|
|
|
67
67
|
import { isPagedReadFile, isImageVisionFile } from './office';
|
|
68
68
|
import { windowedIndexingEnabled } from './config';
|
|
69
69
|
import { MAX_INDEXING_RESUME_PASSES } from './requests';
|
|
70
|
+
import { messageTimeMs, formatIndexDuration } from './time';
|
|
70
71
|
|
|
71
72
|
export type IndexingGroupStatus = 'active' | 'done' | 'error' | 'cancelled';
|
|
72
73
|
|
|
@@ -221,6 +222,13 @@ export type IndexingGroup = {
|
|
|
221
222
|
stubError?: string;
|
|
222
223
|
/** A run:: row that is live with no pass running yet: waiting in the queue. */
|
|
223
224
|
queued?: boolean;
|
|
225
|
+
/** How long the file took to index (ms), from the run:: record's `started` to its
|
|
226
|
+
* `finished`. Set only when the record is 'done' and describes THIS run (a stub, or
|
|
227
|
+
* the newest run of a file whose loaded passes fall inside the record's span; there
|
|
228
|
+
* the first pass's server time stands in for a `started` it disagrees with). Read
|
|
229
|
+
* it through indexGroupDurationLabel, which also holds it back from any row that is
|
|
230
|
+
* not a finished 'done'. */
|
|
231
|
+
durationMs?: number;
|
|
224
232
|
};
|
|
225
233
|
|
|
226
234
|
export type DisplayEntry =
|
|
@@ -460,6 +468,82 @@ function overlayRunRecordVerdict(
|
|
|
460
468
|
grp.resolvingReason = undefined;
|
|
461
469
|
}
|
|
462
470
|
|
|
471
|
+
/** A 'done' run:: record's span in ms (`finished - started`), or undefined when the
|
|
472
|
+
* record is not 'done' or either stamp is missing, non-finite, or out of order. The
|
|
473
|
+
* files page reads the same records, so it uses this too. */
|
|
474
|
+
export function runRecordDurationMs(rec?: { status?: string; started?: number; finished?: number } | null): number | undefined {
|
|
475
|
+
if (!rec || rec.status !== 'done') return undefined;
|
|
476
|
+
var a = rec.started;
|
|
477
|
+
var b = rec.finished;
|
|
478
|
+
if (typeof a !== 'number' || typeof b !== 'number' || !isFinite(a) || !isFinite(b) || b < a) return undefined;
|
|
479
|
+
return b - a;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/** Clock slack between a run:: record's `started` (the browser that queued the run) and
|
|
483
|
+
* a pass's time (the server's request id). */
|
|
484
|
+
var RUN_DURATION_CLOCK_SLACK_MS = 60000;
|
|
485
|
+
/** Slack between two SERVER stamps: a pass's request id and the record's `finished`
|
|
486
|
+
* (the same few seconds overlayRunRecordVerdict allows). */
|
|
487
|
+
var RUN_DURATION_SERVER_SLACK_MS = 5000;
|
|
488
|
+
|
|
489
|
+
/**
|
|
490
|
+
* How long the run a LOADED group shows took, from its run:: record, or undefined when
|
|
491
|
+
* the record is not this run's or its numbers cannot be trusted. The record is per file
|
|
492
|
+
* and a new run rewrites it, so first: is it this run? It must have ended no earlier than
|
|
493
|
+
* the newest loaded pass (an older record is a previous run whose reopen write was lost,
|
|
494
|
+
* or a span minted from the passes themselves), and not before the first one.
|
|
495
|
+
*
|
|
496
|
+
* Then: where did the run start? `started` is the BROWSER's clock, `finished` the
|
|
497
|
+
* server's, so a browser clock that is off by an hour put that hour into the row. When
|
|
498
|
+
* the run's first pass is on screen, its request id is the same moment on the server's
|
|
499
|
+
* clock: the record's `started` is kept while the two agree (so the row says what the
|
|
500
|
+
* record-only row and the files page say), and the pass time replaces a `started` well
|
|
501
|
+
* before it (a browser clock running behind, or a `started` left over from an earlier
|
|
502
|
+
* run whose reopen write was lost). A `started` well AFTER the first loaded pass is a
|
|
503
|
+
* later run, or a browser clock running ahead; the two cannot be told apart, so the row
|
|
504
|
+
* gets no time.
|
|
505
|
+
*/
|
|
506
|
+
function runRecordGroupDurationMs(grp: IndexingGroup, rec: RunStubInfo): number | undefined {
|
|
507
|
+
if (rec.status !== 'done' || !grp.members.length) return undefined;
|
|
508
|
+
var fin = rec.finished;
|
|
509
|
+
if (typeof fin !== 'number' || !isFinite(fin)) return undefined;
|
|
510
|
+
var firstTs = messageTimeMs(grp.members[0].msg);
|
|
511
|
+
var lastTs = messageTimeMs(grp.members[grp.members.length - 1].msg);
|
|
512
|
+
if (!firstTs || !lastTs) return undefined;
|
|
513
|
+
if (fin < firstTs || fin < lastTs - RUN_DURATION_SERVER_SLACK_MS) return undefined;
|
|
514
|
+
var firstPassTs = 0;
|
|
515
|
+
for (var i = 0; i < grp.members.length; i++) {
|
|
516
|
+
var m = grp.members[i].msg;
|
|
517
|
+
if (m.role !== 'user') continue;
|
|
518
|
+
var ref = readFileRef(m);
|
|
519
|
+
if (ref && !ref.continued) firstPassTs = messageTimeMs(m);
|
|
520
|
+
break;
|
|
521
|
+
}
|
|
522
|
+
var st = typeof rec.started === 'number' && isFinite(rec.started) ? rec.started : undefined;
|
|
523
|
+
var start: number;
|
|
524
|
+
// A `started` after the first loaded pass is a later run's (one whose passes are not
|
|
525
|
+
// in this chat), or a browser clock running ahead: no time rather than a wrong one.
|
|
526
|
+
if (st !== undefined && st > firstTs + RUN_DURATION_CLOCK_SLACK_MS) return undefined;
|
|
527
|
+
if (firstPassTs) {
|
|
528
|
+
start = st !== undefined && st >= firstPassTs - RUN_DURATION_CLOCK_SLACK_MS ? st : firstPassTs;
|
|
529
|
+
} else {
|
|
530
|
+
if (st === undefined) return undefined;
|
|
531
|
+
start = st;
|
|
532
|
+
}
|
|
533
|
+
return fin >= start ? fin - start : undefined;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/**
|
|
537
|
+
* The time a row's file took to index ("12 min 5 s"), or '' when the row should not
|
|
538
|
+
* say one: only a finished, settled 'done' row with a duration from its own run::
|
|
539
|
+
* record. Active, queued, error and cancelled rows get nothing. Shared so agent.vue
|
|
540
|
+
* and the widget print the same text in the same place.
|
|
541
|
+
*/
|
|
542
|
+
export function indexGroupDurationLabel(group?: IndexingGroup | null): string {
|
|
543
|
+
if (!group || group.status !== 'done' || !group.finished || group.resolving || group.queued) return '';
|
|
544
|
+
return formatIndexDuration(group.durationMs);
|
|
545
|
+
}
|
|
546
|
+
|
|
463
547
|
export function buildChatDisplayList(
|
|
464
548
|
messages: ChatMessage[],
|
|
465
549
|
opts?: BuildDisplayListOptions,
|
|
@@ -542,8 +626,12 @@ export function buildChatDisplayList(
|
|
|
542
626
|
// label-only behaviour stands, so the re-index case is unchanged.
|
|
543
627
|
var openId = openRunOfKey[key];
|
|
544
628
|
var notLater = false;
|
|
545
|
-
|
|
546
|
-
|
|
629
|
+
// A message's time is its _ts, else its request id's (messageTimeMs): a live
|
|
630
|
+
// worker pass adopted from the queue has no _ts, and without a time on both
|
|
631
|
+
// sides an OLDER first pass loaded after it split the run in two (2026-11-25).
|
|
632
|
+
var msgTime = messageTimeMs(msg);
|
|
633
|
+
if (openId && msgTime > 0 && typeof newestTsOfRun[openId] === 'number') {
|
|
634
|
+
notLater = msgTime <= newestTsOfRun[openId];
|
|
547
635
|
}
|
|
548
636
|
if (!ref.continued && !alreadySeen && !notLater && openRunOfKey[key]) delete openRunOfKey[key];
|
|
549
637
|
runId = openRunOfKey[key];
|
|
@@ -567,9 +655,10 @@ export function buildChatDisplayList(
|
|
|
567
655
|
// or a response whose request is not loaded) stays an ordinary message
|
|
568
656
|
// rather than being folded into whichever group happens to be nearest.
|
|
569
657
|
if (!runId) continue;
|
|
570
|
-
|
|
658
|
+
var memberTime = messageTimeMs(msg);
|
|
659
|
+
if (memberTime > 0) {
|
|
571
660
|
var prevTs = newestTsOfRun[runId];
|
|
572
|
-
if (typeof prevTs !== 'number' ||
|
|
661
|
+
if (typeof prevTs !== 'number' || memberTime > prevTs) newestTsOfRun[runId] = memberTime;
|
|
573
662
|
}
|
|
574
663
|
|
|
575
664
|
var g = groups[runId];
|
|
@@ -1108,6 +1197,8 @@ export function buildChatDisplayList(
|
|
|
1108
1197
|
&& !runningKeys[sp] && !runningKeys[canonIndexKey(sp)] && !runningKeys[fname]) ? true : undefined,
|
|
1109
1198
|
stubError: rec.error || (st === 'error' && !rec.error
|
|
1110
1199
|
? 'Indexing did not finish.' : undefined),
|
|
1200
|
+
// The stub IS the record, so a 'done' record's span is this run's.
|
|
1201
|
+
durationMs: st === 'done' ? runRecordDurationMs(rec) : undefined,
|
|
1111
1202
|
};
|
|
1112
1203
|
// A record with no `started` cannot be placed in the conversation.
|
|
1113
1204
|
// Infinity sorts it to the END (nearest the newest turns) instead of
|
|
@@ -1149,6 +1240,7 @@ export function buildChatDisplayList(
|
|
|
1149
1240
|
tg.runKey = 'run:' + (tg.path || tg.key) + '#' + trec.started;
|
|
1150
1241
|
stubList.push({ started: trec.started, group: tg });
|
|
1151
1242
|
overlayRunRecordVerdict(tg, trec, liveIndexKeys);
|
|
1243
|
+
tg.durationMs = runRecordGroupDurationMs(tg, trec);
|
|
1152
1244
|
}
|
|
1153
1245
|
}
|
|
1154
1246
|
stubList.sort(function (a, b) { return a.started - b.started; });
|
|
@@ -57,6 +57,41 @@ export interface InlineLinkMarkupOptions {
|
|
|
57
57
|
* isLinkUnavailable). Renders a dead chip: ✕, greyed, no href.
|
|
58
58
|
*/
|
|
59
59
|
unavailable?: boolean;
|
|
60
|
+
/**
|
|
61
|
+
* Render the FULL name and let CSS shorten it to the room it has, instead of
|
|
62
|
+
* the fixed LINK_LABEL_MAX_DISPLAY_CHARS cut. Used by the collapsed indexing
|
|
63
|
+
* row head, which is one line with the whole chat width to spend: a 32
|
|
64
|
+
* character cap left most of that line empty and cut names that would have
|
|
65
|
+
* fit. The name is split into a stem that ellipsizes and a tail (the end of
|
|
66
|
+
* the name plus its extension) that never shrinks, so a name too long for the
|
|
67
|
+
* row still shows what kind of file it is. Ignored on an image preview.
|
|
68
|
+
*/
|
|
69
|
+
fitLabel?: boolean;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Characters of the name kept beside the extension in a fitted label's tail. */
|
|
73
|
+
var FIT_LABEL_TAIL_CHARS = 8;
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Split a file name into the part a fitted chip may cut (stem) and the part it
|
|
77
|
+
* always shows (tail): the last few characters of the name plus its extension,
|
|
78
|
+
* e.g. "4500.00.0265.001_Non-ret" + "urn Valve.tiff". Counted in code points so a
|
|
79
|
+
* surrogate pair (emoji, rare CJK) is never split in half. Pure: the two halves
|
|
80
|
+
* concatenate back to the input exactly.
|
|
81
|
+
*/
|
|
82
|
+
export function splitLabelForFit(name: string): { stem: string; tail: string } {
|
|
83
|
+
var chars = Array.from(String(name == null ? '' : name));
|
|
84
|
+
var dot = -1;
|
|
85
|
+
for (var i = chars.length - 1; i > 0; i--) {
|
|
86
|
+
if (chars[i] === '.') { dot = i; break; }
|
|
87
|
+
if (chars[i] === ' ' || chars[i] === '/' || chars.length - i > 10) break;
|
|
88
|
+
}
|
|
89
|
+
// A short name has nothing worth keeping apart: one stem cut at the end reads
|
|
90
|
+
// the same, and an all-tail name could never shrink.
|
|
91
|
+
var extStart = dot > 0 && dot < chars.length - 1 ? dot : chars.length;
|
|
92
|
+
var tailStart = Math.max(0, extStart - FIT_LABEL_TAIL_CHARS);
|
|
93
|
+
if (tailStart < 4) return { stem: chars.join(''), tail: '' };
|
|
94
|
+
return { stem: chars.slice(0, tailStart).join(''), tail: chars.slice(tailStart).join('') };
|
|
60
95
|
}
|
|
61
96
|
|
|
62
97
|
export function renderInlineLinkHtml(link: RenderableInlineLink, opts?: InlineLinkMarkupOptions): string {
|
|
@@ -84,8 +119,22 @@ export function renderInlineLinkHtml(link: RenderableInlineLink, opts?: InlineLi
|
|
|
84
119
|
// margin on the span for the same reason (a space is decorated too).
|
|
85
120
|
var glyphHtml = '<span class="bq-link-glyph" translate="no">'
|
|
86
121
|
+ (unavailable ? INLINE_LINK_UNAVAILABLE_GLYPH : INLINE_LINK_GLYPH) + '</span>';
|
|
87
|
-
var
|
|
88
|
-
|
|
122
|
+
var stateSuffix = unavailable ? INLINE_LINK_UNAVAILABLE_SUFFIX : refreshing ? ' (fetching...)' : '';
|
|
123
|
+
var fit = !!o.fitLabel && !preview;
|
|
124
|
+
if (fit) cls.push('bq-link-fit');
|
|
125
|
+
var labelHtml;
|
|
126
|
+
if (fit) {
|
|
127
|
+
// Three flex items (see .bq-link-fit in chat.css): the stem shrinks with an
|
|
128
|
+
// ellipsis, the tail and the state suffix never do. The full name is also
|
|
129
|
+
// the anchor's title, so a cut name is one hover away.
|
|
130
|
+
var split = splitLabelForFit(full);
|
|
131
|
+
labelHtml = glyphHtml
|
|
132
|
+
+ '<span class="bq-link-stem">' + escapeInlineHtml(split.stem) + '</span>'
|
|
133
|
+
+ (split.tail ? '<span class="bq-link-tail">' + escapeInlineHtml(split.tail) + '</span>' : '')
|
|
134
|
+
+ (stateSuffix ? '<span class="bq-link-tail">' + escapeInlineHtml(stateSuffix) + '</span>' : '');
|
|
135
|
+
} else {
|
|
136
|
+
labelHtml = glyphHtml + escapeInlineHtml(link.label + stateSuffix);
|
|
137
|
+
}
|
|
89
138
|
var attrs = ['class="' + cls.join(' ') + '"'];
|
|
90
139
|
// NO href when the file is unavailable. That is what disables the click:
|
|
91
140
|
// an anchor with no href does not navigate, is not a tab stop and takes the
|
|
@@ -96,13 +96,25 @@ export function buildChatSystemPrompt(params: ChatSystemPromptParams): string {
|
|
|
96
96
|
// a claim about the project's data (product help, a greeting, authored text).
|
|
97
97
|
// The upload suggestion follows canUpload for the same reason the About section
|
|
98
98
|
// does: a visitor who cannot upload must never be told to.
|
|
99
|
+
//
|
|
100
|
+
// NOT FOUND BY searchText (2026-11-26): a photo's serial read as "[?]" at indexing
|
|
101
|
+
// is not in the page text, so the search honestly finds nothing. The answer must
|
|
102
|
+
// then say so, say how much was searched, and point at re-indexing the file (a
|
|
103
|
+
// photo or a recent upload is where a misread is likely), never offer another
|
|
104
|
+
// file as the match. The re-index direction follows canUpload and the client.
|
|
105
|
+
const reindexHint = canUpload === false
|
|
106
|
+
? `asking the project's owner to re-index that file`
|
|
107
|
+
: client === 'console'
|
|
108
|
+
? `re-indexing that file (select it on the Files page and choose Reindex)`
|
|
109
|
+
: `re-indexing that file (attach the same file again and choose to reindex it)`;
|
|
99
110
|
const groundingRules =
|
|
100
111
|
`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.
|
|
101
112
|
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
|
|
102
113
|
? `another name or file to look under, or asking the project's owner to add it`
|
|
103
114
|
: `the document to upload, or another name or file to look under`}.
|
|
115
|
+
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.
|
|
104
116
|
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.
|
|
105
|
-
These
|
|
117
|
+
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.`;
|
|
106
118
|
|
|
107
119
|
// ---- Web switch ---------------------------------------------------------
|
|
108
120
|
// Follows the tool list: with the web off the chat has no such tool, with it on
|
|
@@ -38,7 +38,7 @@ export function buildIndexingSystemPrompt(params: IndexingSystemPromptParams): s
|
|
|
38
38
|
- 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.
|
|
39
39
|
- 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).
|
|
40
40
|
- 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.
|
|
41
|
-
- 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).
|
|
41
|
+
- 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.
|
|
42
42
|
- 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.
|
|
43
43
|
- 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.
|
|
44
44
|
- 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.
|
|
@@ -161,13 +161,18 @@ export function buildIndexingUserMessage(
|
|
|
161
161
|
if (options?.imageFile) {
|
|
162
162
|
// The URL line stays: the engine builds the image block from the URL it finds in this
|
|
163
163
|
// text. The fields named here are the ones the worker writes as the image's page text.
|
|
164
|
+
// "text_regions" (2026-11-26) is the worker's contract: up to 4 boxes, fractions of the
|
|
165
|
+
// image as the model saw it, that the worker can crop and read again at full resolution.
|
|
164
166
|
return (
|
|
165
167
|
head +
|
|
166
168
|
`- temporary URL: ${attachment.url}\n` +
|
|
167
169
|
(options.imageFile === 'attached'
|
|
168
170
|
? `\nThis is an IMAGE file, attached to this message as an image: read it there, not from the URL. `
|
|
169
171
|
: `\nThis 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. `) +
|
|
170
|
-
`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".
|
|
172
|
+
`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". ` +
|
|
173
|
+
`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. ` +
|
|
174
|
+
`Then set "text_rotation", "text_legibility" and "text_regions" on the file's "src::" record, and only then describe what the image shows. ` +
|
|
175
|
+
`"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.`
|
|
171
176
|
);
|
|
172
177
|
}
|
|
173
178
|
|
package/src/engine/session.ts
CHANGED
|
@@ -59,7 +59,7 @@ import { retrievalNoteOfAnswer, answerUsedNoDataTool } from './citations';
|
|
|
59
59
|
import { createInlineLinkRegex, sanitizeAttachmentLinksForHistory } from './links';
|
|
60
60
|
import { markImagePreviewStale } from './image_preview';
|
|
61
61
|
import { chatCacheKey, indexScopeKey, mapHistoryListToMessages, extractLastUserTextFromRequest, listedRequestText, isIndexingRequestText, parseIndexingRequestText, probeBgQueue, BG_PROBE_TTL_MS, fetchLiveIndexingKeys, getSplitChatHistory, shouldRescueInFlightMessage, adoptLocalAnswerIntoPage, adoptLiveTextIntoRunningRow } from './history';
|
|
62
|
-
import { wallClockNow } from './time';
|
|
62
|
+
import { wallClockNow, requestIdTimeMs, messageTimeMs } from './time';
|
|
63
63
|
import { parseAttachmentContent } from './attachment_parsers';
|
|
64
64
|
import type { ChatHost, ChatState, ChatMessage, ChatIdentity, PinnedDispatchContext, IndexQueueSnapshot } from './host';
|
|
65
65
|
import type { IndexingGroup } from './indexing_groups';
|
|
@@ -839,25 +839,8 @@ type LiveStreamState = {
|
|
|
839
839
|
transport: { socket: number; poll: number };
|
|
840
840
|
};
|
|
841
841
|
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
* as 8 bytes of base32hex without padding (the worker's and the producer's _generate_req_id).
|
|
845
|
-
* 0 when it is not one.
|
|
846
|
-
*/
|
|
847
|
-
export function requestIdTimeMs(rid: string): number {
|
|
848
|
-
if (typeof rid !== 'string') return 0;
|
|
849
|
-
var stamp = rid.split(':')[0] || '';
|
|
850
|
-
if (stamp.length !== 13) return 0;
|
|
851
|
-
var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUV';
|
|
852
|
-
var v = 0;
|
|
853
|
-
for (var i = 0; i < stamp.length; i++) {
|
|
854
|
-
var d = alphabet.indexOf(stamp.charAt(i).toUpperCase());
|
|
855
|
-
if (d < 0) return 0;
|
|
856
|
-
v = v * 32 + d;
|
|
857
|
-
}
|
|
858
|
-
// 13 digits are 65 bits for 64 of data: the last bit is padding.
|
|
859
|
-
return Math.floor(v / 2 / 1e6);
|
|
860
|
-
}
|
|
842
|
+
// requestIdTimeMs lives in time.ts (2026-11-25: indexing_groups.ts needs it too); re-exported here.
|
|
843
|
+
export { requestIdTimeMs };
|
|
861
844
|
|
|
862
845
|
/** The visible message the "Wrong answer?" button sends. The chat prompt's WRONG ANSWER rule reacts to it. */
|
|
863
846
|
export var WRONG_ANSWER_MESSAGE = 'This answer seems wrong. Please check it again against the documents.';
|
|
@@ -876,6 +859,13 @@ export function canReportWrongAnswer(msg: ChatMessage | null | undefined): boole
|
|
|
876
859
|
return !!note && !answerUsedNoDataTool(note) && !(msg as any).isCancelled;
|
|
877
860
|
}
|
|
878
861
|
|
|
862
|
+
/** The message of the error an attachment upload rejects with when the user cancelled it. */
|
|
863
|
+
export var UPLOAD_CANCELLED_MESSAGE = 'Upload cancelled';
|
|
864
|
+
/** True for the rejection of an attachment upload the user cancelled (cancelAttachmentUpload). */
|
|
865
|
+
export function isUploadCancelledError(err: any): boolean {
|
|
866
|
+
return !!err && (err.code === 'CANCELLED' || err.message === UPLOAD_CANCELLED_MESSAGE);
|
|
867
|
+
}
|
|
868
|
+
|
|
879
869
|
export class ChatSession {
|
|
880
870
|
host: ChatHost;
|
|
881
871
|
state: ChatState;
|
|
@@ -7602,15 +7592,18 @@ export class ChatSession {
|
|
|
7602
7592
|
});
|
|
7603
7593
|
}
|
|
7604
7594
|
|
|
7605
|
-
/** Insert bubbles before the first message that is newer than them
|
|
7606
|
-
*
|
|
7595
|
+
/** Insert bubbles before the first message that is newer than them; messages whose time
|
|
7596
|
+
* is unknown are skipped over, and the end of the list takes them otherwise. A message's
|
|
7597
|
+
* time is its `_ts`, else (2026-11-25) the time in its request id: a live worker pass
|
|
7598
|
+
* adopted from the queue carries no `_ts`, and a file's older passes loaded by opening its
|
|
7599
|
+
* row (loadRunPasses) used to land AFTER it, which split one run into two rows. */
|
|
7607
7600
|
private _insertByTime(bubbles: ChatMessage[]): void {
|
|
7608
|
-
var at = bubbles[0]
|
|
7601
|
+
var at = messageTimeMs(bubbles[0]);
|
|
7609
7602
|
var idx = this.state.messages.length;
|
|
7610
|
-
if (
|
|
7603
|
+
if (at > 0) {
|
|
7611
7604
|
for (var i = 0; i < this.state.messages.length; i++) {
|
|
7612
|
-
var t = this.state.messages[i]
|
|
7613
|
-
if (
|
|
7605
|
+
var t = messageTimeMs(this.state.messages[i]);
|
|
7606
|
+
if (t > 0 && t > at) { idx = i; break; }
|
|
7614
7607
|
}
|
|
7615
7608
|
}
|
|
7616
7609
|
Array.prototype.splice.apply(this.state.messages, ([idx, 0] as any[]).concat(bubbles));
|
|
@@ -9260,6 +9253,25 @@ export class ChatSession {
|
|
|
9260
9253
|
}
|
|
9261
9254
|
|
|
9262
9255
|
// --- attachment upload orchestration ---------------------------------
|
|
9256
|
+
/**
|
|
9257
|
+
* The user cancelled this chip's upload (the widget's per-chip x or "Cancel all
|
|
9258
|
+
* uploads"). Stops the bytes now when they are moving (the host's abort), and
|
|
9259
|
+
* leaves a flag every later step of uploadSingleAttachment checks, so a cancel
|
|
9260
|
+
* that lands between steps (the get-signed-url round trip before the bytes, or
|
|
9261
|
+
* the src:: record and the indexing request after them) still stops the file
|
|
9262
|
+
* from being indexed and from being attached to the chat turn. A member whose
|
|
9263
|
+
* indexing request has already gone out is past cancelling: it shows as an
|
|
9264
|
+
* indexing row with its own Stop. Returns false for a chip that is not being
|
|
9265
|
+
* uploaded by this session any more.
|
|
9266
|
+
*/
|
|
9267
|
+
cancelAttachmentUpload(att: any): boolean {
|
|
9268
|
+
if (!att || att._cancelled) return false;
|
|
9269
|
+
if (att.status !== 'uploading' && !att._batchId) return false;
|
|
9270
|
+
att._cancelled = true;
|
|
9271
|
+
if (typeof att._abort === 'function') { try { att._abort(); } catch (e) { } }
|
|
9272
|
+
return true;
|
|
9273
|
+
}
|
|
9274
|
+
|
|
9263
9275
|
// Upload one attachment (a file = 1 member, a folder = N) to db storage and
|
|
9264
9276
|
// queue indexing per member. The bytes I/O + chip rendering go through host
|
|
9265
9277
|
// hooks; the overwrite/reindex flow, status lifecycle, and indexing live here.
|
|
@@ -9291,6 +9303,18 @@ export class ChatSession {
|
|
|
9291
9303
|
// below). Counted so a folder chip can say how many it reused.
|
|
9292
9304
|
var reusedCount = 0;
|
|
9293
9305
|
att.reused = false;
|
|
9306
|
+
// Cancel bookkeeping (see cancelAttachmentUpload): which members' bytes are
|
|
9307
|
+
// confirmed stored and which have had their indexing request sent, so the
|
|
9308
|
+
// view can say honestly what a cancel did and did not undo. A retry starts
|
|
9309
|
+
// clean. `_cancelled` is NOT reset: a cancelled chip leaves the list and is
|
|
9310
|
+
// never retried, and a cancel that raced the start must still stop it.
|
|
9311
|
+
att._storedCount = 0; att._indexQueuedCount = 0; att._indexQueued = false;
|
|
9312
|
+
var cancelError = function (): Error {
|
|
9313
|
+
var e: any = new Error(UPLOAD_CANCELLED_MESSAGE);
|
|
9314
|
+
e.code = 'CANCELLED';
|
|
9315
|
+
return e;
|
|
9316
|
+
};
|
|
9317
|
+
var checkCancel = function (): void { if (att._cancelled) throw cancelError(); };
|
|
9294
9318
|
// The members skipped as duplicates, with the STORED copy each one matched, so
|
|
9295
9319
|
// the host can report them after the send and offer to reindex the stored
|
|
9296
9320
|
// copies (reindexStoredFiles). A retry decides afresh.
|
|
@@ -9314,6 +9338,9 @@ export class ChatSession {
|
|
|
9314
9338
|
};
|
|
9315
9339
|
members.forEach(function (member: any, idx: number) {
|
|
9316
9340
|
chain = chain.then(function () {
|
|
9341
|
+
// Cancelled while an earlier member of this folder was uploading: the
|
|
9342
|
+
// rest are never started.
|
|
9343
|
+
checkCancel();
|
|
9317
9344
|
var hadExists = false;
|
|
9318
9345
|
var skipped = false;
|
|
9319
9346
|
// The storage path of the file this member DUPLICATES, when the user
|
|
@@ -9326,6 +9353,10 @@ export class ChatSession {
|
|
|
9326
9353
|
// from hadExists, which must keep driving ONLY the Reindexing/Indexing
|
|
9327
9354
|
// label (isReindex) — overwrite still labels as "Indexing:".
|
|
9328
9355
|
var existedBefore = false;
|
|
9356
|
+
// This upload made a NEW file's record (the no-access retry of the url
|
|
9357
|
+
// mint, or the step before the indexing request): a cancel that lands
|
|
9358
|
+
// after it drops that record again.
|
|
9359
|
+
var madeRecord = false;
|
|
9329
9360
|
var onProg = function (p: any) {
|
|
9330
9361
|
if (p && p.total) {
|
|
9331
9362
|
att.progress = Math.floor(((idx + p.loaded / p.total) / total) * 100);
|
|
@@ -9333,9 +9364,29 @@ export class ChatSession {
|
|
|
9333
9364
|
}
|
|
9334
9365
|
};
|
|
9335
9366
|
var doMemberUpload = function (checkExistence: boolean) {
|
|
9367
|
+
// Cancelled during the EXISTS prompt or between members: no bytes.
|
|
9368
|
+
checkCancel();
|
|
9336
9369
|
return self.host.uploadFile({
|
|
9337
9370
|
file: member.file, storagePath: member.storagePath, checkExistence: checkExistence,
|
|
9338
|
-
onProgress: onProg,
|
|
9371
|
+
onProgress: onProg,
|
|
9372
|
+
// The host hands its abort over just before the bytes start. A
|
|
9373
|
+
// cancel made during the get-signed-url round trip had nothing to
|
|
9374
|
+
// abort yet, so it is applied here, before anything is sent: a
|
|
9375
|
+
// storage POST that never completes leaves no object behind.
|
|
9376
|
+
setAbort: function (abort) {
|
|
9377
|
+
att._abort = abort;
|
|
9378
|
+
if (att._cancelled) { try { abort(); } catch (e) { } }
|
|
9379
|
+
},
|
|
9380
|
+
}).then(function (r: any) {
|
|
9381
|
+
att._abort = null;
|
|
9382
|
+
att._storedCount = (att._storedCount || 0) + 1;
|
|
9383
|
+
return r;
|
|
9384
|
+
}, function (err: any) {
|
|
9385
|
+
att._abort = null;
|
|
9386
|
+
// An abort the user asked for reads as the cancel it is, not as
|
|
9387
|
+
// a failed upload.
|
|
9388
|
+
if (att._cancelled) throw cancelError();
|
|
9389
|
+
throw err;
|
|
9339
9390
|
});
|
|
9340
9391
|
};
|
|
9341
9392
|
if (isIndexRetry) { hadExists = true; existedBefore = true; }
|
|
@@ -9367,6 +9418,9 @@ export class ChatSession {
|
|
|
9367
9418
|
hadExists = true; existedBefore = true; // keep it; Reindex
|
|
9368
9419
|
});
|
|
9369
9420
|
}).then(function () {
|
|
9421
|
+
// Cancelled while the bytes were finishing or during the EXISTS
|
|
9422
|
+
// prompt: no url, no file record, no indexing request.
|
|
9423
|
+
checkCancel();
|
|
9370
9424
|
if (skipped) return; // user skipped this member — no url, no index request
|
|
9371
9425
|
// A duplicate takes the STORED copy's url: the same reuse an EXISTS
|
|
9372
9426
|
// answer gets when the user keeps the file, minus the prompt and
|
|
@@ -9383,11 +9437,21 @@ export class ChatSession {
|
|
|
9383
9437
|
var emsg = String((err && (err.message || (err.body && err.body.message))) || err || '');
|
|
9384
9438
|
var refused = /no access to this file/i.test(emsg) || (ecode === 'INVALID_REQUEST' && /access/i.test(emsg));
|
|
9385
9439
|
if (duplicateOf || !refused || typeof self.host.ensureFileIndexRecord !== 'function') throw err;
|
|
9440
|
+
madeRecord = !existedBefore;
|
|
9386
9441
|
return Promise.resolve(self.host.ensureFileIndexRecord(member.storagePath, {
|
|
9387
9442
|
name: member.file.name, mime: member.file.type || self.host.getMimeType(member.file.name), size: member.file.size,
|
|
9388
9443
|
})).then(function () { return self.host.getTemporaryUrl(member.storagePath); });
|
|
9389
9444
|
});
|
|
9390
9445
|
}).then(function (url: string) {
|
|
9446
|
+
// Cancelled during the url mint. For an uploader who is not the
|
|
9447
|
+
// project owner the mint above made the file record first (the
|
|
9448
|
+
// no-access retry); a file this upload created must not keep it.
|
|
9449
|
+
if (att._cancelled) {
|
|
9450
|
+
var dropEarly = (madeRecord && typeof self.host.deleteExistingFileRecord === 'function')
|
|
9451
|
+
? Promise.resolve(self.host.deleteExistingFileRecord(member.storagePath)).catch(function () { })
|
|
9452
|
+
: Promise.resolve();
|
|
9453
|
+
return dropEarly.then(function () { throw cancelError(); });
|
|
9454
|
+
}
|
|
9391
9455
|
if (skipped) return; // guard the indexing branch for a skipped member
|
|
9392
9456
|
if (duplicateOf) {
|
|
9393
9457
|
urls.push({ name: member.relPath, url: url, storagePath: duplicateOf });
|
|
@@ -9432,13 +9496,20 @@ export class ChatSession {
|
|
|
9432
9496
|
// delete below destroys it: a re-index or an overwrite keeps the file's
|
|
9433
9497
|
// visibility instead of re-deciding it (host.readFileAccessGroup).
|
|
9434
9498
|
var existingGroup: 'public' | 'authorized' | 'private' | null = null;
|
|
9499
|
+
// True once the old index of a file that was already here has been
|
|
9500
|
+
// cleared. A cancel that lands BEFORE that leaves the old index as it
|
|
9501
|
+
// is (a file the user chose to keep and Reindex must not end up with
|
|
9502
|
+
// no index at all because the reindex was cancelled); one that lands
|
|
9503
|
+
// after it still re-creates the file record, which describes a file
|
|
9504
|
+
// that is stored either way.
|
|
9505
|
+
var clearedOld = false;
|
|
9435
9506
|
var preIndex = self.claimIndexRun(member.storagePath).then(function (claimed) {
|
|
9436
9507
|
alreadyIndexing = !claimed;
|
|
9437
9508
|
if (alreadyIndexing) {
|
|
9438
9509
|
console.log('[chat-engine] skipping a duplicate index request for', member.storagePath);
|
|
9439
9510
|
return;
|
|
9440
9511
|
}
|
|
9441
|
-
if (!existedBefore) return;
|
|
9512
|
+
if (!existedBefore || att._cancelled) return;
|
|
9442
9513
|
var readGroup = typeof self.host.readFileAccessGroup === 'function'
|
|
9443
9514
|
? Promise.resolve(self.host.readFileAccessGroup(member.storagePath)).then(function (g) { existingGroup = g || null; }, function (err: any) {
|
|
9444
9515
|
// Unknown is not "no group": deleting now would destroy the only
|
|
@@ -9449,14 +9520,20 @@ export class ChatSession {
|
|
|
9449
9520
|
})
|
|
9450
9521
|
: Promise.resolve();
|
|
9451
9522
|
return readGroup.then(function () {
|
|
9523
|
+
if (att._cancelled) return;
|
|
9452
9524
|
if (typeof self.host.deleteExistingFileRecord === 'function') {
|
|
9525
|
+
clearedOld = true;
|
|
9453
9526
|
return Promise.resolve(self.host.deleteExistingFileRecord(member.storagePath)).catch(function () { });
|
|
9454
9527
|
}
|
|
9455
9528
|
});
|
|
9456
9529
|
});
|
|
9457
9530
|
preIndex = preIndex.then(function () {
|
|
9458
9531
|
if (alreadyIndexing) return;
|
|
9532
|
+
// Cancelled before anything was cleared: no record to make (the
|
|
9533
|
+
// cancel below drops any made early for a new file).
|
|
9534
|
+
if (att._cancelled && !clearedOld) return;
|
|
9459
9535
|
if (typeof self.host.ensureFileIndexRecord !== 'function') return;
|
|
9536
|
+
if (!existedBefore) madeRecord = true;
|
|
9460
9537
|
return Promise.resolve(self.host.ensureFileIndexRecord(member.storagePath, {
|
|
9461
9538
|
name: member.file.name,
|
|
9462
9539
|
mime: mime || undefined,
|
|
@@ -9475,13 +9552,36 @@ export class ChatSession {
|
|
|
9475
9552
|
.then(function (g) { accessGroup = g || undefined; })
|
|
9476
9553
|
.catch(function () { });
|
|
9477
9554
|
});
|
|
9478
|
-
//
|
|
9479
|
-
//
|
|
9480
|
-
//
|
|
9555
|
+
// Cancelled while the file record was being made: hand the indexing
|
|
9556
|
+
// claim back and, for a file this upload created, drop the record
|
|
9557
|
+
// that was just made for it, so nothing points at a file the user
|
|
9558
|
+
// took back. A file that was already here keeps its record (it
|
|
9559
|
+
// still describes a stored file).
|
|
9560
|
+
var abandonIfCancelled = function (): Promise<void> | void {
|
|
9561
|
+
if (!att._cancelled) return;
|
|
9562
|
+
if (!alreadyIndexing) self.releaseIndexRun(member.storagePath);
|
|
9563
|
+
var drop = (!existedBefore && !alreadyIndexing && madeRecord && typeof self.host.deleteExistingFileRecord === 'function')
|
|
9564
|
+
? Promise.resolve(self.host.deleteExistingFileRecord(member.storagePath)).catch(function () { })
|
|
9565
|
+
: Promise.resolve();
|
|
9566
|
+
return drop.then(function () { throw cancelError(); });
|
|
9567
|
+
};
|
|
9481
9568
|
return preIndex.then(function () {
|
|
9569
|
+
return abandonIfCancelled();
|
|
9570
|
+
}).then(function () {
|
|
9571
|
+
// Run a client-side attachment parser (e.g. .hwp) if one matches; its
|
|
9572
|
+
// output is inlined into the indexing request (falls back to office
|
|
9573
|
+
// extraction / web_fetch when no parser matches or it yields nothing).
|
|
9482
9574
|
return parseAttachmentContent(member.file, member.file.name, mime || undefined);
|
|
9575
|
+
}).then(function (parsedContent: string | null) {
|
|
9576
|
+
return Promise.resolve(abandonIfCancelled()).then(function () { return parsedContent; });
|
|
9483
9577
|
}).then(function (parsedContent: string | null) {
|
|
9484
9578
|
if (alreadyIndexing) return;
|
|
9579
|
+
// Past this point the file is on the indexing queue, and a cancel can
|
|
9580
|
+
// no longer take it back: the row it gets has its own Stop. Told to
|
|
9581
|
+
// the view so it stops offering a cancel it cannot honour.
|
|
9582
|
+
att._indexQueuedCount = (att._indexQueuedCount || 0) + 1;
|
|
9583
|
+
if (att.kind !== 'folder') att._indexQueued = true;
|
|
9584
|
+
self.host.renderAttachmentChips();
|
|
9485
9585
|
// Tracked so a chat waiting on awaitIndexingDrained cannot be sent
|
|
9486
9586
|
// in the window between this call and the queue accepting it.
|
|
9487
9587
|
return self.trackIndexDispatch(notifyAgentSaveAttachment({
|
|
@@ -9538,6 +9638,10 @@ export class ChatSession {
|
|
|
9538
9638
|
});
|
|
9539
9639
|
});
|
|
9540
9640
|
return chain.then(function () {
|
|
9641
|
+
// Cancelled after its last member's indexing request went out (a folder
|
|
9642
|
+
// whose cancel came too late for every member): the turn still must not
|
|
9643
|
+
// carry its urls. The members already queued keep their rows and Stop.
|
|
9644
|
+
checkCancel();
|
|
9541
9645
|
att._abort = null; att.progress = 100;
|
|
9542
9646
|
if (att.kind === 'folder') att.uploadedUrls = urls.map(function (u) { return { path: u.name, url: u.url, storagePath: u.storagePath }; });
|
|
9543
9647
|
att.status = anyIndexFailed ? 'indexError' : 'done';
|
|
@@ -9589,6 +9693,14 @@ export class ChatSession {
|
|
|
9589
9693
|
}).catch(function (err: any) {
|
|
9590
9694
|
var removed = !self.state.attachments.some(function (a: any) { return a.id === att.id; });
|
|
9591
9695
|
var aborted = err && (err.message === 'Aborted' || err === 'Aborted');
|
|
9696
|
+
// Cancelled by the user: none of its urls reach the chat turn, and
|
|
9697
|
+
// it is not a failure to report or retry.
|
|
9698
|
+
if (att._cancelled || isUploadCancelledError(err)) {
|
|
9699
|
+
att.status = 'cancelled';
|
|
9700
|
+
att._abort = null;
|
|
9701
|
+
self.host.renderAttachmentChips();
|
|
9702
|
+
return;
|
|
9703
|
+
}
|
|
9592
9704
|
if (removed || aborted) return;
|
|
9593
9705
|
att.status = 'error';
|
|
9594
9706
|
att.errorMessage = 'File upload has failed';
|
|
@@ -9596,6 +9708,12 @@ export class ChatSession {
|
|
|
9596
9708
|
att.errorCode = (err && (err.code || (err.body && err.body.code))) || '';
|
|
9597
9709
|
att.errorDetail = (err && (err.message || (err.body && err.body.message))) || (typeof err === 'string' ? err : '');
|
|
9598
9710
|
self.host.renderAttachmentChips();
|
|
9711
|
+
}).then(function () {
|
|
9712
|
+
// This batch is done with the chip (whatever came of it), so a view
|
|
9713
|
+
// stops offering to cancel its upload while the rest of the batch
|
|
9714
|
+
// runs. Keyed by batch: a failed chip handed back and sent again
|
|
9715
|
+
// is in flight once more.
|
|
9716
|
+
att._settledBatch = att._batchId || true;
|
|
9599
9717
|
});
|
|
9600
9718
|
});
|
|
9601
9719
|
});
|