bunnyquery 1.20.1 → 1.21.3

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.
@@ -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.52__" beats nothing. Only when a character is genuinely unreadable, leave that field null or mark the unreadable span - do NOT invent it, 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).
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
 
@@ -0,0 +1,594 @@
1
+ /**
2
+ * The reconciler's clock and the cross-tab settle lock (reconciler plan, sections 3 and 4b,
3
+ * BUNNYQUERY_CHAT_RECONCILER_PLAN.md).
4
+ *
5
+ * WHAT LIVES HERE. Only the parts that know nothing about chats: one timer chain per page
6
+ * (LookScheduler), the triggers that pull its next look forward, the deadline and the
7
+ * generation that make a hung look harmless, the backoff after a failed look, and the lock
8
+ * that keeps side effects (a next indexing pass, run::/done:: writes, a finalize, a records
9
+ * refresh) to one tab. What a look actually reads and applies is ChatSession's
10
+ * (_reconcileLook in session.ts), handed in as a hook, so this file is testable on its own
11
+ * and the session keeps its own state private.
12
+ *
13
+ * THE RULES IT ENFORCES (owner, 2026-11-24, plan 4b):
14
+ * 1. One loop. One setTimeout handle for the whole page, whatever the number of waiting
15
+ * requests. Scheduling always clears the previous handle first.
16
+ * 2. Returns never add work. A trigger while a look runs sets ONE follow-up look (the
17
+ * triggers are merged), never a second loop or a second timer. A trigger while no look
18
+ * runs starts the look now.
19
+ * 3. A look that does not finish within LOOK_DEADLINE_MS is over: it counts as failed
20
+ * (nothing on screen changes), its in-flight reads are aborted, and anything its
21
+ * generation returns later is ignored by the session (alive() is false).
22
+ */
23
+
24
+ /** How long one look may take in all. */
25
+ export const LOOK_DEADLINE_MS = 15 * 1000;
26
+ /** The visible cadence while anything is waiting. */
27
+ export const LOOK_FAST_MS = 3 * 1000;
28
+ /** The visible cadence while request status frames arrive (statusPush), and the hidden
29
+ * cadence while a client-driven indexing chain is open. */
30
+ export const LOOK_SLOW_MS = 60 * 1000;
31
+ /** Re-read every open item at least this often, whatever the queue counters say. */
32
+ export const LOOK_STALE_MS = 60 * 1000;
33
+ /** A timer that fires this much later than asked, in a visible tab, means the computer slept. */
34
+ const WAKE_GAP_MS = 30 * 1000;
35
+ /** Backoff after a failed look: 1, 2, 4 ... capped here. */
36
+ const BACKOFF_MAX_MS = 30 * 1000;
37
+
38
+ /** Why a look runs. Several merge into one look. */
39
+ export type LookTrigger =
40
+ | 'tick' | 'return' | 'visible' | 'wake' | 'online' | 'pageshow' | 'reconnect' | 'view'
41
+ | 'frame' | 'unknown' | 'promote' | 'send' | 'signin' | 'add';
42
+
43
+ /** The triggers that mean "the user may have been away": live readers are stopped and
44
+ * restarted, the discovery listing and the first page are read. */
45
+ var RETURN_TRIGGERS: { [k: string]: true } = {
46
+ return: true, visible: true, wake: true, online: true, pageshow: true, reconnect: true, view: true, unknown: true, signin: true,
47
+ };
48
+
49
+ export function isReturnTrigger(t: string): boolean {
50
+ return !!RETURN_TRIGGERS[t];
51
+ }
52
+
53
+ /** One look as the session sees it. */
54
+ export type LookRequest = {
55
+ /** Generation: grows by one per look. */
56
+ gen: number;
57
+ triggers: { [k: string]: true };
58
+ /** Any trigger was a return (see RETURN_TRIGGERS). */
59
+ isReturn: boolean;
60
+ /** Aborts every read of this look at its deadline (undefined without AbortController). */
61
+ signal: any;
62
+ /** False once the deadline passed or a newer look started: drop every result. */
63
+ alive: () => boolean;
64
+ /** Milliseconds left before the deadline (at least 1). */
65
+ remaining: () => number;
66
+ };
67
+
68
+ /** How a look ended: 'ok' (it read what it needed), 'transient' (a read failed on the way:
69
+ * backoff, nothing changed), 'auth' (the sign-in is gone), 'idle' (nothing to do). */
70
+ export type LookOutcome = 'ok' | 'transient' | 'auth' | 'idle';
71
+
72
+ export interface LookHooks {
73
+ /** Run one look. Never called twice at once. */
74
+ runLook(req: LookRequest): Promise<LookOutcome>;
75
+ /** Is there anything to follow: `visible` = anything at all (the 3 s cadence), `hidden`
76
+ * = something worth a look once a minute while the tab is hidden. */
77
+ work(): { visible: boolean; hidden: boolean };
78
+ /** Status frames are arriving (statusPush): the visible cadence slows to a minute. */
79
+ pushLive(): boolean;
80
+ /** The reconnecting / sign-in flags changed (for the views). */
81
+ onFlags(flags: { reconnecting: boolean; signInNeeded: boolean }): void;
82
+ }
83
+
84
+ var _g: any = typeof globalThis !== 'undefined' ? globalThis : {};
85
+
86
+ function perfNow(): number {
87
+ return (_g.performance && typeof _g.performance.now === 'function') ? _g.performance.now() : Date.now();
88
+ }
89
+
90
+ function tabHidden(): boolean {
91
+ var doc: any = _g.document;
92
+ return !!doc && doc.visibilityState === 'hidden';
93
+ }
94
+
95
+ /**
96
+ * The one timer chain. See the file note for the rules.
97
+ */
98
+ export class LookScheduler {
99
+ private hooks: LookHooks;
100
+ private timer: any = null;
101
+ /** When the pending timer should fire, on both clocks (wake detection). */
102
+ private expectPerf = 0;
103
+ private expectWall = 0;
104
+ private running = false;
105
+ /** Triggers that arrived while a look ran: exactly one more look runs with them. */
106
+ private pending: { [k: string]: true } | null = null;
107
+ /** Resolvers of trigger() promises, by the look that will serve them. */
108
+ private waitCurrent: Array<() => void> = [];
109
+ private waitNext: Array<() => void> = [];
110
+ private backoff = 0;
111
+ private listening = false;
112
+ private stopped = false;
113
+ gen = 0;
114
+ reconnecting = false;
115
+ signInNeeded = false;
116
+ /** Diagnostics (and the throwaway checks): looks started, timers armed. */
117
+ looks = 0;
118
+ timersArmed = 0;
119
+
120
+ constructor(hooks: LookHooks) {
121
+ this.hooks = hooks;
122
+ }
123
+
124
+ /** Pull the next look forward to now. Resolves when the look that serves it ends. */
125
+ trigger(kind: LookTrigger): Promise<void> {
126
+ var self = this;
127
+ this.stopped = false;
128
+ this._listen();
129
+ return new Promise<void>(function (resolve) {
130
+ if (self.running) {
131
+ if (!self.pending) self.pending = {};
132
+ self.pending[kind] = true;
133
+ self.waitNext.push(resolve);
134
+ return;
135
+ }
136
+ // Started on the next turn of the event loop, so the triggers one event fires
137
+ // at once (the tab shown: this listener, the host's own handler, a socket that
138
+ // reconnects with it) are one look, not a look and a follow-up.
139
+ if (!self.starting) {
140
+ self.starting = {};
141
+ setTimeout(function () {
142
+ var t = self.starting || {};
143
+ self.starting = null;
144
+ if (self.running) {
145
+ // Something started a look meanwhile: these ride on its follow-up.
146
+ if (!self.pending) self.pending = {};
147
+ for (var k in t) self.pending[k] = true;
148
+ self.waitNext = self.waitNext.concat(self.waitStarting);
149
+ self.waitStarting = [];
150
+ return;
151
+ }
152
+ self.waitCurrent = self.waitCurrent.concat(self.waitStarting);
153
+ self.waitStarting = [];
154
+ self._start(t);
155
+ }, 0);
156
+ }
157
+ self.starting[kind] = true;
158
+ self.waitStarting.push(resolve);
159
+ });
160
+ }
161
+
162
+ /** Triggers gathered for a look about to start (see trigger). */
163
+ private starting: { [k: string]: true } | null = null;
164
+ private waitStarting: Array<() => void> = [];
165
+
166
+ /** Make sure the chain runs at its cadence when there is work. Never adds a timer when
167
+ * one is armed or a look is running, so calling it from every add is free. */
168
+ ensure(): void {
169
+ this.stopped = false;
170
+ this._listen();
171
+ if (this.running || this.timer || this.starting) return;
172
+ this._scheduleNext('ok');
173
+ }
174
+
175
+ /** The sign-in came back (or the host says so): looks resume at once. */
176
+ signedIn(): void {
177
+ if (!this.signInNeeded) { this.ensure(); return; }
178
+ this.signInNeeded = false;
179
+ this.backoff = 0;
180
+ this._flags();
181
+ void this.trigger('signin');
182
+ }
183
+
184
+ /** Stop the chain (tests, teardown). A later trigger or ensure starts it again. */
185
+ stop(): void {
186
+ this.stopped = true;
187
+ if (this.timer) { clearTimeout(this.timer); this.timer = null; }
188
+ }
189
+
190
+ isRunning(): boolean {
191
+ return this.running;
192
+ }
193
+
194
+ private _flags(): void {
195
+ try { this.hooks.onFlags({ reconnecting: this.reconnecting, signInNeeded: this.signInNeeded }); } catch (e) { /* view hook */ }
196
+ }
197
+
198
+ private _listen(): void {
199
+ if (this.listening) return;
200
+ this.listening = true;
201
+ var self = this;
202
+ var doc: any = _g.document;
203
+ if (doc && typeof doc.addEventListener === 'function') {
204
+ doc.addEventListener('visibilitychange', function () {
205
+ if (doc.visibilityState === 'hidden') {
206
+ // Re-arm at the hidden cadence (or not at all): a 3 s timer in a hidden
207
+ // tab only gets throttled and then reads as a wake.
208
+ if (!self.running && self.timer) { clearTimeout(self.timer); self.timer = null; self._scheduleNext('ok'); }
209
+ return;
210
+ }
211
+ void self.trigger('visible');
212
+ });
213
+ }
214
+ var win: any = _g.window;
215
+ if (win && typeof win.addEventListener === 'function') {
216
+ win.addEventListener('online', function () { if (!tabHidden()) void self.trigger('online'); });
217
+ win.addEventListener('pageshow', function (ev: any) { if (ev && ev.persisted) void self.trigger('pageshow'); });
218
+ }
219
+ }
220
+
221
+ private _start(triggers: { [k: string]: true }): void {
222
+ var self = this;
223
+ if (this.timer) { clearTimeout(this.timer); this.timer = null; }
224
+ this.running = true;
225
+ var gen = ++this.gen;
226
+ this.looks++;
227
+ var isReturn = false;
228
+ for (var k in triggers) if (RETURN_TRIGGERS[k]) isReturn = true;
229
+ var ac: any = typeof _g.AbortController === 'function' ? new _g.AbortController() : null;
230
+ var startedAt = perfNow();
231
+ var done = false;
232
+ var deadline = setTimeout(function () {
233
+ if (done) return;
234
+ done = true;
235
+ try { if (ac) ac.abort(); } catch (e) { /* best effort */ }
236
+ console.warn('[chat-engine] a reconciler look ran past its deadline; nothing it read is applied');
237
+ self._finish('transient');
238
+ }, LOOK_DEADLINE_MS);
239
+ var req: LookRequest = {
240
+ gen: gen,
241
+ triggers: triggers,
242
+ isReturn: isReturn,
243
+ signal: ac ? ac.signal : undefined,
244
+ alive: function () { return !done && self.gen === gen; },
245
+ remaining: function () { return Math.max(1, Math.round(LOOK_DEADLINE_MS - (perfNow() - startedAt))); },
246
+ };
247
+ var run: Promise<LookOutcome>;
248
+ try { run = Promise.resolve(this.hooks.runLook(req)); } catch (e) { run = Promise.reject(e); }
249
+ run.then(function (outcome) {
250
+ if (done) return;
251
+ done = true;
252
+ clearTimeout(deadline);
253
+ self._finish(outcome || 'ok');
254
+ }, function (err) {
255
+ if (done) return;
256
+ done = true;
257
+ clearTimeout(deadline);
258
+ console.warn('[chat-engine] a reconciler look threw', err);
259
+ self._finish('transient');
260
+ });
261
+ }
262
+
263
+ private _finish(outcome: LookOutcome): void {
264
+ this.running = false;
265
+ var served = this.waitCurrent;
266
+ this.waitCurrent = [];
267
+ if (outcome === 'transient') {
268
+ this.backoff = this.backoff ? Math.min(BACKOFF_MAX_MS, this.backoff * 2) : 1000;
269
+ if (!this.reconnecting) { this.reconnecting = true; this._flags(); }
270
+ } else if (outcome === 'auth') {
271
+ this.backoff = 0;
272
+ var changed = !this.signInNeeded || this.reconnecting;
273
+ this.signInNeeded = true;
274
+ this.reconnecting = false;
275
+ if (changed) this._flags();
276
+ } else {
277
+ this.backoff = 0;
278
+ if (this.reconnecting || this.signInNeeded) {
279
+ this.reconnecting = false;
280
+ this.signInNeeded = false;
281
+ this._flags();
282
+ }
283
+ }
284
+ for (var i = 0; i < served.length; i++) { try { served[i](); } catch (e) { /* caller */ } }
285
+ if (this.pending) {
286
+ // Exactly one more look, carrying every trigger that came in meanwhile.
287
+ var next = this.pending;
288
+ this.pending = null;
289
+ this.waitCurrent = this.waitNext;
290
+ this.waitNext = [];
291
+ this._start(next);
292
+ return;
293
+ }
294
+ this._scheduleNext(outcome);
295
+ }
296
+
297
+ private scheduling = false;
298
+
299
+ private _scheduleNext(outcome: LookOutcome): void {
300
+ // work() may add items, and adding an item calls ensure(): never re-enter.
301
+ if (this.stopped || this.scheduling) return;
302
+ this.scheduling = true;
303
+ try { this._arm(outcome); } finally { this.scheduling = false; }
304
+ }
305
+
306
+ private _arm(outcome: LookOutcome): void {
307
+ if (this.timer) { clearTimeout(this.timer); this.timer = null; }
308
+ var hidden = tabHidden();
309
+ // A hook that throws must not end the chain (nothing would arm a timer again):
310
+ // taken as "something to follow", at the visible cadence.
311
+ var work: { visible: boolean; hidden: boolean };
312
+ try { work = this.hooks.work(); } catch (e) { work = { visible: true, hidden: false }; }
313
+ var delay = -1;
314
+ if (this.signInNeeded) {
315
+ // Nothing can be read until the sign-in is back. One cheap try a minute while
316
+ // someone is looking, and at once on any trigger or signedIn().
317
+ if (!hidden && work.visible) delay = LOOK_SLOW_MS;
318
+ } else if (outcome === 'transient' && this.backoff) {
319
+ if ((!hidden && work.visible) || work.hidden) delay = hidden ? Math.max(this.backoff, LOOK_SLOW_MS) : this.backoff;
320
+ } else if (!hidden && work.visible) {
321
+ var live = false;
322
+ try { live = this.hooks.pushLive(); } catch (e) { live = false; }
323
+ delay = live ? LOOK_SLOW_MS : LOOK_FAST_MS;
324
+ } else if (hidden && work.hidden) {
325
+ delay = LOOK_SLOW_MS;
326
+ }
327
+ if (delay < 0) return;
328
+ var self = this;
329
+ this.expectPerf = perfNow() + delay;
330
+ this.expectWall = Date.now() + delay;
331
+ this.timersArmed++;
332
+ this.timer = setTimeout(function () {
333
+ self.timer = null;
334
+ var t: { [k: string]: true } = { tick: true };
335
+ // A visible tab whose timer fired far too late (or whose wall clock went back)
336
+ // slept: that is a return, not a tick.
337
+ var lateWall = Date.now() - self.expectWall;
338
+ var latePerf = perfNow() - self.expectPerf;
339
+ if (!tabHidden() && (lateWall > WAKE_GAP_MS || latePerf > WAKE_GAP_MS || Date.now() < self.expectWall - delay)) t.wake = true;
340
+ self._start(t);
341
+ }, delay);
342
+ }
343
+ }
344
+
345
+ /* ---- the settle lock ------------------------------------------------------------------
346
+ *
347
+ * A side effect that sends or writes (the next pass of a client-driven file, a run:: or
348
+ * done:: record, a csr-finalize, a records refresh) runs in ONE tab. Every tab of the app
349
+ * may see the same item settle (the chat in one, the files page in another), and each used
350
+ * to do the side effect itself: two next passes for one file, two finalizes racing.
351
+ *
352
+ * How: navigator.locks.request('bq-settle:<project>:<queue>', { ifAvailable: true }) is
353
+ * held for the length of the side effect, and inside it a registry shared by the tabs
354
+ * (localStorage) says whether this side effect (by its key) already ran anywhere. A tab
355
+ * that does not get the lock tries again shortly, so nothing is dropped; the registry makes
356
+ * the retry a no-op once another tab did it. Without navigator.locks the side effect just
357
+ * runs (the registry still dedupes it). Without localStorage the in-memory set dedupes
358
+ * within the tab.
359
+ */
360
+
361
+ var FX_PREFIX = 'bq-fx:';
362
+ /** In-flight marks: a side effect some tab is running right now (see runSettleSideEffect). */
363
+ var FXI_PREFIX = 'bq-fxi:';
364
+ /** The longest one side effect holds the settle lock. */
365
+ var LOCK_HOLD_MAX_MS = 20 * 1000;
366
+ var FX_TTL_MS = 24 * 60 * 60 * 1000;
367
+ /** How long an in-flight mark holds other tabs off. A tab that ran a side effect and died
368
+ * (closed, frozen) leaves its mark behind; after this the others may run it. */
369
+ var FX_INFLIGHT_MS = 60 * 1000;
370
+ /** Tries per side effect in this tab: the first run and up to four retries after a
371
+ * failure, with backoff (FX_RETRY_BASE_MS, doubling). */
372
+ var FX_MAX_TRIES = 5;
373
+ var FX_RETRY_BASE_MS = 2000;
374
+ var _fxDone: { [key: string]: number } = {};
375
+ var _fxBusy: { [key: string]: number } = {};
376
+ var _fxPrunedAt = 0;
377
+
378
+ function storage(): any {
379
+ try {
380
+ var ls = _g.localStorage;
381
+ return ls && typeof ls.getItem === 'function' ? ls : null;
382
+ } catch (e) {
383
+ return null;
384
+ }
385
+ }
386
+
387
+ function fxIsDone(key: string): boolean {
388
+ if (_fxDone[key]) return true;
389
+ var ls = storage();
390
+ if (!ls) return false;
391
+ try {
392
+ var v = Number(ls.getItem(FX_PREFIX + key));
393
+ return isFinite(v) && v > 0 && Date.now() - v < FX_TTL_MS;
394
+ } catch (e) {
395
+ return false;
396
+ }
397
+ }
398
+
399
+ /** When this side effect was marked in flight (this tab or another), if that mark is
400
+ * still young; else 0. */
401
+ function fxBusyAt(key: string): number {
402
+ var now = Date.now();
403
+ var t = _fxBusy[key] || 0;
404
+ if (t && now - t < FX_INFLIGHT_MS) return t;
405
+ var ls = storage();
406
+ if (!ls) return 0;
407
+ try {
408
+ var v = Number(ls.getItem(FXI_PREFIX + key));
409
+ return isFinite(v) && v > 0 && now - v < FX_INFLIGHT_MS ? v : 0;
410
+ } catch (e) {
411
+ return 0;
412
+ }
413
+ }
414
+
415
+ function fxMarkBusy(key: string): void {
416
+ var now = Date.now();
417
+ _fxBusy[key] = now;
418
+ var ls = storage();
419
+ if (!ls) return;
420
+ try { ls.setItem(FXI_PREFIX + key, String(now)); } catch (e) { /* the in-memory mark still holds this tab */ }
421
+ }
422
+
423
+ function fxClearBusy(key: string): void {
424
+ delete _fxBusy[key];
425
+ var ls = storage();
426
+ if (!ls) return;
427
+ try { ls.removeItem(FXI_PREFIX + key); } catch (e) { /* expires on its own */ }
428
+ }
429
+
430
+ /** Once an hour: drop registry entries past their life, in memory and in localStorage. */
431
+ function fxPrune(now: number): void {
432
+ if (now - _fxPrunedAt <= 60 * 60 * 1000) return;
433
+ _fxPrunedAt = now;
434
+ var k: string;
435
+ for (k in _fxDone) if (now - _fxDone[k] > FX_TTL_MS) delete _fxDone[k];
436
+ for (k in _fxBusy) if (now - _fxBusy[k] > FX_INFLIGHT_MS) delete _fxBusy[k];
437
+ var ls = storage();
438
+ if (!ls) return;
439
+ try {
440
+ var drop: string[] = [];
441
+ for (var i = 0; i < ls.length; i++) {
442
+ var lk = ls.key(i);
443
+ if (!lk) continue;
444
+ var life = lk.indexOf(FX_PREFIX) === 0 ? FX_TTL_MS : (lk.indexOf(FXI_PREFIX) === 0 ? FX_INFLIGHT_MS : 0);
445
+ if (!life) continue;
446
+ var t = Number(ls.getItem(lk));
447
+ if (!isFinite(t) || now - t > life) drop.push(lk);
448
+ }
449
+ for (var d = 0; d < drop.length; d++) ls.removeItem(drop[d]);
450
+ } catch (e) { /* privacy mode */ }
451
+ }
452
+
453
+ function fxMarkDone(key: string): void {
454
+ var now = Date.now();
455
+ _fxDone[key] = now;
456
+ delete _fxBusy[key];
457
+ var ls = storage();
458
+ if (ls) {
459
+ try {
460
+ ls.setItem(FX_PREFIX + key, String(now));
461
+ ls.removeItem(FXI_PREFIX + key);
462
+ } catch (e) { /* quota, privacy mode: the in-memory set still dedupes this tab */ }
463
+ }
464
+ fxPrune(now);
465
+ }
466
+
467
+ /** Has this side effect run in any tab (within a day)? */
468
+ export function sideEffectDone(key: string): boolean {
469
+ return fxIsDone(key);
470
+ }
471
+
472
+ /** Take a side effect for this call: false when it already ran (or is running) in some
473
+ * tab, else it is marked done and the caller does it, and handles its own failure. For a
474
+ * step inside one that already holds the lock (the next pass of a file, inside the settle
475
+ * of the pass before it). */
476
+ export function claimSideEffect(key: string): boolean {
477
+ if (!key || fxIsDone(key) || fxBusyAt(key)) return false;
478
+ fxMarkDone(key);
479
+ return true;
480
+ }
481
+
482
+ /** Side effects running right now in this tab: one started inside another already holds
483
+ * the lock (navigator.locks is not re-entrant), so it runs at once. */
484
+ var _fxDepth = 0;
485
+
486
+ /**
487
+ * Run `fn` once across the tabs, under the settle lock of (project, queue). `key` names
488
+ * the side effect (e.g. "resume:<request id>"). Never throws; `fn` may be async.
489
+ *
490
+ * Done only when it worked: the side effect is marked in flight (FX_INFLIGHT_MS, so the
491
+ * other tabs leave it alone) while `fn` runs, and done when `fn` returns, or when the
492
+ * promise it returns resolves. A throw or a rejected promise clears the mark and `fn` runs
493
+ * again after a backoff, up to FX_MAX_TRIES times in this tab; a later call with the same
494
+ * key (the next look, another tab) can still run it after that. A tab that finds it in
495
+ * flight elsewhere looks again once that mark would have expired, so a tab that died
496
+ * mid-write does not leave it undone.
497
+ */
498
+ export function runSettleSideEffect(projectId: string, queue: string, key: string, fn: () => any, attempt?: number, tries?: number): void {
499
+ if (!key || fxIsDone(key)) return;
500
+ var tryNo = tries || 0;
501
+ var again = function (delay: number, nextTry: number) {
502
+ setTimeout(function () { runSettleSideEffect(projectId, queue, key, fn, 0, nextTry); }, delay);
503
+ };
504
+ var run = function (): any {
505
+ if (fxIsDone(key)) return;
506
+ var busy = fxBusyAt(key);
507
+ if (busy) {
508
+ // In flight: in this tab (that run settles it) or in another one. Another tab's
509
+ // mark is looked at again once it would have expired, bounded like the retries.
510
+ if (!_fxBusy[key] && tryNo < FX_MAX_TRIES) again(Math.max(1000, FX_INFLIGHT_MS - (Date.now() - busy) + 1000), tryNo + 1);
511
+ return;
512
+ }
513
+ fxMarkBusy(key);
514
+ var failed = function (e: any) {
515
+ fxClearBusy(key);
516
+ if (tryNo + 1 < FX_MAX_TRIES) {
517
+ console.warn('[chat-engine] a settle side effect failed; trying again', key, e);
518
+ again(FX_RETRY_BASE_MS * Math.pow(2, tryNo), tryNo + 1);
519
+ } else {
520
+ console.warn('[chat-engine] a settle side effect failed ' + FX_MAX_TRIES + ' times; left for a later settle', key, e);
521
+ }
522
+ };
523
+ var out: any;
524
+ _fxDepth++;
525
+ try {
526
+ out = fn();
527
+ } catch (e) {
528
+ _fxDepth--;
529
+ failed(e);
530
+ return;
531
+ }
532
+ _fxDepth--;
533
+ return Promise.resolve(out).then(function () { fxMarkDone(key); }, failed);
534
+ };
535
+ if (_fxDepth > 0 || !locks()) { run(); return; }
536
+ var lk: any = locks();
537
+ var name = 'bq-settle:' + (projectId || '') + ':' + (queue || '');
538
+ var n = attempt || 0;
539
+ var p: any;
540
+ try {
541
+ p = lk.request(name, { ifAvailable: true }, function (lock: any) {
542
+ if (!lock) return false;
543
+ // Held for the side effect, but never for long: a write that hangs (a network
544
+ // that died mid-request) must not keep every other tab's side effects of this
545
+ // project and queue waiting behind it. The in-flight mark keeps them off this
546
+ // one meanwhile.
547
+ return new Promise(function (resolve) {
548
+ var t = setTimeout(function () { resolve(true); }, LOCK_HOLD_MAX_MS);
549
+ Promise.resolve(run()).then(function () { clearTimeout(t); resolve(true); }, function () { clearTimeout(t); resolve(true); });
550
+ });
551
+ });
552
+ } catch (e) {
553
+ run();
554
+ return;
555
+ }
556
+ Promise.resolve(p).then(function (got: any) {
557
+ if (got !== false) return;
558
+ // Another tab holds the lock right now (it is doing a side effect of its own, maybe
559
+ // this very one). Ask again shortly; the registry makes that a no-op if it was.
560
+ // Busy for this long means a tab that holds it and does not let go (frozen, its
561
+ // page suspended): run it here after all. The registry still makes it a no-op when
562
+ // the holder did this very side effect; dropping it would leave a run:: record
563
+ // 'working' or a file's next pass unsent for good.
564
+ if (n >= 30) { run(); return; }
565
+ setTimeout(function () { runSettleSideEffect(projectId, queue, key, fn, n + 1, tryNo); }, Math.min(5000, 250 * Math.pow(2, n)));
566
+ }, function () { run(); });
567
+ }
568
+
569
+ function locks(): any {
570
+ var l: any = _g.navigator && _g.navigator.locks;
571
+ return l && typeof l.request === 'function' ? l : null;
572
+ }
573
+
574
+ /** A client reference for one send: 1 to 64 letters, digits, "_" or "-". */
575
+ export function newClientRef(): string {
576
+ var rnd = '';
577
+ var c: any = _g.crypto;
578
+ if (c && typeof c.getRandomValues === 'function') {
579
+ var a = new Uint32Array(2);
580
+ c.getRandomValues(a);
581
+ rnd = a[0].toString(36) + a[1].toString(36);
582
+ } else {
583
+ rnd = Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2);
584
+ }
585
+ return ('c' + Date.now().toString(36) + '_' + rnd).slice(0, 64);
586
+ }
587
+
588
+ /** A queue name from either shape it arrives in: "<queue>" or "<service>:<queue>|<seq>". */
589
+ export function queueNameOf(q?: string): string {
590
+ if (typeof q !== 'string' || !q) return '';
591
+ var head = q.split('|')[0];
592
+ var i = head.lastIndexOf(':');
593
+ return i === -1 ? head : head.slice(i + 1);
594
+ }