okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-guidata (4c4596746) into f-0213-int22a3d7068

main
8.0 KiB159 linesraw
1// #5180: the Markdown preview in the sidebar is keyed by the text, drawn in bounded slices, and does no work for an unchanged file
2// while unrelated store updates (streamed tokens) re-render the chat. Pure text work plus server rendering; the browser run is in the report.
3import assert from 'node:assert/strict';
4import test from 'node:test';
5import { readFileSync } from 'node:fs';
6import { resolve } from 'node:path';
7import { createRequire } from 'node:module';
8import { build } from 'esbuild';
9
10const root = resolve(import.meta.dirname, '..');
11const bundle = await build({
12  stdin: { contents: `import React from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; import { Markdown } from './src/components/Markdown.tsx'; export * from './src/lib/preview-render.ts'; export const html = text => renderToStaticMarkup(React.createElement(Markdown, { text }));`, resolveDir: root, loader: 'ts' },
13  bundle: true, write: false, platform: 'node', format: 'cjs', jsx: 'automatic', external: ['katex', 'katex/dist/katex.min.css'],
14  plugins: [{ name: 'stub', setup(b) {
15    b.onResolve({ filter: /^\.\/ui$/ }, () => ({ path: 'ui', namespace: 'test-stub' }));
16    b.onLoad({ filter: /.*/, namespace: 'test-stub' }, () => ({ contents: 'export const IconBtn = () => null; export const Btn = () => null; export const Icon = () => null;' }));
17  } }],
18});
19const mod = { exports: {} };
20new Function('require', 'module', 'exports', bundle.outputFiles[0].text)(createRequire(import.meta.url), mod, mod.exports);
21const { html, textRevision, splitPreview, previewSlices, previewStats, previewTier, slicesAfter, slicesAtStart,
22  PREVIEW_SLICE_CHARS, PREVIEW_FIRST_SLICES, PREVIEW_BLOCK_LIMIT, PREVIEW_RENDER_LIMIT } = mod.exports;
23
24/** A long document the way the reports describe it: headings, paragraphs, lists, tables and fenced code with blank lines in them. */
25function longDoc(sections) {
26  const out = [];
27  for (let n = 0; n < sections; n++) {
28    out.push(`# Section ${n}`, '', `Paragraph ${n} with **bold**, *italic*, \`code\` and a [link](https://example.com/${n}).`, 'It continues on a second line.', '');
29    out.push('- first item', '- second item', '', '1. step one', '2. step two', '');
30    out.push('| Name | Value |', '| --- | --- |', ...Array.from({ length: 6 }, (_, r) => `| row ${r} | value ${n}-${r} |`), '');
31    out.push('```js', `const a${n} = 1;`, '', '', `console.log(a${n});`, '```', '');
32    out.push('> a quote', '');
33  }
34  return out.join('\n');
35}
36
37test('the revision key follows the text and nothing else', () => {
38  assert.equal(textRevision('abc'), textRevision('abc'));
39  assert.notEqual(textRevision('abc'), textRevision('abd'));
40  assert.notEqual(textRevision('abc'), textRevision('abc '));
41  assert.notEqual(textRevision(''), textRevision(' '));
42  assert.match(textRevision('x'), /^[0-9a-z]+-[0-9a-z]+$/);
43});
44
45test('slices drawn one after the other are the same elements as the whole file', () => {
46  const docs = [
47    longDoc(40),
48    'one\n\ntwo\n\n\n\nthree',
49    '```\nfenced\n\nwith a blank line\n\n```\n\nafter',
50    '$$\nx = 1\n\ny = 2\n$$\n\ntext',
51    '\\[\na\n\nb\n\\]\n\ntext',
52    '| a | b |\n| --- | --- |\n| 1 | 2 |\n\n| c | d |\n| --- | --- |\n| 3 | 4 |',
53    '- a\n- b\n\n- c\n\n1. x\n\n2. y',
54    '$$ open and never closed\n\nnext paragraph\n\nmore',
55    '',
56    '\n\n\n',
57  ];
58  for (const doc of docs)
59    for (const target of [1, 40, 500, PREVIEW_SLICE_CHARS]) {
60      const whole = html(doc);
61      const sliced = splitPreview(doc, target).map(s => html(s.text)).join('');
62      assert.equal(sliced, whole, `target ${target}, doc starting ${JSON.stringify(doc.slice(0, 30))}`);
63    }
64});
65
66test('a slice never ends inside a fenced block or a display-math block', () => {
67  const doc = ['intro', '', '```', 'a', '', 'b', '```', '', '$$', 'x', '', 'y', '$$', '', 'outro'].join('\n');
68  const slices = splitPreview(doc, 1);
69  for (const s of slices) {
70    const fences = (s.text.match(/^\s*```/gm) ?? []).length;
71    assert.equal(fences % 2, 0, 'balanced fences in ' + JSON.stringify(s.text));
72    const math = (s.text.match(/^\s*\$\$/gm) ?? []).length;
73    assert.equal(math % 2, 0, 'balanced math in ' + JSON.stringify(s.text));
74  }
75  assert.ok(slices.length >= 3);
76});
77
78test('a long file is cut into slices of about the target size, each with its own key', () => {
79  const doc = longDoc(160);
80  assert.ok(doc.length > 60000, 'a long file: ' + doc.length);
81  const slices = splitPreview(doc);
82  assert.ok(slices.length > 8);
83  for (const s of slices.slice(0, -1))
84    assert.ok(s.text.length < PREVIEW_SLICE_CHARS * 2, 'bounded slice ' + s.text.length);
85  assert.equal(new Set(slices.map(s => s.key)).size, slices.length);
86});
87
88test('changing one place changes one slice key; the others keep theirs and are not rendered again', () => {
89  const a = longDoc(60);
90  const b = a.replace('Paragraph 3 with', 'Paragraph 3 changed with');
91  const ka = splitPreview(a).map(s => s.key), kb = splitPreview(b).map(s => s.key);
92  assert.equal(ka.length, kb.length);
93  const changed = ka.filter((k, i) => k !== kb[i]);
94  assert.equal(changed.length, 1);
95});
96
97test('render count: an unchanged file is cut once however many store updates arrive', () => {
98  const doc = longDoc(80);
99  const before = previewStats.cuts;
100  let first;
101  for (let tick = 0; tick < 500; tick++) {          // 500 streamed-token updates of the chat, each asking for the same file
102    const slices = previewSlices(doc);
103    first ??= slices;
104    assert.equal(slices, first, 'the same array: nothing downstream sees a change');
105  }
106  assert.equal(previewStats.cuts - before, 1);
107  // the file changing is one more cut, and going back to the old text is still known
108  const changed = doc + '\nmore';
109  previewSlices(changed); previewSlices(changed);
110  assert.equal(previewStats.cuts - before, 2);
111  previewSlices(doc);
112  assert.equal(previewStats.cuts - before, 2);
113});
114
115test('the cache keeps a few texts only', () => {
116  const before = previewStats.cuts;
117  for (let i = 0; i < 20; i++) previewSlices('text number ' + i);
118  assert.equal(previewStats.cuts - before, 20);
119  previewSlices('text number 0');                 // long gone from a cache of four
120  assert.equal(previewStats.cuts - before, 21);
121});
122
123test('a very large file does not produce unbounded work', () => {
124  const huge = longDoc(2000);
125  assert.ok(huge.length > PREVIEW_RENDER_LIMIT);
126  assert.equal(previewTier(huge), 'plain');
127  assert.equal(previewTier(longDoc(100)), 'markdown');
128  // one table or code block that cannot be cut is plain text, not parsed
129  const bigTable = '| a | b |\n| --- | --- |\n' + Array.from({ length: 5000 }, (_, i) => `| ${i} | ${'x'.repeat(10)} |`).join('\n');
130  assert.ok(bigTable.length > PREVIEW_BLOCK_LIMIT);
131  const slices = splitPreview(bigTable);
132  assert.equal(slices.length, 1);
133  assert.equal(slices[0].plain, true);
134  assert.equal(splitPreview('| a | b |\n| --- | --- |\n| 1 | 2 |')[0].plain, false);
135});
136
137test('the first paint and every step are bounded; a new text never takes back slices already shown', () => {
138  assert.equal(slicesAtStart(0, 100), PREVIEW_FIRST_SLICES);
139  assert.equal(slicesAtStart(0, 1), 1);
140  assert.equal(slicesAtStart(0, 0), 0);
141  assert.equal(slicesAtStart(30, 100), 30);
142  assert.equal(slicesAtStart(30, 10), 10);
143  // steps reach the end in a bounded number of steps and never pass it
144  let shown = slicesAtStart(0, 100), steps = 0;
145  while (shown < 100) { const next = slicesAfter(shown, 100); assert.ok(next > shown && next - shown <= 2); shown = next; steps++; }
146  assert.equal(steps, 49);
147  assert.equal(slicesAfter(100, 100), 100);
148});
149
150test('the sidebar uses the bounded component and the component cancels superseded work', () => {
151  const panel = readFileSync(resolve(root, 'src/components/ArtifactPanel.tsx'), 'utf8');
152  assert.match(panel, /<PreviewMarkdown text=\{text\}\/>/);
153  assert.doesNotMatch(panel, /<Markdown text=\{text\}\/>/);
154  const view = readFileSync(resolve(root, 'src/components/PreviewMarkdown.tsx'), 'utf8');
155  assert.match(view, /export const PreviewMarkdown = memo\(/);
156  assert.match(view, /const Slice = memo\(/);
157  assert.match(view, /return \(\) => clearTimeout\(timer\)/);
158  assert.match(view, /key=\{s\.key\}/);
159});