Skip to content

Commit 13d277f

Browse files
committed
fix(mobile): keep prose scans linear and mentions out of code
Find each paragraph's end once and reuse it for later backtick openers, so a long paragraph of unpaired backticks no longer scans quadratically. Run the mention rewrite through mapMarkdownProse so tilde and long fences keep the author's text and a stray backtick stays literal. Agent transcripts now render escapes the same way messages do. Signed-off-by: Tom Brow <[email protected]>
1 parent c00dcc0 commit 13d277f

6 files changed

Lines changed: 106 additions & 37 deletions

File tree

‎mobile/lib/features/channels/agent_activity/transcript_item_widget.dart‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import 'package:gpt_markdown/gpt_markdown.dart';
66
import 'package:buzz/shared/theme/buzz_icons.dart';
77

88
import '../../../shared/theme/theme.dart';
9+
import '../message_content/markdown_escapes.dart';
910
import 'observer_models.dart';
1011

1112
/// Renders a single [TranscriptItem] in the agent activity transcript.
@@ -68,14 +69,15 @@ class _MessageItemWidget extends StatelessWidget {
6869
const SizedBox(height: Grid.half),
6970
if (item.text.isNotEmpty)
7071
GptMarkdown(
71-
item.text,
72+
escapeMarkdownLiterals(item.text),
7273
style: context.textTheme.bodyMedium?.copyWith(
7374
color: context.colors.onSurface,
7475
),
7576
// No link handler here, so an autolinked URL would draw as a
7677
// link and do nothing when tapped. Transcript URLs stay text,
7778
// as they were before gpt_markdown started autolinking.
7879
autolink: false,
80+
inlinePatterns: _transcriptInlinePatterns,
7981
),
8082
],
8183
),
@@ -143,12 +145,13 @@ class _ThoughtItemWidget extends HookWidget {
143145
if (expanded.value && item.text.isNotEmpty) ...[
144146
const SizedBox(height: Grid.half),
145147
GptMarkdown(
146-
item.text,
148+
escapeMarkdownLiterals(item.text),
147149
style: context.textTheme.bodySmall?.copyWith(
148150
color: context.colors.onSurfaceVariant,
149151
),
150152
// As above: no link handler on this surface either.
151153
autolink: false,
154+
inlinePatterns: _transcriptInlinePatterns,
152155
),
153156
],
154157
],
@@ -490,3 +493,7 @@ class _CodeBlock extends StatelessWidget {
490493
);
491494
}
492495
}
496+
497+
// Escapes read the same here as in messages: `\(` stays a parenthesis rather
498+
// than opening a formula, and an escaped sigil draws as itself.
499+
final _transcriptInlinePatterns = [escapedSigilPattern];

‎mobile/lib/features/channels/message_content.dart‎

