diff --git a/app/lib/features/search/data/search_repository.dart b/app/lib/features/search/data/search_repository.dart new file mode 100644 index 00000000..391aac13 --- /dev/null +++ b/app/lib/features/search/data/search_repository.dart @@ -0,0 +1,28 @@ +import '../../../core/api_gateway.dart'; +import '../domain/search_models.dart'; + +/// Search protocol requests over the application's shared gateway. +/// +/// The request body is exactly `SearchRequest{query, kind, limit}` with +/// `limit: 0`, so the server applies its own default cap (`SearchDefaultLimit`, +/// 50) instead of the client choosing a larger one. +class SearchRepository { + SearchRepository(this._gateway); + + final ApiGateway _gateway; + + /// Returns the bounded `search_results` body, or null when an older server + /// answered without it (its default `pong`) so the caller can report the + /// "cannot search" sentence rather than showing a false empty success. + Future search({ + required String query, + required SearchKind kind, + }) async { + final reply = await _gateway.call('search', { + 'search': {'query': query, 'kind': kind.wire, 'limit': 0}, + }); + final results = reply['search_results']; + if (results is! Map) return null; + return SearchResponse.fromJson(Map.from(results)); + } +} diff --git a/app/lib/features/search/domain/search_controller.dart b/app/lib/features/search/domain/search_controller.dart new file mode 100644 index 00000000..b9a3f8f8 --- /dev/null +++ b/app/lib/features/search/domain/search_controller.dart @@ -0,0 +1,236 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../../../core/api_gateway.dart'; +import '../data/search_repository.dart'; +import 'search_models.dart'; +import 'search_query.dart'; +import 'search_row.dart'; + +/// The body the results area shows, in the browser's precedence order: an error +/// takes precedence over retained results, a refresh keeps results on screen, +/// and a first load shows the searching row. +enum SearchBodyKind { idle, searching, results, empty, error } + +/// Debounced, stale-safe omni-search state. It owns no widgets and no socket: +/// the screen listens to it and the repository talks to the shared gateway. +class OmniSearchController extends ChangeNotifier { + OmniSearchController({ + required this.repository, + this.debounce = const Duration(milliseconds: 250), + }); + + final SearchRepository repository; + final Duration debounce; + final SearchSequencer _sequencer = SearchSequencer(); + + Timer? _timer; + bool _disposed = false; + + String _query = ''; + SearchKind _selectedKind = SearchKind.all; + List _results = const []; + bool _loading = false; + bool _loaded = false; + bool _truncated = false; + int _scannedSteps = 0; + int _scannedBytes = 0; + int _cap = 0; + int _scanBoundBytes = 0; + String? _error; + + String get query => _query; + SearchKind get selectedKind => _selectedKind; + ParsedSearchQuery get parsed => parseSearchQuery(_query, _selectedKind); + List get results => _results; + bool get loading => _loading; + bool get loaded => _loaded; + bool get truncated => _truncated; + int get scannedSteps => _scannedSteps; + int get scannedBytes => _scannedBytes; + int get cap => _cap; + int get scanBoundBytes => _scanBoundBytes; + String? get error => _error; + + /// The results already in hand, re-narrowed to the effective kind so the list + /// always matches the control while a narrowed request loads. + List get shownResults { + final kind = parsed.kind; + if (kind == SearchKind.all) return _results; + return _results + .where((hit) => hit['kind'] == kind.wire) + .toList(growable: false); + } + + SearchBodyKind get bodyKind { + if (_error != null) return SearchBodyKind.error; + if (shownResults.isNotEmpty) return SearchBodyKind.results; + if (_loading && _results.isEmpty) return SearchBodyKind.searching; + if (emptyMessage != null) return SearchBodyKind.empty; + return SearchBodyKind.idle; + } + + /// A thin progress report above retained results while a newer query loads. + bool get showProgress => _loading && _results.isNotEmpty; + + String? get emptyMessage { + if (_error != null || _loading || shownResults.isNotEmpty) return null; + final effective = parsed; + if (effective.query.trim().isEmpty) { + if (!_loaded || effective.kind == SearchKind.all) return null; + final label = effective.kind.label.toLowerCase(); + return _truncated + ? "No $label found within the server's scan limit." + : 'No $label yet.'; + } + final bounded = _truncated ? " within the server's scan limit" : ''; + if (effective.kind == SearchKind.all) { + return 'No matches for "${effective.query}"$bounded.'; + } + return 'No ${effective.kind.label.toLowerCase()} match ' + '"${effective.query}"$bounded.'; + } + + /// The server's own result/scan bounds, so a capped answer is not presented as + /// a complete one. A truncated reply keeps its warning even with no rows; + /// before any loaded reply there is nothing to report. + String? get boundsText { + if (!_loaded) return null; + // A new first load has no current result set yet, so do not carry the + // previous reply's warning while the searching state is on screen. + if (_loading && _results.isEmpty) return null; + if (_results.isEmpty && !_truncated) return null; + final count = _results.length; + final parts = []; + if (_truncated) { + parts.add("Results truncated by the server's result or scan limit."); + } + parts.add('$count ${count == 1 ? 'result' : 'results'}'); + if (_cap > 0) parts.add('cap $_cap'); + parts.add('scanned $_scannedSteps steps'); + parts.add('${humanBytes(_scannedBytes)} scanned'); + if (_scanBoundBytes > 0) { + parts.add('scan limit ${humanBytes(_scanBoundBytes)}'); + } + return parts.join(' · '); + } + + /// Record a keystroke. Blank text with no kind clears locally and sends + /// nothing; valid kind-only browsing is sendable like the browser's search. + void updateQuery(String value) { + _query = value; + _error = null; + _cancelTimer(); + final effective = parsed; + if (!searchQuerySendable(effective.query, effective.kind)) { + _sequencer.edit(''); + _clearResults(); + _notify(); + return; + } + _loading = true; + final edit = _sequencer.edit(value); + _notify(); + _timer = Timer(debounce, () { + _timer = null; + final sent = _sequencer.begin(edit); + if (sent != null) unawaited(_send(sent)); + }); + } + + /// A kind change removes recognised type tokens from the visible text and + /// sends at once, matching the browser's selector behaviour. + void selectKind(SearchKind kind) { + _query = parseSearchQuery(_query, _selectedKind).query; + _selectedKind = kind; + _error = null; + _notify(); + unawaited(sendNow()); + } + + /// Enter: send the current query immediately, skipping the debounce. + Future submit() => sendNow(); + + /// Retry the current query after a failure. + Future retry() => sendNow(); + + Future sendNow() async { + _cancelTimer(); + final effective = parseSearchQuery(_query, _selectedKind); + if (!searchQuerySendable(effective.query, effective.kind)) { + _sequencer.edit(''); + _clearResults(); + _notify(); + return; + } + final sent = _sequencer.begin(_sequencer.edit(_query)); + if (sent == null) return; + await _send(sent); + } + + Future _send(SearchEdit sent) async { + final effective = parseSearchQuery(sent.query, _selectedKind); + _loading = true; + _error = null; + _notify(); + try { + final response = await repository.search( + query: effective.query.trim(), + kind: effective.kind, + ); + if (!_sequencer.accepts(sent.token) || _disposed) return; + if (response == null) { + _loading = false; + _loaded = true; + _error = unsupportedSearchCopy; + _notify(); + return; + } + _results = response.results; + _truncated = response.truncated; + _scannedSteps = response.scannedSteps; + _scannedBytes = response.scannedBytes; + _cap = response.cap; + _scanBoundBytes = response.scanBoundBytes; + _loading = false; + _loaded = true; + _error = null; + _notify(); + } catch (error) { + if (!_sequencer.accepts(sent.token) || _disposed) return; + _loading = false; + _loaded = true; + _error = searchFailureText(error); + _notify(); + } + } + + void _clearResults() { + _results = const []; + _truncated = false; + _scannedSteps = 0; + _scannedBytes = 0; + _cap = 0; + _scanBoundBytes = 0; + _loading = false; + _loaded = false; + _error = null; + } + + void _cancelTimer() { + _timer?.cancel(); + _timer = null; + } + + void _notify() { + if (!_disposed) notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + _cancelTimer(); + super.dispose(); + } +} diff --git a/app/lib/features/search/domain/search_format.dart b/app/lib/features/search/domain/search_format.dart new file mode 100644 index 00000000..8e2f480a --- /dev/null +++ b/app/lib/features/search/domain/search_format.dart @@ -0,0 +1,43 @@ +/// Human bytes with the shared binary units (`2.0 KiB`), matching the browser. +String humanBytes(int size) { + const unit = 1024; + if (size < unit) return '$size B'; + var divisor = unit; + var exponent = 0; + var scaled = size ~/ unit; + while (scaled >= unit && exponent < 5) { + divisor *= unit; + exponent++; + scaled ~/= unit; + } + return '${(size / divisor).toStringAsFixed(1)} ${'KMGTPE'[exponent]}iB'; +} + +const _months = [ + 'Jan', + 'Feb', + 'Mar', + 'Apr', + 'May', + 'Jun', + 'Jul', + 'Aug', + 'Sep', + 'Oct', + 'Nov', + 'Dec', +]; + +/// An RFC3339 timestamp as the app's one human local rendering (`20 Oct 12:00`), +/// or null when blank/unparseable so the caller omits the value rather than +/// printing a blank. +String? formatSearchTimestamp(String value) { + final text = value.trim(); + if (text.isEmpty) return null; + final instant = DateTime.tryParse(text); + if (instant == null) return null; + final local = instant.toLocal(); + final hour = local.hour.toString().padLeft(2, '0'); + final minute = local.minute.toString().padLeft(2, '0'); + return '${local.day} ${_months[local.month - 1]} $hour:$minute'; +} diff --git a/app/lib/features/search/domain/search_models.dart b/app/lib/features/search/domain/search_models.dart new file mode 100644 index 00000000..671e38d9 --- /dev/null +++ b/app/lib/features/search/domain/search_models.dart @@ -0,0 +1,87 @@ +import '../../../core/api_gateway.dart'; + +/// The server's search narrowing vocabulary (`internal/protocol/search.go`), +/// in the control's display order. The empty [wire] value means every kind. +enum SearchKind { + all('', 'All kinds'), + pipeline('pipeline', 'Pipelines'), + run('run', 'Runs'), + step('step', 'Steps'), + field('field', 'Fields'), + artifact('artifact', 'Artifacts'), + version('version', 'Versions'); + + const SearchKind(this.wire, this.label); + + final String wire; + final String label; + + /// A stale or unknown value falls back to [SearchKind.all] rather than + /// inventing an option the server does not accept. + static SearchKind fromWire(String? wire) { + for (final kind in values) { + if (kind.wire == wire) return kind; + } + return SearchKind.all; + } +} + +/// A query after `t:`/`type:` tokens have been recognised. [query] is the text +/// the server should match; [kind] is the effective narrowing. +class ParsedSearchQuery { + const ParsedSearchQuery(this.query, this.kind, this.hasType); + + final String query; + final SearchKind kind; + final bool hasType; +} + +/// The bounded `search_results` body from the server. Every bound the server +/// reports is kept, so the screen can show a truncation/scan indicator instead +/// of pretending a capped reply was complete. +class SearchResponse { + const SearchResponse({ + this.query = '', + this.kind = SearchKind.all, + this.results = const [], + this.truncated = false, + this.scannedSteps = 0, + this.scannedBytes = 0, + this.cap = 0, + this.scanBoundBytes = 0, + }); + + factory SearchResponse.fromJson(JsonMap json) { + final rows = json['results']; + return SearchResponse( + query: '${json['query'] ?? ''}', + kind: SearchKind.fromWire('${json['kind'] ?? ''}'), + results: rows is List + ? rows + .whereType() + .map((row) => Map.from(row)) + .toList(growable: false) + : const [], + truncated: json['truncated'] == true, + scannedSteps: _integer(json['scanned_steps']), + scannedBytes: _integer(json['scanned_bytes']), + cap: _integer(json['cap']), + scanBoundBytes: _integer(json['scan_bound_bytes']), + ); + } + + final String query; + final SearchKind kind; + final List results; + final bool truncated; + final int scannedSteps; + final int scannedBytes; + final int cap; + final int scanBoundBytes; +} + +int _integer(Object? value) { + if (value is int) return value; + if (value is num) return value.toInt(); + return int.tryParse('$value') ?? 0; +} diff --git a/app/lib/features/search/domain/search_query.dart b/app/lib/features/search/domain/search_query.dart new file mode 100644 index 00000000..a7971540 --- /dev/null +++ b/app/lib/features/search/domain/search_query.dart @@ -0,0 +1,82 @@ +import 'search_models.dart'; + +/// Wording for a server that cannot answer `search`: an explicit rejection +/// naming an unknown/unsupported command, or a reply without +/// `search_results`. Kept verbatim from the web client's AppViewModel copy. +const unsupportedSearchCopy = + 'This server does not support search. Update the Pipelines server, then try again.'; + +/// Unquoted, whitespace-delimited `t:`/`type:` tokens; the last supported token +/// wins. Unknown tokens and quoted text stay literal, including their whitespace. +/// The selector is a fallback; explicitly changing it removes tokens in the view. +/// +/// This is the same token grammar as `web/src/search.js`, so `"t:run"`, +/// `t:unknown`, `prefix"t:run"` and `\t:run` all remain searchable text. +ParsedSearchQuery parseSearchQuery( + String value, [ + SearchKind selectedKind = SearchKind.all, +]) { + var kind = selectedKind; + var hasType = false; + final query = value.replaceAllMapped(_tokenPattern, (match) { + final token = match[0] ?? ''; + final type = _typePattern.firstMatch(token); + if (type == null) return token; + final candidate = SearchKind.fromWire(type.group(1)!.toLowerCase()); + if (candidate == SearchKind.all) return token; + kind = candidate; + hasType = true; + return ''; + }); + return ParsedSearchQuery(query, kind, hasType); +} + +final _tokenPattern = RegExp( + r'''(?:[^\s"'\\]|\\[\s\S]|"(?:[^"\\]|\\[\s\S])*(?:"|$)|'(?:[^'\\]|\\[\s\S])*(?:'|$))+''', +); +final _typePattern = RegExp(r'^(?:t|type):([a-z]+)$', caseSensitive: false); + +/// Text searches and valid kind-only browsing are sendable. Empty text with no +/// supported kind clears locally, without an all-kind scan. +bool searchQuerySendable(String query, SearchKind kind) => + query.trim().isNotEmpty || kind != SearchKind.all; + +/// The message for a failed search: the unsupported sentence for a missing +/// payload or an unknown-command rejection, otherwise the server's own text. +String searchFailureText(Object? error) { + if (error == null) return unsupportedSearchCopy; + final message = error.toString().trim(); + if (message.isEmpty) return unsupportedSearchCopy; + if (_unsupportedCommand.hasMatch(message)) return unsupportedSearchCopy; + return message; +} + +final _unsupportedCommand = RegExp( + r'\b(unknown|unsupported|unrecognised|unrecognized)\b[\s\S]*\bcommand\b', + caseSensitive: false, +); + +/// One recorded edit being debounced. +class SearchEdit { + const SearchEdit(this.token, this.query); + + final int token; + final String query; +} + +/// Query sequencing: a burst of keystrokes collapses into one request, and a +/// reply is accepted only for the newest recorded edit, so a stale reply can +/// never overwrite a newer one. Recording an edit (a keystroke, or an empty +/// edit when the field clears) is enough to invalidate an in-flight reply. +class SearchSequencer { + int _newest = 0; + + SearchEdit edit(String query) => SearchEdit(++_newest, query); + + SearchEdit? begin(SearchEdit? edit) { + if (edit == null || edit.token != _newest) return null; + return edit; + } + + bool accepts(int token) => token == _newest; +} diff --git a/app/lib/features/search/domain/search_row.dart b/app/lib/features/search/domain/search_row.dart new file mode 100644 index 00000000..283feca7 --- /dev/null +++ b/app/lib/features/search/domain/search_row.dart @@ -0,0 +1,226 @@ +import '../../../core/api_gateway.dart'; +import 'search_format.dart'; + +export 'search_format.dart' show humanBytes, formatSearchTimestamp; + +/// One run of a field snippet, split so the first case-insensitive occurrence of +/// the query can be emphasised without colour or markup. +class SearchSnippetSpan { + const SearchSnippetSpan(this.text, {required this.matched}); + + final String text; + final bool matched; +} + +/// A render-ready search row. [target] is the server's own stable target token; +/// it is null for an unknown/absent payload or a reply without a target, and +/// such a row is read-only — the client never guesses a route. +class SearchRowView { + const SearchRowView({ + required this.title, + required this.secondary, + required this.kindLabel, + required this.snippetSpans, + required this.target, + this.snippet, + this.recency, + }); + + final String title; + final String secondary; + final String kindLabel; + final String? snippet; + final List snippetSpans; + final String? recency; + final String? target; + + bool get openable => target != null; +} + +/// One rendered search row, mirroring the browser's per-kind row text. Every +/// server-provided string is only ever compared or rendered as text. +SearchRowView searchRowView(JsonMap hit, String query) { + final pipeline = _map(hit['pipeline']); + final version = _map(hit['version']); + final run = _map(hit['run']); + final step = _map(hit['step']); + final field = _map(hit['field']); + final artifact = _map(hit['artifact']); + + final recency = formatSearchTimestamp('${hit['recency'] ?? ''}'); + final target = _serverTarget(hit); + + if (pipeline != null) { + return SearchRowView( + title: _nonBlank(pipeline['name']) ?? 'pipeline ${_num(pipeline['id'])}', + secondary: + 'pipeline ${_num(pipeline['id'])} · v${_num(pipeline['version'])}' + ' · ${_stageCount(pipeline['stages'])}', + kindLabel: 'Pipeline', + snippetSpans: const [], + recency: recency, + target: target, + ); + } + if (version != null) { + final hash = _nonBlank(version['content_hash']); + return SearchRowView( + title: + 'pipeline ${_num(version['pipeline_id'])}' + ' · v${_num(version['version'])}', + secondary: _join([ + hash == null ? null : 'content $hash', + formatSearchTimestamp('${version['created_at'] ?? ''}'), + ]), + kindLabel: 'Pipeline version', + snippetSpans: const [], + recency: recency, + target: target, + ); + } + if (run != null) { + final name = _nonBlank(run['pipeline_name']); + return SearchRowView( + title: 'run #${_num(run['id'])}${name == null ? '' : ' · $name'}', + secondary: _join([ + _nonBlank(run['status']), + _nonBlank(run['workspace']), + formatSearchTimestamp('${run['created_at'] ?? ''}'), + ]), + kindLabel: 'Run', + snippetSpans: const [], + recency: recency, + target: target, + ); + } + if (step != null) { + final stage = _nonBlank(step['stage']) ?? 'step'; + return SearchRowView( + title: + 'run #${_num(step['run_id'])} · $stage' + ' visit ${_num(step['visit'])}', + secondary: _stepSecondary(step), + kindLabel: 'Step', + snippetSpans: const [], + recency: recency, + target: target, + ); + } + if (field != null) { + final snippet = '${field['snippet'] ?? ''}'; + return SearchRowView( + title: + 'run #${_num(field['run_id'])} · step ${_num(field['sequence'])}' + ' · ${_nonBlank(field['field']) ?? 'field'}', + secondary: snippet, + kindLabel: 'Field', + snippet: snippet, + snippetSpans: snippetSpans(snippet, query), + recency: recency, + target: target, + ); + } + if (artifact != null) { + return SearchRowView( + title: _nonBlank(artifact['name']) ?? 'artifact', + secondary: _join([ + 'run #${_num(artifact['run_id'])}', + 'step ${_num(artifact['sequence'])}', + _nonBlank(artifact['content_type']), + humanBytes(_num(artifact['size_bytes'])), + ]), + kindLabel: 'Artifact', + snippetSpans: const [], + recency: recency, + target: target, + ); + } + final kind = _nonBlank(hit['kind']); + return SearchRowView( + title: _nonBlank(hit['target']) ?? 'Unrecognised result', + secondary: kind == null ? 'read-only' : 'kind "$kind" · read-only', + kindLabel: 'Unrecognised result', + snippetSpans: const [], + recency: recency, + target: target, + ); +} + +/// Splits [snippet] so the first case-insensitive occurrence of [query] is a +/// distinct matched span. A blank query or absent match leaves the whole +/// snippet unmatched, so no text is ever dropped. +List snippetSpans(String snippet, String query) { + if (snippet.isEmpty) return const []; + final needle = query.trim(); + if (needle.isEmpty) { + return [SearchSnippetSpan(snippet, matched: false)]; + } + final index = snippet.toLowerCase().indexOf(needle.toLowerCase()); + if (index < 0) return [SearchSnippetSpan(snippet, matched: false)]; + final end = index + needle.length; + return [ + if (index > 0) + SearchSnippetSpan(snippet.substring(0, index), matched: false), + SearchSnippetSpan(snippet.substring(index, end), matched: true), + if (end < snippet.length) + SearchSnippetSpan(snippet.substring(end), matched: false), + ]; +} + +String _stepSecondary(JsonMap step) { + final diagnostic = '${step['diagnostic'] ?? ''}'; + String? line; + for (final candidate in diagnostic.split(RegExp(r'\r?\n'))) { + if (candidate.trim().isNotEmpty) { + line = candidate; + break; + } + } + final target = _nonBlank(step['target']); + final joined = _join([ + _nonBlank(step['outcome']), + target == null ? null : '→ $target', + line?.trim(), + ]); + return joined.isEmpty ? 'step ${_num(step['sequence'])}' : joined; +} + +/// The server's own target token, never a target the client invents. A known +/// payload is not enough: an absent token makes the row read-only. +String? _serverTarget(JsonMap hit) { + final target = _nonBlank(hit['target']); + if (target == null) return null; + final known = [ + 'pipeline', + 'version', + 'run', + 'step', + 'field', + 'artifact', + ].any((key) => _map(hit[key]) != null); + return known ? target : null; +} + +String _stageCount(Object? count) { + final n = _num(count); + return '$n ${n == 1 ? 'stage' : 'stages'}'; +} + +Map? _map(Object? value) { + if (value is! Map) return null; + return Map.from(value); +} + +String? _nonBlank(Object? value) { + final text = '${value ?? ''}'; + return text.trim().isEmpty ? null : text; +} + +int _num(Object? value) { + if (value is int) return value; + if (value is num) return value.toInt(); + return int.tryParse('${value ?? ''}') ?? 0; +} + +String _join(List parts) => + parts.whereType().where((part) => part.isNotEmpty).join(' · '); diff --git a/app/lib/features/search/search_screen.dart b/app/lib/features/search/search_screen.dart new file mode 100644 index 00000000..3c2e80ce --- /dev/null +++ b/app/lib/features/search/search_screen.dart @@ -0,0 +1,228 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../core/api_gateway.dart'; +import 'data/search_repository.dart'; +import 'domain/search_controller.dart'; +import 'domain/search_models.dart'; +import 'ui/cupertino_search_body.dart'; +import 'ui/material_search_body.dart'; + +/// Native omni-search over the Pipelines server: a standard search field, an +/// explicit kind selector, and a flat result list whose rows open the server's +/// own target through [onOpen]. The screen never mutates server state and never +/// guesses a route for an unknown or targetless hit. +class SearchScreen extends StatefulWidget { + const SearchScreen({ + super.key, + required this.gateway, + required this.onOpen, + this.cupertino, + }); + + final ApiGateway gateway; + final ValueChanged onOpen; + + /// Lets the shell state the surface it composed. When omitted, iOS/macOS use + /// Cupertino controls and every other platform uses Material. + final bool? cupertino; + + @override + State createState() => _SearchScreenState(); +} + +class _SearchScreenState extends State { + late final OmniSearchController _controller; + late final TextEditingController _text; + + @override + void initState() { + super.initState(); + _controller = OmniSearchController( + repository: SearchRepository(widget.gateway), + ); + _text = TextEditingController(); + _controller.addListener(_onState); + } + + void _onState() { + final query = _controller.query; + if (_text.text != query) { + _text.value = TextEditingValue( + text: query, + selection: TextSelection.collapsed(offset: query.length), + ); + } + if (mounted) setState(() {}); + } + + void _clear() { + _text.clear(); + _controller.updateQuery(''); + } + + void _selectKind(SearchKind kind) => _controller.selectKind(kind); + + bool get _showHint { + final body = _controller.bodyKind; + return body == SearchBodyKind.idle || body == SearchBodyKind.empty; + } + + Future _pickKind(BuildContext context) async { + final selected = await showCupertinoModalPopup( + context: context, + builder: (context) => CupertinoActionSheet( + title: const Text('Kind'), + actions: [ + for (final kind in SearchKind.values) + CupertinoActionSheetAction( + onPressed: () => Navigator.pop(context, kind), + isDefaultAction: kind == _controller.parsed.kind, + child: Text(kind.label), + ), + ], + cancelButton: CupertinoActionSheetAction( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + ), + ); + if (selected != null) _selectKind(selected); + } + + @override + void dispose() { + _controller.removeListener(_onState); + _controller.dispose(); + _text.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final cupertino = + widget.cupertino ?? + switch (Theme.of(context).platform) { + TargetPlatform.iOS || TargetPlatform.macOS => true, + _ => false, + }; + return cupertino ? _cupertinoScreen() : _materialScreen(); + } + + Widget _materialScreen() => Scaffold( + appBar: AppBar(title: const Text('Search')), + body: SafeArea( + child: MaterialSearchBody( + controller: _controller, + query: _controller.parsed.query, + onOpen: widget.onOpen, + header: _materialHeader(), + ), + ), + ); + + Widget _materialHeader() => Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + spacing: 8, + children: [ + SearchBar( + key: const ValueKey('search.field'), + controller: _text, + autoFocus: true, + hintText: 'Search pipelines, runs and artifacts', + leading: const Icon(Icons.search), + trailing: [ + if (_text.text.isNotEmpty) + IconButton( + key: const ValueKey('search.clear'), + onPressed: _clear, + tooltip: 'Clear search', + icon: const Icon(Icons.close), + ), + ], + textInputAction: TextInputAction.search, + onChanged: _controller.updateQuery, + onSubmitted: (_) => _controller.submit(), + ), + InputDecorator( + decoration: const InputDecoration( + labelText: 'Kind', + border: OutlineInputBorder(), + ), + child: DropdownButtonHideUnderline( + child: DropdownButton( + key: const ValueKey('search.kind'), + value: _controller.parsed.kind, + isExpanded: true, + onChanged: (kind) { + if (kind != null) _selectKind(kind); + }, + items: [ + for (final kind in SearchKind.values) + DropdownMenuItem(value: kind, child: Text(kind.label)), + ], + ), + ), + ), + if (_showHint) const Text(_tokenHint), + if (_controller.boundsText case final bounds?) Text(bounds), + ], + ), + ); + + Widget _cupertinoScreen() => CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar(middle: Text('Search')), + child: SafeArea( + child: CupertinoSearchBody( + controller: _controller, + query: _controller.parsed.query, + onOpen: widget.onOpen, + header: _cupertinoHeader(context), + ), + ), + ); + + Widget _cupertinoHeader(BuildContext context) => Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + spacing: 8, + children: [ + CupertinoSearchTextField( + key: const ValueKey('search.field'), + controller: _text, + autofocus: true, + placeholder: 'Search pipelines, runs and artifacts', + onChanged: _controller.updateQuery, + onSubmitted: (_) => _controller.submit(), + onSuffixTap: _clear, + ), + Align( + alignment: AlignmentDirectional.centerStart, + child: CupertinoButton( + key: const ValueKey('search.kind'), + padding: EdgeInsets.zero, + onPressed: () => _pickKind(context), + child: Row( + mainAxisSize: MainAxisSize.max, + spacing: 6, + children: [ + Expanded(child: Text('Kind: ${_controller.parsed.kind.label}')), + const Icon(CupertinoIcons.chevron_down), + ], + ), + ), + ), + if (_showHint) const Text(_tokenHint), + if (_controller.boundsText case final bounds?) Text(bounds), + ], + ), + ); +} + +const _tokenHint = + 'Filter with t:pipeline or type:artifact (pipeline, run, step, field, ' + 'artifact, version). Last type wins; choosing Kind replaces it. Quote ' + 'tokens to search literally.'; diff --git a/app/lib/features/search/ui/cupertino_search_body.dart b/app/lib/features/search/ui/cupertino_search_body.dart new file mode 100644 index 00000000..2f29d3b0 --- /dev/null +++ b/app/lib/features/search/ui/cupertino_search_body.dart @@ -0,0 +1,174 @@ +import 'package:flutter/cupertino.dart'; + +import '../../../core/api_gateway.dart'; +import '../domain/search_controller.dart'; +import '../domain/search_row.dart'; +import 'search_result_view.dart'; + +/// The Cupertino search view: native search/kind controls and grouped list rows +/// in one scroll view, with standard activity and retry controls. +class CupertinoSearchBody extends StatelessWidget { + const CupertinoSearchBody({ + super.key, + required this.controller, + required this.query, + required this.onOpen, + required this.header, + }); + + final OmniSearchController controller; + final String query; + final ValueChanged onOpen; + final Widget header; + + @override + Widget build(BuildContext context) { + return CustomScrollView( + slivers: [ + SliverToBoxAdapter(child: header), + if (controller.showProgress) + const SliverToBoxAdapter( + child: Padding( + padding: EdgeInsets.symmetric(vertical: 8), + child: CupertinoActivityIndicator(), + ), + ), + ..._content(context), + ], + ); + } + + List _content(BuildContext context) { + switch (controller.bodyKind) { + case SearchBodyKind.error: + return [ + SliverFillRemaining( + hasScrollBody: false, + child: _CupertinoError( + message: controller.error!, + onRetry: controller.retry, + ), + ), + ]; + case SearchBodyKind.searching: + return const [ + SliverFillRemaining( + hasScrollBody: false, + child: _CupertinoSearching(), + ), + ]; + case SearchBodyKind.results: + return [ + SliverToBoxAdapter( + child: CupertinoListSection.insetGrouped( + children: [ + for (final hit in controller.shownResults) + _CupertinoResult(hit: hit, query: query, onOpen: onOpen), + ], + ), + ), + ]; + case SearchBodyKind.empty: + return [ + SliverFillRemaining( + hasScrollBody: false, + child: _CupertinoMessage(message: controller.emptyMessage!), + ), + ]; + case SearchBodyKind.idle: + return const [ + SliverFillRemaining( + hasScrollBody: false, + child: _CupertinoMessage( + message: 'Search pipelines, runs and artifacts.', + ), + ), + ]; + } + } +} + +class _CupertinoResult extends StatelessWidget { + const _CupertinoResult({ + required this.hit, + required this.query, + required this.onOpen, + }); + + final JsonMap hit; + final String query; + final ValueChanged onOpen; + + @override + Widget build(BuildContext context) { + final row = searchRowView(hit, query); + return CupertinoListTile( + key: ValueKey('search.result.${hit['target']}'), + leading: Icon(searchCupertinoIcon('${hit['kind'] ?? ''}')), + title: Text(row.title), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + spacing: 2, + children: [searchRowMeta(row), searchRowSnippet(context, row)], + ), + onTap: row.openable ? () => onOpen(hit) : null, + ); + } +} + +class _CupertinoSearching extends StatelessWidget { + const _CupertinoSearching(); + + @override + Widget build(BuildContext context) => const Center( + child: Padding( + padding: EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + spacing: 12, + children: [CupertinoActivityIndicator(), Text('Searching…')], + ), + ), + ); +} + +class _CupertinoMessage extends StatelessWidget { + const _CupertinoMessage({required this.message}); + + final String message; + + @override + Widget build(BuildContext context) => Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text(message, textAlign: TextAlign.center), + ), + ); +} + +class _CupertinoError extends StatelessWidget { + const _CupertinoError({required this.message, required this.onRetry}); + + final String message; + final Future Function() onRetry; + + @override + Widget build(BuildContext context) => Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + spacing: 12, + children: [ + Text(message, textAlign: TextAlign.center), + CupertinoButton.filled( + key: const ValueKey('search.retry'), + onPressed: onRetry, + child: const Text('Retry'), + ), + ], + ), + ), + ); +} diff --git a/app/lib/features/search/ui/material_search_body.dart b/app/lib/features/search/ui/material_search_body.dart new file mode 100644 index 00000000..462f75ee --- /dev/null +++ b/app/lib/features/search/ui/material_search_body.dart @@ -0,0 +1,166 @@ +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../domain/search_controller.dart'; +import '../domain/search_row.dart'; +import 'search_result_view.dart'; + +/// The Material search view: the controls header and a flat native result list +/// in one scroll view, so text scaling can never clip the controls or a row. +class MaterialSearchBody extends StatelessWidget { + const MaterialSearchBody({ + super.key, + required this.controller, + required this.query, + required this.onOpen, + required this.header, + }); + + final OmniSearchController controller; + final String query; + final ValueChanged onOpen; + final Widget header; + + @override + Widget build(BuildContext context) { + return CustomScrollView( + slivers: [ + SliverToBoxAdapter(child: header), + if (controller.showProgress) + const SliverToBoxAdapter(child: LinearProgressIndicator()), + ..._content(context), + ], + ); + } + + List _content(BuildContext context) { + switch (controller.bodyKind) { + case SearchBodyKind.error: + return [ + SliverFillRemaining( + hasScrollBody: false, + child: _SearchError( + message: controller.error!, + onRetry: controller.retry, + ), + ), + ]; + case SearchBodyKind.searching: + return const [ + SliverFillRemaining(hasScrollBody: false, child: _Searching()), + ]; + case SearchBodyKind.results: + return [ + SliverList.builder( + itemCount: controller.shownResults.length, + itemBuilder: (context, index) { + final hit = controller.shownResults[index]; + return _MaterialResult(hit: hit, query: query, onOpen: onOpen); + }, + ), + ]; + case SearchBodyKind.empty: + return [ + SliverFillRemaining( + hasScrollBody: false, + child: _SearchMessage(message: controller.emptyMessage!), + ), + ]; + case SearchBodyKind.idle: + return const [ + SliverFillRemaining( + hasScrollBody: false, + child: _SearchMessage( + message: 'Search pipelines, runs and artifacts.', + ), + ), + ]; + } + } +} + +class _MaterialResult extends StatelessWidget { + const _MaterialResult({ + required this.hit, + required this.query, + required this.onOpen, + }); + + final JsonMap hit; + final String query; + final ValueChanged onOpen; + + @override + Widget build(BuildContext context) { + final row = searchRowView(hit, query); + return ListTile( + key: ValueKey('search.result.${hit['target']}'), + leading: Icon(searchMaterialIcon('${hit['kind'] ?? ''}')), + title: Text(row.title), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + spacing: 2, + children: [searchRowMeta(row), searchRowSnippet(context, row)], + ), + onTap: row.openable ? () => onOpen(hit) : null, + ); + } +} + +class _Searching extends StatelessWidget { + const _Searching(); + + @override + Widget build(BuildContext context) => const Center( + child: Padding( + padding: EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + spacing: 12, + children: [CircularProgressIndicator(), Text('Searching…')], + ), + ), + ); +} + +class _SearchMessage extends StatelessWidget { + const _SearchMessage({required this.message}); + + final String message; + + @override + Widget build(BuildContext context) => Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text(message, textAlign: TextAlign.center), + ), + ); +} + +class _SearchError extends StatelessWidget { + const _SearchError({required this.message, required this.onRetry}); + + final String message; + final Future Function() onRetry; + + @override + Widget build(BuildContext context) => Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + spacing: 12, + children: [ + Text(message, textAlign: TextAlign.center), + FilledButton.tonalIcon( + key: const ValueKey('search.retry'), + onPressed: onRetry, + icon: const Icon(Icons.refresh), + label: const Text('Retry'), + ), + ], + ), + ), + ); +} diff --git a/app/lib/features/search/ui/search_result_view.dart b/app/lib/features/search/ui/search_result_view.dart new file mode 100644 index 00000000..fef687f3 --- /dev/null +++ b/app/lib/features/search/ui/search_result_view.dart @@ -0,0 +1,59 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../domain/search_row.dart'; + +/// Kind, recency and read-only affordance for one row. Deliberately unstyled +/// beyond weight so Material and Cupertino inherit their own system typography +/// and colours, including dark mode and text scaling. +Widget searchRowMeta(SearchRowView row) { + final parts = [row.kindLabel, if (row.recency != null) row.recency!]; + return Text( + parts.join(' · '), + style: const TextStyle(fontWeight: FontWeight.w600), + ); +} + +/// The snippet with the first query occurrence emphasised by weight, never by +/// parsing server text as markup or by a bespoke colour. +Widget searchRowSnippet(BuildContext context, SearchRowView row) { + final snippet = row.snippet; + if (snippet == null) { + return row.secondary.isEmpty + ? const SizedBox.shrink() + : Text(row.secondary); + } + return Text.rich( + TextSpan( + children: [ + for (final span in row.snippetSpans) + TextSpan( + text: span.text, + style: span.matched + ? const TextStyle(fontWeight: FontWeight.bold) + : null, + ), + ], + ), + ); +} + +IconData searchMaterialIcon(String kind) => switch (kind) { + 'pipeline' => Icons.account_tree_outlined, + 'version' => Icons.layers_outlined, + 'run' => Icons.play_circle_outline, + 'step' => Icons.arrow_forward, + 'field' => Icons.notes, + 'artifact' => Icons.attach_file, + _ => Icons.help_outline, +}; + +IconData searchCupertinoIcon(String kind) => switch (kind) { + 'pipeline' => CupertinoIcons.arrow_branch, + 'version' => CupertinoIcons.square_stack_3d_up, + 'run' => CupertinoIcons.play_circle, + 'step' => CupertinoIcons.arrow_right, + 'field' => CupertinoIcons.doc_text, + 'artifact' => CupertinoIcons.paperclip, + _ => CupertinoIcons.question_circle, +}; diff --git a/app/notes/X1.md b/app/notes/X1.md new file mode 100644 index 00000000..72e19645 --- /dev/null +++ b/app/notes/X1.md @@ -0,0 +1,121 @@ +# X1 — Omni-search + +## Scope and API + +Implemented the `search` feature under `lib/features/search/` with no +`main.dart`, shell, pubspec, server, web or Android edits. + +Entry point: + +```dart +SearchScreen( + gateway: apiGateway, // required ApiGateway + onOpen: (hit) { ... }, // required ValueChanged + cupertino: null, // optional; omitted = iOS/macOS Cupertino, else Material +) +``` + +`onOpen` always receives the server's original result map unchanged, including +its `target`. Unknown/absent payloads and results without a target are +read-only and never call `onOpen`; the client never invents a route or mutates +server state. + +Request shape is exact and shared-gateway only: + +```json +{"type":"search","search":{"query":"plan","kind":"","limit":0}} +``` + +`limit` is always `0` (server default cap), never a client-chosen larger value. + +## Behaviour + +- `t:`/`type:` tokens: unquoted, whitespace-delimited, case-insensitive, last + supported token wins; quoted, escaped, unknown and trailing-punctuation + tokens stay literal. The parser mirrors `web/src/search.js`. +- Kind selector: All kinds / Pipelines / Runs / Steps / Fields / Artifacts / + Versions. Changing it removes recognised type tokens from the field and sends + at once, like the browser's selector. +- Empty text with All kinds clears locally and sends nothing. Blank text with a + valid kind is a kind-only browse, matching the server/browser contract. +- 250 ms debounce; Enter sends at once. Every request carries a monotonically + increasing token, and replies for superseded edits are dropped. +- Loading, searching, retained-results refresh progress, empty (query-specific + and kind-only wording) and error are distinct. A truncated reply with no rows + says the server's scan limit was reached and keeps its truncation/scan bounds + on screen instead of claiming a complete empty; a complete empty has no bounds + line. A reply without `search_results` and an unknown-command rejection use + the server-upgrade sentence; any other failure shows the server's own text. + Error state offers Retry. +- Rows show the kind derived from the server payload (`Unrecognised result` for + an unknown payload), title, snippet (first case-insensitive query occurrence in + bold), and recency. Bounds show result count, cap, scanned steps/bytes, scan + limit and a truncation sentence when the server reports it, including for a + truncated reply with zero rows. +- In-hand results are re-narrowed by the effective kind while a narrowed request + loads, so the list always agrees with the control. +- Standard platform controls only: Material `SearchBar`, dropdown, + `LinearProgressIndicator`, `CircularProgressIndicator`, `ListTile`, + `FilledButton.tonalIcon`; Cupertino `CupertinoSearchTextField`, action-sheet + kind picker, `CupertinoListSection`/`CupertinoListTile`, + `CupertinoActivityIndicator`, `CupertinoButton.filled`. No CSS port, custom + palette, fixed row/bubble dimensions or bespoke buttons. Typography and + colours come from the ambient Material/Cupertino theme; rows and the header + scroll in one `CustomScrollView` so 2× text never clips. + +## Automated checks + +Run from `app/` with `/Users/alan/development/flutter/bin/flutter`: + +- `flutter test test/features/search` — **36 passed** (controller, repository, + query/token parser, row/snippet/routing, Material + Cupertino widget tests). +- `flutter test` — **65 passed** (whole app suite, including existing transport, + runs and shell tests). +- `flutter analyze` — **No issues found**. +- `flutter build web` (default `lib/main.dart`) — **succeeded**. +- `flutter build web -t tool/search_fixture/main.dart` — **succeeded** for the + rendered probe. +- `node --check tool/search_probe.mjs` — passed. +- `git diff --no-index --check /dev/null ` on every touched file — no + whitespace errors (all task files are untracked, so plain `git diff --check` + would not see them). + +Tests were written before the implementation (initial run failed on missing +symbols). Coverage includes the exact envelope, token parsing, selector token +clearing, no-request empty state, stale success and failure replies, +error/retry, truncation/bounds (including a truncated reply with zero rows), +per-kind row text, snippet spans, read-only hits, `onOpen` targets, and +MaterialApp/CupertinoApp at 390/1000 wide with 2× text. + +## Rendered browser evidence + +Built the Web-only fixture (`tool/search_fixture/main.dart`) and drove real +headless Chrome through CDP with `tool/search_probe.mjs` on an OS-assigned +loopback port. The probe typed `plan` into the real field, asserted five rows, +the server snippet, recency and truncation/scanned bounds, then clicked the +pipeline row and asserted that the fixture receiver got `pipeline:24`. It also +typed `needle` with no matching fixtures and asserted the Material and Cupertino +truncated-empty copy plus the retained `Results truncated … 0 results … scanned +2000 steps … scan limit 1.0 MiB` line, capturing both. + +Captures are in the run's shared artifacts: + +- `/Users/alan/.local/share/pipelines/data/artifacts/49/public/x1-search/x1-search-material-phone.png` — 390×844, Material controls, five mixed-kind results with recency/snippet/bounds. +- `/Users/alan/.local/share/pipelines/data/artifacts/49/public/x1-search/x1-search-material-desktop.png` — 1280×800, same results. +- `/Users/alan/.local/share/pipelines/data/artifacts/49/public/x1-search/x1-search-cupertino-phone.png` — 390×844, Cupertino search field/kind picker/grouped rows, dark system theme. +- `/Users/alan/.local/share/pipelines/data/artifacts/49/public/x1-search/x1-search-open-target.png` — the row click landing on `Opened pipeline target: pipeline:24`. +- `/Users/alan/.local/share/pipelines/data/artifacts/49/public/x1-search/x1-search-truncated-empty.png` — 390×844 Material, zero rows with the server's scan-limit sentence and truncation/scan bounds. +- `/Users/alan/.local/share/pipelines/data/artifacts/49/public/x1-search/x1-search-truncated-empty-cupertino.png` — 390×844 Cupertino dark, the same bounded empty state. + +The fixture and probe are development-only entry points; they are not imported +by `lib/main.dart` and are not part of the production routing. The browser run +used a static fake gateway, not a live Pipelines server or operator data. + +## Not verified / open items + +- No shell registration or navigation wiring was added (manager owns + `main.dart`/`shell/`); the screen is exported for that integration. +- No real server, operator chat/run, or production URL was used. +- Mobile targets (Android/iOS) were **not** built, installed or exercised; + only Web was rendered and tested. Source is kept portable. +- No commit, push, deployment or canonical URL change was made. diff --git a/app/test/features/search/search_controller_failure_test.dart b/app/test/features/search/search_controller_failure_test.dart new file mode 100644 index 00000000..43f217c1 --- /dev/null +++ b/app/test/features/search/search_controller_failure_test.dart @@ -0,0 +1,90 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/search/domain/search_controller.dart'; +import 'package:pipelines_app/features/search/domain/search_query.dart'; +import 'search_test_support.dart'; + +void main() { + test('a server error is shown, and retry issues a fresh request', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('plan'); + await pumpEventQueue(); + gateway.fail(0, StateError('server is down')); + await pumpEventQueue(); + + expect(controller.bodyKind, SearchBodyKind.error); + expect(controller.error, contains('server is down')); + + final retry = controller.retry(); + await pumpEventQueue(); + expect(gateway.calls, hasLength(2)); + expect(gateway.lastSearch, {'query': 'plan', 'kind': '', 'limit': 0}); + + gateway.succeed( + 1, + envelope([ + { + 'kind': 'pipeline', + 'target': 'pipeline:7', + 'pipeline': {'id': 7}, + }, + ]), + ); + await retry; + expect(controller.error, isNull); + expect(controller.results, hasLength(1)); + expect(controller.bodyKind, SearchBodyKind.results); + }); + + test('a stale failure never replaces the newest query state', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('first'); + await pumpEventQueue(); + controller.updateQuery('second'); + await pumpEventQueue(); + + gateway.fail(0, StateError('stale failure')); + await pumpEventQueue(); + + expect(controller.error, isNull); + expect(controller.loading, isTrue); + expect(controller.bodyKind, SearchBodyKind.searching); + + gateway.succeed( + 1, + envelope([ + { + 'kind': 'pipeline', + 'target': 'pipeline:9', + 'pipeline': {'id': 9}, + }, + ]), + ); + await pumpEventQueue(); + expect(controller.error, isNull); + expect(controller.results.single['target'], 'pipeline:9'); + expect(controller.bodyKind, SearchBodyKind.results); + }); + + test( + 'a missing search_results payload reports the unsupported copy', + () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('plan'); + await pumpEventQueue(); + gateway.succeed(0, {'type': 'pong'}); + await pumpEventQueue(); + + expect(controller.bodyKind, SearchBodyKind.error); + expect(controller.error, unsupportedSearchCopy); + }, + ); +} diff --git a/app/test/features/search/search_controller_test.dart b/app/test/features/search/search_controller_test.dart new file mode 100644 index 00000000..f9d90fe3 --- /dev/null +++ b/app/test/features/search/search_controller_test.dart @@ -0,0 +1,240 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/search/domain/search_controller.dart'; +import 'package:pipelines_app/features/search/domain/search_models.dart'; +import 'search_test_support.dart'; + +void main() { + test('empty query with no kind is idle and sends no request', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery(' '); + await pumpEventQueue(); + + expect(gateway.calls, isEmpty); + expect(controller.bodyKind, SearchBodyKind.idle); + expect(controller.results, isEmpty); + expect(controller.loaded, isFalse); + expect(controller.loading, isFalse); + }); + + test('the request carries the parsed query, kind and limit 0', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('t:run Plan TYPE:artifact'); + await pumpEventQueue(); + + expect(gateway.calls, hasLength(1)); + expect(gateway.lastSearch, { + 'query': 'Plan', + 'kind': 'artifact', + 'limit': 0, + }); + }); + + test( + 'a kind selector change removes type tokens and sends at once', + () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('plan t:run'); + await pumpEventQueue(); + expect(gateway.lastSearch['kind'], 'run'); + + controller.selectKind(SearchKind.pipeline); + await pumpEventQueue(); + + expect(controller.query.trim(), 'plan'); + expect(controller.query, isNot(contains('t:run'))); + expect(controller.selectedKind, SearchKind.pipeline); + expect(gateway.calls, hasLength(2)); + expect(gateway.lastSearch, { + 'query': 'plan', + 'kind': 'pipeline', + 'limit': 0, + }); + }, + ); + + test( + 'kind-only browsing sends a blank query and reports the empty copy', + () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.selectKind(SearchKind.pipeline); + await pumpEventQueue(); + expect(gateway.lastSearch, {'query': '', 'kind': 'pipeline', 'limit': 0}); + expect(controller.bodyKind, SearchBodyKind.searching); + + gateway.succeed(0, envelope(const [])); + await pumpEventQueue(); + expect(controller.bodyKind, SearchBodyKind.empty); + expect(controller.emptyMessage, 'No pipelines yet.'); + }, + ); + + test('the latest query wins and a stale reply is dropped', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('first'); + await pumpEventQueue(); + controller.updateQuery('second'); + await pumpEventQueue(); + expect(gateway.calls, hasLength(2)); + + gateway.succeed( + 0, + envelope([ + { + 'kind': 'run', + 'target': 'run:1', + 'run': {'id': 1}, + }, + ]), + ); + await pumpEventQueue(); + expect(controller.results, isEmpty); + expect(controller.loading, isTrue); + expect(controller.bodyKind, SearchBodyKind.searching); + + gateway.succeed( + 1, + envelope([ + { + 'kind': 'run', + 'target': 'run:2', + 'run': {'id': 2}, + }, + ]), + ); + await pumpEventQueue(); + expect(controller.results.single['target'], 'run:2'); + expect(controller.loading, isFalse); + expect(controller.bodyKind, SearchBodyKind.results); + }); + + test('truncation and scan bounds come from the server envelope', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('plan'); + await pumpEventQueue(); + gateway.succeed( + 0, + envelope( + [ + { + 'kind': 'field', + 'target': 'run:11:4:output', + 'field': {'run_id': 11}, + }, + ], + truncated: true, + scannedSteps: 2000, + scannedBytes: 1048576, + cap: 50, + ), + ); + await pumpEventQueue(); + + expect(controller.truncated, isTrue); + expect(controller.scannedSteps, 2000); + expect(controller.scannedBytes, 1048576); + expect(controller.cap, 50); + expect(controller.boundsText, contains('truncated')); + expect(controller.boundsText, contains('cap 50')); + expect(controller.boundsText, contains('2000 steps')); + }); + + test( + 'a truncated empty reply reports the scan bound instead of a complete empty', + () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('needle'); + await pumpEventQueue(); + gateway.succeed( + 0, + envelope( + const [], + truncated: true, + scannedSteps: 2000, + scannedBytes: 1048576, + cap: 50, + ), + ); + await pumpEventQueue(); + + expect(controller.bodyKind, SearchBodyKind.empty); + expect( + controller.emptyMessage, + 'No matches for "needle" within the server\'s scan limit.', + ); + expect(controller.boundsText, contains('Results truncated')); + expect(controller.boundsText, contains('0 results')); + expect(controller.boundsText, contains('2000 steps')); + expect(controller.boundsText, contains('scan limit 1.0 MiB')); + }, + ); + + test( + 'a complete empty reply stays a plain empty with no bounds line', + () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('needle'); + await pumpEventQueue(); + gateway.succeed(0, envelope(const [])); + await pumpEventQueue(); + + expect(controller.bodyKind, SearchBodyKind.empty); + expect(controller.emptyMessage, 'No matches for "needle".'); + expect(controller.boundsText, isNull); + }, + ); + + test('in-hand kind narrowing keeps the list honest while loading', () async { + final gateway = QueuedGateway(); + final controller = controllerFor(gateway); + addTearDown(controller.dispose); + + controller.updateQuery('plan'); + await pumpEventQueue(); + gateway.succeed( + 0, + envelope([ + { + 'kind': 'run', + 'target': 'run:1', + 'run': {'id': 1}, + }, + { + 'kind': 'pipeline', + 'target': 'pipeline:7', + 'pipeline': {'id': 7}, + }, + ]), + ); + await pumpEventQueue(); + expect(controller.shownResults, hasLength(2)); + + controller.selectKind(SearchKind.run); + await pumpEventQueue(); + expect(controller.shownResults, hasLength(1)); + expect(controller.shownResults.single['target'], 'run:1'); + }); +} diff --git a/app/test/features/search/search_query_test.dart b/app/test/features/search/search_query_test.dart new file mode 100644 index 00000000..942a9b73 --- /dev/null +++ b/app/test/features/search/search_query_test.dart @@ -0,0 +1,118 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/search/domain/search_models.dart'; +import 'package:pipelines_app/features/search/domain/search_query.dart'; + +const unsupported = + 'This server does not support search. Update the Pipelines server, then try again.'; + +void main() { + test('kind vocabulary is exactly the server vocabulary, All kinds first', () { + expect(SearchKind.values.map((kind) => kind.wire), [ + '', + 'pipeline', + 'run', + 'step', + 'field', + 'artifact', + 'version', + ]); + expect(SearchKind.values.map((kind) => kind.label), [ + 'All kinds', + 'Pipelines', + 'Runs', + 'Steps', + 'Fields', + 'Artifacts', + 'Versions', + ]); + expect(SearchKind.fromWire('run'), SearchKind.run); + expect(SearchKind.fromWire(''), SearchKind.all); + expect(SearchKind.fromWire('prompts'), SearchKind.all); + expect(SearchKind.fromWire(null), SearchKind.all); + }); + + test('both type aliases and kinds are case insensitive', () { + for (final kind in SearchKind.values.where( + (kind) => kind != SearchKind.all, + )) { + for (final prefix in ['t', 'type', 'T', 'TyPe']) { + final parsed = parseSearchQuery( + '$prefix:${kind.wire.toUpperCase()} plan', + ); + expect(parsed.query, ' plan'); + expect(parsed.kind, kind); + expect(parsed.hasType, isTrue); + } + } + }); + + test('normal, quoted and unsupported text is preserved byte for byte', () { + const preserved = [ + ' ordinary text\twith\nspacing ', + '"t:pipeline" "hello world"', + "'type:artifact'", + '"escaped \\" t:run"', + '"unclosed t:run', + 't:prompt type:unknown t: t:PIPELINES', + 'not:t:run t:run,', + 'prefix"t:run"', + '\\t:run', + ]; + for (final query in preserved) { + final parsed = parseSearchQuery(query, SearchKind.field); + expect(parsed.query, query); + expect(parsed.kind, SearchKind.field); + expect(parsed.hasType, isFalse); + } + expect( + parseSearchQuery('t:artifact "t:pipeline" report').query, + ' "t:pipeline" report', + ); + }); + + test('last supported token wins over the selector; unknown tokens stay', () { + final parsed = parseSearchQuery( + 't:run plan TYPE:artifact t:unknown', + SearchKind.pipeline, + ); + expect(parsed.query, ' plan t:unknown'); + expect(parsed.kind, SearchKind.artifact); + expect(parsed.hasType, isTrue); + expect(parseSearchQuery('plan', SearchKind.step).kind, SearchKind.step); + }); + + test('type-only query is distinguishable from literal and blank input', () { + final typed = parseSearchQuery('t:pipeline'); + expect(typed.query, ''); + expect(typed.kind, SearchKind.pipeline); + expect(typed.hasType, isTrue); + final blank = parseSearchQuery(''); + expect(blank.query, ''); + expect(blank.kind, SearchKind.all); + expect(blank.hasType, isFalse); + }); + + test('blank text is sendable only with a supported nonempty kind', () { + for (final kind in SearchKind.values) { + expect(searchQuerySendable(' \n\t ', kind), kind != SearchKind.all); + } + expect(searchQuerySendable('', SearchKind.all), isFalse); + expect(searchQuerySendable('plan', SearchKind.all), isTrue); + expect(searchQuerySendable(' plan ', SearchKind.all), isTrue); + }); + + test( + 'failure copy distinguishes an unsupported server from a plain error', + () { + expect(searchFailureText(null), unsupported); + expect(searchFailureText(' '), unsupported); + expect(searchFailureText('unknown command: search'), unsupported); + expect(searchFailureText('unsupported command'), unsupported); + expect(searchFailureText('boom'), 'boom'); + expect( + searchFailureText('request timed out after 30000ms'), + 'request timed out after 30000ms', + ); + }, + ); +} diff --git a/app/test/features/search/search_repository_test.dart b/app/test/features/search/search_repository_test.dart new file mode 100644 index 00000000..1760b363 --- /dev/null +++ b/app/test/features/search/search_repository_test.dart @@ -0,0 +1,106 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/search/data/search_repository.dart'; +import 'package:pipelines_app/features/search/domain/search_models.dart'; + +class RecordingGateway implements ApiGateway { + String? type; + JsonMap fields = {}; + JsonMap reply = {}; + Object? failure; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + this.type = type; + this.fields = Map.of(fields); + if (failure case final error?) throw error; + return reply; + } + + @override + Stream get frames => const Stream.empty(); +} + +void main() { + test( + 'search sends exactly search/query/kind/limit and parses bounds', + () async { + final gateway = RecordingGateway() + ..reply = { + 'search_results': { + 'query': 'plan', + 'kind': 'run', + 'results': [ + { + 'kind': 'run', + 'target': 'run:11', + 'run': {'id': 11}, + }, + ], + 'truncated': true, + 'scanned_steps': 27, + 'scanned_bytes': 4096, + 'cap': 50, + 'scan_bound_bytes': 1048576, + }, + }; + final repository = SearchRepository(gateway); + + final response = await repository.search( + query: 'plan', + kind: SearchKind.run, + ); + + expect(gateway.type, 'search'); + expect(gateway.fields, { + 'search': {'query': 'plan', 'kind': 'run', 'limit': 0}, + }); + expect(response, isNotNull); + expect(response!.query, 'plan'); + expect(response.kind, SearchKind.run); + expect(response.results.single['target'], 'run:11'); + expect(response.truncated, isTrue); + expect(response.scannedSteps, 27); + expect(response.scannedBytes, 4096); + expect(response.cap, 50); + expect(response.scanBoundBytes, 1048576); + }, + ); + + test('all-kinds search still sends the empty kind field', () async { + final gateway = RecordingGateway() + ..reply = { + 'search_results': {'results': []}, + }; + await SearchRepository(gateway).search(query: 'plan', kind: SearchKind.all); + expect(gateway.fields, { + 'search': {'query': 'plan', 'kind': '', 'limit': 0}, + }); + }); + + test( + 'a reply without search_results is null, not an empty success', + () async { + final gateway = RecordingGateway()..reply = {'type': 'pong'}; + final response = await SearchRepository( + gateway, + ).search(query: 'plan', kind: SearchKind.all); + expect(response, isNull); + }, + ); + + test('server refusals propagate to the caller unchanged', () async { + final gateway = RecordingGateway() + ..failure = StateError('permission denied'); + await expectLater( + SearchRepository(gateway).search(query: 'plan', kind: SearchKind.all), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'permission denied', + ), + ), + ); + }); +} diff --git a/app/test/features/search/search_row_test.dart b/app/test/features/search/search_row_test.dart new file mode 100644 index 00000000..086f2246 --- /dev/null +++ b/app/test/features/search/search_row_test.dart @@ -0,0 +1,161 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/search/domain/search_row.dart'; + +JsonMap pipelineHit([JsonMap overrides = const {}]) => { + 'kind': 'pipeline', + 'target': 'pipeline:7', + 'pipeline': { + 'id': 7, + 'name': 'release', + 'version': 3, + 'stages': 4, + ...overrides, + }, +}; + +JsonMap versionHit() => { + 'kind': 'version', + 'target': 'pipeline:9:v2', + 'recency': '2026-01-01T00:00:00Z', + 'version': { + 'pipeline_id': 9, + 'version': 2, + 'content_hash': 'abc', + 'created_at': '2026-01-01T00:00:00Z', + }, +}; + +JsonMap runHit([JsonMap overrides = const {}]) => { + 'kind': 'run', + 'target': 'run:11', + 'run': { + 'id': 11, + 'pipeline_name': 'release', + 'status': 'succeeded', + 'created_at': '2026-01-01T00:00:00Z', + ...overrides, + }, +}; + +JsonMap stepHit([JsonMap overrides = const {}]) => { + 'kind': 'step', + 'target': 'run:11:4', + 'step': { + 'run_id': 11, + 'sequence': 4, + 'stage': 'builder', + 'visit': 2, + 'outcome': 'success', + ...overrides, + }, +}; + +JsonMap fieldHit([JsonMap overrides = const {}]) => { + 'kind': 'field', + 'target': 'run:11:4:output', + 'matched_field': 'output', + 'field': { + 'run_id': 11, + 'sequence': 4, + 'field': 'output', + 'snippet': 'the release is ready', + ...overrides, + }, +}; + +JsonMap artifactHit([JsonMap overrides = const {}]) => { + 'kind': 'artifact', + 'target': '/artifacts/11/4/notes.md', + 'artifact': { + 'run_id': 11, + 'sequence': 4, + 'name': 'notes.md', + 'content_type': 'text/markdown', + 'size_bytes': 2048, + ...overrides, + }, +}; + +void main() { + test('per-kind rows mirror the browser titles and secondary lines', () { + final pipeline = searchRowView(pipelineHit(), 'release'); + expect(pipeline.title, 'release'); + expect(pipeline.secondary, 'pipeline 7 · v3 · 4 stages'); + expect(pipeline.kindLabel, 'Pipeline'); + expect(pipeline.target, 'pipeline:7'); + + final blankName = searchRowView(pipelineHit({'name': ' '}), 'x'); + expect(blankName.title, 'pipeline 7'); + + final version = searchRowView(versionHit(), 'release'); + expect(version.title, 'pipeline 9 · v2'); + expect(version.secondary, startsWith('content abc · ')); + expect(version.recency, isNotNull); + + final run = searchRowView(runHit(), 'release'); + expect(run.title, 'run #11 · release'); + expect(run.secondary, startsWith('succeeded · ')); + expect(run.secondary.split(' · '), hasLength(2)); + + final unnamed = searchRowView(runHit({'pipeline_name': ''}), ''); + expect(unnamed.title, 'run #11'); + + final step = searchRowView(stepHit({'target': '#success'}), ''); + expect(step.title, 'run #11 · builder visit 2'); + expect(step.secondary, 'success · → #success'); + + final artifact = searchRowView(artifactHit(), 'notes'); + expect(artifact.title, 'notes.md'); + expect(artifact.secondary, 'run #11 · step 4 · text/markdown · 2.0 KiB'); + }); + + test('a field snippet marks the first case-insensitive query occurrence', () { + final row = searchRowView(fieldHit(), 'RELEASE'); + expect(row.snippet, 'the release is ready'); + expect(row.snippetSpans.map((span) => (span.text, span.matched)), [ + ('the ', false), + ('release', true), + (' is ready', false), + ]); + expect(row.snippetSpans.where((span) => span.matched), hasLength(1)); + + final absent = searchRowView(fieldHit({'snippet': 'no match'}), 'absent'); + expect(absent.snippetSpans.single.matched, isFalse); + expect(absent.snippetSpans.single.text, 'no match'); + + final blank = searchRowView(fieldHit({'snippet': ''}), 'release'); + expect(blank.snippetSpans, isEmpty); + }); + + test('unknown or targetless hits are read-only and never open a guess', () { + final unknown = searchRowView({ + 'kind': 'future_kind', + 'target': 'widget:7', + }, 'x'); + expect(unknown.title, 'widget:7'); + expect(unknown.secondary, 'kind "future_kind" · read-only'); + expect(unknown.openable, isFalse); + expect(unknown.target, isNull); + expect(unknown.kindLabel, 'Unrecognised result'); + + final targetless = searchRowView({ + 'kind': 'run', + 'run': {'id': 11}, + }, 'x'); + expect(targetless.openable, isFalse); + expect(targetless.target, isNull); + + expect(searchRowView(pipelineHit(), '').openable, isTrue); + expect(searchRowView(versionHit(), '').openable, isTrue); + expect(searchRowView(artifactHit(), '').openable, isTrue); + }); + + test('byte sizes use the shared binary rendering', () { + expect(humanBytes(0), '0 B'); + expect(humanBytes(1023), '1023 B'); + expect(humanBytes(1024), '1.0 KiB'); + expect(humanBytes(2048), '2.0 KiB'); + expect(humanBytes(1048576), '1.0 MiB'); + }); +} diff --git a/app/test/features/search/search_screen_states_test.dart b/app/test/features/search/search_screen_states_test.dart new file mode 100644 index 00000000..71292861 --- /dev/null +++ b/app/test/features/search/search_screen_states_test.dart @@ -0,0 +1,146 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/search/search_screen.dart'; + +class RecordingGateway implements ApiGateway { + RecordingGateway(this.reply); + + final JsonMap Function(String query, String kind) reply; + final calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add(Map.of(fields)); + final search = Map.from(fields['search'] as Map); + return reply(search['query'] as String, search['kind'] as String); + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap response( + List results, { + bool truncated = false, + int scannedSteps = 2, + int scannedBytes = 128, +}) => { + 'search_results': { + 'results': results, + 'truncated': truncated, + 'scanned_steps': scannedSteps, + 'scanned_bytes': scannedBytes, + 'cap': 50, + 'scan_bound_bytes': 1 << 20, + }, +}; + +final pipeline = { + 'kind': 'pipeline', + 'target': 'pipeline:7', + 'pipeline': {'id': 7, 'name': 'Release planner', 'version': 3, 'stages': 4}, +}; + +Widget material(Widget child) => MaterialApp(home: child); + +void main() { + testWidgets( + 'a fresh screen sends no request and idle is not an empty result', + (tester) async { + final gateway = RecordingGateway((_, _) => response([pipeline])); + await tester.pumpWidget( + material(SearchScreen(gateway: gateway, onOpen: (_) {})), + ); + + expect(gateway.calls, isEmpty); + expect( + find.text('Search pipelines, runs and artifacts.'), + findsOneWidget, + ); + expect(find.textContaining('No matches'), findsNothing); + }, + ); + + testWidgets('an empty server result shows the query-specific empty copy', ( + tester, + ) async { + final gateway = RecordingGateway((_, _) => response(const [])); + await tester.pumpWidget( + material(SearchScreen(gateway: gateway, onOpen: (_) {})), + ); + + await tester.enterText(find.byKey(const ValueKey('search.field')), 'zzz'); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pumpAndSettle(); + + expect(gateway.calls, hasLength(1)); + expect(find.text('No matches for "zzz".'), findsOneWidget); + expect(find.text('Searching…'), findsNothing); + }); + + testWidgets( + 'a truncated empty reply keeps the server scan warning on screen', + (tester) async { + final gateway = RecordingGateway( + (_, _) => response( + const [], + truncated: true, + scannedSteps: 2000, + scannedBytes: 1048576, + ), + ); + await tester.pumpWidget( + material(SearchScreen(gateway: gateway, onOpen: (_) {})), + ); + + await tester.enterText( + find.byKey(const ValueKey('search.field')), + 'needle', + ); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pumpAndSettle(); + + expect( + find.text('No matches for "needle" within the server\'s scan limit.'), + findsOneWidget, + ); + expect(find.textContaining('Results truncated'), findsOneWidget); + expect(find.textContaining('scanned 2000 steps'), findsOneWidget); + expect(find.textContaining('scan limit 1.0 MiB'), findsOneWidget); + }, + ); + + testWidgets('changing Kind clears a typed token and requests the new kind', ( + tester, + ) async { + tester.view.physicalSize = const Size(390, 844); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final gateway = RecordingGateway((_, _) => response([pipeline])); + await tester.pumpWidget( + material(SearchScreen(gateway: gateway, onOpen: (_) {})), + ); + + await tester.enterText( + find.byKey(const ValueKey('search.field')), + 'plan t:run', + ); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pumpAndSettle(); + expect((gateway.calls.single['search'] as Map)['kind'], 'run'); + + await tester.tap(find.byKey(const ValueKey('search.kind'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Pipelines').last); + await tester.pumpAndSettle(); + + final field = tester.widget( + find.byKey(const ValueKey('search.field')), + ); + expect(field.controller!.text.trim(), 'plan'); + expect(field.controller!.text, isNot(contains('t:run'))); + expect((gateway.calls.last['search'] as Map)['kind'], 'pipeline'); + }); +} diff --git a/app/test/features/search/search_screen_test.dart b/app/test/features/search/search_screen_test.dart new file mode 100644 index 00000000..7c1b7eeb --- /dev/null +++ b/app/test/features/search/search_screen_test.dart @@ -0,0 +1,223 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/search/domain/search_models.dart'; +import 'package:pipelines_app/features/search/search_screen.dart'; + +class ImmediateGateway implements ApiGateway { + ImmediateGateway(this.reply); + + final JsonMap Function(String query, String kind) reply; + final calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add(Map.of(fields)); + final search = Map.from(fields['search'] as Map); + return reply(search['query'] as String, search['kind'] as String); + } + + @override + Stream get frames => const Stream.empty(); +} + +class FailingThenSucceedingGateway implements ApiGateway { + FailingThenSucceedingGateway(this.success); + + final JsonMap success; + var calls = 0; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls++; + if (calls == 1) throw StateError('unknown command: search'); + return success; + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap hit({ + required String kind, + required String target, + required Map payload, +}) => {'kind': kind, 'target': target, ...payload}; + +JsonMap response(List results) => { + 'search_results': { + 'results': results, + 'truncated': false, + 'scanned_steps': 4, + 'scanned_bytes': 512, + 'cap': 50, + 'scan_bound_bytes': 1 << 20, + }, +}; + +final pipeline = hit( + kind: 'pipeline', + target: 'pipeline:7', + payload: { + 'pipeline': {'id': 7, 'name': 'Release planner', 'version': 3, 'stages': 4}, + }, +); +final field = hit( + kind: 'field', + target: 'run:11:4:output', + payload: { + 'matched_field': 'output', + 'field': { + 'run_id': 11, + 'sequence': 4, + 'field': 'output', + 'snippet': 'the release is ready', + }, + }, +); + +void useNarrowSurface(WidgetTester tester) { + tester.view.physicalSize = const Size(390, 844); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); +} + +Widget largeText(Widget child) => MediaQuery( + data: const MediaQueryData(textScaler: TextScaler.linear(2)), + child: child, +); + +Future search(WidgetTester tester, String query) async { + await tester.enterText(find.byKey(const ValueKey('search.field')), query); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pumpAndSettle(); +} + +void main() { + for (final width in [390.0, 1000.0]) { + testWidgets( + 'Material search is native and usable at width $width and 2x text', + (tester) async { + useNarrowSurface(tester); + tester.view.physicalSize = Size(width, 844); + final gateway = ImmediateGateway((_, _) => response([pipeline, field])); + JsonMap? opened; + await tester.pumpWidget( + MaterialApp( + home: largeText( + SearchScreen( + gateway: gateway, + onOpen: (value) => opened = value, + cupertino: false, + ), + ), + ), + ); + + expect(find.byType(SearchBar), findsOneWidget); + expect(find.byType(DropdownButton), findsOneWidget); + expect(find.text('All kinds'), findsOneWidget); + expect(gateway.calls, isEmpty); + + await search(tester, 'release'); + + expect(gateway.calls.single, { + 'search': {'query': 'release', 'kind': '', 'limit': 0}, + }); + expect(find.text('Release planner'), findsOneWidget); + expect(find.textContaining('the release is ready'), findsOneWidget); + expect(find.textContaining('4 results'), findsNothing); + expect(tester.takeException(), isNull); + + await tester.tap( + find.byKey(const ValueKey('search.result.pipeline:7')), + ); + expect(opened?['target'], 'pipeline:7'); + expect(opened?['kind'], 'pipeline'); + }, + ); + } + + testWidgets( + 'Cupertino search uses native controls and opens the real target', + (tester) async { + useNarrowSurface(tester); + final gateway = ImmediateGateway((_, _) => response([pipeline])); + JsonMap? opened; + await tester.pumpWidget( + CupertinoApp( + home: largeText( + SearchScreen( + gateway: gateway, + onOpen: (value) => opened = value, + cupertino: true, + ), + ), + ), + ); + + expect(find.byType(CupertinoSearchTextField), findsOneWidget); + await search(tester, 'release'); + + expect(find.text('Release planner'), findsOneWidget); + expect(tester.takeException(), isNull); + await tester.tap(find.byKey(const ValueKey('search.result.pipeline:7'))); + expect(opened?['target'], 'pipeline:7'); + }, + ); + + testWidgets('a read-only hit cannot be opened', (tester) async { + useNarrowSurface(tester); + final unknown = hit( + kind: 'future_kind', + target: 'widget:7', + payload: const {}, + ); + final gateway = ImmediateGateway((_, _) => response([unknown])); + JsonMap? opened; + await tester.pumpWidget( + MaterialApp( + home: SearchScreen( + gateway: gateway, + onOpen: (value) => opened = value, + cupertino: false, + ), + ), + ); + await search(tester, 'widget'); + + expect(find.textContaining('read-only'), findsOneWidget); + await tester.tap(find.byKey(const ValueKey('search.result.widget:7'))); + expect(opened, isNull); + }); + + testWidgets('an unsupported server shows its sentence and retry recovers', ( + tester, + ) async { + useNarrowSurface(tester); + final gateway = FailingThenSucceedingGateway(response([pipeline])); + await tester.pumpWidget( + MaterialApp( + home: SearchScreen(gateway: gateway, onOpen: (_) {}, cupertino: false), + ), + ); + await search(tester, 'release'); + + expect( + find.text( + 'This server does not support search. Update the Pipelines server, then try again.', + ), + findsOneWidget, + ); + expect(find.byKey(const ValueKey('search.retry')), findsOneWidget); + + await tester.tap(find.byKey(const ValueKey('search.retry'))); + await tester.pumpAndSettle(); + + expect(gateway.calls, 2); + expect(find.text('Release planner'), findsOneWidget); + expect(find.byKey(const ValueKey('search.retry')), findsNothing); + }); +} diff --git a/app/test/features/search/search_test_support.dart b/app/test/features/search/search_test_support.dart new file mode 100644 index 00000000..fdad7425 --- /dev/null +++ b/app/test/features/search/search_test_support.dart @@ -0,0 +1,50 @@ +import 'dart:async'; + +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/search/data/search_repository.dart'; +import 'package:pipelines_app/features/search/domain/search_controller.dart'; + +class QueuedGateway implements ApiGateway { + final calls = []; + final pending = >[]; + + @override + Future call(String type, [JsonMap fields = const {}]) { + calls.add(Map.of(fields)); + final completer = Completer(); + pending.add(completer); + return completer.future; + } + + @override + Stream get frames => const Stream.empty(); + + void succeed(int index, JsonMap reply) => pending[index].complete(reply); + void fail(int index, Object error) => pending[index].completeError(error); + + JsonMap get lastSearch => + Map.from((calls.last['search'] as Map)); +} + +JsonMap envelope( + List results, { + bool truncated = false, + int scannedSteps = 0, + int scannedBytes = 0, + int cap = 50, + int scanBoundBytes = 1 << 20, +}) => { + 'search_results': { + 'results': results, + 'truncated': truncated, + 'scanned_steps': scannedSteps, + 'scanned_bytes': scannedBytes, + 'cap': cap, + 'scan_bound_bytes': scanBoundBytes, + }, +}; + +OmniSearchController controllerFor(ApiGateway gateway) => OmniSearchController( + repository: SearchRepository(gateway), + debounce: Duration.zero, +); diff --git a/app/tool/search_fixture/main.dart b/app/tool/search_fixture/main.dart new file mode 100644 index 00000000..1328cd07 --- /dev/null +++ b/app/tool/search_fixture/main.dart @@ -0,0 +1,190 @@ +// Web-only fixture entrypoint for rendered search evidence. It is not part of +// the application's `main.dart`; build it explicitly with: +// flutter build web -t tool/search_fixture/main.dart +// `?cupertino=1` renders the same screen inside a CupertinoApp. +import 'dart:convert'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/search/search_screen.dart'; + +void main() { + final cupertino = Uri.base.queryParameters['cupertino'] == '1'; + runApp( + cupertino + ? const CupertinoApp( + title: 'Search fixture', + home: _FixtureHost(cupertino: true), + ) + : const MaterialApp( + title: 'Search fixture', + home: _FixtureHost(cupertino: false), + ), + ); +} + +class _FixtureHost extends StatelessWidget { + const _FixtureHost({required this.cupertino}); + + final bool cupertino; + + @override + Widget build(BuildContext context) => SearchScreen( + gateway: const _FixtureGateway(), + cupertino: cupertino, + onOpen: (hit) { + final route = cupertino + ? CupertinoPageRoute( + builder: (_) => _Opened(hit: hit, cupertino: true), + ) + : MaterialPageRoute( + builder: (_) => _Opened(hit: hit, cupertino: false), + ); + Navigator.of(context).push(route); + }, + ); +} + +class _Opened extends StatelessWidget { + const _Opened({required this.hit, required this.cupertino}); + + final JsonMap hit; + final bool cupertino; + + @override + Widget build(BuildContext context) { + final body = Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text( + 'Opened ${hit['kind']} target: ${hit['target']}', + textAlign: TextAlign.center, + ), + ), + ); + if (cupertino) { + return CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar(middle: Text('Opened')), + child: body, + ); + } + return Scaffold( + appBar: AppBar(title: const Text('Opened')), + body: body, + ); + } +} + +class _FixtureGateway implements ApiGateway { + const _FixtureGateway(); + + @override + Future call(String type, [JsonMap fields = const {}]) async { + if (type != 'search') throw StateError('unexpected request: $type'); + final request = Map.from(fields['search'] as Map); + final query = '${request['query'] ?? ''}'.trim().toLowerCase(); + final kind = '${request['kind'] ?? ''}'; + await Future.delayed(const Duration(milliseconds: 180)); + var hits = _fixtureHits + .where((hit) { + if (kind.isNotEmpty && hit['kind'] != kind) return false; + if (query.isEmpty) return true; + return jsonEncode(hit).toLowerCase().contains(query); + }) + .toList(growable: false); + return { + 'search_results': { + 'query': request['query'], + 'kind': kind, + 'results': hits, + 'truncated': true, + 'scanned_steps': 2000, + 'scanned_bytes': 1048576, + 'cap': 50, + 'scan_bound_bytes': 1048576, + }, + }; + } + + @override + Stream get frames => const Stream.empty(); +} + +const _fixtureHits = [ + { + 'kind': 'pipeline', + 'target': 'pipeline:24', + 'score': 3, + 'recency': '2026-10-20T09:18:00Z', + 'pipeline': {'id': 24, 'name': 'Plan and land', 'version': 5, 'stages': 4}, + }, + { + 'kind': 'run', + 'target': 'run:457', + 'score': 2, + 'recency': '2026-10-20T08:42:00Z', + 'run': { + 'id': 457, + 'pipeline_name': 'Plan and land', + 'status': 'succeeded', + 'workspace': '/Users/alan/repos/pipelines', + 'created_at': '2026-10-20T08:12:00Z', + 'finished_at': '2026-10-20T08:42:00Z', + }, + }, + { + 'kind': 'field', + 'target': 'run:457:3:input', + 'score': 1, + 'matched_field': 'input', + 'recency': '2026-10-20T08:20:00Z', + 'field': { + 'run_id': 457, + 'sequence': 3, + 'field': 'input', + 'snippet': 'Plan the change before implementing it', + }, + }, + { + 'kind': 'artifact', + 'target': '/artifacts/457/2/plan.md', + 'score': 1, + 'recency': '2026-10-20T08:24:00Z', + 'artifact': { + 'run_id': 457, + 'sequence': 2, + 'name': 'plan.md', + 'content_type': 'text/markdown', + 'size_bytes': 2048, + 'url': '/artifacts/457/2/plan.md', + }, + }, + { + 'kind': 'version', + 'target': 'pipeline:22:v6', + 'score': 2, + 'recency': '2026-10-18T16:05:00Z', + 'version': { + 'pipeline_id': 22, + 'version': 6, + 'content_hash': '9f2c1ad', + 'created_at': '2026-10-18T16:05:00Z', + }, + }, + { + 'kind': 'step', + 'target': 'run:457:1', + 'score': 1, + 'recency': '2026-10-20T08:14:00Z', + 'step': { + 'run_id': 457, + 'sequence': 1, + 'stage': 'planner', + 'visit': 1, + 'outcome': 'success', + 'target': '#success', + 'diagnostic': 'plan accepted', + }, + }, +]; diff --git a/app/tool/search_probe.mjs b/app/tool/search_probe.mjs new file mode 100644 index 00000000..172efb1f --- /dev/null +++ b/app/tool/search_probe.mjs @@ -0,0 +1,246 @@ +// Real Chrome evidence for the Flutter search screen. Serves the fixture build +// from build/web on an OS-assigned loopback port and drives the page through +// Chrome DevTools Protocol, like tool/shell_probe.mjs. Usage: +// flutter build web -t tool/search_fixture/main.dart +// OPENCODE_ARTIFACT_DIR= node tool/search_probe.mjs +import { createServer } from 'node:http'; +import { readFile, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { setTimeout as delay } from 'node:timers/promises'; +import { join, extname, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; + +const root = join(process.cwd(), 'build/web'); +const artifactDir = process.env.OPENCODE_ARTIFACT_DIR; +if (!artifactDir) throw new Error('OPENCODE_ARTIFACT_DIR is required for captures'); +const mime = { + '.html': 'text/html', + '.js': 'text/javascript', + '.json': 'application/json', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.ico': 'image/x-icon', + '.ttf': 'font/ttf', + '.otf': 'font/otf', +}; +const server = createServer(async (req, res) => { + try { + const path = resolve( + root, + '.' + decodeURIComponent(new URL(req.url, 'http://localhost').pathname), + ); + if (path !== root && !path.startsWith(root + sep)) { + return res.writeHead(403).end(); + } + const filePath = + path === root || path.endsWith('/') ? join(path, 'index.html') : path; + const file = await readFile(filePath); + res + .writeHead(200, { + 'content-type': mime[extname(filePath)] ?? 'application/octet-stream', + }) + .end(file); + } catch { + res.writeHead(404).end('not found'); + } +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const port = server.address().port; +const profile = await mkdtemp(join(tmpdir(), 'x1-search-chrome-')); +const chrome = spawn( + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + [ + '--headless=new', + '--no-first-run', + '--no-default-browser-check', + '--disable-gpu', + '--remote-debugging-port=0', + `--user-data-dir=${profile}`, + 'about:blank', + ], + { stdio: ['ignore', 'ignore', 'pipe'] }, +); +let stderr = ''; +chrome.stderr.on('data', (data) => { + stderr += data; +}); +const waitFor = async (fn) => { + for (let i = 0; i < 100; i++) { + const value = await fn(); + if (value) return value; + await delay(100); + } + throw new Error('Timed out waiting for Chrome DevTools'); +}; +const result = { captures: [], evidence: {} }; +let ws; +try { + const endpoint = await waitFor(() => + stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1], + ); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', (event) => { + const msg = JSON.parse(event.data); + if (msg.id && pending.has(msg.id)) { + pending.get(msg.id)(msg); + pending.delete(msg.id); + } + }); + const send = (method, params = {}, sessionId) => + new Promise((resolve) => { + const callId = ++id; + pending.set(callId, resolve); + ws.send( + JSON.stringify({ + id: callId, + method, + params, + ...(sessionId ? { sessionId } : {}), + }), + ); + }); + const created = await send('Target.createTarget', { url: 'about:blank' }); + if (!created.result) { + throw new Error(`Target creation failed: ${JSON.stringify(created)}`); + } + const target = created.result.targetId; + const session = ( + await send('Target.attachToTarget', { targetId: target, flatten: true }) + ).result.sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + const evaluate = async (expression) => { + const response = await send( + 'Runtime.evaluate', + { expression, returnByValue: true, awaitPromise: true }, + session, + ); + if (response.error) { + throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`); + } + return response.result?.result?.value; + }; + const clickMatching = (needle) => + evaluate(`(() => { + const needle = ${JSON.stringify(needle)}; + const nodes = [...document.querySelectorAll('flt-semantics')]; + const e = nodes.find(x => x.hasAttribute('flt-tappable') && + (x.getAttribute('aria-label') || x.innerText || '').includes(needle)); + if (!e) return false; + e.click(); + return true; + })()`); + const capture = async (name, width, height) => { + await send( + 'Emulation.setDeviceMetricsOverride', + { width, height, deviceScaleFactor: 1, mobile: width < 600 }, + session, + ); + await delay(350); + const data = ( + await send( + 'Page.captureScreenshot', + { format: 'png', captureBeyondViewport: false }, + session, + ) + ).result.data; + const path = join(artifactDir, `${name}.png`); + await writeFile(path, Buffer.from(data, 'base64')); + result.captures.push(path); + }; + const load = async (url, width, height) => { + await send( + 'Emulation.setDeviceMetricsOverride', + { width, height, deviceScaleFactor: 1, mobile: width < 600 }, + session, + ); + const navigation = await send('Page.navigate', { url }, session); + if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); + await delay(3500); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(900); + }; + const typeText = async (query) => { + const focused = await evaluate(`(() => { + const input = document.querySelector('input[type="search"]') || document.querySelector('input.flt-text-editing'); + if (!input) return false; input.focus(); return true; })()`); + if (!focused) throw new Error('Search input not found'); + await delay(400); + const inserted = await send('Input.insertText', { text: query }, session); + if (inserted.error) throw new Error(JSON.stringify(inserted)); + await delay(1400); + return (await evaluate('document.body.innerText')).trim(); + }; + const typeQuery = async (query) => { + const trimmed = await typeText(query); + if (!trimmed.includes('Plan and land')) { + throw new Error(`Results missing after typing: ${JSON.stringify(trimmed)}`); + } + return { + typed: query, + resultTitles: ['Plan and land', 'run #457 · Plan and land', 'run #457 · step 3 · input', + 'plan.md', 'run #457 · planner visit 1'].filter((title) => trimmed.includes(title)), + showsServerSnippet: trimmed.includes('Plan the change before implementing it'), + showsRecency: /\d{1,2} [A-Z][a-z]{2} \d{2}:\d{2}/.test(trimmed), + showsBounds: + trimmed.includes('Results truncated') && + trimmed.includes('cap 50') && + trimmed.includes('scanned 2000 steps'), + }; + }; + const typeTruncatedEmpty = async (query) => { + const text = await typeText(query); + const emptyCopy = `No matches for "${query}" within the server's scan limit.`; + const missing = [ + emptyCopy, 'Results truncated', '0 results', + 'scanned 2000 steps', 'scan limit 1.0 MiB', + ].filter((needle) => !text.includes(needle)); + if (missing.length) throw new Error(`Truncated empty missing ${JSON.stringify(missing)}`); + return { typed: query, emptyCopy, showsTruncationWarning: true, showsBounds: true }; + }; + + const base = `http://127.0.0.1:${port}/`; + await load(base, 390, 844); + result.evidence.materialPhone = await typeQuery('plan'); + await capture('x1-search-material-phone', 390, 844); + if (!(await clickMatching('Plan and land'))) { + throw new Error('Could not open the pipeline row'); + } + await delay(700); + const opened = await evaluate('document.body.innerText'); + if (!opened.includes('pipeline:24')) { + throw new Error(`Opened target missing: ${JSON.stringify(opened)}`); + } + result.evidence.opened = 'pipeline:24'; + await capture('x1-search-open-target', 390, 844); + + await load(base, 1280, 800); + result.evidence.materialDesktop = await typeQuery('plan'); + await capture('x1-search-material-desktop', 1280, 800); + + await load(`${base}?cupertino=1`, 390, 844); + result.evidence.cupertinoPhone = await typeQuery('plan'); + await capture('x1-search-cupertino-phone', 390, 844); + + await load(base, 390, 844); + result.evidence.materialTruncatedEmpty = await typeTruncatedEmpty('needle'); + await capture('x1-search-truncated-empty', 390, 844); + + await load(`${base}?cupertino=1`, 390, 844); + result.evidence.cupertinoTruncatedEmpty = + await typeTruncatedEmpty('needle'); + await capture('x1-search-truncated-empty-cupertino', 390, 844); + + console.log(JSON.stringify(result, null, 2)); +} finally { + ws?.close(); + chrome.kill('SIGTERM'); + await Promise.race([once(chrome, 'exit'), delay(3000)]); + server.close(); + await rm(profile, { recursive: true, force: true }); +}