@jsb188/graphql 1.1.10 → 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 (176) hide show
  1. package/audience.d.ts +343 -0
  2. package/cache/config.ts +98 -50
  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 +1017 -127
  8. package/cache/index.ts +1256 -1269
  9. package/cache/optimistic-ui-runtime.ts +46 -0
  10. package/cache/optimistic-ui.ts +401 -0
  11. package/cache/persist.ts +800 -0
  12. package/cache/store.ts +395 -0
  13. package/cache/value.helpers.ts +17 -0
  14. package/client/draft-persistence-indexed-db.ts +413 -0
  15. package/client/draft-persistence.ts +152 -0
  16. package/client/index.ts +3 -0
  17. package/client/request.helpers.ts +14 -0
  18. package/client/request.ts +870 -164
  19. package/deno.lock +187 -0
  20. package/deno.test.json +10 -4
  21. package/gql/eagerQueryMap.ts +12 -0
  22. package/gql/fragments/accountAuthFragments.ts +5 -0
  23. package/gql/fragments/accountFragments.ts +0 -3
  24. package/gql/fragments/accountSessionFragments.ts +16 -0
  25. package/gql/fragments/agentMemoryFragments.ts +23 -0
  26. package/gql/fragments/agentNoteFragments.ts +150 -0
  27. package/gql/fragments/aiChatFragments.ts +42 -0
  28. package/gql/fragments/audienceFragments.ts +141 -0
  29. package/gql/fragments/campaignFragments.ts +566 -0
  30. package/gql/fragments/dataTableFragments.ts +50 -192
  31. package/gql/fragments/emailFragments.ts +32 -17
  32. package/gql/fragments/fieldDocFragments.ts +264 -0
  33. package/gql/fragments/inboundContactFragments.ts +2 -0
  34. package/gql/fragments/logFragments.ts +101 -69
  35. package/gql/fragments/organizationFragments.ts +53 -5
  36. package/gql/fragments/qrCodeFragments.ts +29 -0
  37. package/gql/fragments/scheduleFragments.ts +667 -0
  38. package/gql/fragments/sheetFragments.ts +304 -63
  39. package/gql/fragments/storageFragments.ts +45 -0
  40. package/gql/fragments/workflowFragments.ts +41 -5
  41. package/gql/mutations/accountMutations.ts +0 -2
  42. package/gql/mutations/agentMemoryMutations.ts +68 -0
  43. package/gql/mutations/agentNoteMutations.ts +62 -0
  44. package/gql/mutations/aiChatMutations.ts +49 -4
  45. package/gql/mutations/audienceMutations.ts +71 -0
  46. package/gql/mutations/authMutations.ts +203 -18
  47. package/gql/mutations/billingMutations.ts +17 -27
  48. package/gql/mutations/campaignMutations.ts +258 -0
  49. package/gql/mutations/contactMutations.ts +23 -0
  50. package/gql/mutations/dataTableMutations.ts +19 -54
  51. package/gql/mutations/fieldDocMutations.ts +173 -0
  52. package/gql/mutations/index.ts +10 -2
  53. package/gql/mutations/logMutations.ts +6 -29
  54. package/gql/mutations/organizationMutations.ts +19 -4
  55. package/gql/mutations/qrCodeMutations.ts +20 -0
  56. package/gql/mutations/scheduleMutations.ts +1121 -0
  57. package/gql/mutations/sheetMutations.ts +221 -60
  58. package/gql/mutations/storageMutations.ts +19 -0
  59. package/gql/mutations/workflowMutations.ts +60 -0
  60. package/gql/queries/agentMemoryQueries.ts +28 -0
  61. package/gql/queries/agentNoteQueries.ts +89 -0
  62. package/gql/queries/aiChatQueries.ts +70 -2
  63. package/gql/queries/audienceQueries.ts +128 -0
  64. package/gql/queries/authQueries.ts +47 -0
  65. package/gql/queries/billingQueries.ts +118 -6
  66. package/gql/queries/campaignQueries.ts +236 -0
  67. package/gql/queries/dataTableQueries.ts +61 -13
  68. package/gql/queries/emailQueries.ts +26 -17
  69. package/gql/queries/emailReplyReportQueries.ts +76 -0
  70. package/gql/queries/fieldDocQueries.ts +166 -0
  71. package/gql/queries/inboundContactQueries.ts +4 -0
  72. package/gql/queries/index.ts +10 -2
  73. package/gql/queries/logQueries.ts +68 -30
  74. package/gql/queries/organizationQueries.ts +65 -1
  75. package/gql/queries/qrCodeQueries.ts +20 -0
  76. package/gql/queries/scheduleQueries.ts +691 -0
  77. package/gql/queries/sheetQueries.ts +244 -26
  78. package/gql/queries/storageQueries.ts +38 -0
  79. package/gql/queries/workflowQueries.ts +77 -2
  80. package/hooks/index.helpers.test.ts +50 -0
  81. package/hooks/index.helpers.ts +52 -0
  82. package/hooks/index.ts +2254 -982
  83. package/hooks/use-account-mtn.ts +76 -81
  84. package/hooks/use-agentMemory-mtn.ts +71 -0
  85. package/hooks/use-agentMemory-qry.ts +56 -0
  86. package/hooks/use-agentNote-mtn.ts +82 -0
  87. package/hooks/use-agentNote-qry.ts +190 -0
  88. package/hooks/use-agentNote-recovery.helpers.test.ts +68 -0
  89. package/hooks/use-agentNote-recovery.helpers.ts +58 -0
  90. package/hooks/use-agentNote-recovery.ts +72 -0
  91. package/hooks/use-aiChat-mtn.ts +220 -141
  92. package/hooks/use-aiChat-qry.helpers.test.ts +63 -0
  93. package/hooks/use-aiChat-qry.helpers.ts +124 -0
  94. package/hooks/use-aiChat-qry.ts +341 -237
  95. package/hooks/use-aiChat-stream-mtn.ts +14 -0
  96. package/hooks/use-app-qry.ts +12 -9
  97. package/hooks/use-audience-mtn.ts +194 -0
  98. package/hooks/use-audience-qry.helpers.test.ts +80 -0
  99. package/hooks/use-audience-qry.helpers.ts +63 -0
  100. package/hooks/use-audience-qry.ts +330 -0
  101. package/hooks/use-auth-mtn.ts +435 -252
  102. package/hooks/use-auth-qry.ts +51 -0
  103. package/hooks/use-billing-mtn.ts +31 -0
  104. package/hooks/use-billing-qry.ts +76 -0
  105. package/hooks/use-campaign-generation-recovery.ts +53 -0
  106. package/hooks/use-campaign-mtn.ts +436 -0
  107. package/hooks/use-campaign-qry.helpers.ts +40 -0
  108. package/hooks/use-campaign-qry.ts +834 -0
  109. package/hooks/use-dataTable-mtn.ts +37 -46
  110. package/hooks/use-dataTable-qry.ts +102 -128
  111. package/hooks/use-email-qry.helpers.ts +37 -0
  112. package/hooks/use-email-qry.ts +56 -86
  113. package/hooks/use-emailCampaignReplyReport-qry.ts +27 -0
  114. package/hooks/use-fieldDoc-mtn.ts +262 -0
  115. package/hooks/use-fieldDoc-qry.helpers.test.ts +65 -0
  116. package/hooks/use-fieldDoc-qry.helpers.ts +49 -0
  117. package/hooks/use-fieldDoc-qry.ts +212 -0
  118. package/hooks/use-inboundContact-mtn.ts +19 -16
  119. package/hooks/use-inboundContact-qry.ts +62 -56
  120. package/hooks/use-integration-mtn.ts +56 -38
  121. package/hooks/use-integration-qry.ts +24 -9
  122. package/hooks/use-log-mtn.ts +88 -59
  123. package/hooks/use-log-qry.ts +150 -73
  124. package/hooks/use-organization-mtn.ts +334 -277
  125. package/hooks/use-organization-qry.ts +155 -129
  126. package/hooks/use-publicFormEmail-mtn.ts +27 -0
  127. package/hooks/use-qrCode-mtn.ts +40 -0
  128. package/hooks/use-qrCode-qry.ts +78 -0
  129. package/hooks/use-schedule-mtn.ts +589 -0
  130. package/hooks/use-schedule-qry.ts +738 -0
  131. package/hooks/use-schedule-reactive.ts +486 -0
  132. package/hooks/use-sheet-mtn.ts +157 -79
  133. package/hooks/use-sheet-qry.ts +221 -92
  134. package/hooks/use-storage-mtn.ts +81 -41
  135. package/hooks/use-storage-qry.ts +128 -14
  136. package/hooks/use-workflow-mtn.ts +72 -0
  137. package/hooks/use-workflow-qry.ts +184 -47
  138. package/libs/ai-chat-outgoing.helpers.ts +153 -0
  139. package/libs/ai-chat-outgoing.ts +11 -0
  140. package/libs/ai-chat-outgoing.types.ts +25 -0
  141. package/libs/ai-chat-run-realtime.ts +20 -0
  142. package/libs/ai-chat-submission-realtime.ts +150 -0
  143. package/libs/fragment-realtime-sequence.ts +55 -0
  144. package/libs/fragment-recovery.test.ts +326 -0
  145. package/libs/fragment-recovery.ts +325 -0
  146. package/libs/open-sheet.ts +138 -0
  147. package/libs/orchestrator-realtime.helpers.test.ts +229 -0
  148. package/libs/orchestrator-realtime.helpers.ts +317 -0
  149. package/libs/orchestrator-realtime.ts +433 -0
  150. package/libs/request-cache-regression.test.ts +122 -0
  151. package/libs/request-managed-session.test.ts +574 -0
  152. package/libs/request-no-store.test.ts +419 -0
  153. package/libs/sheet-command-batch.ts +44 -0
  154. package/libs/sheet-view-realtime-router.test.ts +214 -0
  155. package/libs/sheet-view-realtime-router.ts +99 -0
  156. package/libs/sse-ticket.test.ts +26 -0
  157. package/loaders/campaign.test.ts +186 -0
  158. package/loaders/campaign.ts +110 -0
  159. package/loaders/emailPreference.ts +75 -0
  160. package/loaders/rest.ts +12 -0
  161. package/package.json +119 -71
  162. package/schedule.d.ts +1790 -0
  163. package/sse.helpers.ts +19 -0
  164. package/sse.ts +70 -106
  165. package/tests/agent-note-detail-cache.test.ts +120 -0
  166. package/tests/agent-note-search.test.ts +444 -0
  167. package/tsconfig.json +11 -10
  168. package/types.d.ts +77 -26
  169. package/utils.ts +78 -49
  170. package/gql/fragments/billingFragments.ts +0 -25
  171. package/gql/fragments/productFragments.ts +0 -39
  172. package/gql/fragments/reportFragments.ts +0 -90
  173. package/gql/queries/productQueries.ts +0 -31
  174. package/gql/queries/reportQueries.ts +0 -134
  175. package/hooks/use-product-qry.ts +0 -67
  176. package/hooks/use-report-qry.ts +0 -153
