@jsb188/graphql 1.1.11 → 1.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/LICENSE +21 -0
  2. package/audience.d.ts +205 -0
  3. package/cache/config.ts +65 -28
  4. package/cache/index.helpers.ts +96 -0
  5. package/cache/index.ts +364 -808
  6. package/cache/mounted-queries.ts +33 -0
  7. package/cache/optimistic-ui-runtime.ts +46 -0
  8. package/cache/optimistic-ui.ts +401 -0
  9. package/cache/persist.ts +107 -22
  10. package/cache/realtime-fence.ts +47 -0
  11. package/cache/realtime-live.ts +17 -0
  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} +13 -39
  16. package/client/index.ts +4 -2
  17. package/client/request.helpers.ts +14 -0
  18. package/client/request.ts +122 -232
  19. package/client/storage-asset.ts +58 -0
  20. package/gql/fragments/accountAuthFragments.ts +0 -4
  21. package/gql/fragments/agentMemoryFragments.ts +5 -1
  22. package/gql/fragments/agentNoteFragments.ts +156 -0
  23. package/gql/fragments/aiChatFragments.ts +35 -11
  24. package/gql/fragments/aiChatLinkFragments.ts +8 -0
  25. package/gql/fragments/audienceFragments.ts +76 -0
  26. package/gql/fragments/dataTableFragments.ts +48 -80
  27. package/gql/fragments/emailFragments.ts +49 -21
  28. package/gql/fragments/emailOutreachFragments.ts +281 -0
  29. package/gql/fragments/fieldDocFragments.ts +222 -40
  30. package/gql/fragments/inboundContactFragments.ts +2 -0
  31. package/gql/fragments/libraryFragments.ts +120 -0
  32. package/gql/fragments/logFragments.ts +93 -2
  33. package/gql/fragments/organizationFragments.ts +12 -0
  34. package/gql/fragments/qrCodeFragments.ts +29 -0
  35. package/gql/fragments/scheduleFragments.ts +574 -145
  36. package/gql/fragments/sheetFragments.ts +86 -424
  37. package/gql/fragments/storageFragments.ts +25 -1
  38. package/gql/fragments/workWaitFragments.ts +13 -0
  39. package/gql/fragments/workflowFragments.ts +32 -4
  40. package/gql/mutations/agentMemoryMutations.ts +32 -0
  41. package/gql/mutations/agentNoteMutations.ts +64 -0
  42. package/gql/mutations/aiChatLinkMutations.ts +13 -0
  43. package/gql/mutations/aiChatMutations.ts +34 -4
  44. package/gql/mutations/audienceMutations.ts +58 -0
  45. package/gql/mutations/authMutations.ts +24 -28
  46. package/gql/mutations/billingMutations.ts +24 -0
  47. package/gql/mutations/contactMutations.ts +23 -0
  48. package/gql/mutations/dataTableMutations.ts +18 -75
  49. package/gql/mutations/emailMutations.ts +22 -0
  50. package/gql/mutations/emailOutreachMutations.ts +139 -0
  51. package/gql/mutations/fieldDocMutations.ts +162 -13
  52. package/gql/mutations/index.ts +10 -5
  53. package/gql/mutations/organizationMutations.ts +6 -0
  54. package/gql/mutations/qrCodeMutations.ts +20 -0
  55. package/gql/mutations/scheduleMutations.ts +389 -417
  56. package/gql/mutations/sheetMutations.ts +62 -118
  57. package/gql/mutations/storageMutations.ts +1 -1
  58. package/gql/mutations/workflowMutations.ts +94 -0
  59. package/gql/queries/agentMemoryQueries.ts +12 -2
  60. package/gql/queries/agentNoteQueries.ts +86 -0
  61. package/gql/queries/aiChatQueries.ts +63 -12
  62. package/gql/queries/audienceQueries.ts +104 -0
  63. package/gql/queries/authQueries.ts +20 -4
  64. package/gql/queries/billingQueries.ts +114 -9
  65. package/gql/queries/dataTableQueries.ts +43 -75
  66. package/gql/queries/emailOutreachQueries.ts +282 -0
  67. package/gql/queries/emailQueries.ts +48 -64
  68. package/gql/queries/emailReplyReportQueries.ts +127 -0
  69. package/gql/queries/fieldDocQueries.ts +128 -98
  70. package/gql/queries/inboundContactQueries.ts +15 -4
  71. package/gql/queries/index.ts +5 -3
  72. package/gql/queries/libraryQueries.ts +112 -0
  73. package/gql/queries/logQueries.ts +86 -12
  74. package/gql/queries/organizationQueries.ts +44 -12
  75. package/gql/queries/qrCodeQueries.ts +27 -0
  76. package/gql/queries/scheduleQueries.ts +401 -278
  77. package/gql/queries/sheetQueries.ts +94 -165
  78. package/gql/queries/storageQueries.ts +11 -4
  79. package/gql/queries/workflowQueries.ts +61 -12
  80. package/gql/reactivity.ts +98 -0
  81. package/gql/recordReads.ts +171 -0
  82. package/hooks/index.helpers.ts +52 -0
  83. package/hooks/index.ts +920 -715
  84. package/hooks/use-agentMemory-mtn.ts +29 -31
  85. package/hooks/use-agentMemory-qry.ts +15 -3
  86. package/hooks/use-agentNote-mtn.ts +89 -0
  87. package/hooks/use-agentNote-qry.ts +162 -0
  88. package/hooks/use-agentNote-recovery.helpers.ts +58 -0
  89. package/hooks/use-agentNote-recovery.ts +57 -0
  90. package/hooks/use-aiChat-mtn.ts +104 -115
  91. package/hooks/use-aiChat-qry.helpers.ts +124 -0
  92. package/hooks/use-aiChat-qry.ts +254 -387
  93. package/hooks/use-aiChat-stream-mtn.ts +14 -0
  94. package/hooks/use-audience-mtn.ts +170 -0
  95. package/hooks/use-audience-qry.helpers.ts +39 -0
  96. package/hooks/use-audience-qry.ts +245 -0
  97. package/hooks/use-auth-mtn.ts +30 -1
  98. package/hooks/use-billing-mtn.ts +31 -0
  99. package/hooks/use-billing-qry.ts +76 -0
  100. package/hooks/use-dataTable-mtn.ts +23 -115
  101. package/hooks/use-dataTable-qry.ts +69 -914
  102. package/hooks/use-email-mtn.ts +26 -0
  103. package/hooks/use-email-qry.helpers.ts +37 -0
  104. package/hooks/use-email-qry.ts +44 -174
  105. package/hooks/use-emailOutreach-mtn.ts +211 -0
  106. package/hooks/use-emailOutreach-qry.helpers.ts +25 -0
  107. package/hooks/use-emailOutreach-qry.ts +367 -0
  108. package/hooks/use-emailOutreachReplyReport-qry.ts +46 -0
  109. package/hooks/use-fieldDoc-mtn.ts +244 -32
  110. package/hooks/use-fieldDoc-qry.helpers.ts +49 -0
  111. package/hooks/use-fieldDoc-qry.ts +134 -102
  112. package/hooks/use-inboundContact-qry.ts +7 -9
  113. package/hooks/use-library-qry.ts +233 -0
  114. package/hooks/use-log-mtn.ts +25 -12
  115. package/hooks/use-log-qry.ts +99 -46
  116. package/hooks/use-organization-qry.ts +16 -60
  117. package/hooks/use-qrCode-mtn.ts +40 -0
  118. package/hooks/use-qrCode-qry.ts +78 -0
  119. package/hooks/use-schedule-mtn.ts +231 -348
  120. package/hooks/use-schedule-qry.ts +208 -139
  121. package/hooks/use-schedule-reactive.ts +218 -0
  122. package/hooks/use-sheet-mtn.ts +91 -199
  123. package/hooks/use-sheet-qry.ts +88 -237
  124. package/hooks/use-storage-qry.ts +84 -61
  125. package/hooks/use-workflow-mtn.ts +84 -23
  126. package/hooks/use-workflow-qry.ts +60 -61
  127. package/libs/ai-chat-link-events.ts +78 -0
  128. package/libs/ai-chat-outgoing.helpers.ts +153 -0
  129. package/libs/ai-chat-outgoing.ts +11 -0
  130. package/libs/ai-chat-outgoing.types.ts +25 -0
  131. package/libs/ai-chat-run-realtime.ts +20 -0
  132. package/libs/ai-chat-submission-realtime.ts +150 -0
  133. package/libs/data-changes.helpers.ts +161 -0
  134. package/libs/data-changes.ts +382 -0
  135. package/libs/fragment-realtime-sequence.ts +55 -0
  136. package/libs/open-sheet.ts +138 -0
  137. package/libs/record-read.ts +327 -0
  138. package/libs/sheet-command-batch.ts +45 -0
  139. package/libs/sheet-realtime-packet.ts +53 -0
  140. package/libs/sheet-view-realtime-router.ts +99 -0
  141. package/loaders/emailPreference.ts +69 -0
  142. package/loaders/rest.ts +12 -0
  143. package/package.json +77 -25
  144. package/schedule.d.ts +1183 -0
  145. package/sse.helpers.ts +19 -0
  146. package/sse.ts +26 -115
  147. package/types.d.ts +48 -25
  148. package/cache/index.test.ts +0 -881
  149. package/client/data-table-realtime-subscriptions.test.ts +0 -740
  150. package/client/data-table-realtime-subscriptions.ts +0 -955
  151. package/client/data-table-realtime.test.ts +0 -792
  152. package/client/data-table-realtime.ts +0 -1218
  153. package/client/fragment-realtime-sequence.ts +0 -52
  154. package/client/open-sheet.ts +0 -137
  155. package/client/request-managed-session.test.ts +0 -574
  156. package/client/request-no-store.test.ts +0 -157
  157. package/client/sse-ticket.test.ts +0 -26
  158. package/deno.lock +0 -170
  159. package/deno.test.json +0 -10
  160. package/gql/fragments/agentDocFragments.ts +0 -46
  161. package/gql/fragments/billingFragments.ts +0 -14
  162. package/gql/fragments/campaignFragments.ts +0 -277
  163. package/gql/mutations/agentDocMutations.ts +0 -177
  164. package/gql/mutations/campaignMutations.ts +0 -215
  165. package/gql/queries/agentDocQueries.ts +0 -120
  166. package/gql/queries/appQueries.ts +0 -14
  167. package/gql/queries/campaignQueries.ts +0 -127
  168. package/hooks/use-agentDoc-mtn.ts +0 -285
  169. package/hooks/use-agentDoc-qry.ts +0 -208
  170. package/hooks/use-app-qry.ts +0 -22
  171. package/hooks/use-campaign-mtn.ts +0 -377
  172. package/hooks/use-campaign-qry.ts +0 -257
  173. package/loaders/campaign.ts +0 -137
  174. package/tsconfig.json +0 -13
