Next refactors
Some checks failed
Build Linux App / build (push) Failing after 1m18s

This commit is contained in:
Kazimierz Ciołek
2026-02-24 02:19:28 +01:00
parent 0c9eb8878d
commit 9dcc4b87de
40 changed files with 3515 additions and 2575 deletions

View File

@@ -5,56 +5,28 @@ import 'package:dio/dio.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:trainhub_flutter/core/constants/ai_constants.dart';
import 'package:trainhub_flutter/data/services/ai_process_manager.dart';
import 'package:trainhub_flutter/injection.dart' as di;
import 'package:trainhub_flutter/presentation/settings/ai_model_settings_state.dart';
part 'ai_model_settings_controller.g.dart';
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const _llamaBuild = 'b8130';
const _nomicModelFile = 'nomic-embed-text-v1.5.Q4_K_M.gguf';
const _qwenModelFile = 'qwen2.5-7b-instruct-q4_k_m.gguf';
const _nomicModelUrl =
'https://huggingface.co/nomic-ai/nomic-embed-text-v1.5-GGUF/resolve/main/nomic-embed-text-v1.5.Q4_K_M.gguf';
const _qwenModelUrl =
'https://huggingface.co/Qwen/Qwen2.5-7B-Instruct-GGUF/resolve/main/qwen2.5-7b-instruct-q4_k_m.gguf';
// ---------------------------------------------------------------------------
// Platform helpers
// ---------------------------------------------------------------------------
/// Returns the llama.cpp archive download URL for the current platform.
/// Throws [UnsupportedError] if the platform is not supported.
Future<String> _llamaArchiveUrl() async {
final build = AiConstants.llamaBuild;
if (Platform.isMacOS) {
// Detect CPU architecture via `uname -m`
final result = await Process.run('uname', ['-m']);
final arch = (result.stdout as String).trim();
if (arch == 'arm64') {
return 'https://github.com/ggml-org/llama.cpp/releases/download/$_llamaBuild/llama-$_llamaBuild-bin-macos-arm64.tar.gz';
} else {
return 'https://github.com/ggml-org/llama.cpp/releases/download/$_llamaBuild/llama-$_llamaBuild-bin-macos-x64.tar.gz';
}
final suffix = arch == 'arm64' ? 'macos-arm64' : 'macos-x64';
return 'https://github.com/ggml-org/llama.cpp/releases/download/$build/llama-$build-bin-$suffix.tar.gz';
} else if (Platform.isWindows) {
return 'https://github.com/ggml-org/llama.cpp/releases/download/$_llamaBuild/llama-$_llamaBuild-bin-win-vulkan-x64.zip';
return 'https://github.com/ggml-org/llama.cpp/releases/download/$build/llama-$build-bin-win-vulkan-x64.zip';
} else if (Platform.isLinux) {
return 'https://github.com/ggml-org/llama.cpp/releases/download/$_llamaBuild/llama-$_llamaBuild-bin-ubuntu-vulkan-x64.tar.gz';
return 'https://github.com/ggml-org/llama.cpp/releases/download/$build/llama-$build-bin-ubuntu-vulkan-x64.tar.gz';
}
throw UnsupportedError('Unsupported platform: ${Platform.operatingSystem}');
}
/// The expected llama-server binary name for the current platform.
String get _serverBinaryName =>
Platform.isWindows ? 'llama-server.exe' : 'llama-server';
// ---------------------------------------------------------------------------
// Controller
// ---------------------------------------------------------------------------
@riverpod
class AiModelSettingsController extends _$AiModelSettingsController {
final _dio = Dio();
@@ -62,30 +34,21 @@ class AiModelSettingsController extends _$AiModelSettingsController {
@override
AiModelSettingsState build() => const AiModelSettingsState();
// -------------------------------------------------------------------------
// Validation
// -------------------------------------------------------------------------
/// Checks whether all required files exist on disk and updates
/// [AiModelSettingsState.areModelsValidated].
Future<void> validateModels() async {
state = state.copyWith(
currentTask: 'Checking installed files…',
errorMessage: null,
);
try {
final dir = await getApplicationDocumentsDirectory();
final base = dir.path;
final serverBin = File(p.join(base, _serverBinaryName));
final nomicModel = File(p.join(base, _nomicModelFile));
final qwenModel = File(p.join(base, _qwenModelFile));
final validated = serverBin.existsSync() &&
final serverBin = File(p.join(base, AiConstants.serverBinaryName));
final nomicModel = File(p.join(base, AiConstants.nomicModelFile));
final qwenModel = File(p.join(base, AiConstants.qwenModelFile));
final validated =
serverBin.existsSync() &&
nomicModel.existsSync() &&
qwenModel.existsSync();
state = state.copyWith(
areModelsValidated: validated,
currentTask: validated ? 'All files present.' : 'Files missing.',
@@ -99,29 +62,22 @@ class AiModelSettingsController extends _$AiModelSettingsController {
}
}
// -------------------------------------------------------------------------
// Download & Install
// -------------------------------------------------------------------------
/// Downloads and installs the llama.cpp binary and both model files.
Future<void> downloadAll() async {
if (state.isDownloading) return;
try {
await di.getIt<AiProcessManager>().stopServers();
} catch (_) {}
state = state.copyWith(
isDownloading: true,
progress: 0.0,
areModelsValidated: false,
errorMessage: null,
);
try {
final dir = await getApplicationDocumentsDirectory();
// -- 1. llama.cpp binary -----------------------------------------------
final archiveUrl = await _llamaArchiveUrl();
final archiveExt = archiveUrl.endsWith('.zip') ? '.zip' : '.tar.gz';
final archivePath = p.join(dir.path, 'llama_binary$archiveExt');
await _downloadFile(
url: archiveUrl,
savePath: archivePath,
@@ -129,41 +85,32 @@ class AiModelSettingsController extends _$AiModelSettingsController {
overallStart: 0.0,
overallEnd: 0.2,
);
state = state.copyWith(
currentTask: 'Extracting llama.cpp binary…',
progress: 0.2,
);
await _extractBinary(archivePath, dir.path);
// Clean up the archive once extracted
final archiveFile = File(archivePath);
if (archiveFile.existsSync()) archiveFile.deleteSync();
// -- 2. Nomic embedding model ------------------------------------------
await _downloadFile(
url: _nomicModelUrl,
savePath: p.join(dir.path, _nomicModelFile),
url: AiConstants.nomicModelUrl,
savePath: p.join(dir.path, AiConstants.nomicModelFile),
taskLabel: 'Downloading Nomic embedding model…',
overallStart: 0.2,
overallEnd: 0.55,
);
// -- 3. Qwen chat model ------------------------------------------------
await _downloadFile(
url: _qwenModelUrl,
savePath: p.join(dir.path, _qwenModelFile),
url: AiConstants.qwenModelUrl,
savePath: p.join(dir.path, AiConstants.qwenModelFile),
taskLabel: 'Downloading Qwen 2.5 7B model…',
overallStart: 0.55,
overallEnd: 1.0,
);
state = state.copyWith(
isDownloading: false,
progress: 1.0,
currentTask: 'Download complete.',
);
await validateModels();
} on DioException catch (e) {
state = state.copyWith(
@@ -180,11 +127,6 @@ class AiModelSettingsController extends _$AiModelSettingsController {
}
}
// -------------------------------------------------------------------------
// Private helpers
// -------------------------------------------------------------------------
/// Downloads a single file with progress mapped into [overallStart]..[overallEnd].
Future<void> _downloadFile({
required String url,
required String savePath,
@@ -193,7 +135,6 @@ class AiModelSettingsController extends _$AiModelSettingsController {
required double overallEnd,
}) async {
state = state.copyWith(currentTask: taskLabel, progress: overallStart);
await _dio.download(
url,
savePath,
@@ -212,52 +153,62 @@ class AiModelSettingsController extends _$AiModelSettingsController {
);
}
/// Extracts the downloaded archive and moves `llama-server[.exe]` to [destDir].
Future<void> _extractBinary(String archivePath, String destDir) async {
final extractDir = p.join(destDir, '_llama_extract_tmp');
final extractDirObj = Directory(extractDir);
if (extractDirObj.existsSync()) extractDirObj.deleteSync(recursive: true);
extractDirObj.createSync(recursive: true);
try {
if (archivePath.endsWith('.zip')) {
await extractFileToDisk(archivePath, extractDir);
} else {
// .tar.gz — use extractFileToDisk which handles both via the archive package
await extractFileToDisk(archivePath, extractDir);
await extractFileToDisk(archivePath, extractDir);
bool foundServer = false;
final binaryName = AiConstants.serverBinaryName;
for (final entity in extractDirObj.listSync(recursive: true)) {
if (entity is File) {
final ext = p.extension(entity.path).toLowerCase();
final name = p.basename(entity.path);
if (name == binaryName ||
ext == '.dll' ||
ext == '.so' ||
ext == '.dylib') {
final destFile = p.join(destDir, name);
int retryCount = 0;
bool success = false;
while (!success && retryCount < 5) {
try {
if (File(destFile).existsSync()) {
File(destFile).deleteSync();
}
entity.copySync(destFile);
success = true;
} on FileSystemException catch (_) {
if (retryCount >= 4) {
throw Exception(
'Failed to overwrite $name. Ensure no other applications are using it.',
);
}
await Future.delayed(const Duration(milliseconds: 500));
retryCount++;
}
}
if (name == binaryName) {
foundServer = true;
if (Platform.isMacOS || Platform.isLinux) {
await Process.run('chmod', ['+x', destFile]);
}
}
}
}
}
// Walk the extracted tree to find the server binary
final binary = _findFile(extractDirObj, _serverBinaryName);
if (binary == null) {
if (!foundServer) {
throw FileSystemException(
'llama-server binary not found in archive.',
archivePath,
);
}
final destBin = p.join(destDir, _serverBinaryName);
binary.copySync(destBin);
// Make executable on POSIX systems
if (Platform.isMacOS || Platform.isLinux) {
await Process.run('chmod', ['+x', destBin]);
}
} finally {
// Always clean up the temp extraction directory
if (extractDirObj.existsSync()) {
extractDirObj.deleteSync(recursive: true);
}
}
}
/// Recursively searches [dir] for a file named [name].
File? _findFile(Directory dir, String name) {
for (final entity in dir.listSync(recursive: true)) {
if (entity is File && p.basename(entity.path) == name) {
return entity;
}
}
return null;
}
}

View File

@@ -7,7 +7,7 @@ part of 'ai_model_settings_controller.dart';
// **************************************************************************
String _$aiModelSettingsControllerHash() =>
r'5bf80e85e734016b0fa80c6bb84315925f2595b3';
r'27a37c3fafb21b93a8b5523718f1537419bd382a';
/// See also [AiModelSettingsController].
@ProviderFor(AiModelSettingsController)

View File

@@ -3,10 +3,12 @@ import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:trainhub_flutter/core/constants/ui_constants.dart';
import 'package:trainhub_flutter/core/theme/app_colors.dart';
import 'package:trainhub_flutter/core/router/app_router.dart';
import 'package:trainhub_flutter/core/theme/app_colors.dart';
import 'package:trainhub_flutter/presentation/settings/ai_model_settings_controller.dart';
import 'package:trainhub_flutter/presentation/settings/ai_model_settings_state.dart';
import 'package:trainhub_flutter/presentation/settings/widgets/ai_models_section.dart';
import 'package:trainhub_flutter/presentation/settings/widgets/knowledge_base_section.dart';
import 'package:trainhub_flutter/presentation/settings/widgets/settings_top_bar.dart';
@RoutePage()
class SettingsPage extends ConsumerWidget {
@@ -15,17 +17,13 @@ class SettingsPage extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final modelState = ref.watch(aiModelSettingsControllerProvider);
final controller =
ref.read(aiModelSettingsControllerProvider.notifier);
final controller = ref.read(aiModelSettingsControllerProvider.notifier);
return Scaffold(
backgroundColor: AppColors.surface,
body: Column(
children: [
// ── Top bar ──────────────────────────────────────────────────────
_TopBar(onBack: () => context.router.maybePop()),
// ── Scrollable content ──────────────────────────────────────────
SettingsTopBar(onBack: () => context.router.maybePop()),
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.all(UIConstants.pagePadding),
@@ -35,7 +33,6 @@ class SettingsPage extends ConsumerWidget {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Page title
Text(
'Settings',
style: GoogleFonts.inter(
@@ -46,20 +43,15 @@ class SettingsPage extends ConsumerWidget {
),
),
const SizedBox(height: UIConstants.spacing32),
// AI Models section
_AiModelsSection(
AiModelsSection(
modelState: modelState,
onDownload: controller.downloadAll,
onValidate: controller.validateModels,
),
const SizedBox(height: UIConstants.spacing32),
// Knowledge Base section
_KnowledgeBaseSection(
onTap: () => context.router
.push(const KnowledgeBaseRoute()),
KnowledgeBaseSection(
onTap: () =>
context.router.push(const KnowledgeBaseRoute()),
),
],
),
@@ -72,626 +64,3 @@ class SettingsPage extends ConsumerWidget {
);
}
}
// =============================================================================
// Top bar
// =============================================================================
class _TopBar extends StatelessWidget {
const _TopBar({required this.onBack});
final VoidCallback onBack;
@override
Widget build(BuildContext context) {
return Container(
height: 52,
padding: const EdgeInsets.symmetric(horizontal: UIConstants.spacing16),
decoration: const BoxDecoration(
color: AppColors.surfaceContainer,
border: Border(bottom: BorderSide(color: AppColors.border)),
),
child: Row(
children: [
_IconBtn(
icon: Icons.arrow_back_rounded,
tooltip: 'Go back',
onTap: onBack,
),
const SizedBox(width: UIConstants.spacing12),
Text(
'Settings',
style: GoogleFonts.inter(
fontSize: 14,
fontWeight: FontWeight.w600,
color: AppColors.textPrimary,
),
),
],
),
);
}
}
// =============================================================================
// AI Models section
// =============================================================================
class _AiModelsSection extends StatelessWidget {
const _AiModelsSection({
required this.modelState,
required this.onDownload,
required this.onValidate,
});
final AiModelSettingsState modelState;
final VoidCallback onDownload;
final VoidCallback onValidate;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Section heading
Text(
'AI Models',
style: GoogleFonts.inter(
fontSize: 13,
fontWeight: FontWeight.w600,
color: AppColors.textMuted,
letterSpacing: 0.8,
),
),
const SizedBox(height: UIConstants.spacing12),
// Card
Container(
decoration: BoxDecoration(
color: AppColors.surfaceContainer,
borderRadius: BorderRadius.circular(UIConstants.borderRadius),
border: Border.all(color: AppColors.border),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Status rows
const _ModelRow(
name: 'llama-server binary',
description: 'llama.cpp inference server (build b8130)',
icon: Icons.terminal_rounded,
),
const Divider(height: 1, color: AppColors.border),
const _ModelRow(
name: 'Nomic Embed v1.5 Q4_K_M',
description: 'Text embedding model (~300 MB)',
icon: Icons.hub_outlined,
),
const Divider(height: 1, color: AppColors.border),
const _ModelRow(
name: 'Qwen 2.5 7B Instruct Q4_K_M',
description: 'Chat / reasoning model (~4.7 GB)',
icon: Icons.psychology_outlined,
),
// Divider before status / actions
const Divider(height: 1, color: AppColors.border),
Padding(
padding: const EdgeInsets.all(UIConstants.spacing16),
child: _StatusAndActions(
modelState: modelState,
onDownload: onDownload,
onValidate: onValidate,
),
),
],
),
),
],
);
}
}
// =============================================================================
// Single model info row
// =============================================================================
class _ModelRow extends StatelessWidget {
const _ModelRow({
required this.name,
required this.description,
required this.icon,
});
final String name;
final String description;
final IconData icon;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: UIConstants.spacing16,
vertical: UIConstants.spacing12,
),
child: Row(
children: [
Container(
width: 36,
height: 36,
decoration: BoxDecoration(
color: AppColors.surfaceContainerHigh,
borderRadius: BorderRadius.circular(8),
),
child: Icon(icon, size: 16, color: AppColors.textSecondary),
),
const SizedBox(width: UIConstants.spacing12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
name,
style: GoogleFonts.inter(
fontSize: 13,
fontWeight: FontWeight.w500,
color: AppColors.textPrimary,
),
),
const SizedBox(height: 2),
Text(
description,
style: GoogleFonts.inter(
fontSize: 12,
color: AppColors.textMuted,
),
),
],
),
),
],
),
);
}
}
// =============================================================================
// Status badge + action buttons
// =============================================================================
class _StatusAndActions extends StatelessWidget {
const _StatusAndActions({
required this.modelState,
required this.onDownload,
required this.onValidate,
});
final AiModelSettingsState modelState;
final VoidCallback onDownload;
final VoidCallback onValidate;
@override
Widget build(BuildContext context) {
// While downloading, show progress UI
if (modelState.isDownloading) {
return _DownloadingView(modelState: modelState);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Status badge
_StatusBadge(validated: modelState.areModelsValidated),
if (modelState.errorMessage != null) ...[
const SizedBox(height: UIConstants.spacing12),
_ErrorRow(message: modelState.errorMessage!),
],
const SizedBox(height: UIConstants.spacing16),
// Action buttons
if (!modelState.areModelsValidated)
_ActionButton(
label: 'Download AI Models (~5 GB)',
icon: Icons.download_rounded,
color: AppColors.accent,
textColor: AppColors.zinc950,
onPressed: onDownload,
)
else
_ActionButton(
label: 'Re-validate Files',
icon: Icons.verified_outlined,
color: Colors.transparent,
textColor: AppColors.textSecondary,
borderColor: AppColors.border,
onPressed: onValidate,
),
],
);
}
}
class _StatusBadge extends StatelessWidget {
const _StatusBadge({required this.validated});
final bool validated;
@override
Widget build(BuildContext context) {
final color = validated ? AppColors.success : AppColors.textMuted;
final bgColor =
validated ? AppColors.successMuted : AppColors.surfaceContainerHigh;
final label = validated ? 'Ready' : 'Missing';
final icon =
validated ? Icons.check_circle_outline : Icons.radio_button_unchecked;
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Status: ',
style: GoogleFonts.inter(
fontSize: 13,
color: AppColors.textSecondary,
),
),
const SizedBox(width: UIConstants.spacing4),
Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
decoration: BoxDecoration(
color: bgColor,
borderRadius: BorderRadius.circular(20),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 13, color: color),
const SizedBox(width: 5),
Text(
label,
style: GoogleFonts.inter(
fontSize: 12,
fontWeight: FontWeight.w600,
color: color,
),
),
],
),
),
],
);
}
}
class _DownloadingView extends StatelessWidget {
const _DownloadingView({required this.modelState});
final AiModelSettingsState modelState;
@override
Widget build(BuildContext context) {
final pct = (modelState.progress * 100).toStringAsFixed(1);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
modelState.currentTask,
style: GoogleFonts.inter(
fontSize: 13,
color: AppColors.textSecondary,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
Text(
'$pct %',
style: GoogleFonts.inter(
fontSize: 13,
fontWeight: FontWeight.w600,
color: AppColors.accent,
),
),
],
),
const SizedBox(height: UIConstants.spacing8),
ClipRRect(
borderRadius: BorderRadius.circular(4),
child: LinearProgressIndicator(
value: modelState.progress,
minHeight: 6,
backgroundColor: AppColors.zinc800,
valueColor:
const AlwaysStoppedAnimation<Color>(AppColors.accent),
),
),
if (modelState.errorMessage != null) ...[
const SizedBox(height: UIConstants.spacing12),
_ErrorRow(message: modelState.errorMessage!),
],
],
);
}
}
class _ErrorRow extends StatelessWidget {
const _ErrorRow({required this.message});
final String message;
@override
Widget build(BuildContext context) {
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(
Icons.error_outline_rounded,
color: AppColors.destructive,
size: 14,
),
const SizedBox(width: UIConstants.spacing8),
Expanded(
child: Text(
message,
style: GoogleFonts.inter(
fontSize: 12,
color: AppColors.destructive,
height: 1.4,
),
),
),
],
);
}
}
class _ActionButton extends StatefulWidget {
const _ActionButton({
required this.label,
required this.icon,
required this.color,
required this.textColor,
required this.onPressed,
this.borderColor,
});
final String label;
final IconData icon;
final Color color;
final Color textColor;
final Color? borderColor;
final VoidCallback onPressed;
@override
State<_ActionButton> createState() => _ActionButtonState();
}
class _ActionButtonState extends State<_ActionButton> {
bool _hovered = false;
@override
Widget build(BuildContext context) {
final hasBorder = widget.borderColor != null;
return MouseRegion(
onEnter: (_) => setState(() => _hovered = true),
onExit: (_) => setState(() => _hovered = false),
child: AnimatedContainer(
duration: UIConstants.animationDuration,
height: 40,
decoration: BoxDecoration(
color: hasBorder
? (_hovered ? AppColors.zinc800 : Colors.transparent)
: (_hovered
? widget.color.withValues(alpha: 0.85)
: widget.color),
borderRadius: BorderRadius.circular(UIConstants.smallBorderRadius),
border: hasBorder
? Border.all(color: widget.borderColor!)
: null,
),
child: Material(
color: Colors.transparent,
child: InkWell(
borderRadius:
BorderRadius.circular(UIConstants.smallBorderRadius),
onTap: widget.onPressed,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: UIConstants.spacing16,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(widget.icon, size: 16, color: widget.textColor),
const SizedBox(width: UIConstants.spacing8),
Text(
widget.label,
style: GoogleFonts.inter(
fontSize: 13,
fontWeight: FontWeight.w600,
color: widget.textColor,
),
),
],
),
),
),
),
),
);
}
}
// =============================================================================
// Generic icon button
// =============================================================================
class _IconBtn extends StatefulWidget {
const _IconBtn({
required this.icon,
required this.onTap,
this.tooltip = '',
});
final IconData icon;
final VoidCallback onTap;
final String tooltip;
@override
State<_IconBtn> createState() => _IconBtnState();
}
class _IconBtnState extends State<_IconBtn> {
bool _hovered = false;
@override
Widget build(BuildContext context) {
return Tooltip(
message: widget.tooltip,
child: MouseRegion(
onEnter: (_) => setState(() => _hovered = true),
onExit: (_) => setState(() => _hovered = false),
child: GestureDetector(
onTap: widget.onTap,
child: AnimatedContainer(
duration: UIConstants.animationDuration,
width: 32,
height: 32,
decoration: BoxDecoration(
color: _hovered ? AppColors.zinc800 : Colors.transparent,
borderRadius: BorderRadius.circular(6),
),
child: Icon(
widget.icon,
size: 18,
color:
_hovered ? AppColors.textPrimary : AppColors.textSecondary,
),
),
),
),
);
}
}
// =============================================================================
// Knowledge Base navigation section
// =============================================================================
class _KnowledgeBaseSection extends StatelessWidget {
const _KnowledgeBaseSection({required this.onTap});
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Knowledge Base',
style: GoogleFonts.inter(
fontSize: 13,
fontWeight: FontWeight.w600,
color: AppColors.textMuted,
letterSpacing: 0.8,
),
),
const SizedBox(height: UIConstants.spacing12),
_KnowledgeBaseCard(onTap: onTap),
],
);
}
}
class _KnowledgeBaseCard extends StatefulWidget {
const _KnowledgeBaseCard({required this.onTap});
final VoidCallback onTap;
@override
State<_KnowledgeBaseCard> createState() => _KnowledgeBaseCardState();
}
class _KnowledgeBaseCardState extends State<_KnowledgeBaseCard> {
bool _hovered = false;
@override
Widget build(BuildContext context) {
return MouseRegion(
onEnter: (_) => setState(() => _hovered = true),
onExit: (_) => setState(() => _hovered = false),
child: GestureDetector(
onTap: widget.onTap,
child: AnimatedContainer(
duration: UIConstants.animationDuration,
decoration: BoxDecoration(
color: _hovered
? AppColors.surfaceContainerHigh
: AppColors.surfaceContainer,
borderRadius: BorderRadius.circular(UIConstants.borderRadius),
border: Border.all(
color: _hovered
? AppColors.accent.withValues(alpha: 0.3)
: AppColors.border,
),
),
padding: const EdgeInsets.symmetric(
horizontal: UIConstants.spacing16,
vertical: UIConstants.spacing16,
),
child: Row(
children: [
Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: AppColors.accentMuted,
borderRadius: BorderRadius.circular(10),
),
child: const Icon(
Icons.hub_outlined,
color: AppColors.accent,
size: 20,
),
),
const SizedBox(width: UIConstants.spacing16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Manage Knowledge Base',
style: GoogleFonts.inter(
fontSize: 14,
fontWeight: FontWeight.w500,
color: AppColors.textPrimary,
),
),
const SizedBox(height: 3),
Text(
'Add trainer notes to give the AI context-aware answers.',
style: GoogleFonts.inter(
fontSize: 12,
color: AppColors.textMuted,
),
),
],
),
),
Icon(
Icons.chevron_right_rounded,
color:
_hovered ? AppColors.accent : AppColors.textMuted,
size: 20,
),
],
),
),
),
);
}
}

