Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
22.0 KB
Raw Blame
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../models/chat.dart';
import '../models/message.dart';
import '../services/chat_service.dart';
import '../services/log_service.dart';

class ChatProvider with ChangeNotifier {
  ChatProvider({ChatService? chatService})
      : _chatService = chatService ?? ChatService(),
        _ownsChatService = chatService == null;

  final ChatService _chatService;

  /// Whether this provider created [_chatService] itself. An injected service
  /// is owned by the caller and must not be closed on dispose.
  final bool _ownsChatService;
  final LogService _log = LogService.instance;

  List<Chat> _chats = [];
  Chat? _currentChat;
  bool _isLoading = false;
  bool _isSendingMessage = false;
  bool _isWaitingForResponse = false;
  String? _errorMessage;
  Timer? _pollingTimer;
  DateTime? _pollingStartTime;
  bool _isPollingRequestInFlight = false;

  static const _pollingTimeout = Duration(seconds: 20);

  /// Content length of the last assistant message from the previous poll.
  /// Used to detect when the LLM has finished writing (no growth between polls).
  int? _lastAssistantContentLength;

  /// Number of consecutive polls with no content growth.
  /// Requires 2 consecutive stable polls before declaring the response complete,
  /// to avoid prematurely stopping on a brief server-side generation pause.
  int _stablePollingCount = 0;

  /// Ids deleted while a chat-list fetch was awaiting later pages; null when
  /// no fetch is running. Lets the fetch drop chats the user removed meanwhile
  /// instead of restoring them from a stale page.
  final List<Set<String>> _deletedDuringChatListFetches = [];

  List<Chat> get chats => _chats;
  Chat? get currentChat => _currentChat;
  bool get isLoading => _isLoading;
  bool get isSendingMessage => _isSendingMessage;
  bool get isWaitingForResponse => _isWaitingForResponse;
  bool get isPolling => _pollingTimer != null;
  String? get errorMessage => _errorMessage;

  /// True when the current chat could not load all of its message pages, so the
  /// rendered history is a partial, older slice. The UI can surface a
  /// "load more"/retry affordance without treating it as a hard error.
  bool _hasIncompleteHistory = false;
  bool get hasIncompleteHistory => _hasIncompleteHistory;

  /// True when the chat list on screen may be missing chats: a later page
  /// failed to load, or the server reported more pages than we follow. The
  /// UI can offer a retry without treating it as a hard error.
  bool _hasIncompleteChatList = false;
  bool get hasIncompleteChatList => _hasIncompleteChatList;

  /// Fetch list of chats
  Future<void> fetchChats({
    required String accessToken,
    int page = 1,
    int perPage = 25,
  }) async {
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();
    final deletedDuringFetch = <String>{};
    _deletedDuringChatListFetches.add(deletedDuringFetch);

    try {
      final result = await _chatService.getChats(
        accessToken: accessToken,
        page: page,
        perPage: perPage,
      );

      if (result['success'] == true) {
        final loaded = await _loadRemainingChatPages(
          accessToken: accessToken,
          perPage: perPage,
          page: page,
          firstPage: result,
        );
        _hasIncompleteChatList = !loaded.complete;
        // A failed later page returns null chats: keep the list already on
        // screen rather than replacing it with a truncated one.
        if (loaded.chats != null) {
          final deleted = deletedDuringFetch;
          _chats = deleted.isEmpty
              ? loaded.chats!
              : loaded.chats!.where((c) => !deleted.contains(c.id)).toList();
        }
        _errorMessage = null;
      } else {
        _errorMessage = result['error'] ?? 'Failed to fetch chats';
      }
    } catch (e) {
      _log.warning('ChatProvider', 'fetchChats failed: ${e.runtimeType}');
      _errorMessage = 'Something went wrong. Please try again.';
    } finally {
      _deletedDuringChatListFetches.remove(deletedDuringFetch);
      _isLoading = false;
      notifyListeners();
    }
  }

  /// Upper bound on chat-list pages followed in one refresh, so a bogus
  /// `total_pages` from the server cannot trigger an unbounded request loop.
  static const _maxChatListPages = 100;

