@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
package/audience.d.ts ADDED
@@ -0,0 +1,343 @@
1
+ import type { PaginationArgs } from './types.d.ts';
2
+
3
+ export type AudienceListsSort = 'CREATED_ASC' | 'CREATED_DESC';
4
+ export type AudienceListMembersSort = AudienceListsSort;
5
+
6
+ export interface AudienceListsFilter {
7
+ ids?: readonly string[] | null;
8
+ includeArchived?: boolean;
9
+ search?: string | null;
10
+ }
11
+
12
+ export interface AudienceListMembersFilter {
13
+ audienceListId?: string | null;
14
+ subscriptionStatus?: AudienceSubscriptionStatus | null;
15
+ includeRemoved?: boolean;
16
+ search?: string | null;
17
+ }
18
+
19
+ export type CampaignAudienceEligibility = 'ALL' | 'ELIGIBLE' | 'EXCLUDED';
20
+ export type CampaignAudienceMembersSort = 'EMAIL_ASC' | 'EMAIL_DESC';
21
+
22
+ export interface CampaignAudienceMembersFilter {
23
+ eligibility?: CampaignAudienceEligibility | null;
24
+ subscriptionStatus?: AudienceSubscriptionStatus | null;
25
+ audienceListId?: string | null;
26
+ search?: string | null;
27
+ }
28
+
29
+ export type CampaignAudienceMembersArgs = {
30
+ organizationId?: string | null;
31
+ campaignId?: string | null;
32
+ filter?: CampaignAudienceMembersFilter | null;
33
+ sort?: CampaignAudienceMembersSort | null;
34
+ } & PaginationArgs;
35
+
36
+ export type AudienceListsArgs = {
37
+ organizationId?: string | null;
38
+ filter?: AudienceListsFilter | null;
39
+ sort?: AudienceListsSort | null;
40
+ } & PaginationArgs;
41
+
42
+ export type AudienceListMembersArgs = {
43
+ organizationId?: string | null;
44
+ filter: AudienceListMembersFilter;
45
+ sort?: AudienceListMembersSort | null;
46
+ } & PaginationArgs;
47
+
48
+ export type AudienceSubscriptionStatus =
49
+ | 'NON_SUBSCRIBED'
50
+ | 'PENDING'
51
+ | 'SUBSCRIBED'
52
+ | 'UNSUBSCRIBED';
53
+ export type AudienceDeliveryStatus =
54
+ | 'UNKNOWN'
55
+ | 'DELIVERABLE'
56
+ | 'SOFT_BOUNCING'
57
+ | 'CLEANED';
58
+ export type AudienceImportSource = 'MANUAL' | 'IMPORT' | 'INTEGRATION';
59
+ export type AudienceConsentSource =
60
+ | 'EXISTING_PERMISSION'
61
+ | 'SIGNUP'
62
+ | 'RECIPIENT_RESUBSCRIBE';
63
+ export type AudienceSuppressionKind =
64
+ | 'MANUAL'
65
+ | 'COMPLAINT'
66
+ | 'CLEANED'
67
+ | 'PROVIDER';
68
+
69
+ export interface AudiencePageArgs {
70
+ afterId?: string | null;
71
+ limit?: number | null;
72
+ }
73
+
74
+ export interface AudienceListGQL {
75
+ id: string;
76
+ cursor: string;
77
+ organizationId: string;
78
+ name: string;
79
+ description: string | null;
80
+ archivedAt: string | null;
81
+ editVersion: string;
82
+ createdByAccountId: string | null;
83
+ createdAt: string;
84
+ updatedAt: string;
85
+ // Active member count; selected by `audienceLists` only, never by the shared fragment.
86
+ count?: number;
87
+ }
88
+
89
+ export interface AudienceConsentInput {
90
+ source: AudienceConsentSource;
91
+ recordedAt: string;
92
+ permissionSource: string;
93
+ }
94
+
95
+ export interface AudienceMemberDetails {
96
+ personName?: string | null;
97
+ provenance?: {
98
+ source?: AudienceImportSource;
99
+ actorAccountId?: string;
100
+ importRequestId?: string;
101
+ };
102
+ consent?: AudienceConsentInput & { actorAccountId?: string };
103
+ [key: string]: unknown;
104
+ }
105
+
106
+ export interface AudienceAddressDetails {
107
+ preferenceSource?: string;
108
+ lastBounce?: {
109
+ type?: string | null;
110
+ code?: string | number | null;
111
+ reason?: string | null;
112
+ };
113
+ manualSuppression?: {
114
+ reason?: string;
115
+ actorAccountId?: string;
116
+ active?: boolean;
117
+ };
118
+ [key: string]: unknown;
119
+ }
120
+
121
+ export interface AudienceEmailAddressGQL {
122
+ id: string;
123
+ organizationId: string;
124
+ normalizedEmail: string;
125
+ inboundContactId: string | null;
126
+ campaignStatus: 'OPTED_IN' | 'OPTED_OUT' | null;
127
+ campaignStatusAt: string | null;
128
+ deliveryStatus: AudienceDeliveryStatus;
129
+ deliveryStatusAt: string | null;
130
+ cleanedReason:
131
+ | 'HARD_BOUNCE'
132
+ | 'INVALID_ADDRESS'
133
+ | 'REPEATED_SOFT_BOUNCE'
134
+ | null;
135
+ lastDeliveredAt: string | null;
136
+ lastBounceAt: string | null;
137
+ consecutiveSoftBounceCount: number;
138
+ complaintSuppressedAt: string | null;
139
+ manuallySuppressedAt: string | null;
140
+ details: AudienceAddressDetails;
141
+ createdAt: string;
142
+ updatedAt: string;
143
+ }
144
+
145
+ export interface AudienceListMemberGQL {
146
+ id: string;
147
+ cursor: string;
148
+ organizationId: string;
149
+ audienceListId: string;
150
+ emailAddressId: string;
151
+ subscriptionStatus: AudienceSubscriptionStatus;
152
+ subscriptionStatusAt: string;
153
+ subscriptionVersion: string;
154
+ removedAt: string | null;
155
+ details: AudienceMemberDetails;
156
+ address?: AudienceEmailAddressGQL | null;
157
+ createdAt: string;
158
+ updatedAt: string;
159
+ }
160
+
161
+ export interface CampaignAudienceMembershipGQL {
162
+ memberId: string;
163
+ audienceListId: string;
164
+ listName: string;
165
+ personName: string | null;
166
+ subscriptionStatus: AudienceSubscriptionStatus;
167
+ subscriptionVersion: string;
168
+ removedAt: string | null;
169
+ }
170
+
171
+ export interface CampaignAudienceMemberGQL {
172
+ id: string;
173
+ cursor: string;
174
+ organizationId: string;
175
+ campaignId: string;
176
+ emailAddressId: string;
177
+ normalizedEmail: string;
178
+ personName: string | null;
179
+ inboundContactId: string | null;
180
+ reason: string | null;
181
+ memberships: CampaignAudienceMembershipGQL[];
182
+ address?: AudienceEmailAddressGQL | null;
183
+ }
184
+
185
+ export interface AudienceListOverviewGQL {
186
+ total: number;
187
+ subscribed: number;
188
+ unsubscribed: number;
189
+ nonSubscribed: number;
190
+ pending: number;
191
+ cleaned: number;
192
+ eligible: number;
193
+ }
194
+
195
+ export interface AudienceEventGQL {
196
+ id: string;
197
+ organizationId: string;
198
+ normalizedEmail: string | null;
199
+ emailAddressId: string | null;
200
+ audienceListId: string | null;
201
+ audienceListMemberId: string | null;
202
+ eventType: string;
203
+ source: string;
204
+ actorAccountId: string | null;
205
+ campaignId: string | null;
206
+ outboundEmailId: string | null;
207
+ metadata: Record<string, unknown>;
208
+ occurredAt: string;
209
+ createdAt: string;
210
+ }
211
+
212
+ export interface AudienceMemberImportResultGQL {
213
+ index: number;
214
+ emailAddress: string;
215
+ outcome:
216
+ | 'ADDED'
217
+ | 'RESTORED'
218
+ | 'UPDATED'
219
+ | 'ALREADY_PRESENT'
220
+ | 'PRESERVED_UNSUBSCRIBE'
221
+ | 'INVALID'
222
+ | 'CONSENT_MISSING'
223
+ | 'DUPLICATE';
224
+ memberId: string | null;
225
+ }
226
+
227
+ export interface AudienceMemberInput {
228
+ emailAddress: string;
229
+ personName?: string | null;
230
+ inboundContactId?: string | null;
231
+ // Imports intentionally cannot set pending or override an unsubscribe.
232
+ subscriptionStatus?: 'NON_SUBSCRIBED' | 'SUBSCRIBED';
233
+ consent?: AudienceConsentInput | null;
234
+ }
235
+
236
+ export interface CreateAudienceListInput {
237
+ organizationId: string;
238
+ name: string;
239
+ description?: string | null;
240
+ }
241
+
242
+ export interface EditAudienceListInput {
243
+ organizationId: string;
244
+ audienceListId: string;
245
+ expectedEditVersion: string;
246
+ name?: string;
247
+ description?: string | null;
248
+ archived?: boolean;
249
+ }
250
+
251
+ export interface AddAudienceListMembersInput {
252
+ organizationId: string;
253
+ audienceListId: string;
254
+ idempotencyKey: string;
255
+ source: AudienceImportSource;
256
+ members: AudienceMemberInput[];
257
+ }
258
+
259
+ export interface ChangeAudienceListSubscriptionInput {
260
+ organizationId: string;
261
+ audienceListId: string;
262
+ memberId: string;
263
+ expectedSubscriptionVersion: string;
264
+ subscribed: boolean;
265
+ consent?: AudienceConsentInput | null;
266
+ }
267
+
268
+ export interface EditAudienceListMemberInput {
269
+ organizationId: string;
270
+ audienceListId: string;
271
+ memberId: string;
272
+ expectedSubscriptionVersion: string;
273
+ personName?: string | null;
274
+ // Staff may only set NON_SUBSCRIBED or SUBSCRIBED; subscribing requires consent.
275
+ subscriptionStatus?: AudienceSubscriptionStatus | null;
276
+ consent?: AudienceConsentInput | null;
277
+ }
278
+
279
+ export interface RemoveAudienceListMembersInput {
280
+ organizationId: string;
281
+ audienceListId: string;
282
+ memberIds: string[];
283
+ }
284
+
285
+ export interface SetAudienceAddressSuppressionInput {
286
+ organizationId: string;
287
+ emailAddressId: string;
288
+ suppression: AudienceSuppressionKind;
289
+ suppressed: boolean;
290
+ reason: string;
291
+ }
292
+
293
+ export interface CampaignAudienceSessionGQL {
294
+ // Campaign id; keys the cached session fragment.
295
+ id: string;
296
+ campaignId: string;
297
+ organizationId: string;
298
+ editVersion: number;
299
+ editable: boolean;
300
+ selectedAudienceListIds: string[];
301
+ // Addresses skipped for this campaign only; they remain members of their lists.
302
+ excludedEmailAddressIds: string[];
303
+ }
304
+
305
+ // The limits the server enforces when a campaign is sent now.
306
+ export interface CampaignEmailSendLimitsGQL {
307
+ // Recipients one campaign may send to.
308
+ recipientLimit: number;
309
+ monthlyRecipientLimit: number;
310
+ // Recipients this campaign can still send to in the current UTC month.
311
+ monthlyRecipientsRemaining: number;
312
+ sendingPaused: boolean;
313
+ }
314
+
315
+ export interface CampaignAudiencePreviewGQL {
316
+ // Campaign id; keys the cached preview fragment.
317
+ id: string;
318
+ campaignId: string;
319
+ editVersion: number;
320
+ selectedCount: number;
321
+ eligibleCount: number;
322
+ duplicateCount: number;
323
+ excludedCount: number;
324
+ exclusions: Array<{ reason: string; count: number }>;
325
+ // Recipients frozen when the campaign was scheduled or sent; 0 for a draft.
326
+ frozenRecipientCount: number;
327
+ sendLimits: CampaignEmailSendLimitsGQL;
328
+ }
329
+
330
+ // Returned by both the campaignAudience query and the setCampaignAudience mutation.
331
+ export interface CampaignAudienceSelectionGQL {
332
+ session: CampaignAudienceSessionGQL;
333
+ preview: CampaignAudiencePreviewGQL;
334
+ }
335
+
336
+ // Each set replaces the whole server-side set when present and is left unchanged when omitted.
337
+ export interface SetCampaignAudienceInput {
338
+ organizationId: string;
339
+ campaignId: string;
340
+ expectedEditVersion: number;
341
+ audienceListIds?: string[];
342
+ excludedEmailAddressIds?: string[];
343
+ }
package/cache/config.ts CHANGED
@@ -1,7 +1,4 @@
1
- import {
2
- FRAGMENT_NAMES,
3
- getFragmentBaseName,
4
- } from '@jsb188/mday/constants/graphqlReactivity.ts';
1
+ import { FRAGMENT_NAMES, getFragmentBaseName } from '@jsb188/mday/constants/graphqlReactivity.ts';
5
2
 
