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
53 changes: 46 additions & 7 deletions docs/plans/transcript-insight-issues.md
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ rather than leaving it half-translated.

## 4. Track B — streaming-markdown efficiency (mobile-first)

### B1 — defer heavy treatment while `partial:true` (smallest, ship first)
### B1 — defer heavy treatment while `partial:true` (smallest, ship first) — **shipped**

While the chain entry carries `partial:true`, `_markdownBody` renders
fenced blocks as plain mono (skip `HighlightedCodeBuilder`) and skips
Expand All @@ -316,6 +316,13 @@ worst term (highlight.js × chunks) with zero new dependencies and zero
visual change on completed messages. Desktop equivalent: gate
`rehype-highlight`/`rehype-katex` on the partial flag the same way.

Shipped as described, with one clarification worth carrying into B2: the gate
is tested in **both** directions. A test that only asserts a partial *skips*
the work would pass just as well if the builders were deleted outright, so
every case has its completed-message twin proving the final render is
unchanged. That is the actual contract — *streaming is cheap and approximate,
the finished message is exact*.

### B2 — stable-prefix block cache (the markstream idea, in Dart)

Split the accumulated text at **completed block boundaries** (blank-line +
Expand All @@ -330,15 +337,47 @@ visually identical to single-body rendering — snapshot-test the seams
(tight list spacing across split points is the known risk; splitting only
at top-level blank lines avoids most of it).

**Apply the split only while `partial`.** The plan originally asked for the
final text to be block-split too, with a snapshot test proving it identical to
single-body. Keeping the completed render single-body makes that identity hold
*by construction* instead of by test, confines the seam risk (tight list
spacing across split points) to the in-flight frame, and matches what B1
already established: streaming is approximate, the finished message is exact.

**The caching mechanism, to save the next person the dead end.** Memoizing
"blocks" only pays if Flutter can skip their subtrees — which it does when the
child widget is *identical* (same instance), since `updateChild` short-circuits
on `identical(oldWidget, newWidget)`. So the cache must hold built
`MarkdownBody` **instances** keyed by block content, not strings. That in turn
means the cache has to live in `_AgentEventCardState`, while `_markdownBody`
is currently a method on the `AgentEventCard` **widget** — moving it is part of
the work, not an incidental refactor.

### B3 — migrate to `flutter_markdown_plus`

Dependency swap + import sweep; `MarkdownBody`, `MarkdownElementBuilder`,
`builders`, styleSheet are API-identical (v1.0.x, `markdown ^7.3.1` —
our direct `markdown ^7.2.2` pin moves with it). Do B3 *after* B1/B2 so
the perf work is bisectable from the dep swap. Verify the two behaviors we
depend on: builder-append semantics for the `a` element (the
double-render workaround documented in `_markdownBody`) and
inline-`<code>` fallthrough (no `class` attr → styleSheet path).
`builders`, styleSheet are API-identical. Do B3 *after* B1/B2 so the perf work
is bisectable from the dep swap. Verify the two behaviors we depend on:
builder-append semantics for the `a` element (the double-render workaround
documented in `_markdownBody`) and inline-`<code>` fallthrough (no `class`
attr → styleSheet path).

Verified against pub.dev on 2026-07-29 (the plan previously said "v1.0.x"):
**1.0.12**, publisher **Foresight Mobile** (verified), depends on
`markdown ^7.3.1` — so our direct `markdown ^7.2.2` pin moves with it — and it
does expose `MarkdownBody` / `MarkdownElementBuilder` / `builders` /
`styleSheet`. The migration target is real and current.

### Why B2 and B3 stopped here (2026-07-29)

Both are **blocked on verification, not on design**. Flutter is not installed on
the authoring host, so B2 — a rewrite of the transcript's hottest widget whose
whole claim is "the render is unchanged" — cannot have that claim established
before it ships; the pure scanner would be CI-testable but the rendering would
not. B3's own acceptance criteria name two runtime behaviours to confirm, and
confirming them means running the app. This is the same file whose dispatch
logic regressed five times (`feed_reducer.dart` header, v1.0.667–721), which is
exactly the wrong place to ship an unverifiable change. Both need a device run.

## 5. Sequencing & review anchors

Expand Down
78 changes: 58 additions & 20 deletions lib/widgets/transcript/event_card.dart
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,11 @@ class AgentEventCard extends StatefulWidget {
ctx,
(payload['text'] ?? feedJsonPretty(payload)).toString(),
isThought: kind == 'thought',
// Streaming chunks carry the FULL accumulated text and replace the
// chain entry in place (collapseStreamingPartials), so the heavy
// treatment would re-run over the whole message on every chunk —
// see _markdownBody.
isPartial: payload['partial'] == true,
);
case 'raw':
return _rawBody(ctx, payload);
Expand Down Expand Up @@ -701,7 +706,27 @@ class AgentEventCard extends StatefulWidget {
// fenced code blocks, headers. Rendering as plain mono text buries the
// structure; rendering with a tight style sheet keeps the card compact
// while still reading like the agent's terminal output.
Widget _markdownBody(BuildContext ctx, String s, {bool isThought = false}) {
/// Renders a markdown body.
///
/// [isPartial] marks a still-streaming chunk. A partial carries the FULL
/// accumulated text and replaces its chain entry in place, so every chunk
/// re-parses the whole message, re-tokenizes every completed fenced block
/// through highlight.js, and re-lays-out every formula — synchronously on the
/// UI isolate. Over a long turn that is O(n²) (transcript P5 §0b).
///
/// So while partial we drop the two expensive builders and the math syntaxes:
/// fenced blocks render through the styleSheet's own themed codeblock
/// decoration (same background and border, no tokenization) and `$…$` stays
/// literal text. The final, non-partial event runs the full path unchanged,
/// so a COMPLETED message looks exactly as it always did — the only visible
/// difference is that colour and formulas arrive when the message finishes
/// instead of being recomputed on every keystroke of it.
Widget _markdownBody(
BuildContext ctx,
String s, {
bool isThought = false,
bool isPartial = false,
}) {
final isDark = Theme.of(ctx).brightness == Brightness.dark;
final textColor = isThought
? (isDark ? DesignColors.textMuted : DesignColors.textMutedLight)
Expand All @@ -724,7 +749,9 @@ class AgentEventCard extends StatefulWidget {
color: textColor,
);
return MarkdownBody(
data: normalizeMultilineMath(s),
// The multi-line-math preprocessor is a whole-string scan; while partial
// there is nothing for it to feed (the math builders are off), so skip it.
data: isPartial ? s : normalizeMultilineMath(s),
selectable: true,
shrinkWrap: true,
// Tap on `[text](href)` opens the URL in the system browser.
Expand All @@ -734,31 +761,42 @@ class AgentEventCard extends StatefulWidget {
// the default styled inline span — registering one renders the
// visible label twice (once colored-underlined, once tappable).
onTapLink: (text, href, title) => openMarkdownLink(ctx, href),
builders: {
'code': HighlightedCodeBuilder(isDark: isDark),
// KaTeX-style LaTeX math. Two flavors of the same builder so
// the markdown parser can route inline ($...$) and display
// ($$...$$) at different vertical sizes/alignment.
'math': MathBuilder(isDark: isDark, display: false),
'mathblock': MathBuilder(isDark: isDark, display: true),
},
// While partial: no builders at all. An unregistered `code` element falls
// through to the styleSheet's codeblockDecoration/code style — themed,
// but with none of highlight.js's per-chunk tokenization.
builders: isPartial
? const {}
: {
'code': HighlightedCodeBuilder(isDark: isDark),
// KaTeX-style LaTeX math. Two flavors of the same builder so
// the markdown parser can route inline ($...$) and display
// ($$...$$) at different vertical sizes/alignment.
'math': MathBuilder(isDark: isDark, display: false),
'mathblock': MathBuilder(isDark: isDark, display: true),
},
// Custom inline syntaxes only — no BlockSyntax. The preprocessor
// (normalizeMultilineMath) collapses well-formed multi-line
// $$...$$ and \[...\] regions into single-line $$...$$ before
// we get here; unbalanced delimiters fall through to plain text.
// Order matters: $$...$$ must be tried before $...$ or the
// parser will eat the leading $$ as two empty $$s; same for
// \[...\] vs \(...\).
extensionSet: md.ExtensionSet(
md.ExtensionSet.gitHubFlavored.blockSyntaxes,
[
MathBlockInlineSyntax(),
MathInlineSyntax(),
LatexBracketDisplayInlineSyntax(),
LatexBracketInlineSyntax(),
...md.ExtensionSet.gitHubFlavored.inlineSyntaxes,
],
),
//
// While partial the math syntaxes come off too: with no builder to
// render them, a parsed `math` element would have nothing to fall back
// to, so the delimiters stay literal text until the message completes.
extensionSet: isPartial
? md.ExtensionSet.gitHubFlavored
: md.ExtensionSet(
md.ExtensionSet.gitHubFlavored.blockSyntaxes,
[
MathBlockInlineSyntax(),
MathInlineSyntax(),
LatexBracketDisplayInlineSyntax(),
LatexBracketInlineSyntax(),
...md.ExtensionSet.gitHubFlavored.inlineSyntaxes,
],
),
// Keep paragraph and block spacing tight so cards don't balloon.
styleSheet: MarkdownStyleSheet(
p: base,
Expand Down
103 changes: 103 additions & 0 deletions test/widgets/streaming_markdown_partial_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import 'package:flutter/material.dart';
import 'package:flutter_highlight/flutter_highlight.dart';
import 'package:flutter_math_fork/flutter_math.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:termipod/widgets/transcript/event_card.dart';

import '../helpers/test_helpers.dart';

// Transcript P5 B1 — streaming markdown stops re-parsing the world.
//
// A partial carries the FULL accumulated text and replaces its chain entry in
// place (collapseStreamingPartials), so the heavy markdown treatment re-runs
// over the whole message on every chunk: highlight.js re-tokenizes every
// completed fenced block, flutter_math re-lays-out every formula, on the UI
// isolate. Over a long turn that is O(n²).
//
// These pin the gate in BOTH directions. Asserting only that a partial skips
// the work would pass just as well if the builders were removed outright, so
// each case has its completed-message twin proving the final render is
// unchanged — that is the whole contract: colour and formulas arrive when the
// message finishes, and a finished message looks exactly as it always did.

Map<String, dynamic> _textEvent(String text, {bool? partial}) => {
'id': 'e1',
'seq': 1,
'kind': 'text',
'producer': 'agent',
'ts': '2026-07-29T10:00:00Z',
'payload': {
'text': text,
if (partial != null) 'partial': partial,
},
};

const _fenced = 'Here is code:\n\n```dart\nvoid main() {}\n```\n';
const _math = r'Einstein said $E = mc^2$ once.';

/// Matches Text + SelectableText, plain or rich (the card body uses both).
Finder containingText(String s) => find.byWidgetPredicate((w) {
if (w is Text) {
return (w.data ?? w.textSpan?.toPlainText() ?? '').contains(s);
}
if (w is SelectableText) {
return (w.data ?? w.textSpan?.toPlainText() ?? '').contains(s);
}
return false;
});

Future<void> _pump(WidgetTester tester, Map<String, dynamic> event) async {
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: testLocalizationsDelegates,
supportedLocales: testSupportedLocales,
home: Scaffold(
body: SizedBox(width: 420, child: AgentEventCard(event: event)),
),
),
);
await tester.pumpAndSettle();
}

void main() {
testWidgets('a streaming chunk does not run highlight.js over its code',
(tester) async {
await _pump(tester, _textEvent(_fenced, partial: true));
expect(find.byType(HighlightView), findsNothing);
// The block is still there and still readable — it just isn't tokenized.
// `selectable: true` renders through SelectableText.rich, so the content is
// in `textSpan`, not `data` (same predicate transcript_system_card_test
// uses — reading only `data` finds nothing).
expect(containingText('void main'), findsWidgets);
});

testWidgets('the completed message highlights exactly as before',
(tester) async {
await _pump(tester, _textEvent(_fenced));
expect(find.byType(HighlightView), findsOneWidget);
});

testWidgets('an explicit partial:false is treated as complete',
(tester) async {
// The flag is only ever true on a chunk, but a mapper that stamps it false
// on the final frame must not lose the highlighting.
await _pump(tester, _textEvent(_fenced, partial: false));
expect(find.byType(HighlightView), findsOneWidget);
});

testWidgets('a streaming chunk does not lay out math', (tester) async {
await _pump(tester, _textEvent(_math, partial: true));
expect(find.byType(Math), findsNothing);
});

testWidgets('the completed message lays out math as before', (tester) async {
await _pump(tester, _textEvent(_math));
expect(find.byType(Math), findsOneWidget);
});

testWidgets('a thought chunk is gated the same way as text', (tester) async {
final ev = _textEvent(_fenced, partial: true)..['kind'] = 'thought';
await _pump(tester, ev);
expect(find.byType(HighlightView), findsNothing);
});
}
Loading