  /// Fetches the pages after [firstPage] (the response for [page]) of the chat
  /// list and returns all chats. The API paginates `/chats`, so without this
  /// only the first page would ever be shown. If a later page fails, returns
  /// the pages loaded so far when nothing is shown yet, and null chats otherwise
  /// so the caller keeps the list it already has. `complete` is false when a
  /// page failed or the page cap truncated the list.
  Future<({List<Chat>? chats, bool complete})> _loadRemainingChatPages({
    required String accessToken,
    required int perPage,
    required int page,
    required Map<String, dynamic> firstPage,
  }) async {
    final chats = <Chat>[...(firstPage['chats'] as List<Chat>)];
    final pagination = firstPage['pagination'] as Map<String, dynamic>?;
    final totalPages = (pagination?['total_pages'] as int?) ?? 1;
    final lastPage = totalPages < _maxChatListPages ? totalPages : _maxChatListPages;
    final seen = chats.map((c) => c.id).toSet();

    for (var next = page + 1; next <= lastPage; next++) {
      final pageResult = await _chatService.getChats(
        accessToken: accessToken,
        page: next,
        perPage: perPage,
      );

      if (pageResult['success'] != true) {
        _log.warning('ChatProvider', 'fetchChats page $next failed; stopping');
        return (chats: _chats.isEmpty ? chats : null, complete: false);
      }
      for (final chat in pageResult['chats'] as List<Chat>) {
        if (seen.add(chat.id)) chats.add(chat);
      }
    }

    return (chats: chats, complete: totalPages <= lastPage);
  }