@@ -1,13 +1,23 @@
1
+ import { cacheAIChatRunUpdate } from '../libs/ai-chat-run-realtime.ts';
2
+ import type { AIChatRunData } from '@jsb188/app/types/ai.d.ts';
3
+ import { mergeAIChatRuns } from '@jsb188/mday/utils/aiChatWork.ts';
4
+ import { upsertLocalAIChatMessage, mergeSSEPayloadToLocalAIChatMessages, mergeLocalAIChatMessages } from './use-aiChat-qry.helpers.ts';
5
+ import { useResumeAIChatStream } from './use-aiChat-stream-mtn.ts';
1
6
  import { getENVVariable } from '@jsb188/app';
2
- import { getAuthToken } from '@jsb188/app/utils/api.ts';
3
- import { makeVariablesKey } from '@jsb188/app/utils/logic.ts';
7
+ import { FRAGMENT_NAMES, getFragmentBaseName, makeFragmentKey } from '@jsb188/mday/constants/graphqlReactivity.ts';
4
8
  import SSE from '@jsb188/sse';
5
- import { useEffect, useState } from 'react';
6
- import { loadFragment, loadQuery, resetQuery, updateQuery } from '../cache/index.ts';
7
- import { useQuery, useReactiveFragmentMap } from '../client/index.ts';
8
- import { aiChatMessagesQry, aiChatQry, aiChatsQry } from '../gql/queries/aiChatQueries.ts';
9
- import handleSSEData, { type PublishPayload } from '../sse.ts';
10
- import type { UpdateObserversFn, UseQueryParams } from '../types.d.ts';
9
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
10
+ import { loadFragment, resetQuery, updateQuery } from '../cache/index.ts';
11
+ import { useQuery, useReactiveFragment, useReactiveFragmentMap } from '../client/index.ts';
12
+ import { aiChatMessagesQry, aiChatWorkMessagesQry, aiChatQry, aiChatsQry } from '../gql/queries/aiChatQueries.ts';
13
+ import {
14
+ clearAIChatSubmission,
15
+ finishAIChatGeneration,
16
+ startAIChatGeneration,
17
+ subscribeToAIChatSubmission,
18
+ } from '../libs/ai-chat-submission-realtime.ts';
19
+ import handleSSEData, { isStaleSSECheckpoint, type PublishPayload } from '../sse.ts';
20
+ import type { UseQueryParams } from '../types.d.ts';
11
21
 
