refactor: app startup improvements

This commit is contained in:
cogwheel0
2025-09-23 13:43:01 +05:30
parent 8da8a78001
commit f6a1b6123b
10 changed files with 1153 additions and 214 deletions

View File

@@ -396,7 +396,8 @@ class AuthStateManager extends Notifier<AuthState> {
state = state.copyWith(
status: AuthStatus.error,
error: 'Saved server configuration is no longer available. Please reconnect.',
error:
'Saved server configuration is no longer available. Please reconnect.',
isLoading: false,
);
return false;

View File

@@ -197,10 +197,10 @@ final socketServiceProvider = Provider<SocketService?>((ref) {
if (reviewerMode) return null;
final activeServer = ref.watch(activeServerProvider);
final token = ref.watch(authTokenProvider3);
final transportMode = ref
.watch(appSettingsProvider)
.socketTransportMode; // 'auto' or 'ws'
final token = ref.watch(authTokenProvider3.select((t) => t));
final transportMode = ref.watch(
appSettingsProvider.select((s) => s.socketTransportMode),
);
return activeServer.maybeWhen(
data: (server) {
@@ -213,6 +213,10 @@ final socketServiceProvider = Provider<SocketService?>((ref) {
// best-effort connect; errors handled internally
// ignore unawaited_futures
s.connect();
// Keep socket token up-to-date without reconstructing the service
ref.listen<String?>(authTokenProvider3, (prev, next) {
s.updateAuthToken(next);
});
ref.onDispose(() {
try {
s.dispose();
@@ -242,12 +246,12 @@ final attachmentUploadQueueProvider = Provider<AttachmentUploadQueue?>((ref) {
// Auth token integration with API service - using unified auth system
final apiTokenUpdaterProvider = Provider<void>((ref) {
// Listen to unified auth token changes and update API service
ref.listen(authTokenProvider3, (previous, next) {
ref.listen<String?>(authTokenProvider3, (previous, next) {
final api = ref.read(apiServiceProvider);
if (api != null && next != null && next.isNotEmpty) {
api.updateAuthToken(next);
if (api != null) {
api.updateAuthToken(next ?? '');
foundation.debugPrint(
'DEBUG: Updated API service with unified auth token',
'DEBUG: Applied auth token to API (len=${next?.length ?? 0})',
);
}
});

View File

@@ -1,6 +1,7 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../providers/app_providers.dart';
@@ -13,6 +14,7 @@ import '../../features/onboarding/views/onboarding_sheet.dart';
import '../../shared/theme/theme_extensions.dart';
import '../services/connectivity_service.dart';
import '../utils/debug_logger.dart';
import '../models/server_config.dart';
enum _ConversationWarmupStatus { idle, warming, complete }
@@ -56,6 +58,14 @@ void _scheduleConversationWarmup(Ref ref, {bool force = false}) {
return;
}
// If network latency is high, delay warmup further to reduce contention
final latency = ref.read(connectivityServiceProvider).lastLatencyMs;
final extraDelay = latency > 800
? 400
: latency > 400
? 200
: 0;
final statusController = ref.read(_conversationWarmupStatusProvider.notifier);
final status = ref.read(_conversationWarmupStatusProvider);
@@ -80,6 +90,9 @@ void _scheduleConversationWarmup(Ref ref, {bool force = false}) {
statusController.set(_ConversationWarmupStatus.warming);
Future.microtask(() async {
if (extraDelay > 0) {
await Future.delayed(Duration(milliseconds: extraDelay));
}
try {
final existing = ref.read(conversationsProvider);
if (existing.hasValue) {
@@ -109,6 +122,7 @@ final appStartupFlowProvider = Provider<void>((ref) {
// Ensure token integration listeners are active
ref.watch(authApiIntegrationProvider);
ref.watch(apiTokenUpdaterProvider);
ref.watch(silentLoginCoordinatorProvider);
// Kick background model loading flow (non-blocking)
ref.watch(backgroundModelLoadProvider);
@@ -129,8 +143,35 @@ final appStartupFlowProvider = Provider<void>((ref) {
final connectivityService = ref.watch(connectivityServiceProvider);
PersistentStreamingService().attachConnectivityService(connectivityService);
// Warm the conversations list in the background as soon as possible
Future.microtask(() => _scheduleConversationWarmup(ref));
// Warm the conversations list in the background as soon as possible,
// but avoid doing so on poor connectivity to reduce startup load.
// Apply a small randomized delay to smooth load spikes across app wakes.
Future.microtask(() async {
final online = ref.read(isOnlineProvider);
if (!online) return;
final jitter = Duration(
milliseconds: 50 + (DateTime.now().millisecond % 100),
);
await Future.delayed(jitter);
_scheduleConversationWarmup(ref);
});
// One-time, post-frame system UI polish: set status bar icon brightness to
// match theme after the first frame. Avoids flicker at startup.
WidgetsBinding.instance.addPostFrameCallback((_) {
try {
final isDark =
WidgetsBinding.instance.window.platformBrightness == Brightness.dark;
SystemChrome.setSystemUIOverlayStyle(
SystemUiOverlayStyle(
statusBarIconBrightness: isDark ? Brightness.light : Brightness.dark,
systemNavigationBarIconBrightness: isDark
? Brightness.light
: Brightness.dark,
),
);
} catch (_) {}
});
// Watch for auth transitions to trigger warmup and other background work
ref.listen<AuthNavigationState>(authNavigationStateProvider, (prev, next) {
@@ -151,14 +192,23 @@ final appStartupFlowProvider = Provider<void>((ref) {
DebugLogger.auth('StartupFlow: Applied auth token to API');
}
// Preload default model in background (best-effort)
try {
await ref.read(defaultModelProvider.future);
} catch (e) {
DebugLogger.warning(
'StartupFlow: default model preload failed: $e',
);
}
// Preload default model in background (best-effort) with an adaptive
// delay based on network latency to avoid hammering poor networks.
final latency = ref.read(connectivityServiceProvider).lastLatencyMs;
final delayMs = latency < 0
? 300
: latency > 800
? 600
: 200 + (latency ~/ 2);
Future.delayed(Duration(milliseconds: delayMs), () async {
try {
await ref.read(defaultModelProvider.future);
} catch (e) {
DebugLogger.warning(
'StartupFlow: default model preload failed: $e',
);
}
});
// Kick background chat warmup now that we're authenticated
_scheduleConversationWarmup(ref, force: true);
@@ -199,6 +249,66 @@ final appStartupFlowProvider = Provider<void>((ref) {
});
});
// Tracks whether we've already attempted a silent login for the current app session.
final _silentLoginAttemptedProvider =
NotifierProvider<_SilentLoginAttemptedNotifier, bool>(
_SilentLoginAttemptedNotifier.new,
);
class _SilentLoginAttemptedNotifier extends Notifier<bool> {
@override
bool build() => false;
void markAttempted() => state = true;
}
/// Coordinates a one-time silent login attempt when:
/// - There is an active server
/// - The auth navigation state requires login
/// - Saved credentials are present
final silentLoginCoordinatorProvider = Provider<void>((ref) {
Future<void> attempt() async {
final attempted = ref.read(_silentLoginAttemptedProvider);
if (attempted) return;
final authState = ref.read(authNavigationStateProvider);
if (authState != AuthNavigationState.needsLogin) return;
final activeServerAsync = ref.read(activeServerProvider);
final hasActiveServer = activeServerAsync.maybeWhen(
data: (server) => server != null,
orElse: () => false,
);
if (!hasActiveServer) return;
// Perform the attempt in a microtask to avoid side-effects in build
Future.microtask(() async {
try {
final hasCreds = await ref.read(hasSavedCredentialsProvider2.future);
if (hasCreds) {
ref.read(_silentLoginAttemptedProvider.notifier).markAttempted();
await ref.read(authActionsProvider).silentLogin();
}
} catch (_) {
// Ignore silent login errors; app will proceed to manual login
}
});
}
void check() => attempt();
// Initial check
check();
// React to changes in server or auth state
ref.listen<AuthNavigationState>(authNavigationStateProvider, (prev, next) {
check();
});
ref.listen<AsyncValue<ServerConfig?>>(activeServerProvider, (prev, next) {
check();
});
});
/// Listens to app lifecycle and refreshes server state when app returns to foreground.
///
/// Rationale: Socket.IO does not replay historical events. If the app was suspended,

View File

@@ -1,3 +1,4 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
@@ -35,7 +36,16 @@ class RouterNotifier extends ChangeNotifier {
late final List<ProviderSubscription<dynamic>> _subscriptions;
void _onStateChanged(dynamic previous, dynamic next) {
notifyListeners();
// Debounce router refreshes to avoid thrashing on rapid state changes
_scheduleRefresh();
}
Timer? _refreshDebounce;
void _scheduleRefresh() {
_refreshDebounce?.cancel();
_refreshDebounce = Timer(const Duration(milliseconds: 50), () {
notifyListeners();
});
}
String? redirect(BuildContext context, GoRouterState state) {
@@ -44,11 +54,13 @@ class RouterNotifier extends ChangeNotifier {
final activeServerAsync = ref.read(activeServerProvider);
if (reviewerMode) {
// Stay on whatever route if already in chat; otherwise go to chat
if (location == Routes.chat) return null;
return Routes.chat;
}
if (activeServerAsync.isLoading) {
// Avoid redirect loops by keeping splash during server loading
return location == Routes.splash ? null : Routes.splash;
}
@@ -60,6 +72,7 @@ class RouterNotifier extends ChangeNotifier {
final activeServer = activeServerAsync.asData?.value;
if (activeServer == null) {
// Allow auth-related routes while no server configured
if (_isAuthLocation(location)) return null;
return Routes.serverConnection;
}
@@ -67,12 +80,14 @@ class RouterNotifier extends ChangeNotifier {
final authState = ref.read(authNavigationStateProvider);
switch (authState) {
case AuthNavigationState.loading:
// Keep splash while establishing session
return location == Routes.splash ? null : Routes.splash;
case AuthNavigationState.needsLogin:
case AuthNavigationState.error:
if (_isAuthLocation(location)) return null;
return Routes.serverConnection;
case AuthNavigationState.authenticated:
// Avoid unnecessary redirects if already on a non-auth route
if (_isAuthLocation(location) || location == Routes.splash) {
return Routes.chat;
}
@@ -88,6 +103,7 @@ class RouterNotifier extends ChangeNotifier {
@override
void dispose() {
_refreshDebounce?.cancel();
for (final sub in _subscriptions) {
sub.close();
}

View File

@@ -12,6 +12,9 @@ class ConnectivityService {
final _connectivityController =
StreamController<ConnectivityStatus>.broadcast();
ConnectivityStatus _lastStatus = ConnectivityStatus.checking;
int _recentFailures = 0;
Duration _interval = const Duration(seconds: 10);
int _lastLatencyMs = -1;
ConnectivityService(this._dio) {
_startConnectivityMonitoring();
@@ -20,6 +23,7 @@ class ConnectivityService {
Stream<ConnectivityStatus> get connectivityStream =>
_connectivityController.stream;
ConnectivityStatus get currentStatus => _lastStatus;
int get lastLatencyMs => _lastLatencyMs;
/// Stream that emits true when connected, false when offline
Stream<bool> get isConnected =>
@@ -30,12 +34,12 @@ class ConnectivityService {
void _startConnectivityMonitoring() {
// Initial check after a brief delay to avoid showing offline during startup
Timer(const Duration(milliseconds: 1000), () {
Timer(const Duration(milliseconds: 800), () {
_checkConnectivity();
});
// Check periodically; balance responsiveness with battery/network usage
_connectivityTimer = Timer.periodic(const Duration(seconds: 10), (_) {
// Check periodically; interval adapts to recent failures
_connectivityTimer = Timer.periodic(_interval, (_) {
_checkConnectivity();
});
}
@@ -45,7 +49,7 @@ class ConnectivityService {
// DNS lookup is a lightweight, permission-free reachability check
final result = await InternetAddress.lookup(
'google.com',
).timeout(const Duration(seconds: 3));
).timeout(const Duration(seconds: 2));
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
_updateStatus(ConnectivityStatus.online);
@@ -57,20 +61,23 @@ class ConnectivityService {
// As a secondary check, hit a public 204 endpoint that returns quickly
try {
final start = DateTime.now();
await _dio
.get(
'https://www.google.com/generate_204',
options: Options(
method: 'GET',
sendTimeout: const Duration(seconds: 3),
receiveTimeout: const Duration(seconds: 3),
sendTimeout: const Duration(seconds: 2),
receiveTimeout: const Duration(seconds: 2),
followRedirects: false,
validateStatus: (status) => status != null && status < 400,
),
)
.timeout(const Duration(seconds: 3));
.timeout(const Duration(seconds: 2));
_lastLatencyMs = DateTime.now().difference(start).inMilliseconds;
_updateStatus(ConnectivityStatus.online);
} catch (_) {
_lastLatencyMs = -1;
_updateStatus(ConnectivityStatus.offline);
}
}
@@ -80,6 +87,28 @@ class ConnectivityService {
_lastStatus = status;
_connectivityController.add(status);
}
// Adapt polling interval based on recent failures to reduce battery/CPU
if (status == ConnectivityStatus.offline) {
_recentFailures = (_recentFailures + 1).clamp(0, 10);
} else if (status == ConnectivityStatus.online) {
_recentFailures = 0;
}
final newInterval = _recentFailures >= 3
? const Duration(seconds: 20)
: _recentFailures == 2
? const Duration(seconds: 15)
: const Duration(seconds: 10);
if (newInterval != _interval) {
_interval = newInterval;
_connectivityTimer?.cancel();
_connectivityTimer = Timer.periodic(
_interval,
(_) => _checkConnectivity(),
);
}
}
Future<bool> checkConnectivity() async {

View File

@@ -4,18 +4,19 @@ import '../models/server_config.dart';
class SocketService {
final ServerConfig serverConfig;
final String? authToken;
final bool websocketOnly;
io.Socket? _socket;
String? _authToken;
SocketService({
required this.serverConfig,
required this.authToken,
String? authToken,
this.websocketOnly = false,
});
}) : _authToken = authToken;
String? get sessionId => _socket?.id;
io.Socket? get socket => _socket;
String? get authToken => _authToken;
bool get isConnected => _socket?.connected == true;
@@ -39,9 +40,7 @@ class SocketService {
final builder = io.OptionBuilder()
// Transport selection
.setTransports(
websocketOnly ? ['websocket'] : ['polling', 'websocket'],
)
.setTransports(websocketOnly ? ['websocket'] : ['polling', 'websocket'])
.setRememberUpgrade(!websocketOnly)
.setUpgrade(!websocketOnly)
// Tune reconnect/backoff and timeouts
@@ -55,9 +54,9 @@ class SocketService {
// Merge Authorization (if any) with user-defined custom headers for the
// Socket.IO handshake. Avoid overriding reserved headers.
final Map<String, String> extraHeaders = {};
if (authToken != null && authToken!.isNotEmpty) {
extraHeaders['Authorization'] = 'Bearer $authToken';
builder.setAuth({'token': authToken});
if (_authToken != null && _authToken!.isNotEmpty) {
extraHeaders['Authorization'] = 'Bearer $_authToken';
builder.setAuth({'token': _authToken});
}
if (serverConfig.customHeaders.isNotEmpty) {
final reserved = {
@@ -78,7 +77,8 @@ class SocketService {
final lower = key.toLowerCase();
if (!reserved.contains(lower) && value.isNotEmpty) {
// Do not overwrite Authorization we already set from authToken
if (lower == 'authorization' && extraHeaders.containsKey('Authorization')) {
if (lower == 'authorization' &&
extraHeaders.containsKey('Authorization')) {
return;
}
extraHeaders[key] = value;
@@ -93,9 +93,9 @@ class SocketService {
_socket!.on('connect', (_) {
debugPrint('Socket connected: ${_socket!.id}');
if (authToken != null && authToken!.isNotEmpty) {
if (_authToken != null && _authToken!.isNotEmpty) {
_socket!.emit('user-join', {
'auth': {'token': authToken}
'auth': {'token': _authToken},
});
}
});
@@ -110,10 +110,10 @@ class SocketService {
_socket!.on('reconnect', (attempt) {
debugPrint('Socket reconnected after $attempt attempts');
if (authToken != null && authToken!.isNotEmpty) {
if (_authToken != null && _authToken!.isNotEmpty) {
// Best-effort rejoin
_socket!.emit('user-join', {
'auth': {'token': authToken}
'auth': {'token': _authToken},
});
}
});
@@ -127,6 +127,21 @@ class SocketService {
});
}
/// Update the auth token used by the socket service.
/// If connected, emits a best-effort rejoin with the new token.
void updateAuthToken(String? token) {
_authToken = token;
if (_socket?.connected == true &&
_authToken != null &&
_authToken!.isNotEmpty) {
try {
_socket!.emit('user-join', {
'auth': {'token': _authToken},
});
} catch (_) {}
}
}
void onChatEvents(void Function(Map<String, dynamic> event) handler) {
_socket?.on('chat-events', (data) {
try {
@@ -168,6 +183,7 @@ class SocketService {
void offEvent(String eventName) {
_socket?.off(eventName);
}
void dispose() {
try {
_socket?.dispose();
@@ -177,7 +193,9 @@ class SocketService {
// Best-effort: ensure there is an active connection and wait briefly.
// Returns true if connected by the end of the timeout.
Future<bool> ensureConnected({Duration timeout = const Duration(seconds: 2)}) async {
Future<bool> ensureConnected({
Duration timeout = const Duration(seconds: 2),
}) async {
if (isConnected) return true;
try {
await connect();

View File

@@ -0,0 +1,17 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// Applies a single System UI overlay style after first frame to avoid flicker
/// at startup and to align with the active theme brightness.
void applySystemUiOverlayStyleOnce({required Brightness brightness}) {
// On Android 15+, avoid setting bar colors; only control icon brightness.
final isDark = brightness == Brightness.dark;
SystemChrome.setSystemUIOverlayStyle(
SystemUiOverlayStyle(
statusBarIconBrightness: isDark ? Brightness.light : Brightness.dark,
systemNavigationBarIconBrightness: isDark
? Brightness.light
: Brightness.dark,
),
);
}