feat(app): create, rename, star, close and hide chat sessions

This commit is contained in:
2026-10-22 03:22:44 +01:00
parent 16eb1bcb08
commit 68d291602b
25 changed files with 1964 additions and 235 deletions
@@ -159,6 +159,40 @@ class ChatCupertinoMessage extends StatelessWidget {
}
}
/// A row action's refusal, shown at full width beneath its tile.
///
/// It must not sit in a `CupertinoListTile.subtitle`: that slot forces every
/// paragraph to one ellipsised line, which cut the server's reason down to its
/// first few words. Full width also stops a long refusal from turning a single
/// Material row into a column taller than the viewport.
class ChatRowError extends StatelessWidget {
const ChatRowError({super.key, required this.message, this.messageKey});
final String message;
/// Key placed on the message paragraph itself, so a test can assert that the
/// rendered text did not exceed its line limit.
final Key? messageKey;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final style = cupertino
? CupertinoTheme.of(context).textTheme.textStyle.copyWith(
color: CupertinoColors.systemRed.resolveFrom(context),
)
: TextStyle(color: Theme.of(context).colorScheme.error);
return Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 12),
child: DefaultTextStyle.merge(
style: style,
child: Text(message, key: messageKey),
),
);
}
}
class ChatErrorNotice extends StatelessWidget {
const ChatErrorNotice({
super.key,
@@ -198,3 +232,52 @@ class ChatLoadingIndicator extends StatelessWidget {
);
}
}
/// One-row report after hiding a session on this device, with its Undo.
///
/// The screen floats this over the list like the web's fixed report, so a long
/// message can never push the list out of the body's column.
class ChatUndoBar extends StatelessWidget {
const ChatUndoBar({super.key, required this.message, required this.onUndo});
final String message;
final VoidCallback onUndo;
@override
Widget build(BuildContext context) {
final content = Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Row(
children: [
Expanded(
child: DefaultTextStyle.merge(
style: chatControlsStyleOf(context) == ChatControlsStyle.cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: DefaultTextStyle.of(context).style,
child: Text(message),
),
),
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino)
CupertinoButton(
padding: const EdgeInsetsDirectional.only(start: 12),
onPressed: onUndo,
child: const Text('Undo'),
)
else
TextButton(onPressed: onUndo, child: const Text('Undo')),
],
),
);
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
// A standard Cupertino popup surface: the bar floats over the list, so it
// needs its own painted card and shadow to stay legible.
return CupertinoPopupSurface(child: content);
}
return Material(
elevation: 3,
borderRadius: BorderRadius.circular(8),
color: Theme.of(context).colorScheme.surfaceContainerHighest,
child: content,
);
}
}
@@ -0,0 +1,57 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'chat_adaptive.dart';
/// Native chrome for the create dialog: standard Cupertino alert or Material
/// alert, with the same disabled/submitting state in both hosts.
class ChatCreateDialogFrame extends StatelessWidget {
const ChatCreateDialogFrame({
super.key,
required this.content,
required this.canSubmit,
required this.submitting,
required this.onCancel,
required this.onSubmit,
});
final Widget content;
final bool canSubmit;
final bool submitting;
final VoidCallback onCancel;
final VoidCallback onSubmit;
@override
Widget build(BuildContext context) {
final enabled = canSubmit && !submitting;
final label = submitting ? 'Creating…' : 'Create';
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
return CupertinoAlertDialog(
title: const Text('New chat'),
content: content,
actions: [
CupertinoDialogAction(
onPressed: submitting ? null : onCancel,
child: const Text('Cancel'),
),
CupertinoDialogAction(
isDefaultAction: true,
onPressed: enabled ? onSubmit : null,
child: Text(label),
),
],
);
}
return AlertDialog(
title: const Text('New chat'),
content: content,
actions: [
TextButton(
onPressed: submitting ? null : onCancel,
child: const Text('Cancel'),
),
FilledButton(onPressed: enabled ? onSubmit : null, child: Text(label)),
],
);
}
}
@@ -117,16 +117,27 @@ class MaterialPickerField extends StatelessWidget {
return DropdownButtonFormField<String>(
key: Key('chat-create-${label.toLowerCase().replaceAll(' ', '-')}'),
initialValue: value,
isExpanded: true,
// Intrinsic item height: a 2x label must not be clipped by the 48px
// default, and a real path must ellipsize instead of overflowing.
itemHeight: null,
decoration: InputDecoration(labelText: label),
selectedItemBuilder: (context) => [
for (final item in values) _fieldLabel(item),
],
items: [
for (final item in values)
DropdownMenuItem(value: item, child: Text(item)),
DropdownMenuItem(value: item, child: _fieldLabel(item)),
],
onChanged: (item) {
if (item != null) onSelected(item);
},
);
}
Widget _fieldLabel(String item) {
return Text(item, maxLines: 1, overflow: TextOverflow.ellipsis);
}
}
class CupertinoPickerField extends StatelessWidget {
@@ -0,0 +1,119 @@
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
/// Device-local list preferences, mirroring the web client's C13 behaviour:
/// hidden ids and the newest session recency this device has read.
///
/// Titles, stars and the closed state are server-owned and deliberately absent.
class ChatSessionLocal {
const ChatSessionLocal({this.hidden = const [], this.seenAt = const {}});
final List<String> hidden;
final Map<String, int> seenAt;
bool isHidden(String id) => hidden.contains(id);
int watermark(String id) => seenAt[id] ?? 0;
ChatSessionLocal hide(String id) {
if (id.isEmpty || hidden.contains(id)) return this;
return ChatSessionLocal(hidden: [...hidden, id], seenAt: seenAt);
}
ChatSessionLocal restore(String id) {
if (!hidden.contains(id)) return this;
return ChatSessionLocal(
hidden: hidden.where((entry) => entry != id).toList(),
seenAt: seenAt,
);
}
/// Advances only for a strictly newer recency, so a stale list read can never
/// mark newer activity as already seen.
ChatSessionLocal read(String id, int updatedAt) {
if (id.isEmpty || updatedAt <= watermark(id)) return this;
return ChatSessionLocal(hidden: hidden, seenAt: {...seenAt, id: updatedAt});
}
/// The first sight of a session baselines it, so pre-existing chats are not
/// all reported as new.
ChatSessionLocal seed(Iterable<({String id, int updatedAt})> rows) {
var next = this;
for (final row in rows) {
if (row.id.isEmpty || row.updatedAt <= 0) continue;
if (next.watermark(row.id) != 0) continue;
next = ChatSessionLocal(
hidden: next.hidden,
seenAt: {...next.seenAt, row.id: row.updatedAt},
);
}
return next;
}
String encode() => jsonEncode({'hidden': hidden, 'seenAt': seenAt});
static ChatSessionLocal decode(Object? value) {
try {
final parsed = jsonDecode('$value');
if (parsed is! Map) return const ChatSessionLocal();
final hidden = parsed['hidden'];
final seenAt = parsed['seenAt'];
return ChatSessionLocal(
hidden: hidden is List
? hidden.whereType<String>().where((id) => id.isNotEmpty).toList()
: const [],
seenAt: seenAt is Map
? {
for (final entry in seenAt.entries)
if (entry.key is String && entry.value is int)
'${entry.key}': entry.value as int,
}
: const {},
);
} catch (_) {
return const ChatSessionLocal();
}
}
}
abstract interface class ChatSessionLocalStore {
Future<ChatSessionLocal> load();
Future<void> save(ChatSessionLocal state);
}
/// `shared_preferences`-backed storage; unavailable storage degrades to the
/// in-memory choice instead of failing the list.
class SharedPreferencesChatSessionLocalStore implements ChatSessionLocalStore {
const SharedPreferencesChatSessionLocalStore();
static const key = 'pipelines.chat.local.v1';
Future<SharedPreferences?> _preferences() async {
try {
return await SharedPreferences.getInstance();
} catch (_) {
return null;
}
}
@override
Future<ChatSessionLocal> load() async {
final preferences = await _preferences();
try {
return ChatSessionLocal.decode(preferences?.getString(key));
} catch (_) {
return const ChatSessionLocal();
}
}
@override
Future<void> save(ChatSessionLocal state) async {
final preferences = await _preferences();
try {
await preferences?.setString(key, state.encode());
} catch (_) {
// Storage may be unavailable; the in-memory choice still applies.
}
}
}
@@ -22,7 +22,10 @@ class ChatSessionsBody extends StatelessWidget {
required this.onClose,
required this.onReopen,
required this.onStar,
required this.onHide,
required this.onClearSearch,
required this.isUnseen,
required this.errorFor,
});
final List<JsonMap> sessions;
@@ -34,7 +37,10 @@ class ChatSessionsBody extends StatelessWidget {
final ValueChanged<JsonMap> onClose;
final ValueChanged<JsonMap> onReopen;
final ValueChanged<JsonMap> onStar;
final ValueChanged<JsonMap> onHide;
final VoidCallback onClearSearch;
final bool Function(JsonMap) isUnseen;
final String? Function(String sessionId) errorFor;
@override
Widget build(BuildContext context) {
@@ -79,7 +85,10 @@ class ChatSessionsBody extends StatelessWidget {
onClose: onClose,
onReopen: onReopen,
onStar: onStar,
onHide: onHide,
onClearSearch: clearSearch,
isUnseen: isUnseen,
errorFor: errorFor,
);
}
return MaterialSessionList(
@@ -91,7 +100,10 @@ class ChatSessionsBody extends StatelessWidget {
onClose: onClose,
onReopen: onReopen,
onStar: onStar,
onHide: onHide,
onClearSearch: clearSearch,
isUnseen: isUnseen,
errorFor: errorFor,
);
}
}
@@ -3,26 +3,63 @@ import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../../../core/api_gateway.dart';
import '../../../../core/transport/connection_state.dart';
import '../../data/chat_repository.dart';
import 'chat_session_local.dart';
/// Owns the session list, its refresh generation and the row actions.
/// Owns the session list, its refresh generation and the shared row actions.
///
/// A refresh that finishes after a newer one (or after the screen is gone) is
/// discarded, so a slow reply can never replace fresher state.
/// discarded, so a slow reply can never replace fresher state. Accepted
/// mutations always re-read the server list; only this device's hidden ids and
/// read watermark are local.
class ChatSessionsController extends ChangeNotifier {
ChatSessionsController(this.repository);
ChatSessionsController(this.repository, {ChatSessionLocalStore? localStore})
: _localStore =
localStore ?? const SharedPreferencesChatSessionLocalStore();
ChatRepository repository;
final ChatSessionLocalStore _localStore;
ChatSessionLocal _local = const ChatSessionLocal();
final Map<String, String> _actionErrors = {};
List<JsonMap> _sessions = const [];
String? _error;
String? _lastHidden;
bool _loading = true;
bool _localLoaded = false;
Future<void>? _localLoading;
bool _disposed = false;
int _generation = 0;
List<JsonMap> get sessions => _sessions;
List<JsonMap> get sessions => [
for (final session in _sessions)
if (!_local.isHidden('${session['id'] ?? ''}')) session,
];
String? get error => _error;
bool get loading => _loading;
/// The row an action failed on; the message is the server's own words.
String? errorFor(String sessionId) => _actionErrors[sessionId];
/// The last hidden session, while its Undo is still offered.
String? get lastHidden => _lastHidden;
bool isUnseen(JsonMap session) {
final id = '${session['id'] ?? ''}';
// Closed chats keep their recency from the close, but they are not new
// work: both the web list and the Android list suppress unseen there.
if (!_localLoaded ||
id.isEmpty ||
session['running'] == true ||
session['closed_at'] != null ||
session['closed'] == true) {
return false;
}
final updatedAt = _millis(session['updated_at']);
return updatedAt > 0 && updatedAt > _local.watermark(id);
}
void replaceRepository(ChatRepository next) {
if (identical(next.gateway, repository.gateway)) return;
repository = next;
@@ -35,10 +72,14 @@ class ChatSessionsController extends ChangeNotifier {
_loading = true;
_error = null;
_notify();
// Device preferences never gate the server read: a slow platform store
// must not hide the list or delay the first request.
unawaited(_ensureLocal());
try {
final sessions = await repository.sessions();
if (generation != _generation) return;
_sessions = sessions;
_seedLocal();
_loading = false;
_notify();
} catch (error) {
@@ -50,52 +91,150 @@ class ChatSessionsController extends ChangeNotifier {
}
Future<void> star(String sessionId, bool starred) =>
_mutate(() => repository.star(sessionId, starred));
_mutate(sessionId, () => repository.star(sessionId, starred));
Future<void> close(String sessionId) =>
_mutate(() => repository.close(sessionId));
_mutate(sessionId, () => repository.close(sessionId));
Future<void> reopen(String sessionId) =>
_mutate(() => repository.reopen(sessionId));
_mutate(sessionId, () => repository.reopen(sessionId));
Future<void> rename(String sessionId, String title) =>
_mutate(() => repository.rename(sessionId, title));
/// Renames through the shared server field. Throws the server's refusal so the
/// open dialog can keep it in view; success refreshes the list from the server.
///
/// The dialog owns the refusal, so no row error is stored: the same sentence
/// must not also stick under the list row.
Future<void> renameOrThrow(String sessionId, String title) async {
await repository.rename(sessionId, title);
_actionErrors.remove(sessionId);
await refresh();
}
Future<JsonMap?> create({
/// Creates one session and returns the server's `chat_session`. A reply
/// without one is refused rather than opening an invented row.
Future<JsonMap> createOrThrow({
required String title,
required String directory,
required String backend,
required String instructions,
required String operationId,
}) async {
try {
final reply = await repository.create(
title: title,
directory: directory,
backend: backend,
operationId: operationId,
instructions: instructions,
final reply = await repository.create(
title: title,
directory: directory,
backend: backend,
operationId: operationId,
instructions: instructions,
);
final session = reply['chat_session'];
if (session is! Map) {
// The web reports exactly this refusal, so the dialog shows the same
// sentence instead of a Dart `Bad state:` prefix.
throw const ProtocolError(
'The server did not return the new chat session.',
);
// Opening the created chat must not wait for the list refresh: the dialog
// has already closed, so a slow listing would look like a failed create.
unawaited(refresh());
final session = reply['chat_session'];
return session is Map ? Map<String, dynamic>.from(session) : null;
}
// Opening the created chat must not wait for the list refresh: the dialog
// has already closed, so a slow listing would look like a failed create.
unawaited(refresh());
return Map<String, dynamic>.from(session);
}
/// Records that this device has read [session]'s current recency.
Future<void> markOpened(JsonMap session) async {
final id = '${session['id'] ?? ''}';
if (id.isEmpty) return;
await _ensureLocal();
final next = _local.read(id, _millis(session['updated_at']));
if (identical(next, _local)) return;
_local = next;
_notify();
await _persist();
}
/// Hides one row on this device only; the server row is untouched.
Future<void> hide(String sessionId) async {
await _ensureLocal();
final next = _local.hide(sessionId);
if (identical(next, _local)) return;
_local = next;
_lastHidden = sessionId;
_notify();
await _persist();
}
Future<void> undoHide() async {
final id = _lastHidden;
if (id == null) return;
_local = _local.restore(id);
_lastHidden = null;
_notify();
await _persist();
}
void dismissUndo() {
if (_lastHidden == null) return;
_lastHidden = null;
_notify();
}
Future<void> _mutate(
String sessionId,
Future<JsonMap> Function() action,
) async {
try {
await action();
_actionErrors.remove(sessionId);
await refresh();
} catch (error) {
_error = '$error';
_actionErrors[sessionId] = '$error';
_notify();
return null;
}
}
Future<void> _mutate(Future<JsonMap> Function() action) async {
Future<void> _ensureLocal() => _localLoading ??= _loadLocal();
Future<void> _loadLocal() async {
try {
await action();
await refresh();
} catch (error) {
_error = '$error';
_notify();
_local = await _localStore.load();
} catch (_) {
_local = const ChatSessionLocal();
}
_localLoaded = true;
_seedLocal();
_notify();
}
void _seedLocal() {
if (!_localLoaded) return;
final next = _local.seed([
for (final session in _sessions)
(
id: '${session['id'] ?? ''}',
updatedAt: _millis(session['updated_at']),
),
]);
if (identical(next, _local)) return;
_local = next;
unawaited(_persist());
}
Future<void> _persist() async {
try {
await _localStore.save(_local);
} catch (_) {
// The in-memory choice still applies for this session.
}
}
static int _millis(Object? value) {
if (value is int) return value > 0 ? value : 0;
if (value is num) return value > 0 ? value.toInt() : 0;
final text = '${value ?? ''}'.trim();
if (text.isEmpty) return 0;
final number = int.tryParse(text);
if (number != null) return number > 0 ? number : 0;
return DateTime.tryParse(text)?.millisecondsSinceEpoch ?? 0;
}
void _notify() {
@@ -6,6 +6,7 @@ import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../data/chat_repository.dart';
import 'chat_adaptive.dart';
import 'chat_session_local.dart';
import 'chat_sessions_body.dart';
import 'chat_sessions_controller.dart';
import 'create_chat_dialog.dart';
@@ -20,6 +21,7 @@ class ChatSessionsScreen extends StatefulWidget {
required this.onOpen,
this.embedded = false,
this.syncToken = 0,
this.localStore,
});
final ApiGateway gateway;
final void Function(JsonMap session) onOpen;
@@ -31,6 +33,9 @@ class ChatSessionsScreen extends StatefulWidget {
/// closed elsewhere during the gap must not stay invisible until Refresh.
final int syncToken;
/// Overrides the device-local hidden/read store in tests.
final ChatSessionLocalStore? localStore;
@override
State<ChatSessionsScreen> createState() => _ChatSessionsScreenState();
}
@@ -38,8 +43,10 @@ class ChatSessionsScreen extends StatefulWidget {
class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
late final ChatSessionsController _controller = ChatSessionsController(
ChatRepository(widget.gateway),
localStore: widget.localStore,
)..refresh();
final _search = TextEditingController();
Timer? _undoTimer;
@override
void didUpdateWidget(covariant ChatSessionsScreen oldWidget) {
@@ -53,6 +60,7 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
@override
void dispose() {
_undoTimer?.cancel();
_controller.dispose();
_search.dispose();
super.dispose();
@@ -61,9 +69,12 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
String _sessionId(JsonMap session) => '${session['id'] ?? ''}';
Future<void> _rename(JsonMap session) async {
final title = await showRenameChatDialog(context, session);
if (title == null || !mounted) return;
await _controller.rename(_sessionId(session), title);
final id = _sessionId(session);
await showRenameChatDialog(
context,
session,
onSubmit: (title) => _controller.renameOrThrow(id, title),
);
}
Future<void> _close(JsonMap session) async {
@@ -73,27 +84,47 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
}
Future<void> _newChat() async {
// One id per create intent: a refusal retried in the dialog reuses it.
final operationId = 'native-chat-${DateTime.now().microsecondsSinceEpoch}';
final draft = await showChatCreateDialog(
final session = await showChatCreateDialog(
context,
repository: _controller.repository,
);
if (draft == null || !mounted) return;
final session = await _controller.create(
title: draft.title,
directory: draft.directory,
backend: draft.backend,
instructions: draft.instructions,
operationId: operationId,
onSubmit: (draft, id) => _controller.createOrThrow(
title: draft.title,
directory: draft.directory,
backend: draft.backend,
instructions: draft.instructions,
operationId: id,
),
);
if (session != null && mounted) widget.onOpen(session);
}
void _open(JsonMap session) {
unawaited(_controller.markOpened(session));
widget.onOpen(session);
}
Future<void> _hide(JsonMap session) async {
await _controller.hide(_sessionId(session));
_undoTimer?.cancel();
_undoTimer = Timer(const Duration(seconds: 8), () {
if (mounted) _controller.dismissUndo();
});
}
Future<void> _undoHide() async {
_undoTimer?.cancel();
await _controller.undoHide();
}
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: _controller,
builder: (context, _) {
final controls = chatControlsStyleOf(context);
final body = Column(
children: [
ChatSearchField(
@@ -106,23 +137,50 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
onRetry: _controller.refresh,
),
Expanded(
child: ChatSessionsBody(
sessions: _controller.sessions,
query: _search.text,
loading: _controller.loading,
error: _controller.error,
onOpen: widget.onOpen,
onRename: _rename,
onClose: _close,
onReopen: (session) => _controller.reopen(_sessionId(session)),
onStar: (session) => _controller.star(
_sessionId(session),
session['starred'] != true,
),
onClearSearch: () {
_search.clear();
setState(() {});
},
child: Stack(
children: [
ChatSessionsBody(
sessions: _controller.sessions,
query: _search.text,
loading: _controller.loading,
error: _controller.error,
onOpen: _open,
onRename: _rename,
onClose: _close,
onReopen: (session) =>
_controller.reopen(_sessionId(session)),
onStar: (session) => _controller.star(
_sessionId(session),
session['starred'] != true,
),
onHide: _hide,
onClearSearch: () {
_search.clear();
setState(() {});
},
isUnseen: _controller.isUnseen,
errorFor: _controller.errorFor,
),
// The web's hide report is a fixed overlay: replacing or
// growing it must never move the list or overflow the screen.
// A standalone Material screen keeps it clear of the FAB.
if (_controller.lastHidden != null)
Positioned(
left: 8,
right: 8,
bottom:
!widget.embedded &&
controls == ChatControlsStyle.material
? 88
: 8,
child: ChatUndoBar(
key: const Key('chat-undo-hide'),
message:
'Hidden on this device; the chat stays on the server.',
onUndo: _undoHide,
),
),
],
),
),
],
@@ -1,8 +1,10 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../data/chat_repository.dart';
import 'chat_adaptive.dart';
import 'chat_create_dialog_frame.dart';
import 'chat_create_fields.dart';
class ChatDraft {
@@ -19,20 +21,37 @@ class ChatDraft {
final String instructions;
}
Future<ChatDraft?> showChatCreateDialog(
/// The dialog sends the create itself so a refusal can keep the operator's
/// draft and the server's words in place. [operationId] is minted once per
/// create intent and reused across retries, so a retry cannot create twice.
Future<JsonMap?> showChatCreateDialog(
BuildContext context, {
required ChatRepository repository,
required String operationId,
required Future<JsonMap> Function(ChatDraft draft, String operationId)
onSubmit,
}) {
final dialog = CreateChatDialog(repository: repository);
final dialog = CreateChatDialog(
repository: repository,
operationId: operationId,
onSubmit: onSubmit,
);
return chatControlsStyleOf(context) == ChatControlsStyle.cupertino
? showCupertinoDialog<ChatDraft>(context: context, builder: (_) => dialog)
: showDialog<ChatDraft>(context: context, builder: (_) => dialog);
? showCupertinoDialog<JsonMap>(context: context, builder: (_) => dialog)
: showDialog<JsonMap>(context: context, builder: (_) => dialog);
}
class CreateChatDialog extends StatefulWidget {
const CreateChatDialog({super.key, required this.repository});
const CreateChatDialog({
super.key,
required this.repository,
required this.operationId,
required this.onSubmit,
});
final ChatRepository repository;
final String operationId;
final Future<JsonMap> Function(ChatDraft draft, String operationId) onSubmit;
@override
State<CreateChatDialog> createState() => _CreateChatDialogState();
@@ -48,6 +67,7 @@ class _CreateChatDialogState extends State<CreateChatDialog> {
String? _catalogError;
String? _formError;
bool _loading = true;
bool _submitting = false;
int _attempt = 0;
@override
@@ -106,23 +126,37 @@ class _CreateChatDialogState extends State<CreateChatDialog> {
_directories.isNotEmpty &&
_backends.isNotEmpty;
void _submit() {
if (!_catalogReady) return;
Future<void> _submit() async {
if (!_catalogReady || _submitting) return;
final title = _name.text.trim();
final directory = _directory ?? '';
if (title.isEmpty || directory.isEmpty) {
setState(() => _formError = 'Enter a name and server directory.');
return;
}
Navigator.pop(
context,
ChatDraft(
title: title,
directory: directory,
backend: _backend ?? '',
instructions: _instructions.text,
),
);
setState(() {
_submitting = true;
_formError = null;
});
try {
final session = await widget.onSubmit(
ChatDraft(
title: title,
directory: directory,
backend: _backend ?? '',
instructions: _instructions.text,
),
widget.operationId,
);
if (!mounted) return;
Navigator.pop(context, session);
} catch (error) {
if (!mounted) return;
setState(() {
_submitting = false;
_formError = '$error';
});
}
}
@override
@@ -181,42 +215,25 @@ class _CreateChatDialogState extends State<CreateChatDialog> {
),
if (_formError != null) ...[
const SizedBox(height: 8),
Text(_formError!),
Text(
_formError!,
style: TextStyle(
color: cupertino
? CupertinoColors.systemRed.resolveFrom(context)
: Theme.of(context).colorScheme.error,
),
),
],
],
),
);
if (cupertino) {
return CupertinoAlertDialog(
title: const Text('New chat'),
content: content,
actions: [
CupertinoDialogAction(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
CupertinoDialogAction(
isDefaultAction: true,
onPressed: _catalogReady ? _submit : null,
child: const Text('Create'),
),
],
);
}
return AlertDialog(
title: const Text('New chat'),
return ChatCreateDialogFrame(
content: content,
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
FilledButton(
onPressed: _catalogReady ? _submit : null,
child: const Text('Create'),
),
],
canSubmit: _catalogReady,
submitting: _submitting,
onCancel: () => Navigator.pop(context),
onSubmit: _submit,
);
}
}
@@ -5,19 +5,28 @@ import '../../../../core/api_gateway.dart';
import '../../domain/chat_sessions.dart';
import 'chat_adaptive.dart';
/// Renames one session. Save is disabled while the trimmed name is blank,
/// matching the web dialog.
Future<String?> showRenameChatDialog(BuildContext context, JsonMap session) {
final dialog = _RenameChatDialog(initialTitle: chatSessionTitle(session));
/// Renames one session through the shared server field. Save is disabled while
/// the trimmed name is blank, matching the web dialog. A refusal keeps the
/// dialog open with the server's own words.
Future<String?> showRenameChatDialog(
BuildContext context,
JsonMap session, {
required Future<void> Function(String title) onSubmit,
}) {
final dialog = _RenameChatDialog(
initialTitle: chatSessionTitle(session),
onSubmit: onSubmit,
);
return chatControlsStyleOf(context) == ChatControlsStyle.cupertino
? showCupertinoDialog<String>(context: context, builder: (_) => dialog)
: showDialog<String>(context: context, builder: (_) => dialog);
}
class _RenameChatDialog extends StatefulWidget {
const _RenameChatDialog({required this.initialTitle});
const _RenameChatDialog({required this.initialTitle, required this.onSubmit});
final String initialTitle;
final Future<void> Function(String title) onSubmit;
@override
State<_RenameChatDialog> createState() => _RenameChatDialogState();
@@ -30,6 +39,8 @@ class _RenameChatDialogState extends State<_RenameChatDialog> {
baseOffset: 0,
extentOffset: widget.initialTitle.length,
);
String? _error;
bool _saving = false;
@override
void dispose() {
@@ -37,10 +48,25 @@ class _RenameChatDialogState extends State<_RenameChatDialog> {
super.dispose();
}
void _save() {
Future<void> _save() async {
if (_saving) return;
final title = _title.text.trim();
if (title.isEmpty) return;
Navigator.pop(context, title);
setState(() {
_saving = true;
_error = null;
});
try {
await widget.onSubmit(title);
if (!mounted) return;
Navigator.pop(context, title);
} catch (error) {
if (!mounted) return;
setState(() {
_saving = false;
_error = '$error';
});
}
}
@override
@@ -48,7 +74,8 @@ class _RenameChatDialogState extends State<_RenameChatDialog> {
return ValueListenableBuilder<TextEditingValue>(
valueListenable: _title,
builder: (context, value, _) {
final canSave = value.text.trim().isNotEmpty;
final canSave = !_saving && value.text.trim().isNotEmpty;
final error = _error;
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
return CupertinoAlertDialog(
title: const Text('Rename chat'),
@@ -63,11 +90,20 @@ class _RenameChatDialogState extends State<_RenameChatDialog> {
),
const SizedBox(height: 8),
const Text('This name is shared with every device.'),
if (error != null) ...[
const SizedBox(height: 8),
Text(
error,
style: TextStyle(
color: CupertinoColors.systemRed.resolveFrom(context),
),
),
],
],
),
actions: [
CupertinoDialogAction(
onPressed: () => Navigator.pop(context),
onPressed: _saving ? null : () => Navigator.pop(context),
child: const Text('Cancel'),
),
CupertinoDialogAction(
@@ -79,20 +115,36 @@ class _RenameChatDialogState extends State<_RenameChatDialog> {
);
}
return AlertDialog(
// A long server refusal plus a 2x helper text can exceed the dialog
// height at 320px; scroll the content instead of clipping it.
scrollable: true,
title: const Text('Rename chat'),
content: TextField(
key: const Key('chat-rename-field'),
controller: _title,
autofocus: true,
decoration: const InputDecoration(
labelText: 'Name',
helperText: 'This name is shared with every device.',
helperMaxLines: 2,
),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
key: const Key('chat-rename-field'),
controller: _title,
autofocus: true,
decoration: const InputDecoration(
labelText: 'Name',
helperText: 'This name is shared with every device.',
helperMaxLines: 2,
),
),
if (error != null) ...[
const SizedBox(height: 8),
Text(
error,
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
],
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
onPressed: _saving ? null : () => Navigator.pop(context),
child: const Text('Cancel'),
),
FilledButton(
@@ -6,7 +6,7 @@ import '../../domain/chat_sessions.dart';
import 'chat_adaptive.dart';
import 'session_row_style.dart';
enum SessionAction { rename, close, reopen }
enum SessionAction { rename, close, reopen, hide }
/// The close confirmation's body, matching the web client's explanation.
String closeChatConfirmation(String title) =>
@@ -115,6 +115,7 @@ List<({SessionAction action, String label})> _items(JsonMap session) {
isClosed
? (action: SessionAction.reopen, label: 'Reopen')
: (action: SessionAction.close, label: 'Close chat…'),
(action: SessionAction.hide, label: 'Hide on this device'),
];
}
@@ -18,7 +18,10 @@ class CupertinoSessionList extends StatelessWidget {
required this.onClose,
required this.onReopen,
required this.onStar,
required this.onHide,
required this.onClearSearch,
required this.isUnseen,
required this.errorFor,
});
final List<ChatSessionSection> sections;
@@ -29,7 +32,10 @@ class CupertinoSessionList extends StatelessWidget {
final ValueChanged<JsonMap> onClose;
final ValueChanged<JsonMap> onReopen;
final ValueChanged<JsonMap> onStar;
final ValueChanged<JsonMap> onHide;
final VoidCallback? onClearSearch;
final bool Function(JsonMap) isUnseen;
final String? Function(String sessionId) errorFor;
@override
Widget build(BuildContext context) {
@@ -57,50 +63,67 @@ class CupertinoSessionList extends StatelessWidget {
? '${section.title} · ${group.directory.isEmpty ? 'No directory' : group.directory}'
: section.title,
),
children: [
for (final session in group.sessions)
_CupertinoSessionRow(
session: session,
duplicateTitles: duplicateTitles,
onOpen: onOpen,
onRename: onRename,
onClose: onClose,
onReopen: onReopen,
onStar: onStar,
),
],
children: [for (final session in group.sessions) ..._row(session)],
),
];
}
/// The tile plus its refusal. `CupertinoListTile` forces its subtitle to one
/// ellipsised line, so the server's words go in their own full-width row
/// inside the same native card.
List<Widget> _row(JsonMap session) {
final id = '${session['id'] ?? ''}';
final error = errorFor(id);
return [
_CupertinoSessionRow(
session: session,
duplicateTitles: duplicateTitles,
unseen: isUnseen(session),
onOpen: onOpen,
onRename: onRename,
onClose: onClose,
onReopen: onReopen,
onStar: onStar,
onHide: onHide,
),
if (error != null)
ChatRowError(message: error, messageKey: Key('chat-row-error-$id')),
];
}
}
class _CupertinoSessionRow extends StatelessWidget {
const _CupertinoSessionRow({
required this.session,
required this.duplicateTitles,
required this.unseen,
required this.onOpen,
required this.onRename,
required this.onClose,
required this.onReopen,
required this.onStar,
required this.onHide,
});
final JsonMap session;
final Set<String> duplicateTitles;
final bool unseen;
final ValueChanged<JsonMap> onOpen;
final ValueChanged<JsonMap> onRename;
final ValueChanged<JsonMap> onClose;
final ValueChanged<JsonMap> onReopen;
final ValueChanged<JsonMap> onStar;
final ValueChanged<JsonMap> onHide;
@override
Widget build(BuildContext context) {
final id = '${session['id'] ?? ''}';
final subtitle = sessionSubtitle(session, unseen: unseen);
return CupertinoListTile(
key: Key('chat-row-$id'),
leading: Icon(sessionCupertinoIcon(session)),
title: Text(chatSessionTitle(session)),
subtitle: Text(sessionSubtitle(session)),
subtitle: Text(subtitle),
onTap: () => onOpen(session),
trailing: Row(
mainAxisSize: MainAxisSize.min,
@@ -129,6 +152,8 @@ class _CupertinoSessionRow extends StatelessWidget {
onClose(session);
case SessionAction.reopen:
onReopen(session);
case SessionAction.hide:
onHide(session);
}
}
}
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../domain/chat_sessions.dart';
import 'chat_adaptive.dart';
import 'chat_sessions_body.dart';
import 'session_actions.dart';
import 'session_row_style.dart';
@@ -17,7 +18,10 @@ class MaterialSessionList extends StatelessWidget {
required this.onClose,
required this.onReopen,
required this.onStar,
required this.onHide,
required this.onClearSearch,
required this.isUnseen,
required this.errorFor,
});
final List<ChatSessionSection> sections;
@@ -28,7 +32,10 @@ class MaterialSessionList extends StatelessWidget {
final ValueChanged<JsonMap> onClose;
final ValueChanged<JsonMap> onReopen;
final ValueChanged<JsonMap> onStar;
final ValueChanged<JsonMap> onHide;
final VoidCallback? onClearSearch;
final bool Function(JsonMap) isUnseen;
final String? Function(String sessionId) errorFor;
@override
Widget build(BuildContext context) {
@@ -64,40 +71,57 @@ class MaterialSessionList extends StatelessWidget {
group.directory.isEmpty ? 'No directory' : group.directory,
),
),
for (final session in group.sessions)
_MaterialSessionRow(
session: session,
duplicateTitles: duplicateTitles,
onOpen: onOpen,
onRename: onRename,
onClose: onClose,
onReopen: onReopen,
onStar: onStar,
),
for (final session in group.sessions) ..._row(session),
],
],
);
}
/// The tile plus its refusal at full width (a long sentence in `subtitle`
/// made the row taller than the viewport at 320px with 2x text).
List<Widget> _row(JsonMap session) {
final id = '${session['id'] ?? ''}';
final error = errorFor(id);
return [
_MaterialSessionRow(
session: session,
duplicateTitles: duplicateTitles,
unseen: isUnseen(session),
onOpen: onOpen,
onRename: onRename,
onClose: onClose,
onReopen: onReopen,
onStar: onStar,
onHide: onHide,
),
if (error != null)
ChatRowError(message: error, messageKey: Key('chat-row-error-$id')),
];
}
}
class _MaterialSessionRow extends StatelessWidget {
const _MaterialSessionRow({
required this.session,
required this.duplicateTitles,
required this.unseen,
required this.onOpen,
required this.onRename,
required this.onClose,
required this.onReopen,
required this.onStar,
required this.onHide,
});
final JsonMap session;
final Set<String> duplicateTitles;
final bool unseen;
final ValueChanged<JsonMap> onOpen;
final ValueChanged<JsonMap> onRename;
final ValueChanged<JsonMap> onClose;
final ValueChanged<JsonMap> onReopen;
final ValueChanged<JsonMap> onStar;
final ValueChanged<JsonMap> onHide;
@override
Widget build(BuildContext context) {
@@ -106,7 +130,7 @@ class _MaterialSessionRow extends StatelessWidget {
key: Key('chat-row-$id'),
leading: Icon(sessionMaterialIcon(session)),
title: Text(chatSessionTitle(session)),
subtitle: Text(sessionSubtitle(session)),
subtitle: Text(sessionSubtitle(session, unseen: unseen)),
onTap: () => onOpen(session),
trailing: Row(
mainAxisSize: MainAxisSize.min,
@@ -135,6 +159,8 @@ class _MaterialSessionRow extends StatelessWidget {
onClose(session);
case SessionAction.reopen:
onReopen(session);
case SessionAction.hide:
onHide(session);
}
}
}
@@ -23,11 +23,11 @@ String sessionActionsLabel(JsonMap session, Set<String> duplicateTitles) {
: 'Chat actions for $title';
}
String sessionSubtitle(JsonMap session) {
String sessionSubtitle(JsonMap session, {bool? unseen}) {
final directory = '${session['directory'] ?? ''}';
switch (chatSessionActivity(
running: session['running'] == true,
unseen: session['unseen'] == true,
unseen: unseen ?? session['unseen'] == true,
)) {
case 'streaming':
return '$directory · Streaming';