feat(app): split chat sessions into native Material and Cupertino views

Split the 406-line chat session browser into a controller, body, shared
adaptive primitives and separate standard Material and Cupertino lists and
dialogs. Preserve the existing server directory/backend catalogs,
instructions field, closed/starred grouping, directory headings and
empty/no-match states.

- keep refresh generations so stale replies are discarded
- open a created chat immediately and refresh the list in the background
- disable rename Save while the trimmed name is blank
- label row actions per session, with the id on duplicate titles
- wrap Cupertino empty/no-match/error messages instead of clipping, and
  give them a Cupertino text style under a bare MaterialApp
- allow the Material rename helper to wrap at large text scales
- cover both native branches, lifecycle ordering, create/rename/close/star
  and the Cupertino theme path with widget tests
This commit is contained in:
2026-10-21 17:42:39 +01:00
parent 13d8ddac5d
commit 41d30a4280
21 changed files with 2640 additions and 363 deletions
@@ -0,0 +1,200 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
/// Which standard control family this screen renders.
enum ChatControlsStyle { material, cupertino }
/// Cupertino under a Cupertino app or an iOS/macOS Material theme, Material
/// everywhere else. The shell decides the app class, so a bare Cupertino app
/// never has to grow a Material ancestor just for this screen.
ChatControlsStyle chatControlsStyleOf(BuildContext context) {
if (context.findAncestorWidgetOfExactType<MaterialApp>() == null) {
return ChatControlsStyle.cupertino;
}
final platform = Theme.of(context).platform;
return platform == TargetPlatform.iOS || platform == TargetPlatform.macOS
? ChatControlsStyle.cupertino
: ChatControlsStyle.material;
}
class ChatBarAction extends StatelessWidget {
const ChatBarAction({
super.key,
required this.label,
required this.onPressed,
required this.materialIcon,
required this.cupertinoIcon,
});
final String label;
final VoidCallback onPressed;
final IconData materialIcon;
final IconData cupertinoIcon;
@override
Widget build(BuildContext context) {
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
return Semantics(
label: label,
button: true,
child: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: onPressed,
child: Icon(cupertinoIcon),
),
);
}
return IconButton(
tooltip: label,
onPressed: onPressed,
icon: Icon(materialIcon),
);
}
}
class ChatSearchField extends StatelessWidget {
const ChatSearchField({
super.key,
required this.controller,
required this.onChanged,
});
final TextEditingController controller;
final ValueChanged<String> onChanged;
@override
Widget build(BuildContext context) {
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
return Padding(
padding: const EdgeInsets.all(16),
child: CupertinoSearchTextField(
controller: controller,
placeholder: 'Search chats',
onChanged: onChanged,
),
);
}
return Padding(
padding: const EdgeInsets.all(16),
child: TextField(
controller: controller,
onChanged: onChanged,
decoration: const InputDecoration(
prefixIcon: Icon(Icons.search),
labelText: 'Search chats',
),
),
);
}
}
/// A grouped Cupertino card for a message that may wrap onto several lines.
///
/// [CupertinoListTile] forces its title to one ellipsised line, which cut long
/// no-match queries and server reasons. This layout keeps the native card but
/// lets the message wrap, with its action on a separate button below.
class ChatCupertinoMessage extends StatelessWidget {
const ChatCupertinoMessage({
super.key,
required this.message,
this.icon,
this.actionLabel,
this.onAction,
});
final String message;
final IconData? icon;
final String? actionLabel;
final VoidCallback? onAction;
@override
Widget build(BuildContext context) {
return Semantics(
container: true,
explicitChildNodes: true,
child: CupertinoListSection.insetGrouped(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (icon != null) ...[
Icon(
icon,
color: CupertinoColors.secondaryLabel.resolveFrom(context),
),
const SizedBox(width: 12),
],
Expanded(
// Cupertino widgets normally supply their own text style.
// This card is also mounted under a bare MaterialApp (the
// iOS/macOS theme path), where Text would otherwise inherit
// MaterialApp's "missing Material" fallback style.
child: DefaultTextStyle.merge(
style: CupertinoTheme.of(context).textTheme.textStyle,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(message),
if (actionLabel != null && onAction != null)
Align(
alignment: AlignmentDirectional.centerStart,
child: CupertinoButton(
padding: const EdgeInsets.only(top: 8),
onPressed: onAction,
child: Text(actionLabel!),
),
),
],
),
),
),
],
),
),
],
),
);
}
}
class ChatErrorNotice extends StatelessWidget {
const ChatErrorNotice({
super.key,
required this.message,
required this.onRetry,
});
final String message;
final VoidCallback onRetry;
@override
Widget build(BuildContext context) {
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
return ChatCupertinoMessage(
message: message,
icon: CupertinoIcons.exclamationmark_circle,
actionLabel: 'Retry',
onAction: onRetry,
);
}
return MaterialBanner(
content: Text(message),
actions: [TextButton(onPressed: onRetry, child: const Text('Retry'))],
);
}
}
class ChatLoadingIndicator extends StatelessWidget {
const ChatLoadingIndicator({super.key});
@override
Widget build(BuildContext context) {
return Center(
child: chatControlsStyleOf(context) == ChatControlsStyle.cupertino
? const CupertinoActivityIndicator()
: const CircularProgressIndicator(),
);
}
}
@@ -0,0 +1,185 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'chat_adaptive.dart';
/// The create dialog's server catalog area: loading, error with retry, the
/// empty-catalog message, or the two server-backed selectors.
class ChatCatalogFields extends StatelessWidget {
const ChatCatalogFields({
super.key,
required this.loading,
required this.error,
required this.directories,
required this.backends,
required this.directory,
required this.backend,
required this.onDirectory,
required this.onBackend,
required this.onRetry,
});
final bool loading;
final String? error;
final List<String> directories;
final List<String> backends;
final String? directory;
final String? backend;
final ValueChanged<String> onDirectory;
final ValueChanged<String> onBackend;
final VoidCallback onRetry;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
if (loading) return const Text('Loading directories…');
if (error != null) {
return _message(cupertino, 'Unable to load chat options: $error');
}
if (directories.isEmpty || backends.isEmpty) {
return _message(
cupertino,
'The server has no chat directories or backends available.',
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (cupertino)
CupertinoPickerField(
label: 'Server directory',
value: directory,
values: directories,
onSelected: onDirectory,
)
else
MaterialPickerField(
label: 'Server directory',
value: directory,
values: directories,
onSelected: onDirectory,
),
if (cupertino)
CupertinoPickerField(
label: 'Backend',
value: backend,
values: backends,
onSelected: onBackend,
)
else
MaterialPickerField(
label: 'Backend',
value: backend,
values: backends,
onSelected: onBackend,
),
],
);
}
Widget _message(bool cupertino, String text) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(text),
Align(
alignment: AlignmentDirectional.centerStart,
child: cupertino
? CupertinoButton(
padding: EdgeInsets.zero,
onPressed: onRetry,
child: const Text('Retry'),
)
: TextButton(onPressed: onRetry, child: const Text('Retry')),
),
],
);
}
}
class MaterialPickerField extends StatelessWidget {
const MaterialPickerField({
super.key,
required this.label,
required this.value,
required this.values,
required this.onSelected,
});
final String label;
final String? value;
final List<String> values;
final ValueChanged<String> onSelected;
@override
Widget build(BuildContext context) {
return DropdownButtonFormField<String>(
key: Key('chat-create-${label.toLowerCase().replaceAll(' ', '-')}'),
initialValue: value,
decoration: InputDecoration(labelText: label),
items: [
for (final item in values)
DropdownMenuItem(value: item, child: Text(item)),
],
onChanged: (item) {
if (item != null) onSelected(item);
},
);
}
}
class CupertinoPickerField extends StatelessWidget {
const CupertinoPickerField({
super.key,
required this.label,
required this.value,
required this.values,
required this.onSelected,
});
final String label;
final String? value;
final List<String> values;
final ValueChanged<String> onSelected;
Future<void> _choose(BuildContext context) async {
final choice = await showCupertinoModalPopup<String>(
context: context,
builder: (sheetContext) => CupertinoActionSheet(
title: Text(label),
actions: [
for (final item in values)
CupertinoActionSheetAction(
onPressed: () => Navigator.pop(sheetContext, item),
child: Text(item),
),
],
cancelButton: CupertinoActionSheetAction(
onPressed: () => Navigator.pop(sheetContext),
child: const Text('Cancel'),
),
),
);
if (choice != null) onSelected(choice);
}
@override
Widget build(BuildContext context) {
return Semantics(
label: '$label: ${value ?? ''}',
button: true,
child: CupertinoButton(
key: Key('chat-create-${label.toLowerCase().replaceAll(' ', '-')}'),
padding: const EdgeInsets.symmetric(vertical: 4),
onPressed: () => _choose(context),
child: Row(
children: [
Expanded(child: Text('$label: ${value ?? ''}')),
const Icon(CupertinoIcons.chevron_down),
],
),
),
);
}
}
@@ -0,0 +1,97 @@
import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../domain/chat_sessions.dart';
import 'chat_adaptive.dart';
import 'session_list_cupertino.dart';
import 'session_list_material.dart';
import 'session_row_style.dart';
typedef ChatSessionSection = ({String title, List<JsonMap> sessions});
/// Groups the visible sessions the way the server reports them.
class ChatSessionsBody extends StatelessWidget {
const ChatSessionsBody({
super.key,
required this.sessions,
required this.query,
required this.loading,
required this.error,
required this.onOpen,
required this.onRename,
required this.onClose,
required this.onReopen,
required this.onStar,
required this.onClearSearch,
});
final List<JsonMap> sessions;
final String query;
final bool loading;
final String? error;
final ValueChanged<JsonMap> onOpen;
final ValueChanged<JsonMap> onRename;
final ValueChanged<JsonMap> onClose;
final ValueChanged<JsonMap> onReopen;
final ValueChanged<JsonMap> onStar;
final VoidCallback onClearSearch;
@override
Widget build(BuildContext context) {
final visible = filterChatSessions(sessions, query);
final sections = <ChatSessionSection>[
if (visible.any((s) => s['starred'] == true && s['closed_at'] == null))
(
title: 'Starred',
sessions: visible
.where((s) => s['starred'] == true && s['closed_at'] == null)
.toList(),
),
if (visible.any((s) => s['starred'] != true && s['closed_at'] == null))
(
title: 'Chats',
sessions: visible
.where((s) => s['starred'] != true && s['closed_at'] == null)
.toList(),
),
if (visible.any((s) => s['closed_at'] != null))
(
title: 'Closed',
sessions: visible.where((s) => s['closed_at'] != null).toList(),
),
];
final emptyMessage = sessions.isEmpty
? error == null
? 'No chat sessions on this server yet.'
: null
: 'No chats match "${query.trim()}".';
if (loading && sessions.isEmpty) return const ChatLoadingIndicator();
final clearSearch = query.trim().isEmpty ? null : onClearSearch;
final duplicateTitles = duplicateChatTitles(visible);
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
return CupertinoSessionList(
sections: sections,
emptyMessage: visible.isEmpty ? emptyMessage : null,
duplicateTitles: duplicateTitles,
onOpen: onOpen,
onRename: onRename,
onClose: onClose,
onReopen: onReopen,
onStar: onStar,
onClearSearch: clearSearch,
);
}
return MaterialSessionList(
sections: sections,
emptyMessage: visible.isEmpty ? emptyMessage : null,
duplicateTitles: duplicateTitles,
onOpen: onOpen,
onRename: onRename,
onClose: onClose,
onReopen: onReopen,
onStar: onStar,
onClearSearch: clearSearch,
);
}
}
@@ -0,0 +1,111 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../../../core/api_gateway.dart';
import '../../data/chat_repository.dart';
/// Owns the session list, its refresh generation and the row actions.
///
/// A refresh that finishes after a newer one (or after the screen is gone) is
/// discarded, so a slow reply can never replace fresher state.
class ChatSessionsController extends ChangeNotifier {
ChatSessionsController(this.repository);
ChatRepository repository;
List<JsonMap> _sessions = const [];
String? _error;
bool _loading = true;
bool _disposed = false;
int _generation = 0;
List<JsonMap> get sessions => _sessions;
String? get error => _error;
bool get loading => _loading;
void replaceRepository(ChatRepository next) {
if (identical(next.gateway, repository.gateway)) return;
repository = next;
refresh();
}
Future<void> refresh() async {
if (_disposed) return;
final generation = ++_generation;
_loading = true;
_error = null;
_notify();
try {
final sessions = await repository.sessions();
if (generation != _generation) return;
_sessions = sessions;
_loading = false;
_notify();
} catch (error) {
if (generation != _generation) return;
_error = '$error';
_loading = false;
_notify();
}
}
Future<void> star(String sessionId, bool starred) =>
_mutate(() => repository.star(sessionId, starred));
Future<void> close(String sessionId) =>
_mutate(() => repository.close(sessionId));
Future<void> reopen(String sessionId) =>
_mutate(() => repository.reopen(sessionId));
Future<void> rename(String sessionId, String title) =>
_mutate(() => repository.rename(sessionId, title));
Future<JsonMap?> create({
required String title,
required String directory,
required String backend,
required String instructions,
required String operationId,
}) async {
try {
final reply = await repository.create(
title: title,
directory: directory,
backend: backend,
operationId: operationId,
instructions: instructions,
);
// Opening the created chat must not wait for the list refresh: the dialog
// has already closed, so a slow listing would look like a failed create.
unawaited(refresh());
final session = reply['chat_session'];
return session is Map ? Map<String, dynamic>.from(session) : null;
} catch (error) {
_error = '$error';
_notify();
return null;
}
}
Future<void> _mutate(Future<JsonMap> Function() action) async {
try {
await action();
await refresh();
} catch (error) {
_error = '$error';
_notify();
}
}
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
_generation++;
super.dispose();
}
}
@@ -1,8 +1,14 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../data/chat_repository.dart';
import '../../domain/chat_sessions.dart';
import 'chat_adaptive.dart';
import 'chat_sessions_body.dart';
import 'chat_sessions_controller.dart';
import 'create_chat_dialog.dart';
import 'rename_chat_dialog.dart';
import 'session_actions.dart';
/// Browses server-owned sessions. Opening a row is read-only at this layer.
class ChatSessionsScreen extends StatefulWidget {
@@ -19,388 +25,152 @@ class ChatSessionsScreen extends StatefulWidget {
}
class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
late ChatRepository _repository;
late final ChatSessionsController _controller = ChatSessionsController(
ChatRepository(widget.gateway),
)..refresh();
final _search = TextEditingController();
List<JsonMap> _sessions = [];
String? _error;
bool _loading = true;
int _generation = 0;
@override
void initState() {
super.initState();
_repository = ChatRepository(widget.gateway);
_refresh();
}
@override
void didUpdateWidget(covariant ChatSessionsScreen oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.gateway != widget.gateway) {
_repository = ChatRepository(widget.gateway);
_refresh();
_controller.replaceRepository(ChatRepository(widget.gateway));
}
}
@override
void dispose() {
_generation++;
_controller.dispose();
_search.dispose();
super.dispose();
}
Future<void> _refresh() async {
final generation = ++_generation;
setState(() {
_loading = true;
_error = null;
});
try {
final sessions = await _repository.sessions();
if (!mounted || generation != _generation) return;
setState(() {
_sessions = sessions;
_loading = false;
});
} catch (error) {
if (!mounted || generation != _generation) return;
setState(() {
_error = '$error';
_loading = false;
});
}
}
Future<void> _mutate(
Future<JsonMap> Function(String) action,
String id,
) async {
try {
await action(id);
await _refresh();
} catch (error) {
if (mounted) setState(() => _error = '$error');
}
}
String _sessionId(JsonMap session) => '${session['id'] ?? ''}';
Future<void> _rename(JsonMap session) async {
final controller = TextEditingController(text: chatSessionTitle(session));
final title = await showDialog<String>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Rename chat'),
content: TextField(
controller: controller,
autofocus: true,
decoration: const InputDecoration(labelText: 'Chat name'),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () => Navigator.pop(context, controller.text.trim()),
child: const Text('Save'),
),
],
),
);
controller.dispose();
if (title == null || title.trim().isEmpty) return;
try {
await _repository.rename('${session['id']}', title);
await _refresh();
} catch (error) {
if (mounted) setState(() => _error = '$error');
}
final title = await showRenameChatDialog(context, session);
if (title == null || !mounted) return;
await _controller.rename(_sessionId(session), title);
}
Future<void> _close(JsonMap session) async {
if (!await confirmCloseChat(context, session)) return;
if (!mounted) return;
await _controller.close(_sessionId(session));
}
Future<void> _newChat() async {
List<String> directories;
List<String> backends;
try {
final catalog = await Future.wait([
_repository.directories(),
_repository.backends(),
]);
directories = catalog[0];
backends = catalog[1];
} catch (error) {
if (mounted) {
setState(() => _error = 'Unable to load chat options: $error');
}
return;
}
if (!mounted) return;
if (directories.isEmpty || backends.isEmpty) {
setState(
() => _error =
'The server has no chat directories or backends available.',
);
return;
}
final dirs = ValueNotifier<String>(directories.first);
final backend = ValueNotifier<String>(backends.first);
final title = TextEditingController(text: 'New chat');
final instructions = TextEditingController();
final result =
await showDialog<
({
String title,
String directory,
String backend,
String instructions,
})
>(
context: context,
builder: (context) => AlertDialog(
title: const Text('New chat'),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: title,
decoration: const InputDecoration(labelText: 'Name'),
),
ValueListenableBuilder<String>(
valueListenable: dirs,
builder: (context, value, _) =>
DropdownButtonFormField<String>(
initialValue: value,
decoration: const InputDecoration(
labelText: 'Server directory',
),
items: [
for (final item in directories)
DropdownMenuItem(value: item, child: Text(item)),
],
onChanged: (item) {
if (item != null) dirs.value = item;
},
),
),
ValueListenableBuilder<String>(
valueListenable: backend,
builder: (context, value, _) =>
DropdownButtonFormField<String>(
initialValue: value,
decoration: const InputDecoration(
labelText: 'Backend',
),
items: [
for (final item in backends)
DropdownMenuItem(value: item, child: Text(item)),
],
onChanged: (item) {
if (item != null) backend.value = item;
},
),
),
const Text('New chats use the server default model.'),
TextField(
controller: instructions,
decoration: const InputDecoration(
labelText: 'Instructions',
),
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () => Navigator.pop(context, (
title: title.text.trim(),
directory: dirs.value,
backend: backend.value,
instructions: instructions.text,
)),
child: const Text('Create'),
),
],
),
);
title.dispose();
dirs.dispose();
backend.dispose();
instructions.dispose();
if (result == null) return;
if (result.title.isEmpty || result.directory.isEmpty) {
setState(() => _error = 'Enter a name and server directory.');
return;
}
try {
final reply = await _repository.create(
title: result.title,
directory: result.directory,
backend: result.backend,
operationId: 'native-chat-${DateTime.now().microsecondsSinceEpoch}',
instructions: result.instructions,
);
final session = reply['chat_session'];
if (session is Map) widget.onOpen(Map<String, dynamic>.from(session));
await _refresh();
} catch (error) {
if (mounted) setState(() => _error = '$error');
}
final operationId = 'native-chat-${DateTime.now().microsecondsSinceEpoch}';
final draft = await showChatCreateDialog(
context,
repository: _controller.repository,
);
if (draft == null || !mounted) return;
final session = await _controller.create(
title: draft.title,
directory: draft.directory,
backend: draft.backend,
instructions: draft.instructions,
operationId: operationId,
);
if (session != null && mounted) widget.onOpen(session);
}
@override
Widget build(BuildContext context) {
final visible = filterChatSessions(_sessions, _search.text);
final starred = visible
.where((s) => s['starred'] == true && s['closed_at'] == null)
.toList();
final open = visible
.where((s) => s['starred'] != true && s['closed_at'] == null)
.toList();
final closed = visible.where((s) => s['closed_at'] != null).toList();
return Scaffold(
appBar: AppBar(
title: const Text('Chats'),
actions: [
IconButton(
onPressed: _newChat,
tooltip: 'New chat',
icon: const Icon(Icons.add),
),
IconButton(
onPressed: _refresh,
tooltip: 'Refresh',
icon: const Icon(Icons.refresh),
),
],
),
body: Column(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: TextField(
return ListenableBuilder(
listenable: _controller,
builder: (context, _) {
final body = Column(
children: [
ChatSearchField(
controller: _search,
onChanged: (_) => setState(() {}),
decoration: const InputDecoration(
prefixIcon: Icon(Icons.search),
labelText: 'Search chats',
),
if (_controller.error != null)
ChatErrorNotice(
message: _controller.error!,
onRetry: _controller.refresh,
),
Expanded(
child: ChatSessionsBody(
sessions: _controller.sessions,
query: _search.text,
loading: _controller.loading,
error: _controller.error,
onOpen: widget.onOpen,
onRename: _rename,
onClose: _close,
onReopen: (session) => _controller.reopen(_sessionId(session)),
onStar: (session) => _controller.star(
_sessionId(session),
session['starred'] != true,
),
onClearSearch: () {
_search.clear();
setState(() {});
},
),
),
),
if (_error != null)
MaterialBanner(
content: Text(_error!),
actions: [
TextButton(onPressed: _refresh, child: const Text('Retry')),
],
),
Expanded(
child: _loading && _sessions.isEmpty
? const Center(child: CircularProgressIndicator())
: ListView(
children: [
if (starred.isNotEmpty) _section('Starred', starred),
if (open.isNotEmpty) _section('Chats', open),
if (closed.isNotEmpty) _section('Closed', closed),
if (visible.isEmpty && !_loading)
ListTile(
title: Text(
_sessions.isEmpty
? 'No chats yet.'
: 'No chats match "${_search.text.trim()}".',
),
trailing: _search.text.isEmpty
? null
: TextButton(
onPressed: () {
_search.clear();
setState(() {});
},
child: const Text('Clear search'),
),
),
],
],
);
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: const Text('Chats'),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
ChatBarAction(
key: const Key('chat-new-chat'),
label: 'New chat',
onPressed: _newChat,
materialIcon: Icons.add,
cupertinoIcon: CupertinoIcons.add,
),
),
],
),
floatingActionButton: FloatingActionButton.extended(
onPressed: _newChat,
icon: const Icon(Icons.add),
label: const Text('New chat'),
),
);
}
Widget _section(String title, List<JsonMap> sessions) => ExpansionTile(
title: Text(title),
initiallyExpanded: true,
children: [
for (final group in groupChatSessions(sessions)) ...[
if (groupChatSessions(sessions).length > 1)
ListTile(
dense: true,
leading: const Icon(Icons.folder_outlined),
title: Text(
group.directory.isEmpty ? 'No directory' : group.directory,
ChatBarAction(
key: const Key('chat-refresh'),
label: 'Refresh',
onPressed: _controller.refresh,
materialIcon: Icons.refresh,
cupertinoIcon: CupertinoIcons.refresh,
),
],
),
),
child: SafeArea(child: body),
);
}
return Scaffold(
appBar: AppBar(
title: const Text('Chats'),
actions: [
ChatBarAction(
key: const Key('chat-new-chat'),
label: 'New chat',
onPressed: _newChat,
materialIcon: Icons.add,
cupertinoIcon: CupertinoIcons.add,
),
ChatBarAction(
key: const Key('chat-refresh'),
label: 'Refresh',
onPressed: _controller.refresh,
materialIcon: Icons.refresh,
cupertinoIcon: CupertinoIcons.refresh,
),
],
),
for (final session in group.sessions) _row(session),
],
],
);
Widget _row(JsonMap session) {
final id = '${session['id'] ?? ''}';
final isClosed = session['closed_at'] != null;
final starred = session['starred'] == true;
return ListTile(
leading: Icon(
session['running'] == true
? Icons.sync
: starred
? Icons.star
: Icons.chat_bubble_outline,
),
title: Text(chatSessionTitle(session)),
subtitle: Text(
'${session['directory'] ?? ''}${session['running'] == true
? ' · Streaming'
: session['unseen'] == true
? ' · New'
: ''}',
),
onTap: () => widget.onOpen(session),
trailing: PopupMenuButton<String>(
tooltip: 'Chat actions',
onSelected: (value) {
if (value == 'rename') {
_rename(session);
}
if (value == 'star') {
_mutate((id) => _repository.star(id, !starred), id);
}
if (value == 'close') {
_mutate(_repository.close, id);
}
if (value == 'reopen') {
_mutate(_repository.reopen, id);
}
},
itemBuilder: (_) => [
const PopupMenuItem(value: 'rename', child: Text('Rename')),
PopupMenuItem(
value: 'star',
child: Text(starred ? 'Remove from Starred' : 'Star'),
body: body,
floatingActionButton: FloatingActionButton.extended(
key: const Key('chat-new-chat-fab'),
onPressed: _newChat,
icon: const Icon(Icons.add),
label: const Text('New chat'),
),
if (isClosed)
const PopupMenuItem(value: 'reopen', child: Text('Reopen'))
else
const PopupMenuItem(value: 'close', child: Text('Close')),
],
),
);
},
);
}
}
@@ -0,0 +1,222 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../data/chat_repository.dart';
import 'chat_adaptive.dart';
import 'chat_create_fields.dart';
class ChatDraft {
const ChatDraft({
required this.title,
required this.directory,
required this.backend,
required this.instructions,
});
final String title;
final String directory;
final String backend;
final String instructions;
}
Future<ChatDraft?> showChatCreateDialog(
BuildContext context, {
required ChatRepository repository,
}) {
final dialog = CreateChatDialog(repository: repository);
return chatControlsStyleOf(context) == ChatControlsStyle.cupertino
? showCupertinoDialog<ChatDraft>(context: context, builder: (_) => dialog)
: showDialog<ChatDraft>(context: context, builder: (_) => dialog);
}
class CreateChatDialog extends StatefulWidget {
const CreateChatDialog({super.key, required this.repository});
final ChatRepository repository;
@override
State<CreateChatDialog> createState() => _CreateChatDialogState();
}
class _CreateChatDialogState extends State<CreateChatDialog> {
final _name = TextEditingController(text: 'New chat');
final _instructions = TextEditingController();
List<String> _directories = const [];
List<String> _backends = const [];
String? _directory;
String? _backend;
String? _catalogError;
String? _formError;
bool _loading = true;
int _attempt = 0;
@override
void initState() {
super.initState();
_loadCatalog();
}
@override
void dispose() {
_attempt++;
_name.dispose();
_instructions.dispose();
super.dispose();
}
Future<void> _loadCatalog() async {
final attempt = ++_attempt;
setState(() {
_loading = true;
_catalogError = null;
});
try {
final values = await Future.wait([
widget.repository.directories(),
widget.repository.backends(),
]);
if (!mounted || attempt != _attempt) return;
setState(() {
_directories = values[0];
_backends = values[1];
_directory = _directories.contains(_directory)
? _directory
: _directories.isEmpty
? null
: _directories.first;
_backend = _backends.contains(_backend)
? _backend
: _backends.isEmpty
? null
: _backends.first;
_loading = false;
});
} catch (error) {
if (!mounted || attempt != _attempt) return;
setState(() {
_catalogError = '$error';
_loading = false;
});
}
}
bool get _catalogReady =>
!_loading &&
_catalogError == null &&
_directories.isNotEmpty &&
_backends.isNotEmpty;
void _submit() {
if (!_catalogReady) return;
final title = _name.text.trim();
final directory = _directory ?? '';
if (title.isEmpty || directory.isEmpty) {
setState(() => _formError = 'Enter a name and server directory.');
return;
}
Navigator.pop(
context,
ChatDraft(
title: title,
directory: directory,
backend: _backend ?? '',
instructions: _instructions.text,
),
);
}
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final content = SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (cupertino)
CupertinoTextField(
key: const Key('chat-create-name'),
controller: _name,
placeholder: 'Name',
)
else
TextField(
key: const Key('chat-create-name'),
controller: _name,
decoration: const InputDecoration(labelText: 'Name'),
),
const SizedBox(height: 12),
ChatCatalogFields(
loading: _loading,
error: _catalogError,
directories: _directories,
backends: _backends,
directory: _directory,
backend: _backend,
onDirectory: (value) => setState(() => _directory = value),
onBackend: (value) => setState(() => _backend = value),
onRetry: _loadCatalog,
),
if (_catalogReady) ...[
const SizedBox(height: 8),
const Text('New chats use the server default model.'),
],
const SizedBox(height: 12),
if (cupertino)
CupertinoTextField(
key: const Key('chat-create-instructions'),
controller: _instructions,
placeholder: 'Instructions',
minLines: 1,
maxLines: 3,
)
else
TextField(
key: const Key('chat-create-instructions'),
controller: _instructions,
decoration: const InputDecoration(labelText: 'Instructions'),
minLines: 1,
maxLines: 3,
),
if (_formError != null) ...[
const SizedBox(height: 8),
Text(_formError!),
],
],
),
);
if (cupertino) {
return CupertinoAlertDialog(
title: const Text('New chat'),
content: content,
actions: [
CupertinoDialogAction(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
CupertinoDialogAction(
isDefaultAction: true,
onPressed: _catalogReady ? _submit : null,
child: const Text('Create'),
),
],
);
}
return AlertDialog(
title: const Text('New chat'),
content: content,
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
FilledButton(
onPressed: _catalogReady ? _submit : null,
child: const Text('Create'),
),
],
);
}
}
@@ -0,0 +1,107 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../domain/chat_sessions.dart';
import 'chat_adaptive.dart';
/// Renames one session. Save is disabled while the trimmed name is blank,
/// matching the web dialog.
Future<String?> showRenameChatDialog(BuildContext context, JsonMap session) {
final dialog = _RenameChatDialog(initialTitle: chatSessionTitle(session));
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});
final String initialTitle;
@override
State<_RenameChatDialog> createState() => _RenameChatDialogState();
}
class _RenameChatDialogState extends State<_RenameChatDialog> {
late final TextEditingController _title =
TextEditingController(text: widget.initialTitle)
..selection = TextSelection(
baseOffset: 0,
extentOffset: widget.initialTitle.length,
);
@override
void dispose() {
_title.dispose();
super.dispose();
}
void _save() {
final title = _title.text.trim();
if (title.isEmpty) return;
Navigator.pop(context, title);
}
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<TextEditingValue>(
valueListenable: _title,
builder: (context, value, _) {
final canSave = value.text.trim().isNotEmpty;
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
return CupertinoAlertDialog(
title: const Text('Rename chat'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
CupertinoTextField(
key: const Key('chat-rename-field'),
controller: _title,
autofocus: true,
placeholder: 'Name',
),
const SizedBox(height: 8),
const Text('This name is shared with every device.'),
],
),
actions: [
CupertinoDialogAction(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
CupertinoDialogAction(
isDefaultAction: true,
onPressed: canSave ? _save : null,
child: const Text('Save'),
),
],
);
}
return AlertDialog(
title: const Text('Rename chat'),
content: TextField(
key: const Key('chat-rename-field'),
controller: _title,
autofocus: true,
decoration: const InputDecoration(
labelText: 'Name',
helperText: 'This name is shared with every device.',
helperMaxLines: 2,
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
FilledButton(
onPressed: canSave ? _save : null,
child: const Text('Save'),
),
],
);
},
);
}
}
@@ -0,0 +1,161 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../domain/chat_sessions.dart';
import 'chat_adaptive.dart';
import 'session_row_style.dart';
enum SessionAction { rename, close, reopen }
/// The close confirmation's body, matching the web client's explanation.
String closeChatConfirmation(String title) =>
'Closes "$title" and marks it closed on every device. '
'A turn that is running is stopped first. '
'Nothing is deleted — the chat and its history are kept, '
'and you can reopen it from the list.';
class SessionStarButton extends StatelessWidget {
const SessionStarButton({
super.key,
required this.session,
required this.onPressed,
});
final JsonMap session;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
final starred = session['starred'] == true;
final label = starred ? 'Unstar chat' : 'Star chat';
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
return Semantics(
label: label,
button: true,
child: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: onPressed,
child: Icon(starred ? CupertinoIcons.star_fill : CupertinoIcons.star),
),
);
}
return IconButton(
tooltip: label,
onPressed: onPressed,
icon: Icon(starred ? Icons.star : Icons.star_border),
);
}
}
class SessionActionsButton extends StatelessWidget {
const SessionActionsButton({
super.key,
required this.session,
required this.onSelected,
this.duplicateTitles = const {},
});
final JsonMap session;
final ValueChanged<SessionAction> onSelected;
final Set<String> duplicateTitles;
@override
Widget build(BuildContext context) {
final label = sessionActionsLabel(session, duplicateTitles);
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
return Semantics(
label: label,
button: true,
child: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: () => _showSheet(context),
child: const Icon(CupertinoIcons.ellipsis),
),
);
}
return PopupMenuButton<SessionAction>(
tooltip: label,
onSelected: onSelected,
itemBuilder: (context) => _menuItems(session),
);
}
Future<void> _showSheet(BuildContext context) async {
final action = await showCupertinoModalPopup<SessionAction>(
context: context,
builder: (sheetContext) => CupertinoActionSheet(
title: Text(chatSessionTitle(session)),
actions: [
for (final item in _items(session))
CupertinoActionSheetAction(
onPressed: () => Navigator.pop(sheetContext, item.action),
child: Text(item.label),
),
],
cancelButton: CupertinoActionSheetAction(
onPressed: () => Navigator.pop(sheetContext),
child: const Text('Cancel'),
),
),
);
if (action != null && context.mounted) onSelected(action);
}
}
List<PopupMenuEntry<SessionAction>> _menuItems(JsonMap session) => [
for (final item in _items(session))
PopupMenuItem(value: item.action, child: Text(item.label)),
];
List<({SessionAction action, String label})> _items(JsonMap session) {
final isClosed = session['closed_at'] != null;
return [
(action: SessionAction.rename, label: 'Rename…'),
isClosed
? (action: SessionAction.reopen, label: 'Reopen')
: (action: SessionAction.close, label: 'Close chat…'),
];
}
Future<bool> confirmCloseChat(BuildContext context, JsonMap session) async {
final title = chatSessionTitle(session);
final body = closeChatConfirmation(title);
final confirmed = chatControlsStyleOf(context) == ChatControlsStyle.cupertino
? await showCupertinoDialog<bool>(
context: context,
builder: (context) => CupertinoAlertDialog(
title: const Text('Close chat?'),
content: Text(body),
actions: [
CupertinoDialogAction(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
CupertinoDialogAction(
isDestructiveAction: true,
onPressed: () => Navigator.pop(context, true),
child: const Text('Close chat'),
),
],
),
)
: await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Close chat?'),
content: Text(body),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () => Navigator.pop(context, true),
child: const Text('Close chat'),
),
],
),
);
return confirmed == true;
}
@@ -0,0 +1,134 @@
import 'package:flutter/cupertino.dart';
import '../../../../core/api_gateway.dart';
import '../../domain/chat_sessions.dart';
import 'chat_adaptive.dart';
import 'chat_sessions_body.dart';
import 'session_actions.dart';
import 'session_row_style.dart';
class CupertinoSessionList extends StatelessWidget {
const CupertinoSessionList({
super.key,
required this.sections,
required this.emptyMessage,
required this.duplicateTitles,
required this.onOpen,
required this.onRename,
required this.onClose,
required this.onReopen,
required this.onStar,
required this.onClearSearch,
});
final List<ChatSessionSection> sections;
final String? emptyMessage;
final Set<String> duplicateTitles;
final ValueChanged<JsonMap> onOpen;
final ValueChanged<JsonMap> onRename;
final ValueChanged<JsonMap> onClose;
final ValueChanged<JsonMap> onReopen;
final ValueChanged<JsonMap> onStar;
final VoidCallback? onClearSearch;
@override
Widget build(BuildContext context) {
return ListView(
padding: const EdgeInsets.only(bottom: 24),
children: [
for (final section in sections) ..._section(section),
if (emptyMessage != null)
ChatCupertinoMessage(
message: emptyMessage!,
actionLabel: onClearSearch == null ? null : 'Clear search',
onAction: onClearSearch,
),
],
);
}
List<CupertinoListSection> _section(ChatSessionSection section) {
final groups = groupChatSessions(section.sessions);
return [
for (final group in groups)
CupertinoListSection.insetGrouped(
header: Text(
groups.length > 1
? '${section.title} · ${group.directory.isEmpty ? 'No directory' : group.directory}'
: section.title,
),
children: [
for (final session in group.sessions)
_CupertinoSessionRow(
session: session,
duplicateTitles: duplicateTitles,
onOpen: onOpen,
onRename: onRename,
onClose: onClose,
onReopen: onReopen,
onStar: onStar,
),
],
),
];
}
}
class _CupertinoSessionRow extends StatelessWidget {
const _CupertinoSessionRow({
required this.session,
required this.duplicateTitles,
required this.onOpen,
required this.onRename,
required this.onClose,
required this.onReopen,
required this.onStar,
});
final JsonMap session;
final Set<String> duplicateTitles;
final ValueChanged<JsonMap> onOpen;
final ValueChanged<JsonMap> onRename;
final ValueChanged<JsonMap> onClose;
final ValueChanged<JsonMap> onReopen;
final ValueChanged<JsonMap> onStar;
@override
Widget build(BuildContext context) {
final id = '${session['id'] ?? ''}';
return CupertinoListTile(
key: Key('chat-row-$id'),
leading: Icon(sessionCupertinoIcon(session)),
title: Text(chatSessionTitle(session)),
subtitle: Text(sessionSubtitle(session)),
onTap: () => onOpen(session),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
SessionStarButton(
key: Key('chat-star-$id'),
session: session,
onPressed: () => onStar(session),
),
SessionActionsButton(
key: Key('chat-actions-$id'),
session: session,
duplicateTitles: duplicateTitles,
onSelected: _select,
),
],
),
);
}
void _select(SessionAction action) {
switch (action) {
case SessionAction.rename:
onRename(session);
case SessionAction.close:
onClose(session);
case SessionAction.reopen:
onReopen(session);
}
}
}
@@ -0,0 +1,140 @@
import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../domain/chat_sessions.dart';
import 'chat_sessions_body.dart';
import 'session_actions.dart';
import 'session_row_style.dart';
class MaterialSessionList extends StatelessWidget {
const MaterialSessionList({
super.key,
required this.sections,
required this.emptyMessage,
required this.duplicateTitles,
required this.onOpen,
required this.onRename,
required this.onClose,
required this.onReopen,
required this.onStar,
required this.onClearSearch,
});
final List<ChatSessionSection> sections;
final String? emptyMessage;
final Set<String> duplicateTitles;
final ValueChanged<JsonMap> onOpen;
final ValueChanged<JsonMap> onRename;
final ValueChanged<JsonMap> onClose;
final ValueChanged<JsonMap> onReopen;
final ValueChanged<JsonMap> onStar;
final VoidCallback? onClearSearch;
@override
Widget build(BuildContext context) {
return ListView(
children: [
for (final section in sections) _section(section),
if (emptyMessage != null)
ListTile(
title: Text(emptyMessage!),
trailing: onClearSearch == null
? null
: TextButton(
onPressed: onClearSearch,
child: const Text('Clear search'),
),
),
],
);
}
Widget _section(ChatSessionSection section) {
final groups = groupChatSessions(section.sessions);
return ExpansionTile(
title: Text(section.title),
initiallyExpanded: true,
children: [
for (final group in groups) ...[
if (groups.length > 1)
ListTile(
dense: true,
leading: const Icon(Icons.folder_outlined),
title: Text(
group.directory.isEmpty ? 'No directory' : group.directory,
),
),
for (final session in group.sessions)
_MaterialSessionRow(
session: session,
duplicateTitles: duplicateTitles,
onOpen: onOpen,
onRename: onRename,
onClose: onClose,
onReopen: onReopen,
onStar: onStar,
),
],
],
);
}
}
class _MaterialSessionRow extends StatelessWidget {
const _MaterialSessionRow({
required this.session,
required this.duplicateTitles,
required this.onOpen,
required this.onRename,
required this.onClose,
required this.onReopen,
required this.onStar,
});
final JsonMap session;
final Set<String> duplicateTitles;
final ValueChanged<JsonMap> onOpen;
final ValueChanged<JsonMap> onRename;
final ValueChanged<JsonMap> onClose;
final ValueChanged<JsonMap> onReopen;
final ValueChanged<JsonMap> onStar;
@override
Widget build(BuildContext context) {
final id = '${session['id'] ?? ''}';
return ListTile(
key: Key('chat-row-$id'),
leading: Icon(sessionMaterialIcon(session)),
title: Text(chatSessionTitle(session)),
subtitle: Text(sessionSubtitle(session)),
onTap: () => onOpen(session),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
SessionStarButton(
key: Key('chat-star-$id'),
session: session,
onPressed: () => onStar(session),
),
SessionActionsButton(
key: Key('chat-actions-$id'),
session: session,
duplicateTitles: duplicateTitles,
onSelected: (action) => _select(action),
),
],
),
);
}
void _select(SessionAction action) {
switch (action) {
case SessionAction.rename:
onRename(session);
case SessionAction.close:
onClose(session);
case SessionAction.reopen:
onReopen(session);
}
}
}
@@ -0,0 +1,51 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../domain/chat_sessions.dart';
/// Titles shared by more than one visible session, so row action labels can
/// add the session id the way the web client does.
Set<String> duplicateChatTitles(Iterable<JsonMap> sessions) {
final seen = <String>{};
final duplicates = <String>{};
for (final session in sessions) {
final title = chatSessionTitle(session);
if (!seen.add(title)) duplicates.add(title);
}
return duplicates;
}
String sessionActionsLabel(JsonMap session, Set<String> duplicateTitles) {
final title = chatSessionTitle(session);
return duplicateTitles.contains(title)
? 'Chat actions for $title (${session['id'] ?? ''})'
: 'Chat actions for $title';
}
String sessionSubtitle(JsonMap session) {
final directory = '${session['directory'] ?? ''}';
switch (chatSessionActivity(
running: session['running'] == true,
unseen: session['unseen'] == true,
)) {
case 'streaming':
return '$directory · Streaming';
case 'new':
return '$directory · New';
default:
return directory;
}
}
IconData sessionMaterialIcon(JsonMap session) {
if (session['running'] == true) return Icons.sync;
if (session['starred'] == true) return Icons.star;
return Icons.chat_bubble_outline;
}
IconData sessionCupertinoIcon(JsonMap session) {
if (session['running'] == true) return CupertinoIcons.arrow_2_circlepath;
if (session['starred'] == true) return CupertinoIcons.star_fill;
return CupertinoIcons.chat_bubble;
}
+163
View File
@@ -0,0 +1,163 @@
# C1b — Chat session browser completion
The 406-line sessions screen is split into a controller, adaptive primitives,
session groups/rows, action dialogs, a rename dialog and a create dialog. The
server directory and backend catalogs, the instructions field, the closed/star
grouping and the distinct empty/no-match states are retained. No repository,
domain, shell or pubspec file changed.
The UI review's must-fix is addressed: Cupertino no-match, empty and error
messages are no longer forced through `CupertinoListTile`'s one-line title. They
use a wrapping grouped card with `Clear search`/`Retry` as separate buttons. The
same turn also fixed the related behavioural findings: a failed initial load no
longer also shows the empty-server message, creating a chat opens it without
waiting for the list refresh, blank rename disables Save, and row action labels
name their session (adding the id when titles repeat).
The second UI review's must-fixes are also addressed:
- `ChatCupertinoMessage` now sets `DefaultTextStyle.merge` from
`CupertinoTheme.of(context).textTheme.textStyle`. Mounted under a bare
`MaterialApp` (the screen's iOS/macOS path, no `Material` ancestor), its text
previously inherited MaterialApp's intentional "missing Material" fallback
style (48px red monospace with a double yellow underline). The card now
renders as ordinary Cupertino body text in that configuration.
- The Material rename dialog sets `helperMaxLines: 2`, so "This name is shared
with every device." wraps instead of being ellipsised at 2.0x text scale.
## Source layout
All paths under `lib/features/chat/ui/sessions/` (1,584 lines total):
| File | Lines | Responsibility |
| --- | ---: | --- |
| `chat_sessions_screen.dart` | 176 | Screen composition, toolbar/FAB, controller wiring |
| `chat_sessions_controller.dart` | 111 | List state, generation-guarded refresh, row actions, create |
| `chat_sessions_body.dart` | 97 | Filtering, starred/open/closed sections, duplicate titles |
| `session_list_material.dart` | 140 | Material list sections and rows |
| `session_list_cupertino.dart` | 134 | Cupertino list sections and rows |
| `session_row_style.dart` | 51 | Shared subtitle, icons and action labels |
| `session_actions.dart` | 161 | Star control, actions menu/sheet, close confirmation |
| `rename_chat_dialog.dart` | 107 | Rename dialog and its blank-name guard |
| `create_chat_dialog.dart` | 222 | Create state, draft fields, submit |
| `chat_create_fields.dart` | 185 | Catalog loading/error/retry and directory/backend pickers |
| `chat_adaptive.dart` | 200 | Style detection, bar actions, search, wrapping message card, loading |
`chatControlsStyleOf` chooses Cupertino for a Cupertino app (no `MaterialApp`
ancestor) and for iOS/macOS Material themes; Material otherwise. The Cupertino
branch uses only Cupertino controls (`CupertinoPageScaffold`,
`CupertinoNavigationBar`, `CupertinoSearchTextField`, `CupertinoListSection`/
`CupertinoListTile`, `CupertinoAlertDialog`, `CupertinoActionSheet`,
`CupertinoTextField`, `CupertinoActivityIndicator`). It therefore has no
Material ancestor dependency. The `SafeArea` in that branch keeps the search
field below the translucent navigation bar (the first browser capture caught
this overlap).
Behavior:
- `chat_sessions`, `chat_directories`, `chat_backends` and `chat_create` use the
existing repository envelopes; no fallback directory or backend is invented.
- A catalog failure keeps the dialog open, shows the server reason with Retry,
and retains the typed name and instructions.
- Closed starred rows appear once, only under Closed.
- Directory headings appear only when a section has more than one directory.
- Empty and search-no-match states stay distinct; "Clear search" restores the
list. In the Cupertino branch the message and its action are a wrapping
`ChatCupertinoMessage` card, and a failed load uses the same card for the
server reason with Retry. The failed initial load no longer also renders the
empty-server message. The card supplies a Cupertino text style, so it renders
normally when the Cupertino branch is mounted under the app's bare
`MaterialApp` root instead of a `Material`/`CupertinoApp`.
- Creating a chat opens it as soon as `chat_create` replies; the list refresh
continues in the background, so a slow listing cannot look like a failed
create.
- Star, rename, close (with the web's confirmation wording), reopen and row
opening keep their existing request shapes. Save is disabled while the
rename name is blank, matching the web dialog.
- Row action labels are `Chat actions for {title}`, adding `({id})` when two
visible sessions share a title, matching the web's accessible label.
## Checks (actual)
- `flutter test test/features/chat/ui/sessions`: 24 widget tests, all passed.
They cover Material and Cupertino list branches, both create branches, the
delayed catalog failure with draft retention and Retry, rename/close/reopen/
star, blank-name Save disabling in both branches, the close confirmation,
catalog-empty state, stale refresh ordering, dispose while a reply is
pending, opening a created chat before the refresh completes, Cupertino
no-match/error wrapping (including 2x text scale), separate Clear search
semantics, duplicate-title action labels, the Cupertino message card under a
bare `MaterialApp` iOS theme (empty, no-match, long error style), and the
Material rename helper at 2x text scale. The three MaterialApp-hosted tests
fail when the `DefaultTextStyle` merge is removed (verified).
- `flutter test`: 46 tests passed.
- `flutter analyze`: no issues.
- `flutter build web`: built `lib/main.dart` successfully.
- Fixture probe built for both variants and run in real headless Chrome through
the local loopback server in `tool/chat_sessions_probe.mjs`. Each run loaded
the list, opened the create dialog, confirmed the rendered catalog controls,
opened a row action menu/sheet, and captured PNGs. The probe now clicks the
per-session action label and requires `Rename…` in the action labels instead
of accepting the dismiss barrier. Material and Cupertino PNGs were inspected.
Captures from this turn's fix (shared with later stages under
`public/c1b-fix/`):
- `/Users/alan/.local/share/pipelines/data/artifacts/42/public/c1b-fix/cupertino-fix-search-no-match.png` — light, 390x844, long query wraps in full with Clear search on its own line.
- `.../cupertino-fix-search-no-match-dark.png` — same state in dark appearance.
- `.../cupertino-fix-load-error.png` — long server reason wraps; Retry is separate and the empty-server message is absent.
- `.../cupertino-fix-list-phone.png` and `.../material-fix-actions.png` — probe list and actions after the label change.
Probe commands (run from `app/`):
```sh
flutter build web -t tool/chat_sessions_probe_entry.dart \
--dart-define=CHAT_PROBE_STYLE=material --output build/probe-material-fix
PROBE_WEB_ROOT="$PWD/build/probe-material-fix" PROBE_VARIANT=material \
OPENCODE_ARTIFACT_DIR=/private/var/folders/jp/q0qvjyg54fl_c5vhhk1ylz2m0000gn/T/opencode/chat-sessions-capture \
node tool/chat_sessions_probe.mjs
# repeat with CHAT_PROBE_STYLE=cupertino and build/probe-cupertino-fix
```
Captures for the second review's fixes (same `public/c1b-fix/` folder, real
headless Chrome at 390x844 through a temporary fixture entry that was deleted
afterwards; the shipped probe entry was not changed):
- `platform-default-empty-phone.png` — `MaterialApp` default theme (macOS →
Cupertino branch), empty server. The message is ordinary body text.
- `platform-default-search-no-match-phone.png` — long query; message wraps and
`Clear search` is a separate control.
- `platform-default-error-phone.png` — long server reason wraps; `Retry` is
separate and no empty-server message appears.
- `material-scale2-rename-phone.png` — Material rename dialog at 2.0x text
scale; the helper sentence wraps onto two lines in full.
## Not changed in this turn
These review notes remain advisory and were left alone because they predate
C1b or are native behaviour:
- The Material FAB can still cover the last row's star/actions when the list
exactly fills a phone viewport. Same as the base screen.
- Raw exception text (`Bad state: …`, `Exception: …`) is still shown to the
operator; wording belongs to a separate error-presentation change.
- Cupertino row titles/subtitles still truncate to one line (standard
`CupertinoListTile` behaviour). The no-match/error messages no longer do.
- The Cupertino-under-MaterialApp probe still takes its accent from the ambient
`ThemeData`. No theme override was added.
## Remaining gaps
- Mobile is unverified: no Android/iOS builds, devices or installs were run.
Source is portable but only web was exercised.
- Browser evidence uses the fixture gateway, not an authenticated live server.
No real chat was created, renamed, closed or starred in the browser; those
request paths are covered by widget tests.
- The Cupertino list/actions probes use the local Chrome dark appearance; the
no-match fix was captured in both light and dark. The long-error capture came
from a temporary private fixture entry that was deleted afterwards.
- The create dialog still omits the web's default instruction text and its
backend segmented control; it preserves the existing name/directory/backend/
instructions request fields.
- This stage did not commit. The changes remain an uncommitted working-tree
candidate for the next stage.
@@ -0,0 +1,217 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'chat_test_harness.dart';
import 'fake_chat_gateway.dart';
void main() {
testWidgets(
'material create dialog retains the draft through a delayed catalog failure and retry',
(tester) async {
final gateway = FakeChatGateway();
final directories = Completer<JsonMap>();
gateway.directoriesHandler = () => directories.future;
JsonMap? opened;
await pumpMaterialChat(
tester,
gateway,
onOpen: (session) => opened = session,
);
await tester.tap(find.byKey(const Key('chat-new-chat-fab')));
await tester.pump();
await tester.pump(const Duration(milliseconds: 400));
expect(find.text('Loading directories…'), findsOneWidget);
await tester.enterText(
find.byKey(const Key('chat-create-name')),
'Draft chat',
);
await tester.enterText(
find.byKey(const Key('chat-create-instructions')),
'Keep me',
);
directories.completeError(
StateError('Server did not return chat directories.'),
);
await tester.pump();
await tester.pump();
expect(
find.textContaining('Unable to load chat options'),
findsOneWidget,
);
expect(find.text('Draft chat'), findsOneWidget);
expect(find.text('Keep me'), findsOneWidget);
gateway.directoriesHandler = () async => {
'chat_directories': ['/work'],
};
await tester.tap(find.text('Retry'));
await tester.pumpAndSettle();
expect(find.textContaining('Unable to load chat options'), findsNothing);
expect(
find.byKey(const Key('chat-create-server-directory')),
findsOneWidget,
);
expect(
find.text('New chats use the server default model.'),
findsOneWidget,
);
await tester.enterText(find.byKey(const Key('chat-create-name')), '');
await tester.tap(find.text('Create'));
await tester.pump();
expect(find.text('Enter a name and server directory.'), findsOneWidget);
expect(gateway.count('chat_create'), 0);
await tester.enterText(
find.byKey(const Key('chat-create-name')),
'Draft chat',
);
await tester.tap(find.text('Create'));
await tester.pumpAndSettle();
final fields =
gateway.lastFields('chat_create')!['chat_create']! as JsonMap;
expect(fields['title'], 'Draft chat');
expect(fields['directory'], '/work');
expect(fields.containsKey('backend'), isFalse);
expect(fields['instructions'], 'Keep me');
expect(fields.containsKey('operation_id'), isTrue);
expect(opened?['id'], 'created');
},
);
testWidgets('Cupertino create dialog keeps the draft when catalogs fail', (
tester,
) async {
final gateway = FakeChatGateway();
gateway.directoriesHandler = () =>
Future.error(StateError('Server did not return chat directories.'));
await pumpCupertinoChat(tester, gateway);
await tester.tap(find.byKey(const Key('chat-new-chat')));
await tester.pumpAndSettle();
expect(find.textContaining('Unable to load chat options'), findsOneWidget);
await tester.enterText(
find.byKey(const Key('chat-create-name')),
'Cupertino draft',
);
await tester.enterText(
find.byKey(const Key('chat-create-instructions')),
'Keep me too',
);
expect(find.text('Cupertino draft'), findsOneWidget);
expect(find.text('Keep me too'), findsOneWidget);
gateway.directoriesHandler = () async => {
'chat_directories': ['/work'],
};
await tester.tap(find.text('Retry'));
await tester.pumpAndSettle();
expect(find.textContaining('Unable to load chat options'), findsNothing);
expect(find.text('Cupertino draft'), findsOneWidget);
expect(find.text('Keep me too'), findsOneWidget);
});
testWidgets('material create dialog reports an empty catalog', (
tester,
) async {
final gateway = FakeChatGateway();
gateway.directoriesHandler = () async => {'chat_directories': []};
await pumpMaterialChat(tester, gateway);
await tester.tap(find.byKey(const Key('chat-new-chat-fab')));
await tester.pumpAndSettle();
expect(
find.text('The server has no chat directories or backends available.'),
findsOneWidget,
);
});
testWidgets('Cupertino create dialog uses native selectors and fields', (
tester,
) async {
final gateway = FakeChatGateway();
JsonMap? opened;
await pumpCupertinoChat(
tester,
gateway,
onOpen: (session) => opened = session,
);
await tester.tap(find.byKey(const Key('chat-new-chat')));
await tester.pumpAndSettle();
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
expect(find.text('Server directory: /work'), findsOneWidget);
expect(find.text('Backend: opencode'), findsOneWidget);
await tester.tap(find.byKey(const Key('chat-create-backend')));
await tester.pumpAndSettle();
await tester.tap(find.text('codex'));
await tester.pumpAndSettle();
expect(find.text('Backend: codex'), findsOneWidget);
await tester.tap(find.byKey(const Key('chat-create-server-directory')));
await tester.pumpAndSettle();
expect(find.text('/archive'), findsOneWidget);
await tester.tap(find.text('/archive'));
await tester.pumpAndSettle();
expect(find.text('Server directory: /archive'), findsOneWidget);
await tester.enterText(
find.byKey(const Key('chat-create-name')),
'Cupertino draft',
);
await tester.enterText(
find.byKey(const Key('chat-create-instructions')),
'Be careful',
);
await tester.tap(find.text('Create'));
await tester.pumpAndSettle();
final fields =
gateway.lastFields('chat_create')!['chat_create']! as JsonMap;
expect(fields['title'], 'Cupertino draft');
expect(fields['directory'], '/archive');
expect(fields['backend'], 'codex');
expect(fields['instructions'], 'Be careful');
expect(opened?['id'], 'created');
});
testWidgets('a created chat opens before the list refresh completes', (
tester,
) async {
final gateway = FakeChatGateway();
JsonMap? opened;
await pumpMaterialChat(
tester,
gateway,
onOpen: (session) => opened = session,
);
final refresh = Completer<JsonMap>();
gateway.pendingSessions.add(refresh);
await tester.tap(find.byKey(const Key('chat-new-chat-fab')));
await tester.pumpAndSettle();
await tester.tap(find.text('Create'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
expect(gateway.count('chat_create'), 1);
expect(gateway.count('chat_sessions'), 2);
expect(
opened?['id'],
'created',
reason: 'a slow listing must not hold up opening the new chat',
);
refresh.complete({'chat_sessions': []});
await tester.pumpAndSettle();
});
}
@@ -0,0 +1,91 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'chat_test_harness.dart';
import 'fake_chat_gateway.dart';
/// The message card is also mounted under a bare `MaterialApp` (the screen's
/// iOS/macOS path). Without its own style, `Text` inherits MaterialApp's
/// "missing Material" fallback: 48px, red, monospace with a double underline.
void main() {
testWidgets('Cupertino empty message under MaterialApp uses normal text', (
tester,
) async {
usePhoneSurface(tester);
await pumpIosMaterialChat(tester, FakeChatGateway());
expect(find.byType(CupertinoPageScaffold), findsOneWidget);
expect(find.byType(Scaffold), findsNothing);
const message = 'No chat sessions on this server yet.';
expect(find.text(message), findsOneWidget);
expectNormalTextStyle(tester, message);
});
testWidgets('Cupertino no-match message under MaterialApp wraps normally', (
tester,
) async {
usePhoneSurface(tester);
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpIosMaterialChat(tester, gateway);
await tester.enterText(
find.byType(CupertinoSearchTextField),
'zzz-no-match-with-a-long-query',
);
await tester.pumpAndSettle();
const message = 'No chats match "zzz-no-match-with-a-long-query".';
expect(find.text(message), findsOneWidget);
expectNormalTextStyle(tester, message);
expect(
tester.renderObject<RenderBox>(find.text(message)).size.height,
greaterThan(30),
reason: 'the query message must wrap instead of being cut to one line',
);
expect(
find.widgetWithText(CupertinoButton, 'Clear search'),
findsOneWidget,
);
});
testWidgets('Cupertino load error under MaterialApp uses normal text', (
tester,
) async {
usePhoneSurface(tester);
final gateway = FakeChatGateway()
..sessionsHandler = () => Future.error(
StateError(
'server unavailable while listing chat sessions for this operator',
),
);
await pumpIosMaterialChat(tester, gateway);
const message =
'Bad state: server unavailable while listing chat sessions '
'for this operator';
expect(find.text(message), findsOneWidget);
expectNormalTextStyle(tester, message);
expect(find.text('No chat sessions on this server yet.'), findsNothing);
expect(find.widgetWithText(CupertinoButton, 'Retry'), findsOneWidget);
});
}
/// Resolves the style actually painted for [message] and checks it is the
/// ordinary Cupertino body style rather than MaterialApp's fallback style.
void expectNormalTextStyle(WidgetTester tester, String message) {
final paragraph = tester.renderObject<RenderParagraph>(find.text(message));
final style = paragraph.text.style!;
expect(
style.fontSize,
const CupertinoThemeData().textTheme.textStyle.fontSize,
reason: 'message should not use MaterialApp\'s 48px fallback style',
);
expect(style.fontFamily, isNot('monospace'));
expect(style.fontWeight, isNot(FontWeight.w900));
expect(style.decoration, isNot(TextDecoration.underline));
expect(style.color, isNot(const Color(0xD0FF0000)));
}
@@ -0,0 +1,174 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'chat_test_harness.dart';
import 'fake_chat_gateway.dart';
void main() {
testWidgets('material row star, rename, close confirm and reopen', (
tester,
) async {
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpMaterialChat(tester, gateway);
await tester.tap(find.byKey(const Key('chat-star-s2')));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_star'), {
'chat_query': {'session_id': 's2', 'starred': true},
});
await tester.tap(find.byKey(const Key('chat-actions-s2')));
await tester.pumpAndSettle();
await tester.tap(find.text('Rename…'));
await tester.pumpAndSettle();
await tester.enterText(
find.byKey(const Key('chat-rename-field')),
' Renamed chat ',
);
await tester.tap(find.text('Save'));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_rename'), {
'chat_rename': {'session_id': 's2', 'title': 'Renamed chat'},
});
await tester.tap(find.byKey(const Key('chat-actions-s2')));
await tester.pumpAndSettle();
await tester.tap(find.text('Close chat…'));
await tester.pumpAndSettle();
expect(find.text('Close chat?'), findsOneWidget);
await tester.tap(find.text('Cancel'));
await tester.pumpAndSettle();
expect(gateway.count('chat_close'), 0);
await tester.tap(find.byKey(const Key('chat-actions-s2')));
await tester.pumpAndSettle();
await tester.tap(find.text('Close chat…'));
await tester.pumpAndSettle();
await tester.tap(find.text('Close chat'));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_close'), {
'chat_query': {'session_id': 's2'},
});
await tester.ensureVisible(find.byKey(const Key('chat-actions-s4')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('chat-actions-s4')));
await tester.pumpAndSettle();
await tester.tap(find.text('Reopen'));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_reopen'), {
'chat_query': {'session_id': 's4'},
});
});
testWidgets('Cupertino close confirmation uses the action sheet flow', (
tester,
) async {
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpCupertinoChat(tester, gateway);
await tester.tap(find.byKey(const Key('chat-actions-s2')));
await tester.pumpAndSettle();
await tester.tap(find.text('Close chat…'));
await tester.pumpAndSettle();
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
expect(
find.textContaining('marks it closed on every device'),
findsOneWidget,
);
await tester.tap(find.text('Close chat'));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_close'), {
'chat_query': {'session_id': 's2'},
});
});
testWidgets('material rename disables Save while the name is blank', (
tester,
) async {
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpMaterialChat(tester, gateway);
await tester.tap(find.byKey(const Key('chat-actions-s2')));
await tester.pumpAndSettle();
await tester.tap(find.text('Rename…'));
await tester.pumpAndSettle();
await tester.enterText(find.byKey(const Key('chat-rename-field')), ' ');
await tester.pump();
final save = tester.widget<FilledButton>(
find.widgetWithText(FilledButton, 'Save'),
);
expect(save.onPressed, isNull);
expect(gateway.count('chat_rename'), 0);
});
testWidgets('Cupertino rename disables Save while the name is blank', (
tester,
) async {
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpCupertinoChat(tester, gateway);
await tester.tap(find.byKey(const Key('chat-actions-s2')));
await tester.pumpAndSettle();
await tester.tap(find.text('Rename…'));
await tester.pumpAndSettle();
await tester.enterText(find.byKey(const Key('chat-rename-field')), ' ');
await tester.pump();
final save = tester.widget<CupertinoDialogAction>(
find.widgetWithText(CupertinoDialogAction, 'Save'),
);
expect(save.onPressed, isNull);
expect(gateway.count('chat_rename'), 0);
});
testWidgets('material rename helper wraps instead of truncating at 2x', (
tester,
) async {
usePhoneSurface(tester);
tester.platformDispatcher.textScaleFactorTestValue = 2;
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpMaterialChat(tester, gateway);
await tester.tap(find.byKey(const Key('chat-actions-s2')));
await tester.pumpAndSettle();
await tester.tap(find.text('Rename…'));
await tester.pumpAndSettle();
const helper = 'This name is shared with every device.';
expect(find.text(helper), findsOneWidget);
expect(
tester.widget<Text>(find.text(helper)).maxLines,
2,
reason: 'helperMaxLines defaults to one, which truncates the sentence',
);
expect(tester.takeException(), isNull);
});
testWidgets('opening a row calls onOpen with the server session', (
tester,
) async {
JsonMap? opened;
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpMaterialChat(
tester,
gateway,
onOpen: (session) => opened = session,
);
await tester.tap(find.byKey(const Key('chat-row-s2')));
await tester.pumpAndSettle();
expect(opened?['id'], 's2');
});
}
@@ -0,0 +1,76 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_screen.dart';
import 'fake_chat_gateway.dart';
void main() {
testWidgets('a stale refresh reply never replaces the latest listing', (
tester,
) async {
final gateway = FakeChatGateway();
final first = Completer<JsonMap>();
final second = Completer<JsonMap>();
gateway.pendingSessions.addAll([first, second]);
await tester.pumpWidget(
MaterialApp(
home: ChatSessionsScreen(gateway: gateway, onOpen: (_) {}),
),
);
await tester.pump();
await tester.tap(find.byKey(const Key('chat-refresh')));
await tester.pump();
expect(gateway.count('chat_sessions'), 2);
second.complete({
'chat_sessions': [
{'id': 'new', 'title': 'Newest chat'},
],
});
await tester.pump();
await tester.pump();
expect(find.text('Newest chat'), findsOneWidget);
first.complete({
'chat_sessions': [
{'id': 'old', 'title': 'Older chat'},
],
});
await tester.pump();
await tester.pump();
expect(find.text('Older chat'), findsNothing);
expect(find.text('Newest chat'), findsOneWidget);
});
testWidgets('a reply completing after dispose changes nothing', (
tester,
) async {
final gateway = FakeChatGateway();
final pending = Completer<JsonMap>();
gateway.pendingSessions.add(pending);
await tester.pumpWidget(
MaterialApp(
home: ChatSessionsScreen(gateway: gateway, onOpen: (_) {}),
),
);
await tester.pump();
await tester.pumpWidget(const MaterialApp(home: SizedBox()));
pending.complete({
'chat_sessions': [
{'id': 'late', 'title': 'Late chat'},
],
});
await tester.pump();
await tester.pump();
expect(tester.takeException(), isNull);
expect(find.text('Late chat'), findsNothing);
});
}
@@ -0,0 +1,213 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'chat_test_harness.dart';
import 'fake_chat_gateway.dart';
void main() {
testWidgets(
'material list keeps closed starred rows once and groups directories once',
(tester) async {
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpMaterialChat(tester, gateway);
expect(find.text('Starred'), findsOneWidget);
expect(find.text('Chats'), findsNWidgets(2));
expect(find.text('Closed'), findsOneWidget);
expect(find.text('Starred chat'), findsOneWidget);
expect(find.text('Starred closed'), findsOneWidget);
expect(find.text('Open chat'), findsOneWidget);
expect(find.byIcon(Icons.folder_outlined), findsNWidgets(4));
expect(find.byType(Scaffold), findsOneWidget);
},
);
testWidgets('material search distinguishes no-match and clears back', (
tester,
) async {
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpMaterialChat(tester, gateway);
await tester.enterText(find.byType(TextField), 'zzz');
await tester.pumpAndSettle();
expect(find.text('No chats match "zzz".'), findsOneWidget);
expect(find.text('Open chat'), findsNothing);
await tester.tap(find.text('Clear search'));
await tester.pumpAndSettle();
expect(find.text('Open chat'), findsOneWidget);
});
testWidgets('material empty server shows the distinct empty message', (
tester,
) async {
final gateway = FakeChatGateway();
await pumpMaterialChat(tester, gateway);
expect(find.text('No chat sessions on this server yet.'), findsOneWidget);
expect(find.textContaining('No chats match'), findsNothing);
});
testWidgets(
'Cupertino app renders standard controls, groups and renames without Material',
(tester) async {
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpCupertinoChat(tester, gateway);
expect(find.byType(CupertinoPageScaffold), findsOneWidget);
expect(find.byType(CupertinoSearchTextField), findsOneWidget);
expect(find.byType(Scaffold), findsNothing);
expect(
tester.getTopLeft(find.byType(CupertinoSearchTextField)).dy,
greaterThanOrEqualTo(
tester.getBottomLeft(find.byType(CupertinoNavigationBar)).dy,
),
);
expect(find.text('Chats · /work'), findsOneWidget);
expect(find.text('Chats · /else'), findsOneWidget);
await tester.tap(find.byKey(const Key('chat-star-s2')));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_star'), {
'chat_query': {'session_id': 's2', 'starred': true},
});
await tester.tap(find.byKey(const Key('chat-actions-s2')));
await tester.pumpAndSettle();
expect(find.text('Rename…'), findsOneWidget);
await tester.tap(find.text('Rename…'));
await tester.pumpAndSettle();
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
await tester.enterText(
find.byKey(const Key('chat-rename-field')),
'Renamed on Cupertino',
);
await tester.tap(find.text('Save'));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_rename'), {
'chat_rename': {'session_id': 's2', 'title': 'Renamed on Cupertino'},
});
await tester.tap(find.byKey(const Key('chat-actions-s4')));
await tester.pumpAndSettle();
await tester.tap(find.text('Reopen'));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_reopen'), {
'chat_query': {'session_id': 's4'},
});
},
);
testWidgets(
'Cupertino no-match message wraps and Clear search is its own button',
(tester) async {
usePhoneSurface(tester);
final semantics = tester.ensureSemantics();
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpCupertinoChat(tester, gateway);
const query = 'zzz-no-match-with-a-long-query';
await tester.enterText(find.byType(CupertinoSearchTextField), query);
await tester.pumpAndSettle();
const message = 'No chats match "zzz-no-match-with-a-long-query".';
expect(find.text(message), findsOneWidget);
expect(find.text('Open chat'), findsNothing);
final messageBox = tester.renderObject<RenderBox>(find.text(message));
expect(
messageBox.size.height,
greaterThan(30),
reason: 'the query message must wrap instead of being cut to one line',
);
final clear = find.bySemanticsLabel('Clear search');
expect(clear, findsOneWidget);
expect(tester.getSemantics(clear).label, 'Clear search');
await tester.tap(find.text('Clear search'));
await tester.pumpAndSettle();
expect(find.text('Open chat'), findsOneWidget);
semantics.dispose();
},
);
testWidgets(
'Cupertino load failure wraps the reason and hides the empty message',
(tester) async {
usePhoneSurface(tester);
final gateway = FakeChatGateway()
..sessionsHandler = () => Future.error(
StateError(
'server unavailable while listing chat sessions for this operator',
),
);
await pumpCupertinoChat(tester, gateway);
const message =
'Bad state: server unavailable while listing chat sessions '
'for this operator';
expect(find.text(message), findsOneWidget);
expect(find.text('No chat sessions on this server yet.'), findsNothing);
final messageBox = tester.renderObject<RenderBox>(find.text(message));
expect(
messageBox.size.height,
greaterThan(30),
reason: 'the server reason must wrap instead of being cut to one line',
);
expect(find.widgetWithText(CupertinoButton, 'Retry'), findsOneWidget);
},
);
testWidgets('Cupertino no-match message survives 2x text scaling', (
tester,
) async {
usePhoneSurface(tester);
tester.platformDispatcher.textScaleFactorTestValue = 2;
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
final gateway = FakeChatGateway()
..sessionsReply = {'chat_sessions': sampleSessions()};
await pumpCupertinoChat(tester, gateway);
await tester.enterText(
find.byType(CupertinoSearchTextField),
'zzz-no-match-with-a-long-query',
);
await tester.pumpAndSettle();
expect(
find.text('No chats match "zzz-no-match-with-a-long-query".'),
findsOneWidget,
);
expect(find.text('Clear search'), findsOneWidget);
expect(tester.takeException(), isNull);
});
testWidgets('duplicate Cupertino titles disambiguate the action labels', (
tester,
) async {
final semantics = tester.ensureSemantics();
final gateway = FakeChatGateway()
..sessionsReply = {
'chat_sessions': [
{'id': 'd1', 'title': 'New chat', 'directory': '/work'},
{'id': 'd2', 'title': 'New chat', 'directory': '/work'},
],
};
await pumpCupertinoChat(tester, gateway);
expect(
tester.getSemantics(find.byKey(const Key('chat-actions-d1'))).label,
'Chat actions for New chat (d1)',
);
expect(
tester.getSemantics(find.byKey(const Key('chat-actions-d2'))).label,
'Chat actions for New chat (d2)',
);
semantics.dispose();
});
}
@@ -0,0 +1,77 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_screen.dart';
import 'fake_chat_gateway.dart';
List<JsonMap> sampleSessions() => [
{'id': 's1', 'title': 'Starred chat', 'directory': '/work', 'starred': true},
{'id': 's2', 'title': 'Open chat', 'directory': '/work'},
{'id': 's3', 'title': 'Elsewhere chat', 'directory': '/else'},
{
'id': 's4',
'title': 'Closed chat',
'directory': '/else',
'closed_at': '2026-01-01',
},
{
'id': 's5',
'title': 'Starred closed',
'directory': '/work',
'starred': true,
'closed_at': '2026-01-02',
},
];
Future<void> pumpMaterialChat(
WidgetTester tester,
FakeChatGateway gateway, {
ValueChanged<JsonMap>? onOpen,
}) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: ChatSessionsScreen(gateway: gateway, onOpen: onOpen ?? (_) {}),
),
);
await tester.pumpAndSettle();
}
Future<void> pumpCupertinoChat(
WidgetTester tester,
FakeChatGateway gateway, {
ValueChanged<JsonMap>? onOpen,
}) async {
await tester.pumpWidget(
CupertinoApp(
home: ChatSessionsScreen(gateway: gateway, onOpen: onOpen ?? (_) {}),
),
);
await tester.pumpAndSettle();
}
/// The screen's iOS/macOS path: Cupertino controls under the app's ordinary
/// `MaterialApp` root, with no Material or CupertinoTheme ancestor.
Future<void> pumpIosMaterialChat(
WidgetTester tester,
FakeChatGateway gateway, {
ValueChanged<JsonMap>? onOpen,
}) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: TargetPlatform.iOS),
home: ChatSessionsScreen(gateway: gateway, onOpen: onOpen ?? (_) {}),
),
);
await tester.pumpAndSettle();
}
/// Narrows the test surface to a phone so long messages must wrap.
void usePhoneSurface(WidgetTester tester) {
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
}
@@ -0,0 +1,56 @@
import 'dart:async';
import 'dart:collection';
import 'package:pipelines_app/core/api_gateway.dart';
/// Scripted gateway for session-browser widget tests.
class FakeChatGateway implements ApiGateway {
final calls = <({String type, JsonMap fields})>[];
final pendingSessions = Queue<Completer<JsonMap>>();
JsonMap sessionsReply = const {'chat_sessions': []};
Future<JsonMap> Function()? sessionsHandler;
JsonMap createReply = const {
'chat_session': {'id': 'created', 'title': 'New chat'},
};
Future<JsonMap> Function()? directoriesHandler;
Future<JsonMap> Function()? backendsHandler;
@override
Stream<JsonMap> get frames => const Stream.empty();
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
calls.add((type: type, fields: fields));
switch (type) {
case 'chat_sessions':
if (pendingSessions.isNotEmpty) {
return pendingSessions.removeFirst().future;
}
if (sessionsHandler != null) return sessionsHandler!();
return Future.value(sessionsReply);
case 'chat_directories':
return directoriesHandler?.call() ??
Future.value(const {
'chat_directories': ['/work', '/archive'],
});
case 'chat_backends':
return backendsHandler?.call() ??
Future.value(const {
'chat_backends': ['opencode', 'codex'],
});
case 'chat_create':
return Future.value(createReply);
default:
return Future.value(const {});
}
}
int count(String type) => calls.where((call) => call.type == type).length;
JsonMap? lastFields(String type) {
for (final call in calls.reversed) {
if (call.type == type) return call.fields;
}
return null;
}
}
+26 -8
View File
@@ -5,9 +5,12 @@ import { once } from 'node:events';
import { setTimeout as delay } from 'node:timers/promises';
import { join, extname, resolve, sep } from 'node:path';
import { tmpdir } from 'node:os';
import { mkdtemp, rm } from 'node:fs/promises';
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
const root = join(process.cwd(), 'build/web');
const root = resolve(process.env.PROBE_WEB_ROOT ?? join(process.cwd(), 'build/web'));
const variant = process.env.PROBE_VARIANT ?? 'material';
const artifactDir = process.env.OPENCODE_ARTIFACT_DIR ?? join(tmpdir(), 'chat-sessions-capture');
await mkdir(artifactDir, { recursive: true });
const mime = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm', '.png': 'image/png', '.ico': 'image/x-icon' };
const server = createServer(async (req, res) => {
try {
@@ -66,25 +69,40 @@ try {
if (!loaded?.url.includes(`127.0.0.1:${port}`)) throw new Error(`Fixture did not load: ${JSON.stringify(loaded)}`);
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
await delay(2500);
const clickLabel = async label => evaluate(`(() => { const e=[...document.querySelectorAll('flt-semantics')].find(x => (x.getAttribute('aria-label') || x.innerText || '') === ${JSON.stringify(label)}); if (!e) return false; e.click(); return true; })()`);
const clickLabel = async label => {
const point = await evaluate(`(() => { const needle = ${JSON.stringify(label)}; const e=[...document.querySelectorAll('flt-semantics')].find(x => (x.getAttribute('aria-label') || x.innerText || '') === needle); if (!e) return null; const r=e.getBoundingClientRect(); return {x:r.x+r.width/2,y:r.y+r.height/2}; })()`);
if (!point) return false;
await send('Input.dispatchMouseEvent', { type: 'mousePressed', x: point.x, y: point.y, button: 'left', clickCount: 1 }, session);
await send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: point.x, y: point.y, button: 'left', clickCount: 1 }, session);
return true;
};
const labels = await evaluate("[...document.querySelectorAll('flt-semantics')].map(x=>x.getAttribute('aria-label')||x.innerText).filter(Boolean)");
if (!labels?.some(x => x.includes('New chat'))) throw new Error(`Chat fixture semantics unavailable: ${JSON.stringify(labels)}`);
if (process.env.PROBE_DEBUG) console.log(JSON.stringify(labels));
const capture = async (name, width, height) => {
await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 }, session);
await delay(350);
const data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).result.data;
await (await import('node:fs/promises')).writeFile(`${process.env.OPENCODE_ARTIFACT_DIR}/${name}.png`, Buffer.from(data, 'base64'));
await (await import('node:fs/promises')).writeFile(`${artifactDir}/${variant}-${name}.png`, Buffer.from(data, 'base64'));
};
await capture('chat-sessions-desktop', 1280, 800);
await capture('chat-sessions-phone', 390, 844);
if (!await clickLabel('New chat')) throw new Error('Could not open create dialog');
await delay(500);
await delay(600);
await send('Input.dispatchMouseEvent', { type: 'mouseWheel', x: 195, y: 680, deltaY: 598 }, session);
await delay(350);
const changedBody = await evaluate('document.body.innerText');
await capture('chat-sessions-create-dialog', 390, 844);
if (!changedBody.includes('Server directory') || !changedBody.includes('Backend') || !changedBody.includes('New chats use the server default model.') || changedBody.includes('Open fixture')) throw new Error(`Create dialog did not change rendered body to catalog controls: ${changedBody}`);
await capture('chat-sessions-desktop', 1280, 800);
console.log(JSON.stringify({ labels, captures: ['chat-sessions-phone.png', 'chat-sessions-create-dialog.png', 'chat-sessions-desktop.png'], bodyChanged: true }, null, 2));
if (!changedBody.includes('Server directory') || !changedBody.includes('Backend') || !changedBody.includes('New chats use the server default model.')) throw new Error(`Create dialog did not change rendered body to catalog controls: ${changedBody}`);
if (!await clickLabel('Cancel')) throw new Error('Could not close create dialog');
await delay(600);
if (!await clickLabel('Chat actions for Open fixture')) throw new Error('Could not open row actions');
await delay(600);
const actionsBody = await evaluate('document.body.innerText');
const actionLabels = await evaluate("[...document.querySelectorAll('flt-semantics')].map(x => x.getAttribute('aria-label') || x.innerText || '').filter(Boolean)");
await capture('chat-sessions-actions', 390, 844);
if (!actionLabels.some(label => label.includes('Rename…'))) throw new Error(`Row actions unavailable: ${actionsBody} / ${actionLabels}`);
console.log(JSON.stringify({ variant, labels, captures: [`${variant}-chat-sessions-desktop.png`, `${variant}-chat-sessions-phone.png`, `${variant}-chat-sessions-create-dialog.png`, `${variant}-chat-sessions-actions.png`], bodyChanged: true }, null, 2));
} finally {
ws?.close();
chrome.kill('SIGTERM');
+18 -4
View File
@@ -1,3 +1,4 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pipelines_app/core/api_gateway.dart';
@@ -55,8 +56,21 @@ class _FixtureGateway implements ApiGateway {
}
}
void main() => runApp(
MaterialApp(
home: ChatSessionsScreen(gateway: _FixtureGateway(), onOpen: (_) {}),
),
const _probeStyle = String.fromEnvironment(
'CHAT_PROBE_STYLE',
defaultValue: 'material',
);
void main() {
final home = ChatSessionsScreen(gateway: _FixtureGateway(), onOpen: (_) {});
if (_probeStyle == 'cupertino') {
runApp(CupertinoApp(home: home));
return;
}
runApp(
MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: home,
),
);
}