@jsb188/graphql 1.1.11 → 1.1.12

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.
Files changed (165) hide show
  1. package/audience.d.ts +343 -0
  2. package/cache/config.ts +58 -24
  3. package/cache/index.chat-activity.test.ts +119 -0
  4. package/cache/index.chat.test.ts +92 -0
  5. package/cache/index.helpers.ts +96 -0
  6. package/cache/index.regression.test.ts +149 -0
  7. package/cache/index.test.ts +370 -42
  8. package/cache/index.ts +326 -799
  9. package/cache/optimistic-ui-runtime.ts +46 -0
  10. package/cache/optimistic-ui.ts +401 -0
  11. package/cache/persist.ts +98 -19
  12. package/cache/store.ts +22 -64
  13. package/cache/value.helpers.ts +17 -0
  14. package/{drafts/store.ts → client/draft-persistence-indexed-db.ts} +19 -3
  15. package/{drafts/index.ts → client/draft-persistence.ts} +5 -2
  16. package/client/index.ts +3 -2
  17. package/client/request.helpers.ts +14 -0
  18. package/client/request.ts +130 -215
  19. package/deno.lock +17 -0
  20. package/deno.test.json +2 -0
  21. package/gql/fragments/agentMemoryFragments.ts +5 -1
  22. package/gql/fragments/agentNoteFragments.ts +150 -0
  23. package/gql/fragments/aiChatFragments.ts +36 -10
  24. package/gql/fragments/audienceFragments.ts +141 -0
  25. package/gql/fragments/campaignFragments.ts +415 -126
  26. package/gql/fragments/dataTableFragments.ts +48 -80
  27. package/gql/fragments/emailFragments.ts +28 -23
  28. package/gql/fragments/fieldDocFragments.ts +222 -40
  29. package/gql/fragments/inboundContactFragments.ts +2 -0
  30. package/gql/fragments/logFragments.ts +93 -2
  31. package/gql/fragments/organizationFragments.ts +10 -0
  32. package/gql/fragments/qrCodeFragments.ts +29 -0
  33. package/gql/fragments/scheduleFragments.ts +652 -140
  34. package/gql/fragments/sheetFragments.ts +84 -373
  35. package/gql/fragments/storageFragments.ts +25 -1
  36. package/gql/fragments/workflowFragments.ts +13 -1
  37. package/gql/mutations/agentMemoryMutations.ts +32 -0
  38. package/gql/mutations/agentNoteMutations.ts +62 -0
  39. package/gql/mutations/aiChatMutations.ts +36 -4
  40. package/gql/mutations/audienceMutations.ts +71 -0
  41. package/gql/mutations/authMutations.ts +45 -1
  42. package/gql/mutations/billingMutations.ts +24 -0
  43. package/gql/mutations/campaignMutations.ts +170 -127
  44. package/gql/mutations/contactMutations.ts +23 -0
  45. package/gql/mutations/dataTableMutations.ts +18 -75
  46. package/gql/mutations/fieldDocMutations.ts +162 -13
  47. package/gql/mutations/index.ts +8 -5
  48. package/gql/mutations/organizationMutations.ts +6 -0
  49. package/gql/mutations/qrCodeMutations.ts +20 -0
  50. package/gql/mutations/scheduleMutations.ts +1052 -354
  51. package/gql/mutations/sheetMutations.ts +62 -118
  52. package/gql/mutations/storageMutations.ts +0 -1
  53. package/gql/mutations/workflowMutations.ts +18 -0
  54. package/gql/queries/agentMemoryQueries.ts +6 -0
  55. package/gql/queries/agentNoteQueries.ts +89 -0
  56. package/gql/queries/aiChatQueries.ts +56 -4
  57. package/gql/queries/audienceQueries.ts +128 -0
  58. package/gql/queries/authQueries.ts +6 -0
  59. package/gql/queries/billingQueries.ts +95 -6
  60. package/gql/queries/campaignQueries.ts +132 -23
  61. package/gql/queries/dataTableQueries.ts +24 -65
  62. package/gql/queries/emailQueries.ts +18 -61
  63. package/gql/queries/emailReplyReportQueries.ts +76 -0
  64. package/gql/queries/fieldDocQueries.ts +100 -92
  65. package/gql/queries/inboundContactQueries.ts +4 -0
  66. package/gql/queries/index.ts +3 -1
  67. package/gql/queries/logQueries.ts +62 -7
  68. package/gql/queries/organizationQueries.ts +13 -0
  69. package/gql/queries/qrCodeQueries.ts +20 -0
  70. package/gql/queries/scheduleQueries.ts +633 -257
  71. package/gql/queries/sheetQueries.ts +59 -152
  72. package/gql/queries/workflowQueries.ts +10 -4
  73. package/hooks/index.helpers.test.ts +50 -0
  74. package/hooks/index.helpers.ts +52 -0
  75. package/hooks/index.ts +863 -685
  76. package/hooks/use-agentMemory-mtn.ts +29 -31
  77. package/hooks/use-agentMemory-qry.ts +15 -3
  78. package/hooks/use-agentNote-mtn.ts +82 -0
  79. package/hooks/use-agentNote-qry.ts +190 -0
  80. package/hooks/use-agentNote-recovery.helpers.test.ts +68 -0
  81. package/hooks/use-agentNote-recovery.helpers.ts +58 -0
  82. package/hooks/use-agentNote-recovery.ts +72 -0
  83. package/hooks/use-aiChat-mtn.ts +96 -112
  84. package/hooks/use-aiChat-qry.helpers.test.ts +63 -0
  85. package/hooks/use-aiChat-qry.helpers.ts +124 -0
  86. package/hooks/use-aiChat-qry.ts +229 -383
  87. package/hooks/use-aiChat-stream-mtn.ts +14 -0
  88. package/hooks/use-audience-mtn.ts +194 -0
  89. package/hooks/use-audience-qry.helpers.test.ts +80 -0
  90. package/hooks/use-audience-qry.helpers.ts +63 -0
  91. package/hooks/use-audience-qry.ts +330 -0
  92. package/hooks/use-auth-mtn.ts +30 -1
  93. package/hooks/use-billing-mtn.ts +31 -0
  94. package/hooks/use-billing-qry.ts +76 -0
  95. package/hooks/use-campaign-generation-recovery.ts +53 -0
  96. package/hooks/use-campaign-mtn.ts +224 -165
  97. package/hooks/use-campaign-qry.helpers.ts +40 -0
  98. package/hooks/use-campaign-qry.ts +631 -54
  99. package/hooks/use-dataTable-mtn.ts +23 -115
  100. package/hooks/use-dataTable-qry.ts +66 -916
  101. package/hooks/use-email-qry.helpers.ts +37 -0
  102. package/hooks/use-email-qry.ts +33 -178
  103. package/hooks/use-emailCampaignReplyReport-qry.ts +27 -0
  104. package/hooks/use-fieldDoc-mtn.ts +244 -32
  105. package/hooks/use-fieldDoc-qry.helpers.test.ts +65 -0
  106. package/hooks/use-fieldDoc-qry.helpers.ts +49 -0
  107. package/hooks/use-fieldDoc-qry.ts +134 -102
  108. package/hooks/use-inboundContact-qry.ts +7 -9
  109. package/hooks/use-log-mtn.ts +25 -12
  110. package/hooks/use-log-qry.ts +99 -46
  111. package/hooks/use-organization-qry.ts +16 -60
  112. package/hooks/use-publicFormEmail-mtn.ts +27 -0
  113. package/hooks/use-qrCode-mtn.ts +40 -0
  114. package/hooks/use-qrCode-qry.ts +78 -0
  115. package/hooks/use-schedule-mtn.ts +506 -333
  116. package/hooks/use-schedule-qry.ts +682 -101
  117. package/hooks/use-schedule-reactive.ts +486 -0
  118. package/hooks/use-sheet-mtn.ts +91 -199
  119. package/hooks/use-sheet-qry.ts +84 -238
  120. package/hooks/use-storage-qry.ts +84 -61
  121. package/hooks/use-workflow-mtn.ts +39 -22
  122. package/hooks/use-workflow-qry.ts +40 -61
  123. package/libs/ai-chat-outgoing.helpers.ts +153 -0
  124. package/libs/ai-chat-outgoing.ts +11 -0
  125. package/libs/ai-chat-outgoing.types.ts +25 -0
  126. package/libs/ai-chat-run-realtime.ts +20 -0
  127. package/libs/ai-chat-submission-realtime.ts +150 -0
  128. package/libs/fragment-realtime-sequence.ts +55 -0
  129. package/libs/fragment-recovery.test.ts +326 -0
  130. package/libs/fragment-recovery.ts +325 -0
  131. package/libs/open-sheet.ts +138 -0
  132. package/libs/orchestrator-realtime.helpers.test.ts +229 -0
  133. package/libs/orchestrator-realtime.helpers.ts +317 -0
  134. package/libs/orchestrator-realtime.ts +433 -0
  135. package/libs/request-cache-regression.test.ts +122 -0
  136. package/{client → libs}/request-managed-session.test.ts +1 -1
  137. package/libs/request-no-store.test.ts +419 -0
  138. package/libs/sheet-command-batch.ts +44 -0
  139. package/libs/sheet-view-realtime-router.test.ts +214 -0
  140. package/libs/sheet-view-realtime-router.ts +99 -0
  141. package/loaders/campaign.test.ts +186 -0
  142. package/loaders/campaign.ts +56 -83
  143. package/loaders/emailPreference.ts +75 -0
  144. package/loaders/rest.ts +12 -0
  145. package/package.json +42 -17
  146. package/schedule.d.ts +1790 -0
  147. package/sse.helpers.ts +19 -0
  148. package/sse.ts +26 -115
  149. package/tests/agent-note-detail-cache.test.ts +120 -0
  150. package/tests/agent-note-search.test.ts +444 -0
  151. package/types.d.ts +46 -25
  152. package/client/data-table-realtime-subscriptions.test.ts +0 -740
  153. package/client/data-table-realtime-subscriptions.ts +0 -955
  154. package/client/data-table-realtime.test.ts +0 -792
  155. package/client/data-table-realtime.ts +0 -1218
  156. package/client/fragment-realtime-sequence.ts +0 -52
  157. package/client/open-sheet.ts +0 -137
  158. package/client/request-no-store.test.ts +0 -157
  159. package/gql/fragments/agentDocFragments.ts +0 -46
  160. package/gql/fragments/billingFragments.ts +0 -14
  161. package/gql/mutations/agentDocMutations.ts +0 -177
  162. package/gql/queries/agentDocQueries.ts +0 -120
  163. package/hooks/use-agentDoc-mtn.ts +0 -285
  164. package/hooks/use-agentDoc-qry.ts +0 -208
  165. /package/{client → libs}/sse-ticket.test.ts +0 -0
