@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,444 @@
1
+ // @vitest-environment jsdom
2
+ import type { AgentNoteKindEnum } from '@jsb188/mday/types/agentNote.d.ts';
3
+ import { act, createElement } from 'react';
4
+ import { createRoot, type Root } from 'react-dom/client';
5
+ import { afterEach, beforeEach, expect, it, vi } from 'vitest';
6
+ import { makeGraphQLVariablesKey } from '@jsb188/app/utils/logic.ts';
7
+ import {
8
+ clearGraphQLClientCache,
9
+ loadFragment,
10
+ loadQuery,
11
+ resetQueryByTarget,
12
+ setDataToCache,
13
+ updateFragment,
14
+ } from '../cache/index.ts';
15
+ import { updateDataObservers } from '../hooks/index.ts';
16
+ import { useAgentNotes, useSearchAgentNotes } from '../hooks/use-agentNote-qry.ts';
17
+
18
+ const STATE = vi.hoisted(() => ({
19
+ requests: [] as {
20
+ variables: any;
21
+ complete: (headline: string | Record<string, any>[], revision?: string) => void;
22
+ accept: () => boolean;
23
+ }[],
24
+ value: null as any,
25
+ accountId: 'account-1',
26
+ authToken: 'token-1',
27
+ generation: 0,
28
+ revision: '1',
29
+ revisionReads: 0,
30
+ }));
31
+
32
+ vi.mock('@jsb188/app/utils/api.ts', async (original) => ({
33
+ ...(await original<Record<string, unknown>>()),
34
+ getAuthToken: () => STATE.authToken,
35
+ }));
36
+
37
+ vi.mock('@jsb188/react/states', () => ({
38
+ useConnectedToServerValue: () => true,
39
+ useOptimisticConnectedToServerValue: () => true,
40
+ useScreenIsFocusedValue: () => true,
41
+ useCurrentAccount: () => ({ account: { id: STATE.accountId } }),
42
+ useRealtimeConnectionGenerationValue: () => STATE.generation,
43
+ }));
44
+
45
+ vi.mock('../client/request.ts', () => ({
46
+ /* Model the transport's pre-normalization acceptance guard with controllable responses. */
47
+ graphqlRequest: (query: any, variables: any, options: any, _signal: any, observers: any) =>
48
+ new Promise((resolve) => {
49
+ const accept = () => options.shouldAcceptResult?.({}, variables) !== false;
50
+ STATE.requests.push({
51
+ variables,
52
+ accept,
53
+ complete: (headline, revision = STATE.revision) => {
54
+ if (!accept()) {
55
+ resolve({ __clientResultRejected: true });
56
+ return;
57
+ }
58
+ const note = {
59
+ id: 'note-1',
60
+ cursor: [],
61
+ organizationId: variables.organizationId,
62
+ kind: 'INSIGHT',
63
+ canManage: true,
64
+ campaignId: null,
65
+ fieldDocId: null,
66
+ reminderWorkflowId: null,
67
+ emoji: null,
68
+ headline,
69
+ focus: null,
70
+ needsAttention: false,
71
+ pinned: false,
72
+ archivedAt: null,
73
+ archiveReason: null,
74
+ dataChangedAt: '2026-10-15',
75
+ refreshedAt: null,
76
+ refreshOutcome: null,
77
+ createdAt: '2026-10-15',
78
+ updatedAt: '2026-10-15',
79
+ };
80
+ const queryName = query.definitions[0].name.value;
81
+ const items = Array.isArray(headline) ? headline.map((value) => ({ ...note, ...value })) : [note];
82
+ const data = { [queryName]: queryName === 'agentNotes' ? items : { items, revision } };
83
+ setDataToCache(data, query, variables, undefined, observers);
84
+ options.onCompleted?.({ data }, null);
85
+ resolve(data);
86
+ },
87
+ });
88
+ }),
89
+ /* Detect accidental reintroduction of revision polling. */
90
+ graphqlRequestNoStore: () => {
91
+ STATE.revisionReads += 1;
92
+ return Promise.resolve({ agentNotesRevision: STATE.revision });
93
+ },
94
+ }));
95
+
96
+ let root: Root;
97
+
98
+ /* Render the real search hook and normalized fragment observers. */
99
+ const Reader = (p: {
100
+ organizationId?: string;
101
+ query?: string;
102
+ skip?: boolean;
103
+ includeArchived?: boolean;
104
+ kinds?: AgentNoteKindEnum[];
105
+ }) => {
106
+ STATE.value = useSearchAgentNotes(
107
+ { organizationId: p.organizationId || 'org-1', query: p.query || 'tomatoes', includeArchived: p.includeArchived, kinds: p.kinds },
108
+ { skip: p.skip },
109
+ );
110
+ return createElement('span', null, STATE.value.agentNotes?.[0]?.headline);
111
+ };
112
+
113
+ /* Render the homepage collection through the same shared query lifecycle. */
114
+ const BrowseReader = () => {
115
+ STATE.value = useAgentNotes({ organizationId: 'org-1' });
116
+ return createElement('span', null, STATE.value.agentNotes?.[0]?.headline);
117
+ };
118
+
119
+ beforeEach(() => {
120
+ (console as any).dev ||= () => undefined;
121
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
122
+ clearGraphQLClientCache();
123
+ STATE.requests = [];
124
+ STATE.value = null;
125
+ STATE.accountId = 'account-1';
126
+ STATE.authToken = 'token-1';
127
+ STATE.generation = 0;
128
+ STATE.revision = '1';
129
+ STATE.revisionReads = 0;
130
+ document.body.innerHTML = '<div id="root"></div>';
131
+ root = createRoot(document.getElementById('root')!);
132
+ });
133
+
134
+ afterEach(async () => {
135
+ act(() => root.unmount());
136
+ await act(async () => {
137
+ for (const request of STATE.requests) request.complete('Unmounted result');
138
+ });
139
+ clearGraphQLClientCache();
140
+ vi.useRealTimers();
141
+ vi.unstubAllGlobals();
142
+ });
143
+
144
+ it('uses one initial search request and refreshes noncached results on scoped note invalidation', async () => {
145
+ await act(async () => root.render(createElement(Reader)));
146
+ expect(STATE.requests).toHaveLength(1);
147
+ expect(STATE.revisionReads).toBe(0);
148
+ await act(async () => STATE.requests[0].complete('Initial match'));
149
+ expect(STATE.value.acceptedQuery).toBe('tomatoes');
150
+ expect(loadQuery(`#searchAgentNotes:${makeGraphQLVariablesKey(STATE.requests[0].variables)}`)).toBeFalsy();
151
+ act(() => resetQueryByTarget({ name: 'searchAgentNotes', match: { organizationid: 'org-2' } }, true, updateDataObservers));
152
+ expect(STATE.requests).toHaveLength(1);
153
+ act(() => resetQueryByTarget({ name: 'searchAgentNotes', match: { organizationid: 'org-1' } }, true, updateDataObservers));
154
+ expect(STATE.requests).toHaveLength(2);
155
+ expect(document.body.textContent).toContain('Initial match');
156
+ await act(async () => STATE.requests[1].complete('Updated match', '2'));
157
+ expect(document.body.textContent).toContain('Updated match');
158
+ expect(STATE.requests).toHaveLength(2);
159
+ });
160
+
161
+ it('keeps existing matches reactive without revision-driven list refetches', async () => {
162
+ vi.useFakeTimers();
163
+ await act(async () => root.render(createElement(Reader)));
164
+ await act(async () => STATE.requests[0].complete('Initial match'));
165
+ act(() => updateFragment('$agentNoteFragment:note-1', { headline: 'Live match' }, null, false, updateDataObservers));
166
+ expect(document.body.textContent).toContain('Live match');
167
+ STATE.revision = '2';
168
+ await act(async () => vi.advanceTimersByTimeAsync(120_000));
169
+ act(() => updateFragment('$agentNoteFragment:note-1', { headline: 'Later match' }, null, false, updateDataObservers));
170
+ expect(document.body.textContent).toContain('Later match');
171
+ await act(async () => window.dispatchEvent(new Event('online')));
172
+ expect(STATE.revisionReads).toBe(0);
173
+ expect(STATE.requests).toHaveLength(1);
174
+ });
175
+
176
+ it('keeps the homepage list reactive after cache expiry and refetches on a creation reset', async () => {
177
+ vi.useFakeTimers();
178
+ await act(async () => root.render(createElement(BrowseReader)));
179
+ expect(STATE.requests[0].variables).toEqual({ organizationId: 'org-1' });
180
+ await act(async () => STATE.requests[0].complete('Initial note'));
181
+ await act(async () => vi.advanceTimersByTimeAsync(120_000));
182
+ act(() => updateFragment('$agentNoteFragment:note-1', { headline: 'Live note' }, null, false, updateDataObservers));
183
+ expect(document.body.textContent).toContain('Live note');
184
+ expect(STATE.requests).toHaveLength(1);
185
+ act(() => updateFragment('$agentNoteFragment:note-1', { archivedAt: '2026-10-15' }, null, false, updateDataObservers));
186
+ expect(STATE.value.agentNotes).toEqual([]);
187
+ expect(STATE.requests).toHaveLength(1);
188
+ act(() => resetQueryByTarget({ name: 'agentNotes', match: { organizationid: 'org-1' } }, true, updateDataObservers));
189
+ expect(STATE.requests).toHaveLength(2);
190
+ await act(async () => STATE.requests[1].complete('New note'));
191
+ expect(document.body.textContent).toContain('New note');
192
+ });
193
+
194
+ it('recovers once after a replacement socket without duplicating the initial request', async () => {
195
+ await act(async () => root.render(createElement(Reader)));
196
+ expect(STATE.requests).toHaveLength(1);
197
+ await act(async () => STATE.requests[0].complete('Before reconnect'));
198
+ STATE.generation += 1;
199
+ await act(async () => root.render(createElement(Reader)));
200
+ expect(STATE.requests).toHaveLength(2);
201
+ await act(async () => STATE.requests[1].complete('After reconnect'));
202
+ expect(document.body.textContent).toContain('After reconnect');
203
+ expect(STATE.revisionReads).toBe(0);
204
+ });
205
+
206
+ it('retains reconnect recovery until the active request settles and coalesces busy reconnects', async () => {
207
+ await act(async () => root.render(createElement(Reader)));
208
+ STATE.generation += 1;
209
+ await act(async () => root.render(createElement(Reader)));
210
+ STATE.generation += 1;
211
+ await act(async () => root.render(createElement(Reader)));
212
+ expect(STATE.requests).toHaveLength(1);
213
+
214
+ await act(async () => STATE.requests[0].complete('Before reconnect'));
215
+ expect(STATE.requests).toHaveLength(2);
216
+ await act(async () => root.render(createElement(Reader)));
217
+ expect(STATE.requests).toHaveLength(2);
218
+
219
+ STATE.generation += 1;
220
+ await act(async () => root.render(createElement(Reader)));
221
+ expect(STATE.requests).toHaveLength(2);
222
+ await act(async () => STATE.requests[1].complete('Before the next reconnect'));
223
+ expect(STATE.requests).toHaveLength(3);
224
+ await act(async () => STATE.requests[2].complete('After every reconnect'));
225
+ await act(async () => root.render(createElement(Reader)));
226
+ expect(document.body.textContent).toContain('After every reconnect');
227
+ expect(STATE.requests).toHaveLength(3);
228
+ expect(STATE.revisionReads).toBe(0);
229
+ });
230
+
231
+ it.each(['query', 'organization', 'account', 'session', 'skip'])(
232
+ 'discards pending reconnect recovery when the %s activation changes',
233
+ async (change) => {
234
+ await act(async () => root.render(createElement(Reader)));
235
+ const retired = STATE.requests[0];
236
+ STATE.generation += 1;
237
+ await act(async () => root.render(createElement(Reader)));
238
+ expect(STATE.requests).toHaveLength(1);
239
+
240
+ if (change === 'account') STATE.accountId = 'account-2';
241
+ if (change === 'session') STATE.authToken = 'token-2';
242
+ const props = {
243
+ query: change === 'query' ? 'potatoes' : 'tomatoes',
244
+ organizationId: change === 'organization' ? 'org-2' : 'org-1',
245
+ skip: change === 'skip',
246
+ };
247
+ await act(async () => root.render(createElement(Reader, props)));
248
+ expect(retired.accept()).toBe(false);
249
+ await act(async () => retired.complete('Obsolete result'));
250
+
251
+ if (change === 'skip') {
252
+ STATE.generation += 1;
253
+ await act(async () => root.render(createElement(Reader, props)));
254
+ expect(STATE.requests).toHaveLength(1);
255
+ props.skip = false;
256
+ await act(async () => root.render(createElement(Reader, props)));
257
+ }
258
+
259
+ const current = STATE.requests.find((request) => request !== retired && request.accept());
260
+ expect(current).toBeDefined();
261
+ const count = STATE.requests.length;
262
+ await act(async () => current!.complete('Current result'));
263
+ await act(async () => root.render(createElement(Reader, props)));
264
+ expect(document.body.textContent).toContain('Current result');
265
+ expect(STATE.requests).toHaveLength(count);
266
+ },
267
+ );
268
+
269
+ it('removes archived and deleted search fragments without refetching the search', async () => {
270
+ await act(async () => root.render(createElement(Reader, { includeArchived: false })));
271
+ await act(async () => STATE.requests[0].complete('Active match'));
272
+ act(() => updateFragment('$agentNoteFragment:note-1', { archivedAt: '2026-10-15' }, null, false, updateDataObservers));
273
+ expect(STATE.value.agentNotes).toEqual([]);
274
+ act(() => updateFragment('$agentNoteFragment:note-1', { archivedAt: null }, null, false, updateDataObservers));
275
+ expect(STATE.value.agentNotes).toHaveLength(1);
276
+ act(() => updateFragment('$agentNoteFragment:note-1', { __deleted: true }, null, false, updateDataObservers));
277
+ expect(STATE.value.agentNotes).toEqual([]);
278
+ expect(STATE.requests).toHaveLength(1);
279
+ });
280
+
281
+ it('rejects an old query activation even after returning to the same search text', async () => {
282
+ await act(async () => root.render(createElement(Reader, { query: 'tom' })));
283
+ const retired = STATE.requests[0];
284
+ await act(async () => root.render(createElement(Reader, { query: 'potato' })));
285
+ expect(retired.accept()).toBe(false);
286
+ await act(async () => root.render(createElement(Reader, { query: 'tom' })));
287
+ expect(retired.accept()).toBe(false);
288
+ await act(async () => retired.complete('Obsolete result'));
289
+ expect(loadFragment('$agentNoteFragment:note-1')).toBeFalsy();
290
+ const current = STATE.requests.find((request) => request !== retired && request.variables.query === 'tom' && request.accept());
291
+ expect(current).toBeDefined();
292
+ await act(async () => current!.complete('Current result'));
293
+ expect(document.body.textContent).toContain('Current result');
294
+ });
295
+
296
+ it.each(['organization', 'account', 'session', 'skip'])('rejects a pending search after changing its %s scope', async (change) => {
297
+ await act(async () => root.render(createElement(Reader)));
298
+ const retired = STATE.requests[0];
299
+ if (change === 'account') STATE.accountId = 'account-2';
300
+ if (change === 'session') STATE.authToken = 'token-2';
301
+ await act(async () =>
302
+ root.render(createElement(Reader, { organizationId: change === 'organization' ? 'org-2' : 'org-1', skip: change === 'skip' })),
303
+ );
304
+ expect(retired.accept()).toBe(false);
305
+ await act(async () => retired.complete('Obsolete result'));
306
+ expect(loadFragment('$agentNoteFragment:note-1')).toBeFalsy();
307
+ });
308
+
309
+ it('rejects an overtaken collection snapshot before normalization and coalesces later invalidations', async () => {
310
+ await act(async () => root.render(createElement(Reader)));
311
+ await act(async () => STATE.requests[0].complete('Initial match'));
312
+ act(() => resetQueryByTarget({ name: 'searchAgentNotes', match: { organizationid: 'org-1' } }, true, updateDataObservers));
313
+ expect(STATE.requests).toHaveLength(2);
314
+ act(() => {
315
+ updateFragment('$agentNoteFragment:note-1', { headline: 'Newest live content' }, null, false, updateDataObservers);
316
+ for (let i = 0; i < 8; i++)
317
+ resetQueryByTarget({ name: 'searchAgentNotes', match: { organizationid: 'org-1' } }, true, updateDataObservers);
318
+ });
319
+ expect(STATE.requests).toHaveLength(2);
320
+ expect(STATE.requests[1].accept()).toBe(false);
321
+ await act(async () => STATE.requests[1].complete('Stale content'));
322
+ expect(loadFragment('$agentNoteFragment:note-1').headline).toBe('Newest live content');
323
+ expect(STATE.requests).toHaveLength(3);
324
+ await act(async () => STATE.requests[2].complete('Current match'));
325
+ expect(document.body.textContent).toContain('Current match');
326
+ expect(STATE.requests).toHaveLength(3);
327
+ });
328
+
329
+ it('replaces search membership and rank even when every changed note is already cached', async () => {
330
+ await act(async () => root.render(createElement(Reader)));
331
+ await act(async () =>
332
+ STATE.requests[0].complete([
333
+ { id: 'a', headline: 'Tomatoes A' },
334
+ { id: 'b', headline: 'Tomatoes B' },
335
+ ]),
336
+ );
337
+ act(() => {
338
+ updateFragment('$agentNoteFragment:a', { headline: 'Potatoes' }, null, false, updateDataObservers);
339
+ updateFragment('$agentNoteFragment:b', { headline: 'Tomatoes best match' }, null, false, updateDataObservers);
340
+ resetQueryByTarget({ name: 'searchAgentNotes', match: { organizationid: 'org-1' } }, true, updateDataObservers);
341
+ });
342
+ await act(async () =>
343
+ STATE.requests[1].complete(
344
+ [
345
+ { id: 'b', headline: 'Tomatoes best match' },
346
+ { id: 'c', headline: 'Tomatoes C' },
347
+ ],
348
+ '2',
349
+ ),
350
+ );
351
+ expect(STATE.value.agentNotes.map((note: any) => note.id)).toEqual(['b', 'c']);
352
+ expect(STATE.revisionReads).toBe(0);
353
+ });
354
+
355
+ it('removes an archived homepage row and accepts a newly created note', async () => {
356
+ await act(async () => root.render(createElement(BrowseReader)));
357
+ await act(async () =>
358
+ STATE.requests[0].complete([
359
+ { id: 'a', headline: 'First' },
360
+ { id: 'b', headline: 'Second' },
361
+ ]),
362
+ );
363
+ act(() => {
364
+ updateFragment('$agentNoteFragment:a', { archivedAt: '2026-10-17' }, null, false, updateDataObservers);
365
+ resetQueryByTarget({ name: 'agentNotes', match: { organizationid: 'org-1' } }, true, updateDataObservers);
366
+ });
367
+ expect(STATE.value.agentNotes.map((note: any) => note.id)).toEqual(['b']);
368
+ await act(async () =>
369
+ STATE.requests[1].complete([
370
+ { id: 'c', headline: 'New pinned note', pinned: true },
371
+ { id: 'b', headline: 'Second' },
372
+ ]),
373
+ );
374
+ expect(STATE.value.agentNotes.map((note: any) => note.id)).toEqual(['c', 'b']);
375
+ });
376
+
377
+ it('loads every homepage kind in one organization-only request and invalidates it once', async () => {
378
+ await act(async () => root.render(createElement(BrowseReader)));
379
+ expect(STATE.requests.map((request) => request.variables)).toEqual([{ organizationId: 'org-1' }]);
380
+ await act(async () =>
381
+ STATE.requests[0].complete([
382
+ { id: 'task', kind: 'REMINDER', headline: 'Task' },
383
+ { id: 'email', kind: 'CAMPAIGN_EMAIL', headline: 'Email' },
384
+ { id: 'form', kind: 'CAMPAIGN_FORM', headline: 'Form' },
385
+ { id: 'insight', kind: 'INSIGHT', headline: 'Insight' },
386
+ ]),
387
+ );
388
+ expect(STATE.value.agentNotes.map((note: any) => note.id)).toEqual(['task', 'email', 'form', 'insight']);
389
+ act(() => updateFragment('$agentNoteFragment:task', { kind: 'INSIGHT' }, null, false, updateDataObservers));
390
+ expect(STATE.value.agentNotes[0].kind).toBe('INSIGHT');
391
+ await act(async () => root.render(createElement(BrowseReader)));
392
+ expect(STATE.requests).toHaveLength(1);
393
+ act(() => resetQueryByTarget({ name: 'agentNotes', match: { organizationid: 'org-1' } }, true, updateDataObservers));
394
+ expect(STATE.requests.map((request) => request.variables)).toEqual([{ organizationId: 'org-1' }, { organizationId: 'org-1' }]);
395
+ });
396
+
397
+ it('recovers a shared refresh when its owning reader becomes inactive', async () => {
398
+ /* Keep the second reader mounted while retiring the network request owner. */
399
+ const Readers = (p: { skipFirst?: boolean }) =>
400
+ createElement('div', null, createElement(Reader, { skip: p.skipFirst }), createElement(Reader));
401
+ await act(async () => root.render(createElement(Readers)));
402
+ expect(STATE.requests).toHaveLength(1);
403
+ await act(async () => STATE.requests[0].complete('Initial match'));
404
+ act(() => resetQueryByTarget({ name: 'searchAgentNotes', match: { organizationid: 'org-1' } }, true, updateDataObservers));
405
+ expect(STATE.requests).toHaveLength(2);
406
+ await act(async () => root.render(createElement(Readers, { skipFirst: true })));
407
+ expect(STATE.requests[1].accept()).toBe(false);
408
+ await act(async () => STATE.requests[1].complete('Retired owner result'));
409
+ expect(STATE.requests).toHaveLength(3);
410
+ await act(async () => STATE.requests[2].complete('Current match'));
411
+ expect(document.body.textContent).toContain('Current match');
412
+ });
413
+
414
+ it('coalesces overtaken shared refreshes into one replacement request', async () => {
415
+ await act(async () => root.render(createElement('div', null, createElement(Reader), createElement(Reader))));
416
+ await act(async () => STATE.requests[0].complete('Initial match'));
417
+ act(() => resetQueryByTarget({ name: 'searchAgentNotes', match: { organizationid: 'org-1' } }, true, updateDataObservers));
418
+ act(() => resetQueryByTarget({ name: 'searchAgentNotes', match: { organizationid: 'org-1' } }, true, updateDataObservers));
419
+ expect(STATE.requests).toHaveLength(2);
420
+ await act(async () => STATE.requests[1].complete('Overtaken match'));
421
+ expect(STATE.requests).toHaveLength(3);
422
+ await act(async () => STATE.requests[2].complete('Current shared match'));
423
+ expect(document.body.textContent).toBe('Current shared matchCurrent shared match');
424
+ expect(STATE.requests).toHaveLength(3);
425
+ });
426
+
427
+ it('keeps search kind scopes separate and preserves them on invalidation', async () => {
428
+ const Component = Reader;
429
+ await act(async () => root.render(createElement(Component)));
430
+ const previous = STATE.requests[0];
431
+ await act(async () => root.render(createElement(Component, { kinds: ['REMINDER'] })));
432
+ expect(previous.accept()).toBe(false);
433
+ await act(async () => previous.complete('Stale unfiltered result'));
434
+ expect(STATE.requests.at(-1)!.variables.kinds).toEqual(['REMINDER']);
435
+ await act(async () => STATE.requests.at(-1)!.complete([{ kind: 'REMINDER', headline: 'Scheduled task' }]));
436
+ expect(document.body.textContent).toContain('Scheduled task');
437
+ expect(document.body.textContent).not.toContain('Stale unfiltered result');
438
+ act(() => resetQueryByTarget({ name: 'searchAgentNotes', match: { organizationid: 'org-1' } }, true, updateDataObservers));
439
+ expect(STATE.requests.at(-1)!.variables.kinds).toEqual(['REMINDER']);
440
+ await act(async () => STATE.requests.at(-1)!.complete([{ kind: 'REMINDER', headline: 'Updated scheduled task' }]));
441
+ expect(document.body.textContent).toContain('Updated scheduled task');
442
+ act(() => updateFragment('$agentNoteFragment:note-1', { kind: 'INSIGHT' }, null, false, updateDataObservers));
443
+ expect(document.body.textContent).not.toContain('Updated scheduled task');
444
+ });
package/types.d.ts CHANGED
@@ -1,7 +1,4 @@
1
- import type {
2
- ServerErrorObj,
3
- SimpleErrorType,
4
- } from '@jsb188/app/types/app.d.ts';
1
+ import type { ServerErrorObj, SimpleErrorType } from '@jsb188/app/types/app.d.ts';
5
2
  import type { QueryResetTarget } from '@jsb188/app/utils/queryReset.ts';
