@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.
- package/audience.d.ts +343 -0
- package/cache/config.ts +58 -24
- package/cache/index.chat-activity.test.ts +119 -0
- package/cache/index.chat.test.ts +92 -0
- package/cache/index.helpers.ts +96 -0
- package/cache/index.regression.test.ts +149 -0
- package/cache/index.test.ts +370 -42
- package/cache/index.ts +326 -799
- package/cache/optimistic-ui-runtime.ts +46 -0
- package/cache/optimistic-ui.ts +401 -0
- package/cache/persist.ts +98 -19
- package/cache/store.ts +22 -64
- package/cache/value.helpers.ts +17 -0
- package/{drafts/store.ts → client/draft-persistence-indexed-db.ts} +19 -3
- package/{drafts/index.ts → client/draft-persistence.ts} +5 -2
- package/client/index.ts +3 -2
- package/client/request.helpers.ts +14 -0
- package/client/request.ts +130 -215
- package/deno.lock +17 -0
- package/deno.test.json +2 -0
- package/gql/fragments/agentMemoryFragments.ts +5 -1
- package/gql/fragments/agentNoteFragments.ts +150 -0
- package/gql/fragments/aiChatFragments.ts +36 -10
- package/gql/fragments/audienceFragments.ts +141 -0
- package/gql/fragments/campaignFragments.ts +415 -126
- package/gql/fragments/dataTableFragments.ts +48 -80
- package/gql/fragments/emailFragments.ts +28 -23
- package/gql/fragments/fieldDocFragments.ts +222 -40
- package/gql/fragments/inboundContactFragments.ts +2 -0
- package/gql/fragments/logFragments.ts +93 -2
- package/gql/fragments/organizationFragments.ts +10 -0
- package/gql/fragments/qrCodeFragments.ts +29 -0
- package/gql/fragments/scheduleFragments.ts +652 -140
- package/gql/fragments/sheetFragments.ts +84 -373
- package/gql/fragments/storageFragments.ts +25 -1
- package/gql/fragments/workflowFragments.ts +13 -1
- package/gql/mutations/agentMemoryMutations.ts +32 -0
- package/gql/mutations/agentNoteMutations.ts +62 -0
- package/gql/mutations/aiChatMutations.ts +36 -4
- package/gql/mutations/audienceMutations.ts +71 -0
- package/gql/mutations/authMutations.ts +45 -1
- package/gql/mutations/billingMutations.ts +24 -0
- package/gql/mutations/campaignMutations.ts +170 -127
- package/gql/mutations/contactMutations.ts +23 -0
- package/gql/mutations/dataTableMutations.ts +18 -75
- package/gql/mutations/fieldDocMutations.ts +162 -13
- package/gql/mutations/index.ts +8 -5
- package/gql/mutations/organizationMutations.ts +6 -0
- package/gql/mutations/qrCodeMutations.ts +20 -0
- package/gql/mutations/scheduleMutations.ts +1052 -354
- package/gql/mutations/sheetMutations.ts +62 -118
- package/gql/mutations/storageMutations.ts +0 -1
- package/gql/mutations/workflowMutations.ts +18 -0
- package/gql/queries/agentMemoryQueries.ts +6 -0
- package/gql/queries/agentNoteQueries.ts +89 -0
- package/gql/queries/aiChatQueries.ts +56 -4
- package/gql/queries/audienceQueries.ts +128 -0
- package/gql/queries/authQueries.ts +6 -0
- package/gql/queries/billingQueries.ts +95 -6
- package/gql/queries/campaignQueries.ts +132 -23
- package/gql/queries/dataTableQueries.ts +24 -65
- package/gql/queries/emailQueries.ts +18 -61
- package/gql/queries/emailReplyReportQueries.ts +76 -0
- package/gql/queries/fieldDocQueries.ts +100 -92
- package/gql/queries/inboundContactQueries.ts +4 -0
- package/gql/queries/index.ts +3 -1
- package/gql/queries/logQueries.ts +62 -7
- package/gql/queries/organizationQueries.ts +13 -0
- package/gql/queries/qrCodeQueries.ts +20 -0
- package/gql/queries/scheduleQueries.ts +633 -257
- package/gql/queries/sheetQueries.ts +59 -152
- package/gql/queries/workflowQueries.ts +10 -4
- package/hooks/index.helpers.test.ts +50 -0
- package/hooks/index.helpers.ts +52 -0
- package/hooks/index.ts +863 -685
- package/hooks/use-agentMemory-mtn.ts +29 -31
- package/hooks/use-agentMemory-qry.ts +15 -3
- package/hooks/use-agentNote-mtn.ts +82 -0
- package/hooks/use-agentNote-qry.ts +190 -0
- package/hooks/use-agentNote-recovery.helpers.test.ts +68 -0
- package/hooks/use-agentNote-recovery.helpers.ts +58 -0
- package/hooks/use-agentNote-recovery.ts +72 -0
- package/hooks/use-aiChat-mtn.ts +96 -112
- package/hooks/use-aiChat-qry.helpers.test.ts +63 -0
- package/hooks/use-aiChat-qry.helpers.ts +124 -0
- package/hooks/use-aiChat-qry.ts +229 -383
- package/hooks/use-aiChat-stream-mtn.ts +14 -0
- package/hooks/use-audience-mtn.ts +194 -0
- package/hooks/use-audience-qry.helpers.test.ts +80 -0
- package/hooks/use-audience-qry.helpers.ts +63 -0
- package/hooks/use-audience-qry.ts +330 -0
- package/hooks/use-auth-mtn.ts +30 -1
- package/hooks/use-billing-mtn.ts +31 -0
- package/hooks/use-billing-qry.ts +76 -0
- package/hooks/use-campaign-generation-recovery.ts +53 -0
- package/hooks/use-campaign-mtn.ts +224 -165
- package/hooks/use-campaign-qry.helpers.ts +40 -0
- package/hooks/use-campaign-qry.ts +631 -54
- package/hooks/use-dataTable-mtn.ts +23 -115
- package/hooks/use-dataTable-qry.ts +66 -916
- package/hooks/use-email-qry.helpers.ts +37 -0
- package/hooks/use-email-qry.ts +33 -178
- package/hooks/use-emailCampaignReplyReport-qry.ts +27 -0
- package/hooks/use-fieldDoc-mtn.ts +244 -32
- package/hooks/use-fieldDoc-qry.helpers.test.ts +65 -0
- package/hooks/use-fieldDoc-qry.helpers.ts +49 -0
- package/hooks/use-fieldDoc-qry.ts +134 -102
- package/hooks/use-inboundContact-qry.ts +7 -9
- package/hooks/use-log-mtn.ts +25 -12
- package/hooks/use-log-qry.ts +99 -46
- package/hooks/use-organization-qry.ts +16 -60
- package/hooks/use-publicFormEmail-mtn.ts +27 -0
- package/hooks/use-qrCode-mtn.ts +40 -0
- package/hooks/use-qrCode-qry.ts +78 -0
- package/hooks/use-schedule-mtn.ts +506 -333
- package/hooks/use-schedule-qry.ts +682 -101
- package/hooks/use-schedule-reactive.ts +486 -0
- package/hooks/use-sheet-mtn.ts +91 -199
- package/hooks/use-sheet-qry.ts +84 -238
- package/hooks/use-storage-qry.ts +84 -61
- package/hooks/use-workflow-mtn.ts +39 -22
- package/hooks/use-workflow-qry.ts +40 -61
- package/libs/ai-chat-outgoing.helpers.ts +153 -0
- package/libs/ai-chat-outgoing.ts +11 -0
- package/libs/ai-chat-outgoing.types.ts +25 -0
- package/libs/ai-chat-run-realtime.ts +20 -0
- package/libs/ai-chat-submission-realtime.ts +150 -0
- package/libs/fragment-realtime-sequence.ts +55 -0
- package/libs/fragment-recovery.test.ts +326 -0
- package/libs/fragment-recovery.ts +325 -0
- package/libs/open-sheet.ts +138 -0
- package/libs/orchestrator-realtime.helpers.test.ts +229 -0
- package/libs/orchestrator-realtime.helpers.ts +317 -0
- package/libs/orchestrator-realtime.ts +433 -0
- package/libs/request-cache-regression.test.ts +122 -0
- package/{client → libs}/request-managed-session.test.ts +1 -1
- package/libs/request-no-store.test.ts +419 -0
- package/libs/sheet-command-batch.ts +44 -0
- package/libs/sheet-view-realtime-router.test.ts +214 -0
- package/libs/sheet-view-realtime-router.ts +99 -0
- package/loaders/campaign.test.ts +186 -0
- package/loaders/campaign.ts +56 -83
- package/loaders/emailPreference.ts +75 -0
- package/loaders/rest.ts +12 -0
- package/package.json +42 -17
- package/schedule.d.ts +1790 -0
- package/sse.helpers.ts +19 -0
- package/sse.ts +26 -115
- package/tests/agent-note-detail-cache.test.ts +120 -0
- package/tests/agent-note-search.test.ts +444 -0
- package/types.d.ts +46 -25
- package/client/data-table-realtime-subscriptions.test.ts +0 -740
- package/client/data-table-realtime-subscriptions.ts +0 -955
- package/client/data-table-realtime.test.ts +0 -792
- package/client/data-table-realtime.ts +0 -1218
- package/client/fragment-realtime-sequence.ts +0 -52
- package/client/open-sheet.ts +0 -137
- package/client/request-no-store.test.ts +0 -157
- package/gql/fragments/agentDocFragments.ts +0 -46
- package/gql/fragments/billingFragments.ts +0 -14
- package/gql/mutations/agentDocMutations.ts +0 -177
- package/gql/queries/agentDocQueries.ts +0 -120
- package/hooks/use-agentDoc-mtn.ts +0 -285
- package/hooks/use-agentDoc-qry.ts +0 -208
- /package/{client → libs}/sse-ticket.test.ts +0 -0
package/hooks/use-aiChat-qry.ts
CHANGED
|
@@ -1,30 +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 {
|
|
7
|
+
import { FRAGMENT_NAMES, getFragmentBaseName, makeFragmentKey } from '@jsb188/mday/constants/graphqlReactivity.ts';
|
|
3
8
|
import SSE from '@jsb188/sse';
|
|
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';
|
|
4
13
|
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
import {
|
|
11
|
-
|
|
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';
|
|
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';
|
|
28
21
|
|
|
29
22
|
/**
|
|
30
23
|
* Constants
|
|
@@ -33,231 +26,32 @@ import type { UpdateObserversFn, UseQueryParams } from '../types.d.ts';
|
|
|
33
26
|
const AI_CHATS_LIMIT = 70; // Must match server code exactly
|
|
34
27
|
const AI_CHAT_MESSAGES_LIMIT = 55; // Must match server code exactly
|
|
35
28
|
|
|
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
|
-
}
|
|
29
|
+
type AIChatLiveStatus = { phase: 'IDLE' } | { phase: 'SERVER_LOADING' } | { fragmentId: string; phase: 'GENERATING' };
|
|
58
30
|
|
|
59
31
|
/**
|
|
60
|
-
* Helper; get
|
|
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.
|
|
61
34
|
*/
|
|
62
35
|
|
|
63
36
|
function getGeneratingFragmentId(sseData: PublishPayload) {
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
if (__type === 'CONNECTED') {
|
|
69
|
-
return null;
|
|
70
|
-
}
|
|
71
|
-
|
|
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
|
-
}
|
|
86
|
-
}
|
|
87
|
-
|
|
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;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
/**
|
|
100
|
-
* Merge one message into a local live message list.
|
|
101
|
-
*/
|
|
102
|
-
|
|
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;
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
return prepend ? [message, ...messages] : [...messages, message];
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
/**
|
|
126
|
-
* Merge SSE payloads into local live AI chat messages.
|
|
127
|
-
*/
|
|
128
|
-
|
|
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
|
-
}
|
|
189
|
-
}
|
|
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,
|
|
200
|
-
});
|
|
201
|
-
}
|
|
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,
|
|
234
|
-
};
|
|
235
|
-
});
|
|
236
|
-
|
|
237
|
-
for (const message of localMessages) {
|
|
238
|
-
if (!usedMessageIds.has(message.id)) {
|
|
239
|
-
messages.push(message);
|
|
240
|
-
}
|
|
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;
|
|
241
41
|
}
|
|
242
42
|
|
|
243
|
-
return
|
|
244
|
-
...aiChat,
|
|
245
|
-
messages,
|
|
246
|
-
};
|
|
43
|
+
return finished ? null : key;
|
|
247
44
|
}
|
|
248
45
|
|
|
249
46
|
/**
|
|
250
47
|
* Fetch AI chat
|
|
251
48
|
*/
|
|
252
49
|
|
|
253
|
-
export function useAIChatWithSSE(
|
|
254
|
-
aiChatId?: string,
|
|
255
|
-
initialSessionKey?: string | null,
|
|
256
|
-
params: UseQueryParams = {},
|
|
257
|
-
) {
|
|
50
|
+
export function useAIChatWithSSE(aiChatId?: string, initialSessionKey?: string | null, params: UseQueryParams = {}) {
|
|
258
51
|
const { data, ...rest } = useQuery(aiChatQry, {
|
|
259
52
|
variables: {
|
|
260
53
|
aiChatId,
|
|
54
|
+
includeWork: false,
|
|
261
55
|
},
|
|
262
56
|
skip: !aiChatId,
|
|
263
57
|
persistTime: 20 * 60 * 1000,
|
|
@@ -265,54 +59,138 @@ export function useAIChatWithSSE(
|
|
|
265
59
|
});
|
|
266
60
|
|
|
267
61
|
const { updateObservers, variablesKey } = rest;
|
|
268
|
-
const [
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
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
|
+
});
|
|
274
78
|
const [localMessages, setLocalMessages] = useState<any[]>([]);
|
|
275
|
-
const
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
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],
|
|
284
94
|
);
|
|
285
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);
|
|
286
103
|
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
104
|
+
/*
|
|
105
|
+
* Reset connection retry state when the hook starts observing another chat.
|
|
106
|
+
*/
|
|
107
|
+
useEffect(() => {
|
|
108
|
+
setLocalMessages([]);
|
|
109
|
+
resumeAttempts.current = 0;
|
|
110
|
+
}, [aiChatId]);
|
|
292
111
|
|
|
293
112
|
/*
|
|
294
|
-
*
|
|
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.
|
|
295
168
|
*/
|
|
296
169
|
const activateAIChatSession = useCallback(
|
|
297
170
|
(nextSessionKey: string) => {
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
deleted: true,
|
|
305
|
-
finished: true,
|
|
306
|
-
}),
|
|
307
|
-
);
|
|
308
|
-
}
|
|
309
|
-
setSessionKey(nextSessionKey);
|
|
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?.();
|
|
310
177
|
},
|
|
311
|
-
[
|
|
178
|
+
[aiChatId, rest.refetch],
|
|
312
179
|
);
|
|
313
180
|
|
|
314
181
|
useEffect(() => {
|
|
315
|
-
|
|
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
|
+
}
|
|
316
194
|
}, [dataAIChatId]);
|
|
317
195
|
|
|
318
196
|
useEffect(() => {
|
|
@@ -320,82 +198,86 @@ export function useAIChatWithSSE(
|
|
|
320
198
|
// that make it unreliable to use perpetual SSE in production.
|
|
321
199
|
// So we have to write the logic to make it work without perpetual session.
|
|
322
200
|
|
|
323
|
-
if (dataAIChatId && sessionKey) {
|
|
201
|
+
if (dataAIChatId && dataAIChatId === aiChatId && sessionKey) {
|
|
324
202
|
// Only listen to events if data is loaded
|
|
325
203
|
const connection = new SSE({
|
|
326
204
|
host: getENVVariable('SSE_SERVER') as string,
|
|
327
205
|
path: `page_events/ai_chat/${dataAIChatId}`,
|
|
328
|
-
// path: 'test-sse',
|
|
329
206
|
searchParams: {
|
|
330
207
|
session_key: sessionKey,
|
|
331
208
|
variablesKey,
|
|
332
209
|
},
|
|
333
210
|
});
|
|
334
211
|
|
|
212
|
+
let disposed = false;
|
|
213
|
+
const epoch = sessionEpoch.current;
|
|
335
214
|
const connectParams = {
|
|
336
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
|
+
}
|
|
337
243
|
handleSSEData(sseData, updateObservers);
|
|
338
|
-
setLocalMessages((prevMessages) =>
|
|
339
|
-
mergeSSEPayloadToLocalAIChatMessages(prevMessages, sseData),
|
|
340
|
-
);
|
|
244
|
+
setLocalMessages((prevMessages) => mergeSSEPayloadToLocalAIChatMessages(prevMessages, sseData));
|
|
341
245
|
|
|
342
246
|
const nextValue = getGeneratingFragmentId(sseData);
|
|
343
|
-
if (
|
|
344
|
-
|
|
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' });
|
|
345
256
|
}
|
|
346
257
|
},
|
|
347
258
|
onError: () => {
|
|
348
|
-
|
|
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' });
|
|
349
270
|
},
|
|
350
271
|
};
|
|
351
272
|
|
|
352
273
|
connection.connect(connectParams);
|
|
353
|
-
// const removeNetworkListeners = reconnectOnBrowserNetwork(connection, connectParams);
|
|
354
274
|
|
|
355
275
|
return () => {
|
|
276
|
+
disposed = true;
|
|
356
277
|
connection.close();
|
|
357
|
-
// removeNetworkListeners();
|
|
358
278
|
};
|
|
359
279
|
}
|
|
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]);
|
|
280
|
+
}, [aiChatId, dataAIChatId, sessionKey, variablesKey]);
|
|
399
281
|
|
|
400
282
|
useEffect(() => {
|
|
401
283
|
// Force reset if chat message is in progress
|
|
@@ -408,7 +290,11 @@ export function useAIChatWithSSE(
|
|
|
408
290
|
|
|
409
291
|
return {
|
|
410
292
|
aiChat: mergedAIChat,
|
|
293
|
+
runs,
|
|
294
|
+
liveMessages: localMessages,
|
|
295
|
+
generating,
|
|
411
296
|
generatingFragmentId,
|
|
297
|
+
waitingForGeneration,
|
|
412
298
|
sessionKey,
|
|
413
299
|
addLocalMessage,
|
|
414
300
|
setSessionKey: activateAIChatSession,
|
|
@@ -420,18 +306,16 @@ export function useAIChatWithSSE(
|
|
|
420
306
|
* Fetch AI chat messages
|
|
421
307
|
*/
|
|
422
308
|
|
|
423
|
-
export function useAIChatMessages(
|
|
424
|
-
aiChatId?: string,
|
|
425
|
-
params: UseQueryParams = {},
|
|
426
|
-
) {
|
|
309
|
+
export function useAIChatMessages(aiChatId?: string, params: UseQueryParams = {}) {
|
|
427
310
|
const { data, ...other } = useQuery(aiChatMessagesQry, {
|
|
428
311
|
variables: {
|
|
429
312
|
aiChatId,
|
|
430
313
|
cursor: null,
|
|
431
314
|
after: true,
|
|
432
315
|
limit: AI_CHAT_MESSAGES_LIMIT,
|
|
316
|
+
includeWork: false,
|
|
433
317
|
},
|
|
434
|
-
//
|
|
318
|
+
// Imperative pagination obeys skip too; keep this query enabled while the thread is mounted.
|
|
435
319
|
skip: !aiChatId,
|
|
436
320
|
...params,
|
|
437
321
|
});
|
|
@@ -442,57 +326,11 @@ export function useAIChatMessages(
|
|
|
442
326
|
};
|
|
443
327
|
}
|
|
444
328
|
|
|
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
329
|
/**
|
|
488
330
|
* Fetch AI chats list
|
|
489
331
|
*/
|
|
490
332
|
|
|
491
|
-
export function useAIChats(
|
|
492
|
-
organizationId?: string | null,
|
|
493
|
-
filter?: 'CAL_DATE' | 'CHATS' | 'ARCHIVED',
|
|
494
|
-
params: UseQueryParams = {},
|
|
495
|
-
) {
|
|
333
|
+
export function useAIChats(organizationId?: string | null, filter?: 'CAL_DATE' | 'CHATS' | 'ARCHIVED', params: UseQueryParams = {}) {
|
|
496
334
|
const queryOrganizationId = filter === 'CAL_DATE' ? null : organizationId;
|
|
497
335
|
const { data, ...other } = useQuery(aiChatsQry, {
|
|
498
336
|
variables: {
|
|
@@ -517,16 +355,8 @@ export function useAIChats(
|
|
|
517
355
|
* Get reactive AI chat fragment for one chat.
|
|
518
356
|
*/
|
|
519
357
|
|
|
520
|
-
export function useReactiveAIChatFragment(
|
|
521
|
-
aiChatId
|
|
522
|
-
currentData?: any,
|
|
523
|
-
queryCount?: number,
|
|
524
|
-
) {
|
|
525
|
-
return useReactiveFragment(
|
|
526
|
-
currentData,
|
|
527
|
-
aiChatId ? [makeFragmentKey(FRAGMENT_NAMES.aiChat, aiChatId)] : [],
|
|
528
|
-
queryCount,
|
|
529
|
-
);
|
|
358
|
+
export function useReactiveAIChatFragment(aiChatId?: string | null, currentData?: any, queryCount?: number) {
|
|
359
|
+
return useReactiveFragment(currentData, aiChatId ? [makeFragmentKey(FRAGMENT_NAMES.aiChat, aiChatId)] : [], queryCount);
|
|
530
360
|
}
|
|
531
361
|
|
|
532
362
|
/**
|
|
@@ -534,8 +364,24 @@ export function useReactiveAIChatFragment(
|
|
|
534
364
|
*/
|
|
535
365
|
|
|
536
366
|
export function useReactiveAIChatFragmentMap(currentData?: any[] | null) {
|
|
537
|
-
return useReactiveFragmentMap(
|
|
538
|
-
currentData || null,
|
|
539
|
-
getFragmentBaseName(FRAGMENT_NAMES.aiChat),
|
|
540
|
-
);
|
|
367
|
+
return useReactiveFragmentMap(currentData || null, getFragmentBaseName(FRAGMENT_NAMES.aiChat));
|
|
541
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';
|