570 lines
19 KiB
Dart
570 lines
19 KiB
Dart
import '../../../../core/servers/chat/federated_chat_gateway.dart';
|
|
import 'federated_chat_session_local.dart';
|
|
import 'dart:async';
|
|
import 'dart:math';
|
|
|
|
import 'package:flutter/foundation.dart';
|
|
|
|
import '../../../../core/api_gateway.dart';
|
|
import '../../../../core/servers/server_scope.dart';
|
|
import '../../../../core/transport/connection_state.dart';
|
|
import '../../../attention/runtime/attention_ack_sync.dart';
|
|
import '../../data/chat_repository.dart';
|
|
import '../../domain/chat_list_activity.dart';
|
|
import '../../domain/chat_sessions.dart';
|
|
import 'chat_session_local.dart';
|
|
import 'session_attention.dart';
|
|
|
|
/// Owns the session list, its refresh generation and the shared row actions.
|
|
///
|
|
/// A refresh that finishes after a newer one (or after the screen is gone) is
|
|
/// discarded, so a slow reply can never replace fresher state. Accepted
|
|
/// mutations always re-read the server list; only this device's hidden ids and
|
|
/// read watermark are local.
|
|
///
|
|
/// With an [AttentionAckSync] (bound to the gateway by the app, or passed in),
|
|
/// reading is shared: opening a chat acknowledges a `chat_seen` watermark to
|
|
/// every device, and a watermark acknowledged elsewhere that is newer than this
|
|
/// device's own clears the chat's New badge here. The local store remains the
|
|
/// offline cache of both.
|
|
class ChatSessionsController extends ChangeNotifier {
|
|
ChatSessionsController(
|
|
this.repository, {
|
|
ChatSessionLocalStore? localStore,
|
|
AttentionAckSync? ackSync,
|
|
int Function()? nowMillis,
|
|
this.activeAckDelay = const Duration(milliseconds: 1500),
|
|
}) : _localStore =
|
|
localStore ??
|
|
(repository.gateway is FederatedChatGateway
|
|
? FederatedChatSessionLocalStore(
|
|
() => (repository.gateway as FederatedChatGateway).serverIds,
|
|
)
|
|
: SharedPreferencesChatSessionLocalStore(
|
|
serverId: serverStorageScope(
|
|
serverIdentity(repository.gateway),
|
|
),
|
|
)),
|
|
_nowMillis = nowMillis ?? _wallClockMillis {
|
|
_listenFrames();
|
|
_bindAckSync(ackSync ?? attentionAckSyncOf(repository.gateway));
|
|
}
|
|
|
|
static int _wallClockMillis() => DateTime.now().millisecondsSinceEpoch;
|
|
|
|
/// How long the open chat stays quiet before its new content is
|
|
/// acknowledged to the other devices; streaming text arrives in many frames.
|
|
final Duration activeAckDelay;
|
|
|
|
ChatRepository repository;
|
|
final ChatSessionLocalStore _localStore;
|
|
final int Function() _nowMillis;
|
|
AttentionAckSync? _ackSync;
|
|
Timer? _activeAck;
|
|
ChatSessionLocal _local = const ChatSessionLocal();
|
|
final Map<String, String> _actionErrors = {};
|
|
List<JsonMap> _sessions = const [];
|
|
String? _error;
|
|
String? _lastHidden;
|
|
bool _loading = true;
|
|
bool _localLoaded = false;
|
|
Future<void>? _localLoading;
|
|
bool _disposed = false;
|
|
int _generation = 0;
|
|
Future<void> _persistTail = Future<void>.value();
|
|
int _runningRevision = 0;
|
|
final Map<String, ({int revision, bool running})> _runningFrames = {};
|
|
// The newest server activity applied per chat (list row or push), so an
|
|
// older snapshot that arrives later never replaces it.
|
|
final Map<String, ChatListActivity> _activity = {};
|
|
StreamSubscription<JsonMap>? _frameSubscription;
|
|
String? activeSessionId;
|
|
|
|
void _listenFrames() {
|
|
_frameSubscription?.cancel();
|
|
_frameSubscription = repository.gateway.frames.listen(_onFrame);
|
|
}
|
|
|
|
void _onFrame(JsonMap frame) {
|
|
if (frame['type'] == 'chat_session_changed') return _sessionChanged(frame);
|
|
if (frame['type'] == 'chat_activity') {
|
|
return _activityChanged(frame['chat_activity']);
|
|
}
|
|
final effect = chatSessionFrameEffect(frame);
|
|
if (effect == null) return;
|
|
final id = effect.sessionId;
|
|
final session = _sessions.where((row) => '${row['id'] ?? ''}' == id);
|
|
if (session.isEmpty) return;
|
|
final row = session.first;
|
|
if (row['closed_at'] != null || row['closed'] == true) return;
|
|
if (effect.running != null) _setRunning(id, effect.running!);
|
|
if (effect.attention && id != activeSessionId) unawaited(_markUnseen(id));
|
|
if (effect.attention && id == activeSessionId) _scheduleActiveAck(id);
|
|
}
|
|
|
|
/// Another device changed a chat's shared colour, star or title: the row
|
|
/// takes the server's values at once, with no re-list. Each field the
|
|
/// registry row omits is cleared, since omitted means unset on the wire.
|
|
///
|
|
/// A row naming `previous_id` is a chat another device moved to a fresh
|
|
/// session (`/new`): it replaces that row in place and [onSessionReplaced]
|
|
/// lets the destination follow it if that chat is open here.
|
|
void _sessionChanged(JsonMap frame) {
|
|
final changed = frame['chat_session'];
|
|
if (changed is! Map) return;
|
|
final id = '${changed['id'] ?? ''}';
|
|
if (id.isEmpty || _disposed) return;
|
|
final previousId = '${changed['previous_id'] ?? ''}'.trim();
|
|
if (previousId.isNotEmpty && previousId != id) {
|
|
final row = Map<String, dynamic>.from(changed)..remove('previous_id');
|
|
replaceSession(previousId, row);
|
|
onSessionReplaced?.call(previousId, row);
|
|
return;
|
|
}
|
|
var found = false;
|
|
_sessions = [
|
|
for (final row in _sessions)
|
|
if ('${row['id'] ?? ''}' == id)
|
|
() {
|
|
found = true;
|
|
final next = <String, dynamic>{...row};
|
|
for (final key in const ['color', 'starred', 'starred_at']) {
|
|
if (changed.containsKey(key)) {
|
|
next[key] = changed[key];
|
|
} else {
|
|
next.remove(key);
|
|
}
|
|
}
|
|
final title = '${changed['title'] ?? ''}'.trim();
|
|
if (title.isNotEmpty) next['title'] = title;
|
|
return next;
|
|
}()
|
|
else
|
|
row,
|
|
];
|
|
if (found) _notify();
|
|
}
|
|
|
|
/// The server pushed a chat's turn state and background-task count. It
|
|
/// reaches every connection, so every listed chat's spinner and
|
|
/// background-task badge follow it, not only the chat open here. A push
|
|
/// older than the snapshot already applied is ignored.
|
|
void _activityChanged(Object? body) {
|
|
final activity = chatListActivityOf(body);
|
|
if (activity == null || _disposed) return;
|
|
final id = activity.sessionId;
|
|
if (activity.seq <= (_activity[id]?.seq ?? 0)) return;
|
|
_activity[id] = activity;
|
|
_runningFrames[id] = (
|
|
revision: ++_runningRevision,
|
|
running: activity.turnRunning,
|
|
);
|
|
final fields = chatListActivityRowFields(activity);
|
|
var changed = false;
|
|
_sessions = [
|
|
for (final row in _sessions)
|
|
if ('${row['id'] ?? ''}' == id &&
|
|
(row['running'] != fields['running'] ||
|
|
row['background_tasks'] != fields['background_tasks']))
|
|
() {
|
|
changed = true;
|
|
return {...row, ...fields};
|
|
}()
|
|
else
|
|
row,
|
|
];
|
|
if (changed) _notify();
|
|
}
|
|
|
|
/// A listed row with the newest activity known for it: the row's own
|
|
/// `activity` unless a newer push was already applied, then a turn frame
|
|
/// this connection saw during the read. An older server sends no
|
|
/// `activity`, so only the turn frames apply, as before.
|
|
JsonMap _withActivity(JsonMap row, int runningRevision) {
|
|
final id = '${row['id'] ?? ''}';
|
|
var next = row;
|
|
final listed = chatListActivityOf(row['activity'], sessionId: id);
|
|
if (listed != null) {
|
|
final known = _activity[id];
|
|
final activity = known != null && known.seq > listed.seq ? known : listed;
|
|
_activity[id] = activity;
|
|
next = {...row, ...chatListActivityRowFields(activity)};
|
|
}
|
|
final frame = _runningFrames[id];
|
|
if ((frame?.revision ?? 0) > runningRevision) {
|
|
next = {...next, 'running': frame!.running};
|
|
}
|
|
return next;
|
|
}
|
|
|
|
void _bindAckSync(AttentionAckSync? sync) {
|
|
if (identical(sync, _ackSync)) return;
|
|
_ackSync?.removeListener(_ackChanged);
|
|
_ackSync = sync;
|
|
sync?.addListener(_ackChanged);
|
|
_ackChanged();
|
|
}
|
|
|
|
/// Content arriving in the chat this device has open is read here, so it is
|
|
/// acknowledged to the other devices once the stream goes quiet.
|
|
void _scheduleActiveAck(String id) {
|
|
if (_ackSync == null) return;
|
|
_activeAck?.cancel();
|
|
_activeAck = Timer(activeAckDelay, () {
|
|
if (_disposed || id != activeSessionId) return;
|
|
unawaited(_acknowledgeSeen(id, 0));
|
|
});
|
|
}
|
|
|
|
/// Applies watermarks acknowledged on any device: one newer than this
|
|
/// device's own marks the chat read here (clearing its New badge) and raises
|
|
/// the local watermark, so a later badge is not cleared by the same ack.
|
|
void _ackChanged() {
|
|
final seen = _ackSync?.acks.chatSeen;
|
|
if (_disposed || !_localLoaded || seen == null) return;
|
|
var next = _local;
|
|
seen.forEach((id, at) {
|
|
if (at > next.watermark(id)) next = next.read(id, at);
|
|
});
|
|
if (identical(next, _local)) return;
|
|
_local = next;
|
|
_notify();
|
|
unawaited(_persist());
|
|
}
|
|
|
|
/// Marks [id] read up to now here and acknowledges it to every device. The
|
|
/// value is at least the row's own recency; the server lifts it further to
|
|
/// the session's registry recency.
|
|
Future<void> _acknowledgeSeen(String id, int updatedAt) async {
|
|
await _ensureLocal();
|
|
if (_disposed) return;
|
|
final at = max(updatedAt, _nowMillis());
|
|
final next = _local.read(id, at);
|
|
if (!identical(next, _local)) {
|
|
_local = next;
|
|
_notify();
|
|
await _persist();
|
|
}
|
|
if (_disposed) return;
|
|
await _ackSync?.acknowledge(chatSeen: {id: at});
|
|
}
|
|
|
|
void _setRunning(String id, bool running) {
|
|
if (_disposed) return;
|
|
_runningFrames[id] = (revision: ++_runningRevision, running: running);
|
|
var changed = false;
|
|
_sessions = _sessions.map((session) {
|
|
if ('${session['id'] ?? ''}' != id || session['running'] == running) {
|
|
return session;
|
|
}
|
|
changed = true;
|
|
return {...session, 'running': running};
|
|
}).toList();
|
|
if (changed) _notify();
|
|
}
|
|
|
|
Future<void> _markUnseen(String id) async {
|
|
await _ensureLocal();
|
|
// Loading device preferences may race an operator opening this chat. The
|
|
// open is authoritative even when the triggering frame arrived first.
|
|
if (_disposed || id == activeSessionId) return;
|
|
final next = _local.markUnseen(id);
|
|
if (identical(next, _local)) return;
|
|
_local = next;
|
|
_notify();
|
|
await _persist();
|
|
}
|
|
|
|
List<JsonMap> get sessions => [
|
|
for (final session in _sessions)
|
|
if (!_local.isHidden('${session['id'] ?? ''}')) session,
|
|
];
|
|
|
|
String? get error => _error;
|
|
bool get loading => _loading;
|
|
|
|
/// The row an action failed on; the message is the server's own words.
|
|
String? errorFor(String sessionId) => _actionErrors[sessionId];
|
|
|
|
/// The operator acknowledged [sessionId]'s refusal; nothing is sent.
|
|
void dismissError(String sessionId) {
|
|
if (_actionErrors.remove(sessionId) != null) _notify();
|
|
}
|
|
|
|
/// The last hidden session, while its Undo is still offered.
|
|
String? get lastHidden => _lastHidden;
|
|
|
|
bool isUnseen(JsonMap session) {
|
|
final id = '${session['id'] ?? ''}';
|
|
if (id == activeSessionId) return false;
|
|
// Closed chats keep their recency from the close, but they are not new
|
|
// work: both the web list and the Android list suppress unseen there.
|
|
if (!_localLoaded ||
|
|
id.isEmpty ||
|
|
session['closed_at'] != null ||
|
|
session['closed'] == true) {
|
|
return false;
|
|
}
|
|
if (_local.isUnseen(id)) return true;
|
|
return false;
|
|
}
|
|
|
|
void replaceRepository(ChatRepository next) {
|
|
if (identical(next.gateway, repository.gateway)) return;
|
|
repository = next;
|
|
_runningFrames.clear();
|
|
_activity.clear();
|
|
_listenFrames();
|
|
_bindAckSync(attentionAckSyncOf(next.gateway) ?? _ackSync);
|
|
refresh();
|
|
}
|
|
|
|
Future<void> refresh() async {
|
|
if (_disposed) return;
|
|
final generation = ++_generation;
|
|
_loading = true;
|
|
_error = null;
|
|
_notify();
|
|
// Device preferences never gate the server read: a slow platform store
|
|
// must not hide the list or delay the first request.
|
|
unawaited(_ensureLocal());
|
|
try {
|
|
final runningRevision = _runningRevision;
|
|
final sessions = await repository.sessions();
|
|
if (generation != _generation) return;
|
|
_sessions = [
|
|
for (final row in sessions) _withActivity(row, runningRevision),
|
|
];
|
|
_seedLocal();
|
|
_loading = false;
|
|
_notify();
|
|
} catch (error) {
|
|
if (generation != _generation) return;
|
|
_error = '$error';
|
|
_loading = false;
|
|
_notify();
|
|
}
|
|
}
|
|
|
|
Future<void> star(String sessionId, bool starred) => _mutate(
|
|
sessionId,
|
|
() => repository.star(sessionId, starred),
|
|
patch: {'starred': starred},
|
|
);
|
|
|
|
/// Sets [sessionId]'s shared colour (a palette name, null for none).
|
|
Future<void> setColor(String sessionId, String? color) => _mutate(
|
|
sessionId,
|
|
() => repository.setColor(sessionId, color),
|
|
patch: {'color': color},
|
|
);
|
|
|
|
Future<void> close(String sessionId) => _mutate(
|
|
sessionId,
|
|
() => repository.close(sessionId),
|
|
patch: {'closed_at': DateTime.now().toUtc().toIso8601String()},
|
|
);
|
|
|
|
Future<void> reopen(String sessionId) => _mutate(
|
|
sessionId,
|
|
() => repository.reopen(sessionId),
|
|
patch: {'closed_at': null},
|
|
);
|
|
|
|
/// Renames through the shared server field. Throws the server's refusal so the
|
|
/// open dialog can keep it in view; success refreshes the list from the server.
|
|
///
|
|
/// The dialog owns the refusal, so no row error is stored: the same sentence
|
|
/// must not also stick under the list row.
|
|
Future<void> renameOrThrow(String sessionId, String title) async {
|
|
await repository.rename(sessionId, title);
|
|
_actionErrors.remove(sessionId);
|
|
await refresh();
|
|
}
|
|
|
|
/// Creates one session and returns the server's `chat_session`. A reply
|
|
/// without one is refused rather than opening an invented row.
|
|
Future<JsonMap> createOrThrow({
|
|
ChatRepository? targetRepository,
|
|
required String title,
|
|
required String directory,
|
|
required String backend,
|
|
required String instructions,
|
|
required String operationId,
|
|
}) async {
|
|
final reply = await (targetRepository ?? repository).create(
|
|
title: title,
|
|
directory: directory,
|
|
backend: backend,
|
|
operationId: operationId,
|
|
instructions: instructions,
|
|
);
|
|
final session = reply['chat_session'];
|
|
if (session is! Map) {
|
|
// The web reports exactly this refusal, so the dialog shows the same
|
|
// sentence instead of a Dart `Bad state:` prefix.
|
|
throw const ProtocolError(
|
|
'The server did not return the new chat session.',
|
|
);
|
|
}
|
|
// Opening the created chat must not wait for the list refresh: the dialog
|
|
// has already closed, so a slow listing would look like a failed create.
|
|
unawaited(refresh());
|
|
return Map<String, dynamic>.from(session);
|
|
}
|
|
|
|
/// Called when another device moved a listed chat to a fresh session, with
|
|
/// the id it left and its row under the new id.
|
|
void Function(String previousId, JsonMap session)? onSessionReplaced;
|
|
|
|
/// `/new` moved the chat [previousId] to a fresh native session: [session]
|
|
/// takes that row's place in the list (it is the same chat), so it is
|
|
/// present before its conversation opens; the caller re-reads the list from
|
|
/// the server afterwards. A row unknown here is listed at the head, and a
|
|
/// row already under the new id is never duplicated.
|
|
void replaceSession(String previousId, JsonMap session) {
|
|
if (_disposed) return;
|
|
final id = '${session['id'] ?? ''}';
|
|
if (id.isEmpty) return;
|
|
var placed = false;
|
|
final next = <JsonMap>[];
|
|
for (final row in _sessions) {
|
|
final rowId = '${row['id'] ?? ''}';
|
|
if (rowId == previousId) {
|
|
if (!placed) next.add(session);
|
|
placed = true;
|
|
} else if (rowId != id) {
|
|
next.add(row);
|
|
}
|
|
}
|
|
_sessions = placed ? next : [session, ...next];
|
|
if (activeSessionId == previousId) activeSessionId = id;
|
|
_seedLocal();
|
|
_notify();
|
|
}
|
|
|
|
/// Records that this device has read [session]'s current recency.
|
|
Future<void> markOpened(JsonMap session) async {
|
|
final id = '${session['id'] ?? ''}';
|
|
if (id.isEmpty) return;
|
|
activeSessionId = id;
|
|
await _ensureLocal();
|
|
if (_disposed) return;
|
|
final updatedAt = chatSessionMillis(session['updated_at']);
|
|
if (_ackSync != null) return _acknowledgeSeen(id, updatedAt);
|
|
final next = _local.read(id, updatedAt);
|
|
if (identical(next, _local)) return;
|
|
_local = next;
|
|
_notify();
|
|
await _persist();
|
|
}
|
|
|
|
/// Hides one row on this device only; the server row is untouched.
|
|
Future<void> hide(String sessionId) async {
|
|
await _ensureLocal();
|
|
final next = _local.hide(sessionId);
|
|
if (identical(next, _local)) return;
|
|
_local = next;
|
|
_lastHidden = sessionId;
|
|
_notify();
|
|
await _persist();
|
|
}
|
|
|
|
Future<void> undoHide() async {
|
|
final id = _lastHidden;
|
|
if (id == null) return;
|
|
_local = _local.restore(id);
|
|
_lastHidden = null;
|
|
_notify();
|
|
await _persist();
|
|
}
|
|
|
|
void dismissUndo() {
|
|
if (_lastHidden == null) return;
|
|
_lastHidden = null;
|
|
_notify();
|
|
}
|
|
|
|
/// Applies [patch] to the row at once, so the list answers the tap
|
|
/// immediately, then saves it. The server's refusal puts the row back and
|
|
/// shows the reason; success re-reads the list in the background.
|
|
Future<void> _mutate(
|
|
String sessionId,
|
|
Future<JsonMap> Function() action, {
|
|
JsonMap? patch,
|
|
}) async {
|
|
final before = _sessions;
|
|
if (patch != null) {
|
|
_sessions = [
|
|
for (final row in _sessions)
|
|
if ('${row['id'] ?? ''}' == sessionId) {...row, ...patch} else row,
|
|
];
|
|
_actionErrors.remove(sessionId);
|
|
_notify();
|
|
}
|
|
try {
|
|
await action();
|
|
_actionErrors.remove(sessionId);
|
|
unawaited(refresh());
|
|
} catch (error) {
|
|
if (patch != null) _sessions = before;
|
|
_actionErrors[sessionId] = '$error';
|
|
_notify();
|
|
}
|
|
}
|
|
|
|
Future<void> _ensureLocal() => _localLoading ??= _loadLocal();
|
|
|
|
Future<void> _loadLocal() async {
|
|
try {
|
|
_local = await _localStore.load();
|
|
} catch (_) {
|
|
_local = const ChatSessionLocal();
|
|
}
|
|
_localLoaded = true;
|
|
_seedLocal();
|
|
_ackChanged();
|
|
_notify();
|
|
}
|
|
|
|
void _seedLocal() {
|
|
if (!_localLoaded) return;
|
|
final next = _local.seed([
|
|
for (final session in _sessions)
|
|
(
|
|
id: '${session['id'] ?? ''}',
|
|
updatedAt: chatSessionMillis(session['updated_at']),
|
|
),
|
|
]);
|
|
if (identical(next, _local)) return;
|
|
_local = next;
|
|
unawaited(_persist());
|
|
}
|
|
|
|
Future<void> _persist() {
|
|
final snapshot = _local;
|
|
_persistTail = _persistTail.then((_) async {
|
|
try {
|
|
await _localStore.save(snapshot);
|
|
} catch (_) {
|
|
// The in-memory choice still applies for this session.
|
|
}
|
|
});
|
|
return _persistTail;
|
|
}
|
|
|
|
void _notify() {
|
|
if (!_disposed) notifyListeners();
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_disposed = true;
|
|
_generation++;
|
|
unawaited(_frameSubscription?.cancel());
|
|
_activeAck?.cancel();
|
|
_ackSync?.removeListener(_ackChanged);
|
|
super.dispose();
|
|
}
|
|
}
|