12
22
  /**
13
23
  * Constants
@@ -16,174 +26,280 @@ import type { UpdateObserversFn, UseQueryParams } from '../types.d.ts';
16
26
  const AI_CHATS_LIMIT = 70; // Must match server code exactly
17
27
  const AI_CHAT_MESSAGES_LIMIT = 55; // Must match server code exactly
18
28
 
19
- /**
20
- * Params for AI chat query hook with reactive SSE auth
21
- */
22
-
23
- interface UseAIChatWithSSEParams extends UseQueryParams {
24
- authToken?: string | null;
25
- }
26
-
27
- /**
28
- * Helper; build AI chats query key
29
- */
30
-
31
- function getAIChatsQueryKey(
32
- organizationId?: string | null,
33
- filter?: 'CAL_DATE' | 'CHATS' | 'ARCHIVED',
34
- ) {
35
- if (!organizationId || !filter) {
36
- return '';
37
- }
38
-
39
- const variablesKey = makeVariablesKey({
40
- organizationId,
41
- filter,
42
- cursor: null,
43
- after: false,
44
- limit: AI_CHATS_LIMIT
45
- });
46
-
47
- return `#aiChats:${variablesKey}`;
48
- }
29
+ type AIChatLiveStatus = { phase: 'IDLE' } | { phase: 'SERVER_LOADING' } | { fragmentId: string; phase: 'GENERATING' };
49
30
 
