feat(app): open Search from the shell over the shared session

This commit is contained in:
2026-10-21 23:42:41 +01:00
parent a897065fec
commit fd380ef2f4
10 changed files with 1215 additions and 14 deletions
+4 -1
View File
@@ -2,7 +2,7 @@
///
/// The set mirrors [AppDestination] but stays free of widget imports so the
/// parser and serialiser can be exercised without a Flutter host.
enum AppRouteKind { pipelines, runs, chat, settings }
enum AppRouteKind { pipelines, runs, chat, search, settings }
/// One page route: a destination plus the run it opens, if any.
///
@@ -15,6 +15,7 @@ class AppRoute {
static const pipelines = AppRoute(AppRouteKind.pipelines);
static const runs = AppRoute(AppRouteKind.runs);
static const chat = AppRoute(AppRouteKind.chat);
static const search = AppRoute(AppRouteKind.search);
static const settings = AppRoute(AppRouteKind.settings);
static const run = _RunRouteFactory();
@@ -40,6 +41,7 @@ class AppRoute {
chatSessionId == null || !isChatSessionId(chatSessionId!)
? '/chat'
: '/chat/${Uri.encodeComponent(chatSessionId!)}',
AppRouteKind.search => '/search',
AppRouteKind.settings => '/settings',
};
@@ -77,6 +79,7 @@ class AppRoute {
'runs' when segments.length == 2 => _runRoute(segments[1]),
'chat' when segments.length == 1 => chat,
'chat' when segments.length == 2 => _chatRoute(segments[1]),
'search' when segments.length == 1 => search,
'settings' when segments.length == 1 => settings,
_ => pipelines,
};
+53 -11
View File
@@ -29,11 +29,20 @@ class AppRouterDelegate extends RouterDelegate<AppRoute> with ChangeNotifier {
required this.onPopToRuns,
required this.onPopToChat,
required this.cupertino,
this.searchBuilder,
AppRoute initial = AppRoute.pipelines,
}) : _route = initial;
}) : _route = initial,
_searchReturn = initial.kind == AppRouteKind.search
? AppRoute.pipelines
: initial;
final Widget Function(BuildContext context, AppRoute route) builder;
/// The Search page above the shell. Search is transient chrome, not a fifth
/// tab: the shell stays mounted underneath so closing restores its loaded
/// state and selection, and the standard navigation bar supplies Back.
final Widget Function(BuildContext context)? searchBuilder;
/// Called when a system Back belongs to the Runs detail, not the app stack.
final VoidCallback onPopToRuns;
@@ -44,33 +53,62 @@ class AppRouterDelegate extends RouterDelegate<AppRoute> with ChangeNotifier {
final _navigatorKey = GlobalKey<NavigatorState>();
static const _pageKey = ValueKey<String>('pipelines-shell');
static const _searchPageKey = ValueKey<String>('app-search');
AppRoute _route;
/// The destination that was open before Search, restored on close.
AppRoute _searchReturn;
AppRoute get route => _route;
bool get searchOpen => _route.kind == AppRouteKind.search;
@override
AppRoute get currentConfiguration => _route;
/// A single-page Navigator supplies the Overlay, overlay portals and route
/// context that native controls (action sheets, tooltips) require. The page
/// key is stable, so changing the route updates the shell in place instead of
/// remounting it and losing the open run.
Page<void> _page(LocalKey key, Widget child, {bool dialog = false}) =>
cupertino
? CupertinoPage<void>(key: key, child: child, fullscreenDialog: dialog)
: MaterialPage<void>(key: key, child: child, fullscreenDialog: dialog);
/// A page-based Navigator supplies the Overlay, overlay portals and route
/// context that native controls (action sheets, tooltips) require. The shell
/// page key is stable, so changing the route updates it in place instead of
/// remounting it and losing the open run. Search is the only extra page, so
/// its native Close action pops just that page.
@override
Widget build(BuildContext context) {
final child = builder(context, _route);
final searching = searchOpen && searchBuilder != null;
final shellRoute = searching ? _searchReturn : _route;
return Navigator(
key: _navigatorKey,
pages: [
if (cupertino)
CupertinoPage<void>(key: _pageKey, child: child)
else
MaterialPage<void>(key: _pageKey, child: child),
_page(_pageKey, builder(context, shellRoute)),
// Search is a transient full-screen mode, so a full-screen dialog gives
// the standard Close/Cancel action instead of a Back chevron.
if (searching)
_page(_searchPageKey, searchBuilder!(context), dialog: true),
],
onDidRemovePage: (_) {},
onDidRemovePage: (page) {
if (page.key == _searchPageKey) closeSearch();
},
);
}
/// Open Search above the current destination; its route carries the browser
/// history entry, and close/back returns to what was open before.
void openSearch() {
if (searchOpen) return;
_searchReturn = _route;
goTo(AppRoute.search);
}
void closeSearch() {
if (!searchOpen) return;
goTo(_searchReturn);
}
@override
Future<void> setInitialRoutePath(AppRoute configuration) async {
_route = configuration;
@@ -85,6 +123,10 @@ class AppRouterDelegate extends RouterDelegate<AppRoute> with ChangeNotifier {
@override
Future<bool> popRoute() async {
if (searchOpen) {
closeSearch();
return true;
}
if (_route.runId != null) {
onPopToRuns();
return true;
+28
View File
@@ -1,8 +1,10 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import '../core/api_gateway.dart';
import '../core/transport/pipelines_client.dart';
import '../shell/adaptive_shell.dart';
import '../shell/destination.dart';
@@ -14,6 +16,7 @@ import 'app_session.dart';
import 'chat_destination.dart';
import 'pipelines_destination.dart';
import 'runs_destination.dart';
import 'search_destination.dart';
import 'server_endpoint.dart';
/// Composes the live application around one [AppSession] and one [Router].
@@ -73,6 +76,7 @@ class _PipelinesAppState extends State<PipelinesApp> {
cupertino: _cupertino,
onPopToRuns: () => _delegate.goTo(AppRoute.runs),
onPopToChat: () => _delegate.goTo(AppRoute.chat),
searchBuilder: _buildSearch,
builder: _buildShell,
);
_config = RouterConfig<AppRoute>(
@@ -97,11 +101,33 @@ class _PipelinesAppState extends State<PipelinesApp> {
Widget build(BuildContext context) =>
MyApp.router(cupertino: _cupertino, routerConfig: _config);
/// The transient Search page. Escape matches the browser's panel shortcut;
/// the native Back button and browser Back come from the router and page.
Widget _buildSearch(BuildContext context) => CallbackShortcuts(
bindings: {
const SingleActivator(LogicalKeyboardKey.escape): _delegate.closeSearch,
},
child: SearchDestination(
session: _session,
server: widget.server,
onOpen: _openSearchResult,
),
);
/// Open a result through an existing app route only. A run target uses the
/// route the Runs destination already owns; the hit map itself is unchanged,
/// and pipeline/version hits have no route yet, so they are not guessed.
void _openSearchResult(JsonMap hit) {
final runId = searchHitRunId(hit);
if (runId != null) _delegate.goTo(AppRoute.run(runId));
}
Widget _buildShell(BuildContext context, AppRoute route) => AdaptiveShell(
cupertino: _cupertino,
destination: _destinationOf(route.kind),
onDestinationSelected: (destination) =>
_delegate.goTo(_routeOf(destination)),
onSearch: _delegate.openSearch,
destinationBodies: {
AppDestination.pipelines: (_) =>
PipelinesDestination(session: _session, server: widget.server),
@@ -131,6 +157,8 @@ class _PipelinesAppState extends State<PipelinesApp> {
AppRouteKind.pipelines => AppDestination.pipelines,
AppRouteKind.runs => AppDestination.runs,
AppRouteKind.chat => AppDestination.chat,
// Search is a transient page above the shell; it never becomes a tab.
AppRouteKind.search => AppDestination.pipelines,
AppRouteKind.settings => AppDestination.settings,
};
+138
View File
@@ -0,0 +1,138 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../core/api_gateway.dart';
import '../features/search/search_screen.dart';
import '../ui/adaptive/host.dart';
import 'app_session.dart';
import 'connection_status.dart';
import 'server_endpoint.dart';
/// The Search page above the shell: the landed screen over the shared gateway.
///
/// Before the first successful connection there is nothing to search, so the
/// native connection gate is shown inside the same title bar and Close still
/// returns to the previous destination. In a Cupertino host the screen is
/// mounted once the route's entrance has completed: during that transition a
/// focus request is dropped, so mounting earlier would open Search with no
/// keyboard or caret. Material mounts it immediately as usual.
class SearchDestination extends StatefulWidget {
const SearchDestination({
super.key,
required this.session,
required this.server,
required this.onOpen,
});
final AppSession session;
final ServerEndpoint server;
final ValueChanged<JsonMap> onOpen;
@override
State<SearchDestination> createState() => _SearchDestinationState();
}
class _SearchDestinationState extends State<SearchDestination> {
Animation<double>? _animation;
bool _entered = false;
@override
void didChangeDependencies() {
super.didChangeDependencies();
// Material's page transition keeps the autofocus request; only the
// Cupertino push needs to wait for the route to become current.
if (!usesCupertinoHost(context)) {
_entered = true;
return;
}
final animation = ModalRoute.of(context)?.animation;
if (identical(animation, _animation)) return;
_animation?.removeStatusListener(_onStatus);
_animation = animation;
if (animation == null || animation.status == AnimationStatus.completed) {
_entered = true;
} else {
animation.addStatusListener(_onStatus);
}
}
void _onStatus(AnimationStatus status) {
if (status != AnimationStatus.completed) return;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) setState(() => _entered = true);
});
}
@override
void dispose() {
_animation?.removeStatusListener(_onStatus);
super.dispose();
}
@override
Widget build(BuildContext context) => AnimatedBuilder(
animation: widget.session,
builder: (context, _) {
final cupertino = usesCupertinoHost(context);
if (!widget.session.everConnected || !_entered) {
return _SearchPage(
cupertino: cupertino,
child: _entered
? ConnectionGate(
session: widget.session,
server: widget.server,
cupertino: cupertino,
)
: const SizedBox.shrink(),
);
}
return SearchScreen(
gateway: widget.session.gateway,
onOpen: widget.onOpen,
cupertino: cupertino,
);
},
);
}
/// The native title bar that owns Back while Search has no screen yet.
class _SearchPage extends StatelessWidget {
const _SearchPage({required this.cupertino, required this.child});
final bool cupertino;
final Widget child;
@override
Widget build(BuildContext context) => cupertino
? CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(middle: Text('Search')),
child: SafeArea(child: child),
)
: Scaffold(
appBar: AppBar(title: const Text('Search')),
body: SafeArea(child: child),
);
}
/// The run a result names, taken only from the server's own payload document.
///
/// The browser opens run, step, field and artifact hits at their recorded
/// sequence/field; this app has only the run route, so the run id is the one
/// target it can honour. Pipeline/version hits return null: there is no
/// pipeline-detail route yet and a guessed one would be invented navigation.
int? searchHitRunId(JsonMap hit) {
final run = _positiveId(hit['run'], 'id');
if (run != null) return run;
for (final key in const ['step', 'field', 'artifact']) {
final id = _positiveId(hit[key], 'run_id');
if (id != null) return id;
}
return null;
}
int? _positiveId(Object? payload, String key) {
if (payload is! Map) return null;
final value = payload[key];
final id = value is int ? value : int.tryParse('$value');
return id != null && id > 0 ? id : null;
}
+31 -2
View File
@@ -10,6 +10,7 @@ class AdaptiveShell extends StatefulWidget {
this.cupertino = false,
this.destination,
this.onDestinationSelected,
this.onSearch,
});
final Map<AppDestination, WidgetBuilder> destinationBodies;
@@ -20,6 +21,10 @@ class AdaptiveShell extends StatefulWidget {
final AppDestination? destination;
final ValueChanged<AppDestination>? onDestinationSelected;
/// Opens the transient Search page. Null hides the action, so the plain
/// shell tests and compositions without routing keep their tab set only.
final VoidCallback? onSearch;
@override
State<AdaptiveShell> createState() => _AdaptiveShellState();
}
@@ -79,7 +84,20 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
final wide = constraints.maxWidth >= 600;
if (widget.cupertino) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(middle: Text(details.label)),
navigationBar: CupertinoNavigationBar(
middle: Text(details.label),
trailing: widget.onSearch == null
? null
: CupertinoButton(
key: const ValueKey('shell.search'),
padding: EdgeInsets.zero,
onPressed: widget.onSearch,
child: const Icon(
CupertinoIcons.search,
semanticLabel: 'Search',
),
),
),
child: SafeArea(
child: Column(
children: [
@@ -101,7 +119,18 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
);
}
return Scaffold(
appBar: AppBar(title: Text(details.label)),
appBar: AppBar(
title: Text(details.label),
actions: [
if (widget.onSearch != null)
IconButton(
key: const ValueKey('shell.search'),
onPressed: widget.onSearch,
tooltip: 'Search',
icon: const Icon(Icons.search),
),
],
),
body: Row(
children: [
if (wide)
+111
View File
@@ -0,0 +1,111 @@
# X1-wire — register Search in the shell and `/search`
## Scope
Wired the landed `SearchScreen` into the normal `PipelinesApp` composition. No
search internals, `features/pipelines`, `features/chat`, `features/graph`,
`features/artifacts`, server, web, Android or iOS files were changed.
## Behaviour
- The existing shell gains a native search action without a fifth tab:
Material `AppBar` `IconButton` (`tooltip: Search`) and Cupertino
`CupertinoNavigationBar` trailing button (`semanticLabel: Search`). The tab
set stays `Pipelines / Runs / Chat / Settings`.
- `AppRouteKind.search` with the total path `/search`. `/search/` normalises,
`/search/1` and other unknown paths still parse to `/pipelines`.
- Search is a transient full-screen dialog page above the shell (standard
Material close icon, Cupertino `Cancel`), so closing is a normal native
action and the shell below is never remounted. `openSearch` records the
previous route; Close, system Back (`popRoute`) and `onDidRemovePage` return
to it. Browser Back/Forward go through the ordinary Router history.
- Escape closes the page (the browser's search-panel shortcut) through
`CallbackShortcuts`.
- The field is focused on open. Material mounts the screen immediately;
the Cupertino page waits for its entrance to complete, because a focus
request during that transition is dropped (the landing screen was visibly
unfocused without this). A post-frame then mounts `SearchScreen`, whose
existing `autofocus` takes effect.
- Requests use the one shared `AppSession` gateway (`session.gateway`); the
screen and page open no socket. Before the first connection the destination
shows the existing native `ConnectionGate` in the same title bar.
- Results keep the screen's `onOpen` contract: the server hit map is passed
through unchanged. Only a run-family hit (`run.id`, or `step/field/artifact
.run_id`) is opened, through the existing `/runs/:id` route. No route is
invented for pipeline/version hits; those rows still call `onOpen` but this
app has no pipeline-detail route to open yet.
## Files
- `lib/application/app_route.dart` — search kind, path, parser branch.
- `lib/application/app_router.dart` — search page, open/close return route,
native dialog chrome, system Back, page-removal callback.
- `lib/application/pipelines_app.dart` — registration, Escape shortcut,
run-target passthrough, `onSearch` on the shell.
- `lib/application/search_destination.dart` (new) — connection gate, shared
gateway, Cupertino focus mount, `searchHitRunId`.
- `lib/shell/adaptive_shell.dart` — optional native search action.
- `test/application/app_route_test.dart` — `/search` parse/serialise/fallback.
- `test/application/search_wiring_test.dart` (new) — focus, close/state,
result routing, one socket, Cupertino close, hit helper, system Back.
- `tool/runs_probe_server.mjs` — additive `search` branch and
`searchRequests` fixture state (the Runs probe behaviour is unchanged).
- `tool/search_wiring_probe.mjs` (new) — real-browser acceptance driver.
## Checks
Run from `app/` with `/Users/alan/development/flutter/bin/flutter`:
- `flutter analyze` — **No issues found**.
- `flutter test` — **837 passed** (whole app suite).
- `flutter test test/application test/features/search test/widget_test.dart` —
**87 passed**.
- `flutter build web` (default `lib/main.dart`) — **succeeded**.
- `flutter build web -o build/search_wiring_web` — **succeeded** for the probe.
- `node --check tool/search_wiring_probe.mjs` and
`node --check tool/runs_probe_server.mjs` — passed.
- Probe exit 0. Evidence: both hosts opened `/search` with the field as the
focused browser `INPUT`; the exact request was
`{"query":"fixture","kind":"","limit":0}`; the run row opened `/runs/1`;
Escape returned to the same retained run detail with `getRun` unchanged (1);
browser Back returned to `/runs` with `listRuns` unchanged and the transient
page gone; the fixture saw `connections: 1` for the whole Material run; both
boots subscribed on the existing socket (`subscribed: 2`).
- Real Chrome (headless, CDP) against an isolated websocket fixture on an
OS-assigned loopback port; no production or operator data.
Captures (shared artifacts, both hosts, phone and desktop):
- `x1-wire/x1-wire-material-search-phone.png`
- `x1-wire/x1-wire-material-search-desktop.png`
- `x1-wire/x1-wire-material-run-from-search-phone.png`
- `x1-wire/x1-wire-material-escape-restored-phone.png`
- `x1-wire/x1-wire-cupertino-search-phone.png`
- `x1-wire/x1-wire-cupertino-search-desktop.png`
- `x1-wire/x1-wire-cupertino-back-restored-phone.png`
under `/Users/alan/.local/share/pipelines/data/artifacts/88/public/`.
## Not verified / remaining
- Pipeline and version hits do not navigate: no pipeline-detail route exists
in the app yet (PARITY target routing remains open). Step/field/artifact hits
open their run but not the recorded visit/sequence or field tab.
- Mobile targets were not built, installed or exercised; only Web was rendered.
The Cupertino focus handling is covered by widget tests and the macOS-UA web
probe, not an iOS device.
- Live authenticated production search was not exercised.
- No commit, push, deployment or canonical URL change was made.
## Manager completion after an infrastructure failure
This run ended with the server reporting `constraint failed: UNIQUE constraint
failed: step_file_changes.run_id, step_file_changes.sequence (1555)` — a server
persistence bug in file-change capture, not a fault in this slice. The same
failure hit the parallel run-graph slice. The retained edits were complete: the
manager ran the application suite (45 tests pass), inspected the route/shell
changes, and merged them. The server defect is recorded in WORK.md and is being
fixed with a regression on the server side; no retry of this app slice was needed.
Evidence for the wiring is the focused suite plus the real-app probe run after
landing; the server failure means this run's own stage evidence is incomplete.
+3
View File
@@ -11,6 +11,7 @@ void main() {
AppRoute.parse('/chat/abc_DEF-123'),
AppRoute.chatSession('abc_DEF-123'),
);
expect(AppRoute.parse('/search'), AppRoute.search);
expect(AppRoute.parse('/settings'), AppRoute.settings);
});
@@ -41,6 +42,7 @@ void main() {
'/runs/-1',
'/runs/1/extra',
'/pipelines/2',
'/search/1',
'/chat/a/b',
'/chat/%2F',
'/chat/${'x' * 201}',
@@ -58,6 +60,7 @@ void main() {
AppRoute.run(3),
AppRoute.chat,
AppRoute.chatSession('probe_open-1'),
AppRoute.search,
AppRoute.settings,
]) {
expect(AppRoute.parse(route.path), route);
@@ -0,0 +1,416 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/application/app_route.dart';
import 'package:pipelines_app/application/app_router.dart';
import 'package:pipelines_app/application/pipelines_app.dart';
import 'package:pipelines_app/application/search_destination.dart';
import 'package:pipelines_app/application/server_endpoint.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart';
import 'package:pipelines_app/features/search/search_screen.dart';
import '../core/transport/pipelines_client_test.dart' show FakeChannel;
ServerEndpoint webServer() => ServerEndpoint.resolve(
base: Uri.parse('http://127.0.0.1:8096/'),
web: true,
);
List<Map<String, dynamic>> requestsOf(FakeChannel channel, String type) =>
channel.outgoing
.map((frame) => jsonDecode(frame as String) as Map<String, dynamic>)
.where((frame) => frame['type'] == type)
.toList();
Map<String, dynamic>? requestOf(
FakeChannel channel,
String type, {
int index = 0,
}) {
final requests = requestsOf(channel, type);
return index < requests.length ? requests[index] : null;
}
Future<Map<String, dynamic>> waitForRequest(
WidgetTester tester,
FakeChannel channel,
String type, {
int index = 0,
}) async {
for (var attempt = 0; attempt < 80; attempt++) {
final request = requestOf(channel, type, index: index);
if (request != null) return request;
await tester.pump(const Duration(milliseconds: 5));
}
fail('Timed out waiting for $type #$index');
}
Future<void> reply(
WidgetTester tester,
FakeChannel channel,
String type, {
required Map<String, dynamic> body,
int index = 0,
}) async {
final request = await waitForRequest(tester, channel, type, index: index);
channel.incoming.add(jsonEncode({'id': request['id'], ...body}));
await tester.pump();
await tester.pump();
}
Future<void> replyRunList(WidgetTester tester, FakeChannel channel) => reply(
tester,
channel,
'list_runs',
body: {
'type': 'runs',
'runs': [
{'id': 2, 'name': 'Preserved run', 'status': 'running'},
],
},
);
Future<void> replyRunDetail(
WidgetTester tester,
FakeChannel channel,
int id, {
int index = 0,
}) => reply(
tester,
channel,
'get_run',
index: index,
body: {
'type': 'run',
'run_detail': {'id': id, 'title': 'Run $id', 'status': 'running'},
},
);
JsonMap runHit(int id) => {
'kind': 'run',
'target': 'run:$id',
'run': {
'id': id,
'pipeline_name': 'Preserved run',
'status': 'running',
'workspace': '/workspace/demo',
'created_at': '2026-10-21T12:00:00Z',
},
};
Future<void> pumpApp(
WidgetTester tester, {
required FakeChannel channel,
required PipelinesClient client,
required PlatformRouteInformationProvider provider,
required bool cupertino,
}) async {
await tester.pumpWidget(
PipelinesApp(
server: webServer(),
client: client,
cupertino: cupertino,
routeInformationProvider: provider,
),
);
await tester.pump();
}
void main() {
testWidgets(
'the shell action opens focused Search and Close keeps the open run',
(tester) async {
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final channel = FakeChannel()..readyCompleter.complete();
var sockets = 0;
final client = PipelinesClient(
channelFactory: (_) {
sockets++;
return channel;
},
);
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/runs/2')),
);
addTearDown(provider.dispose);
await pumpApp(
tester,
channel: channel,
client: client,
provider: provider,
cupertino: false,
);
await replyRunList(tester, channel);
await replyRunDetail(tester, channel, 2);
expect(find.text('Back to list'), findsOneWidget);
// The shell's existing action opens Search without adding a fifth tab.
await tester.tap(find.byKey(const ValueKey('shell.search')));
await tester.pump();
await tester.pump(const Duration(milliseconds: 600));
await tester.pump(const Duration(milliseconds: 100));
expect(provider.value.uri.path, '/search');
expect(find.byType(SearchScreen), findsOneWidget);
expect(find.byKey(const ValueKey('search.field')), findsOneWidget);
final editable = tester.widget<EditableText>(
find.descendant(
of: find.byKey(const ValueKey('search.field')),
matching: find.byType(EditableText),
),
);
expect(editable.focusNode.hasFocus, isTrue);
expect(find.byType(CloseButton), findsOneWidget);
// Closing is the native dialog action, not a second router or modal.
await tester.tap(find.byType(CloseButton));
await tester.pump();
await tester.pump(const Duration(milliseconds: 400));
await tester.pump(const Duration(milliseconds: 400));
expect(provider.value.uri.path, '/runs/2');
expect(find.byType(SearchScreen), findsNothing);
expect(find.text('Back to list'), findsOneWidget);
expect(find.text('Run 2'), findsWidgets);
// The shell was never remounted, so the open run was not re-read.
expect(requestsOf(channel, 'get_run'), hasLength(1));
expect(requestsOf(channel, 'list_runs'), hasLength(1));
expect(sockets, 1);
// Escape is the browser panel's close shortcut on this page too.
await tester.tap(find.byKey(const ValueKey('shell.search')));
await tester.pump();
await tester.pump(const Duration(milliseconds: 600));
await tester.pump(const Duration(milliseconds: 100));
expect(provider.value.uri.path, '/search');
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
await tester.pump(const Duration(milliseconds: 400));
expect(provider.value.uri.path, '/runs/2');
expect(find.text('Back to list'), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
},
);
testWidgets('a result opens through the existing run route over one socket', (
tester,
) async {
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final channel = FakeChannel()..readyCompleter.complete();
var sockets = 0;
final client = PipelinesClient(
channelFactory: (_) {
sockets++;
return channel;
},
);
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/runs/2')),
);
addTearDown(provider.dispose);
await pumpApp(
tester,
channel: channel,
client: client,
provider: provider,
cupertino: false,
);
await replyRunList(tester, channel);
await replyRunDetail(tester, channel, 2);
await tester.tap(find.byKey(const ValueKey('shell.search')));
await tester.pump();
await tester.pump(const Duration(milliseconds: 600));
await tester.pump(const Duration(milliseconds: 100));
await tester.enterText(
find.byKey(const ValueKey('search.field')),
'release',
);
await tester.pump(const Duration(milliseconds: 300));
final request = await waitForRequest(tester, channel, 'search');
expect(request['search'], {'query': 'release', 'kind': '', 'limit': 0});
channel.incoming.add(
jsonEncode({
'id': request['id'],
'type': 'search_results',
'search_results': {
'query': 'release',
'kind': '',
'results': [runHit(7)],
'truncated': false,
'scanned_steps': 4,
'scanned_bytes': 512,
'cap': 50,
'scan_bound_bytes': 1 << 20,
},
}),
);
await tester.pump();
await tester.pump();
expect(find.text('run #7 · Preserved run'), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('search.result.run:7')));
await tester.pump();
await tester.pump(const Duration(milliseconds: 400));
await tester.pump(const Duration(milliseconds: 400));
// The hit map's own run id uses the route Runs already owns.
expect(provider.value.uri.path, '/runs/7');
await replyRunDetail(tester, channel, 7, index: 1);
expect(find.byType(SearchScreen), findsNothing);
expect(find.text('Back to list'), findsOneWidget);
expect(find.text('Run 7'), findsWidgets);
// One app socket carried the search and the run reads.
expect(sockets, 1);
expect(requestsOf(channel, 'search'), hasLength(1));
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
});
testWidgets('Cupertino uses its native bar action and Back', (tester) async {
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue);
final channel = FakeChannel()..readyCompleter.complete();
var sockets = 0;
final client = PipelinesClient(
channelFactory: (_) {
sockets++;
return channel;
},
);
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/runs')),
);
addTearDown(provider.dispose);
await pumpApp(
tester,
channel: channel,
client: client,
provider: provider,
cupertino: true,
);
await replyRunList(tester, channel);
expect(find.text('Preserved run'), findsWidgets);
await tester.tap(find.byKey(const ValueKey('shell.search')));
await tester.pump();
await tester.pump(const Duration(milliseconds: 600));
await tester.pump(const Duration(milliseconds: 100));
expect(provider.value.uri.path, '/search');
expect(find.byKey(const ValueKey('search.field')), findsOneWidget);
expect(find.byType(Material), findsNothing);
final cupertinoField = tester.widget<EditableText>(
find.descendant(
of: find.byKey(const ValueKey('search.field')),
matching: find.byType(EditableText),
),
);
expect(cupertinoField.focusNode.hasFocus, isTrue);
await tester.tap(find.text('Cancel'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 400));
await tester.pump(const Duration(milliseconds: 400));
expect(provider.value.uri.path, '/runs');
expect(find.byKey(const ValueKey('search.field')), findsNothing);
expect(find.text('Preserved run'), findsWidgets);
expect(sockets, 1);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
});
test(
'the hit helper never guesses a route for pipeline or malformed hits',
() {
expect(searchHitRunId(runHit(3)), 3);
expect(
searchHitRunId({
'kind': 'step',
'step': {'run_id': 8, 'sequence': 2},
}),
8,
);
expect(
searchHitRunId({
'kind': 'field',
'field': {'run_id': '9', 'sequence': 1},
}),
9,
);
expect(
searchHitRunId({
'kind': 'pipeline',
'pipeline': {'id': 4, 'name': 'Alpha'},
}),
isNull,
);
expect(searchHitRunId({'kind': 'artifact', 'artifact': {}}), isNull);
expect(
searchHitRunId({
'kind': 'run',
'run': {'id': 0},
}),
isNull,
);
},
);
test(
'openSearch keeps the previous route and system Back restores it',
() async {
final router = AppRouterDelegate(
builder: (context, route) => const SizedBox.shrink(),
onPopToRuns: () {},
onPopToChat: () {},
cupertino: false,
initial: AppRoute.run(3),
);
addTearDown(router.dispose);
router.openSearch();
expect(router.route, AppRoute.search);
expect(router.searchOpen, isTrue);
expect(await router.popRoute(), isTrue);
expect(router.route, AppRoute.run(3));
expect(router.searchOpen, isFalse);
},
);
test('the /search route is total and survives the parser', () {
expect(AppRoute.parse('/search'), AppRoute.search);
expect(
AppRoute.parse('http://127.0.0.1:8096/search?q=plan'),
AppRoute.search,
);
expect(AppRoute.parse('/search/2'), AppRoute.pipelines);
expect(AppRoute.search.path, '/search');
});
}
+31
View File
@@ -326,6 +326,7 @@ export async function startFixture({ root }) {
const decisionRequests = [];
let chatSubscribed = 0;
let chatHistory = 0;
const searchRequests = [];
const CHAT_SESSION = {
id: 'ses_probechat',
title: 'Probe conversation',
@@ -383,6 +384,7 @@ export async function startFixture({ root }) {
decisionRequests,
chatSubscribed,
chatHistory,
searchRequests,
}));
return;
}
@@ -474,6 +476,35 @@ export async function startFixture({ root }) {
client.send({ id: request.id, type: 'run', run_detail: humanDetail(true) });
return;
}
if (request.type === 'search') {
// Deterministic wire fixture for the Search page probe: the app's
// exact request body is recorded and answered with one hit per kind
// it can target. No production server or operator data is involved.
const search = request.search ?? {};
searchRequests.push(search);
const query = String(search.query ?? '');
client.send({
id: request.id,
type: 'search_results',
search_results: {
query,
kind: search.kind ?? '',
results: query.trim() ? [
{ kind: 'run', target: 'run:1', run: {
id: 1, pipeline_name: 'Fixture live run', status: 'running',
workspace: '/srv/probe', created_at: '2026-10-21T12:00:00Z' } },
{ kind: 'pipeline', target: 'pipeline:10', pipeline: {
id: 10, name: 'Fixture pipeline', version: 1, stages: 2 } },
] : [],
truncated: false,
scanned_steps: 4,
scanned_bytes: 512,
cap: 50,
scan_bound_bytes: 1048576,
},
});
return;
}
if (request.type === 'chat_sessions') {
client.send({ id: request.id, type: 'chat_sessions',
chat_sessions: [CHAT_SESSION] });
+400
View File
@@ -0,0 +1,400 @@
// Real Chrome evidence for the registered Search entry and /search route.
//
// Build the normal app, then run from app/:
// flutter build web -o build/search_wiring_web
// OPENCODE_ARTIFACT_DIR=<dir> node tool/search_wiring_probe.mjs \
// build/search_wiring_web
//
// The fixture is the same isolated websocket server the Runs probe uses, with a
// deterministic `search` branch; no production server or operator data is used.
import { spawn } from 'node:child_process';
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
import { once } from 'node:events';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { startFixture } from './runs_probe_server.mjs';
const output = process.env.OPENCODE_ARTIFACT_DIR;
if (!output) throw new Error('Set OPENCODE_ARTIFACT_DIR for the probe captures');
await mkdir(output, { recursive: true });
const root = resolve(process.argv[2] ?? 'build/search_wiring_web');
const fixture = await startFixture({ root });
const result = { captures: [], evidence: {} };
const profile = await mkdtemp(join(tmpdir(), 'x1-wire-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;
});
async function waitFor(check, label, attempts = 160) {
for (let attempt = 0; attempt < attempts; attempt++) {
const value = await check();
if (value) return value;
await delay(100);
}
throw new Error(`Timed out waiting for ${label}`);
}
let ws;
try {
const endpoint = await waitFor(
() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1],
'Chrome DevTools',
);
ws = new WebSocket(endpoint);
await once(ws, 'open');
let id = 0;
const pending = new Map();
ws.addEventListener('message', (event) => {
const message = JSON.parse(event.data);
if (message.method === 'Runtime.exceptionThrown') {
console.error('PAGE EXCEPTION', JSON.stringify(message.params?.exceptionDetails));
}
if (message.method === 'Runtime.consoleAPICalled') {
const text = (message.params?.args ?? [])
.map((arg) => arg.value ?? arg.description ?? '')
.join(' ');
if (text.includes('X1FOCUS')) console.error(text);
}
if (message.id && pending.has(message.id)) {
pending.get(message.id)(message);
pending.delete(message.id);
}
});
const send = (method, params = {}, sessionId) =>
new Promise((resolveCall) => {
const callId = ++id;
pending.set(callId, resolveCall);
ws.send(
JSON.stringify({
id: callId,
method,
params,
...(sessionId ? { sessionId } : {}),
}),
);
});
const target = (await send('Target.createTarget', { url: 'about:blank' }))
.result.targetId;
const session = (
await send('Target.attachToTarget', { targetId: target, flatten: true })
).result.sessionId;
await send('Page.enable', {}, session);
await send('Runtime.enable', {}, session);
// A headless target can otherwise keep the page unfocused, which would make
// the browser refuse the field's autofocus request rather than test the app.
await send('Page.bringToFront', {}, session);
const evaluate = async (expression) => {
const response = await send(
'Runtime.evaluate',
{ expression, returnByValue: true, awaitPromise: true },
session,
);
if (response.error) throw new Error(JSON.stringify(response));
if (response.result?.exceptionDetails) {
throw new Error(JSON.stringify(response.result.exceptionDetails));
}
return response.result?.result?.value;
};
const enableSemantics = async () => {
await waitFor(
() => evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"),
'Flutter semantics placeholder',
);
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
await delay(600);
};
const text = () =>
evaluate(`(() => {
const chunks = [];
for (const el of document.querySelectorAll('flt-semantics, [aria-label], [aria-valuetext]')) {
const label = el.getAttribute('aria-label');
if (label) chunks.push(label);
if (!el.children.length && el.innerText) chunks.push(el.innerText);
}
if (document.body?.innerText) chunks.push(document.body.innerText);
return [...new Set(chunks)].join('\\n');
})()`);
const assertBody = (needle) =>
waitFor(async () => (await text()).includes(needle), JSON.stringify(needle));
const path = () => evaluate('location.pathname');
const clickSemantics = (needle) =>
evaluate(`(() => {
const wanted = ${JSON.stringify(needle)};
const nodes = [...document.querySelectorAll('flt-semantics')];
const candidates = nodes.filter((el) => {
const label = (el.getAttribute('aria-label') || el.innerText || '').trim();
return label === wanted || label.includes(wanted);
});
const interactive = candidates.find((el) =>
el.hasAttribute('flt-tappable') && ['button', 'link', 'menuitem', 'tab'].includes(el.getAttribute('role')));
const node = interactive || candidates.find((el) => el.hasAttribute('flt-tappable')) || candidates.at(-1);
if (!node) return { clicked: false, candidates: [] };
node.click();
return { clicked: true, candidates: candidates.map((el) => ({
label: (el.getAttribute('aria-label') || el.innerText || '').trim().slice(0, 120),
role: el.getAttribute('role'), tappable: el.hasAttribute('flt-tappable'),
})) };
})()`);
const clickAction = async (label) => {
// A real pointer event keeps user activation and browser focus, unlike a
// synthetic el.click() on the semantics node.
const centre = await evaluate(`(() => {
const wanted = ${JSON.stringify(label)};
const nodes = [...document.querySelectorAll('flt-semantics')]
.filter((el) => ['button', 'link', 'menuitem', 'tab'].includes(el.getAttribute('role')));
const node = nodes.find((el) =>
(el.getAttribute('aria-label') || el.innerText || '').trim() === wanted);
if (!node) return null;
const rect = node.getBoundingClientRect();
return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
})()`);
if (!centre) {
const labels = await evaluate(`[...document.querySelectorAll('flt-semantics')]
.filter((el) => ['button', 'link', 'menuitem', 'tab'].includes(el.getAttribute('role')))
.map((el) => (el.getAttribute('aria-label') || el.innerText || '').trim())`);
throw new Error(`Could not click ${JSON.stringify(label)}: ${JSON.stringify(labels)}`);
}
await send(
'Input.dispatchMouseEvent',
{ type: 'mousePressed', x: centre.x, y: centre.y, button: 'left', clickCount: 1 },
session,
);
await send(
'Input.dispatchMouseEvent',
{ type: 'mouseReleased', x: centre.x, y: centre.y, button: 'left', clickCount: 1 },
session,
);
await delay(350);
};
const setSize = async (width, height, mobile) => {
await send(
'Emulation.setDeviceMetricsOverride',
{ width, height, deviceScaleFactor: 1, mobile },
session,
);
await delay(500);
};
const capture = async (name) => {
const data = (
await send(
'Page.captureScreenshot',
{ format: 'png', captureBeyondViewport: false },
session,
)
).result.data;
const file = join(output, `${name}.png`);
await writeFile(file, Buffer.from(data, 'base64'));
result.captures.push(file);
};
const open = async (url, { width, height, mobile }) => {
await setSize(width, height, mobile);
const navigation = await send('Page.navigate', { url }, session);
if (navigation.error || navigation.result?.errorText) {
throw new Error(JSON.stringify(navigation));
}
await enableSemantics();
};
const fieldFocused = () =>
evaluate(`(() => {
const active = document.activeElement;
const isField = active && (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA');
const node = isField ? active : document.querySelector('input.flt-text-editing, textarea.flt-text-editing, input, textarea');
if (!node) return { found: false, focused: false };
return { found: true, focused: document.activeElement === node, tag: node.tagName };
})()`);
const typeQuery = async (value) => {
const field = await fieldFocused();
if (!field.focused) {
const focused = await evaluate(`(() => {
const nodes = [...document.querySelectorAll('input.flt-text-editing, textarea.flt-text-editing, input, textarea')];
const node = nodes.find((el) => el.checkVisibility?.() ?? true) || nodes.at(-1);
if (!node) return false; node.focus(); return true;
})()`);
if (!focused) throw new Error('Search field not exposed as a semantics input');
await delay(300);
}
const inserted = await send('Input.insertText', { text: value }, session);
if (inserted.error) throw new Error(JSON.stringify(inserted));
await delay(1400);
return field;
};
const fixtureState = async () =>
(await fetch(`${fixture.url}/fixture/state`)).json();
// Search mounts its screen after the native page transition so autofocus is
// not swallowed; wait for the real field before typing.
const openSearch = async () => {
await clickAction('Search');
await waitFor(async () => (await path()) === '/search', 'the /search route');
await waitFor(async () => (await fieldFocused()).focused, 'the focused search field');
};
const stateBefore = await fixtureState();
// Material host (a Linux browser UA picks the Material composition).
await send(
'Emulation.setUserAgentOverride',
{
userAgent:
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 ' +
'(KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36',
platform: 'Linux x86_64',
},
session,
);
await open(`${fixture.url}/runs`, { width: 390, height: 844, mobile: true });
await assertBody('Fixture live run');
if ((await path()) !== '/runs') throw new Error(`Boot moved to ${await path()}`);
const listRunsBefore = (await fixtureState()).listRuns;
await openSearch();
result.evidence.materialFocus = await fieldFocused();
await typeQuery('fixture');
await assertBody('run #1 · Fixture live run');
result.evidence.materialResults = (await text()).includes('Fixture pipeline');
const afterSearch = await fixtureState();
const request = afterSearch.searchRequests.at(-1);
if (JSON.stringify(request) !== JSON.stringify({ query: 'fixture', kind: '', limit: 0 })) {
throw new Error(`Search request mismatch: ${JSON.stringify(request)}`);
}
result.evidence.searchRequest = request;
if (afterSearch.connections !== 1) {
throw new Error(`Search opened another socket: ${JSON.stringify(afterSearch)}`);
}
await capture('x1-wire-material-search-phone');
// A run hit opens through the existing run route and detail.
const openedHit = await clickSemantics('run #1 · Fixture live run');
if (!openedHit.clicked) throw new Error('Could not open the run result');
await waitFor(async () => (await path()) === '/runs/1', 'the run route from search');
await assertBody('Original prompt');
await capture('x1-wire-material-run-from-search-phone');
// Escape closes Search back onto the same detail without re-reading it.
const getRunBeforeEscape = (await fixtureState()).getRun;
await openSearch();
const composeFocus = await fieldFocused();
if (!composeFocus.focused) throw new Error('Search did not focus from the run detail');
await send(
'Input.dispatchKeyEvent',
{ type: 'keyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 },
session,
);
await send(
'Input.dispatchKeyEvent',
{ type: 'keyUp', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 },
session,
);
await waitFor(async () => (await path()) === '/runs/1', 'Escape back to the run');
await assertBody('Original prompt');
const afterEscape = await fixtureState();
if (afterEscape.getRun !== getRunBeforeEscape) {
throw new Error('Escape re-read the retained run detail');
}
result.evidence.escapeRestored = { path: await path(), getRun: afterEscape.getRun };
await capture('x1-wire-material-escape-restored-phone');
await setSize(1280, 800, false);
await openSearch();
await typeQuery('fixture');
await assertBody('run #1 · Fixture live run');
await capture('x1-wire-material-search-desktop');
// Cupertino host: the native navigation-bar action and system Back.
await send(
'Emulation.setUserAgentOverride',
{
userAgent:
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 ' +
'(KHTML, like Gecko) Version/17.0 Safari/605.1.15',
platform: 'MacIntel',
},
session,
);
await open(`${fixture.url}/runs`, { width: 390, height: 844, mobile: true });
await assertBody('Fixture live run');
const cupertinoListBefore = (await fixtureState()).listRuns;
await openSearch();
result.evidence.cupertinoFocus = await fieldFocused();
await typeQuery('fixture');
await assertBody('run #1 · Fixture live run');
await capture('x1-wire-cupertino-search-phone');
// Browser Back is the shell's own history: the loaded list must still be
// there rather than being re-read or replaced.
await evaluate('history.back()');
await waitFor(async () => (await path()) === '/runs', 'browser Back to /runs');
// Wait for the transient page to finish leaving, not just for the URL.
await waitFor(
async () => !(await text()).includes('Kind: All kinds'),
'the search page to close',
);
await assertBody('Fixture live run');
const cupertinoListAfter = (await fixtureState()).listRuns;
if (cupertinoListAfter !== cupertinoListBefore) {
throw new Error(
`Back re-read the retained list: ${cupertinoListBefore} -> ${cupertinoListAfter}`,
);
}
result.evidence.cupertinoBack = {
path: await path(),
listRuns: cupertinoListAfter,
};
await capture('x1-wire-cupertino-back-restored-phone');
await setSize(1280, 800, false);
await openSearch();
await typeQuery('fixture');
await assertBody('run #1 · Fixture live run');
await capture('x1-wire-cupertino-search-desktop');
const finalState = await fixtureState();
if (finalState.subscribed < 2) {
throw new Error(`Expected the shared subscription on both boots: ${JSON.stringify(finalState)}`);
}
if (stateBefore.connections !== 0) {
throw new Error('The isolated fixture already had connections');
}
result.evidence.finalState = finalState;
console.log(JSON.stringify(result, null, 2));
} finally {
ws?.close();
chrome.kill('SIGTERM');
await Promise.race([once(chrome, 'exit'), delay(3000)]);
await fixture.close();
await rm(profile, { recursive: true, force: true });
}