@jsb188/graphql 1.1.10 → 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 (176) hide show
  1. package/audience.d.ts +343 -0
  2. package/cache/config.ts +98 -50
  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 +1017 -127
  8. package/cache/index.ts +1256 -1269
  9. package/cache/optimistic-ui-runtime.ts +46 -0
  10. package/cache/optimistic-ui.ts +401 -0
  11. package/cache/persist.ts +800 -0
  12. package/cache/store.ts +395 -0
  13. package/cache/value.helpers.ts +17 -0
  14. package/client/draft-persistence-indexed-db.ts +413 -0
  15. package/client/draft-persistence.ts +152 -0
  16. package/client/index.ts +3 -0
  17. package/client/request.helpers.ts +14 -0
  18. package/client/request.ts +870 -164
  19. package/deno.lock +187 -0
  20. package/deno.test.json +10 -4
  21. package/gql/eagerQueryMap.ts +12 -0
  22. package/gql/fragments/accountAuthFragments.ts +5 -0
  23. package/gql/fragments/accountFragments.ts +0 -3
  24. package/gql/fragments/accountSessionFragments.ts +16 -0
  25. package/gql/fragments/agentMemoryFragments.ts +23 -0
  26. package/gql/fragments/agentNoteFragments.ts +150 -0
  27. package/gql/fragments/aiChatFragments.ts +42 -0
  28. package/gql/fragments/audienceFragments.ts +141 -0
  29. package/gql/fragments/campaignFragments.ts +566 -0
  30. package/gql/fragments/dataTableFragments.ts +50 -192
  31. package/gql/fragments/emailFragments.ts +32 -17
  32. package/gql/fragments/fieldDocFragments.ts +264 -0
  33. package/gql/fragments/inboundContactFragments.ts +2 -0
  34. package/gql/fragments/logFragments.ts +101 -69
  35. package/gql/fragments/organizationFragments.ts +53 -5
  36. package/gql/fragments/qrCodeFragments.ts +29 -0
  37. package/gql/fragments/scheduleFragments.ts +667 -0
  38. package/gql/fragments/sheetFragments.ts +304 -63
  39. package/gql/fragments/storageFragments.ts +45 -0
  40. package/gql/fragments/workflowFragments.ts +41 -5
  41. package/gql/mutations/accountMutations.ts +0 -2
  42. package/gql/mutations/agentMemoryMutations.ts +68 -0
  43. package/gql/mutations/agentNoteMutations.ts +62 -0
  44. package/gql/mutations/aiChatMutations.ts +49 -4
  45. package/gql/mutations/audienceMutations.ts +71 -0
  46. package/gql/mutations/authMutations.ts +203 -18
  47. package/gql/mutations/billingMutations.ts +17 -27
  48. package/gql/mutations/campaignMutations.ts +258 -0
  49. package/gql/mutations/contactMutations.ts +23 -0
  50. package/gql/mutations/dataTableMutations.ts +19 -54
  51. package/gql/mutations/fieldDocMutations.ts +173 -0
  52. package/gql/mutations/index.ts +10 -2
  53. package/gql/mutations/logMutations.ts +6 -29
  54. package/gql/mutations/organizationMutations.ts +19 -4
  55. package/gql/mutations/qrCodeMutations.ts +20 -0
  56. package/gql/mutations/scheduleMutations.ts +1121 -0
  57. package/gql/mutations/sheetMutations.ts +221 -60
  58. package/gql/mutations/storageMutations.ts +19 -0
  59. package/gql/mutations/workflowMutations.ts +60 -0
  60. package/gql/queries/agentMemoryQueries.ts +28 -0
  61. package/gql/queries/agentNoteQueries.ts +89 -0
  62. package/gql/queries/aiChatQueries.ts +70 -2
  63. package/gql/queries/audienceQueries.ts +128 -0
  64. package/gql/queries/authQueries.ts +47 -0
  65. package/gql/queries/billingQueries.ts +118 -6
  66. package/gql/queries/campaignQueries.ts +236 -0
  67. package/gql/queries/dataTableQueries.ts +61 -13
  68. package/gql/queries/emailQueries.ts +26 -17
  69. package/gql/queries/emailReplyReportQueries.ts +76 -0
  70. package/gql/queries/fieldDocQueries.ts +166 -0
  71. package/gql/queries/inboundContactQueries.ts +4 -0
  72. package/gql/queries/index.ts +10 -2
  73. package/gql/queries/logQueries.ts +68 -30
  74. package/gql/queries/organizationQueries.ts +65 -1
  75. package/gql/queries/qrCodeQueries.ts +20 -0
  76. package/gql/queries/scheduleQueries.ts +691 -0
  77. package/gql/queries/sheetQueries.ts +244 -26
  78. package/gql/queries/storageQueries.ts +38 -0
  79. package/gql/queries/workflowQueries.ts +77 -2
  80. package/hooks/index.helpers.test.ts +50 -0
  81. package/hooks/index.helpers.ts +52 -0
  82. package/hooks/index.ts +2254 -982
  83. package/hooks/use-account-mtn.ts +76 -81
  84. package/hooks/use-agentMemory-mtn.ts +71 -0
  85. package/hooks/use-agentMemory-qry.ts +56 -0
  86. package/hooks/use-agentNote-mtn.ts +82 -0
  87. package/hooks/use-agentNote-qry.ts +190 -0
  88. package/hooks/use-agentNote-recovery.helpers.test.ts +68 -0
  89. package/hooks/use-agentNote-recovery.helpers.ts +58 -0
  90. package/hooks/use-agentNote-recovery.ts +72 -0
  91. package/hooks/use-aiChat-mtn.ts +220 -141
  92. package/hooks/use-aiChat-qry.helpers.test.ts +63 -0
  93. package/hooks/use-aiChat-qry.helpers.ts +124 -0
  94. package/hooks/use-aiChat-qry.ts +341 -237
  95. package/hooks/use-aiChat-stream-mtn.ts +14 -0
  96. package/hooks/use-app-qry.ts +12 -9
  97. package/hooks/use-audience-mtn.ts +194 -0
  98. package/hooks/use-audience-qry.helpers.test.ts +80 -0
  99. package/hooks/use-audience-qry.helpers.ts +63 -0
  100. package/hooks/use-audience-qry.ts +330 -0
  101. package/hooks/use-auth-mtn.ts +435 -252
  102. package/hooks/use-auth-qry.ts +51 -0
  103. package/hooks/use-billing-mtn.ts +31 -0
  104. package/hooks/use-billing-qry.ts +76 -0
  105. package/hooks/use-campaign-generation-recovery.ts +53 -0
  106. package/hooks/use-campaign-mtn.ts +436 -0
  107. package/hooks/use-campaign-qry.helpers.ts +40 -0
  108. package/hooks/use-campaign-qry.ts +834 -0
  109. package/hooks/use-dataTable-mtn.ts +37 -46
  110. package/hooks/use-dataTable-qry.ts +102 -128
  111. package/hooks/use-email-qry.helpers.ts +37 -0
  112. package/hooks/use-email-qry.ts +56 -86
  113. package/hooks/use-emailCampaignReplyReport-qry.ts +27 -0
  114. package/hooks/use-fieldDoc-mtn.ts +262 -0
  115. package/hooks/use-fieldDoc-qry.helpers.test.ts +65 -0
  116. package/hooks/use-fieldDoc-qry.helpers.ts +49 -0
  117. package/hooks/use-fieldDoc-qry.ts +212 -0
  118. package/hooks/use-inboundContact-mtn.ts +19 -16
  119. package/hooks/use-inboundContact-qry.ts +62 -56
  120. package/hooks/use-integration-mtn.ts +56 -38
  121. package/hooks/use-integration-qry.ts +24 -9
  122. package/hooks/use-log-mtn.ts +88 -59
  123. package/hooks/use-log-qry.ts +150 -73
  124. package/hooks/use-organization-mtn.ts +334 -277
  125. package/hooks/use-organization-qry.ts +155 -129
  126. package/hooks/use-publicFormEmail-mtn.ts +27 -0
  127. package/hooks/use-qrCode-mtn.ts +40 -0
  128. package/hooks/use-qrCode-qry.ts +78 -0
  129. package/hooks/use-schedule-mtn.ts +589 -0
  130. package/hooks/use-schedule-qry.ts +738 -0
  131. package/hooks/use-schedule-reactive.ts +486 -0
  132. package/hooks/use-sheet-mtn.ts +157 -79
  133. package/hooks/use-sheet-qry.ts +221 -92
  134. package/hooks/use-storage-mtn.ts +81 -41
  135. package/hooks/use-storage-qry.ts +128 -14
  136. package/hooks/use-workflow-mtn.ts +72 -0
  137. package/hooks/use-workflow-qry.ts +184 -47
  138. package/libs/ai-chat-outgoing.helpers.ts +153 -0
  139. package/libs/ai-chat-outgoing.ts +11 -0
  140. package/libs/ai-chat-outgoing.types.ts +25 -0
  141. package/libs/ai-chat-run-realtime.ts +20 -0
  142. package/libs/ai-chat-submission-realtime.ts +150 -0
  143. package/libs/fragment-realtime-sequence.ts +55 -0
  144. package/libs/fragment-recovery.test.ts +326 -0
  145. package/libs/fragment-recovery.ts +325 -0
  146. package/libs/open-sheet.ts +138 -0
  147. package/libs/orchestrator-realtime.helpers.test.ts +229 -0
  148. package/libs/orchestrator-realtime.helpers.ts +317 -0
  149. package/libs/orchestrator-realtime.ts +433 -0
  150. package/libs/request-cache-regression.test.ts +122 -0
  151. package/libs/request-managed-session.test.ts +574 -0
  152. package/libs/request-no-store.test.ts +419 -0
  153. package/libs/sheet-command-batch.ts +44 -0
  154. package/libs/sheet-view-realtime-router.test.ts +214 -0
  155. package/libs/sheet-view-realtime-router.ts +99 -0
  156. package/libs/sse-ticket.test.ts +26 -0
  157. package/loaders/campaign.test.ts +186 -0
  158. package/loaders/campaign.ts +110 -0
  159. package/loaders/emailPreference.ts +75 -0
  160. package/loaders/rest.ts +12 -0
  161. package/package.json +119 -71
  162. package/schedule.d.ts +1790 -0
  163. package/sse.helpers.ts +19 -0
  164. package/sse.ts +70 -106
  165. package/tests/agent-note-detail-cache.test.ts +120 -0
  166. package/tests/agent-note-search.test.ts +444 -0
  167. package/tsconfig.json +11 -10
  168. package/types.d.ts +77 -26
  169. package/utils.ts +78 -49
  170. package/gql/fragments/billingFragments.ts +0 -25
  171. package/gql/fragments/productFragments.ts +0 -39
  172. package/gql/fragments/reportFragments.ts +0 -90
  173. package/gql/queries/productQueries.ts +0 -31
  174. package/gql/queries/reportQueries.ts +0 -134
  175. package/hooks/use-product-qry.ts +0 -67
  176. package/hooks/use-report-qry.ts +0 -153
