@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,274 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import { AGENT_NOTE_PRIORITY, AGENT_NOTE_REFRESH_TIMING } from '@jsb188/mday/constants/agentNote.ts';
3
+ import type { AgentNoteGQL, AgentNoteRefreshOutcomeObj, AgentNoteResultBlockGQL } from '@jsb188/mday/types/agentNote.d.ts';
4
+ import { makeFieldDocFormPath } from '@jsb188/mday-web/utils/route';
5
+ import { COMMON_ICON_NAMES } from '@jsb188/react-web/svgs/Icon';
6
+ import { AGENT_NOTE_DISPLAY_LIMITS } from './AgentNotes.constants';
7
+
8
+ type AgentNoteSourceFields = Pick<
9
+ AgentNoteGQL,
10
+ 'kind' | 'campaignId' | 'fieldDocId' | 'fieldDocProgramId' | 'reminderWorkflowId' | 'ownedDataTableId'
11
+ >;
12
+
13
+ /*
14
+ * Reveal 25 notes on the first click, then 25 more per click, without a server request or hard cap.
15
+ */
16
+ export function getAgentNotesSectionNextLimit(limit: number) {
17
+ return limit < AGENT_NOTE_DISPLAY_LIMITS.increment
18
+ ? AGENT_NOTE_DISPLAY_LIMITS.increment
19
+ : limit + AGENT_NOTE_DISPLAY_LIMITS.increment;
20
+ }
21
+
22
+ /*
23
+ * Show when the note was last published; notes without a publish time fall back to their last data change.
24
+ */
25
+ export function getAgentNoteDisplayTime(note: AgentNoteGQL) {
26
+ return note.publishedAt || note.dataChangedAt;
27
+ }
28
+
29
+ /*
30
+ * Keep a manual attempt disabled for fifteen minutes, even if a refetch
31
+ * replaces its optimistic refresh timestamp with an older server value.
32
+ */
33
+ export function getAgentNoteRefreshCooldownMS(refreshedAt: string | null, attemptedAt?: string) {
34
+ const latest = Math.max(Date.parse(refreshedAt || '') || 0, Date.parse(attemptedAt || '') || 0);
35
+ return Math.max(0, latest + AGENT_NOTE_REFRESH_TIMING.manualCooldownMS - Date.now());
36
+ }
37
+
38
+ /*
39
+ * Return a note's recency like the server orders it: the later of its last publish (its creation before the first
40
+ * publish) and its last data change.
41
+ */
42
+ function getAgentNoteRecencyMS(note: AgentNoteGQL) {
43
+ return Math.max(Date.parse(note.publishedAt || note.createdAt || '') || 0, Date.parse(note.dataChangedAt) || 0);
44
+ }
45
+
46
+ /*
47
+ * Compare priorities at one instant so fetching a detail cannot lower only that
48
+ * row's score relative to older cached scores from the list request.
49
+ */
50
+ function getAgentNoteSortPriority(note: AgentNoteGQL, now: number) {
51
+ if (note.importance === undefined) return note.priority ?? 0;
52
+ const { pinnedBoost, attentionBoost, defaultImportance, decayPerDay, maxDecay } = AGENT_NOTE_PRIORITY;
53
+ const recency = getAgentNoteRecencyMS(note);
54
+ const decay = recency ? Math.min(maxDecay, decayPerDay * Math.max(0, (now - recency) / 86_400_000)) : maxDecay;
55
+ return (
56
+ Number(!!note.pinned) * pinnedBoost +
57
+ Number(!!note.needsAttention) * attentionBoost +
58
+ (note.importance ?? defaultImportance) -
59
+ decay
60
+ );
61
+ }
62
+
63
+ /* Restore homepage order while preserving received order for equal scores and recency. */
64
+ function compareAgentNotesHomepageOrder(left: AgentNoteGQL, right: AgentNoteGQL, now: number) {
65
+ return (
66
+ Number(!!right.pinned) - Number(!!left.pinned) ||
67
+ getAgentNoteSortPriority(right, now) - getAgentNoteSortPriority(left, now) ||
68
+ getAgentNoteRecencyMS(right) - getAgentNoteRecencyMS(left)
69
+ );
70
+ }
71
+
72
+ /*
73
+ * Keep the organization's active notes and restore homepage order after live updates.
74
+ */
75
+ export function getAgentNotesCollection(notes: AgentNoteGQL[], organizationId: string) {
76
+ const seen = new Set<string>();
77
+ const visible: AgentNoteGQL[] = [];
78
+ for (const note of notes) {
79
+ if (note.__deleted || note.organizationId !== organizationId || seen.has(note.id) || note.archivedAt) continue;
80
+ seen.add(note.id);
81
+ visible.push(note);
82
+ }
83
+ if (visible.length < 2) return visible;
84
+ const now = Date.now();
85
+ return visible.sort((left, right) => compareAgentNotesHomepageOrder(left, right, now));
86
+ }
87
+
88
+ /*
89
+ * Compare rendered row data rather than request metadata, rank scores, cursors or object identity.
90
+ */
91
+ export function getAgentNotesDisplayKey(notes: AgentNoteGQL[]) {
92
+ return JSON.stringify(
93
+ notes.map((note) => [
94
+ note.id,
95
+ note.organizationId,
96
+ note.kind,
97
+ note.campaignId,
98
+ note.fieldDocId,
99
+ note.fieldDocProgramId,
100
+ note.reminderWorkflowId,
101
+ note.ownedDataTableId,
102
+ note.emoji,
103
+ note.headline,
104
+ note.pinned,
105
+ note.importance,
106
+ note.createdAt,
107
+ note.archivedAt,
108
+ note.needsAttention,
109
+ note.publishedAt,
110
+ note.dataChangedAt,
111
+ note.refreshing,
112
+ note.refreshAvailableAt,
113
+ note.refreshedAt,
114
+ note.updatedAt,
115
+ note.refreshOutcome,
116
+ note.canManage,
117
+ note.canRefreshWithoutCooldown,
118
+ note.canPin,
119
+ note.canDelete,
120
+ ]),
121
+ );
122
+ }
123
+
124
+ /*
125
+ * Never retain content after an authoritative request reports that its scope is inaccessible.
126
+ */
127
+ export function isAgentNotesAccessError(error: unknown) {
128
+ if (!error || typeof error !== 'object') return false;
129
+ const statusCode = Number((error as { statusCode?: unknown }).statusCode);
130
+ return statusCode === 401 || statusCode === 403 || statusCode === 404;
131
+ }
132
+
133
+ /*
134
+ * Keep unchanged row objects and nested display snapshots so request metadata
135
+ * and parent renders neither rerender every note nor mutate outgoing content.
136
+ */
137
+ export function reuseAgentNoteRows(previous: AgentNoteGQL[] | null, notes: AgentNoteGQL[]) {
138
+ const byId = new Map(previous?.map((note) => [note.id, note]));
139
+ const rows = notes.map((note) => {
140
+ const existing = byId.get(note.id);
141
+ if (existing && getAgentNotesDisplayKey([existing]) === getAgentNotesDisplayKey([note])) return existing;
142
+ return { ...note, refreshOutcome: note.refreshOutcome ? structuredClone(note.refreshOutcome) : undefined };
143
+ });
144
+ return previous?.length === rows.length && rows.every((note, index) => note === previous[index]) ? previous : rows;
145
+ }
146
+
147
+ /*
148
+ * Apply live actions, attention, outcomes and permissions to retained rows without replacing
149
+ * their outgoing headlines or membership with an unfinished request.
150
+ */
151
+ export function getLiveAgentNoteRows(notes: AgentNoteGQL[], liveNotes: AgentNoteGQL[] | null) {
152
+ if (!notes.length || !liveNotes?.length) return notes;
153
+ const byId = new Map(liveNotes.map((note) => [note.id, note]));
154
+ return notes
155
+ .filter((note) => !byId.get(note.id)?.__deleted)
156
+ .map((note) => {
157
+ const live = byId.get(note.id);
158
+ if (
159
+ !live ||
160
+ (live.pinned === note.pinned &&
161
+ live.needsAttention === note.needsAttention &&
162
+ live.canManage === note.canManage &&
163
+ live.canRefreshWithoutCooldown === note.canRefreshWithoutCooldown &&
164
+ live.canPin === note.canPin &&
165
+ live.canDelete === note.canDelete &&
166
+ live.refreshing === note.refreshing &&
167
+ live.refreshAvailableAt === note.refreshAvailableAt &&
168
+ live.refreshedAt === note.refreshedAt &&
169
+ live.updatedAt === note.updatedAt &&
170
+ (live.refreshOutcome === note.refreshOutcome || JSON.stringify(live.refreshOutcome) === JSON.stringify(note.refreshOutcome)))
171
+ )
172
+ return note;
173
+ return {
174
+ ...note,
175
+ pinned: live.pinned,
176
+ needsAttention: live.needsAttention,
177
+ canManage: live.canManage,
178
+ canRefreshWithoutCooldown: live.canRefreshWithoutCooldown,
179
+ canPin: live.canPin,
180
+ canDelete: live.canDelete,
181
+ refreshing: live.refreshing,
182
+ refreshAvailableAt: live.refreshAvailableAt,
183
+ refreshedAt: live.refreshedAt,
184
+ updatedAt: live.updatedAt,
185
+ refreshOutcome: live.refreshOutcome,
186
+ };
187
+ });
188
+ }
189
+
190
+ /*
191
+ * Describe the latest refresh problem consistently across the inline button and action menu.
192
+ * Only a failed attempt or failed saved queries ask for another refresh, matching when the server retries;
193
+ * an unreadable source or incomplete evidence (a table still syncing, pending or failed AI columns, or
194
+ * content cut by the limits) stays the same on a retry.
195
+ */
196
+ export function getAgentNoteRefreshWarning(outcome?: AgentNoteRefreshOutcomeObj) {
197
+ if (!outcome) return;
198
+ const { lastAttempt, published } = outcome;
199
+ if (lastAttempt?.status === 'FAILED') {
200
+ return i18n.t(lastAttempt.error ? 'agent_note.agent_note_refresh_failed_reason' : 'agent_note.agent_note_refresh_failed', {
201
+ error: lastAttempt.error,
202
+ });
203
+ }
204
+ if (lastAttempt?.status === 'UNSUPPORTED') return i18n.t('agent_note.agent_note_refresh_unsupported');
205
+ if (published?.status !== 'PARTIAL') return;
206
+ const queries = published.queries;
207
+ return Number(queries?.failed) > 0
208
+ ? i18n.t('agent_note.agent_note_refresh_partial_queries', { succeeded: queries.succeeded, total: queries.total })
209
+ : i18n.t('agent_note.agent_note_refresh_incomplete');
210
+ }
211
+
212
+ /* Return the viewer route of a listed data table. */
213
+ export function getAgentNoteDataTablePath(dataTableId: string) {
214
+ return `/app/d/${encodeURIComponent(dataTableId)}`;
215
+ }
216
+
217
+ /*
218
+ * Open a note's originating record only when the source ID matches its kind. An INSIGHT note opens the listed
219
+ * data table it owns; one backed only by internal tables has no source to open. A FIELD_DOC note opens its
220
+ * program page filtered to the form.
221
+ */
222
+ export function getAgentNoteSourcePath(note: AgentNoteSourceFields) {
223
+ switch (note.kind) {
224
+ case 'INSIGHT':
225
+ return note.ownedDataTableId ? getAgentNoteDataTablePath(note.ownedDataTableId) : null;
226
+ case 'CAMPAIGN_FORM':
227
+ return note.campaignId ? `/app/outbound/forms/c/${encodeURIComponent(note.campaignId)}` : null;
228
+ case 'CAMPAIGN_EMAIL':
229
+ return note.campaignId ? `/app/outbound/emails/c/${encodeURIComponent(note.campaignId)}` : null;
230
+ case 'FIELD_DOC':
231
+ return note.fieldDocId && note.fieldDocProgramId ? makeFieldDocFormPath(note.fieldDocProgramId, note.fieldDocId) : null;
232
+ case 'REMINDER':
233
+ return note.reminderWorkflowId ? `/app/runs/${encodeURIComponent(note.reminderWorkflowId)}` : null;
234
+ default:
235
+ return null;
236
+ }
237
+ }
238
+
239
+ /* Describe a note's originating record as a card link, labeled and iconed for its kind. */
240
+ export function getAgentNoteSourceLink(note: AgentNoteSourceFields) {
241
+ const to = getAgentNoteSourcePath(note);
242
+ if (!to) return null;
243
+ return {
244
+ to,
245
+ text: i18n.t('agent_note.view_source', { contentName: i18n.t(`agent_note.source_type.${note.kind}`) }),
246
+ iconName:
247
+ note.kind === 'REMINDER'
248
+ ? COMMON_ICON_NAMES.reminder
249
+ : note.kind === 'INSIGHT'
250
+ ? COMMON_ICON_NAMES.data_table
251
+ : COMMON_ICON_NAMES.open_external_link,
252
+ };
253
+ }
254
+
255
+ /*
256
+ * Share one footer only when every result has content computed at the same time in the same time zone.
257
+ * Incomplete results keep their own metadata so a shared footer cannot imply they are current.
258
+ */
259
+ export function getAgentNoteSharedResultComputedAt(blocks: AgentNoteResultBlockGQL[]) {
260
+ const first = blocks[0];
261
+ if (blocks.length < 2 || !first?.computedAt) return null;
262
+ return blocks.every((block) => block.markdown && block.computedAt === first.computedAt && block.timeZone === first.timeZone)
263
+ ? first.computedAt
264
+ : null;
265
+ }
266
+
267
+ /*
268
+ * Explain a result block that has no current result or could not be updated: a query error (any earlier
269
+ * result stays shown above it), or a result that has not been computed yet. Returns null for a current result.
270
+ */
271
+ export function getAgentNoteResultBlockStatus(block: Pick<AgentNoteResultBlockGQL, 'markdown' | 'error'>) {
272
+ if (block.error) return i18n.t('agent_note.agent_note_result_error', { error: block.error });
273
+ return block.markdown ? null : i18n.t('agent_note.agent_note_result_pending');
274
+ }