@jsb188/ai-chat 0.0.0-stage → 1.1.2

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 (51) hide show
  1. package/README.md +109 -2
  2. package/VERIFICATION.md +118 -0
  3. package/benchmarks/browser.mjs +204 -0
  4. package/benchmarks/streaming.mjs +89 -0
  5. package/package.json +36 -5
  6. package/src/main.ts +5 -0
  7. package/src/modules/AIChatContent.tsx +84 -0
  8. package/src/modules/AgentNoteActionsMenu.tsx +121 -0
  9. package/src/modules/AgentNoteBootstrapProgress.tsx +41 -0
  10. package/src/modules/AgentNoteItem.helpers.ts +115 -0
  11. package/src/modules/AgentNoteItem.tsx +232 -0
  12. package/src/modules/AgentNotes.constants.ts +10 -0
  13. package/src/modules/AgentNotes.helpers.ts +274 -0
  14. package/src/modules/AgentNotes.hooks.ts +449 -0
  15. package/src/modules/AgentNotes.tsx +74 -0
  16. package/src/modules/AgentNotes.types.ts +50 -0
  17. package/src/modules/AgentNotesCollection.hooks.ts +69 -0
  18. package/src/modules/AgentNotesSection.tsx +145 -0
  19. package/src/parser.ts +4 -0
  20. package/src/types/content.ts +103 -0
  21. package/src/ui/AIChatUI.css +557 -0
  22. package/src/ui/AIChatUI.tsx +816 -0
  23. package/src/ui/AgentNotesUI.tsx +375 -0
  24. package/src/ui/AgentNotesUI.types.ts +19 -0
  25. package/src/ui/ChatBlocks.tsx +92 -0
  26. package/src/ui/ChatCodeBlock.tsx +16 -0
  27. package/src/ui/ChatInline.helpers.ts +20 -0
  28. package/src/ui/ChatInline.tsx +89 -0
  29. package/src/ui/ChatTable.helpers.ts +37 -0
  30. package/src/ui/ChatTable.tsx +126 -0
  31. package/src/utils/contentIdentity.ts +108 -0
  32. package/src/utils/parseBlocks.helpers.ts +50 -0
  33. package/src/utils/parseBlocks.ts +266 -0
  34. package/src/utils/parseContent.helpers.ts +102 -0
  35. package/src/utils/parseContent.ts +33 -0
  36. package/src/utils/parseContentIncrementally.ts +46 -0
  37. package/src/utils/parseCsv.ts +99 -0
  38. package/src/utils/parseInline.helpers.ts +48 -0
  39. package/src/utils/parseInline.ts +396 -0
  40. package/src/utils/parseTable.ts +202 -0
  41. package/tests/AgentNotes.test.tsx +1672 -0
  42. package/tests/fixtures/content.ts +13 -0
  43. package/tests/parseContent.test.ts +227 -0
  44. package/tests/parseCsv.test.ts +82 -0
  45. package/tests/parseInline.test.ts +222 -0
  46. package/tests/renderContent.ssr.test.tsx +19 -0
  47. package/tests/renderContent.test.tsx +282 -0
  48. package/tests/streaming.test.ts +51 -0
  49. package/tests/streamingEquivalence.test.ts +265 -0
  50. package/tsconfig.json +16 -0
  51. package/vitest.config.ts +18 -0
