@jsb188/graphql 1.1.12 → 1.1.13

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 (137) hide show
  1. package/LICENSE +21 -0
  2. package/audience.d.ts +14 -152
  3. package/cache/config.ts +35 -32
  4. package/cache/index.helpers.ts +1 -1
  5. package/cache/index.ts +73 -44
  6. package/cache/mounted-queries.ts +33 -0
  7. package/cache/persist.ts +10 -4
  8. package/cache/realtime-fence.ts +47 -0
  9. package/cache/realtime-live.ts +17 -0
  10. package/client/draft-persistence.ts +10 -39
  11. package/client/index.ts +2 -1
  12. package/client/request.ts +9 -34
  13. package/client/storage-asset.ts +58 -0
  14. package/gql/fragments/accountAuthFragments.ts +0 -4
  15. package/gql/fragments/agentNoteFragments.ts +8 -2
  16. package/gql/fragments/aiChatFragments.ts +0 -2
  17. package/gql/fragments/aiChatLinkFragments.ts +8 -0
  18. package/gql/fragments/audienceFragments.ts +1 -66
  19. package/gql/fragments/emailFragments.ts +27 -4
  20. package/gql/fragments/emailOutreachFragments.ts +281 -0
  21. package/gql/fragments/inboundContactFragments.ts +1 -1
  22. package/gql/fragments/libraryFragments.ts +120 -0
  23. package/gql/fragments/organizationFragments.ts +4 -2
  24. package/gql/fragments/scheduleFragments.ts +241 -324
  25. package/gql/fragments/sheetFragments.ts +4 -53
  26. package/gql/fragments/workWaitFragments.ts +13 -0
  27. package/gql/fragments/workflowFragments.ts +20 -4
  28. package/gql/mutations/agentNoteMutations.ts +2 -0
  29. package/gql/mutations/aiChatLinkMutations.ts +13 -0
  30. package/gql/mutations/aiChatMutations.ts +4 -6
  31. package/gql/mutations/audienceMutations.ts +0 -13
  32. package/gql/mutations/authMutations.ts +12 -60
  33. package/gql/mutations/emailMutations.ts +22 -0
  34. package/gql/mutations/emailOutreachMutations.ts +139 -0
  35. package/gql/mutations/index.ts +3 -1
  36. package/gql/mutations/organizationMutations.ts +2 -2
  37. package/gql/mutations/scheduleMutations.ts +61 -787
  38. package/gql/mutations/storageMutations.ts +1 -0
  39. package/gql/mutations/workflowMutations.ts +76 -0
  40. package/gql/queries/agentMemoryQueries.ts +6 -2
  41. package/gql/queries/agentNoteQueries.ts +26 -29
  42. package/gql/queries/aiChatQueries.ts +39 -40
  43. package/gql/queries/audienceQueries.ts +31 -55
  44. package/gql/queries/authQueries.ts +16 -6
  45. package/gql/queries/billingQueries.ts +26 -10
  46. package/gql/queries/dataTableQueries.ts +24 -15
  47. package/gql/queries/emailOutreachQueries.ts +282 -0
  48. package/gql/queries/emailQueries.ts +39 -12
  49. package/gql/queries/emailReplyReportQueries.ts +60 -9
  50. package/gql/queries/fieldDocQueries.ts +36 -14
  51. package/gql/queries/inboundContactQueries.ts +11 -4
  52. package/gql/queries/index.ts +2 -2
  53. package/gql/queries/libraryQueries.ts +112 -0
  54. package/gql/queries/logQueries.ts +31 -12
  55. package/gql/queries/organizationQueries.ts +31 -12
  56. package/gql/queries/qrCodeQueries.ts +11 -4
  57. package/gql/queries/scheduleQueries.ts +252 -505
  58. package/gql/queries/sheetQueries.ts +36 -14
  59. package/gql/queries/storageQueries.ts +11 -4
  60. package/gql/queries/workflowQueries.ts +53 -10
  61. package/gql/reactivity.ts +98 -0
  62. package/gql/recordReads.ts +171 -0
  63. package/hooks/index.ts +79 -52
  64. package/hooks/use-agentNote-mtn.ts +7 -0
  65. package/hooks/use-agentNote-qry.ts +30 -58
  66. package/hooks/use-agentNote-recovery.ts +6 -21
  67. package/hooks/use-aiChat-mtn.ts +9 -4
  68. package/hooks/use-aiChat-qry.ts +28 -7
  69. package/hooks/use-audience-mtn.ts +0 -24
  70. package/hooks/use-audience-qry.helpers.ts +0 -24
  71. package/hooks/use-audience-qry.ts +1 -86
  72. package/hooks/use-dataTable-mtn.ts +3 -3
  73. package/hooks/use-dataTable-qry.ts +7 -2
  74. package/hooks/use-email-mtn.ts +26 -0
  75. package/hooks/use-email-qry.helpers.ts +1 -1
  76. package/hooks/use-email-qry.ts +18 -3
  77. package/hooks/use-emailOutreach-mtn.ts +211 -0
  78. package/hooks/use-emailOutreach-qry.helpers.ts +25 -0
  79. package/hooks/use-emailOutreach-qry.ts +367 -0
  80. package/hooks/use-emailOutreachReplyReport-qry.ts +46 -0
  81. package/hooks/use-fieldDoc-qry.ts +1 -1
  82. package/hooks/use-library-qry.ts +233 -0
  83. package/hooks/use-qrCode-qry.ts +1 -1
  84. package/hooks/use-schedule-mtn.ts +10 -300
  85. package/hooks/use-schedule-qry.ts +168 -680
  86. package/hooks/use-schedule-reactive.ts +71 -339
  87. package/hooks/use-sheet-qry.ts +6 -1
  88. package/hooks/use-workflow-mtn.ts +45 -1
  89. package/hooks/use-workflow-qry.ts +22 -2
  90. package/libs/ai-chat-link-events.ts +78 -0
  91. package/libs/data-changes.helpers.ts +161 -0
  92. package/libs/data-changes.ts +382 -0
  93. package/libs/fragment-realtime-sequence.ts +3 -3
  94. package/libs/record-read.ts +327 -0
  95. package/libs/sheet-command-batch.ts +3 -2
  96. package/libs/sheet-realtime-packet.ts +53 -0
  97. package/loaders/emailPreference.ts +18 -24
  98. package/package.json +44 -17
  99. package/schedule.d.ts +267 -874
  100. package/types.d.ts +3 -1
  101. package/cache/index.chat-activity.test.ts +0 -119
  102. package/cache/index.chat.test.ts +0 -92
  103. package/cache/index.regression.test.ts +0 -149
  104. package/cache/index.test.ts +0 -1209
  105. package/deno.lock +0 -187
  106. package/deno.test.json +0 -12
  107. package/gql/fragments/campaignFragments.ts +0 -566
  108. package/gql/mutations/campaignMutations.ts +0 -258
  109. package/gql/queries/appQueries.ts +0 -14
  110. package/gql/queries/campaignQueries.ts +0 -236
  111. package/hooks/index.helpers.test.ts +0 -50
  112. package/hooks/use-agentNote-recovery.helpers.test.ts +0 -68
  113. package/hooks/use-aiChat-qry.helpers.test.ts +0 -63
  114. package/hooks/use-app-qry.ts +0 -22
  115. package/hooks/use-audience-qry.helpers.test.ts +0 -80
  116. package/hooks/use-campaign-generation-recovery.ts +0 -53
  117. package/hooks/use-campaign-mtn.ts +0 -436
  118. package/hooks/use-campaign-qry.helpers.ts +0 -40
  119. package/hooks/use-campaign-qry.ts +0 -834
  120. package/hooks/use-emailCampaignReplyReport-qry.ts +0 -27
  121. package/hooks/use-fieldDoc-qry.helpers.test.ts +0 -65
  122. package/hooks/use-publicFormEmail-mtn.ts +0 -27
  123. package/libs/fragment-recovery.test.ts +0 -326
  124. package/libs/fragment-recovery.ts +0 -325
  125. package/libs/orchestrator-realtime.helpers.test.ts +0 -229
  126. package/libs/orchestrator-realtime.helpers.ts +0 -317
  127. package/libs/orchestrator-realtime.ts +0 -433
  128. package/libs/request-cache-regression.test.ts +0 -122
  129. package/libs/request-managed-session.test.ts +0 -574
  130. package/libs/request-no-store.test.ts +0 -419
  131. package/libs/sheet-view-realtime-router.test.ts +0 -214
  132. package/libs/sse-ticket.test.ts +0 -26
  133. package/loaders/campaign.test.ts +0 -186
  134. package/loaders/campaign.ts +0 -110
  135. package/tests/agent-note-detail-cache.test.ts +0 -120
  136. package/tests/agent-note-search.test.ts +0 -444
  137. package/tsconfig.json +0 -13
@@ -1,325 +0,0 @@
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
- }
@@ -1,229 +0,0 @@
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
- });