Chat: find in chat (Ctrl+F / Cmd+F)

A find bar over the transcript: query, Match case, n of N (counted from
the newest), Enter for an older match and Shift+Enter for a newer one.
Matches are painted over the rendered text, code blocks included, without
restyling it; the current match is scrolled into view. Matches in history
not loaded yet come from the server's chat:<id>-scoped search and are
reached by loading older pages. Esc closes and returns to the composer.
The key is the pane's, so a focused terminal keeps Ctrl+F. Fixture answers
scoped searches for captures; cheatsheet lists the key. The scoped search
matches the query as typed, spaces included, like the client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 00:41:39 +00:00
parent 32c9c6b1df
commit 8bd219e636
14 changed files with 1581 additions and 126 deletions
@@ -0,0 +1,140 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'chat_find_controller.dart';
/// The chat's find bar, like the terminal's: the query field, the match
/// count, Match case, the older/newer and close buttons. Matches count from
/// the newest; Enter moves to an older match and Shift+Enter to a newer one;
/// Esc closes. [onStep] moves and reveals; [onClose] closes the bar and
/// returns the keyboard to the composer.
class ChatFindBar extends StatefulWidget {
const ChatFindBar({
super.key,
required this.find,
required this.focus,
required this.onStep,
required this.onClose,
});
final ChatFindController find;
final FocusNode focus;
final ValueChanged<int> onStep;
final VoidCallback onClose;
@override
State<ChatFindBar> createState() => _ChatFindBarState();
}
class _ChatFindBarState extends State<ChatFindBar> {
late final TextEditingController _text = TextEditingController(
text: widget.find.query,
);
@override
void dispose() {
_text.dispose();
super.dispose();
}
KeyEventResult _key(FocusNode node, KeyEvent event) {
if (event is KeyUpEvent) return KeyEventResult.ignored;
if (event.logicalKey == LogicalKeyboardKey.escape) {
widget.onClose();
return KeyEventResult.handled;
}
if (event.logicalKey == LogicalKeyboardKey.enter ||
event.logicalKey == LogicalKeyboardKey.numpadEnter) {
widget.onStep(HardwareKeyboard.instance.isShiftPressed ? -1 : 1);
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
String _count(ChatFindController find) {
if (find.query.isEmpty) return '';
if (find.count == 0) return find.capped ? 'Searching…' : 'No results';
final total = find.capped ? '${find.count}+' : '${find.count}';
return '${find.index + 1} of $total';
}
@override
Widget build(BuildContext context) {
final find = widget.find;
final scheme = Theme.of(context).colorScheme;
// The buttons count as part of the field, so clicking one keeps the
// keyboard in it (Enter steps on from there).
return TextFieldTapRegion(
child: Material(
elevation: 3,
color: scheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(8),
child: Padding(
padding: const EdgeInsetsDirectional.only(start: 12, end: 4),
child: ListenableBuilder(
listenable: find,
builder: (context, _) => Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 240),
child: Focus(
onKeyEvent: _key,
skipTraversal: true,
child: TextField(
key: const ValueKey('chat-find-field'),
controller: _text,
focusNode: widget.focus,
autofocus: true,
decoration: const InputDecoration(
hintText: 'Find in chat',
border: InputBorder.none,
isDense: true,
),
onChanged: (value) => find.query = value,
),
),
),
),
Semantics(
liveRegion: true,
child: Text(
_count(find),
key: const ValueKey('chat-find-count'),
style: Theme.of(context).textTheme.bodySmall,
),
),
IconButton(
key: const ValueKey('chat-find-case'),
tooltip: 'Match case',
isSelected: find.caseSensitive,
onPressed: find.toggleCase,
icon: const Text('Aa'),
),
IconButton(
key: const ValueKey('chat-find-older'),
tooltip: 'Older match (Enter)',
onPressed: find.count == 0 ? null : () => widget.onStep(1),
icon: const Icon(Icons.keyboard_arrow_up),
),
IconButton(
key: const ValueKey('chat-find-newer'),
tooltip: 'Newer match (Shift+Enter)',
onPressed: find.count == 0 ? null : () => widget.onStep(-1),
icon: const Icon(Icons.keyboard_arrow_down),
),
IconButton(
key: const ValueKey('chat-find-close'),
tooltip: 'Close find (Esc)',
onPressed: widget.onClose,
icon: const Icon(Icons.close),
),
],
),
),
),
),
);
}
}
@@ -0,0 +1,261 @@
import 'dart:async';
import 'package:flutter/widgets.dart';
import '../../../core/api_gateway.dart';
import '../domain/chat_find.dart';
/// A highlighted range in one rendered text, and whether it is the current
/// match.
typedef ChatFindHighlight = ({int start, int end, bool current});
/// Find in one chat: the query, whether case matters, the matches in the
/// loaded transcript and, through the server's scoped search, those in older
/// history not loaded yet.
///
/// Matches are numbered from the newest: "1 of N" is the newest match and
/// stepping on (Enter) goes back in time, so finding never starts by jumping
/// to the start of a long history. The loaded matches come first; the
/// server's hits in unloaded messages, all older, follow in its order, so a
/// match keeps its number when the page holding it loads.
class ChatFindController extends ChangeNotifier {
ChatFindController({
required this.gateway,
required this.sessionId,
required this.history,
this.debounce = const Duration(milliseconds: 250),
});
final ApiGateway gateway;
final String sessionId;
final Duration debounce;
/// Whether the transcript has older history it has not loaded, and the
/// cursor its next older page would be read with.
final ({bool hasMore, String cursor}) Function() history;
String _query = '';
bool _caseSensitive = false;
List<ChatFindUnit> _units = const [];
Set<String> _loadedIds = const {};
/// Loaded matches, newest first.
List<ChatFindMatch> _local = const [];
List<ChatFindRemoteHit> _remoteAll = const [];
List<ChatFindRemoteHit> _remote = const [];
bool _remoteMore = false;
bool _searching = false;
int _index = -1;
ChatFindMatch? _currentLocal;
int _generation = 0;
Timer? _timer;
Map<String, Map<String, List<ChatFindHighlight>>> _byRow = const {};
bool _disposed = false;
String get query => _query;
bool get caseSensitive => _caseSensitive;
/// How many matches are known: loaded ones and the server's in history
/// that is not loaded.
int get count => _local.length + _remote.length;
/// Whether there may be more matches than [count] (the server's search
/// stopped at its cap, or is still running).
bool get capped =>
_remoteMore || _searching || _local.length >= chatFindLocalCap;
/// The current match's number from the newest (0-based), -1 with none.
int get index => _index;
/// The current match when it is in the loaded transcript.
ChatFindMatch? get current =>
_index >= 0 && _index < _local.length ? _local[_index] : null;
/// The current match when it is in history not loaded yet.
ChatFindRemoteHit? get currentRemote {
final at = _index - _local.length;
return at >= 0 && at < _remote.length ? _remote[at] : null;
}
/// Bumped whenever the current match moves, so the view reveals it once.
int get revealToken => _revealToken;
int _revealToken = 0;
/// The highlights in [text] of row [rowKey].
List<ChatFindHighlight> highlightsFor(String rowKey, String text) =>
_byRow[rowKey]?[text] ?? const [];
set query(String value) {
if (value == _query) return;
_query = value;
_restart();
}
void toggleCase() {
_caseSensitive = !_caseSensitive;
_restart();
}
/// Moves to an older match ([step] 1) or a newer one (-1), wrapping.
void step(int step) {
if (count == 0) return;
_select((_index + step) % count);
}
/// Takes the transcript as it is now. The current loaded match stays
/// current; otherwise the current number does. Listeners hear of a change
/// after this frame, since the transcript calls this while it builds.
void updateTranscript(
List<JsonMap> rows,
List<String> keys,
Iterable<String> loadedMessageIds,
) {
final units = chatFindUnits(rows, keys);
_loadedIds = {...loadedMessageIds};
final sameUnits = _sameUnits(units);
_units = units;
if (sameUnits && _remote.length == _filterRemote().length) return;
_recompute(keepCurrent: true);
WidgetsBinding.instance.addPostFrameCallback((_) => _notify());
}
bool _sameUnits(List<ChatFindUnit> units) {
if (units.length != _units.length) return false;
for (var i = 0; i < units.length; i++) {
if (units[i].rowKey != _units[i].rowKey ||
!identical(units[i].text, _units[i].text) &&
units[i].text != _units[i].text) {
return false;
}
}
return true;
}
List<ChatFindRemoteHit> _filterRemote() => [
for (final hit in _remoteAll)
if (!_loadedIds.contains(hit.messageId)) hit,
];
void _restart() {
_generation++;
_timer?.cancel();
_remoteAll = const [];
_remote = const [];
_remoteMore = false;
_searching = false;
_currentLocal = null;
_index = -1;
_recompute(keepCurrent: false);
_searchHistory();
_notify();
}
void _recompute({required bool keepCurrent}) {
final previous = keepCurrent ? _currentLocal : null;
final previousIndex = _index;
_local = _query.isEmpty
? const []
: chatFindMatches(
_units,
_query,
caseSensitive: _caseSensitive,
).reversed.toList();
_remote = _filterRemote();
var index = -1;
if (previous != null) {
index = _local.indexWhere(previous.sameAs);
}
if (index < 0 && keepCurrent && previousIndex >= 0 && count > 0) {
index = previousIndex.clamp(0, count - 1);
}
if (index < 0 && count > 0) index = 0;
_setIndex(index, reveal: !keepCurrent || index != previousIndex);
_rebuildHighlights();
}
void _select(int index) {
_setIndex(index, reveal: true);
_rebuildHighlights();
_notify();
}
void _setIndex(int index, {required bool reveal}) {
_index = index;
_currentLocal = current;
if (reveal && index >= 0) _revealToken++;
}
void _rebuildHighlights() {
final byRow = <String, Map<String, List<ChatFindHighlight>>>{};
final now = current;
for (final match in _local) {
byRow
.putIfAbsent(match.rowKey, () => {})
.putIfAbsent(match.unit.text, () => [])
.add((
start: match.start,
end: match.end,
current: identical(match, now),
));
}
_byRow = byRow;
}
/// Asks the server for matches in the history before the transcript's
/// loaded pages, after a short pause in typing. Without older history
/// there is nothing to ask.
void _searchHistory() {
final older = history();
if (_query.isEmpty || !older.hasMore) return;
final generation = _generation;
_searching = true;
_timer = Timer(debounce, () {
unawaited(_fetch(generation, '0|${older.cursor}'));
});
}
Future<void> _fetch(int generation, String cursor) async {
var next = cursor;
final hits = <ChatFindRemoteHit>[];
try {
while (true) {
final reply = await gateway.call('search', {
'search': {
'query': _query,
'kind': 'chat',
'scope': 'chat:$sessionId',
'cursor': next,
'case_sensitive': _caseSensitive,
'limit': 200,
},
});
if (_disposed || generation != _generation) return;
hits.addAll(ChatFindRemoteHit.fromReply(reply));
final results = reply['search_results'];
next = results is Map ? '${results['next_cursor'] ?? ''}' : '';
_remoteAll = List.unmodifiable(hits);
_remoteMore = next.isNotEmpty && hits.length >= chatFindRemoteCap;
_recompute(keepCurrent: true);
_notify();
if (next.isEmpty || hits.length >= chatFindRemoteCap) break;
}
} catch (_) {
// An older server without scoped search, or a dropped socket: the
// loaded transcript's matches still stand.
if (_disposed || generation != _generation) return;
}
_searching = false;
_notify();
}
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
_timer?.cancel();
super.dispose();
}
}
@@ -0,0 +1,221 @@
import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/input/keyboard_owner.dart';
import '../shell/chat_shell_terminal_find_bar.dart';
import '../ui/transcript/chat_find_highlight.dart';
import 'chat_find_bar.dart';
import 'chat_find_controller.dart';
import 'chat_thread_controller.dart';
import 'chat_thread_view.dart';
import 'composer_focus_request.dart';
/// Whether [event] is find's key: Cmd+F on Apple platforms, Ctrl+F
/// elsewhere, without Shift or Alt.
bool chatFindShortcut(KeyEvent event, HardwareKeyboard keyboard) {
if (event is! KeyDownEvent || event.logicalKey != LogicalKeyboardKey.keyF) {
return false;
}
final apple =
defaultTargetPlatform == TargetPlatform.macOS ||
defaultTargetPlatform == TargetPlatform.iOS;
final ctrl = keyboard.isControlPressed;
final meta = keyboard.isMetaPressed;
if (keyboard.isAltPressed || keyboard.isShiftPressed) return false;
return apple ? meta && !ctrl : ctrl && !meta;
}
/// Find in one open chat: Ctrl+F (Cmd+F) opens the bar over the transcript,
/// matches are highlighted, the current one is scrolled into view (reading
/// older pages until it is loaded), and Esc closes the bar and returns the
/// keyboard to the composer.
mixin ChatFindHost on State<ChatThreadView> {
ScrollController get findScroll;
ChatThreadController get findThread;
/// Stops the transcript following its end while find moves it.
void findReleaseFollow();
/// Lets the transcript decide again whether it follows its end.
void findSettleFollow();
final findTargets = ChatFindTargets();
final FocusNode _findFocus = FocusNode(debugLabel: 'chat-find');
ChatFindController? _find;
int _revealed = 0;
Map<String, int> _rowIndex = const {};
ChatFindController? get find => _find;
void disposeFind() {
_find?.dispose();
_findFocus.dispose();
}
/// The pane's key handler: find's shortcut from anywhere in this chat,
/// except a terminal (where Ctrl+F is the shell's) and its own find bar.
KeyEventResult findKey(FocusNode node, KeyEvent event) {
if (!chatFindShortcut(event, HardwareKeyboard.instance)) {
return KeyEventResult.ignored;
}
if (primaryFocusIsTypingSurface()) return KeyEventResult.ignored;
final focused = FocusManager.instance.primaryFocus?.context;
if (focused?.findAncestorWidgetOfExactType<ChatShellTerminalFindBar>() !=
null) {
return KeyEventResult.ignored;
}
openFind();
return KeyEventResult.handled;
}
/// Opens the find bar, or focuses its field when it is open.
void openFind() {
if (_find == null) {
final find = ChatFindController(
gateway: widget.gateway,
sessionId: widget.sessionId,
history: () => (hasMore: findThread.hasMore, cursor: findThread.cursor),
)..addListener(_findChanged);
setState(() => _find = find);
}
// The field's autofocus would not take the keyboard from the composer,
// which holds it in the same scope.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && _find != null) _findFocus.requestFocus();
});
}
void closeFind() {
final find = _find;
if (find == null) return;
setState(() => _find = null);
find.dispose();
findSettleFollow();
ChatComposerFocusScope.maybeOf(context)?.requests.request(widget.sessionId);
}
void _findChanged() {
final find = _find;
if (find == null || find.revealToken == _revealed) return;
_revealed = find.revealToken;
unawaited(_reveal(find, _revealed));
}
/// Hands the transcript as built to an open find.
void findTranscript(List<JsonMap> rows, List<String> keys) {
final find = _find;
if (find == null) return;
_rowIndex = {for (var i = 0; i < keys.length; i++) keys[i]: i};
find.updateTranscript(rows, keys, [
for (final message in findThread.messages)
if ('${message['id'] ?? ''}'.isNotEmpty) '${message['id']}',
]);
}
/// [transcript] inside find's scope.
Widget findScope(Widget transcript) =>
ChatFindScope(controller: _find, targets: findTargets, child: transcript);
/// The bar over the transcript's top end while find is open.
Widget? findBar({required double top, required double end}) {
final find = _find;
if (find == null) return null;
return PositionedDirectional(
top: top,
start: 8,
end: end,
child: Align(
alignment: AlignmentDirectional.topEnd,
child: ChatFindBar(
find: find,
focus: _findFocus,
onStep: find.step,
onClose: closeFind,
),
),
);
}
/// Brings find's current match into view: reads older pages until it is
/// loaded, scrolls toward its row until the row is built, then centres the
/// match. A newer move ([token]) abandons this one.
Future<void> _reveal(ChatFindController find, int token) async {
bool stale() => !mounted || _find != find || find.revealToken != token;
findReleaseFollow();
for (var attempt = 0; attempt < 120; attempt++) {
if (stale()) return;
if (find.currentRemote != null) {
if (!findThread.hasMore) return;
if (!findThread.loading) await findThread.loadOlder();
await WidgetsBinding.instance.endOfFrame;
continue;
}
final match = find.current;
if (match == null || !findScroll.hasClients) return;
final rects = findTargets.textFor(match.rowKey, match.unit.text);
final row = findTargets.rows[match.rowKey];
if (rects != null && row != null && row.mounted) {
if (_centre(row, rects, match.start, match.end)) break;
} else if (!_stepToward(match.unit.rowIndex)) {
return;
}
await WidgetsBinding.instance.endOfFrame;
}
if (!stale()) findSettleFollow();
}
/// Scrolls so the match is in the middle of the viewport when it is not
/// already comfortably in view; true once it is placed.
bool _centre(BuildContext row, ChatFindRects rects, int start, int end) {
final object = row.findRenderObject();
if (object == null || !object.attached) return false;
final viewport = RenderAbstractViewport.maybeOf(object);
if (viewport is! RenderBox || !(viewport as RenderBox).hasSize) {
return false;
}
final box = viewport as RenderBox;
final boxes = rects(start, end, box);
if (boxes.isEmpty) {
unawaited(Scrollable.ensureVisible(row, alignment: 0.5));
return false;
}
final match = boxes.reduce((a, b) => a.expandToInclude(b));
final height = box.size.height;
final margin = math.min(64.0, height / 4);
if (match.top >= margin && match.bottom <= height - margin) return true;
final position = findScroll.position;
final target = (position.pixels + match.center.dy - height / 2).clamp(
position.minScrollExtent,
position.maxScrollExtent,
);
if ((target - position.pixels).abs() < 1) return true;
position.jumpTo(target);
return false;
}
/// Moves the transcript a screen toward row [index] when it is not built;
/// false when it cannot move further.
bool _stepToward(int index) {
final built = [
for (final entry in findTargets.rows.entries)
if (entry.value.mounted && _rowIndex[entry.key] != null)
_rowIndex[entry.key]!,
];
final position = findScroll.position;
final older = built.isEmpty || index < built.reduce(math.min);
final distance = position.viewportDimension * 0.8;
final target = (position.pixels + (older ? -distance : distance)).clamp(
position.minScrollExtent,
position.maxScrollExtent,
);
if ((target - position.pixels).abs() < 1) return false;
position.jumpTo(target);
return true;
}
}
@@ -27,6 +27,7 @@ import '../ui/sessions/chat_color_picker.dart';
import '../ui/sessions/session_actions.dart';
import '../ui/sessions/session_row_content.dart';
import '../ui/sessions/chat_adaptive.dart';
import '../ui/transcript/chat_find_highlight.dart';
import '../ui/transcript/chat_markdown_view.dart';
import '../ui/transcript/chat_message_bubble.dart';
import '../ui/transcript/chat_message_view.dart';
@@ -50,6 +51,7 @@ import 'chat_session_section.dart';
import 'chat_background_tasks.dart';
import 'chat_command_actions.dart';
import 'chat_composer_bar.dart';
import 'chat_find_host.dart';
import 'chat_composer_controller.dart';
import 'chat_escape_stop.dart';
import 'chat_delivery_indicator.dart';
@@ -241,7 +243,26 @@ class ChatThreadView extends StatefulWidget {
State<ChatThreadView> createState() => _ChatThreadViewState();
}
class _ChatThreadViewState extends State<ChatThreadView> {
class _ChatThreadViewState extends State<ChatThreadView> with ChatFindHost {
@override
ScrollController get findScroll => _scroll;
@override
ChatThreadController get findThread => _controller;
@override
void findReleaseFollow() {
if (!_following) return;
setState(() {
_following = false;
_newestAtRelease = _newestMessageId();
});
}
@override
void findSettleFollow() {
if (_scroll.hasClients) _updateFollow(_scroll.position);
}
late ChatThreadController _controller = _attach();
late ChatComposerController _composer = _attachComposer();
@@ -831,6 +852,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
_saveTranscript(widget.transcripts, widget.sessionId);
widget.paneCommands?.removeListener(_takeCommands);
widget.paneCommands?.setFinished(widget.sessionId, false);
disposeFind();
_scroll.dispose();
widget.onComposerDisposed?.call(_composer);
_composer.dispose();
@@ -1247,6 +1269,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
// across paging and streaming.
final keys = _rowKeys.forRows(rows);
final split = _splitFor(rows);
findTranscript(rows, keys);
final initialLoad = !_controller.loaded && _controller.loading;
final historyNotice = _noticeOf(
notices,
@@ -1344,32 +1367,35 @@ class _ChatThreadViewState extends State<ChatThreadView> {
// Slivers mount only visible rows. Defer constructing
// their chips and checking cached widgets until then,
// rather than visiting the entire history per delta.
child: ChatDayDivided(
day: days[index],
// An answer row starts at the gutter; the divider
// keeps to the reading column.
inset: rows[index]['kind'] == 'assistant'
? gutter
: 0,
child: ChatTranscriptRowSelection(
child: ChatCopyGutter(
width: rows[index]['kind'] == 'assistant'
? gutter
: 0,
child: Builder(
builder: (_) => _entering(
rows[index],
_transcriptRow(
child: ChatFindRow(
rowKey: keys[index],
child: ChatDayDivided(
day: days[index],
// An answer row starts at the gutter; the divider
// keeps to the reading column.
inset: rows[index]['kind'] == 'assistant'
? gutter
: 0,
child: ChatTranscriptRowSelection(
child: ChatCopyGutter(
width: rows[index]['kind'] == 'assistant'
? gutter
: 0,
child: Builder(
builder: (_) => _entering(
rows[index],
keys[index],
onDismissCompaction:
compactionNotice != null &&
chatNoticeActivityCondition(
rows[index],
) ==
compactionNotice.condition
? () => _dismiss(compactionNotice)
: null,
_transcriptRow(
rows[index],
keys[index],
onDismissCompaction:
compactionNotice != null &&
chatNoticeActivityCondition(
rows[index],
) ==
compactionNotice.condition
? () => _dismiss(compactionNotice)
: null,
),
),
),
),
@@ -1385,108 +1411,114 @@ class _ChatThreadViewState extends State<ChatThreadView> {
// the viewport itself ends above the composer.
// Bottom-anchored at the split row, the newest rows are
// laid out first and older ones only when scrolled to.
ChatTranscriptSelectionArea(
child: ChatTranscriptScrollView(
key: ValueKey<String>(
'chat-thread-${widget.sessionId}',
),
controller: _scroll,
splitAfter: split < 0
? null
: ValueKey<String>(keys[split]),
padding: EdgeInsets.fromLTRB(
side - gutter,
media.top + 8,
side,
8,
),
children: chatCopyGutterInset(gutter, transcript, [
if (initialLoad)
Padding(
key: const Key('chat-thread-loading'),
padding: const EdgeInsets.all(16),
child: const Center(child: AppSpinner()),
),
if (_controller.hasMore)
Padding(
key: const Key('chat-load-older'),
padding: const EdgeInsets.symmetric(
horizontal: 16,
findScope(
ChatTranscriptSelectionArea(
child: ChatTranscriptScrollView(
key: ValueKey<String>(
'chat-thread-${widget.sessionId}',
),
controller: _scroll,
splitAfter: split < 0
? null
: ValueKey<String>(keys[split]),
padding: EdgeInsets.fromLTRB(
side - gutter,
media.top + 8,
side,
8,
),
children: chatCopyGutterInset(gutter, transcript, [
if (initialLoad)
Padding(
key: const Key('chat-thread-loading'),
padding: const EdgeInsets.all(16),
child: const Center(child: AppSpinner()),
),
child: Align(
alignment: AlignmentDirectional.centerStart,
child: TextButton(
onPressed: _controller.loading
? null
: _controller.loadOlder,
child: const Text('Load older'),
if (_controller.hasMore)
Padding(
key: const Key('chat-load-older'),
padding: const EdgeInsets.symmetric(
horizontal: 16,
),
child: Align(
alignment:
AlignmentDirectional.centerStart,
child: TextButton(
onPressed: _controller.loading
? null
: _controller.loadOlder,
child: const Text('Load older'),
),
),
),
),
if (historyNotice != null)
_ChatNoticeLine(
key: const Key('chat-history-error'),
notice: historyNotice,
onDismiss: _dismiss,
onRetry: _controller.load,
),
if (liveNotice != null)
_ChatNoticeLine(
key: const Key('chat-live-error'),
notice: liveNotice,
onDismiss: _dismiss,
onRetry: _controller.resync,
),
if (_controller.loaded &&
allRows.isEmpty &&
allNotices.isEmpty &&
_commandNotices.isEmpty &&
_controller.error == null)
const Padding(
key: Key('chat-thread-empty'),
padding: EdgeInsets.all(16),
child: Text('No messages in this chat yet.'),
),
...transcript,
// Messages the server holds queued (one sent before
// a reload, or from another device) follow the
// transcript: none has reached the harness yet.
for (final prompt
in _controller.queuedOutsideTranscript)
Padding(
key: ValueKey<String>(
'chat-queued-${prompt['operation_id']}',
if (historyNotice != null)
_ChatNoticeLine(
key: const Key('chat-history-error'),
notice: historyNotice,
onDismiss: _dismiss,
onRetry: _controller.load,
),
padding: const EdgeInsets.symmetric(
horizontal: 16,
if (liveNotice != null)
_ChatNoticeLine(
key: const Key('chat-live-error'),
notice: liveNotice,
onDismiss: _dismiss,
onRetry: _controller.resync,
),
child: _queuedRow(prompt),
),
// Messages the server has not accepted follow the
// transcript until they are retried or edited.
for (final send in _composer.deliveries.unsent)
Padding(
key: ValueKey<String>(
'chat-unsent-${send.operationId}',
if (_controller.loaded &&
allRows.isEmpty &&
allNotices.isEmpty &&
_commandNotices.isEmpty &&
_controller.error == null)
const Padding(
key: Key('chat-thread-empty'),
padding: EdgeInsets.all(16),
child: Text(
'No messages in this chat yet.',
),
),
padding: const EdgeInsets.symmetric(
horizontal: 16,
...transcript,
// Messages the server holds queued (one sent before
// a reload, or from another device) follow the
// transcript: none has reached the harness yet.
for (final prompt
in _controller.queuedOutsideTranscript)
Padding(
key: ValueKey<String>(
'chat-queued-${prompt['operation_id']}',
),
padding: const EdgeInsets.symmetric(
horizontal: 16,
),
child: _queuedRow(prompt),
),
child: _unsentRow(send),
),
// The conversation's own command lines sit after the
// turns, as on the web; they are never bubbles.
for (final notice in _commandNotices)
_ChatNoticeLine(
key: ValueKey<String>(
'chat-command-notice-${notice.condition}',
// Messages the server has not accepted follow the
// transcript until they are retried or edited.
for (final send in _composer.deliveries.unsent)
Padding(
key: ValueKey<String>(
'chat-unsent-${send.operationId}',
),
padding: const EdgeInsets.symmetric(
horizontal: 16,
),
child: _unsentRow(send),
),
notice: notice,
onDismiss: _dismiss,
),
]),
// The conversation's own command lines sit after the
// turns, as on the web; they are never bubbles.
for (final notice in _commandNotices)
_ChatNoticeLine(
key: ValueKey<String>(
'chat-command-notice-${notice.condition}',
),
notice: notice,
onDismiss: _dismiss,
),
]),
),
),
),
?findBar(top: media.top + 8, end: side + 8),
if (showJump)
PositionedDirectional(
end: side + 16,
@@ -1511,10 +1543,15 @@ class _ChatThreadViewState extends State<ChatThreadView> {
// scrolls under fixed bars.
// Two Escape presses stop a running turn while the conversation has
// the keyboard; the wheel over the page still scrolls it.
final column = ChatEscapeStop(
running: _controller.running,
onStop: _stopTurn,
child: VerticalWheelForwarder(controller: _scroll, child: page),
final column = Focus(
canRequestFocus: false,
skipTraversal: true,
onKeyEvent: findKey,
child: ChatEscapeStop(
running: _controller.running,
onStop: _stopTurn,
child: VerticalWheelForwarder(controller: _scroll, child: page),
),
);
final wideFiles =
_filesVisible && MediaQuery.sizeOf(context).width >= 700;
+146
View File
@@ -0,0 +1,146 @@
import '../../../core/api_gateway.dart';
/// One piece of transcript text find searches, as the transcript shows it:
/// a user turn's text (its text parts joined by line breaks, as its bubble
/// draws them) or one text part of an answer. [rowKey] is the transcript
/// row's stable key; [text] is exactly the string the row renders.
class ChatFindUnit {
const ChatFindUnit(this.rowIndex, this.rowKey, this.text, this.messageIds);
final int rowIndex;
final String rowKey;
final String text;
/// The stored messages the row holds.
final List<String> messageIds;
}
/// A match's character range in its unit's text.
typedef ChatFindRange = ({int start, int end});
/// One match in the loaded transcript.
class ChatFindMatch {
const ChatFindMatch(this.unit, this.start, this.end, this.ordinal);
final ChatFindUnit unit;
final int start;
final int end;
/// Which occurrence in [unit] this is, from its start.
final int ordinal;
String get rowKey => unit.rowKey;
/// Whether [other] is the same occurrence in the same text.
bool sameAs(ChatFindMatch other) =>
other.rowKey == rowKey &&
other.unit.text == unit.text &&
other.ordinal == ordinal;
}
/// A match the server found in a message the transcript has not loaded yet.
class ChatFindRemoteHit {
const ChatFindRemoteHit(this.messageId, this.part, this.offset);
final String messageId;
final int part;
final int offset;
/// The hits of a scoped chat search reply, newest message first.
static List<ChatFindRemoteHit> fromReply(JsonMap reply) {
final results = reply['search_results'];
final list = results is Map ? results['results'] : null;
if (list is! List) return const [];
return [
for (final result in list)
if (result is Map && result['chat'] is Map)
ChatFindRemoteHit(
'${(result['chat'] as Map)['message_id'] ?? ''}',
_int((result['chat'] as Map)['part']),
_int((result['chat'] as Map)['offset']),
),
];
}
static int _int(Object? value) => value is num ? value.toInt() : 0;
}
/// The text units of transcript [rows] (keyed by [keys]), in display order.
/// Only what reads as conversation is searched: user turns and the text of
/// answers, not activity, cards or notices.
List<ChatFindUnit> chatFindUnits(List<JsonMap> rows, List<String> keys) {
final units = <ChatFindUnit>[];
for (var index = 0; index < rows.length && index < keys.length; index++) {
final row = rows[index];
final kind = row['kind'];
if (kind == 'user') {
final message = row['message'] is Map ? row['message'] as Map : row;
final text = _textParts(message).join('\n');
if (text.trim().isEmpty) continue;
final id = '${row['key'] ?? message['id'] ?? ''}';
units.add(ChatFindUnit(index, keys[index], text, [id]));
} else if (kind == 'assistant') {
final ids = [
for (final id in row['messageIds'] as List? ?? const []) '$id',
];
for (final text in _textParts(row)) {
if (text.trim().isEmpty) continue;
units.add(ChatFindUnit(index, keys[index], text, ids));
}
}
}
return units;
}
List<String> _textParts(Map<dynamic, dynamic> source) {
final parts = source['parts'];
if (parts is! List) return const [];
return [
for (final part in parts)
if (part is Map &&
(part['type'] == null || part['type'] == 'text') &&
part['text'] is String)
part['text'] as String,
];
}
/// The non-overlapping occurrences of [query] in [text].
List<ChatFindRange> chatFindRanges(
String text,
String query, {
required bool caseSensitive,
}) {
if (query.isEmpty || text.length < query.length) return const [];
final pattern = RegExp(RegExp.escape(query), caseSensitive: caseSensitive);
return [
for (final match in pattern.allMatches(text))
(start: match.start, end: match.end),
];
}
/// Every match of [query] in [units], in display order (oldest first).
List<ChatFindMatch> chatFindMatches(
List<ChatFindUnit> units,
String query, {
required bool caseSensitive,
int cap = chatFindLocalCap,
}) {
final matches = <ChatFindMatch>[];
for (final unit in units) {
var ordinal = 0;
for (final range in chatFindRanges(
unit.text,
query,
caseSensitive: caseSensitive,
)) {
matches.add(ChatFindMatch(unit, range.start, range.end, ordinal++));
if (matches.length >= cap) return matches;
}
}
return matches;
}
/// How many matches find counts in the loaded transcript, and in history
/// it has not loaded, before it reports "N+".
const chatFindLocalCap = 2000;
const chatFindRemoteCap = 1000;
@@ -0,0 +1,278 @@
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import '../../conversation/chat_find_controller.dart';
import '../../shell/chat_shell_terminal_theme.dart';
/// The boxes, in [ancestor]'s coordinates, of a character range of a
/// rendered text; empty when it is not laid out.
typedef ChatFindRects =
List<Rect> Function(int start, int end, RenderBox ancestor);
/// Where find's matches are drawn: the open find (null while it is closed)
/// and the rendered texts and rows the transcript has built, so the current
/// match can be scrolled into view.
class ChatFindTargets {
final rows = <String, BuildContext>{};
final texts = <String, Map<String, ChatFindRects>>{};
ChatFindRects? textFor(String rowKey, String text) => texts[rowKey]?[text];
}
class ChatFindScope extends InheritedWidget {
const ChatFindScope({
super.key,
required this.controller,
required this.targets,
required super.child,
});
final ChatFindController? controller;
final ChatFindTargets targets;
static ChatFindScope? maybeOf(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<ChatFindScope>();
@override
bool updateShouldNotify(ChatFindScope oldWidget) =>
controller != oldWidget.controller || targets != oldWidget.targets;
}
/// Marks one transcript row for find: the texts in it highlight their
/// matches under [rowKey], and the row registers itself while built.
class ChatFindRow extends StatefulWidget {
const ChatFindRow({super.key, required this.rowKey, required this.child});
final String rowKey;
final Widget child;
static String? keyOf(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<_ChatFindRowKey>()?.rowKey;
@override
State<ChatFindRow> createState() => _ChatFindRowState();
}
class _ChatFindRowState extends State<ChatFindRow> {
ChatFindTargets? _targets;
String? _registered;
@override
void didChangeDependencies() {
super.didChangeDependencies();
_register();
}
@override
void didUpdateWidget(ChatFindRow oldWidget) {
super.didUpdateWidget(oldWidget);
_register();
}
void _register() {
_unregister();
final targets = ChatFindScope.maybeOf(context)?.targets;
if (targets == null) return;
targets.rows[widget.rowKey] = context;
_targets = targets;
_registered = widget.rowKey;
}
void _unregister() {
final targets = _targets;
final key = _registered;
if (targets != null && key != null && targets.rows[key] == context) {
targets.rows.remove(key);
}
_targets = null;
_registered = null;
}
@override
void dispose() {
_unregister();
super.dispose();
}
@override
Widget build(BuildContext context) =>
_ChatFindRowKey(rowKey: widget.rowKey, child: widget.child);
}
class _ChatFindRowKey extends InheritedWidget {
const _ChatFindRowKey({required this.rowKey, required super.child});
final String rowKey;
@override
bool updateShouldNotify(_ChatFindRowKey oldWidget) =>
rowKey != oldWidget.rowKey;
}
/// Paints find's matches in one rendered [text], the current one stronger,
/// like the terminal's find. The text itself is never restyled, so nothing
/// shifts or rewraps as the current match moves. The translucent marks go
/// over the text, since a code block's own fill would hide them behind it.
class ChatFindHighlight extends StatefulWidget {
const ChatFindHighlight({
super.key,
required this.text,
required this.rects,
required this.child,
});
final String text;
final ChatFindRects rects;
final Widget child;
@override
State<ChatFindHighlight> createState() => _ChatFindHighlightState();
}
class _ChatFindHighlightState extends State<ChatFindHighlight> {
final _anchor = GlobalKey();
ChatFindTargets? _targets;
(String, String)? _registered;
@override
void dispose() {
_unregister();
super.dispose();
}
void _register(ChatFindTargets? targets, String? rowKey) {
final next = rowKey == null ? null : (rowKey, widget.text);
if (identical(targets, _targets) && next == _registered) {
if (next != null) targets!.texts[next.$1]![next.$2] = widget.rects;
return;
}
_unregister();
if (targets == null || next == null) return;
targets.texts.putIfAbsent(next.$1, () => {})[next.$2] = widget.rects;
_targets = targets;
_registered = next;
}
void _unregister() {
final targets = _targets;
final key = _registered;
if (targets != null && key != null) {
final texts = targets.texts[key.$1];
texts?.remove(key.$2);
if (texts != null && texts.isEmpty) targets.texts.remove(key.$1);
}
_targets = null;
_registered = null;
}
@override
Widget build(BuildContext context) {
final scope = ChatFindScope.maybeOf(context);
final rowKey = ChatFindRow.keyOf(context);
_register(scope?.targets, rowKey);
final controller = scope?.controller;
if (controller == null || rowKey == null) {
return KeyedSubtree(key: _anchor, child: widget.child);
}
final colours = chatShellTerminalMatchColours(context);
return CustomPaint(
key: _anchor,
foregroundPainter: _ChatFindPainter(
controller: controller,
rowKey: rowKey,
text: widget.text,
rects: widget.rects,
anchor: _anchor,
hit: colours.hit,
current: colours.current,
),
child: widget.child,
);
}
}
class _ChatFindPainter extends CustomPainter {
_ChatFindPainter({
required this.controller,
required this.rowKey,
required this.text,
required this.rects,
required this.anchor,
required this.hit,
required this.current,
}) : super(repaint: controller);
final ChatFindController controller;
final String rowKey;
final String text;
final ChatFindRects rects;
final GlobalKey anchor;
final Color hit;
final Color current;
@override
void paint(Canvas canvas, Size size) {
final highlights = controller.highlightsFor(rowKey, text);
if (highlights.isEmpty) return;
final box = anchor.currentContext?.findRenderObject();
if (box is! RenderBox || !box.attached) return;
for (final highlight in highlights) {
final fill = Paint()..color = highlight.current ? current : hit;
for (final rect in rects(highlight.start, highlight.end, box)) {
canvas.drawRRect(
RRect.fromRectAndRadius(rect.inflate(1), const Radius.circular(3)),
fill,
);
}
}
}
@override
bool shouldRepaint(_ChatFindPainter oldDelegate) =>
oldDelegate.controller != controller ||
oldDelegate.rowKey != rowKey ||
oldDelegate.text != text ||
oldDelegate.hit != hit ||
oldDelegate.current != current;
}
/// The boxes of characters [start]..[end] of the first paragraph (or
/// editable) under [context], for a text rendered verbatim.
List<Rect> chatFindPlainRects(
BuildContext? context,
int start,
int end,
RenderBox ancestor,
) {
final paragraph = chatFindTextRenderer(context);
if (paragraph == null || !paragraph.attached || !paragraph.hasSize) {
return const [];
}
final selection = TextSelection(baseOffset: start, extentOffset: end);
final boxes = switch (paragraph) {
RenderParagraph() => paragraph.getBoxesForSelection(selection),
RenderEditable() => paragraph.getBoxesForSelection(selection),
_ => const <TextBox>[],
};
final transform = paragraph.getTransformTo(ancestor);
return [
for (final box in boxes) MatrixUtils.transformRect(transform, box.toRect()),
];
}
/// The first [RenderParagraph] or [RenderEditable] under [context].
RenderBox? chatFindTextRenderer(BuildContext? context) {
RenderBox? found;
void visit(RenderObject object) {
if (found != null) return;
if (object is RenderParagraph || object is RenderEditable) {
found = object as RenderBox;
} else {
object.visitChildren(visit);
}
}
final root = context?.findRenderObject();
if (root != null) visit(root);
return found;
}
@@ -2,6 +2,7 @@ import 'dart:async';
import 'package:flutter/material.dart';
import 'chat_find_highlight.dart';
import 'chat_link_launcher.dart';
import 'chat_link_spans.dart';
import 'chat_links.dart';
@@ -38,8 +39,19 @@ class _ChatLinkTextState extends State<ChatLinkText> {
super.dispose();
}
final _textKey = GlobalKey();
/// The text with find's matches painted behind it; it renders verbatim,
/// so a match's offsets are the rendered characters'.
@override
Widget build(BuildContext context) {
Widget build(BuildContext context) => ChatFindHighlight(
text: widget.text,
rects: (start, end, box) =>
chatFindPlainRects(_textKey.currentContext, start, end, box),
child: KeyedSubtree(key: _textKey, child: _text(context)),
);
Widget _text(BuildContext context) {
final text = widget.text;
if (_found.isEmpty) {
return ChatTranscriptSelectionScope.maybeOf(context) == null
@@ -5,6 +5,7 @@ import 'package:flutter/rendering.dart';
import 'chat_transcript_selection.dart';
import 'chat_code_hover.dart';
import 'chat_find_highlight.dart';
import '../../../../ui/text/monospace.dart';
import 'chat_link_launcher.dart';
import 'chat_link_spans.dart';
@@ -110,7 +111,7 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
// The text is built once and never restyled while speaking; the
// spoken word is painted behind it, so nothing shifts or rewraps.
final rendered = _rendered ??= _buildRendered(context);
return CustomPaint(
final spoken = CustomPaint(
key: _paintKey,
painter: SpokenWordPainter(
anchor: _paintKey,
@@ -121,6 +122,13 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
),
child: rendered,
);
// Find's matches are painted the same way, behind the text.
return ChatFindHighlight(
text: widget.text,
rects: (start, end, box) =>
spokenWordRects(_segments, (start: start, end: end), box),
child: spoken,
);
},
);
}
@@ -252,6 +260,7 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
],
);
case MarkdownCode(language: final language, code: final code):
final codeKey = _codeSegment(code);
_skipCodeBlock(code);
final labelStyle = _roleStyle(
context,
@@ -267,6 +276,7 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
child: ChatTranscriptHorizontalScrollView(
label: 'code block',
child: Text.rich(
key: codeKey,
TextSpan(
children: _linked(
context,
@@ -283,6 +293,27 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
}
}
/// Records where a code block's text renders, character for character
/// from its place in the source, so find can highlight matches in it.
GlobalKey _codeSegment(String code) {
if (_textCount == _textKeys.length) _textKeys.add(GlobalKey());
final key = _textKeys[_textCount++];
final start = code.isEmpty ? -1 : widget.text.indexOf(code, _sourceCursor);
if (start >= 0) {
_segments.add(
MarkdownSpokenSegment(
key,
start,
start + code.length,
0,
code.length,
List<int>.generate(code.length, (index) => start + index),
),
);
}
return key;
}
void _skipCodeBlock(String code) {
_sourceCursor = fencedCodeSpan(
widget.text,
@@ -134,6 +134,13 @@ class KeyboardShortcutRegistry {
caveat:
'While the slash command list is open above the composer. Esc dismisses it.',
),
KeyboardShortcutEntry(
group: KeyboardShortcutGroup.chat,
action: 'Find in chat',
keys: _apple ? 'Cmd+F' : 'Ctrl+F',
caveat:
'Enter moves to an older match, Shift+Enter to a newer one; Esc closes and returns to the composer. Older history is searched on the server and loaded as needed. In the terminal the key goes to the terminal.',
),
KeyboardShortcutEntry(
group: KeyboardShortcutGroup.chat,
action: 'Toggle Files',
@@ -0,0 +1,184 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'package:pipelines_app/features/chat/ui/transcript/chat_find_highlight.dart';
import 'chat_thread_fixtures.dart';
JsonMap _text(String text) => {'type': 'text', 'text': text};
/// Answers scoped searches with [searchHits] for history older than the
/// loaded page.
class _FindGateway extends FakeChatGateway {
final searches = <JsonMap>[];
List<JsonMap> searchHits = const [];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
if (type == 'search') {
searches.add(Map<String, dynamic>.from(fields['search'] as Map));
return {
'type': 'search_results',
'search_results': {'results': searchHits},
};
}
return super.call(type, fields);
}
}
final _newest = [
for (var i = 0; i < 30; i++)
chatMessage(
'n$i',
i.isEven ? 'user' : 'assistant',
parts: [
_text(i == 2 || i == 27 ? 'Needle at $i, and needle' : 'filler $i'),
],
),
];
final _older = [
chatMessage('o1', 'user', parts: [_text('an old needle')]),
chatMessage('o2', 'assistant', parts: [_text('nothing')]),
];
Future<_FindGateway> _host(WidgetTester tester, {bool older = false}) async {
tester.view.physicalSize = const Size(1000, 900);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final gateway = _FindGateway()
..history = (fields) async {
final query = fields['chat_query'] as Map;
if (query['cursor'] == 'c1') return chatPage(_older);
return chatPage(_newest, cursor: older ? 'c1' : '', hasMore: older);
};
addTearDown(gateway.close);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ChatThreadView(
gateway: gateway,
sessionId: 's',
onBack: () {},
drafts: MemoryChatDraftStore(),
newOperationId: () => 'op',
),
),
),
);
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
await tester.pump();
return gateway;
}
Future<void> _ctrlF(WidgetTester tester) async {
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyF);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pump();
await tester.pump();
}
String _count(WidgetTester tester) =>
tester.widget<Text>(find.byKey(const ValueKey('chat-find-count'))).data!;
void main() {
testWidgets('Ctrl+F finds in the chat, steps older with Enter and Esc '
'returns to the composer', (tester) async {
await _host(tester);
await tester.tap(find.byType(EditableText).last);
await tester.pump();
await _ctrlF(tester);
expect(find.byKey(const ValueKey('chat-find-field')), findsOneWidget);
await tester.enterText(
find.byKey(const ValueKey('chat-find-field')),
'needle',
);
await tester.pumpAndSettle();
expect(_count(tester), '1 of 4');
// Each built text with a match registers where it draws.
final scope = tester.widget<ChatFindScope>(find.byType(ChatFindScope));
expect(scope.controller, isNotNull);
expect(scope.targets.texts, isNotEmpty);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(_count(tester), '2 of 4');
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(_count(tester), '3 of 4');
// The match in message n2 is near the top of history: it is built now.
expect(
find.textContaining('Needle at 2', findRichText: true),
findsWidgets,
);
await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
await tester.pumpAndSettle();
expect(_count(tester), '2 of 4');
await tester.tap(find.byKey(const ValueKey('chat-find-case')));
await tester.pumpAndSettle();
expect(_count(tester), '1 of 2');
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
expect(find.byKey(const ValueKey('chat-find-field')), findsNothing);
});
testWidgets('matches in unloaded history are counted from the server and '
'reached by loading older pages', (tester) async {
final gateway = await _host(tester, older: true);
gateway.searchHits = [
{
'chat': {'message_id': 'o1', 'part': 0, 'offset': 7},
},
];
await tester.tap(find.byType(EditableText).last);
await tester.pump();
await _ctrlF(tester);
await tester.enterText(
find.byKey(const ValueKey('chat-find-field')),
'needle',
);
await tester.pump(const Duration(milliseconds: 300));
await tester.pumpAndSettle();
expect(gateway.searches.single['scope'], 'chat:s');
expect(gateway.searches.single['cursor'], '0|c1');
expect(_count(tester), '1 of 5');
// Step to the oldest: it is only on the server, so the older page loads.
for (var i = 0; i < 4; i++) {
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
}
expect(_count(tester), '5 of 5');
expect(
gateway.calls.where(
(call) =>
call.type == 'chat_messages' &&
(call.fields['chat_query'] as Map)['cursor'] == 'c1',
),
isNotEmpty,
);
expect(
find.textContaining('an old needle', findRichText: true),
findsWidgets,
);
});
testWidgets('Ctrl+F with no focus in the chat opens nothing', (tester) async {
await _host(tester);
expect(find.byKey(const ValueKey('chat-find-field')), findsNothing);
// No focus in the chat at all: the pane's handler never sees the key.
await _ctrlF(tester);
expect(find.byKey(const ValueKey('chat-find-field')), findsNothing);
});
}
@@ -0,0 +1,78 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/domain/chat_find.dart';
void main() {
final rows = [
{
'kind': 'user',
'key': 'u1',
'message': {
'id': 'u1',
'parts': [
{'type': 'text', 'text': 'Find the Needle'},
{'type': 'text', 'text': 'and another needle'},
],
},
},
{'kind': 'activity', 'key': 'x', 'label': 'needle in activity'},
{
'kind': 'assistant',
'key': 'a1',
'messageIds': ['a1', 'a2'],
'parts': [
{'type': 'reasoning', 'text': 'needle thoughts'},
{'type': 'text', 'text': 'A **needle** here, needle there'},
{'type': 'text', 'text': ' '},
],
},
];
test('units are user turns and answer text parts as rendered', () {
final units = chatFindUnits(rows, ['k0', 'k1', 'k2']);
expect(units.map((u) => u.text), [
'Find the Needle\nand another needle',
'A **needle** here, needle there',
]);
expect(units.map((u) => u.rowKey), ['k0', 'k2']);
expect(units.first.messageIds, ['u1']);
expect(units.last.messageIds, ['a1', 'a2']);
});
test('matches fold case unless asked, in display order', () {
final units = chatFindUnits(rows, ['k0', 'k1', 'k2']);
final folded = chatFindMatches(units, 'needle', caseSensitive: false);
expect(folded.length, 4);
expect(folded.first.start, 'Find the '.length);
expect(folded.map((m) => m.ordinal), [0, 1, 0, 1]);
final exact = chatFindMatches(units, 'Needle', caseSensitive: true);
expect(exact.length, 1);
});
test('regex characters in the query are literal', () {
expect(chatFindRanges('a.b axb (c)', '.', caseSensitive: false), [
(start: 1, end: 2),
]);
expect(chatFindRanges('a.b axb (c)', '(c)', caseSensitive: false), [
(start: 8, end: 11),
]);
});
test('server hits parse from a scoped reply', () {
final hits = ChatFindRemoteHit.fromReply({
'search_results': {
'results': [
{
'chat': {'message_id': 'm9', 'part': 1, 'offset': 4},
},
{
'chat': {'message_id': 'm8'},
},
],
},
});
expect(hits.map((h) => (h.messageId, h.part, h.offset)), [
('m9', 1, 4),
('m8', 0, 0),
]);
});
}
+39
View File
@@ -310,3 +310,42 @@ void chatScrollStream(String sessionId, void Function(JsonMap frame) emit) {
});
});
}
/// A scoped find-in-chat search (`scope: chat:<id>`) the way
/// `internal/server/search_chat_scoped.go` answers it: every occurrence in
/// the text parts of the history before [cursor] ("0|older" for the page
/// `?older=1` holds back), newest message first.
List<JsonMap> chatScrollScopedHits(
String sessionId,
String cursor,
String query,
bool caseSensitive,
) {
if (!_older || !cursor.endsWith('|older') || query.trim().isEmpty) {
return const [];
}
final pattern = RegExp(RegExp.escape(query), caseSensitive: caseSensitive);
final hits = <JsonMap>[];
for (var i = -1; i >= -20; i--) {
final message = _message(sessionId, i);
final parts = message['parts'] as List;
for (var part = 0; part < parts.length; part++) {
final body = parts[part] as Map;
if (body['type'] != 'text') continue;
for (final match in pattern.allMatches('${body['text']}')) {
hits.add({
'kind': 'chat',
'target': 'chat:$sessionId',
'chat': {
'session_id': sessionId,
'message_id': message['id'],
'part': part,
'offset': match.start,
'length': match.end - match.start,
},
});
}
}
}
return hits;
}
@@ -709,6 +709,25 @@ JsonMap? probeReply(JsonMap request) {
// The app must send exactly the browser's SearchRequest body; anything
// else is answered with a visible refusal so the capture cannot pass.
final search = request['search'];
if (search is Map && search['scope'] is String) {
// Find in chat: every occurrence in history not loaded yet.
final session = '${search['scope']}'.replaceFirst('chat:', '');
return {
'id': id,
'type': 'search_results',
'search_results': {
'query': search['query'],
'kind': 'chat',
'results': chatScrollScopedHits(
session,
'${search['cursor'] ?? ''}',
'${search['query'] ?? ''}',
search['case_sensitive'] == true,
),
'cap': 200,
},
};
}
if (search is! Map ||
search.length != 3 ||
search['query'] is! String ||
+4 -2
View File
@@ -78,8 +78,10 @@ func searchChatScoped(ctx context.Context, req protocol.SearchRequest, broker ch
Cap: chatSearchLimit(req.Limit),
ScanBoundBytes: protocol.SearchMaxScanBytes,
}
query := []rune(strings.TrimSpace(req.Query))
if len(query) == 0 {
// Find matches the query as typed, spaces included, like the client's
// own matching of the loaded transcript.
query := []rune(req.Query)
if strings.TrimSpace(req.Query) == "" {
return response, nil
}
ctx, cancel := context.WithTimeout(ctx, scopedChatBudget)