  /// Fetch a specific chat with messages
  Future<void> fetchChat({
    required String accessToken,
    required String chatId,
  }) async {
    // Stop any in-progress polling — the server response is the source of truth
    // when explicitly fetching a chat. This prevents a stale poll from
    // overwriting the freshly fetched data and ensures the message filter lifts.
    _stopPolling();
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    try {
      final result = await _chatService.getChat(
        accessToken: accessToken,
        chatId: chatId,
      );

      if (result['success'] == true) {
        final loaded = await _loadRemainingPages(
          accessToken: accessToken,
          chatId: chatId,
          firstPage: result,
        );
        _currentChat = loaded.chat;
        _hasIncompleteHistory = !loaded.complete;
        _errorMessage = null;
      } else {
        _errorMessage = result['error'] ?? 'Failed to fetch chat';
      }
    } catch (e) {
      _log.warning('ChatProvider', 'fetchChat failed: ${e.runtimeType}');
      _errorMessage = 'Something went wrong. Please try again.';
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// Fetches every remaining page of a chat's messages and merges them into a
  /// single Chat. The API orders messages oldest-first and paginates them, so
  /// [firstPage] only holds the oldest slice — without this, newer messages are
  /// silently dropped once a conversation exceeds one page.
  ///
  /// Pages are appended in ascending order to preserve chronology, and messages
  /// are de-duped by id so an overlapping or locally-injected message can't
  /// render twice.
  ///
  /// Returns the merged chat along with [complete], which is false when one or
  /// more later pages failed to load so callers can flag a partial history.
  Future<({Chat chat, bool complete})> _loadRemainingPages({
    required String accessToken,
    required String chatId,
    required Map<String, dynamic> firstPage,
  }) async {
    final chat = firstPage['chat'] as Chat;
    final pagination = firstPage['pagination'] as Map<String, dynamic>?;
    final totalPages = (pagination?['total_pages'] as int?) ?? 1;

    if (totalPages <= 1) return (chat: chat, complete: true);

    final allMessages = <Message>[...chat.messages];
    var complete = true;

    for (var page = 2; page <= totalPages; page++) {
      final pageResult = await _chatService.getChat(
        accessToken: accessToken,
        chatId: chatId,
        page: page,
      );

      if (pageResult['success'] == true) {
        allMessages.addAll((pageResult['chat'] as Chat).messages);
      } else {
        // Partial failure: keep the pages we have rather than losing the chat
        // entirely. The user sees a truncated-but-chronological history, and
        // [complete] lets callers surface that it's incomplete.
        _log.warning('ChatProvider', 'fetchChat page $page failed; stopping');
        complete = false;
        break;
      }
    }

    return (chat: chat.copyWith(messages: _dedupeById(allMessages)), complete: complete);
  }

  /// Returns the messages with duplicate ids removed, preserving first-seen order.
  List<Message> _dedupeById(List<Message> messages) {
    final seen = <String>{};
    final deduped = <Message>[];
    for (final message in messages) {
      if (seen.add(message.id)) deduped.add(message);
    }
    return deduped;
  }

  /// Create a new chat
  Future<Chat?> createChat({
    required String accessToken,
    String? title,
    String? initialMessage,
  }) async {
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    try {
      final result = await _chatService.createChat(
        accessToken: accessToken,
        title: title,
        initialMessage: initialMessage,
      );

      if (result['success'] == true) {
        final chat = result['chat'] as Chat;
        _errorMessage = null;

        if (initialMessage != null) {
          // Inject the user message locally so the UI renders it immediately
          // without waiting for the first poll.
          final now = DateTime.now();
          final userMessage = Message(
            id: 'pending_${now.millisecondsSinceEpoch}',
            type: 'text',
            role: 'user',
            content: initialMessage,
            createdAt: now,
            updatedAt: now,
          );
          _currentChat = chat.copyWith(messages: [userMessage]);
          _chats.insert(0, _currentChat!);
          _startPolling(accessToken, chat.id);
        } else {
          _currentChat = chat;
          _chats.insert(0, chat);
        }

        _isLoading = false;
        notifyListeners();
        return _currentChat!;
      } else {
        _errorMessage = result['error'] ?? 'Failed to create chat';
        _isLoading = false;
        notifyListeners();
        return null;
      }
    } catch (e) {
      _log.warning('ChatProvider', 'createChat failed: ${e.runtimeType}');
      _errorMessage = 'Something went wrong. Please try again.';
      _isLoading = false;
      notifyListeners();
      return null;
    }
  }

  void _rollbackOptimisticMessage(String optimisticId, String chatId) {
    if (_currentChat != null && _currentChat!.id == chatId) {
      _currentChat = _currentChat!.copyWith(
        messages:
            _currentChat!.messages.where((m) => m.id != optimisticId).toList(),
      );
    }
    _isWaitingForResponse = false;
  }

  /// Send a message to the current chat.
  /// Returns true if delivery succeeded, false otherwise.
  Future<bool> sendMessage({
    required String accessToken,
    required String chatId,
    required String content,
  }) async {
    _isSendingMessage = true;
    _errorMessage = null;

    // Optimistically add the user message so it appears immediately — before
    // the network round-trip completes. This makes the empty-state disappear
    // and the typing indicator show at the same instant.
    final now = DateTime.now();
    final optimisticId = 'pending-${now.millisecondsSinceEpoch}';
    final optimisticMessage = Message(
      id: optimisticId,
      type: 'text',
      role: 'user',
      content: content,
      createdAt: now,
      updatedAt: now,
    );
    if (_currentChat != null && _currentChat!.id == chatId) {
      _currentChat = _currentChat!.copyWith(
        messages: [..._currentChat!.messages, optimisticMessage],
      );
    }
    _isWaitingForResponse = true;
    notifyListeners();

    try {
      final result = await _chatService.sendMessage(
        accessToken: accessToken,
        chatId: chatId,
        content: content,
      );

      if (result['success'] == true) {
        final message = result['message'] as Message;

        // Replace the optimistic message with the confirmed one from the server.
        if (_currentChat != null && _currentChat!.id == chatId) {
          final updated = _currentChat!.messages
              .where((m) => m.id != optimisticMessage.id)
              .toList()
            ..add(message);
          _currentChat = _currentChat!.copyWith(messages: updated);
        }

        _errorMessage = null;

        // Start polling for AI response
        _startPolling(accessToken, chatId);
        return true;
      } else {
        // Roll back the optimistic message on failure.
        _rollbackOptimisticMessage(optimisticId, chatId);
        _errorMessage = result['error'] ?? 'Failed to send message';
        return false;
      }
    } catch (e) {
      // Roll back the optimistic message on error.
      _rollbackOptimisticMessage(optimisticId, chatId);
      _log.warning('ChatProvider', 'sendMessage failed: ${e.runtimeType}');
      _errorMessage = 'Something went wrong. Please try again.';
      return false;
    } finally {
      _isSendingMessage = false;
      notifyListeners();
    }
  }

  /// Update chat title
  Future<void> updateChatTitle({
    required String accessToken,
    required String chatId,
    required String title,
  }) async {
    try {
      final result = await _chatService.updateChat(
        accessToken: accessToken,
        chatId: chatId,
        title: title,
      );

      if (result['success'] == true) {
        final updatedChat = result['chat'] as Chat;

        // Update in the list
        final index = _chats.indexWhere((c) => c.id == chatId);
        if (index != -1) {
          _chats[index] = updatedChat;
        }

        // Update current chat if it's the same.
        // Preserve existing messages — the title-update response may omit them.
        if (_currentChat != null && _currentChat!.id == chatId) {
          final Chat newChat;
          if (updatedChat.messages.isEmpty) {
            newChat = updatedChat.copyWith(messages: _currentChat!.messages);
          } else {
            newChat = updatedChat;
          }
          _currentChat = newChat;
        }

        notifyListeners();
      }
    } catch (e) {
      _log.warning('ChatProvider', 'updateChatTitle failed: ${e.runtimeType}');
      _errorMessage = 'Something went wrong. Please try again.';
      notifyListeners();
    }
  }

  /// Delete a chat
  Future<bool> deleteChat({
    required String accessToken,
    required String chatId,
  }) async {
    try {
      final result = await _chatService.deleteChat(
        accessToken: accessToken,
        chatId: chatId,
      );

      if (result['success'] == true) {
        _chats.removeWhere((c) => c.id == chatId);
        for (final s in _deletedDuringChatListFetches) {
          s.add(chatId);
        }

        if (_currentChat != null && _currentChat!.id == chatId) {
          _currentChat = null;
        }

        notifyListeners();
        return true;
      } else {
        _errorMessage = result['error'] ?? 'Failed to delete chat';
        notifyListeners();
        return false;
      }
    } catch (e) {
      _log.warning('ChatProvider', 'deleteChat failed: ${e.runtimeType}');
      _errorMessage = 'Something went wrong. Please try again.';
      notifyListeners();
      return false;
    }
  }

  /// Delete multiple chats
  Future<bool> deleteMultipleChats({
    required String accessToken,
    required List<String> chatIds,
  }) async {
    try {
      final result = await _chatService.deleteMultipleChats(
        accessToken: accessToken,
        chatIds: chatIds,
      );

      final deletedCount = (result['deletedCount'] as int?) ?? 0;
      if (result['success'] == true || deletedCount > 0) {
        final failedIds =
            ((result['failedIds'] as List?) ?? []).cast<String>().toSet();
        final deleted = chatIds.toSet().difference(failedIds);
        _chats.removeWhere((c) => deleted.contains(c.id));
        for (final s in _deletedDuringChatListFetches) {
          s.addAll(deleted);
        }

        if (_currentChat != null && deleted.contains(_currentChat!.id)) {
          _currentChat = null;
        }

        notifyListeners();
        return true;
      }

      _errorMessage = 'Failed to delete chats';
      notifyListeners();
      return false;
    } catch (e) {
      _log.warning(
        'ChatProvider',
        'deleteMultipleChats failed: ${e.runtimeType}',
      );
      _errorMessage = 'Something went wrong. Please try again.';
      notifyListeners();
      return false;
    }
  }

  /// Start polling for new messages (AI responses)
  void _startPolling(String accessToken, String chatId) {
    _pollingTimer?.cancel();
    _lastAssistantContentLength = null;
    _stablePollingCount = 0;
    _isWaitingForResponse = true;
    _pollingStartTime = DateTime.now();
    notifyListeners();

    _pollingTimer = Timer.periodic(const Duration(seconds: 2), (timer) async {
      if (_isPollingRequestInFlight) return;
      _isPollingRequestInFlight = true;
      try {
        await _pollForUpdates(accessToken, chatId);
      } finally {
        _isPollingRequestInFlight = false;
      }
    });
  }

  /// Stop polling
  void _stopPolling() {
    _pollingTimer?.cancel();
    _pollingTimer = null;
    _pollingStartTime = null;
    _isPollingRequestInFlight = false;
    _isWaitingForResponse = false;
    _lastAssistantContentLength = null;
    _stablePollingCount = 0;
  }

  /// Poll for updates
  Future<void> _pollForUpdates(String accessToken, String chatId) async {
    try {
      final result = await _chatService.getChat(
        accessToken: accessToken,
        chatId: chatId,
      );

      if (result['success'] == true) {
        // Load every page before comparing. A long chat spans multiple server
        // pages, and the newest assistant reply lands on the last page — so a
        // page-1-only poll would never see it and its count/stability checks
        // would compare against a stale slice of the full history.
        final loaded = await _loadRemainingPages(
          accessToken: accessToken,
          chatId: chatId,
          firstPage: result,
        );
        final updatedChat = loaded.chat;
        _hasIncompleteHistory = !loaded.complete;

        if (_currentChat == null || _currentChat!.id != chatId) return;

        final oldMessages = _currentChat!.messages;
        final newMessages = updatedChat.messages;
        final oldMessageCount = oldMessages.length;
        final newMessageCount = newMessages.length;

        final oldContentLengthById = <String, int>{};
        for (final m in oldMessages) {
          if (m.isAssistant) oldContentLengthById[m.id] = m.content.length;
        }

        bool shouldUpdate = false;

        // New messages added
        if (newMessageCount > oldMessageCount) {
          shouldUpdate = true;
          _lastAssistantContentLength = null;
        } else if (newMessageCount == oldMessageCount) {
          // Same count: check if any assistant message has more content
          for (final m in newMessages) {
            if (m.isAssistant) {
              final oldLen = oldContentLengthById[m.id] ?? 0;
              if (m.content.length > oldLen) {
                shouldUpdate = true;
                break;
              }
            }
          }
        }

        if (shouldUpdate) {
          _currentChat = updatedChat;
          notifyListeners();
        }

        if (updatedChat.error != null && updatedChat.error!.isNotEmpty) {
          if (!shouldUpdate) {
            _currentChat = updatedChat;
          }
          _stopPolling();
          _errorMessage = updatedChat.error;
          notifyListeners();
          return;
        }

        final lastMessage = updatedChat.messages.lastOrNull;
        if (lastMessage != null && lastMessage.isAssistant) {
          final newLen = lastMessage.content.length;
          final previousLen = _lastAssistantContentLength;

          if (newLen > (previousLen ?? -1)) {
            _lastAssistantContentLength = newLen;
            _stablePollingCount = 0;
            if (newLen > 0) {
              // Content is growing — reset the inactivity clock.
              _pollingStartTime = DateTime.now();
              return; // progress made, don't evaluate timeout this tick
            }
            // newLen == 0: empty placeholder, keep polling
          } else if (newLen > 0) {
            // Content stable and non-empty.
            // Require 2 consecutive stable polls before declaring done, to avoid
            // stopping prematurely on a brief server-side generation pause.
            _stablePollingCount++;
            if (_stablePollingCount >= 2) {
              _stopPolling();
              _lastAssistantContentLength = null;
              notifyListeners();
              return;
            }
          }
          // newLen == 0 with previousLen already 0: still empty, keep polling
        }
      }
    } catch (e) {
      // Network error — allow polling to continue; timeout check below will
      // stop it if the deadline has passed.
      _log.warning('ChatProvider', 'Polling failed: ${e.runtimeType}');
    }

    // Evaluate timeout only after the attempt, and only when no progress was made.
    if (_pollingStartTime != null &&
        DateTime.now().difference(_pollingStartTime!) >= _pollingTimeout) {
      _stopPolling();
      _errorMessage =
          'The assistant took too long to respond. Please try again.';
      notifyListeners();
    }
  }

  /// Clear current chat
  void clearCurrentChat() {
    _currentChat = null;
    _stopPolling();
    notifyListeners();
  }

  @override
  void dispose() {
    _stopPolling();
    if (_ownsChatService) _chatService.close();
    super.dispose();
  }
}