@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.
- package/README.md +109 -2
- package/VERIFICATION.md +118 -0
- package/benchmarks/browser.mjs +204 -0
- package/benchmarks/streaming.mjs +89 -0
- package/package.json +36 -5
- package/src/main.ts +5 -0
- package/src/modules/AIChatContent.tsx +84 -0
- package/src/modules/AgentNoteActionsMenu.tsx +121 -0
- package/src/modules/AgentNoteBootstrapProgress.tsx +41 -0
- package/src/modules/AgentNoteItem.helpers.ts +115 -0
- package/src/modules/AgentNoteItem.tsx +232 -0
- package/src/modules/AgentNotes.constants.ts +10 -0
- package/src/modules/AgentNotes.helpers.ts +274 -0
- package/src/modules/AgentNotes.hooks.ts +449 -0
- package/src/modules/AgentNotes.tsx +74 -0
- package/src/modules/AgentNotes.types.ts +50 -0
- package/src/modules/AgentNotesCollection.hooks.ts +69 -0
- package/src/modules/AgentNotesSection.tsx +145 -0
- package/src/parser.ts +4 -0
- package/src/types/content.ts +103 -0
- package/src/ui/AIChatUI.css +557 -0
- package/src/ui/AIChatUI.tsx +816 -0
- package/src/ui/AgentNotesUI.tsx +375 -0
- package/src/ui/AgentNotesUI.types.ts +19 -0
- package/src/ui/ChatBlocks.tsx +92 -0
- package/src/ui/ChatCodeBlock.tsx +16 -0
- package/src/ui/ChatInline.helpers.ts +20 -0
- package/src/ui/ChatInline.tsx +89 -0
- package/src/ui/ChatTable.helpers.ts +37 -0
- package/src/ui/ChatTable.tsx +126 -0
- package/src/utils/contentIdentity.ts +108 -0
- package/src/utils/parseBlocks.helpers.ts +50 -0
- package/src/utils/parseBlocks.ts +266 -0
- package/src/utils/parseContent.helpers.ts +102 -0
- package/src/utils/parseContent.ts +33 -0
- package/src/utils/parseContentIncrementally.ts +46 -0
- package/src/utils/parseCsv.ts +99 -0
- package/src/utils/parseInline.helpers.ts +48 -0
- package/src/utils/parseInline.ts +396 -0
- package/src/utils/parseTable.ts +202 -0
- package/tests/AgentNotes.test.tsx +1672 -0
- package/tests/fixtures/content.ts +13 -0
- package/tests/parseContent.test.ts +227 -0
- package/tests/parseCsv.test.ts +82 -0
- package/tests/parseInline.test.ts +222 -0
- package/tests/renderContent.ssr.test.tsx +19 -0
- package/tests/renderContent.test.tsx +282 -0
- package/tests/streaming.test.ts +51 -0
- package/tests/streamingEquivalence.test.ts +265 -0
- package/tsconfig.json +16 -0
- package/vitest.config.ts +18 -0
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import i18n, { i18nTranslations } from '@jsb188/app/i18n/index.ts';
|
|
3
|
+
import { act, StrictMode } from 'react';
|
|
4
|
+
import { createRoot, hydrateRoot, type Root } from 'react-dom/client';
|
|
5
|
+
import { renderToString } from 'react-dom/server';
|
|
6
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
7
|
+
import { AIChatContent } from '../src/modules/AIChatContent.tsx';
|
|
8
|
+
import type { ChatContentStatus, TableBlock } from '../src/types/content.ts';
|
|
9
|
+
import { ChatBlocks } from '../src/ui/ChatBlocks.tsx';
|
|
10
|
+
import { ChatTable } from '../src/ui/ChatTable.tsx';
|
|
11
|
+
import { reconcileContentDocument } from '../src/utils/contentIdentity.ts';
|
|
12
|
+
import { parseContent } from '../src/utils/parseContent.ts';
|
|
13
|
+
|
|
14
|
+
let host: HTMLDivElement;
|
|
15
|
+
let root: Root;
|
|
16
|
+
|
|
17
|
+
/*
|
|
18
|
+
* Commit full accumulated source through the public renderer under React strict rendering checks.
|
|
19
|
+
*/
|
|
20
|
+
async function renderContent(text: string, status: ChatContentStatus = 'complete') {
|
|
21
|
+
await act(async () =>
|
|
22
|
+
root.render(
|
|
23
|
+
<StrictMode>
|
|
24
|
+
<AIChatContent
|
|
25
|
+
text={text}
|
|
26
|
+
status={status}
|
|
27
|
+
/>
|
|
28
|
+
</StrictMode>,
|
|
29
|
+
),
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/*
|
|
34
|
+
* Render a fresh parser table without retained state or browser measurements for prefix comparisons.
|
|
35
|
+
*/
|
|
36
|
+
const FreshTable = (p: { block: TableBlock }) => {
|
|
37
|
+
return (
|
|
38
|
+
<ChatTable
|
|
39
|
+
block={p.block}
|
|
40
|
+
scrollRef={null}
|
|
41
|
+
overflowing={false}
|
|
42
|
+
scrollLabel={i18n.t('c.scrollable_table')}
|
|
43
|
+
/>
|
|
44
|
+
);
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/*
|
|
48
|
+
* Normalize server markup through the DOM to compare it with committed renderer output.
|
|
49
|
+
*/
|
|
50
|
+
function freshContentHtml(text: string, status: ChatContentStatus) {
|
|
51
|
+
const element = document.createElement('div');
|
|
52
|
+
element.innerHTML = renderToString(
|
|
53
|
+
<ChatBlocks
|
|
54
|
+
blocks={parseContent(text, status).blocks}
|
|
55
|
+
TableComponent={FreshTable}
|
|
56
|
+
/>,
|
|
57
|
+
);
|
|
58
|
+
for (const styled of element.querySelectorAll<HTMLElement>('[style]')) {
|
|
59
|
+
// Serialize parsed CSS so server attributes match the browser's normalized style output.
|
|
60
|
+
styled.setAttribute('style', styled.style.cssText);
|
|
61
|
+
}
|
|
62
|
+
return element.innerHTML;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
beforeEach(() => {
|
|
66
|
+
i18n.replace({ c: i18nTranslations.c.en });
|
|
67
|
+
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
|
68
|
+
host = document.createElement('div');
|
|
69
|
+
document.body.append(host);
|
|
70
|
+
root = createRoot(host);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
afterEach(async () => {
|
|
74
|
+
await act(async () => root.unmount());
|
|
75
|
+
host.remove();
|
|
76
|
+
vi.restoreAllMocks();
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
describe('assistant content rendering', () => {
|
|
80
|
+
it('matches a fresh pure parse at every streamed prefix and after truncation or source replacement', async () => {
|
|
81
|
+
const fixtures = [
|
|
82
|
+
'Intro\n\n| Item | Cost |\n| --- | --- |\n| **Rice** | 001 |\n\nNext _thought_',
|
|
83
|
+
'1. item\n - child\n\n```csv\nName,Note\nRice,"one\ntwo"\n```\n\nDone',
|
|
84
|
+
];
|
|
85
|
+
for (const text of fixtures) {
|
|
86
|
+
for (let index = 0; index <= text.length; index++) {
|
|
87
|
+
const prefix = text.slice(0, index);
|
|
88
|
+
await renderContent(prefix, 'streaming');
|
|
89
|
+
expect(host.innerHTML, `Prefix ${index} of ${text}`).toBe(freshContentHtml(prefix, 'streaming'));
|
|
90
|
+
}
|
|
91
|
+
await renderContent(text, 'complete');
|
|
92
|
+
expect(host.innerHTML).toBe(freshContentHtml(text, 'complete'));
|
|
93
|
+
const truncated = text.slice(0, Math.floor(text.length / 2));
|
|
94
|
+
await renderContent(truncated, 'interrupted');
|
|
95
|
+
expect(host.innerHTML).toBe(freshContentHtml(truncated, 'interrupted'));
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it('keeps over-limit source intact without constructing an excessive table DOM', async () => {
|
|
100
|
+
const source = `| ${Array.from({ length: 33 }, (_, index) => `Header ${index}`).join(' | ')} |\n| ${Array(33).fill('---').join(' | ')} |`;
|
|
101
|
+
await renderContent(source);
|
|
102
|
+
expect(host.querySelector('[role="table"]')).toBeNull();
|
|
103
|
+
expect(host.textContent).toBe(source);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it('renders block siblings, full table roles, alignment, empty cells and literal multiline CSV', async () => {
|
|
107
|
+
await renderContent(
|
|
108
|
+
'Before\n\n| **Item** | Count |\n| :--- | ---: |\n| Rice | 00 |\n\n```csv\n"",Note\n,"**literal** :smile: <b>\nnext line"\n```\n\nAfter',
|
|
109
|
+
);
|
|
110
|
+
const tables = host.querySelectorAll('[role="table"]');
|
|
111
|
+
expect(tables).toHaveLength(2);
|
|
112
|
+
expect(host.querySelector('p [role="table"]')).toBeNull();
|
|
113
|
+
expect(tables[0].querySelectorAll('[role="row"]')).toHaveLength(2);
|
|
114
|
+
expect(tables[0].querySelectorAll('[role="columnheader"]')).toHaveLength(2);
|
|
115
|
+
expect(tables[0].querySelectorAll('[role="cell"]')).toHaveLength(2);
|
|
116
|
+
expect(tables[0].querySelector('[role="columnheader"] .ft_semibold')?.textContent).toBe('Item');
|
|
117
|
+
expect((tables[0].querySelectorAll('[role="cell"]')[1] as HTMLElement).style.textAlign).toBe('right');
|
|
118
|
+
expect(tables[1].querySelector('[role="columnheader"]')?.textContent).toBe('');
|
|
119
|
+
expect(tables[1].querySelector('[role="cell"]')?.textContent).toBe('');
|
|
120
|
+
expect(tables[1].querySelectorAll('[role="cell"]')[1]?.textContent).toBe('**literal** :smile: <b>\nnext line');
|
|
121
|
+
expect(tables[1].querySelector('b, .noto_emoji, .ft_semibold span.ft_semibold, .ellip')).toBeNull();
|
|
122
|
+
expect(host.firstElementChild?.textContent).toBe('Before');
|
|
123
|
+
expect(host.lastElementChild?.textContent).toBe('After');
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it('keeps table, row and scroll-container identity while rows and later prose append', async () => {
|
|
127
|
+
const source = '| Item | Cost |\n| --- | --- |\n| Rice | 001 |\n';
|
|
128
|
+
await renderContent(source, 'streaming');
|
|
129
|
+
const table = host.querySelector('[role="table"]');
|
|
130
|
+
const scroll = table?.parentElement as HTMLDivElement;
|
|
131
|
+
const row = table?.querySelectorAll('[role="row"]')[1];
|
|
132
|
+
scroll.scrollLeft = 83;
|
|
133
|
+
await renderContent(`${source}| Beans | 2 |\n`, 'streaming');
|
|
134
|
+
expect(host.querySelector('[role="table"]')).toBe(table);
|
|
135
|
+
expect(table?.querySelectorAll('[role="row"]')[1]).toBe(row);
|
|
136
|
+
expect(table?.parentElement).toBe(scroll);
|
|
137
|
+
expect(scroll.scrollLeft).toBe(83);
|
|
138
|
+
await renderContent(`${source}| Beans | 2 |\n\nFollowing prose`, 'complete');
|
|
139
|
+
expect(host.querySelector('[role="table"]')).toBe(table);
|
|
140
|
+
expect(scroll.scrollLeft).toBe(83);
|
|
141
|
+
expect(host.lastElementChild?.textContent).toBe('Following prose');
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it('shows a provisional row once and consumes it on finalization without remounting the table', async () => {
|
|
145
|
+
const source = '| Item | Cost |\n| --- | --- |\n| Rice | 001 |';
|
|
146
|
+
await renderContent(source, 'streaming');
|
|
147
|
+
const table = host.querySelector('[role="table"]');
|
|
148
|
+
expect(host.textContent?.match(/Rice/g)).toHaveLength(1);
|
|
149
|
+
expect(table?.querySelectorAll('[role="cell"]')).toHaveLength(0);
|
|
150
|
+
await renderContent(source, 'complete');
|
|
151
|
+
expect(host.querySelector('[role="table"]')).toBe(table);
|
|
152
|
+
expect(table?.querySelectorAll('[role="cell"]')).toHaveLength(2);
|
|
153
|
+
expect(host.textContent?.match(/Rice/g)).toHaveLength(1);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it('honors status-only CSV promotion and interrupted source fallback', async () => {
|
|
157
|
+
const source = '```csv\nItem,Count\nRice,001';
|
|
158
|
+
await renderContent(source, 'streaming');
|
|
159
|
+
expect(host.querySelector('[role="table"]')).toBeNull();
|
|
160
|
+
expect(host.textContent).toBe(source);
|
|
161
|
+
await renderContent(source, 'interrupted');
|
|
162
|
+
expect(host.querySelector('[role="table"]')).toBeNull();
|
|
163
|
+
await renderContent(source, 'complete');
|
|
164
|
+
expect(host.querySelector('[role="table"]')).not.toBeNull();
|
|
165
|
+
expect(host.textContent).toContain('001');
|
|
166
|
+
await renderContent('Replacement');
|
|
167
|
+
expect(host.querySelector('[role="table"]')).toBeNull();
|
|
168
|
+
expect(host.textContent).toBe('Replacement');
|
|
169
|
+
await renderContent('');
|
|
170
|
+
expect(host.innerHTML).toBe('');
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
it('enables labelled keyboard scrolling only for actual horizontal overflow', async () => {
|
|
174
|
+
const scrollWidth = vi.spyOn(HTMLElement.prototype, 'scrollWidth', 'get').mockReturnValue(1000);
|
|
175
|
+
vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(320);
|
|
176
|
+
await renderContent('| Item | Count |\n| --- | --- |\n| Rice | 2 |');
|
|
177
|
+
const scroll = host.querySelector('[role="region"]') as HTMLDivElement;
|
|
178
|
+
expect(scroll.tabIndex).toBe(0);
|
|
179
|
+
expect(scroll.getAttribute('aria-label')).toBe(i18n.t('c.scrollable_table'));
|
|
180
|
+
expect(scroll.style.overflowX).toBe('auto');
|
|
181
|
+
expect(scroll.classList.contains('max_w_f')).toBe(true);
|
|
182
|
+
scrollWidth.mockReturnValue(320);
|
|
183
|
+
await act(async () => window.dispatchEvent(new Event('resize')));
|
|
184
|
+
expect(scroll.hasAttribute('tabindex')).toBe(false);
|
|
185
|
+
expect(scroll.hasAttribute('aria-label')).toBe(false);
|
|
186
|
+
expect(scroll.hasAttribute('role')).toBe(false);
|
|
187
|
+
scrollWidth.mockReturnValue(1000);
|
|
188
|
+
await renderContent('| Item | Count |\n| --- | --- |\n| Rice | 2 |\n| Beans | 3 |');
|
|
189
|
+
expect(host.querySelector('[role="region"]')).toBe(scroll);
|
|
190
|
+
expect(scroll.tabIndex).toBe(0);
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
it('uses semantic headings and nested lists, existing style meanings, deterministic emoji, and safe links', async () => {
|
|
194
|
+
await renderContent(
|
|
195
|
+
'# Heading\n\n*medium* **semibold** _italic_ __underline__ ~~strike~~ [hl]highlight[/hl] :smile: 😀\n\n3. first\n - nested\n\n[docs](https://example.com) [bad](javascript:alert(1)) <img src=x>',
|
|
196
|
+
);
|
|
197
|
+
expect(host.querySelector('h1')?.textContent).toBe('Heading');
|
|
198
|
+
expect(host.querySelector('ol')?.start).toBe(3);
|
|
199
|
+
expect(host.querySelector('ol li ul li')?.textContent).toBe('nested');
|
|
200
|
+
expect(host.querySelector('.ft_medium')?.textContent).toBe('medium');
|
|
201
|
+
expect(host.querySelector('.ft_semibold')?.textContent).toBe('semibold');
|
|
202
|
+
expect(host.querySelector('i')?.textContent).toBe('italic');
|
|
203
|
+
expect(host.querySelector('.u')?.textContent).toBe('underline');
|
|
204
|
+
expect(host.querySelector('.strikethrough')?.textContent).toBe('strike');
|
|
205
|
+
expect(host.querySelector('.em_text')?.textContent).toBe('highlight');
|
|
206
|
+
expect(host.querySelectorAll('.noto_emoji')).toHaveLength(2);
|
|
207
|
+
expect(host.querySelectorAll('a')).toHaveLength(1);
|
|
208
|
+
expect(host.querySelector('a')?.rel).toBe('noopener noreferrer');
|
|
209
|
+
expect(host.querySelector('img, script')).toBeNull();
|
|
210
|
+
expect(host.textContent).toContain('[bad](javascript:alert(1))');
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
it('hydrates identical output without replacing table DOM', async () => {
|
|
214
|
+
const text = 'Hello :smile:\n\n```csv\nName,Note\nRice,"line one\nline two"\n```';
|
|
215
|
+
await act(async () => root.unmount());
|
|
216
|
+
host.innerHTML = renderToString(<AIChatContent text={text} />);
|
|
217
|
+
const table = host.querySelector('[role="table"]');
|
|
218
|
+
const errors: unknown[] = [];
|
|
219
|
+
await act(async () => {
|
|
220
|
+
root = hydrateRoot(host, <AIChatContent text={text} />, { onRecoverableError: (error) => errors.push(error) });
|
|
221
|
+
});
|
|
222
|
+
expect(errors).toEqual([]);
|
|
223
|
+
expect(host.querySelector('[role="table"]')).toBe(table);
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
it('retains selected text and emoji spans when later inline formatting streams in', async () => {
|
|
227
|
+
const source = 'Selected :wave: 😀';
|
|
228
|
+
await renderContent(source, 'streaming');
|
|
229
|
+
const text = host.querySelector('p > span')!;
|
|
230
|
+
const emojis = [...host.querySelectorAll('.noto_emoji')];
|
|
231
|
+
const range = document.createRange();
|
|
232
|
+
range.setStart(text.firstChild!, 1);
|
|
233
|
+
range.setEnd(text.firstChild!, 6);
|
|
234
|
+
const selection = window.getSelection()!;
|
|
235
|
+
selection.removeAllRanges();
|
|
236
|
+
selection.addRange(range);
|
|
237
|
+
|
|
238
|
+
await renderContent(`${source} **new** and [label](https://example.com)`, 'streaming');
|
|
239
|
+
expect(host.querySelector('p > span')).toBe(text);
|
|
240
|
+
const updatedEmojis = host.querySelectorAll('.noto_emoji');
|
|
241
|
+
expect(updatedEmojis).toHaveLength(emojis.length);
|
|
242
|
+
for (const [index, emoji] of emojis.entries()) expect(updatedEmojis[index]).toBe(emoji);
|
|
243
|
+
expect(selection.toString()).toBe('elect');
|
|
244
|
+
expect(selection.anchorNode).toBe(text.firstChild);
|
|
245
|
+
expect(host.querySelector('.ft_semibold')?.textContent).toBe('new');
|
|
246
|
+
expect(host.querySelector('a')?.textContent).toBe('label');
|
|
247
|
+
selection.removeAllRanges();
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
it('reuses unchanged block objects and checks status-sensitive parse context', () => {
|
|
251
|
+
const text = 'Finished paragraph\n\n| Item | Count |\n| --- | --- |\n| Rice | 2 |\n\n';
|
|
252
|
+
const previous = parseContent(text, 'streaming');
|
|
253
|
+
const next = reconcileContentDocument(previous, parseContent(`${text}Next`, 'streaming'));
|
|
254
|
+
expect(next.blocks[0]).toBe(previous.blocks[0]);
|
|
255
|
+
expect(next.blocks[1]).toBe(previous.blocks[1]);
|
|
256
|
+
const open = parseContent('```csv\nName\nRice', 'streaming');
|
|
257
|
+
const completed = reconcileContentDocument(open, parseContent(open.source, 'complete'));
|
|
258
|
+
expect(completed.blocks[0].kind).toBe('table');
|
|
259
|
+
expect(completed.blocks[0]).not.toBe(open.blocks[0]);
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
it('retains completed table row and cell objects through partial rows, appends, and unrelated edits', () => {
|
|
263
|
+
const text = '| Item | Cost |\n| --- | ---: |\n| Rice | 001 |\n';
|
|
264
|
+
const previous = parseContent(text, 'streaming');
|
|
265
|
+
const before = previous.blocks[0] as TableBlock;
|
|
266
|
+
const partial = reconcileContentDocument(previous, parseContent(`${text}| Beans`, 'streaming')).blocks[0] as TableBlock;
|
|
267
|
+
expect(partial.headers).toBe(before.headers);
|
|
268
|
+
expect(partial.alignments).toBe(before.alignments);
|
|
269
|
+
expect(partial.rows).toBe(before.rows);
|
|
270
|
+
const appended = reconcileContentDocument(previous, parseContent(`${text}| Beans | 2 |\n`, 'streaming'));
|
|
271
|
+
const table = appended.blocks[0] as TableBlock;
|
|
272
|
+
expect(table.rows).toHaveLength(2);
|
|
273
|
+
expect(table.rows[0]).toBe(before.rows[0]);
|
|
274
|
+
expect(table.rows[0].cells).toBe(before.rows[0].cells);
|
|
275
|
+
const edited = reconcileContentDocument(appended, parseContent(appended.source.replace('Rice', 'Corn'), 'streaming'))
|
|
276
|
+
.blocks[0] as TableBlock;
|
|
277
|
+
expect(edited.rows[0]).not.toBe(table.rows[0]);
|
|
278
|
+
expect(edited.rows[0].cells[0]).not.toBe(table.rows[0].cells[0]);
|
|
279
|
+
expect(edited.rows[0].cells[1]).toBe(table.rows[0].cells[1]);
|
|
280
|
+
expect(edited.rows[1]).toBe(table.rows[1]);
|
|
281
|
+
});
|
|
282
|
+
});
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import type { ContentDocument } from '../src/types/content';
|
|
3
|
+
import { reconcileContentDocument } from '../src/utils/contentIdentity';
|
|
4
|
+
import { parseContent } from '../src/utils/parseContent';
|
|
5
|
+
|
|
6
|
+
/*
|
|
7
|
+
* Feed transport-independent accumulated prefixes through per-message reconciliation.
|
|
8
|
+
*/
|
|
9
|
+
function consumeChunks(source: string, chunks: number[]) {
|
|
10
|
+
let previous: ContentDocument | null = null;
|
|
11
|
+
let length = 0;
|
|
12
|
+
for (const size of chunks) {
|
|
13
|
+
length = Math.min(source.length, length + size);
|
|
14
|
+
const prefix = source.slice(0, length);
|
|
15
|
+
previous = reconcileContentDocument(previous, parseContent(prefix, 'streaming'));
|
|
16
|
+
expect(previous).toEqual(parseContent(prefix, 'streaming'));
|
|
17
|
+
}
|
|
18
|
+
return reconcileContentDocument(previous, parseContent(source, 'complete'));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
describe('accumulated-source streaming', () => {
|
|
22
|
+
it.each([
|
|
23
|
+
'A **bold** word and [link](/a_(b)).',
|
|
24
|
+
'Lead\n\n| A | B |\n| - | - |\n| 01 | value |\nTail',
|
|
25
|
+
'```csv\r\nA,B\r\n"one\r\ntwo",001\r\n```\r\nTail',
|
|
26
|
+
'- One\n - **Two**\n\n# End',
|
|
27
|
+
])('matches a fresh parse at every transport split: %s', (source) => {
|
|
28
|
+
const completed = parseContent(source, 'complete');
|
|
29
|
+
for (let split = 0; split <= source.length; split++) {
|
|
30
|
+
expect(consumeChunks(source, [split, source.length - split])).toEqual(completed);
|
|
31
|
+
}
|
|
32
|
+
expect(
|
|
33
|
+
consumeChunks(
|
|
34
|
+
source,
|
|
35
|
+
Array.from({ length: source.length }, () => 1),
|
|
36
|
+
),
|
|
37
|
+
).toEqual(completed);
|
|
38
|
+
expect(consumeChunks(source, [2, 7, 1, 13, 4, source.length])).toEqual(completed);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('handles interruption, truncation, replacement and empty source without stale blocks', () => {
|
|
42
|
+
let previous = parseContent('| A | B |\n| - | - |\n| value | tail', 'streaming');
|
|
43
|
+
for (const source of ['| A | B |\n| - | - |\n| value | tail', '```csv\nA,B\n1,2', 'Replacement', '']) {
|
|
44
|
+
for (const status of ['interrupted', 'complete', 'streaming'] as const) {
|
|
45
|
+
const fresh = parseContent(source, status);
|
|
46
|
+
previous = reconcileContentDocument(previous, fresh);
|
|
47
|
+
expect(previous).toEqual(fresh);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
});
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import type { ChatContentStatus, ContentDocument, ParserLimits, TableBlock } from '../src/types/content';
|
|
3
|
+
import { reconcileContentDocument } from '../src/utils/contentIdentity';
|
|
4
|
+
import { parseContent } from '../src/utils/parseContent';
|
|
5
|
+
import { parseContentIncrementally } from '../src/utils/parseContentIncrementally';
|
|
6
|
+
|
|
7
|
+
/*
|
|
8
|
+
* Compare every retained node, source range, fallback, and diagnostic with the independent full parser.
|
|
9
|
+
*/
|
|
10
|
+
function assertUpdate(
|
|
11
|
+
previous: ContentDocument | null,
|
|
12
|
+
source: string,
|
|
13
|
+
status: ChatContentStatus = 'streaming',
|
|
14
|
+
limits?: Partial<ParserLimits>,
|
|
15
|
+
) {
|
|
16
|
+
const next = parseContentIncrementally(previous, source, status, limits);
|
|
17
|
+
expect(next, JSON.stringify({ source, status, limits })).toEqual(parseContent(source, status, limits));
|
|
18
|
+
return next;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/*
|
|
22
|
+
* Traverse single-character or transport-sized chunks, then finalize without changing the text.
|
|
23
|
+
*/
|
|
24
|
+
function assertChunks(source: string, sizes: number[], limits?: Partial<ParserLimits>) {
|
|
25
|
+
let previous = assertUpdate(null, '', 'streaming', limits);
|
|
26
|
+
let length = 0;
|
|
27
|
+
let chunk = 0;
|
|
28
|
+
while (length < source.length) {
|
|
29
|
+
length = Math.min(source.length, length + sizes[chunk++ % sizes.length]);
|
|
30
|
+
previous = assertUpdate(previous, source.slice(0, length), 'streaming', limits);
|
|
31
|
+
}
|
|
32
|
+
for (const status of ['interrupted', 'complete', 'streaming', 'complete'] as const) {
|
|
33
|
+
previous = assertUpdate(previous, source, status, limits);
|
|
34
|
+
}
|
|
35
|
+
return previous;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/*
|
|
39
|
+
* Freeze the complete previous snapshot so accidental mutation fails at its origin.
|
|
40
|
+
*/
|
|
41
|
+
function freezeDocument(document: ContentDocument) {
|
|
42
|
+
const pending: object[] = [document];
|
|
43
|
+
while (pending.length) {
|
|
44
|
+
const value = pending.pop()!;
|
|
45
|
+
for (const child of Object.values(value)) if (child && typeof child === 'object') pending.push(child);
|
|
46
|
+
Object.freeze(value);
|
|
47
|
+
}
|
|
48
|
+
return document;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/*
|
|
52
|
+
* Produce deterministic adversarial fixtures without a dependency or a nonreproducible random seed.
|
|
53
|
+
*/
|
|
54
|
+
function randomInteger(seed: number) {
|
|
55
|
+
let value = seed;
|
|
56
|
+
/*
|
|
57
|
+
* Advance a fixed integer generator and bound its result to the requested range.
|
|
58
|
+
*/
|
|
59
|
+
return function next(maximum: number) {
|
|
60
|
+
value = (Math.imul(value, 1_664_525) + 1_013_904_223) >>> 0;
|
|
61
|
+
return value % maximum;
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
describe('incremental parsing equivalence', () => {
|
|
66
|
+
it.each([
|
|
67
|
+
'First\nsecond\nthird\n\nNext',
|
|
68
|
+
'Lead\n\nA **bold\ncontinued** paragraph and [link](/a_(b)).\n\nTail',
|
|
69
|
+
'Lead\n\n[hl]one\r\ntwo[/hl] and `three\nfour`\n\nTail',
|
|
70
|
+
'Lead\n\nparagraph\nheader | value\n-|-\none|two\n\nTail',
|
|
71
|
+
'Lead\n\n# Heading | value\n-|-\none|two\n\nTail',
|
|
72
|
+
'Lead\n\n- first\n continued\n - nested\n\n more\n- second\n\nTail',
|
|
73
|
+
'Lead\n\n3. first\n - nested\n continued\n4. second\n\nTail',
|
|
74
|
+
'Lead\n\n-\tfirst\n\t- nested\n\t continued\n\nTail',
|
|
75
|
+
'Lead\n\n- first\n a|b\n -|-\n 1|2\n\nTail',
|
|
76
|
+
'Lead\n\n> a|b\n-|-\nx|y\n\nTail',
|
|
77
|
+
'Lead\r\n\r\n# Title\r\n\r\na|b\r\n-|-\r\none|two\r\n\r\nTail\r\n',
|
|
78
|
+
'Lead\r\r# Title\r\ra|b\r-|-\rone|two\r\rTail\r',
|
|
79
|
+
'Lead\n\n```js\nvalue\n```not-a-close\nmore\n```\n\nTail',
|
|
80
|
+
'Lead\n\n````typescript\n```csv\na,b\n1,2\n```\n````\n\nTail',
|
|
81
|
+
'Lead\n\n~~~csv extras\na,b\n"one\r\ntwo",001\n~~~\n\nTail',
|
|
82
|
+
'Lead\n\n```csv\na,b\n1,2',
|
|
83
|
+
'Lead\n\n```csv\na,b\n"unfinished,2',
|
|
84
|
+
'Lead\n\n```csv\na,b\n1,2,3\n```\n\nTail',
|
|
85
|
+
'Lead\n\na|b\n-|-\none|two\nthree|four|five\n\nTail',
|
|
86
|
+
'Lead\n\na|b\n-|-\n1|2\n3|4\n| > quote | value |\n- list|text\n\nTail',
|
|
87
|
+
'Lead\n\na|b\n-|-\n`escaped\\|pipe`|value\n`unescaped|pipe`|value\n\nTail',
|
|
88
|
+
'Lead\n\n*open|[unsafe](javascript:alert(1))\n-|-\n[hl]open|`open\n[link](unfinished|_open\n\nTail',
|
|
89
|
+
'Lead\n\na|b\n-|-\n1|2\n\n# Header\n\nEnd',
|
|
90
|
+
'\n\n\t\r\n \r\n',
|
|
91
|
+
'Lead\n\n<aside>unsafe</aside>\n[reference][id]\n\nTail',
|
|
92
|
+
])('matches the full parser through every character: %s', (source) => {
|
|
93
|
+
assertChunks(source, [1]);
|
|
94
|
+
assertChunks(source, [13, 1, 5, 2, 19]);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it('reopens provisional block boundaries after many reusable preceding blocks', () => {
|
|
98
|
+
const prefix = '# Fixed\n\nFirst paragraph.\n\n```js\nfixed()\n```\n\nSecond paragraph.\n\n';
|
|
99
|
+
for (const tail of [
|
|
100
|
+
'paragraph\nheader|value\n-|-\none|two\n\nAfter',
|
|
101
|
+
'# header|value\n-|-\none|two\n\nAfter',
|
|
102
|
+
'- item\n\n continued\n - child\n- sibling\n\nAfter',
|
|
103
|
+
'```js\nvalue\n```still-open\nmore\n```\n\nAfter',
|
|
104
|
+
'a|b\n-|-\none|two\nwrong|width|now\n\nAfter',
|
|
105
|
+
]) {
|
|
106
|
+
let previous = assertUpdate(null, prefix);
|
|
107
|
+
for (let length = 0; length <= tail.length; length++) previous = assertUpdate(previous, prefix + tail.slice(0, length));
|
|
108
|
+
assertUpdate(previous, prefix + tail, 'complete');
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it.each([
|
|
113
|
+
{ inputLength: 50 },
|
|
114
|
+
{ nodes: 8 },
|
|
115
|
+
{ nodes: 0 },
|
|
116
|
+
{ tableRows: 1 },
|
|
117
|
+
{ tableRows: 0 },
|
|
118
|
+
{ tableColumns: 1 },
|
|
119
|
+
{ cellLength: 3 },
|
|
120
|
+
{ nestingDepth: 1 },
|
|
121
|
+
{ nestingDepth: 0, nodes: 15, tableRows: 2, tableColumns: 2, cellLength: 5 },
|
|
122
|
+
])('preserves whole-source and local fallback as limits are crossed: %o', (limits) => {
|
|
123
|
+
assertChunks(
|
|
124
|
+
'# Fixed\n\nFirst **paragraph**.\n\na|b\n-|-\n1|2\nlong|cell\n3|4|5\n\n- one\n - two\n - three\n\n```csv\na,b\n1,2\n3,4\n```',
|
|
125
|
+
[1, 7, 3],
|
|
126
|
+
limits,
|
|
127
|
+
);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it('invalidates cached budgets when limits change for identical or appended source', () => {
|
|
131
|
+
const source = '# Heading\n\nOne **two** three.\n\na|b\n-|-\n1|2\n3|4\n\nTail';
|
|
132
|
+
let previous: ContentDocument | null = null;
|
|
133
|
+
for (const limits of [
|
|
134
|
+
undefined,
|
|
135
|
+
{ nodes: 3 },
|
|
136
|
+
{ tableRows: 0 },
|
|
137
|
+
{ tableColumns: 1 },
|
|
138
|
+
{ inputLength: 5 },
|
|
139
|
+
{ cellLength: 0 },
|
|
140
|
+
{ nestingDepth: 0 },
|
|
141
|
+
{ nodes: Number.POSITIVE_INFINITY, tableRows: Number.NaN },
|
|
142
|
+
{ tableRows: -2.5, tableColumns: 2.8 },
|
|
143
|
+
undefined,
|
|
144
|
+
]) {
|
|
145
|
+
previous = assertUpdate(previous, source, 'streaming', limits);
|
|
146
|
+
previous = assertUpdate(previous, `${source} appended`, 'streaming', limits);
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it('invalidates earlier fallback blocks when limits change through reconciled renders', () => {
|
|
151
|
+
const source = '# Fixed\n\nParagraph\n\na|b\n-|-\n1|2\n\nAfter one\n\nAfter two\n\nAfter three';
|
|
152
|
+
const original = assertUpdate(null, source);
|
|
153
|
+
const limited = assertUpdate(original, source, 'streaming', { tableRows: 0 });
|
|
154
|
+
const reconciled = reconcileContentDocument(original, limited);
|
|
155
|
+
expect(reconciled).toEqual(parseContent(source, 'streaming', { tableRows: 0 }));
|
|
156
|
+
expect(reconciled.blocks[2].kind).toBe('literal');
|
|
157
|
+
const restored = assertUpdate(reconciled, `${source} appended`);
|
|
158
|
+
expect(restored.blocks[2].kind).toBe('table');
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
it('reconciles formatting changes caused only by new parser limits', () => {
|
|
162
|
+
const source = '# Fixed\n\n**Bold** and [hl]highlight[/hl]\n\nEnd';
|
|
163
|
+
let previous = assertUpdate(null, source);
|
|
164
|
+
for (const limits of [{ nestingDepth: 0 }, undefined, { nodes: 4 }, undefined]) {
|
|
165
|
+
previous = reconcileContentDocument(previous, assertUpdate(previous, source, 'streaming', limits));
|
|
166
|
+
expect(previous).toEqual(parseContent(source, 'streaming', limits));
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
it('accepts fresh-parser and reconciled documents while preserving all previous snapshots', () => {
|
|
171
|
+
const source = '# Fixed\n\nParagraph\n\na|b\n-|-\n1|2\n';
|
|
172
|
+
let previous = freezeDocument(parseContent(source, 'streaming'));
|
|
173
|
+
const saved: { document: ContentDocument; snapshot: ContentDocument }[] = [];
|
|
174
|
+
for (const suffix of ['', '3', '3|4', '3|4\n', '3|4\n\nAfter']) {
|
|
175
|
+
saved.push({ document: previous, snapshot: structuredClone(previous) });
|
|
176
|
+
previous = freezeDocument(reconcileContentDocument(previous, assertUpdate(previous, source + suffix)));
|
|
177
|
+
}
|
|
178
|
+
const before = structuredClone(previous);
|
|
179
|
+
for (const status of ['complete', 'interrupted', 'streaming'] as const) assertUpdate(previous, previous.source, status);
|
|
180
|
+
expect(previous).toEqual(before);
|
|
181
|
+
for (const { document, snapshot } of saved) expect(document).toEqual(snapshot);
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
it('keeps unchanged completed blocks and committed table rows available for memoized rendering', () => {
|
|
185
|
+
const source = '# Fixed\n\nParagraph\n\n```js\nfixed()\n```\n\na|b\n-|-\n1|2\n';
|
|
186
|
+
const previous = assertUpdate(null, source);
|
|
187
|
+
const next = reconcileContentDocument(previous, assertUpdate(previous, `${source}3|4\n`));
|
|
188
|
+
expect(next.blocks[0]).toBe(previous.blocks[0]);
|
|
189
|
+
expect(next.blocks[1]).toBe(previous.blocks[1]);
|
|
190
|
+
expect(next.blocks[2]).toBe(previous.blocks[2]);
|
|
191
|
+
const oldTable = previous.blocks[3] as TableBlock;
|
|
192
|
+
const newTable = next.blocks[3] as TableBlock;
|
|
193
|
+
expect(oldTable.kind).toBe('table');
|
|
194
|
+
expect(newTable.kind).toBe('table');
|
|
195
|
+
expect(newTable.headers).toBe(oldTable.headers);
|
|
196
|
+
expect(newTable.rows[0]).toBe(oldTable.rows[0]);
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
it('handles interruption, completion, replacement, truncation, clearing, and resumption', () => {
|
|
200
|
+
const source = '# Fixed\n\nParagraph\n\n```csv\na,b\n1,2';
|
|
201
|
+
let previous: ContentDocument | null = null;
|
|
202
|
+
for (const text of [source, source, `${source}\n3,4`, source.slice(0, 18), 'Replacement\r', 'Replacement\r\ntext', '', source]) {
|
|
203
|
+
for (const status of ['streaming', 'complete', 'interrupted', 'streaming'] as const)
|
|
204
|
+
previous = assertUpdate(previous, text, status);
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
it('keeps parsed rows reusable when reconciliation replaces a growing first table', () => {
|
|
209
|
+
let previous: ContentDocument | null = null;
|
|
210
|
+
for (const rows of ['1|2\n', '1|2\n3|4\n', '1|2\n3|4\n5|6\n']) {
|
|
211
|
+
const next = assertUpdate(previous, `a|b\n-|-\n${rows}`);
|
|
212
|
+
if (previous) {
|
|
213
|
+
// Check before reconciliation: full reparsing would allocate these cells again.
|
|
214
|
+
expect((next.blocks[0] as TableBlock).rows[0]).toBe((previous.blocks[0] as TableBlock).rows[0]);
|
|
215
|
+
expect((next.blocks[0] as TableBlock).headers).toBe((previous.blocks[0] as TableBlock).headers);
|
|
216
|
+
}
|
|
217
|
+
previous = reconcileContentDocument(previous, next);
|
|
218
|
+
}
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
it('matches reproducible malformed markup mixtures across irregular transport boundaries', () => {
|
|
222
|
+
const parts = [
|
|
223
|
+
'plain text',
|
|
224
|
+
'\n',
|
|
225
|
+
'\r',
|
|
226
|
+
'\r\n',
|
|
227
|
+
'\n\n',
|
|
228
|
+
' ',
|
|
229
|
+
'\t',
|
|
230
|
+
'# heading\n',
|
|
231
|
+
'- list\n',
|
|
232
|
+
' - nested\n',
|
|
233
|
+
'1. first\n',
|
|
234
|
+
' continuation\n',
|
|
235
|
+
'a|b\n-|-\n1|2\n',
|
|
236
|
+
'|one|two|three|\n',
|
|
237
|
+
'> quote|value\n',
|
|
238
|
+
'```csv\na,b\n1,2\n',
|
|
239
|
+
'```\n',
|
|
240
|
+
'~~~js\n',
|
|
241
|
+
'```tail',
|
|
242
|
+
'**bold**',
|
|
243
|
+
'_open',
|
|
244
|
+
'[hl]value[/hl]',
|
|
245
|
+
'[link](/a_(b))',
|
|
246
|
+
'`code\\|pipe`',
|
|
247
|
+
'"one\ntwo",003',
|
|
248
|
+
'[:emoji:]',
|
|
249
|
+
'\\|',
|
|
250
|
+
'\\\\|',
|
|
251
|
+
];
|
|
252
|
+
const budgets: (Partial<ParserLimits> | undefined)[] = [
|
|
253
|
+
undefined,
|
|
254
|
+
{ nodes: 18 },
|
|
255
|
+
{ tableRows: 1, cellLength: 4 },
|
|
256
|
+
{ nestingDepth: 1 },
|
|
257
|
+
];
|
|
258
|
+
for (let seed = 1; seed <= 72; seed++) {
|
|
259
|
+
const random = randomInteger(seed);
|
|
260
|
+
let source = '# Fixed\n\nUnchanged paragraph.\n\n';
|
|
261
|
+
for (let part = 0; part < 24; part++) source += parts[random(parts.length)];
|
|
262
|
+
assertChunks(source, [1 + random(13), 1 + random(19), 1 + random(7)], budgets[seed % budgets.length]);
|
|
263
|
+
}
|
|
264
|
+
});
|
|
265
|
+
});
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ES2023",
|
|
4
|
+
"lib": ["ES2023", "DOM", "DOM.Iterable"],
|
|
5
|
+
"types": ["vite/client"],
|
|
6
|
+
"module": "ESNext",
|
|
7
|
+
"moduleResolution": "Bundler",
|
|
8
|
+
"allowImportingTsExtensions": true,
|
|
9
|
+
"jsx": "react-jsx",
|
|
10
|
+
"noEmit": true,
|
|
11
|
+
"strict": true,
|
|
12
|
+
"skipLibCheck": true,
|
|
13
|
+
"esModuleInterop": true
|
|
14
|
+
},
|
|
15
|
+
"include": ["src/**/*", "tests/**/*"]
|
|
16
|
+
}
|
package/vitest.config.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { defineConfig } from 'vitest/config';
|
|
4
|
+
|
|
5
|
+
// Vite treats ':' in real workspace directories as a URL scheme in jsdom.
|
|
6
|
+
const workspaceRoot = fileURLToPath(new URL('../../node_modules/@jsb188/ai-chat/', import.meta.url));
|
|
7
|
+
|
|
8
|
+
export default defineConfig({
|
|
9
|
+
root: existsSync(workspaceRoot) ? workspaceRoot : fileURLToPath(new URL('.', import.meta.url)),
|
|
10
|
+
resolve: {
|
|
11
|
+
preserveSymlinks: true,
|
|
12
|
+
dedupe: ['react', 'react-dom', '@jsb188/react', '@jsb188/app', 'jotai'],
|
|
13
|
+
},
|
|
14
|
+
test: {
|
|
15
|
+
environment: 'node',
|
|
16
|
+
include: ['tests/**/*.test.ts?(x)'],
|
|
17
|
+
},
|
|
18
|
+
});
|