Files
pipelines/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart
T

251 lines
7.3 KiB
Dart

import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../../../core/api_gateway.dart';
import '../../../../core/transport/connection_state.dart';
import '../../data/chat_repository.dart';
import 'chat_session_local.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.
class ChatSessionsController extends ChangeNotifier {
ChatSessionsController(this.repository, {ChatSessionLocalStore? localStore})
: _localStore =
localStore ?? const SharedPreferencesChatSessionLocalStore();
ChatRepository repository;
final ChatSessionLocalStore _localStore;
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;
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 last hidden session, while its Undo is still offered.
String? get lastHidden => _lastHidden;
bool isUnseen(JsonMap session) {
final id = '${session['id'] ?? ''}';
// 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['running'] == true ||
session['closed_at'] != null ||
session['closed'] == true) {
return false;
}
final updatedAt = _millis(session['updated_at']);
return updatedAt > 0 && updatedAt > _local.watermark(id);
}
void replaceRepository(ChatRepository next) {
if (identical(next.gateway, repository.gateway)) return;
repository = next;
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 sessions = await repository.sessions();
if (generation != _generation) return;
_sessions = sessions;
_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));
Future<void> close(String sessionId) =>
_mutate(sessionId, () => repository.close(sessionId));
Future<void> reopen(String sessionId) =>
_mutate(sessionId, () => repository.reopen(sessionId));
/// 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({
required String title,
required String directory,
required String backend,
required String instructions,
required String operationId,
}) async {
final reply = await 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);
}
/// Records that this device has read [session]'s current recency.
Future<void> markOpened(JsonMap session) async {
final id = '${session['id'] ?? ''}';
if (id.isEmpty) return;
await _ensureLocal();
final next = _local.read(id, _millis(session['updated_at']));
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();
}
Future<void> _mutate(
String sessionId,
Future<JsonMap> Function() action,
) async {
try {
await action();
_actionErrors.remove(sessionId);
await refresh();
} catch (error) {
_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();
_notify();
}
void _seedLocal() {
if (!_localLoaded) return;
final next = _local.seed([
for (final session in _sessions)
(
id: '${session['id'] ?? ''}',
updatedAt: _millis(session['updated_at']),
),
]);
if (identical(next, _local)) return;
_local = next;
unawaited(_persist());
}
Future<void> _persist() async {
try {
await _localStore.save(_local);
} catch (_) {
// The in-memory choice still applies for this session.
}
}
static int _millis(Object? value) {
if (value is int) return value > 0 ? value : 0;
if (value is num) return value > 0 ? value.toInt() : 0;
final text = '${value ?? ''}'.trim();
if (text.isEmpty) return 0;
final number = int.tryParse(text);
if (number != null) return number > 0 ? number : 0;
return DateTime.tryParse(text)?.millisecondsSinceEpoch ?? 0;
}
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
_generation++;
super.dispose();
}
}