Lines changed: 13 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -370,29 +370,20 @@ class MessageContent extends HookConsumerWidget {
370370
final finalContent = useMemoized(() {
371371
// Replace spaces with non-breaking spaces inside known mention names
372372
// so _MentionMd's pattern matches multi-word names as one token, in
373-
// the bound name's case.
374-
// Skip content inside backticks to avoid altering inline code.
375-
final mentionParts = markdownContent.split('`');
376-
final mentionBuf = StringBuffer();
377-
for (var i = 0; i < mentionParts.length; i++) {
378-
if (i.isOdd) {
379-
mentionBuf.write('`${mentionParts[i]}`');
380-
} else {
381-
var segment = mentionParts[i];
382-
for (final range in mentionOccurrences(
383-
segment,
384-
mentionBindings.keys,
385-
).reversed) {
386-
segment = segment.replaceRange(
387-
range.start,
388-
range.end,
389-
'@${_markdownMentionName(range.label)}',
390-
);
391-
}
392-
mentionBuf.write(segment);
373+
// the bound name's case. Code, inline or fenced, is left as written.
374+
return mapMarkdownProse(markdownContent, (segment) {
375+
for (final range in mentionOccurrences(
376+
segment,
377+
mentionBindings.keys,
378+
).reversed) {
379+
segment = segment.replaceRange(
380+
range.start,
381+
range.end,
382+
'@${_markdownMentionName(range.label)}',
383+
);
393384
}
394-
}
395-
return mentionBuf.toString();
385+
return segment;
386+
});
396387
}, [markdownContent, mentionPresentationKey]);
397388

398389
final inlinePatterns = _useMessageInlinePatterns(

‎mobile/lib/features/channels/message_content/link_normalizer.dart‎

Lines changed: 30 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,11 @@ String _mapMarkdownProseAt(
107107
var fenceDelimiterLength = 0;
108108
var fenceChar = '';
109109
var fenceQuoteDepth = 0;
110+
// The paragraph end found for the last unpaired opener, reused while later
111+
// openers at the same quote depth sit before it, so a long paragraph is
112+
// walked once rather than once per opener.
113+
var paragraphEnd = -1;
114+
var paragraphDepth = -1;
110115

111116
while (offset < content.length) {
112117
// A fence opened inside a quote ends with that quote, closed or not.
@@ -162,7 +167,17 @@ String _mapMarkdownProseAt(
162167
continue;
163168
} else if (_hasInlineCloserOnLine(content, run.end, runLength) ||
164169
(!_isOpeningFence(content, run.start, runLength) &&
165-
_hasInlineCloser(content, run.end, runLength))) {
170+
_hasInlineCloser(content, run.end, runLength, () {
171+
final depth = _lineQuoteDepth(
172+
content,
173+
content.lastIndexOf('\n', run.start) + 1,
174+
);
175+
if (run.end >= paragraphEnd || depth != paragraphDepth) {
176+
paragraphEnd = _paragraphEnd(content, run.end, depth);
177+
paragraphDepth = depth;
178+
}
179+
return paragraphEnd;
180+
}))) {
166181
buffer.write(
167182
transform(content.substring(proseStart, run.start), proseStart),
168183
);
@@ -268,24 +283,26 @@ bool _hasInlineCloserOnLine(String content, int start, int delimiterLength) {
268283

269284
/// Whether a closing run follows before the paragraph ends: a code span
270285
/// cannot continue past a blank line, a list item, heading, fence or a deeper
271-
/// block quote.
272-
bool _hasInlineCloser(String content, int start, int delimiterLength) {
273-
final end = _paragraphEnd(content, start);
286+
/// block quote. [paragraphEnd] is asked only when no closer is near.
287+
bool _hasInlineCloser(
288+
String content,
289+
int start,
290+
int delimiterLength,
291+
int Function() paragraphEnd,
292+
) {
293+
int? end;
274294
for (final run in _backtickRunPattern.allMatches(content, start)) {
275-
if (run.start >= end) return false;
295+
if (run.start >= (end ??= paragraphEnd())) return false;
276296
if (run.end - run.start == delimiterLength) return true;
277297
}
278298
return false;
279299
}
280300

281-
int _paragraphEnd(String content, int start) {
282-
// A block quote can interrupt a paragraph, so a line opening a deeper quote
283-
// than the paragraph's own line ends it. Equal or shallower markers continue
284-
// it, as in a multi-line code span inside a quote.
285-
final openerDepth = _lineQuoteDepth(
286-
content,
287-
start == 0 ? 0 : content.lastIndexOf('\n', start - 1) + 1,
288-
);
301+
/// Where the paragraph containing [start] ends, for a line at quote depth
302+
/// [openerDepth]. A block quote can interrupt a paragraph, so a line opening a
303+
/// deeper quote ends it. Equal or shallower markers continue it, as in a
304+
/// multi-line code span inside a quote.
305+
int _paragraphEnd(String content, int start, int openerDepth) {
289306
var newline = content.indexOf('\n', start);
290307
while (newline >= 0) {
291308
if (_lineQuoteDepth(content, newline + 1) > openerDepth ||

‎mobile/test/features/channels/agent_activity/transcript_item_widget_test.dart‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,4 +73,28 @@ void main() {
7373
);
7474
expect(_rendersLink(tester), isFalse);
7575
});
76+
77+
testWidgets('reads escapes as literal characters', (tester) async {
78+
await tester.pumpWidget(
79+
_testable(
80+
TranscriptItemWidget(
81+
item: MessageItem(
82+
id: 'm2',
83+
role: 'assistant',
84+
title: 'Assistant',
85+
text: r'Group as \(a + b\), then ping \@alice.',
86+
timestamp: '2026-08-29T09:00:00Z',
87+
),
88+
),
89+
),
90+
);
91+
92+
expect(
93+
find.textContaining(
94+
'Group as (a + b), then ping @alice.',
95+
findRichText: true,
96+
),
97+
findsOneWidget,
98+
);
99+
});
76100
}

‎mobile/test/features/channels/message_content/link_normalizer_test.dart‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,14 @@ void main() {
5555
expect(timer.elapsedMilliseconds, lessThan(500));
5656
});
5757

58+
test('a long paragraph of unpaired backticks takes linear time', () {
59+
// Walking to the paragraph end for every opener took seconds at 64 KB.
60+
final body = 'a `\n` b' * (64 * 1024 ~/ 7);
61+
final timer = Stopwatch()..start();
62+
expect(mapMarkdownProse(body, (prose) => prose), body);
63+
expect(timer.elapsedMilliseconds, lessThan(500));
64+
});
65+
5866
test('keeps punctuation and open Markdown delimiters outside links', () {
5967
expect(
6068
normalizeBareLinks('**open $url**. and **_${url}_**!'),

‎mobile/test/features/channels/message_content_test.dart‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3194,6 +3194,28 @@ Photos
31943194
expect(_allRichText(tester), isNot(contains('Lopez Lopez')));
31953195
});
31963196

3197+
testWidgets('leaves mentions in code and stray backticks as written', (
3198+
tester,
3199+
) async {
3200+
await tester.pumpWidget(
3201+
_testable(
3202+
const MessageContent(
3203+
content:
3204+
'~~~\n@Kenny Lopez ran it\n~~~\n\n'
3205+
'stray ` tick then **bold** and @Kenny Lopez',
3206+
mentionNames: {'pk1': 'Kenny Lopez'},
3207+
),
3208+
),
3209+
);
3210+
3211+
final text = _allRichText(tester);
3212+
// The fence keeps the author's space, not the chip's NBSP.
3213+
expect(text, contains('@Kenny Lopez ran it'));
3214+
expect(text, contains('stray ` tick then bold and '));
3215+
// Only the prose mention becomes a chip.
3216+
expect(find.text('Kenny Lopez'), findsOneWidget);
3217+
});
3218+
31973219
testWidgets('renders unknown @mention as-is', (tester) async {
31983220
await tester.pumpWidget(
31993221
_testable(

0 commit comments

Comments
 (0)