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 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 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 _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.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 _closeSession() async {
+ if (!await confirmClose()) return;
+ try {
+ await repository.close(sessionId);
+ onClosed?.call();
+ } catch (error) {
+ showNotice(_reason(error), failed: true);
+ }
+ }
+
+ /// `/rename `: the same shared `chat_rename` the Rename dialog sends,
+ /// with the trimmed title. No title is a usage error and sends nothing.
+ Future _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 3b2a2089..6b049296 100644
--- a/app/lib/features/chat/conversation/chat_composer_bar.dart
+++ b/app/lib/features/chat/conversation/chat_composer_bar.dart
@@ -10,6 +10,7 @@ import '../domain/chat_attachment_picker.dart';
import '../domain/chat_attachment_wire.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';
@@ -40,10 +41,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
-/// command is not run yet (command actions are a later slice), and 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` consume the draft and run through [commands], the
+/// other recorded commands report that they are not available yet, and 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
@@ -54,10 +56,15 @@ class ChatComposerBar extends StatefulWidget {
required this.composer,
required this.running,
this.picker,
+ this.commands,
});
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;
@@ -212,15 +219,26 @@ class _ChatComposerBarState extends State {
return KeyEventResult.handled;
}
- /// Routes the current slash draft to the command surface. Command actions
- /// are not implemented in this slice, so a recorded command reports that it
- /// is unavailable and keeps its draft; an unknown word takes the web client's
- /// report and consumes the draft into the offer. Neither posts a prompt.
+ /// Routes the current slash draft to the command surface. A session command
+ /// consumes the draft (text and persisted copy) and runs; a recorded command
+ /// without an action here reports that it is unavailable and keeps its
+ /// draft; an unknown word takes the web client's report and consumes the
+ /// draft into the offer. None of them posts a prompt.
void _runSlashDraft() {
final draft = widget.composer.draft;
final word = chatCommandWord(draft);
if (word == null) return;
final command = chatCommandNamed(draft);
+ final actions = widget.commands;
+ if (command != null && actions != null && ChatCommandActions.runs(command)) {
+ final argument = chatCommandArgument(draft);
+ setState(_dismissCommandReport);
+ _text.clear();
+ unawaited(widget.composer.setDraft(''));
+ _focus.requestFocus();
+ unawaited(actions.run(command, argument));
+ return;
+ }
if (command != null) {
setState(() {
_commandOffer = null;
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? 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 {
/// A sent turn shown before history or a live frame echoes it.
final List _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 _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 {
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 {
_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 {
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 {
: 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(
+ '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 {
key: ValueKey('chat-composer-${widget.sessionId}'),
composer: _composer,
running: _controller.running,
+ commands: _commandActions(),
),
],
);
@@ -804,7 +883,15 @@ class _ChatThreadViewState extends State {
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 d93ebd31..22b64fdf 100644
--- a/app/lib/features/chat/domain/chat_commands.dart
+++ b/app/lib/features/chat/domain/chat_commands.dart
@@ -118,3 +118,50 @@ 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';
+
+/// The text after the slash word, trimmed; empty when the draft carries none.
+/// `/rename My chat ` yields `My chat`; `/close` yields the empty string.
+String chatCommandArgument(String draft) {
+ final trimmed = draft.trim();
+ final word = chatCommandWord(trimmed);
+ if (word == null) return '';
+ return trimmed.substring(word.length).trim();
+}
+
+/// `/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 — 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 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 202f3ef2..70e4a5f1 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 {
+ /// 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 {
/// 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 {
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 {
}
}
+ /// `/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 {
}
void _back() {
+ _startNotice = null;
final back = widget.onBack;
if (back != null) {
back();
@@ -114,10 +163,17 @@ class _ChatScreenState extends State {
}
}
+ @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 {
gateway: widget.gateway,
embedded: true,
syncToken: widget.syncToken,
+ controller: _sessions,
onOpen: _open,
onSessions: _adoptRows,
),
@@ -139,8 +196,14 @@ class _ChatScreenState extends State {
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 0b688782..6f173a8b 100644
--- a/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart
+++ b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart
@@ -141,6 +141,21 @@ class ChatSessionsController extends ChangeNotifier {
return Map.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 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 6f262d06..ff9bc375 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,
});
final ApiGateway gateway;
final void Function(JsonMap session) onOpen;
@@ -42,15 +43,23 @@ 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 createState() => _ChatSessionsScreenState();
}
class _ChatSessionsScreenState extends State {
- late final ChatSessionsController _controller = ChatSessionsController(
- ChatRepository(widget.gateway),
- localStore: widget.localStore,
- )..refresh();
+ late final ChatSessionsController _controller =
+ (widget.controller ??
+ ChatSessionsController(
+ ChatRepository(widget.gateway),
+ localStore: widget.localStore,
+ ))
+ ..refresh();
final _search = TextEditingController();
Timer? _undoTimer;
@@ -84,7 +93,7 @@ class _ChatSessionsScreenState extends State {
void dispose() {
_undoTimer?.cancel();
_controller.removeListener(_reportSessions);
- _controller.dispose();
+ if (widget.controller == null) _controller.dispose();
_search.dispose();
super.dispose();
}