import 'dart:async'; import 'package:flutter/foundation.dart'; import '../../../../core/api_gateway.dart'; import '../../data/chat_repository.dart'; /// Owns the session list, its refresh generation and the 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. class ChatSessionsController extends ChangeNotifier { ChatSessionsController(this.repository); ChatRepository repository; List _sessions = const []; String? _error; bool _loading = true; bool _disposed = false; int _generation = 0; List get sessions => _sessions; String? get error => _error; bool get loading => _loading; void replaceRepository(ChatRepository next) { if (identical(next.gateway, repository.gateway)) return; repository = next; refresh(); } Future refresh() async { if (_disposed) return; final generation = ++_generation; _loading = true; _error = null; _notify(); try { final sessions = await repository.sessions(); if (generation != _generation) return; _sessions = sessions; _loading = false; _notify(); } catch (error) { if (generation != _generation) return; _error = '$error'; _loading = false; _notify(); } } Future star(String sessionId, bool starred) => _mutate(() => repository.star(sessionId, starred)); Future close(String sessionId) => _mutate(() => repository.close(sessionId)); Future reopen(String sessionId) => _mutate(() => repository.reopen(sessionId)); Future rename(String sessionId, String title) => _mutate(() => repository.rename(sessionId, title)); Future create({ required String title, required String directory, required String backend, required String instructions, required String operationId, }) async { try { final reply = await repository.create( title: title, directory: directory, backend: backend, operationId: operationId, instructions: instructions, ); // 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()); final session = reply['chat_session']; return session is Map ? Map.from(session) : null; } catch (error) { _error = '$error'; _notify(); return null; } } Future _mutate(Future Function() action) async { try { await action(); await refresh(); } catch (error) { _error = '$error'; _notify(); } } void _notify() { if (!_disposed) notifyListeners(); } @override void dispose() { _disposed = true; _generation++; super.dispose(); } }