6
3
  /**
7
4
  * Rules for GraphQL server that's hard-coded to this package
@@ -13,32 +10,51 @@ import {
13
10
  * the cache stores changes incompatibly; a mismatch wipes the IndexedDB
14
11
  * snapshot on boot. (Stale-but-compatible data self-heals at read time via
15
12
  * fetchCachedData's selection completeness check.)
13
+ *
14
+ * 10: exact JSON variable keys replace lossy lowercased keys; nullable nested
15
+ * selections and lists preserve the server's null and empty values.
16
+ *
17
+ * 11: field doc programs. $fieldDocFragment now holds the form instead of a
18
+ * filled document, and submission, answer and edit-session ids changed, so
19
+ * the old field doc records are dropped instead of lingering as orphans.
16
20
  */
17
21
 
18
- export const CACHE_SCHEMA_VERSION = 5;
22
+ export const CACHE_SCHEMA_VERSION = 11;
19
23
 
20
24
  export const QUERY_EXPIRE_TIMES = {
21
25
  __default: 1.08e7, // 3 hours
26
+ myOrganizations: 15 * 60 * 1000,
22
27
  // 5.4e+6, // 1.5 hours
23
28
  // 2.88e+7, // 8 hours
24
29
  // 6.48e+7, // 18 hours
25
30
 
31
+ // Campaign metrics are live operational data. Realtime resets keep mounted
32
+ // lists current, while this short fallback repairs missed websocket events.
33
+ campaigns: 60 * 1000,
34
+ emailCampaignReplyReport: 60 * 1000,
35
+
36
+ // Note edits use fragments; short freshness windows recover missed events on revisit.
37
+ agentNote: 60 * 1000,
38
+ agentNotes: 60 * 1000,
39
+ searchAgentNotes: 60 * 1000,
40
+
26
41
  // Sheets
27
42
  sheets: 1.08e7,
28
43
  sheetAccess: 2.88e7,
29
- sheetRegionSourcePreviewRows: 2.88e7,
44
+ // Form definitions should refresh quickly between modal sessions without
45
+ // becoming stale again during the same render pass.
46
+ sheetWebFormResultsSource: 1000,
30
47
  sheetAccessGrants: 2.88e7,
31
48
  openSheet: 2.88e7,
32
- openSheetTab: 2.88e7,
33
- sheetTabChanges: 2.88e7,
34
- sheetOperationalHistory: 2.88e7,
35
49
 
36
- // Data tables
37
- dataTables: 1.08e7,
38
- dataTable: 2.88e7,
39
- dataTableMetadata: 2.88e7,
40
- dataTableRowsSnapshot: 2.88e7,
41
- dataTableChanges: 2.88e7,
50
+ // Data tables change through agents, workflows and source sync. Fragments and
51
+ // resets keep mounted views current. After missed events, short freshness
52
+ // windows refetch on focus, reconnect or the next mount; a mounted rows list
53
+ // is rebuilt only by a reset or its RESET_ONLY notice.
54
+ dataTables: 60 * 1000,
55
+ dataTable: 60 * 1000,
56
+ dataTableRows: 60 * 1000,
57
+ dataTableRuns: 60 * 1000,
42
58
  } as {
43
59
  [key: string]: number;
44
60
  };