6
3
 
7
4
  /**
@@ -37,15 +34,38 @@ export interface UpdateDataObserverArgs {
37
34
 
38
35
  export type AnyModalPopUpFn = (data: any, err?: ServerErrorObj) => void;
39
36
  export type UpdateObserversFn = (args: UpdateDataObserverArgs) => void;
40
- export type OnCompletedGQLFn = (
41
- data: any,
42
- error: ServerErrorObj | null,
43
- variables?: any,
44
- ) => void;
45
- export type OnErrorGQLFn = (
46
- error: ServerErrorObj | null,
47
- variables: any,
48
- ) => void;
37
+ export type OnCompletedGQLFn = (data: any, error: ServerErrorObj | null, variables?: any) => void;
38
+ export type OnErrorGQLFn = (error: ServerErrorObj | null, variables: any) => void;
39
+
40
+ /**
41
+ * Optimistically patch one existing normalized fragment before a mutation.
42
+ */
43
+ export interface OptimisticUIUpdateOperation {
44
+ action: 'update';
45
+ fragmentKey: string;
46
+ update: Record<string, any> | ((fragment: any) => Record<string, any> | null | undefined);
47
+ }
48
+
49
+ /**
50
+ * Insert one temporary object into a top-level fragment collection.
51
+ */
52
+ export interface OptimisticUICreatePlaceholderOperation {
53
+ action: 'create-placeholder';
54
+ parentFragmentKey: string;
55
+ field: string;
56
+ data: Record<string, any>;
57
+ position?: 'start' | 'end';
58
+ }
59
+
60
+ /**
61
+ * Describe one cache operation performed before a GraphQL mutation settles.
62
+ */
63
+ export type OptimisticUIOperation = OptimisticUIUpdateOperation | OptimisticUICreatePlaceholderOperation;
64
+
65
+ /**
66
+ * Accept one optimistic cache operation or one atomic list of operations.
67
+ */
68
+ export type OptimisticUI = OptimisticUIOperation | readonly OptimisticUIOperation[];
49
69
 
