diff --git a/app/lib/features/chat/conversation/chat_command_actions.dart b/app/lib/features/chat/conversation/chat_command_actions.dart new file mode 100644 index 00000000..58e85603 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_command_actions.dart @@ -0,0 +1,158 @@ +import '../../../core/api_gateway.dart'; +import '../../../core/error_reason.dart'; +import '../../../core/transport/connection_state.dart'; +import '../data/chat_repository.dart'; +import '../domain/chat_commands.dart'; + +/// Shows one local line in the conversation the command ran in. +typedef ChatCommandNoticeCallback = void Function(String text, {bool failed}); + +/// Hands a created session row to the destination with the line the new +/// conversation opens on. The destination owns navigation: it lists the row, +/// opens it and refreshes the list from the server. +typedef ChatCreatedSessionCallback = + void Function(JsonMap session, String notice); + +/// Runs the recorded commands that act on the open session: `/new`, `/close` +/// and `/rename `. +/// +/// Every outcome is a local notice, never a prompt. The requests are the +/// repository's existing create, close and rename calls, exactly as the list's +/// New chat dialog, Close chat confirm and Rename dialog send them. `/stop` and +/// `/help` are not run here; [runs] says which commands are. +class ChatCommandActions { + ChatCommandActions({ + required this.repository, + required this.sessionId, + required this.directory, + required this.showNotice, + required this.confirmClose, + required this.openCreatedSession, + this.onRenamed, + this.onClosed, + this.newOperationId, + }); + + final ChatRepository repository; + final String sessionId; + + /// The open session's recorded directory, blank when the row is unknown. + /// `/new` starts the created session there. + final String directory; + + final ChatCommandNoticeCallback showNotice; + + /// Opens the row's `Close chat?` confirm; false sends nothing. + final Future<bool> Function() confirmClose; + + final ChatCreatedSessionCallback openCreatedSession; + + /// The server accepted the shared rename with this trimmed title. + final void Function(String title)? onRenamed; + + /// The server accepted the close; the conversation is finished here too. + final void Function()? onClosed; + + /// Test/fixture seam; production mints one id per create intent. + final String Function()? newOperationId; + + /// Whether [command] is one this runner performs. + static bool runs(ChatCommand command) => const { + chatCommandNew, + chatCommandClose, + chatCommandRename, + }.contains(command.name); + + /// Performs [command] with the draft's trimmed [argument]. The caller has + /// already consumed the draft; a usage error here is a failed notice and + /// sends nothing. + Future<void> run(ChatCommand command, String argument) async { + if (!command.takesArgument && argument.isNotEmpty) { + showNotice(chatCommandArgumentReport(command), failed: true); + return; + } + switch (command.name) { + case chatCommandNew: + await _startSession(); + case chatCommandClose: + await _closeSession(); + case chatCommandRename: + await _renameSession(argument); + } + } + + /// `/new`: the existing `chat_create` with the web's fixed title and brief, + /// in this session's directory, with no backend or model field. The reply's + /// row is handed to the destination with the notice the new conversation + /// opens on; a refusal stays in this conversation. + Future<void> _startSession() async { + if (directory.isEmpty) { + showNotice(chatNoDirectoryReport, failed: true); + return; + } + try { + final reply = await repository.create( + title: chatNewSessionTitle, + directory: directory, + operationId: _operationId(), + instructions: chatDefaultSessionInstructions, + ); + final session = reply['chat_session']; + if (session is! Map) { + throw const ProtocolError( + 'The server did not return the new chat session.', + ); + } + final row = Map<String, dynamic>.from(session); + final title = '${row['title'] ?? ''}'.trim(); + openCreatedSession( + row, + chatSessionStartedNotice( + title.isEmpty ? chatNewSessionTitle : title, + directory, + ), + ); + } catch (error) { + showNotice( + chatSessionStartFailedNotice(directory, _reason(error)), + failed: true, + ); + } + } + + /// `/close`: the row's confirm, then the existing `chat_close`. Cancelling + /// sends nothing; a refusal is the server's words. + Future<void> _closeSession() async { + if (!await confirmClose()) return; + try { + await repository.close(sessionId); + onClosed?.call(); + } catch (error) { + showNotice(_reason(error), failed: true); + } + } + + /// `/rename <title>`: the same shared `chat_rename` the Rename dialog sends, + /// with the trimmed title. No title is a usage error and sends nothing. + Future<void> _renameSession(String title) async { + if (title.isEmpty) { + showNotice(chatRenameUsageReport, failed: true); + return; + } + try { + await repository.rename(sessionId, title); + onRenamed?.call(title); + showNotice(chatSessionRenamedNotice(title)); + } catch (error) { + showNotice(_reason(error), failed: true); + } + } + + String _operationId() => + newOperationId?.call() ?? + 'native-chat-${DateTime.now().microsecondsSinceEpoch}'; + + /// The server's words without a Dart runtime prefix, as the web prints them. + String _reason(Object error) => + describeErrorReason(error, fallback: 'The server gave no reason.'); +} diff --git a/app/lib/features/chat/conversation/chat_composer_bar.dart b/app/lib/features/chat/conversation/chat_composer_bar.dart index a103aecb..b08e9e64 100644 --- a/app/lib/features/chat/conversation/chat_composer_bar.dart +++ b/app/lib/features/chat/conversation/chat_composer_bar.dart @@ -11,6 +11,7 @@ import '../domain/chat_attachment_wire.dart'; import '../domain/chat_clipboard_paste.dart'; import '../domain/chat_commands.dart'; import '../ui/sessions/chat_adaptive.dart'; +import 'chat_command_actions.dart'; import 'chat_command_palette.dart'; import 'chat_composer_controller.dart'; @@ -44,10 +45,11 @@ const String chatQueuedNotice = /// sends the plain message. A leading `/` opens the recorded command palette /// above the field: rows are filtered by name prefix, Up/Down move the /// highlight, Enter or a tap completes the highlighted command, Escape closes -/// the palette. A slash draft is never handed to the prompt path: a completed -/// recorded commands run locally or through the existing Stop path; text naming -/// no recorded command becomes the web client's local no-send report with its -/// explicit "Send as message" offer. Picked files are memory-only chips: +/// the palette. A slash draft is never handed to the prompt path: `/new`, +/// `/close` and `/rename` run through [commands], `/stop` and `/help` run +/// locally or through the existing Stop path; text naming no recorded command +/// becomes the web client's local no-send report with its explicit "Send as +/// message" offer. Picked files are memory-only chips: /// their names are shown with the host's own remove action and the bounded /// draft owns every refusal. Send carries the chips as the landed wire parts, /// keeps them until the prompt is accepted and leaves them in place on a @@ -60,11 +62,16 @@ class ChatComposerBar extends StatefulWidget { required this.composer, required this.running, this.picker, + this.commands, this.paste, }); final ChatComposerController composer; + /// Runs `/new`, `/close` and `/rename` for the open session. A host without a + /// session (null) keeps those commands on the unavailable report. + final ChatCommandActions? commands; + /// The thread controller's running bit; it alone decides Send versus Stop. final bool running; @@ -269,6 +276,7 @@ class _ChatComposerBarState extends State<ChatComposerBar> { final word = chatCommandWord(draft); if (word == null) return; final command = chatCommandNamed(draft); + final actions = widget.commands; if (command != null) { final argument = chatCommandArgument(draft); if (!command.takesArgument && argument.isNotEmpty) { @@ -277,6 +285,10 @@ class _ChatComposerBarState extends State<ChatComposerBar> { '${command.usage} does not take an argument.', failed: true, ); + } else if (actions != null && ChatCommandActions.runs(command)) { + _consumeCommandDraft(); + setState(_dismissCommandReport); + unawaited(actions.run(command, argument)); } else if (command.name == chatCommandStop) { _consumeCommandDraft(); if (widget.running) { diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index 22a6d507..bd79e64a 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -5,13 +5,16 @@ import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import '../../../core/api_gateway.dart'; +import '../data/chat_repository.dart'; import '../domain/chat_activity_detail.dart'; import '../domain/chat_notice.dart'; import '../domain/chat_transcript.dart'; import '../ui/sessions/chat_adaptive.dart'; +import '../ui/sessions/session_actions.dart'; import '../ui/transcript/chat_markdown_view.dart'; import '../ui/transcript/chat_message_view.dart'; import 'chat_background_tasks.dart'; +import 'chat_command_actions.dart'; import 'chat_composer_bar.dart'; import 'chat_composer_controller.dart'; import 'chat_draft_store.dart'; @@ -45,12 +48,31 @@ class ChatThreadView extends StatefulWidget { this.drafts, this.newOperationId, this.scrollPositions, + this.initialNotice, + this.onCreatedSession, + this.onSessionRenamed, + this.onSessionClosed, }); final ApiGateway gateway; final String sessionId; final VoidCallback onBack; + /// The local line this conversation opens on: the destination hands over + /// the `/new` notice for a session it just created and opened. + final String? initialNotice; + + /// `/new` created this row; the destination lists it, opens it with the + /// notice and refreshes the list. Without a destination the notice shows + /// here instead, since the session already exists on the server. + final ChatCreatedSessionCallback? onCreatedSession; + + /// `/rename` was accepted with this title, so the header can follow it. + final ValueChanged<String>? onSessionRenamed; + + /// `/close` was accepted: the conversation is finished here as on the web. + final VoidCallback? onSessionClosed; + /// The list row's title when this visit knows it; a deep link may not. final String title; @@ -108,6 +130,12 @@ class _ChatThreadViewState extends State<ChatThreadView> { /// A sent turn shown before history or a live frame echoes it. final List<JsonMap> _optimistic = []; + /// The lines this conversation's slash commands produced, in order. They are + /// this conversation's own: a session switch starts over from the + /// destination's handoff, and a dismissal removes one. + final List<ChatNotice> _commandNotices = []; + int _commandNoticeSeq = 0; + final ScrollController _scroll = ScrollController(); /// True while the transcript's end is in view. The operator's own upward @@ -231,10 +259,47 @@ class _ChatThreadViewState extends State<ChatThreadView> { return native.isNotEmpty && native == message['native_message_id']; } + void _seedCommandNotice() { + final notice = widget.initialNotice; + if (notice == null || notice.isEmpty) return; + _commandNotices.add( + chatCommandNotice(notice, sequence: ++_commandNoticeSeq), + ); + } + + void _showCommandNotice(String text, {bool failed = false}) { + if (!mounted) return; + setState(() { + _commandNotices.add( + chatCommandNotice(text, sequence: ++_commandNoticeSeq, failed: failed), + ); + }); + } + + /// The runner for this session's `/new`, `/close` and `/rename`, rebuilt per + /// build so an adopted row's directory and title are the current ones. + ChatCommandActions _commandActions() { + final session = widget.session ?? {'id': widget.sessionId, 'title': widget.title}; + final onCreated = widget.onCreatedSession; + return ChatCommandActions( + repository: ChatRepository(widget.gateway), + sessionId: widget.sessionId, + directory: '${session['directory'] ?? ''}'.trim(), + showNotice: _showCommandNotice, + confirmClose: () => confirmCloseChat(context, session), + openCreatedSession: onCreated ?? + (created, notice) => _showCommandNotice(notice), + onRenamed: widget.onSessionRenamed, + onClosed: widget.onSessionClosed, + newOperationId: widget.newOperationId, + ); + } + @override void initState() { super.initState(); _savedOffset = widget.scrollPositions?.read(widget.sessionId); + _seedCommandNotice(); } @override @@ -254,6 +319,8 @@ class _ChatThreadViewState extends State<ChatThreadView> { _preGapMessages = null; _syncGeneration++; _optimistic.clear(); + _commandNotices.clear(); + _seedCommandNotice(); _savedOffset = widget.scrollPositions?.read(widget.sessionId); _placed = false; _following = true; @@ -719,6 +786,7 @@ class _ChatThreadViewState extends State<ChatThreadView> { if (_controller.loaded && allRows.isEmpty && allNotices.isEmpty && + _commandNotices.isEmpty && _controller.error == null) const Padding( key: Key('chat-thread-empty'), @@ -739,6 +807,16 @@ class _ChatThreadViewState extends State<ChatThreadView> { : null, ), ), + // The conversation's own command lines sit after the + // turns, as on the web; they are never bubbles. + for (final notice in _commandNotices) + _ChatNoticeLine( + key: ValueKey<String>( + 'chat-command-notice-${notice.condition}', + ), + notice: notice, + onDismiss: _dismiss, + ), if (_controller.running && !awaiting) Padding( key: const Key('chat-running'), @@ -771,6 +849,7 @@ class _ChatThreadViewState extends State<ChatThreadView> { key: ValueKey<String>('chat-composer-${widget.sessionId}'), composer: _composer, running: _controller.running, + commands: _commandActions(), ), ], ); @@ -804,7 +883,15 @@ class _ChatThreadViewState extends State<ChatThreadView> { identical(_controller.messages, _preGapMessages); void _dismiss(ChatNotice notice) { - setState(() => _dismissals.dismiss(notice)); + setState(() { + if (notice.kind == ChatNoticeKind.command) { + // A command line is this conversation's own record, not a recorded + // condition that could recur: dismissing it removes it. + _commandNotices.remove(notice); + } else { + _dismissals.dismiss(notice); + } + }); } Widget _transcriptRow(JsonMap row, {VoidCallback? onDismissCompaction}) { @@ -883,11 +970,12 @@ Widget _noticeDismissControl({ ); } -/// One local failure notice beside the conversation. +/// One local notice beside the conversation: a recorded failure or a slash +/// command's outcome. /// /// It is never a message bubble and never sent to the agent. The line carries /// the kind's own words plus the recorded reason, keeps its native Retry and -/// adds a native dismiss control. Colour only repeats the failure state, so the +/// adds a native dismiss control. Colour only repeats the failed state, so the /// words remain readable without it. A running compaction is a recorded activity /// line and is dismissed there instead. class _ChatNoticeLine extends StatelessWidget { @@ -907,17 +995,24 @@ class _ChatNoticeLine extends StatelessWidget { final cupertino = chatControlsStyleOf(context) == ChatControlsStyle.cupertino; final theme = Theme.of(context); - final color = cupertino - ? CupertinoColors.systemRed.resolveFrom(context) - : theme.colorScheme.error; + final failed = notice.failed; + final color = failed + ? (cupertino + ? CupertinoColors.systemRed.resolveFrom(context) + : theme.colorScheme.error) + : (cupertino + ? CupertinoColors.secondaryLabel.resolveFrom(context) + : theme.colorScheme.onSurfaceVariant); final style = (cupertino ? CupertinoTheme.of(context).textTheme.textStyle : theme.textTheme.bodyMedium) ?.copyWith(color: color); - final icon = cupertino - ? CupertinoIcons.exclamationmark_circle - : Icons.error_outline; + final icon = failed + ? (cupertino + ? CupertinoIcons.exclamationmark_circle + : Icons.error_outline) + : (cupertino ? CupertinoIcons.info_circle : Icons.info_outline); return Padding( padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 8, 4), child: Column( diff --git a/app/lib/features/chat/domain/chat_commands.dart b/app/lib/features/chat/domain/chat_commands.dart index c2e07857..5864fc31 100644 --- a/app/lib/features/chat/domain/chat_commands.dart +++ b/app/lib/features/chat/domain/chat_commands.dart @@ -130,3 +130,41 @@ String chatUnknownCommandReport(String word) => /// text must never become an implicit prompt. String chatCommandUnavailableReport(String word) => '“$word” is not available yet, so nothing was sent to the agent.'; + +/// The behaviour brief a `/new` session is created with, verbatim from the web +/// client's `DEFAULT_CHAT_INSTRUCTIONS`. +const String chatDefaultSessionInstructions = + "Act as a careful coding agent. Read the repository's AGENTS.md and the " + 'relevant skills before acting. Inspect the current state, keep changes ' + 'scoped to the request, run the relevant checks, and report exactly what ' + 'changed and what was not verified. Ask only about real ambiguity, ' + 'destructive actions or changes outside the request.'; + +/// The title every `/new` session is created with, as the web client sends it. +const String chatNewSessionTitle = 'New chat'; + +/// `/new` and `/close` act on the open session alone, so an argument is a +/// usage error the web reports in these exact words. +String chatCommandArgumentReport(ChatCommand command) => + '${command.usage} does not take an argument.'; + +/// `/rename` without a title sends nothing and reports its usage. +const String chatRenameUsageReport = + 'Usage: /rename <title> — renames this session on this device.'; + +/// `/new` needs the open session's directory; without one nothing is sent. +const String chatNoDirectoryReport = + "Can't start a new session here: the server reported no directory for " + 'this chat.'; + +/// The notice the created session opens with. +String chatSessionStartedNotice(String title, String directory) => + 'Started a new session “$title” in $directory.'; + +/// The failed notice the current session shows when the create is refused. +String chatSessionStartFailedNotice(String directory, String reason) => + "Couldn't start a new session in $directory: $reason"; + +/// The notice after the server accepted the shared rename. +String chatSessionRenamedNotice(String title) => + 'Renamed this session to “$title”.'; diff --git a/app/lib/features/chat/domain/chat_notice.dart b/app/lib/features/chat/domain/chat_notice.dart index 27376cab..dca09b28 100644 --- a/app/lib/features/chat/domain/chat_notice.dart +++ b/app/lib/features/chat/domain/chat_notice.dart @@ -6,8 +6,9 @@ import 'chat_transcript.dart'; /// /// A notice is never a chat message and never reaches the agent. Each kind /// reports one recorded condition; the thread stops showing it only while that -/// condition is unchanged (see [ChatNoticeDismissals]). -enum ChatNoticeKind { connectionRefused, liveFailure, compaction } +/// condition is unchanged (see [ChatNoticeDismissals]). A [command] notice is +/// the outcome of one slash command the operator ran in that conversation. +enum ChatNoticeKind { connectionRefused, liveFailure, compaction, command } /// The two failure labels already used by this conversation, kept verbatim so a /// refused read/watch is never mistaken for an empty transcript. @@ -24,6 +25,7 @@ String chatNoticeDismissLabel(ChatNoticeKind kind) => switch (kind) { ChatNoticeKind.connectionRefused => 'Dismiss connection notice', ChatNoticeKind.liveFailure => 'Dismiss live updates notice', ChatNoticeKind.compaction => 'Dismiss compaction notice', + ChatNoticeKind.command => 'Dismiss command notice', }; /// One recorded local notice: what it is, which condition it reports and the @@ -34,10 +36,15 @@ class ChatNotice { required this.condition, required this.label, this.detail = '', + this.failed = true, }); final ChatNoticeKind kind; + /// Whether the line reports a failure. Every recorded condition does; only a + /// command's accepted outcome is a plain line. + final bool failed; + /// The recorded condition this notice reports. A different value is a new /// notice even when the words repeat, and a dismissed value stays hidden only /// while it is still recorded. @@ -99,6 +106,20 @@ List<ChatNotice> chatNotices({ return notices; } +/// One slash command's outcome in its exact words. [sequence] is the +/// conversation's own counter, so the same words twice are two notices and a +/// dismissal hides only the one the operator dismissed. +ChatNotice chatCommandNotice( + String text, { + required int sequence, + bool failed = false, +}) => ChatNotice( + kind: ChatNoticeKind.command, + condition: 'command\n$sequence', + label: text, + failed: failed, +); + /// The condition key of the compaction recorded as [id]. String chatCompactionCondition(String id) => 'compaction\n$id'; diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index 03dbb0ae..0a2268f3 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -1,9 +1,13 @@ +import 'dart:async'; + import 'package:flutter/material.dart'; import '../../core/api_gateway.dart'; import 'conversation/chat_models.dart'; import 'conversation/chat_scroll.dart'; import 'conversation/chat_thread_view.dart'; +import 'data/chat_repository.dart'; +import 'ui/sessions/chat_sessions_controller.dart'; import 'ui/sessions/chat_sessions_screen.dart'; /// The Chat destination's list/detail switch. @@ -11,6 +15,8 @@ import 'ui/sessions/chat_sessions_screen.dart'; /// The route names the open session, so a row tap, a deep link and Back all /// navigate through the same value. The session list stays mounted (offstage) /// while a conversation is open, so returning to it keeps its rows and query. +/// The destination owns the list controller too, so a session a conversation's +/// `/new` creates is listed, opened and refreshed from here. /// The shell owns the app bar; this screen adds no second one. class ChatScreen extends StatefulWidget { const ChatScreen({ @@ -39,6 +45,14 @@ class ChatScreen extends StatefulWidget { } class _ChatScreenState extends State<ChatScreen> { + /// The list's controller, shared with the mounted list screen. The list + /// screen refreshes it on mount and swaps its repository when the socket is + /// replaced; this destination lists created rows and re-reads after a + /// conversation's command changes a session. + late final ChatSessionsController _sessions = ChatSessionsController( + ChatRepository(widget.gateway), + ); + /// Rows this visit has opened, used for the native title and the recorded /// model facts. The mounted list also reports its loaded rows, so a routed id /// (a deep link) resolves the same row without a second list request. @@ -53,6 +67,11 @@ class _ChatScreenState extends State<ChatScreen> { /// conversation view, so Back and a reopened chat return to the same place. final ChatScrollStore _scrollPositions = MemoryChatScrollStore(); + /// The line a just-created conversation opens on, tied to the selection + /// `/new` made. Leaving that conversation drops it, so a later reopen is an + /// ordinary visit. + ({String id, String notice})? _startNotice; + String? _standaloneSelection; String? get _selected { @@ -65,6 +84,7 @@ class _ChatScreenState extends State<ChatScreen> { final id = '${session['id'] ?? ''}'; if (id.isEmpty) return; _openedSessions[id] = session; + if (_startNotice?.id != id) _startNotice = null; final select = widget.onSessionSelected; if (select != null) { select(id); @@ -73,6 +93,34 @@ class _ChatScreenState extends State<ChatScreen> { } } + /// `/new` created [session]: list it at the head before its conversation + /// opens, open it on [notice], then re-read the list from the server. + void _openCreated(JsonMap session, String notice) { + final id = '${session['id'] ?? ''}'; + if (id.isEmpty) return; + _sessions.insertCreated(session); + _startNotice = (id: id, notice: notice); + _open(session); + unawaited(_sessions.refresh()); + } + + /// `/rename` was accepted for [id]: the opened row follows the shared title + /// and the list re-reads it. + void _renamed(String id, String title) { + final row = _openedSessions[id]; + if (row != null) { + setState(() => _openedSessions[id] = {...row, 'title': title}); + } + unawaited(_sessions.refresh()); + } + + /// `/close` was accepted: the conversation leaves, back to the list, which + /// re-reads the closed row. + void _closed() { + _back(); + unawaited(_sessions.refresh()); + } + /// Adopts the list's loaded rows for the routed session: a deep link opens /// the conversation before any row has been tapped, and the header's title /// and model control come from that row. Called after a frame, never during @@ -106,6 +154,7 @@ class _ChatScreenState extends State<ChatScreen> { } void _back() { + _startNotice = null; final back = widget.onBack; if (back != null) { back(); @@ -114,10 +163,17 @@ class _ChatScreenState extends State<ChatScreen> { } } + @override + void dispose() { + _sessions.dispose(); + super.dispose(); + } + @override Widget build(BuildContext context) { final selected = _selected; final row = selected == null ? null : _rowFor(selected); + final start = _startNotice; return Stack( children: [ Offstage( @@ -126,6 +182,7 @@ class _ChatScreenState extends State<ChatScreen> { gateway: widget.gateway, embedded: true, syncToken: widget.syncToken, + controller: _sessions, onOpen: _open, onSessions: _adoptRows, activeSessionId: selected, @@ -140,8 +197,14 @@ class _ChatScreenState extends State<ChatScreen> { session: row, syncToken: widget.syncToken, scrollPositions: _scrollPositions, + initialNotice: start != null && start.id == selected + ? start.notice + : null, onBack: _back, onModelChanged: (applied) => _modelChanged(selected, applied), + onCreatedSession: _openCreated, + onSessionRenamed: (title) => _renamed(selected, title), + onSessionClosed: _closed, ), ], ); diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart index 57662c41..486892d1 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart @@ -182,6 +182,21 @@ class ChatSessionsController extends ChangeNotifier { return Map<String, dynamic>.from(session); } + /// Lists a session the server just created at the head of the loaded rows, + /// so the row is present before its conversation opens; the caller re-reads + /// the list from the server afterwards. A row with the same id is replaced, + /// never duplicated. + void insertCreated(JsonMap session) { + final id = '${session['id'] ?? ''}'; + _sessions = [ + session, + for (final row in _sessions) + if ('${row['id'] ?? ''}' != id) row, + ]; + _seedLocal(); + _notify(); + } + /// Records that this device has read [session]'s current recency. Future<void> markOpened(JsonMap session) async { final id = '${session['id'] ?? ''}'; 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 8cd7e123..1815db8a 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart @@ -23,6 +23,7 @@ class ChatSessionsScreen extends StatefulWidget { this.syncToken = 0, this.onSessions, this.localStore, + this.controller, this.activeSessionId, }); final ApiGateway gateway; @@ -47,16 +48,22 @@ class ChatSessionsScreen extends StatefulWidget { /// Overrides the device-local hidden/read store in tests. final ChatSessionLocalStore? localStore; + /// A list controller the destination owns and keeps across this screen's + /// life, so a session created from an open conversation can be listed here. + /// Null makes this screen own its own. + final ChatSessionsController? controller; + @override State<ChatSessionsScreen> createState() => _ChatSessionsScreenState(); } class _ChatSessionsScreenState extends State<ChatSessionsScreen> { late final ChatSessionsController _controller = - ChatSessionsController( - ChatRepository(widget.gateway), - localStore: widget.localStore, - ) + (widget.controller ?? + ChatSessionsController( + ChatRepository(widget.gateway), + localStore: widget.localStore, + )) ..activeSessionId = widget.activeSessionId ..refresh(); final _search = TextEditingController(); @@ -93,7 +100,7 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> { void dispose() { _undoTimer?.cancel(); _controller.removeListener(_reportSessions); - _controller.dispose(); + if (widget.controller == null) _controller.dispose(); _search.dispose(); super.dispose(); } diff --git a/app/test/features/chat/conversation/chat_command_palette_test.dart b/app/test/features/chat/conversation/chat_command_palette_test.dart index 1b455c8c..67e16054 100644 --- a/app/test/features/chat/conversation/chat_command_palette_test.dart +++ b/app/test/features/chat/conversation/chat_command_palette_test.dart @@ -195,18 +195,16 @@ void main() { expect(palette(), findsNothing); expect(gateway.promptBodies, isEmpty); - // A second Enter re-reports the command instead of sending it. + // A second Enter runs the command: its confirm, never a prompt. await tester.sendKeyEvent(LogicalKeyboardKey.enter); await tester.pumpAndSettle(); expect(gateway.promptBodies, isEmpty); expect(fieldText(tester), ''); - expect( - find.text( - '“/close” is not available yet, so nothing was sent to the agent.', - ), - findsOneWidget, - ); + expect(find.text('Close chat?'), findsOneWidget); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + expect(gateway.calls.where((call) => call.type == 'chat_close'), isEmpty); // An argument is validated locally, then consumed too. await tester.enterText(field, '/close now'); diff --git a/app/test/features/chat/conversation/chat_command_session_test.dart b/app/test/features/chat/conversation/chat_command_session_test.dart new file mode 100644 index 00000000..8cc6d6a9 --- /dev/null +++ b/app/test/features/chat/conversation/chat_command_session_test.dart @@ -0,0 +1,164 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; + +import 'chat_composer_bar_fixtures.dart'; + +/// Answers the session commands' create, close and rename requests. +class _SessionGateway extends ComposerBarGateway { + String? refuse; + + @override + Future<JsonMap> call(String type, [JsonMap fields = const {}]) async { + if (type == 'chat_create' || + type == 'chat_close' || + type == 'chat_rename') { + calls.add((type: type, fields: fields)); + if (refuse != null) throw ProtocolError(refuse!); + if (type == 'chat_create') { + return { + 'chat_session': {'id': 'n1', 'title': 'New chat', 'directory': '/w'}, + }; + } + return <String, dynamic>{}; + } + return super.call(type, fields); + } + + List<JsonMap> sent(String type) => [ + for (final call in calls) + if (call.type == type) call.fields, + ]; +} + +void main() { + late _SessionGateway gateway; + JsonMap? created; + String? createdNotice; + String? renamed; + var closed = 0; + + setUp(() { + gateway = _SessionGateway(); + created = null; + createdNotice = null; + renamed = null; + closed = 0; + }); + + Future<void> pump(WidgetTester tester, {String directory = '/w'}) async { + await tester.pumpWidget( + materialHost( + ChatThreadView( + gateway: gateway, + sessionId: 's', + title: 'Old', + session: {'id': 's', 'title': 'Old', 'directory': directory}, + onBack: () {}, + drafts: MemoryChatDraftStore(), + newOperationId: () => 'op-1', + onCreatedSession: (session, notice) { + created = session; + createdNotice = notice; + }, + onSessionRenamed: (title) => renamed = title, + onSessionClosed: () => closed++, + ), + ), + ); + await tester.pumpAndSettle(); + } + + Future<void> run(WidgetTester tester, String draft) async { + await tester.enterText(find.byKey(const Key('chat-composer-field')), draft); + await tester.pump(); + // The first Enter may complete the palette row; the second runs it. + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pump(); + if (fieldText(tester).isNotEmpty) { + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + } + await tester.pumpAndSettle(); + } + + testWidgets('/new creates in this directory and hands the row over', ( + tester, + ) async { + await pump(tester); + await run(tester, '/new'); + + final body = gateway.sent('chat_create').single['chat_create'] as JsonMap; + expect(body['title'], 'New chat'); + expect(body['directory'], '/w'); + expect(body['operation_id'], 'op-1'); + expect(created?['id'], 'n1'); + expect(createdNotice, 'Started a new session “New chat” in /w.'); + expect(gateway.promptBodies, isEmpty); + }); + + testWidgets('/new without a directory sends nothing and reports it', ( + tester, + ) async { + await pump(tester, directory: ''); + await run(tester, '/new'); + + expect(gateway.sent('chat_create'), isEmpty); + expect( + find.text( + "Can't start a new session here: the server reported no directory " + 'for this chat.', + ), + findsOneWidget, + ); + }); + + testWidgets('/rename sends the trimmed title and reports it', (tester) async { + await pump(tester); + await run(tester, '/rename Fresh title '); + + final body = gateway.sent('chat_rename').single['chat_rename'] as JsonMap; + expect(body, {'session_id': 's', 'title': 'Fresh title'}); + expect(renamed, 'Fresh title'); + expect(find.text('Renamed this session to “Fresh title”.'), findsOneWidget); + }); + + testWidgets('/rename without a title reports usage and sends nothing', ( + tester, + ) async { + await pump(tester); + await run(tester, '/rename'); + + expect(gateway.sent('chat_rename'), isEmpty); + expect( + find.text( + 'Usage: /rename <title> — renames this session on this device.', + ), + findsOneWidget, + ); + }); + + testWidgets('/close confirms, closes and a refusal keeps the reason', ( + tester, + ) async { + await pump(tester); + await run(tester, '/close'); + await tester.tap(find.text('Close chat')); + await tester.pumpAndSettle(); + + expect(gateway.sent('chat_close').single['chat_query'], { + 'session_id': 's', + }); + expect(closed, 1); + + gateway.refuse = 'chat is locked'; + await run(tester, '/close'); + await tester.tap(find.text('Close chat')); + await tester.pumpAndSettle(); + expect(closed, 1); + expect(find.text('chat is locked'), findsOneWidget); + }); +} diff --git a/app/test/features/chat/conversation/chat_notice_test.dart b/app/test/features/chat/conversation/chat_notice_test.dart index 70104b47..14110ff7 100644 --- a/app/test/features/chat/conversation/chat_notice_test.dart +++ b/app/test/features/chat/conversation/chat_notice_test.dart @@ -57,6 +57,7 @@ void main() { 'Dismiss connection notice', 'Dismiss live updates notice', 'Dismiss compaction notice', + 'Dismiss command notice', ], ); // A later compaction has its own recorded condition.