refactor: app startup improvements
This commit is contained in:
@@ -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;
|
||||
|
||||
@@ -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})',
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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();
|
||||
|
||||
17
lib/core/utils/system_ui_style.dart
Normal file
17
lib/core/utils/system_ui_style.dart
Normal 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,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -10,8 +10,7 @@ class AuthActions {
|
||||
final Ref _ref;
|
||||
AuthActions(this._ref);
|
||||
|
||||
AuthStateManager get _auth =>
|
||||
_ref.read(authStateManagerProvider.notifier);
|
||||
AuthStateManager get _auth => _ref.read(authStateManagerProvider.notifier);
|
||||
|
||||
Future<bool> login(
|
||||
String username,
|
||||
@@ -19,21 +18,25 @@ class AuthActions {
|
||||
bool rememberCredentials = false,
|
||||
}) {
|
||||
// Defer mutation to a microtask to avoid provider-build side-effects
|
||||
return Future(() => _auth.login(
|
||||
username,
|
||||
password,
|
||||
rememberCredentials: rememberCredentials,
|
||||
));
|
||||
return Future(
|
||||
() => _auth.login(
|
||||
username,
|
||||
password,
|
||||
rememberCredentials: rememberCredentials,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<bool> loginWithApiKey(
|
||||
String apiKey, {
|
||||
bool rememberCredentials = false,
|
||||
}) {
|
||||
return Future(() => _auth.loginWithApiKey(
|
||||
apiKey,
|
||||
rememberCredentials: rememberCredentials,
|
||||
));
|
||||
return Future(
|
||||
() => _auth.loginWithApiKey(
|
||||
apiKey,
|
||||
rememberCredentials: rememberCredentials,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<bool> silentLogin() {
|
||||
|
||||
259
lib/main.dart
259
lib/main.dart
@@ -1,3 +1,5 @@
|
||||
import 'dart:async';
|
||||
import 'dart:developer' as developer;
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
@@ -8,48 +10,87 @@ import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'core/providers/app_providers.dart';
|
||||
import 'core/router/app_router.dart';
|
||||
import 'shared/theme/app_theme.dart';
|
||||
import 'shared/theme/theme_extensions.dart';
|
||||
import 'shared/widgets/offline_indicator.dart';
|
||||
import 'features/auth/providers/unified_auth_providers.dart';
|
||||
import 'core/auth/auth_state_manager.dart';
|
||||
import 'core/utils/debug_logger.dart';
|
||||
import 'core/utils/system_ui_style.dart';
|
||||
|
||||
import 'package:conduit/l10n/app_localizations.dart';
|
||||
import 'core/services/share_receiver_service.dart';
|
||||
import 'core/providers/app_startup_providers.dart';
|
||||
import 'core/models/server_config.dart';
|
||||
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
developer.TimelineTask? _startupTimeline;
|
||||
|
||||
// Enable edge-to-edge globally (back-compat on pre-Android 15)
|
||||
// Pairs with Activity's EdgeToEdge.enable and our SafeArea usage.
|
||||
// Do not block first frame on system UI mode; apply shortly after startup
|
||||
// ignore: discarded_futures
|
||||
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
|
||||
void main() {
|
||||
runZonedGuarded(
|
||||
() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
final sharedPrefs = await SharedPreferences.getInstance();
|
||||
const secureStorage = FlutterSecureStorage(
|
||||
aOptions: AndroidOptions(
|
||||
encryptedSharedPreferences: true,
|
||||
sharedPreferencesName: 'conduit_secure_prefs',
|
||||
preferencesKeyPrefix: 'conduit_',
|
||||
resetOnError: false,
|
||||
),
|
||||
iOptions: IOSOptions(
|
||||
accountName: 'conduit_secure_storage',
|
||||
synchronizable: false,
|
||||
),
|
||||
);
|
||||
// Global error handlers
|
||||
FlutterError.onError = (FlutterErrorDetails details) {
|
||||
DebugLogger.error('Flutter error', details.exception);
|
||||
final stack = details.stack;
|
||||
if (stack != null) {
|
||||
debugPrint(stack.toString());
|
||||
}
|
||||
};
|
||||
WidgetsBinding.instance.platformDispatcher.onError = (error, stack) {
|
||||
DebugLogger.error('Uncaught platform error', error);
|
||||
debugPrint(stack.toString());
|
||||
return true;
|
||||
};
|
||||
|
||||
runApp(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
sharedPreferencesProvider.overrideWithValue(sharedPrefs),
|
||||
secureStorageProvider.overrideWithValue(secureStorage),
|
||||
],
|
||||
child: const ConduitApp(),
|
||||
),
|
||||
// Start startup timeline instrumentation
|
||||
_startupTimeline = developer.TimelineTask();
|
||||
_startupTimeline!.start('app_startup');
|
||||
_startupTimeline!.instant('bindings_initialized');
|
||||
|
||||
// Enable edge-to-edge globally (back-compat on pre-Android 15)
|
||||
// Pairs with Activity's EdgeToEdge.enable and our SafeArea usage.
|
||||
// Do not block first frame on system UI mode; apply shortly after startup
|
||||
// ignore: discarded_futures
|
||||
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
|
||||
_startupTimeline!.instant('edge_to_edge_enabled');
|
||||
|
||||
final sharedPrefs = await SharedPreferences.getInstance();
|
||||
_startupTimeline!.instant('shared_prefs_ready');
|
||||
const secureStorage = FlutterSecureStorage(
|
||||
aOptions: AndroidOptions(
|
||||
encryptedSharedPreferences: true,
|
||||
sharedPreferencesName: 'conduit_secure_prefs',
|
||||
preferencesKeyPrefix: 'conduit_',
|
||||
resetOnError: false,
|
||||
),
|
||||
iOptions: IOSOptions(
|
||||
accountName: 'conduit_secure_storage',
|
||||
synchronizable: false,
|
||||
),
|
||||
);
|
||||
_startupTimeline!.instant('secure_storage_ready');
|
||||
|
||||
// Finish timeline after first frame paints
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
_startupTimeline?.instant('first_frame_rendered');
|
||||
_startupTimeline?.finish();
|
||||
_startupTimeline = null;
|
||||
});
|
||||
|
||||
runApp(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
sharedPreferencesProvider.overrideWithValue(sharedPrefs),
|
||||
secureStorageProvider.overrideWithValue(secureStorage),
|
||||
],
|
||||
child: const ConduitApp(),
|
||||
),
|
||||
);
|
||||
developer.Timeline.instantSync('runApp_called');
|
||||
},
|
||||
(error, stack) {
|
||||
DebugLogger.error('Uncaught zone error', error);
|
||||
debugPrint(stack.toString());
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -61,42 +102,19 @@ class ConduitApp extends ConsumerStatefulWidget {
|
||||
}
|
||||
|
||||
class _ConduitAppState extends ConsumerState<ConduitApp> {
|
||||
bool _attemptedSilentAutoLogin = false;
|
||||
ProviderSubscription<AuthNavigationState>? _authNavSubscription;
|
||||
ProviderSubscription<AsyncValue<ServerConfig?>>? _activeServerSubscription;
|
||||
ProviderSubscription<void>? _startupFlowSubscription;
|
||||
Brightness? _lastAppliedOverlayBrightness;
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// Defer heavy provider initialization to after first frame to render UI sooner
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) => _initializeAppState());
|
||||
|
||||
_authNavSubscription = ref.listenManual<AuthNavigationState>(
|
||||
authNavigationStateProvider,
|
||||
(previous, next) {
|
||||
if (next == AuthNavigationState.needsLogin) {
|
||||
_maybeAttemptSilentLogin();
|
||||
} else {
|
||||
_attemptedSilentAutoLogin = false;
|
||||
}
|
||||
},
|
||||
// Activate app startup flow without tying it to root widget rebuilds
|
||||
_startupFlowSubscription = ref.listenManual<void>(
|
||||
appStartupFlowProvider,
|
||||
(previous, next) {},
|
||||
);
|
||||
|
||||
_activeServerSubscription = ref.listenManual<AsyncValue<ServerConfig?>>(
|
||||
activeServerProvider,
|
||||
(previous, next) {
|
||||
next.when(
|
||||
data: (server) {
|
||||
if (server != null) {
|
||||
_maybeAttemptSilentLogin();
|
||||
}
|
||||
},
|
||||
loading: () {},
|
||||
error: (error, stackTrace) {},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
Future.microtask(_maybeAttemptSilentLogin);
|
||||
}
|
||||
|
||||
void _initializeAppState() {
|
||||
@@ -110,98 +128,59 @@ class _ConduitAppState extends ConsumerState<ConduitApp> {
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_authNavSubscription?.close();
|
||||
_activeServerSubscription?.close();
|
||||
_startupFlowSubscription?.close();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _maybeAttemptSilentLogin() {
|
||||
if (_attemptedSilentAutoLogin) 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;
|
||||
}
|
||||
|
||||
_attemptedSilentAutoLogin = true;
|
||||
|
||||
Future.microtask(() async {
|
||||
try {
|
||||
final hasCreds = await ref.read(hasSavedCredentialsProvider2.future);
|
||||
if (hasCreds) {
|
||||
await ref.read(authActionsProvider).silentLogin();
|
||||
}
|
||||
} catch (_) {
|
||||
// Ignore silent login errors; fall back to manual login.
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final themeMode = ref.watch(themeModeProvider.select((mode) => mode));
|
||||
final router = ref.watch(goRouterProvider);
|
||||
ref.watch(appStartupFlowProvider);
|
||||
|
||||
final currentTheme = themeMode == ThemeMode.dark
|
||||
? AppTheme.conduitDarkTheme
|
||||
: themeMode == ThemeMode.light
|
||||
? AppTheme.conduitLightTheme
|
||||
: MediaQuery.platformBrightnessOf(context) == Brightness.dark
|
||||
? AppTheme.conduitDarkTheme
|
||||
: AppTheme.conduitLightTheme;
|
||||
|
||||
final locale = ref.watch(localeProvider);
|
||||
|
||||
return AnimatedThemeWrapper(
|
||||
theme: currentTheme,
|
||||
duration: AnimationDuration.medium,
|
||||
child: ErrorBoundary(
|
||||
child: MaterialApp.router(
|
||||
routerConfig: router,
|
||||
onGenerateTitle: (context) => AppLocalizations.of(context)!.appTitle,
|
||||
theme: AppTheme.conduitLightTheme,
|
||||
darkTheme: AppTheme.conduitDarkTheme,
|
||||
themeMode: themeMode,
|
||||
debugShowCheckedModeBanner: false,
|
||||
locale: locale,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
localeListResolutionCallback: (deviceLocales, supported) {
|
||||
if (locale != null) return locale;
|
||||
if (deviceLocales == null || deviceLocales.isEmpty) {
|
||||
return supported.first;
|
||||
}
|
||||
for (final device in deviceLocales) {
|
||||
for (final loc in supported) {
|
||||
if (loc.languageCode == device.languageCode) return loc;
|
||||
}
|
||||
}
|
||||
return ErrorBoundary(
|
||||
child: MaterialApp.router(
|
||||
routerConfig: router,
|
||||
onGenerateTitle: (context) => AppLocalizations.of(context)!.appTitle,
|
||||
theme: AppTheme.conduitLightTheme,
|
||||
darkTheme: AppTheme.conduitDarkTheme,
|
||||
themeMode: themeMode,
|
||||
debugShowCheckedModeBanner: false,
|
||||
locale: locale,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
localeListResolutionCallback: (deviceLocales, supported) {
|
||||
if (locale != null) return locale;
|
||||
if (deviceLocales == null || deviceLocales.isEmpty) {
|
||||
return supported.first;
|
||||
},
|
||||
builder: (context, child) {
|
||||
final mediaQuery = MediaQuery.of(context);
|
||||
return MediaQuery(
|
||||
data: mediaQuery.copyWith(
|
||||
textScaler: mediaQuery.textScaler.clamp(
|
||||
minScaleFactor: 1.0,
|
||||
maxScaleFactor: 3.0,
|
||||
),
|
||||
}
|
||||
for (final device in deviceLocales) {
|
||||
for (final loc in supported) {
|
||||
if (loc.languageCode == device.languageCode) return loc;
|
||||
}
|
||||
}
|
||||
return supported.first;
|
||||
},
|
||||
builder: (context, child) {
|
||||
final brightness = Theme.of(context).brightness;
|
||||
if (_lastAppliedOverlayBrightness != brightness) {
|
||||
_lastAppliedOverlayBrightness = brightness;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
applySystemUiOverlayStyleOnce(brightness: brightness);
|
||||
});
|
||||
}
|
||||
final mediaQuery = MediaQuery.of(context);
|
||||
return MediaQuery(
|
||||
data: mediaQuery.copyWith(
|
||||
textScaler: mediaQuery.textScaler.clamp(
|
||||
minScaleFactor: 1.0,
|
||||
maxScaleFactor: 3.0,
|
||||
),
|
||||
child: OfflineIndicator(child: child ?? const SizedBox.shrink()),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
child: OfflineIndicator(child: child ?? const SizedBox.shrink()),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user