50
31
  /**
51
- * Helper; get generating (status) key from SSE data
32
+ * Helper; get the streaming message key from one SSE checkpoint, null when that
33
+ * message finished, or undefined when the event is not a message checkpoint.
52
34
  */
53
35
 
54
36
  function getGeneratingFragmentId(sseData: PublishPayload) {
55
- const { __type, dataFragmentKey, fragmentKey, fragmentNamespace, data } = sseData;
56
- const finished = data?.finished;
57
-
58
- if (__type === 'CONNECTED') {
59
- return null;
60
- }
61
-
62
- const fragmentName = '$aiChatMessageFragment:';
63
-
64
- if (typeof finished === 'boolean') {
65
- if (dataFragmentKey?.startsWith(fragmentName) ) {
66
- return finished ? null : dataFragmentKey;
67
- } else if (fragmentKey?.startsWith(fragmentName)) {
68
- return finished ? null : fragmentKey;
69
- }
70
- } else if (
71
- fragmentKey?.startsWith(fragmentName) &&
72
- fragmentNamespace === 'text'
73
- ) {
74
- return fragmentKey;
75
- }
37
+ const key = sseData.dataFragmentKey || sseData.fragmentKey;
38
+ const finished = sseData.data?.finished;
39
+ if (!key?.startsWith(FRAGMENT_NAMES.aiChatMessage + ':') || typeof finished !== 'boolean') {
40
+ return undefined;
41
+ }
42
+
43
+ return finished ? null : key;
76
44
  }
77
45
 
78
46
  /**
79
47
  * Fetch AI chat
80
48
  */
81
49
 
