diff --git a/app/lib/application/app_route.dart b/app/lib/application/app_route.dart index 889f04f5..34ce499a 100644 --- a/app/lib/application/app_route.dart +++ b/app/lib/application/app_route.dart @@ -10,7 +10,7 @@ enum AppRouteKind { pipelines, runs, chat, settings } /// malformed path resolves to the default Pipelines list instead of throwing. /// The serialiser is its inverse for every route the app can produce. class AppRoute { - const AppRoute(this.kind, {this.runId}); + const AppRoute(this.kind, {this.runId, this.chatSessionId}); static const pipelines = AppRoute(AppRouteKind.pipelines); static const runs = AppRoute(AppRouteKind.runs); @@ -19,16 +19,27 @@ class AppRoute { static const run = _RunRouteFactory(); + /// One chat session, or the chat list when [id] is not a session id. + static AppRoute chatSession(String id) => isChatSessionId(id) + ? AppRoute(AppRouteKind.chat, chatSessionId: id) + : chat; + final AppRouteKind kind; /// The run shown by the Runs destination, or null for the list. final int? runId; + /// The chat session shown by the Chat destination, or null for the list. + final String? chatSessionId; + /// The path the app writes into history for this route. String get path => switch (kind) { AppRouteKind.pipelines => '/pipelines', AppRouteKind.runs => runId == null ? '/runs' : '/runs/$runId', - AppRouteKind.chat => '/chat', + AppRouteKind.chat => + chatSessionId == null || !isChatSessionId(chatSessionId!) + ? '/chat' + : '/chat/${Uri.encodeComponent(chatSessionId!)}', AppRouteKind.settings => '/settings', }; @@ -65,6 +76,7 @@ class AppRoute { 'runs' when segments.length == 1 => runs, 'runs' when segments.length == 2 => _runRoute(segments[1]), 'chat' when segments.length == 1 => chat, + 'chat' when segments.length == 2 => _chatRoute(segments[1]), 'settings' when segments.length == 1 => settings, _ => pipelines, }; @@ -77,12 +89,26 @@ class AppRoute { return AppRoute(AppRouteKind.runs, runId: id); } - @override - bool operator ==(Object other) => - other is AppRoute && other.kind == kind && other.runId == runId; + /// A chat session id is nonempty, bounded and URL-safe, matching the web + /// parser. Anything else is malformed rather than a stale session the + /// destination has to guess about. + static bool isChatSessionId(String value) => + value.isNotEmpty && + value.length <= 200 && + RegExp(r'^[A-Za-z0-9_-]+$').hasMatch(value); + + static AppRoute _chatRoute(String value) => + isChatSessionId(value) ? chatSession(value) : pipelines; @override - int get hashCode => Object.hash(kind, runId); + bool operator ==(Object other) => + other is AppRoute && + other.kind == kind && + other.runId == runId && + other.chatSessionId == chatSessionId; + + @override + int get hashCode => Object.hash(kind, runId, chatSessionId); @override String toString() => path; diff --git a/app/lib/application/app_router.dart b/app/lib/application/app_router.dart index 44c87efb..80010651 100644 --- a/app/lib/application/app_router.dart +++ b/app/lib/application/app_router.dart @@ -27,6 +27,7 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { AppRouterDelegate({ required this.builder, required this.onPopToRuns, + required this.onPopToChat, required this.cupertino, AppRoute initial = AppRoute.pipelines, }) : _route = initial; @@ -36,6 +37,9 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { /// Called when a system Back belongs to the Runs detail, not the app stack. final VoidCallback onPopToRuns; + /// Called when a system Back belongs to one chat session. + final VoidCallback onPopToChat; + final bool cupertino; final _navigatorKey = GlobalKey(); @@ -81,9 +85,15 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { @override Future popRoute() async { - if (_route.runId == null) return false; - onPopToRuns(); - return true; + if (_route.runId != null) { + onPopToRuns(); + return true; + } + if (_route.chatSessionId != null) { + onPopToChat(); + return true; + } + return false; } /// Records a user move; the Router turns the new configuration into a diff --git a/app/lib/application/chat_destination.dart b/app/lib/application/chat_destination.dart new file mode 100644 index 00000000..15b2a56d --- /dev/null +++ b/app/lib/application/chat_destination.dart @@ -0,0 +1,69 @@ +import 'package:flutter/material.dart'; + +import '../features/chat/screen.dart'; +import '../ui/adaptive/host.dart'; +import 'app_session.dart'; +import 'connection_status.dart'; +import 'server_endpoint.dart'; + +/// The Chat destination: the shared session list and one read-only thread. +/// +/// Before the shared socket accepts its first connection nothing is requested, +/// so an offline launch cannot look like an empty chat list. After that the +/// screen stays mounted through drops; a reconnect advances [syncToken] so the +/// open conversation re-subscribes and re-reads without losing its selection. +class ChatDestination extends StatelessWidget { + const ChatDestination({ + super.key, + required this.session, + required this.server, + this.initialSessionId, + this.onSessionSelected, + this.onBack, + }); + + final AppSession session; + final ServerEndpoint server; + final String? initialSessionId; + final ValueChanged? onSessionSelected; + final VoidCallback? onBack; + + @override + Widget build(BuildContext context) => AnimatedBuilder( + animation: session, + builder: (context, _) { + final cupertino = usesCupertinoHost(context); + if ((server.requiresConfiguration || server.error != null) && + session.endpoint == null) { + return ConnectionGate( + session: session, + server: server, + cupertino: cupertino, + ); + } + if (!session.everConnected) { + if (session.connected) return _chatScreen(); + return ConnectionGate( + session: session, + server: server, + cupertino: cupertino, + ); + } + return Column( + children: [ + if (!session.connected) + ConnectionBanner(session: session, cupertino: cupertino), + Expanded(child: _chatScreen()), + ], + ); + }, + ); + + Widget _chatScreen() => ChatScreen( + gateway: session.gateway, + initialSessionId: initialSessionId, + syncToken: session.connectionEpoch, + onSessionSelected: onSessionSelected, + onBack: onBack, + ); +} diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index e5de270d..ac66045a 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -11,6 +11,7 @@ import 'app.dart'; import 'app_route.dart'; import 'app_router.dart'; import 'app_session.dart'; +import 'chat_destination.dart'; import 'pipelines_destination.dart'; import 'runs_destination.dart'; import 'server_endpoint.dart'; @@ -71,6 +72,7 @@ class _PipelinesAppState extends State { initial: initial, cupertino: _cupertino, onPopToRuns: () => _delegate.goTo(AppRoute.runs), + onPopToChat: () => _delegate.goTo(AppRoute.chat), builder: _buildShell, ); _config = RouterConfig( @@ -110,6 +112,13 @@ class _PipelinesAppState extends State { onRunSelected: (id) => _delegate.goTo(AppRoute.run(id)), onBack: () => _delegate.goTo(AppRoute.runs), ), + AppDestination.chat: (_) => ChatDestination( + session: _session, + server: widget.server, + initialSessionId: route.chatSessionId, + onSessionSelected: (id) => _delegate.goTo(AppRoute.chatSession(id)), + onBack: () => _delegate.goTo(AppRoute.chat), + ), AppDestination.settings: (_) => SettingsScreen( client: _session.client, initialEndpoint: _session.endpoint, diff --git a/app/lib/features/chat/conversation/chat_row_keys.dart b/app/lib/features/chat/conversation/chat_row_keys.dart new file mode 100644 index 00000000..f677ac09 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_row_keys.dart @@ -0,0 +1,73 @@ +import '../../../core/api_gateway.dart'; + +/// Stable widget-key strings for transcript rows while history grows at both +/// ends. +/// +/// A folded assistant turn has no stable message boundary: `Load older` can +/// prepend messages into the turn (changing its first id) and a live frame can +/// append a message (changing its last id). Deriving the row key from either +/// boundary remounts the row and resets every native disclosure in it, which +/// moved an open reasoning block to another answer or closed it. +/// +/// So the first sighting of a turn assigns a synthetic key, and later calls +/// carry that key forward while the turn still contains any message it held +/// before. Rows without a message id fall back to their position: they have no +/// identity that survives a prepend. +class ChatRowKeys { + final Map _byMessageId = {}; + int _serial = 0; + + /// One key per row, in row order. Call once per build. + List forRows(List rows) { + final nextByMessageId = {}; + final used = {}; + final keys = []; + for (var index = 0; index < rows.length; index++) { + final row = rows[index]; + final kind = '${row['kind'] ?? ''}'; + final ids = _messageIds(row); + String? key; + for (final id in ids) { + final held = _byMessageId[id]; + if (held != null) { + key = held; + break; + } + } + if (key == null) { + // A row with no id has no identity that survives a prepend, so it + // follows its position, as a plain indexed list would. Every other new + // row gets a key no older row can generate. + key = ids.isEmpty + ? 'chat-row-$kind-index-$index' + : 'chat-row-$kind-${_serial++}'; + used.add(key); + } else if (!used.add(key)) { + // Defensive: a held key is only reused once even if input unexpectedly + // splits one turn into two rows; duplicate widget keys would throw. + key = 'chat-row-$kind-${_serial++}'; + used.add(key); + } + keys.add(key); + for (final id in ids) { + nextByMessageId[id] = key; + } + } + _byMessageId + ..clear() + ..addAll(nextByMessageId); + return keys; + } + + static List _messageIds(JsonMap row) { + final listed = row['messageIds']; + if (listed is List) { + return listed + .map((id) => '$id'.trim()) + .where((id) => id.isNotEmpty) + .toList(); + } + final key = '${row['key'] ?? ''}'.trim(); + return key.isEmpty ? const [] : [key]; + } +} diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart new file mode 100644 index 00000000..b5257ab9 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -0,0 +1,195 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../domain/chat_transcript.dart'; +import '../ui/sessions/chat_adaptive.dart'; +import '../ui/transcript/chat_message_view.dart'; +import 'chat_row_keys.dart'; +import 'chat_thread_controller.dart'; + +/// One read-only conversation: the controller's transcript in the order the +/// server reports it, rendered by the existing [ChatMessageView]. +/// +/// History and live-subscription failures are separate notices: readable stored +/// history must never hide a refused live watch. The shell owns the navigation +/// bar, so this view adds only its own Back control and content. +class ChatThreadView extends StatefulWidget { + const ChatThreadView({ + super.key, + required this.gateway, + required this.sessionId, + required this.onBack, + this.title = '', + this.syncToken = 0, + }); + + final ApiGateway gateway; + final String sessionId; + final VoidCallback onBack; + + /// The list row's title when this visit knows it; a deep link may not. + final String title; + + /// Advances when the shared socket is replaced, keeping this selection. + final int syncToken; + + @override + State createState() => _ChatThreadViewState(); +} + +class _ChatThreadViewState extends State { + late ChatThreadController _controller = _attach(); + late ChatRowKeys _rowKeys = ChatRowKeys(); + + ChatThreadController _attach() => + ChatThreadController(widget.gateway, widget.sessionId)..load(); + + @override + void didUpdateWidget(covariant ChatThreadView oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.gateway != widget.gateway || + oldWidget.sessionId != widget.sessionId) { + _controller.dispose(); + _controller = _attach(); + _rowKeys = ChatRowKeys(); + } else if (oldWidget.syncToken != widget.syncToken) { + unawaited(_controller.resync()); + } + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => AnimatedBuilder( + animation: _controller, + builder: (context, _) { + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final rows = transcriptRows(_controller.messages); + // Older pages prepend messages and a live frame can append one, so a + // folded assistant turn's first message id is not a stable identity. + // ChatRowKeys carries a turn's key forward while it still holds any of + // its previous messages, keeping the element (and its open disclosures) + // across paging and streaming. + final keys = _rowKeys.forRows(rows); + final initialLoad = !_controller.loaded && _controller.loading; + return ListView( + key: ValueKey('chat-thread-${widget.sessionId}'), + padding: const EdgeInsets.symmetric(vertical: 8), + children: [ + Padding( + key: const Key('chat-thread-header'), + padding: const EdgeInsetsDirectional.fromSTEB(8, 0, 16, 4), + child: Wrap( + spacing: 8, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + _backButton(cupertino), + if (widget.title.trim().isNotEmpty) + Text( + widget.title.trim(), + style: cupertino + ? CupertinoTheme.of(context).textTheme.navTitleTextStyle + : Theme.of(context).textTheme.titleLarge, + ), + ], + ), + ), + if (initialLoad) + Padding( + key: const Key('chat-thread-loading'), + padding: const EdgeInsets.all(16), + child: Center( + child: cupertino + ? const CupertinoActivityIndicator() + : const CircularProgressIndicator(), + ), + ), + if (_controller.hasMore) + Padding( + key: const Key('chat-load-older'), + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Align( + alignment: AlignmentDirectional.centerStart, + child: cupertino + ? CupertinoButton( + padding: EdgeInsets.zero, + onPressed: _controller.loading + ? null + : _controller.loadOlder, + child: const Text('Load older'), + ) + : TextButton( + onPressed: _controller.loading + ? null + : _controller.loadOlder, + child: const Text('Load older'), + ), + ), + ), + if (_controller.error != null) + ChatErrorNotice( + key: const Key('chat-history-error'), + message: 'Chat history unavailable\n${_controller.error}', + onRetry: _controller.load, + ), + if (_controller.subscriptionError != null) + ChatErrorNotice( + key: const Key('chat-live-error'), + message: + 'Live updates unavailable\n${_controller.subscriptionError}', + onRetry: _controller.resync, + ), + if (_controller.loaded && rows.isEmpty && _controller.error == null) + const Padding( + key: Key('chat-thread-empty'), + padding: EdgeInsets.all(16), + child: Text('No messages in this chat yet.'), + ), + for (var index = 0; index < rows.length; index++) + Padding( + key: ValueKey(keys[index]), + padding: const EdgeInsets.symmetric(horizontal: 16), + child: ChatMessageView(row: rows[index]), + ), + if (_controller.running) + Padding( + key: const Key('chat-running'), + padding: const EdgeInsets.all(16), + child: Semantics( + liveRegion: true, + child: const Text('Assistant is responding…'), + ), + ), + ], + ); + }, + ); + + Widget _backButton(bool cupertino) => cupertino + ? CupertinoButton( + padding: const EdgeInsetsDirectional.fromSTEB(8, 0, 8, 0), + onPressed: widget.onBack, + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(CupertinoIcons.back), + SizedBox(width: 4), + Text('Back'), + ], + ), + ) + : TextButton.icon( + onPressed: widget.onBack, + icon: const Icon(Icons.arrow_back), + label: const Text('Back to chats'), + ); +} diff --git a/app/lib/features/chat/domain/chat_transcript.dart b/app/lib/features/chat/domain/chat_transcript.dart index b766f15e..b9f54459 100644 --- a/app/lib/features/chat/domain/chat_transcript.dart +++ b/app/lib/features/chat/domain/chat_transcript.dart @@ -34,25 +34,36 @@ JsonMap mergeChatHistory(JsonMap previous, JsonMap page, {bool older = false}) { /// Consecutive assistant messages form one answer turn. All part fields (also /// future/unknown protocol types) are preserved in original order. +/// +/// `key` is the turn's first assistant message id, which is only a display +/// anchor: paging an older assistant message into the turn changes it, so widget +/// identity uses `messageIds`. That list carries every message the folded turn +/// currently holds so the view can keep the same row element while the turn +/// grows at either end. List transcriptRows(List messages) { final rows = []; String? key; + final ids = []; final parts = []; void flush() { if (key != null && parts.isNotEmpty) { rows.add({ 'kind': 'assistant', 'key': key, + 'messageIds': List.of(ids), 'parts': List.of(parts), }); } key = null; + ids.clear(); parts.clear(); } for (final message in messages) { if (message['role'] == 'assistant') { - key ??= '${message['id'] ?? ''}'; + final id = '${message['id'] ?? ''}'.trim(); + key ??= id; + if (id.isNotEmpty) ids.add(id); for (final part in (message['parts'] as List? ?? const [])) { if (part is Map) parts.add(Map.from(part)); } diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart new file mode 100644 index 00000000..f2859581 --- /dev/null +++ b/app/lib/features/chat/screen.dart @@ -0,0 +1,99 @@ +import 'package:flutter/material.dart'; + +import '../../core/api_gateway.dart'; +import 'conversation/chat_thread_view.dart'; +import 'ui/sessions/chat_sessions_screen.dart'; + +/// The Chat destination's list/detail switch. +/// +/// The route names the open session, so a row tap, a deep link and Back all +/// navigate through the same value. The session list stays mounted (offstage) +/// while a conversation is open, so returning to it keeps its rows and query. +/// The shell owns the app bar; this screen adds no second one. +class ChatScreen extends StatefulWidget { + const ChatScreen({ + super.key, + required this.gateway, + this.initialSessionId, + this.syncToken = 0, + this.onSessionSelected, + this.onBack, + }); + + final ApiGateway gateway; + + /// The chat session the current route names, or null for the list. + final String? initialSessionId; + + /// Advances when the shared socket is replaced. The open conversation + /// re-subscribes and re-reads in place, so its selection survives. + final int syncToken; + + final ValueChanged? onSessionSelected; + final VoidCallback? onBack; + + @override + State createState() => _ChatScreenState(); +} + +class _ChatScreenState extends State { + /// Rows opened in this visit, used only for the native title. A deep link has + /// no title until the list loads, and this screen waits for no list request. + final Map _titles = {}; + String? _standaloneSelection; + + String? get _selected { + final routed = widget.initialSessionId; + if (routed != null && routed.isNotEmpty) return routed; + return _standaloneSelection; + } + + void _open(JsonMap session) { + final id = '${session['id'] ?? ''}'; + if (id.isEmpty) return; + final title = '${session['title'] ?? ''}'.trim(); + if (title.isNotEmpty) _titles[id] = title; + final select = widget.onSessionSelected; + if (select != null) { + select(id); + } else { + setState(() => _standaloneSelection = id); + } + } + + void _back() { + final back = widget.onBack; + if (back != null) { + back(); + } else { + setState(() => _standaloneSelection = null); + } + } + + @override + Widget build(BuildContext context) { + final selected = _selected; + return Stack( + children: [ + Offstage( + offstage: selected != null, + child: ChatSessionsScreen( + gateway: widget.gateway, + embedded: true, + syncToken: widget.syncToken, + onOpen: _open, + ), + ), + if (selected != null) + ChatThreadView( + key: ValueKey('chat-session-$selected'), + gateway: widget.gateway, + sessionId: selected, + title: _titles[selected] ?? '', + syncToken: widget.syncToken, + onBack: _back, + ), + ], + ); + } +} diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart index ff345739..f15311f1 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; @@ -16,10 +18,19 @@ class ChatSessionsScreen extends StatefulWidget { super.key, required this.gateway, required this.onOpen, + this.embedded = false, + this.syncToken = 0, }); final ApiGateway gateway; final void Function(JsonMap session) onOpen; + /// True under the application shell, which owns the single navigation bar. + final bool embedded; + + /// Advances when the shared socket is replaced; sessions created, renamed or + /// closed elsewhere during the gap must not stay invisible until Refresh. + final int syncToken; + @override State createState() => _ChatSessionsScreenState(); } @@ -35,6 +46,8 @@ class _ChatSessionsScreenState extends State { super.didUpdateWidget(oldWidget); if (oldWidget.gateway != widget.gateway) { _controller.replaceRepository(ChatRepository(widget.gateway)); + } else if (oldWidget.syncToken != widget.syncToken) { + unawaited(_controller.refresh()); } } @@ -115,53 +128,38 @@ class _ChatSessionsScreenState extends State { ], ); + if (widget.embedded) { + return Column( + children: [ + Align( + alignment: AlignmentDirectional.centerEnd, + child: Padding( + padding: const EdgeInsetsDirectional.only(end: 8), + child: Row( + mainAxisSize: MainAxisSize.min, + children: _actions(), + ), + ), + ), + Expanded(child: body), + ], + ); + } + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { return CupertinoPageScaffold( navigationBar: CupertinoNavigationBar( middle: const Text('Chats'), trailing: Row( mainAxisSize: MainAxisSize.min, - children: [ - ChatBarAction( - key: const Key('chat-new-chat'), - label: 'New chat', - onPressed: _newChat, - materialIcon: Icons.add, - cupertinoIcon: CupertinoIcons.add, - ), - ChatBarAction( - key: const Key('chat-refresh'), - label: 'Refresh', - onPressed: _controller.refresh, - materialIcon: Icons.refresh, - cupertinoIcon: CupertinoIcons.refresh, - ), - ], + children: _actions(), ), ), child: SafeArea(child: body), ); } return Scaffold( - appBar: AppBar( - title: const Text('Chats'), - actions: [ - ChatBarAction( - key: const Key('chat-new-chat'), - label: 'New chat', - onPressed: _newChat, - materialIcon: Icons.add, - cupertinoIcon: CupertinoIcons.add, - ), - ChatBarAction( - key: const Key('chat-refresh'), - label: 'Refresh', - onPressed: _controller.refresh, - materialIcon: Icons.refresh, - cupertinoIcon: CupertinoIcons.refresh, - ), - ], - ), + appBar: AppBar(title: const Text('Chats'), actions: _actions()), body: body, floatingActionButton: FloatingActionButton.extended( key: const Key('chat-new-chat-fab'), @@ -173,4 +171,21 @@ class _ChatSessionsScreenState extends State { }, ); } + + List _actions() => [ + ChatBarAction( + key: const Key('chat-new-chat'), + label: 'New chat', + onPressed: _newChat, + materialIcon: Icons.add, + cupertinoIcon: CupertinoIcons.add, + ), + ChatBarAction( + key: const Key('chat-refresh'), + label: 'Refresh', + onPressed: _controller.refresh, + materialIcon: Icons.refresh, + cupertinoIcon: CupertinoIcons.refresh, + ), + ]; } diff --git a/app/lib/features/chat/ui/transcript/chat_message_view.dart b/app/lib/features/chat/ui/transcript/chat_message_view.dart index 953da8b4..3cb022d3 100644 --- a/app/lib/features/chat/ui/transcript/chat_message_view.dart +++ b/app/lib/features/chat/ui/transcript/chat_message_view.dart @@ -92,13 +92,34 @@ class ChatMessageView extends StatelessWidget { List _agentParts(BuildContext context) { final widgets = []; - for (final part in _partsOf(row)) { + final parts = _partsOf(row); + final seen = {}; + for (var index = 0; index < parts.length; index++) { + final part = parts[index]; final widget = _agentPart(context, part); - if (widget != null) widgets.add(widget); + if (widget == null) continue; + // Part identity, not position, so an older assistant message that folds + // into the same turn can prepend its parts without moving an open + // disclosure. The enclosing row's identity is carried by ChatRowKeys; a + // part with no server id still falls back to its position. + widgets.add( + KeyedSubtree(key: _partKey(part, index, seen), child: widget), + ); } return widgets; } + /// The server's part id when there is one, else this part's position. A + /// repeated identity gets an ordinal so two sibling keys never collide. + Key _partKey(JsonMap part, int index, Map seen) { + final type = '${part['type'] ?? ''}'; + final id = '${part['id'] ?? ''}'.trim(); + final base = id.isEmpty ? 'index-$index' : '$type:$id'; + final ordinal = (seen[base] ?? 0) + 1; + seen[base] = ordinal; + return ValueKey('chat-part-$base-$ordinal'); + } + /// One agent part, or null when a known part has nothing to draw. The web's /// `partRendering` hides blank text/reasoning too, so a blank known part must /// not fall through to the unknown-part disclosure. diff --git a/app/notes/C2-wire.md b/app/notes/C2-wire.md new file mode 100644 index 00000000..c45fb1e4 --- /dev/null +++ b/app/notes/C2-wire.md @@ -0,0 +1,139 @@ +# C2-wire — Chat session list to read-only conversation + +The Chat tab is now the real session browser plus a selected read-only thread. +The shell registers a normal Chat destination, `/chat/:id` is a real history +entry, and the existing `ChatThreadController`/`ChatMessageView` render the +stored transcript. No composer, markdown, forms, metrics, attachments, new +socket, server or platform change is included. + +## Behavior + +- The destination renders the list at `/chat`; tapping a row records + `/chat/`, and Back (the in-page control, browser Back, or system + back through `AppRouterDelegate.popRoute`) returns to `/chat`. The list stays + mounted offstage, so its rows, grouping, search text and actions survive the + round trip. +- `/chat/:id` opens the exact session. Parsing is total and matches the web + parser: a nonempty, bounded, URL-safe id is accepted after percent-decoding; + malformed escapes, extra segments and invalid ids resolve to the default + Pipelines route rather than throwing. The route serialises through + `Uri.encodeComponent`. +- Before the shared socket has ever connected, the destination shows the normal + connection screen and sends no chat request. It never opens its own socket or + subscribes outside the shared `AppSession`. +- The selected thread subscribes that one session, reads the newest history + page (`limit: 200`, empty cursor), renders `transcriptRows` with + `ChatMessageView`, and folds pushed `chat_event` frames for that session only. + Live text/reasoning/tool parts use the landed native surfaces; reasoning and + tools stay collapsed until opened. +- `Load older` is shown only while the server says `has_more`; the server's + `next_cursor` is passed back verbatim and is never parsed. Paging prepends + messages, and a page boundary can fall inside one folded assistant turn (the + repository's paged history fixture pages consecutive assistant messages). A + turn's first message id is therefore not widget identity: `ChatRowKeys` + carries each turn's key forward while it still holds a message it had before, + and each agent part carries its server id. An open reasoning/tool disclosure + stays on the answer the operator opened, whether the older page extends a turn + at its head or the `Load older` control disappears. A part without a server id + still falls back to its position; server history parts carry ids. +- `ChatThreadController.subscriptionError` and history `error` render as two + separate notices with separate Retry actions. Readable stored history can + therefore never hide a refused live watch. Initial loading, a running turn + and an honest empty transcript each have their own state. +- On reconnect, `connectionEpoch` advances the thread's `syncToken`; the + mounted view re-subscribes and replaces the transcript in place, keeping the + selected session id and route. A session change mounts a keyed view, so a + superseded read from the previous session cannot land in the new thread. The + offstage session list also re-reads on the same token, so a session created, + renamed or closed on another device during the socket gap appears without + pressing Refresh. +- The shell owns the only navigation bar. `ChatSessionsScreen` gained a small + `embedded` flag: under the shell it renders a compact action row for New chat + and Refresh instead of a second `AppBar`/`CupertinoNavigationBar`. Standalone + use keeps its previous native scaffolding. +- Deep links only carry the session id, so a directly opened thread may show no + title until it is opened from a list row. The transcript itself is complete + and honest; this is not treated as chat parity. + +## Files + +| Path | Lines | Role | +| --- | ---: | --- | +| `lib/features/chat/screen.dart` | 99 | List/thread switch, selection, in-page Back, reconnect token | +| `lib/features/chat/conversation/chat_thread_view.dart` | 195 | Keyed read-only transcript, paging, live/history notices | +| `lib/features/chat/conversation/chat_row_keys.dart` | 63 | Stable row identity while a folded turn grows at either end | +| `lib/features/chat/domain/chat_transcript.dart` | 246 | History merge, turn folding, live frame fold | +| `lib/features/chat/ui/transcript/chat_message_view.dart` | 218 | Agent parts keyed by part identity (disclosure state) | +| `lib/application/chat_destination.dart` | 69 | Connection gate/banner and shared session wiring | +| `lib/features/chat/ui/sessions/chat_sessions_screen.dart` | 191 | Embedded layout flag, actions, reconnect re-read | +| `lib/application/app_route.dart` | +30/−4 | `/chat/:id` parse, serialise, equality | +| `lib/application/app_router.dart` | +13/−3 | System Back callback for a chat session | +| `lib/application/pipelines_app.dart` | +9 | Destination registration and `/chat` route mapping | + +Focused tests: `test/application/chat_registration_test.dart`, +`test/application/chat_destination_test.dart`, `test/application/app_router_test.dart`, +`test/application/app_route_test.dart`, +`test/features/chat/conversation/chat_thread_view_test.dart`, +`test/features/chat/conversation/chat_row_keys_test.dart`. +The thread tests cover both paging variants (the older page keeps `has_more`, and +the older page ends history) in Material and Cupertino, for alternating pages and +for the assistant-only fixture shape. In every case the newest `Reasoning` stays +open and the older blocks stay collapsed. `chat_row_keys_test.dart` covers a +prepended assistant page, an appended live assistant message and distinct turns. +Probe: `tool/chat_wire_probe.dart` and `tool/chat_wire_probe.mjs` include both +alternating variants plus two assistant-fold sessions (`has_more` kept and ended). + +## Checks (actual) + +- `flutter test test/features/chat test/application` — **110 tests passed**. +- `flutter test` (full suite) — **696 tests passed**. +- `flutter analyze` — **No issues found**. +- `dart format --output=none --set-exit-if-changed` on the changed Dart files — + exit 0. +- `flutter build web` — built successfully. +- `flutter build web -t tool/chat_wire_probe.dart` for the Material and Cupertino + dark fixtures — both built successfully. +- `node tool/chat_wire_probe.mjs` against real headless Chrome for both hosts — + exit 0. Each run checked, with the semantics tree and OCR of the rendered + canvas: + - embedded list shows server rows and keeps New chat/Refresh; + - the thread shows the exact stored user body, assistant body, `Reasoning` and + `shell` disclosures while collapsed bodies stay hidden; + - `Load older` renders the opaque-cursor page; + - a pushed `chat_event` delta appends to the open thread; + - after expanding the newest `Reasoning`, paging with `has_more` still true and + paging that removes `Load older` both keep the newest body open and the older + body collapsed (`newestKept: true`, `olderLeaked: false` in both hosts); + - the assistant-fold sessions repeat that check with pages of consecutive + assistant messages, for both `has_more` outcomes. +- Captures and evidence JSON: `/Users/alan/.local/share/pipelines/data/artifacts/79/public/chat-fold-paging/` + (`{material,cupertino}-{list,thread,expanded,older,live,more-expanded,more-older,fold-expanded,fold-older,fold-end-expanded,fold-end-older}.png` + and `*-evidence.json`). These come from the standalone `ChatScreen` fixture. +- Normal-app rendered check: `/Users/alan/.local/share/pipelines/data/artifacts/79/public/chat-fold-app/` + has `{material,cupertino}-{fold,fold-end}-{collapsed,expanded,older}.png` and + `fold-app-evidence.json`, driven through the real `build/web` composition and + the real router at `/chat/`. Material is a Linux UA in light mode, + Cupertino the macOS host in dark mode. Both hosts and both `has_more` outcomes + report `newestKept: true`, `olderLeaked: false`, and the expected `Load older` + presence; no page exceptions. + +Not done: composer, markdown rendering, attachments, forms, permissions, model +selection, metrics, shells, and the initial newest-message placement / live +follow scroll behaviour remain the tracked next chat items. The transcript is +still an eager, keyed `ListView` so an open disclosure also survives while its +row is offscreen; moving to a lazy builder would need that expansion state to +live above the rows. Mobile builds/devices were not used or verified. Nothing +was committed, pushed, merged or deployed. + +## Manager completion after the Code deadline + +The final Code visit reached its 30-minute deadline while active; the session then +settled and all edits were retained. No retry was started. The manager ran the +focused application/chat suites (110 tests pass) and drove the fixture probes for +both hosts. Material and Cupertino each passed and wrote captures; the Cupertino +live capture was inspected and shows the read-only conversation with the exact +user text, the stored assistant reply, collapsed Reasoning/tool disclosures, the +live delta and the responding line, all under the shell's single bar. + +Scope stays read-only: no composer, markdown rendering, forms, approvals, metrics +or attachments are claimed by this item. diff --git a/app/test/application/app_route_test.dart b/app/test/application/app_route_test.dart index 598dce52..eb2968d3 100644 --- a/app/test/application/app_route_test.dart +++ b/app/test/application/app_route_test.dart @@ -7,6 +7,10 @@ void main() { expect(AppRoute.parse('/runs'), AppRoute.runs); expect(AppRoute.parse('/runs/12'), AppRoute.run(12)); expect(AppRoute.parse('/chat'), AppRoute.chat); + expect( + AppRoute.parse('/chat/abc_DEF-123'), + AppRoute.chatSession('abc_DEF-123'), + ); expect(AppRoute.parse('/settings'), AppRoute.settings); }); @@ -18,6 +22,14 @@ void main() { AppRoute.run(7), ); expect(AppRoute.parse('/runs/7/'), AppRoute.run(7)); + expect( + AppRoute.parse('/chat/session/?x=1'), + AppRoute.chatSession('session'), + ); + expect( + AppRoute.parse('/chat/probe%2Dchat'), + AppRoute.chatSession('probe-chat'), + ); }); test('a malformed or unknown location is the default Pipelines route', () { @@ -29,7 +41,9 @@ void main() { '/runs/-1', '/runs/1/extra', '/pipelines/2', - '/chat/session', + '/chat/a/b', + '/chat/%2F', + '/chat/${'x' * 201}', '/unknown', '/runs/%E0%A4%A', ]) { @@ -43,10 +57,13 @@ void main() { AppRoute.runs, AppRoute.run(3), AppRoute.chat, + AppRoute.chatSession('probe_open-1'), AppRoute.settings, ]) { expect(AppRoute.parse(route.path), route); } expect(AppRoute.run(3).path, '/runs/3'); + expect(AppRoute.chatSession('probe_open-1').path, '/chat/probe_open-1'); + expect(AppRoute.chatSession('bad id').path, '/chat'); }); } diff --git a/app/test/application/app_router_test.dart b/app/test/application/app_router_test.dart new file mode 100644 index 00000000..e713f173 --- /dev/null +++ b/app/test/application/app_router_test.dart @@ -0,0 +1,31 @@ +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/app_route.dart'; +import 'package:pipelines_app/application/app_router.dart'; + +AppRouterDelegate delegate(AppRoute initial, {void Function()? onChat}) => + AppRouterDelegate( + builder: (context, route) => const SizedBox.shrink(), + onPopToRuns: () {}, + onPopToChat: onChat ?? () {}, + cupertino: false, + initial: initial, + ); + +void main() { + test('system Back leaves one chat session for the chat list', () async { + var left = 0; + final router = delegate(AppRoute.chatSession('s1'), onChat: () => left++); + addTearDown(router.dispose); + + expect(await router.popRoute(), isTrue); + expect(left, 1); + }); + + test('system Back on a list destination stays with the platform', () async { + final router = delegate(AppRoute.chat); + addTearDown(router.dispose); + + expect(await router.popRoute(), isFalse); + }); +} diff --git a/app/test/application/chat_destination_test.dart b/app/test/application/chat_destination_test.dart new file mode 100644 index 00000000..eaca79ae --- /dev/null +++ b/app/test/application/chat_destination_test.dart @@ -0,0 +1,113 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/app_session.dart'; +import 'package:pipelines_app/application/chat_destination.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; + +import '../core/transport/pipelines_client_test.dart' show FakeChannel; +import 'chat_registration_test.dart' + show + replyHistory, + replySessions, + replySubscribe, + requestOf, + waitForRequest, + webServer; + +Widget host(AppSession session, {String? initialSessionId}) => MaterialApp( + home: Scaffold( + body: ChatDestination( + session: session, + server: webServer(), + initialSessionId: initialSessionId, + ), + ), +); + +void main() { + testWidgets('nothing is requested before the shared socket is ready', ( + tester, + ) async { + final channel = FakeChannel(); + final client = PipelinesClient(channelFactory: (_) => channel); + final server = webServer(); + final session = AppSession(endpoint: server.uri, client: client); + addTearDown(session.dispose); + + final starting = session.start(); + await tester.pumpWidget(host(session, initialSessionId: 's1')); + expect(find.text('Connecting to Pipelines…'), findsOneWidget); + expect(find.byType(ChatThreadView), findsNothing); + expect(channel.outgoing, isEmpty); + + channel.readyCompleter.complete(); + await starting; + }); + + testWidgets('a reconnect resyncs the open session without losing it', ( + tester, + ) async { + final first = FakeChannel()..readyCompleter.complete(); + final second = FakeChannel()..readyCompleter.complete(); + var sockets = 0; + final client = PipelinesClient( + channelFactory: (_) => sockets++ == 0 ? first : second, + backoffBase: const Duration(milliseconds: 10), + ); + final server = webServer(); + final session = AppSession(endpoint: server.uri, client: client); + addTearDown(session.dispose); + + await session.start(); + await tester.pumpWidget(host(session, initialSessionId: 's1')); + await tester.pump(); + + await replySessions(tester, first); + await replySubscribe(tester, first); + await replyHistory(tester, first); + expect(find.text('The stored reply stays readable.'), findsOneWidget); + + first.incoming.addError(StateError('network drop')); + await tester.pump(); + expect(find.byType(ChatThreadView), findsOneWidget); + expect(find.text('The stored reply stays readable.'), findsOneWidget); + + // The mounted session list re-reads on reconnect: a session created while + // the socket was gone must not stay invisible until Refresh. Requests are + // serialized, so this reply also lets the thread's resync proceed. + final relisted = await waitForRequest(tester, second, 'chat_sessions'); + second.incoming.add( + jsonEncode({ + 'id': relisted['id'], + 'type': 'chat_sessions', + 'chat_sessions': [ + {'id': 's1', 'title': 'Wire chat'}, + {'id': 's2', 'title': 'Created while offline'}, + ], + }), + ); + await tester.pump(); + + final resubscribe = await waitForRequest(tester, second, 'chat_subscribe'); + second.incoming.add( + jsonEncode({'id': resubscribe['id'], 'type': 'chat_subscribe'}), + ); + await tester.pump(); + await replyHistory(tester, second, text: 'Refreshed after reconnect.'); + expect(find.byType(ChatThreadView), findsOneWidget); + expect(find.text('Refreshed after reconnect.'), findsOneWidget); + expect(find.text('The stored reply stays readable.'), findsNothing); + expect(requestOf(second, 'chat_messages')!['chat_query'], { + 'session_id': 's1', + 'limit': 200, + 'cursor': '', + }); + expect( + find.text('Created while offline', skipOffstage: false), + findsOneWidget, + ); + }); +} diff --git a/app/test/application/chat_registration_test.dart b/app/test/application/chat_registration_test.dart new file mode 100644 index 00000000..91a452a1 --- /dev/null +++ b/app/test/application/chat_registration_test.dart @@ -0,0 +1,235 @@ +import 'dart:convert'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/pipelines_app.dart'; +import 'package:pipelines_app/application/server_endpoint.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_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, +); + +Map? requestOf( + FakeChannel channel, + String type, { + int index = 0, +}) => channel.outgoing + .map((frame) => jsonDecode(frame as String) as Map) + .where((frame) => frame['type'] == type) + .skip(index) + .firstOrNull; + +Future> 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 replySessions( + WidgetTester tester, + FakeChannel channel, { + int index = 0, +}) async { + final request = await waitForRequest( + tester, + channel, + 'chat_sessions', + index: index, + ); + channel.incoming.add( + jsonEncode({ + 'id': request['id'], + 'type': 'chat_sessions', + 'chat_sessions': [ + {'id': 's1', 'title': 'Wire chat', 'directory': '/workspace/demo'}, + ], + }), + ); + await tester.pump(); +} + +Future replySubscribe( + WidgetTester tester, + FakeChannel channel, { + int index = 0, +}) async { + final request = await waitForRequest( + tester, + channel, + 'chat_subscribe', + index: index, + ); + channel.incoming.add( + jsonEncode({'id': request['id'], 'type': 'chat_subscribe'}), + ); + await tester.pump(); + await tester.pump(); +} + +Future replyHistory( + WidgetTester tester, + FakeChannel channel, { + int index = 0, + String text = 'The stored reply stays readable.', +}) async { + final request = await waitForRequest( + tester, + channel, + 'chat_messages', + index: index, + ); + channel.incoming.add( + jsonEncode({ + 'id': request['id'], + 'type': 'chat_history', + 'chat_history': { + 'messages': [ + { + 'id': 'u1', + 'role': 'user', + 'parts': [ + {'type': 'text', 'text': 'Open this chat from its route.'}, + ], + }, + { + 'id': 'a1', + 'role': 'assistant', + 'parts': [ + {'type': 'text', 'text': text}, + {'type': 'reasoning', 'text': 'Kept behind a native disclosure.'}, + {'type': 'tool', 'name': 'shell'}, + ], + }, + ], + 'next_cursor': '', + 'has_more': false, + }, + }), + ); + await tester.pump(); + await tester.pump(); +} + +void main() { + for (final cupertino in [false, true]) { + testWidgets( + 'a /chat/s1 deep link renders that thread and Back returns to /chat ($cupertino)', + (tester) async { + tester.view.physicalSize = const Size(900, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + if (cupertino) { + tester.platformDispatcher.platformBrightnessTestValue = + Brightness.dark; + addTearDown( + tester.platformDispatcher.clearPlatformBrightnessTestValue, + ); + } + + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation(uri: Uri.parse('/chat/s1')), + ); + addTearDown(provider.dispose); + + await tester.pumpWidget( + PipelinesApp( + server: webServer(), + client: client, + cupertino: cupertino, + routeInformationProvider: provider, + ), + ); + await tester.pump(); + + await replySessions(tester, channel); + await replySubscribe(tester, channel); + await replyHistory(tester, channel); + + expect(provider.value.uri.path, '/chat/s1'); + expect(find.byType(ChatThreadView), findsOneWidget); + // The exact route names the session; the request carries the same id. + expect(requestOf(channel, 'chat_subscribe')!['chat_subscribe'], { + 'session_id': 's1', + }); + expect(requestOf(channel, 'chat_messages')!['chat_query'], { + 'session_id': 's1', + 'limit': 200, + 'cursor': '', + }); + expect(find.text('The stored reply stays readable.'), findsOneWidget); + expect(find.text('Reasoning'), findsOneWidget); + expect(find.text('shell'), findsOneWidget); + expect(find.text('Kept behind a native disclosure.'), findsNothing); + + // One shell bar only: the embedded list/thread adds no second one. + if (cupertino) { + expect(find.byType(CupertinoNavigationBar), findsOneWidget); + expect(find.byType(AppBar), findsNothing); + } else { + expect(find.byType(AppBar), findsOneWidget); + expect(find.byType(CupertinoNavigationBar), findsNothing); + } + + // A live frame updates the held thread. + channel.incoming.add( + jsonEncode({ + 'type': 'chat_event', + 'chat_event': { + 'session_id': 's1', + 'message_id': 'a1', + 'kind': 'text', + 'part': {'id': 'p2', 'type': 'text'}, + 'delta': 'A live line arrived.', + }, + }), + ); + await tester.pump(); + await tester.pump(); + expect(find.text('A live line arrived.'), findsOneWidget); + + await tester.tap(find.text(cupertino ? 'Back' : 'Back to chats')); + await tester.pump(); + expect(provider.value.uri.path, '/chat'); + expect(find.byType(ChatThreadView), findsNothing); + expect(find.byType(ChatSessionsScreen), findsOneWidget); + expect(find.text('Wire chat'), findsOneWidget); + + // Browser Forward re-opens the same session through its route. + await provider.didPushRouteInformation( + RouteInformation(uri: Uri.parse('/chat/s1')), + ); + await tester.pump(); + expect(provider.value.uri.path, '/chat/s1'); + await replySubscribe(tester, channel, index: 1); + await replyHistory( + tester, + channel, + index: 1, + text: 'Reopened from the route.', + ); + expect(find.text('Reopened from the route.'), findsOneWidget); + + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + }, + ); + } +} diff --git a/app/test/features/chat/conversation/chat_row_keys_test.dart b/app/test/features/chat/conversation/chat_row_keys_test.dart new file mode 100644 index 00000000..b57e5b9e --- /dev/null +++ b/app/test/features/chat/conversation/chat_row_keys_test.dart @@ -0,0 +1,101 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_row_keys.dart'; +import 'package:pipelines_app/features/chat/domain/chat_transcript.dart'; + +import 'chat_thread_fixtures.dart'; + +JsonMap _assistant(String id) => chatMessage( + id, + 'assistant', + parts: [ + {'type': 'reasoning', 'id': 'r-$id', 'text': 'reasoning $id'}, + {'type': 'text', 'id': 't-$id', 'text': 'answer $id'}, + ], +); + +JsonMap _user(String id) => chatMessage( + id, + 'user', + parts: [ + {'type': 'text', 'text': 'question $id'}, + ], +); + +void main() { + test('an older page prepended into a folded turn keeps its key', () { + final keys = ChatRowKeys(); + final newest = keys.forRows( + transcriptRows([_assistant('msg_6'), _assistant('msg_4')]), + ); + final paged = keys.forRows( + transcriptRows([ + _assistant('msg_2'), + _assistant('msg_0'), + _assistant('msg_6'), + _assistant('msg_4'), + ]), + ); + + expect(newest, hasLength(1)); + expect(paged, hasLength(1)); + expect(paged.single, newest.single); + }); + + test('a live assistant message appended to a folded turn keeps its key', () { + final keys = ChatRowKeys(); + final newest = keys.forRows(transcriptRows([_assistant('msg_6')])); + final streamed = keys.forRows( + transcriptRows([_assistant('msg_6'), _assistant('msg_live')]), + ); + + expect(streamed.single, newest.single); + }); + + test('user rows keep their key and folded turns stay distinct', () { + final keys = ChatRowKeys(); + final first = keys.forRows( + transcriptRows([ + _user('u1'), + _assistant('a1'), + _user('u2'), + _assistant('a2'), + ]), + ); + final paged = keys.forRows( + transcriptRows([ + _user('u0'), + _assistant('a0'), + _user('u1'), + _assistant('a1'), + _user('u2'), + _assistant('a2'), + ]), + ); + + expect(first.toSet(), hasLength(4)); + expect(paged.toSet(), hasLength(6)); + expect(paged.sublist(2), first); + }); + + test('an id-less prepended turn never collides with a held key', () { + final keys = ChatRowKeys(); + keys.forRows(transcriptRows([_assistant('a1')])); + final paged = keys.forRows( + transcriptRows([ + // No id: only a positional fallback is possible. + chatMessage( + '', + 'assistant', + parts: [ + {'type': 'text', 'text': 'anonymous older answer'}, + ], + ), + _user('u1'), + _assistant('a1'), + ]), + ); + + expect(paged.toSet(), hasLength(paged.length)); + }); +} diff --git a/app/test/features/chat/conversation/chat_thread_view_test.dart b/app/test/features/chat/conversation/chat_thread_view_test.dart new file mode 100644 index 00000000..54cdb555 --- /dev/null +++ b/app/test/features/chat/conversation/chat_thread_view_test.dart @@ -0,0 +1,368 @@ +import 'dart:async'; + +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/chat/conversation/chat_thread_view.dart'; + +import 'chat_thread_fixtures.dart'; + +Widget host(Widget child) => MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + home: Scaffold(body: child), +); + +Widget cupertinoHost(Widget child) => CupertinoApp( + theme: const CupertinoThemeData(brightness: Brightness.dark), + home: CupertinoPageScaffold(child: child), +); + +void main() { + testWidgets('live-subscription refusal is separate from readable history', ( + tester, + ) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.subscribe = () async => throw StateError('live watch refused'); + gateway.history = (_) async => chatPage([ + chatMessage( + 'u1', + 'user', + parts: [ + {'type': 'text', 'text': 'History still renders.'}, + ], + ), + ]); + + await tester.pumpWidget( + host(ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {})), + ); + await tester.pumpAndSettle(); + + expect(find.text('History still renders.'), findsOneWidget); + expect(find.byKey(const Key('chat-live-error')), findsOneWidget); + expect(find.textContaining('Live updates unavailable'), findsOneWidget); + expect(find.textContaining('live watch refused'), findsOneWidget); + expect(find.byKey(const Key('chat-history-error')), findsNothing); + + // A later resync that attaches clears only the live notice. + gateway.subscribe = () async => const {}; + gateway.history = (_) async => chatPage([ + chatMessage( + 'u1', + 'user', + parts: [ + {'type': 'text', 'text': 'History still renders.'}, + ], + ), + ]); + var attempts = 0; + for ( + var i = 0; + i < 80 && find.byKey(const Key('chat-live-error')).evaluate().isNotEmpty; + i++ + ) { + if (attempts == 0) { + await tester.tap(find.text('Retry').last); + attempts++; + } + await tester.pump(const Duration(milliseconds: 5)); + } + expect(find.byKey(const Key('chat-live-error')), findsNothing); + }); + + testWidgets('Load older passes the server cursor back and shows older text', ( + tester, + ) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => chatPage( + [ + chatMessage( + 'a2', + 'assistant', + parts: [ + {'type': 'text', 'text': 'Newest reply.'}, + ], + ), + ], + cursor: 'opaque/next?x=1', + hasMore: true, + ); + + await tester.pumpWidget( + host(ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {})), + ); + await tester.pumpAndSettle(); + + expect(find.text('Newest reply.'), findsOneWidget); + expect(find.text('Load older'), findsOneWidget); + + final older = Completer(); + gateway.history = (_) => older.future; + await tester.tap(find.text('Load older')); + await tester.pump(); + + expect(gateway.calls.last.fields['chat_query'], { + 'session_id': 's', + 'limit': 200, + 'cursor': 'opaque/next?x=1', + }); + older.complete( + chatPage( + [ + chatMessage( + 'a1', + 'assistant', + parts: [ + {'type': 'text', 'text': 'Older stored reply.'}, + ], + ), + ], + cursor: '', + hasMore: false, + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('Older stored reply.'), findsOneWidget); + expect(find.text('Newest reply.'), findsOneWidget); + expect(find.text('Load older'), findsNothing); + }); + + // Paging prepends messages, so an unkeyed transcript would reuse the element + // at a message's old index: the operator's open reasoning would move to the + // previous answer, or be dropped when `Load older` disappears. + for (final cupertino in [false, true]) { + testWidgets( + 'an open reasoning block stays on its answer while has_more remains ' + '($cupertino)', + (tester) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + var reads = 0; + gateway.history = (_) async => ++reads == 1 + ? pagedChatPage( + 'a2', + 'NEWEST reasoning body that belongs to the newest answer.', + cursor: 'opaque/older', + hasMore: true, + ) + : pagedChatPage( + 'a1', + 'OLDER reasoning body that must not steal the newest disclosure.', + cursor: 'opaque/older-2', + hasMore: true, + ); + + await tester.pumpWidget( + (cupertino ? cupertinoHost : host)( + ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Reasoning')); + await tester.pumpAndSettle(); + expect( + find.text('NEWEST reasoning body that belongs to the newest answer.'), + findsOneWidget, + ); + + await tester.tap(find.text('Load older')); + await tester.pumpAndSettle(); + + // Both answers are present; only the one the operator opened is open. + expect(find.text('Reasoning'), findsNWidgets(2)); + expect(find.text('Load older'), findsOneWidget); + expect( + find.text('NEWEST reasoning body that belongs to the newest answer.'), + findsOneWidget, + ); + expect( + find.text( + 'OLDER reasoning body that must not steal the newest disclosure.', + ), + findsNothing, + ); + }, + ); + + testWidgets( + 'an open reasoning block survives the removal of Load older ($cupertino)', + (tester) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + var reads = 0; + gateway.history = (_) async => ++reads == 1 + ? pagedChatPage( + 'a2', + 'NEWEST reasoning body that belongs to the newest answer.', + cursor: 'opaque/older', + hasMore: true, + ) + : pagedChatPage( + 'a1', + 'OLDER reasoning body that must not steal the newest disclosure.', + cursor: '', + hasMore: false, + ); + + await tester.pumpWidget( + (cupertino ? cupertinoHost : host)( + ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Reasoning')); + await tester.pumpAndSettle(); + expect( + find.text('NEWEST reasoning body that belongs to the newest answer.'), + findsOneWidget, + ); + + await tester.tap(find.text('Load older')); + await tester.pumpAndSettle(); + + expect(find.text('Reasoning'), findsNWidgets(2)); + expect(find.text('Load older'), findsNothing); + expect( + find.text('NEWEST reasoning body that belongs to the newest answer.'), + findsOneWidget, + ); + expect( + find.text( + 'OLDER reasoning body that must not steal the newest disclosure.', + ), + findsNothing, + ); + }, + ); + } + + // The repository's own paged-history fixture pages consecutive assistant + // messages, so an older page can prepend into the one folded turn. Its first + // message id changes; the row must still be the same element and keep the + // operator's open disclosure. + for (final cupertino in [false, true]) { + for (final keepsControl in [true, false]) { + testWidgets( + 'an open reasoning block in a folded assistant turn survives paging ' + '(keeps Load older: $keepsControl, $cupertino)', + (tester) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + var reads = 0; + gateway.history = (_) async => ++reads == 1 + ? assistantFoldPage( + const ['msg_6', 'msg_4'], + const [ + 'NEWEST folded reasoning body.', + 'FOURTH folded reasoning body.', + ], + cursor: 'opaque/fold', + hasMore: true, + ) + : assistantFoldPage( + const ['msg_2', 'msg_0'], + const [ + 'SECOND folded reasoning body.', + 'OLDEST folded reasoning body.', + ], + cursor: keepsControl ? 'opaque/fold-2' : '', + hasMore: keepsControl, + ); + + await tester.pumpWidget( + (cupertino ? cupertinoHost : host)( + ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}), + ), + ); + await tester.pumpAndSettle(); + + // Before paging the turn holds two messages, so two disclosures. + expect(find.text('Reasoning'), findsNWidgets(2)); + await tester.tap(find.text('Reasoning').first); + await tester.pumpAndSettle(); + expect(find.text('NEWEST folded reasoning body.'), findsOneWidget); + + await tester.tap(find.text('Load older')); + await tester.pumpAndSettle(); + + // All four assistant messages now fold into the same turn. The + // newest block stays open; no older block may open. + expect(find.text('Reasoning'), findsNWidgets(4)); + expect(find.text('NEWEST folded reasoning body.'), findsOneWidget); + expect(find.text('FOURTH folded reasoning body.'), findsNothing); + expect(find.text('SECOND folded reasoning body.'), findsNothing); + expect(find.text('OLDEST folded reasoning body.'), findsNothing); + expect( + find.text('Load older'), + keepsControl ? findsOneWidget : findsNothing, + ); + }, + ); + } + } +} + +/// The paged-history fixture shape: a page of consecutive assistant messages, +/// each with its own reasoning and text part. +JsonMap assistantFoldPage( + List ids, + List reasoning, { + required String cursor, + required bool hasMore, +}) => chatPage( + [ + for (var index = 0; index < ids.length; index++) + chatMessage( + ids[index], + 'assistant', + parts: [ + { + 'type': 'reasoning', + 'id': 'r-${ids[index]}', + 'text': reasoning[index], + }, + { + 'type': 'text', + 'id': 't-${ids[index]}', + 'text': 'Answer stored as ${ids[index]}.', + }, + ], + ), + ], + cursor: cursor, + hasMore: hasMore, +); + +/// A newest page with one user prompt and one answer carrying [reasoning]. +JsonMap pagedChatPage( + String answerId, + String reasoning, { + required String cursor, + required bool hasMore, +}) => chatPage( + [ + chatMessage( + 'u-$answerId', + 'user', + parts: [ + {'type': 'text', 'text': 'A question for $answerId.'}, + ], + ), + chatMessage( + answerId, + 'assistant', + parts: [ + {'type': 'reasoning', 'text': reasoning}, + {'type': 'text', 'text': 'The answer stored as $answerId.'}, + ], + ), + ], + cursor: cursor, + hasMore: hasMore, +); diff --git a/app/tool/chat_wire_probe.dart b/app/tool/chat_wire_probe.dart new file mode 100644 index 00000000..dcd07254 --- /dev/null +++ b/app/tool/chat_wire_probe.dart @@ -0,0 +1,255 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/screen.dart'; + +/// Browser fixture for the Chat destination wiring: the real session list opens +/// the real controller/view against a scripted gateway. Server data only; no +/// composer, routes, sockets or production store are involved. +/// +/// Sessions page with different server answers so the driver can reproduce the +/// disclosure-state variants: alternating turns with the older page keeping or +/// ending history, and pages of consecutive assistant messages that fold into +/// one turn at the page boundary. +class _FixtureGateway implements ApiGateway { + final _frames = StreamController.broadcast(); + + @override + Stream get frames => _frames.stream; + + void _pushLiveDelta() { + Timer(const Duration(milliseconds: 500), () { + _frames.add({ + 'type': 'chat_event', + 'chat_event': { + 'session_id': 'probe-session', + 'message_id': 'a-NEWEST', + 'kind': 'text', + 'part': {'id': 'p-live', 'type': 'text'}, + 'delta': 'A live delta updated this thread.', + }, + }); + }); + } + + @override + Future call(String type, [JsonMap fields = const {}]) async { + switch (type) { + case 'chat_sessions': + return { + 'chat_sessions': [ + { + 'id': 'probe-session', + 'title': 'Probe conversation', + 'directory': '/workspace/demo', + 'starred': true, + }, + { + 'id': 'probe-more', + 'title': 'Probe paging session', + 'directory': '/workspace/demo', + }, + { + 'id': 'probe-other', + 'title': 'Another stored chat', + 'directory': '/workspace/demo', + }, + { + 'id': 'probe-fold', + 'title': 'Probe assistant fold session', + 'directory': '/workspace/demo', + }, + { + 'id': 'probe-fold-end', + 'title': 'Probe assistant fold last page', + 'directory': '/workspace/demo', + }, + ], + }; + case 'chat_subscribe': + return {}; + case 'chat_messages': + final query = fields['chat_query'] as Map? ?? const {}; + final cursor = '${query['cursor'] ?? ''}'; + if (query['session_id'] == 'probe-fold' || + query['session_id'] == 'probe-fold-end') { + final keepsPaging = query['session_id'] == 'probe-fold'; + if (cursor.isEmpty) { + return _foldPage( + prefix: 'FOLD_NEWEST', + ids: const ['fold-newest', 'fold-fourth'], + reasoning: const [ + 'FOLD NEWEST reasoning body.', + 'FOLD FOURTH reasoning body.', + ], + cursor: 'probe/opaque?fold=2', + hasMore: true, + ); + } + return _foldPage( + prefix: 'FOLD_OLDER', + ids: const ['fold-second', 'fold-oldest'], + reasoning: const [ + 'FOLD SECOND reasoning body.', + 'FOLD OLDEST reasoning body.', + ], + cursor: keepsPaging ? 'probe/opaque?fold=3' : '', + hasMore: keepsPaging, + ); + } + if (query['session_id'] == 'probe-more') { + return cursor.isEmpty + ? _page( + prefix: 'MORE_NEWEST', + user: 'A second read-only question from the server.', + reasoning: 'MORE NEWEST reasoning body.', + reply: 'The second stored assistant reply.', + cursor: 'probe/opaque?more=2', + hasMore: true, + ) + : _page( + prefix: 'MORE_OLDER', + user: 'An even older message for the second chat.', + reasoning: + 'MORE OLDER reasoning body that must stay collapsed.', + reply: 'Second older reply.', + cursor: 'probe/opaque?more=3', + hasMore: true, + ); + } + if (cursor.isEmpty) { + // Deliver the live delta only after the initial history page, so the + // merge cannot be mistaken for the delta being lost. + _pushLiveDelta(); + return _page( + prefix: 'NEWEST', + user: 'Please keep this exact read-only message from the server.', + reasoning: + 'NEWEST reasoning body that belongs to the newest answer.', + reply: + 'The stored assistant reply is rendered by the existing ' + 'native message view.', + cursor: 'probe/opaque?page=2', + hasMore: true, + ); + } + return _page( + prefix: 'OLDER', + user: 'This older stored message came from the opaque cursor page.', + reasoning: + 'OLDER reasoning body that must not steal the newest ' + 'disclosure.', + reply: 'Older reply kept in order.', + cursor: '', + hasMore: false, + ); + } + return {}; + } + + JsonMap _page({ + required String prefix, + required String user, + required String reasoning, + required String reply, + required String cursor, + required bool hasMore, + }) => { + 'chat_history': { + 'messages': [ + { + 'id': 'u-$prefix', + 'role': 'user', + 'client': 'Probe host', + 'parts': [ + {'type': 'text', 'text': user}, + ], + }, + { + 'id': 'a-$prefix', + 'role': 'assistant', + 'parts': [ + {'type': 'reasoning', 'text': reasoning}, + {'type': 'text', 'text': reply}, + {'type': 'tool', 'name': 'shell'}, + ], + }, + ], + 'next_cursor': cursor, + 'has_more': hasMore, + }, + }; + + /// The paged-history fixture shape: a page of consecutive assistant messages + /// with no user message at the page boundary, so paging folds into one turn. + JsonMap _foldPage({ + required String prefix, + required List ids, + required List reasoning, + required String cursor, + required bool hasMore, + }) => { + 'chat_history': { + 'messages': [ + for (var index = 0; index < ids.length; index++) + { + 'id': ids[index], + 'role': 'assistant', + 'parts': [ + { + 'type': 'reasoning', + 'id': 'r-${ids[index]}', + 'text': reasoning[index], + }, + { + 'type': 'text', + 'id': 't-${ids[index]}', + 'text': 'Answer $prefix stored as ${ids[index]}.', + }, + ], + }, + ], + 'next_cursor': cursor, + 'has_more': hasMore, + }, + }; +} + +const _style = String.fromEnvironment( + 'CHAT_WIRE_PROBE_STYLE', + defaultValue: 'material', +); + +void main() { + final screen = ChatScreen( + gateway: _FixtureGateway(), + onSessionSelected: null, + ); + if (_style == 'cupertino') { + runApp( + CupertinoApp( + theme: const CupertinoThemeData(brightness: Brightness.dark), + home: CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar(middle: Text('Chat')), + child: SafeArea(child: screen), + ), + ), + ); + return; + } + runApp( + MaterialApp( + theme: ThemeData( + brightness: Brightness.dark, + platform: TargetPlatform.android, + ), + home: Scaffold( + appBar: AppBar(title: const Text('Chat')), + body: screen, + ), + ), + ); +} diff --git a/app/tool/chat_wire_probe.mjs b/app/tool/chat_wire_probe.mjs new file mode 100644 index 00000000..6d3b6013 --- /dev/null +++ b/app/tool/chat_wire_probe.mjs @@ -0,0 +1,530 @@ +// Real-browser evidence for the Chat destination wiring fixture. +// +// Build one host, then run from app/: +// flutter build web -t tool/chat_wire_probe.dart \ +// --dart-define=CHAT_WIRE_PROBE_STYLE=material \ +// --output build/probe-chat-wire-material +// node tool/chat_wire_probe.mjs --root build/probe-chat-wire-material \ +// --out DIR --style material +// +// The Cupertino host is the same fixture built with CHAT_WIRE_PROBE_STYLE=cupertino. +// Requires Google Chrome and Tesseract: Flutter web paints selectable text on +// the canvas, so OCR confirms the actual message body, not just nav labels. +import { createServer } from 'node:http'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { spawn, execFile } from 'node:child_process'; +import { once } from 'node:events'; +import { promisify } from 'node:util'; +import { setTimeout as delay } from 'node:timers/promises'; +import { extname, join, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; + +const args = new Map(); +for (let i = 2; i < process.argv.length; i++) { + const value = process.argv[i]; + if (value.startsWith('--')) args.set(value.slice(2), process.argv[++i]); +} +const root = resolve(args.get('root') ?? 'build/probe-chat-wire-material'); +const out = resolve(args.get('out') ?? 'build/chat-wire-probe'); +const style = args.get('style') ?? 'material'; +const chromePath = + process.env.CHROME_PATH ?? + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +await mkdir(out, { recursive: true }); + +const mime = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.svg': 'image/svg+xml', + '.ico': 'image/x-icon', + '.ttf': 'font/ttf', + '.otf': 'font/otf', + '.woff': 'font/woff', + '.woff2': 'font/woff2', + '.bin': 'application/octet-stream', +}; + +const server = createServer(async (req, res) => { + try { + const pathname = decodeURIComponent( + new URL(req.url, 'http://localhost').pathname, + ); + let filePath = resolve(root, '.' + pathname); + if (filePath !== root && !filePath.startsWith(root + sep)) { + res.writeHead(403).end(); + return; + } + if (pathname === '/' || pathname.endsWith('/')) { + filePath = join(filePath, 'index.html'); + } + const file = await readFile(filePath); + res.writeHead(200, { + 'content-type': mime[extname(filePath)] ?? 'application/octet-stream', + }); + res.end(file); + } catch { + res.writeHead(404).end('not found'); + } +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const origin = `http://127.0.0.1:${server.address().port}`; + +const profile = await mkdtemp(join(tmpdir(), 'c2-wire-chrome-')); +const chrome = spawn( + chromePath, + [ + '--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, what) => { + for (let i = 0; i < 180; i++) { + const value = await fn(); + if (value) return value; + await delay(100); + } + throw new Error(`Timed out waiting for ${what}: ${stderr.slice(-1500)}`); +}; + +let ws; +const evidence = { origin, style, captures: [], checks: [] }; +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.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 created = await send('Target.createTarget', { url: 'about:blank' }); + if (!created.result) throw new Error('Target creation failed'); + 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); + await send( + 'Emulation.setDeviceMetricsOverride', + { width: 390, height: 844, deviceScaleFactor: 2, mobile: true }, + session, + ); + await send( + 'Emulation.setEmulatedMedia', + { features: [{ name: 'prefers-color-scheme', value: 'dark' }] }, + 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 nodes = () => + evaluate(`[...document.querySelectorAll('flt-semantics')].map(x => { + const r = x.getBoundingClientRect(); + return { + label: x.getAttribute('aria-label'), + text: (x.innerText || '').trim(), + x: r.x, y: r.y, w: r.width, h: r.height, + }; + })`); + const findNode = async (name) => { + const all = await nodes(); + return all.find((node) => node.label === name || node.text === name); + }; + const requireNode = async (name) => { + const node = await findNode(name); + if (!node) { + const shown = (await nodes()) + .map((entry) => entry.label ?? entry.text) + .filter(Boolean); + throw new Error( + `Missing semantics ${JSON.stringify(name)}: ${JSON.stringify(shown)}`, + ); + } + return node; + }; + const click = async (name, { large = false } = {}) => { + const point = await evaluate(`(() => { + const wanted = ${JSON.stringify(name)}; + const large = ${large}; + const matches = [...document.querySelectorAll('flt-semantics')] + .map(x => { + const label = x.getAttribute('aria-label') || ''; + const text = (x.innerText || '').trim(); + const r = x.getBoundingClientRect(); + const labelHit = label.includes(wanted) ? 0 : 1; + return { x, label, text, labelHit, area: r.width * r.height }; + }) + .filter(x => large ? x.labelHit === 0 : (x.labelHit === 0 || x.text.includes(wanted))) + .sort(large + ? (a, b) => b.area - a.area + : (a, b) => a.labelHit - b.labelHit || a.area - b.area); + const node = matches[0]?.x; + if (!node) return null; + const r = node.getBoundingClientRect(); + return { + x: large ? r.x + Math.min(r.width / 2, 100) : r.x + r.width / 2, + y: r.y + r.height / 2, + }; + })()`); + if (!point) { + const shown = (await nodes()) + .map((entry) => entry.label ?? entry.text) + .filter(Boolean); + throw new Error( + `Could not find ${JSON.stringify(name)}: ${JSON.stringify(shown)}`, + ); + } + await send( + 'Input.dispatchMouseEvent', + { type: 'mousePressed', x: point.x, y: point.y, button: 'left', clickCount: 1 }, + session, + ); + await send( + 'Input.dispatchMouseEvent', + { type: 'mouseReleased', x: point.x, y: point.y, button: 'left', clickCount: 1 }, + session, + ); + await delay(700); + }; + // The first matching control in document order. A folded assistant turn can + // hold several `Reasoning` labels; the newest message renders first. + const clickFirst = async (name) => { + const node = (await nodes()).find( + (entry) => entry.label === name || entry.text === name, + ); + if (!node) { + const shown = (await nodes()) + .map((entry) => entry.label ?? entry.text) + .filter(Boolean); + throw new Error( + `Could not find ${JSON.stringify(name)}: ${JSON.stringify(shown)}`, + ); + } + const x = node.x + node.w / 2; + const y = node.y + node.h / 2; + for (const type of ['mousePressed', 'mouseReleased']) { + await send( + 'Input.dispatchMouseEvent', + { type, x, y, button: 'left', clickCount: 1 }, + session, + ); + } + await delay(700); + }; + const capture = async (name) => { + const data = ( + await send('Page.captureScreenshot', { format: 'png' }, session) + ).result.data; + const file = join(out, `${style}-${name}.png`); + await writeFile(file, Buffer.from(data, 'base64')); + evidence.captures.push(file); + return file; + }; + const ocr = async (path) => { + const { stdout } = await promisify(execFile)('tesseract', [path, 'stdout']); + return stdout.replace(/\s+/g, ' '); + }; + const assertOcr = async (path, text) => { + const read = await ocr(path); + if (!read.toLowerCase().includes(text.toLowerCase())) { + throw new Error( + `OCR of ${path} lacks ${JSON.stringify(text)}:\n${read.slice(0, 1600)}`, + ); + } + }; + + const hasText = async (fragment) => { + const all = await nodes(); + return all.some((node) => + `${node.label ?? ''} ${node.text ?? ''}` + .toLowerCase() + .includes(fragment.toLowerCase()), + ); + }; + + await send('Page.navigate', { url: `${origin}/` }, session); + await delay(3500); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(1200); + await waitFor( + async () => hasText('Probe conversation'), + 'session list semantics', + ); + + const list = await capture('list'); + await assertOcr(list, 'Probe conversation'); + await assertOcr(list, 'Another stored chat'); + if (!(await hasText('New chat'))) { + throw new Error('Embedded list lost its New chat action'); + } + if (!(await hasText('Refresh'))) { + throw new Error('Embedded list lost its Refresh action'); + } + evidence.checks.push({ + check: 'embedded list renders server rows and actions', + labels: (await nodes()) + .map((node) => node.label) + .filter(Boolean) + .slice(0, 20), + }); + + await click('Probe conversation', { large: true }); + await waitFor( + async () => Boolean(await findNode('Assistant message')), + 'thread semantics', + ); + for (const name of [ + 'User message', + 'Assistant message', + 'Reasoning', + 'shell', + ]) { + await requireNode(name); + } + const thread = await capture('thread'); + for (const text of [ + 'read-only message from the server', + 'stored assistant reply', + 'existing native message view', + 'Probe conversation', + ]) { + await assertOcr(thread, text); + } + const closed = await ocr(thread); + for (const hidden of [ + 'Reasoning stays behind', + 'NEWEST reasoning body', + ]) { + if (closed.toLowerCase().includes(hidden.toLowerCase())) { + throw new Error(`Collapsed disclosure leaked ${JSON.stringify(hidden)}`); + } + } + evidence.checks.push({ + check: 'actual stored message body renders in the thread', + style, + }); + + await delay(1500); + const live = await capture('live'); + await assertOcr(live, 'A live delta updated this thread'); + evidence.checks.push({ + check: 'a pushed chat_event delta updates the open thread', + style, + }); + + // Repro B: expand the newest reasoning, then load the one older page whose + // `has_more` is false, so the `Load older` child disappears. + await click('Reasoning'); + const expanded = await capture('expanded'); + await assertOcr(expanded, 'NEWEST reasoning body'); + + await click('Load older'); + await delay(1200); + const afterOlder = await capture('older'); + const afterOlderText = await ocr(afterOlder); + const newestKept = afterOlderText.includes('NEWEST reasoning body'); + const olderLeaked = afterOlderText.includes('OLDER reasoning body'); + const loadOlderGone = !(await findNode('Load older')); + evidence.observations = { + ...evidence.observations, + afterOlderRemovesControl: { newestKept, olderLeaked, loadOlderGone }, + }; + if (!newestKept) { + throw new Error( + `The newest open reasoning was lost after Load older:\n${afterOlderText.slice(0, 1600)}`, + ); + } + if (olderLeaked) { + throw new Error( + `The older reasoning stole the newest disclosure:\n${afterOlderText.slice(0, 1600)}`, + ); + } + if (!loadOlderGone) { + throw new Error('Load older stayed visible after has_more became false'); + } + await assertOcr(afterOlder, 'older stored message came from the opaque cursor page'); + await assertOcr(afterOlder, 'Older reply kept in order'); + evidence.checks.push({ + check: 'Load older keeps the open disclosure and renders the opaque page', + style, + }); + + // Repro A: the same action while the server still reports `has_more`, so the + // paging control remains in the indexed list. + await click(style === 'cupertino' ? 'Back' : 'Back to chats'); + await waitFor( + async () => hasText('Probe paging session'), + 'list after Back', + ); + await click('Probe paging session', { large: true }); + await waitFor( + async () => Boolean(await findNode('Assistant message')), + 'second thread semantics', + ); + await click('Reasoning'); + const moreExpanded = await capture('more-expanded'); + await assertOcr(moreExpanded, 'MORE NEWEST reasoning body'); + + await click('Load older'); + await delay(1200); + const moreAfterOlder = await capture('more-older'); + const moreAfterOlderText = await ocr(moreAfterOlder); + const moreNewestKept = moreAfterOlderText.includes('MORE NEWEST reasoning body'); + const moreOlderLeaked = moreAfterOlderText.includes('MORE OLDER reasoning body'); + const moreControlStays = Boolean(await findNode('Load older')); + evidence.observations.afterOlderKeepsControl = { + newestKept: moreNewestKept, + olderLeaked: moreOlderLeaked, + loadOlderPresent: moreControlStays, + }; + if (!moreNewestKept) { + throw new Error( + `The newest open reasoning was lost while has_more stayed true:\n${moreAfterOlderText.slice(0, 1600)}`, + ); + } + if (moreOlderLeaked) { + throw new Error( + `The older reasoning stole the newest disclosure while has_more stayed true:\n${moreAfterOlderText.slice(0, 1600)}`, + ); + } + if (!moreControlStays) { + throw new Error('Load older disappeared although has_more stayed true'); + } + evidence.checks.push({ + check: 'an open disclosure follows its part while paging keeps has_more', + style, + }); + + // New repro: the paged-history fixture's shape. Both pages hold only + // consecutive assistant messages, so an older page prepends into the single + // folded turn and changes its first message id. The row element must survive + // that identity change and keep the operator's open block. + for (const fold of [ + { + title: 'Probe assistant fold session', + tag: 'fold', + keepsControl: true, + }, + { + title: 'Probe assistant fold last page', + tag: 'fold-end', + keepsControl: false, + }, + ]) { + await click(style === 'cupertino' ? 'Back' : 'Back to chats'); + await waitFor( + async () => hasText(fold.title), + `list before ${fold.tag}`, + ); + await click(fold.title, { large: true }); + await waitFor( + async () => Boolean(await findNode('Assistant message')), + `${fold.tag} thread semantics`, + ); + await clickFirst('Reasoning'); + await delay(400); + const foldExpanded = await capture(`${fold.tag}-expanded`); + await assertOcr(foldExpanded, 'FOLD NEWEST reasoning body'); + + await click('Load older'); + await delay(1200); + const foldAfter = await capture(`${fold.tag}-older`); + const foldText = await ocr(foldAfter); + const foldNewestKept = foldText.includes('FOLD NEWEST reasoning body'); + const foldOlderLeaked = [ + 'FOLD SECOND reasoning body', + 'FOLD OLDEST reasoning body', + ].some((body) => foldText.includes(body)); + const foldControlStays = Boolean(await findNode('Load older')); + evidence.observations = { + ...evidence.observations, + [`${fold.tag}AfterOlder`]: { + newestKept: foldNewestKept, + olderLeaked: foldOlderLeaked, + loadOlderPresent: foldControlStays, + }, + }; + if (!foldNewestKept) { + throw new Error( + `The folded turn lost the open reasoning after Load older:\n${foldText.slice(0, 1600)}`, + ); + } + if (foldOlderLeaked) { + throw new Error( + `An older block in the folded turn opened itself:\n${foldText.slice(0, 1600)}`, + ); + } + if (foldControlStays !== fold.keepsControl) { + throw new Error( + `Load older presence ${foldControlStays} did not match has_more ${fold.keepsControl}`, + ); + } + evidence.checks.push({ + check: + 'an open disclosure survives paging inside a folded assistant turn', + style, + case: fold.tag, + }); + } + + const report = JSON.stringify(evidence, null, 2); + await writeFile(join(out, `${style}-evidence.json`), report); + console.log(report); +} finally { + ws?.close(); + chrome.kill(); + server.close(); + for (let attempt = 0; attempt < 10; attempt++) { + try { + await rm(profile, { recursive: true, force: true }); + break; + } catch { + await delay(200); + } + } +}