50
70
  /**
51
71
  * GraphQL query hook params
@@ -58,29 +78,30 @@ export interface GraphQLQueryOptions {
58
78
  retryCount?: number;
59
79
  rejectedResultRetryCount?: number;
60
80
  retryTransientErrors?: boolean;
81
+ // Optional network deadline; releases a hung query's shared in-flight slot.
82
+ requestTimeoutMs?: number;
61
83
  variables?: Record<string, any> | null;
62
84
  cacheMap?: any;
63
85
  skip?: boolean;
64
- // Freshness window in ms: a complete cached result younger than this is
65
- // served without any request; an older one is served instantly and then
66
- // revalidated in the background (stale-while-revalidate). Defaults to the
67
- // query's QUERY_EXPIRE_TIMES entry.
86
+ // Revalidate cached data once on mount, query-scope change, or skip -> active.
87
+ // Defaults to true. False retains freshness-window checks for this query.
88
+ // Cached data still renders immediately; active RESET_ONLY notices stay deferred.
89
+ revalidateOnMount?: boolean;
90
+ // Freshness window in ms for cache-age checks, including entry when
91
+ // revalidateOnMount is false. Does not control IndexedDB retention.
92
+ // Defaults to the query's QUERY_EXPIRE_TIMES entry.
68
93
  persistTime?: number;
69
94
  testMode?: boolean;
70
95
  openModalPopUp?: AnyModalPopUpFn | null;
71
96
  onCompleted?: OnCompletedGQLFn;
72
97
  onError?: OnErrorGQLFn;
73
- shouldAcceptResult?: (
74
- data: any,
75
- variables?: Record<string, any> | null,
76
- ) => boolean;
98
+ shouldAcceptResult?: (data: any, variables?: Record<string, any> | null) => boolean;
99
+ // Reject snapshots invalidated during their request before they normalize shared fragments.
100
+ rejectInvalidatedResults?: boolean;
77
101
  }
78
102
 
79
103
  // Params for most GraphQL (query) hooks
80
- export type UseQueryParams = Omit<
81
- GraphQLQueryOptions,
82
- 'name' | 'retryCount' | 'cacheMap'
83
- >;
104
+ export type UseQueryParams = Omit<GraphQLQueryOptions, 'name' | 'retryCount' | 'cacheMap'>;
84
105
 
85
106
  // Params for most GraphQL (mutation) hooks
86
107
  export type UseMutationParams = Partial<{