View File

@@ -0,0 +1,322 @@
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:trainhub_flutter/core/constants/ui_constants.dart';
import 'package:trainhub_flutter/core/theme/app_colors.dart';
import 'package:trainhub_flutter/presentation/settings/ai_model_settings_state.dart';
import 'package:trainhub_flutter/presentation/settings/widgets/settings_action_button.dart';
class AiModelsSection extends StatelessWidget {
const AiModelsSection({
super.key,
required this.modelState,
required this.onDownload,
required this.onValidate,
});
final AiModelSettingsState modelState;
final VoidCallback onDownload;
final VoidCallback onValidate;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'AI Models',
style: GoogleFonts.inter(
fontSize: 13,
fontWeight: FontWeight.w600,
color: AppColors.textMuted,
letterSpacing: 0.8,
),
),
const SizedBox(height: UIConstants.spacing12),
Container(
decoration: BoxDecoration(
color: AppColors.surfaceContainer,
borderRadius: BorderRadius.circular(UIConstants.borderRadius),
border: Border.all(color: AppColors.border),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const _ModelRow(
name: 'llama-server binary',
description: 'llama.cpp inference server (build b8130)',
icon: Icons.terminal_rounded,
),
const Divider(height: 1, color: AppColors.border),
const _ModelRow(
name: 'Nomic Embed v1.5 Q4_K_M',
description: 'Text embedding model (~300 MB)',
icon: Icons.hub_outlined,
),
const Divider(height: 1, color: AppColors.border),
const _ModelRow(
name: 'Qwen 2.5 7B Instruct Q4_K_M',
description: 'Chat / reasoning model (~4.7 GB)',
icon: Icons.psychology_outlined,
),
const Divider(height: 1, color: AppColors.border),
Padding(
padding: const EdgeInsets.all(UIConstants.spacing16),
child: _StatusAndActions(
modelState: modelState,
onDownload: onDownload,
onValidate: onValidate,
),
),
],
),
),
],
);
}
}
class _ModelRow extends StatelessWidget {
const _ModelRow({
required this.name,
required this.description,
required this.icon,
});
final String name;
final String description;
final IconData icon;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: UIConstants.spacing16,
vertical: UIConstants.spacing12,
),
child: Row(
children: [
Container(
width: 36,
height: 36,
decoration: BoxDecoration(
color: AppColors.surfaceContainerHigh,
borderRadius: BorderRadius.circular(8),
),
child: Icon(icon, size: 16, color: AppColors.textSecondary),
),
const SizedBox(width: UIConstants.spacing12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
name,
style: GoogleFonts.inter(
fontSize: 13,
fontWeight: FontWeight.w500,
color: AppColors.textPrimary,
),
),
const SizedBox(height: 2),
Text(
description,
style: GoogleFonts.inter(
fontSize: 12,
color: AppColors.textMuted,
),
),
],
),
),
],
),
);
}
}
class _StatusAndActions extends StatelessWidget {
const _StatusAndActions({
required this.modelState,
required this.onDownload,
required this.onValidate,
});
final AiModelSettingsState modelState;
final VoidCallback onDownload;
final VoidCallback onValidate;
@override
Widget build(BuildContext context) {
if (modelState.isDownloading) {
return _DownloadingView(modelState: modelState);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_StatusBadge(validated: modelState.areModelsValidated),
if (modelState.errorMessage != null) ...[
const SizedBox(height: UIConstants.spacing12),
ErrorRow(message: modelState.errorMessage!),
],
const SizedBox(height: UIConstants.spacing16),
if (!modelState.areModelsValidated)
SettingsActionButton(
label: 'Download AI Models (~5 GB)',
icon: Icons.download_rounded,
color: AppColors.accent,
textColor: AppColors.zinc950,
onPressed: onDownload,
)
else
SettingsActionButton(
label: 'Re-validate Files',
icon: Icons.verified_outlined,
color: Colors.transparent,
textColor: AppColors.textSecondary,
borderColor: AppColors.border,
onPressed: onValidate,
),
],
);
}
}
class _StatusBadge extends StatelessWidget {
const _StatusBadge({required this.validated});
final bool validated;
@override
Widget build(BuildContext context) {
final color = validated ? AppColors.success : AppColors.textMuted;
final bgColor =
validated ? AppColors.successMuted : AppColors.surfaceContainerHigh;
final label = validated ? 'Ready' : 'Missing';
final icon =
validated ? Icons.check_circle_outline : Icons.radio_button_unchecked;
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Status: ',
style: GoogleFonts.inter(
fontSize: 13,
color: AppColors.textSecondary,
),
),
const SizedBox(width: UIConstants.spacing4),
Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
decoration: BoxDecoration(
color: bgColor,
borderRadius: BorderRadius.circular(20),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 13, color: color),
const SizedBox(width: 5),
Text(
label,
style: GoogleFonts.inter(
fontSize: 12,
fontWeight: FontWeight.w600,
color: color,
),
),
],
),
),
],
);
}
}
class _DownloadingView extends StatelessWidget {
const _DownloadingView({required this.modelState});
final AiModelSettingsState modelState;
@override
Widget build(BuildContext context) {
final pct = (modelState.progress * 100).toStringAsFixed(1);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
modelState.currentTask,
style: GoogleFonts.inter(
fontSize: 13,
color: AppColors.textSecondary,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
Text(
'$pct %',
style: GoogleFonts.inter(
fontSize: 13,
fontWeight: FontWeight.w600,
color: AppColors.accent,
),
),
],
),
const SizedBox(height: UIConstants.spacing8),
ClipRRect(
borderRadius: BorderRadius.circular(4),
child: LinearProgressIndicator(
value: modelState.progress,
minHeight: 6,
backgroundColor: AppColors.zinc800,
valueColor:
const AlwaysStoppedAnimation<Color>(AppColors.accent),
),
),
if (modelState.errorMessage != null) ...[
const SizedBox(height: UIConstants.spacing12),
ErrorRow(message: modelState.errorMessage!),
],
],
);
}
}
class ErrorRow extends StatelessWidget {
const ErrorRow({super.key, required this.message});
final String message;
@override
Widget build(BuildContext context) {
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(
Icons.error_outline_rounded,
color: AppColors.destructive,
size: 14,
),
const SizedBox(width: UIConstants.spacing8),
Expanded(
child: Text(
message,
style: GoogleFonts.inter(
fontSize: 12,
color: AppColors.destructive,
height: 1.4,
),
),
),
],
);
}
}