@@ -0,0 +1,449 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import { useMarkAgentNoteReadMutation, useRefreshAgentNote, useUpdateAgentNote } from '@jsb188/graphql/hooks/use-agentNote-mtn';
3
+ import { useStartAIChat } from '@jsb188/graphql/hooks/use-aiChat-mtn';
4
+ import { FRAGMENT_NAMES, makeFragmentKey } from '@jsb188/mday/constants/graphqlReactivity.ts';
5
+ import type { AgentNoteGQL } from '@jsb188/mday/types/agentNote.d.ts';
6
+ import { useOpenModalPopUp } from '@jsb188/react/states';
7
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
8
+ import type { AgentNoteActions } from '../ui/AgentNotesUI.types';
9
+ import { getAgentNoteRefreshCooldownMS } from './AgentNotes.helpers';
10
+ import type {
11
+ AgentNoteChatActions,
12
+ AgentNoteChatStarted,
13
+ AgentNoteStateActions,
14
+ AgentNoteRefreshActions,
15
+ AgentNoteStateCache,
16
+ } from './AgentNotes.types';
17
+
18
+ /*
19
+ * Track independent requests by object identity so late callbacks cannot settle a newer attempt for the same note.
20
+ */
21
+ function useAgentNoteAttempts() {
22
+ const inFlightRef = useRef(new Map<string, { agentNoteId: string }>());
23
+ const [savingNoteIds, setSavingNoteIds] = useState<ReadonlySet<string>>(() => new Set());
24
+
25
+ /* Ignore callbacks after the collection and its state cache have been discarded. */
26
+ useEffect(() => () => inFlightRef.current.clear(), []);
27
+
28
+ /* Start one request per note, including duplicate clicks before React rerenders the button. */
29
+ const startAttempt = useCallback((attempt: { agentNoteId: string }) => {
30
+ if (inFlightRef.current.has(attempt.agentNoteId)) return false;
31
+ inFlightRef.current.set(attempt.agentNoteId, attempt);
32
+ setSavingNoteIds(new Set(inFlightRef.current.keys()));
33
+ return true;
34
+ }, []);
35
+
36
+ /* Release only the request that still owns this note's pending state. */
37
+ const finishAttempt = useCallback((attempt: { agentNoteId: string } | null) => {
38
+ if (!attempt || inFlightRef.current.get(attempt.agentNoteId) !== attempt) return false;
39
+ inFlightRef.current.delete(attempt.agentNoteId);
40
+ setSavingNoteIds(new Set(inFlightRef.current.keys()));
41
+ return true;
42
+ }, []);
43
+
44
+ return { savingNoteIds, startAttempt, finishAttempt };
45
+ }
46
+
47
+ /*
48
+ * Own Boolean state updates above grouped rows so regrouping preserves their pending state.
49
+ */
50
+ export function useAgentNoteStateUpdate(organizationId: string, field: 'pinned' | 'needsAttention' = 'pinned'): AgentNoteStateActions {
51
+ const openModalPopUp = useOpenModalPopUp();
52
+ const { savingNoteIds, startAttempt, finishAttempt } = useAgentNoteAttempts();
53
+
54
+ /*
55
+ * Settle only the current attempt, including local conflicts and transport failures without mutation callbacks.
56
+ */
57
+ const settleAttempt = useCallback(
58
+ (attempt: { agentNoteId: string } | null, showError = false) => {
59
+ if (finishAttempt(attempt) && showError)
60
+ openModalPopUp(null, {
61
+ message: i18n.t(field === 'pinned' ? 'agent_note.agent_note_pin_failed' : 'agent_note.agent_note_priority_failed'),
62
+ });
63
+ },
64
+ [finishAttempt, openModalPopUp, field],
65
+ );
66
+
67
+ const { updateAgentNote } = useUpdateAgentNote(
68
+ {
69
+ checkMountedBeforeCallback: true,
70
+ onCompleted: (updated, error, variables) => settleAttempt(variables, !error && updated !== true),
71
+ onError: (_error, variables) => settleAttempt(variables),
72
+ },
73
+ openModalPopUp,
74
+ );
75
+ const updateRef = useRef(updateAgentNote);
76
+ /* Keep the row action stable while calling the latest mutation implementation. */
77
+ useLayoutEffect(() => {
78
+ updateRef.current = updateAgentNote;
79
+ }, [updateAgentNote]);
80
+
81
+ /*
82
+ * Update each note independently, optimistically pinning while priority waits for the saved state.
83
+ */
84
+ const onChange = useCallback(
85
+ (agentNoteId: string, value: boolean) => {
86
+ const attempt = { organizationId, agentNoteId, [field]: value };
87
+ if (!startAttempt(attempt)) return;
88
+ void updateRef
89
+ .current({
90
+ variables: attempt,
91
+ optimisticUI:
92
+ field === 'pinned'
93
+ ? {
94
+ action: 'update',
95
+ fragmentKey: makeFragmentKey(FRAGMENT_NAMES.agentNote, agentNoteId),
96
+ update: { pinned: value },
97
+ }
98
+ : undefined,
99
+ })
100
+ .then((result) => {
101
+ if (result?.aborted || result?.error) settleAttempt(attempt, true);
102
+ })
103
+ .catch(() => settleAttempt(attempt, true));
104
+ },
105
+ [organizationId, startAttempt, settleAttempt, field],
106
+ );
107
+
108
+ return useMemo(() => ({ savingNoteIds, onChange }), [savingNoteIds, onChange]);
109
+ }
110
+
111
+ /*
112
+ * Own refresh requests and accepted cooldowns above the rows so regrouping or collapsing cannot reset their guards.
113
+ */
114
+ export function useAgentNoteRefresh(p: { organizationId: string; stateCache: AgentNoteStateCache }): AgentNoteRefreshActions {
115
+ const openModalPopUp = useOpenModalPopUp();
116
+ const { savingNoteIds, startAttempt, finishAttempt } = useAgentNoteAttempts();
117
+
118
+ /* Settle only the current request; shared mutation callbacks already present their own errors. */
119
+ const settleAttempt = useCallback(
120
+ (attempt: { agentNoteId: string } | null, showError = false) => {
121
+ if (finishAttempt(attempt) && showError) openModalPopUp(null, { message: i18n.t('agent_note.agent_note_refresh_failed') });
122
+ },
123
+ [finishAttempt, openModalPopUp],
124
+ );
125
+
126
+ const { refreshAgentNote } = useRefreshAgentNote(
127
+ {
128
+ onCompleted: (refreshedNote, error, variables) => {
129
+ if (!finishAttempt(variables)) return;
130
+ if (!error && refreshedNote?.id === variables.agentNoteId) {
131
+ const state = p.stateCache.get(variables.agentNoteId) || { draft: '' };
132
+ p.stateCache.set(variables.agentNoteId, { ...state, refreshAttemptedAt: new Date().toISOString() });
133
+ } else if (!error) {
134
+ openModalPopUp(null, { message: i18n.t('agent_note.agent_note_refresh_failed') });
135
+ }
136
+ },
137
+ onError: (_error, variables) => settleAttempt(variables),
138
+ },
139
+ openModalPopUp,
140
+ );
141
+ const refreshRef = useRef(refreshAgentNote);
142
+ /* Preserve the row's action identity while using the current mutation callbacks. */
143
+ useLayoutEffect(() => {
144
+ refreshRef.current = refreshAgentNote;
145
+ }, [refreshAgentNote]);
146
+
147
+ /* Keep concurrent refreshes independent while rejecting a duplicate request for the same note. */
148
+ const onRefresh = useCallback(
149
+ (agentNoteId: string) => {
150
+ const attempt = { organizationId: p.organizationId, agentNoteId };
151
+ if (!startAttempt(attempt)) return;
152
+ void refreshRef
153
+ .current({ variables: attempt })
154
+ .then((result) => {
155
+ if (result?.aborted || result?.error) settleAttempt(attempt, true);
156
+ })
157
+ .catch(() => settleAttempt(attempt, true));
158
+ },
159
+ [p.organizationId, startAttempt, settleAttempt],
160
+ );
161
+
162
+ return useMemo(() => ({ savingNoteIds, onRefresh }), [savingNoteIds, onRefresh]);
163
+ }
164
+
165
+ /* Keep the queued countdown current and show processing until the persisted refresh job finishes. */
166
+ export function useAgentNoteRefreshLabel(availableAt: string | null | undefined, refreshing: boolean | undefined, enabled: boolean) {
167
+ const [, setTick] = useState(0);
168
+ const now = Date.now();
169
+ const scheduledAt = Date.parse(availableAt || '');
170
+ const minutes = Number.isFinite(scheduledAt) ? Math.max(0, Math.ceil((scheduledAt - now) / 60_000)) : null;
171
+ useEffect(() => {
172
+ if (!enabled || minutes === null || minutes === 0) return;
173
+ const timer = setTimeout(() => setTick((tick) => tick + 1), Math.max(1, scheduledAt - Date.now() - (minutes - 1) * 60_000));
174
+ return () => clearTimeout(timer);
175
+ }, [enabled, scheduledAt, minutes]);
176
+ if (!enabled) return undefined;
177
+ if (minutes === null) return refreshing ? i18n.t('agent_note.refresh_in_progress') : undefined;
178
+ return minutes > 0
179
+ ? i18n.t('agent_note.refresh_queued_minutes', { smart_count: minutes })
180
+ : i18n.t('agent_note.refresh_queued_soon');
181
+ }
182
+
183
+ /*
184
+ * Re-enable refresh as soon as its cooldown expires, without a page reload.
185
+ */
186
+ export function useAgentNoteRefreshCooldown(refreshedAt: string | null, attemptedAt?: string) {
187
+ const [, setTick] = useState(0);
188
+ const remaining = getAgentNoteRefreshCooldownMS(refreshedAt, attemptedAt);
189
+ useEffect(() => {
190
+ if (!remaining) return;
191
+ // Cap browser timer delays and recalculate after waking in case the system clock changed.
192
+ const timer = setTimeout(() => setTick((tick) => tick + 1), Math.min(remaining, 2_147_483_647));
193
+ return () => clearTimeout(timer);
194
+ }, [remaining]);
195
+ return remaining > 0;
196
+ }
197
+
198
+ /*
199
+ * Submit note questions from one stable owner so list reordering cannot interrupt a request or lose its retry identity.
200
+ */
201
+ export function useAgentNoteChat(p: {
202
+ organizationId: string;
203
+ stateCache: AgentNoteStateCache;
204
+ onChatStarted: (chat: AgentNoteChatStarted) => void;
205
+ }): AgentNoteChatActions {
206
+ const openModalPopUp = useOpenModalPopUp();
207
+ const inFlightRef = useRef<{ agentNoteId: string; clientRequestId: string } | null>(null);
208
+ const [sendingNoteId, setSendingNoteId] = useState<string | null>(null);
209
+ const onChatStartedRef = useRef(p.onChatStarted);
210
+
211
+ /* Keep a pending response attached to the current host callback and ignore it after the collection unmounts. */
212
+ useLayoutEffect(() => {
213
+ onChatStartedRef.current = p.onChatStarted;
214
+ }, [p.onChatStarted]);
215
+ useEffect(
216
+ () => () => {
217
+ inFlightRef.current = null;
218
+ },
219
+ [],
220
+ );
221
+
222
+ /*
223
+ * Leave the draft and request ID available for retry; late responses cannot settle a newer attempt using the same ID.
224
+ */
225
+ const failSubmission = useCallback(
226
+ (attempt: { agentNoteId: string; clientRequestId: string } | null, showError = false) => {
227
+ if (!attempt || inFlightRef.current !== attempt) return;
228
+ inFlightRef.current = null;
229
+ setSendingNoteId(null);
230
+ if (showError) openModalPopUp(null, { message: i18n.t('agent_note.agent_note_message_failed') });
231
+ },
232
+ [openModalPopUp],
233
+ );
234
+
235
+ const { startAIChat, setSaving } = useStartAIChat(
236
+ {
237
+ checkMountedBeforeCallback: true,
238
+ onCompleted: (data, error, variables) => {
239
+ const attempt = inFlightRef.current;
240
+ if (!attempt || attempt !== variables) return;
241
+ const { agentNoteId, clientRequestId } = attempt;
242
+ const state = p.stateCache.get(agentNoteId);
243
+ const submission = state?.submission;
244
+ const aiChatId = data?.startAIChat?.node?.id;
245
+ if (!aiChatId || error || !submission || submission.clientRequestId !== clientRequestId) {
246
+ failSubmission(attempt, !error);
247
+ return;
248
+ }
249
+
250
+ p.stateCache.set(agentNoteId, {
251
+ ...state,
252
+ draft: state.draft.trim() === submission.text ? '' : state.draft,
253
+ submission: undefined,
254
+ });
255
+ inFlightRef.current = null;
256
+ setSendingNoteId(null);
257
+ onChatStartedRef.current({
258
+ aiChatId,
259
+ sessionKey: data.startAIChat.sessionKey || null,
260
+ text: submission.text,
261
+ submittedAt: submission.submittedAt,
262
+ });
263
+ },
264
+ onError: (_error, variables) => failSubmission(variables),
265
+ },
266
+ openModalPopUp,
267
+ );
268
+ const mutationRef = useRef({ startAIChat, setSaving });
269
+ /* Parent callbacks may change without replacing every note's send action. */
270
+ useLayoutEffect(() => {
271
+ mutationRef.current = { startAIChat, setSaving };
272
+ }, [startAIChat, setSaving]);
273
+
274
+ /*
275
+ * Reuse a failed submission's request ID while its text is unchanged, preventing duplicate questions on retries.
276
+ */
277
+ const onSend = useCallback(
278
+ (agentNoteId: string) => {
279
+ const state = p.stateCache.get(agentNoteId);
280
+ const text = state?.draft.trim();
281
+ if (!state || !text || inFlightRef.current) return;
282
+
283
+ const submission =
284
+ state.submission?.text === text
285
+ ? state.submission
286
+ : { text, clientRequestId: crypto.randomUUID(), submittedAt: new Date().toISOString() };
287
+ const attempt = { organizationId: p.organizationId, agentNoteId, text, clientRequestId: submission.clientRequestId };
288
+ p.stateCache.set(agentNoteId, { ...state, submission });
289
+ inFlightRef.current = attempt;
290
+ setSendingNoteId(agentNoteId);
291
+ void mutationRef.current
292
+ .startAIChat({
293
+ variables: attempt,
294
+ })
295
+ .then((result) => {
296
+ if (result?.aborted || result?.error) failSubmission(attempt, true);
297
+ })
298
+ .catch(() => {
299
+ if (inFlightRef.current !== attempt) return;
300
+ mutationRef.current.setSaving(false);
301
+ failSubmission(attempt, true);
302
+ });
303
+ },
304
+ [p.organizationId, p.stateCache, failSubmission],
305
+ );
306
+
307
+ return useMemo(() => ({ sendingNoteId, onSend }), [sendingNoteId, onSend]);
308
+ }
309
+
310
+ /*
311
+ * Keep drafts and explicit read markers across temporary row removal and live regrouping.
312
+ */
313
+ function useAgentNoteItemState(note: AgentNoteGQL, stateCache: AgentNoteStateCache, expanded: boolean) {
314
+ const [, setRevision] = useState(0);
315
+ const state = stateCache.get(note.id) || { draft: '' };
316
+ const { markAgentNoteRead } = useMarkAgentNoteReadMutation();
317
+ const markReadRef = useRef(markAgentNoteRead);
318
+
319
+ /* Keep read effects independent of mutation callback identity. */
320
+ useLayoutEffect(() => {
321
+ markReadRef.current = markAgentNoteRead;
322
+ }, [markAgentNoteRead]);
323
+
324
+ /*
325
+ * Count one explicit expansion, including a deep link. The shared marker prevents
326
+ * live reorders and StrictMode effect replays from extending retention again.
327
+ */
328
+ useEffect(() => {
329
+ if (!expanded) return;
330
+ const savedState = stateCache.get(note.id);
331
+ if (savedState?.readMarked) return;
332
+ stateCache.set(note.id, { ...(savedState || { draft: '' }), readMarked: true });
333
+ void markReadRef.current({ variables: { organizationId: note.organizationId, agentNoteId: note.id } }).catch(() => {
334
+ // Read marking is best-effort; fetching or reordering never retries it.
335
+ });
336
+ }, [expanded, note.id, note.organizationId, stateCache]);
337
+
338
+ /* Preserve read markers, refresh timestamps and submissions written by the shared action owners. */
339
+ const changeDraft = (draft: string) => {
340
+ stateCache.set(note.id, { ...stateCache.get(note.id), draft });
341
+ setRevision((revision) => revision + 1);
342
+ };
343
+
344
+ return { state, changeDraft };
345
+ }
346
+
347
+ /*
348
+ * Resolve note permissions and mutation state into the same action contract used by buttons and click guards.
349
+ */
350
+ export function useAgentNoteItem(p: {
351
+ note: AgentNoteGQL;
352
+ stateCache: AgentNoteStateCache;
353
+ updatingPriority: boolean;
354
+ onChangePriority: AgentNoteStateActions['onChange'];
355
+ pinning: boolean;
356
+ onChangePin: AgentNoteStateActions['onChange'];
357
+ refreshing: boolean;
358
+ onRefresh: AgentNoteRefreshActions['onRefresh'];
359
+ expanded: boolean;
360
+ }) {
361
+ const { note, pinning } = p;
362
+ const openModalPopUp = useOpenModalPopUp();
363
+ const { state, changeDraft } = useAgentNoteItemState(note, p.stateCache, p.expanded);
364
+ const refreshCoolingDown = useAgentNoteRefreshCooldown(note.refreshedAt, state.refreshAttemptedAt);
365
+ const reasons = {
366
+ pin: pinning ? i18n.t('agent_note.agent_note_pin_updating') : undefined,
367
+ refresh:
368
+ note.canManage !== true
369
+ ? i18n.t('agent_note.agent_note_manage_not_allowed')
370
+ : p.refreshing || refreshCoolingDown
371
+ ? i18n.t('agent_note.agent_note_recently_refreshed')
372
+ : undefined,
373
+ };
374
+
375
+ /* Change this note’s pin only in response to an authorized explicit action. */
376
+ const togglePinned = () => {
377
+ if (note.canPin !== true || reasons.pin) return;
378
+ p.onChangePin(note.id, !note.pinned);
379
+ };
380
+
381
+ /* Request fresh content only when this note's permissions, pending state and cooldown allow it. */
382
+ const refreshNote = () => {
383
+ if (reasons.refresh) return;
384
+ p.onRefresh(note.id);
385
+ };
386
+
387
+ /* Open the existing archive options only for an authorized note manager. */
388
+ const confirmArchive = () => {
389
+ if (note.canManage !== true) return;
390
+ openModalPopUp({
391
+ name: 'ARCHIVE_AGENT_NOTE',
392
+ preset: 'ARCHIVE_AGENT_NOTE',
393
+ props: {
394
+ organizationId: note.organizationId,
395
+ agentNoteId: note.id,
396
+ headline: note.headline,
397
+ kind: note.kind,
398
+ campaignId: note.campaignId,
399
+ reminderWorkflowId: note.reminderWorkflowId,
400
+ ownedDataTableId: note.ownedDataTableId,
401
+ },
402
+ });
403
+ };
404
+
405
+ /* Confirm scheduled task deletion only for a manageable reminder with a linked workflow. */
406
+ const confirmDeleteScheduledTask = () => {
407
+ if (note.canManage !== true || note.kind !== 'REMINDER' || !note.reminderWorkflowId) return;
408
+ openModalPopUp({
409
+ name: 'DELETE_SCHEDULED_TASK',
410
+ preset: 'DELETE_SCHEDULED_TASK',
411
+ props: {
412
+ organizationId: note.organizationId,
413
+ workflowId: note.reminderWorkflowId,
414
+ title: note.headline?.trim() || i18n.t('agent_note.agent_note'),
415
+ },
416
+ });
417
+ };
418
+
419
+ /* Update priority only when management is allowed and no priority request is pending. */
420
+ const togglePriority = () => {
421
+ if (note.canManage !== true || p.updatingPriority) return;
422
+ p.onChangePriority(note.id, note.needsAttention !== true);
423
+ };
424
+
425
+ const actions: AgentNoteActions = {
426
+ priority: {
427
+ disabledReason: note.canManage === true ? undefined : i18n.t('agent_note.agent_note_manage_not_allowed'),
428
+ busy: p.updatingPriority,
429
+ onClick: togglePriority,
430
+ },
431
+ deleteScheduledTask:
432
+ note.kind === 'REMINDER' && note.reminderWorkflowId
433
+ ? {
434
+ disabledReason: note.canManage === true ? undefined : i18n.t('agent_note.agent_note_manage_not_allowed'),
435
+ busy: false,
436
+ onClick: confirmDeleteScheduledTask,
437
+ }
438
+ : null,
439
+ archive: {
440
+ disabledReason: note.canManage === true ? undefined : i18n.t('agent_note.agent_note_manage_not_allowed'),
441
+ busy: false,
442
+ onClick: confirmArchive,
443
+ },
444
+ pin: note.canPin === true ? { disabledReason: reasons.pin, busy: pinning, onClick: togglePinned } : null,
445
+ refresh: { disabledReason: reasons.refresh, busy: false, onClick: refreshNote },
446
+ };
447
+
448
+ return { draft: state.draft, changeDraft, actions };
449
+ }
@@ -0,0 +1,74 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import { memo, useCallback, useLayoutEffect, useMemo, useState } from 'react';
3
+ import { AGENT_NOTE_GROUPS } from './AgentNotes.constants';
4
+ import { useAgentNoteChat, useAgentNoteStateUpdate, useAgentNoteRefresh } from './AgentNotes.hooks';
5
+ import type { AgentNoteGroupKey, AgentNoteStateCache, AgentNotesProps } from './AgentNotes.types';
6
+ import { useAgentNotesCollection } from './AgentNotesCollection.hooks';
7
+ import { AgentNotesSection } from './AgentNotesSection';
8
+
9
+ /*
10
+ * Fetch one homepage collection and share note drafts and mutations across local groups.
11
+ */
12
+ const AgentNotesCollection = (p: AgentNotesProps) => {
13
+ const stateCache = useMemo<AgentNoteStateCache>(() => new Map(), [p.organizationId]);
14
+ const [expandedNoteId, setExpandedNoteId] = useState<string | null>(null);
15
+
16
+ /* Keep one note open and count each explicit reopening as a new read. */
17
+ const toggleExpanded = useCallback(
18
+ (agentNoteId: string) => {
19
+ const state = stateCache.get(agentNoteId);
20
+ if (state) stateCache.set(agentNoteId, { ...state, readMarked: false });
21
+ setExpandedNoteId((current) => (current === agentNoteId ? null : agentNoteId));
22
+ },
23
+ [stateCache],
24
+ );
25
+ const chatActions = useAgentNoteChat({ organizationId: p.organizationId, stateCache, onChatStarted: p.onChatStarted });
26
+ const pinActions = useAgentNoteStateUpdate(p.organizationId);
27
+ const priorityActions = useAgentNoteStateUpdate(p.organizationId, 'needsAttention');
28
+ const refreshActions = useAgentNoteRefresh({ organizationId: p.organizationId, stateCache });
29
+ const collection = useAgentNotesCollection(p.organizationId);
30
+ const hasNotes = !collection.accessDenied && !!collection.snapshot?.notes.length;
31
+
32
+ /* Keep the surrounding layout aligned with the displayed collection. */
33
+ useLayoutEffect(() => {
34
+ p.onVisibilityChange?.(hasNotes);
35
+ }, [hasNotes, p.onVisibilityChange]);
36
+
37
+ if (!hasNotes) return null;
38
+
39
+ return (
40
+ <section
41
+ className="mt_df"
42
+ aria-label={i18n.t('agent_note.agent_notes')}
43
+ aria-busy={!!collection.loading}
44
+ >
45
+ {(Object.keys(AGENT_NOTE_GROUPS) as AgentNoteGroupKey[]).map((section) => (
46
+ <AgentNotesSection
47
+ key={section}
48
+ section={section}
49
+ snapshot={collection.snapshot}
50
+ ready={collection.ready}
51
+ accessDenied={collection.accessDenied}
52
+ loading={!!collection.loading}
53
+ stateCache={stateCache}
54
+ expandedNoteId={expandedNoteId}
55
+ onToggleExpanded={toggleExpanded}
56
+ chatActions={chatActions}
57
+ pinActions={pinActions}
58
+ priorityActions={priorityActions}
59
+ refreshActions={refreshActions}
60
+ />
61
+ ))}
62
+ </section>
63
+ );
64
+ };
65
+
66
+ /*
67
+ * Reset transitions and local note drafts when the organization changes.
68
+ */
69
+ export const AgentNotes = memo((p: AgentNotesProps) => (
70
+ <AgentNotesCollection
71
+ key={p.organizationId}
72
+ {...p}
73
+ />
74
+ ));
@@ -0,0 +1,50 @@
1
+ import type { AgentNoteGQL } from '@jsb188/mday/types/agentNote.d.ts';
2
+ import type { AGENT_NOTE_GROUPS } from './AgentNotes.constants';
3
+
4
+ export type AgentNoteGroupKey = keyof typeof AGENT_NOTE_GROUPS;
5
+
6
+ export interface AgentNoteItemState {
7
+ draft: string;
8
+ readMarked?: boolean;
9
+ refreshAttemptedAt?: string;
10
+ submission?: {
11
+ text: string;
12
+ clientRequestId: string;
13
+ submittedAt: string;
14
+ };
15
+ }
16
+
17
+ export type AgentNoteStateCache = Map<string, AgentNoteItemState>;
18
+
19
+ export interface AgentNoteChatStarted {
20
+ aiChatId: string;
21
+ sessionKey: string | null;
22
+ text: string;
23
+ submittedAt: string;
24
+ }
25
+
26
+ export interface AgentNoteChatActions {
27
+ sendingNoteId: string | null;
28
+ onSend: (agentNoteId: string) => void;
29
+ }
30
+
31
+ export interface AgentNoteStateActions {
32
+ savingNoteIds: ReadonlySet<string>;
33
+ onChange: (agentNoteId: string, value: boolean) => void;
34
+ }
35
+
36
+ export interface AgentNoteRefreshActions {
37
+ savingNoteIds: ReadonlySet<string>;
38
+ onRefresh: (agentNoteId: string) => void;
39
+ }
40
+
41
+ export interface AgentNotesProps {
42
+ onVisibilityChange?: (hasNotes: boolean) => void;
43
+ organizationId: string;
44
+ onChatStarted: (chat: AgentNoteChatStarted) => void;
45
+ }
46
+
47
+ export interface AgentNotesSnapshot {
48
+ notes: AgentNoteGQL[];
49
+ key: string;
50
+ }
@@ -0,0 +1,69 @@
1
+ import { useReactiveFragmentMap } from '@jsb188/graphql/client';
2
+ import { useAgentNotes } from '@jsb188/graphql/hooks/use-agentNote-qry';
3
+ import { FRAGMENT_NAMES, getFragmentBaseName } from '@jsb188/mday/constants/graphqlReactivity.ts';
4
+ import type { AgentNoteGQL } from '@jsb188/mday/types/agentNote.d.ts';
5
+ import { useLayoutEffect, useMemo, useRef } from 'react';
6
+ import {
7
+ getAgentNotesCollection,
8
+ getAgentNotesDisplayKey,
9
+ getLiveAgentNoteRows,
10
+ isAgentNotesAccessError,
11
+ reuseAgentNoteRows,
12
+ } from './AgentNotes.helpers';
13
+ import type { AgentNotesSnapshot } from './AgentNotes.types';
14
+
15
+ /*
16
+ * Reuse committed display objects by their actual row values. The small cache
17
+ * survives pending requests but never supplies visible data on its own.
18
+ */
19
+ export function useStableAgentNoteRows(notes: AgentNoteGQL[]): AgentNoteGQL[];
20
+ /* Reuse display objects while allowing an unaccepted collection to remain absent. */
21
+ export function useStableAgentNoteRows(notes: AgentNoteGQL[] | null): AgentNoteGQL[] | null;
22
+ /* Preserve only committed display identities across collection and fragment updates. */
23
+ export function useStableAgentNoteRows(notes: AgentNoteGQL[] | null) {
24
+ const previous = useRef<AgentNoteGQL[] | null>(null);
25
+ const key = notes === null ? null : getAgentNotesDisplayKey(notes);
26
+ // The key covers every field used by a row; unrelated query metadata is intentionally ignored.
27
+ const rows = useMemo(() => (notes === null ? null : reuseAgentNoteRows(previous.current, notes)), [key]);
28
+ useLayoutEffect(() => {
29
+ if (rows !== null) previous.current = rows;
30
+ }, [rows]);
31
+ return rows;
32
+ }
33
+
34
+ /*
35
+ * Keep retained rows subscribed to the shared note fragment while a replacement collection is pending.
36
+ */
37
+ export function useLiveAgentNoteRows(notes: AgentNoteGQL[] | null) {
38
+ const liveNotes: AgentNoteGQL[] | null = useReactiveFragmentMap(notes, getFragmentBaseName(FRAGMENT_NAMES.agentNote));
39
+ return useStableAgentNoteRows(getLiveAgentNoteRows(notes || [], liveNotes));
40
+ }
41
+
42
+ /*
43
+ * Fetch the complete homepage collection once. Groups share its accepted snapshot;
44
+ * local display limits never become query variables or trigger another request.
45
+ */
46
+ export function useAgentNotesCollection(organizationId: string) {
47
+ const result = useAgentNotes({ organizationId });
48
+ const accepted = !result.error && !result.loading && result.agentNotes !== null;
49
+ const accessDenied = isAgentNotesAccessError(result.error);
50
+ const loading = !result.error && (result.loading || !result.agentNotes);
51
+ const notes = useStableAgentNoteRows(accepted ? getAgentNotesCollection(result.agentNotes!, organizationId) : null);
52
+ const snapshot = useMemo<AgentNotesSnapshot | null>(
53
+ () => (notes === null ? null : { notes, key: getAgentNotesDisplayKey(notes) }),
54
+ [notes],
55
+ );
56
+ const lastAccepted = useRef(snapshot);
57
+ /* Keep local groups usable during recovery, but discard retained notes on access denial. */
58
+ useLayoutEffect(() => {
59
+ if (accepted || accessDenied) lastAccepted.current = snapshot;
60
+ }, [accepted, accessDenied, snapshot]);
61
+
62
+ return {
63
+ snapshot: accepted || accessDenied ? snapshot : lastAccepted.current,
64
+ ready: accepted || accessDenied,
65
+ accessDenied,
66
+ loading,
67
+ error: result.error,
68
+ };
69
+ }