feat(app): add native chat sessions browser
This commit is contained in:
@@ -1,5 +1,13 @@
|
||||
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);
|
||||
@@ -7,11 +15,14 @@ class ChatRepository {
|
||||
|
||||
Future<List<JsonMap>> sessions() async =>
|
||||
_maps((await gateway.call('chat_sessions'))['chat_sessions']);
|
||||
Future<List<JsonMap>> models(String sessionId) async => _maps(
|
||||
(await gateway.call('chat_models', {
|
||||
Future<JsonMap> models(String sessionId) async {
|
||||
final reply = await gateway.call('chat_models', {
|
||||
'chat_query': {'session_id': sessionId},
|
||||
}))['chat_models'],
|
||||
);
|
||||
});
|
||||
final catalog = reply['chat_models'];
|
||||
return catalog is Map ? Map<String, dynamic>.from(catalog) : {};
|
||||
}
|
||||
|
||||
Future<JsonMap> selectModel(
|
||||
String sessionId,
|
||||
String provider,
|
||||
@@ -34,9 +45,29 @@ class ChatRepository {
|
||||
.whereType<String>()
|
||||
.toList();
|
||||
|
||||
Future<List<String>> backends() async =>
|
||||
((await gateway.call('chat_backends'))['chat_backends'] as List? ??
|
||||
const [])
|
||||
.whereType<String>()
|
||||
.toList();
|
||||
|
||||
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 = 50,
|
||||
int limit = 200,
|
||||
String cursor = '',
|
||||
}) async {
|
||||
final reply = await gateway.call('chat_messages', {
|
||||
@@ -67,15 +98,21 @@ class ChatRepository {
|
||||
required String operationId,
|
||||
String backend = 'opencode',
|
||||
String instructions = '',
|
||||
}) => gateway.call('chat_create', {
|
||||
'chat_create': {
|
||||
'title': title,
|
||||
'directory': directory,
|
||||
'operation_id': operationId,
|
||||
if (backend.isNotEmpty && backend != 'opencode') 'backend': backend,
|
||||
if (instructions.trim().isNotEmpty) 'instructions': instructions.trim(),
|
||||
},
|
||||
});
|
||||
}) {
|
||||
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()},
|
||||
@@ -96,13 +133,22 @@ class ChatRepository {
|
||||
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});
|
||||
}
|
||||
|
||||
@@ -127,17 +173,28 @@ class ChatRepository {
|
||||
String sessionId,
|
||||
String requestId,
|
||||
String decision, {
|
||||
String client = 'web',
|
||||
String client = webChatClient,
|
||||
String message = '',
|
||||
}) => gateway.call('chat_reply', {
|
||||
'chat_reply': {
|
||||
'session_id': sessionId,
|
||||
'request_id': requestId,
|
||||
'decision': decision,
|
||||
'client': client,
|
||||
if (message.trim().isNotEmpty) 'message': message.trim(),
|
||||
},
|
||||
});
|
||||
}) {
|
||||
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>()
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export 'ui/sessions/chat_sessions_screen.dart';
|
||||
@@ -0,0 +1,322 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../../core/api_gateway.dart';
|
||||
import '../../data/chat_repository.dart';
|
||||
import '../../domain/chat_sessions.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 ChatRepository _repository;
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_generation++;
|
||||
_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');
|
||||
}
|
||||
}
|
||||
|
||||
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');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _newChat() async {
|
||||
final dirs = TextEditingController();
|
||||
final title = TextEditingController(text: 'New chat');
|
||||
final instructions = TextEditingController();
|
||||
final result =
|
||||
await showDialog<
|
||||
({String title, String directory, String instructions})
|
||||
>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('New chat'),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
TextField(
|
||||
controller: title,
|
||||
decoration: const InputDecoration(labelText: 'Name'),
|
||||
),
|
||||
TextField(
|
||||
controller: dirs,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Server directory',
|
||||
),
|
||||
),
|
||||
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.text.trim(),
|
||||
instructions: instructions.text,
|
||||
)),
|
||||
child: const Text('Create'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
title.dispose();
|
||||
dirs.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,
|
||||
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');
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final visible = filterChatSessions(_sessions, _search.text);
|
||||
final starred = visible.where((s) => s['starred'] == true).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(
|
||||
controller: _search,
|
||||
onChanged: (_) => setState(() {}),
|
||||
decoration: const InputDecoration(
|
||||
prefixIcon: Icon(Icons.search),
|
||||
labelText: 'Search chats',
|
||||
),
|
||||
),
|
||||
),
|
||||
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)
|
||||
const ListTile(title: Text('No chats found.')),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
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 (group.directory.isNotEmpty)
|
||||
ListTile(
|
||||
dense: true,
|
||||
leading: const Icon(Icons.folder_outlined),
|
||||
title: Text(group.directory),
|
||||
),
|
||||
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'),
|
||||
),
|
||||
if (isClosed)
|
||||
const PopupMenuItem(value: 'reopen', child: Text('Reopen'))
|
||||
else
|
||||
const PopupMenuItem(value: 'close', child: Text('Close')),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# C1 — Chat sessions and repository adapter
|
||||
|
||||
Implemented the native Material sessions browser, search, directory grouping, starred/closed groups, standard session actions, and explicit-directory create dialog. Opening a session only invokes the supplied callback. The chat repository includes the web-compatible native message ID, prompt validation, Web permission label, and 200-message history default.
|
||||
|
||||
Verification: `flutter test test/features/chat` passed. Browser build/captures and mobile builds were not performed here. The fixture entry point is `tool/chat_sessions_probe_entry.dart`; a separate browser review should exercise the rendered states and capture them before claiming UI acceptance.
|
||||
@@ -222,6 +222,7 @@ void main() {
|
||||
'session_id': 's',
|
||||
'text': 'hi',
|
||||
'operation_id': 'same',
|
||||
'native_message_id': 'msg_same',
|
||||
},
|
||||
});
|
||||
await repo.answerForm('s', 'f', {'choice': 'yes'}, action: 'submit');
|
||||
@@ -239,7 +240,7 @@ void main() {
|
||||
'session_id': 's',
|
||||
'request_id': 'r',
|
||||
'decision': 'once',
|
||||
'client': 'web',
|
||||
'client': 'Web',
|
||||
'message': 'approved',
|
||||
},
|
||||
});
|
||||
@@ -255,5 +256,41 @@ void main() {
|
||||
expect(gateway.calls.last.type, 'chat_model');
|
||||
},
|
||||
);
|
||||
test('rejects invalid permissions and prompts before sending', () async {
|
||||
expect(
|
||||
() => repo.prompt(' ', 'hello', operationId: 'x'),
|
||||
throwsArgumentError,
|
||||
);
|
||||
expect(
|
||||
() => repo.prompt('s', ' ', operationId: 'x'),
|
||||
throwsArgumentError,
|
||||
);
|
||||
expect(
|
||||
() => repo.replyPermission('s', 'r', 'approve'),
|
||||
throwsArgumentError,
|
||||
);
|
||||
expect(gateway.calls, isEmpty);
|
||||
});
|
||||
test(
|
||||
'uses the server model catalog object and default history limit',
|
||||
() async {
|
||||
gateway.reply = {
|
||||
'chat_models': {
|
||||
'providers': {
|
||||
'p': ['m'],
|
||||
},
|
||||
},
|
||||
};
|
||||
expect((await repo.models('s'))['providers'], {
|
||||
'p': ['m'],
|
||||
});
|
||||
expect(gateway.calls.single.fields, {
|
||||
'chat_query': {'session_id': 's'},
|
||||
});
|
||||
gateway.calls.clear();
|
||||
await repo.history('s');
|
||||
expect(gateway.calls.single.fields['chat_query']['limit'], 200);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/chat/session_screen.dart';
|
||||
|
||||
class _FixtureGateway implements ApiGateway {
|
||||
@override
|
||||
Stream<JsonMap> get frames => const Stream.empty();
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
|
||||
if (type == 'chat_sessions') {
|
||||
return {
|
||||
'chat_sessions': [
|
||||
{
|
||||
'id': 'probe-open',
|
||||
'title': 'Open fixture',
|
||||
'directory': '/workspace/demo',
|
||||
'starred': true,
|
||||
},
|
||||
{
|
||||
'id': 'probe-closed',
|
||||
'title': 'Closed fixture',
|
||||
'directory': '/workspace/archive',
|
||||
'closed_at': '2026-01-01',
|
||||
},
|
||||
{
|
||||
'id': 'probe-stream',
|
||||
'title': 'Streaming fixture',
|
||||
'directory': '/workspace/demo',
|
||||
'running': true,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (type == 'chat_directories') {
|
||||
return {
|
||||
'chat_directories': ['/workspace/demo', '/workspace/archive'],
|
||||
};
|
||||
}
|
||||
if (type == 'chat_backends') {
|
||||
return {
|
||||
'chat_backends': ['opencode', 'codex'],
|
||||
};
|
||||
}
|
||||
if (type == 'chat_create') {
|
||||
return {
|
||||
'chat_session': {
|
||||
'id': 'probe-new',
|
||||
'title': 'New fixture',
|
||||
'directory': '/workspace/demo',
|
||||
},
|
||||
};
|
||||
}
|
||||
return {'chat_session': {}};
|
||||
}
|
||||
}
|
||||
|
||||
void main() => runApp(
|
||||
MaterialApp(
|
||||
home: ChatSessionsScreen(gateway: _FixtureGateway(), onOpen: (_) {}),
|
||||
),
|
||||
);
|
||||
Reference in New Issue
Block a user