This commit is contained in:
263
lib/presentation/settings/ai_model_settings_controller.dart
Normal file
263
lib/presentation/settings/ai_model_settings_controller.dart
Normal file
@@ -0,0 +1,263 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:archive/archive_io.dart';
|
||||
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/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 {
|
||||
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';
|
||||
}
|
||||
} else if (Platform.isWindows) {
|
||||
return 'https://github.com/ggml-org/llama.cpp/releases/download/$_llamaBuild/llama-$_llamaBuild-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';
|
||||
}
|
||||
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();
|
||||
|
||||
@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() &&
|
||||
nomicModel.existsSync() &&
|
||||
qwenModel.existsSync();
|
||||
|
||||
state = state.copyWith(
|
||||
areModelsValidated: validated,
|
||||
currentTask: validated ? 'All files present.' : 'Files missing.',
|
||||
);
|
||||
} catch (e) {
|
||||
state = state.copyWith(
|
||||
areModelsValidated: false,
|
||||
currentTask: 'Validation failed.',
|
||||
errorMessage: e.toString(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Download & Install
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/// Downloads and installs the llama.cpp binary and both model files.
|
||||
Future<void> downloadAll() async {
|
||||
if (state.isDownloading) return;
|
||||
|
||||
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,
|
||||
taskLabel: 'Downloading llama.cpp binary…',
|
||||
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),
|
||||
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),
|
||||
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(
|
||||
isDownloading: false,
|
||||
currentTask: 'Download failed.',
|
||||
errorMessage: 'Network error: ${e.message}',
|
||||
);
|
||||
} catch (e) {
|
||||
state = state.copyWith(
|
||||
isDownloading: false,
|
||||
currentTask: 'Download failed.',
|
||||
errorMessage: e.toString(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Private helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/// Downloads a single file with progress mapped into [overallStart]..[overallEnd].
|
||||
Future<void> _downloadFile({
|
||||
required String url,
|
||||
required String savePath,
|
||||
required String taskLabel,
|
||||
required double overallStart,
|
||||
required double overallEnd,
|
||||
}) async {
|
||||
state = state.copyWith(currentTask: taskLabel, progress: overallStart);
|
||||
|
||||
await _dio.download(
|
||||
url,
|
||||
savePath,
|
||||
onReceiveProgress: (received, total) {
|
||||
if (total <= 0) return;
|
||||
final fileProgress = received / total;
|
||||
final overall =
|
||||
overallStart + fileProgress * (overallEnd - overallStart);
|
||||
state = state.copyWith(progress: overall);
|
||||
},
|
||||
options: Options(
|
||||
followRedirects: true,
|
||||
maxRedirects: 5,
|
||||
receiveTimeout: const Duration(hours: 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
|
||||
// Walk the extracted tree to find the server binary
|
||||
final binary = _findFile(extractDirObj, _serverBinaryName);
|
||||
if (binary == null) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'ai_model_settings_controller.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$aiModelSettingsControllerHash() =>
|
||||
r'5bf80e85e734016b0fa80c6bb84315925f2595b3';
|
||||
|
||||
/// See also [AiModelSettingsController].
|
||||
@ProviderFor(AiModelSettingsController)
|
||||
final aiModelSettingsControllerProvider =
|
||||
AutoDisposeNotifierProvider<
|
||||
AiModelSettingsController,
|
||||
AiModelSettingsState
|
||||
>.internal(
|
||||
AiModelSettingsController.new,
|
||||
name: r'aiModelSettingsControllerProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$aiModelSettingsControllerHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef _$AiModelSettingsController = AutoDisposeNotifier<AiModelSettingsState>;
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member, deprecated_member_use_from_same_package
|
||||
14
lib/presentation/settings/ai_model_settings_state.dart
Normal file
14
lib/presentation/settings/ai_model_settings_state.dart
Normal file
@@ -0,0 +1,14 @@
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
part 'ai_model_settings_state.freezed.dart';
|
||||
|
||||
@freezed
|
||||
class AiModelSettingsState with _$AiModelSettingsState {
|
||||
const factory AiModelSettingsState({
|
||||
@Default(false) bool isDownloading,
|
||||
@Default(0.0) double progress,
|
||||
@Default('') String currentTask,
|
||||
@Default(false) bool areModelsValidated,
|
||||
String? errorMessage,
|
||||
}) = _AiModelSettingsState;
|
||||
}
|
||||
263
lib/presentation/settings/ai_model_settings_state.freezed.dart
Normal file
263
lib/presentation/settings/ai_model_settings_state.freezed.dart
Normal file
@@ -0,0 +1,263 @@
|
||||
// coverage:ignore-file
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
|
||||
|
||||
part of 'ai_model_settings_state.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
T _$identity<T>(T value) => value;
|
||||
|
||||
final _privateConstructorUsedError = UnsupportedError(
|
||||
'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models',
|
||||
);
|
||||
|
||||
/// @nodoc
|
||||
mixin _$AiModelSettingsState {
|
||||
bool get isDownloading => throw _privateConstructorUsedError;
|
||||
double get progress => throw _privateConstructorUsedError;
|
||||
String get currentTask => throw _privateConstructorUsedError;
|
||||
bool get areModelsValidated => throw _privateConstructorUsedError;
|
||||
String? get errorMessage => throw _privateConstructorUsedError;
|
||||
|
||||
/// Create a copy of AiModelSettingsState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
$AiModelSettingsStateCopyWith<AiModelSettingsState> get copyWith =>
|
||||
throw _privateConstructorUsedError;
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract class $AiModelSettingsStateCopyWith<$Res> {
|
||||
factory $AiModelSettingsStateCopyWith(
|
||||
AiModelSettingsState value,
|
||||
$Res Function(AiModelSettingsState) then,
|
||||
) = _$AiModelSettingsStateCopyWithImpl<$Res, AiModelSettingsState>;
|
||||
@useResult
|
||||
$Res call({
|
||||
bool isDownloading,
|
||||
double progress,
|
||||
String currentTask,
|
||||
bool areModelsValidated,
|
||||
String? errorMessage,
|
||||
});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$AiModelSettingsStateCopyWithImpl<
|
||||
$Res,
|
||||
$Val extends AiModelSettingsState
|
||||
>
|
||||
implements $AiModelSettingsStateCopyWith<$Res> {
|
||||
_$AiModelSettingsStateCopyWithImpl(this._value, this._then);
|
||||
|
||||
// ignore: unused_field
|
||||
final $Val _value;
|
||||
// ignore: unused_field
|
||||
final $Res Function($Val) _then;
|
||||
|
||||
/// Create a copy of AiModelSettingsState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({
|
||||
Object? isDownloading = null,
|
||||
Object? progress = null,
|
||||
Object? currentTask = null,
|
||||
Object? areModelsValidated = null,
|
||||
Object? errorMessage = freezed,
|
||||
}) {
|
||||
return _then(
|
||||
_value.copyWith(
|
||||
isDownloading: null == isDownloading
|
||||
? _value.isDownloading
|
||||
: isDownloading // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
progress: null == progress
|
||||
? _value.progress
|
||||
: progress // ignore: cast_nullable_to_non_nullable
|
||||
as double,
|
||||
currentTask: null == currentTask
|
||||
? _value.currentTask
|
||||
: currentTask // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
areModelsValidated: null == areModelsValidated
|
||||
? _value.areModelsValidated
|
||||
: areModelsValidated // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
errorMessage: freezed == errorMessage
|
||||
? _value.errorMessage
|
||||
: errorMessage // ignore: cast_nullable_to_non_nullable
|
||||
as String?,
|
||||
)
|
||||
as $Val,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract class _$$AiModelSettingsStateImplCopyWith<$Res>
|
||||
implements $AiModelSettingsStateCopyWith<$Res> {
|
||||
factory _$$AiModelSettingsStateImplCopyWith(
|
||||
_$AiModelSettingsStateImpl value,
|
||||
$Res Function(_$AiModelSettingsStateImpl) then,
|
||||
) = __$$AiModelSettingsStateImplCopyWithImpl<$Res>;
|
||||
@override
|
||||
@useResult
|
||||
$Res call({
|
||||
bool isDownloading,
|
||||
double progress,
|
||||
String currentTask,
|
||||
bool areModelsValidated,
|
||||
String? errorMessage,
|
||||
});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$$AiModelSettingsStateImplCopyWithImpl<$Res>
|
||||
extends _$AiModelSettingsStateCopyWithImpl<$Res, _$AiModelSettingsStateImpl>
|
||||
implements _$$AiModelSettingsStateImplCopyWith<$Res> {
|
||||
__$$AiModelSettingsStateImplCopyWithImpl(
|
||||
_$AiModelSettingsStateImpl _value,
|
||||
$Res Function(_$AiModelSettingsStateImpl) _then,
|
||||
) : super(_value, _then);
|
||||
|
||||
/// Create a copy of AiModelSettingsState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({
|
||||
Object? isDownloading = null,
|
||||
Object? progress = null,
|
||||
Object? currentTask = null,
|
||||
Object? areModelsValidated = null,
|
||||
Object? errorMessage = freezed,
|
||||
}) {
|
||||
return _then(
|
||||
_$AiModelSettingsStateImpl(
|
||||
isDownloading: null == isDownloading
|
||||
? _value.isDownloading
|
||||
: isDownloading // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
progress: null == progress
|
||||
? _value.progress
|
||||
: progress // ignore: cast_nullable_to_non_nullable
|
||||
as double,
|
||||
currentTask: null == currentTask
|
||||
? _value.currentTask
|
||||
: currentTask // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
areModelsValidated: null == areModelsValidated
|
||||
? _value.areModelsValidated
|
||||
: areModelsValidated // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
errorMessage: freezed == errorMessage
|
||||
? _value.errorMessage
|
||||
: errorMessage // ignore: cast_nullable_to_non_nullable
|
||||
as String?,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class _$AiModelSettingsStateImpl implements _AiModelSettingsState {
|
||||
const _$AiModelSettingsStateImpl({
|
||||
this.isDownloading = false,
|
||||
this.progress = 0.0,
|
||||
this.currentTask = '',
|
||||
this.areModelsValidated = false,
|
||||
this.errorMessage,
|
||||
});
|
||||
|
||||
@override
|
||||
@JsonKey()
|
||||
final bool isDownloading;
|
||||
@override
|
||||
@JsonKey()
|
||||
final double progress;
|
||||
@override
|
||||
@JsonKey()
|
||||
final String currentTask;
|
||||
@override
|
||||
@JsonKey()
|
||||
final bool areModelsValidated;
|
||||
@override
|
||||
final String? errorMessage;
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'AiModelSettingsState(isDownloading: $isDownloading, progress: $progress, currentTask: $currentTask, areModelsValidated: $areModelsValidated, errorMessage: $errorMessage)';
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _$AiModelSettingsStateImpl &&
|
||||
(identical(other.isDownloading, isDownloading) ||
|
||||
other.isDownloading == isDownloading) &&
|
||||
(identical(other.progress, progress) ||
|
||||
other.progress == progress) &&
|
||||
(identical(other.currentTask, currentTask) ||
|
||||
other.currentTask == currentTask) &&
|
||||
(identical(other.areModelsValidated, areModelsValidated) ||
|
||||
other.areModelsValidated == areModelsValidated) &&
|
||||
(identical(other.errorMessage, errorMessage) ||
|
||||
other.errorMessage == errorMessage));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(
|
||||
runtimeType,
|
||||
isDownloading,
|
||||
progress,
|
||||
currentTask,
|
||||
areModelsValidated,
|
||||
errorMessage,
|
||||
);
|
||||
|
||||
/// Create a copy of AiModelSettingsState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
_$$AiModelSettingsStateImplCopyWith<_$AiModelSettingsStateImpl>
|
||||
get copyWith =>
|
||||
__$$AiModelSettingsStateImplCopyWithImpl<_$AiModelSettingsStateImpl>(
|
||||
this,
|
||||
_$identity,
|
||||
);
|
||||
}
|
||||
|
||||
abstract class _AiModelSettingsState implements AiModelSettingsState {
|
||||
const factory _AiModelSettingsState({
|
||||
final bool isDownloading,
|
||||
final double progress,
|
||||
final String currentTask,
|
||||
final bool areModelsValidated,
|
||||
final String? errorMessage,
|
||||
}) = _$AiModelSettingsStateImpl;
|
||||
|
||||
@override
|
||||
bool get isDownloading;
|
||||
@override
|
||||
double get progress;
|
||||
@override
|
||||
String get currentTask;
|
||||
@override
|
||||
bool get areModelsValidated;
|
||||
@override
|
||||
String? get errorMessage;
|
||||
|
||||
/// Create a copy of AiModelSettingsState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
_$$AiModelSettingsStateImplCopyWith<_$AiModelSettingsStateImpl>
|
||||
get copyWith => throw _privateConstructorUsedError;
|
||||
}
|
||||
102
lib/presentation/settings/knowledge_base_controller.dart
Normal file
102
lib/presentation/settings/knowledge_base_controller.dart
Normal file
@@ -0,0 +1,102 @@
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:trainhub_flutter/domain/repositories/note_repository.dart';
|
||||
import 'package:trainhub_flutter/injection.dart';
|
||||
import 'package:trainhub_flutter/presentation/settings/knowledge_base_state.dart';
|
||||
|
||||
part 'knowledge_base_controller.g.dart';
|
||||
|
||||
@riverpod
|
||||
class KnowledgeBaseController extends _$KnowledgeBaseController {
|
||||
late NoteRepository _repo;
|
||||
|
||||
@override
|
||||
KnowledgeBaseState build() {
|
||||
_repo = getIt<NoteRepository>();
|
||||
// Load the current chunk count asynchronously after first build.
|
||||
_loadCount();
|
||||
return const KnowledgeBaseState();
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Load chunk count
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
Future<void> _loadCount() async {
|
||||
try {
|
||||
final count = await _repo.getChunkCount();
|
||||
state = state.copyWith(chunkCount: count);
|
||||
} catch (_) {
|
||||
// Non-fatal — UI stays at 0.
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Save note
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/// Chunks [text], generates embeddings via Nomic, and stores the result.
|
||||
Future<void> saveNote(String text) async {
|
||||
if (text.trim().isEmpty) return;
|
||||
|
||||
state = state.copyWith(
|
||||
isLoading: true,
|
||||
successMessage: null,
|
||||
errorMessage: null,
|
||||
);
|
||||
|
||||
try {
|
||||
await _repo.addNote(text.trim());
|
||||
final count = await _repo.getChunkCount();
|
||||
state = state.copyWith(
|
||||
isLoading: false,
|
||||
chunkCount: count,
|
||||
successMessage: 'Saved! Knowledge base now has $count chunks.',
|
||||
);
|
||||
} catch (e) {
|
||||
state = state.copyWith(
|
||||
isLoading: false,
|
||||
errorMessage: _friendlyError(e),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Clear knowledge base
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
Future<void> clearKnowledgeBase() async {
|
||||
state = state.copyWith(
|
||||
isLoading: true,
|
||||
successMessage: null,
|
||||
errorMessage: null,
|
||||
);
|
||||
try {
|
||||
await _repo.clearAll();
|
||||
state = state.copyWith(
|
||||
isLoading: false,
|
||||
chunkCount: 0,
|
||||
successMessage: 'Knowledge base cleared.',
|
||||
);
|
||||
} catch (e) {
|
||||
state = state.copyWith(
|
||||
isLoading: false,
|
||||
errorMessage: _friendlyError(e),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Helper
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
String _friendlyError(Object e) {
|
||||
final msg = e.toString();
|
||||
if (msg.contains('Connection refused') ||
|
||||
msg.contains('SocketException')) {
|
||||
return 'Cannot reach the embedding server. '
|
||||
'Make sure AI models are downloaded and the app has had time to '
|
||||
'start the inference servers.';
|
||||
}
|
||||
return 'Error: $msg';
|
||||
}
|
||||
}
|
||||
30
lib/presentation/settings/knowledge_base_controller.g.dart
Normal file
30
lib/presentation/settings/knowledge_base_controller.g.dart
Normal file
@@ -0,0 +1,30 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'knowledge_base_controller.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$knowledgeBaseControllerHash() =>
|
||||
r'1b18418c3e7a66c6517dbbd7167e7406e16c8748';
|
||||
|
||||
/// See also [KnowledgeBaseController].
|
||||
@ProviderFor(KnowledgeBaseController)
|
||||
final knowledgeBaseControllerProvider =
|
||||
AutoDisposeNotifierProvider<
|
||||
KnowledgeBaseController,
|
||||
KnowledgeBaseState
|
||||
>.internal(
|
||||
KnowledgeBaseController.new,
|
||||
name: r'knowledgeBaseControllerProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$knowledgeBaseControllerHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef _$KnowledgeBaseController = AutoDisposeNotifier<KnowledgeBaseState>;
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member, deprecated_member_use_from_same_package
|
||||
726
lib/presentation/settings/knowledge_base_page.dart
Normal file
726
lib/presentation/settings/knowledge_base_page.dart
Normal file
@@ -0,0 +1,726 @@
|
||||
import 'package:auto_route/auto_route.dart';
|
||||
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/presentation/settings/knowledge_base_controller.dart';
|
||||
import 'package:trainhub_flutter/presentation/settings/knowledge_base_state.dart';
|
||||
|
||||
@RoutePage()
|
||||
class KnowledgeBasePage extends ConsumerStatefulWidget {
|
||||
const KnowledgeBasePage({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<KnowledgeBasePage> createState() => _KnowledgeBasePageState();
|
||||
}
|
||||
|
||||
class _KnowledgeBasePageState extends ConsumerState<KnowledgeBasePage> {
|
||||
final _textController = TextEditingController();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_textController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _save(KnowledgeBaseController controller) async {
|
||||
await controller.saveNote(_textController.text);
|
||||
// Only clear the field if save succeeded (no error in state).
|
||||
if (!mounted) return;
|
||||
final s = ref.read(knowledgeBaseControllerProvider);
|
||||
if (s.successMessage != null) _textController.clear();
|
||||
}
|
||||
|
||||
Future<void> _clear(KnowledgeBaseController controller) async {
|
||||
final confirmed = await _showConfirmDialog();
|
||||
if (!confirmed) return;
|
||||
await controller.clearKnowledgeBase();
|
||||
}
|
||||
|
||||
Future<bool> _showConfirmDialog() async {
|
||||
return await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
backgroundColor: AppColors.surfaceContainer,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(UIConstants.borderRadius),
|
||||
side: const BorderSide(color: AppColors.border),
|
||||
),
|
||||
title: Text(
|
||||
'Clear knowledge base?',
|
||||
style: GoogleFonts.inter(
|
||||
color: AppColors.textPrimary,
|
||||
fontWeight: FontWeight.w600,
|
||||
fontSize: 15,
|
||||
),
|
||||
),
|
||||
content: Text(
|
||||
'This will permanently delete all stored chunks and embeddings. '
|
||||
'This action cannot be undone.',
|
||||
style: GoogleFonts.inter(
|
||||
color: AppColors.textSecondary,
|
||||
fontSize: 13,
|
||||
height: 1.5,
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(ctx).pop(false),
|
||||
child: Text(
|
||||
'Cancel',
|
||||
style: GoogleFonts.inter(color: AppColors.textMuted),
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(ctx).pop(true),
|
||||
child: Text(
|
||||
'Clear',
|
||||
style: GoogleFonts.inter(color: AppColors.destructive),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
) ??
|
||||
false;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final kbState = ref.watch(knowledgeBaseControllerProvider);
|
||||
final controller = ref.read(knowledgeBaseControllerProvider.notifier);
|
||||
|
||||
// Show success SnackBar when a note is saved successfully.
|
||||
ref.listen<KnowledgeBaseState>(knowledgeBaseControllerProvider,
|
||||
(prev, next) {
|
||||
if (next.successMessage != null &&
|
||||
next.successMessage != prev?.successMessage) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
next.successMessage!,
|
||||
style: GoogleFonts.inter(
|
||||
color: AppColors.textPrimary,
|
||||
fontSize: 13,
|
||||
),
|
||||
),
|
||||
backgroundColor: AppColors.surfaceContainerHigh,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius:
|
||||
BorderRadius.circular(UIConstants.smallBorderRadius),
|
||||
side: const BorderSide(
|
||||
color: AppColors.success,
|
||||
width: 1,
|
||||
),
|
||||
),
|
||||
duration: const Duration(seconds: 3),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: AppColors.surface,
|
||||
body: Column(
|
||||
children: [
|
||||
// ── Top bar ──────────────────────────────────────────────────────
|
||||
_TopBar(onBack: () => context.router.maybePop()),
|
||||
|
||||
// ── Content ──────────────────────────────────────────────────────
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(UIConstants.pagePadding),
|
||||
child: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 680),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Heading
|
||||
Text(
|
||||
'Knowledge Base',
|
||||
style: GoogleFonts.inter(
|
||||
fontSize: 22,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: AppColors.textPrimary,
|
||||
letterSpacing: -0.3,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: UIConstants.spacing8),
|
||||
Text(
|
||||
'Paste your fitness or university notes below. '
|
||||
'They will be split into chunks, embedded with the '
|
||||
'Nomic model, and used as context when you chat with '
|
||||
'the AI — no internet required.',
|
||||
style: GoogleFonts.inter(
|
||||
fontSize: 13,
|
||||
color: AppColors.textSecondary,
|
||||
height: 1.6,
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: UIConstants.spacing24),
|
||||
|
||||
// ── Status card ──────────────────────────────────────
|
||||
_StatusCard(chunkCount: kbState.chunkCount),
|
||||
|
||||
const SizedBox(height: UIConstants.spacing24),
|
||||
|
||||
// ── Text input ───────────────────────────────────────
|
||||
_SectionLabel('Paste Notes'),
|
||||
const SizedBox(height: UIConstants.spacing8),
|
||||
|
||||
Container(
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceContainer,
|
||||
borderRadius: BorderRadius.circular(
|
||||
UIConstants.borderRadius,
|
||||
),
|
||||
border: Border.all(color: AppColors.border),
|
||||
),
|
||||
child: TextField(
|
||||
controller: _textController,
|
||||
style: GoogleFonts.inter(
|
||||
fontSize: 13,
|
||||
color: AppColors.textPrimary,
|
||||
height: 1.6,
|
||||
),
|
||||
maxLines: 14,
|
||||
minLines: 8,
|
||||
decoration: InputDecoration(
|
||||
hintText:
|
||||
'Paste lecture notes, programming guides, '
|
||||
'exercise descriptions, research summaries…',
|
||||
hintStyle: GoogleFonts.inter(
|
||||
fontSize: 13,
|
||||
color: AppColors.textMuted,
|
||||
height: 1.6,
|
||||
),
|
||||
contentPadding: const EdgeInsets.all(
|
||||
UIConstants.cardPadding,
|
||||
),
|
||||
border: InputBorder.none,
|
||||
enabledBorder: InputBorder.none,
|
||||
focusedBorder: InputBorder.none,
|
||||
),
|
||||
enabled: !kbState.isLoading,
|
||||
),
|
||||
),
|
||||
|
||||
// ── Error message ────────────────────────────────────
|
||||
if (kbState.errorMessage != null) ...[
|
||||
const SizedBox(height: UIConstants.spacing12),
|
||||
_ErrorBanner(message: kbState.errorMessage!),
|
||||
],
|
||||
|
||||
const SizedBox(height: UIConstants.spacing16),
|
||||
|
||||
// ── Action buttons ───────────────────────────────────
|
||||
if (kbState.isLoading)
|
||||
_LoadingIndicator()
|
||||
else
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: _SaveButton(
|
||||
onPressed: () => _save(controller),
|
||||
),
|
||||
),
|
||||
if (kbState.chunkCount > 0) ...[
|
||||
const SizedBox(width: UIConstants.spacing12),
|
||||
_ClearButton(
|
||||
onPressed: () => _clear(controller),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
|
||||
const SizedBox(height: UIConstants.spacing32),
|
||||
|
||||
// ── How it works ─────────────────────────────────────
|
||||
_HowItWorksCard(),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// 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, onTap: onBack),
|
||||
const SizedBox(width: UIConstants.spacing12),
|
||||
Text(
|
||||
'Knowledge Base',
|
||||
style: GoogleFonts.inter(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: AppColors.textPrimary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Status card
|
||||
// =============================================================================
|
||||
class _StatusCard extends StatelessWidget {
|
||||
const _StatusCard({required this.chunkCount});
|
||||
|
||||
final int chunkCount;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final hasChunks = chunkCount > 0;
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: UIConstants.spacing16,
|
||||
vertical: UIConstants.spacing12,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: hasChunks ? AppColors.successMuted : AppColors.surfaceContainer,
|
||||
borderRadius: BorderRadius.circular(UIConstants.smallBorderRadius),
|
||||
border: Border.all(
|
||||
color: hasChunks
|
||||
? AppColors.success.withValues(alpha: 0.3)
|
||||
: AppColors.border,
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
hasChunks
|
||||
? Icons.check_circle_outline_rounded
|
||||
: Icons.info_outline_rounded,
|
||||
size: 16,
|
||||
color: hasChunks ? AppColors.success : AppColors.textMuted,
|
||||
),
|
||||
const SizedBox(width: UIConstants.spacing12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
hasChunks
|
||||
? '$chunkCount chunk${chunkCount == 1 ? '' : 's'} stored — '
|
||||
'AI chat will use these as context.'
|
||||
: 'No notes added yet. The AI chat will use only its base '
|
||||
'training knowledge.',
|
||||
style: GoogleFonts.inter(
|
||||
fontSize: 13,
|
||||
color: hasChunks ? AppColors.success : AppColors.textMuted,
|
||||
height: 1.4,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Loading indicator
|
||||
// =============================================================================
|
||||
class _LoadingIndicator extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(vertical: UIConstants.spacing16),
|
||||
child: Row(
|
||||
children: [
|
||||
const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: AppColors.accent,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: UIConstants.spacing12),
|
||||
Text(
|
||||
'Generating embeddings… this may take a moment.',
|
||||
style: GoogleFonts.inter(
|
||||
fontSize: 13,
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Save button
|
||||
// =============================================================================
|
||||
class _SaveButton extends StatefulWidget {
|
||||
const _SaveButton({required this.onPressed});
|
||||
|
||||
final VoidCallback onPressed;
|
||||
|
||||
@override
|
||||
State<_SaveButton> createState() => _SaveButtonState();
|
||||
}
|
||||
|
||||
class _SaveButtonState extends State<_SaveButton> {
|
||||
bool _hovered = false;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MouseRegion(
|
||||
onEnter: (_) => setState(() => _hovered = true),
|
||||
onExit: (_) => setState(() => _hovered = false),
|
||||
child: AnimatedContainer(
|
||||
duration: UIConstants.animationDuration,
|
||||
height: 42,
|
||||
decoration: BoxDecoration(
|
||||
color: _hovered
|
||||
? AppColors.accent.withValues(alpha: 0.85)
|
||||
: AppColors.accent,
|
||||
borderRadius: BorderRadius.circular(UIConstants.smallBorderRadius),
|
||||
),
|
||||
child: Material(
|
||||
color: Colors.transparent,
|
||||
child: InkWell(
|
||||
borderRadius:
|
||||
BorderRadius.circular(UIConstants.smallBorderRadius),
|
||||
onTap: widget.onPressed,
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.save_outlined,
|
||||
color: AppColors.zinc950,
|
||||
size: 16,
|
||||
),
|
||||
const SizedBox(width: UIConstants.spacing8),
|
||||
Text(
|
||||
'Save to Knowledge Base',
|
||||
style: GoogleFonts.inter(
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: AppColors.zinc950,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Clear button
|
||||
// =============================================================================
|
||||
class _ClearButton extends StatefulWidget {
|
||||
const _ClearButton({required this.onPressed});
|
||||
|
||||
final VoidCallback onPressed;
|
||||
|
||||
@override
|
||||
State<_ClearButton> createState() => _ClearButtonState();
|
||||
}
|
||||
|
||||
class _ClearButtonState extends State<_ClearButton> {
|
||||
bool _hovered = false;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MouseRegion(
|
||||
onEnter: (_) => setState(() => _hovered = true),
|
||||
onExit: (_) => setState(() => _hovered = false),
|
||||
child: AnimatedContainer(
|
||||
duration: UIConstants.animationDuration,
|
||||
height: 42,
|
||||
decoration: BoxDecoration(
|
||||
color: _hovered ? AppColors.destructiveMuted : Colors.transparent,
|
||||
borderRadius: BorderRadius.circular(UIConstants.smallBorderRadius),
|
||||
border: Border.all(
|
||||
color: _hovered
|
||||
? AppColors.destructive.withValues(alpha: 0.4)
|
||||
: AppColors.border,
|
||||
),
|
||||
),
|
||||
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(
|
||||
Icons.delete_outline_rounded,
|
||||
size: 15,
|
||||
color:
|
||||
_hovered ? AppColors.destructive : AppColors.textMuted,
|
||||
),
|
||||
const SizedBox(width: UIConstants.spacing8),
|
||||
Text(
|
||||
'Clear All',
|
||||
style: GoogleFonts.inter(
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w500,
|
||||
color: _hovered
|
||||
? AppColors.destructive
|
||||
: AppColors.textMuted,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Error banner
|
||||
// =============================================================================
|
||||
class _ErrorBanner extends StatelessWidget {
|
||||
const _ErrorBanner({required this.message});
|
||||
|
||||
final String message;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(UIConstants.spacing12),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.destructiveMuted,
|
||||
borderRadius: BorderRadius.circular(UIConstants.smallBorderRadius),
|
||||
border: Border.all(
|
||||
color: AppColors.destructive.withValues(alpha: 0.4),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.error_outline_rounded,
|
||||
color: AppColors.destructive,
|
||||
size: 15,
|
||||
),
|
||||
const SizedBox(width: UIConstants.spacing8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
message,
|
||||
style: GoogleFonts.inter(
|
||||
fontSize: 12,
|
||||
color: AppColors.destructive,
|
||||
height: 1.5,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// How it works info card
|
||||
// =============================================================================
|
||||
class _HowItWorksCard extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(UIConstants.cardPadding),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceContainer,
|
||||
borderRadius: BorderRadius.circular(UIConstants.borderRadius),
|
||||
border: Border.all(color: AppColors.border),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.info_outline_rounded,
|
||||
size: 15,
|
||||
color: AppColors.textMuted,
|
||||
),
|
||||
const SizedBox(width: UIConstants.spacing8),
|
||||
Text(
|
||||
'How it works',
|
||||
style: GoogleFonts.inter(
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: UIConstants.spacing12),
|
||||
_Step(
|
||||
n: '1',
|
||||
text: 'Your text is split into ~500-character chunks at paragraph '
|
||||
'and sentence boundaries.',
|
||||
),
|
||||
const SizedBox(height: UIConstants.spacing8),
|
||||
_Step(
|
||||
n: '2',
|
||||
text:
|
||||
'Each chunk is embedded by the local Nomic model into a 768-dim '
|
||||
'vector and stored in the database.',
|
||||
),
|
||||
const SizedBox(height: UIConstants.spacing8),
|
||||
_Step(
|
||||
n: '3',
|
||||
text:
|
||||
'When you ask a question, the 3 most similar chunks are retrieved '
|
||||
'and injected into the AI system prompt as context.',
|
||||
),
|
||||
const SizedBox(height: UIConstants.spacing8),
|
||||
_Step(
|
||||
n: '4',
|
||||
text:
|
||||
'Everything stays on your device — no data leaves the machine.',
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Step extends StatelessWidget {
|
||||
const _Step({required this.n, required this.text});
|
||||
|
||||
final String n;
|
||||
final String text;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Container(
|
||||
width: 20,
|
||||
height: 20,
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceContainerHigh,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
n,
|
||||
style: GoogleFonts.inter(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: AppColors.accent,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: UIConstants.spacing8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
text,
|
||||
style: GoogleFonts.inter(
|
||||
fontSize: 12,
|
||||
color: AppColors.textMuted,
|
||||
height: 1.5,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Small reusable widgets
|
||||
// =============================================================================
|
||||
|
||||
class _SectionLabel extends StatelessWidget {
|
||||
const _SectionLabel(this.label);
|
||||
|
||||
final String label;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Text(
|
||||
label,
|
||||
style: GoogleFonts.inter(
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: AppColors.textMuted,
|
||||
letterSpacing: 0.8,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _IconBtn extends StatefulWidget {
|
||||
const _IconBtn({required this.icon, required this.onTap});
|
||||
|
||||
final IconData icon;
|
||||
final VoidCallback onTap;
|
||||
|
||||
@override
|
||||
State<_IconBtn> createState() => _IconBtnState();
|
||||
}
|
||||
|
||||
class _IconBtnState extends State<_IconBtn> {
|
||||
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,
|
||||
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,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
13
lib/presentation/settings/knowledge_base_state.dart
Normal file
13
lib/presentation/settings/knowledge_base_state.dart
Normal file
@@ -0,0 +1,13 @@
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
part 'knowledge_base_state.freezed.dart';
|
||||
|
||||
@freezed
|
||||
class KnowledgeBaseState with _$KnowledgeBaseState {
|
||||
const factory KnowledgeBaseState({
|
||||
@Default(false) bool isLoading,
|
||||
@Default(0) int chunkCount,
|
||||
String? successMessage,
|
||||
String? errorMessage,
|
||||
}) = _KnowledgeBaseState;
|
||||
}
|
||||
235
lib/presentation/settings/knowledge_base_state.freezed.dart
Normal file
235
lib/presentation/settings/knowledge_base_state.freezed.dart
Normal file
@@ -0,0 +1,235 @@
|
||||
// coverage:ignore-file
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
|
||||
|
||||
part of 'knowledge_base_state.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
T _$identity<T>(T value) => value;
|
||||
|
||||
final _privateConstructorUsedError = UnsupportedError(
|
||||
'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models',
|
||||
);
|
||||
|
||||
/// @nodoc
|
||||
mixin _$KnowledgeBaseState {
|
||||
bool get isLoading => throw _privateConstructorUsedError;
|
||||
int get chunkCount => throw _privateConstructorUsedError;
|
||||
String? get successMessage => throw _privateConstructorUsedError;
|
||||
String? get errorMessage => throw _privateConstructorUsedError;
|
||||
|
||||
/// Create a copy of KnowledgeBaseState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
$KnowledgeBaseStateCopyWith<KnowledgeBaseState> get copyWith =>
|
||||
throw _privateConstructorUsedError;
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract class $KnowledgeBaseStateCopyWith<$Res> {
|
||||
factory $KnowledgeBaseStateCopyWith(
|
||||
KnowledgeBaseState value,
|
||||
$Res Function(KnowledgeBaseState) then,
|
||||
) = _$KnowledgeBaseStateCopyWithImpl<$Res, KnowledgeBaseState>;
|
||||
@useResult
|
||||
$Res call({
|
||||
bool isLoading,
|
||||
int chunkCount,
|
||||
String? successMessage,
|
||||
String? errorMessage,
|
||||
});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$KnowledgeBaseStateCopyWithImpl<$Res, $Val extends KnowledgeBaseState>
|
||||
implements $KnowledgeBaseStateCopyWith<$Res> {
|
||||
_$KnowledgeBaseStateCopyWithImpl(this._value, this._then);
|
||||
|
||||
// ignore: unused_field
|
||||
final $Val _value;
|
||||
// ignore: unused_field
|
||||
final $Res Function($Val) _then;
|
||||
|
||||
/// Create a copy of KnowledgeBaseState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({
|
||||
Object? isLoading = null,
|
||||
Object? chunkCount = null,
|
||||
Object? successMessage = freezed,
|
||||
Object? errorMessage = freezed,
|
||||
}) {
|
||||
return _then(
|
||||
_value.copyWith(
|
||||
isLoading: null == isLoading
|
||||
? _value.isLoading
|
||||
: isLoading // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
chunkCount: null == chunkCount
|
||||
? _value.chunkCount
|
||||
: chunkCount // ignore: cast_nullable_to_non_nullable
|
||||
as int,
|
||||
successMessage: freezed == successMessage
|
||||
? _value.successMessage
|
||||
: successMessage // ignore: cast_nullable_to_non_nullable
|
||||
as String?,
|
||||
errorMessage: freezed == errorMessage
|
||||
? _value.errorMessage
|
||||
: errorMessage // ignore: cast_nullable_to_non_nullable
|
||||
as String?,
|
||||
)
|
||||
as $Val,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract class _$$KnowledgeBaseStateImplCopyWith<$Res>
|
||||
implements $KnowledgeBaseStateCopyWith<$Res> {
|
||||
factory _$$KnowledgeBaseStateImplCopyWith(
|
||||
_$KnowledgeBaseStateImpl value,
|
||||
$Res Function(_$KnowledgeBaseStateImpl) then,
|
||||
) = __$$KnowledgeBaseStateImplCopyWithImpl<$Res>;
|
||||
@override
|
||||
@useResult
|
||||
$Res call({
|
||||
bool isLoading,
|
||||
int chunkCount,
|
||||
String? successMessage,
|
||||
String? errorMessage,
|
||||
});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$$KnowledgeBaseStateImplCopyWithImpl<$Res>
|
||||
extends _$KnowledgeBaseStateCopyWithImpl<$Res, _$KnowledgeBaseStateImpl>
|
||||
implements _$$KnowledgeBaseStateImplCopyWith<$Res> {
|
||||
__$$KnowledgeBaseStateImplCopyWithImpl(
|
||||
_$KnowledgeBaseStateImpl _value,
|
||||
$Res Function(_$KnowledgeBaseStateImpl) _then,
|
||||
) : super(_value, _then);
|
||||
|
||||
/// Create a copy of KnowledgeBaseState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({
|
||||
Object? isLoading = null,
|
||||
Object? chunkCount = null,
|
||||
Object? successMessage = freezed,
|
||||
Object? errorMessage = freezed,
|
||||
}) {
|
||||
return _then(
|
||||
_$KnowledgeBaseStateImpl(
|
||||
isLoading: null == isLoading
|
||||
? _value.isLoading
|
||||
: isLoading // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
chunkCount: null == chunkCount
|
||||
? _value.chunkCount
|
||||
: chunkCount // ignore: cast_nullable_to_non_nullable
|
||||
as int,
|
||||
successMessage: freezed == successMessage
|
||||
? _value.successMessage
|
||||
: successMessage // ignore: cast_nullable_to_non_nullable
|
||||
as String?,
|
||||
errorMessage: freezed == errorMessage
|
||||
? _value.errorMessage
|
||||
: errorMessage // ignore: cast_nullable_to_non_nullable
|
||||
as String?,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class _$KnowledgeBaseStateImpl implements _KnowledgeBaseState {
|
||||
const _$KnowledgeBaseStateImpl({
|
||||
this.isLoading = false,
|
||||
this.chunkCount = 0,
|
||||
this.successMessage,
|
||||
this.errorMessage,
|
||||
});
|
||||
|
||||
@override
|
||||
@JsonKey()
|
||||
final bool isLoading;
|
||||
@override
|
||||
@JsonKey()
|
||||
final int chunkCount;
|
||||
@override
|
||||
final String? successMessage;
|
||||
@override
|
||||
final String? errorMessage;
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'KnowledgeBaseState(isLoading: $isLoading, chunkCount: $chunkCount, successMessage: $successMessage, errorMessage: $errorMessage)';
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _$KnowledgeBaseStateImpl &&
|
||||
(identical(other.isLoading, isLoading) ||
|
||||
other.isLoading == isLoading) &&
|
||||
(identical(other.chunkCount, chunkCount) ||
|
||||
other.chunkCount == chunkCount) &&
|
||||
(identical(other.successMessage, successMessage) ||
|
||||
other.successMessage == successMessage) &&
|
||||
(identical(other.errorMessage, errorMessage) ||
|
||||
other.errorMessage == errorMessage));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(
|
||||
runtimeType,
|
||||
isLoading,
|
||||
chunkCount,
|
||||
successMessage,
|
||||
errorMessage,
|
||||
);
|
||||
|
||||
/// Create a copy of KnowledgeBaseState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
_$$KnowledgeBaseStateImplCopyWith<_$KnowledgeBaseStateImpl> get copyWith =>
|
||||
__$$KnowledgeBaseStateImplCopyWithImpl<_$KnowledgeBaseStateImpl>(
|
||||
this,
|
||||
_$identity,
|
||||
);
|
||||
}
|
||||
|
||||
abstract class _KnowledgeBaseState implements KnowledgeBaseState {
|
||||
const factory _KnowledgeBaseState({
|
||||
final bool isLoading,
|
||||
final int chunkCount,
|
||||
final String? successMessage,
|
||||
final String? errorMessage,
|
||||
}) = _$KnowledgeBaseStateImpl;
|
||||
|
||||
@override
|
||||
bool get isLoading;
|
||||
@override
|
||||
int get chunkCount;
|
||||
@override
|
||||
String? get successMessage;
|
||||
@override
|
||||
String? get errorMessage;
|
||||
|
||||
/// Create a copy of KnowledgeBaseState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
_$$KnowledgeBaseStateImplCopyWith<_$KnowledgeBaseStateImpl> get copyWith =>
|
||||
throw _privateConstructorUsedError;
|
||||
}
|
||||
697
lib/presentation/settings/settings_page.dart
Normal file
697
lib/presentation/settings/settings_page.dart
Normal file
@@ -0,0 +1,697 @@
|
||||
import 'package:auto_route/auto_route.dart';
|
||||
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/presentation/settings/ai_model_settings_controller.dart';
|
||||
import 'package:trainhub_flutter/presentation/settings/ai_model_settings_state.dart';
|
||||
|
||||
@RoutePage()
|
||||
class SettingsPage extends ConsumerWidget {
|
||||
const SettingsPage({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final modelState = ref.watch(aiModelSettingsControllerProvider);
|
||||
final controller =
|
||||
ref.read(aiModelSettingsControllerProvider.notifier);
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: AppColors.surface,
|
||||
body: Column(
|
||||
children: [
|
||||
// ── Top bar ──────────────────────────────────────────────────────
|
||||
_TopBar(onBack: () => context.router.maybePop()),
|
||||
|
||||
// ── Scrollable content ──────────────────────────────────────────
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(UIConstants.pagePadding),
|
||||
child: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 680),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Page title
|
||||
Text(
|
||||
'Settings',
|
||||
style: GoogleFonts.inter(
|
||||
fontSize: 22,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: AppColors.textPrimary,
|
||||
letterSpacing: -0.3,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: UIConstants.spacing32),
|
||||
|
||||
// AI Models section
|
||||
_AiModelsSection(
|
||||
modelState: modelState,
|
||||
onDownload: controller.downloadAll,
|
||||
onValidate: controller.validateModels,
|
||||
),
|
||||
|
||||
const SizedBox(height: UIConstants.spacing32),
|
||||
|
||||
// Knowledge Base section
|
||||
_KnowledgeBaseSection(
|
||||
onTap: () => context.router
|
||||
.push(const KnowledgeBaseRoute()),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// 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,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user