@jsb188/ai-chat 0.0.0-stage → 1.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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
package/README.md CHANGED
@@ -1,3 +1,110 @@
1
- # Temporary Holding Version
1
+ # AI chat content
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Custom, deterministic chat-markup parsing and React rendering. This package owns its block, inline, and CSV scanners; it does not depend on a Markdown/CSV parser, syntax highlighter, streaming library, or the legacy `Markdown` renderer.
4
+
5
+ ```tsx
6
+ import { AIChatContent } from '@jsb188/ai-chat';
7
+
8
+ <AIChatContent text={accumulatedMessage} status='streaming' />
9
+ ```
10
+
11
+ `status` is `streaming`, `complete` (the default), or `interrupted`. The application owns loading indicators, errors, interrupted-response notices, persistence, and transport. Pass the entire accumulated message unchanged on every update.
12
+
13
+ ## Public surfaces
14
+
15
+ - `@jsb188/ai-chat`: `AIChatContent`, `AIChatContentProps`, `ChatContentStatus`, `AgentNotes`.
16
+ - `@jsb188/ai-chat/parser`: `parseContent(source, status?, limits?)`, `parseInline(source, offset?, limits?, diagnostics?)`, `parseCsv(source, offset?, limits?)`, `DEFAULT_PARSER_LIMITS`.
17
+ - `@jsb188/ai-chat/types`: document, block, inline, range, diagnostic, table-cell, status, and limit types.
18
+
19
+ The parser export has no runtime dependencies or transitive UI imports. Source ranges use JavaScript string offsets. Original LF, CRLF, and CR separators are retained; fallback never uses globally normalized text. `parseCsv` returns a structured result with rows including the header. It never throws for ordinary malformed content.
20
+
21
+ `<AgentNotes organizationId={organizationId} onChatStarted={openChat} />` lists all readable organization notes, including archived notes, through the existing GraphQL provider. Member-pinned notes appear first in their own section; the remaining notes share one section, ordered by attention first and then the latest data change. Members with `agent_notes_manage` permission can pin or unpin a note from its header. It follows every summary page, loads full content when a header opens, and renders bodies with `AIChatContent`. Each note retains its expansion and draft while mounted, including across live list reordering. Sending a question creates or resumes the member's dedicated chat for that note. Failed sends retain the draft and retry request ID; successful sends call `onChatStarted` with the chat ID, stream ticket, submitted text, and timestamp so the host can open its chat route. Key the component by organization ID when switching organizations.
22
+
23
+ AI notes and AI chat work history share `ToggleExpand` and `ToggleExpandHeader` from `@jsb188/react-web/modules/Accordian`. The shared item uses the existing accordion animation; only AI note items apply `bg_fade` while expanded. Its optional `expandedHeight` caps the body in pixels, with “Show all” for overflowing content; `FooterComponent` remains below that cap while the item is open. Notes use a 320 px cap. Chat work omits `expandedHeight` and expands to full height by default. Header actions do not toggle expansion.
24
+
25
+ ## Supported grammar
26
+
27
+ This is a documented chat subset, not full CommonMark or GFM.
28
+
29
+ - Paragraphs preserve intentional single line breaks. Blank lines separate blocks without empty paragraphs.
30
+ - ATX headings use one through six `#` markers followed by whitespace or end of line.
31
+ - Unordered lists use `-`, `+`, `*`, or the existing `•` bullet. Ordered lists use numbers followed by `.` or `)`. Indentation creates nested lists; a tab advances to the next four-column stop. List markers and fences accept up to three spaces relative to their container.
32
+ - Fences use three or more backticks or tildes. A closing fence uses the same character, at least the opening length, and no trailing content. The first language token is compared case-insensitively; only `csv` enables CSV promotion. Other fence metadata is inert.
33
+ - Tables are supported only at the top level. Lists and blockquotes do not promote nested table examples. Table-like prose without a valid delimiter row, unfenced CSV, unknown HTML, reference links, images, task controls, math, and other unsupported constructs stay readable.
34
+
35
+ ### Inline compatibility
36
+
37
+ | Source | Presentation |
38
+ | --- | --- |
39
+ | `*text*` | Medium weight |
40
+ | `**text**`, `***text***` | Semibold |
41
+ | `_text_` | Italic |
42
+ | `__text__` | Underline |
43
+ | `___text___` | Underline and italic |
44
+ | `~~text~~` | Strikethrough |
45
+ | `[hl]text[/hl]` | Existing highlight style |
46
+ | Supported `:emoji_name:` | Existing deterministic emoji mapping |
47
+
48
+ Combined styles nest. Underscores inside identifiers remain literal. Unmatched delimiters remain visible until a complete pair exists. Escapes and matching backtick code spans take precedence over formatting. Code spans and highlights can contain physical line breaks. Stars/underscores retain the legacy single-line boundary behavior. No random/dynamic prompt substitutions run during rendering.
49
+
50
+ Explicit `[label](destination)` links support escaped brackets and balanced destination parentheses. HTTP, HTTPS, mailto, tel, and relative destinations are allowed; controls, whitespace, backslashes, encoded HTML-entity obfuscation, and unsupported schemes are rejected. Incomplete or rejected links remain readable source. External web links use `noopener noreferrer`.
51
+
52
+ The migration inventory found no assistant callers of `codesMap` or `MappedCodeComponent`; the old `MessageBody` props were unused pass-throughs. Class-style `[class##text]` tokens appeared in separate translated notices/document status templates, not assistant inputs. These tokens remain literal here; arbitrary model-provided classes or attributes are never applied. Existing user and notice renderers remain separate.
53
+
54
+ ### Markdown tables
55
+
56
+ A header and delimiter must have the same width. Delimiter cells contain one or more hyphens with optional edge colons for alignment. Outer pipes are optional. Escape a literal pipe even inside an inline code span. Backslash parity determines whether a pipe separates cells; only structural horizontal padding is trimmed.
57
+
58
+ Body candidates must contain an unescaped pipe and match the header width. Blank lines, fences, lists, or blockquotes end a table; use outer pipes when a cell starts with a list/blockquote marker. A pipe-containing body row beginning with `#` remains inline cell content, not a heading. Completed malformed rows fall back with the entire candidate source intact, rather than padding or dropping data. Cells cannot span physical lines.
59
+
60
+ While streaming or interrupted, an unterminated final row is a provisional literal tail immediately after the table. It is consumed exactly once when its line completes or the message becomes complete. A delimiter at unfinished EOF remains ordinary text until terminated/finalized.
61
+
62
+ ### CSV tables
63
+
64
+ The first record is the header; duplicate and empty headers are preserved. One-column and header-only tables are valid. Fields are literal strings: leading zeros, whitespace, Unicode, commas/newlines inside quotes, doubled quotes, empty/trailing fields, Markdown, HTML, emoji names, and formulas are never coerced or interpreted.
65
+
66
+ LF, CRLF, and CR separate records outside quotes. A leading BOM may be skipped for interpretation. Completely blank physical lines outside quotes are ignored; whitespace-only values, quoted empty fields, all-empty multi-column records, and blank lines inside quotes are retained. A terminal line ending creates no extra record.
67
+
68
+ Malformed quoting, unequal record widths, and exceeded limits keep the complete fence readable as code/source. An open CSV fence stays code during streaming and interruption. A closed valid fence promotes immediately. Complete messages may promote an unclosed fence only when its CSV body is independently valid at EOF.
69
+
70
+ ## Resource and rendering policy
71
+
72
+ | Limit | Default |
73
+ | --- | ---: |
74
+ | Input string length | 200,000 UTF-16 code units |
75
+ | Nested containers | 8 |
76
+ | Document nodes | 20,000 |
77
+ | Data rows per table (excluding header) | 500 |
78
+ | Columns | 32 |
79
+ | Cell value length | 16,000 |
80
+
81
+ Pure parser callers may override limits with finite nonnegative integers. Recursive nesting is always capped at 64. Input/document limits use whole-source fallback; table limits preserve the affected table/fence; inline limits preserve the affected inline source. Structured diagnostics record incomplete, malformed, unsupported/limited input as applicable. Diagnostics are not shown or logged in the product. No rows or cells are silently truncated.
82
+
83
+ Rendering uses React text nodes and the shared static `TableList`. Headers/cells wrap without ellipsis or invented `-` placeholders. Column widths are bounded by column count. Horizontal overflow stays within the message; overflowing wrappers expose a translated region label and keyboard focus. Grid rows expose complete table, row, columnheader, and cell roles. No sort/edit controls or virtualization are added.
84
+
85
+ The public pure parser parses full input. The renderer synchronously reuses verified append-only prefixes from its last committed document, reopening the final two blocks because later text can change their interpretation. Active Markdown tables reuse validated cells and their diagnostics; retained node counts avoid repeated tree walks. Edits, truncation, changed budgets, and whole-document fallback use full parsing. Status-only finalization is handled immediately. Weak metadata caches do not keep messages alive after their renderer releases them.
86
+
87
+ Per-instance reconciliation retains unchanged block objects, and keys use source position and kind rather than message text. Completed tables retain DOM and scroll state as later source arrives. Streaming cadence, markup, animations, selection, CSV downloads, and scrolling are unchanged; there is no batching, queued parser task, delayed finalization, or virtualization. Active table lines and complex unfinished paragraphs still require repeated scans, so this is not a claim of universally linear cumulative streaming cost.
88
+
89
+ ## Verification
90
+
91
+ Run from the repository root:
92
+
93
+ ```sh
94
+ yarn workspace @jsb188/ai-chat test
95
+ yarn workspace @jsb188/ai-chat typecheck
96
+ ```
97
+
98
+ Tests cover source ranges, malformed data, every legacy inline style, resource limits, adversarial delimiters, every split boundary/character of representative short inputs, status transitions, replacement/truncation, hydration, accessible roles, and stable DOM/scroll identity. The plan did not include actual screenshot text; receipt and three-column CSV fixtures are explicitly synthetic.
99
+
100
+ The deterministic streaming benchmark measures parsing plus reconciliation at 256- and 2,048-character updates. It checks final output and reports timing samples without machine-dependent pass/fail thresholds. Run with Node 24 or newer from the repository root:
101
+
102
+ ```sh
103
+ node packages/@jsb188:ai-chat/benchmarks/streaming.mjs /tmp/chat-streaming.json
104
+ ```
105
+
106
+ An optional second argument points to a saved baseline parser bundle exporting `parseContent`, allowing comparison with the original implementation as well as the current full parser. The browser benchmark accepts a built preview directory and JSON output path; see the build and comparison instructions in `VERIFICATION.md`.
107
+
108
+ The application includes a local browser fixture at `apps/marketday/tests/fixtures/AIChatContentPreview.html`. Its standalone Vite config bypasses application routing and uses synthetic data only. From `apps/marketday`, run `npx vite --config tests/fixtures/ai-chat.vite.config.ts --port 3010 --strictPort` (3011 if occupied). It exercises the real assistant container, themes, sidebar widths, status changes, streaming, and parsing/React profiling. It never creates production messages.
109
+
110
+ See [verification results](./VERIFICATION.md) for measured performance, commands, and environment limitations. Application integration and this package live in separate repositories (`packages` is a submodule); coordinate them when committing or deploying. No backend schema, persisted text format, or migration changed.
@@ -0,0 +1,118 @@
1
+ # AI chat content verification
2
+
3
+ ## October 14, 2026: performance-only update
4
+
5
+ Verified on Apple M1 Max/macOS, Node 24.15.0, Vite 8.1.5, and headless Chromium 151.0.7922.34. The comparison uses locally built production bundles with React's profiling renderer, the same checked-in synthetic preview, and no application API calls. The unchanged baseline was captured before edits from application commit `df006d667b2da32f7a4f4f77b5c126c681fdecd8` and packages commit `3c4e16390bfde300a06d610a2ffbcb45856e1a40`.
6
+
7
+ The renderer now retains safe source prefixes, reopens the last two blocks, reuses validated Markdown cells and diagnostics, and caches immutable node counts. Plain inline text avoids delimiter indexing. Text and emoji rendering omit one internal React component layer while retaining identical spans and keys. No CSS, DOM structure, animation, update scheduling, streaming cadence, scrolling, table virtualization, or transport behavior was changed.
8
+
9
+ ### Browser comparison
10
+
11
+ Each figure is the median of five samples after one warm-up. Content mount means mounting the fixture's content inside the existing assistant message, after an open CSV code block has removed previous tables. Streamed React peak is `Profiler.actualDuration` across the fixture's approximately 60 animation-frame updates. Browser JavaScript time comes from Chromium performance counters over that stream; it includes the fixture and app, not just parsing. These are local synthetic observations, not production latency guarantees.
12
+
13
+ | Fixture | Content mount before → after | Peak streamed React render before → after | Streaming JavaScript before → after |
14
+ | --- | ---: | ---: | ---: |
15
+ | Receipt, CSV, and prose | 2.3 → 1.6 ms | 1.0 → 0.9 ms | 55.39 → 53.10 ms |
16
+ | 10 tables × 35 rows | 24.8 → 21.9 ms | 2.9 → 1.1 ms | 126.60 → 64.59 ms |
17
+ | 500-row × 5-column table | 52.8 → 40.3 ms | 9.7 → 1.6 ms | 363.03 → 109.45 ms |
18
+ | 192,000-character unfinished paragraph | 23.3 → 3.1 ms | 11.6 → 0.7 ms | 401.13 → 48.50 ms |
19
+
20
+ The large table's peak streamed React work decreased about 84%, its streaming JavaScript time about 70%, and its content mount about 24%. Browser layout work remains: the long paragraph still spent about 340 ms cumulatively in layout across the stream. Median maximum observed frame intervals fell from 35.1 to 27.2 ms for the large table and 37.0 to 27.3 ms for the paragraph; these results do not establish a universal frame-time guarantee.
21
+
22
+ All five completed DOM snapshots for each of the four fixtures had exactly matching SHA-256 hashes across the builds, including identical element counts. The mobile dark-mode screenshot PNG bytes and CSV download contents also matched exactly. Browser checks passed at 320/420/780px content widths and a 375px mobile viewport, including keyboard horizontal scrolling, preserved table DOM/scroll offsets after appending prose, overflow containment, and status-only CSV promotion/interruption. Both builds start measurements after the existing 250 ms message-animation warm-up, so differences in measurement overhead cannot change the captured animation state.
23
+
24
+ ### Parsing plus reconciliation
25
+
26
+ The Node benchmark compares the saved original pure-parser bundle with the final incremental renderer path, including identity reconciliation on every update. It alternates execution order, discards one warm-up, records five samples, and validates final output. Values below use 256-character chunks; the runner also covers 2,048-character chunks.
27
+
28
+ | Fixture | Updates | Cumulative work before → after | Per-update p95 before → after |
29
+ | --- | ---: | ---: | ---: |
30
+ | 10 tables × 35 rows | 105 | 105.769 → 4.819 ms | 1.852 → 0.056 ms |
31
+ | 500-row × 5-column table | 645 | 3,368.447 → 258.910 ms | 10.016 → 0.737 ms |
32
+ | 192,000-character unfinished paragraph | 750 | 3,783.147 → 279.518 ms | 9.484 → 0.715 ms |
33
+
34
+ The active table still scans physical lines and retained row references. Complex unfinished paragraphs, active lists, and CSV fences can still require repeated parsing. Prefix checking and reconciliation also retain some work proportional to existing content. These improvements do not claim universally linear cumulative cost.
35
+
36
+ ### Correctness and integration
37
+
38
+ - Package: 163 tests pass, including full-parser equivalence, immutable prior snapshots, late table fallback, diagnostic retention, resource budgets, CRLF boundaries, status transitions, source replacement/truncation, hydration, selection, and stable DOM identities. Package typecheck passes.
39
+ - Application chat integration/work/reconnect: 43 tests pass. Shared table and virtualized-list pagination/scroll behavior: 26 tests pass. Total: 232 tests.
40
+ - An independent audit against parser files extracted from the unchanged packages commit passed 183,900 comparisons across 2,400 deterministic adversarial sources and varied lifecycle states/budgets. This additionally checked changes shared by the full and incremental parsers.
41
+ - Review caught and fixed metadata loss through table reconciliation and stale reuse after changing parser budgets. Budget metadata follows each parse's diagnostics array, which reconciliation preserves. Different budgets invalidate structural reuse. WeakMap values contain counts/budgets/diagnostics rather than references that keep whole documents alive.
42
+ - Repository formatter and whitespace checks pass. The production profiling fixture builds successfully. Full Marketday typecheck remains blocked by the same pre-existing ambient-context errors in `app/routes/app.d.$dataTableId.helpers.ts` at lines 8, 9, and 11; that file was not changed.
43
+
44
+ ### Reproduction
45
+
46
+ From the repository root, build the synthetic preview with production profiling enabled:
47
+
48
+ ```sh
49
+ node --input-type=module <<'JS'
50
+ import { build } from 'vite';
51
+ import { resolve } from 'node:path';
52
+ await build({
53
+ configFile: 'apps/marketday/tests/fixtures/ai-chat.vite.config.ts',
54
+ resolve: { alias: { 'react-dom/client': 'react-dom/profiling' } },
55
+ build: {
56
+ outDir: '/tmp/chat-profile',
57
+ emptyOutDir: true,
58
+ rollupOptions: { input: resolve('apps/marketday/tests/fixtures/AIChatContentPreview.html') },
59
+ },
60
+ });
61
+ JS
62
+ node packages/@jsb188:ai-chat/benchmarks/browser.mjs /tmp/chat-profile /tmp/chat-browser.json
63
+ node packages/@jsb188:ai-chat/benchmarks/streaming.mjs /tmp/chat-streaming.json
64
+ ```
65
+
66
+ The browser runner uses the installed Playwright Chromium and localhost port 3010, falling back to 3011 only if necessary. It closes its browser/server afterward and saves raw timing samples, completed DOM hashes/HTML, a mobile screenshot, and interaction results. Repeat against separately preserved before/after build directories using the same runner. Compare matching fixtures' `htmlHash` values and `interactions` results before interpreting timing changes.
67
+
68
+ For a parser comparison against an earlier implementation, preserve a bundle exporting `parseContent` before editing (`esbuild` with `bundle: true`, `platform: 'node'`, `format: 'esm'` and entry `packages/@jsb188:ai-chat/src/parser.ts`), then pass its path as the optional second argument to `benchmarks/streaming.mjs`. Without that argument, the runner compares the current full parser against incremental parsing. Timings are reported rather than asserted, avoiding hardware-dependent test failures.
69
+
70
+ ## Original October 3 verification
71
+
72
+ Verified October 3, 2026, on the local macOS development workspace with Node 24.15.0, Vite 8.1.5, React development/profiling builds, and the Codex in-app browser. Browser measurements use the checked-in synthetic preview and real `AIChatMessage`/shared table components; no production records were created.
73
+
74
+ ## Automated checks
75
+
76
+ | Check | Result |
77
+ | --- | --- |
78
+ | `yarn workspace @jsb188/ai-chat test` | 110 passing tests in 6 files |
79
+ | `yarn workspace @jsb188/ai-chat typecheck` | Pass |
80
+ | Shared `TableListUI.test.tsx` and `VirtualizedList.pagination.test.tsx` | 23 passing tests; table defaults, roles, and scroll-follow behavior |
81
+ | App `AIChatContent.integration`, `AIChatWork`, `AIChatThread.work`, `AIChatStreamReconnect` | 39 passing tests |
82
+ | Pure parser bundle inspection with esbuild | 9 local TypeScript modules; no dependency, React, or TSX imports |
83
+ | Repository-configured Biome formatting and both repositories' `git diff --check` | Pass |
84
+ | `yarn workspace marketday typecheck` | Blocked by three pre-existing ambient-context errors in `app/routes/app.d.$dataTableId.helpers.ts`, lines 8, 9, and 11 (TS1183, TS1254, TS1036); no feature errors |
85
+
86
+ The app checks exercise full accumulated source, stable table DOM, source/status-only CSV transitions, loading vs settled empty messages, interrupted indicators, deletion, unchanged user formatting, existing work disclosures, and reconnection. Shared-list tests explicitly exercise growth while following the bottom, preserving an older reading position, navigation to older pagination windows, and observer cleanup. Renderer tests cover hydration, every streamed prefix against a fresh pure parse, provisional tails, resource fallback, and stable row/cell identities through appends and edits.
87
+
88
+ ## Browser observations
89
+
90
+ - Desktop 1280px and mobile 375px viewports; chat containers 320px, 420px, and 780px; light and dark modes.
91
+ - Five-column receipt table and three-column CSV table retain source order with surrounding prose, lists, headings, and code. Duplicate/empty cells, leading zeros, explicit zero values, and multiline CSV remain intact.
92
+ - No horizontal page or message-container overflow. Wide tables scroll inside their own wrapper, with complete header/row/cell roles and a translated accessible overflow label.
93
+ - Arrow keys scroll the focused table. After its native scroll animation settled at 80px, appending later prose retained the same wrapper and scroll offset.
94
+ - Open CSV showed code while streaming, promoted to a table on completion with unchanged text, and stayed source/code when interrupted with the incomplete-response indicator.
95
+ - Text remains selectable browser text, and leaf text keeps protective span wrappers. Third-party browser translation services were not invoked; markup and dynamic-update coverage verify the wrapper strategy.
96
+
97
+ ## Performance
98
+
99
+ Measurements are development-build observations, not production guarantees. Parser figures are median/max of 20 synchronous full-input parses. Streaming peak is React Profiler `actualDuration` across approximately 60 accumulated-source updates at animation-frame boundaries. DOM counts include the assistant container. The fixture exposes the measurement values as visible output.
100
+
101
+ | Synthetic input | Characters | Parser median / max | DOM elements | Peak streamed React render |
102
+ | --- | ---: | ---: | ---: | ---: |
103
+ | Receipt, CSV, and prose | 476 | 0.1 / 0.9 ms | 111 | Small initial render: 5.4–9.2 ms |
104
+ | 10 tables × 35 data rows | 26,681 | 2.1 / 2.9 ms | 3,673 | 5.5 ms |
105
+ | 500-row × 5-column active table | 164,934 | 9.2 / 10.2 ms | 8,526 | 12.4 ms |
106
+ | Long unfinished paragraph | 192,000 | 8.1 / 11.5 ms | 5 (8 with loading UI) | 9.6 ms |
107
+
108
+ The initial implementation's 500-row streaming peak was 120.6 ms. Reusing completed table rows/cells and memoizing their shared-table presentation reduced that measured peak to 12.4 ms. Earlier completed blocks remain memoized. No animation-frame coalescer was added to production: the measured update cost was addressed directly, and status finalization remains synchronous.
109
+
110
+ Large cold mounts still construct all rows: the near-limit table measured about 195 ms for its initial development render (earlier run 174 ms). There is deliberately no virtualization in this release. Input, node, cell, column, and row limits bound the work and provide intact literal fallback. Repeated full-input parsing still has potentially quadratic cumulative streaming cost; these measurements do not establish a universal frame-time guarantee.
111
+
112
+ ## Environment notes
113
+
114
+ Yarn Classic workspace linkage requires no new registry dependency or lock entry. An offline install attempt encountered unrelated existing Stripe version/cache mismatches; the new workspace symlink was linked locally for validation. Existing package manifests and lockfile versions were not upgraded as part of this rendering feature.
115
+
116
+ The existing application server cached a missing-file import during parallel package creation. A Vite config-triggered restart cleared it; the existing port 3010 application returned HTTP 200 afterward. Verification used an isolated fixture server on port 3011; standalone React Router routing redirects arbitrary fixture HTML, so its dedicated Vite config serves the fixture without application routing. Neither transport nor production data was involved.
117
+
118
+ The original plan contains no screenshot transcriptions. Fixtures demonstrate the specified five-column receipt shape and three-column/two-row CSV shape with clearly synthetic values.
@@ -0,0 +1,204 @@
1
+ import assert from 'node:assert/strict';
2
+ import { createHash } from 'node:crypto';
3
+ import { readFile, writeFile } from 'node:fs/promises';
4
+ import { createServer } from 'node:http';
5
+ import { extname, resolve, sep } from 'node:path';
6
+ import { chromium } from 'playwright';
7
+
8
+ /*
9
+ * Serve a prebuilt synthetic preview on an approved local development port.
10
+ */
11
+ async function serve(directory) {
12
+ const root = resolve(directory);
13
+ const server = createServer(async (request, response) => {
14
+ try {
15
+ const path = resolve(root, `.${new URL(request.url, 'http://localhost').pathname}`);
16
+ if (!path.startsWith(`${root}${sep}`)) throw new Error('Invalid fixture path.');
17
+ const body = await readFile(path);
18
+ response.setHeader(
19
+ 'Content-Type',
20
+ { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css' }[extname(path)] || 'application/octet-stream',
21
+ );
22
+ response.end(body);
23
+ } catch {
24
+ response.writeHead(404).end();
25
+ }
26
+ });
27
+ for (const port of [3010, 3011]) {
28
+ try {
29
+ await new Promise((resolve, reject) => {
30
+ server.once('error', reject);
31
+ server.listen(port, '127.0.0.1', resolve);
32
+ });
33
+ server.removeAllListeners('error');
34
+ return { server, url: `http://127.0.0.1:${port}/tests/fixtures/AIChatContentPreview.html` };
35
+ } catch (error) {
36
+ server.removeAllListeners('error');
37
+ if (error.code !== 'EADDRINUSE' || port === 3011) throw error;
38
+ }
39
+ }
40
+ }
41
+
42
+ /*
43
+ * Read browser CPU counters separately from the React-only profiling duration.
44
+ */
45
+ async function metrics(session) {
46
+ return Object.fromEntries((await session.send('Performance.getMetrics')).metrics.map(({ name, value }) => [name, value]));
47
+ }
48
+
49
+ /*
50
+ * Exercise the unchanged table interactions, overflow, themes, and status-only CSV finalization in the real message container.
51
+ */
52
+ async function verifyInteractions(browser, url, output) {
53
+ const page = await browser.newPage({ viewport: { width: 1280, height: 900 } });
54
+ try {
55
+ await page.goto(url);
56
+ for (const width of [320, 420, 780]) {
57
+ await page.getByRole('button', { name: `${width}px`, exact: true }).click();
58
+ await page.getByRole('button', { name: 'Measure', exact: true }).click();
59
+ const report = JSON.parse(await page.locator('output').textContent());
60
+ assert.equal(report.pageOverflow, false);
61
+ assert.equal(report.containerOverflow, false);
62
+ }
63
+ await page.setViewportSize({ width: 375, height: 900 });
64
+ await page.getByRole('button', { name: '320px', exact: true }).click();
65
+ await page.getByRole('button', { name: 'Toggle theme', exact: true }).click();
66
+ const scroll = page.locator('[role="table"]').first().locator('..');
67
+ await scroll.focus();
68
+ await page.keyboard.press('ArrowRight');
69
+ await page.waitForFunction(() => document.querySelector('[role="table"]')?.parentElement.scrollLeft > 0);
70
+ await page.waitForTimeout(300);
71
+ await page.getByRole('button', { name: 'Append prose', exact: true }).click();
72
+ await page.getByRole('button', { name: 'Measure', exact: true }).click();
73
+ const appended = JSON.parse(await page.locator('output').textContent());
74
+ assert.equal(appended.sameTable, true);
75
+ assert.equal(appended.scrollRetained, true);
76
+ assert.equal(appended.pageOverflow, false);
77
+ assert.equal(appended.containerOverflow, false);
78
+ await page.locator('[data-theme] > div:last-child').screenshot({ path: `${output}.mobile-dark.png` });
79
+ const downloading = page.waitForEvent('download');
80
+ await page.getByRole('button', { name: 'Download CSV', exact: true }).first().click();
81
+ const download = await downloading;
82
+ const csv = await readFile(await download.path(), 'utf8');
83
+ assert.ok(csv.includes('001') && csv.includes('Coffee beans'));
84
+ await page.getByRole('button', { name: 'csv', exact: true }).click();
85
+ await page.getByRole('button', { name: 'streaming', exact: true }).click();
86
+ assert.equal(await page.locator('[role="table"]').count(), 0);
87
+ await page.getByRole('button', { name: 'interrupted', exact: true }).click();
88
+ assert.equal(await page.locator('[role="table"]').count(), 0);
89
+ await page.getByRole('button', { name: 'complete', exact: true }).click();
90
+ assert.equal(await page.locator('[role="table"]').count(), 1);
91
+ return {
92
+ widths: [320, 420, 780],
93
+ mobileDark: true,
94
+ keyboardScroll: true,
95
+ preservedScroll: true,
96
+ csvStatusTransitions: true,
97
+ csvDownloadHash: createHash('sha256').update(csv).digest('hex'),
98
+ };
99
+ } finally {
100
+ await page.close();
101
+ }
102
+ }
103
+
104
+ /*
105
+ * Measure a table mount and deterministic stream, retaining DOM hashes for paired output checks.
106
+ */
107
+ async function measure(browser, url, fixture) {
108
+ const page = await browser.newPage({ viewport: { width: 1280, height: 900 } });
109
+ const errors = [];
110
+ page.on('pageerror', (error) => errors.push(error.message));
111
+ try {
112
+ await page.goto(url);
113
+ await page.getByRole('button', { name: 'csv', exact: true }).click();
114
+ await page.getByRole('button', { name: 'streaming', exact: true }).click();
115
+ // Start both builds after the existing 250 ms message-animation warm-up has settled.
116
+ await page.waitForTimeout(300);
117
+ // The open CSV is code, so the next fixture mounts its table rows from scratch.
118
+ await page.getByRole('button', { name: fixture, exact: true }).click();
119
+ await page.getByRole('button', { name: 'Measure', exact: true }).click();
120
+ const mount = JSON.parse(await page.locator('output').textContent());
121
+ const session = await page.context().newCDPSession(page);
122
+ await session.send('Performance.enable');
123
+ const before = await metrics(session);
124
+ await page.evaluate(() => {
125
+ window.benchmarkFrames = [];
126
+ window.benchmarkFrameActive = true;
127
+ let previous;
128
+ /* Record browser frame intervals while the synthetic response streams. */
129
+ function frame(now) {
130
+ if (!window.benchmarkFrameActive) return;
131
+ if (previous !== undefined) window.benchmarkFrames.push(now - previous);
132
+ previous = now;
133
+ requestAnimationFrame(frame);
134
+ }
135
+ requestAnimationFrame(frame);
136
+ });
137
+ await page.getByRole('button', { name: 'Stream fixture', exact: true }).click();
138
+ await page.waitForFunction(() => document.querySelector('[data-theme] > p')?.textContent?.includes('complete'));
139
+ const after = await metrics(session);
140
+ const frames = await page.evaluate(() => {
141
+ window.benchmarkFrameActive = false;
142
+ return window.benchmarkFrames;
143
+ });
144
+ await page.getByRole('button', { name: 'Measure', exact: true }).click();
145
+ const stream = JSON.parse(await page.locator('output').textContent());
146
+ const html = await page.locator('[data-theme] > div:last-child').innerHTML();
147
+ const cpu = Object.fromEntries(
148
+ ['ScriptDuration', 'LayoutDuration', 'RecalcStyleDuration', 'TaskDuration'].map((name) => [
149
+ name,
150
+ +(1000 * (after[name] - before[name])).toFixed(2),
151
+ ]),
152
+ );
153
+ assert.deepEqual(errors, []);
154
+ assert.equal(stream.pageOverflow, false);
155
+ assert.equal(stream.containerOverflow, false);
156
+ return {
157
+ html,
158
+ fixture,
159
+ mountMs: mount.maxCommitMs,
160
+ streamMs: stream.maxCommitMs,
161
+ nodes: stream.nodes,
162
+ htmlHash: createHash('sha256').update(html).digest('hex'),
163
+ frameMaxMs: +Math.max(...frames).toFixed(2),
164
+ cpu,
165
+ };
166
+ } finally {
167
+ await page.close();
168
+ }
169
+ }
170
+
171
+ /*
172
+ * Compare fixed builds using one warm-up and five recorded runs; this never calls application APIs.
173
+ */
174
+ async function main() {
175
+ const [directory, output, samples = '5'] = process.argv.slice(2);
176
+ assert.ok(directory && output, 'Usage: node benchmarks/browser.mjs BUILD_DIRECTORY OUTPUT.json [SAMPLES=5]');
177
+ assert.ok(Number.isInteger(Number(samples)) && Number(samples) > 0, 'SAMPLES must be a positive integer.');
178
+ const { server, url } = await serve(directory);
179
+ let browser;
180
+ try {
181
+ browser = await chromium.launch({ headless: true });
182
+ const interactions = await verifyInteractions(browser, url, output);
183
+ const results = [];
184
+ const snapshots = new Set();
185
+ for (let run = 0; run <= Number(samples); run++) {
186
+ for (const fixture of ['receipt', 'long', 'limit', 'paragraph']) {
187
+ const { html, ...result } = await measure(browser, url, fixture);
188
+ if (!snapshots.has(result.htmlHash)) {
189
+ await writeFile(`${output}.${fixture}.${result.htmlHash}.html`, html);
190
+ snapshots.add(result.htmlHash);
191
+ }
192
+ if (run) results.push({ run, ...result });
193
+ }
194
+ console.log(`Finished ${run ? `sample ${run}/${samples}` : 'warm-up'}`);
195
+ }
196
+ await writeFile(output, `${JSON.stringify({ browser: browser.version(), interactions, results }, null, 2)}\n`);
197
+ console.log(`Saved ${output}`);
198
+ } finally {
199
+ await browser?.close();
200
+ await new Promise((resolve) => server.close(resolve));
201
+ }
202
+ }
203
+
204
+ await main();
@@ -0,0 +1,89 @@
1
+ import assert from 'node:assert/strict';
2
+ import { writeFile } from 'node:fs/promises';
3
+ import { cpus } from 'node:os';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { reconcileContentDocument } from '../src/utils/contentIdentity.ts';
6
+ import { parseContent } from '../src/utils/parseContent.ts';
7
+ import { parseContentIncrementally } from '../src/utils/parseContentIncrementally.ts';
8
+
9
+ const fixtures = {
10
+ receipt: '## Receipt\n\n| Item | Count |\n| --- | --- |\n| Tea | 001 |\n\nDone **today**.',
11
+ long: Array.from(
12
+ { length: 10 },
13
+ (_, index) =>
14
+ `## Table ${index + 1}\n\n| Name | Description | Code |\n| --- | --- | --- |\n${Array.from({ length: 35 }, (_, row) => `| Item ${row} | A longer synthetic description for wrapping in chat. | 000${row} |`).join('\n')}\n\n`,
15
+ ).join(''),
16
+ limit: `| A | B | C | D | E |\n| - | - | - | - | - |\n${Array.from({ length: 500 }, (_, row) => `| ${row} | ${'description '.repeat(24)} | 0001 | **Value** | More text |`).join('\n')}\n`,
17
+ paragraph: 'An unfinished paragraph '.repeat(8000),
18
+ };
19
+
20
+ /*
21
+ * Measure all synchronous parsing and identity reconciliation across fixed-size transport updates.
22
+ */
23
+ function measure(source, chunkSize, parse) {
24
+ let previous = null;
25
+ const durations = [];
26
+ for (let end = chunkSize; end < source.length + chunkSize; end += chunkSize) {
27
+ const prefix = source.slice(0, end);
28
+ const status = end >= source.length ? 'complete' : 'streaming';
29
+ const start = performance.now();
30
+ previous = reconcileContentDocument(previous, parse(previous, prefix, status));
31
+ durations.push(performance.now() - start);
32
+ }
33
+ const totalMs = durations.reduce((sum, duration) => sum + duration, 0);
34
+ durations.sort((a, b) => a - b);
35
+ assert.deepEqual(previous, parseContent(source));
36
+ return { updates: durations.length, totalMs, p95Ms: durations[Math.ceil(durations.length * 0.95) - 1], maxMs: durations.at(-1) };
37
+ }
38
+
39
+ /*
40
+ * Summarize repeated samples without treating noisy wall-clock measurements as test assertions.
41
+ */
42
+ function median(samples, key) {
43
+ return +samples
44
+ .map((sample) => sample[key])
45
+ .sort((a, b) => a - b)
46
+ [Math.floor(samples.length / 2)].toFixed(3);
47
+ }
48
+
49
+ /*
50
+ * Compare full parsing with incremental rendering using either the current oracle or a saved baseline bundle.
51
+ */
52
+ async function main() {
53
+ const [output, baselinePath] = process.argv.slice(2);
54
+ assert.ok(output, 'Usage: node benchmarks/streaming.mjs OUTPUT.json [BASELINE_PARSER.mjs]');
55
+ const baseline = baselinePath ? (await import(pathToFileURL(baselinePath).href)).parseContent : parseContent;
56
+ const parsers = { full: (_previous, source, status) => baseline(source, status), incremental: parseContentIncrementally };
57
+ const results = [];
58
+ for (const [fixture, source] of Object.entries(fixtures)) {
59
+ for (const chunkSize of [256, 2048]) {
60
+ const samples = { full: [], incremental: [] };
61
+ for (let run = 0; run < 6; run++) {
62
+ // Alternate order to avoid always warming or cooling the same implementation first.
63
+ for (const name of run % 2 ? ['incremental', 'full'] : ['full', 'incremental']) {
64
+ const result = measure(source, chunkSize, parsers[name]);
65
+ if (run) samples[name].push(result);
66
+ }
67
+ }
68
+ for (const [parser, values] of Object.entries(samples))
69
+ results.push({
70
+ fixture,
71
+ chars: source.length,
72
+ chunkSize,
73
+ parser,
74
+ updates: values[0].updates,
75
+ totalMs: median(values, 'totalMs'),
76
+ p95Ms: median(values, 'p95Ms'),
77
+ maxMs: median(values, 'maxMs'),
78
+ samples: values,
79
+ });
80
+ console.log(`Measured ${fixture}, ${chunkSize}-character chunks`);
81
+ }
82
+ }
83
+ await writeFile(
84
+ output,
85
+ `${JSON.stringify({ node: process.version, cpu: cpus()[0]?.model, baseline: baselinePath || 'current full parser', results }, null, 2)}\n`,
86
+ );
87
+ }
88
+
89
+ await main();
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
- "name": "@jsb188/ai-chat",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@jsb188/ai-chat",
3
+ "version": "1.1.12",
4
+ "description": "Source-preserving AI chat content parsing and rendering.",
5
+ "license": "ISC",
6
+ "author": "jsb188",
7
+ "type": "module",
8
+ "exports": {
9
+ ".": "./src/main.ts",
10
+ "./parser": "./src/parser.ts",
11
+ "./types": "./src/types/content.ts",
12
+ "./ui/AIChatUI": "./src/ui/AIChatUI.tsx"
13
+ },
14
+ "peerDependencies": {
15
+ "@jsb188/app": "1.1.12",
16
+ "@jsb188/form": "1.1.12",
17
+ "@jsb188/graphql": "1.1.12",
18
+ "@jsb188/mday": "1.1.12",
19
+ "@jsb188/mday-web": "1.1.12",
20
+ "@jsb188/react-web": "1.1.12",
21
+ "react": "^19.3.0",
22
+ "react-dom": "^19.3.0"
23
+ },
24
+ "devDependencies": {
25
+ "@types/react": "^19.3.0",
26
+ "@types/react-dom": "^19.3.0",
27
+ "jsdom": "^29.1.1",
28
+ "react-dom": "^19.3.0",
29
+ "typescript": "^7.0.2",
30
+ "vite": "^8.1.5",
31
+ "vitest": "4.1.10"
32
+ },
33
+ "scripts": {
34
+ "test": "vitest run --config ./vitest.config.ts",
35
+ "typecheck": "tsc --project ./tsconfig.json"
36
+ }
37
+ }
package/src/main.ts ADDED
@@ -0,0 +1,5 @@
1
+ export { AIChatContent } from './modules/AIChatContent';
2
+ export type { AIChatContentProps } from './modules/AIChatContent';
3
+ export { AgentNotes } from './modules/AgentNotes';
4
+ export type { AgentNoteChatStarted, AgentNotesProps } from './modules/AgentNotes.types';
5
+ export type { ChatContentStatus } from './types/content';