@jsb188/ai-chat 1.1.2 → 1.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1672 +0,0 @@
1
- // @vitest-environment jsdom
2
- import { getFullDateTime } from '@jsb188/app/utils/datetime.ts';
3
- import { usePopOverActions, usePopOverDefinition, useTooltip } from '@jsb188/react/states';
4
- import { COMMON_ICON_NAMES } from '@jsb188/react-web/svgs/Icon';
5
- import { act, StrictMode, useEffect, useState, useSyncExternalStore } from 'react';
6
- import { createRoot, type Root } from 'react-dom/client';
7
- import { afterEach, beforeEach, expect, it, vi } from 'vitest';
8
- import { AgentNotes } from '../src/modules/AgentNotes';
9
- import { getAgentNotesCollection, getAgentNoteSourceLink } from '../src/modules/AgentNotes.helpers';
10
-
11
- const STATE = vi.hoisted(() => ({
12
- notes: [] as any[],
13
- bootstrapProgress: null as any,
14
- bootstrapError: null as any,
15
- bootstrapQueries: [] as any[],
16
- browseQueries: [] as any[],
17
- pendingBrowse: false,
18
- deletedIds: new Set<string>(),
19
- liveNotes: new Map<string, any>(),
20
- fragmentListeners: new Set<() => void>(),
21
- fragmentRevision: 0,
22
- fragmentSignature: '',
23
- rowRenders: new Map<string, number>(),
24
- requests: [] as { variables: any; callbacks: any }[],
25
- refreshRequests: [] as { variables: any; callbacks: any }[],
26
- updateRequests: [] as { variables: any; optimisticUI: any; callbacks: any }[],
27
- readRequests: [] as { organizationId: string; agentNoteId: string }[],
28
- rejectedMutation: null as 'refresh' | null,
29
- opened: vi.fn(),
30
- openModal: vi.fn(),
31
- }));
32
-
33
- vi.mock('@jsb188/react/states', async (importOriginal) => ({
34
- ...(await importOriginal<typeof import('@jsb188/react/states')>()),
35
- useOpenModalPopUp: () => STATE.openModal,
36
- }));
37
- vi.mock('@jsb188/graphql/hooks/use-organization-qry', () => ({
38
- /* Reference menus may render without organization display preferences in this note fixture. */
39
- useOrgRelFromMyOrganizations: () => ({ organization: null }),
40
- }));
41
- vi.mock('@jsb188/app/i18n/index.ts', () => ({
42
- default: {
43
- t: (key: string, values?: { documentType?: string; contentName?: string; query?: string; date?: string }) =>
44
- key === 'agent_note.view_source'
45
- ? `${key}:${values?.contentName}`
46
- : key === 'c.open_linked_document'
47
- ? `${key}:${values?.documentType}`
48
- : key === 'c.showing_search_results_for'
49
- ? `Showing search results for "${values?.query}"`
50
- : key === 'c.last_updated'
51
- ? `${key}:${values?.date}`
52
- : key,
53
- },
54
- }));
55
- vi.mock('@jsb188/graphql/hooks/use-aiChat-mtn', () => ({
56
- /*
57
- * Capture the callbacks belonging to each mutation attempt without starting a network request.
58
- */
59
- useStartAIChat: (callbacks: any, openModalPopUp: any) => ({
60
- startAIChat: (request: any) => {
61
- STATE.requests.push({
62
- variables: request.variables,
63
- callbacks: {
64
- ...callbacks,
65
- /* Mirror the request layer opening the error popup before notifying the owner. */
66
- onError: (error: any, variables: any) => {
67
- openModalPopUp?.(null, error);
68
- callbacks.onError(error, variables);
69
- },
70
- },
71
- });
72
- return Promise.resolve({});
73
- },
74
- setSaving: vi.fn(),
75
- }),
76
- }));
77
- vi.mock('@jsb188/graphql/hooks/use-agentNote-mtn', () => ({
78
- useMarkAgentNoteReadMutation: () => ({
79
- markAgentNoteRead: (request: any) => {
80
- STATE.readRequests.push(request.variables);
81
- return Promise.resolve({});
82
- },
83
- }),
84
- /* Model mutation state so transport failures must release the busy button and publish its error. */
85
- useRefreshAgentNote: (callbacks: any, openModalPopUp: any) => {
86
- const [saving, setSaving] = useState(false);
87
- const [error, setError] = useState<any>(null);
88
- return {
89
- refreshAgentNote: (request: any) => {
90
- setSaving(true);
91
- setError(null);
92
- STATE.refreshRequests.push({
93
- variables: request.variables,
94
- callbacks: {
95
- /* Settle mock transport state before delivering the domain mutation completion. */
96
- onCompleted: (note: any, resultError: any, variables: any) => {
97
- setSaving(false);
98
- setError(resultError);
99
- if (resultError) openModalPopUp?.(null, resultError);
100
- callbacks.onCompleted(note, resultError, variables);
101
- },
102
- },
103
- });
104
- return STATE.rejectedMutation === 'refresh' ? Promise.reject(new Error('Transport failed')) : Promise.resolve({});
105
- },
106
- saving,
107
- setSaving,
108
- error,
109
- setError,
110
- };
111
- },
112
- useUpdateAgentNote: (callbacks: any, openModalPopUp: any) => ({
113
- updateAgentNote: (request: any) => {
114
- STATE.updateRequests.push({
115
- ...request,
116
- callbacks: {
117
- ...callbacks,
118
- /* Mirror the shared mutation error popup while retaining attempt-specific callbacks. */
119
- onError: (error: any, variables: any) => {
120
- openModalPopUp?.(null, error);
121
- callbacks.onError(error, variables);
122
- },
123
- },
124
- });
125
- return Promise.resolve({});
126
- },
127
- saving: false,
128
- }),
129
- }));
130
- vi.mock('@jsb188/graphql/client', () => ({
131
- /* Deliver fragment changes through an observer, including when the memoized row parent does not rerender. */
132
- useReactiveFragmentMap: (notes: any[] | null) => {
133
- useSyncExternalStore(
134
- (listener) => {
135
- STATE.fragmentListeners.add(listener);
136
- return () => STATE.fragmentListeners.delete(listener);
137
- },
138
- () => STATE.fragmentRevision,
139
- () => 0,
140
- );
141
- return notes?.map((note) => ({ ...note, ...STATE.liveNotes.get(note.id), __deleted: STATE.deletedIds.has(note.id) }));
142
- },
143
- }));
144
- vi.mock('../src/ui/AgentNotesUI', async (original) => {
145
- const actual = await original<typeof import('../src/ui/AgentNotesUI')>();
146
- return {
147
- ...actual,
148
- /* Count real row renders while preserving the disclosure and controlled composer behavior. */
149
- AgentNoteItemUI: (props: Parameters<typeof actual.AgentNoteItemUI>[0]) => {
150
- STATE.rowRenders.set(props.headline, (STATE.rowRenders.get(props.headline) || 0) + 1);
151
- return <actual.AgentNoteItemUI {...props} />;
152
- },
153
- };
154
- });
155
- vi.mock('@jsb188/graphql/hooks/use-agentNote-qry', () => ({
156
- /* Keep review memory unavailable while exercising the safe status returned by the API. */
157
- useAgentNoteBootstrapProgress: (variables: any) => {
158
- STATE.bootstrapQueries.push(variables);
159
- return { progress: STATE.bootstrapProgress, error: STATE.bootstrapError };
160
- },
161
- /* The homepage loads every note once, independent of local groups and display limits. */
162
- useAgentNotes: (variables: any) => {
163
- STATE.browseQueries.push(variables);
164
- return { agentNotes: STATE.pendingBrowse ? null : STATE.notes, loading: STATE.pendingBrowse };
165
- },
166
- useSearchAgentNotes: () => {
167
- throw new Error('Agent Notes must not request search results.');
168
- },
169
- /* Preserve the query hook's default mount stamp unless its caller owns read marking. */
170
- useAgentNote: ({ organizationId, agentNoteId }: any, options: { markRead?: boolean } = {}) => {
171
- useEffect(() => {
172
- if (options.markRead !== false) STATE.readRequests.push({ organizationId, agentNoteId });
173
- }, [organizationId, agentNoteId, options.markRead]);
174
- return { agentNote: STATE.notes.find((note) => note.id === agentNoteId) };
175
- },
176
- }));
177
- vi.mock('@jsb188/react-web/svgs/Icon', async (importOriginal) => ({
178
- ...(await importOriginal<typeof import('@jsb188/react-web/svgs/Icon')>()),
179
- Icon: () => null,
180
- }));
181
- vi.mock('../src/modules/AIChatContent', () => ({ AIChatContent: ({ text }: any) => <p>{text}</p> }));
182
- vi.mock('@jsb188/react-web/modules/Link', async (importOriginal) => ({
183
- ...(await importOriginal<typeof import('@jsb188/react-web/modules/Link')>()),
184
- /* Render router links as plain anchors because the note list mounts without a router. */
185
- SmartLink: ({ to, linkClassName, ...props }: any) => (
186
- <a
187
- href={to}
188
- {...props}
189
- />
190
- ),
191
- }));
192
-
193
- let root: Root;
194
- let container: HTMLDivElement;
195
-
196
- beforeEach(() => {
197
- STATE.bootstrapProgress = null;
198
- STATE.bootstrapError = null;
199
- STATE.bootstrapQueries = [];
200
- vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
201
- vi.stubGlobal(
202
- 'ResizeObserver',
203
- class {
204
- observe = vi.fn();
205
- unobserve = vi.fn();
206
- disconnect = vi.fn();
207
- },
208
- );
209
- STATE.notes = [
210
- {
211
- id: 'note-one',
212
- organizationId: 'org-one',
213
- kind: 'INSIGHT',
214
- headline: 'First note',
215
- emoji: '📝',
216
- body: 'Current saved note',
217
- pinned: false,
218
- canManage: true,
219
- canPin: true,
220
- canDelete: true,
221
- },
222
- {
223
- id: 'note-two',
224
- organizationId: 'org-one',
225
- kind: 'INSIGHT',
226
- headline: 'Second note',
227
- emoji: '📝',
228
- body: 'Another note',
229
- pinned: false,
230
- canManage: true,
231
- canPin: true,
232
- canDelete: true,
233
- },
234
- ];
235
- STATE.browseQueries = [];
236
- STATE.pendingBrowse = false;
237
- STATE.deletedIds.clear();
238
- STATE.liveNotes.clear();
239
- STATE.fragmentRevision = 0;
240
- STATE.fragmentSignature = '';
241
- STATE.rowRenders.clear();
242
- STATE.requests = [];
243
- STATE.refreshRequests = [];
244
- STATE.updateRequests = [];
245
- STATE.readRequests = [];
246
- STATE.rejectedMutation = null;
247
- STATE.opened.mockClear();
248
- STATE.openModal.mockClear();
249
- container = document.createElement('div');
250
- document.body.append(container);
251
- root = createRoot(container);
252
- });
253
-
254
- afterEach(() => {
255
- act(() => root.unmount());
256
- container.remove();
257
- vi.restoreAllMocks();
258
- vi.unstubAllGlobals();
259
- vi.useRealTimers();
260
- });
261
-
262
- let tooltipState: ReturnType<typeof useTooltip>;
263
- let menuDefinition: ReturnType<typeof usePopOverDefinition>;
264
-
265
- /*
266
- * Observe real tooltip state and render the menu definition without the application's positioning shell.
267
- */
268
- const NoteMenuHost = () => {
269
- tooltipState = useTooltip();
270
- const menu = usePopOverDefinition();
271
- menuDefinition = menu;
272
- const { publishPopOverEvent } = usePopOverActions();
273
- if (menu?.name !== 'PO_LIST' || menu.closing) return null;
274
- return (
275
- <div data-note-menu>
276
- {menu.variables.options?.map((option) =>
277
- option.__type === 'LIST_ITEM' ? (
278
- <button
279
- key={option.name}
280
- type="button"
281
- aria-label={option.text}
282
- disabled={option.disabled || option.loading}
283
- aria-busy={!!option.loading}
284
- onClick={() => publishPopOverEvent({ action: 'ITEM', name: option.name ?? null, value: option.value })}
285
- >
286
- {option.text}
287
- {option.description}
288
- </button>
289
- ) : null,
290
- )}
291
- </div>
292
- );
293
- };
294
-
295
- /*
296
- * Find the requested inline action or open its menu option.
297
- */
298
- function getActionButton(action: string, headline?: string) {
299
- if (headline || !container.querySelector('.an_item [aria-expanded="true"]')) {
300
- const heading = headline
301
- ? container.querySelector<HTMLDivElement>(`.an_item [aria-expanded][aria-label="${headline}"]`)!
302
- : container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!;
303
- if (heading.getAttribute('aria-expanded') !== 'true') act(() => heading.click());
304
- }
305
- if (action !== 'archive_note' && action !== 'collapse_item') {
306
- return container
307
- .querySelector('.an_item [aria-expanded="true"]')!
308
- .querySelector<HTMLButtonElement>(`button[aria-label="agent_note.${action}"]`)!;
309
- }
310
- if (!container.querySelector('[data-note-menu]')) {
311
- act(() => container.querySelector<HTMLButtonElement>('button[aria-label="c.actions"]')!.click());
312
- }
313
- return container.querySelector<HTMLButtonElement>(
314
- `[data-note-menu] button[aria-label="${action === 'collapse_item' ? 'c' : 'agent_note'}.${action}"]`,
315
- )!;
316
- }
317
-
318
- /* Read the source navigation option from the open note menu. */
319
- function sourceLink() {
320
- if (!container.querySelector('[data-note-menu]')) return null;
321
- return menuDefinition?.name === 'PO_LIST'
322
- ? (menuDefinition.variables.options?.find((option) => option.__type === 'LIST_ITEM' && option.name === 'source') ?? null)
323
- : null;
324
- }
325
-
326
- /* Execute an inline action or an opened menu option. */
327
- function clickAction(action: string) {
328
- const button = getActionButton(action);
329
- act(() => button.click());
330
- }
331
-
332
- /*
333
- * Render the note list with a fresh host callback so mock query changes reach its memoized container.
334
- */
335
- function renderNotes(strictMode = false) {
336
- const notes = (
337
- <AgentNotes
338
- organizationId="org-one"
339
- onChatStarted={(chat) => STATE.opened(chat)}
340
- />
341
- );
342
- act(() => {
343
- root.render(
344
- <>
345
- <NoteMenuHost />
346
- {strictMode ? <StrictMode>{notes}</StrictMode> : notes}
347
- </>,
348
- );
349
- const signature = JSON.stringify([[...STATE.deletedIds], [...STATE.liveNotes]]);
350
- if (signature !== STATE.fragmentSignature) {
351
- STATE.fragmentSignature = signature;
352
- STATE.fragmentRevision += 1;
353
- for (const listener of STATE.fragmentListeners) listener();
354
- }
355
- });
356
- }
357
-
358
- it('shows safe review status only on an accepted empty homepage, never beside notes', () => {
359
- STATE.bootstrapProgress = {
360
- outcome: 'NO_USEFUL_BRIEF',
361
- lastReviewedAt: '2026-10-23T03:00:00Z',
362
- nextReviewAt: '2026-10-24T03:00:00Z',
363
- progressReport: 'Private source evidence must never be displayed.',
364
- };
365
- renderNotes();
366
- expect(STATE.bootstrapQueries).toHaveLength(0);
367
- expect(container.textContent).not.toContain('agent_note.no_ai_notes_found');
368
- STATE.notes = [];
369
- STATE.pendingBrowse = true;
370
- renderNotes();
371
- expect(container.textContent).not.toContain('agent_note.no_ai_notes_found');
372
- STATE.pendingBrowse = false;
373
- renderNotes();
374
- expect(container.textContent).toContain('agent_note.no_ai_notes_found');
375
- expect(STATE.bootstrapQueries.at(-1)).toEqual({ organizationId: 'org-one' });
376
- expect(container.textContent).toContain('agent_note.agent_note_discovery_waiting');
377
- expect(container.textContent).toContain('agent_note.agent_note_discovery_last_reviewed');
378
- expect(container.textContent).toContain('agent_note.agent_note_discovery_next_review');
379
- expect(container.textContent).not.toContain(STATE.bootstrapProgress.progressReport);
380
- });
381
-
382
- it('hides completed reviews and denied progress instead of showing stale status or internal errors', () => {
383
- STATE.notes = [];
384
- STATE.bootstrapProgress = {
385
- outcome: 'CREATED',
386
- lastReviewedAt: '2026-10-23T03:00:00Z',
387
- nextReviewAt: null,
388
- };
389
- renderNotes();
390
- expect(container.querySelector('[role="status"]')).toBeNull();
391
- STATE.bootstrapProgress.outcome = 'NO_USEFUL_BRIEF';
392
- STATE.bootstrapError = { message: 'Private database error' };
393
- renderNotes();
394
- expect(container.querySelector('[role="status"]')).toBeNull();
395
- expect(container.textContent).not.toContain('Private database error');
396
- });
397
-
398
- it('reorders homepage fragments by pin, priority and recency while keeping equal rows stable', () => {
399
- STATE.notes = [
400
- {
401
- ...STATE.notes[0],
402
- id: 'opaque-z',
403
- priority: 50,
404
- publishedAt: '2026-10-14T12:00:00Z',
405
- dataChangedAt: '2026-10-14T12:00:00Z',
406
- },
407
- {
408
- ...STATE.notes[1],
409
- id: 'opaque-a',
410
- priority: 50,
411
- publishedAt: '2026-10-15T12:00:00Z',
412
- dataChangedAt: '2026-10-13T12:00:00Z',
413
- },
414
- ];
415
- /* Read the actual rendered note order after each fragment-backed state update. */
416
- const headlines = () => Array.from(container.querySelectorAll('.an_item [aria-expanded] .ellip'), (element) => element.textContent);
417
- renderNotes();
418
- expect(headlines()).toEqual(['Second note', 'First note']);
419
-
420
- // An optimistic pin sorts first before the saved note brings its priority boost.
421
- STATE.notes = [{ ...STATE.notes[0], pinned: true }, STATE.notes[1]];
422
- renderNotes();
423
- expect(headlines()).toEqual(['First note', 'Second note']);
424
- expect(container.querySelector('h2')).toBeNull();
425
-
426
- STATE.notes = [
427
- { ...STATE.notes[0], priority: 1050 },
428
- { ...STATE.notes[1], pinned: true, needsAttention: true, priority: 1090 },
429
- ];
430
- renderNotes();
431
- expect(headlines()).toEqual(['Second note', 'First note']);
432
- expect(container.querySelectorAll('h2')).toHaveLength(0);
433
-
434
- // Equal priorities fall back to recency: the later publish or data change.
435
- STATE.notes = [{ ...STATE.notes[0], priority: 1090, dataChangedAt: '2026-10-16T12:00:00Z' }, STATE.notes[1]];
436
- renderNotes();
437
- expect(headlines()).toEqual(['First note', 'Second note']);
438
-
439
- // Equal priority and recency keep the received order.
440
- STATE.notes = [STATE.notes[1], { ...STATE.notes[0], dataChangedAt: STATE.notes[1].publishedAt }];
441
- renderNotes();
442
- expect(headlines()).toEqual(['Second note', 'First note']);
443
- });
444
-
445
- it('shows the publish time on the card and falls back to the data change time', () => {
446
- const publishedAt = '2026-10-12T15:00:00Z';
447
- const dataChangedAt = '2026-10-20T15:00:00Z';
448
- STATE.notes = [{ ...STATE.notes[0], publishedAt, dataChangedAt, updatedAt: '2026-10-25T15:00:00Z' }];
449
- renderNotes();
450
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
451
- const card = () => container.querySelector<HTMLElement>('.an_item')!.textContent;
452
- expect(card()).toContain(`c.last_updated:${getFullDateTime(publishedAt, { textDateStyle: 'short' })}`);
453
- STATE.notes = [{ ...STATE.notes[0], publishedAt: null }];
454
- renderNotes();
455
- expect(card()).toContain(`c.last_updated:${getFullDateTime(dataChangedAt, { textDateStyle: 'short' })}`);
456
- });
457
-
458
- it('preserves the expanded note DOM and marks explicit opens once across live regrouping', () => {
459
- renderNotes();
460
- expect(STATE.readRequests).toEqual([]);
461
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
462
- expect(STATE.readRequests).toEqual([{ organizationId: 'org-one', agentNoteId: 'note-one' }]);
463
- const originalComposer = getComposer();
464
- enterDraft('Preserve my caret');
465
- originalComposer.focus();
466
- originalComposer.setSelectionRange(4, 9);
467
- STATE.notes = [{ ...STATE.notes[0], pinned: true }, STATE.notes[1]];
468
- renderNotes();
469
- expect(getComposer()).toBe(originalComposer);
470
- expect(document.activeElement).toBe(originalComposer);
471
- expect(originalComposer.selectionStart).toBe(4);
472
- expect(originalComposer.selectionEnd).toBe(9);
473
- expect(STATE.readRequests).toHaveLength(1);
474
-
475
- // Reopening is a new user read even before the accordion's close animation unmounts its body.
476
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
477
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
478
- expect(STATE.readRequests).toHaveLength(2);
479
- renderNotes();
480
- expect(STATE.readRequests).toHaveLength(2);
481
- });
482
-
483
- it('marks an explicit expansion once across StrictMode replay and later detail remounts', () => {
484
- renderNotes(true);
485
- expect(STATE.readRequests).toEqual([]);
486
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
487
- expect(STATE.readRequests).toEqual([{ organizationId: 'org-one', agentNoteId: 'note-one' }]);
488
- STATE.notes = [{ ...STATE.notes[0], pinned: true }, STATE.notes[1]];
489
- renderNotes(true);
490
- expect(STATE.readRequests).toHaveLength(1);
491
- });
492
-
493
- /*
494
- * Find the first note's composer after expanding its disclosure.
495
- */
496
- function getComposer() {
497
- return container.querySelector('textarea') as HTMLTextAreaElement;
498
- }
499
-
500
- /*
501
- * Enter text through React's real controlled textarea event handling.
502
- */
503
- function enterDraft(text: string) {
504
- const textarea = getComposer();
505
- act(() => {
506
- Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!.call(textarea, text);
507
- textarea.dispatchEvent(new Event('input', { bubbles: true }));
508
- });
509
- }
510
-
511
- /*
512
- * Click the first note's send control, which is distinct from its disclosure and pin buttons.
513
- */
514
- function sendQuestion() {
515
- act(() => getComposer().closest('.v_stretch')!.querySelector<HTMLButtonElement>('button')!.click());
516
- }
517
-
518
- /*
519
- * Complete a captured request with the accepted chat and streaming ticket.
520
- */
521
- function completeRequest(index: number, aiChatId = 'existing-note-chat') {
522
- const request = STATE.requests[index];
523
- act(() =>
524
- request.callbacks.onCompleted({ startAIChat: { node: { id: aiChatId }, sessionKey: 'stream-ticket' } }, null, request.variables),
525
- );
526
- }
527
-
528
- it('retains failed drafts and retries once with the same request ID before opening the accepted note chat', () => {
529
- renderNotes();
530
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
531
- enterDraft(' What changed in this note? ');
532
- sendQuestion();
533
- sendQuestion();
534
-
535
- expect(STATE.requests).toHaveLength(1);
536
- expect(STATE.requests[0].variables).toEqual({
537
- organizationId: 'org-one',
538
- agentNoteId: 'note-one',
539
- text: 'What changed in this note?',
540
- clientRequestId: expect.any(String),
541
- });
542
- expect(getComposer().disabled).toBe(true);
543
- const first = STATE.requests[0];
544
- act(() => first.callbacks.onError({ message: 'Retry' }, first.variables));
545
- expect(getComposer().value).toBe(' What changed in this note? ');
546
- expect(getComposer().disabled).toBe(false);
547
- expect(container.querySelector('[role="alert"]')).toBeNull();
548
- expect(STATE.openModal).toHaveBeenCalledExactlyOnceWith(null, { message: 'Retry' });
549
-
550
- sendQuestion();
551
- expect(STATE.requests[1].variables.clientRequestId).toBe(first.variables.clientRequestId);
552
- completeRequest(1);
553
- expect(STATE.opened).toHaveBeenCalledOnce();
554
- expect(STATE.opened).toHaveBeenCalledWith({
555
- aiChatId: 'existing-note-chat',
556
- sessionKey: 'stream-ticket',
557
- text: 'What changed in this note?',
558
- submittedAt: expect.any(String),
559
- });
560
- expect(getComposer().value).toBe('');
561
- });
562
-
563
- /* Sending and settling a question must not update unrelated note headers or pin controls. */
564
- it('keeps unrelated rows stable across message submission, failure and success', () => {
565
- renderNotes();
566
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
567
- enterDraft('Summarize this note');
568
- const secondRow = container.querySelector('.an_item [aria-label="Second note"][aria-expanded]')!;
569
- const secondPin = secondRow.querySelector<HTMLButtonElement>('button[aria-label="agent_note.pin_note"]')!;
570
- const secondRenders = STATE.rowRenders.get('Second note');
571
- sendQuestion();
572
- expect(STATE.rowRenders.get('Second note')).toBe(secondRenders);
573
- const first = STATE.requests[0];
574
- act(() => first.callbacks.onError({ message: 'Retry' }, first.variables));
575
- expect(STATE.rowRenders.get('Second note')).toBe(secondRenders);
576
- sendQuestion();
577
- completeRequest(1);
578
- expect(STATE.rowRenders.get('Second note')).toBe(secondRenders);
579
- expect(secondRow.querySelector('button[aria-label="agent_note.pin_note"]')).toBe(secondPin);
580
- expect(secondPin.disabled).toBe(false);
581
- });
582
-
583
- /* Switching disclosures retains the single-chat guard without disabling note header actions. */
584
- it('keeps the newly opened composer disabled until the pending chat settles', () => {
585
- renderNotes();
586
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
587
- enterDraft('First question');
588
- sendQuestion();
589
- getActionButton('pin_note', 'Second note');
590
- expect(getComposer().disabled).toBe(true);
591
- expect(getActionButton('pin_note').disabled).toBe(false);
592
- const first = STATE.requests[0];
593
- act(() => first.callbacks.onError({ message: 'Retry' }, first.variables));
594
- expect(getComposer().disabled).toBe(false);
595
- enterDraft('Second question');
596
- sendQuestion();
597
- expect(STATE.requests[1].variables.agentNoteId).toBe('note-two');
598
- });
599
-
600
- it('keeps a pending question across a live pin reorder and clears only the accepted draft', () => {
601
- renderNotes();
602
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
603
- enterDraft('Summarize the latest changes');
604
- sendQuestion();
605
- STATE.notes = [{ ...STATE.notes[0], pinned: true }, STATE.notes[1]];
606
- renderNotes();
607
- expect(getComposer().value).toBe('Summarize the latest changes');
608
- expect(getComposer().disabled).toBe(true);
609
- completeRequest(0);
610
- expect(getComposer().value).toBe('');
611
- expect(STATE.opened).toHaveBeenCalledOnce();
612
- });
613
-
614
- it('ignores late chat callbacks from a failed attempt while retrying the same request ID', () => {
615
- renderNotes();
616
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
617
- enterDraft('Retry this question');
618
- sendQuestion();
619
- const first = STATE.requests[0];
620
- act(() => first.callbacks.onError({ message: 'Retry' }, first.variables));
621
- sendQuestion();
622
- expect(STATE.requests[1].variables.clientRequestId).toBe(first.variables.clientRequestId);
623
-
624
- completeRequest(0, 'outdated-chat');
625
- act(() => first.callbacks.onError({ message: 'Late failure' }, first.variables));
626
- expect(getComposer().disabled).toBe(true);
627
- expect(getComposer().value).toBe('Retry this question');
628
- expect(STATE.opened).not.toHaveBeenCalled();
629
- expect(container.querySelector('[role="alert"]')).toBeNull();
630
-
631
- completeRequest(1, 'accepted-chat');
632
- expect(getComposer().disabled).toBe(false);
633
- expect(getComposer().value).toBe('');
634
- expect(STATE.opened).toHaveBeenCalledOnce();
635
- expect(STATE.opened.mock.calls[0][0].aiChatId).toBe('accepted-chat');
636
- });
637
-
638
- it('patches only the requested pin and follows server updates when toggling it again', () => {
639
- renderNotes();
640
- const pinButton = container.querySelector<HTMLButtonElement>('button[aria-label="agent_note.pin_note"]')!;
641
- expect(pinButton.getAttribute('aria-pressed')).toBe('false');
642
- act(() => pinButton.click());
643
- expect(container.querySelector('.an_item [aria-expanded="true"]')).toBeNull();
644
- expect(STATE.updateRequests[0].variables).toEqual({
645
- organizationId: 'org-one',
646
- agentNoteId: 'note-one',
647
- pinned: true,
648
- });
649
- expect(STATE.updateRequests[0].optimisticUI).toEqual({
650
- action: 'update',
651
- fragmentKey: '$agentNoteFragment:note-one',
652
- update: { pinned: true },
653
- });
654
- STATE.notes = [{ ...STATE.notes[0], pinned: true }, STATE.notes[1]];
655
- renderNotes();
656
- const first = STATE.updateRequests[0];
657
- act(() => first.callbacks.onCompleted(true, null, first.variables));
658
- expect(container.querySelector('button[aria-label="agent_note.unpin_note"]')?.getAttribute('aria-pressed')).toBe('true');
659
- clickAction('unpin_note');
660
- expect(container.querySelector('.an_item [aria-expanded="true"]')).not.toBeNull();
661
- expect(STATE.updateRequests[1].variables).toEqual({
662
- organizationId: 'org-one',
663
- agentNoteId: 'note-one',
664
- pinned: false,
665
- });
666
- expect(STATE.updateRequests[1].optimisticUI.update).toEqual({ pinned: false });
667
- });
668
-
669
- /* Pin state and tooltip DOM changes belong only to the note being saved. */
670
- it('does not rerender or replace other pin buttons while pinning and unpinning a note', () => {
671
- renderNotes();
672
- const firstRow = container.querySelector('.an_item [aria-label="First note"][aria-expanded]')!;
673
- const secondRow = container.querySelector('.an_item [aria-label="Second note"][aria-expanded]')!;
674
- const secondPin = secondRow.querySelector<HTMLButtonElement>('button[aria-label="agent_note.pin_note"]')!;
675
- const secondRenders = STATE.rowRenders.get('Second note');
676
- for (const pinned of [true, false]) {
677
- act(() => firstRow.querySelector<HTMLButtonElement>(`button[aria-label="agent_note.${pinned ? 'pin' : 'unpin'}_note"]`)!.click());
678
- expect(secondPin.disabled).toBe(false);
679
- expect(secondRow.querySelector('button[aria-label="agent_note.pin_note"]')).toBe(secondPin);
680
- expect(STATE.rowRenders.get('Second note')).toBe(secondRenders);
681
- STATE.notes = [{ ...STATE.notes[0], pinned }, STATE.notes[1]];
682
- renderNotes();
683
- const request = STATE.updateRequests.at(-1)!;
684
- act(() => request.callbacks.onCompleted(true, null, request.variables));
685
- expect(STATE.rowRenders.get('Second note')).toBe(secondRenders);
686
- expect(secondRow.querySelector('button[aria-label="agent_note.pin_note"]')).toBe(secondPin);
687
- expect(secondPin.disabled).toBe(false);
688
- }
689
- expect(STATE.updateRequests).toHaveLength(2);
690
- });
691
-
692
- /* Requests for different notes can finish out of order without unlocking one another. */
693
- it('allows independent pin requests and settles only the matching note', () => {
694
- renderNotes();
695
- const rows = container.querySelectorAll('.an_item [aria-expanded]');
696
- /* Resolve the current button because pending tooltip wrappers replace it. */
697
- const pin = (index: number) => rows[index].querySelector<HTMLButtonElement>('button[aria-label="agent_note.pin_note"]')!;
698
- act(() => pin(0).click());
699
- expect(pin(0).disabled).toBe(true);
700
- expect(pin(1).disabled).toBe(false);
701
- act(() => pin(1).click());
702
- expect(pin(0).disabled).toBe(true);
703
- expect(pin(1).disabled).toBe(true);
704
- expect(STATE.updateRequests).toHaveLength(2);
705
- const [first, second] = STATE.updateRequests;
706
- act(() => second.callbacks.onCompleted(true, null, second.variables));
707
- expect(pin(0).disabled).toBe(true);
708
- expect(pin(1).disabled).toBe(false);
709
- act(() => first.callbacks.onError({ message: 'Pin failed' }, first.variables));
710
- expect(pin(0).disabled).toBe(false);
711
- expect(pin(1).disabled).toBe(false);
712
- });
713
-
714
- it('keeps a pin pending across optimistic regrouping and shows a popup after rollback', () => {
715
- renderNotes();
716
- clickAction('pin_note');
717
- STATE.notes = [{ ...STATE.notes[0], pinned: true }, STATE.notes[1]];
718
- renderNotes();
719
- const pendingPin = getActionButton('unpin_note');
720
- expect(pendingPin.disabled).toBe(true);
721
- act(() => pendingPin.click());
722
- expect(getActionButton('pin_note', 'Second note').disabled).toBe(false);
723
- expect(STATE.updateRequests).toHaveLength(1);
724
- const first = STATE.updateRequests[0];
725
- act(() => first.callbacks.onError({ message: 'Pin failed' }, first.variables));
726
- STATE.notes = [{ ...STATE.notes[0], pinned: false, canManage: true, canPin: true, canDelete: true }, STATE.notes[1]];
727
- renderNotes();
728
- expect(container.querySelector('[role="alert"]')).toBeNull();
729
- expect(STATE.openModal).toHaveBeenCalledExactlyOnceWith(null, { message: 'Pin failed' });
730
- const retryPin = getActionButton('pin_note', 'First note');
731
- expect(retryPin.disabled).toBe(false);
732
- act(() => retryPin.click());
733
- expect(STATE.updateRequests).toHaveLength(2);
734
- expect(container.querySelector('[role="alert"]')).toBeNull();
735
- });
736
-
737
- it('ignores late pin callbacks from a failed attempt while its retry remains pending', () => {
738
- renderNotes();
739
- /* Read the current inline control after pending state changes. */
740
- const pinButton = () => getActionButton('pin_note');
741
- clickAction('pin_note');
742
- const first = STATE.updateRequests[0];
743
- act(() => first.callbacks.onError({ message: 'Retry' }, first.variables));
744
- clickAction('pin_note');
745
- const retry = STATE.updateRequests[1];
746
-
747
- act(() => first.callbacks.onCompleted(true, null, first.variables));
748
- act(() => first.callbacks.onError({ message: 'Late failure' }, first.variables));
749
- expect(pinButton().disabled).toBe(true);
750
- expect(container.querySelector('[role="alert"]')).toBeNull();
751
- clickAction('pin_note');
752
- expect(STATE.updateRequests).toHaveLength(2);
753
-
754
- act(() => retry.callbacks.onCompleted(true, null, retry.variables));
755
- expect(pinButton().disabled).toBe(false);
756
- expect(container.querySelector('[role="alert"]')).toBeNull();
757
- });
758
-
759
- it('uses a new request ID for a changed question and respects multiline and composition input', () => {
760
- renderNotes();
761
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
762
- enterDraft(' ');
763
- sendQuestion();
764
- expect(STATE.requests).toHaveLength(0);
765
- enterDraft('First question');
766
- act(() => getComposer().dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', shiftKey: true, bubbles: true })));
767
- act(() => getComposer().dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', isComposing: true, bubbles: true })));
768
- expect(STATE.requests).toHaveLength(0);
769
- act(() => getComposer().dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })));
770
- const first = STATE.requests[0];
771
- act(() => first.callbacks.onError({}, first.variables));
772
- enterDraft('Different question');
773
- sendQuestion();
774
- expect(STATE.requests[1].variables.clientRequestId).not.toBe(first.variables.clientRequestId);
775
- completeRequest(1);
776
- expect(STATE.opened.mock.calls[0][0].text).toBe('Different question');
777
- });
778
-
779
- /* Read marking, refresh and note management must leave unrelated note rows and controls intact. */
780
- it('isolates read marking, refresh state and archive updates to the affected note', () => {
781
- renderNotes();
782
- const secondRow = container.querySelector('.an_item [aria-label="Second note"][aria-expanded]')!;
783
- const secondPin = secondRow.querySelector<HTMLButtonElement>('button[aria-label="agent_note.pin_note"]')!;
784
- const secondRenders = STATE.rowRenders.get('Second note');
785
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
786
- expect(STATE.readRequests).toHaveLength(1);
787
- expect(STATE.rowRenders.get('Second note')).toBe(secondRenders);
788
- clickAction('refresh_note');
789
- expect(STATE.rowRenders.get('Second note')).toBe(secondRenders);
790
- const failed = STATE.refreshRequests[0];
791
- act(() => failed.callbacks.onCompleted(null, { message: 'Retry' }, failed.variables));
792
- expect(STATE.rowRenders.get('Second note')).toBe(secondRenders);
793
- clickAction('refresh_note');
794
- const refreshed = STATE.refreshRequests[1];
795
- act(() => refreshed.callbacks.onCompleted(STATE.notes[0], null, refreshed.variables));
796
- expect(STATE.rowRenders.get('Second note')).toBe(secondRenders);
797
- clickAction('archive_note');
798
- expect(STATE.rowRenders.get('Second note')).toBe(secondRenders);
799
- STATE.notes = [{ ...STATE.notes[0], archivedAt: '2026-10-21T12:00:00Z' }, STATE.notes[1]];
800
- renderNotes();
801
- expect(STATE.rowRenders.get('Second note')).toBe(secondRenders);
802
- expect(secondRow.querySelector('button[aria-label="agent_note.pin_note"]')).toBe(secondPin);
803
- expect(secondPin.disabled).toBe(false);
804
- });
805
-
806
- it('disables refresh for fifteen minutes after receiving the current note, including refetches and reorders', () => {
807
- vi.useFakeTimers();
808
- vi.setSystemTime(new Date('2026-10-13T12:00:00Z'));
809
- renderNotes();
810
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
811
- const refreshButton = () => getActionButton('refresh_note');
812
- expect(refreshButton().disabled).toBe(false);
813
- clickAction('refresh_note');
814
- const request = STATE.refreshRequests[0];
815
- act(() => request.callbacks.onCompleted(STATE.notes[0], null, request.variables));
816
- expect(refreshButton().disabled).toBe(true);
817
- clickAction('refresh_note');
818
- expect(STATE.refreshRequests).toHaveLength(1);
819
- // A server refetch and pin reorder must not forget the local attempt or its remaining cooldown.
820
- STATE.notes = [{ ...STATE.notes[0], pinned: true, refreshedAt: '2026-10-12T12:00:00Z' }, STATE.notes[1]];
821
- renderNotes();
822
- expect(refreshButton().disabled).toBe(true);
823
- expect(getActionButton('archive_note').disabled).toBe(false);
824
- act(() => vi.advanceTimersByTime(15 * 60 * 1000 - 1));
825
- expect(refreshButton().disabled).toBe(true);
826
- act(() => vi.advanceTimersByTime(1));
827
- expect(refreshButton().disabled).toBe(false);
828
- });
829
-
830
- it('starts from the cached refresh time and does not start a cooldown on a failed request', () => {
831
- vi.useFakeTimers();
832
- vi.setSystemTime(new Date('2026-10-13T12:00:00Z'));
833
- STATE.notes[0].refreshedAt = '2026-10-13T11:50:00Z';
834
- renderNotes();
835
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
836
- const refreshButton = () => getActionButton('refresh_note');
837
- expect(refreshButton().disabled).toBe(true);
838
- act(() => vi.advanceTimersByTime(5 * 60 * 1000));
839
- expect(refreshButton().disabled).toBe(false);
840
- clickAction('refresh_note');
841
- const request = STATE.refreshRequests[0];
842
- act(() => request.callbacks.onCompleted(null, { message: 'Failed' }, request.variables));
843
- expect(refreshButton().disabled).toBe(false);
844
- });
845
-
846
- it.each(['refresh'] as const)('restores the %s action and shows an error popup after a transport rejection', async (action) => {
847
- STATE.rejectedMutation = action;
848
- renderNotes();
849
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
850
- /* Read the current inline control after transport state changes. */
851
- const actionButton = () => getActionButton(`${action}_note`);
852
- clickAction(`${action}_note`);
853
- expect(actionButton().disabled).toBe(true);
854
- expect(actionButton().getAttribute('aria-busy')).toBe(action === 'refresh' ? 'false' : 'true');
855
- await act(async () => {});
856
- expect(actionButton().disabled).toBe(false);
857
- expect(actionButton().getAttribute('aria-busy')).toBe('false');
858
- expect(container.querySelector('[role="alert"]')).toBeNull();
859
- expect(STATE.openModal).toHaveBeenCalledExactlyOnceWith(null, { message: `agent_note.agent_note_${action}_failed` });
860
- });
861
-
862
- it('shows a refresh warning on the inline refresh button and allows another refresh', () => {
863
- STATE.notes[0].refreshOutcome = {
864
- lastAttempt: { status: 'FAILED', completedAt: '2026-10-13T12:00:00Z', error: 'Writer unavailable' },
865
- published: {
866
- status: 'PARTIAL',
867
- completedAt: '2026-10-12T12:00:00Z',
868
- truncated: true,
869
- queries: {
870
- total: 2,
871
- succeeded: 1,
872
- failed: 1,
873
- errors: [{ name: 'Monthly revenue', code: 'GROUPS_OVERFLOW', message: 'Too many groups' }],
874
- },
875
- },
876
- };
877
- renderNotes();
878
- expect(container.textContent).not.toContain('agent_note.agent_note_refresh_partial_queries');
879
- expect(container.querySelector('[role="status"]')).toBeNull();
880
- expect(container.querySelector('[role="alert"]')).toBeNull();
881
- expect(container.textContent).not.toContain('agent_note.agent_note_refresh_query_failed');
882
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
883
- expect(container.textContent).not.toContain('agent_note.agent_note_refresh_incomplete');
884
- expect(container.querySelector('[role="status"]')).toBeNull();
885
- expect(container.textContent).not.toContain('agent_note.agent_note_refresh_query_failed');
886
- expect(container.textContent).not.toContain('agent_note.agent_note_refresh_failed_reason');
887
- expect(container.querySelector('button[aria-label="agent_note.refresh_note"] .bg_err')).not.toBeNull();
888
- clickAction('refresh_note');
889
- expect(STATE.refreshRequests).toHaveLength(1);
890
- expect(STATE.refreshRequests[0].variables.agentNoteId).toBe('note-one');
891
- });
892
-
893
- /*
894
- * Expanded reminder actions remain visible but disabled when management is not permitted.
895
- */
896
- it('hides collapsed management actions and disables them without permission when expanded', () => {
897
- STATE.notes = [{ ...STATE.notes[0], kind: 'REMINDER', canManage: false, canPin: false, canDelete: false }];
898
- renderNotes();
899
- for (const expanded of [false, true]) {
900
- if (expanded) {
901
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
902
- getActionButton('archive_note');
903
- }
904
- expect(container.querySelector('[aria-label="agent_note.pin_note"]')).toBeNull();
905
- for (const action of ['refresh_note', 'archive_note']) {
906
- const button = container.querySelector<HTMLButtonElement>(`button[aria-label="agent_note.${action}"]`);
907
- if (!expanded) {
908
- expect(button).toBeNull();
909
- continue;
910
- }
911
- expect(button!.disabled).toBe(true);
912
- act(() => button!.click());
913
- }
914
- }
915
- expect(STATE.refreshRequests).toHaveLength(0);
916
- expect(STATE.openModal).not.toHaveBeenCalled();
917
- STATE.notes = [{ ...STATE.notes[0], canManage: true, canPin: true }];
918
- renderNotes();
919
- expect(getActionButton('pin_note').disabled).toBe(false);
920
- expect(getActionButton('refresh_note').disabled).toBe(false);
921
- expect(getActionButton('archive_note').disabled).toBe(false);
922
- });
923
-
924
- it('applies the refresh cooldown to owners/admins while keeping archive usable', () => {
925
- vi.useFakeTimers();
926
- vi.setSystemTime(new Date('2026-10-13T12:00:00Z'));
927
- STATE.notes = [{ ...STATE.notes[0], kind: 'REMINDER', canRefreshWithoutCooldown: true, refreshedAt: '2026-10-13T11:59:59Z' }];
928
- renderNotes();
929
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
930
- expect(getActionButton('refresh_note').disabled).toBe(true);
931
- clickAction('refresh_note');
932
- expect(STATE.refreshRequests).toHaveLength(0);
933
- expect(getActionButton('archive_note').disabled).toBe(false);
934
- });
935
-
936
- it('allows pinning a shared reminder without enabling refresh or deletion', () => {
937
- STATE.notes = [{ ...STATE.notes[0], kind: 'REMINDER', canManage: false, canPin: true, canDelete: false }];
938
- renderNotes();
939
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
940
- const pin = getActionButton('pin_note');
941
- expect(pin.disabled).toBe(false);
942
- expect(getActionButton('refresh_note').disabled).toBe(true);
943
- expect(getActionButton('archive_note').disabled).toBe(true);
944
- act(() => pin.click());
945
- expect(STATE.updateRequests[0].variables.pinned).toBe(true);
946
- });
947
-
948
- /* Find a section's "show more" control below its list. */
949
- function showMoreButton(section = 'data_insights') {
950
- return (
951
- Array.from(sectionContent(section)?.querySelectorAll<HTMLButtonElement>('button') ?? []).find(
952
- (button) => button.textContent === 'c.show_more',
953
- ) ?? null
954
- );
955
- }
956
-
957
- it('reveals the remaining loaded notes without querying again', () => {
958
- STATE.notes = Array.from({ length: 7 }, (_, index) => ({ ...STATE.notes[0], id: `note-${index}`, headline: `Note ${index}` }));
959
- renderNotes();
960
- const queryCount = STATE.browseQueries.length;
961
- act(() => showMoreButton()!.click());
962
- expect(STATE.browseQueries).toHaveLength(queryCount);
963
- expect(sectionContent().querySelectorAll('.an_item')).toHaveLength(7);
964
- expect(showMoreButton()).toBeNull();
965
- });
966
-
967
- /* Exercise each group's display limit independently without asking the query owner to render again. */
968
- it('shows five per group and reveals 25 at a time beyond fifty without any further query', () => {
969
- const base = STATE.notes[0];
970
- STATE.notes = [
971
- ...Array.from({ length: 80 }, (_, index) => ({ ...base, id: `insight-${index}`, headline: `Insight ${index}` })),
972
- ...Array.from({ length: 6 }, (_, index) => ({
973
- ...base,
974
- id: `campaign-${index}`,
975
- kind: index % 2 ? 'CAMPAIGN_EMAIL' : 'CAMPAIGN_FORM',
976
- headline: `Campaign ${index}`,
977
- })),
978
- ...Array.from({ length: 5 }, (_, index) => ({ ...base, id: `task-${index}`, kind: 'REMINDER', headline: `Task ${index}` })),
979
- ];
980
- renderNotes();
981
- expect(STATE.browseQueries).toEqual([{ organizationId: 'org-one' }]);
982
- for (const group of ['scheduled_tasks', 'campaigns', 'data_insights']) {
983
- expect(sectionContent(group).querySelectorAll('.an_item')).toHaveLength(5);
984
- }
985
- expect(showMoreButton('scheduled_tasks')).toBeNull();
986
- for (const count of [25, 50, 75, 80]) {
987
- act(() => showMoreButton()!.click());
988
- expect(sectionContent().querySelectorAll('.an_item')).toHaveLength(count);
989
- expect(sectionContent('campaigns').querySelectorAll('.an_item')).toHaveLength(5);
990
- expect(STATE.browseQueries).toHaveLength(1);
991
- }
992
- expect(showMoreButton()).toBeNull();
993
- act(() => showMoreButton('campaigns')!.click());
994
- expect(sectionContent('campaigns').querySelectorAll('.an_item')).toHaveLength(6);
995
- expect(showMoreButton('campaigns')).toBeNull();
996
- expect(STATE.browseQueries).toHaveLength(1);
997
- });
998
-
999
- /* Local disclosure must not repeat the original identity/reordering bug after revealing more rows. */
1000
- it('expands the newly revealed note by ID and preserves its draft and order through collapse', () => {
1001
- STATE.notes = Array.from({ length: 8 }, (_, index) => ({ ...STATE.notes[0], id: `note-${index}`, headline: `Note ${index}` }));
1002
- renderNotes();
1003
- act(() => showMoreButton()!.click());
1004
- const header = container.querySelector<HTMLDivElement>('.an_item [aria-label="Note 5"]')!;
1005
- act(() => header.click());
1006
- expect(container.querySelector('.an_item [aria-expanded="true"]')).toBe(header);
1007
- expect(STATE.readRequests.at(-1)?.agentNoteId).toBe('note-5');
1008
- enterDraft('Keep the sixth note draft');
1009
- act(() => header.click());
1010
- expect(container.querySelector('.an_item [aria-expanded="true"]')).toBeNull();
1011
- expect(Array.from(container.querySelectorAll('.an_item [aria-expanded]'), (item) => item.getAttribute('aria-label'))).toEqual(
1012
- STATE.notes.map((note) => note.headline),
1013
- );
1014
- act(() => header.click());
1015
- expect(getComposer().value).toBe('Keep the sixth note draft');
1016
- });
1017
-
1018
- /* A server-driven collection refresh must not reset local disclosure or prevent revealing cached rows. */
1019
- it('retains local show more counts during refreshes and resets them on group collapse', () => {
1020
- vi.stubGlobal('matchMedia', () => ({ matches: true }));
1021
- STATE.notes = Array.from({ length: 30 }, (_, index) => ({ ...STATE.notes[0], id: `note-${index}`, headline: `Note ${index}` }));
1022
- renderNotes();
1023
- act(() => showMoreButton()!.click());
1024
- STATE.pendingBrowse = true;
1025
- renderNotes();
1026
- const queries = STATE.browseQueries.length;
1027
- act(() => showMoreButton()!.click());
1028
- expect(sectionContent().querySelectorAll('.an_item')).toHaveLength(30);
1029
- expect(STATE.browseQueries).toHaveLength(queries);
1030
- act(() => sectionHeader().click());
1031
- act(() => sectionHeader().click());
1032
- expect(sectionContent().querySelectorAll('.an_item')).toHaveLength(5);
1033
- STATE.pendingBrowse = false;
1034
- renderNotes();
1035
- expect(sectionContent().querySelectorAll('.an_item')).toHaveLength(5);
1036
- expect(showMoreButton()).not.toBeNull();
1037
- });
1038
-
1039
- /* Membership changes reveal and remove groups without a group-specific query. */
1040
- it('shows a campaign group when a campaign arrives and hides it after its last note is removed', () => {
1041
- renderNotes();
1042
- expect(sectionHeader('campaigns')).toBeNull();
1043
- STATE.notes = [...STATE.notes, { ...STATE.notes[0], id: 'campaign', kind: 'CAMPAIGN_EMAIL', headline: 'Email summary' }];
1044
- renderNotes();
1045
- expect(sectionContent('campaigns').textContent).toContain('Email summary');
1046
- STATE.notes = STATE.notes.filter((note) => note.id !== 'campaign');
1047
- renderNotes();
1048
- expect(sectionHeader('campaigns')).toBeNull();
1049
- expect(STATE.browseQueries.every((variables) => JSON.stringify(variables) === JSON.stringify({ organizationId: 'org-one' }))).toBe(
1050
- true,
1051
- );
1052
- });
1053
-
1054
- it('rerenders only the changed note when a same-query update publishes a new headline', () => {
1055
- renderNotes();
1056
- const second = STATE.rowRenders.get('Second note');
1057
- STATE.notes = [{ ...STATE.notes[0], headline: 'Updated first note' }, { ...STATE.notes[1] }];
1058
- renderNotes();
1059
- expect(container.textContent).toContain('Updated first note');
1060
- expect(STATE.rowRenders.get('Updated first note')).toBe(1);
1061
- expect(STATE.rowRenders.get('Second note')).toBe(second);
1062
- });
1063
-
1064
- it('uses the latest chat callback without rerendering idle note rows when the host callback changes', () => {
1065
- renderNotes();
1066
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
1067
- enterDraft('Send using latest callback');
1068
- const renders = new Map(STATE.rowRenders);
1069
- const latest = vi.fn();
1070
- act(() =>
1071
- root.render(
1072
- <>
1073
- <NoteMenuHost />
1074
- <AgentNotes
1075
- organizationId="org-one"
1076
- onChatStarted={latest}
1077
- />
1078
- </>,
1079
- ),
1080
- );
1081
- expect(STATE.rowRenders).toEqual(renders);
1082
- sendQuestion();
1083
- completeRequest(0);
1084
- expect(latest).toHaveBeenCalledOnce();
1085
- expect(STATE.opened).not.toHaveBeenCalled();
1086
- });
1087
-
1088
- /* Verify the merged control opens the modal with its source, without issuing a mutation. */
1089
- it('opens note management from one trash button and passes the reminder source', () => {
1090
- STATE.notes = [
1091
- {
1092
- ...STATE.notes[0],
1093
- title: 'Stale title',
1094
- headline: 'Current finding',
1095
- kind: 'REMINDER',
1096
- reminderWorkflowId: 'reminder-1',
1097
- ownedDataTableId: 'table-1',
1098
- canDelete: false,
1099
- },
1100
- ];
1101
- renderNotes();
1102
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
1103
- getActionButton('archive_note');
1104
- expect(container.querySelectorAll('button[aria-label="agent_note.archive_note"]')).toHaveLength(1);
1105
- expect(container.querySelector('button[aria-label="agent_note.delete_note"]')).toBeNull();
1106
- clickAction('archive_note');
1107
- expect(STATE.openModal).toHaveBeenCalledWith(
1108
- expect.objectContaining({
1109
- preset: 'ARCHIVE_AGENT_NOTE',
1110
- props: expect.objectContaining({
1111
- agentNoteId: 'note-one',
1112
- headline: 'Current finding',
1113
- kind: 'REMINDER',
1114
- reminderWorkflowId: 'reminder-1',
1115
- ownedDataTableId: 'table-1',
1116
- }),
1117
- }),
1118
- );
1119
- expect(STATE.updateRequests).toHaveLength(0);
1120
- });
1121
-
1122
- /* A nullable label never falls back to a stale title or removes the note's actions. */
1123
- it('uses the generic note label when headline is absent and preserves note identity', () => {
1124
- STATE.notes = [{ ...STATE.notes[0], title: 'Stale title', headline: null }];
1125
- renderNotes();
1126
- const header = container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!;
1127
- expect(header.getAttribute('aria-label')).toBe('agent_note.agent_note');
1128
- expect(container.textContent).not.toContain('Stale title');
1129
- act(() => header.click());
1130
- clickAction('archive_note');
1131
- expect(STATE.openModal).toHaveBeenCalledWith(
1132
- expect.objectContaining({
1133
- preset: 'ARCHIVE_AGENT_NOTE',
1134
- props: expect.objectContaining({ agentNoteId: 'note-one', headline: null }),
1135
- }),
1136
- );
1137
- });
1138
-
1139
- it('opens scheduled task deletion from a linked reminder without issuing a mutation', () => {
1140
- STATE.notes = [{ ...STATE.notes[0], kind: 'REMINDER', reminderWorkflowId: 'reminder-1' }];
1141
- renderNotes();
1142
- getActionButton('archive_note');
1143
- const button = container.querySelector<HTMLButtonElement>('button[aria-label="workflow.delete_scheduled_task"]')!;
1144
- expect(button.disabled).toBe(false);
1145
- act(() => button.click());
1146
- expect(STATE.openModal).toHaveBeenCalledExactlyOnceWith({
1147
- name: 'DELETE_SCHEDULED_TASK',
1148
- preset: 'DELETE_SCHEDULED_TASK',
1149
- props: {
1150
- organizationId: STATE.notes[0].organizationId,
1151
- workflowId: 'reminder-1',
1152
- title: STATE.notes[0].headline,
1153
- },
1154
- });
1155
- expect(STATE.updateRequests).toHaveLength(0);
1156
- });
1157
-
1158
- it.each([
1159
- ['INSIGHT', null, true, false],
1160
- ['REMINDER', null, true, false],
1161
- ['REMINDER', 'reminder-1', false, true],
1162
- ])('guards scheduled task deletion for %s with source %s and management access %s', (kind, reminderWorkflowId, canManage, visible) => {
1163
- STATE.notes = [{ ...STATE.notes[0], kind, reminderWorkflowId, canManage }];
1164
- renderNotes();
1165
- getActionButton('archive_note');
1166
- const button = container.querySelector<HTMLButtonElement>('button[aria-label="workflow.delete_scheduled_task"]');
1167
- if (visible) {
1168
- expect(button?.disabled).toBe(true);
1169
- act(() => button!.click());
1170
- } else expect(button).toBeNull();
1171
- expect(STATE.openModal).not.toHaveBeenCalled();
1172
- });
1173
-
1174
- /* Locate one outer disclosure independently of its note headers. */
1175
- function sectionHeader(section = 'data_insights') {
1176
- return container.querySelector<HTMLDivElement>(
1177
- `[role="button"][aria-label="${section === 'campaigns' ? 'campaign.campaigns' : `c.${section}`}"]`,
1178
- )!;
1179
- }
1180
-
1181
- /* Read a section's visible content independently of other lists. */
1182
- function sectionContent(section = 'data_insights') {
1183
- return container.querySelector<HTMLElement>(
1184
- `[role="region"][aria-label="${section === 'campaigns' ? 'campaign.campaigns' : `c.${section}`}"]`,
1185
- )!;
1186
- }
1187
-
1188
- it('hides every empty group', () => {
1189
- STATE.notes = [];
1190
- renderNotes();
1191
- expect(sectionContent('scheduled_tasks')).toBeNull();
1192
- expect(sectionContent()).toBeNull();
1193
- expect(sectionContent('campaigns')).toBeNull();
1194
- expect(showMoreButton('scheduled_tasks')).toBeNull();
1195
- expect(showMoreButton()).toBeNull();
1196
- });
1197
-
1198
- it('renders three sections by kind with attention as a row marker and only a title and chevron in each header', () => {
1199
- vi.stubGlobal('matchMedia', () => ({ matches: true }));
1200
- const base = STATE.notes[0];
1201
- STATE.notes = [
1202
- { ...base, id: 'attention-reminder', headline: 'Urgent reminder', kind: 'REMINDER', needsAttention: true, pinned: true },
1203
- { ...base, id: 'attention-data', headline: 'Urgent insight', kind: 'INSIGHT', needsAttention: true, pinned: false },
1204
- { ...base, id: 'reminder', headline: 'Scheduled digest', kind: 'REMINDER', pinned: true },
1205
- { ...base, id: 'other-reminder', headline: 'Other digest', kind: 'REMINDER', pinned: false },
1206
- { ...base, id: 'data', headline: 'Form summary', kind: 'CAMPAIGN_FORM', pinned: true },
1207
- { ...base, id: 'other-data', headline: 'Tracker', kind: 'INSIGHT', pinned: false },
1208
- ];
1209
- renderNotes();
1210
- expect(container.querySelectorAll('.an_item')).toHaveLength(6);
1211
- expect(sectionHeader('needs_attention')).toBeNull();
1212
- expect(sectionContent('scheduled_tasks').textContent).toContain('Urgent reminder');
1213
- expect(sectionContent().textContent).toContain('Urgent insight');
1214
- expect(sectionContent('campaigns').textContent).toContain('Form summary');
1215
- expect(sectionContent().textContent).not.toContain('Form summary');
1216
- for (const section of ['scheduled_tasks', 'campaigns', 'data_insights']) {
1217
- expect(sectionHeader(section).querySelectorAll('button')).toHaveLength(0);
1218
- expect(sectionHeader(section).querySelector('.h_right')?.lastElementChild?.classList.contains('toggle_expand_chevron')).toBe(true);
1219
- expect(sectionHeader(section).getAttribute('aria-expanded')).toBe('true');
1220
- expect(sectionContent(section).querySelectorAll('.an_item')).toHaveLength(
1221
- section === 'scheduled_tasks' ? 3 : section === 'campaigns' ? 1 : 2,
1222
- );
1223
- }
1224
- // The marker is visual only; the row's accessible name announces the attention state
1225
- const rows = Array.from(container.querySelectorAll('.an_item [aria-expanded]'), (header) => ({
1226
- label: header.getAttribute('aria-label'),
1227
- markers: header.querySelectorAll('.h_right button.cl_err[aria-label="c.needs_attention"]').length,
1228
- }));
1229
- expect(rows.filter((row) => row.markers || row.label?.includes('c.needs_attention'))).toEqual([
1230
- { label: 'Urgent reminder, c.needs_attention', markers: 1 },
1231
- { label: 'Urgent insight, c.needs_attention', markers: 1 },
1232
- ]);
1233
- expect(STATE.browseQueries).toEqual([{ organizationId: 'org-one' }]);
1234
- });
1235
-
1236
- it('preserves an expanded note and its draft while the outer list is collapsed and reopened', () => {
1237
- vi.stubGlobal('matchMedia', () => ({ matches: true }));
1238
- renderNotes();
1239
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
1240
- enterDraft('Keep this draft');
1241
- expect(sectionHeader().getAttribute('aria-expanded')).toBe('true');
1242
- const reads = STATE.readRequests.length;
1243
- act(() => sectionHeader().click());
1244
- expect(sectionHeader().getAttribute('aria-expanded')).toBe('false');
1245
- expect(container.querySelector('textarea')).toBeNull();
1246
- expect(sectionHeader('scheduled_tasks')).toBeNull();
1247
- act(() => sectionHeader().click());
1248
- expect(container.querySelector('.an_item [aria-expanded]')?.getAttribute('aria-expanded')).toBe('true');
1249
- expect(getComposer().value).toBe('Keep this draft');
1250
- expect(STATE.readRequests).toHaveLength(reads);
1251
- });
1252
-
1253
- /*
1254
- * Keep pin beside the disclosure control and dismiss its owned menu when the disclosure closes.
1255
- */
1256
- it('replaces the expanded chevron with an action menu and does not replay selections after reopening', () => {
1257
- renderNotes();
1258
- const heading = container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!;
1259
- const row = heading;
1260
- expect(row.querySelector('.toggle_expand_chevron')).not.toBeNull();
1261
- expect(row.querySelector('[aria-label="c.actions"]')).toBeNull();
1262
- expect(row.querySelectorAll('.h_right button')).toHaveLength(1);
1263
- act(() => heading.click());
1264
- expect(row.querySelector('.toggle_expand_chevron')).toBeNull();
1265
- expect(Array.from(row.lastElementChild!.querySelectorAll('button'), (button) => button.getAttribute('aria-label'))).toEqual([
1266
- 'agent_note.pin_note',
1267
- 'c.actions',
1268
- ]);
1269
- expect(container.querySelector('[data-note-menu]')).toBeNull();
1270
- getActionButton('archive_note');
1271
- expect(heading.getAttribute('aria-expanded')).toBe('true');
1272
- expect(Array.from(container.querySelectorAll('[data-note-menu] button'), (button) => button.getAttribute('aria-label'))).toEqual([
1273
- 'c.collapse_item',
1274
- 'agent_note.increase_priority',
1275
- 'agent_note.archive_note',
1276
- ]);
1277
- clickAction('archive_note');
1278
- expect(STATE.openModal).toHaveBeenCalledOnce();
1279
- expect(container.querySelector('[data-note-menu]')).toBeNull();
1280
- expect(heading.getAttribute('aria-expanded')).toBe('true');
1281
- getActionButton('archive_note');
1282
- clickAction('collapse_item');
1283
- expect(heading.getAttribute('aria-expanded')).toBe('false');
1284
- expect(container.querySelector('[data-note-menu]')).toBeNull();
1285
- expect(row.querySelector('.toggle_expand_chevron')).not.toBeNull();
1286
- expect(row.querySelector('[aria-label="c.actions"]')).toBeNull();
1287
- getActionButton('archive_note');
1288
- expect(heading.getAttribute('aria-expanded')).toBe('true');
1289
- expect(STATE.openModal).toHaveBeenCalledOnce();
1290
- expect(STATE.refreshRequests).toHaveLength(0);
1291
- expect(STATE.updateRequests).toHaveLength(0);
1292
- });
1293
-
1294
- /* Keep inline refresh independent of expansion and preserve its cooldown and permission rules. */
1295
- it('shows refresh after the expanded row timestamp without collapsing and shares cooldown and permissions', () => {
1296
- vi.useFakeTimers();
1297
- vi.setSystemTime(new Date('2026-10-13T12:00:00Z'));
1298
- renderNotes();
1299
- const heading = container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!;
1300
- const row = heading;
1301
- expect(row.querySelector('button[aria-label="agent_note.refresh_note"]')).toBeNull();
1302
- act(() => heading.click());
1303
- /* Disabled tooltip controls can replace the native button, so always read the current one. */
1304
- const refreshButton = () => row.querySelector<HTMLButtonElement>('button[aria-label="agent_note.refresh_note"]')!;
1305
- expect(heading.firstElementChild!.contains(refreshButton())).toBe(true);
1306
- expect(heading.lastElementChild!.contains(refreshButton())).toBe(false);
1307
- expect(refreshButton().disabled).toBe(false);
1308
- act(() => refreshButton().click());
1309
- expect(heading.getAttribute('aria-expanded')).toBe('true');
1310
- expect(STATE.refreshRequests).toHaveLength(1);
1311
- expect(refreshButton().disabled).toBe(true);
1312
- expect(refreshButton().getAttribute('aria-busy')).toBe('false');
1313
- const request = STATE.refreshRequests[0];
1314
- act(() => request.callbacks.onCompleted(STATE.notes[0], null, request.variables));
1315
- expect(refreshButton().disabled).toBe(true);
1316
- act(() => vi.advanceTimersByTime(15 * 60 * 1000));
1317
- expect(refreshButton().disabled).toBe(false);
1318
- STATE.notes = [{ ...STATE.notes[0], canManage: false }, STATE.notes[1]];
1319
- renderNotes();
1320
- expect(refreshButton().disabled).toBe(true);
1321
- act(() => refreshButton().click());
1322
- act(() => refreshButton().parentElement!.click());
1323
- expect(heading.getAttribute('aria-expanded')).toBe('true');
1324
- expect(STATE.refreshRequests).toHaveLength(1);
1325
- act(() => heading.click());
1326
- expect(row.querySelector('button[aria-label="agent_note.refresh_note"]')).toBeNull();
1327
- });
1328
-
1329
- /* Read the same tooltip that pointer hover or keyboard focus exposes on a disabled refresh control. */
1330
- function focusInlineRefresh() {
1331
- const row = container.querySelector('.an_item [aria-expanded="true"]')!;
1332
- const button = row.querySelector<HTMLButtonElement>('button[aria-label="agent_note.refresh_note"]')!;
1333
- const trigger = button.disabled ? button.parentElement! : button;
1334
- act(() => {
1335
- document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab', bubbles: true }));
1336
- trigger.focus();
1337
- });
1338
- return button;
1339
- }
1340
-
1341
- it.each([
1342
- [{ canManage: false }, true, 'agent_note.agent_note_manage_not_allowed'],
1343
- [{ refreshedAt: '2026-10-13T11:59:00Z' }, true, 'agent_note.agent_note_recently_refreshed'],
1344
- [{ refreshedAt: '2026-10-13T11:59:00Z', canRefreshWithoutCooldown: true }, true, 'agent_note.agent_note_recently_refreshed'],
1345
- [
1346
- { refreshOutcome: { lastAttempt: { status: 'FAILED', error: 'Unavailable' } } },
1347
- false,
1348
- 'agent_note.agent_note_refresh_failed_reason',
1349
- ],
1350
- [{ refreshOutcome: { lastAttempt: { status: 'FAILED' } } }, false, 'agent_note.agent_note_refresh_failed'],
1351
- [
1352
- {
1353
- refreshOutcome: {
1354
- published: { status: 'PARTIAL', truncated: false, queries: { total: 2, succeeded: 1, failed: 1, errors: [] } },
1355
- },
1356
- },
1357
- false,
1358
- 'agent_note.agent_note_refresh_partial_queries',
1359
- ],
1360
- [
1361
- {
1362
- refreshOutcome: {
1363
- published: { status: 'PARTIAL', truncated: true, queries: { total: 0, succeeded: 0, failed: 0, errors: [] } },
1364
- },
1365
- },
1366
- false,
1367
- 'agent_note.agent_note_refresh_incomplete',
1368
- ],
1369
- [
1370
- {
1371
- refreshOutcome: {
1372
- lastAttempt: { status: 'UNSUPPORTED', error: 'ANCHOR_UNAVAILABLE' },
1373
- published: { status: 'PARTIAL', truncated: false, queries: { total: 1, succeeded: 0, failed: 1, errors: [] } },
1374
- },
1375
- },
1376
- false,
1377
- 'agent_note.agent_note_refresh_unsupported',
1378
- ],
1379
- [{ canManage: false, refreshOutcome: { published: { status: 'PARTIAL' } } }, true, 'agent_note.agent_note_manage_not_allowed'],
1380
- ])('preserves the old inline refresh disabled state and tooltip for %j', (note, disabled, message) => {
1381
- vi.useFakeTimers();
1382
- vi.setSystemTime(new Date('2026-10-13T12:00:00Z'));
1383
- STATE.notes = [{ ...STATE.notes[0], ...note }];
1384
- renderNotes();
1385
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
1386
- expect(focusInlineRefresh().disabled).toBe(disabled);
1387
- expect(tooltipState.tooltip?.message).toBe(message);
1388
- expect(tooltipState.tooltip?.tooltipClassName).toBe('a_c');
1389
- });
1390
-
1391
- it('shows the queued reason without loading while the refresh request is pending and accepted', () => {
1392
- vi.useFakeTimers();
1393
- vi.setSystemTime(new Date('2026-10-13T12:00:00Z'));
1394
- renderNotes();
1395
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
1396
- const button = focusInlineRefresh();
1397
- act(() => button.click());
1398
- expect(focusInlineRefresh().disabled).toBe(true);
1399
- expect(tooltipState.tooltip?.message).toBe('agent_note.agent_note_recently_refreshed');
1400
- expect(button.getAttribute('aria-busy')).toBe('false');
1401
- const request = STATE.refreshRequests[0];
1402
- act(() => request.callbacks.onCompleted(STATE.notes[0], null, request.variables));
1403
- expect(tooltipState.tooltip?.message).toBe('agent_note.agent_note_recently_refreshed');
1404
- });
1405
-
1406
- /* Check the card's source link against the same destinations used by linked chat content. */
1407
- it.each([
1408
- [
1409
- 'CAMPAIGN_FORM',
1410
- { campaignId: 'campaign/form' },
1411
- '/app/outbound/forms/c/campaign%2Fform',
1412
- 'agent_note.view_source:agent_note.source_type.CAMPAIGN_FORM',
1413
- COMMON_ICON_NAMES.open_external_link,
1414
- ],
1415
- [
1416
- 'CAMPAIGN_EMAIL',
1417
- { campaignId: 'campaign-email' },
1418
- '/app/outbound/emails/c/campaign-email',
1419
- 'agent_note.view_source:agent_note.source_type.CAMPAIGN_EMAIL',
1420
- COMMON_ICON_NAMES.open_external_link,
1421
- ],
1422
- [
1423
- 'FIELD_DOC',
1424
- { fieldDocId: 'document-1', fieldDocProgramId: 'program-1' },
1425
- '/app/fd/program-1?filter=fieldDocIds,document-1',
1426
- 'agent_note.view_source:agent_note.source_type.FIELD_DOC',
1427
- COMMON_ICON_NAMES.open_external_link,
1428
- ],
1429
- [
1430
- 'REMINDER',
1431
- { reminderWorkflowId: 'reminder-1' },
1432
- '/app/runs/reminder-1',
1433
- 'agent_note.view_source:agent_note.source_type.REMINDER',
1434
- COMMON_ICON_NAMES.reminder,
1435
- ],
1436
- [
1437
- 'INSIGHT',
1438
- { ownedDataTableId: 'table/1' },
1439
- '/app/d/table%2F1',
1440
- 'agent_note.view_source:agent_note.source_type.INSIGHT',
1441
- COMMON_ICON_NAMES.data_table,
1442
- ],
1443
- ])(
1444
- 'links %s notes to their originating source in the menu without requiring note management permission',
1445
- (kind, source, to, text, iconName) => {
1446
- STATE.notes = [{ ...STATE.notes[0], kind, ...source, canManage: false, canPin: false }];
1447
- expect(getAgentNoteSourceLink(STATE.notes[0])).toEqual({ to, text, iconName });
1448
- renderNotes();
1449
- expect(sourceLink()).toBeNull();
1450
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
1451
- expect(container.querySelector('.an_item a[href]')).toBeNull();
1452
- getActionButton('archive_note');
1453
- expect(sourceLink()).toMatchObject({ to, text });
1454
- const options = menuDefinition?.name === 'PO_LIST' ? menuDefinition.variables.options : undefined;
1455
- expect(options?.some((option) => option.__type === 'LIST_ITEM' && option.name === 'source')).toBe(true);
1456
- expect(container.querySelector(`[data-note-menu] [aria-label="${text}"]`)).not.toBeNull();
1457
- },
1458
- );
1459
-
1460
- it.each([
1461
- ['INSIGHT', {}],
1462
- ['CAMPAIGN_FORM', {}],
1463
- ['CAMPAIGN_EMAIL', {}],
1464
- ['FIELD_DOC', {}],
1465
- ['FIELD_DOC', { fieldDocId: 'document-1' }],
1466
- ['REMINDER', {}],
1467
- ])('shows no source link for %s without an originating source (%o)', (kind, source) => {
1468
- STATE.notes = [{ ...STATE.notes[0], kind, ...source }];
1469
- renderNotes();
1470
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
1471
- expect(container.querySelector('.an_item [aria-expanded="true"]')).not.toBeNull();
1472
- getActionButton('archive_note');
1473
- expect(sourceLink()).toBeNull();
1474
- });
1475
-
1476
- it.each([
1477
- ['REMINDER', 'reminderWorkflowId', {}, (id: string) => `/app/runs/${id}`],
1478
- ['FIELD_DOC', 'fieldDocId', { fieldDocProgramId: 'program-1' }, (id: string) => `/app/fd/program-1?filter=fieldDocIds,${id}`],
1479
- ['INSIGHT', 'ownedDataTableId', {}, (id: string) => `/app/d/${id}`],
1480
- ])('updates and removes an obsolete %s source link while the card is open', (kind, sourceField, base, getSourcePath) => {
1481
- STATE.notes = [{ ...STATE.notes[0], kind, ...base, [sourceField]: 'source-one' }];
1482
- renderNotes();
1483
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
1484
- getActionButton('archive_note');
1485
- expect(sourceLink()).toMatchObject({ to: getSourcePath('source-one') });
1486
- STATE.notes = [{ ...STATE.notes[0], [sourceField]: 'source-two' }];
1487
- renderNotes();
1488
- expect(sourceLink()).toMatchObject({ to: getSourcePath('source-two') });
1489
- STATE.notes = [{ ...STATE.notes[0], [sourceField]: null }];
1490
- renderNotes();
1491
- expect(sourceLink()).toBeNull();
1492
- expect(container.querySelector('.an_item [aria-expanded="true"]')).not.toBeNull();
1493
- });
1494
-
1495
- /* Server-rendered results follow the body; a listed table's title opens it, and missing or failed results say so. */
1496
- it('renders result blocks below the note body with table links and missing or failed result lines', () => {
1497
- const block = {
1498
- display: 'TABLE',
1499
- computedAt: '2026-10-30T12:00:00Z',
1500
- timeZone: 'America/Los_Angeles',
1501
- shownCount: 50,
1502
- matchedCount: 120,
1503
- truncated: false,
1504
- error: null,
1505
- };
1506
- STATE.notes = [
1507
- {
1508
- ...STATE.notes[0],
1509
- kind: 'INSIGHT',
1510
- resultBlocks: [
1511
- { ...block, name: 'weekly', title: 'Weekly sales', markdown: '| Week | Sales |', dataTableId: 'table-1' },
1512
- { ...block, name: 'harvest', title: 'Harvest total', markdown: 'Total: 5', dataTableId: null, error: 'Column removed' },
1513
- { ...block, name: 'pending', title: null, markdown: '', computedAt: null, dataTableId: null },
1514
- ],
1515
- },
1516
- ];
1517
- renderNotes();
1518
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
1519
- const card = container.querySelector<HTMLElement>('.an_item')!;
1520
- const text = card.textContent!;
1521
- expect(text.indexOf('Current saved note')).toBeLessThan(text.indexOf('Weekly sales'));
1522
- expect(text.indexOf('| Week | Sales |')).toBeLessThan(text.indexOf('Total: 5'));
1523
- expect(Array.from(card.querySelectorAll('h4'), (heading) => heading.textContent)).toEqual(['Weekly sales', 'Harvest total']);
1524
- expect(Array.from(card.querySelectorAll('h4 a'), (link) => link.getAttribute('href'))).toEqual(['/app/d/table-1']);
1525
- expect(text.indexOf('Total: 5')).toBeLessThan(text.indexOf('agent_note.agent_note_result_error'));
1526
- expect(text).toContain('agent_note.agent_note_result_pending');
1527
- expect(text.match(/agent_note\.agent_note_result_/g)).toHaveLength(2);
1528
- expect(card.querySelectorAll('p.cl_lt.mt_md')).toHaveLength(4);
1529
- expect(text).toContain('agent_note.result_showing');
1530
- expect(text).toContain('agent_note.result_as_of');
1531
- });
1532
-
1533
- /* The collapsed row summarizes with the headline; the opened header displays the update time. */
1534
- it('shows the update time in the expanded header and keeps the headline in the body', () => {
1535
- STATE.notes = [{ ...STATE.notes[0], title: 'Weekly sales tracker', headline: 'Sales rose this week' }];
1536
- renderNotes();
1537
- const header = container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!;
1538
- expect(header.getAttribute('aria-label')).toBe('Sales rose this week');
1539
- expect(header.textContent).toContain('Sales rose this week');
1540
- expect(header.textContent).not.toContain('Weekly sales tracker');
1541
- act(() => header.click());
1542
- expect(header.getAttribute('aria-expanded')).toBe('true');
1543
- expect(header.getAttribute('aria-label')).toContain('c.last_updated:');
1544
- expect(header.textContent).toContain('c.last_updated:');
1545
- expect(header.textContent).not.toContain('Weekly sales tracker');
1546
- expect(header.querySelector('.ellip')?.classList.contains('cl_md')).toBe(true);
1547
- expect(header.textContent).not.toContain('Sales rose this week');
1548
- const card = container.querySelector<HTMLElement>('.an_item')!;
1549
- expect(card.textContent).toContain('Sales rose this week');
1550
- expect(card.textContent).toContain('c.last_updated');
1551
- });
1552
-
1553
- /* A row can move within its section or be hidden without owning the pending refresh request. */
1554
- it('retains a pending refresh across reordering and records its cooldown while its section is collapsed', () => {
1555
- vi.useFakeTimers();
1556
- vi.setSystemTime(new Date('2026-10-22T12:00:00Z'));
1557
- vi.stubGlobal('matchMedia', () => ({ matches: true }));
1558
- renderNotes();
1559
- clickAction('refresh_note');
1560
- const request = STATE.refreshRequests[0];
1561
- STATE.notes = [STATE.notes[1], { ...STATE.notes[0], needsAttention: true, priority: 90 }];
1562
- renderNotes();
1563
- const pendingButton = getActionButton('refresh_note');
1564
- expect(pendingButton.disabled).toBe(true);
1565
- expect(pendingButton.getAttribute('aria-busy')).toBe('false');
1566
- act(() => pendingButton.click());
1567
- expect(STATE.refreshRequests).toHaveLength(1);
1568
-
1569
- act(() => sectionHeader().click());
1570
- expect(getComposer()).toBeNull();
1571
- act(() => request.callbacks.onCompleted(STATE.notes[1], null, request.variables));
1572
- act(() => sectionHeader().click());
1573
- const acceptedButton = getActionButton('refresh_note');
1574
- expect(acceptedButton.getAttribute('aria-busy')).toBe('false');
1575
- expect(acceptedButton.disabled).toBe(true);
1576
- act(() => vi.advanceTimersByTime(15 * 60 * 1000));
1577
- expect(getActionButton('refresh_note').disabled).toBe(false);
1578
- });
1579
-
1580
- /* A previous response must not release a newer refresh request for the same note. */
1581
- it('ignores stale refresh completions while a retry remains pending', () => {
1582
- renderNotes();
1583
- clickAction('refresh_note');
1584
- const first = STATE.refreshRequests[0];
1585
- act(() => first.callbacks.onCompleted(null, { message: 'Retry' }, first.variables));
1586
- clickAction('refresh_note');
1587
- const retry = STATE.refreshRequests[1];
1588
- act(() => first.callbacks.onCompleted(STATE.notes[0], null, first.variables));
1589
- expect(getActionButton('refresh_note').getAttribute('aria-busy')).toBe('false');
1590
- expect(getActionButton('pin_note').disabled).toBe(false);
1591
- act(() => retry.callbacks.onCompleted(null, { message: 'Try again' }, retry.variables));
1592
- expect(getActionButton('refresh_note').disabled).toBe(false);
1593
- });
1594
-
1595
- /* A pending request must hand its accepted chat to the current host callback. */
1596
- it('uses the latest chat callback when the host changes during a pending question', () => {
1597
- renderNotes();
1598
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
1599
- enterDraft('Keep the pending question');
1600
- sendQuestion();
1601
- const latest = vi.fn();
1602
- act(() =>
1603
- root.render(
1604
- <>
1605
- <NoteMenuHost />
1606
- <AgentNotes
1607
- organizationId="org-one"
1608
- onChatStarted={latest}
1609
- />
1610
- </>,
1611
- ),
1612
- );
1613
- completeRequest(0);
1614
- expect(latest).toHaveBeenCalledOnce();
1615
- expect(STATE.opened).not.toHaveBeenCalled();
1616
- });
1617
-
1618
- /* Verify live menu updates and duplicate-click protection for both priority directions. */
1619
- it.each([false, true])('updates priority from %s while keeping its open menu disabled until settlement', (needsAttention) => {
1620
- STATE.notes[0].needsAttention = needsAttention;
1621
- renderNotes();
1622
- getActionButton('archive_note');
1623
- const label = needsAttention ? 'decrease_priority' : 'increase_priority';
1624
- const option = container.querySelector<HTMLButtonElement>(`[aria-label="agent_note.${label}"]`)!;
1625
- act(() => option.click());
1626
- expect(STATE.updateRequests).toHaveLength(1);
1627
- const request = STATE.updateRequests[0];
1628
- expect(request.variables).toEqual({ organizationId: 'org-one', agentNoteId: STATE.notes[0].id, needsAttention: !needsAttention });
1629
- expect(request.optimisticUI).toBeUndefined();
1630
- const saving = container.querySelector<HTMLButtonElement>('[aria-label="agent_note.updating_priority"]')!;
1631
- expect(saving.disabled).toBe(true);
1632
- act(() => saving.click());
1633
- expect(STATE.updateRequests).toHaveLength(1);
1634
- act(() => request.callbacks.onError({}, request.variables));
1635
- expect(container.querySelector<HTMLButtonElement>(`[aria-label="agent_note.${label}"]`)!.disabled).toBe(false);
1636
- });
1637
-
1638
- /* A detail response recalculates decay later than the paginated collection. */
1639
- it('keeps tied notes in order when opening one refreshes only its decayed priority', () => {
1640
- const notes = STATE.notes.map((note, index) => ({
1641
- ...note,
1642
- kind: 'REMINDER' as const,
1643
- importance: 50,
1644
- needsAttention: false,
1645
- pinned: false,
1646
- publishedAt: '2026-10-31T12:00:00Z',
1647
- dataChangedAt: '2026-10-31T12:00:00Z',
1648
- priority: index === 0 ? 49.999 : 50,
1649
- }));
1650
- expect(getAgentNotesCollection(notes, notes[0].organizationId).map((note) => note.id)).toEqual(notes.map((note) => note.id));
1651
- });
1652
-
1653
- /* Worker activity does not control refresh loading or pin availability. */
1654
- it.each([false, true])('keeps refresh disabled without loading independently of the worker (cooldown bypass: %s)', (bypass) => {
1655
- STATE.notes[0] = { ...STATE.notes[0], canRefreshWithoutCooldown: bypass };
1656
- renderNotes();
1657
- act(() => container.querySelector<HTMLDivElement>('.an_item [aria-expanded]')!.click());
1658
- clickAction('refresh_note');
1659
- const request = STATE.refreshRequests[0];
1660
- STATE.notes[0] = { ...STATE.notes[0], refreshing: true };
1661
- act(() => request.callbacks.onCompleted(STATE.notes[0], null, request.variables));
1662
- renderNotes();
1663
- expect(getActionButton('refresh_note').disabled).toBe(true);
1664
- expect(getActionButton('refresh_note').getAttribute('aria-busy')).toBe('false');
1665
- expect(getActionButton('pin_note').disabled).toBe(false);
1666
- clickAction('refresh_note');
1667
- expect(STATE.refreshRequests).toHaveLength(1);
1668
- STATE.notes[0] = { ...STATE.notes[0], refreshing: false };
1669
- renderNotes();
1670
- expect(getActionButton('refresh_note').getAttribute('aria-busy')).toBe('false');
1671
- expect(getActionButton('refresh_note').disabled).toBe(true);
1672
- });