bunnyquery 1.19.3 → 1.20.0
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 +23 -2
- package/bunnyquery.css +21 -0
- package/bunnyquery.js +291 -12
- package/dist/engine.cjs +262 -8
- package/dist/engine.cjs.map +1 -1
- package/dist/engine.d.mts +96 -1
- package/dist/engine.d.ts +96 -1
- package/dist/engine.mjs +261 -9
- package/dist/engine.mjs.map +1 -1
- package/package.json +1 -1
- package/src/engine/config.ts +36 -0
- package/src/engine/index.ts +4 -0
- package/src/engine/prompts/chat_system_prompt.ts +10 -1
- package/src/engine/requests.ts +8 -2
- package/src/engine/session.ts +268 -10
- package/styles/chat.css +21 -0
package/package.json
CHANGED
package/src/engine/config.ts
CHANGED
|
@@ -204,6 +204,27 @@ export interface ChatEngineConfig {
|
|
|
204
204
|
* `liveStreamingRealtime`; that name is now ignored.
|
|
205
205
|
*/
|
|
206
206
|
liveStreaming?: boolean;
|
|
207
|
+
/**
|
|
208
|
+
* Request STATUS PUSH over skapi's websocket (skapi-js 2.5.0 or newer, plus the
|
|
209
|
+
* backend that knows `notify`). Indexing passes are dispatched with `notify: true`,
|
|
210
|
+
* their polls then read the row once a minute instead of every few seconds while
|
|
211
|
+
* status frames are arriving, and read it at once when a frame names them. The
|
|
212
|
+
* engine also listens with `onRequestStatus` while a chat view is open: a frame for
|
|
213
|
+
* a pass it holds nothing for picks that pass up, and a (re)connected socket runs
|
|
214
|
+
* the return catch-up (ChatSession.catchUpHistory), since frames sent while it was
|
|
215
|
+
* down are lost.
|
|
216
|
+
*
|
|
217
|
+
* Off by default for the same reason as `liveStreaming`: it keeps a websocket open
|
|
218
|
+
* on the host's skapi instance. The dashboard owns its instance and opts in; the
|
|
219
|
+
* widget leaves it to the embedder. Needs `onRequestStatus` below too: without it,
|
|
220
|
+
* or on an older skapi-js, nothing changes. Every frame is a hint: polls and
|
|
221
|
+
* listings still decide every status on screen.
|
|
222
|
+
*/
|
|
223
|
+
statusPush?: boolean;
|
|
224
|
+
/** skapi.onRequestStatus, bound to the consumer's skapi instance (skapi-js 2.5.0+). */
|
|
225
|
+
onRequestStatus?: (callback: (event: any) => void) => () => void;
|
|
226
|
+
/** skapi.isRequestStatusLive, bound to the consumer's skapi instance (skapi-js 2.5.0+). */
|
|
227
|
+
isRequestStatusLive?: () => boolean;
|
|
207
228
|
/**
|
|
208
229
|
* Whether a CHAT answer may reach the open web: Claude's `web_fetch` and
|
|
209
230
|
* OpenAI's `web_search` are attached to a chat request only when this
|
|
@@ -439,6 +460,21 @@ export function windowedIndexingEnabled(): boolean {
|
|
|
439
460
|
|
|
440
461
|
/** True when the consumer has opted in to live streaming of chat turns. */
|
|
441
462
|
/** Socket delivery of the stream: the host asked (`liveStreaming`) AND the turn streams. */
|
|
463
|
+
/** Request status push is on: the host asked for it and handed over onRequestStatus. */
|
|
464
|
+
export function statusPushEnabled(): boolean {
|
|
465
|
+
return _config?.statusPush === true && typeof _config?.onRequestStatus === 'function';
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/** Status frames are arriving right now (false when status push is off). */
|
|
469
|
+
export function statusPushLive(): boolean {
|
|
470
|
+
if (!statusPushEnabled() || typeof _config?.isRequestStatusLive !== 'function') return false;
|
|
471
|
+
try {
|
|
472
|
+
return !!_config.isRequestStatusLive();
|
|
473
|
+
} catch (e) {
|
|
474
|
+
return false;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
442
478
|
export function liveStreamingSocketEnabled(): boolean {
|
|
443
479
|
return liveStreamingEnabled() && _config?.liveStreaming === true;
|
|
444
480
|
}
|
package/src/engine/index.ts
CHANGED
|
@@ -43,6 +43,10 @@ export {
|
|
|
43
43
|
// `skipDuplicateFiles: false`.
|
|
44
44
|
skipDuplicateFilesEnabled,
|
|
45
45
|
resolveSkipDuplicateFiles,
|
|
46
|
+
// Request status push (ChatEngineConfig.statusPush): whether the host turned it on,
|
|
47
|
+
// and whether status messages are arriving right now.
|
|
48
|
+
statusPushEnabled,
|
|
49
|
+
statusPushLive,
|
|
46
50
|
} from './config';
|
|
47
51
|
|
|
48
52
|
// "Has this user already uploaded this file here?", answered from the `src::` file
|
|
@@ -129,8 +129,17 @@ These three rules govern every claim about the project's data. They do not limit
|
|
|
129
129
|
// reads on every step. That description must stay self-sufficient for
|
|
130
130
|
// third-party MCP clients, so the duplicate is removed HERE and the prompt only
|
|
131
131
|
// points at it. What stays is what no tool text says: quote and cite.
|
|
132
|
+
//
|
|
133
|
+
// Book search (2026-11-23): a long file is searched by chapter (getFileOutline,
|
|
134
|
+
// then searchText page_from/page_to), searchText gets the user's own question
|
|
135
|
+
// only for a document question (it ends up in shared learned tags), a re-search
|
|
136
|
+
// after a complaint passes the original question, never the complaint, and
|
|
137
|
+
// WRONG ANSWER is what the "Wrong answer?" button (and a user saying so)
|
|
138
|
+
// triggers: check again, then one of three outcomes, and a learned link
|
|
139
|
+
// changes only on proof (correctSearchLink with page and exact quote).
|
|
132
140
|
const documentRules =
|
|
133
|
-
`DOCUMENTS (a contract, a report, a manual, a letter, any uploaded file the user asks about the content of): FIRST FIND THE FILE, with getFileOutline when you know its storage path, otherwise by its "src::" record (see WHERE INDEXED CONTENT LIVES) using the name the user used. THEN FIND THE PAGE with searchText: with the file's path when the user named a file, without a path when they did not ("find a file that contains X"), and follow its description's steps 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"); never present a paraphrase as a quote. A file with no page text is read with readFileContent instead and cited by its file name
|
|
141
|
+
`DOCUMENTS (a contract, a report, a manual, a letter, any uploaded file the user asks about the content of): FIRST FIND THE FILE, with getFileOutline when you know its storage path, otherwise by its "src::" record (see WHERE INDEXED CONTENT LIVES) using the name the user used. THEN FIND THE PAGE with searchText: with the file's path when the user named a file, without a path when they did not ("find a file that contains X"), and follow its description's steps 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"); never present a paraphrase as a quote. A file with no page text is read with readFileContent instead and cited by its file name. For a long file (a manual, a book), call getFileOutline first 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 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.`;
|
|
134
143
|
|
|
135
144
|
// ---- Access group -----------------------------------------------------
|
|
136
145
|
// Trimmed 2026-11-23: the server's default-filling (an index or tag query auto-filled with
|
package/src/engine/requests.ts
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
*/
|
|
15
15
|
import { buildIndexingSystemPrompt, buildIndexingUserMessage, buildIndexingContinueMessage, buildIndexingRenderMessage, buildIndexingRenderContinueTemplate, buildIndexingWindowMessage } from './prompts';
|
|
16
16
|
import { isServerExtractable, isPagedReadFile, isImageVisionFile, isWindowedReadFile, makeExtractPlaceholder, makeRenderPlaceholder, makeWindowPlaceholder, RENDER_PAGES_PER_WINDOW, type ExtractDirective, type FileUrlDirective } from './office';
|
|
17
|
-
import { chatEngineConfig, resolveForwardRequest, resolveForwardRequestHistory, pollOpt, windowedIndexingEnabled, liveStreamingEnabled, liveStreamingSocketEnabled, resolveWebAccess, resolveAnswerMode } from './config';
|
|
17
|
+
import { chatEngineConfig, resolveForwardRequest, resolveForwardRequestHistory, pollOpt, windowedIndexingEnabled, liveStreamingEnabled, liveStreamingSocketEnabled, resolveWebAccess, resolveAnswerMode, statusPushEnabled } from './config';
|
|
18
18
|
import { type AnswerMode } from './project_settings';
|
|
19
19
|
import { csrEnvelopeError } from './errors';
|
|
20
20
|
// Output sizing lives in budget.ts so the request cap and the reserve the input
|
|
@@ -1440,6 +1440,9 @@ export async function notifyAgentSaveAttachment(info: AttachmentSaveInfo) {
|
|
|
1440
1440
|
service,
|
|
1441
1441
|
owner,
|
|
1442
1442
|
...pollOpt(),
|
|
1443
|
+
// Status push for this pass and the continuations the worker queues from it
|
|
1444
|
+
// (see ChatEngineConfig.statusPush). Absent unless the host turned it on.
|
|
1445
|
+
...(statusPushEnabled() ? { notify: true } : {}),
|
|
1443
1446
|
url: OPENAI_RESPONSES_API_URL,
|
|
1444
1447
|
method: 'POST',
|
|
1445
1448
|
headers: {
|
|
@@ -1485,6 +1488,9 @@ export async function notifyAgentSaveAttachment(info: AttachmentSaveInfo) {
|
|
|
1485
1488
|
service,
|
|
1486
1489
|
owner,
|
|
1487
1490
|
...pollOpt(),
|
|
1491
|
+
// Status push for this pass and the continuations the worker queues from it
|
|
1492
|
+
// (see ChatEngineConfig.statusPush). Absent unless the host turned it on.
|
|
1493
|
+
...(statusPushEnabled() ? { notify: true } : {}),
|
|
1488
1494
|
url: ANTHROPIC_MESSAGES_API_URL,
|
|
1489
1495
|
method: 'POST',
|
|
1490
1496
|
headers: {
|
|
@@ -1790,7 +1796,7 @@ export type BgTaskEntry = {
|
|
|
1790
1796
|
// REQUEST rather than the response: `executed` is when the worker began
|
|
1791
1797
|
// running it, which rides on a running poll tick's status envelope and is
|
|
1792
1798
|
// therefore free to a caller already polling.
|
|
1793
|
-
poll: ((opts: { latency: number; onResponse?: (res: any, meta?: { executed?: number }) => void }) => Promise<any>) | undefined;
|
|
1799
|
+
poll: ((opts: { latency: number; notify?: boolean; onResponse?: (res: any, meta?: { executed?: number }) => void }) => Promise<any>) | undefined;
|
|
1794
1800
|
/** How many CONTINUE passes have already run for this file (resume-across-passes). */
|
|
1795
1801
|
resumePass?: number;
|
|
1796
1802
|
/** The STAGED chat turn these files were attached to (ChatSession.stageOutgoingMessage).
|
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 } from './config';
|
|
48
|
+
import { windowedIndexingEnabled, liveStreamingEnabled, streamRecoveryEnabled, chatEngineConfig, resolveForwardRequestFinalize, resolveForwardRequestStream, resolveSkipDuplicateFiles, statusPushEnabled, statusPushLive } from './config';
|
|
49
49
|
// The wire-format knowledge. skapi relays the provider's bytes without reading them,
|
|
50
50
|
// so the session hands them straight to this parser and never inspects a frame itself.
|
|
51
51
|
import { createSseParser, type SseParser } from './sse';
|
|
@@ -53,6 +53,7 @@ import { isErrorResponseBody, isAuthExpiredError, isNonRetryableRequestError, ge
|
|
|
53
53
|
import { buildBoundedChatMessages } from './budget';
|
|
54
54
|
import { extractRetrievalNote, type RetrievalNote } from './retrieval_memory';
|
|
55
55
|
import { findingsForTurn } from './findings';
|
|
56
|
+
import { retrievalNoteOfAnswer, answerUsedNoDataTool } from './citations';
|
|
56
57
|
import { createInlineLinkRegex, sanitizeAttachmentLinksForHistory } from './links';
|
|
57
58
|
import { markImagePreviewStale } from './image_preview';
|
|
58
59
|
import { chatCacheKey, indexScopeKey, mapHistoryListToMessages, extractLastUserTextFromRequest, isIndexingRequestText, parseIndexingRequestText, probeBgQueue, BG_PROBE_TTL_MS, getSplitChatHistory, shouldRescueInFlightMessage, adoptLocalAnswerIntoPage } from './history';
|
|
@@ -99,6 +100,15 @@ const RECENT_INDEX_PASS_EVIDENCE_MS = 10 * 60 * 1000;
|
|
|
99
100
|
// it ended (3.5 min on a 110-page PDF, nine passes done meanwhile). One look is the two
|
|
100
101
|
// status queries (running, pending); it stops by itself when nothing is tracked.
|
|
101
102
|
const ADOPT_TICK_MS = 10 * 1000;
|
|
103
|
+
/** The queue check's interval while request status frames are arriving (statusPush). */
|
|
104
|
+
const STATUS_PUSH_ADOPT_TICK_MS = 60 * 1000;
|
|
105
|
+
/** Several reasons to catch up at once (tab shown, socket back, network back) run one. */
|
|
106
|
+
const CATCH_UP_MIN_GAP_MS = 2000;
|
|
107
|
+
/** The return watch: how often it looks, and the gap that means the computer slept. */
|
|
108
|
+
const RETURN_WATCH_MS = 15 * 1000;
|
|
109
|
+
const RETURN_WATCH_SLEEP_GAP_MS = 45 * 1000;
|
|
110
|
+
/** Frame-driven queue checks run at most this often (status push). */
|
|
111
|
+
const STATUS_NUDGE_MIN_GAP_MS = 2000;
|
|
102
112
|
|
|
103
113
|
// awaitIndexingDrained: how often it re-asks the background-indexing queue, and
|
|
104
114
|
// how many consecutive empty answers it needs before believing the chains are
|
|
@@ -579,6 +589,23 @@ export function requestIdTimeMs(rid: string): number {
|
|
|
579
589
|
return Math.floor(v / 2 / 1e6);
|
|
580
590
|
}
|
|
581
591
|
|
|
592
|
+
/** The visible message the "Wrong answer?" button sends. The chat prompt's WRONG ANSWER rule reacts to it. */
|
|
593
|
+
export var WRONG_ANSWER_MESSAGE = 'This answer seems wrong. Please check it again against the documents.';
|
|
594
|
+
/** The button's label, shared so the two clients word it the same. */
|
|
595
|
+
export var WRONG_ANSWER_LABEL = 'Wrong answer?';
|
|
596
|
+
|
|
597
|
+
/**
|
|
598
|
+
* True when a bubble gets the "Wrong answer?" button: a settled chat answer that
|
|
599
|
+
* read project data (a retrieval note that is not the no-source mark). Both
|
|
600
|
+
* clients gate through ChatSession.canReportWrongAnswer, which also keeps it to
|
|
601
|
+
* the latest answer, and
|
|
602
|
+
* ChatSession.wrongAnswerReported says whether it was used.
|
|
603
|
+
*/
|
|
604
|
+
export function canReportWrongAnswer(msg: ChatMessage | null | undefined): boolean {
|
|
605
|
+
var note = retrievalNoteOfAnswer(msg);
|
|
606
|
+
return !!note && !answerUsedNoDataTool(note) && !(msg as any).isCancelled;
|
|
607
|
+
}
|
|
608
|
+
|
|
582
609
|
export class ChatSession {
|
|
583
610
|
host: ChatHost;
|
|
584
611
|
state: ChatState;
|
|
@@ -622,6 +649,9 @@ export class ChatSession {
|
|
|
622
649
|
* settleDeadStagedMessages). Today the cache dies with the page too and every
|
|
623
650
|
* restored stage is live; this stays correct if that ever changes. */
|
|
624
651
|
private _liveStages: { [stageId: string]: boolean };
|
|
652
|
+
/** Answers whose "Wrong answer?" was already sent, by server id (else local id),
|
|
653
|
+
* so a history refetch that rebuilds the bubble does not offer it again. */
|
|
654
|
+
private _wrongReported: { [msgKey: string]: boolean };
|
|
625
655
|
/** Files the SERVER currently has unresolved indexing work for, by the same key
|
|
626
656
|
* a collapsed row uses (storage path, else filename), and whether we have asked
|
|
627
657
|
* even once for this chat.
|
|
@@ -689,6 +719,7 @@ export class ChatSession {
|
|
|
689
719
|
this.historyItemPolls = new Map();
|
|
690
720
|
this._pauseReasons = new Set();
|
|
691
721
|
this._resuming = false;
|
|
722
|
+
this._wrongReported = {};
|
|
692
723
|
this._lidSeq = 0;
|
|
693
724
|
this._stageSeq = 0;
|
|
694
725
|
this._uploadBatches = 0;
|
|
@@ -2502,13 +2533,12 @@ export class ChatSession {
|
|
|
2502
2533
|
return Promise.resolve()
|
|
2503
2534
|
.then(function () {
|
|
2504
2535
|
self.drainBgTaskQueue();
|
|
2505
|
-
//
|
|
2506
|
-
//
|
|
2507
|
-
//
|
|
2508
|
-
//
|
|
2509
|
-
//
|
|
2510
|
-
|
|
2511
|
-
self.refreshLiveIndexState();
|
|
2536
|
+
// EVERY return re-reads the first page (owner, 2026-11-23: "when the user is
|
|
2537
|
+
// away and comes back it should always have all the chat, no missing"). This
|
|
2538
|
+
// replaces the 2026-11-20 rule that loaded history once and relied on polls
|
|
2539
|
+
// alone: a poll that was stopped, throttled or lost while the tab slept had
|
|
2540
|
+
// nothing behind it. See catchUpHistory.
|
|
2541
|
+
return self.catchUpHistory();
|
|
2512
2542
|
})
|
|
2513
2543
|
.catch(function (e: any) { console.error('[chat-engine] resume polling failed', e); })
|
|
2514
2544
|
.then(function () { self._resuming = false; });
|
|
@@ -4003,6 +4033,63 @@ export class ChatSession {
|
|
|
4003
4033
|
});
|
|
4004
4034
|
}
|
|
4005
4035
|
|
|
4036
|
+
/** The button's label and the message it sends, read off the session so the
|
|
4037
|
+
* clients need no extra import. */
|
|
4038
|
+
readonly wrongAnswerLabel: string = WRONG_ANSWER_LABEL;
|
|
4039
|
+
readonly wrongAnswerMessage: string = WRONG_ANSWER_MESSAGE;
|
|
4040
|
+
|
|
4041
|
+
/**
|
|
4042
|
+
* Does this bubble get the "Wrong answer?" button: the free function's gate,
|
|
4043
|
+
* and only on the latest answer, because the message it sends names no answer
|
|
4044
|
+
* and the model reads it right after the last one. An answer already reported
|
|
4045
|
+
* keeps its (disabled) button after the complaint turn lands below it.
|
|
4046
|
+
*/
|
|
4047
|
+
canReportWrongAnswer(msg: ChatMessage): boolean {
|
|
4048
|
+
if (!canReportWrongAnswer(msg)) return false;
|
|
4049
|
+
return this.wrongAnswerReported(msg) || this._isLatestAnswer(msg);
|
|
4050
|
+
}
|
|
4051
|
+
|
|
4052
|
+
/** True when no chat turn follows `msg` in state.messages. Indexing rows and
|
|
4053
|
+
* cancelled turns do not count (neither reaches the model's history). Matched
|
|
4054
|
+
* by identity or by item id, since agent.vue hands in reactive proxies. */
|
|
4055
|
+
private _isLatestAnswer(msg: ChatMessage): boolean {
|
|
4056
|
+
var list = this.state.messages || [];
|
|
4057
|
+
var sid = msg._serverItemId, lid = msg._localId;
|
|
4058
|
+
for (var i = list.length - 1; i >= 0; i--) {
|
|
4059
|
+
var m = list[i];
|
|
4060
|
+
if (!m) continue;
|
|
4061
|
+
if (m === msg || (m.role === 'assistant' && ((sid && m._serverItemId === sid) || (lid && m._localId === lid)))) return true;
|
|
4062
|
+
if (m.isBackgroundTask || m.isCancelled) continue;
|
|
4063
|
+
return false;
|
|
4064
|
+
}
|
|
4065
|
+
return false;
|
|
4066
|
+
}
|
|
4067
|
+
|
|
4068
|
+
/** True once this answer's "Wrong answer?" was sent (one click per answer). */
|
|
4069
|
+
wrongAnswerReported(msg: ChatMessage): boolean {
|
|
4070
|
+
if (!msg) return false;
|
|
4071
|
+
if ((msg as any)._wrongReported) return true;
|
|
4072
|
+
var key = msg._serverItemId || msg._localId;
|
|
4073
|
+
return !!key && !!this._wrongReported[key];
|
|
4074
|
+
}
|
|
4075
|
+
|
|
4076
|
+
/**
|
|
4077
|
+
* The "Wrong answer?" button: sends WRONG_ANSWER_MESSAGE as an ordinary visible
|
|
4078
|
+
* user turn through dispatchComposedMessage, so it reads the same after a reload
|
|
4079
|
+
* and both clients behave alike. The answer is marked first, so the button goes
|
|
4080
|
+
* disabled at once. False when the bubble does not qualify or was already used.
|
|
4081
|
+
* `pinned` is the caller's usual pinned identity and prompt (agent.vue pins them).
|
|
4082
|
+
*/
|
|
4083
|
+
reportWrongAnswer(msg: ChatMessage, pinned?: PinnedDispatchContext): boolean {
|
|
4084
|
+
if (this.wrongAnswerReported(msg) || !this.canReportWrongAnswer(msg)) return false;
|
|
4085
|
+
(msg as any)._wrongReported = true;
|
|
4086
|
+
var key = msg._serverItemId || msg._localId;
|
|
4087
|
+
if (key) this._wrongReported[key] = true;
|
|
4088
|
+
this.host.notify();
|
|
4089
|
+
this.dispatchComposedMessage(WRONG_ANSWER_MESSAGE, false, undefined, undefined, undefined, pinned);
|
|
4090
|
+
return true;
|
|
4091
|
+
}
|
|
4092
|
+
|
|
4006
4093
|
/**
|
|
4007
4094
|
* Stop waiting for the reply to the chat turn that is running now, and move on.
|
|
4008
4095
|
*
|
|
@@ -5061,6 +5148,168 @@ export class ChatSession {
|
|
|
5061
5148
|
/** Start the ADOPT_TICK_MS follow-up if this page is tracking live indexing work and
|
|
5062
5149
|
* is visible. Idempotent; each tick re-checks and stops when the work is gone, the tab
|
|
5063
5150
|
* is hidden (resume restarts it through refreshLiveIndexState) or the view closed. */
|
|
5151
|
+
// ── RETURN CATCH-UP + REQUEST STATUS PUSH (owner, 2026-11-23) ──────────────
|
|
5152
|
+
// The rule: when the user comes back to the chat (the tab shown again, the computer
|
|
5153
|
+
// awake again, the network or the websocket back), the chat is re-read from the
|
|
5154
|
+
// server, so nothing that happened while they were away is missing. The re-read is
|
|
5155
|
+
// loadHistory's own first-page refresh, the one every mount runs: it keeps older pages
|
|
5156
|
+
// the user loaded, keeps a send still in flight, never lets an empty answer replace a
|
|
5157
|
+
// known one, re-attaches polls to whatever is still waiting, and reads back a streamed
|
|
5158
|
+
// answer nobody finalized. Status frames (statusPush) only make things faster; they
|
|
5159
|
+
// never decide anything on screen.
|
|
5160
|
+
|
|
5161
|
+
private _catchUpAt = 0;
|
|
5162
|
+
private _catchUpTimer: any = null;
|
|
5163
|
+
private _returnWatchTimer: any = null;
|
|
5164
|
+
private _returnWatchAt = 0;
|
|
5165
|
+
private _returnListeners = false;
|
|
5166
|
+
private _statusUnsub: (() => void) | null = null;
|
|
5167
|
+
private _statusNudgeTimer: any = null;
|
|
5168
|
+
private _statusNudgeAt = 0;
|
|
5169
|
+
private _statusSeenConnect = false;
|
|
5170
|
+
|
|
5171
|
+
/**
|
|
5172
|
+
* Re-read the chat from the server now (see the rule above). Safe to call from any
|
|
5173
|
+
* number of triggers at once: calls within CATCH_UP_MIN_GAP_MS of the last one run
|
|
5174
|
+
* once, at the end of the gap. Nothing happens while no chat view is mounted (the
|
|
5175
|
+
* mount loads the chat anyway) or while background polling is paused (the tab is
|
|
5176
|
+
* hidden: showing it calls this again).
|
|
5177
|
+
*/
|
|
5178
|
+
catchUpHistory(): Promise<void> {
|
|
5179
|
+
var self = this;
|
|
5180
|
+
var id = this.host.getIdentity();
|
|
5181
|
+
if (!id.projectId || id.platform === 'none') return Promise.resolve();
|
|
5182
|
+
if (!this.host.isViewMounted || !this.host.isViewMounted() || this.isPollingPaused()) return Promise.resolve();
|
|
5183
|
+
this._ensureReturnWatch();
|
|
5184
|
+
var wait = this._catchUpAt + CATCH_UP_MIN_GAP_MS - Date.now();
|
|
5185
|
+
if (wait > 0) {
|
|
5186
|
+
if (!this._catchUpTimer) {
|
|
5187
|
+
this._catchUpTimer = setTimeout(function () {
|
|
5188
|
+
self._catchUpTimer = null;
|
|
5189
|
+
self.catchUpHistory();
|
|
5190
|
+
}, wait);
|
|
5191
|
+
}
|
|
5192
|
+
return Promise.resolve();
|
|
5193
|
+
}
|
|
5194
|
+
this._catchUpAt = Date.now();
|
|
5195
|
+
// loadHistory's first-page path ends with refreshLiveIndexState, so indexing rows
|
|
5196
|
+
// are re-asked as well.
|
|
5197
|
+
return this.loadHistory(false, this.state.gateRefreshToken).catch(function (e: any) {
|
|
5198
|
+
console.error('[chat-engine] catch-up failed', e);
|
|
5199
|
+
});
|
|
5200
|
+
}
|
|
5201
|
+
|
|
5202
|
+
/**
|
|
5203
|
+
* Watch for the moments the user comes back without the tab being hidden first: the
|
|
5204
|
+
* computer waking from sleep (the timer finds a gap far longer than its interval),
|
|
5205
|
+
* the network coming back, a page restored from the back-forward cache. Also starts
|
|
5206
|
+
* the status push listener. Runs while a chat view is mounted and stops itself when
|
|
5207
|
+
* none is.
|
|
5208
|
+
*/
|
|
5209
|
+
private _ensureReturnWatch(): void {
|
|
5210
|
+
var self = this;
|
|
5211
|
+
if (typeof window === 'undefined') return;
|
|
5212
|
+
if (!this._returnListeners) {
|
|
5213
|
+
this._returnListeners = true;
|
|
5214
|
+
var onBack = function () {
|
|
5215
|
+
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return;
|
|
5216
|
+
self.catchUpHistory();
|
|
5217
|
+
};
|
|
5218
|
+
window.addEventListener('online', onBack);
|
|
5219
|
+
window.addEventListener('pageshow', function (ev: any) { if (ev && ev.persisted) onBack(); });
|
|
5220
|
+
}
|
|
5221
|
+
this._startStatusPush();
|
|
5222
|
+
if (this._returnWatchTimer) return;
|
|
5223
|
+
this._returnWatchAt = Date.now();
|
|
5224
|
+
var look = function () {
|
|
5225
|
+
self._returnWatchTimer = null;
|
|
5226
|
+
if (!self.host.isViewMounted || !self.host.isViewMounted()) {
|
|
5227
|
+
self._stopStatusPush();
|
|
5228
|
+
return;
|
|
5229
|
+
}
|
|
5230
|
+
var now = Date.now();
|
|
5231
|
+
var gap = now - self._returnWatchAt;
|
|
5232
|
+
self._returnWatchAt = now;
|
|
5233
|
+
// A hidden tab's timers are slowed too, so only a gap seen while VISIBLE is a
|
|
5234
|
+
// wake from sleep; a hidden tab catches up when it is shown (resumePolling).
|
|
5235
|
+
if (gap > RETURN_WATCH_SLEEP_GAP_MS && (typeof document === 'undefined' || document.visibilityState !== 'hidden')) {
|
|
5236
|
+
self.catchUpHistory();
|
|
5237
|
+
}
|
|
5238
|
+
self._returnWatchTimer = setTimeout(look, RETURN_WATCH_MS);
|
|
5239
|
+
};
|
|
5240
|
+
this._returnWatchTimer = setTimeout(look, RETURN_WATCH_MS);
|
|
5241
|
+
}
|
|
5242
|
+
|
|
5243
|
+
/** Listen to request status frames while a chat view is mounted (statusPush on). */
|
|
5244
|
+
private _startStatusPush(): void {
|
|
5245
|
+
if (this._statusUnsub || !statusPushEnabled()) return;
|
|
5246
|
+
var self = this;
|
|
5247
|
+
// The first 'connected' is the socket this subscription found or opened, right
|
|
5248
|
+
// after the view loaded the chat itself: nothing can have been missed yet.
|
|
5249
|
+
this._statusSeenConnect = false;
|
|
5250
|
+
try {
|
|
5251
|
+
var unsub = chatEngineConfig().onRequestStatus!(function (ev: any) { self._onRequestStatus(ev); });
|
|
5252
|
+
this._statusUnsub = typeof unsub === 'function' ? unsub : function () { };
|
|
5253
|
+
} catch (e) {
|
|
5254
|
+
this._statusUnsub = null;
|
|
5255
|
+
}
|
|
5256
|
+
}
|
|
5257
|
+
|
|
5258
|
+
private _stopStatusPush(): void {
|
|
5259
|
+
var unsub = this._statusUnsub;
|
|
5260
|
+
this._statusUnsub = null;
|
|
5261
|
+
if (this._statusNudgeTimer) { clearTimeout(this._statusNudgeTimer); this._statusNudgeTimer = null; }
|
|
5262
|
+
if (unsub) {
|
|
5263
|
+
try { unsub(); } catch (e) { /* best effort */ }
|
|
5264
|
+
}
|
|
5265
|
+
}
|
|
5266
|
+
|
|
5267
|
+
/**
|
|
5268
|
+
* One status frame event. 'connected' (first connection, and every reconnect after a
|
|
5269
|
+
* drop, a sleep or the planned renewal) catches up, because frames sent while the
|
|
5270
|
+
* socket was down are lost. A status change of an indexing pass this page does not
|
|
5271
|
+
* poll runs the queue check now instead of at its next heartbeat; a pass that IS polled
|
|
5272
|
+
* was already woken by skapi-js itself. Chat turns are left to their own polls.
|
|
5273
|
+
*/
|
|
5274
|
+
private _onRequestStatus(ev: any): void {
|
|
5275
|
+
if (!ev || !this.host.isViewMounted()) return;
|
|
5276
|
+
if (ev.type === 'connected') {
|
|
5277
|
+
if (!this._statusSeenConnect) { this._statusSeenConnect = true; return; }
|
|
5278
|
+
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return;
|
|
5279
|
+
this.catchUpHistory();
|
|
5280
|
+
return;
|
|
5281
|
+
}
|
|
5282
|
+
if (ev.type !== 'status' || typeof ev.id !== 'string') return;
|
|
5283
|
+
if (!ev.queue || !isBgIndexingQueue(ev.queue)) return;
|
|
5284
|
+
if (this.historyItemPolls.has(ev.id)) return;
|
|
5285
|
+
var tracked = false;
|
|
5286
|
+
for (var i = 0; i < this.bgTaskQueue.length; i++) {
|
|
5287
|
+
var e = this.bgTaskQueue[i];
|
|
5288
|
+
if (e && e.id === ev.id) { tracked = !e.byListing; break; }
|
|
5289
|
+
}
|
|
5290
|
+
if (tracked) return;
|
|
5291
|
+
this._nudgeQueueCheck();
|
|
5292
|
+
}
|
|
5293
|
+
|
|
5294
|
+
/** Run the queue check (adopt, settle by listing, page progress) now, at most once per
|
|
5295
|
+
* STATUS_NUDGE_MIN_GAP_MS, then let the heartbeat carry on. */
|
|
5296
|
+
private _nudgeQueueCheck(): void {
|
|
5297
|
+
var self = this;
|
|
5298
|
+
if (this._statusNudgeTimer) return;
|
|
5299
|
+
var wait = Math.max(0, this._statusNudgeAt + STATUS_NUDGE_MIN_GAP_MS - Date.now());
|
|
5300
|
+
this._statusNudgeTimer = setTimeout(function () {
|
|
5301
|
+
self._statusNudgeTimer = null;
|
|
5302
|
+
self._statusNudgeAt = Date.now();
|
|
5303
|
+
var id = self.host.getIdentity();
|
|
5304
|
+
if (!id.projectId || (id.platform !== 'claude' && id.platform !== 'openai')) return;
|
|
5305
|
+
if (self.isPollingPaused() || !self.host.isViewMounted()) return;
|
|
5306
|
+
self._adoptWorkerIndexingPasses(0, false, true);
|
|
5307
|
+
self._settleByListing();
|
|
5308
|
+
self._refreshPageProgress();
|
|
5309
|
+
self._ensureAdoptTick();
|
|
5310
|
+
}, wait);
|
|
5311
|
+
}
|
|
5312
|
+
|
|
5064
5313
|
private _ensureAdoptTick(): void {
|
|
5065
5314
|
if (this._adoptTickTimer) return;
|
|
5066
5315
|
var self = this;
|
|
@@ -5078,7 +5327,9 @@ export class ChatSession {
|
|
|
5078
5327
|
self._settleByListing();
|
|
5079
5328
|
self._refreshPageProgress();
|
|
5080
5329
|
self._ensureAdoptTick();
|
|
5081
|
-
|
|
5330
|
+
// While status frames are arriving the queue check is a heartbeat only: a frame
|
|
5331
|
+
// about a pass this page does not follow yet runs it at once (_onRequestStatus).
|
|
5332
|
+
}, statusPushLive() ? STATUS_PUSH_ADOPT_TICK_MS : ADOPT_TICK_MS);
|
|
5082
5333
|
}
|
|
5083
5334
|
|
|
5084
5335
|
/** The last COMPLETE running+pending look at this user's bg queue: which pass ids were
|
|
@@ -5780,6 +6031,8 @@ export class ChatSession {
|
|
|
5780
6031
|
var id = this.host.getIdentity();
|
|
5781
6032
|
var svcId = id.projectId, plat = id.platform;
|
|
5782
6033
|
if (!svcId || plat === 'none' || !this.host.isViewMounted()) return;
|
|
6034
|
+
// A chat view is up: watch for the user coming back (see catchUpHistory).
|
|
6035
|
+
this._ensureReturnWatch();
|
|
5783
6036
|
// Before anything is surfaced: drop continuations of files the user stopped
|
|
5784
6037
|
// (and let a fresh first pass lift the stop), then cancel any worker-queued
|
|
5785
6038
|
// pass of a stopped file that reached the chat through history.
|
|
@@ -5916,6 +6169,11 @@ export class ChatSession {
|
|
|
5916
6169
|
var executedAt: number | undefined;
|
|
5917
6170
|
var bp = entry.poll({
|
|
5918
6171
|
latency: POLL_INTERVAL,
|
|
6172
|
+
// Status push (statusPushEnabled): a pass adopted from a listing is polled
|
|
6173
|
+
// slowly while frames arrive, like one this page dispatched. A dispatch
|
|
6174
|
+
// reply's poll decides that from the server's acknowledgement and
|
|
6175
|
+
// ignores this key.
|
|
6176
|
+
notify: statusPushEnabled(),
|
|
5919
6177
|
onResponse: function (_res: any, meta: any) {
|
|
5920
6178
|
if (meta && typeof meta.executed === 'number' && meta.executed > 0) executedAt = meta.executed;
|
|
5921
6179
|
},
|
|
@@ -6780,7 +7038,7 @@ export class ChatSession {
|
|
|
6780
7038
|
},
|
|
6781
7039
|
};
|
|
6782
7040
|
var pp = isBg
|
|
6783
|
-
? item.poll(Object.assign({ latency: POLL_INTERVAL }, pollOpts))
|
|
7041
|
+
? item.poll(Object.assign({ latency: POLL_INTERVAL, notify: statusPushEnabled() }, pollOpts))
|
|
6784
7042
|
// Pinned to the chat this LOAD is for, snapshotted at its start
|
|
6785
7043
|
// (loadKey/platform/projectId/owner), never a live read: a load can
|
|
6786
7044
|
// still be attaching polls after the user has moved on, and a stream
|
package/styles/chat.css
CHANGED
|
@@ -180,6 +180,27 @@
|
|
|
180
180
|
color: var(--bq-muted);
|
|
181
181
|
clear: both;
|
|
182
182
|
}
|
|
183
|
+
/* "Wrong answer?" under an answer that read data: a small muted text button, no
|
|
184
|
+
box and no hover colour (the hover is an underline). Disabled once sent. */
|
|
185
|
+
.bq-wrong-answer-btn {
|
|
186
|
+
display: block;
|
|
187
|
+
margin-top: 0.3rem;
|
|
188
|
+
padding: 0;
|
|
189
|
+
min-height: 0;
|
|
190
|
+
border: 0;
|
|
191
|
+
background: transparent;
|
|
192
|
+
color: var(--bq-muted);
|
|
193
|
+
font: inherit;
|
|
194
|
+
font-size: 0.68rem;
|
|
195
|
+
line-height: 1.3;
|
|
196
|
+
text-align: left;
|
|
197
|
+
cursor: pointer;
|
|
198
|
+
box-shadow: none;
|
|
199
|
+
border-radius: 0;
|
|
200
|
+
clear: both;
|
|
201
|
+
}
|
|
202
|
+
.bq-wrong-answer-btn:hover:not(:disabled) { text-decoration: underline; }
|
|
203
|
+
.bq-wrong-answer-btn:disabled { cursor: default; opacity: 0.6; }
|
|
183
204
|
/* Timestamp under a settled bubble (created for a user turn, response time for an
|
|
184
205
|
assistant turn). Muted and small so it never competes with the message. */
|
|
185
206
|
.bq-msg-time {
|