bunnyquery 1.18.0 → 1.19.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 +22 -16
- package/bunnyquery.css +14 -0
- package/bunnyquery.js +8818 -7335
- package/dist/engine.cjs +8518 -7380
- package/dist/engine.cjs.map +1 -1
- package/dist/engine.d.mts +458 -193
- package/dist/engine.d.ts +458 -193
- package/dist/engine.mjs +8512 -7381
- package/dist/engine.mjs.map +1 -1
- package/package.json +1 -1
- package/src/engine/config.ts +72 -138
- package/src/engine/duplicates.ts +114 -35
- package/src/engine/findings.ts +305 -0
- package/src/engine/history.ts +27 -2
- package/src/engine/host.ts +25 -1
- package/src/engine/index.ts +15 -1
- package/src/engine/indexing_groups.ts +18 -0
- package/src/engine/prompts/chat_system_prompt.ts +2 -1
- package/src/engine/prompts/indexing_system_prompt.ts +2 -2
- package/src/engine/prompts/indexing_user_message.ts +4 -3
- package/src/engine/requests.ts +57 -3
- package/src/engine/retrieval_memory.ts +11 -0
- package/src/engine/session.ts +859 -83
- package/styles/chat.css +14 -0
package/src/engine/session.ts
CHANGED
|
@@ -48,7 +48,8 @@ import { windowedIndexingEnabled, liveStreamingEnabled, streamRecoveryEnabled, c
|
|
|
48
48
|
import { createSseParser, type SseParser } from './sse';
|
|
49
49
|
import { isErrorResponseBody, isAuthExpiredError, isNonRetryableRequestError, getErrorMessage, isCsrStatusEnvelope } from './errors';
|
|
50
50
|
import { buildBoundedChatMessages } from './budget';
|
|
51
|
-
import { extractRetrievalNote } from './retrieval_memory';
|
|
51
|
+
import { extractRetrievalNote, type RetrievalNote } from './retrieval_memory';
|
|
52
|
+
import { findingsForTurn } from './findings';
|
|
52
53
|
import { createInlineLinkRegex, sanitizeAttachmentLinksForHistory } from './links';
|
|
53
54
|
import { markImagePreviewStale } from './image_preview';
|
|
54
55
|
import { chatCacheKey, indexScopeKey, mapHistoryListToMessages, extractLastUserTextFromRequest, isIndexingRequestText, parseIndexingRequestText, probeBgQueue, BG_PROBE_TTL_MS, getSplitChatHistory, shouldRescueInFlightMessage, adoptLocalAnswerIntoPage } from './history';
|
|
@@ -88,6 +89,13 @@ const WORKER_PASS_ADOPT_ATTEMPTS = [0, 2000, 6000];
|
|
|
88
89
|
* round trips, while the cost of being too tight is a file that reads "Indexed"
|
|
89
90
|
* while it is still being read. */
|
|
90
91
|
const RECENT_INDEX_PASS_EVIDENCE_MS = 10 * 60 * 1000;
|
|
92
|
+
// While this chat is following a worker-driven indexing run and its tab is visible, look
|
|
93
|
+
// for newly minted passes this often (2026-11-20). Adoption used to run only when a pass
|
|
94
|
+
// this client tracked SETTLED, and with parallel windows the one pass the client sent is
|
|
95
|
+
// just one of eight: the other lanes, and everything they finished, stayed invisible until
|
|
96
|
+
// it ended (3.5 min on a 110-page PDF, nine passes done meanwhile). One look is the two
|
|
97
|
+
// status queries (running, pending); it stops by itself when nothing is tracked.
|
|
98
|
+
const ADOPT_TICK_MS = 10 * 1000;
|
|
91
99
|
|
|
92
100
|
// awaitIndexingDrained: how often it re-asks the background-indexing queue, and
|
|
93
101
|
// how many consecutive empty answers it needs before believing the chains are
|
|
@@ -548,6 +556,26 @@ type LiveStreamState = {
|
|
|
548
556
|
transport: { socket: number; poll: number };
|
|
549
557
|
};
|
|
550
558
|
|
|
559
|
+
/**
|
|
560
|
+
* Creation time (ms epoch) of a request id "stamp:entropy", whose stamp is a time_ns written
|
|
561
|
+
* as 8 bytes of base32hex without padding (the worker's and the producer's _generate_req_id).
|
|
562
|
+
* 0 when it is not one.
|
|
563
|
+
*/
|
|
564
|
+
export function requestIdTimeMs(rid: string): number {
|
|
565
|
+
if (typeof rid !== 'string') return 0;
|
|
566
|
+
var stamp = rid.split(':')[0] || '';
|
|
567
|
+
if (stamp.length !== 13) return 0;
|
|
568
|
+
var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUV';
|
|
569
|
+
var v = 0;
|
|
570
|
+
for (var i = 0; i < stamp.length; i++) {
|
|
571
|
+
var d = alphabet.indexOf(stamp.charAt(i).toUpperCase());
|
|
572
|
+
if (d < 0) return 0;
|
|
573
|
+
v = v * 32 + d;
|
|
574
|
+
}
|
|
575
|
+
// 13 digits are 65 bits for 64 of data: the last bit is padding.
|
|
576
|
+
return Math.floor(v / 2 / 1e6);
|
|
577
|
+
}
|
|
578
|
+
|
|
551
579
|
export class ChatSession {
|
|
552
580
|
host: ChatHost;
|
|
553
581
|
state: ChatState;
|
|
@@ -642,7 +670,10 @@ export class ChatSession {
|
|
|
642
670
|
historyRequestToken: 0,
|
|
643
671
|
gateRefreshToken: 0,
|
|
644
672
|
liveIndexKeys: {},
|
|
673
|
+
indexPageProgress: {},
|
|
674
|
+
passPaging: {},
|
|
645
675
|
liveIndexChecked: false,
|
|
676
|
+
liveIndexRunning: {},
|
|
646
677
|
stoppedIndexIds: {},
|
|
647
678
|
};
|
|
648
679
|
this.bgTaskQueue = [];
|
|
@@ -670,8 +701,8 @@ export class ChatSession {
|
|
|
670
701
|
/** What the display layer needs to decide whether a run is finished. `keys` holds
|
|
671
702
|
* every file the server still has indexing work for; `checked` is false until the
|
|
672
703
|
* first answer for this chat, and false means "we do not know yet". */
|
|
673
|
-
getLiveIndexState(): { keys: { [fileKey: string]: boolean }; checked: boolean } {
|
|
674
|
-
return { keys: this.state.liveIndexKeys, checked: this.state.liveIndexChecked };
|
|
704
|
+
getLiveIndexState(): { keys: { [fileKey: string]: boolean }; checked: boolean; running: { [fileKey: string]: boolean } } {
|
|
705
|
+
return { keys: this.state.liveIndexKeys, checked: this.state.liveIndexChecked, running: this.state.liveIndexRunning || {} };
|
|
675
706
|
}
|
|
676
707
|
|
|
677
708
|
/** Passes that were on a row when the user stopped it, so the display layer can
|
|
@@ -809,6 +840,95 @@ export class ChatSession {
|
|
|
809
840
|
if (storagePath) delete this._indexClaims[this._indexClaimKey(storagePath)];
|
|
810
841
|
}
|
|
811
842
|
|
|
843
|
+
/**
|
|
844
|
+
* Index files that are ALREADY STORED again, without uploading anything: the
|
|
845
|
+
* Reindex answer of the "already uploaded" report, offered for the members a send
|
|
846
|
+
* skipped as duplicates (att.duplicates, see uploadSingleAttachment). The same
|
|
847
|
+
* steps the Files page's Reindex takes: claim the file (one already being indexed
|
|
848
|
+
* is left alone), keep its access group (host.readFileAccessGroup, read before the
|
|
849
|
+
* delete), clear the old index, re-create the file record, queue the first pass.
|
|
850
|
+
* Each file appears in the chat as a "Reindexing" row. Never rejects; resolves to
|
|
851
|
+
* the number of files queued.
|
|
852
|
+
*/
|
|
853
|
+
reindexStoredFiles(list: Array<{ storagePath: string; name?: string; size?: number; mime?: string }>): Promise<number> {
|
|
854
|
+
var self = this;
|
|
855
|
+
var id = this.host.getIdentity();
|
|
856
|
+
var queued = 0;
|
|
857
|
+
if (!id.projectId || (id.platform !== 'claude' && id.platform !== 'openai')) return Promise.resolve(0);
|
|
858
|
+
var chain: Promise<any> = Promise.resolve();
|
|
859
|
+
(list || []).forEach(function (d) {
|
|
860
|
+
if (!d || !d.storagePath) return;
|
|
861
|
+
var storagePath = d.storagePath;
|
|
862
|
+
var name = d.name || storagePath.split('/').filter(Boolean).pop() || storagePath;
|
|
863
|
+
var mime = d.mime || self.host.getMimeType(name) || undefined;
|
|
864
|
+
chain = chain.then(function () {
|
|
865
|
+
var claimed = false;
|
|
866
|
+
var url = '';
|
|
867
|
+
var group: 'public' | 'authorized' | 'private' | undefined;
|
|
868
|
+
return self.claimIndexRun(storagePath).then(function (ok) {
|
|
869
|
+
claimed = ok;
|
|
870
|
+
if (!ok) return; // already being indexed
|
|
871
|
+
return Promise.resolve(self.host.getTemporaryUrl(storagePath)).then(function (u: any) {
|
|
872
|
+
url = typeof u === 'string' ? u : (u && u.url) || '';
|
|
873
|
+
if (!url) return;
|
|
874
|
+
return typeof self.host.readFileAccessGroup === 'function'
|
|
875
|
+
? Promise.resolve(self.host.readFileAccessGroup(storagePath)).then(function (g) { group = g || undefined; })
|
|
876
|
+
: undefined;
|
|
877
|
+
}).then(function () {
|
|
878
|
+
if (!url) return;
|
|
879
|
+
if (typeof self.host.deleteExistingFileRecord === 'function') {
|
|
880
|
+
return Promise.resolve(self.host.deleteExistingFileRecord(storagePath)).catch(function () { });
|
|
881
|
+
}
|
|
882
|
+
}).then(function () {
|
|
883
|
+
if (!url) return;
|
|
884
|
+
if (typeof self.host.ensureFileIndexRecord === 'function') {
|
|
885
|
+
return Promise.resolve(self.host.ensureFileIndexRecord(storagePath, { name: name, mime: mime, size: d.size }, group)).catch(function () { });
|
|
886
|
+
}
|
|
887
|
+
}).then(function () {
|
|
888
|
+
if (!url || group || typeof self.host.uploadAccessGroup !== 'function') return;
|
|
889
|
+
// No stored group (the file record was gone): the group the
|
|
890
|
+
// re-created record was just written at.
|
|
891
|
+
return Promise.resolve(self.host.uploadAccessGroup(storagePath)).then(function (g) { group = g || undefined; }).catch(function () { });
|
|
892
|
+
}).then(function () {
|
|
893
|
+
if (!url) { self.releaseIndexRun(storagePath); return; }
|
|
894
|
+
return self.trackIndexDispatch(notifyAgentSaveAttachment({
|
|
895
|
+
platform: id.platform as 'claude' | 'openai',
|
|
896
|
+
model: id.model,
|
|
897
|
+
service: id.projectId,
|
|
898
|
+
publicProjectId: id.publicProjectId,
|
|
899
|
+
owner: id.owner,
|
|
900
|
+
userId: id.userId || id.projectId,
|
|
901
|
+
serviceName: id.serviceName,
|
|
902
|
+
serviceDescription: id.serviceDescription,
|
|
903
|
+
attachment: { name: name, storagePath: storagePath, mime: mime, size: d.size, url: url, accessGroup: group },
|
|
904
|
+
})).then(function (ack: any) {
|
|
905
|
+
if (ack && typeof ack.id === 'string') {
|
|
906
|
+
queued += 1;
|
|
907
|
+
self.bgTaskQueue.push({
|
|
908
|
+
projectId: id.projectId, platform: id.platform as 'claude' | 'openai', id: ack.id,
|
|
909
|
+
filename: name,
|
|
910
|
+
storagePath: storagePath,
|
|
911
|
+
isReindex: true,
|
|
912
|
+
mime: mime,
|
|
913
|
+
size: d.size,
|
|
914
|
+
status: ack.status === 'running' ? 'running' : 'pending',
|
|
915
|
+
poll: ack.poll,
|
|
916
|
+
});
|
|
917
|
+
self.drainBgTaskQueue();
|
|
918
|
+
} else {
|
|
919
|
+
self.releaseIndexRun(storagePath);
|
|
920
|
+
}
|
|
921
|
+
});
|
|
922
|
+
});
|
|
923
|
+
}).catch(function (err: any) {
|
|
924
|
+
console.error('[chat-engine] reindex of a stored file failed', storagePath, err);
|
|
925
|
+
if (claimed) self.releaseIndexRun(storagePath);
|
|
926
|
+
});
|
|
927
|
+
});
|
|
928
|
+
});
|
|
929
|
+
return chain.then(function () { self.drainBgTaskQueue(); return queued; });
|
|
930
|
+
}
|
|
931
|
+
|
|
812
932
|
/**
|
|
813
933
|
* The same question, asked of the SERVER when this page cannot answer it.
|
|
814
934
|
*
|
|
@@ -877,6 +997,7 @@ export class ChatSession {
|
|
|
877
997
|
*/
|
|
878
998
|
private _recordLiveIndexKeys(lists: any[]): void {
|
|
879
999
|
var next: { [k: string]: boolean } = {};
|
|
1000
|
+
var running: { [k: string]: boolean } = {};
|
|
880
1001
|
// A page that came back FULL is not a whole-queue answer: the query is capped
|
|
881
1002
|
// and ordered newest-first, so a bulk upload of 40 files returns the 20 newest
|
|
882
1003
|
// and omits the 20 about to run. Absence would then read as "finished" for
|
|
@@ -914,6 +1035,10 @@ export class ChatSession {
|
|
|
914
1035
|
// wrong.
|
|
915
1036
|
if (ref.path) next[ref.path] = true;
|
|
916
1037
|
if (ref.name) next[ref.name] = true;
|
|
1038
|
+
if (item.status === 'running') {
|
|
1039
|
+
if (ref.path) running[ref.path] = true;
|
|
1040
|
+
if (ref.name) running[ref.name] = true;
|
|
1041
|
+
}
|
|
917
1042
|
}
|
|
918
1043
|
}
|
|
919
1044
|
var nowChecked = !truncated;
|
|
@@ -922,7 +1047,13 @@ export class ChatSession {
|
|
|
922
1047
|
for (var k in next) if (!was[k]) { changed = true; break; }
|
|
923
1048
|
if (!changed) for (var k2 in was) if (!next[k2]) { changed = true; break; }
|
|
924
1049
|
}
|
|
1050
|
+
if (!changed) {
|
|
1051
|
+
var wasRun = this.state.liveIndexRunning || {};
|
|
1052
|
+
for (var r1 in running) if (!wasRun[r1]) { changed = true; break; }
|
|
1053
|
+
if (!changed) for (var r2 in wasRun) if (!running[r2]) { changed = true; break; }
|
|
1054
|
+
}
|
|
925
1055
|
this.state.liveIndexKeys = next;
|
|
1056
|
+
this.state.liveIndexRunning = running;
|
|
926
1057
|
this.state.liveIndexChecked = nowChecked;
|
|
927
1058
|
this._liveIndexAt = nowMs();
|
|
928
1059
|
// Claim the snapshot for the CURRENT chat. Both callers verify identity before
|
|
@@ -943,8 +1074,11 @@ export class ChatSession {
|
|
|
943
1074
|
* project the user just switched to is unknown until it is asked for again. */
|
|
944
1075
|
private _resetLiveIndexKeys(): void {
|
|
945
1076
|
this.state.liveIndexKeys = {};
|
|
1077
|
+
this.state.liveIndexRunning = {};
|
|
946
1078
|
this.state.liveIndexChecked = false;
|
|
947
1079
|
this._liveIndexAt = 0;
|
|
1080
|
+
// Steps loaded into rows belong to that chat too.
|
|
1081
|
+
this.state.passPaging = {};
|
|
948
1082
|
}
|
|
949
1083
|
|
|
950
1084
|
/**
|
|
@@ -976,7 +1110,21 @@ export class ChatSession {
|
|
|
976
1110
|
// pass-boundary gap the ladder exists for presumes a chain was alive,
|
|
977
1111
|
// and on an idle tab return the climb was three round trips of asking
|
|
978
1112
|
// a question whose answer had not changed.
|
|
1113
|
+
//
|
|
1114
|
+
// SKIPPED (2026-11-20) when a look already confirmed the queue idle, no pass on
|
|
1115
|
+
// screen is newer than that, and this page tracks nothing live: then the answer is
|
|
1116
|
+
// known, and every tab return used to ask it again. "Nothing live" is still RECORDED,
|
|
1117
|
+
// as the look would have, so finished rows do not fall back to spinning. A run begun
|
|
1118
|
+
// elsewhere since shows up in the history page this follows (newer `_ts`, or a bg
|
|
1119
|
+
// poll attached to its running item), which is evidence, and the look runs.
|
|
1120
|
+
var sid = this.host.getIdentity().projectId;
|
|
1121
|
+
var idleAt = sid ? this._idleVerdictAt[sid] : 0;
|
|
1122
|
+
if (sid && idleAt && !this._hasLocalLiveIndexWork(sid) && this._newestIndexPassTs() <= idleAt) {
|
|
1123
|
+
this._recordLiveIndexKeys([{ list: [] }, { list: [] }]);
|
|
1124
|
+
return;
|
|
1125
|
+
}
|
|
979
1126
|
this._adoptWorkerIndexingPasses(0, true);
|
|
1127
|
+
this._ensureAdoptTick();
|
|
980
1128
|
}
|
|
981
1129
|
|
|
982
1130
|
/** Forget what we know about which files are indexing — but ONLY when the
|
|
@@ -2170,6 +2318,7 @@ export class ChatSession {
|
|
|
2170
2318
|
if (!isErr) {
|
|
2171
2319
|
var rNote = extractRetrievalNote(body, text);
|
|
2172
2320
|
if (rNote) reply._retrieval = rNote;
|
|
2321
|
+
this._saveFindings(itemId, body, text, rNote);
|
|
2173
2322
|
}
|
|
2174
2323
|
if (ownerKey && this.getHistoryCacheKey() !== ownerKey) {
|
|
2175
2324
|
// The reader is in another chat. Settle it where it belongs and touch
|
|
@@ -2320,12 +2469,42 @@ export class ChatSession {
|
|
|
2320
2469
|
return Promise.resolve()
|
|
2321
2470
|
.then(function () {
|
|
2322
2471
|
self.drainBgTaskQueue();
|
|
2323
|
-
|
|
2472
|
+
// History is loaded ONCE (owner, 2026-11-20): coming back to the tab does not
|
|
2473
|
+
// refetch it. What changed while away arrives the way it would have live:
|
|
2474
|
+
// replies through their polls (foreground polls never paused), indexing
|
|
2475
|
+
// passes through the queue check that drainBgTaskQueue restarts. Only a
|
|
2476
|
+
// waiting bubble left with nothing to settle it needs the first page again.
|
|
2477
|
+
if (self.needsHistoryRefetch()) return self.loadHistory(false, self.state.gateRefreshToken);
|
|
2478
|
+
self.refreshLiveIndexState();
|
|
2324
2479
|
})
|
|
2325
2480
|
.catch(function (e: any) { console.error('[chat-engine] resume polling failed', e); })
|
|
2326
2481
|
.then(function () { self._resuming = false; });
|
|
2327
2482
|
}
|
|
2328
2483
|
|
|
2484
|
+
/**
|
|
2485
|
+
* Does the chat on screen need its first history page fetched again to stay right?
|
|
2486
|
+
* Only when a waiting bubble of THIS chat has nothing that will settle it: no live poll
|
|
2487
|
+
* and no entry in bgTaskQueue (whose passes the drain and the queue check follow). Then
|
|
2488
|
+
* the page is the only place its poll handle or its answer can come from (a turn on the
|
|
2489
|
+
* background queue whose poll paused while the tab was hidden, for instance). A bubble
|
|
2490
|
+
* with no server id yet is a send still in flight, which resolves on its own.
|
|
2491
|
+
*/
|
|
2492
|
+
needsHistoryRefetch(): boolean {
|
|
2493
|
+
var key = this.getHistoryCacheKey();
|
|
2494
|
+
var tracked: { [id: string]: true } = {};
|
|
2495
|
+
for (var q = 0; q < this.bgTaskQueue.length; q++) if (this.bgTaskQueue[q]) tracked[this.bgTaskQueue[q].id] = true;
|
|
2496
|
+
for (var i = 0; i < this.state.messages.length; i++) {
|
|
2497
|
+
var m = this.state.messages[i];
|
|
2498
|
+
if (!m || !(m.isPending || m.isPendingQueued || m.isPendingInProcess)) continue;
|
|
2499
|
+
if (m._ownerKey !== undefined && m._ownerKey !== key) continue;
|
|
2500
|
+
var sid = m._serverItemId;
|
|
2501
|
+
if (!sid) continue;
|
|
2502
|
+
if (this.historyItemPolls.has(sid) || tracked[sid]) continue;
|
|
2503
|
+
return true;
|
|
2504
|
+
}
|
|
2505
|
+
return false;
|
|
2506
|
+
}
|
|
2507
|
+
|
|
2329
2508
|
private _newLocalId(): string {
|
|
2330
2509
|
this._lidSeq += 1;
|
|
2331
2510
|
return 'lid_' + this._lidSeq;
|
|
@@ -2680,7 +2859,7 @@ export class ChatSession {
|
|
|
2680
2859
|
answer = (answer || '').trim();
|
|
2681
2860
|
// Retrieval memory: what this turn read, off the body's tool blocks (a
|
|
2682
2861
|
// streamed turn's `response` is already the assembled body here).
|
|
2683
|
-
return { content: answer || 'No text response received from AI provider.', isError: false, retrieval: extractRetrievalNote(response, answer) };
|
|
2862
|
+
return { content: answer || 'No text response received from AI provider.', isError: false, retrieval: extractRetrievalNote(response, answer), body: response };
|
|
2684
2863
|
})
|
|
2685
2864
|
.catch(function (err: any) { return { content: getErrorMessage(err), isError: true }; })
|
|
2686
2865
|
.then(function (result: any) {
|
|
@@ -2700,6 +2879,7 @@ export class ChatSession {
|
|
|
2700
2879
|
var reply: ChatMessage = { role: 'assistant', content: result.content, isError: result.isError };
|
|
2701
2880
|
if (dispatchItemId) reply._serverItemId = dispatchItemId;
|
|
2702
2881
|
if (result.retrieval) reply._retrieval = result.retrieval;
|
|
2882
|
+
if (!result.isError && result.body) self._saveFindings(dispatchItemId, result.body, result.content, result.retrieval);
|
|
2703
2883
|
|
|
2704
2884
|
// REPLACE the trailing pending "Thinking..." bubble in the cache with
|
|
2705
2885
|
// the answer, regardless of whether this chat is the currently-visible
|
|
@@ -3337,9 +3517,19 @@ export class ChatSession {
|
|
|
3337
3517
|
}
|
|
3338
3518
|
|
|
3339
3519
|
promoteNextBgQueuedToRunning(): void {
|
|
3340
|
-
|
|
3520
|
+
// Passes the queue check follows (byListing) are never promoted by this guess: the
|
|
3521
|
+
// worker runs several at once in any order, so "the next waiting one" is often the
|
|
3522
|
+
// wrong one, and the running listing promotes them by id (_promoteListedRunning).
|
|
3523
|
+
// The guess stays for anything else on the background queue.
|
|
3524
|
+
var listed: { [id: string]: true } = {};
|
|
3525
|
+
for (var q = 0; q < this.bgTaskQueue.length; q++) {
|
|
3526
|
+
var qe = this.bgTaskQueue[q];
|
|
3527
|
+
if (qe && qe.byListing) listed[qe.id] = true;
|
|
3528
|
+
}
|
|
3529
|
+
var guessed = function (m: ChatMessage) { return !(m._serverItemId && listed[m._serverItemId]); };
|
|
3530
|
+
if (this.state.messages.some(function (m) { return m.isPending && m.role === 'assistant' && m.isBackgroundTask && guessed(m); })) return;
|
|
3341
3531
|
var nextIdx = this.state.messages.findIndex(function (m) {
|
|
3342
|
-
return m.isPendingQueued && m.role === 'user' && m.isBackgroundTask;
|
|
3532
|
+
return m.isPendingQueued && m.role === 'user' && m.isBackgroundTask && guessed(m);
|
|
3343
3533
|
});
|
|
3344
3534
|
if (nextIdx === -1) return;
|
|
3345
3535
|
var existing = this.state.messages[nextIdx];
|
|
@@ -3538,6 +3728,7 @@ export class ChatSession {
|
|
|
3538
3728
|
if (!offReply.isError) {
|
|
3539
3729
|
var offNote = extractRetrievalNote(response, offReply.content);
|
|
3540
3730
|
if (offNote) offReply._retrieval = offNote;
|
|
3731
|
+
this._saveFindings(serverId, response, offReply.content, offNote);
|
|
3541
3732
|
}
|
|
3542
3733
|
this._applyReplyToCache(ownerKey, offReply, serverId);
|
|
3543
3734
|
if (serverId) this.cancelledServerIds.delete(serverId);
|
|
@@ -3557,6 +3748,7 @@ export class ChatSession {
|
|
|
3557
3748
|
// Retrieval memory for this turn, attached to whichever bubble below ends up
|
|
3558
3749
|
// holding the answer.
|
|
3559
3750
|
var qNote = extractRetrievalNote(response, answer);
|
|
3751
|
+
this._saveFindings(serverId, response, answer, qNote);
|
|
3560
3752
|
var lid = this._newLocalId();
|
|
3561
3753
|
if (targetIdx >= 0 && this.state.messages[targetIdx] && this.state.messages[targetIdx].isPending) {
|
|
3562
3754
|
// Same resume as the immediate-send path: keep what the stream painted
|
|
@@ -4541,6 +4733,7 @@ export class ChatSession {
|
|
|
4541
4733
|
// Retrieval memory for a CHAT turn that settled through a re-attached poll.
|
|
4542
4734
|
// Read once here; the background branches below never use it.
|
|
4543
4735
|
var hNote = isErr ? null : extractRetrievalNote(response, answer);
|
|
4736
|
+
if (hNote) this._saveFindings(itemId, response, answer, hNote);
|
|
4544
4737
|
var stripMarker = function (t: string): string {
|
|
4545
4738
|
return reportedComplete ? t.split(INDEXING_COMPLETE_MARKER).join('').trim() : t;
|
|
4546
4739
|
};
|
|
@@ -4754,7 +4947,488 @@ export class ChatSession {
|
|
|
4754
4947
|
* shape that previously looped fetchHistoryPage after an already-DONE index.
|
|
4755
4948
|
*/
|
|
4756
4949
|
private _adoptingWorkerPasses = false;
|
|
4757
|
-
|
|
4950
|
+
/** Per project: when a look last CONFIRMED the bg queue held nothing pending or running
|
|
4951
|
+
* (2026-11-20). A recent pass older than this is a finished run, not evidence of live
|
|
4952
|
+
* work, so a tab return no longer re-asks for ten minutes after every run. Memory only:
|
|
4953
|
+
* a reload starts without it and asks once, as before. */
|
|
4954
|
+
private _idleVerdictAt: { [svcId: string]: number } = {};
|
|
4955
|
+
private _adoptTickTimer: any = null;
|
|
4956
|
+
|
|
4957
|
+
/** Newest wall-clock `_ts` of any indexing pass on screen, or 0. */
|
|
4958
|
+
private _newestIndexPassTs(): number {
|
|
4959
|
+
var newest = 0;
|
|
4960
|
+
var msgs = this.state.messages;
|
|
4961
|
+
for (var i = 0; i < msgs.length; i++) {
|
|
4962
|
+
var m = msgs[i];
|
|
4963
|
+
if (m && m._indexFile && typeof m._ts === 'number' && m._ts > newest) newest = m._ts;
|
|
4964
|
+
}
|
|
4965
|
+
return newest;
|
|
4966
|
+
}
|
|
4967
|
+
|
|
4968
|
+
/** Live indexing work THIS page is tracking for the project: a queued or adopted pass,
|
|
4969
|
+
* an attached bg poll, or a live key a look recorded. No recency guess. */
|
|
4970
|
+
private _hasLocalLiveIndexWork(svcId: string): boolean {
|
|
4971
|
+
for (var i = 0; i < this.bgTaskQueue.length; i++) {
|
|
4972
|
+
var e = this.bgTaskQueue[i];
|
|
4973
|
+
if (e && e.projectId === svcId) return true;
|
|
4974
|
+
}
|
|
4975
|
+
var keys = this.state.liveIndexKeys || {};
|
|
4976
|
+
for (var k in keys) { if (keys[k]) return true; }
|
|
4977
|
+
var found = false;
|
|
4978
|
+
this.historyItemPolls.forEach(function (h: any) { if (h && h.kind === 'bg') found = true; });
|
|
4979
|
+
return found;
|
|
4980
|
+
}
|
|
4981
|
+
|
|
4982
|
+
/** Start the ADOPT_TICK_MS follow-up if this page is tracking live indexing work and
|
|
4983
|
+
* is visible. Idempotent; each tick re-checks and stops when the work is gone, the tab
|
|
4984
|
+
* is hidden (resume restarts it through refreshLiveIndexState) or the view closed. */
|
|
4985
|
+
private _ensureAdoptTick(): void {
|
|
4986
|
+
if (this._adoptTickTimer) return;
|
|
4987
|
+
var self = this;
|
|
4988
|
+
var id = this.host.getIdentity();
|
|
4989
|
+
if (!id.projectId || (id.platform !== 'claude' && id.platform !== 'openai')) return;
|
|
4990
|
+
if (this.isPollingPaused() || !this.host.isViewMounted()) return;
|
|
4991
|
+
if (!this._hasLocalLiveIndexWork(id.projectId)) return;
|
|
4992
|
+
this._adoptTickTimer = setTimeout(function () {
|
|
4993
|
+
self._adoptTickTimer = null;
|
|
4994
|
+
var now = self.host.getIdentity();
|
|
4995
|
+
if (self.isPollingPaused() || !self.host.isViewMounted()) return;
|
|
4996
|
+
if (now.projectId !== id.projectId) { self._ensureAdoptTick(); return; }
|
|
4997
|
+
if (!self._hasLocalLiveIndexWork(now.projectId)) return;
|
|
4998
|
+
self._adoptWorkerIndexingPasses(0, false, true);
|
|
4999
|
+
self._settleByListing();
|
|
5000
|
+
self._refreshPageProgress();
|
|
5001
|
+
self._ensureAdoptTick();
|
|
5002
|
+
}, ADOPT_TICK_MS);
|
|
5003
|
+
}
|
|
5004
|
+
|
|
5005
|
+
/** The last COMPLETE running+pending look at this user's bg queue: which pass ids were
|
|
5006
|
+
* live. Complete means both lists came back shorter than their limit, so a tracked pass
|
|
5007
|
+
* missing from it really has left the queue. */
|
|
5008
|
+
private _lastLiveLook: { svcId: string; platform: string; at: number; ids: { [id: string]: true } } | null = null;
|
|
5009
|
+
/** By-listing passes whose by-id lookup is in flight, so one tick never reads a pass twice. */
|
|
5010
|
+
private _listingSettling: { [id: string]: true } = {};
|
|
5011
|
+
private _listingLookInflight = false;
|
|
5012
|
+
|
|
5013
|
+
/**
|
|
5014
|
+
* Follow an indexing pass found in a loaded history page through the queue check
|
|
5015
|
+
* instead of polling it (owner, 2026-11-20): polls on one queue run one at a time in
|
|
5016
|
+
* skapi-js, so after a reload mid-run every lane waited behind the first. Only for a
|
|
5017
|
+
* pass the worker drives (a client-driven chain is resumed off its dispatching entry,
|
|
5018
|
+
* whose pass count caps it) and only when the host can read a row by id. True when the
|
|
5019
|
+
* pass is now tracked (the caller then attaches no poll).
|
|
5020
|
+
*/
|
|
5021
|
+
trackHistoryIndexPass(item: any): boolean {
|
|
5022
|
+
if (typeof chatEngineConfig().csrHistoryItemLookup !== 'function') return false;
|
|
5023
|
+
if (!item || typeof item.id !== 'string' || !item.id) return false;
|
|
5024
|
+
if (item.status !== 'pending' && item.status !== 'running') return false;
|
|
5025
|
+
for (var q = 0; q < this.bgTaskQueue.length; q++) {
|
|
5026
|
+
if (this.bgTaskQueue[q] && this.bgTaskQueue[q].id === item.id) return !!this.bgTaskQueue[q].byListing;
|
|
5027
|
+
}
|
|
5028
|
+
var id = this.host.getIdentity();
|
|
5029
|
+
var platform = id.platform;
|
|
5030
|
+
if (!id.projectId || (platform !== 'claude' && platform !== 'openai')) return false;
|
|
5031
|
+
var text = typeof item.request_text === 'string' && item.request_text
|
|
5032
|
+
? item.request_text
|
|
5033
|
+
: extractLastUserTextFromRequest(item.request_body);
|
|
5034
|
+
var ref = parseIndexingRequestText(text);
|
|
5035
|
+
if (!ref || !ref.name) return false;
|
|
5036
|
+
if (!this._isWorkerDrivenIndexing(ref.name, ref.mime)) return false;
|
|
5037
|
+
this.bgTaskQueue.push({
|
|
5038
|
+
projectId: id.projectId,
|
|
5039
|
+
platform: platform,
|
|
5040
|
+
id: item.id,
|
|
5041
|
+
filename: ref.name,
|
|
5042
|
+
storagePath: ref.path,
|
|
5043
|
+
mime: ref.mime,
|
|
5044
|
+
size: ref.size,
|
|
5045
|
+
status: item.status === 'running' ? 'running' : 'pending',
|
|
5046
|
+
poll: typeof item.poll === 'function' ? item.poll : undefined,
|
|
5047
|
+
resumePass: ref.continued ? 1 : 0,
|
|
5048
|
+
byListing: true,
|
|
5049
|
+
adoptedAt: Date.now(),
|
|
5050
|
+
});
|
|
5051
|
+
return true;
|
|
5052
|
+
}
|
|
5053
|
+
|
|
5054
|
+
/**
|
|
5055
|
+
* Show a pass as RUNNING once the queue says it is. A pass this client sent starts out
|
|
5056
|
+
* waiting (the server queues it), and its own poll's running tick used to be what
|
|
5057
|
+
* moved it on. Settled from the listing, it has no poll, so the running listing the
|
|
5058
|
+
* 10-second check already takes does it instead (owner, 2026-11-20).
|
|
5059
|
+
*/
|
|
5060
|
+
private _promoteListedRunning(runningRes: any): void {
|
|
5061
|
+
var list = runningRes && Array.isArray(runningRes.list) ? runningRes.list : [];
|
|
5062
|
+
if (!list.length) return;
|
|
5063
|
+
var running: { [id: string]: true } = {};
|
|
5064
|
+
for (var i = 0; i < list.length; i++) if (list[i] && typeof list[i].id === 'string') running[list[i].id] = true;
|
|
5065
|
+
var changed = false;
|
|
5066
|
+
for (var q = 0; q < this.bgTaskQueue.length; q++) {
|
|
5067
|
+
var e = this.bgTaskQueue[q];
|
|
5068
|
+
if (!e || e.status !== 'pending' || !running[e.id]) continue;
|
|
5069
|
+
e.status = 'running';
|
|
5070
|
+
if (this._promoteBgItemToRunning(e.id)) changed = true;
|
|
5071
|
+
}
|
|
5072
|
+
if (changed) {
|
|
5073
|
+
this.host.notify();
|
|
5074
|
+
this.updateHistoryCache();
|
|
5075
|
+
}
|
|
5076
|
+
}
|
|
5077
|
+
|
|
5078
|
+
/** promoteNextBgQueuedToRunning for one named pass: its waiting request bubble becomes
|
|
5079
|
+
* the running one, with a "Thinking..." placeholder under it. False when that pass has
|
|
5080
|
+
* no waiting bubble (already running, settled, or not on screen). */
|
|
5081
|
+
private _promoteBgItemToRunning(itemId: string): boolean {
|
|
5082
|
+
var idx = this.state.messages.findIndex(function (m) {
|
|
5083
|
+
return m.role === 'user' && m.isBackgroundTask && m.isPendingQueued && m._serverItemId === itemId;
|
|
5084
|
+
});
|
|
5085
|
+
if (idx === -1) return false;
|
|
5086
|
+
var existing = this.state.messages[idx];
|
|
5087
|
+
var promoted: ChatMessage = { role: 'user', content: existing.content, isPendingInProcess: true, isBackgroundTask: true, _serverItemId: itemId };
|
|
5088
|
+
if (existing._indexFile) promoted._indexFile = existing._indexFile;
|
|
5089
|
+
if (existing._ts !== undefined) promoted._ts = existing._ts;
|
|
5090
|
+
if (existing._ownerKey !== undefined) promoted._ownerKey = existing._ownerKey;
|
|
5091
|
+
this.state.messages[idx] = promoted;
|
|
5092
|
+
var placeholder: ChatMessage = { role: 'assistant', content: '', isPending: true, isPendingInProcess: true, isBackgroundTask: true, _serverItemId: itemId };
|
|
5093
|
+
if (existing._ownerKey !== undefined) placeholder._ownerKey = existing._ownerKey;
|
|
5094
|
+
this.state.messages.splice(idx + 1, 0, placeholder);
|
|
5095
|
+
return true;
|
|
5096
|
+
}
|
|
5097
|
+
|
|
5098
|
+
/** Turns whose findings were already looked at (a turn can settle by more than one path). */
|
|
5099
|
+
private _findingsDone: { [itemId: string]: true } = {};
|
|
5100
|
+
|
|
5101
|
+
/**
|
|
5102
|
+
* Save where a hard search found its answer (findings.ts), through the host's
|
|
5103
|
+
* saveSearchFinding hook. Never for an indexing pass, never twice for one turn, never
|
|
5104
|
+
* throws, never waited on.
|
|
5105
|
+
*/
|
|
5106
|
+
private _saveFindings(itemId: string | undefined, body: any, answer: string | null | undefined, note: RetrievalNote | null | undefined): void {
|
|
5107
|
+
try {
|
|
5108
|
+
var save = chatEngineConfig().saveSearchFinding;
|
|
5109
|
+
if (typeof save !== 'function' || !note || !body) return;
|
|
5110
|
+
if (itemId) {
|
|
5111
|
+
if (this._findingsDone[itemId]) return;
|
|
5112
|
+
this._findingsDone[itemId] = true;
|
|
5113
|
+
}
|
|
5114
|
+
// The question: the user bubble of this turn (same server id), when it is on screen.
|
|
5115
|
+
var question: string | null = null;
|
|
5116
|
+
if (itemId) {
|
|
5117
|
+
for (var i = 0; i < this.state.messages.length; i++) {
|
|
5118
|
+
var m = this.state.messages[i];
|
|
5119
|
+
if (m && m.role === 'user' && m._serverItemId === itemId) {
|
|
5120
|
+
if (m.isBackgroundTask) return; // an indexing pass, not a chat turn
|
|
5121
|
+
question = typeof m.content === 'string' ? m.content : null;
|
|
5122
|
+
break;
|
|
5123
|
+
}
|
|
5124
|
+
}
|
|
5125
|
+
}
|
|
5126
|
+
var found = findingsForTurn({ question: question, body: body, note: note, answer: answer });
|
|
5127
|
+
if (!found.length) return;
|
|
5128
|
+
var id = this.host.getIdentity();
|
|
5129
|
+
if (!id.projectId) return;
|
|
5130
|
+
for (var f = 0; f < found.length; f++) {
|
|
5131
|
+
var payload = Object.assign({ service: id.projectId, owner: id.owner }, found[f]);
|
|
5132
|
+
Promise.resolve(save(payload)).catch(function () { /* best effort */ });
|
|
5133
|
+
}
|
|
5134
|
+
} catch (e) { /* never in the way of the answer */ }
|
|
5135
|
+
}
|
|
5136
|
+
|
|
5137
|
+
/**
|
|
5138
|
+
* Chats-only history (owner, 2026-11-21): on when the host can list a file's passes
|
|
5139
|
+
* (listIndexPasses) and read one by id (csrHistoryItemLookup). The history fetch then
|
|
5140
|
+
* skips the indexing queue, a file's row comes from its run:: record, and opening the
|
|
5141
|
+
* row loads its passes (loadRunPasses), a page at a time.
|
|
5142
|
+
*/
|
|
5143
|
+
lazyIndexRowsEnabled(): boolean {
|
|
5144
|
+
var cfg = chatEngineConfig();
|
|
5145
|
+
return typeof cfg.listIndexPasses === 'function' && typeof cfg.csrHistoryItemLookup === 'function';
|
|
5146
|
+
}
|
|
5147
|
+
|
|
5148
|
+
/** How many passes one "Load more" brings into a file's row. */
|
|
5149
|
+
static RUN_PASS_PAGE = 10;
|
|
5150
|
+
|
|
5151
|
+
/** The paging state of a file's passes, or null before its row was first opened. */
|
|
5152
|
+
runPassPaging(storagePath?: string): { ids: string[]; loaded: number; loading: boolean; done: boolean; error?: string } | null {
|
|
5153
|
+
if (!storagePath || !this.state.passPaging) return null;
|
|
5154
|
+
return this.state.passPaging[storagePath] || null;
|
|
5155
|
+
}
|
|
5156
|
+
|
|
5157
|
+
/**
|
|
5158
|
+
* Load the next page of a file's indexing passes into the chat, newest first (owner,
|
|
5159
|
+
* 2026-11-21). The ids come from the file's pass records (listIndexPasses, once), each
|
|
5160
|
+
* pass is read by id (csrHistoryItemLookup) and lands as the same request + reply bubbles
|
|
5161
|
+
* a live pass produces, so its file's row groups it like any other. A pass still running
|
|
5162
|
+
* or waiting is left to the live queue check, which shows it as it settles; one already
|
|
5163
|
+
* in the chat is not read again. Never throws.
|
|
5164
|
+
*/
|
|
5165
|
+
loadRunPasses(storagePath: string, fileName?: string): Promise<void> {
|
|
5166
|
+
var self = this;
|
|
5167
|
+
var cfg = chatEngineConfig();
|
|
5168
|
+
var list = cfg.listIndexPasses, lookup = cfg.csrHistoryItemLookup;
|
|
5169
|
+
var id = this.host.getIdentity();
|
|
5170
|
+
var platform = id.platform;
|
|
5171
|
+
if (!storagePath || typeof list !== 'function' || typeof lookup !== 'function') return Promise.resolve();
|
|
5172
|
+
if (!id.projectId || (platform !== 'claude' && platform !== 'openai')) return Promise.resolve();
|
|
5173
|
+
if (!this.state.passPaging) this.state.passPaging = {};
|
|
5174
|
+
var paging = this.state.passPaging[storagePath];
|
|
5175
|
+
if (paging && (paging.loading || paging.done)) return Promise.resolve();
|
|
5176
|
+
if (!paging) {
|
|
5177
|
+
this.state.passPaging[storagePath] = { ids: [], loaded: 0, loading: false, done: false };
|
|
5178
|
+
}
|
|
5179
|
+
// Read back through the state, never the object just stored: a host may hold the state
|
|
5180
|
+
// as a reactive proxy (Vue), and writes to the raw object would never reach the screen.
|
|
5181
|
+
var p = this.state.passPaging[storagePath];
|
|
5182
|
+
p.loading = true;
|
|
5183
|
+
p.error = undefined;
|
|
5184
|
+
this.host.notify();
|
|
5185
|
+
var svcId = id.projectId, owner = id.owner;
|
|
5186
|
+
var name = fileName || storagePath.split('/').pop() || storagePath;
|
|
5187
|
+
var idsReady: Promise<string[]> = p.ids.length
|
|
5188
|
+
? Promise.resolve(p.ids)
|
|
5189
|
+
: Promise.resolve(list(svcId, storagePath)).then(function (ids) {
|
|
5190
|
+
var clean = (Array.isArray(ids) ? ids : []).filter(function (x) { return typeof x === 'string' && !!x; });
|
|
5191
|
+
// Request ids sort by time ("stamp:entropy", the stamp a time_ns): newest first.
|
|
5192
|
+
clean.sort(function (a, b) { return a < b ? 1 : a > b ? -1 : 0; });
|
|
5193
|
+
p.ids = clean;
|
|
5194
|
+
return clean;
|
|
5195
|
+
});
|
|
5196
|
+
return idsReady.then(function (ids) {
|
|
5197
|
+
var oldest = ids.length ? ids[ids.length - 1] : '';
|
|
5198
|
+
var present: { [rid: string]: true } = {};
|
|
5199
|
+
for (var i = 0; i < self.state.messages.length; i++) {
|
|
5200
|
+
var m = self.state.messages[i];
|
|
5201
|
+
if (m && m._serverItemId) present[m._serverItemId] = true;
|
|
5202
|
+
}
|
|
5203
|
+
// The next RUN_PASS_PAGE steps not already on screen (a step the live check or an
|
|
5204
|
+
// earlier page brought in is passed over, not counted).
|
|
5205
|
+
var page: string[] = [];
|
|
5206
|
+
var next = p.loaded;
|
|
5207
|
+
while (next < ids.length && page.length < ChatSession.RUN_PASS_PAGE) {
|
|
5208
|
+
if (!present[ids[next]]) page.push(ids[next]);
|
|
5209
|
+
next++;
|
|
5210
|
+
}
|
|
5211
|
+
return Promise.all(page.map(function (rid) {
|
|
5212
|
+
return Promise.resolve(lookup!(buildHistoryItemFullId(platform as 'claude' | 'openai', svcId, rid), svcId, owner))
|
|
5213
|
+
.then(function (body: any) { return { rid: rid, body: body, err: null as any }; },
|
|
5214
|
+
function (err: any) { return { rid: rid, body: null, err: err }; });
|
|
5215
|
+
})).then(function (got) {
|
|
5216
|
+
if (self.host.getIdentity().projectId !== svcId) return;
|
|
5217
|
+
var add: ChatMessage[][] = [];
|
|
5218
|
+
for (var g = 0; g < got.length; g++) {
|
|
5219
|
+
var r = got[g];
|
|
5220
|
+
if (!r) continue;
|
|
5221
|
+
var body = r.body;
|
|
5222
|
+
// Live work (running or waiting) is the queue check's to show.
|
|
5223
|
+
if (isCsrStatusEnvelope(body) && (body.status === 'running' || body.status === 'pending')) continue;
|
|
5224
|
+
var notExists = r.err && (r.err.code === 'NOT_EXISTS' || (r.err.body && r.err.body.code === 'NOT_EXISTS'));
|
|
5225
|
+
if (notExists) continue;
|
|
5226
|
+
var continued = r.rid !== oldest;
|
|
5227
|
+
var when = requestIdTimeMs(r.rid);
|
|
5228
|
+
var user: ChatMessage = {
|
|
5229
|
+
role: 'user',
|
|
5230
|
+
content: self.host.formatIndexingLabel(name, undefined, null, storagePath, false, continued),
|
|
5231
|
+
isBackgroundTask: true,
|
|
5232
|
+
_serverItemId: r.rid,
|
|
5233
|
+
_indexFile: { name: name, path: storagePath, isReindex: false, continued: continued },
|
|
5234
|
+
};
|
|
5235
|
+
if (when) user._ts = when;
|
|
5236
|
+
var reply: ChatMessage;
|
|
5237
|
+
if (r.err) {
|
|
5238
|
+
reply = { role: 'assistant', content: getErrorMessage(r.err), isError: true, isBackgroundTask: true, _serverItemId: r.rid };
|
|
5239
|
+
} else if (isCsrStatusEnvelope(body) && body.status === 'cancelled') {
|
|
5240
|
+
user.isCancelled = true;
|
|
5241
|
+
add.push([user]);
|
|
5242
|
+
continue;
|
|
5243
|
+
} else if (isErrorResponseBody(body)) {
|
|
5244
|
+
reply = { role: 'assistant', content: getErrorMessage(body), isError: true, isBackgroundTask: true, _serverItemId: r.rid };
|
|
5245
|
+
} else {
|
|
5246
|
+
var text = ((platform === 'openai' ? extractOpenAIText(body) : extractClaudeText(body)) || '').trim();
|
|
5247
|
+
var complete = text.indexOf(INDEXING_COMPLETE_MARKER) !== -1;
|
|
5248
|
+
if (complete) text = text.split(INDEXING_COMPLETE_MARKER).join('').trim();
|
|
5249
|
+
reply = { role: 'assistant', content: text || EMPTY_INDEXING_REPLY, isBackgroundTask: true, _serverItemId: r.rid };
|
|
5250
|
+
if (complete) reply._indexComplete = true;
|
|
5251
|
+
}
|
|
5252
|
+
if (when) reply._ts = when;
|
|
5253
|
+
add.push([user, reply]);
|
|
5254
|
+
}
|
|
5255
|
+
// Oldest first, each pair at its place in time among the messages.
|
|
5256
|
+
add.sort(function (a, b) { return (a[0]._ts || 0) - (b[0]._ts || 0); });
|
|
5257
|
+
for (var k = 0; k < add.length; k++) self._insertByTime(add[k]);
|
|
5258
|
+
p.loaded = next;
|
|
5259
|
+
p.done = p.loaded >= ids.length;
|
|
5260
|
+
});
|
|
5261
|
+
}).catch(function (err: any) {
|
|
5262
|
+
p.error = getErrorMessage(err) || 'The steps could not be loaded.';
|
|
5263
|
+
}).then(function () {
|
|
5264
|
+
p.loading = false;
|
|
5265
|
+
self.host.notify();
|
|
5266
|
+
self.updateHistoryCache();
|
|
5267
|
+
});
|
|
5268
|
+
}
|
|
5269
|
+
|
|
5270
|
+
/** Insert bubbles before the first message that is newer than them (by `_ts`); messages
|
|
5271
|
+
* without a time are skipped over, and the end of the list takes them otherwise. */
|
|
5272
|
+
private _insertByTime(bubbles: ChatMessage[]): void {
|
|
5273
|
+
var at = bubbles[0] && bubbles[0]._ts;
|
|
5274
|
+
var idx = this.state.messages.length;
|
|
5275
|
+
if (typeof at === 'number') {
|
|
5276
|
+
for (var i = 0; i < this.state.messages.length; i++) {
|
|
5277
|
+
var t = this.state.messages[i] && this.state.messages[i]._ts;
|
|
5278
|
+
if (typeof t === 'number' && t > at) { idx = i; break; }
|
|
5279
|
+
}
|
|
5280
|
+
}
|
|
5281
|
+
Array.prototype.splice.apply(this.state.messages, ([idx, 0] as any[]).concat(bubbles));
|
|
5282
|
+
}
|
|
5283
|
+
|
|
5284
|
+
private _progressInflight = false;
|
|
5285
|
+
|
|
5286
|
+
/**
|
|
5287
|
+
* Refresh the page progress ("175 of 530 pages") of the documents this page is still
|
|
5288
|
+
* tracking passes for, one read per file (config readIndexProgress, the MCP's
|
|
5289
|
+
* prog::<path> record). Runs on the ADOPT_TICK_MS check; a file with nothing tracked is
|
|
5290
|
+
* not asked about. Never throws.
|
|
5291
|
+
*/
|
|
5292
|
+
private _refreshPageProgress(): void {
|
|
5293
|
+
var read = chatEngineConfig().readIndexProgress;
|
|
5294
|
+
if (typeof read !== 'function' || this._progressInflight) return;
|
|
5295
|
+
var id = this.host.getIdentity();
|
|
5296
|
+
if (!id.projectId || this.isPollingPaused() || !this.host.isViewMounted()) return;
|
|
5297
|
+
var svcId = id.projectId;
|
|
5298
|
+
var paths: string[] = [];
|
|
5299
|
+
for (var i = 0; i < this.bgTaskQueue.length; i++) {
|
|
5300
|
+
var e = this.bgTaskQueue[i];
|
|
5301
|
+
if (e && e.projectId === svcId && e.storagePath && paths.indexOf(e.storagePath) === -1) paths.push(e.storagePath);
|
|
5302
|
+
}
|
|
5303
|
+
if (!paths.length) return;
|
|
5304
|
+
var self = this;
|
|
5305
|
+
this._progressInflight = true;
|
|
5306
|
+
Promise.all(paths.map(function (path) {
|
|
5307
|
+
return Promise.resolve(read!(svcId, path)).then(function (data) { return { path: path, data: data }; }, function () { return { path: path, data: null }; });
|
|
5308
|
+
})).then(function (rows) {
|
|
5309
|
+
self._progressInflight = false;
|
|
5310
|
+
if (self.host.getIdentity().projectId !== svcId) return;
|
|
5311
|
+
if (!self.state.indexPageProgress) self.state.indexPageProgress = {};
|
|
5312
|
+
var changed = false;
|
|
5313
|
+
for (var r = 0; r < rows.length; r++) {
|
|
5314
|
+
var d: any = rows[r].data;
|
|
5315
|
+
var saved = d && typeof d.pages_saved === 'number' ? d.pages_saved : null;
|
|
5316
|
+
if (saved === null) continue;
|
|
5317
|
+
var total = d && typeof d.pages_total === 'number' && d.pages_total > 0 ? d.pages_total : null;
|
|
5318
|
+
var prev = self.state.indexPageProgress[rows[r].path];
|
|
5319
|
+
if (prev && prev.saved === saved && prev.total === total) continue;
|
|
5320
|
+
self.state.indexPageProgress[rows[r].path] = { saved: saved, total: total, at: Date.now() };
|
|
5321
|
+
changed = true;
|
|
5322
|
+
}
|
|
5323
|
+
if (changed) self.host.notify();
|
|
5324
|
+
}, function () { self._progressInflight = false; });
|
|
5325
|
+
}
|
|
5326
|
+
|
|
5327
|
+
/** The page progress to show for a file's row, or null (see _refreshPageProgress). */
|
|
5328
|
+
pageProgressFor(storagePath?: string): { saved: number; total: number | null } | null {
|
|
5329
|
+
if (!storagePath || !this.state.indexPageProgress) return null;
|
|
5330
|
+
var p = this.state.indexPageProgress[storagePath];
|
|
5331
|
+
return p ? { saved: p.saved, total: p.total } : null;
|
|
5332
|
+
}
|
|
5333
|
+
|
|
5334
|
+
private _noteLiveLook(svcId: string, platform: 'claude' | 'openai', results: any[]): void {
|
|
5335
|
+
var ids: { [id: string]: true } = {};
|
|
5336
|
+
var complete = true;
|
|
5337
|
+
for (var r = 0; r < results.length; r++) {
|
|
5338
|
+
var list = results[r] && Array.isArray(results[r].list) ? results[r].list : [];
|
|
5339
|
+
if (list.length >= WORKER_PASS_ADOPT_LIMIT) complete = false;
|
|
5340
|
+
for (var i = 0; i < list.length; i++) if (list[i] && typeof list[i].id === 'string') ids[list[i].id] = true;
|
|
5341
|
+
}
|
|
5342
|
+
this._lastLiveLook = complete ? { svcId: svcId, platform: platform, at: Date.now(), ids: ids } : null;
|
|
5343
|
+
}
|
|
5344
|
+
|
|
5345
|
+
/**
|
|
5346
|
+
* Settle indexing passes from the queue instead of from their own polls (owner,
|
|
5347
|
+
* 2026-11-20): the worker's lanes AND the first passes this client sent. Runs on the
|
|
5348
|
+
* ADOPT_TICK_MS check, beside the adoption look.
|
|
5349
|
+
*
|
|
5350
|
+
* WHY. skapi-js runs every poll on one queue one at a time, each until its request
|
|
5351
|
+
* finishes. The worker runs a document's windows in parallel lanes on that one queue, so
|
|
5352
|
+
* a lane that finished waited behind every pass ahead of it (measured: passes done at
|
|
5353
|
+
* 17:04 shown at 17:06-17:07, one every ~5 s, after a 3-minute first pass).
|
|
5354
|
+
*
|
|
5355
|
+
* HOW. One compact listing each of the queue's `resolved` and `failed` rows (stubs, no
|
|
5356
|
+
* bodies). A tracked pass found there, or one missing from a COMPLETE running+pending look
|
|
5357
|
+
* taken after it was adopted (cancelled, removed), is read ONCE by id through the host's
|
|
5358
|
+
* csrHistoryItemLookup, the same row a poll's last read returns, and settled through
|
|
5359
|
+
* _settleBgOutcome exactly as its poll would have been. A lookup that still says
|
|
5360
|
+
* running/pending (the status index lags the table) leaves the pass for the next tick.
|
|
5361
|
+
*/
|
|
5362
|
+
private _settleByListing(): void {
|
|
5363
|
+
var self = this;
|
|
5364
|
+
if (this._listingLookInflight) return;
|
|
5365
|
+
var lookup = chatEngineConfig().csrHistoryItemLookup;
|
|
5366
|
+
if (typeof lookup !== 'function') return;
|
|
5367
|
+
var id = this.host.getIdentity();
|
|
5368
|
+
var platform = id.platform;
|
|
5369
|
+
if (!id.projectId || (platform !== 'claude' && platform !== 'openai')) return;
|
|
5370
|
+
if (this.isPollingPaused() || !this.host.isViewMounted()) return;
|
|
5371
|
+
var svcId = id.projectId, owner = id.owner;
|
|
5372
|
+
var waiting: BgTaskEntry[] = [];
|
|
5373
|
+
for (var i = 0; i < this.bgTaskQueue.length; i++) {
|
|
5374
|
+
var e = this.bgTaskQueue[i];
|
|
5375
|
+
if (e && e.byListing && e.projectId === svcId && e.platform === platform && !this._listingSettling[e.id]) waiting.push(e);
|
|
5376
|
+
}
|
|
5377
|
+
if (!waiting.length) return;
|
|
5378
|
+
var queue = bgIndexingQueueName(id.userId, svcId);
|
|
5379
|
+
var ask = function (status: 'resolved' | 'failed') {
|
|
5380
|
+
return Promise.resolve(getChatHistory(
|
|
5381
|
+
{ service: svcId, owner: owner, platform: platform as 'claude' | 'openai', queue: queue, status: status, queue_exact: true, compact: true },
|
|
5382
|
+
{ limit: WORKER_PASS_ADOPT_LIMIT, fetchMore: false },
|
|
5383
|
+
)).then(function (res: any) { return res && Array.isArray(res.list) ? res.list : []; })
|
|
5384
|
+
.catch(function () { return []; });
|
|
5385
|
+
};
|
|
5386
|
+
this._listingLookInflight = true;
|
|
5387
|
+
Promise.all([ask('resolved'), ask('failed')]).then(function (lists: any[][]) {
|
|
5388
|
+
self._listingLookInflight = false;
|
|
5389
|
+
var now = self.host.getIdentity();
|
|
5390
|
+
if (now.projectId !== svcId || now.platform !== platform || !self.host.isViewMounted()) return;
|
|
5391
|
+
var finished: { [id: string]: any } = {};
|
|
5392
|
+
for (var l = 0; l < lists.length; l++) {
|
|
5393
|
+
for (var k = 0; k < lists[l].length; k++) {
|
|
5394
|
+
var row = lists[l][k];
|
|
5395
|
+
if (row && typeof row.id === 'string') finished[row.id] = row;
|
|
5396
|
+
}
|
|
5397
|
+
}
|
|
5398
|
+
var look = self._lastLiveLook;
|
|
5399
|
+
var lookUsable = !!look && look.svcId === svcId && look.platform === platform && Date.now() - look.at <= 2 * ADOPT_TICK_MS;
|
|
5400
|
+
for (var w = 0; w < waiting.length; w++) {
|
|
5401
|
+
var entry = waiting[w];
|
|
5402
|
+
if (self.bgTaskQueue.indexOf(entry) === -1) continue; // settled meanwhile (history, cancel)
|
|
5403
|
+
var row2 = finished[entry.id];
|
|
5404
|
+
var leftQueue = !row2 && lookUsable && !look!.ids[entry.id]
|
|
5405
|
+
&& typeof entry.adoptedAt === 'number' && entry.adoptedAt < look!.at;
|
|
5406
|
+
if (!row2 && !leftQueue) continue;
|
|
5407
|
+
self._settleListedEntry(entry, platform as 'claude' | 'openai', lookup,
|
|
5408
|
+
row2 && typeof row2.executed === 'number' && row2.executed > 0 ? row2.executed : undefined);
|
|
5409
|
+
}
|
|
5410
|
+
}, function () { self._listingLookInflight = false; });
|
|
5411
|
+
}
|
|
5412
|
+
|
|
5413
|
+
/** One by-id read of a by-listing pass, then the shared settle. */
|
|
5414
|
+
private _settleListedEntry(entry: BgTaskEntry, platform: 'claude' | 'openai', lookup: (fullId: string, service: string, owner: string) => Promise<any>, executedAt: number | undefined): void {
|
|
5415
|
+
var self = this;
|
|
5416
|
+
var id = this.host.getIdentity();
|
|
5417
|
+
this._listingSettling[entry.id] = true;
|
|
5418
|
+
Promise.resolve(lookup(buildHistoryItemFullId(platform, entry.projectId, entry.id), entry.projectId, id.owner)).then(function (body: any) {
|
|
5419
|
+
delete self._listingSettling[entry.id];
|
|
5420
|
+
if (self.bgTaskQueue.indexOf(entry) === -1) return;
|
|
5421
|
+
// Still going by the table's own reading: leave it for the next tick.
|
|
5422
|
+
if (isCsrStatusEnvelope(body) && (body.status === 'running' || body.status === 'pending')) return;
|
|
5423
|
+
self._settleBgOutcome(entry, platform, Promise.resolve(body), function () { return executedAt; });
|
|
5424
|
+
}, function (err: any) {
|
|
5425
|
+
delete self._listingSettling[entry.id];
|
|
5426
|
+
if (self.bgTaskQueue.indexOf(entry) === -1) return;
|
|
5427
|
+
self._settleBgOutcome(entry, platform, Promise.reject(err), function () { return executedAt; });
|
|
5428
|
+
});
|
|
5429
|
+
}
|
|
5430
|
+
|
|
5431
|
+
private _adoptWorkerIndexingPasses(attempt: number, passive?: boolean, single?: boolean): void {
|
|
4758
5432
|
var self = this;
|
|
4759
5433
|
// One in flight at a time. The query is queue-WIDE, so a second file's pass
|
|
4760
5434
|
// settling in the same moment is covered by the query already running.
|
|
@@ -4790,13 +5464,35 @@ export class ChatSession {
|
|
|
4790
5464
|
// list — harmless there (nothing to adopt) but not here: recording it would
|
|
4791
5465
|
// publish "the queue holds nothing" on the strength of a request that never
|
|
4792
5466
|
// answered, which reads as finished. Not knowing is the honest state.
|
|
4793
|
-
if (results[0] !== null && results[1] !== null)
|
|
5467
|
+
if (results[0] !== null && results[1] !== null) {
|
|
5468
|
+
self._recordLiveIndexKeys(results);
|
|
5469
|
+
self._noteLiveLook(svcId, platform as 'claude' | 'openai', results);
|
|
5470
|
+
// A file the queue still works on keeps being looked at until it leaves the
|
|
5471
|
+
// queue, even when this page tracks none of its passes (a reload, or a run
|
|
5472
|
+
// started elsewhere): its row is drawn from the look, and a look nobody
|
|
5473
|
+
// repeats would leave the row "Indexing" after the run had ended.
|
|
5474
|
+
self._ensureAdoptTick();
|
|
5475
|
+
}
|
|
5476
|
+
if (results[0] !== null) self._promoteListedRunning(results[0]);
|
|
5477
|
+
// Both queries answered and both empty: the queue holds nothing for this user.
|
|
5478
|
+
var emptyLook = results[0] !== null && results[1] !== null
|
|
5479
|
+
&& !((results[0].list || []).length) && !((results[1].list || []).length);
|
|
4794
5480
|
var adoptedIds: string[] = [];
|
|
5481
|
+
// OLDEST FIRST, across both lists. A file's row starts at the first pass the
|
|
5482
|
+
// grouping meets: adopted in the queue's own order (running, then pending, each
|
|
5483
|
+
// newest first), a run's "continuing" passes landed before its opening pass, and
|
|
5484
|
+
// the run drew two rows until the opening pass settled. Request ids sort by time.
|
|
5485
|
+
var found: any[] = [];
|
|
4795
5486
|
for (var ri = 0; ri < results.length; ri++) {
|
|
4796
5487
|
var list = results[ri] && Array.isArray(results[ri].list) ? results[ri].list : [];
|
|
4797
|
-
for (var i = 0; i < list.length; i++)
|
|
4798
|
-
|
|
4799
|
-
|
|
5488
|
+
for (var i = 0; i < list.length; i++) if (list[i]) found.push(list[i]);
|
|
5489
|
+
}
|
|
5490
|
+
found.sort(function (a: any, b: any) {
|
|
5491
|
+
var x = String(a.id || ''), y = String(b.id || '');
|
|
5492
|
+
return x < y ? -1 : x > y ? 1 : 0;
|
|
5493
|
+
});
|
|
5494
|
+
for (var fi = 0; fi < found.length; fi++) {
|
|
5495
|
+
if (self._adoptWorkerIndexingItem(found[fi], svcId, platform as 'claude' | 'openai')) adoptedIds.push(found[fi].id);
|
|
4800
5496
|
}
|
|
4801
5497
|
if (adoptedIds.length) {
|
|
4802
5498
|
self.drainBgTaskQueue();
|
|
@@ -4807,8 +5503,10 @@ export class ChatSession {
|
|
|
4807
5503
|
// pass belonging to a file the user stopped is dropped on sight. Both
|
|
4808
5504
|
// used to read as "found the next pass", which ended the search for a
|
|
4809
5505
|
// pass that had not been written yet.
|
|
4810
|
-
if (self._isTrackingAny(adoptedIds)) return;
|
|
5506
|
+
if (self._isTrackingAny(adoptedIds)) { self._ensureAdoptTick(); return; }
|
|
4811
5507
|
}
|
|
5508
|
+
// A periodic look (_ensureAdoptTick) never climbs: the next tick is its retry.
|
|
5509
|
+
if (single) return;
|
|
4812
5510
|
// Nothing yet. The worker writes pass N+1 a few milliseconds AFTER it
|
|
4813
5511
|
// flips pass N to resolved, so a poll that lands in that gap sees an
|
|
4814
5512
|
// empty queue for a chain that is very much alive — and with no pass
|
|
@@ -4822,8 +5520,12 @@ export class ChatSession {
|
|
|
4822
5520
|
// re-asked an unchanged question three more times on every tab return.
|
|
4823
5521
|
// (No nudge here either: a send waiting on indexing implies local
|
|
4824
5522
|
// entries, which IS evidence, so the passive stop never starves it.)
|
|
4825
|
-
if (passive && !self._hasLiveIndexEvidence(svcId))
|
|
5523
|
+
if (passive && !self._hasLiveIndexEvidence(svcId)) {
|
|
5524
|
+
if (emptyLook) self._idleVerdictAt[svcId] = Date.now();
|
|
5525
|
+
return;
|
|
5526
|
+
}
|
|
4826
5527
|
if (attempt + 1 >= WORKER_PASS_ADOPT_ATTEMPTS.length) {
|
|
5528
|
+
if (emptyLook) self._idleVerdictAt[svcId] = Date.now();
|
|
4827
5529
|
// The ladder is the only thing that can tell a worker-driven chain has
|
|
4828
5530
|
// really ended, and it just did. This is the earliest honest moment to
|
|
4829
5531
|
// let a turn waiting on these files stop waiting.
|
|
@@ -4878,6 +5580,9 @@ export class ChatSession {
|
|
|
4878
5580
|
// true for any chat that has ever indexed anything: exactly the always-climb
|
|
4879
5581
|
// this gate was added to stop.
|
|
4880
5582
|
var cutoff = Date.now() - RECENT_INDEX_PASS_EVIDENCE_MS;
|
|
5583
|
+
// A pass from before the last confirmed-idle look belongs to a run that is over.
|
|
5584
|
+
var idleAt = this._idleVerdictAt[svcId] || 0;
|
|
5585
|
+
if (idleAt > cutoff) cutoff = idleAt;
|
|
4881
5586
|
var msgs = this.state.messages;
|
|
4882
5587
|
for (var mi = msgs.length - 1; mi >= 0; mi--) {
|
|
4883
5588
|
var m = msgs[mi];
|
|
@@ -4949,6 +5654,10 @@ export class ChatSession {
|
|
|
4949
5654
|
// _applyIndexCancellations, which must not read a CONTINUE pass as the
|
|
4950
5655
|
// fresh first pass that lifts a stop.
|
|
4951
5656
|
resumePass: ref.continued ? 1 : 0,
|
|
5657
|
+
// Settled by the 10-second queue check when the host can look a row up by id
|
|
5658
|
+
// (csrHistoryItemLookup); otherwise polled as before.
|
|
5659
|
+
byListing: typeof chatEngineConfig().csrHistoryItemLookup === 'function',
|
|
5660
|
+
adoptedAt: Date.now(),
|
|
4952
5661
|
});
|
|
4953
5662
|
return true;
|
|
4954
5663
|
}
|
|
@@ -4983,6 +5692,8 @@ export class ChatSession {
|
|
|
4983
5692
|
// pass of a stopped file that reached the chat through history.
|
|
4984
5693
|
this._applyIndexCancellations();
|
|
4985
5694
|
this._sweepCancelledIndexing();
|
|
5695
|
+
// A dispatched or adopted pass is live work: follow the run while the tab shows it.
|
|
5696
|
+
this._ensureAdoptTick();
|
|
4986
5697
|
// Index messages by _serverItemId ONCE, so the per-entry presence/pending
|
|
4987
5698
|
// checks below are O(1) instead of a full messages.some() scan each. With a
|
|
4988
5699
|
// large bg queue (bulk uploads) the old nested scan was O(queue x messages)
|
|
@@ -5016,6 +5727,13 @@ export class ChatSession {
|
|
|
5016
5727
|
// entry; only the polling is rationed, and an unpolled entry picks up a
|
|
5017
5728
|
// poll on the drain that follows the next resolution.
|
|
5018
5729
|
var bgPollBudget = MAX_CONCURRENT_BG_POLLS - this._countBgPolls();
|
|
5730
|
+
// Every indexing pass is settled by the 10-second queue check rather than by its own
|
|
5731
|
+
// poll when the host can read a row by id (owner, 2026-11-20): first passes too, not
|
|
5732
|
+
// only the worker's lanes. skapi-js runs a queue's polls one at a time, so a file's
|
|
5733
|
+
// first pass that finished waited behind another file's (a PDF's first pass runs for
|
|
5734
|
+
// minutes). Decided HERE, the one place polls are attached, so a pass added by any
|
|
5735
|
+
// caller (this engine, agent.vue, the files page) is covered alike.
|
|
5736
|
+
var listingSettles = typeof chatEngineConfig().csrHistoryItemLookup === 'function';
|
|
5019
5737
|
// Set by the injection branch; drives the single render/cache/scroll below.
|
|
5020
5738
|
var injectedAny = false;
|
|
5021
5739
|
this.bgTaskQueue.forEach(function (entry) {
|
|
@@ -5085,11 +5803,17 @@ export class ChatSession {
|
|
|
5085
5803
|
// are gone.
|
|
5086
5804
|
injectedAny = true;
|
|
5087
5805
|
}
|
|
5088
|
-
if (
|
|
5806
|
+
if (listingSettles && !entry.byListing) {
|
|
5807
|
+
entry.byListing = true;
|
|
5808
|
+
if (typeof entry.adoptedAt !== 'number') entry.adoptedAt = Date.now();
|
|
5809
|
+
}
|
|
5810
|
+
// A by-listing pass is never polled: the 10-second queue check settles it
|
|
5811
|
+
// (_settleByListing), so it neither waits in skapi-js's per-queue poll line nor
|
|
5812
|
+
// spends this budget.
|
|
5813
|
+
if (!entry.byListing && bgPollBudget > 0 && !self.isPollingPaused() && !self.historyItemPolls.has(entry.id) && typeof entry.poll === 'function') {
|
|
5089
5814
|
bgPollBudget--;
|
|
5090
|
-
var
|
|
5815
|
+
var capturedPlat = plat;
|
|
5091
5816
|
var capturedEntry = entry;
|
|
5092
|
-
var wasStopped = false;
|
|
5093
5817
|
// When the worker BEGAN running this pass. It rides on the poll's status
|
|
5094
5818
|
// envelope (a running tick), never on the terminal read, which hands back
|
|
5095
5819
|
// the destination's own body. Captured here so a settled pass can show how
|
|
@@ -5104,68 +5828,7 @@ export class ChatSession {
|
|
|
5104
5828
|
},
|
|
5105
5829
|
});
|
|
5106
5830
|
self._trackPoll(entry.id, 'bg', bp);
|
|
5107
|
-
|
|
5108
|
-
// A stopped poll is not a result: leave the bubble and the queue entry
|
|
5109
|
-
// exactly as they were so resumePolling can re-attach.
|
|
5110
|
-
if (isPollStopped(response)) { wasStopped = true; return; }
|
|
5111
|
-
self.handleHistoryItemResolution(capturedId, response, capturedPlat, executedAt);
|
|
5112
|
-
self.maybeResumeIndexing(capturedEntry, response, capturedPlat);
|
|
5113
|
-
}).catch(function (err: any) {
|
|
5114
|
-
self.historyItemPolls.delete(capturedId);
|
|
5115
|
-
var isNotExists = err && (err.code === 'NOT_EXISTS' || (err.body && err.body.code === 'NOT_EXISTS'));
|
|
5116
|
-
// Settle the REQUEST bubble first, unconditionally. Only a RUNNING
|
|
5117
|
-
// pass gets an assistant placeholder, so for a queued one the lookup
|
|
5118
|
-
// below finds nothing and every branch was skipped — leaving the
|
|
5119
|
-
// request bubble isPendingQueued with its queue entry about to be
|
|
5120
|
-
// spliced away, i.e. no poll left to ever clear it. One such bubble
|
|
5121
|
-
// pins the whole collapsed row to "active": a spinner and a Stop
|
|
5122
|
-
// button against a dead id, until the page is reloaded.
|
|
5123
|
-
self._clearPendingUserBubble(capturedId);
|
|
5124
|
-
var bi = self.state.messages.findIndex(function (m) { return m.isPending && m._serverItemId === capturedId; });
|
|
5125
|
-
if (bi !== -1) {
|
|
5126
|
-
if (isNotExists) self.state.messages.splice(bi, 1);
|
|
5127
|
-
else self.state.messages[bi] = { role: 'assistant', content: getErrorMessage(err), isError: true, isBackgroundTask: true, _serverItemId: capturedId };
|
|
5128
|
-
} else if (!isNotExists) {
|
|
5129
|
-
// No placeholder to turn into the error (a queued pass). Put one
|
|
5130
|
-
// after the request bubble so the row reports the failure instead
|
|
5131
|
-
// of quietly settling to "Indexed".
|
|
5132
|
-
var ui = self.state.messages.findIndex(function (m) { return m.role === 'user' && m._serverItemId === capturedId; });
|
|
5133
|
-
if (ui !== -1) {
|
|
5134
|
-
self.state.messages.splice(ui + 1, 0, { role: 'assistant', content: getErrorMessage(err), isError: true, isBackgroundTask: true, _serverItemId: capturedId });
|
|
5135
|
-
}
|
|
5136
|
-
}
|
|
5137
|
-
self.host.notify(); self.updateHistoryCache();
|
|
5138
|
-
// A pass that FAILED dispatches no continuation on any path, so a
|
|
5139
|
-
// CLIENT-driven file is finished either way — let a turn waiting on it
|
|
5140
|
-
// look now. Not for a worker-driven one: this catch also fires on a
|
|
5141
|
-
// dropped poll, and the worker may have resolved that pass and written
|
|
5142
|
-
// the next one regardless. Nudging there would pull the two confirming
|
|
5143
|
-
// looks into the window where the new pass is not yet in the status
|
|
5144
|
-
// index, which is the same way a nudge on work STARTING went wrong.
|
|
5145
|
-
if (!self._isWorkerDrivenIndexing(capturedEntry.filename, capturedEntry.mime)) {
|
|
5146
|
-
// Also close the run record: for a CLIENT-driven file a failed
|
|
5147
|
-
// pass ends the chain on every path, and a removed row reads as
|
|
5148
|
-
// a cancel. Worker-driven files are excluded for the same reason
|
|
5149
|
-
// as the nudge — this catch fires on dropped polls too, and the
|
|
5150
|
-
// worker may be writing the next pass regardless.
|
|
5151
|
-
if (isNotExists) self._flipRunRecord(capturedEntry, 'cancelled');
|
|
5152
|
-
else self._flipRunRecord(capturedEntry, 'error', self._runErrorText(err));
|
|
5153
|
-
self._nudgeIndexingDrain();
|
|
5154
|
-
}
|
|
5155
|
-
}).then(function () {
|
|
5156
|
-
// Keep the queue entry when the poll was merely stopped, or resuming
|
|
5157
|
-
// would have nothing left to re-attach to.
|
|
5158
|
-
if (wasStopped) return;
|
|
5159
|
-
var qi = self.bgTaskQueue.findIndex(function (q) { return q.id === capturedId; });
|
|
5160
|
-
if (qi !== -1) self.bgTaskQueue.splice(qi, 1);
|
|
5161
|
-
// This resolution freed a slot in the MAX_CONCURRENT_BG_POLLS budget,
|
|
5162
|
-
// so hand it to the next-oldest unpolled entry. Load-bearing under the
|
|
5163
|
-
// cap: with thousands of entries queued, only the handful holding
|
|
5164
|
-
// polls can ever settle, and without this re-drain the remaining
|
|
5165
|
-
// entries would sit unpolled forever. Not left to a host-side watcher
|
|
5166
|
-
// on bgTaskQueue — agent.vue has one, the widget does not.
|
|
5167
|
-
self.drainBgTaskQueue();
|
|
5168
|
-
});
|
|
5831
|
+
self._settleBgOutcome(capturedEntry, capturedPlat, bp, function () { return executedAt; });
|
|
5169
5832
|
}
|
|
5170
5833
|
});
|
|
5171
5834
|
// One render, one cache write, one scroll for the whole drain — however many
|
|
@@ -5178,6 +5841,83 @@ export class ChatSession {
|
|
|
5178
5841
|
this.promoteNextBgQueuedToRunning();
|
|
5179
5842
|
}
|
|
5180
5843
|
|
|
5844
|
+
|
|
5845
|
+
/**
|
|
5846
|
+
* Settle one background pass from the outcome of reading it: its poll (drainBgTaskQueue)
|
|
5847
|
+
* or a single by-id lookup made by the 10-second queue check (_settleByListing). Both
|
|
5848
|
+
* read the same row the same way, so they share this one path: the resolution, the
|
|
5849
|
+
* resume/chain follow-up, the failure bubble and run record, and the queue entry's removal.
|
|
5850
|
+
* A stopped poll (isPollStopped) leaves the bubble and the entry as they were.
|
|
5851
|
+
*/
|
|
5852
|
+
private _settleBgOutcome(entry: BgTaskEntry, plat: 'claude' | 'openai', outcome: Promise<any>, getExecutedAt: () => number | undefined): void {
|
|
5853
|
+
var self = this;
|
|
5854
|
+
var capturedId = entry.id, capturedPlat = plat;
|
|
5855
|
+
var capturedEntry = entry;
|
|
5856
|
+
var wasStopped = false;
|
|
5857
|
+
outcome.then(function (response: any) {
|
|
5858
|
+
// A stopped poll is not a result: leave the bubble and the queue entry
|
|
5859
|
+
// exactly as they were so resumePolling can re-attach.
|
|
5860
|
+
if (isPollStopped(response)) { wasStopped = true; return; }
|
|
5861
|
+
self.handleHistoryItemResolution(capturedId, response, capturedPlat, getExecutedAt());
|
|
5862
|
+
self.maybeResumeIndexing(capturedEntry, response, capturedPlat);
|
|
5863
|
+
}).catch(function (err: any) {
|
|
5864
|
+
self.historyItemPolls.delete(capturedId);
|
|
5865
|
+
var isNotExists = err && (err.code === 'NOT_EXISTS' || (err.body && err.body.code === 'NOT_EXISTS'));
|
|
5866
|
+
// Settle the REQUEST bubble first, unconditionally. Only a RUNNING
|
|
5867
|
+
// pass gets an assistant placeholder, so for a queued one the lookup
|
|
5868
|
+
// below finds nothing and every branch was skipped — leaving the
|
|
5869
|
+
// request bubble isPendingQueued with its queue entry about to be
|
|
5870
|
+
// spliced away, i.e. no poll left to ever clear it. One such bubble
|
|
5871
|
+
// pins the whole collapsed row to "active": a spinner and a Stop
|
|
5872
|
+
// button against a dead id, until the page is reloaded.
|
|
5873
|
+
self._clearPendingUserBubble(capturedId);
|
|
5874
|
+
var bi = self.state.messages.findIndex(function (m) { return m.isPending && m._serverItemId === capturedId; });
|
|
5875
|
+
if (bi !== -1) {
|
|
5876
|
+
if (isNotExists) self.state.messages.splice(bi, 1);
|
|
5877
|
+
else self.state.messages[bi] = { role: 'assistant', content: getErrorMessage(err), isError: true, isBackgroundTask: true, _serverItemId: capturedId };
|
|
5878
|
+
} else if (!isNotExists) {
|
|
5879
|
+
// No placeholder to turn into the error (a queued pass). Put one
|
|
5880
|
+
// after the request bubble so the row reports the failure instead
|
|
5881
|
+
// of quietly settling to "Indexed".
|
|
5882
|
+
var ui = self.state.messages.findIndex(function (m) { return m.role === 'user' && m._serverItemId === capturedId; });
|
|
5883
|
+
if (ui !== -1) {
|
|
5884
|
+
self.state.messages.splice(ui + 1, 0, { role: 'assistant', content: getErrorMessage(err), isError: true, isBackgroundTask: true, _serverItemId: capturedId });
|
|
5885
|
+
}
|
|
5886
|
+
}
|
|
5887
|
+
self.host.notify(); self.updateHistoryCache();
|
|
5888
|
+
// A pass that FAILED dispatches no continuation on any path, so a
|
|
5889
|
+
// CLIENT-driven file is finished either way — let a turn waiting on it
|
|
5890
|
+
// look now. Not for a worker-driven one: this catch also fires on a
|
|
5891
|
+
// dropped poll, and the worker may have resolved that pass and written
|
|
5892
|
+
// the next one regardless. Nudging there would pull the two confirming
|
|
5893
|
+
// looks into the window where the new pass is not yet in the status
|
|
5894
|
+
// index, which is the same way a nudge on work STARTING went wrong.
|
|
5895
|
+
if (!self._isWorkerDrivenIndexing(capturedEntry.filename, capturedEntry.mime)) {
|
|
5896
|
+
// Also close the run record: for a CLIENT-driven file a failed
|
|
5897
|
+
// pass ends the chain on every path, and a removed row reads as
|
|
5898
|
+
// a cancel. Worker-driven files are excluded for the same reason
|
|
5899
|
+
// as the nudge — this catch fires on dropped polls too, and the
|
|
5900
|
+
// worker may be writing the next pass regardless.
|
|
5901
|
+
if (isNotExists) self._flipRunRecord(capturedEntry, 'cancelled');
|
|
5902
|
+
else self._flipRunRecord(capturedEntry, 'error', self._runErrorText(err));
|
|
5903
|
+
self._nudgeIndexingDrain();
|
|
5904
|
+
}
|
|
5905
|
+
}).then(function () {
|
|
5906
|
+
// Keep the queue entry when the poll was merely stopped, or resuming
|
|
5907
|
+
// would have nothing left to re-attach to.
|
|
5908
|
+
if (wasStopped) return;
|
|
5909
|
+
var qi = self.bgTaskQueue.findIndex(function (q) { return q.id === capturedId; });
|
|
5910
|
+
if (qi !== -1) self.bgTaskQueue.splice(qi, 1);
|
|
5911
|
+
// This resolution freed a slot in the MAX_CONCURRENT_BG_POLLS budget,
|
|
5912
|
+
// so hand it to the next-oldest unpolled entry. Load-bearing under the
|
|
5913
|
+
// cap: with thousands of entries queued, only the handful holding
|
|
5914
|
+
// polls can ever settle, and without this re-drain the remaining
|
|
5915
|
+
// entries would sit unpolled forever. Not left to a host-side watcher
|
|
5916
|
+
// on bgTaskQueue — agent.vue has one, the widget does not.
|
|
5917
|
+
self.drainBgTaskQueue();
|
|
5918
|
+
});
|
|
5919
|
+
}
|
|
5920
|
+
|
|
5181
5921
|
// Resume-across-passes: if a background INDEXING task for a paged file (spreadsheet or
|
|
5182
5922
|
// text) finished WITHOUT the completion marker, the agent ran out of room before reading
|
|
5183
5923
|
// the whole file - dispatch a CONTINUE pass (up to a cap) that resumes from where the
|
|
@@ -5417,6 +6157,8 @@ export class ChatSession {
|
|
|
5417
6157
|
this._resetLiveIndexKeys();
|
|
5418
6158
|
}
|
|
5419
6159
|
if (fetchMore) this.state.loadingOlderHistory = true;
|
|
6160
|
+
// A first page replaces the messages, and with them any steps loaded into rows.
|
|
6161
|
+
if (!fetchMore) this.state.passPaging = {};
|
|
5420
6162
|
this.host.notify(); // surface "Fetching history..." while it loads
|
|
5421
6163
|
var platform = id.platform as 'claude' | 'openai';
|
|
5422
6164
|
var projectId = id.projectId, owner = id.owner;
|
|
@@ -5438,6 +6180,8 @@ export class ChatSession {
|
|
|
5438
6180
|
// share. Read this device's own queue instead. See
|
|
5439
6181
|
// scopeSurfaceToQueue.
|
|
5440
6182
|
scopeSurfaceToQueue: !!id.anonymous,
|
|
6183
|
+
// Chats only when a file's row can load its own passes (lazyIndexRowsEnabled).
|
|
6184
|
+
skipBg: self.lazyIndexRowsEnabled(),
|
|
5441
6185
|
}, options);
|
|
5442
6186
|
};
|
|
5443
6187
|
|
|
@@ -5867,6 +6611,9 @@ export class ChatSession {
|
|
|
5867
6611
|
// poll had since died — with no live poller, leaving a "Thinking..."
|
|
5868
6612
|
// that never clears even after the server settled everything.
|
|
5869
6613
|
if (self.historyItemPolls.has(item.id)) return;
|
|
6614
|
+
// An indexing pass the worker drives is followed by the queue check, not
|
|
6615
|
+
// polled (see trackHistoryIndexPass).
|
|
6616
|
+
if (item._isBgTask && self.trackHistoryIndexPass(item)) return;
|
|
5870
6617
|
// An in-flight immediate dispatch polls its own MAIN-QUEUE item but
|
|
5871
6618
|
// registers that id in historyItemPolls only AFTER its provider POST
|
|
5872
6619
|
// returns; in the sliver before that, a remount can surface the item
|
|
@@ -6016,6 +6763,10 @@ export class ChatSession {
|
|
|
6016
6763
|
// below). Counted so a folder chip can say how many it reused.
|
|
6017
6764
|
var reusedCount = 0;
|
|
6018
6765
|
att.reused = false;
|
|
6766
|
+
// The members skipped as duplicates, with the STORED copy each one matched, so
|
|
6767
|
+
// the host can report them after the send and offer to reindex the stored
|
|
6768
|
+
// copies (reindexStoredFiles). A retry decides afresh.
|
|
6769
|
+
delete att.duplicates;
|
|
6019
6770
|
var chain: Promise<any> = Promise.resolve();
|
|
6020
6771
|
// "Already uploaded by this user, same name and size" -> the stored copy's
|
|
6021
6772
|
// storage path, else null. Asked only while the skip-duplicates switch
|
|
@@ -6095,6 +6846,14 @@ export class ChatSession {
|
|
|
6095
6846
|
if (skipped) return; // guard the indexing branch for a skipped member
|
|
6096
6847
|
if (duplicateOf) {
|
|
6097
6848
|
urls.push({ name: member.relPath, url: url, storagePath: duplicateOf });
|
|
6849
|
+
if (!att.duplicates) att.duplicates = [];
|
|
6850
|
+
att.duplicates.push({
|
|
6851
|
+
label: member.relPath,
|
|
6852
|
+
storagePath: duplicateOf,
|
|
6853
|
+
name: member.file.name,
|
|
6854
|
+
size: member.file.size,
|
|
6855
|
+
mime: member.file.type || self.host.getMimeType(member.file.name) || undefined,
|
|
6856
|
+
});
|
|
6098
6857
|
reusedCount += 1;
|
|
6099
6858
|
if (att.kind !== 'folder') { att.uploadedUrl = url; att.storagePath = duplicateOf; att.reused = true; }
|
|
6100
6859
|
else att.reusedCount = reusedCount;
|
|
@@ -6124,15 +6883,31 @@ export class ChatSession {
|
|
|
6124
6883
|
// run has already written and then not re-index them. Asked of the
|
|
6125
6884
|
// QUEUE, not just this page — see isIndexRunLive.
|
|
6126
6885
|
var alreadyIndexing = false;
|
|
6886
|
+
// The group the file's EXISTING src:: record is at, read BEFORE the
|
|
6887
|
+
// delete below destroys it: a re-index or an overwrite keeps the file's
|
|
6888
|
+
// visibility instead of re-deciding it (host.readFileAccessGroup).
|
|
6889
|
+
var existingGroup: 'public' | 'authorized' | 'private' | null = null;
|
|
6127
6890
|
var preIndex = self.claimIndexRun(member.storagePath).then(function (claimed) {
|
|
6128
6891
|
alreadyIndexing = !claimed;
|
|
6129
6892
|
if (alreadyIndexing) {
|
|
6130
6893
|
console.log('[chat-engine] skipping a duplicate index request for', member.storagePath);
|
|
6131
6894
|
return;
|
|
6132
6895
|
}
|
|
6133
|
-
if (existedBefore
|
|
6134
|
-
|
|
6135
|
-
|
|
6896
|
+
if (!existedBefore) return;
|
|
6897
|
+
var readGroup = typeof self.host.readFileAccessGroup === 'function'
|
|
6898
|
+
? Promise.resolve(self.host.readFileAccessGroup(member.storagePath)).then(function (g) { existingGroup = g || null; }, function (err: any) {
|
|
6899
|
+
// Unknown is not "no group": deleting now would destroy the only
|
|
6900
|
+
// record of it. Fail this member (the chip turns red and can be
|
|
6901
|
+
// retried) and hand the claim back so the retry is not refused.
|
|
6902
|
+
self.releaseIndexRun(member.storagePath);
|
|
6903
|
+
throw err;
|
|
6904
|
+
})
|
|
6905
|
+
: Promise.resolve();
|
|
6906
|
+
return readGroup.then(function () {
|
|
6907
|
+
if (typeof self.host.deleteExistingFileRecord === 'function') {
|
|
6908
|
+
return Promise.resolve(self.host.deleteExistingFileRecord(member.storagePath)).catch(function () { });
|
|
6909
|
+
}
|
|
6910
|
+
});
|
|
6136
6911
|
});
|
|
6137
6912
|
preIndex = preIndex.then(function () {
|
|
6138
6913
|
if (alreadyIndexing) return;
|
|
@@ -6141,7 +6916,7 @@ export class ChatSession {
|
|
|
6141
6916
|
name: member.file.name,
|
|
6142
6917
|
mime: mime || undefined,
|
|
6143
6918
|
size: member.file.size,
|
|
6144
|
-
})).catch(function () { });
|
|
6919
|
+
}, existingGroup || undefined)).catch(function () { });
|
|
6145
6920
|
});
|
|
6146
6921
|
// The access group the host actually recorded this file at. Read
|
|
6147
6922
|
// AFTER ensureFileIndexRecord so the value here is the one the
|
|
@@ -6149,6 +6924,7 @@ export class ChatSession {
|
|
|
6149
6924
|
var accessGroup: 'public' | 'authorized' | 'private' | undefined;
|
|
6150
6925
|
preIndex = preIndex.then(function () {
|
|
6151
6926
|
if (alreadyIndexing) return;
|
|
6927
|
+
if (existingGroup) { accessGroup = existingGroup; return; }
|
|
6152
6928
|
if (typeof self.host.uploadAccessGroup !== 'function') return;
|
|
6153
6929
|
return Promise.resolve(self.host.uploadAccessGroup(member.storagePath))
|
|
6154
6930
|
.then(function (g) { accessGroup = g || undefined; })
|