bunnyquery 1.21.0 → 1.21.4
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 +22 -6
- package/bunnyquery.js +184 -89
- package/dist/engine.cjs +174 -83
- package/dist/engine.cjs.map +1 -1
- package/dist/engine.d.mts +52 -5
- package/dist/engine.d.ts +52 -5
- package/dist/engine.mjs +173 -84
- package/dist/engine.mjs.map +1 -1
- package/package.json +1 -1
- package/src/engine/citations.ts +12 -0
- package/src/engine/config.ts +16 -2
- package/src/engine/indexing_groups.ts +10 -4
- package/src/engine/prompts/chat_system_prompt.ts +3 -3
- package/src/engine/prompts/indexing_system_prompt.ts +3 -3
- package/src/engine/prompts/indexing_user_message.ts +20 -0
- package/src/engine/requests.ts +39 -2
- package/src/engine/retrieval_memory.ts +21 -6
- package/src/engine/session.ts +54 -35
- package/src/engine/time.ts +36 -0
package/package.json
CHANGED
package/src/engine/citations.ts
CHANGED
|
@@ -74,10 +74,18 @@ export function citationsFor(note: RetrievalNote | null | undefined): Citation[]
|
|
|
74
74
|
var out: Citation[] = [];
|
|
75
75
|
var hitPaths: string[] = [];
|
|
76
76
|
var byPath: Record<string, number[]> = {};
|
|
77
|
+
// spreadsheet hits: one chip per sheet, "file · sheet", no page (a sheet page is no place to open)
|
|
78
|
+
var sheetsByPath: Record<string, string[]> = {};
|
|
77
79
|
var i: number;
|
|
78
80
|
for (i = 0; i < note.hits.length; i++) {
|
|
79
81
|
var h: RetrievalHit = note.hits[i];
|
|
80
82
|
if (!h || typeof h.path !== 'string' || !isMintablePath(h.path)) continue;
|
|
83
|
+
if (typeof h.sheet === 'string' && h.sheet) {
|
|
84
|
+
if (!byPath[h.path]) { byPath[h.path] = []; hitPaths.push(h.path); }
|
|
85
|
+
if (!sheetsByPath[h.path]) sheetsByPath[h.path] = [];
|
|
86
|
+
if (sheetsByPath[h.path].indexOf(h.sheet) === -1) sheetsByPath[h.path].push(h.sheet);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
81
89
|
var page = typeof h.page === 'number' ? h.page : Number(h.page);
|
|
82
90
|
if (!isFinite(page) || page <= 0) continue;
|
|
83
91
|
page = Math.floor(page);
|
|
@@ -86,6 +94,10 @@ export function citationsFor(note: RetrievalNote | null | undefined): Citation[]
|
|
|
86
94
|
}
|
|
87
95
|
for (i = 0; i < hitPaths.length; i++) {
|
|
88
96
|
var p = hitPaths[i];
|
|
97
|
+
var sheets = sheetsByPath[p] || [];
|
|
98
|
+
for (var sj = 0; sj < sheets.length; sj++) {
|
|
99
|
+
out.push({ path: p, label: citationFileName(p) + ' · ' + sheets[sj] });
|
|
100
|
+
}
|
|
89
101
|
var pages = byPath[p].slice().sort(function (a, b) { return a - b; });
|
|
90
102
|
for (var j = 0; j < pages.length; j++) {
|
|
91
103
|
out.push({ path: p, page: pages[j], label: citationLabel(p, pages[j]) });
|
package/src/engine/config.ts
CHANGED
|
@@ -141,6 +141,16 @@ export interface ChatEngineConfig {
|
|
|
141
141
|
* until the worker is deployed, then flip it per environment.
|
|
142
142
|
*/
|
|
143
143
|
windowedIndexing?: boolean;
|
|
144
|
+
/**
|
|
145
|
+
* The worker writes the ending (done:: and run::) of a file read in ONE pass (an image,
|
|
146
|
+
* or any file not rendered, windowed or paged), as it does for paged chains: the engine
|
|
147
|
+
* then no longer marks such a run "Indexing stopped ... (the page was closed)" when no
|
|
148
|
+
* page here kept its chain. The engine always sends the request flag (index_end); this
|
|
149
|
+
* switch only stops the client-side "lost" verdict. Turn it on only once every region's
|
|
150
|
+
* worker and polling-recovery Lambda carry the 2026-11-25 change: with an older worker
|
|
151
|
+
* a page closed mid-pass would leave the run 'working'. Off unless true.
|
|
152
|
+
*/
|
|
153
|
+
workerIndexEndings?: boolean;
|
|
144
154
|
/**
|
|
145
155
|
* Mint the durable "indexing finished" marker record ("done::<path>",
|
|
146
156
|
* reference "src::<path>", table __INDEXING__ — same shape the backend
|
|
@@ -263,8 +273,8 @@ export interface ChatEngineConfig {
|
|
|
263
273
|
* `mcp_list_tools` item and OpenAI skips asking the MCP server for its tools again
|
|
264
274
|
* (four sequential requests, about 0.6 s before the model starts).
|
|
265
275
|
*
|
|
266
|
-
* OFF unless set to `true
|
|
267
|
-
*
|
|
276
|
+
* OFF unless set to `true` (the widget and bunnyquery.com set it; verified on a live
|
|
277
|
+
* OpenAI chat 2026-11-25). An account that refuses the item fails one turn, after
|
|
268
278
|
* which reuse stays off for that project in this browser. Costs when on: each
|
|
269
279
|
* reused turn's request body, and so its stored history row, is about 31 to 34 KB
|
|
270
280
|
* larger (the tool list), which also comes back with every history page.
|
|
@@ -520,6 +530,10 @@ export function windowedIndexingEnabled(): boolean {
|
|
|
520
530
|
return _config?.windowedIndexing === true;
|
|
521
531
|
}
|
|
522
532
|
|
|
533
|
+
export function workerIndexEndingsEnabled(): boolean {
|
|
534
|
+
return _config?.workerIndexEndings === true;
|
|
535
|
+
}
|
|
536
|
+
|
|
523
537
|
/** True when the consumer has opted in to live streaming of chat turns. */
|
|
524
538
|
/** Socket delivery of the stream: the host asked (`liveStreaming`) AND the turn streams. */
|
|
525
539
|
/** Request status push is on: the host asked for it and handed over onRequestStatus. */
|
|
@@ -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 } from './time';
|
|
70
71
|
|
|
71
72
|
export type IndexingGroupStatus = 'active' | 'done' | 'error' | 'cancelled';
|
|
72
73
|
|
|
@@ -542,8 +543,12 @@ export function buildChatDisplayList(
|
|
|
542
543
|
// label-only behaviour stands, so the re-index case is unchanged.
|
|
543
544
|
var openId = openRunOfKey[key];
|
|
544
545
|
var notLater = false;
|
|
545
|
-
|
|
546
|
-
|
|
546
|
+
// A message's time is its _ts, else its request id's (messageTimeMs): a live
|
|
547
|
+
// worker pass adopted from the queue has no _ts, and without a time on both
|
|
548
|
+
// sides an OLDER first pass loaded after it split the run in two (2026-11-25).
|
|
549
|
+
var msgTime = messageTimeMs(msg);
|
|
550
|
+
if (openId && msgTime > 0 && typeof newestTsOfRun[openId] === 'number') {
|
|
551
|
+
notLater = msgTime <= newestTsOfRun[openId];
|
|
547
552
|
}
|
|
548
553
|
if (!ref.continued && !alreadySeen && !notLater && openRunOfKey[key]) delete openRunOfKey[key];
|
|
549
554
|
runId = openRunOfKey[key];
|
|
@@ -567,9 +572,10 @@ export function buildChatDisplayList(
|
|
|
567
572
|
// or a response whose request is not loaded) stays an ordinary message
|
|
568
573
|
// rather than being folded into whichever group happens to be nearest.
|
|
569
574
|
if (!runId) continue;
|
|
570
|
-
|
|
575
|
+
var memberTime = messageTimeMs(msg);
|
|
576
|
+
if (memberTime > 0) {
|
|
571
577
|
var prevTs = newestTsOfRun[runId];
|
|
572
|
-
if (typeof prevTs !== 'number' ||
|
|
578
|
+
if (typeof prevTs !== 'number' || memberTime > prevTs) newestTsOfRun[runId] = memberTime;
|
|
573
579
|
}
|
|
574
580
|
|
|
575
581
|
var g = groups[runId];
|
|
@@ -138,8 +138,8 @@ These three rules govern every claim about the project's data. They do not limit
|
|
|
138
138
|
// triggers: check again, then one of three outcomes, and a learned link
|
|
139
139
|
// changes only on proof (correctSearchLink with page and exact quote).
|
|
140
140
|
const documentRules =
|
|
141
|
-
`DOCUMENTS (a contract, a report, a manual, a letter, any uploaded file the user asks about the content of):
|
|
142
|
-
WRONG ANSWER: when the user says an answer is wrong (or sends "This answer seems wrong. Please check it again against the documents."), re-read the pages you cited and search again, passing searchText "question" = the user's ORIGINAL question that the disputed answer answered, never the complaint message itself. Then do exactly one of: correct the answer only; correct the answer and call correctSearchLink (when it is among your tools); or keep the answer and quote the text that supports it. Call correctSearchLink only with the page and an exact quote that prove it, and never change data on the user's word alone.`;
|
|
141
|
+
`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 총괄"), 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.
|
|
142
|
+
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.`;
|
|
143
143
|
|
|
144
144
|
// ---- Access group -----------------------------------------------------
|
|
145
145
|
// Trimmed 2026-11-23: the server's default-filling (an index or tag query auto-filled with
|
|
@@ -180,7 +180,7 @@ Scope: Only answer questions about this project and its data. Do not answer ques
|
|
|
180
180
|
Knowledge lookup: before saying you don't know, or that something isn't in the chat history, ALWAYS search this project's data with the tools: the project's data lives in its database, not in the earlier messages of this chat.
|
|
181
181
|
${groundingRules}
|
|
182
182
|
${webRule}
|
|
183
|
-
FINDING THE DATA: the database is the way in, for every kind of file.
|
|
183
|
+
FINDING THE DATA: the database is the way in, for every kind of file. A question about what the documents SAY (a procedure, a passage, a definition, how to fix or do something), or one that names a code, a number or a phrase to find (a quote no., a part no., a name), starts with searchText (DOCUMENTS below), not with getTables: the sheets of spreadsheets are in page text too. searchText finds WHICH file, sheet and row holds a value; a total, count or list over rows is still computed from the full row set (NUMBERS FROM A SPREADSHEET below). Everything else (numbers, rows, records, lists, counts, files) follows the search path in getTables' description, with one exception for this project: when getTables' one page is the whole list (end_of_list true), skip its table-name search even when no name fits: you already see every table, and a table is never named after a company, a person or a single fact, so when no table fits, the answer is in a document's text: use searchText (DOCUMENTS below). Pick EVERY table that could hold the answer, not the first that fits. Read getIndexes and getTags one page each, never with fetch_all: name and tag lists can be millions of characters long and are never read whole, so when the name is not on that page, search for it with the user's words as their descriptions say. Never call getTags with neither table_name nor tag: that lists every tag of every table. Then getRecords in that table and group with the selector that matched (an index, one exact tag, or none for the whole table), always with fetch_all true. WHERE INDEXED CONTENT LIVES: a document's extracted content (PDF, Word, slides, scans) is in table "document_entries", one record per row / entry / section, with its page in "page"; spreadsheet rows are in "spreadsheet_rows". Files indexed before 2026-11-20 may still hold theirs in other tables, so a file's records are found wherever they are with getRecords reference "src::<path>" (see the access group rule below); every later mention of a file's records means this call. Every stored file has a record whose unique_id is "src::<its storage path>", so getUniqueId with unique_id "src::" and condition "gte" lists every file across every table (add the start of a path to narrow it; condition "lte" with a file name alone finds it in any folder).
|
|
184
184
|
NUMBERS FROM A SPREADSHEET are computed from the ROWS, never from one page and never from a guess. Each row of each sheet is one record in its table: reference "src::<path>", unique_id "row::<path>#<sheet>#R<n>", the cells by header name, plus "_sheet", "_row", "_grain" ("detail" or "summary") and, on a total or preamble row, "_row_type". Its tags carry the file name, the sheet, the grain and up to four key values of the row (a name, a code), so getRecords with one exact tag selects every row about that thing across all the files in the table. Workbooks state the same money more than once: a detail sheet, then per-song, per-album and per-artist sheets that re-total it, plus a summary. Use rows whose "_grain" is "detail" and whose "_row_type" is not "total", pick ONE sheet per file and say which, and never add a sheet to its summary. Fetch the COMPLETE matching set, keep only the rows whose column or tag names what was asked, then add them up carefully, in groups, and check that the group sums agree with the grand total. A FILE TOTAL IS NOT A ROW'S TOTAL: the biggest number on a summary sheet is the whole file, not the thing asked about, so check every figure is scoped to what the question named (filter by the column that identifies it). Quote the row count, the sheet(s) and the file(s) the figure was made from and label it as calculated.
|
|
185
185
|
${documentRules}
|
|
186
186
|
${accessGroupRule}
|
|
@@ -32,13 +32,13 @@ export function buildIndexingSystemPrompt(params: IndexingSystemPromptParams): s
|
|
|
32
32
|
|
|
33
33
|
let systemPrompt =
|
|
34
34
|
`You are a background indexing agent for project ${projectId}.
|
|
35
|
-
- Image files (.jpg, .jpeg, .png, .gif, .webp) are ALREADY attached inline as image content blocks in the same message: look at them directly, and never fetch an image URL.
|
|
35
|
+
- Image files (.jpg, .jpeg, .png, .gif, .webp) are ALREADY attached inline as image content blocks in the same message: look at them directly, and never fetch an image URL. Any other image file (.tif, .tiff, .bmp, .heic) is attached only when the message shows an image of it (the server attaches a converted copy when it can); when none is attached, index it from its metadata and never guess its contents.
|
|
36
36
|
- Most files (office documents like .docx/.xlsx/.pptx/.hwp/.hwpx/.ods, email messages (.eml), and text/data/code files like .csv/.tsv/.json/.xml/.txt/.md and source code) have ALREADY been extracted on the server and included inline in the user message between the "BEGIN FILE CONTENT" / "END FILE CONTENT" markers - read that directly. If the inline content is a "[skapi: ...]" note, the file could not be extracted - index it from its metadata only.
|
|
37
37
|
- BIG SPREADSHEETS / TEXT: the inline content may be only the FIRST part of a large file (it can end with a truncation or "more remains" note). UNLESS this message already embeds a window of the file (in which case the message tells you not to call readFileContent, and you must not), read big spreadsheets and big text/data files WITH THE readFileContent TOOL: it returns the file ONE WINDOW at a time (spreadsheets as coordinate-tagged grid rows, text as a range of characters). Pass the file's storage path. After each window: datafy it into records and SAVE them, THEN if the window says MORE REMAINS call readFileContent again with the cursor it gives you. Repeat until it says END OF FILE, so the WHOLE file is indexed - never stop after the first window.
|
|
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
|
-
- 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", "tag_id" and "date". 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.
|
|
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).
|
|
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).
|
|
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.
|
|
@@ -56,6 +56,13 @@ export type BuildIndexingUserMessageOptions = {
|
|
|
56
56
|
* message instructs the agent to page through EVERY window and datafy each.
|
|
57
57
|
*/
|
|
58
58
|
pagedRead?: boolean;
|
|
59
|
+
/**
|
|
60
|
+
* An IMAGE file (2026-11-25). 'attached': the engine attaches it to this message as an
|
|
61
|
+
* image block (jpg/jpeg/png/gif/webp, the ones its image-URL pattern matches). 'maybe': a
|
|
62
|
+
* format the providers do not take (tif/tiff/bmp/heic); a newer worker attaches a
|
|
63
|
+
* converted copy, an older one attaches nothing, so the message never claims a picture.
|
|
64
|
+
*/
|
|
65
|
+
imageFile?: 'attached' | 'maybe';
|
|
59
66
|
};
|
|
60
67
|
|
|
61
68
|
/**
|
|
@@ -151,6 +158,19 @@ export function buildIndexingUserMessage(
|
|
|
151
158
|
);
|
|
152
159
|
}
|
|
153
160
|
|
|
161
|
+
if (options?.imageFile) {
|
|
162
|
+
// The URL line stays: the engine builds the image block from the URL it finds in this
|
|
163
|
+
// text. The fields named here are the ones the worker writes as the image's page text.
|
|
164
|
+
return (
|
|
165
|
+
head +
|
|
166
|
+
`- temporary URL: ${attachment.url}\n` +
|
|
167
|
+
(options.imageFile === 'attached'
|
|
168
|
+
? `\nThis is an IMAGE file, attached to this message as an image: read it there, not from the URL. `
|
|
169
|
+
: `\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". Then set "text_rotation" and "text_legibility" on the file's "src::" record, and only then describe what the image shows.`
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
|
|
154
174
|
return head + `- temporary URL (fetch this to read the file contents): ${attachment.url}`;
|
|
155
175
|
}
|
|
156
176
|
|
package/src/engine/requests.ts
CHANGED
|
@@ -573,6 +573,19 @@ export type ClaudeMcpServerRequest = {
|
|
|
573
573
|
const IMAGE_URL_REGEX =
|
|
574
574
|
/\bhttps?:\/\/[^\s<>"'()\[\]]+?\.(?:jpg|jpeg|png|gif|webp)(?:\?[^\s<>"'()\[\]]*)?/gi;
|
|
575
575
|
|
|
576
|
+
// An IMAGE file being indexed (2026-11-25), and whether its indexing message carries it as an
|
|
577
|
+
// image block. 'attached' only when the file's URL is one IMAGE_URL_REGEX turns into a block
|
|
578
|
+
// (so the message never claims a picture that is not there); 'maybe' for an image format the
|
|
579
|
+
// providers do not take, which a newer worker attaches as a converted copy and an older one
|
|
580
|
+
// does not attach at all; undefined for every other file.
|
|
581
|
+
const INDEX_IMAGE_OTHER_EXT = /\.(?:tiff?|bmp|heic|heif)$/i;
|
|
582
|
+
function indexingImageFile(attachment: { name?: string; storagePath?: string; url?: string }): 'attached' | 'maybe' | undefined {
|
|
583
|
+
const url = typeof attachment.url === 'string' ? attachment.url : '';
|
|
584
|
+
if (url && new RegExp(IMAGE_URL_REGEX.source, 'i').test(url)) return 'attached';
|
|
585
|
+
if (INDEX_IMAGE_OTHER_EXT.test(attachment.name || '') || INDEX_IMAGE_OTHER_EXT.test(attachment.storagePath || '')) return 'maybe';
|
|
586
|
+
return undefined;
|
|
587
|
+
}
|
|
588
|
+
|
|
576
589
|
export function transformContentWithImages(
|
|
577
590
|
content: string,
|
|
578
591
|
): string | Array<Record<string, any>> {
|
|
@@ -1397,8 +1410,30 @@ export async function notifyAgentSaveAttachment(info: AttachmentSaveInfo) {
|
|
|
1397
1410
|
// content arrives another way (server-side extraction, rendered pages) - the
|
|
1398
1411
|
// url still appears as the attachment link, and a dead link in front of the
|
|
1399
1412
|
// model is worth avoiding either way.
|
|
1413
|
+
// index_end (2026-11-25): a file read in ONE pass (an image, or any file not rendered,
|
|
1414
|
+
// windowed or paged) has no chain for the worker to end, so its done:: and run:: were
|
|
1415
|
+
// written only by a page that saw the pass settle, and a page closed or opened mid-pass
|
|
1416
|
+
// left it 'working' or flipped it to "the page was closed". With the flag the worker writes
|
|
1417
|
+
// the ending itself (an older worker ignores the key). The client still writes its own,
|
|
1418
|
+
// with the same verdict rule, so the two never disagree.
|
|
1419
|
+
const singlePass = !visionFile && !windowedRead && !pagedRead && !continuing;
|
|
1420
|
+
// An IMAGE file read in this one pass (2026-11-25): its message asks for a transcription at
|
|
1421
|
+
// any angle plus text_rotation, and claims an attached image only when this engine attaches
|
|
1422
|
+
// one (see indexingImageFile). On OpenAI the entry also carries the image `detail` the
|
|
1423
|
+
// model takes, for the image block a newer worker adds for a converted TIFF (an older
|
|
1424
|
+
// worker ignores the key).
|
|
1425
|
+
const imageFile = singlePass && !parsedContent && !serverExtract ? indexingImageFile(attachment) : undefined;
|
|
1426
|
+
const fileUrlDetail = imageFile && platform === 'openai'
|
|
1427
|
+
? getOpenAIImageDetail(info.model || DEFAULT_OPENAI_MODEL)
|
|
1428
|
+
: undefined;
|
|
1400
1429
|
const skapiFileUrls = attachment.url && attachment.storagePath
|
|
1401
|
-
? {
|
|
1430
|
+
? {
|
|
1431
|
+
_skapi_file_urls: [{
|
|
1432
|
+
path: attachment.storagePath, url: attachment.url,
|
|
1433
|
+
...(singlePass ? { index_end: true } : {}),
|
|
1434
|
+
...(fileUrlDetail ? { detail: fileUrlDetail } : {}),
|
|
1435
|
+
}],
|
|
1436
|
+
}
|
|
1402
1437
|
: {};
|
|
1403
1438
|
|
|
1404
1439
|
const userMessage = (visionFile && renderPlaceholder)
|
|
@@ -1415,7 +1450,9 @@ export async function notifyAgentSaveAttachment(info: AttachmentSaveInfo) {
|
|
|
1415
1450
|
? { inlineContentPlaceholder: placeholder }
|
|
1416
1451
|
: pagedRead
|
|
1417
1452
|
? { pagedRead: true }
|
|
1418
|
-
:
|
|
1453
|
+
: imageFile
|
|
1454
|
+
? { imageFile }
|
|
1455
|
+
: undefined,
|
|
1419
1456
|
);
|
|
1420
1457
|
|
|
1421
1458
|
const systemPrompt = buildIndexingSystemPrompt({
|
|
@@ -39,7 +39,8 @@
|
|
|
39
39
|
|
|
40
40
|
import { normalizeStoredPathTarget, normalizeTrailingInlineToken } from './links';
|
|
41
41
|
|
|
42
|
-
|
|
42
|
+
/** sheet: the hit was on a spreadsheet's sheet page (MCP 2026-11-25), whose page number means nothing to a reader. */
|
|
43
|
+
export type RetrievalHit = { path: string; page: number; sheet?: string };
|
|
43
44
|
|
|
44
45
|
export type RetrievalNote = {
|
|
45
46
|
/** Storage paths (the part after "src::") the turn read, queried or linked. */
|
|
@@ -97,16 +98,21 @@ function pushGroup(list: string[], value: unknown): void {
|
|
|
97
98
|
else pushUnique(list, value);
|
|
98
99
|
}
|
|
99
100
|
|
|
100
|
-
function pushHit(list: RetrievalHit[], path: unknown, page: unknown): void {
|
|
101
|
+
function pushHit(list: RetrievalHit[], path: unknown, page: unknown, sheet?: unknown): void {
|
|
101
102
|
if (typeof path !== 'string' || !path.trim()) return;
|
|
102
103
|
var n = typeof page === 'number' ? page : Number(page);
|
|
103
104
|
if (!isFinite(n) || n <= 0) return;
|
|
104
105
|
n = Math.floor(n);
|
|
106
|
+
var sh = typeof sheet === 'string' && sheet.trim() ? sheet.trim() : '';
|
|
105
107
|
for (var i = 0; i < list.length; i++) {
|
|
106
|
-
|
|
108
|
+
// one slot per sheet, whatever page of it was hit: several pages of one sheet must not
|
|
109
|
+
// crowd the document hits out of the note
|
|
110
|
+
if (sh ? (list[i].path === path && list[i].sheet === sh) : (list[i].path === path && list[i].page === n)) return;
|
|
107
111
|
}
|
|
108
112
|
if (list.length >= RETRIEVAL_NOTE_MAX_ITEMS) return;
|
|
109
|
-
|
|
113
|
+
var hit: RetrievalHit = { path: path.trim(), page: n };
|
|
114
|
+
if (sh) hit.sheet = sh;
|
|
115
|
+
list.push(hit);
|
|
110
116
|
}
|
|
111
117
|
|
|
112
118
|
/** A storage path out of a src:: id, or null when the value is not one. */
|
|
@@ -161,7 +167,7 @@ function readHits(note: RetrievalNote, result: any): void {
|
|
|
161
167
|
return;
|
|
162
168
|
}
|
|
163
169
|
if (typeof node.path === 'string' && node.page !== undefined) {
|
|
164
|
-
pushHit(note.hits, node.path, node.page);
|
|
170
|
+
pushHit(note.hits, node.path, node.page, node.sheet);
|
|
165
171
|
}
|
|
166
172
|
for (var k in node) {
|
|
167
173
|
if (!Object.prototype.hasOwnProperty.call(node, k)) continue;
|
|
@@ -353,8 +359,17 @@ export function formatRetrievalNote(note: RetrievalNote | null | undefined): str
|
|
|
353
359
|
if (!byFile[h.path]) { byFile[h.path] = []; order.push(h.path); }
|
|
354
360
|
byFile[h.path].push(h.page);
|
|
355
361
|
}
|
|
362
|
+
// A spreadsheet hit is named by its sheet: its page number is no place a reader can open.
|
|
363
|
+
var sheetsOf: Record<string, string[]> = {};
|
|
364
|
+
for (var s2 = 0; s2 < note.hits.length; s2++) {
|
|
365
|
+
var hs = note.hits[s2];
|
|
366
|
+
if (hs.sheet) {
|
|
367
|
+
if (!sheetsOf[hs.path]) sheetsOf[hs.path] = [];
|
|
368
|
+
if (sheetsOf[hs.path].indexOf(hs.sheet) === -1) sheetsOf[hs.path].push(hs.sheet);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
356
371
|
parts.push('searchText hits ' + order.map(function (p) {
|
|
357
|
-
return p + ' p' + byFile[p].join(', p');
|
|
372
|
+
return sheetsOf[p] ? p + ' sheet ' + sheetsOf[p].join(', sheet ') : p + ' p' + byFile[p].join(', p');
|
|
358
373
|
}).join('; '));
|
|
359
374
|
}
|
|
360
375
|
if (note.tools.length) parts.push('tools ' + note.tools.join(', '));
|
package/src/engine/session.ts
CHANGED
|
@@ -45,7 +45,7 @@ import {
|
|
|
45
45
|
type BgTaskEntry,
|
|
46
46
|
} from './requests';
|
|
47
47
|
import { isPagedReadFile, isImageVisionFile, isWindowedReadFile } from './office';
|
|
48
|
-
import { windowedIndexingEnabled, liveStreamingEnabled, streamRecoveryEnabled, chatEngineConfig, resolveForwardRequestFinalize, resolveForwardRequestStream, resolveSkipDuplicateFiles, statusPushEnabled, statusPushLive, resolveForwardRequestStatus, resolveForwardRequestRead, resolveForwardRequestQueueCounters, reconcilerReadsEnabled, crefSupported } from './config';
|
|
48
|
+
import { windowedIndexingEnabled, workerIndexEndingsEnabled, liveStreamingEnabled, streamRecoveryEnabled, chatEngineConfig, resolveForwardRequestFinalize, resolveForwardRequestStream, resolveSkipDuplicateFiles, statusPushEnabled, statusPushLive, resolveForwardRequestStatus, resolveForwardRequestRead, resolveForwardRequestQueueCounters, reconcilerReadsEnabled, crefSupported } from './config';
|
|
49
49
|
// The reconciler's clock (one timer chain per page) and the cross-tab settle lock. What a
|
|
50
50
|
// look reads and applies is this file's (_reconcileLook).
|
|
51
51
|
import { LookScheduler, LOOK_STALE_MS, runSettleSideEffect, claimSideEffect, sideEffectDone, newClientRef, queueNameOf, type LookRequest, type LookOutcome, type LookTrigger } from './reconciler';
|
|
@@ -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.';
|
|
@@ -1311,6 +1294,9 @@ export class ChatSession {
|
|
|
1311
1294
|
private _recordLiveIndexKeys(lists: any[]): void {
|
|
1312
1295
|
var next: { [k: string]: boolean } = {};
|
|
1313
1296
|
var running: { [k: string]: boolean } = {};
|
|
1297
|
+
// Every listed pending/running indexing row, locally settled or not (see _flipIfChainLost:
|
|
1298
|
+
// a run the server still lists is never "lost", whatever this page's bubbles say).
|
|
1299
|
+
var rawListed: { [k: string]: boolean } = {};
|
|
1314
1300
|
// A page that came back FULL is not a whole-queue answer: the query is capped
|
|
1315
1301
|
// and ordered newest-first, so a bulk upload of 40 files returns the 20 newest
|
|
1316
1302
|
// and omits the 20 about to run. Absence would then read as "finished" for
|
|
@@ -1347,6 +1333,11 @@ export class ChatSession {
|
|
|
1347
1333
|
for (var i = 0; i < list.length; i++) {
|
|
1348
1334
|
var item = list[i];
|
|
1349
1335
|
if (!item || (item.status !== 'pending' && item.status !== 'running')) continue;
|
|
1336
|
+
var rawRef = parseIndexingRequestText(listedRequestText(item));
|
|
1337
|
+
if (rawRef) {
|
|
1338
|
+
if (rawRef.path) rawListed[rawRef.path] = true;
|
|
1339
|
+
if (rawRef.name) rawListed[rawRef.name] = true;
|
|
1340
|
+
}
|
|
1350
1341
|
if (item.id && settledIds[item.id]) continue;
|
|
1351
1342
|
// A compact listing (probeBgQueue) carries the label as request_text.
|
|
1352
1343
|
var text = listedRequestText(item);
|
|
@@ -1381,6 +1372,7 @@ export class ChatSession {
|
|
|
1381
1372
|
if (!changed) for (var r2 in wasRun) if (!running[r2]) { changed = true; break; }
|
|
1382
1373
|
}
|
|
1383
1374
|
this.state.liveIndexKeys = next;
|
|
1375
|
+
this._rawListedIndexKeys = rawListed;
|
|
1384
1376
|
if (this.state.liveIndexRunningChecked !== !runningTruncated) changed = true;
|
|
1385
1377
|
// Files seen to LEAVE the queue: live in the previous look, absent from a complete
|
|
1386
1378
|
// one. Kept until the file is live again, so a later look that comes back cut off
|
|
@@ -5955,21 +5947,43 @@ export class ChatSession {
|
|
|
5955
5947
|
* worker-driven file (the worker writes its endings), another user's run (their chain is
|
|
5956
5948
|
* in their browser), or a run whose next pass is being looked for.
|
|
5957
5949
|
*/
|
|
5958
|
-
|
|
5950
|
+
/** Files the last queue look listed pending or running, settled bubbles included. */
|
|
5951
|
+
private _rawListedIndexKeys: { [k: string]: boolean } = {};
|
|
5952
|
+
/** Runs found idle on one complete look, waiting for a second before "lost" (see below). */
|
|
5953
|
+
private _lostLooks: { [k: string]: number } = {};
|
|
5954
|
+
private _lostKey(run: FileRun): string { return run.projectId + '\u0000' + run.storagePath + '\u0000' + run.since; }
|
|
5955
|
+
|
|
5956
|
+
private _flipIfChainLost(run: FileRun): boolean {
|
|
5959
5957
|
var self = this;
|
|
5960
|
-
if (!run.owner) return;
|
|
5958
|
+
if (!run.owner) return false;
|
|
5959
|
+
// The server still lists a pass of it (pending or running), under its path or its file
|
|
5960
|
+
// name: not lost, whatever this page's bubbles say (2026-11-25: a TIF whose pass the
|
|
5961
|
+
// worker was running was flipped by a chat page that had just opened).
|
|
5962
|
+
var raw = this._rawListedIndexKeys || {};
|
|
5963
|
+
if (raw[run.storagePath] || (run.filename && raw[run.filename])) {
|
|
5964
|
+
delete this._lostLooks[this._lostKey(run)];
|
|
5965
|
+
return true;
|
|
5966
|
+
}
|
|
5967
|
+
// Idle on TWO complete looks in a row, not one: the status index is eventually
|
|
5968
|
+
// consistent, and one look can miss a row that was just written.
|
|
5969
|
+
var lk = this._lostKey(run);
|
|
5970
|
+
if (!this._lostLooks[lk]) { this._lostLooks[lk] = 1; return true; }
|
|
5971
|
+
delete this._lostLooks[lk];
|
|
5961
5972
|
var live: ChatIdentity | null = null;
|
|
5962
5973
|
try { live = this.host.getIdentity(); } catch (e) { live = null; }
|
|
5963
|
-
if (!live || !live.userId || live.userId !== run.owner || live.projectId !== run.projectId) return;
|
|
5974
|
+
if (!live || !live.userId || live.userId !== run.owner || live.projectId !== run.projectId) return false;
|
|
5964
5975
|
var name = run.filename || run.storagePath.split('/').pop() || run.storagePath;
|
|
5965
|
-
if (this._isWorkerDrivenIndexing(name, undefined)) return;
|
|
5966
|
-
|
|
5976
|
+
if (this._isWorkerDrivenIndexing(name, undefined)) return false;
|
|
5977
|
+
// A single-pass file's ending is the worker's to write (index_end) once the host says
|
|
5978
|
+
// every region's worker does so: nothing here may call it lost.
|
|
5979
|
+
if (workerIndexEndingsEnabled() && !isPagedReadFile(name, undefined)) return false;
|
|
5980
|
+
if (this._chainKept(run.projectId, run.storagePath)) return false;
|
|
5967
5981
|
for (var q = 0; q < this.bgTaskQueue.length; q++) {
|
|
5968
5982
|
var e = this.bgTaskQueue[q];
|
|
5969
|
-
if (e && e.projectId === run.projectId && e.storagePath === run.storagePath) return;
|
|
5983
|
+
if (e && e.projectId === run.projectId && e.storagePath === run.storagePath) return false;
|
|
5970
5984
|
}
|
|
5971
5985
|
if (this._recPending) for (var c in this._recPending) {
|
|
5972
|
-
if (this._recPending[c].kind === 'indexing' && this._recPending[c].projectId === run.projectId) return;
|
|
5986
|
+
if (this._recPending[c].kind === 'indexing' && this._recPending[c].projectId === run.projectId) return false;
|
|
5973
5987
|
}
|
|
5974
5988
|
var projectId = run.projectId, path = run.storagePath;
|
|
5975
5989
|
runSettleSideEffect(projectId, bgIndexingQueueName(live.userId, projectId), 'lost:' + projectId + ':' + path + ':' + run.since, function () {
|
|
@@ -5980,6 +5994,7 @@ export class ChatSession {
|
|
|
5980
5994
|
}
|
|
5981
5995
|
});
|
|
5982
5996
|
});
|
|
5997
|
+
return false;
|
|
5983
5998
|
}
|
|
5984
5999
|
|
|
5985
6000
|
/** A file run the queue says is live, or that this page has a pass queued for. */
|
|
@@ -6011,8 +6026,9 @@ export class ChatSession {
|
|
|
6011
6026
|
var closed: string[] = [];
|
|
6012
6027
|
for (var k in runs) {
|
|
6013
6028
|
if (runs[k].projectId !== projectId || this._fileRunLive(runs[k])) continue;
|
|
6029
|
+
// still listed by the server, or idle on only one look so far: kept open
|
|
6030
|
+
if (this._flipIfChainLost(runs[k])) continue;
|
|
6014
6031
|
closed.push(runs[k].storagePath);
|
|
6015
|
-
this._flipIfChainLost(runs[k]);
|
|
6016
6032
|
delete runs[k];
|
|
6017
6033
|
if (!this._fileRunsIdle) this._fileRunsIdle = {};
|
|
6018
6034
|
this._fileRunsIdle[k] = true;
|
|
@@ -7569,15 +7585,18 @@ export class ChatSession {
|
|
|
7569
7585
|
});
|
|
7570
7586
|
}
|
|
7571
7587
|
|
|
7572
|
-
/** Insert bubbles before the first message that is newer than them
|
|
7573
|
-
*
|
|
7588
|
+
/** Insert bubbles before the first message that is newer than them; messages whose time
|
|
7589
|
+
* is unknown are skipped over, and the end of the list takes them otherwise. A message's
|
|
7590
|
+
* time is its `_ts`, else (2026-11-25) the time in its request id: a live worker pass
|
|
7591
|
+
* adopted from the queue carries no `_ts`, and a file's older passes loaded by opening its
|
|
7592
|
+
* row (loadRunPasses) used to land AFTER it, which split one run into two rows. */
|
|
7574
7593
|
private _insertByTime(bubbles: ChatMessage[]): void {
|
|
7575
|
-
var at = bubbles[0]
|
|
7594
|
+
var at = messageTimeMs(bubbles[0]);
|
|
7576
7595
|
var idx = this.state.messages.length;
|
|
7577
|
-
if (
|
|
7596
|
+
if (at > 0) {
|
|
7578
7597
|
for (var i = 0; i < this.state.messages.length; i++) {
|
|
7579
|
-
var t = this.state.messages[i]
|
|
7580
|
-
if (
|
|
7598
|
+
var t = messageTimeMs(this.state.messages[i]);
|
|
7599
|
+
if (t > 0 && t > at) { idx = i; break; }
|
|
7581
7600
|
}
|
|
7582
7601
|
}
|
|
7583
7602
|
Array.prototype.splice.apply(this.state.messages, ([idx, 0] as any[]).concat(bubbles));
|
package/src/engine/time.ts
CHANGED
|
@@ -61,3 +61,39 @@ export function formatDuration(ms?: number): string {
|
|
|
61
61
|
out.push(s + 's');
|
|
62
62
|
return out.join(' ');
|
|
63
63
|
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Creation time (ms epoch) of a request id "stamp:entropy", whose stamp is a time_ns written
|
|
67
|
+
* as 8 bytes of base32hex without padding (the worker's and the producer's _generate_req_id).
|
|
68
|
+
* 0 when it is not one.
|
|
69
|
+
*/
|
|
70
|
+
export function requestIdTimeMs(rid: string): number {
|
|
71
|
+
if (typeof rid !== 'string') return 0;
|
|
72
|
+
var stamp = rid.split(':')[0] || '';
|
|
73
|
+
if (stamp.length !== 13) return 0;
|
|
74
|
+
var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUV';
|
|
75
|
+
var v = 0;
|
|
76
|
+
for (var i = 0; i < stamp.length; i++) {
|
|
77
|
+
var d = alphabet.indexOf(stamp.charAt(i).toUpperCase());
|
|
78
|
+
if (d < 0) return 0;
|
|
79
|
+
v = v * 32 + d;
|
|
80
|
+
}
|
|
81
|
+
// 13 digits are 65 bits for 64 of data: the last bit is padding.
|
|
82
|
+
return Math.floor(v / 2 / 1e6);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* A chat message's time in epoch ms, for ORDERING and grouping (never for display): the time
|
|
87
|
+
* in its request id (`_serverItemId`, "stamp:entropy", the server's clock) when it has one,
|
|
88
|
+
* else its `_ts`, else 0 (unknown). Request-id first so every comparison uses one clock: a
|
|
89
|
+
* live-settled reply's `_ts` is the browser's Date.now(), and mixing the two let a browser
|
|
90
|
+
* running ahead of the server fold a re-index into the previous run. A request and its reply
|
|
91
|
+
* share one id, so nothing is ever ordered between them. A live background pass adopted from
|
|
92
|
+
* the queue has no `_ts` at all until it settles.
|
|
93
|
+
*/
|
|
94
|
+
export function messageTimeMs(m: { _ts?: number; _serverItemId?: string } | null | undefined): number {
|
|
95
|
+
if (!m) return 0;
|
|
96
|
+
var r = typeof m._serverItemId === 'string' ? requestIdTimeMs(m._serverItemId) : 0;
|
|
97
|
+
if (r > 0) return r;
|
|
98
|
+
return typeof m._ts === 'number' && m._ts > 0 ? m._ts : 0;
|
|
99
|
+
}
|