Bring projects, wikis, and teams together with AI. AppFlowy is the AI collaborative workspace where you achieve more without losing control of your data. The leading open source Notion alternative.
Dart blogconfluence-alternativecontent-managementcontent-servicesdocumentationflutternote-takingnotion-alternativeproject-managementtask-managementteam-collaborationwiki
feat: improve local ai settings page UI (#7643)
Richard Shiue3a879b01865c
diff --git a/frontend/appflowy_flutter/lib/workspace/application/settings/ai/download_offline_ai_app_bloc.dart b/frontend/appflowy_flutter/lib/workspace/application/settings/ai/download_offline_ai_app_bloc.dartdeleted file mode 100644index 185a8c049f..0000000000--- a/frontend/appflowy_flutter/lib/workspace/application/settings/ai/download_offline_ai_app_bloc.dart+++ /dev/null@@ -1,41 +0,0 @@-import 'dart:async';--import 'package:appflowy_backend/dispatch/dispatch.dart';-import 'package:bloc/bloc.dart';-import 'package:freezed_annotation/freezed_annotation.dart';-import 'package:url_launcher/url_launcher.dart' show launchUrl;-part 'download_offline_ai_app_bloc.freezed.dart';--class DownloadOfflineAIBloc- extends Bloc<DownloadOfflineAIEvent, DownloadOfflineAIState> {- DownloadOfflineAIBloc() : super(const DownloadOfflineAIState()) {- on<DownloadOfflineAIEvent>(_handleEvent);- }-- Future<void> _handleEvent(- DownloadOfflineAIEvent event,- Emitter<DownloadOfflineAIState> emit,- ) async {- await event.when(- started: () async {- final result = await AIEventGetLocalAIDownloadLink().send();- await result.fold(- (app) async {- await launchUrl(Uri.parse(app.link));- },- (err) {},- );- },- );- }-}--@freezed-class DownloadOfflineAIEvent with _$DownloadOfflineAIEvent {- const factory DownloadOfflineAIEvent.started() = _Started;-}--@freezed-class DownloadOfflineAIState with _$DownloadOfflineAIState {- const factory DownloadOfflineAIState() = _DownloadOfflineAIState;-}diff --git a/frontend/appflowy_flutter/lib/workspace/application/settings/ai/local_ai_bloc.dart b/frontend/appflowy_flutter/lib/workspace/application/settings/ai/local_ai_bloc.dartindex 66ba7fe572..24befd9480 100644--- a/frontend/appflowy_flutter/lib/workspace/application/settings/ai/local_ai_bloc.dart+++ b/frontend/appflowy_flutter/lib/workspace/application/settings/ai/local_ai_bloc.dart@@ -1,94 +1,121 @@import 'dart:async';import 'package:appflowy_backend/dispatch/dispatch.dart';+import 'package:appflowy_backend/log.dart';import 'package:appflowy_backend/protobuf/flowy-ai/entities.pb.dart';-import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';import 'package:appflowy_result/appflowy_result.dart';import 'package:bloc/bloc.dart';import 'package:freezed_annotation/freezed_annotation.dart';++import 'local_llm_listener.dart';+part 'local_ai_bloc.freezed.dart';-class LocalAIToggleBloc extends Bloc<LocalAIToggleEvent, LocalAIToggleState> {- LocalAIToggleBloc() : super(const LocalAIToggleState()) {- on<LocalAIToggleEvent>(_handleEvent);+class LocalAiPluginBloc extends Bloc<LocalAiPluginEvent, LocalAiPluginState> {+ LocalAiPluginBloc() : super(const LoadingLocalAiPluginState()) {+ on<LocalAiPluginEvent>(_handleEvent);+ _startListening();+ _getLocalAiState();+ }++ final listener = LocalAIStateListener();++ @override+ Future<void> close() async {+ await listener.stop();+ return super.close();}Future<void> _handleEvent(- LocalAIToggleEvent event,- Emitter<LocalAIToggleState> emit,+ LocalAiPluginEvent event,+ Emitter<LocalAiPluginState> emit,) async {await event.when(- started: () async {- final result = await AIEventGetLocalAIState().send();- _handleResult(emit, result);- },- toggle: () async {+ didReceiveAiState: (aiState) {emit(- state.copyWith(- pageIndicator: const LocalAIToggleStateIndicator.loading(),+ ReadyLocalAiPluginState(+ isEnabled: aiState.enabled,+ runningState: aiState.state,+ lackOfResource:+ aiState.hasLackOfResource() ? aiState.lackOfResource : null,),);- unawaited(- AIEventToggleLocalAI().send().then(- (result) {- if (!isClosed) {- add(LocalAIToggleEvent.handleResult(result));- }- },- ),+ },+ didReceiveLackOfResources: (resources) {+ if (state case final ReadyLocalAiPluginState readyState) {+ emit(+ ReadyLocalAiPluginState(+ isEnabled: readyState.isEnabled,+ runningState: readyState.runningState,+ lackOfResource: resources,+ ),+ );+ }+ },+ toggle: () async {+ emit(LoadingLocalAiPluginState());+ await AIEventToggleLocalAI().send().fold(+ (aiState) {+ add(LocalAiPluginEvent.didReceiveAiState(aiState));+ },+ Log.error,);},- handleResult: (result) {- _handleResult(emit, result);+ restart: () async {+ emit(LoadingLocalAiPluginState());+ await AIEventRestartLocalAI().send();},);}- void _handleResult(- Emitter<LocalAIToggleState> emit,- FlowyResult<LocalAIPB, FlowyError> result,- ) {- result.fold(- (localAI) {- emit(- state.copyWith(- pageIndicator:- LocalAIToggleStateIndicator.isEnabled(localAI.enabled),- ),- );+ void _startListening() {+ listener.start(+ stateCallback: (pluginState) {+ add(LocalAiPluginEvent.didReceiveAiState(pluginState));},- (err) {- emit(- state.copyWith(- pageIndicator: LocalAIToggleStateIndicator.error(err),- ),- );+ resourceCallback: (data) {+ add(LocalAiPluginEvent.didReceiveLackOfResources(data));},);}++ void _getLocalAiState() {+ AIEventGetLocalAIState().send().fold(+ (aiState) {+ add(LocalAiPluginEvent.didReceiveAiState(aiState));+ },+ Log.error,+ );+ }}@freezed-class LocalAIToggleEvent with _$LocalAIToggleEvent {- const factory LocalAIToggleEvent.started() = _Started;- const factory LocalAIToggleEvent.toggle() = _Toggle;- const factory LocalAIToggleEvent.handleResult(- FlowyResult<LocalAIPB, FlowyError> result,- ) = _HandleResult;+class LocalAiPluginEvent with _$LocalAiPluginEvent {+ const factory LocalAiPluginEvent.didReceiveAiState(LocalAIPB aiState) =+ _DidReceiveAiState;+ const factory LocalAiPluginEvent.didReceiveLackOfResources(+ LackOfAIResourcePB resources,+ ) = _DidReceiveLackOfResources;+ const factory LocalAiPluginEvent.toggle() = _Toggle;+ const factory LocalAiPluginEvent.restart() = _Restart;}-@freezed-class LocalAIToggleState with _$LocalAIToggleState {- const factory LocalAIToggleState({- @Default(LocalAIToggleStateIndicator.loading())- LocalAIToggleStateIndicator pageIndicator,- }) = _LocalAIToggleState;+sealed class LocalAiPluginState {+ const LocalAiPluginState();}-@freezed-class LocalAIToggleStateIndicator with _$LocalAIToggleStateIndicator {- // when start downloading the model- const factory LocalAIToggleStateIndicator.error(FlowyError error) = _OnError;- const factory LocalAIToggleStateIndicator.isEnabled(bool isEnabled) = _Ready;- const factory LocalAIToggleStateIndicator.loading() = _Loading;+class ReadyLocalAiPluginState extends LocalAiPluginState {+ const ReadyLocalAiPluginState({+ required this.isEnabled,+ required this.runningState,+ required this.lackOfResource,+ });++ final bool isEnabled;+ final RunningStatePB runningState;+ final LackOfAIResourcePB? lackOfResource;+}++class LoadingLocalAiPluginState extends LocalAiPluginState {+ const LoadingLocalAiPluginState();}diff --git a/frontend/appflowy_flutter/lib/workspace/application/settings/ai/local_ai_on_boarding_bloc.dart b/frontend/appflowy_flutter/lib/workspace/application/settings/ai/local_ai_on_boarding_bloc.dartindex 2c1bf34a87..3bb26a182b 100644--- a/frontend/appflowy_flutter/lib/workspace/application/settings/ai/local_ai_on_boarding_bloc.dart+++ b/frontend/appflowy_flutter/lib/workspace/application/settings/ai/local_ai_on_boarding_bloc.dart@@ -26,7 +26,7 @@ class LocalAIOnBoardingBloc_dispatch();}- Future<void> _onPaymentSuccessful() async {+ void _onPaymentSuccessful() {if (isClosed) {return;}diff --git a/frontend/appflowy_flutter/lib/workspace/application/settings/ai/local_ai_setting_panel_bloc.dart b/frontend/appflowy_flutter/lib/workspace/application/settings/ai/local_ai_setting_panel_bloc.dartdeleted file mode 100644index f6d5ef949d..0000000000--- a/frontend/appflowy_flutter/lib/workspace/application/settings/ai/local_ai_setting_panel_bloc.dart+++ /dev/null@@ -1,92 +0,0 @@-import 'dart:async';--import 'package:appflowy/workspace/application/settings/ai/local_llm_listener.dart';-import 'package:appflowy_backend/dispatch/dispatch.dart';-import 'package:appflowy_backend/log.dart';-import 'package:appflowy_backend/protobuf/flowy-ai/entities.pb.dart';-import 'package:appflowy_result/appflowy_result.dart';-import 'package:bloc/bloc.dart';-import 'package:freezed_annotation/freezed_annotation.dart';--part 'local_ai_setting_panel_bloc.freezed.dart';--class LocalAISettingPanelBloc- extends Bloc<LocalAISettingPanelEvent, LocalAISettingPanelState> {- LocalAISettingPanelBloc()- : listener = LocalAIStateListener(),- super(const LocalAISettingPanelState()) {- on<LocalAISettingPanelEvent>(_handleEvent);-- listener.start(- stateCallback: (newState) {- if (!isClosed) {- add(LocalAISettingPanelEvent.updateAIState(newState));- }- },- );-- AIEventGetLocalAIState().send().fold(- (localAIState) {- if (!isClosed) {- add(LocalAISettingPanelEvent.updateAIState(localAIState));- }- },- Log.error,- );- }-- final LocalAIStateListener listener;-- /// Handles incoming events and dispatches them to the appropriate handler.- Future<void> _handleEvent(- LocalAISettingPanelEvent event,- Emitter<LocalAISettingPanelState> emit,- ) async {- event.when(- updateAIState: (LocalAIPB pluginState) {- if (pluginState.isPluginExecutableReady) {- emit(- state.copyWith(- runningState: pluginState.state,- progressIndicator: const LocalAIProgress.checkPluginState(),- ),- );- } else {- emit(- state.copyWith(- progressIndicator: const LocalAIProgress.downloadLocalAIApp(),- ),- );- }- },- );- }-- @override- Future<void> close() async {- await listener.stop();- return super.close();- }-}--@freezed-class LocalAISettingPanelEvent with _$LocalAISettingPanelEvent {- const factory LocalAISettingPanelEvent.updateAIState(- LocalAIPB aiState,- ) = _UpdateAIState;-}--@freezed-class LocalAISettingPanelState with _$LocalAISettingPanelState {- const factory LocalAISettingPanelState({- LocalAIProgress? progressIndicator,- @Default(RunningStatePB.Connecting) RunningStatePB runningState,- }) = _LocalAIChatSettingState;-}--@freezed-class LocalAIProgress with _$LocalAIProgress {- const factory LocalAIProgress.checkPluginState() = _CheckPluginStateProgress;- const factory LocalAIProgress.downloadLocalAIApp() =- _DownloadLocalAIAppProgress;-}diff --git a/frontend/appflowy_flutter/lib/workspace/application/settings/ai/ollama_setting_bloc.dart b/frontend/appflowy_flutter/lib/workspace/application/settings/ai/ollama_setting_bloc.dartindex 8555d8cdc8..f5c4209028 100644--- a/frontend/appflowy_flutter/lib/workspace/application/settings/ai/ollama_setting_bloc.dart+++ b/frontend/appflowy_flutter/lib/workspace/application/settings/ai/ollama_setting_bloc.dart@@ -80,11 +80,9 @@ class OllamaSettingBloc extends Bloc<OllamaSettingEvent, OllamaSettingState> {}add(OllamaSettingEvent.updateSetting(setting));AIEventUpdateLocalAISetting(setting).send().fold(- (_) {- Log.info('AI setting updated successfully');- },- (err) => Log.error("update ai setting failed: $err"),- );+ (_) => Log.info('AI setting updated successfully'),+ (err) => Log.error("update ai setting failed: $err"),+ );},);}diff --git a/frontend/appflowy_flutter/lib/workspace/application/settings/ai/plugin_state_bloc.dart b/frontend/appflowy_flutter/lib/workspace/application/settings/ai/plugin_state_bloc.dartdeleted file mode 100644index 4c3130ea00..0000000000--- a/frontend/appflowy_flutter/lib/workspace/application/settings/ai/plugin_state_bloc.dart+++ /dev/null@@ -1,146 +0,0 @@-import 'dart:async';--import 'package:appflowy/workspace/application/settings/ai/local_llm_listener.dart';-import 'package:appflowy_backend/dispatch/dispatch.dart';-import 'package:appflowy_backend/log.dart';-import 'package:appflowy_backend/protobuf/flowy-ai/entities.pb.dart';-import 'package:bloc/bloc.dart';-import 'package:freezed_annotation/freezed_annotation.dart';--part 'plugin_state_bloc.freezed.dart';--class PluginStateBloc extends Bloc<PluginStateEvent, PluginStateState> {- PluginStateBloc()- : listener = LocalAIStateListener(),- super(- const PluginStateState(- action: PluginStateAction.unknown(),- ),- ) {- listener.start(- stateCallback: (pluginState) {- if (!isClosed) {- add(PluginStateEvent.updateLocalAIState(pluginState));- }- },- resourceCallback: (data) {- if (!isClosed) {- add(PluginStateEvent.resourceStateChange(data));- }- },- );-- on<PluginStateEvent>(_handleEvent);- }-- final LocalAIStateListener listener;-- @override- Future<void> close() async {- await listener.stop();- return super.close();- }-- Future<void> _handleEvent(- PluginStateEvent event,- Emitter<PluginStateState> emit,- ) async {- await event.when(- started: () async {- final result = await AIEventGetLocalAIState().send();- result.fold(- (pluginState) {- if (!isClosed) {- add(PluginStateEvent.updateLocalAIState(pluginState));- }- },- (err) => Log.error(err.toString()),- );- },- updateLocalAIState: (LocalAIPB aiState) {- // if the offline ai is not started, ask user to start it- if (aiState.hasLackOfResource()) {- emit(- PluginStateState(- action: PluginStateAction.lackOfResource(aiState.lackOfResource),- ),- );- return;- }-- // Chech state of the plugin- switch (aiState.state) {- case RunningStatePB.ReadyToRun:- emit(- const PluginStateState(- action: PluginStateAction.readToRun(),- ),- );-- case RunningStatePB.Connecting:- emit(- const PluginStateState(- action: PluginStateAction.initializingPlugin(),- ),- );- case RunningStatePB.Connected:- emit(- const PluginStateState(- action: PluginStateAction.initializingPlugin(),- ),- );- break;- case RunningStatePB.Running:- emit(const PluginStateState(action: PluginStateAction.running()));- break;- case RunningStatePB.Stopped:- emit(- state.copyWith(action: const PluginStateAction.restartPlugin()),- );- default:- break;- }- },- restartLocalAI: () async {- emit(- const PluginStateState(action: PluginStateAction.restartPlugin()),- );- unawaited(AIEventRestartLocalAI().send());- },- resourceStateChange: (data) {- emit(- PluginStateState(- action: PluginStateAction.lackOfResource(data.resourceDesc),- ),- );- },- );- }-}--@freezed-class PluginStateEvent with _$PluginStateEvent {- const factory PluginStateEvent.started() = _Started;- const factory PluginStateEvent.updateLocalAIState(LocalAIPB aiState) =- _UpdateLocalAIState;- const factory PluginStateEvent.restartLocalAI() = _RestartLocalAI;- const factory PluginStateEvent.resourceStateChange(LackOfAIResourcePB data) =- _ResourceStateChange;-}--@freezed-class PluginStateState with _$PluginStateState {- const factory PluginStateState({- required PluginStateAction action,- }) = _PluginStateState;-}--@freezed-class PluginStateAction with _$PluginStateAction {- const factory PluginStateAction.unknown() = _Unknown;- const factory PluginStateAction.readToRun() = _ReadyToRun;- const factory PluginStateAction.initializingPlugin() = _InitializingPlugin;- const factory PluginStateAction.running() = _PluginRunning;- const factory PluginStateAction.restartPlugin() = _RestartPlugin;- const factory PluginStateAction.lackOfResource(String desc) = _LackOfResource;-}diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/init_local_ai.dart b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/init_local_ai.dartdeleted file mode 100644index 2de410a5e5..0000000000--- a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/init_local_ai.dart+++ /dev/null@@ -1,82 +0,0 @@-import 'package:appflowy/generated/flowy_svgs.g.dart';-import 'package:appflowy/generated/locale_keys.g.dart';-import 'package:appflowy/workspace/application/settings/ai/local_ai_setting_panel_bloc.dart';-import 'package:appflowy_backend/protobuf/flowy-ai/entities.pb.dart';-import 'package:easy_localization/easy_localization.dart';-import 'package:flowy_infra_ui/style_widget/text.dart';-import 'package:flowy_infra_ui/widget/spacing.dart';-import 'package:flutter/material.dart';-import 'package:flutter_bloc/flutter_bloc.dart';--class InitLocalAIIndicator extends StatelessWidget {- const InitLocalAIIndicator({super.key});-- @override- Widget build(BuildContext context) {- return DecoratedBox(- decoration: const BoxDecoration(- color: Color(0xFFEDF7ED),- borderRadius: BorderRadius.all(- Radius.circular(4),- ),- ),- child: Padding(- padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4),- child: BlocBuilder<LocalAISettingPanelBloc, LocalAISettingPanelState>(- builder: (context, state) {- switch (state.runningState) {- case RunningStatePB.Connecting:- case RunningStatePB.Connected:- return Row(- children: [- const HSpace(8),- Expanded(- child: FlowyText(- LocaleKeys.settings_aiPage_keys_localAIInitializing- .tr(),- fontSize: 11,- color: const Color(0xFF1E4620),- maxLines: 3,- ),- ),- ],- );- case RunningStatePB.Running:- return SizedBox(- height: 30,- child: Row(- children: [- const HSpace(8),- const FlowySvg(- FlowySvgs.download_success_s,- color: Color(0xFF2E7D32),- ),- const HSpace(6),- FlowyText(- LocaleKeys.settings_aiPage_keys_localAILoaded.tr(),- fontSize: 11,- color: const Color(0xFF1E4620),- ),- ],- ),- );- case RunningStatePB.Stopped:- return Row(- children: [- const HSpace(8),- FlowyText(- LocaleKeys.settings_aiPage_keys_localAIStopped.tr(),- fontSize: 11,- color: const Color(0xFFC62828),- ),- ],- );- default:- return const SizedBox.shrink();- }- },- ),- ),- );- }-}diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/local_ai_setting.dart b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/local_ai_setting.dartindex 57a72b6ca1..080dc426d1 100644--- a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/local_ai_setting.dart+++ b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/local_ai_setting.dart@@ -1,130 +1,174 @@-import 'package:flutter/material.dart';-import 'package:appflowy/generated/locale_keys.g.dart';import 'package:appflowy/workspace/application/settings/ai/local_ai_bloc.dart';-import 'package:appflowy/workspace/presentation/settings/pages/setting_ai_view/local_ai_setting_panel.dart';import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';import 'package:appflowy/workspace/presentation/widgets/toggle/toggle.dart';+import 'package:appflowy_backend/protobuf/flowy-ai/protobuf.dart';import 'package:easy_localization/easy_localization.dart';import 'package:expandable/expandable.dart';import 'package:flowy_infra_ui/style_widget/text.dart';import 'package:flowy_infra_ui/widget/spacing.dart';+import 'package:flutter/material.dart';import 'package:flutter_bloc/flutter_bloc.dart';-class LocalAISetting extends StatelessWidget {+import 'ollama_setting.dart';+import 'plugin_status_indicator.dart';++class LocalAISetting extends StatefulWidget {const LocalAISetting({super.key});+ @override+ State<LocalAISetting> createState() => _LocalAISettingState();+}++class _LocalAISettingState extends State<LocalAISetting> {+ final expandableController = ExpandableController(initialExpanded: false);++ @override+ void dispose() {+ expandableController.dispose();+ super.dispose();+ }+@overrideWidget build(BuildContext context) {return BlocProvider(- create: (context) =>- LocalAIToggleBloc()..add(const LocalAIToggleEvent.started()),- child: Padding(- padding: const EdgeInsets.symmetric(vertical: 6),- child: ExpandableNotifier(- child: BlocListener<LocalAIToggleBloc, LocalAIToggleState>(- listener: (context, state) {- final controller =- ExpandableController.of(context, required: true)!;-- state.pageIndicator.when(- error: (_) => controller.expanded = true,- isEnabled: (enabled) => controller.expanded = enabled,- loading: () => controller.expanded = true,- );- },- child: ExpandablePanel(- theme: const ExpandableThemeData(- headerAlignment: ExpandablePanelHeaderAlignment.center,- tapBodyToCollapse: false,- hasIcon: false,- tapBodyToExpand: false,- tapHeaderToExpand: false,+ create: (context) => LocalAiPluginBloc(),+ child: BlocConsumer<LocalAiPluginBloc, LocalAiPluginState>(+ listener: (context, state) {+ final newIsExpanded = switch (state) {+ final ReadyLocalAiPluginState readyLocalAiToggleState =>+ readyLocalAiToggleState.isEnabled,+ _ => false,+ };+ expandableController.value = newIsExpanded;+ },+ builder: (context, state) {+ return ExpandablePanel(+ controller: expandableController,+ theme: ExpandableThemeData(+ tapBodyToCollapse: false,+ hasIcon: false,+ tapBodyToExpand: false,+ tapHeaderToExpand: false,+ ),+ header: LocalAiSettingHeader(+ isEnabled: state is ReadyLocalAiPluginState && state.isEnabled,+ isToggleable: state is ReadyLocalAiPluginState,+ ),+ collapsed: const SizedBox.shrink(),+ expanded: Padding(+ padding: EdgeInsets.only(top: 12),+ child: LocalAISettingPanel(),+ ),+ );+ },+ ),+ );+ }+}++class LocalAiSettingHeader extends StatelessWidget {+ const LocalAiSettingHeader({+ super.key,+ required this.isEnabled,+ required this.isToggleable,+ });++ final bool isEnabled;+ final bool isToggleable;++ @override+ Widget build(BuildContext context) {+ return Row(+ children: [+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ FlowyText.medium(+ LocaleKeys.settings_aiPage_keys_localAIToggleTitle.tr(),),- header: const LocalAISettingHeader(),- collapsed: const SizedBox.shrink(),- expanded: Column(- children: [- const VSpace(12),- DecoratedBox(- decoration: BoxDecoration(- color:- Theme.of(context).colorScheme.surfaceContainerHighest,- borderRadius: const BorderRadius.all(Radius.circular(4)),- ),- child: const Padding(- padding:- EdgeInsets.symmetric(horizontal: 12, vertical: 6),- child: LocalAISettingPanel(),- ),- ),- ],+ const VSpace(4),+ FlowyText(+ LocaleKeys.settings_aiPage_keys_localAIToggleSubTitle.tr(),+ maxLines: 3,+ fontSize: 12,),+ ],+ ),+ ),+ IgnorePointer(+ ignoring: !isToggleable,+ child: Opacity(+ opacity: isToggleable ? 1 : 0.5,+ child: Toggle(+ value: isEnabled,+ onChanged: (_) => _onToggleChanged(context),),),),- ),+ ],);}++ void _onToggleChanged(BuildContext context) {+ if (isEnabled) {+ showConfirmDialog(+ context: context,+ title: LocaleKeys.settings_aiPage_keys_disableLocalAITitle.tr(),+ description:+ LocaleKeys.settings_aiPage_keys_disableLocalAIDescription.tr(),+ confirmLabel: LocaleKeys.button_confirm.tr(),+ onConfirm: () {+ context+ .read<LocalAiPluginBloc>()+ .add(const LocalAiPluginEvent.toggle());+ },+ );+ } else {+ context.read<LocalAiPluginBloc>().add(const LocalAiPluginEvent.toggle());+ }+ }}-class LocalAISettingHeader extends StatelessWidget {- const LocalAISettingHeader({super.key});+class LocalAISettingPanel extends StatelessWidget {+ const LocalAISettingPanel({super.key});@overrideWidget build(BuildContext context) {- return BlocBuilder<LocalAIToggleBloc, LocalAIToggleState>(+ return BlocBuilder<LocalAiPluginBloc, LocalAiPluginState>(builder: (context, state) {- return state.pageIndicator.when(- error: (error) => SizedBox.shrink(),- loading: () => const SizedBox.shrink(),- isEnabled: (isEnabled) {- return Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Row(- children: [- FlowyText.medium(- LocaleKeys.settings_aiPage_keys_localAIToggleTitle.tr(),- ),- const Spacer(),- Toggle(- value: isEnabled,- onChanged: (_) {- if (isEnabled) {- showConfirmDialog(- context: context,- title: LocaleKeys- .settings_aiPage_keys_disableLocalAITitle- .tr(),- description: LocaleKeys- .settings_aiPage_keys_disableLocalAIDescription- .tr(),- confirmLabel: LocaleKeys.button_confirm.tr(),- onConfirm: () => context- .read<LocalAIToggleBloc>()- .add(const LocalAIToggleEvent.toggle()),- );- } else {- context- .read<LocalAIToggleBloc>()- .add(const LocalAIToggleEvent.toggle());- }- },- ),- ],- ),- const VSpace(4),- FlowyText(- LocaleKeys.settings_aiPage_keys_localAIToggleSubTitle.tr(),- maxLines: 3,- fontSize: 12,- ),- ],- );- },+ if (state is! ReadyLocalAiPluginState) {+ return const SizedBox.shrink();+ }++ final showIndicator = _showIndicator(state);+ final showSettings = _showSettings(state);++ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ if (showIndicator) const LocalAIStatusIndicator(),+ if (showSettings && showIndicator) const VSpace(10),+ if (showSettings) OllamaSettingPage(),+ ],);},);}++ bool _showIndicator(ReadyLocalAiPluginState state) {+ return state.runningState != RunningStatePB.Running ||+ state.lackOfResource != null;+ }++ bool _showSettings(ReadyLocalAiPluginState state) {+ return ![+ RunningStatePB.Connecting,+ RunningStatePB.Connected,+ ].contains(state.runningState) &&+ (state.lackOfResource == null ||+ state.lackOfResource!.resourceType ==+ LackOfAIResourceTypePB.MissingModel);+ }}diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/local_ai_setting_panel.dart b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/local_ai_setting_panel.dartdeleted file mode 100644index 5357db5c91..0000000000--- a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/local_ai_setting_panel.dart+++ /dev/null@@ -1,32 +0,0 @@-import 'package:appflowy/workspace/application/settings/ai/local_ai_setting_panel_bloc.dart';-import 'package:appflowy/workspace/presentation/settings/pages/setting_ai_view/ollma_setting.dart';-import 'package:flowy_infra_ui/widget/spacing.dart';-import 'package:flutter/material.dart';-import 'package:flutter_bloc/flutter_bloc.dart';-import 'plugin_state.dart';--class LocalAISettingPanel extends StatelessWidget {- const LocalAISettingPanel({super.key});-- @override- Widget build(BuildContext context) {- return BlocProvider(- create: (context) => LocalAISettingPanelBloc(),- child: Padding(- padding: const EdgeInsets.symmetric(vertical: 6),- child: BlocBuilder<LocalAISettingPanelBloc, LocalAISettingPanelState>(- builder: (context, state) {- return Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- OllamaSettingPage(),- VSpace(6),- PluginStateIndicator(),- ],- );- },- ),- ),- );- }-}diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/ollama_setting.dart b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/ollama_setting.dartnew file mode 100644index 0000000000..2abcb552d1--- /dev/null+++ b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/ollama_setting.dart@@ -0,0 +1,114 @@+import 'package:appflowy/workspace/application/settings/ai/ollama_setting_bloc.dart';+import 'package:flowy_infra_ui/style_widget/button.dart';+import 'package:flowy_infra_ui/style_widget/text.dart';+import 'package:flowy_infra_ui/style_widget/text_field.dart';+import 'package:flowy_infra_ui/widget/flowy_tooltip.dart';+import 'package:flowy_infra_ui/widget/spacing.dart';+import 'package:flutter/material.dart';+import 'package:flutter_bloc/flutter_bloc.dart';++class OllamaSettingPage extends StatelessWidget {+ const OllamaSettingPage({super.key});++ @override+ Widget build(BuildContext context) {+ return BlocProvider(+ create: (context) =>+ OllamaSettingBloc()..add(const OllamaSettingEvent.started()),+ child: BlocBuilder<OllamaSettingBloc, OllamaSettingState>(+ buildWhen: (previous, current) =>+ previous.inputItems != current.inputItems ||+ previous.isEdited != current.isEdited,+ builder: (context, state) {+ return Container(+ decoration: BoxDecoration(+ color: Theme.of(context).colorScheme.surfaceContainerHighest,+ borderRadius: const BorderRadius.all(Radius.circular(8.0)),+ ),+ padding: EdgeInsets.all(12),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ spacing: 10,+ children: [+ for (final item in state.inputItems)+ _SettingItemWidget(item: item),+ _SaveButton(isEdited: state.isEdited),+ ],+ ),+ );+ },+ ),+ );+ }+}++class _SettingItemWidget extends StatelessWidget {+ const _SettingItemWidget({required this.item});++ final SettingItem item;++ @override+ Widget build(BuildContext context) {+ return Column(+ key: ValueKey(item.content + item.settingType.title),+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ FlowyText(+ item.settingType.title,+ fontSize: 12,+ figmaLineHeight: 16,+ ),+ const VSpace(4),+ SizedBox(+ height: 32,+ child: FlowyTextField(+ hintText: item.hintText,+ text: item.content,+ onChanged: (content) {+ context.read<OllamaSettingBloc>().add(+ OllamaSettingEvent.onEdit(content, item.settingType),+ );+ },+ ),+ ),+ ],+ );+ }+}++class _SaveButton extends StatelessWidget {+ const _SaveButton({required this.isEdited});++ final bool isEdited;++ @override+ Widget build(BuildContext context) {+ return Align(+ alignment: AlignmentDirectional.centerEnd,+ child: FlowyTooltip(+ message: isEdited ? null : 'No changes',+ child: SizedBox(+ child: FlowyButton(+ text: FlowyText(+ 'Apply',+ figmaLineHeight: 20,+ color: Theme.of(context).colorScheme.onPrimary,+ ),+ disable: !isEdited,+ expandText: false,+ margin: EdgeInsets.symmetric(horizontal: 16.0, vertical: 6.0),+ backgroundColor: Theme.of(context).colorScheme.primary,+ hoverColor: Theme.of(context).colorScheme.primary.withAlpha(200),+ onTap: () {+ if (isEdited) {+ context+ .read<OllamaSettingBloc>()+ .add(const OllamaSettingEvent.submit());+ }+ },+ ),+ ),+ ),+ );+ }+}diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/ollma_setting.dart b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/ollma_setting.dartdeleted file mode 100644index 8af4e35914..0000000000--- a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/ollma_setting.dart+++ /dev/null@@ -1,168 +0,0 @@-import 'package:appflowy/core/helpers/url_launcher.dart';-import 'package:appflowy/generated/locale_keys.g.dart';-import 'package:appflowy/workspace/application/settings/ai/ollama_setting_bloc.dart';-import 'package:easy_localization/easy_localization.dart';-import 'package:flowy_infra/size.dart';-import 'package:flowy_infra_ui/style_widget/button.dart';-import 'package:flowy_infra_ui/style_widget/text.dart';-import 'package:flowy_infra_ui/style_widget/text_field.dart';-import 'package:flowy_infra_ui/widget/flowy_tooltip.dart';-import 'package:flowy_infra_ui/widget/spacing.dart';-import 'package:flutter/gestures.dart';-import 'package:flutter/material.dart';-import 'package:flutter_bloc/flutter_bloc.dart';--class OllamaSettingPage extends StatelessWidget {- const OllamaSettingPage({super.key});-- @override- Widget build(BuildContext context) {- return BlocProvider(- create: (context) =>- OllamaSettingBloc()..add(const OllamaSettingEvent.started()),- child: BlocBuilder<OllamaSettingBloc, OllamaSettingState>(- buildWhen: (previous, current) =>- previous.inputItems != current.inputItems ||- previous.isEdited != current.isEdited,- builder: (context, state) {- return Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- ListView.separated(- physics: NeverScrollableScrollPhysics(),- shrinkWrap: true,- itemCount: state.inputItems.length,- separatorBuilder: (_, __) => const VSpace(10),- itemBuilder: (context, index) {- final item = state.inputItems[index];- return _SettingItemWidget(item: item);- },- ),- const VSpace(6),- Opacity(- opacity: 0.6,- child: _InstallOllamaInstruction(),- ),- _SaveButton(isEdited: state.isEdited),- ],- );- },- ),- );- }-}--class _SettingItemWidget extends StatelessWidget {- const _SettingItemWidget({required this.item});- final SettingItem item;-- @override- Widget build(BuildContext context) {- return Column(- key: ValueKey(item.content + item.settingType.title),- crossAxisAlignment: CrossAxisAlignment.start,- children: [- FlowyText(item.settingType.title),- const VSpace(8),- FlowyTextField(- hintText: item.hintText,- text: item.content,- onChanged: (content) {- context.read<OllamaSettingBloc>().add(- OllamaSettingEvent.onEdit(content, item.settingType),- );- },- ),- ],- );- }-}--class _SaveButton extends StatelessWidget {- const _SaveButton({required this.isEdited});-- final bool isEdited;-- @override- Widget build(BuildContext context) {- final tooltipMessage = isEdited ? 'Click to apply changes' : 'No changes';- return SizedBox(- height: 50,- child: Row(- children: [- const Spacer(),- SizedBox(- width: 120,- child: FlowyTooltip(- message: tooltipMessage,- child: Opacity(- opacity: isEdited ? 1 : 0.5,- child: FlowyTextButton(- 'Apply',- mainAxisAlignment: MainAxisAlignment.center,- onPressed: isEdited- ? () {- context- .read<OllamaSettingBloc>()- .add(const OllamaSettingEvent.submit());- }- : null,- ),- ),- ),- ),- ],- ),- );- }-}--class _InstallOllamaInstruction extends StatelessWidget {- const _InstallOllamaInstruction();-- @override- Widget build(BuildContext context) {- return Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- RichText(- maxLines: 3,- textAlign: TextAlign.left,- text: TextSpan(- children: <TextSpan>[- TextSpan(- text:- "${LocaleKeys.settings_aiPage_keys_localAISetupInstruction1.tr()} ",- style: Theme.of(context)- .textTheme- .bodySmall!- .copyWith(height: 1.5),- ),- TextSpan(- text:- " ${LocaleKeys.settings_aiPage_keys_localAISetupInstruction2.tr()} ",- style: Theme.of(context).textTheme.bodyMedium!.copyWith(- fontSize: FontSizes.s14,- color: Theme.of(context).colorScheme.primary,- height: 1.5,- ),- recognizer: TapGestureRecognizer()- ..onTap = () => afLaunchUrlString(- "https://appflowy.com/guide/appflowy-local-ai-ollama",- ),- ),- TextSpan(- text:- " ${LocaleKeys.settings_aiPage_keys_localAISetupInstruction3.tr()} ",- style: Theme.of(context)- .textTheme- .bodySmall!- .copyWith(height: 1.5),- ),- ],- ),- ),- ],- );- }-}diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/plugin_state.dart b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/plugin_state.dartdeleted file mode 100644index ab9303b429..0000000000--- a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/plugin_state.dart+++ /dev/null@@ -1,248 +0,0 @@-import 'package:appflowy/core/helpers/url_launcher.dart';-import 'package:appflowy/generated/flowy_svgs.g.dart';-import 'package:appflowy/generated/locale_keys.g.dart';-import 'package:appflowy/workspace/application/settings/ai/download_offline_ai_app_bloc.dart';-import 'package:appflowy/workspace/application/settings/ai/plugin_state_bloc.dart';-import 'package:appflowy/workspace/presentation/settings/pages/setting_ai_view/init_local_ai.dart';-import 'package:easy_localization/easy_localization.dart';-import 'package:flowy_infra/size.dart';-import 'package:flowy_infra_ui/style_widget/button.dart';-import 'package:flowy_infra_ui/style_widget/text.dart';-import 'package:flowy_infra_ui/widget/spacing.dart';-import 'package:flutter/gestures.dart';-import 'package:flutter/material.dart';-import 'package:flutter_bloc/flutter_bloc.dart';--class PluginStateIndicator extends StatelessWidget {- const PluginStateIndicator({super.key});-- @override- Widget build(BuildContext context) {- return BlocProvider(- create: (context) =>- PluginStateBloc()..add(const PluginStateEvent.started()),- child: BlocBuilder<PluginStateBloc, PluginStateState>(- builder: (context, state) {- return state.action.when(- unknown: () => const SizedBox.shrink(),- readToRun: () => const _PrepareRunning(),- initializingPlugin: () => const InitLocalAIIndicator(),- running: () => const _LocalAIRunning(),- restartPlugin: () => const _RestartPluginButton(),- lackOfResource: (desc) => _LackOfResource(desc: desc),- );- },- ),- );- }-}--class _PrepareRunning extends StatelessWidget {- const _PrepareRunning();-- @override- Widget build(BuildContext context) {- return Row(- children: [- Expanded(- child: FlowyText(- LocaleKeys.settings_aiPage_keys_localAIStart.tr(),- maxLines: 3,- ),- ),- ],- );- }-}--class _RestartPluginButton extends StatelessWidget {- const _RestartPluginButton();-- @override- Widget build(BuildContext context) {- return Row(- children: [- const FlowySvg(- FlowySvgs.download_warn_s,- color: Color(0xFFC62828),- ),- const HSpace(6),- FlowyText(LocaleKeys.settings_aiPage_keys_failToLoadLocalAI.tr()),- const Spacer(),- SizedBox(- height: 30,- child: FlowyButton(- useIntrinsicWidth: true,- text:- FlowyText(LocaleKeys.settings_aiPage_keys_restartLocalAI.tr()),- onTap: () {- context.read<PluginStateBloc>().add(- const PluginStateEvent.restartLocalAI(),- );- },- ),- ),- ],- );- }-}--class _LocalAIRunning extends StatelessWidget {- const _LocalAIRunning();-- @override- Widget build(BuildContext context) {- return DecoratedBox(- decoration: const BoxDecoration(- color: Color(0xFFEDF7ED),- borderRadius: BorderRadius.all(- Radius.circular(4),- ),- ),- child: Padding(- padding: const EdgeInsets.symmetric(vertical: 4),- child: Row(- mainAxisAlignment: MainAxisAlignment.spaceBetween,- children: [- Flexible(- child: Row(- children: [- const HSpace(8),- const FlowySvg(- FlowySvgs.download_success_s,- color: Color(0xFF2E7D32),- ),- const HSpace(6),- Flexible(- child: FlowyText(- LocaleKeys.settings_aiPage_keys_localAIRunning.tr(),- fontSize: 11,- color: const Color(0xFF1E4620),- maxLines: 3,- ),- ),- ],- ),- ),- ],- ),- ),- );- }-}--class OpenOrDownloadOfflineAIApp extends StatelessWidget {- const OpenOrDownloadOfflineAIApp({required this.onRetry, super.key});-- final VoidCallback onRetry;-- @override- Widget build(BuildContext context) {- return BlocProvider(- create: (context) => DownloadOfflineAIBloc(),- child: BlocBuilder<DownloadOfflineAIBloc, DownloadOfflineAIState>(- builder: (context, state) {- return Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- RichText(- maxLines: 3,- textAlign: TextAlign.left,- text: TextSpan(- children: <TextSpan>[- TextSpan(- text:- "${LocaleKeys.settings_aiPage_keys_offlineAIInstruction1.tr()} ",- style: Theme.of(context)- .textTheme- .bodySmall!- .copyWith(height: 1.5),- ),- TextSpan(- text:- " ${LocaleKeys.settings_aiPage_keys_offlineAIInstruction2.tr()} ",- style: Theme.of(context).textTheme.bodyMedium!.copyWith(- fontSize: FontSizes.s14,- color: Theme.of(context).colorScheme.primary,- height: 1.5,- ),- recognizer: TapGestureRecognizer()- ..onTap = () => afLaunchUrlString(- "https://docs.appflowy.io/docs/appflowy/product/appflowy-ai-offline",- ),- ),- TextSpan(- text:- " ${LocaleKeys.settings_aiPage_keys_offlineAIInstruction3.tr()} ",- style: Theme.of(context)- .textTheme- .bodySmall!- .copyWith(height: 1.5),- ),- TextSpan(- text:- "${LocaleKeys.settings_aiPage_keys_offlineAIDownload1.tr()} ",- style: Theme.of(context)- .textTheme- .bodySmall!- .copyWith(height: 1.5),- ),- TextSpan(- text:- " ${LocaleKeys.settings_aiPage_keys_offlineAIDownload2.tr()} ",- style: Theme.of(context).textTheme.bodyMedium!.copyWith(- fontSize: FontSizes.s14,- color: Theme.of(context).colorScheme.primary,- height: 1.5,- ),- recognizer: TapGestureRecognizer()- ..onTap =- () => context.read<DownloadOfflineAIBloc>().add(- const DownloadOfflineAIEvent.started(),- ),- ),- TextSpan(- text:- " ${LocaleKeys.settings_aiPage_keys_offlineAIDownload3.tr()} ",- style: Theme.of(context)- .textTheme- .bodySmall!- .copyWith(height: 1.5),- ),- ],- ),- ),- ],- );- },- ),- );- }-}--class _LackOfResource extends StatelessWidget {- const _LackOfResource({required this.desc});-- final String desc;-- @override- Widget build(BuildContext context) {- return Row(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- FlowySvg(- FlowySvgs.toast_warning_filled_s,- size: const Size.square(20.0),- blendMode: null,- ),- const HSpace(6),- Expanded(- child: FlowyText(- desc,- maxLines: 3,- ),- ),- ],- );- }-}diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/plugin_status_indicator.dart b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/plugin_status_indicator.dartnew file mode 100644index 0000000000..b79e228a0c--- /dev/null+++ b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/plugin_status_indicator.dart@@ -0,0 +1,309 @@+import 'package:appflowy/core/helpers/url_launcher.dart';+import 'package:appflowy/generated/flowy_svgs.g.dart';+import 'package:appflowy/generated/locale_keys.g.dart';+import 'package:appflowy/util/theme_extension.dart';+import 'package:appflowy/workspace/application/settings/ai/local_ai_bloc.dart';+import 'package:appflowy_backend/dispatch/dispatch.dart';+import 'package:appflowy_backend/protobuf/flowy-ai/protobuf.dart';+import 'package:appflowy_result/appflowy_result.dart';+import 'package:easy_localization/easy_localization.dart';+import 'package:flowy_infra_ui/style_widget/text.dart';+import 'package:flowy_infra_ui/widget/spacing.dart';+import 'package:flutter/gestures.dart';+import 'package:flutter/material.dart';+import 'package:flutter_bloc/flutter_bloc.dart';++class LocalAIStatusIndicator extends StatelessWidget {+ const LocalAIStatusIndicator({super.key});++ @override+ Widget build(BuildContext context) {+ return BlocBuilder<LocalAiPluginBloc, LocalAiPluginState>(+ builder: (context, state) {+ final readyState = switch (state) {+ final ReadyLocalAiPluginState readyLocalAiToggleState =>+ readyLocalAiToggleState,+ _ => null,+ };+ if (readyState == null) {+ return const SizedBox.shrink();+ }++ final lackOfResource = readyState.lackOfResource;+ if (lackOfResource != null) {+ return _LackOfResource(resource: lackOfResource);+ }++ return switch (readyState.runningState) {+ RunningStatePB.ReadyToRun => const _ReadyToRun(),+ RunningStatePB.Connecting ||+ RunningStatePB.Connected =>+ _Initializing(),+ RunningStatePB.Running => const _LocalAIRunning(),+ RunningStatePB.Stopped => const _RestartPluginButton(),+ _ => const SizedBox.shrink(),+ };+ },+ );+ }+}++class _ReadyToRun extends StatelessWidget {+ const _ReadyToRun();++ @override+ Widget build(BuildContext context) {+ return FlowyText(+ LocaleKeys.settings_aiPage_keys_localAIStart.tr(),+ maxLines: 3,+ );+ }+}++class _Initializing extends StatelessWidget {+ const _Initializing();++ @override+ Widget build(BuildContext context) {+ return Container(+ decoration: const BoxDecoration(+ color: Color(0xFFEDF7ED),+ borderRadius: BorderRadius.all(Radius.circular(8)),+ ),+ padding: const EdgeInsets.all(8.0),+ width: double.infinity,+ child: FlowyText(+ LocaleKeys.settings_aiPage_keys_localAIInitializing.tr(),+ color: const Color(0xFF1E4620),+ maxLines: 3,+ ),+ );+ }+}++class _RestartPluginButton extends StatelessWidget {+ const _RestartPluginButton();++ @override+ Widget build(BuildContext context) {+ final textStyle =+ Theme.of(context).textTheme.bodyMedium?.copyWith(height: 1.5);++ return Container(+ decoration: BoxDecoration(+ color: Theme.of(context).isLightMode+ ? const Color(0x80FFE7EE)+ : const Color(0x80591734),+ borderRadius: BorderRadius.all(Radius.circular(8.0)),+ ),+ padding: const EdgeInsets.all(8.0),+ child: Row(+ children: [+ const FlowySvg(+ FlowySvgs.toast_warning_filled_s,+ color: Color(0xFFC62828),+ ),+ const HSpace(8),+ Expanded(+ child: RichText(+ maxLines: 3,+ text: TextSpan(+ children: [+ TextSpan(+ text:+ LocaleKeys.settings_aiPage_keys_failToLoadLocalAI.tr(),+ style: textStyle,+ ),+ TextSpan(+ text: ' ',+ style: textStyle,+ ),+ TextSpan(+ text: LocaleKeys.settings_aiPage_keys_restartLocalAI.tr(),+ style: textStyle?.copyWith(+ fontWeight: FontWeight.w600,+ decoration: TextDecoration.underline,+ ),+ recognizer: TapGestureRecognizer()+ ..onTap = () {+ afLaunchUrlString(+ "https://appflowy.com/guide/appflowy-local-ai-ollama",+ );+ },+ ),+ ],+ ),+ ),+ ),+ ],+ ),+ );+ }+}++class _LocalAIRunning extends StatelessWidget {+ const _LocalAIRunning();++ @override+ Widget build(BuildContext context) {+ return Container(+ decoration: const BoxDecoration(+ color: Color(0xFFEDF7ED),+ borderRadius: BorderRadius.all(Radius.circular(8.0)),+ ),+ padding: const EdgeInsets.all(8.0),+ child: Row(+ children: [+ const FlowySvg(+ FlowySvgs.download_success_s,+ color: Color(0xFF2E7D32),+ ),+ const HSpace(6),+ Expanded(+ child: FlowyText(+ LocaleKeys.settings_aiPage_keys_localAIRunning.tr(),+ color: const Color(0xFF1E4620),+ maxLines: 3,+ ),+ ),+ ],+ ),+ );+ }+}++class _LackOfResource extends StatelessWidget {+ const _LackOfResource({required this.resource});++ final LackOfAIResourcePB resource;++ @override+ Widget build(BuildContext context) {+ return Container(+ decoration: BoxDecoration(+ color: Theme.of(context).isLightMode+ ? const Color(0x80FFE7EE)+ : const Color(0x80591734),+ borderRadius: BorderRadius.all(Radius.circular(8.0)),+ ),+ padding: const EdgeInsets.all(8.0),+ child: Row(+ children: [+ FlowySvg(+ FlowySvgs.toast_error_filled_s,+ size: const Size.square(20.0),+ blendMode: null,+ ),+ const HSpace(8),+ Expanded(+ child: switch (resource.resourceType) {+ LackOfAIResourceTypePB.PluginExecutableNotReady =>+ _buildNoLAI(context),+ LackOfAIResourceTypePB.OllamaServerNotReady =>+ _buildNoOllama(context),+ LackOfAIResourceTypePB.MissingModel =>+ _buildNoModel(context, resource.missingModelNames),+ _ => const SizedBox.shrink(),+ },+ ),+ ],+ ),+ );+ }++ TextStyle? _textStyle(BuildContext context) {+ return Theme.of(context).textTheme.bodyMedium?.copyWith(height: 1.5);+ }++ Widget _buildNoLAI(BuildContext context) {+ final textStyle = _textStyle(context);+ return RichText(+ maxLines: 3,+ text: TextSpan(+ children: [+ TextSpan(+ text: LocaleKeys.settings_aiPage_keys_laiNotReady.tr(),+ style: textStyle,+ ),+ TextSpan(text: ' ', style: _textStyle(context)),+ ..._downloadInstructions(textStyle),+ ],+ ),+ );+ }++ Widget _buildNoOllama(BuildContext context) {+ final textStyle = _textStyle(context);+ return RichText(+ maxLines: 3,+ text: TextSpan(+ children: [+ TextSpan(+ text: LocaleKeys.settings_aiPage_keys_ollamaNotReady.tr(),+ style: textStyle,+ ),+ TextSpan(text: ' ', style: textStyle),+ ..._downloadInstructions(textStyle),+ ],+ ),+ );+ }++ Widget _buildNoModel(BuildContext context, List<String> modelNames) {+ final textStyle = _textStyle(context);++ return RichText(+ maxLines: 3,+ text: TextSpan(+ children: [+ TextSpan(+ text: LocaleKeys.settings_aiPage_keys_modelsMissing.tr(),+ style: textStyle,+ ),+ TextSpan(+ text: ' ',+ style: textStyle,+ ),+ ],+ ),+ );+ }++ List<TextSpan> _downloadInstructions(TextStyle? textStyle) {+ return [+ TextSpan(+ text: LocaleKeys.settings_aiPage_keys_localAISetupInstruction1.tr(),+ style: textStyle,+ ),+ TextSpan(+ text: ' ',+ style: textStyle,+ ),+ TextSpan(+ text: LocaleKeys.settings_aiPage_keys_localAISetupInstruction2.tr(),+ style: textStyle?.copyWith(+ fontWeight: FontWeight.w600,+ decoration: TextDecoration.underline,+ ),+ recognizer: TapGestureRecognizer()+ ..onTap = () {+ afLaunchUrlString(+ "https://appflowy.com/guide/appflowy-local-ai-ollama",+ );+ },+ ),+ TextSpan(text: ' ', style: textStyle),+ TextSpan(+ text: LocaleKeys.settings_aiPage_keys_localAISetupInstruction3.tr(),+ style: textStyle,+ ),+ ];+ }+}++void onDownloadButtonPressed() {+ AIEventGetLocalAIDownloadLink().send().fold(+ (app) => afLaunchUri(Uri.parse(app.link)),+ (err) {},+ );+}diff --git a/frontend/resources/translations/en.json b/frontend/resources/translations/en.jsonindex 2b22da596c..01c3a51b19 100644--- a/frontend/resources/translations/en.json+++ b/frontend/resources/translations/en.json@@ -854,14 +854,14 @@"downloadAIModelButton": "Download","downloadingModel": "Downloading","localAILoaded": "Local AI Model successfully added and ready to use",- "localAIStart": "Local AI is starting. If it’s slow, try toggling it off and on",+ "localAIStart": "Local AI is starting. If it's slow, try toggling it off and on","localAILoading": "Local AI Chat Model is loading...","localAIStopped": "Local AI stopped","localAIRunning": "Local AI is running",- "localAIInitializing": "Local AI is loading and may take a few minutes, depending on your device",+ "localAIInitializing": "Local AI is loading. This may take a few minutes depending on your device","localAINotReadyTextFieldPrompt": "You can not edit while Local AI is loading","failToLoadLocalAI": "Failed to start local AI",- "restartLocalAI": "Restart Local AI",+ "restartLocalAI": "Restart","disableLocalAITitle": "Disable local AI","disableLocalAIDescription": "Do you want to disable local AI?","localAIToggleTitle": "AppFlowy Local AI (LAI)",@@ -875,10 +875,12 @@"activeOfflineAI": "Active","downloadOfflineAI": "Download","openModelDirectory": "Open folder",- "localAISetupInstruction1": "Follow these",+ "localAISetupInstruction1": "Please follow these","localAISetupInstruction2": "instructions",- "localAISetupInstruction3": "to set up Ollama and AppFlowy Local AI. Skip if you've already set it up",- "startLocalAI": "It may take a few seconds to start the local AI"+ "localAISetupInstruction3": "to set up Ollama and AppFlowy Local AI.",+ "laiNotReady": "The Local AI app was not installed correctly.",+ "ollamaNotReady": "The Ollama server is not ready.",+ "modelsMissing": "Cannot find the model. You can use the ollama pull command to install them."}},"planPage": {diff --git a/frontend/rust-lib/flowy-ai/src/entities.rs b/frontend/rust-lib/flowy-ai/src/entities.rsindex b24d0cb13e..a7915aae23 100644--- a/frontend/rust-lib/flowy-ai/src/entities.rs+++ b/frontend/rust-lib/flowy-ai/src/entities.rs@@ -589,7 +589,7 @@ pub struct LocalAIPB {pub is_plugin_executable_ready: bool,#[pb(index = 3, one_of)]- pub lack_of_resource: Option<String>,+ pub lack_of_resource: Option<LackOfAIResourcePB>,#[pb(index = 4)]pub state: RunningStatePB,@@ -724,5 +724,35 @@ impl From<LocalAISettingPB> for LocalAISetting {#[derive(Default, ProtoBuf, Clone, Debug)]pub struct LackOfAIResourcePB {#[pb(index = 1)]- pub resource_desc: String,+ pub resource_type: LackOfAIResourceTypePB,++ #[pb(index = 2)]+ pub missing_model_names: Vec<String>,+}++#[derive(Debug, Default, Clone, ProtoBuf_Enum)]+pub enum LackOfAIResourceTypePB {+ #[default]+ PluginExecutableNotReady = 0,+ OllamaServerNotReady = 1,+ MissingModel = 2,+}++impl From<PendingResource> for LackOfAIResourcePB {+ fn from(value: PendingResource) -> Self {+ match value {+ PendingResource::PluginExecutableNotReady => Self {+ resource_type: LackOfAIResourceTypePB::PluginExecutableNotReady,+ missing_model_names: vec![],+ },+ PendingResource::OllamaServerNotReady => Self {+ resource_type: LackOfAIResourceTypePB::OllamaServerNotReady,+ missing_model_names: vec![],+ },+ PendingResource::MissingModel(model_name) => Self {+ resource_type: LackOfAIResourceTypePB::MissingModel,+ missing_model_names: vec![model_name],+ },+ }+ }}diff --git a/frontend/rust-lib/flowy-ai/src/local_ai/controller.rs b/frontend/rust-lib/flowy-ai/src/local_ai/controller.rsindex c3f57e6fac..bca710a907 100644--- a/frontend/rust-lib/flowy-ai/src/local_ai/controller.rs+++ b/frontend/rust-lib/flowy-ai/src/local_ai/controller.rs@@ -1,5 +1,5 @@use crate::ai_manager::AIUserService;-use crate::entities::{LackOfAIResourcePB, LocalAIPB, RunningStatePB};+use crate::entities::{LocalAIPB, RunningStatePB};use crate::local_ai::resource::{LLMResourceService, LocalAIResourceController};use crate::notification::{chat_notification_builder, ChatNotification, APPFLOWY_AI_NOTIFICATION_KEY,@@ -274,14 +274,15 @@ impl LocalAIController {pub async fn get_local_ai_state(&self) -> LocalAIPB {let start = std::time::Instant::now();let enabled = self.is_enabled();- let mut is_plugin_executable_ready = false;- let mut state = RunningState::ReadyToConnect;- let mut lack_of_resource = None;- if enabled {- is_plugin_executable_ready = is_plugin_ready();- state = self.ai_plugin.get_plugin_running_state();- lack_of_resource = self.resource.get_lack_of_resource().await;- }+ let (is_plugin_executable_ready, state, lack_of_resource) = if enabled {+ (+ is_plugin_ready(),+ self.ai_plugin.get_plugin_running_state(),+ self.resource.get_lack_of_resource().await,+ )+ } else {+ (false, RunningState::ReadyToConnect, None)+ };let elapsed = start.elapsed();debug!("[AI Plugin] get local ai state, elapsed: {:?}, thread: {:?}",@@ -482,9 +483,7 @@ async fn initialize_ai_plugin(APPFLOWY_AI_NOTIFICATION_KEY,ChatNotification::LocalAIResourceUpdated,)- .payload(LackOfAIResourcePB {- resource_desc: lack_of_resource,- })+ .payload(lack_of_resource).send();return Ok(());diff --git a/frontend/rust-lib/flowy-ai/src/local_ai/resource.rs b/frontend/rust-lib/flowy-ai/src/local_ai/resource.rsindex 3eddcf2039..c40a9a9b88 100644--- a/frontend/rust-lib/flowy-ai/src/local_ai/resource.rs+++ b/frontend/rust-lib/flowy-ai/src/local_ai/resource.rs@@ -47,22 +47,13 @@ pub enum WatchDiskEvent {Remove,}+#[derive(Debug, Clone)]pub enum PendingResource {PluginExecutableNotReady,OllamaServerNotReady,MissingModel(String),}-impl PendingResource {- pub fn desc(self) -> String {- match self {- PendingResource::PluginExecutableNotReady => "The Local AI app was not installed correctly. Please follow the instructions to install the Local AI application".to_string(),- PendingResource::OllamaServerNotReady => "Ollama is not ready. Please follow the instructions to install Ollama".to_string(),- PendingResource::MissingModel(model) => format!("Cannot find the model: {}. Please use the ollama pull command to install the model", model),- }- }-}-pub struct LocalAIResourceController {user_service: Arc<dyn AIUserService>,resource_service: Arc<dyn LLMResourceService>,@@ -128,10 +119,10 @@ impl LocalAIResourceController {return false;}- match self.calculate_pending_resources().await {- Ok(res) => res.is_empty(),- Err(_) => false,- }+ self+ .calculate_pending_resources()+ .await+ .is_ok_and(|r| r.is_none())}pub async fn get_plugin_download_link(&self) -> FlowyResult<String> {@@ -147,36 +138,35 @@ impl LocalAIResourceController {#[instrument(level = "info", skip_all, err)]pub async fn set_llm_setting(&self, setting: LocalAISetting) -> FlowyResult<()> {self.resource_service.store_setting(setting)?;- let mut resources = self.calculate_pending_resources().await?;- if let Some(resource) = resources.pop() {+ if let Some(resource) = self.calculate_pending_resources().await? {chat_notification_builder(APPFLOWY_AI_NOTIFICATION_KEY,ChatNotification::LocalAIResourceUpdated,)- .payload(LackOfAIResourcePB {- resource_desc: resource.desc(),- })+ .payload(LackOfAIResourcePB::from(resource)).send();}Ok(())}- pub async fn get_lack_of_resource(&self) -> Option<String> {- let mut resources = self.calculate_pending_resources().await.ok()?;- resources.pop().map(|r| r.desc())+ pub async fn get_lack_of_resource(&self) -> Option<LackOfAIResourcePB> {+ self+ .calculate_pending_resources()+ .await+ .ok()?+ .map(Into::into)}- pub async fn calculate_pending_resources(&self) -> FlowyResult<Vec<PendingResource>> {- let mut resources = vec![];+ pub async fn calculate_pending_resources(&self) -> FlowyResult<Option<PendingResource>> {let app_path = ollama_plugin_path();if !is_plugin_ready() {trace!("[LLM Resource] offline app not found: {:?}", app_path);- resources.push(PendingResource::PluginExecutableNotReady);- return Ok(resources);+ return Ok(Some(PendingResource::PluginExecutableNotReady));}let setting = self.get_llm_setting();let client = Client::builder().timeout(Duration::from_secs(5)).build()?;+match client.get(&setting.ollama_server_url).send().await {Ok(resp) if resp.status().is_success() => {info!(@@ -189,8 +179,7 @@ impl LocalAIResourceController {"[LLM Resource] Ollama server is not responding at {}",setting.ollama_server_url);- resources.push(PendingResource::OllamaServerNotReady);- return Ok(resources);+ return Ok(Some(PendingResource::OllamaServerNotReady));},}@@ -201,12 +190,8 @@ impl LocalAIResourceController {match client.get(&tags_url).send().await {Ok(resp) if resp.status().is_success() => {- let tags: TagsResponse = resp.json().await.map_err(|e| {- log::error!(- "[LLM Resource] Failed to parse /api/tags JSON response: {:?}",- e- );- e+ let tags: TagsResponse = resp.json().await.inspect_err(|e| {+ log::error!("[LLM Resource] Failed to parse /api/tags JSON response: {e:?}")})?;// Check each required model is present in the response.for required in &required_models {@@ -215,9 +200,7 @@ impl LocalAIResourceController {"[LLM Resource] required model '{}' not found in API response",required);- resources.push(PendingResource::MissingModel(required.clone()));- // Optionally, you could continue checking all models rather than returning early.- return Ok(resources);+ return Ok(Some(PendingResource::MissingModel(required.clone())));}}},@@ -226,12 +209,11 @@ impl LocalAIResourceController {"[LLM Resource] Failed to fetch models from {} (GET /api/tags)",setting.ollama_server_url);- resources.push(PendingResource::OllamaServerNotReady);- return Ok(resources);+ return Ok(Some(PendingResource::OllamaServerNotReady));},}- Ok(resources)+ Ok(None)}#[instrument(level = "info", skip_all)]