@@ -52,6 +68,20 @@ export const RULES = {
52
68
  // but if you want to skip some, add it here
53
69
  accountAuthFragment: false,
54
70
 
71
+ // Editor and access sessions contain heavy mutable trees or short-lived
72
+ // authorization state. Keep normalized core fragments, but never persist
73
+ // the root session response across unmounts.
74
+ campaignEditSession: false,
75
+ // Reply identities and captured answers live only in the mounted report hook.
76
+ emailCampaignReplyReport: false,
77
+ campaignFormAccessSession: false,
78
+ campaignTemplateEditSession: false,
79
+ // Typeahead prefixes live only in the mounted hook; note fragments remain shared.
80
+ searchAgentNotes: false,
81
+ // Billing payment-form inputs: the Stripe key and tax previews must be
82
+ // fetched fresh for each payment form, never replayed from disk.
83
+ billingClientConfig: false,
84
+ billingPurchasePreview: false,
55
85
  // NOTE: ALL queries are cached by default,
56
86
  // but if you want to skip some, add it here
57
87
  // e.g.: someQueryName: false,
@@ -65,18 +95,22 @@ export const RULES = {
65
95
 
66
96
  export const PARTIALS_MAP = {
67
97
  // Partial fragments are supported if you map them to its original fragment name
68
- dataTablePartialFragment: getFragmentBaseName(FRAGMENT_NAMES.dataTable),
69
98
  sheetViewPatchFragment: getFragmentBaseName(FRAGMENT_NAMES.sheetView),
70
- // List rows are a narrower projection of the same record. Without these the
71
- // server's $campaignTemplateFragment / $campaignFragment patches would only
72
- // reach a detail view, and a GENERATING card in a list would never settle to
73
- // ACTIVE.
74
- campaignTemplateSummaryFragment: getFragmentBaseName(
75
- FRAGMENT_NAMES.campaignTemplate,
76
- ),
99
+ // List rows are narrower projections of the same records. Map them to the
100
+ // canonical fragment keys so realtime core patches update both detail and
101
+ // summary consumers without duplicating fragment authorities.
102
+ campaignTemplateSummaryFragment: getFragmentBaseName(FRAGMENT_NAMES.campaignTemplate),
103
+ campaignTemplateLifecycleFragment: getFragmentBaseName(FRAGMENT_NAMES.campaignTemplate),
104
+ campaignAccessFragment: getFragmentBaseName(FRAGMENT_NAMES.campaign),
105
+ campaignGenerationLifecycleFragment: getFragmentBaseName(FRAGMENT_NAMES.campaign),
106
+ campaignLifecycleFragment: getFragmentBaseName(FRAGMENT_NAMES.campaign),
107
+ campaignSettingsFragment: getFragmentBaseName(FRAGMENT_NAMES.campaign),
77
108
  campaignSummaryFragment: getFragmentBaseName(FRAGMENT_NAMES.campaign),
109
+ // The note detail projection shares the realtime agentNoteFragment identity
110
+ agentNoteDetailFragment: getFragmentBaseName(FRAGMENT_NAMES.agentNote),
111
+ emailMessageDetailsFragment: getFragmentBaseName(FRAGMENT_NAMES.emailMessage),
78
112
  } as Record<string, string>;
79
113
 
80
114
  export const PARTIAL_NULL_PRESERVE_FIELDS = {
81
- sheetViewPatchFragment: ['ranges', 'sheetTab'],
115
+ sheetViewPatchFragment: ['sheetTab'],
82
116
  } as Record<string, string[]>;
@@ -0,0 +1,119 @@
1
+ import { makeGraphQLVariablesKey } from '@jsb188/app/utils/logic.ts';
2
+ import { makeQueryResetTarget } from '@jsb188/app/utils/queryReset.ts';
3
+ import { getActiveAIChatsByActivity, getAIChatActivityOrder } from '@jsb188/mday/utils/aiChat.ts';
4
+ import { aiChatQry, aiChatsQry } from '../gql/queries/aiChatQueries.ts';
5
+ import {
6
+ clearGraphQLClientCache,
7
+ loadFragment,
8
+ loadQuery,
9
+ resetQueryByTargetIfFragmentsMissing,
10
+ setDataToCache,
11
+ updateFragment,
12
+ } from './index.ts';
13
+
14
+ if (typeof (console as any).dev !== 'function') (console as any).dev = () => {};
15
+
16
+ /* Fail with the actual value when cache behavior differs from the expected result. */
17
+ function assertEqual(actual: unknown, expected: unknown) {
18
+ if (JSON.stringify(actual) !== JSON.stringify(expected))
19
+ throw new Error(`Expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);
20
+ }
21
+
22
+ /* Build the exact sidebar variables used by the mounted query. */
23
+ function sidebarVariables(organizationId = 'org') {
24
+ return { organizationId, filter: 'CHATS', cursor: null, after: false, limit: 70 };
25
+ }
26
+
27
+ /* Seed a small authoritative sidebar snapshot with opaque identifiers. */
28
+ function seedSidebar(organizationId = 'org') {
29
+ const chats = [
30
+ { id: 'opaque-a', updatedAt: '2026-10-04T12:00:00.000Z', activityOrder: getAIChatActivityOrder('2026-10-04T12:00:00.000Z', 9) },
31
+ { id: 'opaque-z', updatedAt: '2026-10-04T11:00:00.000Z', activityOrder: getAIChatActivityOrder('2026-10-04T11:00:00.000Z', 10) },
32
+ ];
33
+ setDataToCache({ aiChats: chats }, aiChatsQry, sidebarVariables(organizationId));
34
+ return chats;
35
+ }
36
+
37
+ Deno.test('listed chat activity reorders immediately without requesting any query reset', () => {
38
+ clearGraphQLClientCache();
39
+ seedSidebar();
40
+ const events: unknown[] = [];
41
+ resetQueryByTargetIfFragmentsMissing(
42
+ makeQueryResetTarget('aiChats', { organizationId: 'org', filter: 'CHATS' }),
43
+ ['$aiChatFragment:opaque-z'],
44
+ (event) => events.push(event),
45
+ );
46
+ assertEqual(events, []);
47
+ updateFragment('$aiChatFragment:opaque-z', {
48
+ updatedAt: '2026-10-04T13:00:00.000Z',
49
+ activityOrder: getAIChatActivityOrder('2026-10-04T13:00:00.000Z', 10),
50
+ });
51
+ const chats = loadQuery(`#aiChats:${makeGraphQLVariablesKey(sidebarVariables())}`);
52
+ assertEqual(
53
+ getActiveAIChatsByActivity(chats).map((chat: any) => chat.id),
54
+ ['opaque-z', 'opaque-a'],
55
+ );
56
+ assertEqual(
57
+ chats.map((chat: any) => chat.id),
58
+ ['opaque-a', 'opaque-z'],
59
+ );
60
+ });
61
+
62
+ Deno.test('a globally cached chat outside the sidebar resets only that organization list', () => {
63
+ clearGraphQLClientCache();
64
+ seedSidebar();
65
+ seedSidebar('other');
66
+ setDataToCache({ aiChat: { id: 'outside', updatedAt: '2026-10-04T13:00:00.000Z' } }, aiChatQry, { aiChatId: 'outside' });
67
+ const events: any[] = [];
68
+ resetQueryByTargetIfFragmentsMissing(
69
+ makeQueryResetTarget('aiChats', { organizationId: 'org', filter: 'CHATS' }),
70
+ ['$aiChatFragment:outside'],
71
+ (event) => events.push(event),
72
+ );
73
+ assertEqual(
74
+ events.map((event) => ({ queryId: event.queryId, forceRefetch: event.forceRefetch })),
75
+ [
76
+ {
77
+ queryId: `#aiChats:${makeGraphQLVariablesKey(sidebarVariables())}`,
78
+ forceRefetch: true,
79
+ },
80
+ ],
81
+ );
82
+ });
83
+
84
+ Deno.test('a missing chat and an in-flight initial sidebar snapshot both request recovery', () => {
85
+ clearGraphQLClientCache();
86
+ const target = makeQueryResetTarget('aiChats', { organizationId: 'org', filter: 'CHATS' });
87
+ const events: any[] = [];
88
+ resetQueryByTargetIfFragmentsMissing(target, ['$aiChatFragment:new'], (event) => events.push(event));
89
+ assertEqual(events[0]?.queryTarget, target);
90
+ seedSidebar();
91
+ resetQueryByTargetIfFragmentsMissing(target, ['$aiChatFragment:new'], (event) => events.push(event));
92
+ assertEqual(events.length, 2);
93
+ });
94
+
95
+ Deno.test('late queries and realtime metadata cannot move a chat back to older activity', () => {
96
+ clearGraphQLClientCache();
97
+ const stale = seedSidebar();
98
+ const fresh = { updatedAt: '2026-10-04T13:00:00.000Z', activityOrder: getAIChatActivityOrder('2026-10-04T13:00:00.000Z', 10) };
99
+ updateFragment('$aiChatFragment:opaque-z', fresh);
100
+ setDataToCache({ aiChats: stale }, aiChatsQry, sidebarVariables());
101
+ updateFragment('$aiChatFragment:opaque-z', { ...stale[1], summary: 'New title' });
102
+ const chat = loadFragment('$aiChatFragment:opaque-z');
103
+ assertEqual(
104
+ { updatedAt: chat.updatedAt, activityOrder: chat.activityOrder, summary: chat.summary },
105
+ { ...fresh, summary: 'New title' },
106
+ );
107
+ });
108
+
109
+ Deno.test('timestamp ties use database id order rather than scrambled GenericID order', () => {
110
+ const updatedAt = '2026-10-04T13:00:00.000Z';
111
+ assertEqual(
112
+ getActiveAIChatsByActivity([
113
+ { id: 'zzz', updatedAt, activityOrder: getAIChatActivityOrder(updatedAt, 9) },
114
+ { id: 'aaa', updatedAt, activityOrder: getAIChatActivityOrder(updatedAt, 10) },
115
+ { id: 'archived', updatedAt, archivedAt: updatedAt, activityOrder: getAIChatActivityOrder(updatedAt, 11) },
116
+ ]).map((chat) => chat.id),
117
+ ['aaa', 'zzz'],
118
+ );
119
+ });
@@ -0,0 +1,92 @@
1
+ import { makeGraphQLVariablesKey } from '@jsb188/app/utils/logic.ts';
2
+ import type { AIChatRunData } from '@jsb188/app/types/ai.d.ts';
3
+ import { aiChatMessagesQry, aiChatQry, aiChatWorkMessagesQry } from '../gql/queries/aiChatQueries.ts';
4
+ import { cacheAIChatRunUpdate } from '../libs/ai-chat-run-realtime.ts';
5
+ import { clearGraphQLClientCache, loadFragment, loadQuery, setDataToCache, updateFragment } from './index.ts';
6
+
7
+ if (typeof (console as any).dev !== 'function') (console as any).dev = () => {};
8
+
9
+ /* Assert the observable cache state without relying on a mounted hook's local state. */
10
+ function assertEqual(actual: unknown, expected: unknown) {
11
+ if (JSON.stringify(actual) !== JSON.stringify(expected))
12
+ throw new Error(`Expected ${JSON.stringify(expected)}, received ${JSON.stringify(actual)}`);
13
+ }
14
+
15
+ /* Build authoritative run snapshots with a fixed immutable start time. */
16
+ function makeRun(inProgress: boolean): AIChatRunData {
17
+ return {
18
+ id: 'run-1',
19
+ sourceMessageIds: ['source'],
20
+ status: inProgress ? 'RUNNING' : 'COMPLETED',
21
+ inProgress,
22
+ createdAt: '2026-10-02T10:00:00Z',
23
+ claimedAt: '2026-10-02T10:00:01Z',
24
+ updatedAt: inProgress ? '2026-10-02T10:00:01Z' : '2026-10-02T10:01:00Z',
25
+ finishedAt: inProgress ? null : '2026-10-02T10:01:00Z',
26
+ };
27
+ }
28
+
29
+ Deno.test('late chat queries cannot reopen canonical or embedded runs when the transcript is read again', () => {
30
+ clearGraphQLClientCache();
31
+ const variables = { aiChatId: 'chat', includeWork: false };
32
+ const stale = {
33
+ aiChat: {
34
+ id: 'chat',
35
+ inProgress: true,
36
+ latestRun: makeRun(true),
37
+ messages: [{ id: 'source', accountId: 'account', run: makeRun(true) }],
38
+ },
39
+ };
40
+ setDataToCache(stale, aiChatQry, variables);
41
+ cacheAIChatRunUpdate(makeRun(false), () => {});
42
+ setDataToCache(stale, aiChatQry, variables);
43
+ const reopened = loadQuery(`#aiChat:${makeGraphQLVariablesKey(variables)}`);
44
+ assertEqual(reopened.latestRun, makeRun(false));
45
+ assertEqual(reopened.messages[0].run, makeRun(false));
46
+ assertEqual(loadFragment('$aiChatRunFragment:run-1'), makeRun(false));
47
+ });
48
+
49
+ Deno.test('late run history pages retain streamed message revisions and stay separate from the outer transcript', () => {
50
+ clearGraphQLClientCache();
51
+ const stale = {
52
+ id: 'message',
53
+ runId: 'run-1',
54
+ run: makeRun(true),
55
+ revision: '1',
56
+ text: 'Partial',
57
+ finished: false,
58
+ generationStatus: 'STREAMING',
59
+ };
60
+ const fresh = { ...stale, revision: '2', text: 'Complete', finished: true, generationStatus: 'COMPLETED' };
61
+ setDataToCache({ aiChatMessages: [stale] }, aiChatMessagesQry);
62
+ updateFragment('$aiChatMessageFragment:message', fresh);
63
+ cacheAIChatRunUpdate(makeRun(false), () => {});
64
+ setDataToCache({ aiChatMessages: [stale] }, aiChatMessagesQry);
65
+ const workVariables = { aiChatId: 'chat', runId: 'run-1', cursor: null, after: false, limit: 55 };
66
+ setDataToCache({ aiChatMessages: [stale] }, aiChatWorkMessagesQry, workVariables);
67
+ setDataToCache({ aiChatMessages: [] }, aiChatMessagesQry);
68
+ const reread = loadQuery(`#aiChatMessages:${makeGraphQLVariablesKey(workVariables)}`);
69
+ assertEqual(reread, [{ ...fresh, run: makeRun(false) }]);
70
+ assertEqual(loadQuery(`#aiChatMessages:${makeGraphQLVariablesKey(undefined)}`), []);
71
+ });
72
+
73
+ Deno.test('older message text can carry newer run settlement without a canonical run fragment', () => {
74
+ clearGraphQLClientCache();
75
+ const current = { id: 'message', runId: 'run-1', run: makeRun(true), revision: '9', text: 'Latest text' };
76
+ const incoming = { ...current, revision: '8', text: 'Older text', run: makeRun(false) };
77
+ setDataToCache({ aiChatMessages: [current] }, aiChatMessagesQry);
78
+ setDataToCache({ aiChatMessages: [incoming] }, aiChatMessagesQry);
79
+ assertEqual(loadFragment('$aiChatRunFragment:run-1'), null);
80
+ assertEqual(loadFragment('$aiChatMessageFragment:message'), { ...current, run: makeRun(false) });
81
+ });
82
+
83
+ Deno.test('an older canonical run cannot replace a newer source message association', () => {
84
+ clearGraphQLClientCache();
85
+ const newerRun = { ...makeRun(true), id: 'run-2', createdAt: '2026-10-02T10:02:00Z', updatedAt: '2026-10-02T10:02:01Z' };
86
+ const current = { id: 'source', run: newerRun, revision: '9', text: 'Latest text' };
87
+ setDataToCache({ aiChatMessages: [current] }, aiChatMessagesQry);
88
+ // Normalize the prior run without issuing a source-association SSE update.
89
+ setDataToCache({ aiChat: { id: 'chat', latestRun: makeRun(false) } }, aiChatQry);
90
+ setDataToCache({ aiChatMessages: [{ ...current, revision: '8', text: 'Older text', run: makeRun(false) }] }, aiChatMessagesQry);
91
+ assertEqual(loadFragment('$aiChatMessageFragment:source'), current);
92
+ });