import 'dart:async'; import 'package:cutdex_agent/cutdex_agent.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import '../../integrations/agent/agent_settings.dart'; import '../../integrations/agent/conversation_repository.dart'; import 'agent_conversation_service.dart'; import 'chat_state.dart'; part 'chat_controller.g.dart'; /// Presentation state for one project conversation. @riverpod class ChatController extends _$ChatController { late AgentConversationService _conversation; AgentConversationService? _activeConversation; int _sendRevision = 0; @override ChatState build( String projectId, { String? conversationId, String? draftKey, }) { _conversation = ref.watch( agentConversationServiceProvider( projectId, draftKey ?? conversationId ?? 'new', conversationId, ), ); final subscription = _conversation.changes.listen((_) { if (!ref.mounted) return; state = state.copyWith( busy: _conversation.busy, partialResponse: _conversation.partialResponse, activity: _conversation.activity, ); if (!_conversation.busy && _activeConversation == null) { unawaited(_restore(force: true)); } }); ref.onDispose(subscription.cancel); unawaited(Future.microtask(_restore)); return ChatState( busy: _conversation.busy, partialResponse: _conversation.partialResponse, activity: _conversation.activity, ); } List _messages(List messages) => [ for (final message in messages) ChatMessage( text: message.text, isUser: message.isUser, elapsedMs: message.elapsedMs, ), ]; Future _restore({bool force = false}) async { if ((_sendRevision != 0 && !force) || !ref.mounted) return; final revision = _sendRevision; try { final history = await _conversation.restore(); if (!ref.mounted || revision != _sendRevision) return; state = state.copyWith( messages: history == null ? state.messages : _messages(history.messages), conversation: _conversation.metadata, error: history?.exportReplyFailed == true ? AgentChatError.exportReplyFailed : history?.recoveryRequired == true ? AgentChatError.recoveryRequired : history?.resumeAvailable == true ? AgentChatError.interrupted : null, ); } on AgentConversationException catch (error) { if (ref.mounted && revision == _sendRevision) { state = state.copyWith( error: error.failure == AgentConversationFailure.configurationRead ? AgentChatError.configurationReadFailed : AgentChatError.sessionRestoreFailed, ); } } catch (_) { if (ref.mounted && revision == _sendRevision) { state = state.copyWith(error: AgentChatError.sessionRestoreFailed); } } } Future selectModel(String providerId, String modelId) async { if (state.busy) return; final previous = state.conversation; await ref .read(agentSettingsProvider.notifier) .selectModel(providerId, modelId); if (!ref.mounted) return; if ((previous != null && (previous.providerId != providerId || previous.modelId != modelId)) || (previous == null && conversationId != null)) { _sendRevision++; _conversation.startNewConversation(); state = const ChatState(); } } Future send( String input, { required String timelineId, bool summaryOnly = false, bool resumeOnly = false, void Function(ConversationMetadata value)? onCreated, void Function(ConversationMetadata value)? onUpdated, }) async { final text = input.trim(); if (text.isEmpty || state.busy) return; _sendRevision++; state = state.copyWith( messages: [ ...state.messages, if (!resumeOnly) ChatMessage(text: text, isUser: true), ], partialResponse: '', busy: true, stopping: false, error: null, ); final conversation = _conversation; _activeConversation = conversation; var streamed = ''; try { final outcome = await conversation.send( text, timelineId: timelineId, summaryOnly: summaryOnly, resumeOnly: resumeOnly, onCreated: (item) { if (ref.mounted) state = state.copyWith(conversation: item); onCreated?.call(item); }, onPrepared: (preparation) { if (!ref.mounted || !preparation.sessionChanged) return; state = state.copyWith( messages: [ ..._messages(preparation.messages), if (!resumeOnly) ChatMessage(text: text, isUser: true), ], ); }, onTextDelta: (delta) { streamed += delta; if (ref.mounted) { state = state.copyWith( partialResponse: state.partialResponse + delta, ); } }, ); if (outcome.conversation case final item?) { if (ref.mounted) state = state.copyWith(conversation: item); onUpdated?.call(item); } if (outcome.recoveryRequired) { final history = await conversation.restore(); if (ref.mounted && history != null) { state = state.copyWith(messages: _messages(history.messages)); } } if (!ref.mounted) return; final response = outcome.completed && outcome.response.isNotEmpty ? outcome.response : streamed; state = state.copyWith( messages: [ ...state.messages, if (response.isNotEmpty) ChatMessage( text: response, interrupted: !outcome.completed, elapsedMs: outcome.elapsedMs, ), ], partialResponse: '', error: outcome.exportReplyFailed ? AgentChatError.exportReplyFailed : outcome.recoveryRequired ? AgentChatError.recoveryRequired : outcome.paused ? AgentChatError.turnLimit : outcome.failed ? switch (outcome.failure) { RunFailure.contextBudget => AgentChatError.contextBudget, RunFailure.authentication => AgentChatError.authentication, RunFailure.connection => AgentChatError.connection, RunFailure.protocol => AgentChatError.protocol, _ => AgentChatError.replyFailed, } : null, ); } on AgentConversationException catch (error) { if (ref.mounted) { state = state.copyWith( messages: [ ...state.messages, if (streamed.isNotEmpty) ChatMessage(text: streamed, interrupted: true), ], partialResponse: '', error: switch (error.failure) { AgentConversationFailure.configurationRead => AgentChatError.configurationReadFailed, AgentConversationFailure.notConfigured => AgentChatError.configurationRequired, AgentConversationFailure.contextBudget => AgentChatError.contextBudget, AgentConversationFailure.authentication => AgentChatError.authentication, AgentConversationFailure.connection => AgentChatError.connection, AgentConversationFailure.protocol => AgentChatError.protocol, AgentConversationFailure.request => AgentChatError.requestFailed, }, ); } } catch (_) { if (ref.mounted) { state = state.copyWith( partialResponse: '', error: AgentChatError.requestFailed, ); } } finally { if (identical(_activeConversation, conversation)) { _activeConversation = null; } if (ref.mounted) { state = state.copyWith(busy: false, stopping: false); } } } Future stop() async { if (!state.busy) return; state = state.copyWith(stopping: true); final conversation = _activeConversation ?? _conversation; await conversation.cancel(); } }