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
chore: improve local ai settings page (#7651)
Richard Shiue34d2b7f24e3e
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..c4a4ee3afa 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,145 @@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(),+ LocalAiPluginState.ready(+ isEnabled: aiState.enabled,+ version: aiState.pluginVersion,+ runningState: aiState.state,+ lackOfResource:+ aiState.hasLackOfResource() ? aiState.lackOfResource : null,),);- unawaited(- AIEventToggleLocalAI().send().then(- (result) {- if (!isClosed) {- add(LocalAIToggleEvent.handleResult(result));- }- },- ),+ },+ didReceiveLackOfResources: (resources) {+ state.maybeMap(+ ready: (readyState) {+ emit(readyState.copyWith(lackOfResource: resources));+ },+ orElse: () {},);},- handleResult: (result) {- _handleResult(emit, result);+ toggle: () async {+ emit(LocalAiPluginState.loading());+ await AIEventToggleLocalAI().send().fold(+ (aiState) {+ add(LocalAiPluginEvent.didReceiveAiState(aiState));+ },+ Log.error,+ );+ },+ restart: () async {+ emit(LocalAiPluginState.loading());+ 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));},);}-}-@freezed-class LocalAIToggleEvent with _$LocalAIToggleEvent {- const factory LocalAIToggleEvent.started() = _Started;- const factory LocalAIToggleEvent.toggle() = _Toggle;- const factory LocalAIToggleEvent.handleResult(- FlowyResult<LocalAIPB, FlowyError> result,- ) = _HandleResult;+ void _getLocalAiState() {+ AIEventGetLocalAIState().send().fold(+ (aiState) {+ add(LocalAiPluginEvent.didReceiveAiState(aiState));+ },+ Log.error,+ );+ }}@freezed-class LocalAIToggleState with _$LocalAIToggleState {- const factory LocalAIToggleState({- @Default(LocalAIToggleStateIndicator.loading())- LocalAIToggleStateIndicator pageIndicator,- }) = _LocalAIToggleState;+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 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 LocalAiPluginState with _$LocalAiPluginState {+ const LocalAiPluginState._();++ const factory LocalAiPluginState.ready({+ required bool isEnabled,+ required String version,+ required RunningStatePB runningState,+ required LackOfAIResourcePB? lackOfResource,+ }) = ReadyLocalAiPluginState;++ const factory LocalAiPluginState.loading() = LoadingLocalAiPluginState;++ bool get isEnabled {+ return maybeWhen(+ ready: (isEnabled, _, __, ___) => isEnabled,+ orElse: () => false,+ );+ }++ bool get showIndicator {+ return maybeWhen(+ ready: (isEnabled, _, runningState, lackOfResource) =>+ runningState != RunningStatePB.Running || lackOfResource != null,+ orElse: () => false,+ );+ }++ bool get showSettings {+ return maybeWhen(+ ready: (isEnabled, _, runningState, lackOfResource) {+ final isConnecting = [+ RunningStatePB.Connecting,+ RunningStatePB.Connected,+ ].contains(runningState);++ final resourcesReadyOrMissingModel = lackOfResource == null ||+ lackOfResource.resourceType == LackOfAIResourceTypePB.MissingModel;++ return !isConnecting && resourcesReadyOrMissingModel;+ },+ orElse: () => false,+ );+ }}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 60c68b70c6..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.pluginDownloaded) {- 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 d91d7151ab..0000000000--- a/frontend/appflowy_flutter/lib/workspace/application/settings/ai/plugin_state_bloc.dart+++ /dev/null@@ -1,150 +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(- PluginStateState(- action: PluginStateAction.running(aiState.pluginVersion),- ),- );- 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(String version) = _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..751e7a6180 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,128 +1,150 @@-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: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)!;+ create: (context) => LocalAiPluginBloc(),+ child: BlocConsumer<LocalAiPluginBloc, LocalAiPluginState>(+ listener: (context, state) {+ expandableController.value = state.isEnabled;+ },+ builder: (context, state) {+ return ExpandablePanel(+ controller: expandableController,+ theme: ExpandableThemeData(+ tapBodyToCollapse: false,+ hasIcon: false,+ tapBodyToExpand: false,+ tapHeaderToExpand: false,+ ),+ header: LocalAiSettingHeader(+ isEnabled: state.isEnabled,+ isToggleable: state is ReadyLocalAiPluginState,+ ),+ collapsed: const SizedBox.shrink(),+ expanded: Padding(+ padding: EdgeInsets.only(top: 12),+ child: LocalAISettingPanel(),+ ),+ );+ },+ ),+ );+ }+}- 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,+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();+ }++ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ const LocalAIStatusIndicator(),+ if (state.showSettings) ...[+ const VSpace(10),+ OllamaSettingPage(),+ ],+ ],);},);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/model_selection.dart b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/model_selection.dartindex 05db831e04..861ef72432 100644--- a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/model_selection.dart+++ b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/model_selection.dart@@ -20,25 +20,28 @@ class AIModelSelection extends StatelessWidget {buildWhen: (previous, current) =>previous.availableModels != current.availableModels,builder: (context, state) {- if (state.availableModels == null) {+ final models = state.availableModels?.models;++ if (models == null) {return const SizedBox(// Using same height as SettingsDropdown to avoid layout shiftheight: height,);}+ final localModels = models.where((model) => model.isLocal).toList();+ final cloudModels = models.where((model) => !model.isLocal).toList();+return Padding(padding: const EdgeInsets.symmetric(vertical: 6),child: Row(- mainAxisAlignment: MainAxisAlignment.spaceBetween,children: [- Flexible(+ Expanded(child: FlowyText.medium(LocaleKeys.settings_aiPage_keys_llmModelType.tr(),- fontSize: 14,+ overflow: TextOverflow.ellipsis,),),- const Spacer(),Flexible(child: SettingsDropdown<AIModelPB>(key: const Key('_AIModelSelection'),@@ -46,12 +49,14 @@ class AIModelSelection extends StatelessWidget {.read<SettingsAIBloc>().add(SettingsAIEvent.selectModel(model)),selectedOption: state.availableModels!.selectedModel,- options: state.availableModels!.models+ options: [...localModels, ...cloudModels].map((model) => buildDropdownMenuEntry<AIModelPB>(context,value: model,- label: model.i18n,+ label: model.isLocal+ ? "${model.i18n} (Local)"+ : model.i18n,subLabel: model.desc,maximumHeight: height,),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 12ce391a29..0000000000--- a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/plugin_state.dart+++ /dev/null@@ -1,168 +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/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_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/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: (version) => _LocalAIRunning(- key: ValueKey(version),- version: version,- ),- 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({required this.version, super.key});-- final String version;-- @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),- if (version.isNotEmpty)- Flexible(- child: FlowyText(- "($version) ",- fontSize: 11,- color: const Color(0xFF1E4620),- ),- ),- Flexible(- child: FlowyText(- LocaleKeys.settings_aiPage_keys_localAIRunning.tr(),- fontSize: 11,- color: const Color(0xFF1E4620),- maxLines: 3,- ),- ),- ],- ),- ),- ],- ),- ),- );- }-}--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..fdf03bb9ca--- /dev/null+++ b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/setting_ai_view/plugin_status_indicator.dart@@ -0,0 +1,359 @@+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/protobuf/flowy-ai/protobuf.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) {+ return state.maybeWhen(+ ready: (_, version, runningState, lackOfResource) {+ if (lackOfResource != null) {+ return _LackOfResource(resource: lackOfResource);+ }++ return switch (runningState) {+ RunningStatePB.ReadyToRun => const _ReadyToRun(),+ RunningStatePB.Connecting ||+ RunningStatePB.Connected =>+ _Initializing(),+ RunningStatePB.Running => _LocalAIRunning(version: version),+ RunningStatePB.Stopped => const _RestartPluginButton(),+ _ => const SizedBox.shrink(),+ };+ },+ orElse: () => const SizedBox.shrink(),+ );+ },+ );+ }+}++class _ReadyToRun extends StatelessWidget {+ const _ReadyToRun();++ @override+ Widget build(BuildContext context) {+ return Padding(+ padding: const EdgeInsets.symmetric(vertical: 8.0),+ child: Row(+ children: [+ const SizedBox.square(+ dimension: 20.0,+ child: CircularProgressIndicator(+ strokeWidth: 2.0,+ strokeAlign: BorderSide.strokeAlignInside,+ ),+ ),+ const HSpace(8.0),+ Expanded(+ child: FlowyText(+ LocaleKeys.settings_aiPage_keys_localAIStart.tr(),+ maxLines: 3,+ overflow: TextOverflow.ellipsis,+ ),+ ),+ ],+ ),+ );+ }+}++class _Initializing extends StatelessWidget {+ const _Initializing();++ @override+ Widget build(BuildContext context) {+ return Padding(+ padding: const EdgeInsets.symmetric(vertical: 8.0),+ child: Row(+ children: [+ const SizedBox.square(+ dimension: 20.0,+ child: CircularProgressIndicator(+ strokeWidth: 2.0,+ strokeAlign: BorderSide.strokeAlignInside,+ ),+ ),+ HSpace(8),+ Expanded(+ child: FlowyText(+ LocaleKeys.settings_aiPage_keys_localAIInitializing.tr(),+ maxLines: 3,+ overflow: TextOverflow.ellipsis,+ ),+ ),+ ],+ ),+ );+ }+}++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_error_filled_s,+ size: Size.square(20.0),+ blendMode: null,+ ),+ 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 = () {+ context+ .read<LocalAiPluginBloc>()+ .add(const LocalAiPluginEvent.restart());+ },+ ),+ ],+ ),+ ),+ ),+ ],+ ),+ );+ }+}++class _LocalAIRunning extends StatelessWidget {+ const _LocalAIRunning({+ required this.version,+ });++ final String version;++ @override+ Widget build(BuildContext context) {+ final runningText = LocaleKeys.settings_aiPage_keys_localAIRunning.tr();+ final text = version.isEmpty ? runningText : "$runningText ($version)";++ 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(+ text,+ 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,+ ),+ TextSpan(+ text: LocaleKeys.settings_aiPage_keys_pleaseFollowThese.tr(),+ style: textStyle,+ ),+ TextSpan(+ text: ' ',+ style: textStyle,+ ),+ TextSpan(+ text: LocaleKeys.settings_aiPage_keys_instructions.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_downloadModel.tr(),+ style: textStyle,+ ),+ ],+ ),+ );+ }++ List<TextSpan> _downloadInstructions(TextStyle? textStyle) {+ return [+ TextSpan(+ text: LocaleKeys.settings_aiPage_keys_pleaseFollowThese.tr(),+ style: textStyle,+ ),+ TextSpan(+ text: ' ',+ style: textStyle,+ ),+ TextSpan(+ text: LocaleKeys.settings_aiPage_keys_instructions.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_installOllamaLai.tr(),+ style: textStyle,+ ),+ ];+ }+}diff --git a/frontend/resources/translations/ar-SA.json b/frontend/resources/translations/ar-SA.jsonindex e6a8be240c..6642644580 100644--- a/frontend/resources/translations/ar-SA.json+++ b/frontend/resources/translations/ar-SA.json@@ -875,9 +875,9 @@"activeOfflineAI": "نشط","downloadOfflineAI": "التنزيل","openModelDirectory": "افتح المجلد",- "localAISetupInstruction1": "اتبع هؤلاء",- "localAISetupInstruction2": "التعليمات",- "localAISetupInstruction3": "لإعداد Ollama وAppFlowy Local AI. تخطَّ هذه الخطوة إذا كنت قد قمت بإعدادها بالفعل",+ "pleaseFollowThese": "اتبع هؤلاء",+ "instructions": "التعليمات",+ "installOllamaLai": "لإعداد Ollama وAppFlowy Local AI. تخطَّ هذه الخطوة إذا كنت قد قمت بإعدادها بالفعل","startLocalAI": "قد يستغرق الأمر بضع ثوانٍ لبدء تشغيل الذكاء الاصطناعي المحلي"}},@@ -3217,4 +3217,4 @@"rewrite": "إعادة كتابة","insertBelow": "أدخل أدناه"}-}\ No newline at end of file+}diff --git a/frontend/resources/translations/en.json b/frontend/resources/translations/en.jsonindex e93f5273e5..dcb39527c8 100644--- a/frontend/resources/translations/en.json+++ b/frontend/resources/translations/en.json@@ -854,16 +854,16 @@"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 seconds, depending on your device","localAINotReadyRetryLater": "Local AI is initializing, please retry later","localAIDisabled": "You are using local AI, but it is disabled. Please go to settings to enable it or try different model",+ "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",+ "failToLoadLocalAI": "Failed to start local AI.",+ "restartLocalAI": "Restart","disableLocalAITitle": "Disable local AI","disableLocalAIDescription": "Do you want to disable local AI?","localAIToggleTitle": "AppFlowy Local AI (LAI)",@@ -877,10 +877,13 @@"activeOfflineAI": "Active","downloadOfflineAI": "Download","openModelDirectory": "Open folder",- "localAISetupInstruction1": "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"+ "laiNotReady": "The Local AI app was not installed correctly.",+ "ollamaNotReady": "The Ollama server is not ready.",+ "pleaseFollowThese": "Please follow these",+ "instructions": "instructions",+ "installOllamaLai": "to set up Ollama and AppFlowy Local AI.",+ "modelsMissing": "Cannot find the required models.",+ "downloadModel": "to download them."}},"planPage": {@@ -3204,4 +3207,4 @@"rewrite": "Rewrite","insertBelow": "Insert below"}-}\ No newline at end of file+}diff --git a/frontend/resources/translations/ko-KR.json b/frontend/resources/translations/ko-KR.jsonindex 635efe92de..8e7192cf0b 100644--- a/frontend/resources/translations/ko-KR.json+++ b/frontend/resources/translations/ko-KR.json@@ -868,9 +868,9 @@"activeOfflineAI": "활성화됨","downloadOfflineAI": "다운로드","openModelDirectory": "폴더 열기",- "localAISetupInstruction1": "이 지침을 따르세요",- "localAISetupInstruction2": "지침",- "localAISetupInstruction3": "Ollama 및 AppFlowy 로컬 AI를 설정합니다. 이미 설정한 경우 건너뛰세요",+ "pleaseFollowThese": "지침",+ "instructions": "이 지침을 따르세요",+ "installOllamaLai": "Ollama 및 AppFlowy 로컬 AI를 설정합니다. 이미 설정한 경우 건너뛰세요","startLocalAI": "로컬 AI를 시작하는 데 몇 초가 소요될 수 있습니다"}},@@ -3185,4 +3185,4 @@"rewrite": "다시 작성","insertBelow": "아래에 삽입"}-}\ No newline at end of file+}diff --git a/frontend/rust-lib/flowy-ai/src/entities.rs b/frontend/rust-lib/flowy-ai/src/entities.rsindex 30a3e5dd28..0075e35c04 100644--- a/frontend/rust-lib/flowy-ai/src/entities.rs+++ b/frontend/rust-lib/flowy-ai/src/entities.rs@@ -586,7 +586,7 @@ pub struct LocalAIPB {pub enabled: bool,#[pb(index = 2, one_of)]- pub lack_of_resource: Option<String>,+ pub lack_of_resource: Option<LackOfAIResourcePB>,#[pb(index = 3)]pub state: RunningStatePB,@@ -721,5 +721,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 03b014c89d..b63401b829 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,@@ -539,9 +539,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)]