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

287 lines
10 KiB
Dart

import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import 'chat_composer_send.dart';
/// Where one of the operator's own messages is on its way to the server.
enum ChatDelivery {
/// The prompt request is awaiting the server's reply.
sending,
/// The server accepted the prompt.
sent,
/// The server accepted the prompt behind the turn in flight.
queued,
/// The server handed the prompt to the turn already running.
steered,
/// The server refused the prompt, or its request was lost.
failed,
}
/// The delivery state of this conversation's own sends, and the messages that
/// were not sent.
///
/// Messages read from history carry no state: they were sent. Only sends made
/// from this composer (and intents read back from device storage) are
/// tracked. An unsent intent is not a transcript message, so it is listed in
/// [unsent] and drawn after the transcript until it is re-sent, edited or
/// found in the server's history.
class ChatDeliveries extends ChangeNotifier {
final Map<String, ChatDelivery> _states = {};
final Map<String, String> _operationByNative = {};
final List<ChatComposerSend> _unsent = [];
/// Intents read back from device storage that no history read has checked.
final List<ChatComposerSend> _unverified = [];
String? _latestSent;
bool _disposed = false;
/// The intents the server has not accepted, in send order.
List<ChatComposerSend> get unsent => List.unmodifiable(_unsent);
/// Whether any intent still waits for a history read to settle it.
bool get hasUnverified => _unverified.isNotEmpty;
/// The state to draw under a transcript user [message], or null for a quiet
/// message. "Sent" is shown only on the newest accepted send.
ChatDelivery? stateFor(JsonMap message) {
final operation = _operationOf(message);
if (operation == null) return null;
final state = _states[operation];
if ((state == ChatDelivery.sent || state == ChatDelivery.steered) &&
operation != _latestSent) {
return null;
}
return state;
}
String? _operationOf(JsonMap message) {
final operation = message['operation_id'];
if (operation is String && _states.containsKey(operation)) {
return operation;
}
for (final key in [message['native_message_id'], message['id']]) {
if (key is String && _operationByNative.containsKey(key)) {
return _operationByNative[key];
}
}
return null;
}
void sending(ChatComposerSend send) {
_own.add(send.operationId);
_unsent.removeWhere((item) => item.operationId == send.operationId);
_set(send, ChatDelivery.sending);
}
void accepted(
ChatComposerSend send, {
required bool queued,
bool steered = false,
}) {
// The server's queue report may already have moved this prompt on (its
// frame and the reply race on the socket); never step it back.
final current = _states[send.operationId];
if (queued &&
_serverQueueKnown &&
!_serverQueued.contains(send.operationId) &&
current == ChatDelivery.sent) {
return;
}
if (!queued) _latestSent = send.operationId;
_set(
send,
queued
? ChatDelivery.queued
: steered
? ChatDelivery.steered
: ChatDelivery.sent,
);
}
void failed(ChatComposerSend send) {
_unsent
..removeWhere((item) => item.operationId == send.operationId)
..add(send);
_set(send, ChatDelivery.failed);
}
/// The operation ids the server reported holding in its queue, and the
/// prompts themselves (to draw one the harness refused as "Not sent").
final Set<String> _serverQueued = {};
final Map<String, JsonMap> _serverPrompts = {};
/// Operation ids sent from this composer, so its "Queued" notice reflects
/// only its own prompts, not another device's.
final Set<String> _own = {};
/// Set once the server reported its queue: from then on only its reports
/// move a prompt out of "Queued".
bool _serverQueueKnown = false;
/// Whether one of this composer's own prompts waits in the server's queue.
bool get ownQueued => _own.any(_serverQueued.contains);
/// Whether the server reports its queue (so no local heuristic applies).
bool get serverQueueKnown => _serverQueueKnown;
/// Whether the server reported holding [operationId] in its queue.
bool serverHolds(String operationId) => _serverQueued.contains(operationId);
/// Whether [operationId] is currently drawn as "Queued".
bool isQueued(String operationId) =>
_states[operationId] == ChatDelivery.queued;
/// Adopts the server's queue [frame] (`prompts` plus the change it reports).
/// Every listed prompt is "Queued" — including one this device stored but
/// never saw acknowledged, which is the server's now. One that left the
/// queue was sent, unless the frame says it was removed (forgotten) or the
/// harness refused it ("Not sent", re-sendable when it carried no files).
/// Returns the listed operation ids so their stored copies can be dropped.
Set<String> applyServerQueue(JsonMap frame) {
_serverQueueKnown = true;
final listed = <String>{};
for (final prompt in frame['prompts'] as List? ?? const []) {
if (prompt is! Map) continue;
final operation = '${prompt['operation_id'] ?? ''}';
if (operation.isEmpty) continue;
listed.add(operation);
_states[operation] = ChatDelivery.queued;
for (final key in [prompt['native_message_id'], prompt['message_id']]) {
if (key is String && key.isNotEmpty) {
_operationByNative[key] = operation;
}
}
}
_unsent.removeWhere((item) => listed.contains(item.operationId));
_unverified.removeWhere((item) => listed.contains(item.operationId));
final removed = '${frame['removed'] ?? ''}';
final failed = '${frame['failed'] ?? ''}';
for (final operation in _serverQueued.difference(listed)) {
if (operation == removed) {
_states.remove(operation);
} else if (operation == failed) {
_states[operation] = ChatDelivery.failed;
final prompt = _serverPrompts[operation];
if (prompt != null) {
final attachments = [
for (final part in prompt['attachments'] as List? ?? const [])
if (part is Map) {'name': part['name'], 'mime': part['mime']},
];
final send = ChatComposerSend(
sessionId: '${frame['session_id'] ?? ''}',
text: '${prompt['text'] ?? ''}',
operationId: operation,
nativeMessageId: '${prompt['native_message_id'] ?? ''}',
attachments: attachments,
// Only the server held the files; they cannot be sent again from
// here, so such a message can be discarded but not retried.
attachmentsOmitted: attachments.isNotEmpty,
);
_unsent
..removeWhere((item) => item.operationId == operation)
..add(send);
}
} else if (_states[operation] == ChatDelivery.queued) {
_states[operation] = ChatDelivery.sent;
_latestSent = operation;
}
}
_serverQueued
..clear()
..addAll(listed);
_serverPrompts
..clear()
..addAll({
for (final prompt in frame['prompts'] as List? ?? const [])
if (prompt is Map && listed.contains(prompt['operation_id']))
'${prompt['operation_id']}': Map<String, dynamic>.from(prompt),
});
_notify();
return listed;
}
/// A queued prompt was admitted: the turn it waited behind moved on. Only
/// used with a server that does not report its queue.
void admitQueued() {
if (_serverQueueKnown) return;
var changed = false;
for (final entry in _states.entries.toList()) {
if (entry.value != ChatDelivery.queued) continue;
_states[entry.key] = ChatDelivery.sent;
_latestSent = entry.key;
changed = true;
}
if (changed) _notify();
}
/// Drops an unsent intent the operator took back into the composer.
void forget(String operationId) {
final before = _unsent.length + _unverified.length;
_unsent.removeWhere((item) => item.operationId == operationId);
_unverified.removeWhere((item) => item.operationId == operationId);
_states.remove(operationId);
if (_unsent.length + _unverified.length != before) _notify();
}
/// Adopts intents read back from device storage. They stay hidden until
/// [reconcile] has checked them against an authoritative history read.
void restore(List<ChatComposerSend> intents) {
var changed = false;
for (final intent in intents) {
if (_states.containsKey(intent.operationId)) continue;
_remember(intent);
_states[intent.operationId] = ChatDelivery.failed;
_unverified.add(intent);
changed = true;
}
if (changed) _notify();
}
/// Settles stored and unsent intents against an authoritative transcript:
/// one the server recorded was sent and is returned so its stored copy can
/// be cleared; an unchecked one that is absent becomes "Not sent".
List<ChatComposerSend> reconcile(List<JsonMap> messages) {
bool recorded(ChatComposerSend intent) =>
messages.any((message) => intent.recordedBy(message));
final confirmed = <ChatComposerSend>[
for (final intent in [..._unverified, ..._unsent])
if (recorded(intent)) intent,
];
final changed = confirmed.isNotEmpty || _unverified.isNotEmpty;
for (final intent in confirmed) {
_states[intent.operationId] = ChatDelivery.sent;
}
_unsent.removeWhere(confirmed.contains);
_unverified.removeWhere(confirmed.contains);
_unsent.addAll(_unverified);
_unverified.clear();
if (changed) _notify();
return confirmed;
}
void _remember(ChatComposerSend send) {
if (send.nativeMessageId.isEmpty) return;
_operationByNative[send.nativeMessageId] = send.operationId;
}
void _set(ChatComposerSend send, ChatDelivery state) {
_remember(send);
_states[send.operationId] = state;
_notify();
}
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}