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

174 lines
4.9 KiB
Dart

import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import '../../../core/error_reason.dart';
import '../data/chat_repository.dart';
import '../domain/chat_shells.dart';
/// One session's live background tasks and lazy, bounded output selection.
class ChatBackgroundTasksController extends ChangeNotifier {
ChatBackgroundTasksController(this.gateway, this.sessionId) {
_listen();
unawaited(refresh());
}
ApiGateway gateway;
String sessionId;
late ChatRepository _repository = ChatRepository(gateway);
StreamSubscription<JsonMap>? _frames;
List<JsonMap> _shells = const [];
Map<String, JsonMap>? _loadFrames;
String? selectedId;
ChatShellOutputSnapshot? output;
String? error;
bool loading = true;
bool _disposed = false;
int _generation = 0;
int _outputGeneration = 0;
List<JsonMap> get running => runningShells(_shells);
JsonMap? get selectedShell =>
running.where((shell) => shellIdOf(shell) == selectedId).firstOrNull;
void replace(
ApiGateway nextGateway,
String nextSessionId, {
bool notify = true,
}) {
if (_disposed) return;
unawaited(_frames?.cancel());
gateway = nextGateway;
sessionId = nextSessionId;
_repository = ChatRepository(gateway);
_listen();
reconnect(notify: notify);
}
void reconnect({bool notify = true}) {
if (_disposed) return;
_shells = const [];
selectedId = null;
output = null;
error = null;
_outputGeneration++;
unawaited(refresh(notify: notify));
}
void _listen() => _frames = gateway.frames.listen((envelope) {
if (_disposed || envelope['type'] != 'chat_event') return;
final frame = envelope['chat_event'];
if (frame is! Map ||
frame['session_id'] != sessionId ||
frame['kind'] != 'shell' ||
frame['shell'] is! Map) {
return;
}
_shells = mergeShellFrame(
_shells,
Map<String, dynamic>.from(frame['shell'] as Map),
);
final id = shellIdOf(Map<String, dynamic>.from(frame['shell'] as Map));
if (_loadFrames != null && !blankShellValue(id)) {
_loadFrames![id] = _shells.firstWhere((shell) => shellIdOf(shell) == id);
if (_loadFrames!.length > observedShellLimit) {
_loadFrames!.remove(_loadFrames!.keys.first);
}
}
_dropStaleSelection();
notifyListeners();
}, onError: (_) {});
Future<void> refresh({bool notify = true}) async {
if (_disposed) return;
final token = ++_generation;
final observed = <String, JsonMap>{};
_loadFrames = observed;
loading = true;
if (notify) notifyListeners();
try {
final shells = await _repository.shells(sessionId);
if (_disposed || token != _generation) return;
_shells = shellsLoaded(_shells, shells);
// Live frames are newer than a snapshot requested before they arrived.
for (final frame in observed.values) {
_shells = mergeShellFrame(_shells, frame);
}
error = null;
_dropStaleSelection();
} catch (failure) {
if (_disposed || token != _generation) return;
error = describeErrorReason(
failure,
fallback: 'The server did not answer.',
);
}
loading = false;
_loadFrames = null;
notifyListeners();
}
void _dropStaleSelection() {
if (selectedId == null || selectedShell != null) return;
selectedId = null;
output = null;
_outputGeneration++;
}
void select(String id) {
if (_disposed) return;
if (selectedId == id) {
selectedId = null;
output = null;
_outputGeneration++;
notifyListeners();
return;
}
if (!running.any((shell) => shellIdOf(shell) == id)) return;
selectedId = id;
unawaited(readOutput());
}
Future<void> readOutput() async {
final id = selectedId;
if (_disposed || id == null) return;
final token = ++_outputGeneration;
output = const ChatShellOutputSnapshot(loading: true);
notifyListeners();
try {
final reply = await _repository.shellOutput(
sessionId,
id,
cursor: 0,
limit: chatShellOutputLimit,
);
if (_disposed || token != _outputGeneration || selectedId != id) return;
final page = ChatShellOutputPage.fromReply(reply);
if (page.shell case final shell? when !blankShellValue(shell['id'])) {
_shells = mergeShellFrame(_shells, shell);
}
output = ChatShellOutputSnapshot(page: page);
_dropStaleSelection();
} catch (failure) {
if (_disposed || token != _outputGeneration || selectedId != id) return;
output = ChatShellOutputSnapshot(
error: describeErrorReason(
failure,
fallback: 'The server did not answer.',
),
);
}
notifyListeners();
}
@override
void dispose() {
_disposed = true;
_generation++;
_outputGeneration++;
unawaited(_frames?.cancel());
super.dispose();
}
}