merge(app): land reviewed native chat sessions

This commit is contained in:
2026-10-21 17:45:52 +01:00
28 changed files with 3692 additions and 0 deletions
@@ -0,0 +1,215 @@
import '../../../core/api_gateway.dart';
const webChatClient = 'Web';
String nativeChatMessageId(String operationId) {
final compact = operationId.replaceAll(RegExp('[^A-Za-z0-9]'), '');
final capped = compact.length > 120 ? compact.substring(0, 120) : compact;
return capped.isEmpty ? '' : 'msg_$capped';
}
/// Chat wire adapter. ApiGateway supplies request ids and returns full envelopes.
class ChatRepository {
ChatRepository(this.gateway);
final ApiGateway gateway;
Future<List<JsonMap>> sessions() async =>
_maps((await gateway.call('chat_sessions'))['chat_sessions']);
Future<JsonMap> models(String sessionId) async {
final reply = await gateway.call('chat_models', {
'chat_query': {'session_id': sessionId},
});
final catalog = reply['chat_models'];
return catalog is Map ? Map<String, dynamic>.from(catalog) : {};
}
Future<JsonMap> selectModel(
String sessionId,
String provider,
String model,
) => gateway.call('chat_model', {
'chat_model': {
'session_id': sessionId,
'provider': provider,
'model': model,
},
});
Future<List<JsonMap>> shells(String sessionId) async => _maps(
(await gateway.call('chat_shells', {
'chat_query': {'session_id': sessionId},
}))['chat_shells'],
);
Future<List<String>> directories() async {
final value = (await gateway.call('chat_directories'))['chat_directories'];
if (value is! List) {
throw StateError('Server did not return chat directories.');
}
return value
.whereType<String>()
.where((entry) => entry.trim().isNotEmpty)
.toList();
}
Future<List<String>> backends() async {
final value = (await gateway.call('chat_backends'))['chat_backends'];
if (value is! List) {
throw StateError('Server did not return chat backends.');
}
final result = value
.whereType<String>()
.where((entry) => entry.trim().isNotEmpty)
.toList();
if (result.isEmpty) throw StateError('Server returned no chat backends.');
return result;
}
Future<JsonMap> shellOutput(
String sessionId,
String shellId, {
int cursor = 0,
int limit = 65536,
}) => gateway.call('chat_shell_output', {
'chat_shell_output_query': {
'session_id': sessionId,
'shell_id': shellId,
'cursor': cursor,
'limit': limit,
},
});
Future<JsonMap> history(
String sessionId, {
int limit = 200,
String cursor = '',
}) async {
final reply = await gateway.call('chat_messages', {
'chat_query': {'session_id': sessionId, 'limit': limit, 'cursor': cursor},
});
final page = reply['chat_history'];
if (page is Map) {
return {
'messages': _maps(page['messages']),
'nextCursor': '${page['next_cursor'] ?? ''}',
'hasMore': page['has_more'] == true,
};
}
return {
'messages': _maps(reply['chat_messages']),
'nextCursor': '',
'hasMore': false,
};
}
Future<JsonMap> subscribe(String sessionId) =>
gateway.call('chat_subscribe', {
'chat_subscribe': {'session_id': sessionId},
});
Future<JsonMap> create({
required String title,
required String directory,
required String operationId,
String backend = 'opencode',
String instructions = '',
}) {
if (title.trim().isEmpty || directory.trim().isEmpty) {
throw ArgumentError('Enter a chat name and choose a directory.');
}
return gateway.call('chat_create', {
'chat_create': {
'title': title.trim(),
'directory': directory.trim(),
'operation_id': operationId,
if (backend.isNotEmpty && backend != 'opencode') 'backend': backend,
if (instructions.trim().isNotEmpty) 'instructions': instructions.trim(),
},
});
}
Future<JsonMap> rename(String sessionId, String title) =>
gateway.call('chat_rename', {
'chat_rename': {'session_id': sessionId, 'title': title.trim()},
});
Future<JsonMap> star(String sessionId, bool starred) =>
gateway.call('chat_star', {
'chat_query': {'session_id': sessionId, 'starred': starred},
});
Future<JsonMap> close(String sessionId) => gateway.call('chat_close', {
'chat_query': {'session_id': sessionId},
});
Future<JsonMap> reopen(String sessionId) => gateway.call('chat_reopen', {
'chat_query': {'session_id': sessionId},
});
Future<JsonMap> prompt(
String sessionId,
String text, {
required String operationId,
List<String> files = const [],
List<JsonMap> attachments = const [],
}) {
if (sessionId.trim().isEmpty) {
throw ArgumentError('Select a chat session first.');
}
if (text.trim().isEmpty) {
throw ArgumentError('Enter a message before sending.');
}
final body = <String, dynamic>{
'session_id': sessionId,
'text': text.trim(),
'operation_id': operationId,
'native_message_id': nativeChatMessageId(operationId),
};
if (files.isNotEmpty) body['files'] = files;
if (attachments.isNotEmpty) body['attachments'] = attachments;
return gateway.call('chat_prompt', {'chat_prompt': body});
}
Future<JsonMap> interrupt(String sessionId) =>
gateway.call('chat_interrupt', {
'chat_query': {'session_id': sessionId},
});
Future<JsonMap> answerForm(
String sessionId,
String formId,
JsonMap answers, {
String action = '',
}) => gateway.call('chat_answer', {
'chat_answer': {
'session_id': sessionId,
'form_id': formId,
'answers': answers,
if (action.isNotEmpty) 'action': action,
},
});
Future<JsonMap> replyPermission(
String sessionId,
String requestId,
String decision, {
String client = webChatClient,
String message = '',
}) {
if (sessionId.trim().isEmpty) {
throw ArgumentError('Select a chat session first.');
}
if (requestId.trim().isEmpty) {
throw ArgumentError('This approval request is no longer available.');
}
if (!const ['once', 'always', 'reject'].contains(decision.trim())) {
throw ArgumentError('Choose once, always or reject.');
}
return gateway.call('chat_reply', {
'chat_reply': {
'session_id': sessionId,
'request_id': requestId,
'decision': decision,
'client': client,
if (message.trim().isNotEmpty) 'message': message.trim(),
},
});
}
static List<JsonMap> _maps(Object? value) => (value as List? ?? const [])
.whereType<Map>()
.map((item) => Map<String, dynamic>.from(item))
.toList();
}
@@ -0,0 +1,64 @@
import '../../../core/api_gateway.dart';
/// Pure session-list operations. Unknown server fields remain on each row.
String chatSessionTitle(JsonMap session) {
final title = '${session['title'] ?? ''}';
if (title.trim().isNotEmpty) return title;
final id = '${session['id'] ?? ''}';
return id.isEmpty ? 'Untitled chat' : id.substring(0, id.length.clamp(0, 18));
}
List<JsonMap> filterChatSessions(List<JsonMap> sessions, String query) {
final needle = query.trim().toLowerCase();
if (needle.isEmpty) return sessions;
return sessions
.where(
(session) =>
'${chatSessionTitle(session)}\u0000${session['directory'] ?? ''}'
.toLowerCase()
.contains(needle),
)
.toList();
}
/// Directory groups retain server recency order, both within and between groups.
List<({String directory, List<JsonMap> sessions})> groupChatSessions(
List<JsonMap> sessions,
) {
final groups = <String, List<JsonMap>>{};
for (final session in sessions) {
groups.putIfAbsent('${session['directory'] ?? ''}', () => []).add(session);
}
return groups.entries
.map((entry) => (directory: entry.key, sessions: entry.value))
.toList();
}
String chatSessionActivity({required bool running, required bool unseen}) =>
running
? 'streaming'
: unseen
? 'new'
: 'idle';
/// Native reported values only; missing and invalid values remain unavailable.
JsonMap? chatUsageSnapshot(Object? value) {
if (value is! Map || value is List) return null;
final usage = Map<String, dynamic>.from(value);
final result = <String, dynamic>{};
for (final key in ['total_tokens', 'context_tokens', 'context_window']) {
final n = usage[key];
result[key] = n is int && n >= 0 ? n : null;
}
for (final key in ['cost_usd', 'output_tokens_per_second']) {
final n = usage[key];
result[key] = n is num && n.isFinite && n >= 0 ? n : null;
}
result['scope'] = ['session', 'turn'].contains(usage['scope'])
? usage['scope']
: '';
result['rate_basis'] = ['generation', 'turn'].contains(usage['rate_basis'])
? usage['rate_basis']
: '';
return result.values.any((v) => v != null && v != '') ? result : null;
}
@@ -0,0 +1,235 @@
import '../../../core/api_gateway.dart';
/// Merge chronological history pages by message id. Incoming authoritative
/// copies replace held copies without changing their order; cursor is opaque.
JsonMap mergeChatHistory(JsonMap previous, JsonMap page, {bool older = false}) {
final held = (previous['messages'] as List? ?? const [])
.whereType<Map>()
.map((m) => Map<String, dynamic>.from(m))
.toList();
final incoming = (page['messages'] as List? ?? const [])
.whereType<Map>()
.map((m) => Map<String, dynamic>.from(m))
.toList();
final latest = <Object, JsonMap>{};
for (final message in incoming) {
if (message['id'] != null) latest[message['id']] = message;
}
final combined = older ? [...incoming, ...held] : [...held, ...incoming];
final seen = <Object>{};
final messages = <JsonMap>[];
for (final message in combined) {
final id = message['id'];
if (id != null && !seen.add(id)) continue;
messages.add(id == null ? message : latest[id] ?? message);
}
return {
'messages': messages,
'nextCursor': '${page['nextCursor'] ?? ''}',
'hasMore': page['hasMore'] == true,
'loaded': true,
'loading': false,
};
}
/// Consecutive assistant messages form one answer turn. All part fields (also
/// future/unknown protocol types) are preserved in original order.
List<JsonMap> transcriptRows(List<JsonMap> messages) {
final rows = <JsonMap>[];
String? key;
final parts = <JsonMap>[];
void flush() {
if (key != null && parts.isNotEmpty) {
rows.add({
'kind': 'assistant',
'key': key,
'parts': List<JsonMap>.of(parts),
});
}
key = null;
parts.clear();
}
for (final message in messages) {
if (message['role'] == 'assistant') {
key ??= '${message['id'] ?? ''}';
for (final part in (message['parts'] as List? ?? const [])) {
if (part is Map) parts.add(Map<String, dynamic>.from(part));
}
} else {
flush();
rows.add({'kind': 'user', 'key': message['id'], 'message': message});
}
}
flush();
return rows;
}
/// Replace a local optimistic user row when its server echo identifies the
/// same operation/native message; otherwise append once by authoritative id.
List<JsonMap> reconcileChatUser(List<JsonMap> messages, JsonMap remote) {
final operation = remote['operation_id'];
final nativeId = remote['native_message_id'];
final id = remote['id'];
final index = messages.indexWhere(
(message) =>
(operation != null && message['operation_id'] == operation) ||
(nativeId != null && message['native_message_id'] == nativeId) ||
(id != null && message['id'] == id),
);
if (index < 0) return [...messages, remote];
final result = List<JsonMap>.of(messages);
result[index] = remote;
return result;
}
/// Fold a live chat frame into an immutable thread snapshot. Text and reasoning
/// deltas append by part id, tool snapshots merge without dropping prior fields,
/// and step frames update turn activity. Frames for another session are ignored.
JsonMap applyChatEvent(JsonMap thread, JsonMap frame) {
final session = thread['sessionId'];
if (session != null &&
frame['session_id'] != null &&
session != frame['session_id']) {
return thread;
}
final messages = (thread['messages'] as List? ?? const [])
.whereType<Map>()
.map((m) => Map<String, dynamic>.from(m))
.toList();
final kind = frame['kind'];
if (kind == 'user') {
final part = frame['part'];
final text = part is Map ? part['text'] : null;
final id = frame['message_id'];
if (text is! String ||
text.isEmpty ||
id == null ||
messages.any(
(m) =>
m['id'] == id ||
(frame['operation_id'] != null &&
m['operation_id'] == frame['operation_id']),
)) {
return thread;
}
messages.add({
'id': id,
'session_id': frame['session_id'],
'role': 'user',
'client': frame['client'],
'operation_id': frame['operation_id'],
'parts': [
{'type': 'text', 'text': text},
...(frame['attachments'] is List
? frame['attachments'] as List
: const []),
],
});
return {...thread, 'messages': messages};
}
if (kind == 'text' || kind == 'reasoning' || kind == 'tool') {
final incoming = frame['part'];
if (incoming is! Map || incoming['id'] == null) return thread;
final messageId = frame['message_id'];
var index = messages.indexWhere(
(m) => m['id'] == messageId && m['role'] == 'assistant',
);
if (index < 0) {
messages.add({
'id': messageId,
'session_id': frame['session_id'],
'role': 'assistant',
'parts': <JsonMap>[],
});
index = messages.length - 1;
}
final message = messages[index];
final parts = (message['parts'] as List? ?? const [])
.whereType<Map>()
.map((p) => Map<String, dynamic>.from(p))
.toList();
final partIndex = parts.indexWhere(
(p) => p['id'] == incoming['id'] && p['type'] == kind,
);
if (kind == 'text' || kind == 'reasoning') {
final delta = frame['delta'];
if (delta is! String || delta.isEmpty) return thread;
if (partIndex < 0) {
parts.add({'type': kind, 'id': incoming['id'], 'text': delta});
} else {
parts[partIndex] = {
...parts[partIndex],
'text': '${parts[partIndex]['text'] ?? ''}$delta',
};
}
} else if (partIndex < 0) {
parts.add(Map<String, dynamic>.from(incoming));
} else {
final merged = {
...parts[partIndex],
...Map<String, dynamic>.from(incoming),
};
if (parts[partIndex]['state'] is Map && incoming['state'] is Map) {
merged['state'] = {
...Map<String, dynamic>.from(parts[partIndex]['state'] as Map),
...Map<String, dynamic>.from(incoming['state'] as Map),
};
}
parts[partIndex] = merged;
}
messages[index] = {...message, 'parts': parts};
return {...thread, 'messages': messages, 'running': true};
}
if (kind == 'step' && frame['step'] is Map) {
final step = frame['step'] as Map;
if (step['intermediate'] == true) return thread;
return {
...thread,
'running': step['status'] != 'ended',
'nativeTurnId': step['status'] == 'ended'
? ''
: (step['turn_id'] ?? thread['nativeTurnId'] ?? ''),
};
}
return thread;
}
/// Queue serialized sends per session; operation ids survive retries/replays.
class QueuedChatSend {
QueuedChatSend({
required this.operationId,
required this.text,
this.files = const [],
});
final String operationId;
final String text;
final List<String> files;
/// Retry the same immutable intent with the same idempotency key.
QueuedChatSend retry() => QueuedChatSend(
operationId: operationId,
text: text,
files: List.unmodifiable(files),
);
}
class ChatSendQueue {
final Map<String, List<QueuedChatSend>> _sessions = {};
List<QueuedChatSend> forSession(String sessionId) =>
List.unmodifiable(_sessions[sessionId] ?? const []);
bool enqueue(String sessionId, QueuedChatSend send) {
final queue = _sessions.putIfAbsent(sessionId, () => []);
if (queue.any((item) => item.operationId == send.operationId)) return false;
queue.add(send);
return true;
}
QueuedChatSend? takeNext(String sessionId) {
final queue = _sessions[sessionId];
if (queue == null || queue.isEmpty) return null;
final result = queue.removeAt(0);
if (queue.isEmpty) _sessions.remove(sessionId);
return result;
}
}
@@ -0,0 +1 @@
export 'ui/sessions/chat_sessions_screen.dart';
@@ -0,0 +1,200 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
/// Which standard control family this screen renders.
enum ChatControlsStyle { material, cupertino }
/// Cupertino under a Cupertino app or an iOS/macOS Material theme, Material
/// everywhere else. The shell decides the app class, so a bare Cupertino app
/// never has to grow a Material ancestor just for this screen.
ChatControlsStyle chatControlsStyleOf(BuildContext context) {
if (context.findAncestorWidgetOfExactType<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();
}
}
@@ -0,0 +1,176 @@
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_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 {
const ChatSessionsScreen({
super.key,
required this.gateway,
required this.onOpen,
});
final ApiGateway gateway;
final void Function(JsonMap session) onOpen;
@override
State<ChatSessionsScreen> createState() => _ChatSessionsScreenState();
}
class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
late final ChatSessionsController _controller = ChatSessionsController(
ChatRepository(widget.gateway),
)..refresh();
final _search = TextEditingController();
@override
void didUpdateWidget(covariant ChatSessionsScreen oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.gateway != widget.gateway) {
_controller.replaceRepository(ChatRepository(widget.gateway));
}
}
@override
void dispose() {
_controller.dispose();
_search.dispose();
super.dispose();
}
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);
}
Future<void> _close(JsonMap session) async {
if (!await confirmCloseChat(context, session)) return;
if (!mounted) return;
await _controller.close(_sessionId(session));
}
Future<void> _newChat() async {
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) {
return ListenableBuilder(
listenable: _controller,
builder: (context, _) {
final body = Column(
children: [
ChatSearchField(
controller: _search,
onChanged: (_) => setState(() {}),
),
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 (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,
),
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,
),
],
),
body: body,
floatingActionButton: FloatingActionButton.extended(
key: const Key('chat-new-chat-fab'),
onPressed: _newChat,
icon: const Icon(Icons.add),
label: const Text('New chat'),
),
);
},
);
}
}
@@ -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;
}