82
- export function useAIChatWithSSE(aiChatId?: string, initialSessionKey?: string | null, params: UseAIChatWithSSEParams = {}) {
83
-
84
- const { authToken, ...queryParams } = params;
85
-
86
- const { data, ...rest } = useQuery(aiChatQry, {
87
- variables: {
88
- aiChatId
89
- },
90
- skip: !aiChatId,
91
- ...queryParams,
92
- });
93
-
94
- const { updateObservers } = rest;
95
- const [sessionKey, setSessionKey] = useState<string | null>(initialSessionKey || null);
96
- const [generatingFragmentId, setGeneratingFragmentId] = useState<string | null>(null);
97
- const aiChat = data?.aiChat || loadFragment(`$aiChatFragment:${aiChatId}`);
98
- const dataAIChatId = aiChat?.id;
99
-
100
- useEffect(() => {
101
- // Browser has too many issues such as proxy, network, roadblocks
102
- // that make it unreliable to use perpetual SSE in production.
103
- // So we have to write the logic to make it work without perpetual session.
104
-
105
- if (dataAIChatId && sessionKey) {
106
- const currentAuthToken = authToken ?? getAuthToken();
107
-
108
- // Only listen to events if data is loaded
109
- const connection = new SSE({
110
- host: getENVVariable('SSE_SERVER') as string,
111
- path: `page_events/ai_chat/${dataAIChatId}`,
112
- // path: 'test-sse',
113
- searchParams: {
114
- session_key: sessionKey,
115
- auth_token: currentAuthToken
116
- }
117
- });
118
-
119
- const connectParams = {
120
- onMessage: (sseData: PublishPayload) => {
121
- handleSSEData(sseData, updateObservers);
122
-
123
- const nextValue = getGeneratingFragmentId(sseData);
124
- if (nextValue === null || typeof nextValue === 'string') {
125
- setGeneratingFragmentId(nextValue);
126
- }
127
- },
128
- onError: () => {
129
- setGeneratingFragmentId(null);
130
- }
131
- };
132
-
133
- connection.connect(connectParams);
134
- // const removeNetworkListeners = reconnectOnBrowserNetwork(connection, connectParams);
135
-
136
- return () => {
137
- connection.close();
138
- // removeNetworkListeners();
139
- };
140
- }
141
- }, [authToken, dataAIChatId, sessionKey]);
142
-
143
- useEffect(() => {
144
- // Every time AIChat is fetched, check if it exists in lists cache
145
- if (dataAIChatId) {
146
- const queryKey = getAIChatsQueryKey(
147
- aiChat.organizationId,
148
- aiChat.calDate ? 'CAL_DATE' : aiChat.archivedAt ? 'ARCHIVED' : 'CHATS'
149
- );
150
- const queryCache = loadQuery(queryKey);
151
-
152
- if (queryCache) {
153
- const notFound = queryCache.every((a: any) => a.id !== dataAIChatId);
154
-
155
- if (notFound) {
156
- // If not found, add to cache
157
- updateQuery(queryKey, (prev: any) => {
158
- return [{
159
- cursor: aiChat.cursor,
160
- __flat: {
161
- __cache: true,
162
- data: [`$aiChatFragment:${dataAIChatId}`],
163
- }
164
- }, ...prev];
165
- }, false, updateObservers);
166
- }
167
- }
168
- }
169
- }, [dataAIChatId]);
170
-
171
- useEffect(() => {
172
- // Force reset if chat message is in progress
173
- if (aiChat?.inProgress) {
174
- return () => {
175
- resetQuery(rest.queryKey, true, updateObservers);
176
- };
177
- }
178
- }, [aiChat?.inProgress]);
179
-
180
- return {
181
- aiChat,
182
- generatingFragmentId,
183
- sessionKey,
184
- setSessionKey,
185
- ...rest
186
- };
50
+ export function useAIChatWithSSE(aiChatId?: string, initialSessionKey?: string | null, params: UseQueryParams = {}) {
51
+ const { data, ...rest } = useQuery(aiChatQry, {
52
+ variables: {
53
+ aiChatId,
54
+ includeWork: false,
55
+ },
56
+ skip: !aiChatId,
57
+ persistTime: 20 * 60 * 1000,
58
+ ...params,
59
+ });
60
+
61
+ const { updateObservers, variablesKey } = rest;
62
+ const [session, setSession] = useState({
63
+ aiChatId,
64
+ key: initialSessionKey || null,
65
+ inProgress: initialSessionKey ? true : (null as boolean | null),
66
+ });
67
+ const sessionKey = session.aiChatId === aiChatId ? session.key : null;
68
+ const sessionEpoch = useRef(0);
69
+ const activeChatRef = useRef(aiChatId);
70
+ if (activeChatRef.current !== aiChatId) {
71
+ activeChatRef.current = aiChatId;
72
+ sessionEpoch.current++;
73
+ }
74
+ const [resumeTick, setResumeTick] = useState(0);
75
+ const [liveStatus, setLiveStatus] = useState<AIChatLiveStatus>({
76
+ phase: 'IDLE',
77
+ });
78
+ const [localMessages, setLocalMessages] = useState<any[]>([]);
79
+ const [liveRuns, setLiveRuns] = useState<{ chatId?: string; runs: Record<string, AIChatRunData> }>({ chatId: aiChatId, runs: {} });
80
+ const baseAIChat = data?.aiChat || (aiChatId ? loadFragment(makeFragmentKey(FRAGMENT_NAMES.aiChat, aiChatId)) : null);
81
+ const aiChat = useReactiveAIChatFragment(aiChatId, baseAIChat, rest.updatedCount);
82
+ const mergedAIChat = useMemo(() => mergeLocalAIChatMessages(aiChat, localMessages), [aiChat, localMessages]);
83
+ const runs = useMemo(
84
+ () =>
85
+ mergeAIChatRuns(
86
+ mergeAIChatRuns({}, [
87
+ aiChat?.latestRun,
88
+ ...(aiChat?.messages || []).map((message: any) => message.run),
89
+ ...(mergedAIChat?.messages || []).map((message: any) => message.run),
90
+ ]),
91
+ Object.values(liveRuns.chatId === aiChatId ? liveRuns.runs : {}),
92
+ ),
93
+ [aiChatId, aiChat?.latestRun, aiChat?.messages, mergedAIChat?.messages, liveRuns],
94
+ );
95
+ const dataAIChatId = aiChat?.id;
96
+ const resumeAttempts = useRef(0);
97
+ const { resumeAIChatStream } = useResumeAIChatStream();
98
+ // A delayed HTTP response can retain an old chat flag after the run settled.
99
+ const runInProgress =
100
+ session.aiChatId === aiChatId && session.inProgress !== null
101
+ ? session.inProgress
102
+ : (runs[aiChat?.latestRun?.id]?.inProgress ?? aiChat?.inProgress);
103
+
104
+ /*
105
+ * Reset connection retry state when the hook starts observing another chat.
106
+ */
107
+ useEffect(() => {
108
+ setLocalMessages([]);
109
+ resumeAttempts.current = 0;
110
+ }, [aiChatId]);
111
+
112
+ /*
113
+ * Resume an existing run with a fresh single-use ticket. Failed ticket requests
114
+ * retry with bounded backoff, and superseded requests cannot replace a new send.
115
+ */
116
+ useEffect(() => {
117
+ if (!dataAIChatId || dataAIChatId !== aiChatId || !runInProgress || sessionKey || resumeAttempts.current >= 3) return;
118
+ const epoch = sessionEpoch.current;
119
+ let disposed = false;
120
+ let timer: ReturnType<typeof setTimeout> | undefined;
121
+ resumeAttempts.current++;
122
+ /*
123
+ * Schedule another ticket request only while this chat still owns the attempt.
124
+ */
125
+ const retry = () => {
126
+ if (!disposed && epoch === sessionEpoch.current && resumeAttempts.current < 3) {
127
+ timer = setTimeout(() => setResumeTick((value) => value + 1), 1000 * resumeAttempts.current);
128
+ }
129
+ };
130
+ resumeAIChatStream({ variables: { aiChatId: dataAIChatId } })
131
+ .then((result: any) => {
132
+ if (disposed || epoch !== sessionEpoch.current) return;
133
+ if (result?.resumeAIChatStream) {
134
+ setSession({
135
+ aiChatId: dataAIChatId,
136
+ key: result.resumeAIChatStream,
137
+ inProgress: true,
138
+ });
139
+ } else if (result?.error || result?.aborted) {
140
+ retry();
141
+ }
142
+ })
143
+ .catch(retry);
144
+ return () => {
145
+ disposed = true;
146
+ clearTimeout(timer);
147
+ };
148
+ }, [aiChatId, dataAIChatId, runInProgress, sessionKey, resumeTick]);
149
+
150
+ const generatingFragmentId = liveStatus.phase === 'GENERATING' ? liveStatus.fragmentId : null;
151
+ const waitingForGeneration = liveStatus.phase === 'SERVER_LOADING';
152
+ // A run stays active between its rows (tool calls, the next model step) until
153
+ // CHAT_RUN_STATUS closes the subscription
154
+ const generating = !!runInProgress || !!sessionKey || !!generatingFragmentId;
155
+
156
+ /* Ignore delayed submission callbacks after this hook starts displaying a different chat. */
157
+ const addLocalMessage = useCallback(
158
+ (message: any) => {
159
+ if (activeChatRef.current !== aiChatId) return;
160
+ setLocalMessages((prevMessages) => upsertLocalAIChatMessage(prevMessages, message));
161
+ },
162
+ [aiChatId],
163
+ );
164
+
165
+ /*
166
+ * Switch to a newly issued SSE session. Superseded drafts stay visible as
167
+ * incomplete, matching the persisted transcript after reload.
168
+ */
169
+ const activateAIChatSession = useCallback(
170
+ (nextSessionKey: string) => {
171
+ if (activeChatRef.current !== aiChatId) return;
172
+ sessionEpoch.current++;
173
+ resumeAttempts.current = 0;
174
+ setSession({ aiChatId, key: nextSessionKey, inProgress: true });
175
+ // Refresh cancelled predecessors after switching away from their stream.
176
+ rest.refetch?.();
177
+ },
178
+ [aiChatId, rest.refetch],
179
+ );
180
+
181
+ useEffect(() => {
182
+ setLiveStatus({ phase: 'IDLE' });
183
+ if (dataAIChatId) {
184
+ return subscribeToAIChatSubmission(dataAIChatId, (waiting) => {
185
+ setLiveStatus((currentStatus) => {
186
+ if (currentStatus.phase === 'GENERATING') {
187
+ return currentStatus;
188
+ }
189
+
190
+ return waiting ? { phase: 'SERVER_LOADING' } : { phase: 'IDLE' };
191
+ });
192
+ });
193
+ }
194
+ }, [dataAIChatId]);
195
+
196
+ useEffect(() => {
197
+ // Browser has too many issues such as proxy, network, roadblocks
198
+ // that make it unreliable to use perpetual SSE in production.
199
+ // So we have to write the logic to make it work without perpetual session.
200
+
201
+ if (dataAIChatId && dataAIChatId === aiChatId && sessionKey) {
202
+ // Only listen to events if data is loaded
203
+ const connection = new SSE({
204
+ host: getENVVariable('SSE_SERVER') as string,
205
+ path: `page_events/ai_chat/${dataAIChatId}`,
206
+ searchParams: {
207
+ session_key: sessionKey,
208
+ variablesKey,
209
+ },
210
+ });
211
+
212
+ let disposed = false;
213
+ const epoch = sessionEpoch.current;
214
+ const connectParams = {
215
+ onMessage: (sseData: PublishPayload) => {
216
+ if (disposed || epoch !== sessionEpoch.current || isStaleSSECheckpoint(sseData)) return;
217
+ // A connection that delivers run data has succeeded; later drops get a fresh retry budget
218
+ if (sseData.__type !== 'CONNECTED') resumeAttempts.current = 0;
219
+ const run = sseData.__type === 'CHAT_RUN_UPDATE' ? sseData.data : sseData.data?.run;
220
+ if (run?.id) {
221
+ const canonicalRun = cacheAIChatRunUpdate(run as AIChatRunData, updateObservers);
222
+ setLiveRuns((current) => ({
223
+ chatId: dataAIChatId,
224
+ runs: mergeAIChatRuns(current.chatId === dataAIChatId ? current.runs : {}, [canonicalRun]),
225
+ }));
226
+ }
227
+ if (sseData.__type === 'CHAT_RUN_UPDATE') return;
228
+ if (sseData.__type === 'CHAT_RUN_STATUS') {
229
+ connection.close();
230
+ disposed = true;
231
+ const inProgress = sseData.data.inProgress === true;
232
+ updateQuery(rest.queryKey, { inProgress }, false, updateObservers);
233
+ setSession({
234
+ aiChatId: dataAIChatId,
235
+ key: null,
236
+ inProgress: inProgress ? true : null,
237
+ });
238
+ finishAIChatGeneration(dataAIChatId);
239
+ clearAIChatSubmission(dataAIChatId);
240
+ setLiveStatus({ phase: 'IDLE' });
241
+ return;
242
+ }
243
+ handleSSEData(sseData, updateObservers);
244
+ setLocalMessages((prevMessages) => mergeSSEPayloadToLocalAIChatMessages(prevMessages, sseData));
245
+
246
+ const nextValue = getGeneratingFragmentId(sseData);
247
+ if (typeof nextValue === 'string') {
248
+ startAIChatGeneration(dataAIChatId);
249
+ setLiveStatus({
250
+ fragmentId: nextValue,
251
+ phase: 'GENERATING',
252
+ });
253
+ } else if (nextValue === null) {
254
+ // One finished row does not end the run; CHAT_RUN_STATUS does
255
+ setLiveStatus({ phase: 'IDLE' });
256
+ }
257
+ },
258
+ onError: () => {
259
+ if (disposed || epoch !== sessionEpoch.current) return;
260
+ disposed = true;
261
+ connection.close();
262
+ setSession({
263
+ aiChatId: dataAIChatId,
264
+ key: null,
265
+ inProgress: runInProgress === true,
266
+ });
267
+ finishAIChatGeneration(dataAIChatId);
268
+ clearAIChatSubmission(dataAIChatId);
269
+ setLiveStatus({ phase: 'IDLE' });
270
+ },
271
+ };
272
+
273
+ connection.connect(connectParams);
274
+
275
+ return () => {
276
+ disposed = true;
277
+ connection.close();
278
+ };
279
+ }
280
+ }, [aiChatId, dataAIChatId, sessionKey, variablesKey]);
281
+
282
+ useEffect(() => {
283
+ // Force reset if chat message is in progress
284
+ if (aiChat?.inProgress) {
285
+ return () => {
286
+ resetQuery(rest.queryKey, true, updateObservers);
287
+ };
288
+ }
289
+ }, [aiChat?.inProgress]);
290
+
291
+ return {
292
+ aiChat: mergedAIChat,
293
+ runs,
294
+ liveMessages: localMessages,
295
+ generating,
296
+ generatingFragmentId,
297
+ waitingForGeneration,
298
+ sessionKey,
299
+ addLocalMessage,
300
+ setSessionKey: activateAIChatSession,
301
+ ...rest,
302
+ };
187
303
  }
188
304
 
189
305
  /**
@@ -191,87 +307,56 @@ export function useAIChatWithSSE(aiChatId?: string, initialSessionKey?: string |
191
307
  */
192
308
 
193
309
  export function useAIChatMessages(aiChatId?: string, params: UseQueryParams = {}) {
194
-
195
- const { data, ...other } = useQuery(aiChatMessagesQry, {
196
- variables: {
197
- aiChatId,
198
- cursor: null,
199
- after: true,
200
- limit: AI_CHAT_MESSAGES_LIMIT
201
- },
202
- // If this query is used for virtualized list pagination, set {params.skip=true}
203
- skip: !aiChatId,
204
- ...params,
205
- });
206
-
207
- return {
208
- aiChatMessages: data?.aiChatMessages,
209
- ...other
210
- };
310
+ const { data, ...other } = useQuery(aiChatMessagesQry, {
311
+ variables: {
312
+ aiChatId,
313
+ cursor: null,
314
+ after: true,
315
+ limit: AI_CHAT_MESSAGES_LIMIT,
316
+ includeWork: false,
317
+ },
318
+ // Imperative pagination obeys skip too; keep this query enabled while the thread is mounted.
319
+ skip: !aiChatId,
320
+ ...params,
321
+ });
322
+
323
+ return {
324
+ aiChatMessages: data?.aiChatMessages,
325
+ ...other,
326
+ };
211
327
  }
212
328
 
213
329
  /**
214
- * Update sidebar AI chats query
330
+ * Fetch AI chats list
215
331
  */
216
332
 
217
- export function updateAIChats(
218
- aiChat: any,
219
- organizationId: string | null | undefined,
220
- updateObservers: UpdateObserversFn
221
- ) {
222
- if (aiChat) {
223
- const isCalDate = !!aiChat.calDate;
224
- const isArchived = !!aiChat.archivedAt;
225
- const queryKey = getAIChatsQueryKey(
226
- organizationId || aiChat.organizationId,
227
- isCalDate ? 'CAL_DATE' : isArchived ? 'ARCHIVED' : 'CHATS'
228
- );
229
- const fragmentKey = `$aiChatFragment:${aiChat.id}`;
230
-
231
- updateQuery(
232
- queryKey,
233
- (res: any[]) => {
234
- if (res.some((item: any) => item?.__flat?.data?.[0] === fragmentKey)) {
235
- return res;
236
- }
237
-
238
- return [
239
- {
240
- cursor: aiChat.cursor,
241
- __flat: {
242
- __cache: true,
243
- data: [fragmentKey]
244
- }
245
- },
246
- ...res
247
- ];
248
- },
249
- false,
250
- updateObservers
251
- );
252
- }
333
+ export function useAIChats(organizationId?: string | null, filter?: 'CAL_DATE' | 'CHATS' | 'ARCHIVED', params: UseQueryParams = {}) {
334
+ const queryOrganizationId = filter === 'CAL_DATE' ? null : organizationId;
335
+ const { data, ...other } = useQuery(aiChatsQry, {
336
+ variables: {
337
+ organizationId: queryOrganizationId,
338
+ filter,
339
+ cursor: null,
340
+ after: false,
341
+ limit: AI_CHATS_LIMIT,
342
+ },
343
+ skip: filter !== 'CAL_DATE' && !organizationId,
344
+ ...params,
345
+ persistTime: params.persistTime ?? 15 * 60 * 1000,
346
+ });
347
+
348
+ return {
349
+ aiChats: data?.aiChats,
350
+ ...other,
351
+ };
253
352
  }
254
353
 
255
354
  /**
256
- * Fetch AI chats list
355
+ * Get reactive AI chat fragment for one chat.
257
356
  */
258
357
 
259
- export function useAIChats(organizationId: string, filter?: 'CAL_DATE' | 'CHATS' | 'ARCHIVED') {
260
- const { data, ...other } = useQuery(aiChatsQry, {
261
- variables: {
262
- organizationId,
263
- filter,
264
- cursor: null,
265
- after: false,
266
- limit: AI_CHATS_LIMIT
267
- },
268
- skip: !organizationId,
269
- });
270
-
271
- return {
272
- aiChats: data?.aiChats,
273
- ...other
274
- };
358
+ export function useReactiveAIChatFragment(aiChatId?: string | null, currentData?: any, queryCount?: number) {
359
+ return useReactiveFragment(currentData, aiChatId ? [makeFragmentKey(FRAGMENT_NAMES.aiChat, aiChatId)] : [], queryCount);
275
360
  }
276
361
 
277
362
  /**
@@ -279,5 +364,24 @@ export function useAIChats(organizationId: string, filter?: 'CAL_DATE' | 'CHATS'
279
364
  */
280
365
 
281
366
  export function useReactiveAIChatFragmentMap(currentData?: any[] | null) {
282
- return useReactiveFragmentMap(currentData || null, 'aiChatFragment');
367
+ return useReactiveFragmentMap(currentData || null, getFragmentBaseName(FRAGMENT_NAMES.aiChat));
283
368
  }
369
+
370
+ /*
371
+ * Page one run independently from the outer transcript; collapsed runs do not fetch.
372
+ */
373
+ export function useAIChatWorkMessages(aiChatId: string, runId: string, expanded: boolean) {
374
+ const { data, ...rest } = useQuery(aiChatWorkMessagesQry, {
375
+ variables: { aiChatId, runId, cursor: null, after: false, limit: 55 },
376
+ skip: !expanded,
377
+ persistTime: 0,
378
+ });
379
+ return { messages: data?.aiChatMessages, ...rest };
380
+ }
381
+
382
+ /* Observe one run's transcript rows through the same canonical fragment keys as SSE. */
383
+ export function useReactiveAIChatMessageMap(messages: any[]) {
384
+ return useReactiveFragmentMap(messages, getFragmentBaseName(FRAGMENT_NAMES.aiChatMessage));
385
+ }
386
+
387
+ export { upsertLocalAIChatMessage } from './use-aiChat-qry.helpers.ts';
@@ -0,0 +1,14 @@
1
+ import { useMutation } from '../client/index.ts';
2
+ import { resumeAIChatStreamMtn } from '../gql/mutations/aiChatMutations.ts';
3
+ import type { UseMutationParams } from '../types.d.ts';
4
+
5
+ /*
6
+ * Request a fresh authenticated subscription to an existing durable chat run.
7
+ */
8
+ export function useResumeAIChatStream(params: UseMutationParams = {}) {
9
+ const [resumeAIChatStream, values] = useMutation(
10
+ resumeAIChatStreamMtn,
11
+ params,
12
+ );
13
+ return { resumeAIChatStream, ...values };
14
+ }
@@ -6,14 +6,17 @@ import type { UseQueryParams } from '../types.d.ts';
6
6
  * Fetch update notes
7
7
  */
8
8
 
9
- export function useUpdateNote(accountId?: string | null, params: UseQueryParams = {}) {
10
- const { data, ...other } = useQuery(updateNoteQry, {
11
- skip: !accountId,
12
- ...params,
13
- });
9
+ export function useUpdateNote(
10
+ accountId?: string | null,
11
+ params: UseQueryParams = {},
12
+ ) {
13
+ const { data, ...other } = useQuery(updateNoteQry, {
14
+ skip: !accountId,
15
+ ...params,
16
+ });
14
17
 
15
- return {
16
- updateNote: data?.updateNote,
17
- ...other
18
- };
18
+ return {
19
+ updateNote: data?.updateNote,
20
+ ...other,
21
+ };
19
22
  }