Files
pipelines/app/lib/features/chat/conversation/chat_thread_cards.dart
T

191 lines
6.4 KiB
Dart

import '../../../core/api_gateway.dart';
import '../data/chat_repository.dart';
import 'chat_permission_card_model.dart';
import 'chat_question_card_model.dart';
/// The open conversation's recorded approval requests and question forms.
///
/// This is the transcript controller's card collaborator: it owns frame folding,
/// the operator's optimistic answers, server refusals and the one-shot send
/// gates, so the controller itself stays about messages and live turn state.
///
/// The web drops an approval or form once it is resolved. This app keeps the
/// latest settled cards as read-only evidence, which is an intentional addition;
/// [settledLimit] bounds that history so a long session cannot grow without
/// limit while pending cards are never dropped.
class ChatThreadCards {
ChatThreadCards({
required this.repository,
required this.sessionId,
required this.notify,
required this.isAlive,
});
static const settledLimit = 20;
final ChatRepository repository;
final String sessionId;
final void Function() notify;
final bool Function() isAlive;
final List<JsonMap> _permissions = [];
final Map<String, JsonMap> _forms = {};
final Map<String, String> _answers = {};
final Map<String, String> _permissionErrors = {};
final Map<String, String> _formErrors = {};
final ChatActionGate _permissionGate = ChatActionGate();
final ChatActionGate _questionGate = ChatActionGate();
/// Every retained permission request, settled or still open, in server order.
List<JsonMap> get permissions => List.unmodifiable(_permissions);
/// Every retained question form, including answered and expired ones.
List<JsonMap> get forms => List.unmodifiable(_forms.values);
String answerFor(String requestId) => _answers[requestId] ?? '';
String? permissionErrorFor(String requestId) =>
_permissionErrors[requestId];
String? formErrorFor(String formId) => _formErrors[formId];
/// Answer one pending approval. The local decision settles the card before
/// the reply lands; a refusal reopens the same request with the server's
/// reason so an unaccepted decision is never shown as accepted. A second tap
/// of the same confirmed action is ignored until it settles.
Future<void> replyPermission(String requestId, String decision) async {
final id = requestId.trim();
if (id.isEmpty || !chatDecisions.contains(decision)) return;
final frame = _permissionFrame(id);
if (frame == null || frame['resolved'] == true) return;
final replyId = chatPermissionReplyId(id, decision);
if (!_permissionGate.start(replyId)) return;
_answers[id] = decision;
_permissionErrors.remove(id);
notify();
try {
await repository.replyPermission(sessionId, id, decision);
if (!isAlive()) return;
// A previous refusal's reason no longer describes an accepted reply.
if (_permissionErrors.remove(id) != null) notify();
} catch (error) {
if (!isAlive()) return;
final current = _permissionFrame(id);
// A server resolution that raced the refusal wins: do not reopen it.
if (current == null || current['resolved'] == true) return;
_answers.remove(id);
_permissionErrors[id] = '$error';
_permissionGate.release(replyId);
notify();
}
}
/// Answer or close a pending question with the web's field-keyed body. A
/// refusal keeps the card open and reports the server's reason.
Future<void> answerQuestion(
String formId,
Map<String, dynamic> answers,
String action,
) async {
final id = formId.trim();
final form = _forms[id];
if (id.isEmpty || form == null || !chatFormPending(form)) return;
final replyId = chatQuestionReplyId(id, action: action);
if (!_questionGate.start(replyId)) return;
_formErrors.remove(id);
notify();
try {
await repository.answerForm(
sessionId,
id,
Map<String, dynamic>.from(answers),
action: action,
);
if (!isAlive()) return;
_forms[id] = {
...form,
'resolved': true,
if (answers.isNotEmpty)
'answers': Map<String, dynamic>.from(answers),
};
_pruneSettledForms();
notify();
} catch (error) {
if (!isAlive()) return;
_formErrors[id] = '$error';
_questionGate.release(replyId);
notify();
}
}
/// Fold one pushed `chat_permission` frame. A repeat for the same request
/// replaces the recorded frame (a server resolution then wins over any local
/// answer); a frame for a new request is added after the held cards.
void foldPermission(JsonMap frame) {
final id = '${frame['request_id'] ?? ''}'.trim();
if (id.isEmpty) return;
final index = _permissions.indexWhere(
(held) => '${held['request_id'] ?? ''}'.trim() == id,
);
if (index < 0) {
_permissions.add(frame);
} else {
_permissions[index] = frame;
}
if (frame['resolved'] == true) _permissionErrors.remove(id);
_pruneSettledPermissions();
notify();
}
/// Fold one `form` event. A folded update keeps a settled form's recorded
/// answers for the read-only card.
void foldForm(JsonMap form) {
final id = '${form['id'] ?? ''}'.trim();
if (id.isEmpty) return;
final next = chatFoldQuestionFrame(_forms, form);
if (identical(next, _forms)) return;
_forms
..clear()
..addAll(next);
_formErrors.remove(id);
_pruneSettledForms();
notify();
}
JsonMap? _permissionFrame(String requestId) {
for (final frame in _permissions) {
if ('${frame['request_id'] ?? ''}'.trim() == requestId) return frame;
}
return null;
}
bool _permissionSettled(JsonMap frame) =>
frame['resolved'] == true ||
'${frame['decision'] ?? ''}'.trim().isNotEmpty;
void _pruneSettledPermissions() {
final settled = _permissions.where(_permissionSettled).toList();
final excess = settled.length - settledLimit;
if (excess <= 0) return;
for (final frame in settled.take(excess)) {
_permissions.remove(frame);
final id = '${frame['request_id'] ?? ''}'.trim();
_answers.remove(id);
_permissionErrors.remove(id);
}
}
void _pruneSettledForms() {
final settled = [
for (final entry in _forms.entries)
if (!chatFormPending(entry.value)) entry.key,
];
final excess = settled.length - settledLimit;
if (excess <= 0) return;
for (final id in settled.take(excess)) {
_forms.remove(id);
_formErrors.remove(id);
}
}
}