View File

@@ -0,0 +1,118 @@
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:trainhub_flutter/core/constants/ui_constants.dart';
import 'package:trainhub_flutter/core/theme/app_colors.dart';
class KnowledgeBaseSection extends StatelessWidget {
const KnowledgeBaseSection({super.key, required this.onTap});
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Knowledge Base',
style: GoogleFonts.inter(
fontSize: 13,
fontWeight: FontWeight.w600,
color: AppColors.textMuted,
letterSpacing: 0.8,
),
),
const SizedBox(height: UIConstants.spacing12),
_KnowledgeBaseCard(onTap: onTap),
],
);
}
}
class _KnowledgeBaseCard extends StatefulWidget {
const _KnowledgeBaseCard({required this.onTap});
final VoidCallback onTap;
@override
State<_KnowledgeBaseCard> createState() => _KnowledgeBaseCardState();
}
class _KnowledgeBaseCardState extends State<_KnowledgeBaseCard> {
bool _hovered = false;
@override
Widget build(BuildContext context) {
return MouseRegion(
onEnter: (_) => setState(() => _hovered = true),
onExit: (_) => setState(() => _hovered = false),
child: GestureDetector(
onTap: widget.onTap,
child: AnimatedContainer(
duration: UIConstants.animationDuration,
decoration: BoxDecoration(
color: _hovered
? AppColors.surfaceContainerHigh
: AppColors.surfaceContainer,
borderRadius: BorderRadius.circular(UIConstants.borderRadius),
border: Border.all(
color: _hovered
? AppColors.accent.withValues(alpha: 0.3)
: AppColors.border,
),
),
padding: const EdgeInsets.symmetric(
horizontal: UIConstants.spacing16,
vertical: UIConstants.spacing16,
),
child: Row(
children: [
Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: AppColors.accentMuted,
borderRadius: BorderRadius.circular(10),
),
child: const Icon(
Icons.hub_outlined,
color: AppColors.accent,
size: 20,
),
),
const SizedBox(width: UIConstants.spacing16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Manage Knowledge Base',
style: GoogleFonts.inter(
fontSize: 14,
fontWeight: FontWeight.w500,
color: AppColors.textPrimary,
),
),
const SizedBox(height: 3),
Text(
'Add trainer notes to give the AI context-aware answers.',
style: GoogleFonts.inter(
fontSize: 12,
color: AppColors.textMuted,
),
),
],
),
),
Icon(
Icons.chevron_right_rounded,
color: _hovered ? AppColors.accent : AppColors.textMuted,
size: 20,
),
],
),
),
),
);
}
}

