@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,30 +1,24 @@
1
+ import { cacheAIChatRunUpdate } from '../libs/ai-chat-run-realtime.ts';
2
+ import type { AIChatLink } from '@jsb188/mday/types/linkedEntity.d.ts';
3
+ import type { AIChatRunData } from '@jsb188/app/types/ai.d.ts';
4
+ import { mergeAIChatRuns } from '@jsb188/mday/utils/aiChatWork.ts';
5
+ import { upsertLocalAIChatMessage, mergeSSEPayloadToLocalAIChatMessages, mergeLocalAIChatMessages } from './use-aiChat-qry.helpers.ts';
6
+ import { useResumeAIChatStream } from './use-aiChat-stream-mtn.ts';
1
7
  import { getENVVariable } from '@jsb188/app';
2
- import { makeVariablesKey } from '@jsb188/app/utils/logic.ts';
8
+ import { FRAGMENT_NAMES, getFragmentBaseName, makeFragmentKey } from '@jsb188/mday/constants/graphqlReactivity.ts';
3
9
  import SSE from '@jsb188/sse';
10
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
11
+ import { loadFragment, resetQuery, updateQuery } from '../cache/index.ts';
12
+ import { useQuery, useReactiveFragment, useReactiveFragmentMap } from '../client/index.ts';
13
+ import { aiChatLinksQry, aiChatMessagesQry, aiChatWorkMessagesQry, aiChatQry, aiChatsQry } from '../gql/queries/aiChatQueries.ts';
4
14
  import {
5
- FRAGMENT_NAMES,
6
- getFragmentBaseName,
7
- makeFragmentKey,
8
- } from '@jsb188/mday/constants/graphqlReactivity.ts';
9
- import { useCallback, useEffect, useMemo, useState } from 'react';
10
- import {
11
- loadFragment,
12
- loadQuery,
13
- resetQuery,
14
- updateQuery,
15
- } from '../cache/index.ts';
16
- import {
17
- useQuery,
18
- useReactiveFragment,
19
- useReactiveFragmentMap,
20
- } from '../client/index.ts';
21
- import {
22
- aiChatMessagesQry,
23
- aiChatQry,
24
- aiChatsQry,
25
- } from '../gql/queries/aiChatQueries.ts';
26
- import handleSSEData, { type PublishPayload } from '../sse.ts';
27
- import type { UpdateObserversFn, UseQueryParams } from '../types.d.ts';
15
+ clearAIChatSubmission,
16
+ finishAIChatGeneration,
17
+ startAIChatGeneration,
18
+ subscribeToAIChatSubmission,
19
+ } from '../libs/ai-chat-submission-realtime.ts';
20
+ import handleSSEData, { isStaleSSECheckpoint, type PublishPayload } from '../sse.ts';
21
+ import type { UseQueryParams } from '../types.d.ts';
28
22
 
29
23
  /**
30
24
  * Constants
@@ -33,286 +27,175 @@ import type { UpdateObserversFn, UseQueryParams } from '../types.d.ts';
33
27
  const AI_CHATS_LIMIT = 70; // Must match server code exactly
34
28
  const AI_CHAT_MESSAGES_LIMIT = 55; // Must match server code exactly
35
29
 
36
- /**
37
- * Helper; build AI chats query key
38
- */
39
-
40
- function getAIChatsQueryKey(
41
- organizationId?: string | null,
42
- filter?: 'CAL_DATE' | 'CHATS' | 'ARCHIVED',
43
- ) {
44
- if (!filter || (filter !== 'CAL_DATE' && !organizationId)) {
45
- return '';
46
- }
47
-
48
- const variablesKey = makeVariablesKey({
49
- organizationId: filter === 'CAL_DATE' ? null : organizationId,
50
- filter,
51
- cursor: null,
52
- after: false,
53
- limit: AI_CHATS_LIMIT,
54
- });
55
-
56
- return `#aiChats:${variablesKey}`;
57
- }
30
+ type AIChatLiveStatus = { phase: 'IDLE' } | { phase: 'SERVER_LOADING' } | { fragmentId: string; phase: 'GENERATING' };
58
31
 
