@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,326 @@
1
+ import assert from 'node:assert/strict';
2
+ import { registerENV } from '@jsb188/app';
3
+ import type { WSDataUpdateObj } from '@jsb188/app/types/app.d.ts';
4
+ import { setAuthToken } from '@jsb188/app/utils/api.ts';
5
+ import { FRAGMENT_NAMES } from '@jsb188/mday/constants/graphqlReactivity.ts';
6
+ import { addFragmentToCache, clearGraphQLClientCache, loadFragment, loadQuery } from '../cache/index.ts';
7
+ import { clearFragmentRealtimeSequences, shouldApplyFragmentRealtimeSequence } from './fragment-realtime-sequence.ts';
8
+ import {
9
+ resolveFragmentRecoveryUpdate as applyFragmentRecoveryUpdate,
10
+ clearFragmentRecoveryRequests,
11
+ noteFragmentRealtimeUpdate,
12
+ } from './fragment-recovery.ts';
13
+
14
+ /* Capture the synchronously guarded apply callback for assertions without mutating cache. */
15
+ async function resolveFragmentRecoveryUpdate(update: WSDataUpdateObj) {
16
+ let result: { update: WSDataUpdateObj } | null = null;
17
+ await applyFragmentRecoveryUpdate(update, (resolved) => {
18
+ result = { update: resolved };
19
+ });
20
+ return result as { update: WSDataUpdateObj } | null;
21
+ }
22
+
23
+ /* Build a real supported marker without depending on server mapper implementations. */
24
+ function marker(name = FRAGMENT_NAMES.agentNote as string, dataId = 'n1', sequence = '10'): WSDataUpdateObj {
25
+ return {
26
+ id: `${dataId}:${sequence}`,
27
+ fragments: [
28
+ {
29
+ name,
30
+ dataId,
31
+ data: { id: dataId },
32
+ sequence,
33
+ recovery: { kind: name === FRAGMENT_NAMES.agentNote ? 'AGENT_NOTE' : 'LOG_ENTRY', organizationId: 'org1' },
34
+ },
35
+ ],
36
+ };
37
+ }
38
+
39
+ /* Isolate global transport/cache state while exercising the real no-store GraphQL request path. */
40
+ async function withRecoveryTest(run: () => Promise<void>) {
41
+ const originalFetch = globalThis.fetch;
42
+ registerENV({ GQL_SERVER: 'https://graphql.test/recovery', IS_BROWSER: '' });
43
+ clearFragmentRecoveryRequests();
44
+ clearGraphQLClientCache();
45
+ clearFragmentRealtimeSequences();
46
+ try {
47
+ await run();
48
+ } finally {
49
+ globalThis.fetch = originalFetch;
50
+ clearFragmentRecoveryRequests();
51
+ clearGraphQLClientCache();
52
+ clearFragmentRealtimeSequences();
53
+ }
54
+ }
55
+
56
+ /* Provide a manually settled fetch for deterministic interleaving of websocket and HTTP activity. */
57
+ function deferredResponse() {
58
+ let resolve!: (value: Response) => void;
59
+ const promise = new Promise<Response>((settle) => {
60
+ resolve = settle;
61
+ });
62
+ return { promise, resolve: (data: any) => resolve(Response.json({ data })) };
63
+ }
64
+
65
+ /* Let the request pipeline dispatch without introducing wall-clock sleeps. */
66
+ async function flushRequests() {
67
+ for (let index = 0; index < 10; index += 1) await Promise.resolve();
68
+ }
69
+
70
+ Deno.test('oversized note recovery uses its detail contract without normalizing unrelated data', () =>
71
+ withRecoveryTest(async () => {
72
+ let variables: any;
73
+ globalThis.fetch = (_input, init) => {
74
+ variables = JSON.parse(String(init?.body)).variables;
75
+ return Promise.resolve(
76
+ Response.json({
77
+ data: {
78
+ agentNote: {
79
+ id: 'n1',
80
+ organizationId: 'org1',
81
+ headline: 'Recovered',
82
+ body: 'Body',
83
+ links: [{ entityType: 'LOG', entityId: 'l1', unselected: 'private' }],
84
+ unselected: 'private',
85
+ },
86
+ },
87
+ }),
88
+ );
89
+ };
90
+ const result = await resolveFragmentRecoveryUpdate(marker());
91
+ assert.deepEqual(variables, { organizationId: 'org1', agentNoteId: 'n1' });
92
+ assert.equal(result?.update.fragments?.[0]?.recovery, undefined);
93
+ assert.equal(result?.update.fragments?.[0]?.data.body, 'Body');
94
+ assert.equal(result?.update.fragments?.[0]?.data.unselected, undefined);
95
+ assert.equal(result?.update.fragments?.[0]?.data.links[0].unselected, undefined);
96
+ assert.equal(loadFragment(`${FRAGMENT_NAMES.agentNote}:n1`), null);
97
+ assert.equal(loadQuery('#agentNote:'), null);
98
+ }));
99
+
100
+ Deno.test('log core and details share one read and retain only their selected projections', () =>
101
+ withRecoveryTest(async () => {
102
+ let reads = 0;
103
+ globalThis.fetch = () => {
104
+ reads += 1;
105
+ return Promise.resolve(
106
+ Response.json({
107
+ data: {
108
+ logEntry: {
109
+ id: 'l1',
110
+ summary: 'Recovered',
111
+ details: { id: 'l1', notes: 'Details', secret: 'omit' },
112
+ account: { id: 'a1' },
113
+ files: [],
114
+ },
115
+ },
116
+ }),
117
+ );
118
+ };
119
+ const update = marker(FRAGMENT_NAMES.logEntry, 'l1');
120
+ update.fragments!.push(marker(FRAGMENT_NAMES.logEntryDetails, 'l1').fragments![0]);
121
+ const result = await resolveFragmentRecoveryUpdate(update);
122
+ assert.equal(reads, 1);
123
+ assert.deepEqual(result?.update.fragments?.[0]?.data, { id: 'l1', summary: 'Recovered' });
124
+ assert.deepEqual(result?.update.fragments?.[1]?.data, { id: 'l1', notes: 'Details' });
125
+ }));
126
+
127
+ Deno.test('stale markers make no HTTP read and retain reset controls', () =>
128
+ withRecoveryTest(async () => {
129
+ let reads = 0;
130
+ globalThis.fetch = () => {
131
+ reads += 1;
132
+ throw new Error('Unexpected read');
133
+ };
134
+ shouldApplyFragmentRealtimeSequence(`${FRAGMENT_NAMES.agentNote}:n1`, '20');
135
+ const update = {
136
+ ...marker(),
137
+ resetQueryRule: 'ALWAYS' as const,
138
+ resetQueries: [{ name: 'agentNotes', match: { organizationId: 'org1' } }],
139
+ };
140
+ const result = await resolveFragmentRecoveryUpdate(update);
141
+ assert.equal(reads, 0);
142
+ assert.deepEqual(result?.update, update);
143
+ }));
144
+
145
+ Deno.test('ordinary partial writes during a read retry the authoritative target', () =>
146
+ withRecoveryTest(async () => {
147
+ const first = deferredResponse();
148
+ let reads = 0;
149
+ globalThis.fetch = () =>
150
+ ++reads === 1
151
+ ? first.promise
152
+ : Promise.resolve(Response.json({ data: { agentNote: { id: 'n1', headline: 'Latest', body: 'Fresh body' } } }));
153
+ const pending = resolveFragmentRecoveryUpdate(marker());
154
+ await flushRequests();
155
+ addFragmentToCache(`${FRAGMENT_NAMES.agentNote}:n1`, { id: 'n1', headline: 'Latest' });
156
+ noteFragmentRealtimeUpdate({ name: FRAGMENT_NAMES.agentNote, dataId: 'n1', data: { headline: 'Latest' } });
157
+ first.resolve({ agentNote: { id: 'n1', headline: 'Old', body: 'Old body' } });
158
+ const result = await pending;
159
+ assert.equal(reads, 2);
160
+ assert.equal(result?.update.fragments?.[0]?.data.body, 'Fresh body');
161
+ }));
162
+
163
+ Deno.test('a deleted log parent prevents its pending details recovery from resurrecting content', () =>
164
+ withRecoveryTest(async () => {
165
+ const response = deferredResponse();
166
+ let reads = 0;
167
+ globalThis.fetch = () => {
168
+ reads += 1;
169
+ return response.promise;
170
+ };
171
+ const pending = resolveFragmentRecoveryUpdate(marker(FRAGMENT_NAMES.logEntryDetails, 'l1'));
172
+ await flushRequests();
173
+ addFragmentToCache(`${FRAGMENT_NAMES.logEntry}:l1`, { id: 'l1', __deleted: true });
174
+ noteFragmentRealtimeUpdate({ name: FRAGMENT_NAMES.logEntry, dataId: 'l1', data: { __deleted: true } });
175
+ response.resolve({ logEntry: { id: 'l1', details: { id: 'l1', notes: 'Deleted content' } } });
176
+ const result = await pending;
177
+ assert.equal(reads, 1);
178
+ assert.ok(result?.update.fragments?.[0]?.recovery);
179
+ }));
180
+
181
+ Deno.test('cache clearing without a sequence reset rejects an old private HTTP response', () =>
182
+ withRecoveryTest(async () => {
183
+ const response = deferredResponse();
184
+ globalThis.fetch = () => response.promise;
185
+ const pending = resolveFragmentRecoveryUpdate(marker());
186
+ await flushRequests();
187
+ clearGraphQLClientCache();
188
+ response.resolve({ agentNote: { id: 'n1', body: 'Old scope' } });
189
+ assert.equal(await pending, null);
190
+ }));
191
+
192
+ Deno.test('a delayed older marker cannot take ownership from a higher in-flight revision', () =>
193
+ withRecoveryTest(async () => {
194
+ const response = deferredResponse();
195
+ let reads = 0;
196
+ globalThis.fetch = () => {
197
+ reads += 1;
198
+ return response.promise;
199
+ };
200
+ const newer = resolveFragmentRecoveryUpdate(marker(FRAGMENT_NAMES.agentNote, 'n1', '20'));
201
+ await flushRequests();
202
+ const older = resolveFragmentRecoveryUpdate(marker(FRAGMENT_NAMES.agentNote, 'n1', '10'));
203
+ response.resolve({ agentNote: { id: 'n1', body: 'Latest' } });
204
+ const [latest, obsolete] = await Promise.all([newer, older]);
205
+ assert.equal(reads, 1);
206
+ assert.equal(latest?.update.fragments?.[0]?.recovery, undefined);
207
+ assert.equal(latest?.update.fragments?.[0]?.sequence, '20');
208
+ assert.ok(obsolete?.update.fragments?.[0]?.recovery);
209
+ }));
210
+
211
+ Deno.test('a reused outbox id with a newer revision forces a fresh read', () =>
212
+ withRecoveryTest(async () => {
213
+ const response = deferredResponse();
214
+ let reads = 0;
215
+ globalThis.fetch = () =>
216
+ ++reads === 1 ? response.promise : Promise.resolve(Response.json({ data: { agentNote: { id: 'n1', body: 'Revision 20' } } }));
217
+ const first = { ...marker(FRAGMENT_NAMES.agentNote, 'n1', '10'), id: 'outbox1' };
218
+ const pendingFirst = resolveFragmentRecoveryUpdate(first);
219
+ await flushRequests();
220
+ const second = { ...marker(FRAGMENT_NAMES.agentNote, 'n1', '20'), id: 'outbox1' };
221
+ const pendingSecond = resolveFragmentRecoveryUpdate(second);
222
+ response.resolve({ agentNote: { id: 'n1', body: 'Revision 10' } });
223
+ const [old, latest] = await Promise.all([pendingFirst, pendingSecond]);
224
+ assert.equal(reads, 2);
225
+ assert.ok(old?.update.fragments?.[0]?.recovery);
226
+ assert.equal(latest?.update.fragments?.[0]?.data.body, 'Revision 20');
227
+ }));
228
+
229
+ Deno.test('fast recovered data is revalidated after a slower sibling completes', () =>
230
+ withRecoveryTest(async () => {
231
+ const slow = deferredResponse();
232
+ let firstReads = 0;
233
+ globalThis.fetch = (_input, init) => {
234
+ const id = JSON.parse(String(init?.body)).variables.logEntryId;
235
+ if (id === 'l2') return slow.promise;
236
+ firstReads += 1;
237
+ return Promise.resolve(Response.json({ data: { logEntry: { id: 'l1', summary: firstReads === 1 ? 'Old' : 'Latest' } } }));
238
+ };
239
+ const update = marker(FRAGMENT_NAMES.logEntry, 'l1');
240
+ update.fragments!.push(marker(FRAGMENT_NAMES.logEntry, 'l2').fragments![0]);
241
+ const pending = resolveFragmentRecoveryUpdate(update);
242
+ await flushRequests();
243
+ addFragmentToCache(`${FRAGMENT_NAMES.logEntry}:l1`, { id: 'l1', summary: 'Latest' });
244
+ noteFragmentRealtimeUpdate({ name: FRAGMENT_NAMES.logEntry, dataId: 'l1', data: { summary: 'Latest' } });
245
+ slow.resolve({ logEntry: { id: 'l2', summary: 'Second' } });
246
+ const result = await pending;
247
+ assert.equal(firstReads, 2);
248
+ assert.equal(result?.update.fragments?.[0]?.data.summary, 'Latest');
249
+ }));
250
+
251
+ Deno.test('denied or missing reads retain the marker and cached value without inventing deletion', () =>
252
+ withRecoveryTest(async () => {
253
+ addFragmentToCache(`${FRAGMENT_NAMES.agentNote}:n1`, { id: 'n1', body: 'Retained' });
254
+ let reads = 0;
255
+ globalThis.fetch = () => {
256
+ reads += 1;
257
+ return Promise.resolve(
258
+ Response.json({
259
+ data: { agentNote: null },
260
+ errors: [{ errorCode: 20232, statusCode: 404, message: '20232', path: ['agentNote'] }],
261
+ }),
262
+ );
263
+ };
264
+ const result = await resolveFragmentRecoveryUpdate(marker());
265
+ assert.equal(reads, 1);
266
+ assert.ok(result?.update.fragments?.[0]?.recovery);
267
+ assert.equal(loadFragment(`${FRAGMENT_NAMES.agentNote}:n1`)?.body, 'Retained');
268
+ }));
269
+
270
+ Deno.test('a no-op websocket write after a fast read still invalidates it while a sibling is pending', () =>
271
+ withRecoveryTest(async () => {
272
+ const slow = deferredResponse();
273
+ addFragmentToCache(`${FRAGMENT_NAMES.logEntry}:l1`, { id: 'l1', summary: 'Same' });
274
+ let reads = 0;
275
+ globalThis.fetch = (_input, init) => {
276
+ if (JSON.parse(String(init?.body)).variables.logEntryId === 'l2') return slow.promise;
277
+ reads += 1;
278
+ return Promise.resolve(Response.json({ data: { logEntry: { id: 'l1', summary: reads === 1 ? 'Old snapshot' : 'Same' } } }));
279
+ };
280
+ const update = marker(FRAGMENT_NAMES.logEntry, 'l1');
281
+ update.fragments!.push(marker(FRAGMENT_NAMES.logEntry, 'l2').fragments![0]);
282
+ const pending = resolveFragmentRecoveryUpdate(update);
283
+ for (let index = 0; index < 5; index += 1) await flushRequests();
284
+ noteFragmentRealtimeUpdate({ name: FRAGMENT_NAMES.logEntry, dataId: 'l1', data: { summary: 'Same' } });
285
+ slow.resolve({ logEntry: { id: 'l2', summary: 'Second' } });
286
+ const result = await pending;
287
+ assert.equal(reads, 2);
288
+ assert.equal(result?.update.fragments?.[0]?.data.summary, 'Same');
289
+ }));
290
+
291
+ Deno.test('switching authenticated sessions rejects a pending recovery before application', () =>
292
+ withRecoveryTest(async () => {
293
+ registerENV({ IS_BROWSER: 'true' });
294
+ setAuthToken('first-session');
295
+ try {
296
+ const response = deferredResponse();
297
+ globalThis.fetch = () => response.promise;
298
+ const pending = resolveFragmentRecoveryUpdate(marker());
299
+ await flushRequests();
300
+ setAuthToken('second-session');
301
+ response.resolve({ agentNote: { id: 'n1', body: 'Prior session' } });
302
+ assert.equal(await pending, null);
303
+ } finally {
304
+ setAuthToken(null);
305
+ registerENV({ IS_BROWSER: '' });
306
+ }
307
+ }));
308
+
309
+ Deno.test('explicit recovery cancellation cannot restart old work after a slower sibling returns', () =>
310
+ withRecoveryTest(async () => {
311
+ const slow = deferredResponse();
312
+ let reads = 0;
313
+ globalThis.fetch = (_input, init) => {
314
+ reads += 1;
315
+ if (JSON.parse(String(init?.body)).variables.logEntryId === 'l2') return slow.promise;
316
+ return Promise.resolve(Response.json({ data: { logEntry: { id: 'l1', summary: 'Old scope' } } }));
317
+ };
318
+ const update = marker(FRAGMENT_NAMES.logEntry, 'l1');
319
+ update.fragments!.push(marker(FRAGMENT_NAMES.logEntry, 'l2').fragments![0]);
320
+ const pending = resolveFragmentRecoveryUpdate(update);
321
+ for (let index = 0; index < 5; index += 1) await flushRequests();
322
+ clearFragmentRecoveryRequests();
323
+ slow.resolve({ logEntry: { id: 'l2', summary: 'Old scope' } });
324
+ assert.equal(await pending, null);
325
+ assert.equal(reads, 2);
326
+ }));
@@ -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
+ }