View File

@@ -0,0 +1,81 @@
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:trainhub_flutter/core/constants/ui_constants.dart';
import 'package:trainhub_flutter/core/theme/app_colors.dart';
class SettingsActionButton extends StatefulWidget {
const SettingsActionButton({
super.key,
required this.label,
required this.icon,
required this.color,
required this.textColor,
required this.onPressed,
this.borderColor,
});
final String label;
final IconData icon;
final Color color;
final Color textColor;
final Color? borderColor;
final VoidCallback onPressed;
@override
State<SettingsActionButton> createState() => _SettingsActionButtonState();
}
class _SettingsActionButtonState extends State<SettingsActionButton> {
bool _hovered = false;
@override
Widget build(BuildContext context) {
final hasBorder = widget.borderColor != null;
return MouseRegion(
onEnter: (_) => setState(() => _hovered = true),
onExit: (_) => setState(() => _hovered = false),
child: AnimatedContainer(
duration: UIConstants.animationDuration,
height: 40,
decoration: BoxDecoration(
color: hasBorder
? (_hovered ? AppColors.zinc800 : Colors.transparent)
: (_hovered
? widget.color.withValues(alpha: 0.85)
: widget.color),
borderRadius: BorderRadius.circular(UIConstants.smallBorderRadius),
border: hasBorder ? Border.all(color: widget.borderColor!) : null,
),
child: Material(
color: Colors.transparent,
child: InkWell(
borderRadius:
BorderRadius.circular(UIConstants.smallBorderRadius),
onTap: widget.onPressed,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: UIConstants.spacing16,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(widget.icon, size: 16, color: widget.textColor),
const SizedBox(width: UIConstants.spacing8),
Text(
widget.label,
style: GoogleFonts.inter(
fontSize: 13,
fontWeight: FontWeight.w600,
color: widget.textColor,
),
),
],
),
),
),
),
),
);
}
}

