Files
pipelines/app/lib/features/chat/data/chat_repository.dart
T
alan 3374bea2ef Show a chat turn's changed files as a chip that opens its diff
The answer footer shows '3 files changed +9 -2'; tapping opens the turn's
files in the sheet (wide) or a full-screen page (narrow), and a file opens
the run Changes diff viewer. Patches load through the chat's own gateway.
2026-11-09 16:08:35 +00:00

327 lines
11 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(),
},
});
}
/// The permission modes the session's harness offers, in the server's
/// order, and the session's stored mode (empty for the harness default).
Future<({List<JsonMap> modes, String current})> modes(
String sessionId,
) async {
final session = sessionId.trim();
if (session.isEmpty) {
throw ArgumentError('Select a chat session first.');
}
final reply = await gateway.call('chat_modes', {
'chat_query': {'session_id': session},
});
final value = reply['chat_modes'];
final current = reply['chat_mode'];
return (
modes: value is List ? _maps(value) : const <JsonMap>[],
current: current is Map ? '${current['mode'] ?? ''}'.trim() : '',
);
}
/// Switches the session's mode; the reply echoes the stored mode.
Future<String> selectMode(String sessionId, String mode) async {
final session = sessionId.trim();
if (session.isEmpty) {
throw ArgumentError('Select a chat session first.');
}
if (mode.trim().isEmpty) throw ArgumentError('Choose a mode first.');
final reply = await gateway.call('chat_mode', {
'chat_mode': {'session_id': session, 'mode': mode.trim()},
});
final echoed = reply['chat_mode'];
return echoed is Map ? '${echoed['mode'] ?? ''}'.trim() : mode.trim();
}
Future<List<JsonMap>> shells(String sessionId) async => _maps(
(await gateway.call('chat_shells', {
'chat_query': {'session_id': sessionId},
}))['chat_shells'],
);
Future<JsonMap> automations(String sessionId) =>
gateway.call('chat_automations', {
'chat_query': {'session_id': sessionId},
});
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'];
// The session's recorded per-turn changes ride with its history.
final turnDiffs = reply['chat_turn_diffs'];
if (page is Map) {
return {
'messages': _maps(page['messages']),
'nextCursor': '${page['next_cursor'] ?? ''}',
'hasMore': page['has_more'] == true,
'turnDiffs': ?turnDiffs,
};
}
return {
'messages': _maps(reply['chat_messages']),
'nextCursor': '',
'hasMore': false,
'turnDiffs': ?turnDiffs,
};
}
/// One turn's recorded file changes: the `chat_turn_diff` body with its
/// `summary` and `changes` (a `file_changes`-shaped capture).
Future<JsonMap> turnDiff(String sessionId, String turnId) async {
final reply = await gateway.call('chat_turn_diff', {
'chat_turn_diff': {'session_id': sessionId, 'turn_id': turnId},
});
final body = reply['chat_turn_diff'];
if (body is! Map || body['changes'] is! Map) {
throw StateError('The server returned no changes for this turn.');
}
return Map<String, dynamic>.from(body);
}
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(),
},
});
}
/// `/new`: the same chat continues on a fresh native session with an empty
/// context. The reply's `chat_session` is the chat under its new id, with
/// `previous_id` naming [sessionId].
Future<JsonMap> newSession(String sessionId, {String instructions = ''}) =>
gateway.call('chat_new_session', {
'chat_new_session': {
'session_id': sessionId,
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()},
});
/// The chat as one file: `chat_export_file` with name, mime and content.
/// A reply without a file is refused rather than saved as an empty file.
Future<JsonMap> export(String sessionId, String format) async {
final reply = await gateway.call('chat_export', {
'chat_export': {'session_id': sessionId, 'format': format},
});
final file = reply['chat_export_file'];
if (file is! Map || '${file['name'] ?? ''}'.trim().isEmpty) {
throw StateError('The server did not return an export file.');
}
return file.cast<String, dynamic>();
}
Future<JsonMap> star(String sessionId, bool starred) =>
gateway.call('chat_star', {
'chat_query': {'session_id': sessionId, 'starred': starred},
});
/// Sets the shared highlight colour by palette name; null clears it.
Future<JsonMap> setColor(String sessionId, String? color) =>
gateway.call('chat_color', {
'chat_query': {'session_id': sessionId, 'color': color},
});
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},
});
/// Removes one prompt the server still holds in the session's queue. The
/// reply's `chat_queue` is the queue afterwards; a prompt already handed to
/// the harness is refused.
Future<JsonMap> unqueue(String sessionId, String operationId) =>
gateway.call('chat_unqueue', {
'chat_unqueue': {'session_id': sessionId, 'operation_id': operationId},
});
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();
}