Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/web-ui/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,12 @@ establish visual fidelity):
pnpm --dir src/web-ui run test:run src/infrastructure/update src/infrastructure/api/service-api/SystemAPI.test.ts src/shared/notification-system/components/NotificationContainer.test.tsx
```

For Markdown section boundaries, streaming prefix reuse, and cache isolation, run
`pnpm --dir src/web-ui run test:run src/infrastructure/markdown/markdownSections.test.ts src/infrastructure/markdown/markdownSections.streaming.test.ts`.
These local parser fixtures compare streamed and cold boundaries and measure the
actual parser input size. They do not establish native frame latency or live
remote behavior.

For Markdown parse prewarming or dependency resolution, run
`pnpm --dir src/web-ui run test:run src/infrastructure/markdown/markdownParse.worker.test.ts src/infrastructure/markdown/markdownParseCache.test.ts`.
This builds the real Worker entry with the product aliases, checks parsing without
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';

const { parsedSources } = vi.hoisted(() => ({ parsedSources: [] as string[] }));
vi.mock('stream-markdown-parser', async importOriginal => {
const actual = await importOriginal<typeof import('stream-markdown-parser')>();
return {
...actual,
getMarkdown: (...args: Parameters<typeof actual.getMarkdown>) => {
const parser = actual.getMarkdown(...args);
const parse = parser.block.parse;
vi.spyOn(parser.block, 'parse').mockImplementation(function (...parseArgs) {
parsedSources.push(parseArgs[0]);
return parse.apply(parser.block, parseArgs);
});
return parser;
},
};
});

beforeEach(() => {
vi.restoreAllMocks();
vi.resetModules();
parsedSources.length = 0;
});

const paragraph = `${'A paragraph with **bold** and Unicode 中文. '.repeat(24)}\n\n`;
const prefix = paragraph.repeat(24);

describe('streaming Markdown section parsing', () => {
it('parses only the tail and reuses closed sections over repeated updates', async () => {
const { markdownSections } = await import('./markdownSections');
let source = prefix;
let previous = markdownSections(source, { streaming: true });
expect(previous.length).toBeGreaterThan(3);
for (let index = 0; index < 25; index += 1) {
source += `Update ${index}.\n\n`;
parsedSources.length = 0;
const next = markdownSections(source, { streaming: true });
expect(parsedSources).toHaveLength(1);
expect(parsedSources[0].length).toBeLessThan(source.length / 2);
expect(next[0]).toBe(previous[0]);
expect(next.map(section => source.slice(section.start, section.end)).join('')).toBe(source);
previous = next;
}
// A fresh module has no streaming record: compare with a full parse.
vi.restoreAllMocks();
vi.resetModules();
const cold = await import('./markdownSections');
expect(previous).toEqual(cold.markdownSections(source));
});

it.each(['\n', '\r\n', '\r'])('matches full parsing with %j newlines and appended blocks', async newline => {
const { markdownSections } = await import('./markdownSections');
let source = prefix.replace(/\n/g, newline);
markdownSections(source, { streaming: true });
const chunks = ['```ts\n', paragraph.repeat(5), '```\n\n', '- List\n - Nested\n\n', '| A | B |\n|---|---|\n| one | two |\n\n'];
const frames = chunks.map(chunk => {
source += chunk.replace(/\n/g, newline);
return { source, sections: markdownSections(source, { streaming: true }) };
});
for (const frame of frames) {
vi.restoreAllMocks();
vi.resetModules();
const cold = await import('./markdownSections');
expect(frame.sections).toEqual(cold.markdownSections(frame.source));
}
});

it.each(['\n[id]: https://example.org\n', '\n[^1]: Footnote\n', '\n<div>HTML</div>\n'])
('collapses frozen sections when the tail adds a document dependency: %s', async suffix => {
const { markdownSections } = await import('./markdownSections');
const source = '[id]\n\n' + prefix;
expect(markdownSections(source, { streaming: true }).length).toBeGreaterThan(3);
const extended = source + suffix;
expect(markdownSections(extended, { streaming: true })).toEqual([{ start: 0, end: extended.length }]);
});

it('preserves journal blank-line coordinates across streaming and settlement', async () => {
const { markdownSections } = await import('./markdownSections');
const source = prefix.replace(/\n\n/g, '\n\n\n\n');
markdownSections(source, { streaming: true });
const extended = source + paragraph;
const sections = markdownSections(extended, { streaming: true });
const normalized = extended.replace(/\n{3,}/g, '\n\n');
expect(sections.map(s => extended.slice(s.start, s.end).replace(/\n{3,}/g, '\n\n')))
.toEqual(markdownSections(normalized).map(s => normalized.slice(s.start, s.end)));
expect(markdownSections(extended)).toEqual(sections);
});

it('fully parses replacement content instead of reusing an unrelated prefix', async () => {
const { markdownSections } = await import('./markdownSections');
markdownSections(prefix, { streaming: true });
const replacement = 'Replacement\n\n' + prefix;
parsedSources.length = 0;
markdownSections(replacement, { streaming: true });
expect(parsedSources).toEqual([replacement]);
});
});
114 changes: 82 additions & 32 deletions src/web-ui/src/infrastructure/markdown/markdownSections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,50 @@ const parser = getMarkdown('flowchat-section-boundaries', {
markdownItOptions: { typographer: false },
});

interface SettledPrefixRecord {
source: string;
boundaries: number[];
extendable: boolean;
}

let lastRecord: SettledPrefixRecord | undefined;

function computeRawBoundaries(source: string): { boundaries: number[]; extendable: boolean } {
const normalized = source.replace(/\r\n?|\0/g, match => match === '\0' ? '\uFFFD' : '\n');
const tokens: Parameters<typeof parser.block.parse>[3] = [];
const environment: Record<string, unknown> = {};
parser.block.parse(normalized, parser, environment, tokens);
if (environment.references || environment.footnotes
|| tokens.some(token => token.type.startsWith('html') || token.type.startsWith('footnote')
// Inline HTML/reference definitions may bind beyond a top-level block.
|| (token.type === 'inline' && /<|\]\s*\[|\[\^/.test(token.content)))) {
return { boundaries: [0], extendable: false };
}
const offsets = [0];
const endings = /\r\n|\r|\n/g;
let match: RegExpExecArray | null;
while ((match = endings.exec(source))) offsets.push(match.index + match[0].length);
const starts = tokens.filter(token => token.level === 0 && token.map && token.nesting !== -1)
.map(token => offsets[token.map![0]]).filter((value): value is number => value !== undefined);
const boundaries = [0];
// Streaming coalesces blank lines; journal records retain the original
// source. Budget in the same coordinates while returning exact raw ranges.
const blankRuns = source.matchAll(/\n{3,}/g);
let blankRun = blankRuns.next(), removed = 0, normalizedBoundary = 0;
for (const start of starts) {
while (!blankRun.done && blankRun.value.index + blankRun.value[0].length <= start) {
removed += blankRun.value[0].length - 2;
blankRun = blankRuns.next();
}
const normalizedStart = start - removed;
if (normalizedStart - normalizedBoundary >= SECTION_CHARS) {
boundaries.push(start);
normalizedBoundary = normalizedStart;
}
}
return { boundaries, extendable: true };
}

/** Block tokenization only (~linear), never inline parsing or a second renderer.
* Actual sections still use the product's remark/rehype/sanitizer pipeline.
* Documents with cross-block references/raw HTML stay together. */
Expand All @@ -29,40 +73,46 @@ export function markdownSections(
const cached = cache.get(source) ?? (options.streaming ? streamingCache.get(source) : undefined);
if (cached) return cached;
const started = isStartupRenderTraceEnabled() ? performance.now() : undefined;
const normalized = source.replace(/\r\n?|\0/g, match => match === '\0' ? '\uFFFD' : '\n');
const tokens: Parameters<typeof parser.block.parse>[3] = [];
const environment: Record<string, unknown> = {};
parser.block.parse(normalized, parser, environment, tokens);
let sections = whole();
if (!environment.references && !environment.footnotes
&& !tokens.some(token => token.type.startsWith('html') || token.type.startsWith('footnote')
// Inline HTML/reference definitions may bind beyond a top-level block.
|| (token.type === 'inline' && /<|\]\s*\[|\[\^/.test(token.content)))) {
const offsets = [0];
const endings = /\r\n|\r|\n/g;
let match: RegExpExecArray | null;
while ((match = endings.exec(source))) offsets.push(match.index + match[0].length);
const starts = tokens.filter(token => token.level === 0 && token.map && token.nesting !== -1)
.map(token => offsets[token.map![0]]).filter((value): value is number => value !== undefined);
const boundaries = [0];
// Streaming coalesces blank lines; journal records retain the original
// source. Budget in the same coordinates while returning exact raw ranges.
const blankRuns = source.matchAll(/\n{3,}/g);
let blankRun = blankRuns.next(), removed = 0, normalizedBoundary = 0;
for (const start of starts) {
while (!blankRun.done && blankRun.value.index + blankRun.value[0].length <= start) {
removed += blankRun.value[0].length - 2;
blankRun = blankRuns.next();
}
const normalizedStart = start - removed;
if (normalizedStart - normalizedBoundary >= SECTION_CHARS) {
boundaries.push(start);
normalizedBoundary = normalizedStart;
}
}
sections = boundaries.map((start, index) => ({ start, end: boundaries[index + 1] ?? source.length }));

let boundaries: number[];
let extendable = true;

// Streaming prefix optimization: if source strictly starts with lastRecord.source
// and the settled prefix has frozen closed boundaries, avoid re-parsing the settled head.
const prevRecord = lastRecord && source.startsWith(lastRecord.source) ? lastRecord : undefined;
if (prevRecord && prevRecord.extendable && prevRecord.boundaries.length > 1) {
const frozenBoundaries = prevRecord.boundaries.slice(0, -1);
const tailOffset = frozenBoundaries[frozenBoundaries.length - 1];
const tailSource = source.slice(tailOffset);
// Keep one section of lookbehind: the trailing block can change as text
// arrives. This tail is at least SECTION_CHARS long; never skip parsing it
// based on size, since new HTML or definitions can invalidate all splits.
const tailResult = computeRawBoundaries(tailSource);
extendable = tailResult.extendable;
boundaries = extendable
? frozenBoundaries.concat(tailResult.boundaries.slice(1).map(b => b + tailOffset))
: [0];
} else {
const raw = computeRawBoundaries(source);
boundaries = raw.boundaries;
extendable = raw.extendable;
}

const prevSections = prevRecord
? cache.get(prevRecord.source) ?? streamingCache.get(prevRecord.source)
: undefined;
const sections: readonly MarkdownSection[] = extendable
? boundaries.map((start, index) => {
const end = boundaries[index + 1] ?? source.length;
// Reuse immutable closed section instances from previous stream frame
const previous = prevSections?.[index];
return previous?.start === start && previous.end === end ? previous : { start, end };
})
: whole();

target.set(source, sections, source.length * 2 + sections.length * 32);
// Do not retain an unbounded source that the resource cache rejected.
lastRecord = target.has(source) ? { source, boundaries, extendable } : undefined;
if (started !== undefined) startupTrace.markPhase('flowchat_markdown_sections', {
durationMs: performance.now() - started, contentLength: source.length, sections: sections.length,
});
Expand Down
Loading