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, ), );