59
32
  /**
60
- * Helper; get generating (status) key from SSE data
33
+ * Helper; get the streaming message key from one SSE checkpoint, null when that
34
+ * message finished, or undefined when the event is not a message checkpoint.
61
35
  */
62
36
 
63
37
  function getGeneratingFragmentId(sseData: PublishPayload) {
64
- const { __type, dataFragmentKey, fragmentKey, fragmentNamespace, data } =
65
- sseData;
66
- const finished = data?.finished;
67
-
68
- if (__type === 'CONNECTED') {
69
- return null;
38
+ const key = sseData.dataFragmentKey || sseData.fragmentKey;
39
+ const finished = sseData.data?.finished;
40
+ if (!key?.startsWith(FRAGMENT_NAMES.aiChatMessage + ':') || typeof finished !== 'boolean') {
41
+ return undefined;
70
42
  }
71
43
 
72
- const fragmentName = FRAGMENT_NAMES.aiChatMessage + ':';
73
-
74
- if (typeof finished === 'boolean') {
75
- if (dataFragmentKey?.startsWith(fragmentName)) {
76
- return finished ? null : dataFragmentKey;
77
- } else if (fragmentKey?.startsWith(fragmentName)) {
78
- return finished ? null : fragmentKey;
79
- }
80
- } else if (
81
- fragmentKey?.startsWith(fragmentName) &&
82
- fragmentNamespace === 'text'
83
- ) {
84
- return fragmentKey;
85
- }
44
+ return finished ? null : key;
86
45
  }
87
46
 
88
- /**
89
- * Return the message id from an AI chat message fragment key.
90
- */
91
-
92
- function getAIChatMessageIdFromFragmentKey(fragmentKey?: string | null) {
93
- const fragmentName = FRAGMENT_NAMES.aiChatMessage + ':';
94
- return fragmentKey?.startsWith(fragmentName)
95
- ? fragmentKey.substring(fragmentName.length)
96
- : null;
47
+ /* Fetch transcript details independently from sidebar membership so link resets cannot replace streaming messages. */
48
+ function useAIChatQuery(aiChatId?: string | null, params: UseQueryParams = {}) {
49
+ return useQuery(aiChatQry, {
50
+ variables: {
51
+ aiChatId,
52
+ includeWork: false,
53
+ },
54
+ skip: !aiChatId,
55
+ persistTime: 20 * 60 * 1000,
56
+ ...params,
57
+ });
97
58
  }
98
59
 
99
60
  /**
100
- * Merge one message into a local live message list.
61
+ * Fetch AI chat and stream subsequent message updates.
101
62
  */
63
+ export function useAIChatWithSSE(aiChatId?: string, initialSessionKey?: string | null, params: UseQueryParams = {}) {
64
+ const { data, ...rest } = useAIChatQuery(aiChatId, params);
102
65
 
103
- function upsertLocalAIChatMessage(
104
- messages: any[],
105
- message: any,
106
- prepend?: boolean,
107
- ) {
108
- if (!message?.id) {
109
- return messages;
110
- }
111
-
112
- const index = messages.findIndex((item) => item?.id === message.id);
113
- if (index >= 0) {
114
- const nextMessages = messages.slice(0);
115
- nextMessages[index] = {
116
- ...nextMessages[index],
117
- ...message,
118
- };
119
- return nextMessages;
66
+ const { updateObservers, variablesKey } = rest;
67
+ const [session, setSession] = useState({
68
+ aiChatId,
69
+ key: initialSessionKey || null,
70
+ inProgress: initialSessionKey ? true : (null as boolean | null),
71
+ });
72
+ const sessionKey = session.aiChatId === aiChatId ? session.key : null;
73
+ const sessionEpoch = useRef(0);
74
+ const activeChatRef = useRef(aiChatId);
75
+ if (activeChatRef.current !== aiChatId) {
76
+ activeChatRef.current = aiChatId;
77
+ sessionEpoch.current++;
120
78
  }
79
+ const [resumeTick, setResumeTick] = useState(0);
80
+ const [liveStatus, setLiveStatus] = useState<AIChatLiveStatus>({
81
+ phase: 'IDLE',
82
+ });
83
+ const [localMessages, setLocalMessages] = useState<any[]>([]);
84
+ const [liveRuns, setLiveRuns] = useState<{ chatId?: string; runs: Record<string, AIChatRunData> }>({ chatId: aiChatId, runs: {} });
85
+ const baseAIChat = data?.aiChat || (aiChatId ? loadFragment(makeFragmentKey(FRAGMENT_NAMES.aiChat, aiChatId)) : null);
86
+ const aiChat = useReactiveAIChatFragment(aiChatId, baseAIChat, rest.updatedCount);
87
+ const mergedAIChat = useMemo(() => mergeLocalAIChatMessages(aiChat, localMessages), [aiChat, localMessages]);
88
+ const runs = useMemo(
89
+ () =>
90
+ mergeAIChatRuns(
91
+ mergeAIChatRuns({}, [
92
+ aiChat?.latestRun,
93
+ ...(aiChat?.messages || []).map((message: any) => message.run),
94
+ ...(mergedAIChat?.messages || []).map((message: any) => message.run),
95
+ ]),
96
+ Object.values(liveRuns.chatId === aiChatId ? liveRuns.runs : {}),
97
+ ),
98
+ [aiChatId, aiChat?.latestRun, aiChat?.messages, mergedAIChat?.messages, liveRuns],
99
+ );
100
+ const dataAIChatId = aiChat?.id;
101
+ const resumeAttempts = useRef(0);
102
+ const { resumeAIChatStream } = useResumeAIChatStream();
103
+ // A delayed HTTP response can retain an old chat flag after the run settled.
104
+ const runInProgress =
105
+ session.aiChatId === aiChatId && session.inProgress !== null
106
+ ? session.inProgress
107
+ : (runs[aiChat?.latestRun?.id]?.inProgress ?? aiChat?.inProgress);
121
108
 
122
- return prepend ? [message, ...messages] : [...messages, message];
123
- }
124
-
125
- /**
126
- * Merge SSE payloads into local live AI chat messages.
127
- */
109
+ /*
110
+ * Reset connection retry state when the hook starts observing another chat.
111
+ */
112
+ useEffect(() => {
113
+ setLocalMessages([]);
114
+ resumeAttempts.current = 0;
115
+ }, [aiChatId]);
128
116
 
129
- function mergeSSEPayloadToLocalAIChatMessages(
130
- messages: any[],
131
- sseData: PublishPayload,
132
- ) {
133
- const {
134
- __type,
135
- data,
136
- dataFragmentKey,
137
- fragmentKey,
138
- fragmentNamespace,
139
- otherData,
140
- } = sseData;
141
-
142
- switch (__type) {
143
- case 'QUERY_APPEND':
144
- case 'QUERY_PREPEND':
145
- {
146
- const messageId = getAIChatMessageIdFromFragmentKey(dataFragmentKey);
147
- if (messageId && data && typeof data === 'object') {
148
- return upsertLocalAIChatMessage(
149
- messages,
150
- {
151
- ...data,
152
- id: data.id || messageId,
153
- },
154
- __type === 'QUERY_PREPEND',
155
- );
156
- }
157
- }
158
- break;
159
- case 'DATA_APPEND':
160
- case 'DATA_PREPEND':
161
- {
162
- const messageId = getAIChatMessageIdFromFragmentKey(fragmentKey);
163
- if (messageId && fragmentNamespace === 'text') {
164
- const index = messages.findIndex((item) => item?.id === messageId);
165
- const currentMessage =
166
- index >= 0
167
- ? messages[index]
168
- : {
169
- id: messageId,
170
- accountId: null,
171
- type: 'NORMAL',
172
- cursor: null,
173
- text: '',
174
- finished: false,
175
- at: new Date().toISOString(),
176
- };
177
- const currentText = currentMessage.text || '';
178
- const nextText =
179
- __type === 'DATA_PREPEND'
180
- ? `${data || ''}${currentText}`
181
- : `${currentText}${data || ''}`;
182
-
183
- return upsertLocalAIChatMessage(messages, {
184
- ...currentMessage,
185
- ...(otherData && typeof otherData === 'object' ? otherData : {}),
186
- text: nextText,
187
- });
188
- }
117
+ /*
118
+ * Resume an existing run with a fresh single-use ticket. Failed ticket requests
119
+ * retry with bounded backoff, and superseded requests cannot replace a new send.
120
+ */
121
+ useEffect(() => {
122
+ if (!dataAIChatId || dataAIChatId !== aiChatId || !runInProgress || sessionKey || resumeAttempts.current >= 3) return;
123
+ const epoch = sessionEpoch.current;
124
+ let disposed = false;
125
+ let timer: ReturnType<typeof setTimeout> | undefined;
126
+ resumeAttempts.current++;
127
+ /*
128
+ * Schedule another ticket request only while this chat still owns the attempt.
129
+ */
130
+ const retry = () => {
131
+ if (!disposed && epoch === sessionEpoch.current && resumeAttempts.current < 3) {
132
+ timer = setTimeout(() => setResumeTick((value) => value + 1), 1000 * resumeAttempts.current);
189
133
  }
190
- break;
191
- case 'DATA_UPDATE':
192
- {
193
- const messageId = getAIChatMessageIdFromFragmentKey(
194
- dataFragmentKey || fragmentKey,
195
- );
196
- if (messageId && data && typeof data === 'object') {
197
- return upsertLocalAIChatMessage(messages, {
198
- id: messageId,
199
- ...data,
134
+ };
135
+ resumeAIChatStream({ variables: { aiChatId: dataAIChatId } })
136
+ .then((result: any) => {
137
+ if (disposed || epoch !== sessionEpoch.current) return;
138
+ if (result?.resumeAIChatStream) {
139
+ setSession({
140
+ aiChatId: dataAIChatId,
141
+ key: result.resumeAIChatStream,
142
+ inProgress: true,
200
143
  });
144
+ } else if (result?.error || result?.aborted) {
145
+ retry();
201
146
  }
202
- }
203
- break;
204
- default:
205
- break;
206
- }
207
-
208
- return messages;
209
- }
210
-
211
- /**
212
- * Merge local live messages into the cached AI chat response.
213
- */
214
-
215
- function mergeLocalAIChatMessages(aiChat: any, localMessages: any[]) {
216
- if (!aiChat || !localMessages.length) {
217
- return aiChat;
218
- }
219
-
220
- const localMessageMap = new Map(
221
- localMessages.map((message) => [message.id, message]),
222
- );
223
- const usedMessageIds = new Set<string>();
224
- const messages = (aiChat.messages || []).map((message: any) => {
225
- const localMessage = localMessageMap.get(message.id);
226
- if (!localMessage) {
227
- return message;
228
- }
229
-
230
- usedMessageIds.add(message.id);
231
- return {
232
- ...message,
233
- ...localMessage,
147
+ })
148
+ .catch(retry);
149
+ return () => {
150
+ disposed = true;
151
+ clearTimeout(timer);
234
152
  };
235
- });
236
-
237
- for (const message of localMessages) {
238
- if (!usedMessageIds.has(message.id)) {
239
- messages.push(message);
240
- }
241
- }
242
-
243
- return {
244
- ...aiChat,
245
- messages,
246
- };
247
- }
248
-
249
- /**
250
- * Fetch AI chat
251
- */
252
-
253
- export function useAIChatWithSSE(
254
- aiChatId?: string,
255
- initialSessionKey?: string | null,
256
- params: UseQueryParams = {},
257
- ) {
258
- const { data, ...rest } = useQuery(aiChatQry, {
259
- variables: {
260
- aiChatId,
153
+ }, [aiChatId, dataAIChatId, runInProgress, sessionKey, resumeTick]);
154
+
155
+ const generatingFragmentId = liveStatus.phase === 'GENERATING' ? liveStatus.fragmentId : null;
156
+ const waitingForGeneration = liveStatus.phase === 'SERVER_LOADING';
157
+ // A run stays active between its rows (tool calls, the next model step) until
158
+ // CHAT_RUN_STATUS closes the subscription
159
+ const generating = !!runInProgress || !!sessionKey || !!generatingFragmentId;
160
+
161
+ /* Ignore delayed submission callbacks after this hook starts displaying a different chat. */
162
+ const addLocalMessage = useCallback(
163
+ (message: any) => {
164
+ if (activeChatRef.current !== aiChatId) return;
165
+ setLocalMessages((prevMessages) => upsertLocalAIChatMessage(prevMessages, message));
261
166
  },
262
- skip: !aiChatId,
263
- persistTime: 20 * 60 * 1000,
264
- ...params,
265
- });
266
-
267
- const { updateObservers, variablesKey } = rest;
268
- const [sessionKey, setSessionKey] = useState<string | null>(
269
- initialSessionKey || null,
167
+ [aiChatId],
270
168
  );
271
- const [generatingFragmentId, setGeneratingFragmentId] = useState<
272
- string | null
273
- >(null);
274
- const [localMessages, setLocalMessages] = useState<any[]>([]);
275
- const baseAIChat =
276
- data?.aiChat ||
277
- (aiChatId
278
- ? loadFragment(makeFragmentKey(FRAGMENT_NAMES.aiChat, aiChatId))
279
- : null);
280
- const aiChat = useReactiveAIChatFragment(aiChatId, baseAIChat);
281
- const mergedAIChat = useMemo(
282
- () => mergeLocalAIChatMessages(aiChat, localMessages),
283
- [aiChat, localMessages],
284
- );
285
- const dataAIChatId = aiChat?.id;
286
-
287
- const addLocalMessage = useCallback((message: any) => {
288
- setLocalMessages((prevMessages) =>
289
- upsertLocalAIChatMessage(prevMessages, message),
290
- );
291
- }, []);
292
169
 
293
170
  /*
294
- * Switch to a newly issued SSE session and hide the assistant draft superseded by that send.
171
+ * Switch to a newly issued SSE session. Superseded drafts stay visible as
172
+ * incomplete, matching the persisted transcript after reload.
295
173
  */
296
174
  const activateAIChatSession = useCallback(
297
175
  (nextSessionKey: string) => {
298
- const supersededMessageId =
299
- getAIChatMessageIdFromFragmentKey(generatingFragmentId);
300
- if (supersededMessageId) {
301
- setLocalMessages((prevMessages) =>
302
- upsertLocalAIChatMessage(prevMessages, {
303
- id: supersededMessageId,
304
- deleted: true,
305
- finished: true,
306
- }),
307
- );
308
- }
309
- setSessionKey(nextSessionKey);
176
+ if (activeChatRef.current !== aiChatId) return;
177
+ sessionEpoch.current++;
178
+ resumeAttempts.current = 0;
179
+ setSession({ aiChatId, key: nextSessionKey, inProgress: true });
180
+ // Refresh cancelled predecessors after switching away from their stream.
181
+ rest.refetch?.();
310
182
  },
311
- [generatingFragmentId],
183
+ [aiChatId, rest.refetch],
312
184
  );
313
185
 
314
186
  useEffect(() => {
315
- setLocalMessages([]);
187
+ setLiveStatus({ phase: 'IDLE' });
188
+ if (dataAIChatId) {
189
+ return subscribeToAIChatSubmission(dataAIChatId, (waiting) => {
190
+ setLiveStatus((currentStatus) => {
191
+ if (currentStatus.phase === 'GENERATING') {
192
+ return currentStatus;
193
+ }
194
+
195
+ return waiting ? { phase: 'SERVER_LOADING' } : { phase: 'IDLE' };
196
+ });
197
+ });
198
+ }
316
199
  }, [dataAIChatId]);
317
200
 
318
201
  useEffect(() => {
@@ -320,82 +203,86 @@ export function useAIChatWithSSE(
320
203
  // that make it unreliable to use perpetual SSE in production.
321
204
  // So we have to write the logic to make it work without perpetual session.
322
205
 
323
- if (dataAIChatId && sessionKey) {
206
+ if (dataAIChatId && dataAIChatId === aiChatId && sessionKey) {
324
207
  // Only listen to events if data is loaded
325
208
  const connection = new SSE({
326
209
  host: getENVVariable('SSE_SERVER') as string,
327
210
  path: `page_events/ai_chat/${dataAIChatId}`,
328
- // path: 'test-sse',
329
211
  searchParams: {
330
212
  session_key: sessionKey,
331
213
  variablesKey,
332
214
  },
333
215
  });
334
216
 
217
+ let disposed = false;
218
+ const epoch = sessionEpoch.current;
335
219
  const connectParams = {
336
220
  onMessage: (sseData: PublishPayload) => {
221
+ if (disposed || epoch !== sessionEpoch.current || isStaleSSECheckpoint(sseData)) return;
222
+ // A connection that delivers run data has succeeded; later drops get a fresh retry budget
223
+ if (sseData.__type !== 'CONNECTED') resumeAttempts.current = 0;
224
+ const run = sseData.__type === 'CHAT_RUN_UPDATE' ? sseData.data : sseData.data?.run;
225
+ if (run?.id) {
226
+ const canonicalRun = cacheAIChatRunUpdate(run as AIChatRunData, updateObservers);
227
+ setLiveRuns((current) => ({
228
+ chatId: dataAIChatId,
229
+ runs: mergeAIChatRuns(current.chatId === dataAIChatId ? current.runs : {}, [canonicalRun]),
230
+ }));
231
+ }
232
+ if (sseData.__type === 'CHAT_RUN_UPDATE') return;
233
+ if (sseData.__type === 'CHAT_RUN_STATUS') {
234
+ connection.close();
235
+ disposed = true;
236
+ const inProgress = sseData.data.inProgress === true;
237
+ updateQuery(rest.queryKey, { inProgress }, false, updateObservers);
238
+ setSession({
239
+ aiChatId: dataAIChatId,
240
+ key: null,
241
+ inProgress: inProgress ? true : null,
242
+ });
243
+ finishAIChatGeneration(dataAIChatId);
244
+ clearAIChatSubmission(dataAIChatId);
245
+ setLiveStatus({ phase: 'IDLE' });
246
+ return;
247
+ }
337
248
  handleSSEData(sseData, updateObservers);
338
- setLocalMessages((prevMessages) =>
339
- mergeSSEPayloadToLocalAIChatMessages(prevMessages, sseData),
340
- );
249
+ setLocalMessages((prevMessages) => mergeSSEPayloadToLocalAIChatMessages(prevMessages, sseData));
341
250
 
342
251
  const nextValue = getGeneratingFragmentId(sseData);
343
- if (nextValue === null || typeof nextValue === 'string') {
344
- setGeneratingFragmentId(nextValue);
252
+ if (typeof nextValue === 'string') {
253
+ startAIChatGeneration(dataAIChatId);
254
+ setLiveStatus({
255
+ fragmentId: nextValue,
256
+ phase: 'GENERATING',
257
+ });
258
+ } else if (nextValue === null) {
259
+ // One finished row does not end the run; CHAT_RUN_STATUS does
260
+ setLiveStatus({ phase: 'IDLE' });
345
261
  }
346
262
  },
347
263
  onError: () => {
348
- setGeneratingFragmentId(null);
264
+ if (disposed || epoch !== sessionEpoch.current) return;
265
+ disposed = true;
266
+ connection.close();
267
+ setSession({
268
+ aiChatId: dataAIChatId,
269
+ key: null,
270
+ inProgress: runInProgress === true,
271
+ });
272
+ finishAIChatGeneration(dataAIChatId);
273
+ clearAIChatSubmission(dataAIChatId);
274
+ setLiveStatus({ phase: 'IDLE' });
349
275
  },
350
276
  };
351
277
 
352
278
  connection.connect(connectParams);
353
- // const removeNetworkListeners = reconnectOnBrowserNetwork(connection, connectParams);
354
279
 
355
280
  return () => {
281
+ disposed = true;
356
282
  connection.close();
357
- // removeNetworkListeners();
358
283
  };
359
284
  }
360
- }, [dataAIChatId, sessionKey, variablesKey]);
361
-
362
- useEffect(() => {
363
- // Every time AIChat is fetched, check if it exists in lists cache
364
- if (dataAIChatId) {
365
- const queryKey = getAIChatsQueryKey(
366
- aiChat.organizationId,
367
- aiChat.calDate ? 'CAL_DATE' : aiChat.archivedAt ? 'ARCHIVED' : 'CHATS',
368
- );
369
- const queryCache = loadQuery(queryKey);
370
-
371
- if (queryCache) {
372
- const notFound = queryCache.every((a: any) => a.id !== dataAIChatId);
373
-
374
- if (notFound) {
375
- // If not found, add to cache
376
- updateQuery(
377
- queryKey,
378
- (prev: any) => {
379
- return [
380
- {
381
- cursor: aiChat.cursor,
382
- __flat: {
383
- __cache: true,
384
- data: [
385
- makeFragmentKey(FRAGMENT_NAMES.aiChat, dataAIChatId),
386
- ],
387
- },
388
- },
389
- ...prev,
390
- ];
391
- },
392
- false,
393
- updateObservers,
394
- );
395
- }
396
- }
397
- }
398
- }, [dataAIChatId]);
285
+ }, [aiChatId, dataAIChatId, sessionKey, variablesKey]);
399
286
 
400
287
  useEffect(() => {
401
288
  // Force reset if chat message is in progress
@@ -408,7 +295,11 @@ export function useAIChatWithSSE(
408
295
 
409
296
  return {
410
297
  aiChat: mergedAIChat,
298
+ runs,
299
+ liveMessages: localMessages,
300
+ generating,
411
301
  generatingFragmentId,
302
+ waitingForGeneration,
412
303
  sessionKey,
413
304
  addLocalMessage,
414
305
  setSessionKey: activateAIChatSession,
@@ -420,18 +311,16 @@ export function useAIChatWithSSE(
420
311
  * Fetch AI chat messages
421
312
  */
422
313
 
423
- export function useAIChatMessages(
424
- aiChatId?: string,
425
- params: UseQueryParams = {},
426
- ) {
314
+ export function useAIChatMessages(aiChatId?: string, params: UseQueryParams = {}) {
427
315
  const { data, ...other } = useQuery(aiChatMessagesQry, {
428
316
  variables: {
429
317
  aiChatId,
430
318
  cursor: null,
431
319
  after: true,
432
320
  limit: AI_CHAT_MESSAGES_LIMIT,
321
+ includeWork: false,
433
322
  },
434
- // If this query is used for virtualized list pagination, set {params.skip=true}
323
+ // Imperative pagination obeys skip too; keep this query enabled while the thread is mounted.
435
324
  skip: !aiChatId,
436
325
  ...params,
437
326
  });
@@ -442,57 +331,11 @@ export function useAIChatMessages(
442
331
  };
443
332
  }
444
333
 
445
- /**
446
- * Update sidebar AI chats query
447
- */
448
-
449
- export function updateAIChats(
450
- aiChat: any,
451
- organizationId: string | null | undefined,
452
- updateObservers: UpdateObserversFn,
453
- ) {
454
- if (aiChat) {
455
- const isCalDate = !!aiChat.calDate;
456
- const isArchived = !!aiChat.archivedAt;
457
- const queryKey = getAIChatsQueryKey(
458
- isCalDate ? null : organizationId || aiChat.organizationId,
459
- isCalDate ? 'CAL_DATE' : isArchived ? 'ARCHIVED' : 'CHATS',
460
- );
461
- const fragmentKey = makeFragmentKey(FRAGMENT_NAMES.aiChat, aiChat.id);
462
-
463
- updateQuery(
464
- queryKey,
465
- (res: any[]) => {
466
- if (res.some((item: any) => item?.__flat?.data?.[0] === fragmentKey)) {
467
- return res;
468
- }
469
-
470
- return [
471
- {
472
- cursor: aiChat.cursor,
473
- __flat: {
474
- __cache: true,
475
- data: [fragmentKey],
476
- },
477
- },
478
- ...res,
479
- ];
480
- },
481
- false,
482
- updateObservers,
483
- );
484
- }
485
- }
486
-
487
334
  /**
488
335
  * Fetch AI chats list
489
336
  */
490
337
 
491
- export function useAIChats(
492
- organizationId?: string | null,
493
- filter?: 'CAL_DATE' | 'CHATS' | 'ARCHIVED',
494
- params: UseQueryParams = {},
495
- ) {
338
+ export function useAIChats(organizationId?: string | null, filter?: 'CAL_DATE' | 'CHATS' | 'ARCHIVED', params: UseQueryParams = {}) {
496
339
  const queryOrganizationId = filter === 'CAL_DATE' ? null : organizationId;
497
340
  const { data, ...other } = useQuery(aiChatsQry, {
498
341
  variables: {
@@ -517,16 +360,8 @@ export function useAIChats(
517
360
  * Get reactive AI chat fragment for one chat.
518
361
  */
519
362
 
520
- export function useReactiveAIChatFragment(
521
- aiChatId?: string | null,
522
- currentData?: any,
523
- queryCount?: number,
524
- ) {
525
- return useReactiveFragment(
526
- currentData,
527
- aiChatId ? [makeFragmentKey(FRAGMENT_NAMES.aiChat, aiChatId)] : [],
528
- queryCount,
529
- );
363
+ export function useReactiveAIChatFragment(aiChatId?: string | null, currentData?: any, queryCount?: number) {
364
+ return useReactiveFragment(currentData, aiChatId ? [makeFragmentKey(FRAGMENT_NAMES.aiChat, aiChatId)] : [], queryCount);
530
365
  }
531
366
 
532
367
  /**
@@ -534,8 +369,40 @@ export function useReactiveAIChatFragment(
534
369
  */
535
370
 
536
371
  export function useReactiveAIChatFragmentMap(currentData?: any[] | null) {
537
- return useReactiveFragmentMap(
538
- currentData || null,
539
- getFragmentBaseName(FRAGMENT_NAMES.aiChat),
540
- );
372
+ return useReactiveFragmentMap(currentData || null, getFragmentBaseName(FRAGMENT_NAMES.aiChat));
373
+ }
374
+
375
+ /*
376
+ * Page one run independently from the outer transcript; collapsed runs do not fetch.
377
+ */
378
+ export function useAIChatWorkMessages(aiChatId: string, runId: string, expanded: boolean) {
379
+ const { data, ...rest } = useQuery(aiChatWorkMessagesQry, {
380
+ variables: { aiChatId, runId, cursor: null, after: false, limit: 55 },
381
+ skip: !expanded,
382
+ persistTime: 0,
383
+ });
384
+ return { messages: data?.aiChatMessages, ...rest };
385
+ }
386
+
387
+ /* Observe one run's transcript rows through the same canonical fragment keys as SSE. */
388
+ export function useReactiveAIChatMessageMap(messages: any[]) {
389
+ return useReactiveFragmentMap(messages, getFragmentBaseName(FRAGMENT_NAMES.aiChatMessage));
390
+ }
391
+
392
+ export { upsertLocalAIChatMessage } from './use-aiChat-qry.helpers.ts';
393
+
394
+ /* Fetch sidebar membership only for its mounted web-chat host and observe the canonical link fragments. */
395
+ export function useAIChatLinks(aiChatId?: string | null, params: UseQueryParams = {}) {
396
+ const { data, updatedCount, ...state } = useQuery(aiChatLinksQry, {
397
+ ...params,
398
+ variables: { aiChatId },
399
+ skip: !aiChatId || params.skip,
400
+ persistTime: params.persistTime ?? 20 * 60 * 1000,
401
+ });
402
+ const links = useReactiveAIChatLinkFragmentMap(data?.aiChatLinks, updatedCount);
403
+ return { links: useMemo(() => (links || []).filter((link) => !link.hiddenAt), [links]), ...state };
404
+ }
405
+ /* Share normalized fragment keys between list queries and run-footer readers. */
406
+ export function useReactiveAIChatLinkFragmentMap(links?: AIChatLink[] | null, updatedCount?: number): AIChatLink[] | null {
407
+ return useReactiveFragmentMap(links || null, getFragmentBaseName(FRAGMENT_NAMES.aiChatLink), updatedCount);
541
408
  }