@@ -1,15 +1,9 @@
1
- import {
2
- FRAGMENT_NAMES,
3
- makeFragmentKey,
4
- } from '@jsb188/mday/constants/graphqlReactivity.ts';
5
- import { useOpenModalPopUp } from '@jsb188/react/states';
1
+ import { setAIChatLinkHiddenMtn } from '../gql/mutations/aiChatLinkMutations.ts';
2
+ import { FRAGMENT_NAMES, makeFragmentKey } from '@jsb188/mday/constants/graphqlReactivity.ts';
3
+ import { type OpenModalPopUpFn, useOpenModalPopUp } from '@jsb188/react/states';
6
4
  import { useCallback, useEffect, useRef } from 'react';
7
- import {
8
- loadFragment,
9
- resetQuery,
10
- updateFragment,
11
- updateQuery,
12
- } from '../cache/index.ts';
5
+ import { normalizeServerError } from '@jsb188/app/utils/api.ts';
6
+ import { loadFragment, resetQuery, updateFragment, updateQuery } from '../cache/index.ts';
13
7
  import { type GraphQLMutationFn, useMutation } from '../client/index.ts';
14
8
  import {
15
9
  deleteAIChatMtn,
@@ -18,34 +12,27 @@ import {
18
12
  startAIChatMtn,
19
13
  stopAIChatMessageMtn,
20
14
  } from '../gql/mutations/aiChatMutations.ts';
21
- import type { UseMutationParams } from '../types.d.ts';
22
- import { updateAIChats } from './use-aiChat-qry.ts';
15
+ import type { UseMutationParams, UseMutationParamsExtra } from '../types.d.ts';
16
+ import { acceptAIChatOutgoingMessage, failAIChatOutgoingMessage } from '../libs/ai-chat-outgoing.ts';
23
17
 
24
18
  /**
25
19
  * Start AI chat
26
20
  */
27
21
 
28
- export function useStartAIChat(params: UseMutationParams = {}) {
29
- const { onCompleted, onError } = params;
30
- const openModalPopUp = useOpenModalPopUp();
22
+ export function useStartAIChat(params: UseMutationParamsExtra = {}, openModalPopUp?: OpenModalPopUpFn) {
23
+ const { onCompleted, onError, ...rest } = params;
31
24
 
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
- );
25
+ const [startAIChat, mtnValues, mtnHandlers] = useMutation(startAIChatMtn, {
26
+ ...rest,
27
+ openModalPopUp,
28
+ onCompleted,
29
+ onError,
30
+ });
45
31
 
46
32
  return {
47
33
  startAIChat,
48
34
  ...mtnValues,
35
+ ...mtnHandlers,
49
36
  };
50
37
  }
51
38
 
@@ -57,14 +44,11 @@ export function useEditAIChat(params: UseMutationParams = {}) {
57
44
  const { onCompleted, onError } = params;
58
45
  const openModalPopUp = useOpenModalPopUp();
59
46
 
60
- const [mutateAIChat, mtnValues, mtnHandlers, updateObservers] = useMutation(
61
- editAIChatMtn,
62
- {
63
- openModalPopUp,
64
- onCompleted,
65
- onError,
66
- },
67
- );
47
+ const [mutateAIChat, mtnValues, mtnHandlers, updateObservers] = useMutation(editAIChatMtn, {
48
+ openModalPopUp,
49
+ onCompleted,
50
+ onError,
51
+ });
68
52
 
69
53
  /*
70
54
  * Optimistically write a submitted summary to its fragment and roll it back
@@ -85,7 +69,6 @@ export function useEditAIChat(params: UseMutationParams = {}) {
85
69
  fragmentKey,
86
70
  {
87
71
  summary: nextSummary,
88
- userManagedSummary: true,
89
72
  },
90
73
  null,
91
74
  false,
@@ -100,9 +83,8 @@ export function useEditAIChat(params: UseMutationParams = {}) {
100
83
  (currentFragment: any) =>
101
84
  currentFragment?.summary === nextSummary
102
85
  ? {
103
- summary: previousFragment.summary,
104
- userManagedSummary: previousFragment.userManagedSummary,
105
- }
86
+ summary: previousFragment.summary,
87
+ }
106
88
  : {},
107
89
  null,
108
90
  false,
@@ -126,70 +108,79 @@ export function useEditAIChat(params: UseMutationParams = {}) {
126
108
  * Send a new message to AI Chat
127
109
  */
128
110
 
129
- export function useAIChatTextarea(
130
- variablesKey: string,
131
- params: UseMutationParams = {},
132
- ) {
111
+ export function useAIChatTextarea(variablesKey: string, params: UseMutationParams = {}) {
133
112
  const { onCompleted, onError } = params;
134
113
  const didSendRef = useRef(false);
135
114
  const openModalPopUp = useOpenModalPopUp();
136
115
 
137
116
  // Send AI chat message
138
117
 
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
- }
118
+ const [mutateAIChatMessage, mtnValues1, sendHandlers, updateObservers] = useMutation(sendAIChatMessageMtn, {
119
+ onCompleted: (data: any, err: any, variables: any) => {
120
+ if (data.sendAIChatMessage?.node?.id) {
121
+ acceptAIChatOutgoingMessage(variables.aiChatId, variables.clientRequestId, data.sendAIChatMessage.node);
122
+ }
123
+
124
+ onCompleted?.(data, err, variables);
125
+
126
+ const aiChatId = variables.aiChatId;
127
+ const messageId = data.sendAIChatMessage?.node?.id;
128
+
129
+ if (messageId && aiChatId && variablesKey) {
130
+ const fragmentKey = makeFragmentKey(FRAGMENT_NAMES.aiChatMessage, messageId);
131
+
132
+ updateQuery(
133
+ `#aiChat:${variablesKey}`,
134
+ (currentData: any) => {
135
+ const currentList = currentData?.messages?.data;
136
+
137
+ // The updater receives the stored references by reference, so the
138
+ // new message must be appended into fresh objects; mutating them
139
+ // in place leaves the version stamp (and the persisted snapshot)
140
+ // unchanged, which drops the sent message on the next page load.
141
+ if (!Array.isArray(currentList) || currentList.some((item: any) => item?.[0] === fragmentKey)) {
142
+ return currentData;
143
+ }
144
+
145
+ return {
146
+ ...currentData,
147
+ messages: {
148
+ ...currentData.messages,
149
+ data: [...currentList, [fragmentKey]],
150
+ },
151
+ };
152
+ },
153
+ false,
154
+ updateObservers,
155
+ );
156
+ } else if (data && !err) {
157
+ console.dev(`Unknown error: {${messageId ? 'aiChatId' : 'messageId'}} was not found.`, 'warning');
158
+ }
159
+ },
160
+ onError: (error, variables) => {
161
+ failAIChatOutgoingMessage(variables?.aiChatId, variables?.clientRequestId, error);
162
+ onError?.(error, variables);
163
+ },
164
+ });
172
165
 
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
- );
166
+ /* Mutations can abort without callbacks; preserve those outgoing payloads for retry too. */
167
+ const sendAIChatMessage = useCallback<GraphQLMutationFn>(
168
+ async (options, triedCount) => {
169
+ didSendRef.current = true;
170
+ try {
171
+ const result = await mutateAIChatMessage(options, triedCount);
172
+ if (result?.aborted || (!result?.sendAIChatMessage?.node?.id && !result?.error)) {
173
+ failAIChatOutgoingMessage(options?.variables?.aiChatId, options?.variables?.clientRequestId);
189
174
  }
190
- },
191
- onError,
175
+ return result;
176
+ } catch (error) {
177
+ const serverError = normalizeServerError(error);
178
+ sendHandlers.setSaving(false);
179
+ failAIChatOutgoingMessage(options?.variables?.aiChatId, options?.variables?.clientRequestId, serverError);
180
+ return { error: serverError };
181
+ }
192
182
  },
183
+ [mutateAIChatMessage],
193
184
  );
194
185
 
195
186
  // Stop AI chat message
@@ -207,12 +198,13 @@ export function useAIChatTextarea(
207
198
  // as a result of the SSE pipe breaking at unmount.
208
199
 
209
200
  useEffect(() => {
201
+ didSendRef.current = false;
210
202
  return () => {
211
203
  if (didSendRef.current) {
212
204
  resetQuery(`#aiChat:${variablesKey}`, true, updateObservers);
213
205
  }
214
206
  };
215
- }, []);
207
+ }, [variablesKey]);
216
208
 
