@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
@@ -1,15 +1,8 @@
1
- import {
2
- FRAGMENT_NAMES,
3
- makeFragmentKey,
4
- } from '@jsb188/mday/constants/graphqlReactivity.ts';
5
- import { useOpenModalPopUp } from '@jsb188/react/states';
1
+ import { FRAGMENT_NAMES, makeFragmentKey } from '@jsb188/mday/constants/graphqlReactivity.ts';
2
+ import { type OpenModalPopUpFn, useOpenModalPopUp } from '@jsb188/react/states';
6
3
  import { useCallback, useEffect, useRef } from 'react';
7
- import {
8
- loadFragment,
9
- resetQuery,
10
- updateFragment,
11
- updateQuery,
12
- } from '../cache/index.ts';
4
+ import { normalizeServerError } from '@jsb188/app/utils/api.ts';
5
+ import { loadFragment, resetQuery, updateFragment, updateQuery } from '../cache/index.ts';
13
6
  import { type GraphQLMutationFn, useMutation } from '../client/index.ts';
14
7
  import {
15
8
  deleteAIChatMtn,
@@ -18,34 +11,27 @@ import {
18
11
  startAIChatMtn,
19
12
  stopAIChatMessageMtn,
20
13
  } from '../gql/mutations/aiChatMutations.ts';
21
- import type { UseMutationParams } from '../types.d.ts';
22
- import { updateAIChats } from './use-aiChat-qry.ts';
14
+ import type { UseMutationParams, UseMutationParamsExtra } from '../types.d.ts';
15
+ import { acceptAIChatOutgoingMessage, failAIChatOutgoingMessage } from '../libs/ai-chat-outgoing.ts';
23
16
 
24
17
  /**
25
18
  * Start AI chat
26
19
  */
27
20
 
28
- export function useStartAIChat(params: UseMutationParams = {}) {
29
- const { onCompleted, onError } = params;
30
- const openModalPopUp = useOpenModalPopUp();
21
+ export function useStartAIChat(params: UseMutationParamsExtra = {}, openModalPopUp?: OpenModalPopUpFn) {
22
+ const { onCompleted, onError, ...rest } = params;
31
23
 
32
- const [startAIChat, mtnValues, , updateObservers] = useMutation(
33
- startAIChatMtn,
34
- {
35
- openModalPopUp,
36
- onCompleted: (data: any, err: any, variables: any) => {
37
- onCompleted?.(data, err, variables);
38
-
39
- const aiChat = data.startAIChat?.node;
40
- updateAIChats(aiChat, variables?.organizationId, updateObservers);
41
- },
42
- onError,
43
- },
44
- );
24
+ const [startAIChat, mtnValues, mtnHandlers] = useMutation(startAIChatMtn, {
25
+ ...rest,
26
+ openModalPopUp,
27
+ onCompleted,
28
+ onError,
29
+ });
45
30
 
46
31
  return {
47
32
  startAIChat,
48
33
  ...mtnValues,
34
+ ...mtnHandlers,
49
35
  };
50
36
  }
51
37
 
@@ -57,14 +43,11 @@ export function useEditAIChat(params: UseMutationParams = {}) {
57
43
  const { onCompleted, onError } = params;
58
44
  const openModalPopUp = useOpenModalPopUp();
59
45
 
60
- const [mutateAIChat, mtnValues, mtnHandlers, updateObservers] = useMutation(
61
- editAIChatMtn,
62
- {
63
- openModalPopUp,
64
- onCompleted,
65
- onError,
66
- },
67
- );
46
+ const [mutateAIChat, mtnValues, mtnHandlers, updateObservers] = useMutation(editAIChatMtn, {
47
+ openModalPopUp,
48
+ onCompleted,
49
+ onError,
50
+ });
68
51
 
69
52
  /*
70
53
  * Optimistically write a submitted summary to its fragment and roll it back
@@ -126,70 +109,79 @@ export function useEditAIChat(params: UseMutationParams = {}) {
126
109
  * Send a new message to AI Chat
127
110
  */
128
111
 
129
- export function useAIChatTextarea(
130
- variablesKey: string,
131
- params: UseMutationParams = {},
132
- ) {
112
+ export function useAIChatTextarea(variablesKey: string, params: UseMutationParams = {}) {
133
113
  const { onCompleted, onError } = params;
134
114
  const didSendRef = useRef(false);
135
115
  const openModalPopUp = useOpenModalPopUp();
136
116
 
137
117
  // Send AI chat message
138
118
 
139
- const [sendAIChatMessage, mtnValues1, , updateObservers] = useMutation(
140
- sendAIChatMessageMtn,
141
- {
142
- openModalPopUp,
143
- onCompleted: (data: any, err: any, variables: any) => {
144
- didSendRef.current = true;
145
-
146
- onCompleted?.(data, err, variables);
147
-
148
- const aiChatId = variables.aiChatId;
149
- const messageId = data.sendAIChatMessage?.node?.id;
150
-
151
- if (messageId && aiChatId && variablesKey) {
152
- const fragmentKey = makeFragmentKey(
153
- FRAGMENT_NAMES.aiChatMessage,
154
- messageId,
155
- );
156
-
157
- updateQuery(
158
- `#aiChat:${variablesKey}`,
159
- (currentData: any) => {
160
- const currentList = currentData?.messages?.data;
161
-
162
- // The updater receives the stored references by reference, so the
163
- // new message must be appended into fresh objects; mutating them
164
- // in place leaves the version stamp (and the persisted snapshot)
165
- // unchanged, which drops the sent message on the next page load.
166
- if (
167
- !Array.isArray(currentList) ||
168
- currentList.some((item: any) => item?.[0] === fragmentKey)
169
- ) {
170
- return currentData;
171
- }
172
-
173
- return {
174
- ...currentData,
175
- messages: {
176
- ...currentData.messages,
177
- data: [...currentList, [fragmentKey]],
178
- },
179
- };
180
- },
181
- false,
182
- updateObservers,
183
- );
184
- } else if (data && !err) {
185
- console.dev(
186
- `Unknown error: {${messageId ? 'aiChatId' : 'messageId'}} was not found.`,
187
- 'warning',
188
- );
119
+ const [mutateAIChatMessage, mtnValues1, sendHandlers, updateObservers] = useMutation(sendAIChatMessageMtn, {
120
+ onCompleted: (data: any, err: any, variables: any) => {
121
+ if (data.sendAIChatMessage?.node?.id) {
122
+ acceptAIChatOutgoingMessage(variables.aiChatId, variables.clientRequestId, data.sendAIChatMessage.node);
123
+ }
124
+
125
+ onCompleted?.(data, err, variables);
126
+
127
+ const aiChatId = variables.aiChatId;
128
+ const messageId = data.sendAIChatMessage?.node?.id;
129
+
130
+ if (messageId && aiChatId && variablesKey) {
131
+ const fragmentKey = makeFragmentKey(FRAGMENT_NAMES.aiChatMessage, messageId);
132
+
133
+ updateQuery(
134
+ `#aiChat:${variablesKey}`,
135
+ (currentData: any) => {
136
+ const currentList = currentData?.messages?.data;
137
+
138
+ // The updater receives the stored references by reference, so the
139
+ // new message must be appended into fresh objects; mutating them
140
+ // in place leaves the version stamp (and the persisted snapshot)
141
+ // unchanged, which drops the sent message on the next page load.
142
+ if (!Array.isArray(currentList) || currentList.some((item: any) => item?.[0] === fragmentKey)) {
143
+ return currentData;
144
+ }
145
+
146
+ return {
147
+ ...currentData,
148
+ messages: {
149
+ ...currentData.messages,
150
+ data: [...currentList, [fragmentKey]],
151
+ },
152
+ };
153
+ },
154
+ false,
155
+ updateObservers,
156
+ );
157
+ } else if (data && !err) {
158
+ console.dev(`Unknown error: {${messageId ? 'aiChatId' : 'messageId'}} was not found.`, 'warning');
159
+ }
160
+ },
161
+ onError: (error, variables) => {
162
+ failAIChatOutgoingMessage(variables?.aiChatId, variables?.clientRequestId, error);
163
+ onError?.(error, variables);
164
+ },
165
+ });
166
+
167
+ /* Mutations can abort without callbacks; preserve those outgoing payloads for retry too. */
168
+ const sendAIChatMessage = useCallback<GraphQLMutationFn>(
169
+ async (options, triedCount) => {
170
+ didSendRef.current = true;
171
+ try {
172
+ const result = await mutateAIChatMessage(options, triedCount);
173
+ if (result?.aborted || (!result?.sendAIChatMessage?.node?.id && !result?.error)) {
174
+ failAIChatOutgoingMessage(options?.variables?.aiChatId, options?.variables?.clientRequestId);
189
175
  }
190
- },
191
- onError,
176
+ return result;
177
+ } catch (error) {
178
+ const serverError = normalizeServerError(error);
179
+ sendHandlers.setSaving(false);
180
+ failAIChatOutgoingMessage(options?.variables?.aiChatId, options?.variables?.clientRequestId, serverError);
181
+ return { error: serverError };
182
+ }
192
183
  },
184
+ [mutateAIChatMessage],
193
185
  );
194
186
 
195
187
  // Stop AI chat message
@@ -207,12 +199,13 @@ export function useAIChatTextarea(
207
199
  // as a result of the SSE pipe breaking at unmount.
208
200
 
209
201
  useEffect(() => {
202
+ didSendRef.current = false;
210
203
  return () => {
211
204
  if (didSendRef.current) {
212
205
  resetQuery(`#aiChat:${variablesKey}`, true, updateObservers);
213
206
  }
214
207
  };
215
- }, []);
208
+ }, [variablesKey]);
216
209
 
217
210
  return {
218
211
  send: {
@@ -234,26 +227,17 @@ export function useDeleteAIChat(params: UseMutationParams = {}) {
234
227
  const { onCompleted, onError } = params;
235
228
  const openModalPopUp = useOpenModalPopUp();
236
229
 
237
- const [deleteAIChat, mtnValues, mtnHandlers, updateObservers] = useMutation(
238
- deleteAIChatMtn,
239
- {
240
- openModalPopUp,
241
- onCompleted: (data: any, err: any, variables: any) => {
242
- if (data?.deleteAIChat) {
243
- updateFragment(
244
- makeFragmentKey(FRAGMENT_NAMES.aiChat, variables.aiChatId),
245
- { __deleted: true },
246
- null,
247
- false,
248
- updateObservers,
249
- );
250
- }
230
+ const [deleteAIChat, mtnValues, mtnHandlers, updateObservers] = useMutation(deleteAIChatMtn, {
231
+ openModalPopUp,
232
+ onCompleted: (data: any, err: any, variables: any) => {
233
+ if (data?.deleteAIChat) {
234
+ updateFragment(makeFragmentKey(FRAGMENT_NAMES.aiChat, variables.aiChatId), { __deleted: true }, null, false, updateObservers);
235
+ }
251
236
 
252
- onCompleted?.(data, err, variables);
253
- },
254
- onError,
237
+ onCompleted?.(data, err, variables);
255
238
  },
256
- );
239
+ onError,
240
+ });
257
241
 
258
242
  return {
259
243
  deleteAIChat,
@@ -0,0 +1,63 @@
1
+ import {
2
+ mergeLocalAIChatMessages,
3
+ mergeSSEPayloadToLocalAIChatMessages,
4
+ upsertLocalAIChatMessage,
5
+ } from './use-aiChat-qry.helpers.ts';
6
+
7
+ Deno.test('reconnected chat checkpoints ignore stale revisions without bigint precision loss', () => {
8
+ const latest = {
9
+ id: 'message',
10
+ revision: '9007199254740993',
11
+ text: 'Complete answer',
12
+ finished: true,
13
+ };
14
+ const stale = {
15
+ ...latest,
16
+ revision: '9007199254740992',
17
+ text: 'Complete',
18
+ finished: false,
19
+ };
20
+ const rows = [latest];
21
+ if (upsertLocalAIChatMessage(rows, stale) !== rows)
22
+ throw new Error('Old reconnect must not overwrite completed text');
23
+ const merged = mergeSSEPayloadToLocalAIChatMessages(rows, {
24
+ __type: 'DATA_UPDATE',
25
+ fragmentKey: '$aiChatMessageFragment:message',
26
+ data: stale,
27
+ });
28
+ if (merged[0].text !== latest.text)
29
+ throw new Error('Stale stream update must be ignored');
30
+ const cached = mergeLocalAIChatMessages({ messages: [latest] }, [stale]);
31
+ if (cached.messages.length !== 1 || cached.messages[0].text !== latest.text)
32
+ throw new Error('Stale local draft must not mask fresher database data');
33
+ });
34
+
35
+ Deno.test('replaying a full checkpoint does not duplicate message rows or append its text twice', () => {
36
+ const payload = {
37
+ __type: 'QUERY_APPEND',
38
+ fragmentKey: '#aiChat:chat',
39
+ dataFragmentKey: '$aiChatMessageFragment:message',
40
+ data: { id: 'message', revision: '8', text: 'Hello' },
41
+ } as const;
42
+ const first = mergeSSEPayloadToLocalAIChatMessages([], payload);
43
+ const second = mergeSSEPayloadToLocalAIChatMessages(first, payload);
44
+ if (second.length !== 1 || second[0].text !== 'Hello')
45
+ throw new Error('Full checkpoints must be idempotent');
46
+ });
47
+
48
+ Deno.test('a terminal checkpoint cannot be reopened by an equal-revision streaming snapshot', () => {
49
+ const terminal = {
50
+ id: 'message',
51
+ revision: '12',
52
+ generationStatus: 'INCOMPLETE',
53
+ finished: true,
54
+ };
55
+ const rows = [terminal];
56
+ const streaming = {
57
+ ...terminal,
58
+ generationStatus: 'STREAMING',
59
+ finished: false,
60
+ };
61
+ if (upsertLocalAIChatMessage(rows, streaming) !== rows)
62
+ throw new Error('Terminal checkpoint must win a same-revision tie');
63
+ });
@@ -0,0 +1,124 @@
1
+ import { FRAGMENT_NAMES } from '@jsb188/mday/constants/graphqlReactivity.ts';
2
+ import type { PublishPayload } from '../sse.ts';
3
+ import { isOlderChatCheckpoint } from '../sse.helpers.ts';
4
+
5
+ /**
6
+ * Return the message id from an AI chat message fragment key.
7
+ */
8
+
9
+ export function getAIChatMessageIdFromFragmentKey(fragmentKey?: string | null) {
10
+ const fragmentName = FRAGMENT_NAMES.aiChatMessage + ':';
11
+ return fragmentKey?.startsWith(fragmentName) ? fragmentKey.substring(fragmentName.length) : null;
12
+ }
13
+
14
+ /**
15
+ * Merge one message into a local live message list.
16
+ */
17
+
18
+ export function upsertLocalAIChatMessage(messages: any[], message: any) {
19
+ if (!message?.id) {
20
+ return messages;
21
+ }
22
+
23
+ const index = messages.findIndex((item) => item?.id === message.id);
24
+ if (index >= 0) {
25
+ if (isOlderChatCheckpoint(messages[index], message)) return messages;
26
+ const nextMessages = messages.slice(0);
27
+ nextMessages[index] = {
28
+ ...nextMessages[index],
29
+ ...message,
30
+ };
31
+ return nextMessages;
32
+ }
33
+
34
+ return [...messages, message];
35
+ }
36
+
37
+ /*
38
+ * Merge transcript pages in linear time while retaining newer streamed checkpoints.
39
+ */
40
+ export function mergeAIChatMessagePages(...pages: any[][]) {
41
+ const messages = new Map<string, any>();
42
+ for (const page of pages) {
43
+ for (const message of page) {
44
+ if (!message?.id) continue;
45
+ const previous = messages.get(message.id);
46
+ if (previous && isOlderChatCheckpoint(previous, message)) continue;
47
+ messages.set(message.id, previous ? { ...previous, ...message } : message);
48
+ }
49
+ }
50
+ return [...messages.values()];
51
+ }
52
+
53
+ /**
54
+ * Merge SSE payloads into local live AI chat messages.
55
+ */
56
+
57
+ export function mergeSSEPayloadToLocalAIChatMessages(messages: any[], sseData: PublishPayload) {
58
+ const { __type, data, dataFragmentKey, fragmentKey } = sseData;
59
+
60
+ switch (__type) {
61
+ case 'QUERY_APPEND':
62
+ {
63
+ const messageId = getAIChatMessageIdFromFragmentKey(dataFragmentKey);
64
+ if (messageId && data && typeof data === 'object') {
65
+ return upsertLocalAIChatMessage(messages, {
66
+ ...data,
67
+ id: data.id || messageId,
68
+ });
69
+ }
70
+ }
71
+ break;
72
+ case 'DATA_UPDATE':
73
+ {
74
+ const messageId = getAIChatMessageIdFromFragmentKey(dataFragmentKey || fragmentKey);
75
+ if (messageId && data && typeof data === 'object') {
76
+ return upsertLocalAIChatMessage(messages, {
77
+ id: messageId,
78
+ ...data,
79
+ });
80
+ }
81
+ }
82
+ break;
83
+ default:
84
+ break;
85
+ }
86
+
87
+ return messages;
88
+ }
89
+
90
+ /**
91
+ * Merge local live messages into the cached AI chat response.
92
+ */
93
+
94
+ export function mergeLocalAIChatMessages(aiChat: any, localMessages: any[]) {
95
+ if (!aiChat || !localMessages.length) {
96
+ return aiChat;
97
+ }
98
+
99
+ const localMessageMap = new Map(localMessages.map((message) => [message.id, message]));
100
+ const usedMessageIds = new Set<string>();
101
+ const messages = (aiChat.messages || []).map((message: any) => {
102
+ const localMessage = localMessageMap.get(message.id);
103
+ usedMessageIds.add(message.id);
104
+ if (!localMessage || isOlderChatCheckpoint(message, localMessage)) {
105
+ return message;
106
+ }
107
+
108
+ return {
109
+ ...message,
110
+ ...localMessage,
111
+ };
112
+ });
113
+
114
+ for (const message of localMessages) {
115
+ if (!usedMessageIds.has(message.id)) {
116
+ messages.push(message);
117
+ }
118
+ }
119
+
120
+ return {
121
+ ...aiChat,
122
+ messages,
123
+ };
124
+ }