From 68d291602b85a28c178b8ed14cc184e33bdbc6fe Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 03:22:44 +0100 Subject: [PATCH 1/5] feat(app): create, rename, star, close and hide chat sessions --- app/PARITY.md | 2 +- .../chat/ui/sessions/chat_adaptive.dart | 83 ++++++ .../ui/sessions/chat_create_dialog_frame.dart | 57 ++++ .../chat/ui/sessions/chat_create_fields.dart | 13 +- .../chat/ui/sessions/chat_session_local.dart | 119 ++++++++ .../chat/ui/sessions/chat_sessions_body.dart | 12 + .../ui/sessions/chat_sessions_controller.dart | 199 ++++++++++++-- .../ui/sessions/chat_sessions_screen.dart | 114 ++++++-- .../chat/ui/sessions/create_chat_dialog.dart | 109 ++++---- .../chat/ui/sessions/rename_chat_dialog.dart | 90 ++++-- .../chat/ui/sessions/session_actions.dart | 3 +- .../ui/sessions/session_list_cupertino.dart | 51 +++- .../ui/sessions/session_list_material.dart | 48 +++- .../chat/ui/sessions/session_row_style.dart | 4 +- app/notes/C5-list.md | 147 ++++++++++ .../chat_session_dialog_layout_test.dart | 97 +++++++ .../chat_session_local_state_test.dart | 206 ++++++++++++++ .../ui/sessions/chat_session_local_test.dart | 67 +++++ .../chat_session_shared_actions_test.dart | 226 +++++++++++++++ .../chat_sessions_lifecycle_test.dart | 13 +- .../chat/ui/sessions/chat_test_harness.dart | 42 ++- .../chat/ui/sessions/chat_undo_bar_test.dart | 63 +++++ .../chat/ui/sessions/fake_chat_gateway.dart | 8 + app/tool/chat_sessions_probe.mjs | 257 +++++++++++++++--- app/tool/chat_sessions_probe_entry.dart | 169 +++++++++--- 25 files changed, 1964 insertions(+), 235 deletions(-) create mode 100644 app/lib/features/chat/ui/sessions/chat_create_dialog_frame.dart create mode 100644 app/lib/features/chat/ui/sessions/chat_session_local.dart create mode 100644 app/notes/C5-list.md create mode 100644 app/test/features/chat/ui/sessions/chat_session_dialog_layout_test.dart create mode 100644 app/test/features/chat/ui/sessions/chat_session_local_state_test.dart create mode 100644 app/test/features/chat/ui/sessions/chat_session_local_test.dart create mode 100644 app/test/features/chat/ui/sessions/chat_session_shared_actions_test.dart create mode 100644 app/test/features/chat/ui/sessions/chat_undo_bar_test.dart diff --git a/app/PARITY.md b/app/PARITY.md index bce99029..1b18968a 100644 --- a/app/PARITY.md +++ b/app/PARITY.md @@ -40,7 +40,7 @@ or scratch servers only, never real operator sessions/runs/workflows. | Artifact preview | Preview: image + markdown/text in-app through the chat renderer, paging, honest unsupported/external/HTTP states | video and HTML remain external-only | | Artifact actions | Preview: external Open, Copy link, download and native share carry the recorded name/MIME bytes; progress, cancel, HTTP failure and unsupported-share states | OS share/download on Android/iOS remain unverified until the final build | | Session audit/export repair facts | Missing UI | session.html read-only open, partial/missing/skipped/repair choices without fabricating complete evidence | -| Chat session management | Preview list + open session; actions from the list | directory groups/search, shared rename/star/close/reopen/create, local hide/undo/seen state, create dialog in the shell | +| Chat session management | Preview list + open session; shared create/rename/star/close/reopen with server-refreshed rows and full-width row refusals; local hide/undo and this device's read watermark (open rows only; a closed row never shows `New`) | dismissible web action-failed report (refusals stay under their row until the next accepted action), web `Open` badge and active/deep-linked read suppression, live `New` marks from pushed chat events, hide closing an already-open conversation, create dialog in the shell, editable create title (the web fixes `New chat`) | | Chat history/live transport | Preview: `/chat` list and `/chat/:id` history, paging, live failure notice | run-detail-style reconnect verification in the real app, then composer integration | | Chat message surfaces | Preview: formatted assistant markdown (safe links/headings/lists/tables/fences), user text exact, disclosures plain | exact attachments, unknown-part rendering beyond retained placeholders | | Chat activity/reasoning/tools | Source raw fields only | one activity line, compaction, native reasoning/tools overlays, lifecycle/input/output/error/duration/edit diff | diff --git a/app/lib/features/chat/ui/sessions/chat_adaptive.dart b/app/lib/features/chat/ui/sessions/chat_adaptive.dart index 4dcf7008..0607e926 100644 --- a/app/lib/features/chat/ui/sessions/chat_adaptive.dart +++ b/app/lib/features/chat/ui/sessions/chat_adaptive.dart @@ -159,6 +159,40 @@ class ChatCupertinoMessage extends StatelessWidget { } } +/// A row action's refusal, shown at full width beneath its tile. +/// +/// It must not sit in a `CupertinoListTile.subtitle`: that slot forces every +/// paragraph to one ellipsised line, which cut the server's reason down to its +/// first few words. Full width also stops a long refusal from turning a single +/// Material row into a column taller than the viewport. +class ChatRowError extends StatelessWidget { + const ChatRowError({super.key, required this.message, this.messageKey}); + + final String message; + + /// Key placed on the message paragraph itself, so a test can assert that the + /// rendered text did not exceed its line limit. + final Key? messageKey; + + @override + Widget build(BuildContext context) { + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final style = cupertino + ? CupertinoTheme.of(context).textTheme.textStyle.copyWith( + color: CupertinoColors.systemRed.resolveFrom(context), + ) + : TextStyle(color: Theme.of(context).colorScheme.error); + return Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 12), + child: DefaultTextStyle.merge( + style: style, + child: Text(message, key: messageKey), + ), + ); + } +} + class ChatErrorNotice extends StatelessWidget { const ChatErrorNotice({ super.key, @@ -198,3 +232,52 @@ class ChatLoadingIndicator extends StatelessWidget { ); } } + +/// One-row report after hiding a session on this device, with its Undo. +/// +/// The screen floats this over the list like the web's fixed report, so a long +/// message can never push the list out of the body's column. +class ChatUndoBar extends StatelessWidget { + const ChatUndoBar({super.key, required this.message, required this.onUndo}); + + final String message; + final VoidCallback onUndo; + + @override + Widget build(BuildContext context) { + final content = Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Row( + children: [ + Expanded( + child: DefaultTextStyle.merge( + style: chatControlsStyleOf(context) == ChatControlsStyle.cupertino + ? CupertinoTheme.of(context).textTheme.textStyle + : DefaultTextStyle.of(context).style, + child: Text(message), + ), + ), + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) + CupertinoButton( + padding: const EdgeInsetsDirectional.only(start: 12), + onPressed: onUndo, + child: const Text('Undo'), + ) + else + TextButton(onPressed: onUndo, child: const Text('Undo')), + ], + ), + ); + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { + // A standard Cupertino popup surface: the bar floats over the list, so it + // needs its own painted card and shadow to stay legible. + return CupertinoPopupSurface(child: content); + } + return Material( + elevation: 3, + borderRadius: BorderRadius.circular(8), + color: Theme.of(context).colorScheme.surfaceContainerHighest, + child: content, + ); + } +} diff --git a/app/lib/features/chat/ui/sessions/chat_create_dialog_frame.dart b/app/lib/features/chat/ui/sessions/chat_create_dialog_frame.dart new file mode 100644 index 00000000..149d6095 --- /dev/null +++ b/app/lib/features/chat/ui/sessions/chat_create_dialog_frame.dart @@ -0,0 +1,57 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'chat_adaptive.dart'; + +/// Native chrome for the create dialog: standard Cupertino alert or Material +/// alert, with the same disabled/submitting state in both hosts. +class ChatCreateDialogFrame extends StatelessWidget { + const ChatCreateDialogFrame({ + super.key, + required this.content, + required this.canSubmit, + required this.submitting, + required this.onCancel, + required this.onSubmit, + }); + + final Widget content; + final bool canSubmit; + final bool submitting; + final VoidCallback onCancel; + final VoidCallback onSubmit; + + @override + Widget build(BuildContext context) { + final enabled = canSubmit && !submitting; + final label = submitting ? 'Creating…' : 'Create'; + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { + return CupertinoAlertDialog( + title: const Text('New chat'), + content: content, + actions: [ + CupertinoDialogAction( + onPressed: submitting ? null : onCancel, + child: const Text('Cancel'), + ), + CupertinoDialogAction( + isDefaultAction: true, + onPressed: enabled ? onSubmit : null, + child: Text(label), + ), + ], + ); + } + return AlertDialog( + title: const Text('New chat'), + content: content, + actions: [ + TextButton( + onPressed: submitting ? null : onCancel, + child: const Text('Cancel'), + ), + FilledButton(onPressed: enabled ? onSubmit : null, child: Text(label)), + ], + ); + } +} diff --git a/app/lib/features/chat/ui/sessions/chat_create_fields.dart b/app/lib/features/chat/ui/sessions/chat_create_fields.dart index f477811a..5719c703 100644 --- a/app/lib/features/chat/ui/sessions/chat_create_fields.dart +++ b/app/lib/features/chat/ui/sessions/chat_create_fields.dart @@ -117,16 +117,27 @@ class MaterialPickerField extends StatelessWidget { return DropdownButtonFormField( key: Key('chat-create-${label.toLowerCase().replaceAll(' ', '-')}'), initialValue: value, + isExpanded: true, + // Intrinsic item height: a 2x label must not be clipped by the 48px + // default, and a real path must ellipsize instead of overflowing. + itemHeight: null, decoration: InputDecoration(labelText: label), + selectedItemBuilder: (context) => [ + for (final item in values) _fieldLabel(item), + ], items: [ for (final item in values) - DropdownMenuItem(value: item, child: Text(item)), + DropdownMenuItem(value: item, child: _fieldLabel(item)), ], onChanged: (item) { if (item != null) onSelected(item); }, ); } + + Widget _fieldLabel(String item) { + return Text(item, maxLines: 1, overflow: TextOverflow.ellipsis); + } } class CupertinoPickerField extends StatelessWidget { diff --git a/app/lib/features/chat/ui/sessions/chat_session_local.dart b/app/lib/features/chat/ui/sessions/chat_session_local.dart new file mode 100644 index 00000000..cd5904d1 --- /dev/null +++ b/app/lib/features/chat/ui/sessions/chat_session_local.dart @@ -0,0 +1,119 @@ +import 'dart:convert'; + +import 'package:shared_preferences/shared_preferences.dart'; + +/// Device-local list preferences, mirroring the web client's C13 behaviour: +/// hidden ids and the newest session recency this device has read. +/// +/// Titles, stars and the closed state are server-owned and deliberately absent. +class ChatSessionLocal { + const ChatSessionLocal({this.hidden = const [], this.seenAt = const {}}); + + final List hidden; + final Map seenAt; + + bool isHidden(String id) => hidden.contains(id); + + int watermark(String id) => seenAt[id] ?? 0; + + ChatSessionLocal hide(String id) { + if (id.isEmpty || hidden.contains(id)) return this; + return ChatSessionLocal(hidden: [...hidden, id], seenAt: seenAt); + } + + ChatSessionLocal restore(String id) { + if (!hidden.contains(id)) return this; + return ChatSessionLocal( + hidden: hidden.where((entry) => entry != id).toList(), + seenAt: seenAt, + ); + } + + /// Advances only for a strictly newer recency, so a stale list read can never + /// mark newer activity as already seen. + ChatSessionLocal read(String id, int updatedAt) { + if (id.isEmpty || updatedAt <= watermark(id)) return this; + return ChatSessionLocal(hidden: hidden, seenAt: {...seenAt, id: updatedAt}); + } + + /// The first sight of a session baselines it, so pre-existing chats are not + /// all reported as new. + ChatSessionLocal seed(Iterable<({String id, int updatedAt})> rows) { + var next = this; + for (final row in rows) { + if (row.id.isEmpty || row.updatedAt <= 0) continue; + if (next.watermark(row.id) != 0) continue; + next = ChatSessionLocal( + hidden: next.hidden, + seenAt: {...next.seenAt, row.id: row.updatedAt}, + ); + } + return next; + } + + String encode() => jsonEncode({'hidden': hidden, 'seenAt': seenAt}); + + static ChatSessionLocal decode(Object? value) { + try { + final parsed = jsonDecode('$value'); + if (parsed is! Map) return const ChatSessionLocal(); + final hidden = parsed['hidden']; + final seenAt = parsed['seenAt']; + return ChatSessionLocal( + hidden: hidden is List + ? hidden.whereType().where((id) => id.isNotEmpty).toList() + : const [], + seenAt: seenAt is Map + ? { + for (final entry in seenAt.entries) + if (entry.key is String && entry.value is int) + '${entry.key}': entry.value as int, + } + : const {}, + ); + } catch (_) { + return const ChatSessionLocal(); + } + } +} + +abstract interface class ChatSessionLocalStore { + Future load(); + Future save(ChatSessionLocal state); +} + +/// `shared_preferences`-backed storage; unavailable storage degrades to the +/// in-memory choice instead of failing the list. +class SharedPreferencesChatSessionLocalStore implements ChatSessionLocalStore { + const SharedPreferencesChatSessionLocalStore(); + + static const key = 'pipelines.chat.local.v1'; + + Future _preferences() async { + try { + return await SharedPreferences.getInstance(); + } catch (_) { + return null; + } + } + + @override + Future load() async { + final preferences = await _preferences(); + try { + return ChatSessionLocal.decode(preferences?.getString(key)); + } catch (_) { + return const ChatSessionLocal(); + } + } + + @override + Future save(ChatSessionLocal state) async { + final preferences = await _preferences(); + try { + await preferences?.setString(key, state.encode()); + } catch (_) { + // Storage may be unavailable; the in-memory choice still applies. + } + } +} diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_body.dart b/app/lib/features/chat/ui/sessions/chat_sessions_body.dart index 0489a365..0b545b18 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_body.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_body.dart @@ -22,7 +22,10 @@ class ChatSessionsBody extends StatelessWidget { required this.onClose, required this.onReopen, required this.onStar, + required this.onHide, required this.onClearSearch, + required this.isUnseen, + required this.errorFor, }); final List sessions; @@ -34,7 +37,10 @@ class ChatSessionsBody extends StatelessWidget { final ValueChanged onClose; final ValueChanged onReopen; final ValueChanged onStar; + final ValueChanged onHide; final VoidCallback onClearSearch; + final bool Function(JsonMap) isUnseen; + final String? Function(String sessionId) errorFor; @override Widget build(BuildContext context) { @@ -79,7 +85,10 @@ class ChatSessionsBody extends StatelessWidget { onClose: onClose, onReopen: onReopen, onStar: onStar, + onHide: onHide, onClearSearch: clearSearch, + isUnseen: isUnseen, + errorFor: errorFor, ); } return MaterialSessionList( @@ -91,7 +100,10 @@ class ChatSessionsBody extends StatelessWidget { onClose: onClose, onReopen: onReopen, onStar: onStar, + onHide: onHide, onClearSearch: clearSearch, + isUnseen: isUnseen, + errorFor: errorFor, ); } } diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart index 3c5799c6..2aa38cdf 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart @@ -3,26 +3,63 @@ import 'dart:async'; import 'package:flutter/foundation.dart'; import '../../../../core/api_gateway.dart'; +import '../../../../core/transport/connection_state.dart'; import '../../data/chat_repository.dart'; +import 'chat_session_local.dart'; -/// Owns the session list, its refresh generation and the row actions. +/// Owns the session list, its refresh generation and the shared row actions. /// /// A refresh that finishes after a newer one (or after the screen is gone) is -/// discarded, so a slow reply can never replace fresher state. +/// discarded, so a slow reply can never replace fresher state. Accepted +/// mutations always re-read the server list; only this device's hidden ids and +/// read watermark are local. class ChatSessionsController extends ChangeNotifier { - ChatSessionsController(this.repository); + ChatSessionsController(this.repository, {ChatSessionLocalStore? localStore}) + : _localStore = + localStore ?? const SharedPreferencesChatSessionLocalStore(); ChatRepository repository; + final ChatSessionLocalStore _localStore; + ChatSessionLocal _local = const ChatSessionLocal(); + final Map _actionErrors = {}; List _sessions = const []; String? _error; + String? _lastHidden; bool _loading = true; + bool _localLoaded = false; + Future? _localLoading; bool _disposed = false; int _generation = 0; - List get sessions => _sessions; + List get sessions => [ + for (final session in _sessions) + if (!_local.isHidden('${session['id'] ?? ''}')) session, + ]; + String? get error => _error; bool get loading => _loading; + /// The row an action failed on; the message is the server's own words. + String? errorFor(String sessionId) => _actionErrors[sessionId]; + + /// The last hidden session, while its Undo is still offered. + String? get lastHidden => _lastHidden; + + bool isUnseen(JsonMap session) { + final id = '${session['id'] ?? ''}'; + // Closed chats keep their recency from the close, but they are not new + // work: both the web list and the Android list suppress unseen there. + if (!_localLoaded || + id.isEmpty || + session['running'] == true || + session['closed_at'] != null || + session['closed'] == true) { + return false; + } + final updatedAt = _millis(session['updated_at']); + return updatedAt > 0 && updatedAt > _local.watermark(id); + } + void replaceRepository(ChatRepository next) { if (identical(next.gateway, repository.gateway)) return; repository = next; @@ -35,10 +72,14 @@ class ChatSessionsController extends ChangeNotifier { _loading = true; _error = null; _notify(); + // Device preferences never gate the server read: a slow platform store + // must not hide the list or delay the first request. + unawaited(_ensureLocal()); try { final sessions = await repository.sessions(); if (generation != _generation) return; _sessions = sessions; + _seedLocal(); _loading = false; _notify(); } catch (error) { @@ -50,52 +91,150 @@ class ChatSessionsController extends ChangeNotifier { } Future star(String sessionId, bool starred) => - _mutate(() => repository.star(sessionId, starred)); + _mutate(sessionId, () => repository.star(sessionId, starred)); Future close(String sessionId) => - _mutate(() => repository.close(sessionId)); + _mutate(sessionId, () => repository.close(sessionId)); Future reopen(String sessionId) => - _mutate(() => repository.reopen(sessionId)); + _mutate(sessionId, () => repository.reopen(sessionId)); - Future rename(String sessionId, String title) => - _mutate(() => repository.rename(sessionId, title)); + /// Renames through the shared server field. Throws the server's refusal so the + /// open dialog can keep it in view; success refreshes the list from the server. + /// + /// The dialog owns the refusal, so no row error is stored: the same sentence + /// must not also stick under the list row. + Future renameOrThrow(String sessionId, String title) async { + await repository.rename(sessionId, title); + _actionErrors.remove(sessionId); + await refresh(); + } - Future create({ + /// Creates one session and returns the server's `chat_session`. A reply + /// without one is refused rather than opening an invented row. + Future createOrThrow({ required String title, required String directory, required String backend, required String instructions, required String operationId, }) async { - try { - final reply = await repository.create( - title: title, - directory: directory, - backend: backend, - operationId: operationId, - instructions: instructions, + final reply = await repository.create( + title: title, + directory: directory, + backend: backend, + operationId: operationId, + instructions: instructions, + ); + final session = reply['chat_session']; + if (session is! Map) { + // The web reports exactly this refusal, so the dialog shows the same + // sentence instead of a Dart `Bad state:` prefix. + throw const ProtocolError( + 'The server did not return the new chat session.', ); - // Opening the created chat must not wait for the list refresh: the dialog - // has already closed, so a slow listing would look like a failed create. - unawaited(refresh()); - final session = reply['chat_session']; - return session is Map ? Map.from(session) : null; + } + // Opening the created chat must not wait for the list refresh: the dialog + // has already closed, so a slow listing would look like a failed create. + unawaited(refresh()); + return Map.from(session); + } + + /// Records that this device has read [session]'s current recency. + Future markOpened(JsonMap session) async { + final id = '${session['id'] ?? ''}'; + if (id.isEmpty) return; + await _ensureLocal(); + final next = _local.read(id, _millis(session['updated_at'])); + if (identical(next, _local)) return; + _local = next; + _notify(); + await _persist(); + } + + /// Hides one row on this device only; the server row is untouched. + Future hide(String sessionId) async { + await _ensureLocal(); + final next = _local.hide(sessionId); + if (identical(next, _local)) return; + _local = next; + _lastHidden = sessionId; + _notify(); + await _persist(); + } + + Future undoHide() async { + final id = _lastHidden; + if (id == null) return; + _local = _local.restore(id); + _lastHidden = null; + _notify(); + await _persist(); + } + + void dismissUndo() { + if (_lastHidden == null) return; + _lastHidden = null; + _notify(); + } + + Future _mutate( + String sessionId, + Future Function() action, + ) async { + try { + await action(); + _actionErrors.remove(sessionId); + await refresh(); } catch (error) { - _error = '$error'; + _actionErrors[sessionId] = '$error'; _notify(); - return null; } } - Future _mutate(Future Function() action) async { + Future _ensureLocal() => _localLoading ??= _loadLocal(); + + Future _loadLocal() async { try { - await action(); - await refresh(); - } catch (error) { - _error = '$error'; - _notify(); + _local = await _localStore.load(); + } catch (_) { + _local = const ChatSessionLocal(); } + _localLoaded = true; + _seedLocal(); + _notify(); + } + + void _seedLocal() { + if (!_localLoaded) return; + final next = _local.seed([ + for (final session in _sessions) + ( + id: '${session['id'] ?? ''}', + updatedAt: _millis(session['updated_at']), + ), + ]); + if (identical(next, _local)) return; + _local = next; + unawaited(_persist()); + } + + Future _persist() async { + try { + await _localStore.save(_local); + } catch (_) { + // The in-memory choice still applies for this session. + } + } + + static int _millis(Object? value) { + if (value is int) return value > 0 ? value : 0; + if (value is num) return value > 0 ? value.toInt() : 0; + final text = '${value ?? ''}'.trim(); + if (text.isEmpty) return 0; + final number = int.tryParse(text); + if (number != null) return number > 0 ? number : 0; + return DateTime.tryParse(text)?.millisecondsSinceEpoch ?? 0; } void _notify() { 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 f15311f1..9d0825f9 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart @@ -6,6 +6,7 @@ import 'package:flutter/material.dart'; import '../../../../core/api_gateway.dart'; import '../../data/chat_repository.dart'; import 'chat_adaptive.dart'; +import 'chat_session_local.dart'; import 'chat_sessions_body.dart'; import 'chat_sessions_controller.dart'; import 'create_chat_dialog.dart'; @@ -20,6 +21,7 @@ class ChatSessionsScreen extends StatefulWidget { required this.onOpen, this.embedded = false, this.syncToken = 0, + this.localStore, }); final ApiGateway gateway; final void Function(JsonMap session) onOpen; @@ -31,6 +33,9 @@ class ChatSessionsScreen extends StatefulWidget { /// closed elsewhere during the gap must not stay invisible until Refresh. final int syncToken; + /// Overrides the device-local hidden/read store in tests. + final ChatSessionLocalStore? localStore; + @override State createState() => _ChatSessionsScreenState(); } @@ -38,8 +43,10 @@ class ChatSessionsScreen extends StatefulWidget { class _ChatSessionsScreenState extends State { late final ChatSessionsController _controller = ChatSessionsController( ChatRepository(widget.gateway), + localStore: widget.localStore, )..refresh(); final _search = TextEditingController(); + Timer? _undoTimer; @override void didUpdateWidget(covariant ChatSessionsScreen oldWidget) { @@ -53,6 +60,7 @@ class _ChatSessionsScreenState extends State { @override void dispose() { + _undoTimer?.cancel(); _controller.dispose(); _search.dispose(); super.dispose(); @@ -61,9 +69,12 @@ class _ChatSessionsScreenState extends State { String _sessionId(JsonMap session) => '${session['id'] ?? ''}'; Future _rename(JsonMap session) async { - final title = await showRenameChatDialog(context, session); - if (title == null || !mounted) return; - await _controller.rename(_sessionId(session), title); + final id = _sessionId(session); + await showRenameChatDialog( + context, + session, + onSubmit: (title) => _controller.renameOrThrow(id, title), + ); } Future _close(JsonMap session) async { @@ -73,27 +84,47 @@ class _ChatSessionsScreenState extends State { } Future _newChat() async { + // One id per create intent: a refusal retried in the dialog reuses it. final operationId = 'native-chat-${DateTime.now().microsecondsSinceEpoch}'; - final draft = await showChatCreateDialog( + final session = await showChatCreateDialog( context, repository: _controller.repository, - ); - if (draft == null || !mounted) return; - final session = await _controller.create( - title: draft.title, - directory: draft.directory, - backend: draft.backend, - instructions: draft.instructions, operationId: operationId, + onSubmit: (draft, id) => _controller.createOrThrow( + title: draft.title, + directory: draft.directory, + backend: draft.backend, + instructions: draft.instructions, + operationId: id, + ), ); if (session != null && mounted) widget.onOpen(session); } + void _open(JsonMap session) { + unawaited(_controller.markOpened(session)); + widget.onOpen(session); + } + + Future _hide(JsonMap session) async { + await _controller.hide(_sessionId(session)); + _undoTimer?.cancel(); + _undoTimer = Timer(const Duration(seconds: 8), () { + if (mounted) _controller.dismissUndo(); + }); + } + + Future _undoHide() async { + _undoTimer?.cancel(); + await _controller.undoHide(); + } + @override Widget build(BuildContext context) { return ListenableBuilder( listenable: _controller, builder: (context, _) { + final controls = chatControlsStyleOf(context); final body = Column( children: [ ChatSearchField( @@ -106,23 +137,50 @@ class _ChatSessionsScreenState extends State { onRetry: _controller.refresh, ), Expanded( - child: ChatSessionsBody( - sessions: _controller.sessions, - query: _search.text, - loading: _controller.loading, - error: _controller.error, - onOpen: widget.onOpen, - onRename: _rename, - onClose: _close, - onReopen: (session) => _controller.reopen(_sessionId(session)), - onStar: (session) => _controller.star( - _sessionId(session), - session['starred'] != true, - ), - onClearSearch: () { - _search.clear(); - setState(() {}); - }, + child: Stack( + children: [ + ChatSessionsBody( + sessions: _controller.sessions, + query: _search.text, + loading: _controller.loading, + error: _controller.error, + onOpen: _open, + onRename: _rename, + onClose: _close, + onReopen: (session) => + _controller.reopen(_sessionId(session)), + onStar: (session) => _controller.star( + _sessionId(session), + session['starred'] != true, + ), + onHide: _hide, + onClearSearch: () { + _search.clear(); + setState(() {}); + }, + isUnseen: _controller.isUnseen, + errorFor: _controller.errorFor, + ), + // The web's hide report is a fixed overlay: replacing or + // growing it must never move the list or overflow the screen. + // A standalone Material screen keeps it clear of the FAB. + if (_controller.lastHidden != null) + Positioned( + left: 8, + right: 8, + bottom: + !widget.embedded && + controls == ChatControlsStyle.material + ? 88 + : 8, + child: ChatUndoBar( + key: const Key('chat-undo-hide'), + message: + 'Hidden on this device; the chat stays on the server.', + onUndo: _undoHide, + ), + ), + ], ), ), ], diff --git a/app/lib/features/chat/ui/sessions/create_chat_dialog.dart b/app/lib/features/chat/ui/sessions/create_chat_dialog.dart index 6a0e2617..7f7e50a1 100644 --- a/app/lib/features/chat/ui/sessions/create_chat_dialog.dart +++ b/app/lib/features/chat/ui/sessions/create_chat_dialog.dart @@ -1,8 +1,10 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import '../../../../core/api_gateway.dart'; import '../../data/chat_repository.dart'; import 'chat_adaptive.dart'; +import 'chat_create_dialog_frame.dart'; import 'chat_create_fields.dart'; class ChatDraft { @@ -19,20 +21,37 @@ class ChatDraft { final String instructions; } -Future showChatCreateDialog( +/// The dialog sends the create itself so a refusal can keep the operator's +/// draft and the server's words in place. [operationId] is minted once per +/// create intent and reused across retries, so a retry cannot create twice. +Future showChatCreateDialog( BuildContext context, { required ChatRepository repository, + required String operationId, + required Future Function(ChatDraft draft, String operationId) + onSubmit, }) { - final dialog = CreateChatDialog(repository: repository); + final dialog = CreateChatDialog( + repository: repository, + operationId: operationId, + onSubmit: onSubmit, + ); return chatControlsStyleOf(context) == ChatControlsStyle.cupertino - ? showCupertinoDialog(context: context, builder: (_) => dialog) - : showDialog(context: context, builder: (_) => dialog); + ? showCupertinoDialog(context: context, builder: (_) => dialog) + : showDialog(context: context, builder: (_) => dialog); } class CreateChatDialog extends StatefulWidget { - const CreateChatDialog({super.key, required this.repository}); + const CreateChatDialog({ + super.key, + required this.repository, + required this.operationId, + required this.onSubmit, + }); final ChatRepository repository; + final String operationId; + final Future Function(ChatDraft draft, String operationId) onSubmit; @override State createState() => _CreateChatDialogState(); @@ -48,6 +67,7 @@ class _CreateChatDialogState extends State { String? _catalogError; String? _formError; bool _loading = true; + bool _submitting = false; int _attempt = 0; @override @@ -106,23 +126,37 @@ class _CreateChatDialogState extends State { _directories.isNotEmpty && _backends.isNotEmpty; - void _submit() { - if (!_catalogReady) return; + Future _submit() async { + if (!_catalogReady || _submitting) return; final title = _name.text.trim(); final directory = _directory ?? ''; if (title.isEmpty || directory.isEmpty) { setState(() => _formError = 'Enter a name and server directory.'); return; } - Navigator.pop( - context, - ChatDraft( - title: title, - directory: directory, - backend: _backend ?? '', - instructions: _instructions.text, - ), - ); + setState(() { + _submitting = true; + _formError = null; + }); + try { + final session = await widget.onSubmit( + ChatDraft( + title: title, + directory: directory, + backend: _backend ?? '', + instructions: _instructions.text, + ), + widget.operationId, + ); + if (!mounted) return; + Navigator.pop(context, session); + } catch (error) { + if (!mounted) return; + setState(() { + _submitting = false; + _formError = '$error'; + }); + } } @override @@ -181,42 +215,25 @@ class _CreateChatDialogState extends State { ), if (_formError != null) ...[ const SizedBox(height: 8), - Text(_formError!), + Text( + _formError!, + style: TextStyle( + color: cupertino + ? CupertinoColors.systemRed.resolveFrom(context) + : Theme.of(context).colorScheme.error, + ), + ), ], ], ), ); - if (cupertino) { - return CupertinoAlertDialog( - title: const Text('New chat'), - content: content, - actions: [ - CupertinoDialogAction( - onPressed: () => Navigator.pop(context), - child: const Text('Cancel'), - ), - CupertinoDialogAction( - isDefaultAction: true, - onPressed: _catalogReady ? _submit : null, - child: const Text('Create'), - ), - ], - ); - } - return AlertDialog( - title: const Text('New chat'), + return ChatCreateDialogFrame( content: content, - actions: [ - TextButton( - onPressed: () => Navigator.pop(context), - child: const Text('Cancel'), - ), - FilledButton( - onPressed: _catalogReady ? _submit : null, - child: const Text('Create'), - ), - ], + canSubmit: _catalogReady, + submitting: _submitting, + onCancel: () => Navigator.pop(context), + onSubmit: _submit, ); } } diff --git a/app/lib/features/chat/ui/sessions/rename_chat_dialog.dart b/app/lib/features/chat/ui/sessions/rename_chat_dialog.dart index 9dd0000d..9872dfa1 100644 --- a/app/lib/features/chat/ui/sessions/rename_chat_dialog.dart +++ b/app/lib/features/chat/ui/sessions/rename_chat_dialog.dart @@ -5,19 +5,28 @@ import '../../../../core/api_gateway.dart'; import '../../domain/chat_sessions.dart'; import 'chat_adaptive.dart'; -/// Renames one session. Save is disabled while the trimmed name is blank, -/// matching the web dialog. -Future showRenameChatDialog(BuildContext context, JsonMap session) { - final dialog = _RenameChatDialog(initialTitle: chatSessionTitle(session)); +/// Renames one session through the shared server field. Save is disabled while +/// the trimmed name is blank, matching the web dialog. A refusal keeps the +/// dialog open with the server's own words. +Future showRenameChatDialog( + BuildContext context, + JsonMap session, { + required Future Function(String title) onSubmit, +}) { + final dialog = _RenameChatDialog( + initialTitle: chatSessionTitle(session), + onSubmit: onSubmit, + ); return chatControlsStyleOf(context) == ChatControlsStyle.cupertino ? showCupertinoDialog(context: context, builder: (_) => dialog) : showDialog(context: context, builder: (_) => dialog); } class _RenameChatDialog extends StatefulWidget { - const _RenameChatDialog({required this.initialTitle}); + const _RenameChatDialog({required this.initialTitle, required this.onSubmit}); final String initialTitle; + final Future Function(String title) onSubmit; @override State<_RenameChatDialog> createState() => _RenameChatDialogState(); @@ -30,6 +39,8 @@ class _RenameChatDialogState extends State<_RenameChatDialog> { baseOffset: 0, extentOffset: widget.initialTitle.length, ); + String? _error; + bool _saving = false; @override void dispose() { @@ -37,10 +48,25 @@ class _RenameChatDialogState extends State<_RenameChatDialog> { super.dispose(); } - void _save() { + Future _save() async { + if (_saving) return; final title = _title.text.trim(); if (title.isEmpty) return; - Navigator.pop(context, title); + setState(() { + _saving = true; + _error = null; + }); + try { + await widget.onSubmit(title); + if (!mounted) return; + Navigator.pop(context, title); + } catch (error) { + if (!mounted) return; + setState(() { + _saving = false; + _error = '$error'; + }); + } } @override @@ -48,7 +74,8 @@ class _RenameChatDialogState extends State<_RenameChatDialog> { return ValueListenableBuilder( valueListenable: _title, builder: (context, value, _) { - final canSave = value.text.trim().isNotEmpty; + final canSave = !_saving && value.text.trim().isNotEmpty; + final error = _error; if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { return CupertinoAlertDialog( title: const Text('Rename chat'), @@ -63,11 +90,20 @@ class _RenameChatDialogState extends State<_RenameChatDialog> { ), const SizedBox(height: 8), const Text('This name is shared with every device.'), + if (error != null) ...[ + const SizedBox(height: 8), + Text( + error, + style: TextStyle( + color: CupertinoColors.systemRed.resolveFrom(context), + ), + ), + ], ], ), actions: [ CupertinoDialogAction( - onPressed: () => Navigator.pop(context), + onPressed: _saving ? null : () => Navigator.pop(context), child: const Text('Cancel'), ), CupertinoDialogAction( @@ -79,20 +115,36 @@ class _RenameChatDialogState extends State<_RenameChatDialog> { ); } return AlertDialog( + // A long server refusal plus a 2x helper text can exceed the dialog + // height at 320px; scroll the content instead of clipping it. + scrollable: true, title: const Text('Rename chat'), - content: TextField( - key: const Key('chat-rename-field'), - controller: _title, - autofocus: true, - decoration: const InputDecoration( - labelText: 'Name', - helperText: 'This name is shared with every device.', - helperMaxLines: 2, - ), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + TextField( + key: const Key('chat-rename-field'), + controller: _title, + autofocus: true, + decoration: const InputDecoration( + labelText: 'Name', + helperText: 'This name is shared with every device.', + helperMaxLines: 2, + ), + ), + if (error != null) ...[ + const SizedBox(height: 8), + Text( + error, + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + ], + ], ), actions: [ TextButton( - onPressed: () => Navigator.pop(context), + onPressed: _saving ? null : () => Navigator.pop(context), child: const Text('Cancel'), ), FilledButton( diff --git a/app/lib/features/chat/ui/sessions/session_actions.dart b/app/lib/features/chat/ui/sessions/session_actions.dart index f70a20b2..25bacd3b 100644 --- a/app/lib/features/chat/ui/sessions/session_actions.dart +++ b/app/lib/features/chat/ui/sessions/session_actions.dart @@ -6,7 +6,7 @@ import '../../domain/chat_sessions.dart'; import 'chat_adaptive.dart'; import 'session_row_style.dart'; -enum SessionAction { rename, close, reopen } +enum SessionAction { rename, close, reopen, hide } /// The close confirmation's body, matching the web client's explanation. String closeChatConfirmation(String title) => @@ -115,6 +115,7 @@ List<({SessionAction action, String label})> _items(JsonMap session) { isClosed ? (action: SessionAction.reopen, label: 'Reopen') : (action: SessionAction.close, label: 'Close chat…'), + (action: SessionAction.hide, label: 'Hide on this device'), ]; } diff --git a/app/lib/features/chat/ui/sessions/session_list_cupertino.dart b/app/lib/features/chat/ui/sessions/session_list_cupertino.dart index a6f6456b..a0f65345 100644 --- a/app/lib/features/chat/ui/sessions/session_list_cupertino.dart +++ b/app/lib/features/chat/ui/sessions/session_list_cupertino.dart @@ -18,7 +18,10 @@ class CupertinoSessionList extends StatelessWidget { required this.onClose, required this.onReopen, required this.onStar, + required this.onHide, required this.onClearSearch, + required this.isUnseen, + required this.errorFor, }); final List sections; @@ -29,7 +32,10 @@ class CupertinoSessionList extends StatelessWidget { final ValueChanged onClose; final ValueChanged onReopen; final ValueChanged onStar; + final ValueChanged onHide; final VoidCallback? onClearSearch; + final bool Function(JsonMap) isUnseen; + final String? Function(String sessionId) errorFor; @override Widget build(BuildContext context) { @@ -57,50 +63,67 @@ class CupertinoSessionList extends StatelessWidget { ? '${section.title} · ${group.directory.isEmpty ? 'No directory' : group.directory}' : section.title, ), - children: [ - for (final session in group.sessions) - _CupertinoSessionRow( - session: session, - duplicateTitles: duplicateTitles, - onOpen: onOpen, - onRename: onRename, - onClose: onClose, - onReopen: onReopen, - onStar: onStar, - ), - ], + children: [for (final session in group.sessions) ..._row(session)], ), ]; } + + /// The tile plus its refusal. `CupertinoListTile` forces its subtitle to one + /// ellipsised line, so the server's words go in their own full-width row + /// inside the same native card. + List _row(JsonMap session) { + final id = '${session['id'] ?? ''}'; + final error = errorFor(id); + return [ + _CupertinoSessionRow( + session: session, + duplicateTitles: duplicateTitles, + unseen: isUnseen(session), + onOpen: onOpen, + onRename: onRename, + onClose: onClose, + onReopen: onReopen, + onStar: onStar, + onHide: onHide, + ), + if (error != null) + ChatRowError(message: error, messageKey: Key('chat-row-error-$id')), + ]; + } } class _CupertinoSessionRow extends StatelessWidget { const _CupertinoSessionRow({ required this.session, required this.duplicateTitles, + required this.unseen, required this.onOpen, required this.onRename, required this.onClose, required this.onReopen, required this.onStar, + required this.onHide, }); final JsonMap session; final Set duplicateTitles; + final bool unseen; final ValueChanged onOpen; final ValueChanged onRename; final ValueChanged onClose; final ValueChanged onReopen; final ValueChanged onStar; + final ValueChanged onHide; @override Widget build(BuildContext context) { final id = '${session['id'] ?? ''}'; + final subtitle = sessionSubtitle(session, unseen: unseen); return CupertinoListTile( key: Key('chat-row-$id'), leading: Icon(sessionCupertinoIcon(session)), title: Text(chatSessionTitle(session)), - subtitle: Text(sessionSubtitle(session)), + subtitle: Text(subtitle), onTap: () => onOpen(session), trailing: Row( mainAxisSize: MainAxisSize.min, @@ -129,6 +152,8 @@ class _CupertinoSessionRow extends StatelessWidget { onClose(session); case SessionAction.reopen: onReopen(session); + case SessionAction.hide: + onHide(session); } } } diff --git a/app/lib/features/chat/ui/sessions/session_list_material.dart b/app/lib/features/chat/ui/sessions/session_list_material.dart index d05cc6e7..d035fe1a 100644 --- a/app/lib/features/chat/ui/sessions/session_list_material.dart +++ b/app/lib/features/chat/ui/sessions/session_list_material.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import '../../../../core/api_gateway.dart'; import '../../domain/chat_sessions.dart'; +import 'chat_adaptive.dart'; import 'chat_sessions_body.dart'; import 'session_actions.dart'; import 'session_row_style.dart'; @@ -17,7 +18,10 @@ class MaterialSessionList extends StatelessWidget { required this.onClose, required this.onReopen, required this.onStar, + required this.onHide, required this.onClearSearch, + required this.isUnseen, + required this.errorFor, }); final List sections; @@ -28,7 +32,10 @@ class MaterialSessionList extends StatelessWidget { final ValueChanged onClose; final ValueChanged onReopen; final ValueChanged onStar; + final ValueChanged onHide; final VoidCallback? onClearSearch; + final bool Function(JsonMap) isUnseen; + final String? Function(String sessionId) errorFor; @override Widget build(BuildContext context) { @@ -64,40 +71,57 @@ class MaterialSessionList extends StatelessWidget { group.directory.isEmpty ? 'No directory' : group.directory, ), ), - for (final session in group.sessions) - _MaterialSessionRow( - session: session, - duplicateTitles: duplicateTitles, - onOpen: onOpen, - onRename: onRename, - onClose: onClose, - onReopen: onReopen, - onStar: onStar, - ), + for (final session in group.sessions) ..._row(session), ], ], ); } + + /// The tile plus its refusal at full width (a long sentence in `subtitle` + /// made the row taller than the viewport at 320px with 2x text). + List _row(JsonMap session) { + final id = '${session['id'] ?? ''}'; + final error = errorFor(id); + return [ + _MaterialSessionRow( + session: session, + duplicateTitles: duplicateTitles, + unseen: isUnseen(session), + onOpen: onOpen, + onRename: onRename, + onClose: onClose, + onReopen: onReopen, + onStar: onStar, + onHide: onHide, + ), + if (error != null) + ChatRowError(message: error, messageKey: Key('chat-row-error-$id')), + ]; + } } class _MaterialSessionRow extends StatelessWidget { const _MaterialSessionRow({ required this.session, required this.duplicateTitles, + required this.unseen, required this.onOpen, required this.onRename, required this.onClose, required this.onReopen, required this.onStar, + required this.onHide, }); final JsonMap session; final Set duplicateTitles; + final bool unseen; final ValueChanged onOpen; final ValueChanged onRename; final ValueChanged onClose; final ValueChanged onReopen; final ValueChanged onStar; + final ValueChanged onHide; @override Widget build(BuildContext context) { @@ -106,7 +130,7 @@ class _MaterialSessionRow extends StatelessWidget { key: Key('chat-row-$id'), leading: Icon(sessionMaterialIcon(session)), title: Text(chatSessionTitle(session)), - subtitle: Text(sessionSubtitle(session)), + subtitle: Text(sessionSubtitle(session, unseen: unseen)), onTap: () => onOpen(session), trailing: Row( mainAxisSize: MainAxisSize.min, @@ -135,6 +159,8 @@ class _MaterialSessionRow extends StatelessWidget { onClose(session); case SessionAction.reopen: onReopen(session); + case SessionAction.hide: + onHide(session); } } } diff --git a/app/lib/features/chat/ui/sessions/session_row_style.dart b/app/lib/features/chat/ui/sessions/session_row_style.dart index 59b8f4b3..443927ac 100644 --- a/app/lib/features/chat/ui/sessions/session_row_style.dart +++ b/app/lib/features/chat/ui/sessions/session_row_style.dart @@ -23,11 +23,11 @@ String sessionActionsLabel(JsonMap session, Set duplicateTitles) { : 'Chat actions for $title'; } -String sessionSubtitle(JsonMap session) { +String sessionSubtitle(JsonMap session, {bool? unseen}) { final directory = '${session['directory'] ?? ''}'; switch (chatSessionActivity( running: session['running'] == true, - unseen: session['unseen'] == true, + unseen: unseen ?? session['unseen'] == true, )) { case 'streaming': return '$directory · Streaming'; diff --git a/app/notes/C5-list.md b/app/notes/C5-list.md new file mode 100644 index 00000000..10eedf61 --- /dev/null +++ b/app/notes/C5-list.md @@ -0,0 +1,147 @@ +# C5-list — shared chat session actions + +The landed chat list already had rename/star/close/reopen request shapes. This +slice makes their outcome handling match the current web client (B1/B10 moved +rename and star to server-shared state) and adds the list-local hide/read state +from C13. All changes are under `lib/features/chat/ui/sessions/`, its tests, +`tool/chat_sessions_probe*`, `notes/` and one `PARITY.md` row. No thread, +composer, permission, runs, pipelines, graph, application, artifacts, schedules +or templates file changed. + +## Behaviour + +- **Create** is sent by the open dialog. The reply's `chat_session` is required + (a reply without one is refused with the web's exact sentence + `The server did not return the new chat session.` instead of opening an + invented row), the accepted session opens immediately and the list re-reads + `chat_sessions` in the background. A refusal keeps the dialog, its fields and + the server's words in place. The operation id is minted once per create intent + in the screen and passed back unchanged on every retry; `_submitting` plus a + disabled Creating… action makes a double submit send once. + Request: `{chat_create:{title,directory,operation_id}}`, plus `backend` only + when it is not `opencode` and `instructions` only when non-blank — the web's + exact shape. The pre-existing dialog title field remains (default `New chat`); + the web's own create pane fixes that title. +- **Rename** is sent by the open dialog, seeded with the effective current title + and sending only `{chat_rename:{session_id,title}}` (trimmed). The dialog stays + open with the server's words on refusal; an accepted reply closes it and the + rows come from a fresh `chat_sessions` read, never a guessed local update. The + refusal is shown only in the dialog — it is not duplicated under the row. +- **Star** sends only `{chat_star, chat_query:{session_id, starred:}}`. **Close** / **Reopen** keep the web's confirmation and send + `{chat_query:{session_id}}` to `chat_close` / `chat_reopen`. Every accepted + reply refreshes the rows from the server. A refusal is shown at full width + beneath its row in the host's error colour, so the whole server sentence + wraps instead of being clipped by `CupertinoListTile`'s one-line subtitle, and + a long reason cannot make one Material row taller than the viewport. +- **Local hide** (`Hide on this device`, after Rename and Close/Reopen in the + menu) removes the row without a server call and offers Undo in a floating + one-bar report (`Hidden on this device; the chat stays on the server.`, eight + seconds), the way the web's fixed report behaves. In Material it sits clear of + the New-chat FAB; both hosts keep it out of the body column so 2x text cannot + push the list off screen. + Hidden ids and the read watermark persist through `shared_preferences` under + `pipelines.chat.local.v1`. A first sight of a session seeds its baseline, and + `New` appears only for a strictly newer `updated_at`; opening the row advances + the watermark monotonically. The local store never gates the server read. A + closed row never reports `New`, matching `!session.closed` in the web list and + `!session.closed` in `ChatListPane.kt`. +- No session or title is invented. The local-only `New` marker reads the server + row's recency; explicit unseen marks arriving as pushed `chat_event`s and the + web's `Open` badge are not wired in this list slice. + +## Files + +- `lib/features/chat/ui/sessions/chat_session_local.dart` — pure hidden/seen + model, tolerant decoder and `SharedPreferences` store. +- `chat_sessions_controller.dart` — per-row action errors, create/rename + throw-paths, server refresh after acceptance, hide/undo, read watermark. +- `chat_sessions_screen.dart`, `chat_sessions_body.dart`, + `session_list_material.dart`, `session_list_cupertino.dart` — full-width row + refusals beneath the tile, local `New`, hide wiring and the floating Undo bar + (placed above the Material FAB and outside the body column). +- `create_chat_dialog.dart` + `chat_create_dialog_frame.dart`, + `rename_chat_dialog.dart` — in-dialog submit, refusal retention, one-shot guard. +- `chat_create_fields.dart` — expanded, ellipsised Material dropdowns with + intrinsic item height so real paths and 2x text fit. +- `session_actions.dart` — `Hide on this device`. +- `chat_adaptive.dart` — `ChatRowError` (full-width, host error colour) and the + native Undo surface. +- `tool/chat_sessions_probe_entry.dart` — stateful fixture: accepted mutations + change the next list read; `Refused title` returns the server's rename refusal; + reopening `Closed fixture` returns a multi-line refusal; `No session title` + omits `chat_session`; `?unseen=1` reports newer recency so the browser can + prove `New` (and its absence on the closed row). +- `tool/chat_sessions_probe.mjs` — real-browser flow for both hosts, including + hide/Undo at 390 and 320/2x, the `New` marker, both dialogs at 320/2x, and a + refused reopen whose full reason is captured in both hosts. + +## Checks (actual) + +- `flutter test test/features/chat/ui/sessions` — 47 tests pass. New coverage + this pass: a long row refusal keeps the whole sentence on both hosts at + 320px/2x (`RenderParagraph.didExceedMaxLines == false`, and the message is not + inside a `CupertinoListTile`/`ListTile`), the Undo bar fits 320px/2x on both + hosts and Undo still restores the row. Earlier coverage retained: create + refusal keeps the dialog and retries the same `operation_id`; double submit + sends one create; a reply without `chat_session` shows exactly + `The server did not return the new chat session.` (no `Bad state:`); rename is + seeded and sends only its two fields; a rename refusal stays in the dialog and + not under the row; star flips one field and refreshes the icon; close refusal + is visible on the row; hide/Undo touches no server action; `New` follows the + local watermark and never appears on a closed row; Material and Cupertino + rename refusals fit 320px at 2x; both create catalogs fit a real directory + path at 320px/2x, including the Material opened menu. +- Review probes (outside the repo, not committed): + `flutter test /Users/alan/.local/share/pipelines/data/artifacts/98/public/review/review_findings_test.dart` + — 5 passed (closed `New`, exact missing-session wording, Material rename + overflow, create dialog with a real path, create dialog at 320/2x). +- `flutter test` — 1006 tests pass. +- `flutter analyze` — no issues. +- `flutter build web` — built successfully. +- Fixture bundles built with + `flutter build web -t tool/chat_sessions_probe_entry.dart --dart-define=CHAT_PROBE_STYLE={material,cupertino}` + and driven in real headless Chrome over isolated loopback ports. Each host + passed list → hide/Undo (390 and 320/2x) → `New` marker → dialogs at 320/2x → + missing-session wording → create → rename → star → close → rename refusal → + refused reopen, and captured fourteen PNGs. The probe asserts: the hidden row + leaves and returns with Undo and the report stays on screen at 320/2x; the open + row reads `New` while the closed row does not; the missing-session dialog shows + the exact web sentence and no `Bad state`; the created/renamed titles come back + from the fixture's `chat_sessions`; the star count increases; the closed row + offers `Reopen`; the rename refusal keeps the dialog with + `a title with usable text is required`; and the refused reopen shows the whole + multi-line server reason under its row on both hosts. Captures are in + `public/chat-list/`: + - `material-{list-phone,list-dark-320-2x,hidden-undo,hidden-undo-320-2x,create-320-2x,rename-320-2x,new-marker,create-missing-session,created-list,renamed-list,starred-list,rename-refusal,row-refusal,row-refusal-320-2x}.png` + - the same fourteen `cupertino-*` files + +## Limits / not verified + +- Mobile (Android/iOS builds, devices, installs) is unverified. +- Browser evidence uses the in-process fixture, not an authenticated live + server; no real operator chat was created, renamed, starred, closed or hidden. +- The Cupertino list truncates long *titles* at 320px/2x (standard + `CupertinoListTile` behaviour, unchanged). Row refusals are no longer in that + one-line subtitle slot. +- A star/close/reopen refusal stays under its row until a later accepted action + on that row; the web shows a dismissible action-failed report instead. + `PARITY.md` records this as remaining. +- The Undo report is offered for eight seconds; the web uses six + (`installChatSnackbar`). Wording and one-slot replacement match. +- Hiding a row does not close an already-open conversation (the web does); that + belongs to chat-shell state, outside this list slice. +- `New` is driven by the list read plus the local watermark. The web's `Open` + badge and its active/deep-linked read suppression are not in this slice; a + deep-linked conversation is not marked read until the list reopens it. +- The Material FAB can still overlap the last row's action button at 320px/2x. + That is pre-existing list layout; the browser flow filters the refused row into + view for its 320/2x capture rather than changing the list. +- The 320/2x browser dialog captures show the fixture's default + `/workspace/demo`; selecting the real long path at that size is covered by the + widget test, not by a rendered capture. +- In the real browser, the Cupertino Undo coordinate tap is swallowed by Flutter + web's semantics DOM node; the probe activates the same rendered button through + its semantics click. Material accepts the coordinate tap. Widget tests tap the + native control directly. +- The candidate is uncommitted; no merge, push or deploy was performed. diff --git a/app/test/features/chat/ui/sessions/chat_session_dialog_layout_test.dart b/app/test/features/chat/ui/sessions/chat_session_dialog_layout_test.dart new file mode 100644 index 00000000..ca561f85 --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_session_dialog_layout_test.dart @@ -0,0 +1,97 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'chat_test_harness.dart'; +import 'fake_chat_gateway.dart'; + +/// The dialogs this slice delivers at the smallest supported size with 2x text. +void main() { + testWidgets('Material rename refusal fits 320px at 2x', (tester) async { + useSmallTextSurface(tester); + final gateway = FakeChatGateway() + ..sessionsReply = { + 'chat_sessions': [ + {'id': 's2', 'title': 'Open chat', 'directory': '/work'}, + ], + } + ..failures['chat_rename'] = 'a title with usable text is required'; + await pumpMaterialChat(tester, gateway); + + await tester.tap(find.byKey(const Key('chat-actions-s2'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Rename…')); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(const Key('chat-rename-field')), ' x '); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + + expect(find.text('a title with usable text is required'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('Cupertino rename refusal fits 320px at 2x', (tester) async { + useSmallTextSurface(tester); + final gateway = FakeChatGateway() + ..sessionsReply = { + 'chat_sessions': [ + {'id': 's2', 'title': 'Open chat', 'directory': '/work'}, + ], + } + ..failures['chat_rename'] = 'a title with usable text is required'; + await pumpCupertinoChat(tester, gateway); + + await tester.tap(find.byKey(const Key('chat-actions-s2'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Rename…')); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(const Key('chat-rename-field')), ' x '); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + + expect(find.text('a title with usable text is required'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('Material create catalog fits real paths at 320px and 2x', ( + tester, + ) async { + useSmallTextSurface(tester); + final gateway = FakeChatGateway() + ..directoriesHandler = () async => { + 'chat_directories': [ + '/work', + '/Users/alan/repos/pipelines/tmp/flutter-chat-list', + ], + }; + await pumpMaterialChat(tester, gateway); + + await tester.tap(find.byKey(const Key('chat-new-chat-fab'))); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + + await tester.tap(find.byKey(const Key('chat-create-server-directory'))); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + + await tester.tap( + find.text('/Users/alan/repos/pipelines/tmp/flutter-chat-list').last, + ); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(find.byKey(const Key('chat-create-name')), findsOneWidget); + }); + + testWidgets('Cupertino create catalog fits real paths at 320px and 2x', ( + tester, + ) async { + useSmallTextSurface(tester); + final gateway = FakeChatGateway(); + await pumpCupertinoChat(tester, gateway); + + await tester.tap(find.byKey(const Key('chat-new-chat'))); + await tester.pumpAndSettle(); + + expect(find.textContaining('Server directory:'), findsOneWidget); + expect(tester.takeException(), isNull); + }); +} diff --git a/app/test/features/chat/ui/sessions/chat_session_local_state_test.dart b/app/test/features/chat/ui/sessions/chat_session_local_state_test.dart new file mode 100644 index 00000000..85b08e94 --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_session_local_state_test.dart @@ -0,0 +1,206 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_screen.dart'; + +import 'chat_test_harness.dart'; +import 'fake_chat_gateway.dart'; + +/// Long enough that a single ellipsised line would visibly lose the reason. +const _refusal = + 'the chat is locked by another operator and cannot be reopened from here; ' + 'refresh the list to see its current state'; + +void main() { + testWidgets('hide is device-local and Undo restores the row', (tester) async { + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()}; + await pumpMaterialChat(tester, gateway); + + await tester.tap(find.byKey(const Key('chat-actions-s2'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Hide on this device')); + await tester.pumpAndSettle(); + expect(find.text('Open chat'), findsNothing); + expect( + find.text('Hidden on this device; the chat stays on the server.'), + findsOneWidget, + ); + expect(gateway.count('chat_close'), 0); + + await tester.tap(find.text('Undo')); + await tester.pumpAndSettle(); + expect(find.text('Open chat'), findsOneWidget); + expect( + find.text('Hidden on this device; the chat stays on the server.'), + findsNothing, + ); + }); + + testWidgets('New appears only for a recency newer than this device read', ( + tester, + ) async { + final gateway = FakeChatGateway(); + var updatedAt = 1000; + gateway.sessionsHandler = () async => { + 'chat_sessions': [ + { + 'id': 's1', + 'title': 'Seen chat', + 'directory': '/work', + 'updated_at': updatedAt, + }, + ], + }; + await pumpMaterialChat(tester, gateway); + expect(find.text('/work · New'), findsNothing); + + updatedAt = 2000; + await tester.tap(find.byKey(const Key('chat-refresh'))); + await tester.pumpAndSettle(); + expect(find.text('/work · New'), findsOneWidget); + + await tester.tap(find.byKey(const Key('chat-row-s1'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('chat-refresh'))); + await tester.pumpAndSettle(); + expect(find.text('/work · New'), findsNothing); + }); + + testWidgets('a closed row never reports New after newer activity', ( + tester, + ) async { + final gateway = FakeChatGateway(); + var updatedAt = 1000; + var closed = false; + gateway.sessionsHandler = () async => { + 'chat_sessions': [ + { + 'id': 's1', + 'title': 'Seen chat', + 'directory': '/work', + 'updated_at': updatedAt, + if (closed) 'closed_at': '2026-01-03', + }, + ], + }; + await pumpMaterialChat(tester, gateway); + expect(find.text('/work · New'), findsNothing); + + // Another device moved the chat on and closed it after this device read it. + updatedAt = 2000; + closed = true; + await tester.tap(find.byKey(const Key('chat-refresh'))); + await tester.pumpAndSettle(); + + expect(find.text('/work · New'), findsNothing); + expect(find.text('Closed'), findsOneWidget); + }); + + testWidgets('Material row refusal is readable at 320px 2x dark', ( + tester, + ) async { + useSmallTextSurface(tester); + final gateway = FakeChatGateway() + ..sessionsReply = { + 'chat_sessions': [ + { + 'id': 's4', + 'title': 'Closed chat', + 'directory': '/work', + 'closed_at': '2026-01-01', + }, + ], + } + ..failures['chat_reopen'] = _refusal; + await tester.pumpWidget( + MaterialApp( + theme: ThemeData( + platform: TargetPlatform.android, + brightness: Brightness.dark, + ), + home: ChatSessionsScreen( + gateway: gateway, + onOpen: (_) {}, + localStore: MemoryChatSessionLocalStore(), + ), + ), + ); + await tester.pumpAndSettle(); + + await tester.ensureVisible(find.byKey(const Key('chat-actions-s4'))); + await tester.tap(find.byKey(const Key('chat-actions-s4'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Reopen')); + await tester.pumpAndSettle(); + + final paragraph = tester.renderObject( + find.byKey(const Key('chat-row-error-s4')), + ); + expect(paragraph.didExceedMaxLines, isFalse); + expect(find.text(_refusal), findsOneWidget); + // The refusal is its own full-width row, never a `ListTile` subtitle that + // would squeeze the passage into the tile's trailing controls. + expect( + find.ancestor( + of: find.byKey(const Key('chat-row-error-s4')), + matching: find.byType(ListTile), + ), + findsNothing, + ); + expect(tester.takeException(), isNull); + }); + + testWidgets('Cupertino row refusal is readable at 320px 2x dark', ( + tester, + ) async { + useSmallTextSurface(tester); + final gateway = FakeChatGateway() + ..sessionsReply = { + 'chat_sessions': [ + { + 'id': 's4', + 'title': 'Closed chat', + 'directory': '/work', + 'closed_at': '2026-01-01', + }, + ], + } + ..failures['chat_reopen'] = _refusal; + await tester.pumpWidget( + CupertinoApp( + theme: const CupertinoThemeData(brightness: Brightness.dark), + home: ChatSessionsScreen( + gateway: gateway, + onOpen: (_) {}, + localStore: MemoryChatSessionLocalStore(), + ), + ), + ); + await tester.pumpAndSettle(); + + await tester.ensureVisible(find.byKey(const Key('chat-actions-s4'))); + await tester.tap(find.byKey(const Key('chat-actions-s4'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Reopen')); + await tester.pumpAndSettle(); + + // Regression: `CupertinoListTile.subtitle` is wrapped by the SDK in + // `DefaultTextStyle(maxLines: 1, overflow: ellipsis)`. The full sentence + // must be readable, so it cannot live inside that tile. + final paragraph = tester.renderObject( + find.byKey(const Key('chat-row-error-s4')), + ); + expect(paragraph.didExceedMaxLines, isFalse); + expect(find.text(_refusal), findsOneWidget); + expect( + find.ancestor( + of: find.byKey(const Key('chat-row-error-s4')), + matching: find.byType(CupertinoListTile), + ), + findsNothing, + ); + expect(tester.takeException(), isNull); + }); +} diff --git a/app/test/features/chat/ui/sessions/chat_session_local_test.dart b/app/test/features/chat/ui/sessions/chat_session_local_test.dart new file mode 100644 index 00000000..6905145f --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_session_local_test.dart @@ -0,0 +1,67 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_session_local.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + test('hidden ids are local, idempotent and restorable', () { + const empty = ChatSessionLocal(); + final hidden = empty.hide('s1').hide('s1').hide(''); + expect(hidden.hidden, ['s1']); + expect(hidden.isHidden('s1'), isTrue); + expect(hidden.restore('s2'), same(hidden)); + expect(hidden.restore('s1').hidden, isEmpty); + }); + + test('the read watermark only advances and cannot rewind', () { + const empty = ChatSessionLocal(); + expect(empty.watermark('s1'), 0); + final read = empty.read('s1', 200); + expect(read.watermark('s1'), 200); + expect(read.read('s1', 100), same(read)); + expect(read.read('', 500), same(read)); + }); + + test('first sight seeds a baseline only when no watermark exists', () { + const empty = ChatSessionLocal(); + final seeded = empty.seed([ + (id: 's1', updatedAt: 50), + (id: 's2', updatedAt: 0), + (id: '', updatedAt: 60), + ]); + expect(seeded.watermark('s1'), 50); + expect(seeded.watermark('s2'), 0); + final newer = seeded.seed([(id: 's1', updatedAt: 90)]); + expect(newer.watermark('s1'), 50); + }); + + test('corrupt stored values decode to the empty model', () { + expect(ChatSessionLocal.decode(null).hidden, isEmpty); + expect(ChatSessionLocal.decode('not json').seenAt, isEmpty); + expect( + ChatSessionLocal.decode('{"hidden":"x","seenAt":[]}').hidden, + isEmpty, + ); + expect( + ChatSessionLocal.decode( + '{"hidden":["s1",3],"seenAt":{"s1":"x","s2":7}}', + ).hidden, + ['s1'], + ); + expect(ChatSessionLocal.decode('{"seenAt":{"s2":7}}').watermark('s2'), 7); + }); + + test('the preferences store round-trips the device state', () async { + SharedPreferences.setMockInitialValues({}); + const store = SharedPreferencesChatSessionLocalStore(); + expect((await store.load()).hidden, isEmpty); + + final saved = const ChatSessionLocal().hide('s1').read('s1', 42); + await store.save(saved); + final loaded = await store.load(); + expect(loaded.hidden, ['s1']); + expect(loaded.watermark('s1'), 42); + + final encoded = loaded.encode(); + expect(ChatSessionLocal.decode(encoded).hidden, ['s1']); + }); +} diff --git a/app/test/features/chat/ui/sessions/chat_session_shared_actions_test.dart b/app/test/features/chat/ui/sessions/chat_session_shared_actions_test.dart new file mode 100644 index 00000000..79d55760 --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_session_shared_actions_test.dart @@ -0,0 +1,226 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; + +import 'chat_test_harness.dart'; +import 'fake_chat_gateway.dart'; + +void main() { + testWidgets('create refusal keeps the dialog and retries the same intent', ( + tester, + ) async { + final gateway = FakeChatGateway(); + final bodies = []; + JsonMap? opened; + gateway.createHandler = (fields) async { + final body = fields['chat_create']! as JsonMap; + bodies.add(body); + if (bodies.length == 1) { + throw StateError('no chat harness is available on this server'); + } + return { + 'chat_session': {'id': 'created', 'title': body['title']}, + }; + }; + await pumpMaterialChat( + tester, + gateway, + onOpen: (session) => opened = session, + ); + + await tester.tap(find.byKey(const Key('chat-new-chat-fab'))); + await tester.pumpAndSettle(); + await tester.enterText( + find.byKey(const Key('chat-create-name')), + 'Probe chat', + ); + await tester.tap(find.text('Create')); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('chat-create-name')), findsOneWidget); + expect( + find.text('Bad state: no chat harness is available on this server'), + findsOneWidget, + ); + expect(opened, isNull); + + await tester.tap(find.text('Create')); + await tester.pumpAndSettle(); + expect(bodies, hasLength(2)); + expect(bodies[1]['operation_id'], bodies[0]['operation_id']); + expect(bodies[1]['title'], 'Probe chat'); + expect(find.byKey(const Key('chat-create-name')), findsNothing); + expect(opened?['id'], 'created'); + expect(gateway.count('chat_sessions'), greaterThanOrEqualTo(2)); + }); + + testWidgets('double submit sends one create with one operation id', ( + tester, + ) async { + final gateway = FakeChatGateway(); + final reply = Completer(); + gateway.createHandler = (_) => reply.future; + await pumpMaterialChat(tester, gateway); + + await tester.tap(find.byKey(const Key('chat-new-chat-fab'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Create')); + await tester.pump(); + await tester.tap(find.text('Creating…'), warnIfMissed: false); + await tester.pump(); + expect(gateway.count('chat_create'), 1); + + reply.complete({ + 'chat_session': {'id': 'created'}, + }); + await tester.pumpAndSettle(); + expect(gateway.count('chat_create'), 1); + }); + + testWidgets('rename seeds the current title and refreshes from the server', ( + tester, + ) async { + final gateway = FakeChatGateway(); + var sessions = sampleSessions(); + gateway.sessionsHandler = () async => {'chat_sessions': sessions}; + gateway.actionHandler = (type, fields) async { + if (type == 'chat_rename') { + final body = fields['chat_rename']! as JsonMap; + sessions = [ + for (final session in sessions) + if (session['id'] == body['session_id']) + {...session, 'title': body['title']} + else + session, + ]; + } + return const {}; + }; + await pumpMaterialChat(tester, gateway); + + await tester.tap(find.byKey(const Key('chat-actions-s2'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Rename…')); + await tester.pumpAndSettle(); + expect( + tester + .widget(find.byKey(const Key('chat-rename-field'))) + .controller! + .text, + 'Open chat', + ); + + await tester.enterText( + find.byKey(const Key('chat-rename-field')), + ' Renamed chat ', + ); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + + expect(gateway.lastFields('chat_rename'), { + 'chat_rename': {'session_id': 's2', 'title': 'Renamed chat'}, + }); + expect(gateway.count('chat_sessions'), greaterThanOrEqualTo(2)); + expect(find.text('Renamed chat'), findsOneWidget); + }); + + testWidgets('star toggles one field and refreshes the rows', (tester) async { + final gateway = FakeChatGateway(); + var sessions = sampleSessions(); + gateway.sessionsHandler = () async => {'chat_sessions': sessions}; + gateway.actionHandler = (type, fields) async { + if (type == 'chat_star') { + final body = fields['chat_query']! as JsonMap; + sessions = [ + for (final session in sessions) + if (session['id'] == body['session_id']) + {...session, 'starred': body['starred']} + else + session, + ]; + } + return const {}; + }; + await pumpMaterialChat(tester, gateway); + + await tester.tap(find.byKey(const Key('chat-star-s2'))); + await tester.pumpAndSettle(); + expect(gateway.lastFields('chat_star'), { + 'chat_query': {'session_id': 's2', 'starred': true}, + }); + expect(gateway.count('chat_sessions'), greaterThanOrEqualTo(2)); + expect( + find.descendant( + of: find.byKey(const Key('chat-star-s2')), + matching: find.byIcon(Icons.star), + ), + findsOneWidget, + ); + }); + + testWidgets('close refusal stays visible on its row', (tester) async { + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()} + ..failures['chat_close'] = 'another operator already closed this chat'; + await pumpMaterialChat(tester, gateway); + + await tester.tap(find.byKey(const Key('chat-actions-s2'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Close chat…')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Close chat')); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('chat-row-error-s2')), findsOneWidget); + expect( + find.text('another operator already closed this chat'), + findsOneWidget, + ); + expect(gateway.count('chat_sessions'), 1); + }); + + testWidgets('a create reply without chat_session shows the web wording', ( + tester, + ) async { + final gateway = FakeChatGateway()..createReply = const {}; + await pumpMaterialChat(tester, gateway); + + await tester.tap(find.byKey(const Key('chat-new-chat-fab'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Create')); + await tester.pumpAndSettle(); + + expect( + find.text('The server did not return the new chat session.'), + findsOneWidget, + ); + expect(find.textContaining('Bad state'), findsNothing); + expect(find.byKey(const Key('chat-create-name')), findsOneWidget); + }); + + testWidgets('rename refusal stays in the dialog, not on the row', ( + tester, + ) async { + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()} + ..failures['chat_rename'] = 'a title with usable text is required'; + await pumpMaterialChat(tester, gateway); + + await tester.tap(find.byKey(const Key('chat-actions-s2'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Rename…')); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(const Key('chat-rename-field')), ' x '); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('chat-rename-field')), findsOneWidget); + expect(find.byKey(const Key('chat-row-error-s2')), findsNothing); + + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('chat-row-error-s2')), findsNothing); + }); +} diff --git a/app/test/features/chat/ui/sessions/chat_sessions_lifecycle_test.dart b/app/test/features/chat/ui/sessions/chat_sessions_lifecycle_test.dart index c2df3dad..0f2a44fa 100644 --- a/app/test/features/chat/ui/sessions/chat_sessions_lifecycle_test.dart +++ b/app/test/features/chat/ui/sessions/chat_sessions_lifecycle_test.dart @@ -5,6 +5,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_screen.dart'; +import 'chat_test_harness.dart'; import 'fake_chat_gateway.dart'; void main() { @@ -18,7 +19,11 @@ void main() { await tester.pumpWidget( MaterialApp( - home: ChatSessionsScreen(gateway: gateway, onOpen: (_) {}), + home: ChatSessionsScreen( + gateway: gateway, + onOpen: (_) {}, + localStore: MemoryChatSessionLocalStore(), + ), ), ); await tester.pump(); @@ -56,7 +61,11 @@ void main() { await tester.pumpWidget( MaterialApp( - home: ChatSessionsScreen(gateway: gateway, onOpen: (_) {}), + home: ChatSessionsScreen( + gateway: gateway, + onOpen: (_) {}, + localStore: MemoryChatSessionLocalStore(), + ), ), ); await tester.pump(); diff --git a/app/test/features/chat/ui/sessions/chat_test_harness.dart b/app/test/features/chat/ui/sessions/chat_test_harness.dart index d56e3b81..d7ed0221 100644 --- a/app/test/features/chat/ui/sessions/chat_test_harness.dart +++ b/app/test/features/chat/ui/sessions/chat_test_harness.dart @@ -3,9 +3,23 @@ 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/ui/sessions/chat_sessions_screen.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_session_local.dart'; import 'fake_chat_gateway.dart'; +/// In-memory device-local store; widget tests never read real preferences. +class MemoryChatSessionLocalStore implements ChatSessionLocalStore { + MemoryChatSessionLocalStore([this.state]); + + ChatSessionLocal? state; + + @override + Future load() async => state ?? const ChatSessionLocal(); + + @override + Future save(ChatSessionLocal next) async => state = next; +} + List sampleSessions() => [ {'id': 's1', 'title': 'Starred chat', 'directory': '/work', 'starred': true}, {'id': 's2', 'title': 'Open chat', 'directory': '/work'}, @@ -33,7 +47,11 @@ Future pumpMaterialChat( await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.android), - home: ChatSessionsScreen(gateway: gateway, onOpen: onOpen ?? (_) {}), + home: ChatSessionsScreen( + gateway: gateway, + onOpen: onOpen ?? (_) {}, + localStore: MemoryChatSessionLocalStore(), + ), ), ); await tester.pumpAndSettle(); @@ -46,7 +64,11 @@ Future pumpCupertinoChat( }) async { await tester.pumpWidget( CupertinoApp( - home: ChatSessionsScreen(gateway: gateway, onOpen: onOpen ?? (_) {}), + home: ChatSessionsScreen( + gateway: gateway, + onOpen: onOpen ?? (_) {}, + localStore: MemoryChatSessionLocalStore(), + ), ), ); await tester.pumpAndSettle(); @@ -62,7 +84,11 @@ Future pumpIosMaterialChat( await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.iOS), - home: ChatSessionsScreen(gateway: gateway, onOpen: onOpen ?? (_) {}), + home: ChatSessionsScreen( + gateway: gateway, + onOpen: onOpen ?? (_) {}, + localStore: MemoryChatSessionLocalStore(), + ), ), ); await tester.pumpAndSettle(); @@ -75,3 +101,13 @@ void usePhoneSurface(WidgetTester tester) { addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio); } + +/// The project's smallest supported acceptance size with 2x text. +void useSmallTextSurface(WidgetTester tester) { + tester.view.physicalSize = const Size(320, 640); + tester.view.devicePixelRatio = 1; + tester.platformDispatcher.textScaleFactorTestValue = 2; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); +} diff --git a/app/test/features/chat/ui/sessions/chat_undo_bar_test.dart b/app/test/features/chat/ui/sessions/chat_undo_bar_test.dart new file mode 100644 index 00000000..0444cd19 --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_undo_bar_test.dart @@ -0,0 +1,63 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'chat_test_harness.dart'; +import 'fake_chat_gateway.dart'; + +/// The hide report is a floating overlay, not a body row: at the project's +/// smallest size with 2x text it must stay on screen and leave the list usable. +void main() { + testWidgets('Material Undo bar fits 320px at 2x', (tester) async { + useSmallTextSurface(tester); + final gateway = FakeChatGateway() + ..sessionsReply = { + 'chat_sessions': [ + {'id': 's2', 'title': 'Open chat', 'directory': '/work'}, + ], + }; + await pumpMaterialChat(tester, gateway); + + await tester.ensureVisible(find.byKey(const Key('chat-actions-s2'))); + await tester.tap(find.byKey(const Key('chat-actions-s2'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Hide on this device')); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('chat-undo-hide')), findsOneWidget); + expect( + find.text('Hidden on this device; the chat stays on the server.'), + findsOneWidget, + ); + expect(tester.takeException(), isNull); + + await tester.tap(find.text('Undo')); + await tester.pumpAndSettle(); + expect(find.text('Open chat'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('Cupertino Undo bar fits 320px at 2x', (tester) async { + useSmallTextSurface(tester); + final gateway = FakeChatGateway() + ..sessionsReply = { + 'chat_sessions': [ + {'id': 's2', 'title': 'Open chat', 'directory': '/work'}, + ], + }; + await pumpCupertinoChat(tester, gateway); + + await tester.ensureVisible(find.byKey(const Key('chat-actions-s2'))); + await tester.tap(find.byKey(const Key('chat-actions-s2'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Hide on this device')); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('chat-undo-hide')), findsOneWidget); + expect(tester.takeException(), isNull); + + await tester.tap(find.text('Undo')); + await tester.pumpAndSettle(); + expect(find.text('Open chat'), findsOneWidget); + expect(tester.takeException(), isNull); + }); +} diff --git a/app/test/features/chat/ui/sessions/fake_chat_gateway.dart b/app/test/features/chat/ui/sessions/fake_chat_gateway.dart index 6fa13aca..dfe51f74 100644 --- a/app/test/features/chat/ui/sessions/fake_chat_gateway.dart +++ b/app/test/features/chat/ui/sessions/fake_chat_gateway.dart @@ -2,16 +2,20 @@ import 'dart:async'; import 'dart:collection'; import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; /// Scripted gateway for session-browser widget tests. class FakeChatGateway implements ApiGateway { final calls = <({String type, JsonMap fields})>[]; final pendingSessions = Queue>(); + final failures = {}; JsonMap sessionsReply = const {'chat_sessions': []}; Future Function()? sessionsHandler; JsonMap createReply = const { 'chat_session': {'id': 'created', 'title': 'New chat'}, }; + Future Function(JsonMap fields)? createHandler; + Future Function(String type, JsonMap fields)? actionHandler; Future Function()? directoriesHandler; Future Function()? backendsHandler; @@ -21,6 +25,8 @@ class FakeChatGateway implements ApiGateway { @override Future call(String type, [JsonMap fields = const {}]) { calls.add((type: type, fields: fields)); + final failure = failures[type]; + if (failure != null) return Future.error(ProtocolError(failure)); switch (type) { case 'chat_sessions': if (pendingSessions.isNotEmpty) { @@ -39,8 +45,10 @@ class FakeChatGateway implements ApiGateway { 'chat_backends': ['opencode', 'codex'], }); case 'chat_create': + if (createHandler != null) return createHandler!(fields); return Future.value(createReply); default: + if (actionHandler != null) return actionHandler!(type, fields); return Future.value(const {}); } } diff --git a/app/tool/chat_sessions_probe.mjs b/app/tool/chat_sessions_probe.mjs index 42935d24..362473c5 100644 --- a/app/tool/chat_sessions_probe.mjs +++ b/app/tool/chat_sessions_probe.mjs @@ -7,6 +7,17 @@ import { join, extname, resolve, sep } from 'node:path'; import { tmpdir } from 'node:os'; import { mkdir, mkdtemp, rm } from 'node:fs/promises'; +// Real-browser acceptance for the chat session list's shared actions. +// +// Usage (from app/): +// flutter build web -t tool/chat_sessions_probe_entry.dart \ +// --dart-define=CHAT_PROBE_STYLE=material -o build/chat-list-material +// PROBE_WEB_ROOT=$PWD/build/chat-list-material PROBE_VARIANT=material \ +// OPENCODE_ARTIFACT_DIR= node tool/chat_sessions_probe.mjs +// +// The fixture answers the app's real protocol in-process: accepted create, +// rename, star and close calls change the list the next chat_sessions read +// returns, and the title `Refused title` is refused with the server's words. const root = resolve(process.env.PROBE_WEB_ROOT ?? join(process.cwd(), 'build/web')); const variant = process.env.PROBE_VARIANT ?? 'material'; const artifactDir = process.env.OPENCODE_ARTIFACT_DIR ?? join(tmpdir(), 'chat-sessions-capture'); @@ -24,20 +35,20 @@ const server = createServer(async (req, res) => { server.listen(0, '127.0.0.1'); await once(server, 'listening'); const port = server.address().port; - const profile = await mkdtemp(join(tmpdir(), 'chat-sessions-chrome-')); +const profile = await mkdtemp(join(tmpdir(), 'chat-sessions-chrome-')); const chrome = spawn('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', [ '--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-gpu', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank', ], { stdio: ['ignore', 'ignore', 'pipe'] }); let stderr = ''; chrome.stderr.on('data', data => { stderr += data; }); -const waitFor = async fn => { +const waitFor = async (fn, label = 'condition') => { for (let i = 0; i < 100; i++) { const value = await fn(); if (value) return value; await delay(100); } - throw new Error('Timed out waiting for Chrome DevTools'); + throw new Error(`Timed out waiting for ${label}`); }; let ws; try { - const endpoint = await waitFor(() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1]); + 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; @@ -57,52 +68,230 @@ try { const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId; await send('Page.enable', {}, session); await send('Runtime.enable', {}, session); - const navigation = await send('Page.navigate', { url: `http://127.0.0.1:${port}/` }, session); - if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); 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; }; - await delay(3500); - const loaded = await evaluate("({url:location.href, ready:document.readyState, body:document.body.innerText, html:document.body.innerHTML.slice(0,500)})"); - if (!loaded?.url.includes(`127.0.0.1:${port}`)) throw new Error(`Fixture did not load: ${JSON.stringify(loaded)}`); - await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); - await delay(2500); + const load = async (suffix = '') => { + const navigation = await send('Page.navigate', { url: `http://127.0.0.1:${port}/${suffix}` }, session); + if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); + await delay(3500); + const loaded = await evaluate("({url:location.href, ready:document.readyState, body:document.body.innerText, html:document.body.innerHTML.slice(0,500)})"); + if (!loaded?.url?.includes(`127.0.0.1:${port}`)) throw new Error(`Fixture did not load: ${JSON.stringify(loaded)}`); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(2500); + }; + await load(); + + const semantics = async () => evaluate("[...document.querySelectorAll('flt-semantics')].map(x => x.getAttribute('aria-label') || x.innerText || '').filter(Boolean)"); + const bodyText = async () => evaluate('document.body.innerText'); + const visibleText = async () => `${await bodyText()}\n${(await semantics()).join('\n')}`; const clickLabel = async label => { const point = await evaluate(`(() => { const needle = ${JSON.stringify(label)}; const e=[...document.querySelectorAll('flt-semantics')].find(x => (x.getAttribute('aria-label') || x.innerText || '') === needle); if (!e) return null; const r=e.getBoundingClientRect(); return {x:r.x+r.width/2,y:r.y+r.height/2}; })()`); if (!point) return false; 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(500); return true; }; - const labels = await evaluate("[...document.querySelectorAll('flt-semantics')].map(x=>x.getAttribute('aria-label')||x.innerText).filter(Boolean)"); - if (!labels?.some(x => x.includes('New chat'))) throw new Error(`Chat fixture semantics unavailable: ${JSON.stringify(labels)}`); - if (process.env.PROBE_DEBUG) console.log(JSON.stringify(labels)); - const capture = async (name, width, height) => { - await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 }, session); - await delay(350); + const click = async (label, what = label) => { + if (!await clickLabel(label)) throw new Error(`Could not click ${what}`); + }; + const clickFirst = async label => { + const point = await evaluate(`(() => { const needle = ${JSON.stringify(label)}; const e=[...document.querySelectorAll('flt-semantics')].find(x => (x.getAttribute('aria-label') || x.innerText || '') === needle); if (!e) return null; e.scrollIntoView({block:'center'}); const r=e.getBoundingClientRect(); return {x:r.x+r.width/2,y:r.y+r.height/2}; })()`); + if (!point) throw new Error(`Could not find ${label}`); + 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(500); + }; + const waitText = (needle, label = needle) => waitFor(async () => (await visibleText()).includes(needle), label); + const focusInput = async () => { + const focused = await evaluate(`(() => { + const node = document.querySelector('input.flt-text-editing, flt-semantics input, input, textarea'); + if (!node) return false; + node.focus(); + node.select?.(); + node.setSelectionRange?.(0, (node.value || '').length); + return true; + })()`); + if (!focused) throw new Error('No semantics text field available'); + await delay(250); + return evaluate(`(() => { const node = document.querySelector('input.flt-text-editing, flt-semantics input, input, textarea'); return node ? node.value : null; })()`); + }; + const type = async text => { + await send('Input.insertText', { text }, session); + await delay(400); + }; + const resize = async (width, height, scale = 1) => { + await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: scale, mobile: width < 600 }, session); + await delay(500); + }; + const capture = async (name, width, height, scale = 1) => { + await resize(width, height, scale); const data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).result.data; await (await import('node:fs/promises')).writeFile(`${artifactDir}/${variant}-${name}.png`, Buffer.from(data, 'base64')); }; - await capture('chat-sessions-desktop', 1280, 800); - await capture('chat-sessions-phone', 390, 844); - if (!await clickLabel('New chat')) throw new Error('Could not open create dialog'); + const captures = []; + const shot = async (name, width, height, scale = 1) => { + await capture(name, width, height, scale); + captures.push(`${variant}-${name}.png`); + }; + + const labels = await semantics(); + if (!labels.some(x => x.includes('New chat'))) throw new Error(`Chat fixture semantics unavailable: ${JSON.stringify(labels)}`); + + await resize(390, 844); + await shot('list-phone', 390, 844); + await load('?dark=1'); + await shot('list-dark-320-2x', 320, 640, 2); + await load(); + await resize(390, 844); + + // Hide is device-local: the row leaves with an Undo and no server call. + await click('Chat actions for Open fixture', 'the open row actions'); + await click('Hide on this device', 'Hide on this device'); + await waitText('Hidden on this device', 'the hide Undo'); + if ((await visibleText()).includes('Open fixture')) { + throw new Error('The hidden row stayed in the list'); + } + await shot('hidden-undo', 390, 844); + await shot('hidden-undo-320-2x', 320, 640, 2); + if (!(await visibleText()).includes('Hidden on this device')) { + throw new Error('The Undo bar left the 320px view'); + } + await resize(390, 844); + await click('Undo', 'Undo'); + await delay(600); + if (!(await visibleText()).includes('Open fixture')) { + // Flutter web's semantics DOM swallows the coordinate hit for this + // Cupertino button; activate the same rendered node through its semantics + // action instead of pretending the Undo happened. + const activated = await evaluate(`(() => { const e = [...document.querySelectorAll('flt-semantics')].find(x => (x.getAttribute('aria-label') || x.innerText || '') === 'Undo'); e?.click(); return !!e; })()`); + if (!activated) throw new Error('Could not activate Undo'); await delay(600); - await send('Input.dispatchMouseEvent', { type: 'mouseWheel', x: 195, y: 680, deltaY: 598 }, session); - await delay(350); - const changedBody = await evaluate('document.body.innerText'); - await capture('chat-sessions-create-dialog', 390, 844); - if (!changedBody.includes('Server directory') || !changedBody.includes('Backend') || !changedBody.includes('New chats use the server default model.')) throw new Error(`Create dialog did not change rendered body to catalog controls: ${changedBody}`); - if (!await clickLabel('Cancel')) throw new Error('Could not close create dialog'); - await delay(600); - if (!await clickLabel('Chat actions for Open fixture')) throw new Error('Could not open row actions'); - await delay(600); - const actionsBody = await evaluate('document.body.innerText'); - const actionLabels = await evaluate("[...document.querySelectorAll('flt-semantics')].map(x => x.getAttribute('aria-label') || x.innerText || '').filter(Boolean)"); - await capture('chat-sessions-actions', 390, 844); - if (!actionLabels.some(label => label.includes('Rename…'))) throw new Error(`Row actions unavailable: ${actionsBody} / ${actionLabels}`); - console.log(JSON.stringify({ variant, labels, captures: [`${variant}-chat-sessions-desktop.png`, `${variant}-chat-sessions-phone.png`, `${variant}-chat-sessions-create-dialog.png`, `${variant}-chat-sessions-actions.png`], bodyChanged: true }, null, 2)); + } + await waitText('Open fixture', 'the restored row'); + await waitText('Open fixture', 'the restored row'); + + // Dialog chrome at the smallest size the list supports (320 CSS px, 2x DPR). + await click('New chat', 'the New chat action'); + await waitText('Server directory', 'the create dialog at 320'); + await shot('create-320-2x', 320, 640, 2); + await click('Cancel', 'Cancel the create dialog'); + await resize(390, 844); + + await click('Chat actions for Open fixture', 'the open row actions'); + await click('Rename…', 'Rename…'); + await waitText('Rename chat', 'the rename dialog at 320'); + await shot('rename-320-2x', 320, 640, 2); + await click('Cancel', 'Cancel the rename dialog'); + await resize(390, 844); + + // The New marker follows this device's read watermark and never a closed row. + await load('?unseen=1'); + await resize(390, 844); + await click('Refresh', 'Refresh'); + await waitText('/workspace/demo · New', 'the open row New marker'); + const unseenBody = await visibleText(); + if (unseenBody.includes('/workspace/archive · New')) { + throw new Error('The closed row reported New'); + } + await shot('new-marker', 390, 844); + await load(); + await resize(390, 844); + + // A create reply without `chat_session` uses the web's exact sentence. + await click('New chat', 'the New chat action'); + await waitText('Server directory', 'the create dialog'); + await focusInput(); + await type('No session title'); + await click('Create', 'the create dialog confirm'); + await waitText( + 'The server did not return the new chat session.', + 'the missing-session wording', + ); + if ((await visibleText()).includes('Bad state')) { + throw new Error('The missing-session refusal leaked a Dart StateError'); + } + await shot('create-missing-session', 390, 844); + await click('Cancel', 'Cancel the refused create'); + + // Create: the dialog sends once and the accepted row arrives from a list read. + await click('New chat', 'the New chat action'); + await waitText('Create', 'the create dialog'); + await focusInput(); + await type('Probe created'); + await click('Create', 'the create dialog confirm'); + if (process.env.PROBE_DEBUG) console.log(JSON.stringify({ afterCreate: await bodyText(), labels: await semantics() }, null, 2)); + await waitText('Probe created', 'the created row'); + if ((await visibleText()).includes('no chat harness')) throw new Error('Create did not reach the fixture'); + await shot('created-list', 390, 844); + + // Rename: seeded with the current title, then the row reads the accepted name. + await click('Chat actions for Probe created', 'the created row actions'); + await click('Rename…', 'Rename…'); + await waitText('Rename chat', 'the rename dialog'); + const seeded = await focusInput(); + if (seeded !== 'Probe created') throw new Error(`Rename was seeded with ${JSON.stringify(seeded)}`); + await type('Probe renamed'); + await click('Save', 'the rename Save'); + await waitText('Probe renamed', 'the renamed row'); + if ((await visibleText()).includes('Probe created')) throw new Error('The old title survived the accepted rename'); + await shot('renamed-list', 390, 844); + + // Star the renamed row (the first unstarred row in server order). + const unstarredBefore = (await semantics()).filter(label => label === 'Unstar chat').length; + await clickFirst('Star chat'); + await waitFor(async () => (await semantics()).filter(label => label === 'Unstar chat').length === unstarredBefore + 1, 'the shared star to refresh'); + const starredBody = await visibleText(); + if (starredBody.indexOf('Probe renamed') > starredBody.indexOf('Streaming fixture')) { + throw new Error('The starred row did not move to the Starred group'); + } + await shot('starred-list', 390, 844); + + // Close: accepted close changes the row's available action to Reopen. + await click('Chat actions for Probe renamed', 'the starred row actions'); + await click('Close chat…', 'Close chat…'); + await click('Close chat', 'the close confirmation'); + await click('Chat actions for Probe renamed', 'the closed row actions'); + if (!(await semantics()).includes('Reopen')) throw new Error('The closed row does not offer Reopen'); + await click('Rename…', 'Rename… on the closed row'); + + // Refusal: the dialog keeps the field and the server's own words. + await waitText('Rename chat', 'the rename dialog'); + await focusInput(); + await type('Refused title'); + await click('Save', 'the refused Save'); + await waitText('a title with usable text is required', 'the rename refusal'); + const kept = await evaluate(`(() => { const node = document.querySelector('input.flt-text-editing, flt-semantics input, input, textarea'); return node ? node.value : null; })()`); + const keptLabels = await semantics(); + if (kept !== 'Refused title' && !keptLabels.some(label => label.includes('Refused title'))) { + throw new Error(`The refusal lost the dialog draft: ${JSON.stringify({ kept, keptLabels })}`); + } + if (!keptLabels.includes('Cancel')) throw new Error('The refusal closed the dialog'); + await shot('rename-refusal', 390, 844); + await click('Cancel', 'Cancel after the refusal'); + + // A refused row action keeps the server's whole reason under its own row on + // both hosts — never one ellipsised line inside a Cupertino subtitle. + await clickFirst('Chat actions for Closed fixture'); + await click('Reopen', 'Reopen on the closed fixture'); + await waitText('the chat is locked by another operator', 'the row refusal'); + if ( + !(await visibleText()).includes('refresh the list to see its current state') + ) { + throw new Error('The row refusal lost the end of the server reason'); + } + await shot('row-refusal', 390, 844); + // Filter to the refused row so the 320px capture keeps the whole message + // clear of the floating action button. + await focusInput(); + await type('Closed fixture'); + await delay(600); + await shot('row-refusal-320-2x', 320, 640, 2); + + console.log(JSON.stringify({ variant, captures, hiddenUndo: true, newMarker: true, missingSessionWording: true, refusalVisible: true, rowRefusal: true, renamedFromServer: true, starredFromServer: true, closedFromServer: true }, null, 2)); } finally { ws?.close(); chrome.kill('SIGTERM'); diff --git a/app/tool/chat_sessions_probe_entry.dart b/app/tool/chat_sessions_probe_entry.dart index a0be1e08..042d6c96 100644 --- a/app/tool/chat_sessions_probe_entry.dart +++ b/app/tool/chat_sessions_probe_entry.dart @@ -2,57 +2,123 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; import 'package:pipelines_app/features/chat/session_screen.dart'; +/// Stateful chat-session fixture for the real-browser probe: every accepted +/// mutation changes the list the next `chat_sessions` read returns, so the +/// screen must refresh from the server rather than guess. A title of +/// `Refused title` is refused with the server's words; `No session title` +/// returns a create reply without `chat_session`; `?unseen=1` reports newer +/// recency after the first read so the `New` marker can be observed. class _FixtureGateway implements ApiGateway { + _FixtureGateway({this.bumpAfterFirstRead = false}); + + /// `?unseen=1`: the first list read seeds the device watermark and later + /// reads report newer activity, so the browser can prove the `New` marker. + final bool bumpAfterFirstRead; + int _reads = 0; + + final _sessions = [ + { + 'id': 'probe-open', + 'title': 'Open fixture', + 'directory': '/workspace/demo', + 'starred': true, + }, + { + 'id': 'probe-closed', + 'title': 'Closed fixture', + 'directory': '/workspace/archive', + 'closed_at': '2026-01-01', + }, + { + 'id': 'probe-stream', + 'title': 'Streaming fixture', + 'directory': '/workspace/demo', + 'running': true, + }, + ]; + int _nextId = 1; + @override Stream get frames => const Stream.empty(); + @override Future call(String type, [JsonMap fields = const {}]) async { - if (type == 'chat_sessions') { - return { - 'chat_sessions': [ - { - 'id': 'probe-open', - 'title': 'Open fixture', - 'directory': '/workspace/demo', - 'starred': true, - }, - { - 'id': 'probe-closed', - 'title': 'Closed fixture', - 'directory': '/workspace/archive', - 'closed_at': '2026-01-01', - }, - { - 'id': 'probe-stream', - 'title': 'Streaming fixture', - 'directory': '/workspace/demo', - 'running': true, - }, - ], - }; + switch (type) { + case 'chat_sessions': + _reads++; + return { + 'chat_sessions': [for (final session in _sessions) _row(session)], + }; + case 'chat_directories': + return { + 'chat_directories': [ + '/workspace/demo', + '/workspace/archive', + '/Users/alan/repos/pipelines/tmp/flutter-chat-list', + ], + }; + case 'chat_backends': + return { + 'chat_backends': ['opencode', 'codex'], + }; + case 'chat_create': + final body = fields['chat_create']! as JsonMap; + // The web's exact refusal for a reply without a created session. + if ('${body['title']}' == 'No session title') return const {}; + final session = { + 'id': 'probe-new-${_nextId++}', + 'title': body['title'], + 'directory': body['directory'], + }; + _sessions.insert(0, session); + return {'chat_session': Map.from(session)}; + case 'chat_rename': + final body = fields['chat_rename']! as JsonMap; + if ('${body['title']}' == 'Refused title') { + throw const ProtocolError('a title with usable text is required'); + } + _update('${body['session_id']}', 'title', body['title']); + return const {}; + case 'chat_star': + final body = fields['chat_query']! as JsonMap; + _update('${body['session_id']}', 'starred', body['starred']); + return const {}; + case 'chat_close': + final body = fields['chat_query']! as JsonMap; + _update('${body['session_id']}', 'closed_at', '2026-01-02'); + return const {}; + case 'chat_reopen': + final body = fields['chat_query']! as JsonMap; + // A refusal long enough to need several lines at 320px with 2x text. + if ('${body['session_id']}' == 'probe-closed') { + throw const ProtocolError( + 'the chat is locked by another operator and cannot be reopened ' + 'from here; refresh the list to see its current state', + ); + } + _update('${body['session_id']}', 'closed_at', null); + return const {}; + default: + return {'chat_session': {}}; } - if (type == 'chat_directories') { - return { - 'chat_directories': ['/workspace/demo', '/workspace/archive'], - }; + } + + void _update(String id, String key, Object? value) { + for (final session in _sessions) { + if (session['id'] == id) session[key] = value; } - if (type == 'chat_backends') { - return { - 'chat_backends': ['opencode', 'codex'], - }; + } + + JsonMap _row(JsonMap session) { + final row = Map.from(session); + if (bumpAfterFirstRead && + (row['id'] == 'probe-open' || row['id'] == 'probe-closed')) { + row['updated_at'] = _reads > 1 ? 2000 : 1000; } - if (type == 'chat_create') { - return { - 'chat_session': { - 'id': 'probe-new', - 'title': 'New fixture', - 'directory': '/workspace/demo', - }, - }; - } - return {'chat_session': {}}; + return row; } } @@ -62,14 +128,29 @@ const _probeStyle = String.fromEnvironment( ); void main() { - final home = ChatSessionsScreen(gateway: _FixtureGateway(), onOpen: (_) {}); + final dark = Uri.base.queryParameters['dark'] == '1'; + final unseen = Uri.base.queryParameters['unseen'] == '1'; + final home = ChatSessionsScreen( + gateway: _FixtureGateway(bumpAfterFirstRead: unseen), + onOpen: (_) {}, + ); if (_probeStyle == 'cupertino') { - runApp(CupertinoApp(home: home)); + runApp( + CupertinoApp( + theme: CupertinoThemeData( + brightness: dark ? Brightness.dark : Brightness.light, + ), + home: home, + ), + ); return; } runApp( MaterialApp( - theme: ThemeData(platform: TargetPlatform.android), + theme: ThemeData( + platform: TargetPlatform.android, + brightness: dark ? Brightness.dark : Brightness.light, + ), home: home, ), ); From 3fa4657be7c88c9b2d2c76d751386ea4bf5b1aa1 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 03:24:40 +0100 Subject: [PATCH 2/5] feat(app): turn documents in the artifact gallery --- .../artifacts/domain/artifact_document.dart | 153 ++++++++++ .../artifacts/domain/artifact_groups.dart | 53 +++- .../artifacts/domain/artifact_record.dart | 4 +- .../artifacts/domain/artifact_summary.dart | 19 +- .../artifacts/domain/gallery_navigation.dart | 26 +- .../ui/artifact_document_section.dart | 124 ++++++++ .../artifacts/ui/artifact_gallery_page.dart | 17 +- .../artifacts/ui/artifact_record_row.dart | 82 +++++ .../artifacts/ui/artifact_row_labels.dart | 32 ++ .../ui/artifact_selection_facts.dart | 2 +- .../artifacts/ui/artifact_viewer_body.dart | 9 +- .../artifacts/ui/artifact_visit_list.dart | 178 +++-------- app/notes/A4-docs.md | 110 +++++++ .../domain/artifact_document_test.dart | 281 ++++++++++++++++++ .../ui/artifact_gallery_documents_test.dart | 183 ++++++++++++ .../ui/artifact_viewer_page_test.dart | 38 +++ app/tool/artifact_gallery_probe.dart | 58 ++++ app/tool/artifact_gallery_probe.mjs | 164 +++++++++- 18 files changed, 1365 insertions(+), 168 deletions(-) create mode 100644 app/lib/features/artifacts/domain/artifact_document.dart create mode 100644 app/lib/features/artifacts/ui/artifact_document_section.dart create mode 100644 app/lib/features/artifacts/ui/artifact_record_row.dart create mode 100644 app/lib/features/artifacts/ui/artifact_row_labels.dart create mode 100644 app/notes/A4-docs.md create mode 100644 app/test/features/artifacts/domain/artifact_document_test.dart create mode 100644 app/test/features/artifacts/ui/artifact_gallery_documents_test.dart diff --git a/app/lib/features/artifacts/domain/artifact_document.dart b/app/lib/features/artifacts/domain/artifact_document.dart new file mode 100644 index 00000000..66e7c958 --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_document.dart @@ -0,0 +1,153 @@ +import '../../../core/api_gateway.dart'; +import 'artifact_capture.dart'; +import 'artifact_kind.dart'; +import 'artifact_record.dart'; +import 'artifact_selection.dart'; + +/// The exact server-recorded name of a visit's session export. It is the one +/// turn document that only ever opens externally. +const String sessionExportDocumentName = 'session.html'; + +/// The turn-protocol documents a visit records, in the order the audit surface +/// presents them. These are the same files the stage-artifact filter treats as +/// turn-owned ([systemArtifactNames]), aliased so a rename cannot make the +/// gallery and the filter disagree. +const List turnDocumentNames = systemArtifactNames; + +/// The exact absence wording for a missing turn document. Session absence is +/// contextual and comes from [sessionDocumentAbsence]. +const String noInputDocument = 'No input recorded.'; +const String noOutputDocument = 'No output recorded.'; +const String noMemoryDocument = 'No memory recorded for this visit.'; + +/// One presented turn document of a visit. +/// +/// [record] is the server's exact recorded artifact, or null when the visit did +/// not record that document. A null record is never completed from a step field +/// or another document: the entry carries [absence] instead, so the gallery can +/// show why the document is missing. +class ArtifactDocument { + const ArtifactDocument({ + required this.name, + required this.record, + required this.absence, + }); + + final String name; + final ArtifactRecord? record; + + /// The exact wording shown when [record] is null; empty when recorded. + final String absence; + + /// The session export is read-only evidence: it only ever opens externally. + bool get externalOnly => name == sessionExportDocumentName; + + /// Whether selecting this document opens the existing in-app renderer. A + /// session export is excluded even if the server sniffed it as text. + bool get opensInViewer { + final recorded = record; + if (recorded == null || externalOnly) return false; + return isViewerArtifact(recorded.contentType, recorded.name); + } +} + +String? _text(dynamic value) { + if (value == null) return null; + final text = '$value'; + return text.isEmpty ? null : text; +} + +/// The web client's contextual session wording, used only when no exact +/// `session.html` artifact was recorded. A recorded session id and a missing +/// export are different facts and are never collapsed into "not recorded". +String sessionDocumentAbsence(JsonMap step) { + final export = step['session_export']; + final evidence = export is Map ? Map.from(export) : null; + final evidenceSessionId = _text(evidence?['session_id']); + final sessionId = _text(step['session_id']) ?? evidenceSessionId ?? ''; + if (sessionId.isNotEmpty) { + final recoveryValue = step['session_export_recovery']; + final recovery = recoveryValue is Map + ? Map.from(recoveryValue) + : null; + final recoveryStatus = _text(recovery?['status']); + final evidenceStatus = _text(evidence?['status']); + final status = recoveryStatus == 'pending' || recoveryStatus == 'running' + ? 'pending recovery' + : evidenceStatus == 'complete' + ? 'not available in the artifact inventory' + : evidenceStatus ?? 'not yet available'; + final diagnostic = _text(evidence?['diagnostic']); + return 'Session $sessionId is recorded. Its export is $status.' + '${diagnostic == null ? '' : ' $diagnostic'}'; + } + final model = _text(step['model']) != null || _text(step['provider']) != null; + final status = _text(step['status']); + final outcome = _text(step['outcome']); + if (status == 'skipped' || outcome == 'skipped') { + return 'This visit was skipped; no harness session was started.'; + } + if (status == 'canceled' || status == 'interrupted') { + return 'The stage stopped before a harness session was recorded.'; + } + if (model) { + if (status == 'running') return 'The stage session is being created.'; + if (status == 'failed') { + final diagnostic = _text(step['diagnostic']); + return diagnostic == null + ? 'The stage did not create a harness session.' + : 'The stage did not create a harness session. $diagnostic'; + } + return 'Runtime error: this model stage has no recorded session identity.'; + } + return 'This visit has no harness session.'; +} + +String _absenceFor(String name, JsonMap step) => switch (name) { + 'input.md' => noInputDocument, + 'output.md' => noOutputDocument, + 'memory.md' => noMemoryDocument, + _ => sessionDocumentAbsence(step), +}; + +/// Every turn document slot of one visit, recorded or absent. +/// +/// A capture whose `artifacts` field is absent yields no slots at all: a missing +/// capture is not evidence that the visit recorded no document. A visit that +/// recorded none of the four turn documents yields no slots either, so a stage +/// outside the turn protocol is never presented as four missing documents. Only +/// exact recorded names are presented; nothing is synthesized from other step +/// fields. +List visitDocuments(JsonMap step) { + final capture = ArtifactCapture.fromStep(step); + if (!capture.isAvailable) return const []; + final recorded = presentedArtifacts(capture.artifacts); + ArtifactRecord? firstNamed(String name) { + for (final artifact in recorded) { + if (artifact.name == name) return artifact; + } + return null; + } + + final records = {}; + for (final name in turnDocumentNames) { + final record = firstNamed(name); + if (record != null) records[name] = record; + } + if (records.isEmpty) return const []; + + final documents = []; + for (final name in turnDocumentNames) { + final record = records[name]; + documents.add( + record == null + ? ArtifactDocument( + name: name, + record: null, + absence: _absenceFor(name, step), + ) + : ArtifactDocument(name: name, record: record, absence: ''), + ); + } + return List.unmodifiable(documents); +} diff --git a/app/lib/features/artifacts/domain/artifact_groups.dart b/app/lib/features/artifacts/domain/artifact_groups.dart index f9d861f3..49ff4f9d 100644 --- a/app/lib/features/artifacts/domain/artifact_groups.dart +++ b/app/lib/features/artifacts/domain/artifact_groups.dart @@ -1,14 +1,17 @@ import '../../../core/api_gateway.dart'; import '../../graph/domain/stage_visits.dart'; +import 'artifact_document.dart'; import 'artifact_record.dart'; import 'artifact_selection.dart'; -/// One gallery group: the stage-produced artifacts of a recorded stage visit. +/// One gallery group: the stage-produced artifacts of a recorded stage visit +/// plus that visit's turn documents, recorded or explicitly absent. class ArtifactGroup { const ArtifactGroup({ required this.stageKey, required this.visit, required this.artifacts, + this.documents = const [], }); final String stageKey; @@ -18,6 +21,15 @@ class ArtifactGroup { final int visit; final List artifacts; + + /// The visit's turn-document slots. Empty when the capture was unavailable, + /// so an unknown capture is never presented as four missing documents. + final List documents; + + /// The count the gallery header reports: stage artifacts plus the turn + /// documents the server actually recorded, never an absent slot. + int get recordedCount => + artifacts.length + documents.where((doc) => doc.record != null).length; } int _sequenceOf(JsonMap step) { @@ -86,6 +98,45 @@ List artifactGroups(List steps) { return List.unmodifiable(groups); } +String _galleryKey(String stageKey, int visit) => '$stageKey\u0000$visit'; + +/// The gallery's per-visit groups: stage artifacts and turn documents in one +/// section per recorded visit. +/// +/// Stage-only grouping is unchanged ([artifactGroups]); this function adds the +/// turn-document slots a visit recorded and keeps a visit whose only recorded +/// files are turn documents. A visit with neither stage artifacts nor a +/// recorded document, or whose capture is unavailable, produces no group. +List galleryGroups(List steps) { + if (steps.isEmpty) return const []; + final stageGroups = { + for (final group in artifactGroups(steps)) + _galleryKey(group.stageKey, group.visit): group, + }; + final groups = []; + for (final entry in visitsByStage(steps).entries) { + for (var index = 0; index < entry.value.length; index += 1) { + final step = entry.value[index]; + final visit = displayVisit(step, index); + final base = stageGroups[_galleryKey(entry.key, visit)]; + final documents = visitDocuments(step); + final recordedDocuments = documents.where((doc) => doc.record != null); + if ((base?.artifacts.isEmpty ?? true) && recordedDocuments.isEmpty) { + continue; + } + groups.add( + ArtifactGroup( + stageKey: entry.key, + visit: visit, + artifacts: base?.artifacts ?? const [], + documents: documents, + ), + ); + } + } + return List.unmodifiable(groups); +} + /// One visit's stage artifacts, excluding shared public files that an earlier /// visit already recorded. A repeated non-public name in a later visit stays /// because it is a different recorded artifact, not the same shared file. diff --git a/app/lib/features/artifacts/domain/artifact_record.dart b/app/lib/features/artifacts/domain/artifact_record.dart index 6c6bc845..3faef2df 100644 --- a/app/lib/features/artifacts/domain/artifact_record.dart +++ b/app/lib/features/artifacts/domain/artifact_record.dart @@ -6,8 +6,8 @@ import '../../../core/api_gateway.dart'; const String legacySessionMarkdownArtifact = 'session.md'; /// The files the turn protocol itself writes for every visit. They are audit -/// evidence, not stage output, so the artifact gallery lists stage files first -/// and keeps these for an audit/debug surface. +/// evidence, not stage output: the artifact gallery presents them as the visit's +/// turn documents, and the stage-file list still excludes them. const List systemArtifactNames = [ 'input.md', 'memory.md', diff --git a/app/lib/features/artifacts/domain/artifact_summary.dart b/app/lib/features/artifacts/domain/artifact_summary.dart index 44161a86..58534cc2 100644 --- a/app/lib/features/artifacts/domain/artifact_summary.dart +++ b/app/lib/features/artifacts/domain/artifact_summary.dart @@ -16,14 +16,15 @@ String artifactsEmptyMessage(bool executing) => executing /// The run summary's Artifacts section header. /// -/// The recorded count is exactly the number of tiles [artifactGroups] yields; -/// the title takes its singular form for one. A run whose capture is unavailable -/// says so instead of claiming that nothing was recorded. Partial capture is -/// flagged when any visit excluded or omitted files. +/// The recorded count is the number of recorded entries [galleryGroups] yields: +/// stage files plus the turn documents the server actually recorded, never an +/// absent slot. The title takes its singular form for one. A run whose capture is +/// unavailable says so instead of claiming that nothing was recorded. Partial +/// capture is flagged when any visit excluded or omitted files. String artifactsHeader(List steps, {required bool executing}) { - final recorded = artifactGroups( + final recorded = galleryGroups( steps, - ).fold(0, (sum, group) => sum + group.artifacts.length); + ).fold(0, (sum, group) => sum + group.recordedCount); if (recorded == 0) { if (executing) return artifactsEmptyMessage(true); final unavailable = steps.any( @@ -44,8 +45,10 @@ String artifactsHeader(List steps, {required bool executing}) { /// /// A running visit says capture pending. A finished visit whose capture field was /// absent says capture unavailable rather than "not recorded"; only an explicitly -/// empty capture says "not recorded for this visit". Recorded counts exclude the -/// turn-owned files and the retired session markdown, so the words match tiles. +/// empty capture says "not recorded for this visit". Without [count] the recorded +/// number excludes the turn-owned files and the retired session markdown, so the +/// stage-artifact words match the stage tiles; a caller that presents the turn +/// documents too passes its own recorded entry count. String artifactsSummary(JsonMap step, {int? count}) { final capture = ArtifactCapture.fromStep(step); final recorded = count ?? stageArtifacts(step).length; diff --git a/app/lib/features/artifacts/domain/gallery_navigation.dart b/app/lib/features/artifacts/domain/gallery_navigation.dart index a5d519a9..856f31ee 100644 --- a/app/lib/features/artifacts/domain/gallery_navigation.dart +++ b/app/lib/features/artifacts/domain/gallery_navigation.dart @@ -36,21 +36,27 @@ String artifactVisitIdentityOf(ArtifactGroup group, ArtifactRecord artifact) { } /// The artifacts the viewer can page through, in gallery order: group by group, -/// each group's images, videos and markdown/text documents in recorded order. -/// Other artifacts open externally and are not part of this list. Pure: it only -/// filters and orders records the gallery already holds. +/// each group's images, videos and markdown/text documents in recorded order, +/// then the visit's recorded turn documents that open in the renderer. A session +/// export is external-only and never enters the page list. Pure: it only filters +/// and orders records the gallery already holds. List pagedArtifacts(List groups) { final pages = []; + void add(ArtifactGroup group, ArtifactRecord artifact) { + pages.add( + PagedArtifact(group: group, artifact: artifact, pageIndex: pages.length), + ); + } + for (final group in groups) { for (final artifact in group.artifacts) { if (!isViewerArtifact(artifact.contentType, artifact.name)) continue; - pages.add( - PagedArtifact( - group: group, - artifact: artifact, - pageIndex: pages.length, - ), - ); + add(group, artifact); + } + for (final document in group.documents) { + final artifact = document.record; + if (artifact == null || !document.opensInViewer) continue; + add(group, artifact); } } return List.unmodifiable(pages); diff --git a/app/lib/features/artifacts/ui/artifact_document_section.dart b/app/lib/features/artifacts/ui/artifact_document_section.dart new file mode 100644 index 00000000..003af5e9 --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_document_section.dart @@ -0,0 +1,124 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; +import '../domain/artifact_document.dart'; +import '../domain/artifact_groups.dart'; +import 'artifact_record_row.dart'; +import 'artifact_row_labels.dart'; + +/// One visit's turn documents, shown below its stage artifacts. +/// +/// A recorded document is a normal gallery row with its recorded name, MIME and +/// size. A document the visit did not record is a non-actionable row carrying +/// the exact absence wording. The section never synthesizes a missing document +/// from another field and never offers an action for it. +class ArtifactDocumentSection extends StatelessWidget { + const ArtifactDocumentSection({ + super.key, + required this.group, + this.selectedIdentity, + this.onSelected, + }); + + final ArtifactGroup group; + final String? selectedIdentity; + final ArtifactSelected? onSelected; + + @override + Widget build(BuildContext context) { + final rows = [ + for (final document in group.documents) _row(document), + ]; + if (usesCupertinoHost(context)) { + return CupertinoListSection.insetGrouped( + header: Semantics( + container: true, + header: true, + child: const Text('Turn documents'), + ), + hasLeading: false, + children: rows, + ); + } + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 16, 4), + child: Semantics( + container: true, + header: true, + child: const Text('Turn documents'), + ), + ), + ...rows, + ], + ); + } + + Widget _row(ArtifactDocument document) { + final record = document.record; + if (record == null) return _AbsentDocumentRow(document: document); + final key = ValueKey( + '${artifactVisitIdentity(group, record)}\u0000document', + ); + return ArtifactRecordRow( + key: key, + group: group, + artifact: record, + selected: selectedIdentity == artifactVisitIdentity(group, record), + onSelected: onSelected, + ); + } +} + +/// A document the visit did not record: the recorded name and its exact absence +/// wording, with no tap target. +class _AbsentDocumentRow extends StatelessWidget { + const _AbsentDocumentRow({required this.document}); + + final ArtifactDocument document; + + @override + Widget build(BuildContext context) { + if (!usesCupertinoHost(context)) { + // The absence line is informational product content, so it keeps the + // theme's normal secondary label colour. A disabled tile would paint both + // lines at the disabled colour (about 2.7:1 in light mode); no `onTap` + // keeps the row non-actionable without dimming it. + return ListTile( + title: Text(document.name), + subtitle: Text( + document.absence, + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ); + } + final textTheme = CupertinoTheme.of(context).textTheme; + final absenceStyle = textTheme.textStyle.copyWith( + color: CupertinoColors.secondaryLabel.resolveFrom(context), + ); + return Semantics( + container: true, + child: SizedBox( + width: double.infinity, + child: Padding( + padding: kCupertinoButtonPadding[CupertinoButtonSize.large]!, + child: DefaultTextStyle.merge( + style: textTheme.textStyle, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(document.name), + Text(document.absence, style: absenceStyle), + ], + ), + ), + ), + ), + ); + } +} diff --git a/app/lib/features/artifacts/ui/artifact_gallery_page.dart b/app/lib/features/artifacts/ui/artifact_gallery_page.dart index e97c8b41..b2a2087e 100644 --- a/app/lib/features/artifacts/ui/artifact_gallery_page.dart +++ b/app/lib/features/artifacts/ui/artifact_gallery_page.dart @@ -7,6 +7,7 @@ import '../../../ui/adaptive/host.dart'; import '../../chat/ui/transcript/chat_markdown_view.dart'; import '../actions/artifact_file_actions.dart'; import '../actions/artifact_file_bridge.dart'; +import '../domain/artifact_document.dart'; import '../domain/artifact_groups.dart'; import '../domain/artifact_kind.dart'; import '../domain/artifact_record.dart'; @@ -76,9 +77,17 @@ class _ArtifactGalleryPageState extends State { String? _status; List _groupsOf(int? focusIndex) { - if (focusIndex == null) return artifactGroups(widget.steps); + if (focusIndex == null) return galleryGroups(widget.steps); final group = visitArtifactGroup(widget.steps, focusIndex); - return group == null ? const [] : [group]; + if (group == null) return const []; + // The visit pane sees the same document-enriched group the gallery shows for + // that visit, not only its recorded files. + for (final enriched in galleryGroups(widget.steps)) { + if (enriched.stageKey == group.stageKey && enriched.visit == group.visit) { + return [enriched]; + } + } + return [group]; } Future _select(ArtifactGroup group, ArtifactRecord artifact) async { @@ -86,11 +95,13 @@ class _ArtifactGalleryPageState extends State { final resolved = artifact.hasUrl ? resolveArtifactUrl(widget.configuredEndpoint, artifact.url) : null; + final externalOnly = artifact.name == sessionExportDocumentName; setState(() { _selectedIdentity = identity; _status = null; }); - if (resolved != null && + if (!externalOnly && + resolved != null && isViewerArtifact(artifact.contentType, artifact.name)) { await _openViewer(identity); return; diff --git a/app/lib/features/artifacts/ui/artifact_record_row.dart b/app/lib/features/artifacts/ui/artifact_record_row.dart new file mode 100644 index 00000000..2abd427c --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_record_row.dart @@ -0,0 +1,82 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; +import '../domain/artifact_groups.dart'; +import '../domain/artifact_record.dart'; +import 'artifact_row_labels.dart'; + +/// One recorded artifact row in a gallery section. +/// +/// Material draws a standard [ListTile]; Cupertino draws the same content in a +/// grouped-row button. The row only reports the selection; it never resolves a +/// url, opens a preview, downloads, shares or filters. +class ArtifactRecordRow extends StatelessWidget { + const ArtifactRecordRow({ + super.key, + required this.group, + required this.artifact, + required this.selected, + required this.onSelected, + }); + + final ArtifactGroup group; + final ArtifactRecord artifact; + final bool selected; + final ArtifactSelected? onSelected; + + @override + Widget build(BuildContext context) { + if (!usesCupertinoHost(context)) { + return ListTile( + selected: selected, + title: Text(artifactDisplayName(artifact)), + subtitle: Text(artifactFactsLabel(artifact)), + trailing: selected ? const Icon(Icons.check) : null, + onTap: onSelected == null ? null : () => onSelected!(group, artifact), + ); + } + final textTheme = CupertinoTheme.of(context).textTheme; + final factsStyle = textTheme.textStyle.copyWith( + color: CupertinoColors.secondaryLabel.resolveFrom(context), + ); + final content = DefaultTextStyle.merge( + style: textTheme.textStyle, + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(artifactDisplayName(artifact)), + Text(artifactFactsLabel(artifact), style: factsStyle), + ], + ), + ), + if (selected) const Icon(CupertinoIcons.check_mark), + ], + ), + ); + // `container` makes this row its own semantics node, so the section + // heading stays a separate header node and never covers the row. + return Semantics( + container: true, + selected: selected, + child: SizedBox( + width: double.infinity, + // A read-only row is not a button: a disabled CupertinoButton would + // still expose a button role to assistive technology. + child: onSelected == null + ? Padding( + padding: kCupertinoButtonPadding[CupertinoButtonSize.large]!, + child: content, + ) + : CupertinoButton( + alignment: AlignmentDirectional.centerStart, + onPressed: () => onSelected!(group, artifact), + child: content, + ), + ), + ); + } +} diff --git a/app/lib/features/artifacts/ui/artifact_row_labels.dart b/app/lib/features/artifacts/ui/artifact_row_labels.dart new file mode 100644 index 00000000..89442343 --- /dev/null +++ b/app/lib/features/artifacts/ui/artifact_row_labels.dart @@ -0,0 +1,32 @@ +import '../domain/artifact_groups.dart'; +import '../domain/artifact_kind.dart'; +import '../domain/artifact_record.dart'; +import '../domain/gallery_navigation.dart'; + +/// A selection callback carrying the recorded group and the exact record the +/// operator chose, so the visit is never lost when two groups share a name. +typedef ArtifactSelected = + void Function(ArtifactGroup group, ArtifactRecord artifact); + +/// The identity of [artifact] inside [group], shared by rows and the viewer. +String artifactVisitIdentity(ArtifactGroup group, ArtifactRecord artifact) => + artifactVisitIdentityOf(group, artifact); + +/// The recorded group heading, matching the web client's group vocabulary. +String artifactGroupLabel(ArtifactGroup group) => + '${group.stageKey} · visit ${group.visit}'; + +/// The displayed artifact name: a missing server name stays explicit. +String artifactDisplayName(ArtifactRecord artifact) => + artifact.name.isEmpty ? '(unnamed artifact)' : artifact.name; + +/// The recorded MIME and byte size, never inferred from the name. +/// +/// The value and its unit are joined by a non-breaking space so a narrow row +/// never wraps `120.6` away from `KiB`. +String artifactFactsLabel(ArtifactRecord artifact) { + final type = artifact.contentType.split(';').first.trim(); + final mime = type.isEmpty ? 'type not recorded' : type; + final size = humanBytes(artifact.sizeBytes).replaceFirst(' ', '\u00a0'); + return '$mime · $size'; +} diff --git a/app/lib/features/artifacts/ui/artifact_selection_facts.dart b/app/lib/features/artifacts/ui/artifact_selection_facts.dart index 083a322e..391820c5 100644 --- a/app/lib/features/artifacts/ui/artifact_selection_facts.dart +++ b/app/lib/features/artifacts/ui/artifact_selection_facts.dart @@ -54,7 +54,7 @@ class ArtifactSelectionFacts extends StatelessWidget { Text(artifactGroupLabel(group)), if (recordedStep != null) ...[ const SizedBox(height: 8), - Text(artifactsSummary(recordedStep, count: group.artifacts.length)), + Text(artifactsSummary(recordedStep, count: group.recordedCount)), for (final note in artifactCaptureNotes(recordedStep)) Padding(padding: const EdgeInsets.only(top: 4), child: Text(note)), ], diff --git a/app/lib/features/artifacts/ui/artifact_viewer_body.dart b/app/lib/features/artifacts/ui/artifact_viewer_body.dart index f5ffdbfe..4014bb09 100644 --- a/app/lib/features/artifacts/ui/artifact_viewer_body.dart +++ b/app/lib/features/artifacts/ui/artifact_viewer_body.dart @@ -222,8 +222,13 @@ class _Pager extends StatelessWidget { top: false, child: Padding( padding: const EdgeInsetsDirectional.fromSTEB(8, 0, 8, 4), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, + // A `Row` clips the second labelled button once 2x text is wider than + // the viewport; a `Wrap` keeps both controls whole and lets them take + // separate lines, like the Cupertino pager. + child: Wrap( + alignment: WrapAlignment.spaceBetween, + spacing: 8, + runSpacing: 4, children: [ TextButton.icon( onPressed: hasPrevious ? onPrevious : null, diff --git a/app/lib/features/artifacts/ui/artifact_visit_list.dart b/app/lib/features/artifacts/ui/artifact_visit_list.dart index a134d250..38250b2f 100644 --- a/app/lib/features/artifacts/ui/artifact_visit_list.dart +++ b/app/lib/features/artifacts/ui/artifact_visit_list.dart @@ -3,50 +3,28 @@ import 'package:flutter/material.dart'; import '../../../ui/adaptive/host.dart'; import '../domain/artifact_groups.dart'; -import '../domain/artifact_kind.dart'; import '../domain/artifact_record.dart'; -import '../domain/gallery_navigation.dart'; +import 'artifact_document_section.dart'; +import 'artifact_record_row.dart'; +import 'artifact_row_labels.dart'; -/// A selection callback carrying the recorded group and the exact record the -/// operator chose, so the visit is never lost when two groups share a name. -typedef ArtifactSelected = - void Function(ArtifactGroup group, ArtifactRecord artifact); - -/// The identity of [artifact] inside [group], for -/// [ArtifactVisitList.selectedIdentity]. -/// -/// The recorded stage visit is part of the key, so two visits that both -/// recorded `result.csv` stay distinct even when their urls are identical. -/// A filename alone is never an identity. -String artifactVisitIdentity(ArtifactGroup group, ArtifactRecord artifact) => - artifactVisitIdentityOf(group, artifact); - -/// The recorded group heading, matching the web client's group vocabulary. -String artifactGroupLabel(ArtifactGroup group) => - '${group.stageKey} · visit ${group.visit}'; - -/// The displayed artifact name: a missing server name stays explicit. -String artifactDisplayName(ArtifactRecord artifact) => - artifact.name.isEmpty ? '(unnamed artifact)' : artifact.name; - -/// The recorded MIME and byte size, never inferred from the name. -/// -/// The value and its unit are joined by a non-breaking space so a narrow row -/// never wraps `120.6` away from `KiB`. -String artifactFactsLabel(ArtifactRecord artifact) { - final type = artifact.contentType.split(';').first.trim(); - final mime = type.isEmpty ? 'type not recorded' : type; - final size = humanBytes(artifact.sizeBytes).replaceFirst(' ', '\u00a0'); - return '$mime · $size'; -} +export 'artifact_row_labels.dart' + show + ArtifactSelected, + artifactDisplayName, + artifactFactsLabel, + artifactGroupLabel, + artifactVisitIdentity; /// A read-only, selectable list of recorded artifact groups. /// -/// Each group shows its recorded stage and visit, and each row its recorded -/// filename, content type and size. Rendering uses the host's own controls: -/// Material list tiles under [MaterialApp] and grouped Cupertino list sections -/// under [CupertinoApp]. It never resolves a url, opens a preview, downloads, -/// shares or filters; the only action is [onSelected]. +/// Each group shows its recorded stage and visit, its stage-produced artifacts, +/// then its turn documents. Every recorded row shows its recorded filename, +/// content type and size; a turn document the visit did not record stays a +/// non-actionable row with the exact absence wording. Rendering uses the host's +/// own controls: Material list tiles under [MaterialApp] and grouped Cupertino +/// list sections under [CupertinoApp]. It never resolves a url, opens a preview, +/// downloads, shares or filters. class ArtifactVisitList extends StatelessWidget { const ArtifactVisitList({ super.key, @@ -70,7 +48,7 @@ class ArtifactVisitList extends StatelessWidget { if (usesCupertinoHost(context)) { return ListView( children: [ - for (final group in groups) + for (final group in groups) ...[ CupertinoListSection.insetGrouped( // `container` keeps the heading a separate semantics node. Without // it the heading merges into the neighbouring row button, so it is @@ -83,15 +61,16 @@ class ArtifactVisitList extends StatelessWidget { hasLeading: false, children: [ for (var index = 0; index < group.artifacts.length; index += 1) - _CupertinoRow( - key: _rowKey(group, group.artifacts[index], index), - group: group, - artifact: group.artifacts[index], - selected: _isSelected(group, group.artifacts[index]), - onSelected: onSelected, - ), + _row(group, group.artifacts[index], index), ], ), + if (group.documents.isNotEmpty) + ArtifactDocumentSection( + group: group, + selectedIdentity: selectedIdentity, + onSelected: onSelected, + ), + ], ], ); } @@ -107,11 +86,11 @@ class ArtifactVisitList extends StatelessWidget { ), ), for (var index = 0; index < group.artifacts.length; index += 1) - _MaterialRow( - key: _rowKey(group, group.artifacts[index], index), + _row(group, group.artifacts[index], index), + if (group.documents.isNotEmpty) + ArtifactDocumentSection( group: group, - artifact: group.artifacts[index], - selected: _isSelected(group, group.artifacts[index]), + selectedIdentity: selectedIdentity, onSelected: onSelected, ), ], @@ -119,96 +98,15 @@ class ArtifactVisitList extends StatelessWidget { ); } - bool _isSelected(ArtifactGroup group, ArtifactRecord artifact) => - selectedIdentity == artifactVisitIdentity(group, artifact); - - static Key _rowKey(ArtifactGroup group, ArtifactRecord artifact, int index) => - ValueKey('${artifactVisitIdentity(group, artifact)}\u0000$index'); -} - -class _MaterialRow extends StatelessWidget { - const _MaterialRow({ - super.key, - required this.group, - required this.artifact, - required this.selected, - required this.onSelected, - }); - - final ArtifactGroup group; - final ArtifactRecord artifact; - final bool selected; - final ArtifactSelected? onSelected; - - @override - Widget build(BuildContext context) { - return ListTile( - selected: selected, - title: Text(artifactDisplayName(artifact)), - subtitle: Text(artifactFactsLabel(artifact)), - trailing: selected ? const Icon(Icons.check) : null, - onTap: onSelected == null ? null : () => onSelected!(group, artifact), - ); - } -} - -class _CupertinoRow extends StatelessWidget { - const _CupertinoRow({ - super.key, - required this.group, - required this.artifact, - required this.selected, - required this.onSelected, - }); - - final ArtifactGroup group; - final ArtifactRecord artifact; - final bool selected; - final ArtifactSelected? onSelected; - - @override - Widget build(BuildContext context) { - final textTheme = CupertinoTheme.of(context).textTheme; - final factsStyle = textTheme.textStyle.copyWith( - color: CupertinoColors.secondaryLabel.resolveFrom(context), - ); - final content = DefaultTextStyle.merge( - style: textTheme.textStyle, - child: Row( - children: [ - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(artifactDisplayName(artifact)), - Text(artifactFactsLabel(artifact), style: factsStyle), - ], - ), - ), - if (selected) const Icon(CupertinoIcons.check_mark), - ], - ), - ); - // `container` makes this row its own semantics node, so the section - // heading stays a separate header node and never covers the row. - return Semantics( - container: true, - selected: selected, - child: SizedBox( - width: double.infinity, - // A read-only row is not a button: a disabled CupertinoButton would - // still expose a button role to assistive technology. - child: onSelected == null - ? Padding( - padding: kCupertinoButtonPadding[CupertinoButtonSize.large]!, - child: content, - ) - : CupertinoButton( - alignment: AlignmentDirectional.centerStart, - onPressed: () => onSelected!(group, artifact), - child: content, - ), + Widget _row(ArtifactGroup group, ArtifactRecord artifact, int index) { + return ArtifactRecordRow( + key: ValueKey( + '${artifactVisitIdentity(group, artifact)}\u0000$index', ), + group: group, + artifact: artifact, + selected: selectedIdentity == artifactVisitIdentity(group, artifact), + onSelected: onSelected, ); } } diff --git a/app/notes/A4-docs.md b/app/notes/A4-docs.md new file mode 100644 index 00000000..c189ffe4 --- /dev/null +++ b/app/notes/A4-docs.md @@ -0,0 +1,110 @@ +# A4 — turn documents in the artifact gallery + +## Scope + +The run-detail Artifacts page now lists a visit's turn documents beside its +stage files: `input.md`, `memory.md`, `output.md` and `session.html`. They are +entries of the visit group, not a separate run-level list. + +## Behaviour + +- A recorded document is a normal gallery row with the server's exact recorded + name, MIME and byte size. Selecting it uses the same `ArtifactSelectionFacts` + and URL-state rules as a stage file. +- Markdown documents (`input.md`, `memory.md`, `output.md`) open in the existing + in-app artifact viewer and join its recorded paging order. +- `session.html` is external-only by name. It always takes the selection dialog + with the existing Open/Copy actions, even when the server sniffed it as + `text/plain`; it is never fetched or drawn in the renderer. +- A document the visit did not record keeps its row with the exact audit words: + `No input recorded.`, `No memory recorded for this visit.`, + `No output recorded.`, and the web session wording (for example + `This visit has no harness session.` or + `Session ses-42 is recorded. Its export is not yet available.`). The missing + row is not tappable. +- Nothing is synthesized: a document exists only when its exact recorded name is + in the step's artifact list. Step fields named `input`/`memory`/`output` are + ignored. An absent artifact capture yields no document slots, and a visit that + recorded none of the four documents shows no document section rather than four + fabricated absences. +- The run header count now counts stage files plus recorded documents; absent + slots are never counted. Stage-only grouping (`artifactGroups`) is unchanged. + +## Files + +| File | Lines | Responsibility | +| --- | ---: | --- | +| `lib/features/artifacts/domain/artifact_document.dart` | 153 | Document slots, exact absence wording, exact-name lookup, external-only/viewer eligibility | +| `lib/features/artifacts/domain/artifact_groups.dart` | 160 | `galleryGroups` merging stage groups with per-visit documents; recorded count | +| `lib/features/artifacts/domain/gallery_navigation.dart` | 91 | Viewer paging includes recorded markdown documents, excludes session exports | +| `lib/features/artifacts/domain/artifact_record.dart` | 85 | Turn-file vocabulary and recorded record model | +| `lib/features/artifacts/domain/artifact_summary.dart` | 81 | Header counts recorded gallery entries | +| `lib/features/artifacts/ui/artifact_row_labels.dart` | 32 | Shared group/name/facts labels and identity | +| `lib/features/artifacts/ui/artifact_record_row.dart` | 82 | Native Material/Cupertino recorded row | +| `lib/features/artifacts/ui/artifact_document_section.dart` | 124 | Per-visit document rows and exact absence rows | +| `lib/features/artifacts/ui/artifact_visit_list.dart` | 128 | Group list composing stage rows and document sections | +| `lib/features/artifacts/ui/artifact_gallery_page.dart` | 277 | Uses gallery groups; session export bypasses the viewer | +| `lib/features/artifacts/ui/artifact_selection_facts.dart` | 71 | Same facts panel with the recorded-entry count | +| `lib/features/artifacts/ui/artifact_viewer_body.dart` | 248 | Material pager wraps instead of clipping | +| `test/features/artifacts/domain/artifact_document_test.dart` | 281 | Exact records, all absence words, no synthesis, grouping, paging | +| `test/features/artifacts/ui/artifact_gallery_documents_test.dart` | 183 | Both hosts: entries, grouping, missing wording, row semantics, viewer, external-only session | +| `tool/artifact_gallery_probe.dart` | 385 | New isolated `documents` fixture state | +| `tool/artifact_gallery_probe.mjs` | 936 | Real-browser A4 checks, contrast, pager geometry and captures | + +## Fixes after the review stages + +- **Material absence rows use normal text contrast.** The absent-document row is + no longer a disabled `ListTile`. It keeps no `onTap` (still non-actionable) but + paints the explanation with the theme's `onSurfaceVariant`, like every other + secondary label. Measured from 3x rasterised pixels: **8.88:1** in light mode + and **10.91:1** in dark mode (previous: 2.67:1 and 3.64:1). +- **Material viewer pager no longer clips at 320 px/2x.** The fixed `Row` became a + `Wrap`, so at 320 px with 2× text `Previous artifact` (x=8, w=236.4) and + `Next artifact` (x=8, w=186.1) each take their own line and stay inside the + viewport (previous: Next ended at 430.6 px). This also fixes the pre-existing + stage-artifact pager case. +- Quality follow-ups from the code review: the changed files are `dart format` + clean; `turnDocumentNames` is aliased to `systemArtifactNames`; `visitDocuments` + parses the capture once; the external-only session is detected by its domain + name (`sessionExportDocumentName`) instead of object identity; the stale + `artifact_summary`/`artifact_record` comments now match the gallery surface. +- Tests now pin every `sessionDocumentAbsence` branch (skipped, canceled, + interrupted, running, failed with/without diagnostic, runtime error, pending + recovery, complete-inventory, evidence diagnostic), the absent row's + non-actionable but enabled Material tile and secondary colour, and the 320 px/2× + Material pager geometry. + +## Checks + +- `flutter analyze`: clean (`No issues found!`). +- `dart format --output=none --set-exit-if-changed` on every changed/new Dart + file: clean. +- `flutter test test/features/artifacts`: 148 pass. +- `flutter test` (integrated): 1049 pass. +- `flutter build web`: succeeds. +- Probe build: `flutter build web --target tool/artifact_gallery_probe.dart --output build/probe-a4-fix`. +- Real headless Chrome probe: 36 checks, 41 captures, 0 failures. A4 captures: + `a4-material-documents`, `a4-material-session`, `a4-material-document-viewer`, + the same three for Cupertino, `a4-material-light-absence-row`, + `a4-material-dark-absence-row` and `a4-material-320-2x-document-viewer`. + Inspected the light/dark absence pages (legible, no disabled dimming), the + 320/2× document viewer (both pager controls whole, wrapped) and the Cupertino + document list (unchanged native grouped rows). +- Evidence: `public/a4-code-fix/evidence.json` plus the captures above. + +The probe serves only its own loopback fixture. No server, operator run or +authenticated production data was touched. + +## Known limits + +- Not committed: this stage is read-only for history, so the candidate is left + in the worktree for the landing stage. +- Repaired session exports (`session-repair-*.html`) are still not resolved; the + web client prefers the verified repair, and `PARITY.md` still lists this as + deferred. A repaired visit can show `session.html` or the + "not available in the artifact inventory" wording instead of the repair. +- The dialog still offers Download/Share for an external-only session export; + external-only here means it cannot be rendered in-app, not that its bytes are + unavailable. +- Mobile (Android/iOS) rendering and OS behavior remain unverified; only web was + tested. diff --git a/app/test/features/artifacts/domain/artifact_document_test.dart b/app/test/features/artifacts/domain/artifact_document_test.dart new file mode 100644 index 00000000..f0e1761a --- /dev/null +++ b/app/test/features/artifacts/domain/artifact_document_test.dart @@ -0,0 +1,281 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_document.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_summary.dart'; +import 'package:pipelines_app/features/artifacts/domain/gallery_navigation.dart'; + +import 'artifact_fixtures.dart'; + +Map _doc( + String name, { + String contentType = 'text/markdown', + int sizeBytes = 12, +}) => artifact(name, contentType: contentType, sizeBytes: sizeBytes); + +ArtifactGroup _docGroup(List recorded) { + final recordedStep = step( + stage: 'review', + visit: 1, + artifacts: [for (final name in recorded) _doc(name)], + ); + return ArtifactGroup( + stageKey: 'review', + visit: 1, + artifacts: const [], + documents: visitDocuments(recordedStep), + ); +} + +void main() { + group('visit documents', () { + test('a recorded document carries its exact recorded record', () { + final docs = visitDocuments( + step( + stage: 'review', + visit: 1, + artifacts: [ + _doc('input.md', sizeBytes: 12), + _doc('memory.md', sizeBytes: 34), + _doc('output.md', sizeBytes: 56), + _doc('session.html', contentType: 'text/html', sizeBytes: 78), + ], + ), + ); + expect(docs.map((doc) => doc.name), turnDocumentNames); + expect(docs.every((doc) => doc.record != null), isTrue); + expect(docs.every((doc) => doc.absence.isEmpty), isTrue); + expect(docs[0].record!.contentType, 'text/markdown'); + expect(docs[0].record!.sizeBytes, 12); + expect(docs[3].record!.contentType, 'text/html'); + expect(docs[3].record!.sizeBytes, 78); + }); + + test('only input and output absent messages use the audit words', () { + final docs = visitDocuments( + step( + stage: 'review', + visit: 1, + artifacts: [_doc('input.md'), _doc('output.md')], + ), + ); + expect(docs[1].record, isNull); + expect(docs[1].absence, 'No memory recorded for this visit.'); + expect(docs[3].record, isNull); + expect(docs[3].absence, 'This visit has no harness session.'); + }); + + test('a missing capture yields no slots, never four missing documents', () { + final docs = visitDocuments( + step(stage: 'review', visit: 1, includeArtifacts: false), + ); + expect(docs, isEmpty); + }); + + test('step fields never stand in for a missing document', () { + final docs = visitDocuments({ + 'stage': 'review', + 'sequence': 1, + 'status': 'completed', + 'input': 'looks like input', + 'memory': 'looks like memory', + 'output': 'looks like output', + 'artifacts': >[], + }); + expect(docs, isEmpty); + }); + + test('a recorded session id is not reported as no session', () { + final docs = visitDocuments({ + 'stage': 'review', + 'sequence': 1, + 'status': 'completed', + 'session_id': 'ses-42', + 'artifacts': >[_doc('input.md')], + }); + expect( + docs[3].absence, + 'Session ses-42 is recorded. Its export is not yet available.', + ); + }); + + test('the session export is external-only even when sniffed as text', () { + final docs = visitDocuments( + step( + stage: 'review', + visit: 1, + artifacts: [ + _doc('input.md'), + _doc('session.html', contentType: 'text/plain', sizeBytes: 99), + ], + ), + ); + expect(docs[3].externalOnly, isTrue); + expect(docs[3].opensInViewer, isFalse); + expect(docs[0].opensInViewer, isTrue); + }); + + test('the turn document names share the stage filter order', () { + expect(turnDocumentNames, systemArtifactNames); + }); + + // Every remaining branch of the contextual session wording is exact product + // copy, so each is pinned rather than reached only through the probe. + String sessionAbsence(Map fields) => + visitDocuments({ + 'stage': 'review', + 'sequence': 1, + 'artifacts': >[_doc('input.md')], + ...fields, + })[3].absence; + + test('a skipped or stopped stage never claims a harness session', () { + expect( + sessionAbsence({'status': 'skipped'}), + 'This visit was skipped; no harness session was started.', + ); + expect( + sessionAbsence({'outcome': 'skipped'}), + 'This visit was skipped; no harness session was started.', + ); + expect( + sessionAbsence({'status': 'canceled'}), + 'The stage stopped before a harness session was recorded.', + ); + expect( + sessionAbsence({'status': 'interrupted'}), + 'The stage stopped before a harness session was recorded.', + ); + }); + + test('a model stage states whether its session is running or failed', () { + expect( + sessionAbsence({'status': 'running', 'model': 'luna'}), + 'The stage session is being created.', + ); + expect( + sessionAbsence({'status': 'failed', 'model': 'luna'}), + 'The stage did not create a harness session.', + ); + expect( + sessionAbsence({ + 'status': 'failed', + 'model': 'luna', + 'diagnostic': 'provider rejected the request.', + }), + 'The stage did not create a harness session.' + ' provider rejected the request.', + ); + expect( + sessionAbsence({'provider': 'local'}), + 'Runtime error: this model stage has no recorded session identity.', + ); + }); + + test('a recorded session reports its export recovery state', () { + expect( + sessionAbsence({ + 'session_id': 'ses-9', + 'session_export_recovery': {'status': 'pending'}, + }), + 'Session ses-9 is recorded. Its export is pending recovery.', + ); + expect( + sessionAbsence({ + 'session_id': 'ses-9', + 'session_export_recovery': {'status': 'running'}, + }), + 'Session ses-9 is recorded. Its export is pending recovery.', + ); + expect( + sessionAbsence({ + 'session_export': { + 'session_id': 'ses-8', + 'status': 'complete', + }, + }), + 'Session ses-8 is recorded.' + ' Its export is not available in the artifact inventory.', + ); + expect( + sessionAbsence({ + 'session_export': { + 'session_id': 'ses-7', + 'status': 'failed', + 'diagnostic': 'Disk full.', + }, + }), + 'Session ses-7 is recorded. Its export is failed. Disk full.', + ); + }); + }); + + group('gallery groups', () { + test('groups documents per visit without changing stage grouping', () { + final steps = >[ + step( + stage: 'review', + sequence: 1, + visit: 1, + artifacts: [_doc('input.md'), _doc('output.md')], + ), + step( + stage: 'review', + sequence: 2, + visit: 2, + artifacts: [_doc('input.md'), _doc('memory.md')], + ), + ]; + expect(artifactGroups(steps), isEmpty); + final groups = galleryGroups(steps); + expect(groups.map((group) => group.visit), [1, 2]); + expect(groups[0].artifacts, isEmpty); + expect(groups[0].documents[0].record!.sizeBytes, 12); + expect(groups[1].documents[2].record, isNull); + expect(groups.map((group) => group.recordedCount), [2, 2]); + }); + + test('a visit with neither artifacts nor recorded documents is absent', () { + final steps = >[ + step(stage: 'a', sequence: 1, includeArtifacts: false), + step(stage: 'a', sequence: 2, artifacts: const []), + ]; + expect(galleryGroups(steps), isEmpty); + }); + + test('the header counts recorded documents and stage artifacts', () { + final steps = >[ + step( + stage: 'review', + sequence: 1, + visit: 1, + artifacts: [ + artifact('report.csv', contentType: 'text/csv'), + _doc('input.md'), + _doc('output.md'), + ], + ), + ]; + expect( + artifactsHeader(steps, executing: false), + 'Artifacts · 3 recorded', + ); + }); + + test( + 'markdown documents page in the viewer but session.html never does', + () { + final group = _docGroup([ + 'input.md', + 'output.md', + 'session.html', + ]); + final pages = pagedArtifacts([group]); + expect(pages.map((page) => page.artifact.name), [ + 'input.md', + 'output.md', + ]); + }, + ); + }); +} diff --git a/app/test/features/artifacts/ui/artifact_gallery_documents_test.dart b/app/test/features/artifacts/ui/artifact_gallery_documents_test.dart new file mode 100644 index 00000000..f8335281 --- /dev/null +++ b/app/test/features/artifacts/ui/artifact_gallery_documents_test.dart @@ -0,0 +1,183 @@ +import 'dart:typed_data'; + +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/artifacts/ui/artifact_external_open.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_gallery_page.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_fetch.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_page.dart'; + +import '../domain/artifact_fixtures.dart'; + +enum _Platform { material, cupertino } + +const String _endpoint = 'ws://127.0.0.1:8081/connect'; + +JsonMap _recorded( + String name, { + required String contentType, + required int sizeBytes, +}) => artifact(name, contentType: contentType, sizeBytes: sizeBytes); + +/// Visit 1 records every turn document except memory. Visit 2 records input and +/// memory only, so both visits carry recorded and missing document slots. +List _steps() => [ + step( + stage: 'review', + sequence: 1, + visit: 1, + artifacts: [ + _recorded('report.csv', contentType: 'text/csv', sizeBytes: 23), + _recorded('input.md', contentType: 'text/markdown', sizeBytes: 120), + _recorded('output.md', contentType: 'text/markdown', sizeBytes: 240), + _recorded('session.html', contentType: 'text/plain', sizeBytes: 512), + ], + ), + step( + stage: 'review', + sequence: 2, + visit: 2, + artifacts: [ + _recorded('notes.md', contentType: 'text/markdown', sizeBytes: 64), + _recorded('input.md', contentType: 'text/markdown', sizeBytes: 130), + _recorded('memory.md', contentType: 'text/markdown', sizeBytes: 256), + ], + ), +]; + +Future _pump( + WidgetTester tester, + _Platform platform, { + List? steps, + ArtifactFetch? fetch, + ArtifactExternalOpen? openExternal, +}) async { + tester.view.physicalSize = const Size(900, 2600); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final page = ArtifactGalleryPage( + steps: steps ?? _steps(), + configuredEndpoint: _endpoint, + openExternal: openExternal ?? (_) async => true, + fetch: + fetch ?? + (_) async => ArtifactFetchResult( + status: 200, + bytes: Uint8List.fromList('# Recorded input'.codeUnits), + ), + markdownBuilder: (context, value) => Text(value), + ); + await tester.pumpWidget( + platform == _Platform.material + ? MaterialApp(home: page) + : CupertinoApp(home: page), + ); + await tester.pumpAndSettle(); +} + +Finder _dialog(_Platform platform, String text) => find.descendant( + of: find.byType( + platform == _Platform.material ? AlertDialog : CupertinoAlertDialog, + ), + matching: find.text(text), +); + +void main() { + for (final platform in _Platform.values) { + testWidgets('${platform.name}: every recorded document is an entry', ( + tester, + ) async { + await _pump(tester, platform); + expect(find.text('Turn documents'), findsNWidgets(2)); + expect(find.text('input.md'), findsNWidgets(2)); + expect(find.text('output.md'), findsNWidgets(2)); + expect(find.text('session.html'), findsNWidgets(2)); + expect(find.text('memory.md'), findsNWidgets(2)); + expect(find.text('text/markdown · 120\u00a0B'), findsOneWidget); + expect(find.text('text/plain · 512\u00a0B'), findsOneWidget); + }); + + testWidgets('${platform.name}: missing documents show exact wording', ( + tester, + ) async { + await _pump(tester, platform); + expect(find.text('No memory recorded for this visit.'), findsOneWidget); + expect(find.text('No output recorded.'), findsOneWidget); + expect(find.text('This visit has no harness session.'), findsOneWidget); + expect(find.text('No input recorded.'), findsNothing); + }); + + testWidgets('${platform.name}: markdown opens the existing renderer', ( + tester, + ) async { + await _pump(tester, platform); + await tester.tap(find.text('input.md').first); + await tester.pumpAndSettle(); + expect(find.byType(ArtifactViewerPage), findsOneWidget); + expect(find.text('# Recorded input'), findsOneWidget); + expect(find.text('review · visit 1'), findsOneWidget); + expect(find.text('text/markdown · 120\u00a0B'), findsOneWidget); + }); + + testWidgets( + '${platform.name}: absent rows are informational, not controls', + (tester) async { + await _pump(tester, platform); + final absence = find.text('No output recorded.'); + expect(absence, findsOneWidget); + if (platform == _Platform.material) { + // Not disabled: the absence line is content, not a skipped action, and + // is painted with the normal secondary label colour. + final tile = tester.widget( + find.ancestor(of: absence, matching: find.byType(ListTile)), + ); + expect(tile.enabled, isTrue); + expect(tile.onTap, isNull); + expect( + tester.widget(absence).style?.color, + Theme.of(tester.element(absence)).colorScheme.onSurfaceVariant, + ); + } else { + expect( + find.ancestor(of: absence, matching: find.byType(CupertinoButton)), + findsNothing, + ); + } + await tester.tap(absence); + await tester.pumpAndSettle(); + expect(find.byType(ArtifactViewerPage), findsNothing); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byType(CupertinoAlertDialog), findsNothing); + }, + ); + + testWidgets('${platform.name}: session.html stays external-only', ( + tester, + ) async { + final opened = []; + await _pump( + tester, + platform, + openExternal: (uri) async { + opened.add(uri); + return true; + }, + fetch: (_) async => throw StateError('x'), + ); + await tester.tap(find.text('session.html').first); + await tester.pumpAndSettle(); + expect(find.byType(ArtifactViewerPage), findsNothing); + expect(_dialog(platform, 'session.html'), findsOneWidget); + expect(_dialog(platform, 'text/plain · 512\u00a0B'), findsOneWidget); + await tester.tap(_dialog(platform, 'Open')); + await tester.pumpAndSettle(); + expect(find.byType(ArtifactViewerPage), findsNothing); + expect(opened, [ + Uri.parse('http://127.0.0.1:8081/artifacts/1/1/session.html'), + ]); + }); + } +} diff --git a/app/test/features/artifacts/ui/artifact_viewer_page_test.dart b/app/test/features/artifacts/ui/artifact_viewer_page_test.dart index abd7915a..3a4b319a 100644 --- a/app/test/features/artifacts/ui/artifact_viewer_page_test.dart +++ b/app/test/features/artifacts/ui/artifact_viewer_page_test.dart @@ -515,4 +515,42 @@ void main() { // The viewer and its markdown add no Material control to a Cupertino host. expect(find.byType(Material), findsNothing); }); + + testWidgets('Material paging stays inside 320px at 2x text', (tester) async { + tester.view.physicalSize = const Size(640, 1200); + tester.view.devicePixelRatio = 2; + tester.platformDispatcher.textScaleFactorTestValue = 2; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + + final first = recordedArtifact( + 'a.png', + url: '/artifacts/1/1/a.png', + contentType: 'image/png', + ); + final second = recordedArtifact( + 'b.png', + url: '/artifacts/1/2/b.png', + contentType: 'image/png', + ); + final groups = [ + _group([first], visit: 1), + _group([second], visit: 2), + ]; + await _pumpViewer( + tester, + groups: groups, + selected: artifactVisitIdentity(groups[0], first), + ); + + expect(tester.takeException(), isNull); + // Both labelled controls are whole: a clipped Row overflowed the viewport. + for (final label in ['Previous artifact', 'Next artifact']) { + final rect = tester.getRect(find.text(label)); + expect(rect.left, greaterThanOrEqualTo(0), reason: label); + expect(rect.right, lessThanOrEqualTo(320), reason: label); + expect(rect.width, greaterThan(0), reason: label); + } + }); } diff --git a/app/tool/artifact_gallery_probe.dart b/app/tool/artifact_gallery_probe.dart index c16a24b9..df16c30a 100644 --- a/app/tool/artifact_gallery_probe.dart +++ b/app/tool/artifact_gallery_probe.dart @@ -121,6 +121,64 @@ List _steps(String origin, String state) { }, ]; } + if (state == 'documents') { + return [ + { + 'stage': 'reviewer', + 'sequence': 1, + 'status': 'completed', + 'control': {'visit': 1}, + 'artifacts': [ + _file( + 'report.csv', + url: '$origin/fixture/report.csv', + contentType: 'text/csv', + sizeBytes: 23, + ), + _file( + 'input.md', + url: '$origin/fixture/input.md', + contentType: 'text/markdown', + sizeBytes: 120, + ), + _file( + 'output.md', + url: '$origin/fixture/output.md', + contentType: 'text/markdown', + sizeBytes: 240, + ), + // Deliberately sniffed as text/plain: the session export must still + // stay external-only. + _file( + 'session.html', + url: '$origin/fixture/session.html', + contentType: 'text/plain', + sizeBytes: 512, + ), + ], + }, + { + 'stage': 'reviewer', + 'sequence': 2, + 'status': 'completed', + 'control': {'visit': 2}, + 'artifacts': [ + _file( + 'input.md', + url: '$origin/fixture/input-2.md', + contentType: 'text/markdown', + sizeBytes: 130, + ), + _file( + 'memory.md', + url: '$origin/fixture/memory.md', + contentType: 'text/markdown', + sizeBytes: 256, + ), + ], + }, + ]; + } if (state == 'files') { return [ { diff --git a/app/tool/artifact_gallery_probe.mjs b/app/tool/artifact_gallery_probe.mjs index 6903e981..c77a44ac 100644 --- a/app/tool/artifact_gallery_probe.mjs +++ b/app/tool/artifact_gallery_probe.mjs @@ -156,7 +156,7 @@ const waitFor = async (fn, what) => { throw new Error(`Timed out waiting for ${what}: ${stderr.slice(-1500)}`); }; -const evidence = { origin, captures: [], checks: [] }; +const evidence = { origin, captures: [], checks: [], contrast: [], pager: null }; let ws; try { const endpoint = await waitFor( @@ -366,6 +366,58 @@ try { return { max, width: img.width, height: img.height }; })()`); }; + // WCAG contrast of the explanatory (subtitle) line of a two-line row against + // its own background. Only the row's lower half is sampled, so the darker + // title glyphs cannot mask a dim absence line. The text luminance is the + // text-coloured extreme (p2 in light mode, p98 in dark); the background is + // the opposite extreme. + const subtitleContrast = async (prefix, dark) => { + const rect = await rectOfPrefix(prefix); + if (!rect) throw new Error(`No row starting ${JSON.stringify(prefix)}`); + const clip = { + x: rect.x, + y: rect.y + rect.height * 0.45, + width: rect.width, + height: rect.height * 0.55, + scale: 1, + }; + const shot = await send('Page.captureScreenshot', { format: 'png', clip }, session); + return evaluate(`(async () => { + const img = new Image(); + img.src = 'data:image/png;base64,${shot.result.data}'; + await img.decode(); + const canvas = document.createElement('canvas'); + canvas.width = img.width; + canvas.height = img.height; + const ctx = canvas.getContext('2d'); + ctx.drawImage(img, 0, 0); + const data = ctx.getImageData(0, 0, img.width, img.height).data; + const linear = (value) => { + const c = value / 255; + return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); + }; + const lums = []; + for (let i = 0; i < data.length; i += 4) { + lums.push(0.2126 * linear(data[i]) + 0.7152 * linear(data[i + 1]) + 0.0722 * linear(data[i + 2])); + } + lums.sort((a, b) => a - b); + const at = (fraction) => lums[Math.min(lums.length - 1, Math.floor(lums.length * fraction))]; + const text = ${dark} ? at(0.98) : at(0.02); + const background = ${dark} ? at(0.02) : at(0.98); + const high = Math.max(text, background); + const low = Math.min(text, background); + return { + ratio: (high + 0.05) / (low + 0.05), + textLuminance: text, + backgroundLuminance: background, + p01: at(0.01), + p99: at(0.99), + pixels: lums.length, + width: img.width, + height: img.height, + }; + })()`); + }; const openGallery = async (query) => { await navigate(`${origin}/?${query}`); if (!(await hasLabel('Artifacts'))) { @@ -660,6 +712,116 @@ try { await openScaled('cupertino', 'a1w-cupertino-2x-320'); evidence.checks.push({ check: 'Cupertino 2x/320 keeps the recorded rows, facts and actions', value: true }); + // Turn documents: recorded input/memory/output/session.html are their own + // rows per visit, absent ones carry the exact wording, markdown opens in the + // renderer and the session export stays external-only even when sniffed as + // text/plain. + for (const platform of ['material', 'cupertino']) { + const prefix = `a4-${platform}`; + await navigate(galleryView('&state=documents', platform), 'Artifacts'); + const documentsBody = await bodyText(); + for (const fact of [ + 'Turn documents', + 'input.md', + 'output.md', + 'session.html', + 'memory.md', + 'text/markdown · 120\u00a0B', + 'text/plain · 512\u00a0B', + 'No memory recorded for this visit.', + 'No output recorded.', + 'This visit has no harness session.', + ]) { + if (!documentsBody.includes(fact)) { + throw new Error(`${platform} documents view is missing ${fact}: ${JSON.stringify(documentsBody)}`); + } + } + if (documentsBody.includes('No input recorded.')) { + throw new Error(`${platform} fabricated a missing input document: ${JSON.stringify(documentsBody)}`); + } + evidence.checks.push({ check: `${platform} presents recorded turn documents and exact absence wording`, value: true }); + await capture(`${prefix}-documents`); + + await clickExact('session.html'); + const sessionBody = await visibleText(); + if (!sessionBody.includes('text/plain · 512\u00a0B') || !(await hasLabel('Open'))) { + throw new Error(`${platform} session export lost its facts/Open: ${JSON.stringify(sessionBody)}`); + } + if (sessionBody.includes('Previous artifact') || sessionBody.includes('1 of ')) { + throw new Error(`${platform} opened session.html in the in-app renderer`); + } + evidence.checks.push({ check: `${platform} keeps session.html external-only`, value: true }); + await capture(`${prefix}-session`); + await clickExact('Close'); + await delay(300); + + await navigate(galleryView('&state=documents', platform), 'Artifacts'); + await clickExact('input.md'); + await delay(700); + const inputBody = await visibleText(); + if (!inputBody.includes('recorded artifact /fixture/input.md') || + !inputBody.includes('1 of 4 · text/markdown')) { + throw new Error(`${platform} markdown document did not render in the viewer: ${JSON.stringify(inputBody)}`); + } + evidence.checks.push({ check: `${platform} opens a recorded markdown document in the renderer`, value: true }); + await capture(`${prefix}-document-viewer`); + await clickExact('Back'); + await delay(400); + } + + // Absence rows are informational text, not disabled controls: the Material + // subtitle keeps readable contrast in both themes. + for (const theme of ['light', 'dark']) { + // Rasterise at 3x so a 14px subtitle stroke reaches its nominal colour; + // at 1x, antialiasing dilutes every text colour. + await send('Emulation.setDeviceMetricsOverride', { + width: 390, height: 844, deviceScaleFactor: 3, mobile: true, + }, session); + await navigate(galleryView(`&state=documents&theme=${theme}`), 'Artifacts'); + const sample = await subtitleContrast('memory.md', theme === 'dark'); + evidence.contrast.push({ + sample: `material ${theme} absence subtitle (memory.md)`, + ...sample, + }); + if (sample.ratio < 4.5) { + throw new Error(`Material ${theme} absence subtitle contrast is ${sample.ratio.toFixed(2)}:1`); + } + evidence.checks.push({ + check: `material ${theme} absence subtitle meets 4.5:1`, + value: true, + ratio: Number(sample.ratio.toFixed(2)), + }); + await capture(`a4-material-${theme}-absence-row`); + } + + // The Material pager must keep both labelled controls whole at 320 px with 2x + // text, not clip the second button at the viewport edge. + await send('Emulation.setDeviceMetricsOverride', { + width: 320, height: 720, deviceScaleFactor: 1, mobile: true, + }, session); + await navigate(galleryView('&state=documents&scale=2'), 'Artifacts'); + await clickExact('input.md'); + await delay(700); + if (!(await visibleText()).includes('1 of 4 · text/markdown')) { + throw new Error(`2x document viewer did not open: ${JSON.stringify(await visibleText())}`); + } + const pagerControls = {}; + for (const label of ['Previous artifact', 'Next artifact']) { + const rect = await rectOfPrefix(label); + if (!rect) throw new Error(`2x pager lost ${label}: ${JSON.stringify(await labels())}`); + if (rect.x < -0.5 || rect.x + rect.width > 320.5) { + throw new Error(`${label} leaves the 320px viewport: ${JSON.stringify(rect)}`); + } + pagerControls[label] = rect; + } + evidence.pager = { viewport: 320, textScale: 2, controls: pagerControls }; + evidence.checks.push({ + check: 'Material paging controls stay inside a 320px viewport at 2x text', + value: true, + controls: pagerControls, + }); + await capture('a4-material-320-2x-document-viewer', 320, 720, 1); + // File actions: a real same-origin artifact is fetched, then handed to the // host as a named file. Blob/anchor and navigator.share are intercepted above // so the evidence is the exact bytes, MIME type and download name, not a From 379872b94ad38bdb83748e591344e8b7d595f689 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 03:30:09 +0100 Subject: [PATCH 3/5] fix(app): keep the session export out of the per-visit stage drill-down --- .../artifacts/ui/artifact_gallery_page.dart | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/app/lib/features/artifacts/ui/artifact_gallery_page.dart b/app/lib/features/artifacts/ui/artifact_gallery_page.dart index b2a2087e..33e416e8 100644 --- a/app/lib/features/artifacts/ui/artifact_gallery_page.dart +++ b/app/lib/features/artifacts/ui/artifact_gallery_page.dart @@ -84,7 +84,20 @@ class _ArtifactGalleryPageState extends State { // that visit, not only its recorded files. for (final enriched in galleryGroups(widget.steps)) { if (enriched.stageKey == group.stageKey && enriched.visit == group.visit) { - return [enriched]; + // The visit pane's own Session section opens session.html, so the + // per-visit Artifacts drill-down keeps only stage output and the other + // turn documents; the run-wide gallery still shows every document. + final documents = enriched.documents + .where((doc) => doc.record?.name != sessionExportDocumentName) + .toList(growable: false); + return [ + ArtifactGroup( + stageKey: enriched.stageKey, + visit: enriched.visit, + artifacts: enriched.artifacts, + documents: documents, + ), + ]; } } return [group]; From 4aee83c262bf175e4e64943ab38517444364bb4c Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 03:18:37 +0100 Subject: [PATCH 4/5] feat(app): pick chat attachments from the host file input --- .../chat/domain/chat_attachment_picker.dart | 87 +++++++++++++++++++ .../domain/chat_attachment_picker_stub.dart | 13 +++ .../domain/chat_attachment_picker_web.dart | 71 +++++++++++++++ .../domain/chat_attachment_picker_test.dart | 80 +++++++++++++++++ 4 files changed, 251 insertions(+) create mode 100644 app/lib/features/chat/domain/chat_attachment_picker.dart create mode 100644 app/lib/features/chat/domain/chat_attachment_picker_stub.dart create mode 100644 app/lib/features/chat/domain/chat_attachment_picker_web.dart create mode 100644 app/test/features/chat/domain/chat_attachment_picker_test.dart diff --git a/app/lib/features/chat/domain/chat_attachment_picker.dart b/app/lib/features/chat/domain/chat_attachment_picker.dart new file mode 100644 index 00000000..2a41516b --- /dev/null +++ b/app/lib/features/chat/domain/chat_attachment_picker.dart @@ -0,0 +1,87 @@ +import 'dart:typed_data'; + +import 'chat_attachment_draft.dart'; +import 'chat_attachment_picker_stub.dart' + if (dart.library.js_interop) 'chat_attachment_picker_web.dart' + as impl; + +/// One file the operator chose in the host's file picker, with the bytes the +/// host handed back. +/// +/// The seam records only what the picker supplied: the file's own name, its +/// MIME type and its bytes. It applies no name fallback and no size or count +/// policy; [ChatAttachmentDraft] owns those decisions. +class ChatPickedFile { + const ChatPickedFile({ + required this.name, + required this.mime, + required this.bytes, + }); + + /// The file name exactly as the host recorded it, blank when the host + /// supplied none. [ChatAttachmentDraft.add] refuses a blank name rather than + /// replacing it. + final String name; + + /// The MIME type the host recorded, empty when the host supplied none. + final String mime; + + /// The file's complete contents as read when it was chosen. + final Uint8List bytes; + + /// The recorded size, taken from the bytes that were actually read. + int get sizeBytes => bytes.length; + + /// The draft row for this file. The draft still owns the blank-name and + /// total-size decisions. + ChatAttachment get attachment => + ChatAttachment(name: name, mime: mime, sizeBytes: sizeBytes); +} + +/// Opens the host's file selection and returns the files the operator chose. +/// +/// A null result means the operator dismissed the picker without choosing +/// anything, which is different from an empty list. Only one selection is +/// returned per call. +typedef ChatFileSelection = Future?> Function(); + +/// The file picker seam for one host. +/// +/// [pick] is the operator's explicit pick action: on web it opens the host's +/// native file input, and the chosen files are read before the future +/// completes. A host without a picker constructs +/// [ChatAttachmentPicker.unsupported] so the missing capability is reported +/// plainly instead of silently returning nothing. Tests inject a fake +/// [select] to exercise the seam without a browser. +class ChatAttachmentPicker { + const ChatAttachmentPicker({required ChatFileSelection this.select}) + : unsupportedMessage = null; + + const ChatAttachmentPicker.unsupported(String message) + : select = null, + unsupportedMessage = message; + + /// The host selection, or null when this host cannot pick files. + final ChatFileSelection? select; + + /// Why this host cannot pick files, when [select] is null. + final String? unsupportedMessage; + + /// Whether this host can open a file selection at all. + bool get isSupported => select != null; + + /// Opens the host's file selection and resolves with the chosen files, or + /// null when the operator cancelled. + /// + /// Throws [UnsupportedError] with [unsupportedMessage] on a host that cannot + /// pick files. + Future?> pick() async { + final select = this.select; + if (select == null) throw UnsupportedError(unsupportedMessage!); + return select(); + } +} + +/// The picker for the running host. +ChatAttachmentPicker get hostChatAttachmentPicker => + impl.hostChatAttachmentPicker; diff --git a/app/lib/features/chat/domain/chat_attachment_picker_stub.dart b/app/lib/features/chat/domain/chat_attachment_picker_stub.dart new file mode 100644 index 00000000..c99a9b31 --- /dev/null +++ b/app/lib/features/chat/domain/chat_attachment_picker_stub.dart @@ -0,0 +1,13 @@ +import 'chat_attachment_picker.dart'; + +/// Native fallback for the chat attachment picker. +/// +/// No native file-picker plugin is a dependency of this slice, so a non-web +/// host reports the missing capability instead of pretending the operator +/// cancelled. The attach control can disable itself from [isSupported] and +/// show this exact explanation. +const String chatAttachmentUnsupportedMessage = + 'Attaching files is not supported on this platform yet.'; + +ChatAttachmentPicker get hostChatAttachmentPicker => + const ChatAttachmentPicker.unsupported(chatAttachmentUnsupportedMessage); diff --git a/app/lib/features/chat/domain/chat_attachment_picker_web.dart b/app/lib/features/chat/domain/chat_attachment_picker_web.dart new file mode 100644 index 00000000..6b9ae40c --- /dev/null +++ b/app/lib/features/chat/domain/chat_attachment_picker_web.dart @@ -0,0 +1,71 @@ +import 'dart:async'; +import 'dart:js_interop'; + +import 'package:web/web.dart' as web; + +import 'chat_attachment_picker.dart'; + +/// The web file picker: one explicit pick action creates the host's native +/// file input, opens it and reads the files the operator chose. +/// +/// The input is `multiple` and has no `accept` filter, matching the web +/// composer's attach control. Only a selection or a cancel completes the +/// future; a document without a body has nothing to open and yields null. +ChatAttachmentPicker get hostChatAttachmentPicker => + const ChatAttachmentPicker(select: _selectFiles); + +Future?> _selectFiles() { + final input = web.HTMLInputElement() + ..type = 'file' + ..multiple = true; + input.style.display = 'none'; + + final completer = Completer?>(); + + void finish(List? files) { + if (completer.isCompleted) return; + input.remove(); + completer.complete(files); + } + + Future readSelection() async { + final selected = input.files; + if (selected == null || selected.length == 0) { + finish(null); + return; + } + try { + final files = []; + for (var index = 0; index < selected.length; index += 1) { + final file = selected.item(index); + if (file == null) continue; + final buffer = await file.arrayBuffer().toDart; + files.add( + ChatPickedFile( + name: file.name, + mime: file.type, + bytes: buffer.toDart.asUint8List(), + ), + ); + } + finish(files); + } catch (error, stackTrace) { + if (completer.isCompleted) return; + input.remove(); + completer.completeError(error, stackTrace); + } + } + + input.addEventListener('change', ((web.Event _) { + unawaited(readSelection()); + }).toJS); + input.addEventListener('cancel', ((web.Event _) { + finish(null); + }).toJS); + + final body = web.document.body; + if (body == null) return Future.value(null); + body.appendChild(input); + input.click(); + return completer.future; +} diff --git a/app/test/features/chat/domain/chat_attachment_picker_test.dart b/app/test/features/chat/domain/chat_attachment_picker_test.dart new file mode 100644 index 00000000..e090bb5f --- /dev/null +++ b/app/test/features/chat/domain/chat_attachment_picker_test.dart @@ -0,0 +1,80 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/domain/chat_attachment_draft.dart'; +import 'package:pipelines_app/features/chat/domain/chat_attachment_picker.dart'; + +void main() { + test('passes the chosen names, MIME types and bytes through', () async { + final bytes = Uint8List.fromList([0, 1, 2, 250]); + final picked = ChatPickedFile( + name: 'screen.png', + mime: 'image/png', + bytes: bytes, + ); + final picker = ChatAttachmentPicker(select: () async => [picked]); + + expect(picker.isSupported, isTrue); + final files = await picker.pick(); + + expect(files, hasLength(1)); + expect(files!.single.name, 'screen.png'); + expect(files.single.mime, 'image/png'); + expect(files.single.bytes, bytes); + expect(files.single.sizeBytes, 4); + }); + + test('feeds the picked file to the attachment draft', () async { + final picker = ChatAttachmentPicker( + select: () async => [ + ChatPickedFile( + name: 'notes.txt', + mime: 'text/plain', + bytes: Uint8List.fromList([1, 2, 3]), + ), + ], + ); + final draft = ChatAttachmentDraft(); + + final files = await picker.pick(); + + expect(draft.add(files!.single.attachment), isNull); + expect( + draft.attachments.single, + const ChatAttachment( + name: 'notes.txt', + mime: 'text/plain', + sizeBytes: 3, + ), + ); + }); + + test('returns nothing when the operator dismisses the picker', () async { + var opened = 0; + final picker = ChatAttachmentPicker( + select: () async { + opened += 1; + return null; + }, + ); + + expect(await picker.pick(), isNull); + expect(opened, 1); + }); + + test('the host picker reports its unsupported capability honestly', () async { + final picker = hostChatAttachmentPicker; + + expect(picker.isSupported, isFalse); + await expectLater( + picker.pick(), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'Attaching files is not supported on this platform yet.', + ), + ), + ); + }); +} From d1603615039f24f44198c00af20b179233075747 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 03:32:52 +0100 Subject: [PATCH 5/5] docs(app): record chat sessions, turn documents and the attachment picker --- app/PARITY.md | 4 ++-- app/WORK.md | 4 ++++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/app/PARITY.md b/app/PARITY.md index 1b18968a..354862f2 100644 --- a/app/PARITY.md +++ b/app/PARITY.md @@ -36,7 +36,7 @@ or scratch servers only, never real operator sessions/runs/workflows. | Run graph | Preview: Graph tab with legend, recorded-stage selection, canvas pan/zoom and an expanded view | live activity pulse | | Timeline/recorded visit pane | Preview: selection opens the recorded facts with Input/Output/Artifacts/Session/Definition sections and exact absence wording | per-visit session-repair choices (separate row) | | Changes/diffs | Preview via run detail | settled-run aggregate gate, recorded file/diff/close/back verified in the real app; per-visit capture entry and paging remain | -| Artifact groups | Preview: run detail → recorded groups, selection facts, external Open/Copy link | present the visit's turn documents (input.md/memory.md/output.md, session.html) as gallery entries; in-app viewer next | +| Artifact groups | Preview: recorded groups in run detail, per-visit drill-down, turn documents (input/memory/output, session.html) in the run gallery | video/HTML preview remains external-only | | Artifact preview | Preview: image + markdown/text in-app through the chat renderer, paging, honest unsupported/external/HTTP states | video and HTML remain external-only | | Artifact actions | Preview: external Open, Copy link, download and native share carry the recorded name/MIME bytes; progress, cancel, HTTP failure and unsupported-share states | OS share/download on Android/iOS remain unverified until the final build | | Session audit/export repair facts | Missing UI | session.html read-only open, partial/missing/skipped/repair choices without fabricating complete evidence | @@ -45,7 +45,7 @@ or scratch servers only, never real operator sessions/runs/workflows. | Chat message surfaces | Preview: formatted assistant markdown (safe links/headings/lists/tables/fences), user text exact, disclosures plain | exact attachments, unknown-part rendering beyond retained placeholders | | Chat activity/reasoning/tools | Source raw fields only | one activity line, compaction, native reasoning/tools overlays, lifecycle/input/output/error/duration/edit diff | | Chat composer | Preview: field, Send/Stop, persisted draft, queued/refusal lines; one verified send in the real app flow | attachments, paste and slash palette remain | -| Chat attachments | Source request facade | picker/paste, latest1MiB total wire bound, base64 files, removable named chips, exact history reconciliation | +| Chat attachments | Source: bounded draft model (1 MiB) and a native host file picker seam | composer chips, base64 send payload, paste, history reconciliation | | Chat permissions/questions | Source: native approval/risk and question cards in the conversation view | authenticated smoke with a real pending approval/question; live multi-client resolution; no production decision sent | | Chat model/Info/background tasks | Source request facade | current-model selection, numeric Info modal (unknown !=0), bounded running shell pages | | Chat commands/notices/scroll | Missing | slash palette/actions, unknown-command send-as-message, dismissible local notices, saved scroll/follow intent | diff --git a/app/WORK.md b/app/WORK.md index dc81da40..e11f4635 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -68,6 +68,10 @@ All work under app/. Existing applications remain running and unchanged. | Activity line | One line per recorded activity | run104 micro | single behaviour, no probe; chat tests | merged main | overlay landed | | Attachment model | Bounded draft (1 MiB) | run106 micro | single behaviour; chat tests | merged main | picker/send next | | Visit changes | Changes for one recorded visit | run107 micro | single behaviour; runs tests | merged main | paging next | +| Chat sessions | Create/rename/star/close/hide | run98 retained + canceled | oversized run cancelled after 3h; manager verified 155 chat tests, rebased, merged; 1259 suite | merged main | directory groups/search | +| Turn documents | Gallery document slots | run102 retained + canceled | oversized run cancelled; 148 artifact tests, rebased; manager fixed visit drill-down to keep session.html out of stage files | merged main | 1284 suite | +| Attach picker | Host file input seam | run112 micro | single behaviour; 193 chat tests | merged main | chips/send next | +| Schedules list | (no change needed) | run109 no-op | list screen already landed; only route registration remains (manager) | - | route wiring | | Pipeline metadata | Recorded list-row facts | run108 micro | single behaviour; pipelines tests | merged main | miniature next | | Search target | Exact hit identity model | run105 /cbba026c | micro lane (single behaviour, no probe); 41 search tests | merged main | navigation wiring next | | Start pipeline | Native launch dialog | run97 /f6575fff | succeeded after 1h21m (oversized slice); manager ran304 pipelines/application/runs tests + 3-check/10-capture both-host probe | merged main; ancestry verified | production launch unverified |