import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:shared_preferences/shared_preferences.dart'; const chatAutoContinuePreferenceKey = 'pipelines.chatAutoContinue.v1'; /// The usage-limit banner's "Auto-continue when limits reset" choice: one /// preference for every chat, on by default, kept in shared preferences so a /// reload remembers it. class ChatAutoContinue extends ChangeNotifier { ChatAutoContinue({this.preferences}); /// The instance chats use unless a test hands them their own. static final ChatAutoContinue shared = ChatAutoContinue( preferences: SharedPreferences.getInstance, ); /// Where the choice is kept; null keeps it in memory. final Future Function()? preferences; bool _enabled = true; bool _loaded = false; Future? _loading; bool get enabled => _enabled; /// Whether the stored choice has been read, so nothing is scheduled on the /// default before an operator's "off" is known. bool get loaded => _loaded; /// Reads the stored choice once. Future load() => _loading ??= _read(); Future _read() async { final preferences = this.preferences; try { if (preferences != null) { final stored = (await preferences()).getBool( chatAutoContinuePreferenceKey, ); // A choice made while reading wins. if (stored != null && !_loaded) _enabled = stored; } } on Object catch (error) { // Without storage the default holds for this app session. debugPrint('Auto-continue: could not read preferences: $error'); } _loaded = true; notifyListeners(); } /// Records the operator's choice. Future set(bool enabled) async { _loaded = true; if (enabled == _enabled) return; _enabled = enabled; notifyListeners(); final preferences = this.preferences; if (preferences == null) return; try { await (await preferences()).setBool( chatAutoContinuePreferenceKey, enabled, ); } on Object catch (error) { debugPrint('Auto-continue: could not save preferences: $error'); } } }