@@ -0,0 +1,325 @@
1
+ import type { WSDataUpdateObj, WSFragmentRecoveryTarget } from '@jsb188/app/types/app.d.ts';
2
+ import { getAuthToken, getManagedAccessTokenBinding, managedAccessTokensShareBinding } from '@jsb188/app/utils/api.ts';
3
+ import { FRAGMENT_NAMES } from '@jsb188/mday/constants/graphqlReactivity.ts';
4
+ import { getFragmentVersionStamp, getGraphQLCacheEpoch, loadFragment } from '../cache/index.ts';
5
+ import { graphqlRequestNoStore } from '../client/request.ts';
6
+ import { agentNoteQry } from '../gql/queries/agentNoteQueries.ts';
7
+ import { logEntryQry } from '../gql/queries/logQueries.ts';
8
+ import { getFragmentRealtimeEpoch, isFragmentRealtimeSequenceCurrent } from './fragment-realtime-sequence.ts';
9
+
10
+ type Fragment = NonNullable<NonNullable<WSDataUpdateObj['fragments']>[number]>;
11
+ type RecoveryFlight = {
12
+ key: string;
13
+ users: number;
14
+ settled: boolean;
15
+ authToken: string | null;
16
+ epoch: number;
17
+ cacheEpoch: number;
18
+ recoveryEpoch: number;
19
+ organizationId: string;
20
+ dataId: string;
21
+ kind: WSFragmentRecoveryTarget['kind'];
22
+ controller: AbortController;
23
+ keys: Set<string>;
24
+ markers: Map<string, { eventId: string; sequence?: string }>;
25
+ dirty: number;
26
+ promise: Promise<{ data: any; version: string; dirty: number } | null>;
27
+ };
28
+
29
+ type RecoveryResolution = { fragment: Fragment | null; original: Fragment | null; isCurrent?: () => boolean };
30
+
31
+ const RECOVERY_FLIGHTS = new Map<string, RecoveryFlight>();
32
+ const FILE_CONSTANTS = { attempts: 3, timeoutMs: 10_000 };
33
+ let recoveryEpoch = 0;
34
+
35
+ /* Accept transparent token renewal only within the same authenticated session. */
36
+ function isRecoveryAuthenticationCurrent(authToken: string | null) {
37
+ const current = getAuthToken();
38
+ return authToken === current || !!(authToken && current && managedAccessTokensShareBinding(authToken, current));
39
+ }
40
+
41
+ /* Reject detached work after an authorization/cache epoch or authenticated session changes. */
42
+ function isRecoveryFlightCurrent(flight: RecoveryFlight) {
43
+ return (
44
+ flight.epoch === getFragmentRealtimeEpoch() &&
45
+ flight.cacheEpoch === getGraphQLCacheEpoch() &&
46
+ flight.recoveryEpoch === recoveryEpoch &&
47
+ !flight.controller.signal.aborted &&
48
+ isRecoveryAuthenticationCurrent(flight.authToken)
49
+ );
50
+ }
51
+
52
+ /* A deleted parent must not be resurrected by a late detail response. */
53
+ function isRecoveryEntityDeleted(flight: RecoveryFlight) {
54
+ const parentName = flight.kind === 'AGENT_NOTE' ? FRAGMENT_NAMES.agentNote : FRAGMENT_NAMES.logEntry;
55
+ return loadFragment(`${parentName}:${flight.dataId}`)?.__deleted === true;
56
+ }
57
+
58
+ /* Compare valid decimal marker revisions without losing precision or allowing an older owner to take over. */
59
+ function isRecoveryMarkerOlder(sequence: string | undefined, current: string | undefined) {
60
+ if (!sequence || !current || !/^\d+$/.test(sequence) || !/^\d+$/.test(current)) return false;
61
+ const left = sequence.replace(/^0+(?=\d)/, '');
62
+ const right = current.replace(/^0+(?=\d)/, '');
63
+ return left.length < right.length || (left.length === right.length && left < right);
64
+ }
65
+
66
+ /* Select only the supported point-read contract for this fragment identity. */
67
+ function getRecoveryDocument(fragment: Fragment) {
68
+ const recovery = fragment.recovery;
69
+ if (!recovery?.organizationId || !fragment.dataId || fragment.appendRule) return null;
70
+ if (recovery.kind === 'AGENT_NOTE' && fragment.name === FRAGMENT_NAMES.agentNote) {
71
+ return { query: agentNoteQry, root: 'agentNote', fragmentName: 'agentNoteDetailFragment', nested: null };
72
+ }
73
+ if (
74
+ recovery.kind === 'LOG_ENTRY' &&
75
+ (fragment.name === FRAGMENT_NAMES.logEntry || fragment.name === FRAGMENT_NAMES.logEntryDetails)
76
+ ) {
77
+ return {
78
+ query: logEntryQry,
79
+ root: 'logEntry',
80
+ fragmentName: fragment.name.slice(1),
81
+ nested: fragment.name === FRAGMENT_NAMES.logEntryDetails ? 'details' : null,
82
+ };
83
+ }
84
+ return null;
85
+ }
86
+
87
+ /* Project the current document's selected fields without normalizing unrelated nested entities. */
88
+ function projectRecoverySelection(value: any, selections: readonly any[], definitions: readonly any[]): any {
89
+ if (value === null || value === undefined) return value;
90
+ if (Array.isArray(value)) return value.map((item) => projectRecoverySelection(item, selections, definitions));
91
+ const result: Record<string, any> = {};
92
+ for (const selection of selections) {
93
+ if (selection.kind === 'FragmentSpread') {
94
+ const definition = definitions.find(
95
+ (candidate) => candidate.kind === 'FragmentDefinition' && candidate.name.value === selection.name.value,
96
+ );
97
+ if (definition) Object.assign(result, projectRecoverySelection(value, definition.selectionSet.selections, definitions));
98
+ } else if (selection.kind === 'InlineFragment') {
99
+ Object.assign(result, projectRecoverySelection(value, selection.selectionSet.selections, definitions));
100
+ } else if (selection.kind === 'Field') {
101
+ const key = selection.alias?.value || selection.name.value;
102
+ if (!Object.hasOwn(value, key)) continue;
103
+ result[key] = selection.selectionSet
104
+ ? projectRecoverySelection(value[key], selection.selectionSet.selections, definitions)
105
+ : value[key];
106
+ }
107
+ }
108
+ return result;
109
+ }
110
+
111
+ /* Read one entity again when a concurrent write makes its in-flight snapshot unsafe to apply. */
112
+ async function readRecoveryFlight(flight: RecoveryFlight) {
113
+ const query = flight.kind === 'AGENT_NOTE' ? agentNoteQry : logEntryQry;
114
+ const variables = {
115
+ organizationId: flight.organizationId,
116
+ [flight.kind === 'AGENT_NOTE' ? 'agentNoteId' : 'logEntryId']: flight.dataId,
117
+ };
118
+ for (let attempt = 0; attempt < FILE_CONSTANTS.attempts && isRecoveryFlightCurrent(flight); attempt += 1) {
119
+ if (isRecoveryEntityDeleted(flight)) return null;
120
+ const dirty = flight.dirty;
121
+ const keys = [...flight.keys];
122
+ const version = getFragmentVersionStamp(keys);
123
+ const controller = new AbortController();
124
+ /* Propagate session cancellation to the currently active network attempt. */
125
+ const abort = () => controller.abort();
126
+ flight.controller.signal.addEventListener('abort', abort, { once: true });
127
+ const timeout = setTimeout(abort, FILE_CONSTANTS.timeoutMs);
128
+ let result: any;
129
+ try {
130
+ result = await graphqlRequestNoStore(
131
+ query,
132
+ variables,
133
+ { shouldAcceptResult: () => isRecoveryFlightCurrent(flight) },
134
+ controller.signal,
135
+ );
136
+ } finally {
137
+ clearTimeout(timeout);
138
+ flight.controller.signal.removeEventListener('abort', abort);
139
+ }
140
+ if (!isRecoveryFlightCurrent(flight)) return null;
141
+ if (dirty !== flight.dirty || keys.length !== flight.keys.size || version !== getFragmentVersionStamp(keys)) continue;
142
+ if (!result?.error && !result?.aborted && !result?.__clientResultRejected) {
143
+ return { data: result, version, dirty };
144
+ }
145
+ // Authorization and missing reads are ambiguous; retain the cached value and never invent a tombstone.
146
+ if ([20052, 20059, 20232].includes(Number(result?.error?.errorCode))) break;
147
+ if (attempt + 1 < FILE_CONSTANTS.attempts)
148
+ await new Promise((resolve) => setTimeout(resolve, 150 * 2 ** attempt + Math.floor(Math.random() * 100)));
149
+ }
150
+ if (isRecoveryFlightCurrent(flight)) console.warn('Unable to recover an oversized realtime fragment; preserving its cached value.');
151
+ return null;
152
+ }
153
+
154
+ /* Share a bounded point read across simultaneous core/detail markers for one authorized entity. */
155
+ function getRecoveryFlight(fragment: Fragment, eventId: string) {
156
+ eventId = JSON.stringify([eventId, fragment.sequenceKey, fragment.sequence]);
157
+ const recovery = fragment.recovery!;
158
+ const authToken = getAuthToken();
159
+ const epoch = getFragmentRealtimeEpoch();
160
+ const cacheEpoch = getGraphQLCacheEpoch();
161
+ const scope = authToken ? getManagedAccessTokenBinding(authToken) || authToken : null;
162
+ const flightKey = JSON.stringify([epoch, cacheEpoch, scope, recovery.kind, recovery.organizationId, fragment.dataId]);
163
+ let flight = RECOVERY_FLIGHTS.get(flightKey);
164
+ if (!flight) {
165
+ flight = {
166
+ key: flightKey,
167
+ users: 0,
168
+ settled: false,
169
+ authToken,
170
+ epoch,
171
+ cacheEpoch,
172
+ recoveryEpoch,
173
+ organizationId: recovery.organizationId,
174
+ dataId: fragment.dataId,
175
+ kind: recovery.kind,
176
+ controller: new AbortController(),
177
+ keys: new Set(),
178
+ markers: new Map(),
179
+ dirty: 0,
180
+ promise: Promise.resolve(null),
181
+ };
182
+ const activeFlight = flight;
183
+ // Defer dispatch until synchronous marker registration has gathered every projection of this entity.
184
+ flight.promise = Promise.resolve()
185
+ .then(() => readRecoveryFlight(activeFlight))
186
+ .finally(() => {
187
+ activeFlight.settled = true;
188
+ });
189
+ RECOVERY_FLIGHTS.set(flightKey, flight);
190
+ }
191
+ const key = `${fragment.name}:${fragment.dataId}`;
192
+ const priorMarker = flight.markers.get(key);
193
+ if (priorMarker && isRecoveryMarkerOlder(fragment.sequence, priorMarker.sequence)) return flight;
194
+ if (priorMarker && priorMarker.eventId !== eventId) flight.dirty += 1;
195
+ flight.keys.add(key);
196
+ if (recovery.kind === 'LOG_ENTRY') flight.keys.add(`${FRAGMENT_NAMES.logEntry}:${fragment.dataId}`);
197
+ flight.markers.set(key, { eventId, sequence: fragment.sequence });
198
+ if (flight.settled) {
199
+ const activeFlight = flight;
200
+ flight.settled = false;
201
+ flight.promise = Promise.resolve()
202
+ .then(() => readRecoveryFlight(activeFlight))
203
+ .finally(() => {
204
+ activeFlight.settled = true;
205
+ });
206
+ }
207
+ return flight;
208
+ }
209
+
210
+ /* Register accepted ordinary writes only while a related point read is in flight. */
211
+ export function noteFragmentRealtimeUpdate(fragment: Fragment) {
212
+ const key = `${fragment.name}:${fragment.dataId}`;
213
+ for (const flight of RECOVERY_FLIGHTS.values()) {
214
+ if (flight.keys.has(key)) flight.dirty += 1;
215
+ }
216
+ }
217
+
218
+ /* Abort outstanding private reads when the surrounding websocket/cache scope is discarded. */
219
+ export function clearFragmentRecoveryRequests() {
220
+ recoveryEpoch += 1;
221
+ for (const flight of RECOVERY_FLIGHTS.values()) flight.controller.abort();
222
+ RECOVERY_FLIGHTS.clear();
223
+ }
224
+
225
+ /* Resolve one marker without ever writing its placeholder or an unguarded HTTP response into cache. */
226
+ async function resolveRecoveryFragment(
227
+ fragment: Fragment | null,
228
+ eventId: string,
229
+ ownedFlights: Set<RecoveryFlight>,
230
+ ): Promise<RecoveryResolution> {
231
+ const unchanged = { fragment, original: fragment };
232
+ if (!fragment?.recovery) return unchanged;
233
+ const contract = getRecoveryDocument(fragment);
234
+ const sequenceKey = `${fragment.sequenceKey || fragment.name}:${fragment.dataId}`;
235
+ if (!contract || !isFragmentRealtimeSequenceCurrent(sequenceKey, fragment.sequence)) return unchanged;
236
+ const flight = getRecoveryFlight(fragment, eventId);
237
+ if (!ownedFlights.has(flight)) {
238
+ ownedFlights.add(flight);
239
+ flight.users += 1;
240
+ }
241
+ const markerId = JSON.stringify([eventId, fragment.sequenceKey, fragment.sequence]);
242
+ const read = await flight.promise;
243
+ const result = read?.data;
244
+ /* Recheck after sibling reads finish, immediately before the packet can enter the normal apply path. */
245
+ const isCurrent = () =>
246
+ isRecoveryFlightCurrent(flight) &&
247
+ !isRecoveryEntityDeleted(flight) &&
248
+ flight.markers.get(`${fragment.name}:${fragment.dataId}`)?.eventId === markerId &&
249
+ isFragmentRealtimeSequenceCurrent(sequenceKey, fragment.sequence) &&
250
+ read?.dirty === flight.dirty &&
251
+ read?.version === getFragmentVersionStamp([...flight.keys]);
252
+ if (!result || !isCurrent()) return unchanged;
253
+ const root = result[contract.root];
254
+ if (
255
+ !root ||
256
+ String(root.id) !== fragment.dataId ||
257
+ (root.organizationId && root.organizationId !== fragment.recovery.organizationId)
258
+ )
259
+ return unchanged;
260
+ const value = contract.nested ? root?.[contract.nested] : root;
261
+ if (!value || String(value.id) !== fragment.dataId) return unchanged;
262
+ const definitions = contract.query.definitions;
263
+ const definition = definitions.find(
264
+ (candidate: any) => candidate.kind === 'FragmentDefinition' && candidate.name.value === contract.fragmentName,
265
+ );
266
+ if (definition?.kind !== 'FragmentDefinition') return unchanged;
267
+ const { recovery: _recovery, ...resolved } = fragment;
268
+ return {
269
+ fragment: { ...resolved, data: projectRecoverySelection(value, definition.selectionSet.selections, definitions) },
270
+ original: fragment,
271
+ isCurrent,
272
+ };
273
+ }
274
+
275
+ /* Resolve a fragment-only packet after its original inline fragments and reset controls have been applied. */
276
+ export async function resolveFragmentRecoveryUpdate(
277
+ update: WSDataUpdateObj,
278
+ applyRecovered: (update: WSDataUpdateObj) => void,
279
+ ): Promise<void> {
280
+ const authToken = getAuthToken();
281
+ const epoch = getFragmentRealtimeEpoch();
282
+ const cacheEpoch = getGraphQLCacheEpoch();
283
+ const initialRecoveryEpoch = recoveryEpoch;
284
+ const ownedFlights = new Set<RecoveryFlight>();
285
+ try {
286
+ let resolutions = await Promise.all(
287
+ (update.fragments || []).map((fragment) => resolveRecoveryFragment(fragment, update.id, ownedFlights)),
288
+ );
289
+ for (let attempt = 1; attempt < FILE_CONSTANTS.attempts; attempt += 1) {
290
+ if (
291
+ initialRecoveryEpoch !== recoveryEpoch ||
292
+ epoch !== getFragmentRealtimeEpoch() ||
293
+ cacheEpoch !== getGraphQLCacheEpoch() ||
294
+ !isRecoveryAuthenticationCurrent(authToken)
295
+ )
296
+ return;
297
+ if (!resolutions.some((resolution) => resolution.isCurrent && !resolution.isCurrent())) break;
298
+ resolutions = await Promise.all(
299
+ resolutions.map((resolution) =>
300
+ resolution.isCurrent && !resolution.isCurrent()
301
+ ? resolveRecoveryFragment(resolution.original, update.id, ownedFlights)
302
+ : resolution,
303
+ ),
304
+ );
305
+ }
306
+ if (
307
+ initialRecoveryEpoch !== recoveryEpoch ||
308
+ epoch !== getFragmentRealtimeEpoch() ||
309
+ cacheEpoch !== getGraphQLCacheEpoch() ||
310
+ !isRecoveryAuthenticationCurrent(authToken)
311
+ )
312
+ return;
313
+ applyRecovered({
314
+ ...update,
315
+ fragments: resolutions.map((resolution) =>
316
+ resolution.isCurrent && !resolution.isCurrent() ? resolution.original : resolution.fragment,
317
+ ),
318
+ });
319
+ } finally {
320
+ for (const flight of ownedFlights) {
321
+ flight.users -= 1;
322
+ if (!flight.users && RECOVERY_FLIGHTS.get(flight.key) === flight) RECOVERY_FLIGHTS.delete(flight.key);
323
+ }
324
+ }
325
+ }
@@ -0,0 +1,138 @@
1
+ import type {
2
+ SheetBootstrapGQL,
3
+ SheetJournalSeqInput,
4
+ SheetRealtimeCapabilityGQL,
5
+ SheetTabBootstrapGQL,
6
+ } from '@jsb188/mday/types/sheet.d.ts';
7
+ import { parseSheetJournalSeq } from '@jsb188/mday/utils/sheetSequence.ts';
8
+ import { graphqlRequestNoStore } from '../client/request.ts';
9
+ import { openSheetQry, renewSheetRealtimeCapabilityQry, syncSheetTabQry } from '../gql/queries/sheetQueries.ts';
10
+
11
+ /*
12
+ * Bootstrap contract 4 (DESIGN §1.3): openSheet negotiates the workbook and
13
+ * its selected tab, syncSheetTab one tab once the manifest is known. Both ask
14
+ * for the rows after the tab's applied `sinceSeq` (DELTA) and fall back to a
15
+ * snapshot plus its tail; there is no viewport and no base-snapshot proof.
16
+ */
17
+
18
+ export type FetchOpenSheetOnceParams = {
19
+ selectedTabId?: string | null;
20
+ sinceSeq?: SheetJournalSeqInput;
21
+ requireSnapshot?: boolean;
22
+
23
+ authToken?: string | null;
24
+ signal?: AbortSignal | null;
25
+ };
26
+
27
+ export type FetchSyncSheetTabOnceParams = {
28
+ sinceSeq?: SheetJournalSeqInput;
29
+ requireSnapshot?: boolean;
30
+ minimumCellsRevision?: SheetJournalSeqInput;
31
+ minimumDesignRevision?: SheetJournalSeqInput;
32
+
33
+ authToken?: string | null;
34
+ signal?: AbortSignal | null;
35
+ };
36
+
37
+ /*
38
+ * Return the canonical openSheet variables of one fetch. Journal cursors are
39
+ * sent as canonical decimal strings; an absent or malformed one is null..
40
+ */
41
+ export function getOpenSheetQueryVariables(sheetId: string, params: FetchOpenSheetOnceParams = {}) {
42
+ return {
43
+ sheetId,
44
+ selectedTabId: params.selectedTabId || null,
45
+ sinceSeq: parseSheetJournalSeq(params.sinceSeq),
46
+ requireSnapshot: Boolean(params.requireSnapshot),
47
+ };
48
+ }
49
+
50
+ /*
51
+ * Return the canonical syncSheetTab variables of one fetch.
52
+ */
53
+ export function getSyncSheetTabQueryVariables(sheetId: string, sheetTabId: string, params: FetchSyncSheetTabOnceParams = {}) {
54
+ return {
55
+ sheetId,
56
+ sheetTabId,
57
+ sinceSeq: parseSheetJournalSeq(params.sinceSeq),
58
+ requireSnapshot: Boolean(params.requireSnapshot),
59
+ minimumCellsRevision: parseSheetJournalSeq(params.minimumCellsRevision),
60
+ minimumDesignRevision: parseSheetJournalSeq(params.minimumDesignRevision),
61
+ };
62
+ }
63
+
64
+ /*
65
+ * Return one no-store operation's field, throwing an AbortError for an
66
+ * aborted request and the normalized server error for a failed one.
67
+ */
68
+ function getSheetBootstrapOperationResult<T>(
69
+ result: any,
70
+ operation: 'openSheet' | 'renewSheetRealtimeCapability' | 'syncSheetTab',
71
+ ): T | null {
72
+ if (result?.aborted) {
73
+ throw new DOMException(`${operation} request was aborted.`, 'AbortError');
74
+ }
75
+ if (result?.error) {
76
+ throw result.error;
77
+ }
78
+
79
+ return result?.[operation] || null;
80
+ }
81
+
82
+ /*
83
+ * Imperatively fetch one openSheet response exactly once without reading,
84
+ * writing, or joining the normalized GraphQL cache. Each invocation owns its
85
+ * network request and carries its authorization token only in request headers.
86
+ */
87
+ export async function fetchOpenSheetOnce(sheetId: string, params: FetchOpenSheetOnceParams = {}): Promise<SheetBootstrapGQL | null> {
88
+ const result = await graphqlRequestNoStore(
89
+ openSheetQry,
90
+ getOpenSheetQueryVariables(sheetId, params),
91
+ { authToken: params.authToken },
92
+ params.signal,
93
+ );
94
+
95
+ return getSheetBootstrapOperationResult<SheetBootstrapGQL>(result, 'openSheet');
96
+ }
97
+
98
+ /*
99
+ * Renew one Sheet's realtime capability without reading or writing the normalized GraphQL cache.
100
+ */
101
+ export async function fetchSheetRealtimeCapabilityOnce(
102
+ sheetId: string,
103
+ params: {
104
+ authToken?: string | null;
105
+
106
+ signal?: AbortSignal | null;
107
+ } = {},
108
+ ): Promise<SheetRealtimeCapabilityGQL | null> {
109
+ const result = await graphqlRequestNoStore(
110
+ renewSheetRealtimeCapabilityQry,
111
+ {
112
+ sheetId,
113
+ },
114
+ { authToken: params.authToken },
115
+ params.signal,
116
+ );
117
+
118
+ return getSheetBootstrapOperationResult<SheetRealtimeCapabilityGQL>(result, 'renewSheetRealtimeCapability');
119
+ }
120
+
121
+ /*
122
+ * Synchronize one tab through the snapshot/delta negotiation without
123
+ * consulting or mutating the normalized GraphQL cache.
124
+ */
125
+ export async function fetchSyncSheetTabOnce(
126
+ sheetId: string,
127
+ sheetTabId: string,
128
+ params: FetchSyncSheetTabOnceParams = {},
129
+ ): Promise<SheetTabBootstrapGQL | null> {
130
+ const result = await graphqlRequestNoStore(
131
+ syncSheetTabQry,
132
+ getSyncSheetTabQueryVariables(sheetId, sheetTabId, params),
133
+ { authToken: params.authToken },
134
+ params.signal,
135
+ );
136
+
137
+ return getSheetBootstrapOperationResult<SheetTabBootstrapGQL>(result, 'syncSheetTab');
138
+ }
@@ -0,0 +1,229 @@
1
+ import type { OrchestratorArtifactWSObj } from '@jsb188/app/types/app.d.ts';
2
+ import {
3
+ applyOrchestratorArtifactUpdate,
4
+ type OrchestratorSessionData,
5
+ getEmptyOrchestratorSessionData,
6
+ mergeOrchestratorArtifactUpdates,
7
+ } from './orchestrator-realtime.helpers.ts';
8
+
9
+ /*
10
+ * Throw one readable test failure when a condition is false.
11
+ */
12
+ function expect(value: unknown, message: string) {
13
+ if (!value) {
14
+ throw new Error(message);
15
+ }
16
+ }
17
+
18
+ /*
19
+ * Build one artifact event of the orchestrator chat used by every case.
20
+ */
21
+ function event(callId: string, at: string, fields: Partial<OrchestratorArtifactWSObj>): OrchestratorArtifactWSObj {
22
+ return {
23
+ aiChatId: 'chat-1',
24
+ runId: 'run-1',
25
+ callId,
26
+ organizationId: 'org-1',
27
+ toolName: 'create_sheet_tab',
28
+ kind: 'SHEET_TAB',
29
+ action: 'CREATED',
30
+ sheetId: 'S1',
31
+ at: `2026-09-25T00:00:0${at}.000Z`,
32
+ ...fields,
33
+ };
34
+ }
35
+
36
+ /*
37
+ * Apply live events in order, the way the store does as they arrive.
38
+ */
39
+ function applyLive(updates: OrchestratorArtifactWSObj[]) {
40
+ let session: OrchestratorSessionData = {
41
+ ...getEmptyOrchestratorSessionData(),
42
+ aiChatId: 'chat-1',
43
+ };
44
+ for (const update of updates) {
45
+ session = applyOrchestratorArtifactUpdate(session, update)?.session || session;
46
+ }
47
+ return session;
48
+ }
49
+
50
+ Deno.test('caught-up events fill gaps without regressing newer live entries', () => {
51
+ const renamed = event('c3', '3', {
52
+ toolName: 'update_sheet_tab',
53
+ action: 'UPDATED',
54
+ sheetTabId: 'T1',
55
+ title: 'Costs',
56
+ });
57
+ const live = applyLive([renamed]);
58
+ const merged = mergeOrchestratorArtifactUpdates(live, [
59
+ event('c1', '1', { sheetTabId: 'T1', title: 'Sheet 2' }),
60
+ event('c2', '2', {
61
+ toolName: 'create_data_table',
62
+ kind: 'DATA_TABLE',
63
+ sheetId: null,
64
+ dataTableId: 'D1',
65
+ title: 'Inventory',
66
+ }),
67
+ renamed,
68
+ ]);
69
+
70
+ expect(merged, 'Missed calls must change the session.');
71
+ const [tab, table] = merged!.artifacts;
72
+ expect(
73
+ tab.key === 'SHEET_TAB:T1' && tab.state === 'CREATED' && tab.title === 'Costs' && tab.at === renamed.at,
74
+ 'An older caught-up creation may add the CREATED state but must keep the newer title and time.',
75
+ );
76
+ expect(table.key === 'DATA_TABLE:D1' && merged!.artifacts.length === 2, 'The missed table is listed after the newer tab.');
77
+ expect(merged!.hasCreated, 'Caught-up creations count toward hasCreated.');
78
+ expect(merged!.callIds.join() === 'c1,c2,c3', 'Caught-up call ids are remembered as the newest.');
79
+ expect(mergeOrchestratorArtifactUpdates(merged!, [renamed]) === null, 'A repeated catch-up changes nothing.');
80
+ });
81
+
82
+ Deno.test('a deletion received live still wins over its older caught-up creation', () => {
83
+ const deleted = event('c2', '2', {
84
+ toolName: 'delete_sheet_tab',
85
+ action: 'DELETED',
86
+ sheetTabId: 'T1',
87
+ });
88
+ const merged = mergeOrchestratorArtifactUpdates(applyLive([deleted]), [event('c1', '1', { sheetTabId: 'T1' }), deleted]);
89
+
90
+ expect(merged && merged.artifacts.length === 0, 'The deleted tab must not be resurrected by its creation.');
91
+ });
92
+
93
+ Deno.test('live creations navigate once, and a data table only before any other grid', () => {
94
+ const tab = event('c1', '1', { sheetTabId: 'T1' });
95
+ const first = applyOrchestratorArtifactUpdate(applyLive([]), tab);
96
+ expect(first?.navigateTo?.key === 'SHEET_TAB:T1' && first.session.hasCreated, 'A created tab navigates and counts as a creation.');
97
+ expect(applyOrchestratorArtifactUpdate(first!.session, tab) === null, 'A tool call is applied once.');
98
+ expect(
99
+ applyOrchestratorArtifactUpdate(first!.session, { ...tab, callId: 'c1b' })?.navigateTo === null,
100
+ 'A replayed creation of an already created entry does not navigate again.',
101
+ );
102
+
103
+ const table = event('c2', '2', {
104
+ toolName: 'create_data_table',
105
+ kind: 'DATA_TABLE',
106
+ sheetId: null,
107
+ dataTableId: 'D1',
108
+ });
109
+ expect(
110
+ applyOrchestratorArtifactUpdate(applyLive([]), table)?.navigateTo?.key === 'DATA_TABLE:D1',
111
+ 'A data table created first navigates.',
112
+ );
113
+ expect(
114
+ applyOrchestratorArtifactUpdate(first!.session, table)?.navigateTo === null,
115
+ 'A data table created after a sheet tab is only listed.',
116
+ );
117
+ });
118
+
119
+ Deno.test('forms and workflows are listed with their organization and state, never navigated to', () => {
120
+ const form = event('c1', '1', {
121
+ toolName: 'save_field_doc',
122
+ kind: 'FIELD_DOC',
123
+ sheetId: null,
124
+ fieldDocId: 'F1',
125
+ fieldDocProgramId: 'P1',
126
+ title: 'Delivery check',
127
+ });
128
+ const workflow = event('c2', '2', {
129
+ toolName: 'save_workflow',
130
+ kind: 'WORKFLOW',
131
+ sheetId: null,
132
+ workflowId: 'W1',
133
+ active: false,
134
+ title: 'Notify dispatch',
135
+ });
136
+ const applied = applyOrchestratorArtifactUpdate(applyLive([]), form);
137
+ expect(
138
+ applied?.navigateTo === null && !applied.session.hasCreated,
139
+ 'A created form is not navigated to and does not block table navigation.',
140
+ );
141
+
142
+ const activated = event('c3', '3', {
143
+ toolName: 'set_workflow_active',
144
+ kind: 'WORKFLOW',
145
+ action: 'UPDATED',
146
+ sheetId: null,
147
+ workflowId: 'W1',
148
+ active: true,
149
+ organizationId: null,
150
+ });
151
+ const session = applyLive([form, workflow, activated]);
152
+ const [listedWorkflow, listedForm] = session.artifacts;
153
+ expect(
154
+ listedWorkflow.key === 'WORKFLOW:W1' &&
155
+ listedWorkflow.state === 'CREATED' &&
156
+ listedWorkflow.active === true &&
157
+ listedWorkflow.title === 'Notify dispatch' &&
158
+ listedWorkflow.organizationId === 'org-1',
159
+ 'Activation updates the state and keeps what the creation reported.',
160
+ );
161
+ expect(
162
+ listedForm.key === 'FIELD_DOC:F1' && listedForm.fieldDocProgramId === 'P1' && listedForm.organizationId === 'org-1',
163
+ 'The form keeps its program and organization.',
164
+ );
165
+
166
+ const merged = mergeOrchestratorArtifactUpdates(applyLive([activated]), [workflow, activated]);
167
+ expect(
168
+ merged?.artifacts[0].active === true && merged.artifacts[0].state === 'CREATED',
169
+ 'An older caught-up save adds CREATED without undoing the newer activation.',
170
+ );
171
+ });
172
+
173
+ Deno.test('deleting a tab clears it from its spreadsheet entry', () => {
174
+ const sheet = event('c1', '1', {
175
+ toolName: 'create_spreadsheet',
176
+ kind: 'SHEET',
177
+ sheetTabId: 'T1',
178
+ });
179
+ const deleted = event('c2', '2', {
180
+ toolName: 'delete_sheet_tab',
181
+ action: 'DELETED',
182
+ sheetTabId: 'T1',
183
+ });
184
+ const live = applyLive([sheet, deleted]);
185
+ expect(live.artifacts.length === 1 && live.artifacts[0].sheetTabId === null, 'The spreadsheet no longer opens on the deleted tab.');
186
+
187
+ const merged = mergeOrchestratorArtifactUpdates(applyLive([deleted, sheet]), [sheet, deleted]);
188
+ expect(
189
+ merged?.artifacts[0].key === 'SHEET:S1' && merged.artifacts[0].sheetTabId === null,
190
+ 'A caught-up deletion clears a tab the spreadsheet regained from a live event.',
191
+ );
192
+ });
193
+
194
+ Deno.test('publishing clears a draft and delayed draft receipts cannot bring it back', () => {
195
+ const draft = event('draft', '1', {
196
+ kind: 'FIELD_DOC',
197
+ fieldDocId: 'F1',
198
+ fieldDocProgramId: 'P1',
199
+ hasDraft: true,
200
+ });
201
+ const published = event('publish', '3', {
202
+ kind: 'FIELD_DOC',
203
+ fieldDocId: 'F1',
204
+ action: 'UPDATED',
205
+ hasDraft: false,
206
+ });
207
+ const live = applyLive([draft, published]);
208
+ expect(live.artifacts[0].hasDraft === false, 'Publishing must clear the saved draft reminder.');
209
+ const delayed = applyOrchestratorArtifactUpdate(live, { ...draft, callId: 'delayed' });
210
+ expect(delayed?.session.artifacts[0].hasDraft === false, 'An older live save cannot restore draft status.');
211
+ const caughtUp = mergeOrchestratorArtifactUpdates(applyLive([published]), [draft]);
212
+ expect(caughtUp?.artifacts[0].hasDraft === false, 'An older caught-up draft cannot restore draft status.');
213
+ });
214
+
215
+ Deno.test('catch-up refreshes an already-seen draft from current stored state independently of call order', () => {
216
+ const draft = event('draft', '1', {
217
+ kind: 'FIELD_DOC',
218
+ fieldDocId: 'F1',
219
+ hasDraft: true,
220
+ });
221
+ const publishedElsewhere = { ...draft, hasDraft: false, draftStateAt: '2026-09-25T00:00:04.000Z' };
222
+ const merged = mergeOrchestratorArtifactUpdates(applyLive([draft]), [publishedElsewhere]);
223
+ expect(merged?.artifacts[0].hasDraft === false, 'An already-seen call must accept freshly read publication state.');
224
+ expect(merged?.artifacts[0].at === draft.at, 'Refreshing current state must not pretend another tool edit occurred.');
225
+ const staleCatchUp = mergeOrchestratorArtifactUpdates(merged!, [{ ...draft, draftStateAt: '2026-09-25T00:00:02.000Z' }]);
226
+ expect(staleCatchUp === null, 'An older response arriving late must not replace newer observed publication state.');
227
+ const nextDraft = applyOrchestratorArtifactUpdate(merged!, { ...draft, callId: 'next', at: '2026-09-25T00:00:05.000Z' });
228
+ expect(nextDraft?.session.artifacts[0].hasDraft === true, 'A later edit can create a new draft after publication.');
229
+ });