View File

@@ -0,0 +1,89 @@
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:trainhub_flutter/core/constants/ui_constants.dart';
import 'package:trainhub_flutter/core/theme/app_colors.dart';
class SettingsTopBar extends StatelessWidget {
const SettingsTopBar({super.key, required this.onBack});
final VoidCallback onBack;
@override
Widget build(BuildContext context) {
return Container(
height: 52,
padding: const EdgeInsets.symmetric(horizontal: UIConstants.spacing16),
decoration: const BoxDecoration(
color: AppColors.surfaceContainer,
border: Border(bottom: BorderSide(color: AppColors.border)),
),
child: Row(
children: [
SettingsIconButton(
icon: Icons.arrow_back_rounded,
tooltip: 'Go back',
onTap: onBack,
),
const SizedBox(width: UIConstants.spacing12),
Text(
'Settings',
style: GoogleFonts.inter(
fontSize: 14,
fontWeight: FontWeight.w600,
color: AppColors.textPrimary,
),
),
],
),
);
}
}
class SettingsIconButton extends StatefulWidget {
const SettingsIconButton({
super.key,
required this.icon,
required this.onTap,
this.tooltip = '',
});
final IconData icon;
final VoidCallback onTap;
final String tooltip;
@override
State<SettingsIconButton> createState() => _SettingsIconButtonState();
}
class _SettingsIconButtonState extends State<SettingsIconButton> {
bool _hovered = false;
@override
Widget build(BuildContext context) {
return Tooltip(
message: widget.tooltip,
child: MouseRegion(
onEnter: (_) => setState(() => _hovered = true),
onExit: (_) => setState(() => _hovered = false),
child: GestureDetector(
onTap: widget.onTap,
child: AnimatedContainer(
duration: UIConstants.animationDuration,
width: 32,
height: 32,
decoration: BoxDecoration(
color: _hovered ? AppColors.zinc800 : Colors.transparent,
borderRadius: BorderRadius.circular(6),
),
child: Icon(
widget.icon,
size: 18,
color:
_hovered ? AppColors.textPrimary : AppColors.textSecondary,
),
),
),
),
);
}
}