Files
pipelines/app/lib/features/chat/data/chat_repository.dart
T
alan 2a66be7b27 feat(app): choose a chat model from the conversation header
Native model control and chooser in the chat thread header, matching the web
chat_models/chat_model exchange. Fixes the chat_models list parsing, keeps the
accepted server echo across Back/reopen, and resolves the session row for
/chat/:id deep links.
2026-10-22 12:28:13 +01:00

231 lines
7.1 KiB
Dart

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']);
/// The models the session's harness offers, in the server's order.
///
/// `chat_models` is a JSON list, the same shape the web client reads. A
/// missing or wrong-typed field is an empty catalog, never invented rows.
Future<List<JsonMap>> models(String sessionId) async {
final session = sessionId.trim();
if (session.isEmpty) {
throw ArgumentError('Select a chat session first.');
}
final reply = await gateway.call('chat_models', {
'chat_query': {'session_id': session},
});
final value = reply['chat_models'];
return value is List ? _maps(value) : const [];
}
Future<JsonMap> selectModel(String sessionId, String provider, String model) {
final session = sessionId.trim();
if (session.isEmpty) {
throw ArgumentError('Select a chat session first.');
}
if (provider.trim().isEmpty || model.trim().isEmpty) {
throw ArgumentError('Choose a model first.');
}
return gateway.call('chat_model', {
'chat_model': {
'session_id': session,
'provider': provider.trim(),
'model': model.trim(),
},
});
}
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();
}