217
209
  return {
218
210
  send: {
@@ -234,26 +226,17 @@ export function useDeleteAIChat(params: UseMutationParams = {}) {
234
226
  const { onCompleted, onError } = params;
235
227
  const openModalPopUp = useOpenModalPopUp();
236
228
 
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
- }
229
+ const [deleteAIChat, mtnValues, mtnHandlers, updateObservers] = useMutation(deleteAIChatMtn, {
230
+ openModalPopUp,
231
+ onCompleted: (data: any, err: any, variables: any) => {
232
+ if (data?.deleteAIChat) {
233
+ updateFragment(makeFragmentKey(FRAGMENT_NAMES.aiChat, variables.aiChatId), { __deleted: true }, null, false, updateObservers);
234
+ }
251
235
 
252
- onCompleted?.(data, err, variables);
253
- },
254
- onError,
236
+ onCompleted?.(data, err, variables);
255
237
  },
256
- );
238
+ onError,
239
+ });
257
240
 
258
241
  return {
259
242
  deleteAIChat,
@@ -261,3 +244,9 @@ export function useDeleteAIChat(params: UseMutationParams = {}) {
261
244
  ...mtnHandlers,
262
245
  };
263
246
  }
247
+
248
+ /* Hide or restore only the current chat's membership row; server reactivity owns list reconciliation. */
249
+ export function useSetAIChatLinkHidden(params: UseMutationParamsExtra = {}) {
250
+ const [setAIChatLinkHidden, values, handlers] = useMutation(setAIChatLinkHiddenMtn, params);
251
+ return { setAIChatLinkHidden, ...values, ...handlers };
252
+ }
@@ -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
+ }