@@ -0,0 +1,433 @@
1
+ import type { AIChatType } from '@jsb188/app/types/ai.d.ts';
2
+ import type { OrchestratorArtifactWSObj } from '@jsb188/app/types/app.d.ts';
3
+ import { releaseObjectUrl, retainObjectUrl } from '@jsb188/app/utils/url_client.ts';
4
+ import { graphqlRequestNoStore } from '../client/request.ts';
5
+ import { orchestratorArtifactsQry } from '../gql/queries/aiChatQueries.ts';
6
+ import {
7
+ applyOrchestratorArtifactUpdate,
8
+ type OrchestratorArtifactObj,
9
+ type OrchestratorSessionData,
10
+ getEmptyOrchestratorSessionData,
11
+ mergeOrchestratorArtifactUpdates,
12
+ } from './orchestrator-realtime.helpers.ts';
13
+
14
+ export type {
15
+ OrchestratorArtifactObj,
16
+ OrchestratorArtifactState,
17
+ } from './orchestrator-realtime.helpers.ts';
18
+
19
+ /*
20
+ * In-memory orchestrator sessions scoped to account + organization. The browser URL selects
21
+ * the chat; messages and artifacts are recovered from the server after a reload.
22
+ * Live artifact creations navigate only in the tab that started or sent to the chat.
23
+ */
24
+
25
+ /**
26
+ * Types
27
+ */
28
+
29
+ // An uploaded file sent with the first message (uri is the storage file URI)
30
+ export interface OrchestratorAttachmentObj {
31
+ uri: string;
32
+ name: string;
33
+ contentType: string;
34
+ // Local object URL of the picked file, held by the session while it shows it
35
+ previewUrl?: string | null;
36
+ }
37
+
38
+ // A submitted first message whose startAIChat mutation has not returned yet
39
+ export interface OrchestratorPendingStartObj {
40
+ qrCodeTokens?: string[];
41
+ clientRequestId: string;
42
+ text: string;
43
+ attachments: OrchestratorAttachmentObj[];
44
+ at: string;
45
+ }
46
+
47
+ // Optimistic first turn of a just-started chat and its single-use SSE ticket
48
+ export interface OrchestratorInitialTurnObj {
49
+ sessionKey: string | null;
50
+ message: string;
51
+ attachments: OrchestratorAttachmentObj[];
52
+ at: string;
53
+ }
54
+
55
+ export interface OrchestratorSessionObj extends OrchestratorSessionData {
56
+ // Memory only (never persisted)
57
+ pendingStart: OrchestratorPendingStartObj | null;
58
+ initialTurn: OrchestratorInitialTurnObj | null;
59
+ }
60
+
61
+ // The artifact names the organization the orchestrator made it in
62
+ type OrchestratorNavigationListener = (scopeKey: string, artifact: OrchestratorArtifactObj) => void;
63
+
64
+ interface PendingOrchestratorUpdateObj {
65
+ receivedAt: number;
66
+ update: OrchestratorArtifactWSObj;
67
+ }
68
+
69
+ /**
70
+ * Constants
71
+ */
72
+
73
+ const FILE_CONSTANTS = {
74
+ // Events for a chat no session claims yet wait this long
75
+ pendingUpdateMaxAgeMs: 60_000,
76
+ pendingUpdatesMax: 25,
77
+ };
78
+
79
+ const ORCHESTRATOR_SESSIONS = new Map<string, OrchestratorSessionObj>();
80
+ const ORCHESTRATOR_SESSION_LISTENERS = new Map<string, Set<() => void>>();
81
+ const ORCHESTRATOR_NAVIGATION_LISTENERS = new Set<OrchestratorNavigationListener>();
82
+ const PENDING_ORCHESTRATOR_UPDATES: PendingOrchestratorUpdateObj[] = [];
83
+ const ORCHESTRATOR_SERVER_SESSION = createOrchestratorSession();
84
+
85
+ /*
86
+ * Return a session with no chat, no artifacts, and no memory-only state.
87
+ */
88
+ function createOrchestratorSession(): OrchestratorSessionObj {
89
+ return {
90
+ ...getEmptyOrchestratorSessionData(),
91
+ pendingStart: null,
92
+ initialTurn: null,
93
+ };
94
+ }
95
+
96
+ /*
97
+ * Return the sessionStorage key naming the chat this tab owns in one scope.
98
+ */
99
+ function getOrchestratorOwnedChatKey(scopeKey: string) {
100
+ return `orchestratorOwned:${scopeKey}`;
101
+ }
102
+
103
+ /*
104
+ * Return whether this tab started or sent to one chat. sessionStorage survives a reload of the
105
+ * same tab; opening a chat URL in another tab does not claim ownership.
106
+ */
107
+ function isOrchestratorChatOwnedByTab(scopeKey: string, aiChatId: string) {
108
+ try {
109
+ const ownedChatId = globalThis.sessionStorage?.getItem(getOrchestratorOwnedChatKey(scopeKey));
110
+ // Without sessionStorage tabs cannot be told apart; keep navigating
111
+ return ownedChatId === undefined || ownedChatId === aiChatId;
112
+ } catch {
113
+ return true;
114
+ }
115
+ }
116
+
117
+ /*
118
+ * Record (or with null, forget) the chat this tab owns in one scope.
119
+ */
120
+ function setOrchestratorChatOwnedByTab(scopeKey: string, aiChatId: string | null) {
121
+ try {
122
+ const ownedChatKey = getOrchestratorOwnedChatKey(scopeKey);
123
+ if (aiChatId) {
124
+ globalThis.sessionStorage?.setItem(ownedChatKey, aiChatId);
125
+ } else {
126
+ globalThis.sessionStorage?.removeItem(ownedChatKey);
127
+ }
128
+ } catch {
129
+ // Storage blocked; ownership falls back to isOrchestratorChatOwnedByTab's default
130
+ }
131
+ }
132
+
133
+ /*
134
+ * Return the local preview URLs shown by a session's memory-only first turn.
135
+ */
136
+ function getOrchestratorPreviewUrls(session?: OrchestratorSessionObj) {
137
+ const attachments = [...(session?.pendingStart?.attachments || []), ...(session?.initialTurn?.attachments || [])];
138
+
139
+ return new Set(attachments.flatMap((attachment) => (attachment.previewUrl ? [attachment.previewUrl] : [])));
140
+ }
141
+
142
+ /*
143
+ * Hold the local previews a session starts showing and release the ones it
144
+ * stops showing, so a preview outlives the orchestrator's components (modal
145
+ * closed, app shell remounted) but not its session.
146
+ */
147
+ function holdOrchestratorPreviewUrls(previousSession: OrchestratorSessionObj | undefined, session: OrchestratorSessionObj) {
148
+ const previousUrls = getOrchestratorPreviewUrls(previousSession);
149
+ const urls = getOrchestratorPreviewUrls(session);
150
+
151
+ for (const url of urls) {
152
+ if (!previousUrls.has(url)) {
153
+ retainObjectUrl(url);
154
+ }
155
+ }
156
+
157
+ for (const url of previousUrls) {
158
+ if (!urls.has(url)) {
159
+ releaseObjectUrl(url);
160
+ }
161
+ }
162
+ }
163
+
164
+ /*
165
+ * Replace one scope's in-memory session and notify its observers.
166
+ */
167
+ function commitOrchestratorSession(scopeKey: string, session: OrchestratorSessionObj) {
168
+ holdOrchestratorPreviewUrls(ORCHESTRATOR_SESSIONS.get(scopeKey), session);
169
+ ORCHESTRATOR_SESSIONS.set(scopeKey, session);
170
+
171
+ ORCHESTRATOR_SESSION_LISTENERS.get(scopeKey)?.forEach((listener) => {
172
+ listener();
173
+ });
174
+ }
175
+
176
+ /*
177
+ * Return whether a realtime or caught-up payload has the fields every artifact event needs.
178
+ */
179
+ function isOrchestratorArtifactUpdate(update: OrchestratorArtifactWSObj | null | undefined): update is OrchestratorArtifactWSObj {
180
+ return !!(update?.aiChatId && update.callId && update.kind && update.action);
181
+ }
182
+
183
+ /*
184
+ * Apply one artifact event to the session that owns its chat. Returns false when no session owns it.
185
+ */
186
+ function applyOrchestratorArtifactToSessions(update: OrchestratorArtifactWSObj) {
187
+ for (const [scopeKey, session] of ORCHESTRATOR_SESSIONS) {
188
+ if (session.aiChatId !== update.aiChatId) {
189
+ continue;
190
+ }
191
+
192
+ const result = applyOrchestratorArtifactUpdate(session, update);
193
+ if (result) {
194
+ commitOrchestratorSession(scopeKey, { ...session, ...result.session });
195
+
196
+ const { navigateTo } = result;
197
+ if (navigateTo && isOrchestratorChatOwnedByTab(scopeKey, update.aiChatId)) {
198
+ ORCHESTRATOR_NAVIGATION_LISTENERS.forEach((listener) => {
199
+ listener(scopeKey, navigateTo);
200
+ });
201
+ }
202
+ }
203
+ return true;
204
+ }
205
+
206
+ return false;
207
+ }
208
+
209
+ /*
210
+ * Apply buffered events whose chat now has an owning session, and drop expired ones.
211
+ */
212
+ function flushPendingOrchestratorUpdates() {
213
+ const minReceivedAt = Date.now() - FILE_CONSTANTS.pendingUpdateMaxAgeMs;
214
+ const pendingUpdates = PENDING_ORCHESTRATOR_UPDATES.splice(0);
215
+
216
+ for (const pendingUpdate of pendingUpdates) {
217
+ if (pendingUpdate.receivedAt >= minReceivedAt && !applyOrchestratorArtifactToSessions(pendingUpdate.update)) {
218
+ PENDING_ORCHESTRATOR_UPDATES.push(pendingUpdate);
219
+ }
220
+ }
221
+ }
222
+
223
+ /*
224
+ * Return the store scope of one account and organization.
225
+ */
226
+ export function getOrchestratorScopeKey(accountId: string, organizationId: string) {
227
+ return `${accountId}:${organizationId}`;
228
+ }
229
+
230
+ /*
231
+ * Return the current in-memory session of one account and organization.
232
+ */
233
+ export function getOrchestratorSession(scopeKey: string) {
234
+ let session = ORCHESTRATOR_SESSIONS.get(scopeKey);
235
+ if (!session) {
236
+ session = createOrchestratorSession();
237
+ ORCHESTRATOR_SESSIONS.set(scopeKey, session);
238
+ }
239
+ return session;
240
+ }
241
+
242
+ /*
243
+ * Return the placeholder session rendered where no browser store exists (SSR).
244
+ */
245
+ export function getOrchestratorServerSession() {
246
+ return ORCHESTRATOR_SERVER_SESSION;
247
+ }
248
+
249
+ /*
250
+ * Observe one scope's session.
251
+ */
252
+ export function subscribeToOrchestratorSession(scopeKey: string, listener: () => void) {
253
+ let listeners = ORCHESTRATOR_SESSION_LISTENERS.get(scopeKey);
254
+ if (!listeners) {
255
+ listeners = new Set();
256
+ ORCHESTRATOR_SESSION_LISTENERS.set(scopeKey, listeners);
257
+ }
258
+ listeners.add(listener);
259
+
260
+ return () => {
261
+ listeners.delete(listener);
262
+ if (!listeners.size) {
263
+ ORCHESTRATOR_SESSION_LISTENERS.delete(scopeKey);
264
+ }
265
+ };
266
+ }
267
+
268
+ /*
269
+ * Observe live artifact creations that call for navigation (owned chats only, never restored entries).
270
+ */
271
+ export function subscribeToOrchestratorNavigation(listener: OrchestratorNavigationListener) {
272
+ ORCHESTRATOR_NAVIGATION_LISTENERS.add(listener);
273
+
274
+ return () => {
275
+ ORCHESTRATOR_NAVIGATION_LISTENERS.delete(listener);
276
+ };
277
+ }
278
+
279
+ /*
280
+ * Record a submitted first message while its chat is being started.
281
+ */
282
+ export function startOrchestratorChat(scopeKey: string, chatType: AIChatType, pendingStart: OrchestratorPendingStartObj) {
283
+ const session = getOrchestratorSession(scopeKey);
284
+ commitOrchestratorSession(scopeKey, { ...session, chatType, pendingStart, initialTurn: null });
285
+ }
286
+
287
+ /*
288
+ * Attach the started chat to its pending first message. Ignored when the session moved on
289
+ * (e.g. "New chat" was clicked while the start mutation was in flight).
290
+ */
291
+ export function setOrchestratorChat(
292
+ scopeKey: string,
293
+ params: {
294
+ clientRequestId: string;
295
+ aiChatId: string;
296
+ chatType: AIChatType;
297
+ initialTurn: OrchestratorInitialTurnObj;
298
+ },
299
+ ) {
300
+ const session = getOrchestratorSession(scopeKey);
301
+ if (session.pendingStart?.clientRequestId !== params.clientRequestId) {
302
+ return false;
303
+ }
304
+
305
+ setOrchestratorChatOwnedByTab(scopeKey, params.aiChatId);
306
+ commitOrchestratorSession(scopeKey, {
307
+ ...session,
308
+ aiChatId: params.aiChatId,
309
+ chatType: params.chatType,
310
+ pendingStart: null,
311
+ initialTurn: params.initialTurn,
312
+ });
313
+ flushPendingOrchestratorUpdates();
314
+ return true;
315
+ }
316
+
317
+ /*
318
+ * Restore a validated existing orchestrator chat without carrying artifacts or pending turns from another chat.
319
+ */
320
+ export function openOrchestratorChat(scopeKey: string, aiChatId: string, chatType: AIChatType) {
321
+ if (chatType !== 'ORCHESTRATOR') {
322
+ return;
323
+ }
324
+ const session = getOrchestratorSession(scopeKey);
325
+ if (session.aiChatId === aiChatId) {
326
+ return;
327
+ }
328
+ commitOrchestratorSession(scopeKey, { ...createOrchestratorSession(), aiChatId, chatType });
329
+ flushPendingOrchestratorUpdates();
330
+ }
331
+
332
+ /*
333
+ * Make a chat this tab's own when the person sends to it, so its creations navigate here.
334
+ */
335
+ export function claimOrchestratorChat(scopeKey: string, aiChatId: string) {
336
+ const session = getOrchestratorSession(scopeKey);
337
+ if (session.aiChatId !== aiChatId) {
338
+ return;
339
+ }
340
+
341
+ setOrchestratorChatOwnedByTab(scopeKey, aiChatId);
342
+ }
343
+
344
+ /*
345
+ * Forget the first turn's single-use SSE ticket once a thread consumed it, so a remount resumes instead.
346
+ */
347
+ export function consumeOrchestratorInitialSessionKey(scopeKey: string, aiChatId: string) {
348
+ const session = getOrchestratorSession(scopeKey);
349
+ if (session.aiChatId !== aiChatId || !session.initialTurn?.sessionKey) {
350
+ return;
351
+ }
352
+
353
+ commitOrchestratorSession(scopeKey, {
354
+ ...session,
355
+ initialTurn: { ...session.initialTurn, sessionKey: null },
356
+ });
357
+ }
358
+
359
+ /*
360
+ * Drop the first turn once the thread shows its canonical messages, which releases the local
361
+ * previews it held. A reopened orchestrator then renders the chat like any other.
362
+ */
363
+ export function settleOrchestratorInitialTurn(scopeKey: string, aiChatId: string) {
364
+ const session = getOrchestratorSession(scopeKey);
365
+ if (session.aiChatId !== aiChatId || !session.initialTurn) {
366
+ return;
367
+ }
368
+
369
+ commitOrchestratorSession(scopeKey, { ...session, initialTurn: null });
370
+ }
371
+
372
+ /*
373
+ * Start over: drop the chat and its artifact list.
374
+ */
375
+ export function resetOrchestratorSession(scopeKey: string) {
376
+ setOrchestratorChatOwnedByTab(scopeKey, null);
377
+ commitOrchestratorSession(scopeKey, createOrchestratorSession());
378
+ }
379
+
380
+ /*
381
+ * Merge caught-up artifact events of one chat into its session. They are only listed, never
382
+ * navigated to, and calls this tab already received live are skipped.
383
+ */
384
+ export function mergeOrchestratorArtifacts(scopeKey: string, aiChatId: string, updates: OrchestratorArtifactWSObj[]) {
385
+ const session = ORCHESTRATOR_SESSIONS.get(scopeKey);
386
+ if (!session || session.aiChatId !== aiChatId) {
387
+ return;
388
+ }
389
+
390
+ const merged = mergeOrchestratorArtifactUpdates(
391
+ session,
392
+ updates.filter((update) => isOrchestratorArtifactUpdate(update) && update.aiChatId === aiChatId),
393
+ );
394
+ if (merged) {
395
+ commitOrchestratorSession(scopeKey, { ...session, ...merged });
396
+ }
397
+ }
398
+
399
+ /*
400
+ * Read the artifact events one chat's runs emitted so far and merge the ones this tab missed
401
+ * while it was not watching (orchestrator closed, socket reconnecting). Failures are silent: the
402
+ * next catch-up (reopen or reconnect) tries again.
403
+ */
404
+ export async function catchUpOrchestratorArtifacts(scopeKey: string, aiChatId: string, signal: AbortSignal) {
405
+ const result = await graphqlRequestNoStore(orchestratorArtifactsQry, { aiChatId }, undefined, signal);
406
+ const updates = result?.orchestratorArtifacts;
407
+ if (!signal.aborted && !result?.error && Array.isArray(updates)) {
408
+ mergeOrchestratorArtifacts(scopeKey, aiChatId, updates);
409
+ }
410
+ }
411
+
412
+ /*
413
+ * Apply one realtime artifact event. Events for a chat no session owns yet are
414
+ * buffered briefly while the URL-selected chat is being validated.
415
+ */
416
+ export function receiveOrchestratorArtifact(update: OrchestratorArtifactWSObj) {
417
+ if (!isOrchestratorArtifactUpdate(update)) {
418
+ return;
419
+ }
420
+
421
+ if (applyOrchestratorArtifactToSessions(update)) {
422
+ return;
423
+ }
424
+
425
+ const minReceivedAt = Date.now() - FILE_CONSTANTS.pendingUpdateMaxAgeMs;
426
+ const keptUpdates = PENDING_ORCHESTRATOR_UPDATES.splice(0).filter(
427
+ (pendingUpdate) => pendingUpdate.receivedAt >= minReceivedAt && pendingUpdate.update.callId !== update.callId,
428
+ );
429
+ PENDING_ORCHESTRATOR_UPDATES.push(...keptUpdates.slice(-(FILE_CONSTANTS.pendingUpdatesMax - 1)), {
430
+ receivedAt: Date.now(),
431
+ update,
432
+ });
433
+ }
@@ -0,0 +1,122 @@
1
+ import { registerENV } from '@jsb188/app';
2
+ import { makeGraphQLVariablesKey } from '@jsb188/app/utils/logic.ts';
3
+ import { gql } from 'graphql-tag';
4
+ import { clearGraphQLClientCache, fetchCachedData, getQueryLastFetchedAt } from '../cache/index.ts';
5
+ import { graphqlRequest, graphqlRequestWithRetry } from '../client/request.ts';
6
+ import { isQueryDataStale } from '../hooks/index.helpers.ts';
7
+
8
+ const QUERY = gql`query cacheRecord { cacheRecord { id } }`;
9
+
10
+ Deno.test('late HTTP responses cannot repopulate a cleared cache or call completed handlers', async () => {
11
+ clearGraphQLClientCache();
12
+ registerENV({ GQL_SERVER: 'https://graphql.test/cache-epoch', IS_BROWSER: '' });
13
+ const originalFetch = globalThis.fetch;
14
+ let complete!: (response: Response) => void;
15
+ let callbackCount = 0;
16
+ globalThis.fetch = () =>
17
+ new Promise((resolve) => {
18
+ complete = resolve;
19
+ });
20
+ try {
21
+ const pending = graphqlRequest(QUERY, undefined, {
22
+ onCompleted: () => {
23
+ callbackCount++;
24
+ },
25
+ });
26
+ await Promise.resolve();
27
+ clearGraphQLClientCache();
28
+ complete(Response.json({ data: { cacheRecord: { id: 'old-session' } } }));
29
+ const result = await pending;
30
+ if (!result.aborted || callbackCount || fetchCachedData(QUERY, makeGraphQLVariablesKey(undefined)))
31
+ throw new Error('An obsolete response survived the cache epoch boundary');
32
+ } finally {
33
+ globalThis.fetch = originalFetch;
34
+ clearGraphQLClientCache();
35
+ }
36
+ });
37
+
38
+ Deno.test('late successful fetch completion respects an already-aborted signal', async () => {
39
+ clearGraphQLClientCache();
40
+ registerENV({ GQL_SERVER: 'https://graphql.test/aborted-cache', IS_BROWSER: '' });
41
+ const originalFetch = globalThis.fetch;
42
+ const controller = new AbortController();
43
+ globalThis.fetch = () => {
44
+ controller.abort();
45
+ return Promise.resolve(Response.json({ data: { cacheRecord: { id: 'cancelled' } } }));
46
+ };
47
+ try {
48
+ const result = await graphqlRequest(QUERY, undefined, undefined, controller.signal);
49
+ if (!result.aborted || fetchCachedData(QUERY, makeGraphQLVariablesKey(undefined)))
50
+ throw new Error('Cancelled data entered the cache');
51
+ } finally {
52
+ globalThis.fetch = originalFetch;
53
+ }
54
+ });
55
+
56
+ Deno.test('partial GraphQL errors never certify a cached query as fresh', async () => {
57
+ clearGraphQLClientCache();
58
+ registerENV({ GQL_SERVER: 'https://graphql.test/partial-cache', IS_BROWSER: '' });
59
+ const originalFetch = globalThis.fetch;
60
+ let fail = false;
61
+ globalThis.fetch = () =>
62
+ Promise.resolve(
63
+ Response.json(
64
+ fail ? { data: { cacheRecord: null }, errors: [{ message: '20120' }] } : { data: { cacheRecord: { id: 'visible' } } },
65
+ ),
66
+ );
67
+ try {
68
+ await graphqlRequest(QUERY);
69
+ const key = '#cacheRecord:' + makeGraphQLVariablesKey(undefined);
70
+ if (getQueryLastFetchedAt(key) === undefined) throw new Error('Successful query did not become fresh');
71
+ fail = true;
72
+ await graphqlRequest(QUERY);
73
+ if (getQueryLastFetchedAt(key) !== undefined) throw new Error('Partial failure retained a freshness certificate');
74
+ if (fetchCachedData(QUERY, makeGraphQLVariablesKey(undefined))?.cacheRecord !== null)
75
+ throw new Error('Server null was replaced by older data');
76
+ } finally {
77
+ globalThis.fetch = originalFetch;
78
+ }
79
+ });
80
+
81
+ Deno.test('the retry request wrapper preserves auth, result guards and no-store policy', async () => {
82
+ clearGraphQLClientCache();
83
+ registerENV({ GQL_SERVER: 'https://graphql.test/retry-options', IS_BROWSER: '' });
84
+ const originalFetch = globalThis.fetch;
85
+ let authorization: string | null = null;
86
+ let guarded = false;
87
+ globalThis.fetch = (_input, init) => {
88
+ authorization = new Headers(init?.headers).get('authorization');
89
+ return Promise.resolve(Response.json({ data: { cacheRecord: { id: 'private' } } }));
90
+ };
91
+ try {
92
+ await graphqlRequestWithRetry(QUERY, {
93
+ authToken: 'custom',
94
+ cachePolicy: 'no-store',
95
+ shouldAcceptResult: () => {
96
+ guarded = true;
97
+ return true;
98
+ },
99
+ });
100
+ if (authorization !== 'custom' || !guarded || fetchCachedData(QUERY, makeGraphQLVariablesKey(undefined)))
101
+ throw new Error('The retry wrapper dropped request options');
102
+ } finally {
103
+ globalThis.fetch = originalFetch;
104
+ }
105
+ });
106
+
107
+ Deno.test('freshness handles exact boundaries, zero, Infinity and clock rollback consistently', () => {
108
+ const now = 1000000;
109
+ const cases: Array<[number | undefined, number, boolean]> = [
110
+ [undefined, Infinity, true],
111
+ [now, 0, true],
112
+ [now, Infinity, false],
113
+ [now - 999, 1000, false],
114
+ [now - 1000, 1000, true],
115
+ [now + 1, 1000, true],
116
+ [NaN, Infinity, true],
117
+ ];
118
+ for (const [fetchedAt, window, expected] of cases) {
119
+ if (isQueryDataStale('cacheRecord', fetchedAt, window, now) !== expected)
120
+ throw new Error(`Wrong freshness for ${fetchedAt}/${window}`);
121
+ }
122
+ });
@@ -4,7 +4,7 @@ import {
4
4
  graphqlRequestNoStore,
5
5
  setGraphQLAccessTokenRefreshHandler,
6
6
  setGraphQLManagedSessionVersion,
7
- } from './request.ts';
7
+ } from '../client/request.ts';
8
8
 
9
9
  /**
10
10
  * Build the smallest GraphQL document needed to test request authorization.