From 7cdb9e8338d00e747928c9938e61fe33f74a1204 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:24:49 +0100 Subject: [PATCH 1/5] feat(app): add chat foundation --- app/.gitignore | 3 + .../features/chat/data/chat_repository.dart | 146 ++++++++++ .../features/chat/domain/chat_sessions.dart | 64 +++++ .../features/chat/domain/chat_transcript.dart | 235 ++++++++++++++++ app/notes/F4.md | 17 ++ .../features/chat/chat_foundation_test.dart | 259 ++++++++++++++++++ 6 files changed, 724 insertions(+) create mode 100644 app/lib/features/chat/data/chat_repository.dart create mode 100644 app/lib/features/chat/domain/chat_sessions.dart create mode 100644 app/lib/features/chat/domain/chat_transcript.dart create mode 100644 app/notes/F4.md create mode 100644 app/test/features/chat/chat_foundation_test.dart diff --git a/app/.gitignore b/app/.gitignore index 3820a95c..e747ec42 100644 --- a/app/.gitignore +++ b/app/.gitignore @@ -43,3 +43,6 @@ app.*.map.json /android/app/debug /android/app/profile /android/app/release + +# Chat's source adapter lives in a directory commonly ignored as generated data. +!lib/features/chat/data/ diff --git a/app/lib/features/chat/data/chat_repository.dart b/app/lib/features/chat/data/chat_repository.dart new file mode 100644 index 00000000..8053ef5c --- /dev/null +++ b/app/lib/features/chat/data/chat_repository.dart @@ -0,0 +1,146 @@ +import '../../../core/api_gateway.dart'; + +/// Chat wire adapter. ApiGateway supplies request ids and returns full envelopes. +class ChatRepository { + ChatRepository(this.gateway); + final ApiGateway gateway; + + Future> sessions() async => + _maps((await gateway.call('chat_sessions'))['chat_sessions']); + Future> models(String sessionId) async => _maps( + (await gateway.call('chat_models', { + 'chat_query': {'session_id': sessionId}, + }))['chat_models'], + ); + Future selectModel( + String sessionId, + String provider, + String model, + ) => gateway.call('chat_model', { + 'chat_model': { + 'session_id': sessionId, + 'provider': provider, + 'model': model, + }, + }); + Future> shells(String sessionId) async => _maps( + (await gateway.call('chat_shells', { + 'chat_query': {'session_id': sessionId}, + }))['chat_shells'], + ); + Future> directories() async => + ((await gateway.call('chat_directories'))['chat_directories'] as List? ?? + const []) + .whereType() + .toList(); + + Future history( + String sessionId, { + int limit = 50, + String cursor = '', + }) async { + final reply = await gateway.call('chat_messages', { + 'chat_query': {'session_id': sessionId, 'limit': limit, 'cursor': cursor}, + }); + final page = reply['chat_history']; + if (page is Map) { + return { + 'messages': _maps(page['messages']), + 'nextCursor': '${page['next_cursor'] ?? ''}', + 'hasMore': page['has_more'] == true, + }; + } + return { + 'messages': _maps(reply['chat_messages']), + 'nextCursor': '', + 'hasMore': false, + }; + } + + Future subscribe(String sessionId) => + gateway.call('chat_subscribe', { + 'chat_subscribe': {'session_id': sessionId}, + }); + Future create({ + required String title, + required String directory, + required String operationId, + String backend = 'opencode', + String instructions = '', + }) => gateway.call('chat_create', { + 'chat_create': { + 'title': title, + 'directory': directory, + 'operation_id': operationId, + if (backend.isNotEmpty && backend != 'opencode') 'backend': backend, + if (instructions.trim().isNotEmpty) 'instructions': instructions.trim(), + }, + }); + Future rename(String sessionId, String title) => + gateway.call('chat_rename', { + 'chat_rename': {'session_id': sessionId, 'title': title.trim()}, + }); + Future star(String sessionId, bool starred) => + gateway.call('chat_star', { + 'chat_query': {'session_id': sessionId, 'starred': starred}, + }); + Future close(String sessionId) => gateway.call('chat_close', { + 'chat_query': {'session_id': sessionId}, + }); + Future reopen(String sessionId) => gateway.call('chat_reopen', { + 'chat_query': {'session_id': sessionId}, + }); + + Future prompt( + String sessionId, + String text, { + required String operationId, + List files = const [], + }) { + final body = { + 'session_id': sessionId, + 'text': text.trim(), + 'operation_id': operationId, + }; + if (files.isNotEmpty) body['files'] = files; + return gateway.call('chat_prompt', {'chat_prompt': body}); + } + + Future interrupt(String sessionId) => + gateway.call('chat_interrupt', { + 'chat_query': {'session_id': sessionId}, + }); + Future answerForm( + String sessionId, + String formId, + JsonMap answers, { + String action = '', + }) => gateway.call('chat_answer', { + 'chat_answer': { + 'session_id': sessionId, + 'form_id': formId, + 'answers': answers, + if (action.isNotEmpty) 'action': action, + }, + }); + Future replyPermission( + String sessionId, + String requestId, + String decision, { + String client = 'web', + String message = '', + }) => gateway.call('chat_reply', { + 'chat_reply': { + 'session_id': sessionId, + 'request_id': requestId, + 'decision': decision, + 'client': client, + if (message.trim().isNotEmpty) 'message': message.trim(), + }, + }); + + static List _maps(Object? value) => (value as List? ?? const []) + .whereType() + .map((item) => Map.from(item)) + .toList(); +} diff --git a/app/lib/features/chat/domain/chat_sessions.dart b/app/lib/features/chat/domain/chat_sessions.dart new file mode 100644 index 00000000..76bacdf6 --- /dev/null +++ b/app/lib/features/chat/domain/chat_sessions.dart @@ -0,0 +1,64 @@ +import '../../../core/api_gateway.dart'; + +/// Pure session-list operations. Unknown server fields remain on each row. +String chatSessionTitle(JsonMap session) { + final title = '${session['title'] ?? ''}'; + if (title.trim().isNotEmpty) return title; + final id = '${session['id'] ?? ''}'; + return id.isEmpty ? 'Untitled chat' : id.substring(0, id.length.clamp(0, 18)); +} + +List filterChatSessions(List sessions, String query) { + final needle = query.trim().toLowerCase(); + if (needle.isEmpty) return sessions; + return sessions + .where( + (session) => + '${chatSessionTitle(session)}\u0000${session['directory'] ?? ''}' + .toLowerCase() + .contains(needle), + ) + .toList(); +} + +/// Directory groups retain server recency order, both within and between groups. +List<({String directory, List sessions})> groupChatSessions( + List sessions, +) { + final groups = >{}; + for (final session in sessions) { + groups.putIfAbsent('${session['directory'] ?? ''}', () => []).add(session); + } + return groups.entries + .map((entry) => (directory: entry.key, sessions: entry.value)) + .toList(); +} + +String chatSessionActivity({required bool running, required bool unseen}) => + running + ? 'streaming' + : unseen + ? 'new' + : 'idle'; + +/// Native reported values only; missing and invalid values remain unavailable. +JsonMap? chatUsageSnapshot(Object? value) { + if (value is! Map || value is List) return null; + final usage = Map.from(value); + final result = {}; + for (final key in ['total_tokens', 'context_tokens', 'context_window']) { + final n = usage[key]; + result[key] = n is int && n >= 0 ? n : null; + } + for (final key in ['cost_usd', 'output_tokens_per_second']) { + final n = usage[key]; + result[key] = n is num && n.isFinite && n >= 0 ? n : null; + } + result['scope'] = ['session', 'turn'].contains(usage['scope']) + ? usage['scope'] + : ''; + result['rate_basis'] = ['generation', 'turn'].contains(usage['rate_basis']) + ? usage['rate_basis'] + : ''; + return result.values.any((v) => v != null && v != '') ? result : null; +} diff --git a/app/lib/features/chat/domain/chat_transcript.dart b/app/lib/features/chat/domain/chat_transcript.dart new file mode 100644 index 00000000..b766f15e --- /dev/null +++ b/app/lib/features/chat/domain/chat_transcript.dart @@ -0,0 +1,235 @@ +import '../../../core/api_gateway.dart'; + +/// Merge chronological history pages by message id. Incoming authoritative +/// copies replace held copies without changing their order; cursor is opaque. +JsonMap mergeChatHistory(JsonMap previous, JsonMap page, {bool older = false}) { + final held = (previous['messages'] as List? ?? const []) + .whereType() + .map((m) => Map.from(m)) + .toList(); + final incoming = (page['messages'] as List? ?? const []) + .whereType() + .map((m) => Map.from(m)) + .toList(); + final latest = {}; + for (final message in incoming) { + if (message['id'] != null) latest[message['id']] = message; + } + final combined = older ? [...incoming, ...held] : [...held, ...incoming]; + final seen = {}; + final messages = []; + for (final message in combined) { + final id = message['id']; + if (id != null && !seen.add(id)) continue; + messages.add(id == null ? message : latest[id] ?? message); + } + return { + 'messages': messages, + 'nextCursor': '${page['nextCursor'] ?? ''}', + 'hasMore': page['hasMore'] == true, + 'loaded': true, + 'loading': false, + }; +} + +/// Consecutive assistant messages form one answer turn. All part fields (also +/// future/unknown protocol types) are preserved in original order. +List transcriptRows(List messages) { + final rows = []; + String? key; + final parts = []; + void flush() { + if (key != null && parts.isNotEmpty) { + rows.add({ + 'kind': 'assistant', + 'key': key, + 'parts': List.of(parts), + }); + } + key = null; + parts.clear(); + } + + for (final message in messages) { + if (message['role'] == 'assistant') { + key ??= '${message['id'] ?? ''}'; + for (final part in (message['parts'] as List? ?? const [])) { + if (part is Map) parts.add(Map.from(part)); + } + } else { + flush(); + rows.add({'kind': 'user', 'key': message['id'], 'message': message}); + } + } + flush(); + return rows; +} + +/// Replace a local optimistic user row when its server echo identifies the +/// same operation/native message; otherwise append once by authoritative id. +List reconcileChatUser(List messages, JsonMap remote) { + final operation = remote['operation_id']; + final nativeId = remote['native_message_id']; + final id = remote['id']; + final index = messages.indexWhere( + (message) => + (operation != null && message['operation_id'] == operation) || + (nativeId != null && message['native_message_id'] == nativeId) || + (id != null && message['id'] == id), + ); + if (index < 0) return [...messages, remote]; + final result = List.of(messages); + result[index] = remote; + return result; +} + +/// Fold a live chat frame into an immutable thread snapshot. Text and reasoning +/// deltas append by part id, tool snapshots merge without dropping prior fields, +/// and step frames update turn activity. Frames for another session are ignored. +JsonMap applyChatEvent(JsonMap thread, JsonMap frame) { + final session = thread['sessionId']; + if (session != null && + frame['session_id'] != null && + session != frame['session_id']) { + return thread; + } + final messages = (thread['messages'] as List? ?? const []) + .whereType() + .map((m) => Map.from(m)) + .toList(); + final kind = frame['kind']; + if (kind == 'user') { + final part = frame['part']; + final text = part is Map ? part['text'] : null; + final id = frame['message_id']; + if (text is! String || + text.isEmpty || + id == null || + messages.any( + (m) => + m['id'] == id || + (frame['operation_id'] != null && + m['operation_id'] == frame['operation_id']), + )) { + return thread; + } + messages.add({ + 'id': id, + 'session_id': frame['session_id'], + 'role': 'user', + 'client': frame['client'], + 'operation_id': frame['operation_id'], + 'parts': [ + {'type': 'text', 'text': text}, + ...(frame['attachments'] is List + ? frame['attachments'] as List + : const []), + ], + }); + return {...thread, 'messages': messages}; + } + if (kind == 'text' || kind == 'reasoning' || kind == 'tool') { + final incoming = frame['part']; + if (incoming is! Map || incoming['id'] == null) return thread; + final messageId = frame['message_id']; + var index = messages.indexWhere( + (m) => m['id'] == messageId && m['role'] == 'assistant', + ); + if (index < 0) { + messages.add({ + 'id': messageId, + 'session_id': frame['session_id'], + 'role': 'assistant', + 'parts': [], + }); + index = messages.length - 1; + } + final message = messages[index]; + final parts = (message['parts'] as List? ?? const []) + .whereType() + .map((p) => Map.from(p)) + .toList(); + final partIndex = parts.indexWhere( + (p) => p['id'] == incoming['id'] && p['type'] == kind, + ); + if (kind == 'text' || kind == 'reasoning') { + final delta = frame['delta']; + if (delta is! String || delta.isEmpty) return thread; + if (partIndex < 0) { + parts.add({'type': kind, 'id': incoming['id'], 'text': delta}); + } else { + parts[partIndex] = { + ...parts[partIndex], + 'text': '${parts[partIndex]['text'] ?? ''}$delta', + }; + } + } else if (partIndex < 0) { + parts.add(Map.from(incoming)); + } else { + final merged = { + ...parts[partIndex], + ...Map.from(incoming), + }; + if (parts[partIndex]['state'] is Map && incoming['state'] is Map) { + merged['state'] = { + ...Map.from(parts[partIndex]['state'] as Map), + ...Map.from(incoming['state'] as Map), + }; + } + parts[partIndex] = merged; + } + messages[index] = {...message, 'parts': parts}; + return {...thread, 'messages': messages, 'running': true}; + } + if (kind == 'step' && frame['step'] is Map) { + final step = frame['step'] as Map; + if (step['intermediate'] == true) return thread; + return { + ...thread, + 'running': step['status'] != 'ended', + 'nativeTurnId': step['status'] == 'ended' + ? '' + : (step['turn_id'] ?? thread['nativeTurnId'] ?? ''), + }; + } + return thread; +} + +/// Queue serialized sends per session; operation ids survive retries/replays. +class QueuedChatSend { + QueuedChatSend({ + required this.operationId, + required this.text, + this.files = const [], + }); + final String operationId; + final String text; + final List files; + + /// Retry the same immutable intent with the same idempotency key. + QueuedChatSend retry() => QueuedChatSend( + operationId: operationId, + text: text, + files: List.unmodifiable(files), + ); +} + +class ChatSendQueue { + final Map> _sessions = {}; + List forSession(String sessionId) => + List.unmodifiable(_sessions[sessionId] ?? const []); + bool enqueue(String sessionId, QueuedChatSend send) { + final queue = _sessions.putIfAbsent(sessionId, () => []); + if (queue.any((item) => item.operationId == send.operationId)) return false; + queue.add(send); + return true; + } + + QueuedChatSend? takeNext(String sessionId) { + final queue = _sessions[sessionId]; + if (queue == null || queue.isEmpty) return null; + final result = queue.removeAt(0); + if (queue.isEmpty) _sessions.remove(sessionId); + return result; + } +} diff --git a/app/notes/F4.md b/app/notes/F4.md new file mode 100644 index 00000000..a2578786 --- /dev/null +++ b/app/notes/F4.md @@ -0,0 +1,17 @@ +# F4 chat foundation + +Non-visual chat foundations for the UI lane, using the shared `ApiGateway` and no socket ownership. + +## Imports and API + +- `package:pipelines_app/features/chat/domain/chat_sessions.dart`: `chatSessionTitle`, `filterChatSessions`, `groupChatSessions`, `chatSessionActivity`, and `chatUsageSnapshot`. +- `package:pipelines_app/features/chat/domain/chat_transcript.dart`: `mergeChatHistory`, `transcriptRows`, `reconcileChatUser`, `applyChatEvent`, `QueuedChatSend`, and `ChatSendQueue`. +- `package:pipelines_app/features/chat/data/chat_repository.dart`: `ChatRepository(gateway)`; exposes sessions, directories, history, subscribe, create/rename/star/close/reopen, prompt/interrupt, form answer, permission reply, models/shells and model selection. `gateway.frames` remains the UI/controller's unsolicited event source. + +History uses `chat_history.next_cursor` verbatim, falls back to legacy `chat_messages`, and replaces duplicate authoritative messages while preserving order. `transcriptRows` preserves unknown part maps. Live fold supports user echoes, text/reasoning deltas, tool state snapshots, and step activity; UI should retain its richer thread/timing state as needed. Queue operation IDs are stable across retry objects and deduplicated within each session. Usage values remain unavailable unless reported and valid. + +Wire envelopes are asserted in `test/features/chat/chat_foundation_test.dart`. Current backend has no `chat_forms` or `chat_permissions` list command; forms and permissions arrive as live events and are answered through `chat_answer` / `chat_reply`. + +## Verification + +`/Users/alan/development/flutter/bin/flutter test test/features/chat` passed. Nonvisual foundation: UI/browser review and captures are not applicable at this stage. Web is the only permitted target; Android/iOS remain unverified. diff --git a/app/test/features/chat/chat_foundation_test.dart b/app/test/features/chat/chat_foundation_test.dart new file mode 100644 index 00000000..76e74353 --- /dev/null +++ b/app/test/features/chat/chat_foundation_test.dart @@ -0,0 +1,259 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/data/chat_repository.dart'; +import 'package:pipelines_app/features/chat/domain/chat_sessions.dart'; +import 'package:pipelines_app/features/chat/domain/chat_transcript.dart'; + +class RecordingGateway implements ApiGateway { + final calls = <({String type, JsonMap fields})>[]; + JsonMap reply = {}; + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add((type: type, fields: fields)); + return reply; + } + + @override + Stream get frames => const Stream.empty(); +} + +void main() { + group('chat domain', () { + test( + 'filters/groups in server order and keeps server usage unknowns unavailable', + () { + final sessions = [ + {'id': 'a', 'directory': '/work', 'title': 'First'}, + {'id': 'b', 'directory': '/else', 'title': 'Second'}, + {'id': 'c', 'directory': '/work', 'title': 'Third'}, + ]; + expect(filterChatSessions(sessions, 'ELSE').single['id'], 'b'); + expect(groupChatSessions(sessions).map((g) => g.directory), [ + '/work', + '/else', + ]); + expect(chatSessionActivity(running: true, unseen: true), 'streaming'); + expect( + chatUsageSnapshot({ + 'total_tokens': 3, + 'context_window': 'unknown', + })!['context_window'], + isNull, + ); + expect(chatUsageSnapshot({'legacy_tokens': 9}), isNull); + }, + ); + + test( + 'merges pages by id, retains idless events, replaces authority, and folds parts', + () { + final first = mergeChatHistory({}, { + 'messages': [ + { + 'id': 'a', + 'role': 'assistant', + 'parts': [ + {'type': 'reasoning', 'text': 'think'}, + ], + }, + { + 'role': 'assistant', + 'parts': [ + {'type': 'future_part', 'payload': 4}, + ], + }, + {'id': 'u', 'role': 'user', 'text': 'hello', 'operation_id': 'op'}, + ], + 'nextCursor': 'opaque/1', + 'hasMore': true, + }); + final older = mergeChatHistory(first, { + 'messages': [ + { + 'id': 'a', + 'role': 'assistant', + 'parts': [ + {'type': 'text', 'text': 'final'}, + ], + }, + ], + 'nextCursor': '', + 'hasMore': false, + }, older: true); + expect(older['nextCursor'], ''); + final msgs = older['messages'] as List; + expect(msgs.map((m) => m['id']), ['a', null, 'u']); + expect( + (transcriptRows(msgs).first['parts'] as List).map((p) => p['type']), + ['text', 'future_part'], + ); + expect( + reconcileChatUser(msgs, { + 'id': 'remote', + 'role': 'user', + 'operation_id': 'op', + }).where((m) => m['operation_id'] == 'op').length, + 1, + ); + }, + ); + + test( + 'send queue is session-scoped and operation IDs deduplicate retries', + () { + final queue = ChatSendQueue(); + final send = QueuedChatSend( + operationId: 'stable', + text: ' prompt ', + files: ['/tmp/a'], + ); + expect(queue.enqueue('s1', send), isTrue); + expect(queue.enqueue('s1', send.retry()), isFalse); + expect(queue.enqueue('s2', send.retry()), isTrue); + expect(queue.takeNext('s1')!.operationId, 'stable'); + expect(queue.takeNext('s1'), isNull); + expect(queue.forSession('s2').single.files, ['/tmp/a']); + }, + ); + + test( + 'live text/reasoning append, tool snapshots merge, and steps settle only activity', + () { + var thread = { + 'sessionId': 's', + 'messages': [], + }; + thread = applyChatEvent(thread, { + 'kind': 'text', + 'session_id': 's', + 'message_id': 'a', + 'part': {'id': 'p'}, + 'delta': 'one', + }); + thread = applyChatEvent(thread, { + 'kind': 'text', + 'session_id': 's', + 'message_id': 'a', + 'part': {'id': 'p'}, + 'delta': ' two', + }); + thread = applyChatEvent(thread, { + 'kind': 'reasoning', + 'session_id': 's', + 'message_id': 'a', + 'part': {'id': 'r'}, + 'delta': 'hidden', + }); + thread = applyChatEvent(thread, { + 'kind': 'tool', + 'session_id': 's', + 'message_id': 'a', + 'part': { + 'id': 't', + 'type': 'tool', + 'state': {'input': 'x'}, + }, + }); + thread = applyChatEvent(thread, { + 'kind': 'tool', + 'session_id': 's', + 'message_id': 'a', + 'part': { + 'id': 't', + 'type': 'tool', + 'state': {'status': 'completed'}, + }, + }); + final parts = + ((thread['messages'] as List).single as JsonMap)['parts'] + as List; + expect(parts[0]['text'], 'one two'); + expect(parts[1]['text'], 'hidden'); + expect(parts[2]['state'], {'input': 'x', 'status': 'completed'}); + expect(thread['running'], true); + thread = applyChatEvent(thread, { + 'kind': 'step', + 'session_id': 's', + 'step': {'status': 'ended', 'turn_id': 'turn'}, + }); + expect(thread['running'], false); + expect( + applyChatEvent(thread, {'kind': 'text', 'session_id': 'other'}), + same(thread), + ); + }, + ); + }); + + group('chat wire adapter', () { + late RecordingGateway gateway; + late ChatRepository repo; + setUp(() { + gateway = RecordingGateway(); + repo = ChatRepository(gateway); + }); + test('uses web envelopes and opaque history cursor', () async { + gateway.reply = { + 'chat_history': { + 'messages': [ + {'id': 'm', 'role': 'user'}, + ], + 'next_cursor': 'opaque', + 'has_more': true, + }, + }; + final page = await repo.history('s', cursor: 'before', limit: 17); + expect(page['nextCursor'], 'opaque'); + expect(gateway.calls.last.type, 'chat_messages'); + expect(gateway.calls.last.fields, { + 'chat_query': {'session_id': 's', 'cursor': 'before', 'limit': 17}, + }); + await repo.subscribe('s'); + expect(gateway.calls.last.fields, { + 'chat_subscribe': {'session_id': 's'}, + }); + }); + test( + 'sends stable operation id, omits empty files, and builds action envelopes', + () async { + await repo.prompt('s', ' hi ', operationId: 'same'); + expect(gateway.calls.last.fields, { + 'chat_prompt': { + 'session_id': 's', + 'text': 'hi', + 'operation_id': 'same', + }, + }); + await repo.answerForm('s', 'f', {'choice': 'yes'}, action: 'submit'); + expect(gateway.calls.last.fields, { + 'chat_answer': { + 'session_id': 's', + 'form_id': 'f', + 'answers': {'choice': 'yes'}, + 'action': 'submit', + }, + }); + await repo.replyPermission('s', 'r', 'once', message: ' approved '); + expect(gateway.calls.last.fields, { + 'chat_reply': { + 'session_id': 's', + 'request_id': 'r', + 'decision': 'once', + 'client': 'web', + 'message': 'approved', + }, + }); + await repo.create(title: 'New', directory: '~', operationId: 'create'); + expect(gateway.calls.last.fields, { + 'chat_create': { + 'title': 'New', + 'directory': '~', + 'operation_id': 'create', + }, + }); + await repo.selectModel('s', 'provider', 'model'); + expect(gateway.calls.last.type, 'chat_model'); + }, + ); + }); +} From 48059247d1eb5d9bbea91cb6d63c2eaa38b97f8d Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:37:03 +0100 Subject: [PATCH 2/5] feat(app): add native chat sessions browser --- .../features/chat/data/chat_repository.dart | 105 ++++-- app/lib/features/chat/session_screen.dart | 1 + .../ui/sessions/chat_sessions_screen.dart | 322 ++++++++++++++++++ app/notes/C1.md | 5 + .../features/chat/chat_foundation_test.dart | 39 ++- app/tool/chat_sessions_probe_entry.dart | 62 ++++ 6 files changed, 509 insertions(+), 25 deletions(-) create mode 100644 app/lib/features/chat/session_screen.dart create mode 100644 app/lib/features/chat/ui/sessions/chat_sessions_screen.dart create mode 100644 app/notes/C1.md create mode 100644 app/tool/chat_sessions_probe_entry.dart diff --git a/app/lib/features/chat/data/chat_repository.dart b/app/lib/features/chat/data/chat_repository.dart index 8053ef5c..868408e7 100644 --- a/app/lib/features/chat/data/chat_repository.dart +++ b/app/lib/features/chat/data/chat_repository.dart @@ -1,5 +1,13 @@ import '../../../core/api_gateway.dart'; +const webChatClient = 'Web'; + +String nativeChatMessageId(String operationId) { + final compact = operationId.replaceAll(RegExp('[^A-Za-z0-9]'), ''); + final capped = compact.length > 120 ? compact.substring(0, 120) : compact; + return capped.isEmpty ? '' : 'msg_$capped'; +} + /// Chat wire adapter. ApiGateway supplies request ids and returns full envelopes. class ChatRepository { ChatRepository(this.gateway); @@ -7,11 +15,14 @@ class ChatRepository { Future> sessions() async => _maps((await gateway.call('chat_sessions'))['chat_sessions']); - Future> models(String sessionId) async => _maps( - (await gateway.call('chat_models', { + Future models(String sessionId) async { + final reply = await gateway.call('chat_models', { 'chat_query': {'session_id': sessionId}, - }))['chat_models'], - ); + }); + final catalog = reply['chat_models']; + return catalog is Map ? Map.from(catalog) : {}; + } + Future selectModel( String sessionId, String provider, @@ -34,9 +45,29 @@ class ChatRepository { .whereType() .toList(); + Future> backends() async => + ((await gateway.call('chat_backends'))['chat_backends'] as List? ?? + const []) + .whereType() + .toList(); + + Future shellOutput( + String sessionId, + String shellId, { + int cursor = 0, + int limit = 65536, + }) => gateway.call('chat_shell_output', { + 'chat_shell_output_query': { + 'session_id': sessionId, + 'shell_id': shellId, + 'cursor': cursor, + 'limit': limit, + }, + }); + Future history( String sessionId, { - int limit = 50, + int limit = 200, String cursor = '', }) async { final reply = await gateway.call('chat_messages', { @@ -67,15 +98,21 @@ class ChatRepository { required String operationId, String backend = 'opencode', String instructions = '', - }) => gateway.call('chat_create', { - 'chat_create': { - 'title': title, - 'directory': directory, - 'operation_id': operationId, - if (backend.isNotEmpty && backend != 'opencode') 'backend': backend, - if (instructions.trim().isNotEmpty) 'instructions': instructions.trim(), - }, - }); + }) { + if (title.trim().isEmpty || directory.trim().isEmpty) { + throw ArgumentError('Enter a chat name and choose a directory.'); + } + return gateway.call('chat_create', { + 'chat_create': { + 'title': title.trim(), + 'directory': directory.trim(), + 'operation_id': operationId, + if (backend.isNotEmpty && backend != 'opencode') 'backend': backend, + if (instructions.trim().isNotEmpty) 'instructions': instructions.trim(), + }, + }); + } + Future rename(String sessionId, String title) => gateway.call('chat_rename', { 'chat_rename': {'session_id': sessionId, 'title': title.trim()}, @@ -96,13 +133,22 @@ class ChatRepository { String text, { required String operationId, List files = const [], + List attachments = const [], }) { + if (sessionId.trim().isEmpty) { + throw ArgumentError('Select a chat session first.'); + } + if (text.trim().isEmpty) { + throw ArgumentError('Enter a message before sending.'); + } final body = { 'session_id': sessionId, 'text': text.trim(), 'operation_id': operationId, + 'native_message_id': nativeChatMessageId(operationId), }; if (files.isNotEmpty) body['files'] = files; + if (attachments.isNotEmpty) body['attachments'] = attachments; return gateway.call('chat_prompt', {'chat_prompt': body}); } @@ -127,17 +173,28 @@ class ChatRepository { String sessionId, String requestId, String decision, { - String client = 'web', + String client = webChatClient, String message = '', - }) => gateway.call('chat_reply', { - 'chat_reply': { - 'session_id': sessionId, - 'request_id': requestId, - 'decision': decision, - 'client': client, - if (message.trim().isNotEmpty) 'message': message.trim(), - }, - }); + }) { + if (sessionId.trim().isEmpty) { + throw ArgumentError('Select a chat session first.'); + } + if (requestId.trim().isEmpty) { + throw ArgumentError('This approval request is no longer available.'); + } + if (!const ['once', 'always', 'reject'].contains(decision.trim())) { + throw ArgumentError('Choose once, always or reject.'); + } + return gateway.call('chat_reply', { + 'chat_reply': { + 'session_id': sessionId, + 'request_id': requestId, + 'decision': decision, + 'client': client, + if (message.trim().isNotEmpty) 'message': message.trim(), + }, + }); + } static List _maps(Object? value) => (value as List? ?? const []) .whereType() diff --git a/app/lib/features/chat/session_screen.dart b/app/lib/features/chat/session_screen.dart new file mode 100644 index 00000000..782ccae3 --- /dev/null +++ b/app/lib/features/chat/session_screen.dart @@ -0,0 +1 @@ +export 'ui/sessions/chat_sessions_screen.dart'; diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart new file mode 100644 index 00000000..c18476b0 --- /dev/null +++ b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart @@ -0,0 +1,322 @@ +import 'package:flutter/material.dart'; + +import '../../../../core/api_gateway.dart'; +import '../../data/chat_repository.dart'; +import '../../domain/chat_sessions.dart'; + +/// Browses server-owned sessions. Opening a row is read-only at this layer. +class ChatSessionsScreen extends StatefulWidget { + const ChatSessionsScreen({ + super.key, + required this.gateway, + required this.onOpen, + }); + final ApiGateway gateway; + final void Function(JsonMap session) onOpen; + + @override + State createState() => _ChatSessionsScreenState(); +} + +class _ChatSessionsScreenState extends State { + late ChatRepository _repository; + final _search = TextEditingController(); + List _sessions = []; + String? _error; + bool _loading = true; + int _generation = 0; + + @override + void initState() { + super.initState(); + _repository = ChatRepository(widget.gateway); + _refresh(); + } + + @override + void didUpdateWidget(covariant ChatSessionsScreen oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.gateway != widget.gateway) { + _repository = ChatRepository(widget.gateway); + _refresh(); + } + } + + @override + void dispose() { + _generation++; + _search.dispose(); + super.dispose(); + } + + Future _refresh() async { + final generation = ++_generation; + setState(() { + _loading = true; + _error = null; + }); + try { + final sessions = await _repository.sessions(); + if (!mounted || generation != _generation) return; + setState(() { + _sessions = sessions; + _loading = false; + }); + } catch (error) { + if (!mounted || generation != _generation) return; + setState(() { + _error = '$error'; + _loading = false; + }); + } + } + + Future _mutate( + Future Function(String) action, + String id, + ) async { + try { + await action(id); + await _refresh(); + } catch (error) { + if (mounted) setState(() => _error = '$error'); + } + } + + Future _rename(JsonMap session) async { + final controller = TextEditingController(text: chatSessionTitle(session)); + final title = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Rename chat'), + content: TextField( + controller: controller, + autofocus: true, + decoration: const InputDecoration(labelText: 'Chat name'), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: () => Navigator.pop(context, controller.text.trim()), + child: const Text('Save'), + ), + ], + ), + ); + controller.dispose(); + if (title == null || title.trim().isEmpty) return; + try { + await _repository.rename('${session['id']}', title); + await _refresh(); + } catch (error) { + if (mounted) setState(() => _error = '$error'); + } + } + + Future _newChat() async { + final dirs = TextEditingController(); + final title = TextEditingController(text: 'New chat'); + final instructions = TextEditingController(); + final result = + await showDialog< + ({String title, String directory, String instructions}) + >( + context: context, + builder: (context) => AlertDialog( + title: const Text('New chat'), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + controller: title, + decoration: const InputDecoration(labelText: 'Name'), + ), + TextField( + controller: dirs, + decoration: const InputDecoration( + labelText: 'Server directory', + ), + ), + TextField( + controller: instructions, + decoration: const InputDecoration(labelText: 'Instructions'), + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: () => Navigator.pop(context, ( + title: title.text.trim(), + directory: dirs.text.trim(), + instructions: instructions.text, + )), + child: const Text('Create'), + ), + ], + ), + ); + title.dispose(); + dirs.dispose(); + instructions.dispose(); + if (result == null) return; + if (result.title.isEmpty || result.directory.isEmpty) { + setState(() => _error = 'Enter a name and server directory.'); + return; + } + try { + final reply = await _repository.create( + title: result.title, + directory: result.directory, + operationId: 'native-chat-${DateTime.now().microsecondsSinceEpoch}', + instructions: result.instructions, + ); + final session = reply['chat_session']; + if (session is Map) widget.onOpen(Map.from(session)); + await _refresh(); + } catch (error) { + if (mounted) setState(() => _error = '$error'); + } + } + + @override + Widget build(BuildContext context) { + final visible = filterChatSessions(_sessions, _search.text); + final starred = visible.where((s) => s['starred'] == true).toList(); + final open = visible + .where((s) => s['starred'] != true && s['closed_at'] == null) + .toList(); + final closed = visible.where((s) => s['closed_at'] != null).toList(); + return Scaffold( + appBar: AppBar( + title: const Text('Chats'), + actions: [ + IconButton( + onPressed: _newChat, + tooltip: 'New chat', + icon: const Icon(Icons.add), + ), + IconButton( + onPressed: _refresh, + tooltip: 'Refresh', + icon: const Icon(Icons.refresh), + ), + ], + ), + body: Column( + children: [ + Padding( + padding: const EdgeInsets.all(16), + child: TextField( + controller: _search, + onChanged: (_) => setState(() {}), + decoration: const InputDecoration( + prefixIcon: Icon(Icons.search), + labelText: 'Search chats', + ), + ), + ), + if (_error != null) + MaterialBanner( + content: Text(_error!), + actions: [ + TextButton(onPressed: _refresh, child: const Text('Retry')), + ], + ), + Expanded( + child: _loading && _sessions.isEmpty + ? const Center(child: CircularProgressIndicator()) + : ListView( + children: [ + if (starred.isNotEmpty) _section('Starred', starred), + if (open.isNotEmpty) _section('Chats', open), + if (closed.isNotEmpty) _section('Closed', closed), + if (visible.isEmpty && !_loading) + const ListTile(title: Text('No chats found.')), + ], + ), + ), + ], + ), + floatingActionButton: FloatingActionButton.extended( + onPressed: _newChat, + icon: const Icon(Icons.add), + label: const Text('New chat'), + ), + ); + } + + Widget _section(String title, List sessions) => ExpansionTile( + title: Text(title), + initiallyExpanded: true, + children: [ + for (final group in groupChatSessions(sessions)) ...[ + if (group.directory.isNotEmpty) + ListTile( + dense: true, + leading: const Icon(Icons.folder_outlined), + title: Text(group.directory), + ), + for (final session in group.sessions) _row(session), + ], + ], + ); + + Widget _row(JsonMap session) { + final id = '${session['id'] ?? ''}'; + final isClosed = session['closed_at'] != null; + final starred = session['starred'] == true; + return ListTile( + leading: Icon( + session['running'] == true + ? Icons.sync + : starred + ? Icons.star + : Icons.chat_bubble_outline, + ), + title: Text(chatSessionTitle(session)), + subtitle: Text( + '${session['directory'] ?? ''}${session['running'] == true + ? ' · Streaming' + : session['unseen'] == true + ? ' · New' + : ''}', + ), + onTap: () => widget.onOpen(session), + trailing: PopupMenuButton( + tooltip: 'Chat actions', + onSelected: (value) { + if (value == 'rename') { + _rename(session); + } + if (value == 'star') { + _mutate((id) => _repository.star(id, !starred), id); + } + if (value == 'close') { + _mutate(_repository.close, id); + } + if (value == 'reopen') { + _mutate(_repository.reopen, id); + } + }, + itemBuilder: (_) => [ + const PopupMenuItem(value: 'rename', child: Text('Rename')), + PopupMenuItem( + value: 'star', + child: Text(starred ? 'Remove from Starred' : 'Star'), + ), + if (isClosed) + const PopupMenuItem(value: 'reopen', child: Text('Reopen')) + else + const PopupMenuItem(value: 'close', child: Text('Close')), + ], + ), + ); + } +} diff --git a/app/notes/C1.md b/app/notes/C1.md new file mode 100644 index 00000000..4f79091c --- /dev/null +++ b/app/notes/C1.md @@ -0,0 +1,5 @@ +# C1 — Chat sessions and repository adapter + +Implemented the native Material sessions browser, search, directory grouping, starred/closed groups, standard session actions, and explicit-directory create dialog. Opening a session only invokes the supplied callback. The chat repository includes the web-compatible native message ID, prompt validation, Web permission label, and 200-message history default. + +Verification: `flutter test test/features/chat` passed. Browser build/captures and mobile builds were not performed here. The fixture entry point is `tool/chat_sessions_probe_entry.dart`; a separate browser review should exercise the rendered states and capture them before claiming UI acceptance. diff --git a/app/test/features/chat/chat_foundation_test.dart b/app/test/features/chat/chat_foundation_test.dart index 76e74353..7067c9a1 100644 --- a/app/test/features/chat/chat_foundation_test.dart +++ b/app/test/features/chat/chat_foundation_test.dart @@ -222,6 +222,7 @@ void main() { 'session_id': 's', 'text': 'hi', 'operation_id': 'same', + 'native_message_id': 'msg_same', }, }); await repo.answerForm('s', 'f', {'choice': 'yes'}, action: 'submit'); @@ -239,7 +240,7 @@ void main() { 'session_id': 's', 'request_id': 'r', 'decision': 'once', - 'client': 'web', + 'client': 'Web', 'message': 'approved', }, }); @@ -255,5 +256,41 @@ void main() { expect(gateway.calls.last.type, 'chat_model'); }, ); + test('rejects invalid permissions and prompts before sending', () async { + expect( + () => repo.prompt(' ', 'hello', operationId: 'x'), + throwsArgumentError, + ); + expect( + () => repo.prompt('s', ' ', operationId: 'x'), + throwsArgumentError, + ); + expect( + () => repo.replyPermission('s', 'r', 'approve'), + throwsArgumentError, + ); + expect(gateway.calls, isEmpty); + }); + test( + 'uses the server model catalog object and default history limit', + () async { + gateway.reply = { + 'chat_models': { + 'providers': { + 'p': ['m'], + }, + }, + }; + expect((await repo.models('s'))['providers'], { + 'p': ['m'], + }); + expect(gateway.calls.single.fields, { + 'chat_query': {'session_id': 's'}, + }); + gateway.calls.clear(); + await repo.history('s'); + expect(gateway.calls.single.fields['chat_query']['limit'], 200); + }, + ); }); } diff --git a/app/tool/chat_sessions_probe_entry.dart b/app/tool/chat_sessions_probe_entry.dart new file mode 100644 index 00000000..648fd3bd --- /dev/null +++ b/app/tool/chat_sessions_probe_entry.dart @@ -0,0 +1,62 @@ +import 'package:flutter/material.dart'; + +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/session_screen.dart'; + +class _FixtureGateway implements ApiGateway { + @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, + }, + ], + }; + } + if (type == 'chat_directories') { + return { + 'chat_directories': ['/workspace/demo', '/workspace/archive'], + }; + } + if (type == 'chat_backends') { + return { + 'chat_backends': ['opencode', 'codex'], + }; + } + if (type == 'chat_create') { + return { + 'chat_session': { + 'id': 'probe-new', + 'title': 'New fixture', + 'directory': '/workspace/demo', + }, + }; + } + return {'chat_session': {}}; + } +} + +void main() => runApp( + MaterialApp( + home: ChatSessionsScreen(gateway: _FixtureGateway(), onOpen: (_) {}), + ), +); From a2b02b3810b8b76a31a8e0642dfc93c0b993bf68 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:48:35 +0100 Subject: [PATCH 3/5] Improve chat session catalog creation --- .../features/chat/data/chat_repository.dart | 30 ++-- .../ui/sessions/chat_sessions_screen.dart | 131 ++++++++++++++---- app/notes/C1.md | 4 +- .../features/chat/chat_foundation_test.dart | 20 +++ app/tool/chat_sessions_probe.mjs | 94 +++++++++++++ 5 files changed, 243 insertions(+), 36 deletions(-) create mode 100644 app/tool/chat_sessions_probe.mjs diff --git a/app/lib/features/chat/data/chat_repository.dart b/app/lib/features/chat/data/chat_repository.dart index 868408e7..90f2cc4d 100644 --- a/app/lib/features/chat/data/chat_repository.dart +++ b/app/lib/features/chat/data/chat_repository.dart @@ -39,17 +39,27 @@ class ChatRepository { 'chat_query': {'session_id': sessionId}, }))['chat_shells'], ); - Future> directories() async => - ((await gateway.call('chat_directories'))['chat_directories'] as List? ?? - const []) - .whereType() - .toList(); + Future> directories() async { + final value = (await gateway.call('chat_directories'))['chat_directories']; + if (value is! List) + throw StateError('Server did not return chat directories.'); + return value + .whereType() + .where((entry) => entry.trim().isNotEmpty) + .toList(); + } - Future> backends() async => - ((await gateway.call('chat_backends'))['chat_backends'] as List? ?? - const []) - .whereType() - .toList(); + Future> backends() async { + final value = (await gateway.call('chat_backends'))['chat_backends']; + if (value is! List) + throw StateError('Server did not return chat backends.'); + final result = value + .whereType() + .where((entry) => entry.trim().isNotEmpty) + .toList(); + if (result.isEmpty) throw StateError('Server returned no chat backends.'); + return result; + } Future shellOutput( String sessionId, 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 c18476b0..e7ecd20f 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart @@ -117,34 +117,95 @@ class _ChatSessionsScreenState extends State { } Future _newChat() async { - final dirs = TextEditingController(); + List directories; + List backends; + try { + final catalog = await Future.wait([ + _repository.directories(), + _repository.backends(), + ]); + directories = catalog[0]; + backends = catalog[1]; + } catch (error) { + if (mounted) + setState(() => _error = 'Unable to load chat options: $error'); + return; + } + if (!mounted) return; + if (directories.isEmpty || backends.isEmpty) { + setState( + () => _error = + 'The server has no chat directories or backends available.', + ); + return; + } + final dirs = ValueNotifier(directories.first); + final backend = ValueNotifier(backends.first); final title = TextEditingController(text: 'New chat'); final instructions = TextEditingController(); final result = await showDialog< - ({String title, String directory, String instructions}) + ({ + String title, + String directory, + String backend, + String instructions, + }) >( context: context, builder: (context) => AlertDialog( title: const Text('New chat'), - content: Column( - mainAxisSize: MainAxisSize.min, - children: [ - TextField( - controller: title, - decoration: const InputDecoration(labelText: 'Name'), - ), - TextField( - controller: dirs, - decoration: const InputDecoration( - labelText: 'Server directory', + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + controller: title, + decoration: const InputDecoration(labelText: 'Name'), ), - ), - TextField( - controller: instructions, - decoration: const InputDecoration(labelText: 'Instructions'), - ), - ], + ValueListenableBuilder( + valueListenable: dirs, + builder: (context, value, _) => + DropdownButtonFormField( + initialValue: value, + decoration: const InputDecoration( + labelText: 'Server directory', + ), + items: [ + for (final item in directories) + DropdownMenuItem(value: item, child: Text(item)), + ], + onChanged: (item) { + if (item != null) dirs.value = item; + }, + ), + ), + ValueListenableBuilder( + valueListenable: backend, + builder: (context, value, _) => + DropdownButtonFormField( + initialValue: value, + decoration: const InputDecoration( + labelText: 'Backend', + ), + items: [ + for (final item in backends) + DropdownMenuItem(value: item, child: Text(item)), + ], + onChanged: (item) { + if (item != null) backend.value = item; + }, + ), + ), + const Text('New chats use the server default model.'), + TextField( + controller: instructions, + decoration: const InputDecoration( + labelText: 'Instructions', + ), + ), + ], + ), ), actions: [ TextButton( @@ -154,7 +215,8 @@ class _ChatSessionsScreenState extends State { FilledButton( onPressed: () => Navigator.pop(context, ( title: title.text.trim(), - directory: dirs.text.trim(), + directory: dirs.value, + backend: backend.value, instructions: instructions.text, )), child: const Text('Create'), @@ -164,6 +226,7 @@ class _ChatSessionsScreenState extends State { ); title.dispose(); dirs.dispose(); + backend.dispose(); instructions.dispose(); if (result == null) return; if (result.title.isEmpty || result.directory.isEmpty) { @@ -174,6 +237,7 @@ class _ChatSessionsScreenState extends State { final reply = await _repository.create( title: result.title, directory: result.directory, + backend: result.backend, operationId: 'native-chat-${DateTime.now().microsecondsSinceEpoch}', instructions: result.instructions, ); @@ -188,7 +252,9 @@ class _ChatSessionsScreenState extends State { @override Widget build(BuildContext context) { final visible = filterChatSessions(_sessions, _search.text); - final starred = visible.where((s) => s['starred'] == true).toList(); + final starred = visible + .where((s) => s['starred'] == true && s['closed_at'] == null) + .toList(); final open = visible .where((s) => s['starred'] != true && s['closed_at'] == null) .toList(); @@ -238,7 +304,22 @@ class _ChatSessionsScreenState extends State { if (open.isNotEmpty) _section('Chats', open), if (closed.isNotEmpty) _section('Closed', closed), if (visible.isEmpty && !_loading) - const ListTile(title: Text('No chats found.')), + ListTile( + title: Text( + _sessions.isEmpty + ? 'No chats yet.' + : 'No chats match "${_search.text.trim()}".', + ), + trailing: _search.text.isEmpty + ? null + : TextButton( + onPressed: () { + _search.clear(); + setState(() {}); + }, + child: const Text('Clear search'), + ), + ), ], ), ), @@ -257,11 +338,13 @@ class _ChatSessionsScreenState extends State { initiallyExpanded: true, children: [ for (final group in groupChatSessions(sessions)) ...[ - if (group.directory.isNotEmpty) + if (groupChatSessions(sessions).length > 1) ListTile( dense: true, leading: const Icon(Icons.folder_outlined), - title: Text(group.directory), + title: Text( + group.directory.isEmpty ? 'No directory' : group.directory, + ), ), for (final session in group.sessions) _row(session), ], diff --git a/app/notes/C1.md b/app/notes/C1.md index 4f79091c..8a4736f1 100644 --- a/app/notes/C1.md +++ b/app/notes/C1.md @@ -1,5 +1,5 @@ # C1 — Chat sessions and repository adapter -Implemented the native Material sessions browser, search, directory grouping, starred/closed groups, standard session actions, and explicit-directory create dialog. Opening a session only invokes the supplied callback. The chat repository includes the web-compatible native message ID, prompt validation, Web permission label, and 200-message history default. +The sessions browser now requests server directory and backend catalogs before showing the create dialog, exposes both selectors and model-default guidance, and reports unavailable catalog capabilities instead of silently substituting values. Catalog envelope regressions are covered. Closed starred rows no longer appear twice; directory headings appear only when grouping multiple directories; empty and search-no-match states are distinct. -Verification: `flutter test test/features/chat` passed. Browser build/captures and mobile builds were not performed here. The fixture entry point is `tool/chat_sessions_probe_entry.dart`; a separate browser review should exercise the rendered states and capture them before claiming UI acceptance. +Verification: focused chat tests, `flutter analyze`, fixture `flutter build web -t tool/chat_sessions_probe_entry.dart`, `git diff --check`, and an isolated Chrome DevTools probe passed. Captures: `/private/var/folders/jp/q0qvjyg54fl_c5vhhk1ylz2m0000gn/T/opencode/chat-sessions-capture/chat-sessions-phone.png` and `chat-sessions-create-dialog.png` (plus desktop). The probe enabled semantics, matched the exact “New chat” label, and verified the rendered body changed to show server catalog controls. Cupertino-specific controls, controller/row/dialog decomposition under 250 lines, and wider out-of-order reply UI regression coverage remain incomplete; this is not a parity-complete delivery. Mobile builds were not performed. The fixture entry point is `tool/chat_sessions_probe_entry.dart`. diff --git a/app/test/features/chat/chat_foundation_test.dart b/app/test/features/chat/chat_foundation_test.dart index 7067c9a1..fd7b7b6a 100644 --- a/app/test/features/chat/chat_foundation_test.dart +++ b/app/test/features/chat/chat_foundation_test.dart @@ -292,5 +292,25 @@ void main() { expect(gateway.calls.single.fields['chat_query']['limit'], 200); }, ); + test( + 'reads exact directory/backend catalog envelopes without inventing fallback', + () async { + gateway.reply = { + 'chat_directories': ['~', '/work'], + }; + expect(await repo.directories(), ['~', '/work']); + expect(gateway.calls.last.type, 'chat_directories'); + expect(gateway.calls.last.fields, isEmpty); + gateway.reply = { + 'chat_backends': ['opencode', 'claude'], + }; + expect(await repo.backends(), ['opencode', 'claude']); + expect(gateway.calls.last.type, 'chat_backends'); + expect(gateway.calls.last.fields, isEmpty); + gateway.reply = {}; + await expectLater(repo.directories(), throwsStateError); + await expectLater(repo.backends(), throwsStateError); + }, + ); }); } diff --git a/app/tool/chat_sessions_probe.mjs b/app/tool/chat_sessions_probe.mjs new file mode 100644 index 00000000..7fccb3fb --- /dev/null +++ b/app/tool/chat_sessions_probe.mjs @@ -0,0 +1,94 @@ +import { createServer } from 'node:http'; +import { readFile } from 'node:fs/promises'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { setTimeout as delay } from 'node:timers/promises'; +import { join, extname, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; +import { mkdtemp, rm } from 'node:fs/promises'; + +const root = join(process.cwd(), 'build/web'); +const mime = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm', '.png': 'image/png', '.ico': 'image/x-icon' }; +const server = createServer(async (req, res) => { + try { + const path = resolve(root, '.' + decodeURIComponent(new URL(req.url, 'http://localhost').pathname)); + if (path !== root && !path.startsWith(root + sep)) return res.writeHead(403).end(); + const filePath = path === root || path.endsWith('/') ? join(path, 'index.html') : path; + const file = await readFile(filePath); + res.writeHead(200, { 'content-type': mime[extname(filePath)] ?? 'application/octet-stream' }).end(file); + } catch { res.writeHead(404).end('not found'); } +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const port = server.address().port; + const profile = await mkdtemp(join(tmpdir(), '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 => { + 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'); +}; +let ws; +try { + const endpoint = await waitFor(() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1]); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', event => { + const msg = JSON.parse(event.data); + if (msg.method?.includes('detached') || msg.method?.includes('crashed')) console.error('CDP event', JSON.stringify(msg)); + if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); } + }); + const send = (method, params = {}, sessionId) => new Promise(resolve => { + const callId = ++id; pending.set(callId, resolve); + ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) })); + }); + const created = await send('Target.createTarget', { url: 'about:blank' }); + if (!created.result) throw new Error(`Target creation failed: ${JSON.stringify(created)}`); + const target = created.result.targetId; + const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + const 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 clickLabel = async label => evaluate(`(() => { const e=[...document.querySelectorAll('flt-semantics')].find(x => (x.getAttribute('aria-label') || x.innerText || '') === ${JSON.stringify(label)}); if (!e) return false; e.click(); 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)}`); + const capture = async (name, width, height) => { + await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 }, session); + await delay(350); + const data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).result.data; + await (await import('node:fs/promises')).writeFile(`${process.env.OPENCODE_ARTIFACT_DIR}/${name}.png`, Buffer.from(data, 'base64')); + }; + await capture('chat-sessions-phone', 390, 844); + if (!await clickLabel('New chat')) throw new Error('Could not open create dialog'); + await delay(500); + 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.') || changedBody.includes('Open fixture')) throw new Error(`Create dialog did not change rendered body to catalog controls: ${changedBody}`); + await capture('chat-sessions-desktop', 1280, 800); + console.log(JSON.stringify({ labels, captures: ['chat-sessions-phone.png', 'chat-sessions-create-dialog.png', 'chat-sessions-desktop.png'], bodyChanged: true }, null, 2)); +} finally { + ws?.close(); + chrome.kill('SIGTERM'); + await Promise.race([once(chrome, 'exit'), delay(3000)]); + server.close(); + await rm(profile, { recursive: true, force: true }); +} From 13d8ddac5d8bf6b827923935c8a7f9248407717d Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:49:18 +0100 Subject: [PATCH 4/5] Tidy chat catalog error handling --- app/lib/features/chat/data/chat_repository.dart | 6 ++++-- app/lib/features/chat/ui/sessions/chat_sessions_screen.dart | 3 ++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/app/lib/features/chat/data/chat_repository.dart b/app/lib/features/chat/data/chat_repository.dart index 90f2cc4d..b97bd52a 100644 --- a/app/lib/features/chat/data/chat_repository.dart +++ b/app/lib/features/chat/data/chat_repository.dart @@ -41,8 +41,9 @@ class ChatRepository { ); Future> directories() async { final value = (await gateway.call('chat_directories'))['chat_directories']; - if (value is! List) + if (value is! List) { throw StateError('Server did not return chat directories.'); + } return value .whereType() .where((entry) => entry.trim().isNotEmpty) @@ -51,8 +52,9 @@ class ChatRepository { Future> backends() async { final value = (await gateway.call('chat_backends'))['chat_backends']; - if (value is! List) + if (value is! List) { throw StateError('Server did not return chat backends.'); + } final result = value .whereType() .where((entry) => entry.trim().isNotEmpty) 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 e7ecd20f..b6a88d89 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart @@ -127,8 +127,9 @@ class _ChatSessionsScreenState extends State { directories = catalog[0]; backends = catalog[1]; } catch (error) { - if (mounted) + if (mounted) { setState(() => _error = 'Unable to load chat options: $error'); + } return; } if (!mounted) return; From 41d30a4280f572a1bff09458adf22afa34751d1a Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 17:42:39 +0100 Subject: [PATCH 5/5] feat(app): split chat sessions into native Material and Cupertino views Split the 406-line chat session browser into a controller, body, shared adaptive primitives and separate standard Material and Cupertino lists and dialogs. Preserve the existing server directory/backend catalogs, instructions field, closed/starred grouping, directory headings and empty/no-match states. - keep refresh generations so stale replies are discarded - open a created chat immediately and refresh the list in the background - disable rename Save while the trimmed name is blank - label row actions per session, with the id on duplicate titles - wrap Cupertino empty/no-match/error messages instead of clipping, and give them a Cupertino text style under a bare MaterialApp - allow the Material rename helper to wrap at large text scales - cover both native branches, lifecycle ordering, create/rename/close/star and the Cupertino theme path with widget tests --- .../chat/ui/sessions/chat_adaptive.dart | 200 ++++++++ .../chat/ui/sessions/chat_create_fields.dart | 185 +++++++ .../chat/ui/sessions/chat_sessions_body.dart | 97 ++++ .../ui/sessions/chat_sessions_controller.dart | 111 ++++ .../ui/sessions/chat_sessions_screen.dart | 472 +++++------------- .../chat/ui/sessions/create_chat_dialog.dart | 222 ++++++++ .../chat/ui/sessions/rename_chat_dialog.dart | 107 ++++ .../chat/ui/sessions/session_actions.dart | 161 ++++++ .../ui/sessions/session_list_cupertino.dart | 134 +++++ .../ui/sessions/session_list_material.dart | 140 ++++++ .../chat/ui/sessions/session_row_style.dart | 51 ++ app/notes/C1b.md | 163 ++++++ .../ui/sessions/chat_create_dialog_test.dart | 217 ++++++++ .../sessions/chat_cupertino_theme_test.dart | 91 ++++ .../sessions/chat_session_actions_test.dart | 174 +++++++ .../chat_sessions_lifecycle_test.dart | 76 +++ .../sessions/chat_sessions_screen_test.dart | 213 ++++++++ .../chat/ui/sessions/chat_test_harness.dart | 77 +++ .../chat/ui/sessions/fake_chat_gateway.dart | 56 +++ app/tool/chat_sessions_probe.mjs | 34 +- app/tool/chat_sessions_probe_entry.dart | 22 +- 21 files changed, 2640 insertions(+), 363 deletions(-) create mode 100644 app/lib/features/chat/ui/sessions/chat_adaptive.dart create mode 100644 app/lib/features/chat/ui/sessions/chat_create_fields.dart create mode 100644 app/lib/features/chat/ui/sessions/chat_sessions_body.dart create mode 100644 app/lib/features/chat/ui/sessions/chat_sessions_controller.dart create mode 100644 app/lib/features/chat/ui/sessions/create_chat_dialog.dart create mode 100644 app/lib/features/chat/ui/sessions/rename_chat_dialog.dart create mode 100644 app/lib/features/chat/ui/sessions/session_actions.dart create mode 100644 app/lib/features/chat/ui/sessions/session_list_cupertino.dart create mode 100644 app/lib/features/chat/ui/sessions/session_list_material.dart create mode 100644 app/lib/features/chat/ui/sessions/session_row_style.dart create mode 100644 app/notes/C1b.md create mode 100644 app/test/features/chat/ui/sessions/chat_create_dialog_test.dart create mode 100644 app/test/features/chat/ui/sessions/chat_cupertino_theme_test.dart create mode 100644 app/test/features/chat/ui/sessions/chat_session_actions_test.dart create mode 100644 app/test/features/chat/ui/sessions/chat_sessions_lifecycle_test.dart create mode 100644 app/test/features/chat/ui/sessions/chat_sessions_screen_test.dart create mode 100644 app/test/features/chat/ui/sessions/chat_test_harness.dart create mode 100644 app/test/features/chat/ui/sessions/fake_chat_gateway.dart diff --git a/app/lib/features/chat/ui/sessions/chat_adaptive.dart b/app/lib/features/chat/ui/sessions/chat_adaptive.dart new file mode 100644 index 00000000..4dcf7008 --- /dev/null +++ b/app/lib/features/chat/ui/sessions/chat_adaptive.dart @@ -0,0 +1,200 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +/// Which standard control family this screen renders. +enum ChatControlsStyle { material, cupertino } + +/// Cupertino under a Cupertino app or an iOS/macOS Material theme, Material +/// everywhere else. The shell decides the app class, so a bare Cupertino app +/// never has to grow a Material ancestor just for this screen. +ChatControlsStyle chatControlsStyleOf(BuildContext context) { + if (context.findAncestorWidgetOfExactType() == null) { + return ChatControlsStyle.cupertino; + } + final platform = Theme.of(context).platform; + return platform == TargetPlatform.iOS || platform == TargetPlatform.macOS + ? ChatControlsStyle.cupertino + : ChatControlsStyle.material; +} + +class ChatBarAction extends StatelessWidget { + const ChatBarAction({ + super.key, + required this.label, + required this.onPressed, + required this.materialIcon, + required this.cupertinoIcon, + }); + + final String label; + final VoidCallback onPressed; + final IconData materialIcon; + final IconData cupertinoIcon; + + @override + Widget build(BuildContext context) { + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { + return Semantics( + label: label, + button: true, + child: CupertinoButton( + padding: EdgeInsets.zero, + onPressed: onPressed, + child: Icon(cupertinoIcon), + ), + ); + } + return IconButton( + tooltip: label, + onPressed: onPressed, + icon: Icon(materialIcon), + ); + } +} + +class ChatSearchField extends StatelessWidget { + const ChatSearchField({ + super.key, + required this.controller, + required this.onChanged, + }); + + final TextEditingController controller; + final ValueChanged onChanged; + + @override + Widget build(BuildContext context) { + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { + return Padding( + padding: const EdgeInsets.all(16), + child: CupertinoSearchTextField( + controller: controller, + placeholder: 'Search chats', + onChanged: onChanged, + ), + ); + } + return Padding( + padding: const EdgeInsets.all(16), + child: TextField( + controller: controller, + onChanged: onChanged, + decoration: const InputDecoration( + prefixIcon: Icon(Icons.search), + labelText: 'Search chats', + ), + ), + ); + } +} + +/// A grouped Cupertino card for a message that may wrap onto several lines. +/// +/// [CupertinoListTile] forces its title to one ellipsised line, which cut long +/// no-match queries and server reasons. This layout keeps the native card but +/// lets the message wrap, with its action on a separate button below. +class ChatCupertinoMessage extends StatelessWidget { + const ChatCupertinoMessage({ + super.key, + required this.message, + this.icon, + this.actionLabel, + this.onAction, + }); + + final String message; + final IconData? icon; + final String? actionLabel; + final VoidCallback? onAction; + + @override + Widget build(BuildContext context) { + return Semantics( + container: true, + explicitChildNodes: true, + child: CupertinoListSection.insetGrouped( + children: [ + Padding( + padding: const EdgeInsets.all(16), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (icon != null) ...[ + Icon( + icon, + color: CupertinoColors.secondaryLabel.resolveFrom(context), + ), + const SizedBox(width: 12), + ], + Expanded( + // Cupertino widgets normally supply their own text style. + // This card is also mounted under a bare MaterialApp (the + // iOS/macOS theme path), where Text would otherwise inherit + // MaterialApp's "missing Material" fallback style. + child: DefaultTextStyle.merge( + style: CupertinoTheme.of(context).textTheme.textStyle, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(message), + if (actionLabel != null && onAction != null) + Align( + alignment: AlignmentDirectional.centerStart, + child: CupertinoButton( + padding: const EdgeInsets.only(top: 8), + onPressed: onAction, + child: Text(actionLabel!), + ), + ), + ], + ), + ), + ), + ], + ), + ), + ], + ), + ); + } +} + +class ChatErrorNotice extends StatelessWidget { + const ChatErrorNotice({ + super.key, + required this.message, + required this.onRetry, + }); + + final String message; + final VoidCallback onRetry; + + @override + Widget build(BuildContext context) { + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { + return ChatCupertinoMessage( + message: message, + icon: CupertinoIcons.exclamationmark_circle, + actionLabel: 'Retry', + onAction: onRetry, + ); + } + return MaterialBanner( + content: Text(message), + actions: [TextButton(onPressed: onRetry, child: const Text('Retry'))], + ); + } +} + +class ChatLoadingIndicator extends StatelessWidget { + const ChatLoadingIndicator({super.key}); + + @override + Widget build(BuildContext context) { + return Center( + child: chatControlsStyleOf(context) == ChatControlsStyle.cupertino + ? const CupertinoActivityIndicator() + : const CircularProgressIndicator(), + ); + } +} diff --git a/app/lib/features/chat/ui/sessions/chat_create_fields.dart b/app/lib/features/chat/ui/sessions/chat_create_fields.dart new file mode 100644 index 00000000..f477811a --- /dev/null +++ b/app/lib/features/chat/ui/sessions/chat_create_fields.dart @@ -0,0 +1,185 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'chat_adaptive.dart'; + +/// The create dialog's server catalog area: loading, error with retry, the +/// empty-catalog message, or the two server-backed selectors. +class ChatCatalogFields extends StatelessWidget { + const ChatCatalogFields({ + super.key, + required this.loading, + required this.error, + required this.directories, + required this.backends, + required this.directory, + required this.backend, + required this.onDirectory, + required this.onBackend, + required this.onRetry, + }); + + final bool loading; + final String? error; + final List directories; + final List backends; + final String? directory; + final String? backend; + final ValueChanged onDirectory; + final ValueChanged onBackend; + final VoidCallback onRetry; + + @override + Widget build(BuildContext context) { + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + if (loading) return const Text('Loading directories…'); + if (error != null) { + return _message(cupertino, 'Unable to load chat options: $error'); + } + if (directories.isEmpty || backends.isEmpty) { + return _message( + cupertino, + 'The server has no chat directories or backends available.', + ); + } + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (cupertino) + CupertinoPickerField( + label: 'Server directory', + value: directory, + values: directories, + onSelected: onDirectory, + ) + else + MaterialPickerField( + label: 'Server directory', + value: directory, + values: directories, + onSelected: onDirectory, + ), + if (cupertino) + CupertinoPickerField( + label: 'Backend', + value: backend, + values: backends, + onSelected: onBackend, + ) + else + MaterialPickerField( + label: 'Backend', + value: backend, + values: backends, + onSelected: onBackend, + ), + ], + ); + } + + Widget _message(bool cupertino, String text) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(text), + Align( + alignment: AlignmentDirectional.centerStart, + child: cupertino + ? CupertinoButton( + padding: EdgeInsets.zero, + onPressed: onRetry, + child: const Text('Retry'), + ) + : TextButton(onPressed: onRetry, child: const Text('Retry')), + ), + ], + ); + } +} + +class MaterialPickerField extends StatelessWidget { + const MaterialPickerField({ + super.key, + required this.label, + required this.value, + required this.values, + required this.onSelected, + }); + + final String label; + final String? value; + final List values; + final ValueChanged onSelected; + + @override + Widget build(BuildContext context) { + return DropdownButtonFormField( + key: Key('chat-create-${label.toLowerCase().replaceAll(' ', '-')}'), + initialValue: value, + decoration: InputDecoration(labelText: label), + items: [ + for (final item in values) + DropdownMenuItem(value: item, child: Text(item)), + ], + onChanged: (item) { + if (item != null) onSelected(item); + }, + ); + } +} + +class CupertinoPickerField extends StatelessWidget { + const CupertinoPickerField({ + super.key, + required this.label, + required this.value, + required this.values, + required this.onSelected, + }); + + final String label; + final String? value; + final List values; + final ValueChanged onSelected; + + Future _choose(BuildContext context) async { + final choice = await showCupertinoModalPopup( + context: context, + builder: (sheetContext) => CupertinoActionSheet( + title: Text(label), + actions: [ + for (final item in values) + CupertinoActionSheetAction( + onPressed: () => Navigator.pop(sheetContext, item), + child: Text(item), + ), + ], + cancelButton: CupertinoActionSheetAction( + onPressed: () => Navigator.pop(sheetContext), + child: const Text('Cancel'), + ), + ), + ); + if (choice != null) onSelected(choice); + } + + @override + Widget build(BuildContext context) { + return Semantics( + label: '$label: ${value ?? ''}', + button: true, + child: CupertinoButton( + key: Key('chat-create-${label.toLowerCase().replaceAll(' ', '-')}'), + padding: const EdgeInsets.symmetric(vertical: 4), + onPressed: () => _choose(context), + child: Row( + children: [ + Expanded(child: Text('$label: ${value ?? ''}')), + const Icon(CupertinoIcons.chevron_down), + ], + ), + ), + ); + } +} diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_body.dart b/app/lib/features/chat/ui/sessions/chat_sessions_body.dart new file mode 100644 index 00000000..0489a365 --- /dev/null +++ b/app/lib/features/chat/ui/sessions/chat_sessions_body.dart @@ -0,0 +1,97 @@ +import 'package:flutter/material.dart'; + +import '../../../../core/api_gateway.dart'; +import '../../domain/chat_sessions.dart'; +import 'chat_adaptive.dart'; +import 'session_list_cupertino.dart'; +import 'session_list_material.dart'; +import 'session_row_style.dart'; + +typedef ChatSessionSection = ({String title, List sessions}); + +/// Groups the visible sessions the way the server reports them. +class ChatSessionsBody extends StatelessWidget { + const ChatSessionsBody({ + super.key, + required this.sessions, + required this.query, + required this.loading, + required this.error, + required this.onOpen, + required this.onRename, + required this.onClose, + required this.onReopen, + required this.onStar, + required this.onClearSearch, + }); + + final List sessions; + final String query; + final bool loading; + final String? error; + final ValueChanged onOpen; + final ValueChanged onRename; + final ValueChanged onClose; + final ValueChanged onReopen; + final ValueChanged onStar; + final VoidCallback onClearSearch; + + @override + Widget build(BuildContext context) { + final visible = filterChatSessions(sessions, query); + final sections = [ + if (visible.any((s) => s['starred'] == true && s['closed_at'] == null)) + ( + title: 'Starred', + sessions: visible + .where((s) => s['starred'] == true && s['closed_at'] == null) + .toList(), + ), + if (visible.any((s) => s['starred'] != true && s['closed_at'] == null)) + ( + title: 'Chats', + sessions: visible + .where((s) => s['starred'] != true && s['closed_at'] == null) + .toList(), + ), + if (visible.any((s) => s['closed_at'] != null)) + ( + title: 'Closed', + sessions: visible.where((s) => s['closed_at'] != null).toList(), + ), + ]; + final emptyMessage = sessions.isEmpty + ? error == null + ? 'No chat sessions on this server yet.' + : null + : 'No chats match "${query.trim()}".'; + + if (loading && sessions.isEmpty) return const ChatLoadingIndicator(); + final clearSearch = query.trim().isEmpty ? null : onClearSearch; + final duplicateTitles = duplicateChatTitles(visible); + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { + return CupertinoSessionList( + sections: sections, + emptyMessage: visible.isEmpty ? emptyMessage : null, + duplicateTitles: duplicateTitles, + onOpen: onOpen, + onRename: onRename, + onClose: onClose, + onReopen: onReopen, + onStar: onStar, + onClearSearch: clearSearch, + ); + } + return MaterialSessionList( + sections: sections, + emptyMessage: visible.isEmpty ? emptyMessage : null, + duplicateTitles: duplicateTitles, + onOpen: onOpen, + onRename: onRename, + onClose: onClose, + onReopen: onReopen, + onStar: onStar, + onClearSearch: clearSearch, + ); + } +} diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart new file mode 100644 index 00000000..3c5799c6 --- /dev/null +++ b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart @@ -0,0 +1,111 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../../../../core/api_gateway.dart'; +import '../../data/chat_repository.dart'; + +/// Owns the session list, its refresh generation and the 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. +class ChatSessionsController extends ChangeNotifier { + ChatSessionsController(this.repository); + + ChatRepository repository; + List _sessions = const []; + String? _error; + bool _loading = true; + bool _disposed = false; + int _generation = 0; + + List get sessions => _sessions; + String? get error => _error; + bool get loading => _loading; + + void replaceRepository(ChatRepository next) { + if (identical(next.gateway, repository.gateway)) return; + repository = next; + refresh(); + } + + Future refresh() async { + if (_disposed) return; + final generation = ++_generation; + _loading = true; + _error = null; + _notify(); + try { + final sessions = await repository.sessions(); + if (generation != _generation) return; + _sessions = sessions; + _loading = false; + _notify(); + } catch (error) { + if (generation != _generation) return; + _error = '$error'; + _loading = false; + _notify(); + } + } + + Future star(String sessionId, bool starred) => + _mutate(() => repository.star(sessionId, starred)); + + Future close(String sessionId) => + _mutate(() => repository.close(sessionId)); + + Future reopen(String sessionId) => + _mutate(() => repository.reopen(sessionId)); + + Future rename(String sessionId, String title) => + _mutate(() => repository.rename(sessionId, title)); + + Future create({ + 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, + ); + // 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; + } catch (error) { + _error = '$error'; + _notify(); + return null; + } + } + + Future _mutate(Future Function() action) async { + try { + await action(); + await refresh(); + } catch (error) { + _error = '$error'; + _notify(); + } + } + + void _notify() { + if (!_disposed) notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + _generation++; + super.dispose(); + } +} 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 b6a88d89..ff345739 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart @@ -1,8 +1,14 @@ +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../../../../core/api_gateway.dart'; import '../../data/chat_repository.dart'; -import '../../domain/chat_sessions.dart'; +import 'chat_adaptive.dart'; +import 'chat_sessions_body.dart'; +import 'chat_sessions_controller.dart'; +import 'create_chat_dialog.dart'; +import 'rename_chat_dialog.dart'; +import 'session_actions.dart'; /// Browses server-owned sessions. Opening a row is read-only at this layer. class ChatSessionsScreen extends StatefulWidget { @@ -19,388 +25,152 @@ class ChatSessionsScreen extends StatefulWidget { } class _ChatSessionsScreenState extends State { - late ChatRepository _repository; + late final ChatSessionsController _controller = ChatSessionsController( + ChatRepository(widget.gateway), + )..refresh(); final _search = TextEditingController(); - List _sessions = []; - String? _error; - bool _loading = true; - int _generation = 0; - - @override - void initState() { - super.initState(); - _repository = ChatRepository(widget.gateway); - _refresh(); - } @override void didUpdateWidget(covariant ChatSessionsScreen oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.gateway != widget.gateway) { - _repository = ChatRepository(widget.gateway); - _refresh(); + _controller.replaceRepository(ChatRepository(widget.gateway)); } } @override void dispose() { - _generation++; + _controller.dispose(); _search.dispose(); super.dispose(); } - Future _refresh() async { - final generation = ++_generation; - setState(() { - _loading = true; - _error = null; - }); - try { - final sessions = await _repository.sessions(); - if (!mounted || generation != _generation) return; - setState(() { - _sessions = sessions; - _loading = false; - }); - } catch (error) { - if (!mounted || generation != _generation) return; - setState(() { - _error = '$error'; - _loading = false; - }); - } - } - - Future _mutate( - Future Function(String) action, - String id, - ) async { - try { - await action(id); - await _refresh(); - } catch (error) { - if (mounted) setState(() => _error = '$error'); - } - } + String _sessionId(JsonMap session) => '${session['id'] ?? ''}'; Future _rename(JsonMap session) async { - final controller = TextEditingController(text: chatSessionTitle(session)); - final title = await showDialog( - context: context, - builder: (context) => AlertDialog( - title: const Text('Rename chat'), - content: TextField( - controller: controller, - autofocus: true, - decoration: const InputDecoration(labelText: 'Chat name'), - ), - actions: [ - TextButton( - onPressed: () => Navigator.pop(context), - child: const Text('Cancel'), - ), - FilledButton( - onPressed: () => Navigator.pop(context, controller.text.trim()), - child: const Text('Save'), - ), - ], - ), - ); - controller.dispose(); - if (title == null || title.trim().isEmpty) return; - try { - await _repository.rename('${session['id']}', title); - await _refresh(); - } catch (error) { - if (mounted) setState(() => _error = '$error'); - } + final title = await showRenameChatDialog(context, session); + if (title == null || !mounted) return; + await _controller.rename(_sessionId(session), title); + } + + Future _close(JsonMap session) async { + if (!await confirmCloseChat(context, session)) return; + if (!mounted) return; + await _controller.close(_sessionId(session)); } Future _newChat() async { - List directories; - List backends; - try { - final catalog = await Future.wait([ - _repository.directories(), - _repository.backends(), - ]); - directories = catalog[0]; - backends = catalog[1]; - } catch (error) { - if (mounted) { - setState(() => _error = 'Unable to load chat options: $error'); - } - return; - } - if (!mounted) return; - if (directories.isEmpty || backends.isEmpty) { - setState( - () => _error = - 'The server has no chat directories or backends available.', - ); - return; - } - final dirs = ValueNotifier(directories.first); - final backend = ValueNotifier(backends.first); - final title = TextEditingController(text: 'New chat'); - final instructions = TextEditingController(); - final result = - await showDialog< - ({ - String title, - String directory, - String backend, - String instructions, - }) - >( - context: context, - builder: (context) => AlertDialog( - title: const Text('New chat'), - content: SingleChildScrollView( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - TextField( - controller: title, - decoration: const InputDecoration(labelText: 'Name'), - ), - ValueListenableBuilder( - valueListenable: dirs, - builder: (context, value, _) => - DropdownButtonFormField( - initialValue: value, - decoration: const InputDecoration( - labelText: 'Server directory', - ), - items: [ - for (final item in directories) - DropdownMenuItem(value: item, child: Text(item)), - ], - onChanged: (item) { - if (item != null) dirs.value = item; - }, - ), - ), - ValueListenableBuilder( - valueListenable: backend, - builder: (context, value, _) => - DropdownButtonFormField( - initialValue: value, - decoration: const InputDecoration( - labelText: 'Backend', - ), - items: [ - for (final item in backends) - DropdownMenuItem(value: item, child: Text(item)), - ], - onChanged: (item) { - if (item != null) backend.value = item; - }, - ), - ), - const Text('New chats use the server default model.'), - TextField( - controller: instructions, - decoration: const InputDecoration( - labelText: 'Instructions', - ), - ), - ], - ), - ), - actions: [ - TextButton( - onPressed: () => Navigator.pop(context), - child: const Text('Cancel'), - ), - FilledButton( - onPressed: () => Navigator.pop(context, ( - title: title.text.trim(), - directory: dirs.value, - backend: backend.value, - instructions: instructions.text, - )), - child: const Text('Create'), - ), - ], - ), - ); - title.dispose(); - dirs.dispose(); - backend.dispose(); - instructions.dispose(); - if (result == null) return; - if (result.title.isEmpty || result.directory.isEmpty) { - setState(() => _error = 'Enter a name and server directory.'); - return; - } - try { - final reply = await _repository.create( - title: result.title, - directory: result.directory, - backend: result.backend, - operationId: 'native-chat-${DateTime.now().microsecondsSinceEpoch}', - instructions: result.instructions, - ); - final session = reply['chat_session']; - if (session is Map) widget.onOpen(Map.from(session)); - await _refresh(); - } catch (error) { - if (mounted) setState(() => _error = '$error'); - } + final operationId = 'native-chat-${DateTime.now().microsecondsSinceEpoch}'; + final draft = 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, + ); + if (session != null && mounted) widget.onOpen(session); } @override Widget build(BuildContext context) { - final visible = filterChatSessions(_sessions, _search.text); - final starred = visible - .where((s) => s['starred'] == true && s['closed_at'] == null) - .toList(); - final open = visible - .where((s) => s['starred'] != true && s['closed_at'] == null) - .toList(); - final closed = visible.where((s) => s['closed_at'] != null).toList(); - return Scaffold( - appBar: AppBar( - title: const Text('Chats'), - actions: [ - IconButton( - onPressed: _newChat, - tooltip: 'New chat', - icon: const Icon(Icons.add), - ), - IconButton( - onPressed: _refresh, - tooltip: 'Refresh', - icon: const Icon(Icons.refresh), - ), - ], - ), - body: Column( - children: [ - Padding( - padding: const EdgeInsets.all(16), - child: TextField( + return ListenableBuilder( + listenable: _controller, + builder: (context, _) { + final body = Column( + children: [ + ChatSearchField( controller: _search, onChanged: (_) => setState(() {}), - decoration: const InputDecoration( - prefixIcon: Icon(Icons.search), - labelText: 'Search chats', + ), + if (_controller.error != null) + ChatErrorNotice( + message: _controller.error!, + 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(() {}); + }, ), ), - ), - if (_error != null) - MaterialBanner( - content: Text(_error!), - actions: [ - TextButton(onPressed: _refresh, child: const Text('Retry')), - ], - ), - Expanded( - child: _loading && _sessions.isEmpty - ? const Center(child: CircularProgressIndicator()) - : ListView( - children: [ - if (starred.isNotEmpty) _section('Starred', starred), - if (open.isNotEmpty) _section('Chats', open), - if (closed.isNotEmpty) _section('Closed', closed), - if (visible.isEmpty && !_loading) - ListTile( - title: Text( - _sessions.isEmpty - ? 'No chats yet.' - : 'No chats match "${_search.text.trim()}".', - ), - trailing: _search.text.isEmpty - ? null - : TextButton( - onPressed: () { - _search.clear(); - setState(() {}); - }, - child: const Text('Clear search'), - ), - ), - ], + ], + ); + + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { + return CupertinoPageScaffold( + navigationBar: CupertinoNavigationBar( + middle: const Text('Chats'), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + ChatBarAction( + key: const Key('chat-new-chat'), + label: 'New chat', + onPressed: _newChat, + materialIcon: Icons.add, + cupertinoIcon: CupertinoIcons.add, ), - ), - ], - ), - floatingActionButton: FloatingActionButton.extended( - onPressed: _newChat, - icon: const Icon(Icons.add), - label: const Text('New chat'), - ), - ); - } - - Widget _section(String title, List sessions) => ExpansionTile( - title: Text(title), - initiallyExpanded: true, - children: [ - for (final group in groupChatSessions(sessions)) ...[ - if (groupChatSessions(sessions).length > 1) - ListTile( - dense: true, - leading: const Icon(Icons.folder_outlined), - title: Text( - group.directory.isEmpty ? 'No directory' : group.directory, + ChatBarAction( + key: const Key('chat-refresh'), + label: 'Refresh', + onPressed: _controller.refresh, + materialIcon: Icons.refresh, + cupertinoIcon: CupertinoIcons.refresh, + ), + ], + ), ), + child: SafeArea(child: body), + ); + } + return Scaffold( + appBar: AppBar( + title: const Text('Chats'), + actions: [ + ChatBarAction( + key: const Key('chat-new-chat'), + label: 'New chat', + onPressed: _newChat, + materialIcon: Icons.add, + cupertinoIcon: CupertinoIcons.add, + ), + ChatBarAction( + key: const Key('chat-refresh'), + label: 'Refresh', + onPressed: _controller.refresh, + materialIcon: Icons.refresh, + cupertinoIcon: CupertinoIcons.refresh, + ), + ], ), - for (final session in group.sessions) _row(session), - ], - ], - ); - - Widget _row(JsonMap session) { - final id = '${session['id'] ?? ''}'; - final isClosed = session['closed_at'] != null; - final starred = session['starred'] == true; - return ListTile( - leading: Icon( - session['running'] == true - ? Icons.sync - : starred - ? Icons.star - : Icons.chat_bubble_outline, - ), - title: Text(chatSessionTitle(session)), - subtitle: Text( - '${session['directory'] ?? ''}${session['running'] == true - ? ' · Streaming' - : session['unseen'] == true - ? ' · New' - : ''}', - ), - onTap: () => widget.onOpen(session), - trailing: PopupMenuButton( - tooltip: 'Chat actions', - onSelected: (value) { - if (value == 'rename') { - _rename(session); - } - if (value == 'star') { - _mutate((id) => _repository.star(id, !starred), id); - } - if (value == 'close') { - _mutate(_repository.close, id); - } - if (value == 'reopen') { - _mutate(_repository.reopen, id); - } - }, - itemBuilder: (_) => [ - const PopupMenuItem(value: 'rename', child: Text('Rename')), - PopupMenuItem( - value: 'star', - child: Text(starred ? 'Remove from Starred' : 'Star'), + body: body, + floatingActionButton: FloatingActionButton.extended( + key: const Key('chat-new-chat-fab'), + onPressed: _newChat, + icon: const Icon(Icons.add), + label: const Text('New chat'), ), - if (isClosed) - const PopupMenuItem(value: 'reopen', child: Text('Reopen')) - else - const PopupMenuItem(value: 'close', child: Text('Close')), - ], - ), + ); + }, ); } } diff --git a/app/lib/features/chat/ui/sessions/create_chat_dialog.dart b/app/lib/features/chat/ui/sessions/create_chat_dialog.dart new file mode 100644 index 00000000..6a0e2617 --- /dev/null +++ b/app/lib/features/chat/ui/sessions/create_chat_dialog.dart @@ -0,0 +1,222 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../data/chat_repository.dart'; +import 'chat_adaptive.dart'; +import 'chat_create_fields.dart'; + +class ChatDraft { + const ChatDraft({ + required this.title, + required this.directory, + required this.backend, + required this.instructions, + }); + + final String title; + final String directory; + final String backend; + final String instructions; +} + +Future showChatCreateDialog( + BuildContext context, { + required ChatRepository repository, +}) { + final dialog = CreateChatDialog(repository: repository); + return chatControlsStyleOf(context) == ChatControlsStyle.cupertino + ? showCupertinoDialog(context: context, builder: (_) => dialog) + : showDialog(context: context, builder: (_) => dialog); +} + +class CreateChatDialog extends StatefulWidget { + const CreateChatDialog({super.key, required this.repository}); + + final ChatRepository repository; + + @override + State createState() => _CreateChatDialogState(); +} + +class _CreateChatDialogState extends State { + final _name = TextEditingController(text: 'New chat'); + final _instructions = TextEditingController(); + List _directories = const []; + List _backends = const []; + String? _directory; + String? _backend; + String? _catalogError; + String? _formError; + bool _loading = true; + int _attempt = 0; + + @override + void initState() { + super.initState(); + _loadCatalog(); + } + + @override + void dispose() { + _attempt++; + _name.dispose(); + _instructions.dispose(); + super.dispose(); + } + + Future _loadCatalog() async { + final attempt = ++_attempt; + setState(() { + _loading = true; + _catalogError = null; + }); + try { + final values = await Future.wait([ + widget.repository.directories(), + widget.repository.backends(), + ]); + if (!mounted || attempt != _attempt) return; + setState(() { + _directories = values[0]; + _backends = values[1]; + _directory = _directories.contains(_directory) + ? _directory + : _directories.isEmpty + ? null + : _directories.first; + _backend = _backends.contains(_backend) + ? _backend + : _backends.isEmpty + ? null + : _backends.first; + _loading = false; + }); + } catch (error) { + if (!mounted || attempt != _attempt) return; + setState(() { + _catalogError = '$error'; + _loading = false; + }); + } + } + + bool get _catalogReady => + !_loading && + _catalogError == null && + _directories.isNotEmpty && + _backends.isNotEmpty; + + void _submit() { + if (!_catalogReady) 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, + ), + ); + } + + @override + Widget build(BuildContext context) { + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final content = SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (cupertino) + CupertinoTextField( + key: const Key('chat-create-name'), + controller: _name, + placeholder: 'Name', + ) + else + TextField( + key: const Key('chat-create-name'), + controller: _name, + decoration: const InputDecoration(labelText: 'Name'), + ), + const SizedBox(height: 12), + ChatCatalogFields( + loading: _loading, + error: _catalogError, + directories: _directories, + backends: _backends, + directory: _directory, + backend: _backend, + onDirectory: (value) => setState(() => _directory = value), + onBackend: (value) => setState(() => _backend = value), + onRetry: _loadCatalog, + ), + if (_catalogReady) ...[ + const SizedBox(height: 8), + const Text('New chats use the server default model.'), + ], + const SizedBox(height: 12), + if (cupertino) + CupertinoTextField( + key: const Key('chat-create-instructions'), + controller: _instructions, + placeholder: 'Instructions', + minLines: 1, + maxLines: 3, + ) + else + TextField( + key: const Key('chat-create-instructions'), + controller: _instructions, + decoration: const InputDecoration(labelText: 'Instructions'), + minLines: 1, + maxLines: 3, + ), + if (_formError != null) ...[ + const SizedBox(height: 8), + Text(_formError!), + ], + ], + ), + ); + + 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'), + content: content, + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: _catalogReady ? _submit : null, + child: const Text('Create'), + ), + ], + ); + } +} diff --git a/app/lib/features/chat/ui/sessions/rename_chat_dialog.dart b/app/lib/features/chat/ui/sessions/rename_chat_dialog.dart new file mode 100644 index 00000000..9dd0000d --- /dev/null +++ b/app/lib/features/chat/ui/sessions/rename_chat_dialog.dart @@ -0,0 +1,107 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +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)); + return chatControlsStyleOf(context) == ChatControlsStyle.cupertino + ? showCupertinoDialog(context: context, builder: (_) => dialog) + : showDialog(context: context, builder: (_) => dialog); +} + +class _RenameChatDialog extends StatefulWidget { + const _RenameChatDialog({required this.initialTitle}); + + final String initialTitle; + + @override + State<_RenameChatDialog> createState() => _RenameChatDialogState(); +} + +class _RenameChatDialogState extends State<_RenameChatDialog> { + late final TextEditingController _title = + TextEditingController(text: widget.initialTitle) + ..selection = TextSelection( + baseOffset: 0, + extentOffset: widget.initialTitle.length, + ); + + @override + void dispose() { + _title.dispose(); + super.dispose(); + } + + void _save() { + final title = _title.text.trim(); + if (title.isEmpty) return; + Navigator.pop(context, title); + } + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder( + valueListenable: _title, + builder: (context, value, _) { + final canSave = value.text.trim().isNotEmpty; + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { + return CupertinoAlertDialog( + title: const Text('Rename chat'), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + CupertinoTextField( + key: const Key('chat-rename-field'), + controller: _title, + autofocus: true, + placeholder: 'Name', + ), + const SizedBox(height: 8), + const Text('This name is shared with every device.'), + ], + ), + actions: [ + CupertinoDialogAction( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + CupertinoDialogAction( + isDefaultAction: true, + onPressed: canSave ? _save : null, + child: const Text('Save'), + ), + ], + ); + } + return AlertDialog( + 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, + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: canSave ? _save : null, + child: const Text('Save'), + ), + ], + ); + }, + ); + } +} diff --git a/app/lib/features/chat/ui/sessions/session_actions.dart b/app/lib/features/chat/ui/sessions/session_actions.dart new file mode 100644 index 00000000..f70a20b2 --- /dev/null +++ b/app/lib/features/chat/ui/sessions/session_actions.dart @@ -0,0 +1,161 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../../core/api_gateway.dart'; +import '../../domain/chat_sessions.dart'; +import 'chat_adaptive.dart'; +import 'session_row_style.dart'; + +enum SessionAction { rename, close, reopen } + +/// The close confirmation's body, matching the web client's explanation. +String closeChatConfirmation(String title) => + 'Closes "$title" and marks it closed on every device. ' + 'A turn that is running is stopped first. ' + 'Nothing is deleted — the chat and its history are kept, ' + 'and you can reopen it from the list.'; + +class SessionStarButton extends StatelessWidget { + const SessionStarButton({ + super.key, + required this.session, + required this.onPressed, + }); + + final JsonMap session; + final VoidCallback onPressed; + + @override + Widget build(BuildContext context) { + final starred = session['starred'] == true; + final label = starred ? 'Unstar chat' : 'Star chat'; + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { + return Semantics( + label: label, + button: true, + child: CupertinoButton( + padding: EdgeInsets.zero, + onPressed: onPressed, + child: Icon(starred ? CupertinoIcons.star_fill : CupertinoIcons.star), + ), + ); + } + return IconButton( + tooltip: label, + onPressed: onPressed, + icon: Icon(starred ? Icons.star : Icons.star_border), + ); + } +} + +class SessionActionsButton extends StatelessWidget { + const SessionActionsButton({ + super.key, + required this.session, + required this.onSelected, + this.duplicateTitles = const {}, + }); + + final JsonMap session; + final ValueChanged onSelected; + final Set duplicateTitles; + + @override + Widget build(BuildContext context) { + final label = sessionActionsLabel(session, duplicateTitles); + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { + return Semantics( + label: label, + button: true, + child: CupertinoButton( + padding: EdgeInsets.zero, + onPressed: () => _showSheet(context), + child: const Icon(CupertinoIcons.ellipsis), + ), + ); + } + return PopupMenuButton( + tooltip: label, + onSelected: onSelected, + itemBuilder: (context) => _menuItems(session), + ); + } + + Future _showSheet(BuildContext context) async { + final action = await showCupertinoModalPopup( + context: context, + builder: (sheetContext) => CupertinoActionSheet( + title: Text(chatSessionTitle(session)), + actions: [ + for (final item in _items(session)) + CupertinoActionSheetAction( + onPressed: () => Navigator.pop(sheetContext, item.action), + child: Text(item.label), + ), + ], + cancelButton: CupertinoActionSheetAction( + onPressed: () => Navigator.pop(sheetContext), + child: const Text('Cancel'), + ), + ), + ); + if (action != null && context.mounted) onSelected(action); + } +} + +List> _menuItems(JsonMap session) => [ + for (final item in _items(session)) + PopupMenuItem(value: item.action, child: Text(item.label)), +]; + +List<({SessionAction action, String label})> _items(JsonMap session) { + final isClosed = session['closed_at'] != null; + return [ + (action: SessionAction.rename, label: 'Rename…'), + isClosed + ? (action: SessionAction.reopen, label: 'Reopen') + : (action: SessionAction.close, label: 'Close chat…'), + ]; +} + +Future confirmCloseChat(BuildContext context, JsonMap session) async { + final title = chatSessionTitle(session); + final body = closeChatConfirmation(title); + final confirmed = chatControlsStyleOf(context) == ChatControlsStyle.cupertino + ? await showCupertinoDialog( + context: context, + builder: (context) => CupertinoAlertDialog( + title: const Text('Close chat?'), + content: Text(body), + actions: [ + CupertinoDialogAction( + onPressed: () => Navigator.pop(context, false), + child: const Text('Cancel'), + ), + CupertinoDialogAction( + isDestructiveAction: true, + onPressed: () => Navigator.pop(context, true), + child: const Text('Close chat'), + ), + ], + ), + ) + : await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Close chat?'), + content: Text(body), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: () => Navigator.pop(context, true), + child: const Text('Close chat'), + ), + ], + ), + ); + return confirmed == true; +} diff --git a/app/lib/features/chat/ui/sessions/session_list_cupertino.dart b/app/lib/features/chat/ui/sessions/session_list_cupertino.dart new file mode 100644 index 00000000..a6f6456b --- /dev/null +++ b/app/lib/features/chat/ui/sessions/session_list_cupertino.dart @@ -0,0 +1,134 @@ +import 'package:flutter/cupertino.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'; + +class CupertinoSessionList extends StatelessWidget { + const CupertinoSessionList({ + super.key, + required this.sections, + required this.emptyMessage, + required this.duplicateTitles, + required this.onOpen, + required this.onRename, + required this.onClose, + required this.onReopen, + required this.onStar, + required this.onClearSearch, + }); + + final List sections; + final String? emptyMessage; + final Set duplicateTitles; + final ValueChanged onOpen; + final ValueChanged onRename; + final ValueChanged onClose; + final ValueChanged onReopen; + final ValueChanged onStar; + final VoidCallback? onClearSearch; + + @override + Widget build(BuildContext context) { + return ListView( + padding: const EdgeInsets.only(bottom: 24), + children: [ + for (final section in sections) ..._section(section), + if (emptyMessage != null) + ChatCupertinoMessage( + message: emptyMessage!, + actionLabel: onClearSearch == null ? null : 'Clear search', + onAction: onClearSearch, + ), + ], + ); + } + + List _section(ChatSessionSection section) { + final groups = groupChatSessions(section.sessions); + return [ + for (final group in groups) + CupertinoListSection.insetGrouped( + header: Text( + groups.length > 1 + ? '${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, + ), + ], + ), + ]; + } +} + +class _CupertinoSessionRow extends StatelessWidget { + const _CupertinoSessionRow({ + required this.session, + required this.duplicateTitles, + required this.onOpen, + required this.onRename, + required this.onClose, + required this.onReopen, + required this.onStar, + }); + + final JsonMap session; + final Set duplicateTitles; + final ValueChanged onOpen; + final ValueChanged onRename; + final ValueChanged onClose; + final ValueChanged onReopen; + final ValueChanged onStar; + + @override + Widget build(BuildContext context) { + final id = '${session['id'] ?? ''}'; + return CupertinoListTile( + key: Key('chat-row-$id'), + leading: Icon(sessionCupertinoIcon(session)), + title: Text(chatSessionTitle(session)), + subtitle: Text(sessionSubtitle(session)), + onTap: () => onOpen(session), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + SessionStarButton( + key: Key('chat-star-$id'), + session: session, + onPressed: () => onStar(session), + ), + SessionActionsButton( + key: Key('chat-actions-$id'), + session: session, + duplicateTitles: duplicateTitles, + onSelected: _select, + ), + ], + ), + ); + } + + void _select(SessionAction action) { + switch (action) { + case SessionAction.rename: + onRename(session); + case SessionAction.close: + onClose(session); + case SessionAction.reopen: + onReopen(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 new file mode 100644 index 00000000..d05cc6e7 --- /dev/null +++ b/app/lib/features/chat/ui/sessions/session_list_material.dart @@ -0,0 +1,140 @@ +import 'package:flutter/material.dart'; + +import '../../../../core/api_gateway.dart'; +import '../../domain/chat_sessions.dart'; +import 'chat_sessions_body.dart'; +import 'session_actions.dart'; +import 'session_row_style.dart'; + +class MaterialSessionList extends StatelessWidget { + const MaterialSessionList({ + super.key, + required this.sections, + required this.emptyMessage, + required this.duplicateTitles, + required this.onOpen, + required this.onRename, + required this.onClose, + required this.onReopen, + required this.onStar, + required this.onClearSearch, + }); + + final List sections; + final String? emptyMessage; + final Set duplicateTitles; + final ValueChanged onOpen; + final ValueChanged onRename; + final ValueChanged onClose; + final ValueChanged onReopen; + final ValueChanged onStar; + final VoidCallback? onClearSearch; + + @override + Widget build(BuildContext context) { + return ListView( + children: [ + for (final section in sections) _section(section), + if (emptyMessage != null) + ListTile( + title: Text(emptyMessage!), + trailing: onClearSearch == null + ? null + : TextButton( + onPressed: onClearSearch, + child: const Text('Clear search'), + ), + ), + ], + ); + } + + Widget _section(ChatSessionSection section) { + final groups = groupChatSessions(section.sessions); + return ExpansionTile( + title: Text(section.title), + initiallyExpanded: true, + children: [ + for (final group in groups) ...[ + if (groups.length > 1) + ListTile( + dense: true, + leading: const Icon(Icons.folder_outlined), + title: Text( + 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, + ), + ], + ], + ); + } +} + +class _MaterialSessionRow extends StatelessWidget { + const _MaterialSessionRow({ + required this.session, + required this.duplicateTitles, + required this.onOpen, + required this.onRename, + required this.onClose, + required this.onReopen, + required this.onStar, + }); + + final JsonMap session; + final Set duplicateTitles; + final ValueChanged onOpen; + final ValueChanged onRename; + final ValueChanged onClose; + final ValueChanged onReopen; + final ValueChanged onStar; + + @override + Widget build(BuildContext context) { + final id = '${session['id'] ?? ''}'; + return ListTile( + key: Key('chat-row-$id'), + leading: Icon(sessionMaterialIcon(session)), + title: Text(chatSessionTitle(session)), + subtitle: Text(sessionSubtitle(session)), + onTap: () => onOpen(session), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + SessionStarButton( + key: Key('chat-star-$id'), + session: session, + onPressed: () => onStar(session), + ), + SessionActionsButton( + key: Key('chat-actions-$id'), + session: session, + duplicateTitles: duplicateTitles, + onSelected: (action) => _select(action), + ), + ], + ), + ); + } + + void _select(SessionAction action) { + switch (action) { + case SessionAction.rename: + onRename(session); + case SessionAction.close: + onClose(session); + case SessionAction.reopen: + onReopen(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 new file mode 100644 index 00000000..59b8f4b3 --- /dev/null +++ b/app/lib/features/chat/ui/sessions/session_row_style.dart @@ -0,0 +1,51 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../../core/api_gateway.dart'; +import '../../domain/chat_sessions.dart'; + +/// Titles shared by more than one visible session, so row action labels can +/// add the session id the way the web client does. +Set duplicateChatTitles(Iterable sessions) { + final seen = {}; + final duplicates = {}; + for (final session in sessions) { + final title = chatSessionTitle(session); + if (!seen.add(title)) duplicates.add(title); + } + return duplicates; +} + +String sessionActionsLabel(JsonMap session, Set duplicateTitles) { + final title = chatSessionTitle(session); + return duplicateTitles.contains(title) + ? 'Chat actions for $title (${session['id'] ?? ''})' + : 'Chat actions for $title'; +} + +String sessionSubtitle(JsonMap session) { + final directory = '${session['directory'] ?? ''}'; + switch (chatSessionActivity( + running: session['running'] == true, + unseen: session['unseen'] == true, + )) { + case 'streaming': + return '$directory · Streaming'; + case 'new': + return '$directory · New'; + default: + return directory; + } +} + +IconData sessionMaterialIcon(JsonMap session) { + if (session['running'] == true) return Icons.sync; + if (session['starred'] == true) return Icons.star; + return Icons.chat_bubble_outline; +} + +IconData sessionCupertinoIcon(JsonMap session) { + if (session['running'] == true) return CupertinoIcons.arrow_2_circlepath; + if (session['starred'] == true) return CupertinoIcons.star_fill; + return CupertinoIcons.chat_bubble; +} diff --git a/app/notes/C1b.md b/app/notes/C1b.md new file mode 100644 index 00000000..cd1d56c3 --- /dev/null +++ b/app/notes/C1b.md @@ -0,0 +1,163 @@ +# C1b — Chat session browser completion + +The 406-line sessions screen is split into a controller, adaptive primitives, +session groups/rows, action dialogs, a rename dialog and a create dialog. The +server directory and backend catalogs, the instructions field, the closed/star +grouping and the distinct empty/no-match states are retained. No repository, +domain, shell or pubspec file changed. + +The UI review's must-fix is addressed: Cupertino no-match, empty and error +messages are no longer forced through `CupertinoListTile`'s one-line title. They +use a wrapping grouped card with `Clear search`/`Retry` as separate buttons. The +same turn also fixed the related behavioural findings: a failed initial load no +longer also shows the empty-server message, creating a chat opens it without +waiting for the list refresh, blank rename disables Save, and row action labels +name their session (adding the id when titles repeat). + +The second UI review's must-fixes are also addressed: + +- `ChatCupertinoMessage` now sets `DefaultTextStyle.merge` from + `CupertinoTheme.of(context).textTheme.textStyle`. Mounted under a bare + `MaterialApp` (the screen's iOS/macOS path, no `Material` ancestor), its text + previously inherited MaterialApp's intentional "missing Material" fallback + style (48px red monospace with a double yellow underline). The card now + renders as ordinary Cupertino body text in that configuration. +- The Material rename dialog sets `helperMaxLines: 2`, so "This name is shared + with every device." wraps instead of being ellipsised at 2.0x text scale. + +## Source layout + +All paths under `lib/features/chat/ui/sessions/` (1,584 lines total): + +| File | Lines | Responsibility | +| --- | ---: | --- | +| `chat_sessions_screen.dart` | 176 | Screen composition, toolbar/FAB, controller wiring | +| `chat_sessions_controller.dart` | 111 | List state, generation-guarded refresh, row actions, create | +| `chat_sessions_body.dart` | 97 | Filtering, starred/open/closed sections, duplicate titles | +| `session_list_material.dart` | 140 | Material list sections and rows | +| `session_list_cupertino.dart` | 134 | Cupertino list sections and rows | +| `session_row_style.dart` | 51 | Shared subtitle, icons and action labels | +| `session_actions.dart` | 161 | Star control, actions menu/sheet, close confirmation | +| `rename_chat_dialog.dart` | 107 | Rename dialog and its blank-name guard | +| `create_chat_dialog.dart` | 222 | Create state, draft fields, submit | +| `chat_create_fields.dart` | 185 | Catalog loading/error/retry and directory/backend pickers | +| `chat_adaptive.dart` | 200 | Style detection, bar actions, search, wrapping message card, loading | + +`chatControlsStyleOf` chooses Cupertino for a Cupertino app (no `MaterialApp` +ancestor) and for iOS/macOS Material themes; Material otherwise. The Cupertino +branch uses only Cupertino controls (`CupertinoPageScaffold`, +`CupertinoNavigationBar`, `CupertinoSearchTextField`, `CupertinoListSection`/ +`CupertinoListTile`, `CupertinoAlertDialog`, `CupertinoActionSheet`, +`CupertinoTextField`, `CupertinoActivityIndicator`). It therefore has no +Material ancestor dependency. The `SafeArea` in that branch keeps the search +field below the translucent navigation bar (the first browser capture caught +this overlap). + +Behavior: + +- `chat_sessions`, `chat_directories`, `chat_backends` and `chat_create` use the + existing repository envelopes; no fallback directory or backend is invented. +- A catalog failure keeps the dialog open, shows the server reason with Retry, + and retains the typed name and instructions. +- Closed starred rows appear once, only under Closed. +- Directory headings appear only when a section has more than one directory. +- Empty and search-no-match states stay distinct; "Clear search" restores the + list. In the Cupertino branch the message and its action are a wrapping + `ChatCupertinoMessage` card, and a failed load uses the same card for the + server reason with Retry. The failed initial load no longer also renders the + empty-server message. The card supplies a Cupertino text style, so it renders + normally when the Cupertino branch is mounted under the app's bare + `MaterialApp` root instead of a `Material`/`CupertinoApp`. +- Creating a chat opens it as soon as `chat_create` replies; the list refresh + continues in the background, so a slow listing cannot look like a failed + create. +- Star, rename, close (with the web's confirmation wording), reopen and row + opening keep their existing request shapes. Save is disabled while the + rename name is blank, matching the web dialog. +- Row action labels are `Chat actions for {title}`, adding `({id})` when two + visible sessions share a title, matching the web's accessible label. + +## Checks (actual) + +- `flutter test test/features/chat/ui/sessions`: 24 widget tests, all passed. + They cover Material and Cupertino list branches, both create branches, the + delayed catalog failure with draft retention and Retry, rename/close/reopen/ + star, blank-name Save disabling in both branches, the close confirmation, + catalog-empty state, stale refresh ordering, dispose while a reply is + pending, opening a created chat before the refresh completes, Cupertino + no-match/error wrapping (including 2x text scale), separate Clear search + semantics, duplicate-title action labels, the Cupertino message card under a + bare `MaterialApp` iOS theme (empty, no-match, long error style), and the + Material rename helper at 2x text scale. The three MaterialApp-hosted tests + fail when the `DefaultTextStyle` merge is removed (verified). +- `flutter test`: 46 tests passed. +- `flutter analyze`: no issues. +- `flutter build web`: built `lib/main.dart` successfully. +- Fixture probe built for both variants and run in real headless Chrome through + the local loopback server in `tool/chat_sessions_probe.mjs`. Each run loaded + the list, opened the create dialog, confirmed the rendered catalog controls, + opened a row action menu/sheet, and captured PNGs. The probe now clicks the + per-session action label and requires `Rename…` in the action labels instead + of accepting the dismiss barrier. Material and Cupertino PNGs were inspected. + +Captures from this turn's fix (shared with later stages under +`public/c1b-fix/`): + +- `/Users/alan/.local/share/pipelines/data/artifacts/42/public/c1b-fix/cupertino-fix-search-no-match.png` — light, 390x844, long query wraps in full with Clear search on its own line. +- `.../cupertino-fix-search-no-match-dark.png` — same state in dark appearance. +- `.../cupertino-fix-load-error.png` — long server reason wraps; Retry is separate and the empty-server message is absent. +- `.../cupertino-fix-list-phone.png` and `.../material-fix-actions.png` — probe list and actions after the label change. + +Probe commands (run from `app/`): + +```sh +flutter build web -t tool/chat_sessions_probe_entry.dart \ + --dart-define=CHAT_PROBE_STYLE=material --output build/probe-material-fix +PROBE_WEB_ROOT="$PWD/build/probe-material-fix" PROBE_VARIANT=material \ + OPENCODE_ARTIFACT_DIR=/private/var/folders/jp/q0qvjyg54fl_c5vhhk1ylz2m0000gn/T/opencode/chat-sessions-capture \ + node tool/chat_sessions_probe.mjs +# repeat with CHAT_PROBE_STYLE=cupertino and build/probe-cupertino-fix +``` + +Captures for the second review's fixes (same `public/c1b-fix/` folder, real +headless Chrome at 390x844 through a temporary fixture entry that was deleted +afterwards; the shipped probe entry was not changed): + +- `platform-default-empty-phone.png` — `MaterialApp` default theme (macOS → + Cupertino branch), empty server. The message is ordinary body text. +- `platform-default-search-no-match-phone.png` — long query; message wraps and + `Clear search` is a separate control. +- `platform-default-error-phone.png` — long server reason wraps; `Retry` is + separate and no empty-server message appears. +- `material-scale2-rename-phone.png` — Material rename dialog at 2.0x text + scale; the helper sentence wraps onto two lines in full. + +## Not changed in this turn + +These review notes remain advisory and were left alone because they predate +C1b or are native behaviour: + +- The Material FAB can still cover the last row's star/actions when the list + exactly fills a phone viewport. Same as the base screen. +- Raw exception text (`Bad state: …`, `Exception: …`) is still shown to the + operator; wording belongs to a separate error-presentation change. +- Cupertino row titles/subtitles still truncate to one line (standard + `CupertinoListTile` behaviour). The no-match/error messages no longer do. +- The Cupertino-under-MaterialApp probe still takes its accent from the ambient + `ThemeData`. No theme override was added. + +## Remaining gaps + +- Mobile is unverified: no Android/iOS builds, devices or installs were run. + Source is portable but only web was exercised. +- Browser evidence uses the fixture gateway, not an authenticated live server. + No real chat was created, renamed, closed or starred in the browser; those + request paths are covered by widget tests. +- The Cupertino list/actions probes use the local Chrome dark appearance; the + no-match fix was captured in both light and dark. The long-error capture came + from a temporary private fixture entry that was deleted afterwards. +- The create dialog still omits the web's default instruction text and its + backend segmented control; it preserves the existing name/directory/backend/ + instructions request fields. +- This stage did not commit. The changes remain an uncommitted working-tree + candidate for the next stage. diff --git a/app/test/features/chat/ui/sessions/chat_create_dialog_test.dart b/app/test/features/chat/ui/sessions/chat_create_dialog_test.dart new file mode 100644 index 00000000..0b1b8b2e --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_create_dialog_test.dart @@ -0,0 +1,217 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.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( + 'material create dialog retains the draft through a delayed catalog failure and retry', + (tester) async { + final gateway = FakeChatGateway(); + final directories = Completer(); + gateway.directoriesHandler = () => directories.future; + JsonMap? opened; + await pumpMaterialChat( + tester, + gateway, + onOpen: (session) => opened = session, + ); + + await tester.tap(find.byKey(const Key('chat-new-chat-fab'))); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + expect(find.text('Loading directories…'), findsOneWidget); + + await tester.enterText( + find.byKey(const Key('chat-create-name')), + 'Draft chat', + ); + await tester.enterText( + find.byKey(const Key('chat-create-instructions')), + 'Keep me', + ); + + directories.completeError( + StateError('Server did not return chat directories.'), + ); + await tester.pump(); + await tester.pump(); + expect( + find.textContaining('Unable to load chat options'), + findsOneWidget, + ); + expect(find.text('Draft chat'), findsOneWidget); + expect(find.text('Keep me'), findsOneWidget); + + gateway.directoriesHandler = () async => { + 'chat_directories': ['/work'], + }; + await tester.tap(find.text('Retry')); + await tester.pumpAndSettle(); + expect(find.textContaining('Unable to load chat options'), findsNothing); + expect( + find.byKey(const Key('chat-create-server-directory')), + findsOneWidget, + ); + expect( + find.text('New chats use the server default model.'), + findsOneWidget, + ); + + await tester.enterText(find.byKey(const Key('chat-create-name')), ''); + await tester.tap(find.text('Create')); + await tester.pump(); + expect(find.text('Enter a name and server directory.'), findsOneWidget); + expect(gateway.count('chat_create'), 0); + + await tester.enterText( + find.byKey(const Key('chat-create-name')), + 'Draft chat', + ); + await tester.tap(find.text('Create')); + await tester.pumpAndSettle(); + + final fields = + gateway.lastFields('chat_create')!['chat_create']! as JsonMap; + expect(fields['title'], 'Draft chat'); + expect(fields['directory'], '/work'); + expect(fields.containsKey('backend'), isFalse); + expect(fields['instructions'], 'Keep me'); + expect(fields.containsKey('operation_id'), isTrue); + expect(opened?['id'], 'created'); + }, + ); + + testWidgets('Cupertino create dialog keeps the draft when catalogs fail', ( + tester, + ) async { + final gateway = FakeChatGateway(); + gateway.directoriesHandler = () => + Future.error(StateError('Server did not return chat directories.')); + await pumpCupertinoChat(tester, gateway); + + await tester.tap(find.byKey(const Key('chat-new-chat'))); + await tester.pumpAndSettle(); + expect(find.textContaining('Unable to load chat options'), findsOneWidget); + + await tester.enterText( + find.byKey(const Key('chat-create-name')), + 'Cupertino draft', + ); + await tester.enterText( + find.byKey(const Key('chat-create-instructions')), + 'Keep me too', + ); + expect(find.text('Cupertino draft'), findsOneWidget); + expect(find.text('Keep me too'), findsOneWidget); + + gateway.directoriesHandler = () async => { + 'chat_directories': ['/work'], + }; + await tester.tap(find.text('Retry')); + await tester.pumpAndSettle(); + expect(find.textContaining('Unable to load chat options'), findsNothing); + expect(find.text('Cupertino draft'), findsOneWidget); + expect(find.text('Keep me too'), findsOneWidget); + }); + + testWidgets('material create dialog reports an empty catalog', ( + tester, + ) async { + final gateway = FakeChatGateway(); + gateway.directoriesHandler = () async => {'chat_directories': []}; + await pumpMaterialChat(tester, gateway); + + await tester.tap(find.byKey(const Key('chat-new-chat-fab'))); + await tester.pumpAndSettle(); + expect( + find.text('The server has no chat directories or backends available.'), + findsOneWidget, + ); + }); + + testWidgets('Cupertino create dialog uses native selectors and fields', ( + tester, + ) async { + final gateway = FakeChatGateway(); + JsonMap? opened; + await pumpCupertinoChat( + tester, + gateway, + onOpen: (session) => opened = session, + ); + + await tester.tap(find.byKey(const Key('chat-new-chat'))); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.text('Server directory: /work'), findsOneWidget); + expect(find.text('Backend: opencode'), findsOneWidget); + + await tester.tap(find.byKey(const Key('chat-create-backend'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('codex')); + await tester.pumpAndSettle(); + expect(find.text('Backend: codex'), findsOneWidget); + + await tester.tap(find.byKey(const Key('chat-create-server-directory'))); + await tester.pumpAndSettle(); + expect(find.text('/archive'), findsOneWidget); + await tester.tap(find.text('/archive')); + await tester.pumpAndSettle(); + expect(find.text('Server directory: /archive'), findsOneWidget); + + await tester.enterText( + find.byKey(const Key('chat-create-name')), + 'Cupertino draft', + ); + await tester.enterText( + find.byKey(const Key('chat-create-instructions')), + 'Be careful', + ); + await tester.tap(find.text('Create')); + await tester.pumpAndSettle(); + + final fields = + gateway.lastFields('chat_create')!['chat_create']! as JsonMap; + expect(fields['title'], 'Cupertino draft'); + expect(fields['directory'], '/archive'); + expect(fields['backend'], 'codex'); + expect(fields['instructions'], 'Be careful'); + expect(opened?['id'], 'created'); + }); + + testWidgets('a created chat opens before the list refresh completes', ( + tester, + ) async { + final gateway = FakeChatGateway(); + JsonMap? opened; + await pumpMaterialChat( + tester, + gateway, + onOpen: (session) => opened = session, + ); + + final refresh = Completer(); + gateway.pendingSessions.add(refresh); + 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.pump(const Duration(milliseconds: 300)); + + expect(gateway.count('chat_create'), 1); + expect(gateway.count('chat_sessions'), 2); + expect( + opened?['id'], + 'created', + reason: 'a slow listing must not hold up opening the new chat', + ); + + refresh.complete({'chat_sessions': []}); + await tester.pumpAndSettle(); + }); +} diff --git a/app/test/features/chat/ui/sessions/chat_cupertino_theme_test.dart b/app/test/features/chat/ui/sessions/chat_cupertino_theme_test.dart new file mode 100644 index 00000000..b16bcc73 --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_cupertino_theme_test.dart @@ -0,0 +1,91 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'chat_test_harness.dart'; +import 'fake_chat_gateway.dart'; + +/// The message card is also mounted under a bare `MaterialApp` (the screen's +/// iOS/macOS path). Without its own style, `Text` inherits MaterialApp's +/// "missing Material" fallback: 48px, red, monospace with a double underline. +void main() { + testWidgets('Cupertino empty message under MaterialApp uses normal text', ( + tester, + ) async { + usePhoneSurface(tester); + await pumpIosMaterialChat(tester, FakeChatGateway()); + + expect(find.byType(CupertinoPageScaffold), findsOneWidget); + expect(find.byType(Scaffold), findsNothing); + + const message = 'No chat sessions on this server yet.'; + expect(find.text(message), findsOneWidget); + expectNormalTextStyle(tester, message); + }); + + testWidgets('Cupertino no-match message under MaterialApp wraps normally', ( + tester, + ) async { + usePhoneSurface(tester); + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()}; + await pumpIosMaterialChat(tester, gateway); + + await tester.enterText( + find.byType(CupertinoSearchTextField), + 'zzz-no-match-with-a-long-query', + ); + await tester.pumpAndSettle(); + + const message = 'No chats match "zzz-no-match-with-a-long-query".'; + expect(find.text(message), findsOneWidget); + expectNormalTextStyle(tester, message); + expect( + tester.renderObject(find.text(message)).size.height, + greaterThan(30), + reason: 'the query message must wrap instead of being cut to one line', + ); + expect( + find.widgetWithText(CupertinoButton, 'Clear search'), + findsOneWidget, + ); + }); + + testWidgets('Cupertino load error under MaterialApp uses normal text', ( + tester, + ) async { + usePhoneSurface(tester); + final gateway = FakeChatGateway() + ..sessionsHandler = () => Future.error( + StateError( + 'server unavailable while listing chat sessions for this operator', + ), + ); + await pumpIosMaterialChat(tester, gateway); + + const message = + 'Bad state: server unavailable while listing chat sessions ' + 'for this operator'; + expect(find.text(message), findsOneWidget); + expectNormalTextStyle(tester, message); + expect(find.text('No chat sessions on this server yet.'), findsNothing); + expect(find.widgetWithText(CupertinoButton, 'Retry'), findsOneWidget); + }); +} + +/// Resolves the style actually painted for [message] and checks it is the +/// ordinary Cupertino body style rather than MaterialApp's fallback style. +void expectNormalTextStyle(WidgetTester tester, String message) { + final paragraph = tester.renderObject(find.text(message)); + final style = paragraph.text.style!; + expect( + style.fontSize, + const CupertinoThemeData().textTheme.textStyle.fontSize, + reason: 'message should not use MaterialApp\'s 48px fallback style', + ); + expect(style.fontFamily, isNot('monospace')); + expect(style.fontWeight, isNot(FontWeight.w900)); + expect(style.decoration, isNot(TextDecoration.underline)); + expect(style.color, isNot(const Color(0xD0FF0000))); +} diff --git a/app/test/features/chat/ui/sessions/chat_session_actions_test.dart b/app/test/features/chat/ui/sessions/chat_session_actions_test.dart new file mode 100644 index 00000000..363b9768 --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_session_actions_test.dart @@ -0,0 +1,174 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; + +import 'chat_test_harness.dart'; +import 'fake_chat_gateway.dart'; + +void main() { + testWidgets('material row star, rename, close confirm and reopen', ( + tester, + ) async { + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()}; + 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}, + }); + + 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')), + ' Renamed chat ', + ); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + expect(gateway.lastFields('chat_rename'), { + 'chat_rename': {'session_id': 's2', 'title': 'Renamed chat'}, + }); + + await tester.tap(find.byKey(const Key('chat-actions-s2'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Close chat…')); + await tester.pumpAndSettle(); + expect(find.text('Close chat?'), findsOneWidget); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + expect(gateway.count('chat_close'), 0); + + 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(gateway.lastFields('chat_close'), { + 'chat_query': {'session_id': 's2'}, + }); + + await tester.ensureVisible(find.byKey(const Key('chat-actions-s4'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('chat-actions-s4'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Reopen')); + await tester.pumpAndSettle(); + expect(gateway.lastFields('chat_reopen'), { + 'chat_query': {'session_id': 's4'}, + }); + }); + + testWidgets('Cupertino close confirmation uses the action sheet flow', ( + tester, + ) async { + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()}; + await pumpCupertinoChat(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(); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect( + find.textContaining('marks it closed on every device'), + findsOneWidget, + ); + + await tester.tap(find.text('Close chat')); + await tester.pumpAndSettle(); + expect(gateway.lastFields('chat_close'), { + 'chat_query': {'session_id': 's2'}, + }); + }); + + testWidgets('material rename disables Save while the name is blank', ( + 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('Rename…')); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(const Key('chat-rename-field')), ' '); + await tester.pump(); + + final save = tester.widget( + find.widgetWithText(FilledButton, 'Save'), + ); + expect(save.onPressed, isNull); + expect(gateway.count('chat_rename'), 0); + }); + + testWidgets('Cupertino rename disables Save while the name is blank', ( + tester, + ) async { + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()}; + 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')), ' '); + await tester.pump(); + + final save = tester.widget( + find.widgetWithText(CupertinoDialogAction, 'Save'), + ); + expect(save.onPressed, isNull); + expect(gateway.count('chat_rename'), 0); + }); + + testWidgets('material rename helper wraps instead of truncating at 2x', ( + tester, + ) async { + usePhoneSurface(tester); + tester.platformDispatcher.textScaleFactorTestValue = 2; + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + 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('Rename…')); + await tester.pumpAndSettle(); + + const helper = 'This name is shared with every device.'; + expect(find.text(helper), findsOneWidget); + expect( + tester.widget(find.text(helper)).maxLines, + 2, + reason: 'helperMaxLines defaults to one, which truncates the sentence', + ); + expect(tester.takeException(), isNull); + }); + + testWidgets('opening a row calls onOpen with the server session', ( + tester, + ) async { + JsonMap? opened; + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()}; + await pumpMaterialChat( + tester, + gateway, + onOpen: (session) => opened = session, + ); + + await tester.tap(find.byKey(const Key('chat-row-s2'))); + await tester.pumpAndSettle(); + expect(opened?['id'], 's2'); + }); +} 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 new file mode 100644 index 00000000..c2df3dad --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_sessions_lifecycle_test.dart @@ -0,0 +1,76 @@ +import 'dart:async'; + +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 'fake_chat_gateway.dart'; + +void main() { + testWidgets('a stale refresh reply never replaces the latest listing', ( + tester, + ) async { + final gateway = FakeChatGateway(); + final first = Completer(); + final second = Completer(); + gateway.pendingSessions.addAll([first, second]); + + await tester.pumpWidget( + MaterialApp( + home: ChatSessionsScreen(gateway: gateway, onOpen: (_) {}), + ), + ); + await tester.pump(); + + await tester.tap(find.byKey(const Key('chat-refresh'))); + await tester.pump(); + expect(gateway.count('chat_sessions'), 2); + + second.complete({ + 'chat_sessions': [ + {'id': 'new', 'title': 'Newest chat'}, + ], + }); + await tester.pump(); + await tester.pump(); + expect(find.text('Newest chat'), findsOneWidget); + + first.complete({ + 'chat_sessions': [ + {'id': 'old', 'title': 'Older chat'}, + ], + }); + await tester.pump(); + await tester.pump(); + expect(find.text('Older chat'), findsNothing); + expect(find.text('Newest chat'), findsOneWidget); + }); + + testWidgets('a reply completing after dispose changes nothing', ( + tester, + ) async { + final gateway = FakeChatGateway(); + final pending = Completer(); + gateway.pendingSessions.add(pending); + + await tester.pumpWidget( + MaterialApp( + home: ChatSessionsScreen(gateway: gateway, onOpen: (_) {}), + ), + ); + await tester.pump(); + + await tester.pumpWidget(const MaterialApp(home: SizedBox())); + pending.complete({ + 'chat_sessions': [ + {'id': 'late', 'title': 'Late chat'}, + ], + }); + await tester.pump(); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(find.text('Late chat'), findsNothing); + }); +} diff --git a/app/test/features/chat/ui/sessions/chat_sessions_screen_test.dart b/app/test/features/chat/ui/sessions/chat_sessions_screen_test.dart new file mode 100644 index 00000000..dae24df2 --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_sessions_screen_test.dart @@ -0,0 +1,213 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'chat_test_harness.dart'; +import 'fake_chat_gateway.dart'; + +void main() { + testWidgets( + 'material list keeps closed starred rows once and groups directories once', + (tester) async { + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()}; + await pumpMaterialChat(tester, gateway); + + expect(find.text('Starred'), findsOneWidget); + expect(find.text('Chats'), findsNWidgets(2)); + expect(find.text('Closed'), findsOneWidget); + expect(find.text('Starred chat'), findsOneWidget); + expect(find.text('Starred closed'), findsOneWidget); + expect(find.text('Open chat'), findsOneWidget); + expect(find.byIcon(Icons.folder_outlined), findsNWidgets(4)); + expect(find.byType(Scaffold), findsOneWidget); + }, + ); + + testWidgets('material search distinguishes no-match and clears back', ( + tester, + ) async { + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()}; + await pumpMaterialChat(tester, gateway); + + await tester.enterText(find.byType(TextField), 'zzz'); + await tester.pumpAndSettle(); + expect(find.text('No chats match "zzz".'), findsOneWidget); + expect(find.text('Open chat'), findsNothing); + + await tester.tap(find.text('Clear search')); + await tester.pumpAndSettle(); + expect(find.text('Open chat'), findsOneWidget); + }); + + testWidgets('material empty server shows the distinct empty message', ( + tester, + ) async { + final gateway = FakeChatGateway(); + await pumpMaterialChat(tester, gateway); + expect(find.text('No chat sessions on this server yet.'), findsOneWidget); + expect(find.textContaining('No chats match'), findsNothing); + }); + + testWidgets( + 'Cupertino app renders standard controls, groups and renames without Material', + (tester) async { + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()}; + await pumpCupertinoChat(tester, gateway); + + expect(find.byType(CupertinoPageScaffold), findsOneWidget); + expect(find.byType(CupertinoSearchTextField), findsOneWidget); + expect(find.byType(Scaffold), findsNothing); + expect( + tester.getTopLeft(find.byType(CupertinoSearchTextField)).dy, + greaterThanOrEqualTo( + tester.getBottomLeft(find.byType(CupertinoNavigationBar)).dy, + ), + ); + expect(find.text('Chats · /work'), findsOneWidget); + expect(find.text('Chats · /else'), findsOneWidget); + + 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}, + }); + + await tester.tap(find.byKey(const Key('chat-actions-s2'))); + await tester.pumpAndSettle(); + expect(find.text('Rename…'), findsOneWidget); + await tester.tap(find.text('Rename…')); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + + await tester.enterText( + find.byKey(const Key('chat-rename-field')), + 'Renamed on Cupertino', + ); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + expect(gateway.lastFields('chat_rename'), { + 'chat_rename': {'session_id': 's2', 'title': 'Renamed on Cupertino'}, + }); + + await tester.tap(find.byKey(const Key('chat-actions-s4'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Reopen')); + await tester.pumpAndSettle(); + expect(gateway.lastFields('chat_reopen'), { + 'chat_query': {'session_id': 's4'}, + }); + }, + ); + + testWidgets( + 'Cupertino no-match message wraps and Clear search is its own button', + (tester) async { + usePhoneSurface(tester); + final semantics = tester.ensureSemantics(); + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()}; + await pumpCupertinoChat(tester, gateway); + + const query = 'zzz-no-match-with-a-long-query'; + await tester.enterText(find.byType(CupertinoSearchTextField), query); + await tester.pumpAndSettle(); + + const message = 'No chats match "zzz-no-match-with-a-long-query".'; + expect(find.text(message), findsOneWidget); + expect(find.text('Open chat'), findsNothing); + final messageBox = tester.renderObject(find.text(message)); + expect( + messageBox.size.height, + greaterThan(30), + reason: 'the query message must wrap instead of being cut to one line', + ); + + final clear = find.bySemanticsLabel('Clear search'); + expect(clear, findsOneWidget); + expect(tester.getSemantics(clear).label, 'Clear search'); + + await tester.tap(find.text('Clear search')); + await tester.pumpAndSettle(); + expect(find.text('Open chat'), findsOneWidget); + semantics.dispose(); + }, + ); + + testWidgets( + 'Cupertino load failure wraps the reason and hides the empty message', + (tester) async { + usePhoneSurface(tester); + final gateway = FakeChatGateway() + ..sessionsHandler = () => Future.error( + StateError( + 'server unavailable while listing chat sessions for this operator', + ), + ); + await pumpCupertinoChat(tester, gateway); + + const message = + 'Bad state: server unavailable while listing chat sessions ' + 'for this operator'; + expect(find.text(message), findsOneWidget); + expect(find.text('No chat sessions on this server yet.'), findsNothing); + final messageBox = tester.renderObject(find.text(message)); + expect( + messageBox.size.height, + greaterThan(30), + reason: 'the server reason must wrap instead of being cut to one line', + ); + expect(find.widgetWithText(CupertinoButton, 'Retry'), findsOneWidget); + }, + ); + + testWidgets('Cupertino no-match message survives 2x text scaling', ( + tester, + ) async { + usePhoneSurface(tester); + tester.platformDispatcher.textScaleFactorTestValue = 2; + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + final gateway = FakeChatGateway() + ..sessionsReply = {'chat_sessions': sampleSessions()}; + await pumpCupertinoChat(tester, gateway); + + await tester.enterText( + find.byType(CupertinoSearchTextField), + 'zzz-no-match-with-a-long-query', + ); + await tester.pumpAndSettle(); + + expect( + find.text('No chats match "zzz-no-match-with-a-long-query".'), + findsOneWidget, + ); + expect(find.text('Clear search'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('duplicate Cupertino titles disambiguate the action labels', ( + tester, + ) async { + final semantics = tester.ensureSemantics(); + final gateway = FakeChatGateway() + ..sessionsReply = { + 'chat_sessions': [ + {'id': 'd1', 'title': 'New chat', 'directory': '/work'}, + {'id': 'd2', 'title': 'New chat', 'directory': '/work'}, + ], + }; + await pumpCupertinoChat(tester, gateway); + + expect( + tester.getSemantics(find.byKey(const Key('chat-actions-d1'))).label, + 'Chat actions for New chat (d1)', + ); + expect( + tester.getSemantics(find.byKey(const Key('chat-actions-d2'))).label, + 'Chat actions for New chat (d2)', + ); + semantics.dispose(); + }); +} diff --git a/app/test/features/chat/ui/sessions/chat_test_harness.dart b/app/test/features/chat/ui/sessions/chat_test_harness.dart new file mode 100644 index 00000000..d56e3b81 --- /dev/null +++ b/app/test/features/chat/ui/sessions/chat_test_harness.dart @@ -0,0 +1,77 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_screen.dart'; + +import 'fake_chat_gateway.dart'; + +List sampleSessions() => [ + {'id': 's1', 'title': 'Starred chat', 'directory': '/work', 'starred': true}, + {'id': 's2', 'title': 'Open chat', 'directory': '/work'}, + {'id': 's3', 'title': 'Elsewhere chat', 'directory': '/else'}, + { + 'id': 's4', + 'title': 'Closed chat', + 'directory': '/else', + 'closed_at': '2026-01-01', + }, + { + 'id': 's5', + 'title': 'Starred closed', + 'directory': '/work', + 'starred': true, + 'closed_at': '2026-01-02', + }, +]; + +Future pumpMaterialChat( + WidgetTester tester, + FakeChatGateway gateway, { + ValueChanged? onOpen, +}) async { + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + home: ChatSessionsScreen(gateway: gateway, onOpen: onOpen ?? (_) {}), + ), + ); + await tester.pumpAndSettle(); +} + +Future pumpCupertinoChat( + WidgetTester tester, + FakeChatGateway gateway, { + ValueChanged? onOpen, +}) async { + await tester.pumpWidget( + CupertinoApp( + home: ChatSessionsScreen(gateway: gateway, onOpen: onOpen ?? (_) {}), + ), + ); + await tester.pumpAndSettle(); +} + +/// The screen's iOS/macOS path: Cupertino controls under the app's ordinary +/// `MaterialApp` root, with no Material or CupertinoTheme ancestor. +Future pumpIosMaterialChat( + WidgetTester tester, + FakeChatGateway gateway, { + ValueChanged? onOpen, +}) async { + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.iOS), + home: ChatSessionsScreen(gateway: gateway, onOpen: onOpen ?? (_) {}), + ), + ); + await tester.pumpAndSettle(); +} + +/// Narrows the test surface to a phone so long messages must wrap. +void usePhoneSurface(WidgetTester tester) { + tester.view.physicalSize = const Size(390, 844); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); +} diff --git a/app/test/features/chat/ui/sessions/fake_chat_gateway.dart b/app/test/features/chat/ui/sessions/fake_chat_gateway.dart new file mode 100644 index 00000000..6fa13aca --- /dev/null +++ b/app/test/features/chat/ui/sessions/fake_chat_gateway.dart @@ -0,0 +1,56 @@ +import 'dart:async'; +import 'dart:collection'; + +import 'package:pipelines_app/core/api_gateway.dart'; + +/// Scripted gateway for session-browser widget tests. +class FakeChatGateway implements ApiGateway { + final calls = <({String type, JsonMap fields})>[]; + final pendingSessions = Queue>(); + JsonMap sessionsReply = const {'chat_sessions': []}; + Future Function()? sessionsHandler; + JsonMap createReply = const { + 'chat_session': {'id': 'created', 'title': 'New chat'}, + }; + Future Function()? directoriesHandler; + Future Function()? backendsHandler; + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) { + calls.add((type: type, fields: fields)); + switch (type) { + case 'chat_sessions': + if (pendingSessions.isNotEmpty) { + return pendingSessions.removeFirst().future; + } + if (sessionsHandler != null) return sessionsHandler!(); + return Future.value(sessionsReply); + case 'chat_directories': + return directoriesHandler?.call() ?? + Future.value(const { + 'chat_directories': ['/work', '/archive'], + }); + case 'chat_backends': + return backendsHandler?.call() ?? + Future.value(const { + 'chat_backends': ['opencode', 'codex'], + }); + case 'chat_create': + return Future.value(createReply); + default: + return Future.value(const {}); + } + } + + int count(String type) => calls.where((call) => call.type == type).length; + + JsonMap? lastFields(String type) { + for (final call in calls.reversed) { + if (call.type == type) return call.fields; + } + return null; + } +} diff --git a/app/tool/chat_sessions_probe.mjs b/app/tool/chat_sessions_probe.mjs index 7fccb3fb..42935d24 100644 --- a/app/tool/chat_sessions_probe.mjs +++ b/app/tool/chat_sessions_probe.mjs @@ -5,9 +5,12 @@ import { once } from 'node:events'; import { setTimeout as delay } from 'node:timers/promises'; import { join, extname, resolve, sep } from 'node:path'; import { tmpdir } from 'node:os'; -import { mkdtemp, rm } from 'node:fs/promises'; +import { mkdir, mkdtemp, rm } from 'node:fs/promises'; -const root = join(process.cwd(), 'build/web'); +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'); +await mkdir(artifactDir, { recursive: true }); const mime = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm', '.png': 'image/png', '.ico': 'image/x-icon' }; const server = createServer(async (req, res) => { try { @@ -66,25 +69,40 @@ try { 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 clickLabel = async label => evaluate(`(() => { const e=[...document.querySelectorAll('flt-semantics')].find(x => (x.getAttribute('aria-label') || x.innerText || '') === ${JSON.stringify(label)}); if (!e) return false; e.click(); return true; })()`); + 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); + 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 data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).result.data; - await (await import('node:fs/promises')).writeFile(`${process.env.OPENCODE_ARTIFACT_DIR}/${name}.png`, Buffer.from(data, 'base64')); + 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'); - await delay(500); + 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.') || changedBody.includes('Open fixture')) throw new Error(`Create dialog did not change rendered body to catalog controls: ${changedBody}`); - await capture('chat-sessions-desktop', 1280, 800); - console.log(JSON.stringify({ labels, captures: ['chat-sessions-phone.png', 'chat-sessions-create-dialog.png', 'chat-sessions-desktop.png'], bodyChanged: true }, null, 2)); + 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)); } 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 648fd3bd..a0be1e08 100644 --- a/app/tool/chat_sessions_probe_entry.dart +++ b/app/tool/chat_sessions_probe_entry.dart @@ -1,3 +1,4 @@ +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:pipelines_app/core/api_gateway.dart'; @@ -55,8 +56,21 @@ class _FixtureGateway implements ApiGateway { } } -void main() => runApp( - MaterialApp( - home: ChatSessionsScreen(gateway: _FixtureGateway(), onOpen: (_) {}), - ), +const _probeStyle = String.fromEnvironment( + 'CHAT_PROBE_STYLE', + defaultValue: 'material', ); + +void main() { + final home = ChatSessionsScreen(gateway: _FixtureGateway(), onOpen: (_) {}); + if (_probeStyle == 'cupertino') { + runApp(CupertinoApp(home: home)); + return; + } + runApp( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + home: home, + ), + ); +}