Files
iiEsaywebUIapp/lib/main.dart

302 lines
11 KiB
Dart
Raw Normal View History

2025-08-10 01:20:45 +05:30
import 'package:flutter/material.dart';
2025-08-28 20:18:24 +05:30
import 'package:flutter/services.dart';
2025-08-10 01:20:45 +05:30
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'core/services/navigation_service.dart';
import 'core/widgets/error_boundary.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'core/providers/app_providers.dart';
import 'shared/theme/app_theme.dart';
import 'shared/theme/theme_extensions.dart';
import 'shared/widgets/offline_indicator.dart';
import 'features/auth/views/connect_signin_page.dart';
import 'features/auth/providers/unified_auth_providers.dart';
import 'core/auth/auth_state_manager.dart';
2025-08-20 22:15:26 +05:30
import 'core/utils/debug_logger.dart';
import 'package:conduit/l10n/app_localizations.dart';
2025-08-10 01:20:45 +05:30
import 'features/chat/views/chat_page.dart';
import 'features/navigation/views/splash_launcher_page.dart';
import 'core/services/share_receiver_service.dart';
2025-09-02 21:19:07 +05:30
import 'core/providers/app_startup_providers.dart';
2025-08-10 01:20:45 +05:30
void main() async {
WidgetsFlutterBinding.ensureInitialized();
2025-08-28 20:18:24 +05:30
// Enable edge-to-edge globally (back-compat on pre-Android 15)
// Pairs with Activity's EdgeToEdge.enable and our SafeArea usage.
2025-09-16 20:10:53 +05:30
// Do not block first frame on system UI mode; apply shortly after startup
// ignore: discarded_futures
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
2025-08-28 20:18:24 +05:30
2025-08-10 01:20:45 +05:30
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,
),
);
2025-08-10 01:20:45 +05:30
runApp(
ProviderScope(
overrides: [
sharedPreferencesProvider.overrideWithValue(sharedPrefs),
secureStorageProvider.overrideWithValue(secureStorage),
],
child: const ConduitApp(),
),
);
}
class ConduitApp extends ConsumerStatefulWidget {
const ConduitApp({super.key});
@override
ConsumerState<ConduitApp> createState() => _ConduitAppState();
}
class _ConduitAppState extends ConsumerState<ConduitApp> {
bool _attemptedSilentAutoLogin = false;
@override
void initState() {
super.initState();
2025-09-16 20:10:53 +05:30
// Defer heavy provider initialization to after first frame to render UI sooner
WidgetsBinding.instance.addPostFrameCallback((_) => _initializeAppState());
2025-08-10 01:20:45 +05:30
}
Widget _buildInitialLoadingSkeleton(BuildContext context) {
// Replace skeleton with branded splash during initialization
return const SplashLauncherPage();
}
void _initializeAppState() {
// Initialize unified auth state manager and API integration synchronously
// This ensures auth state is loaded before first widget build
2025-08-20 22:15:26 +05:30
DebugLogger.auth('Initializing unified auth system');
2025-08-10 01:20:45 +05:30
// Initialize auth state manager (will handle token validation automatically)
ref.read(authStateManagerProvider);
// Ensure API service auth integration is active
ref.read(authApiIntegrationProvider);
2025-08-28 19:17:05 +05:30
// Initialize auto-selection listener for default model changes in settings
ref.read(defaultModelAutoSelectionProvider);
// Initialize OS share receiver so users can share text/files to Conduit
ref.read(shareReceiverInitializerProvider);
2025-08-10 01:20:45 +05:30
}
@override
Widget build(BuildContext context) {
// Use select to watch only the specific themeMode property to reduce rebuilds
final themeMode = ref.watch(themeModeProvider.select((mode) => mode));
// Reduced debug noise - only log when necessary
// debugPrint('DEBUG: Building app');
// Determine the current theme based on themeMode
// Default to Conduit brand theme globally
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);
2025-08-10 01:20:45 +05:30
return AnimatedThemeWrapper(
theme: currentTheme,
duration: AnimationDuration.medium,
child: ErrorBoundary(
child: MaterialApp(
onGenerateTitle: (context) => AppLocalizations.of(context)!.appTitle,
2025-08-10 01:20:45 +05:30
theme: AppTheme.conduitLightTheme,
darkTheme: AppTheme.conduitDarkTheme,
themeMode: themeMode,
debugShowCheckedModeBanner: false,
navigatorKey: NavigationService.navigatorKey,
locale: locale,
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
localeListResolutionCallback: (deviceLocales, supported) {
if (locale != null) return locale; // User override wins
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 supported.first;
},
2025-08-10 01:20:45 +05:30
builder: (context, child) {
2025-08-25 11:16:09 +05:30
// Apply edge-to-edge inset handling and responsive design
return MediaQuery(
data: MediaQuery.of(context).copyWith(
// Ensure proper text scaling for edge-to-edge
2025-09-16 20:10:53 +05:30
textScaler: MediaQuery.of(
context,
).textScaler.clamp(minScaleFactor: 0.8, maxScaleFactor: 1.3),
2025-08-25 11:16:09 +05:30
),
2025-09-16 20:10:53 +05:30
child: OfflineIndicator(child: child ?? const SizedBox.shrink()),
2025-08-10 01:20:45 +05:30
);
},
home: _getInitialPageWithReactiveState(),
onGenerateRoute: NavigationService.generateRoute,
navigatorObservers: [_NavigationObserver()],
),
),
);
}
Widget _getInitialPageWithReactiveState() {
return Consumer(
builder: (context, ref, child) {
// Watch for server connection state changes
final activeServerAsync = ref.watch(activeServerProvider);
final reviewerMode = ref.watch(reviewerModeProvider);
if (reviewerMode) {
// In reviewer mode, skip server/auth flows and go to chat
NavigationService.setCurrentRoute(Routes.chat);
return const ChatPage();
}
return activeServerAsync.when(
data: (activeServer) {
if (activeServer == null) {
return const ConnectAndSignInPage();
}
// Server is connected, now check authentication reactively
final authNavState = ref.watch(authNavigationStateProvider);
if (authNavState == AuthNavigationState.needsLogin) {
// Try one-shot silent login if credentials are saved
if (!_attemptedSilentAutoLogin) {
_attemptedSilentAutoLogin = true;
Future.microtask(() async {
try {
final hasCreds = await ref.read(
hasSavedCredentialsProvider2.future,
);
if (hasCreds) {
2025-08-29 12:58:56 +05:30
await ref.read(authActionsProvider).silentLogin();
2025-08-10 01:20:45 +05:30
}
} catch (_) {
// Ignore errors, fallback to showing unified page
}
});
}
return const ConnectAndSignInPage();
}
if (authNavState == AuthNavigationState.loading) {
return _buildInitialLoadingSkeleton(context);
}
if (authNavState == AuthNavigationState.error) {
return _buildErrorState(
ref.watch(authErrorProvider3) ??
AppLocalizations.of(context)!.errorMessage,
2025-08-10 01:20:45 +05:30
);
}
// User is authenticated, navigate directly to chat page
2025-09-02 21:19:07 +05:30
// Kick off and keep app startup/background task flow alive
ref.watch(appStartupFlowProvider);
2025-08-10 01:20:45 +05:30
// Set the current route for navigation tracking
NavigationService.setCurrentRoute(Routes.chat);
return const ChatPage();
},
loading: () => _buildInitialLoadingSkeleton(context),
error: (error, stackTrace) {
2025-08-20 22:15:26 +05:30
DebugLogger.error('Server provider error', error);
return _buildErrorState(
AppLocalizations.of(context)!.unableToConnectServer,
);
2025-08-10 01:20:45 +05:30
},
);
},
);
}
2025-09-02 21:19:07 +05:30
// Background initialization moved to app-based task flow provider
2025-08-10 01:20:45 +05:30
Widget _buildErrorState(String error) {
return Scaffold(
backgroundColor: context.conduitTheme.surfaceBackground,
body: Center(
child: Padding(
padding: const EdgeInsets.all(Spacing.lg),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.error_outline,
size: IconSize.xxl + Spacing.md,
color: context.conduitTheme.error,
),
const SizedBox(height: Spacing.md),
Text(
AppLocalizations.of(context)!.initializationFailed,
2025-08-10 01:20:45 +05:30
style: TextStyle(
fontSize: AppTypography.headlineLarge,
fontWeight: FontWeight.bold,
color: context.conduitTheme.textPrimary,
),
),
const SizedBox(height: Spacing.sm),
Text(
error,
style: TextStyle(color: context.conduitTheme.textSecondary),
textAlign: TextAlign.center,
),
const SizedBox(height: Spacing.lg),
ElevatedButton(
onPressed: () {
// Restart the app
WidgetsBinding.instance.reassembleApplication();
},
style: ElevatedButton.styleFrom(
backgroundColor: context.conduitTheme.buttonPrimary,
foregroundColor: context.conduitTheme.buttonPrimaryText,
),
child: Text(AppLocalizations.of(context)!.retry),
2025-08-10 01:20:45 +05:30
),
],
),
),
),
);
}
}
class _NavigationObserver extends NavigatorObserver {
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
super.didPush(route, previousRoute);
// Log navigation for debugging and analytics
2025-08-20 22:15:26 +05:30
DebugLogger.navigation('Pushed: ${route.settings.name}');
2025-08-10 01:20:45 +05:30
}
@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
super.didPop(route, previousRoute);
2025-08-20 22:15:26 +05:30
DebugLogger.navigation('Popped: ${route.settings.name}');
2025-08-10 01:20:45 +05:30
}
}