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 password error message (#7842)
Lucas2661ad27ec0d
diff --git a/.github/workflows/ios_ci.yaml b/.github/workflows/ios_ci.yamlindex e13863f4a7..43611cc141 100644--- a/.github/workflows/ios_ci.yaml+++ b/.github/workflows/ios_ci.yaml@@ -94,26 +94,26 @@ jobs:cargo make --profile development-ios-arm64-sim appflowy-core-dev-ioscargo make --profile development-ios-arm64-sim code_generation- - uses: futureware-tech/simulator-action@v3- id: simulator-action- with:- model: "iPhone 15"- shutdown_after_job: false-- - name: Run AppFlowy on simulator- working-directory: frontend/appflowy_flutter- run: |- flutter run -d ${{ steps.simulator-action.outputs.udid }} &- pid=$!- sleep 500- kill $pid- continue-on-error: true-- # Integration tests- - name: Run integration tests- working-directory: frontend/appflowy_flutter- # The integration tests are flaky and sometimes fail with "Connection timed out":- # Don't block the CI. If the tests fail, the CI will still pass.- # Instead, we're using Code Magic to re-run the tests to check if they pass.- continue-on-error: true- run: flutter test integration_test/runner.dart -d ${{ steps.simulator-action.outputs.udid }}+ # - uses: futureware-tech/simulator-action@v3+ # id: simulator-action+ # with:+ # model: "iPhone 15"+ # shutdown_after_job: false++ # - name: Run AppFlowy on simulator+ # working-directory: frontend/appflowy_flutter+ # run: |+ # flutter run -d ${{ steps.simulator-action.outputs.udid }} &+ # pid=$!+ # sleep 500+ # kill $pid+ # continue-on-error: true++ # # Integration tests+ # - name: Run integration tests+ # working-directory: frontend/appflowy_flutter+ # # The integration tests are flaky and sometimes fail with "Connection timed out":+ # # Don't block the CI. If the tests fail, the CI will still pass.+ # # Instead, we're using Code Magic to re-run the tests to check if they pass.+ # continue-on-error: true+ # run: flutter test integration_test/runner.dart -d ${{ steps.simulator-action.outputs.udid }}diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/account/account_deletion.dart b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/account/account_deletion.dartindex e746bec4d9..58428f9f6a 100644--- a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/account/account_deletion.dart+++ b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/account/account_deletion.dart@@ -45,7 +45,6 @@ class _AccountDeletionButtonState extends State<AccountDeletionButton> {Widget build(BuildContext context) {final theme = AppFlowyTheme.of(context);return Row(- crossAxisAlignment: CrossAxisAlignment.start,children: [Expanded(child: Column(diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/account/password/change_password.dart b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/account/password/change_password.dartindex e865da79f0..876fc71350 100644--- a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/account/password/change_password.dart+++ b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/account/password/change_password.dart@@ -1,6 +1,7 @@import 'package:appflowy/generated/flowy_svgs.g.dart';import 'package:appflowy/generated/locale_keys.g.dart';import 'package:appflowy/user/application/password/password_bloc.dart';+import 'package:appflowy/workspace/presentation/settings/pages/account/password/error_extensions.dart';import 'package:appflowy/workspace/presentation/settings/pages/account/password/password_suffix_icon.dart';import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';import 'package:appflowy_backend/protobuf/flowy-user/user_profile.pb.dart';@@ -342,18 +343,25 @@ class _ChangePasswordDialogContentStatemessage = LocaleKeys.newSettings_myAccount_password_toast_passwordUpdatedFailed.tr();- if (error.msg.contains('Incorrect current password')) {++ if (AFPasswordErrorExtension.incorrectPasswordPattern+ .hasMatch(error.msg)) {currentPasswordTextFieldKey.currentState?.syncError(- errorText: LocaleKeys- .newSettings_myAccount_password_error_currentPasswordIsIncorrect- .tr(),+ errorText: AFPasswordErrorExtension.getErrorMessage(error),+ );+ } else if (AFPasswordErrorExtension.tooShortPasswordPattern+ .hasMatch(error.msg)) {+ newPasswordTextFieldKey.currentState?.syncError(+ errorText: AFPasswordErrorExtension.getErrorMessage(error),+ );+ } else if (AFPasswordErrorExtension.tooLongPasswordPattern+ .hasMatch(error.msg)) {+ newPasswordTextFieldKey.currentState?.syncError(+ errorText: AFPasswordErrorExtension.getErrorMessage(error),);- } else if (error.msg- .contains('Password should be at least 6 characters.')) {+ } else {newPasswordTextFieldKey.currentState?.syncError(- errorText: LocaleKeys- .newSettings_myAccount_password_error_passwordShouldBeAtLeast6Characters- .tr(),+ errorText: error.msg,);}},@@ -367,9 +375,6 @@ class _ChangePasswordDialogContentState},(error) {hasError = true;- message = LocaleKeys- .newSettings_myAccount_password_toast_passwordSetupFailed- .tr();},);}@@ -379,9 +384,6 @@ class _ChangePasswordDialogContentStateshowToastNotification(message: message,);- }-- if (!hasError) {Navigator.of(context).pop();}}diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/account/password/error_extensions.dart b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/account/password/error_extensions.dartnew file mode 100644index 0000000000..371d67ef06--- /dev/null+++ b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/account/password/error_extensions.dart@@ -0,0 +1,39 @@+import 'package:appflowy/generated/locale_keys.g.dart';+import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';+import 'package:easy_localization/easy_localization.dart';++class AFPasswordErrorExtension {+ static final RegExp incorrectPasswordPattern =+ RegExp('Incorrect current password');+ static final RegExp tooShortPasswordPattern =+ RegExp(r'Password should be at least (\d+) characters');+ static final RegExp tooLongPasswordPattern =+ RegExp(r'Password cannot be longer than (\d+) characters');++ static String getErrorMessage(FlowyError error) {+ final msg = error.msg;+ if (incorrectPasswordPattern.hasMatch(msg)) {+ return LocaleKeys+ .newSettings_myAccount_password_error_currentPasswordIsIncorrect+ .tr();+ } else if (tooShortPasswordPattern.hasMatch(msg)) {+ return LocaleKeys+ .newSettings_myAccount_password_error_passwordShouldBeAtLeast6Characters+ .tr(+ namedArgs: {+ 'min': tooShortPasswordPattern.firstMatch(msg)?.group(1) ?? '6',+ },+ );+ } else if (tooLongPasswordPattern.hasMatch(msg)) {+ return LocaleKeys+ .newSettings_myAccount_password_error_passwordCannotBeLongerThan72Characters+ .tr(+ namedArgs: {+ 'max': tooLongPasswordPattern.firstMatch(msg)?.group(1) ?? '72',+ },+ );+ }++ return msg;+ }+}diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/account/password/setup_password.dart b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/account/password/setup_password.dartindex cf839a7327..c70f1d96c8 100644--- a/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/account/password/setup_password.dart+++ b/frontend/appflowy_flutter/lib/workspace/presentation/settings/pages/account/password/setup_password.dart@@ -1,6 +1,7 @@import 'package:appflowy/generated/flowy_svgs.g.dart';import 'package:appflowy/generated/locale_keys.g.dart';import 'package:appflowy/user/application/password/password_bloc.dart';+import 'package:appflowy/workspace/presentation/settings/pages/account/password/error_extensions.dart';import 'package:appflowy/workspace/presentation/settings/pages/account/password/password_suffix_icon.dart';import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';import 'package:appflowy_backend/protobuf/flowy-user/user_profile.pb.dart';@@ -268,7 +269,6 @@ class _SetupPasswordDialogContentStatevoid _onPasswordStateChanged(BuildContext context, PasswordState state) {bool hasError = false;String message = '';- String description = '';final setPasswordResult = state.setupPasswordResult;@@ -281,22 +281,31 @@ class _SetupPasswordDialogContentState},(error) {hasError = true;- message = LocaleKeys- .newSettings_myAccount_password_toast_passwordSetupFailed- .tr();- description = error.msg;+ if (AFPasswordErrorExtension.tooShortPasswordPattern+ .hasMatch(error.msg)) {+ passwordTextFieldKey.currentState?.syncError(+ errorText: AFPasswordErrorExtension.getErrorMessage(error),+ );+ } else if (AFPasswordErrorExtension.tooLongPasswordPattern+ .hasMatch(error.msg)) {+ passwordTextFieldKey.currentState?.syncError(+ errorText: AFPasswordErrorExtension.getErrorMessage(error),+ );+ } else {+ passwordTextFieldKey.currentState?.syncError(+ errorText: error.msg,+ );+ }},);}if (!state.isSubmitting && message.isNotEmpty) {- showToastNotification(- message: message,- description: description,- type: hasError ? ToastificationType.error : ToastificationType.success,- );-if (!hasError) {+ showToastNotification(+ message: message,+ );+Navigator.of(context).pop();}}diff --git a/frontend/resources/translations/en.json b/frontend/resources/translations/en.jsonindex 9f15e1b05e..86841c0b5a 100644--- a/frontend/resources/translations/en.json+++ b/frontend/resources/translations/en.json@@ -2721,7 +2721,8 @@"passwordsDoNotMatch": "Passwords do not match","newPasswordIsSameAsCurrent": "New password is same as current password","currentPasswordIsIncorrect": "Current password is incorrect",- "passwordShouldBeAtLeast6Characters": "Password should be at least 6 characters"+ "passwordShouldBeAtLeast6Characters": "Password should be at least {min} characters",+ "passwordCannotBeLongerThan72Characters": "Password cannot be longer than {max} characters"},"toast": {"passwordUpdatedSuccessfully": "Password updated successfully",@@ -3371,4 +3372,4 @@"rewrite": "Rewrite","insertBelow": "Insert below"}-}+}\ No newline at end of filediff --git a/frontend/rust-lib/Cargo.lock b/frontend/rust-lib/Cargo.lockindex 4689ed5c4f..6521d3999b 100644--- a/frontend/rust-lib/Cargo.lock+++ b/frontend/rust-lib/Cargo.lock@@ -493,7 +493,7 @@ checksum = "dcfed56ad506cb2c684a14971b8861fdc3baaaae314b9e5f9bb532cbe3ba7a4f"[[package]]name = "app-error"version = "0.1.0"-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=c7176311ca375a672bc01bec0baa101986af023f#c7176311ca375a672bc01bec0baa101986af023f"+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=6ed0f4e#6ed0f4e21c622f692f0f0b2143523e9346b395b9"dependencies = ["anyhow","bincode",@@ -513,7 +513,7 @@ dependencies = [[[package]]name = "appflowy-ai-client"version = "0.1.0"-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=c7176311ca375a672bc01bec0baa101986af023f#c7176311ca375a672bc01bec0baa101986af023f"+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=6ed0f4e#6ed0f4e21c622f692f0f0b2143523e9346b395b9"dependencies = ["anyhow","bytes",@@ -1159,7 +1159,7 @@ dependencies = [[[package]]name = "client-api"version = "0.2.0"-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=c7176311ca375a672bc01bec0baa101986af023f#c7176311ca375a672bc01bec0baa101986af023f"+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=6ed0f4e#6ed0f4e21c622f692f0f0b2143523e9346b395b9"dependencies = ["again","anyhow",@@ -1214,7 +1214,7 @@ dependencies = [[[package]]name = "client-api-entity"version = "0.1.0"-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=c7176311ca375a672bc01bec0baa101986af023f#c7176311ca375a672bc01bec0baa101986af023f"+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=6ed0f4e#6ed0f4e21c622f692f0f0b2143523e9346b395b9"dependencies = ["collab-entity","collab-rt-entity",@@ -1227,7 +1227,7 @@ dependencies = [[[package]]name = "client-websocket"version = "0.1.0"-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=c7176311ca375a672bc01bec0baa101986af023f#c7176311ca375a672bc01bec0baa101986af023f"+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=6ed0f4e#6ed0f4e21c622f692f0f0b2143523e9346b395b9"dependencies = ["futures-channel","futures-util",@@ -1499,7 +1499,7 @@ dependencies = [[[package]]name = "collab-rt-entity"version = "0.1.0"-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=c7176311ca375a672bc01bec0baa101986af023f#c7176311ca375a672bc01bec0baa101986af023f"+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=6ed0f4e#6ed0f4e21c622f692f0f0b2143523e9346b395b9"dependencies = ["anyhow","bincode",@@ -1521,7 +1521,7 @@ dependencies = [[[package]]name = "collab-rt-protocol"version = "0.1.0"-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=c7176311ca375a672bc01bec0baa101986af023f#c7176311ca375a672bc01bec0baa101986af023f"+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=6ed0f4e#6ed0f4e21c622f692f0f0b2143523e9346b395b9"dependencies = ["anyhow","async-trait",@@ -1969,7 +1969,7 @@ checksum = "c2e66c9d817f1720209181c316d28635c050fa304f9c79e47a520882661b7308"[[package]]name = "database-entity"version = "0.1.0"-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=c7176311ca375a672bc01bec0baa101986af023f#c7176311ca375a672bc01bec0baa101986af023f"+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=6ed0f4e#6ed0f4e21c622f692f0f0b2143523e9346b395b9"dependencies = ["bincode","bytes",@@ -3414,7 +3414,7 @@ dependencies = [[[package]]name = "gotrue"version = "0.1.0"-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=c7176311ca375a672bc01bec0baa101986af023f#c7176311ca375a672bc01bec0baa101986af023f"+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=6ed0f4e#6ed0f4e21c622f692f0f0b2143523e9346b395b9"dependencies = ["anyhow","getrandom 0.2.10",@@ -3429,7 +3429,7 @@ dependencies = [[[package]]name = "gotrue-entity"version = "0.1.0"-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=c7176311ca375a672bc01bec0baa101986af023f#c7176311ca375a672bc01bec0baa101986af023f"+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=6ed0f4e#6ed0f4e21c622f692f0f0b2143523e9346b395b9"dependencies = ["app-error","jsonwebtoken",@@ -4054,7 +4054,7 @@ dependencies = [[[package]]name = "infra"version = "0.1.0"-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=c7176311ca375a672bc01bec0baa101986af023f#c7176311ca375a672bc01bec0baa101986af023f"+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=6ed0f4e#6ed0f4e21c622f692f0f0b2143523e9346b395b9"dependencies = ["anyhow","bytes",@@ -6720,7 +6720,7 @@ dependencies = [[[package]]name = "shared-entity"version = "0.1.0"-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=c7176311ca375a672bc01bec0baa101986af023f#c7176311ca375a672bc01bec0baa101986af023f"+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=6ed0f4e#6ed0f4e21c622f692f0f0b2143523e9346b395b9"dependencies = ["anyhow","app-error",@@ -8693,7 +8693,7 @@ dependencies = [[[package]]name = "workspace-template"version = "0.1.0"-source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=c7176311ca375a672bc01bec0baa101986af023f#c7176311ca375a672bc01bec0baa101986af023f"+source = "git+https://github.com/AppFlowy-IO/AppFlowy-Cloud?rev=6ed0f4e#6ed0f4e21c622f692f0f0b2143523e9346b395b9"dependencies = ["anyhow","async-trait",diff --git a/frontend/rust-lib/Cargo.toml b/frontend/rust-lib/Cargo.tomlindex 998495f165..ea5db0cbc9 100644--- a/frontend/rust-lib/Cargo.toml+++ b/frontend/rust-lib/Cargo.toml@@ -109,9 +109,9 @@ num_enum = "0.7.3"# Run the script.add_workspace_members:# scripts/tool/update_client_api_rev.sh new_rev_id# ⚠️⚠️⚠️️-client-api = { git = "https://github.com/AppFlowy-IO/AppFlowy-Cloud", rev = "c7176311ca375a672bc01bec0baa101986af023f" }-client-api-entity = { git = "https://github.com/AppFlowy-IO/AppFlowy-Cloud", rev = "c7176311ca375a672bc01bec0baa101986af023f" }-workspace-template = { git = "https://github.com/AppFlowy-IO/AppFlowy-Cloud", rev = "c7176311ca375a672bc01bec0baa101986af023f" }+client-api = { git = "https://github.com/AppFlowy-IO/AppFlowy-Cloud", rev = "6ed0f4e" }+client-api-entity = { git = "https://github.com/AppFlowy-IO/AppFlowy-Cloud", rev = "6ed0f4e" }+workspace-template = { git = "https://github.com/AppFlowy-IO/AppFlowy-Cloud", rev = "6ed0f4e" }[profile.dev]opt-level = 0diff --git a/frontend/rust-lib/flowy-ai/src/local_ai/controller.rs b/frontend/rust-lib/flowy-ai/src/local_ai/controller.rsindex 6b147b9c0c..feb03b721c 100644--- a/frontend/rust-lib/flowy-ai/src/local_ai/controller.rs+++ b/frontend/rust-lib/flowy-ai/src/local_ai/controller.rs@@ -23,8 +23,6 @@ use flowy_ai_pub::persistence::{use flowy_ai_pub::user_service::AIUserService;use futures_util::SinkExt;use lib_infra::util::get_operating_system;-use ollama_rs::generation::embeddings::request::{EmbeddingsInput, GenerateEmbeddingsRequest};-use ollama_rs::Ollama;use serde::{Deserialize, Serialize};use std::ops::Deref;use std::path::PathBuf;@@ -34,6 +32,11 @@ use tokio_stream::StreamExt;use tracing::{debug, error, info, instrument, warn};use uuid::Uuid;+#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]+use ollama_rs::generation::embeddings::request::{EmbeddingsInput, GenerateEmbeddingsRequest};+#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]+use ollama_rs::Ollama;+#[derive(Clone, Debug, Serialize, Deserialize)]pub struct LocalAISetting {pub ollama_server_url: String,@@ -59,6 +62,7 @@ pub struct LocalAIController {current_chat_id: ArcSwapOption<Uuid>,store_preferences: Weak<KVStorePreferences>,user_service: Arc<dyn AIUserService>,+ #[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]ollama: ArcSwapOption<Ollama>,}@@ -91,87 +95,105 @@ impl LocalAIController {res_impl,));- let ollama = ArcSwapOption::default();- let sys = get_operating_system();- if sys.is_desktop() {- let setting = local_ai_resource.get_llm_setting();- ollama.store(- Ollama::try_new(&setting.ollama_server_url)- .map(Arc::new)- .ok(),- );+ #[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]+ let ollama = {+ let mut ollama = ArcSwapOption::default();+ let sys = get_operating_system();+ if sys.is_desktop() {+ let setting = local_ai_resource.get_llm_setting();+ ollama.store(+ Ollama::try_new(&setting.ollama_server_url)+ .map(Arc::new)+ .ok(),+ );+ }+ ollama+ };- // Subscribe to state changes- let mut running_state_rx = local_ai.subscribe_running_state();- let cloned_llm_res = Arc::clone(&local_ai_resource);- let cloned_store_preferences = store_preferences.clone();- let cloned_local_ai = Arc::clone(&local_ai);- let cloned_user_service = Arc::clone(&user_service);-- // Spawn a background task to listen for plugin state changes- tokio::spawn(async move {- while let Some(state) = running_state_rx.next().await {- // Skip if we can't get workspace_id- let Ok(workspace_id) = cloned_user_service.workspace_id() else {- continue;- };+ // Subscribe to state changes+ let mut running_state_rx = local_ai.subscribe_running_state();+ let cloned_llm_res = Arc::clone(&local_ai_resource);+ let cloned_store_preferences = store_preferences.clone();+ let cloned_local_ai = Arc::clone(&local_ai);+ let cloned_user_service = Arc::clone(&user_service);- let key = crate::local_ai::controller::local_ai_enabled_key(&workspace_id.to_string());- info!("[AI Plugin] state: {:?}", state);-- // Read whether plugin is enabled from store; default to true- if let Some(store_preferences) = cloned_store_preferences.upgrade() {- let enabled = store_preferences.get_bool(&key).unwrap_or(true);- // Only check resource status if the plugin isn't in "UnexpectedStop" and is enabled- let (plugin_downloaded, lack_of_resource) =- if !matches!(state, RunningState::UnexpectedStop { .. }) && enabled {- // Possibly check plugin readiness and resource concurrency in parallel,- // but here we do it sequentially for clarity.- let downloaded = is_plugin_ready();- let resource_lack = cloned_llm_res.get_lack_of_resource().await;- (downloaded, resource_lack)- } else {- (false, None)- };-- // If plugin is running, retrieve version- let plugin_version = if matches!(state, RunningState::Running { .. }) {- match cloned_local_ai.plugin_info().await {- Ok(info) => Some(info.version),- Err(_) => None,- }+ // Spawn a background task to listen for plugin state changes+ tokio::spawn(async move {+ while let Some(state) = running_state_rx.next().await {+ // Skip if we can't get workspace_id+ let Ok(workspace_id) = cloned_user_service.workspace_id() else {+ continue;+ };++ let key = crate::local_ai::controller::local_ai_enabled_key(&workspace_id.to_string());+ info!("[AI Plugin] state: {:?}", state);++ // Read whether plugin is enabled from store; default to true+ if let Some(store_preferences) = cloned_store_preferences.upgrade() {+ let enabled = store_preferences.get_bool(&key).unwrap_or(true);+ // Only check resource status if the plugin isn't in "UnexpectedStop" and is enabled+ let (plugin_downloaded, lack_of_resource) =+ if !matches!(state, RunningState::UnexpectedStop { .. }) && enabled {+ // Possibly check plugin readiness and resource concurrency in parallel,+ // but here we do it sequentially for clarity.+ let downloaded = is_plugin_ready();+ let resource_lack = cloned_llm_res.get_lack_of_resource().await;+ (downloaded, resource_lack)} else {- None+ (false, None)};- // Broadcast the new local AI state- let new_state = RunningStatePB::from(state);- chat_notification_builder(- APPFLOWY_AI_NOTIFICATION_KEY,- ChatNotification::UpdateLocalAIState,- )- .payload(LocalAIPB {- enabled,- plugin_downloaded,- lack_of_resource,- state: new_state,- plugin_version,- })- .send();+ // If plugin is running, retrieve version+ let plugin_version = if matches!(state, RunningState::Running { .. }) {+ match cloned_local_ai.plugin_info().await {+ Ok(info) => Some(info.version),+ Err(_) => None,+ }} else {- warn!("[AI Plugin] store preferences is dropped");- }+ None+ };++ // Broadcast the new local AI state+ let new_state = RunningStatePB::from(state);+ chat_notification_builder(+ APPFLOWY_AI_NOTIFICATION_KEY,+ ChatNotification::UpdateLocalAIState,+ )+ .payload(LocalAIPB {+ enabled,+ plugin_downloaded,+ lack_of_resource,+ state: new_state,+ plugin_version,+ })+ .send();+ } else {+ warn!("[AI Plugin] store preferences is dropped");}- });+ }+ });++ #[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]+ {+ Self {+ ai_plugin: local_ai,+ resource: local_ai_resource,+ current_chat_id: ArcSwapOption::default(),+ store_preferences,+ user_service,+ ollama,+ }}- Self {- ai_plugin: local_ai,- resource: local_ai_resource,- current_chat_id: ArcSwapOption::default(),- store_preferences,- user_service,- ollama,+ #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]+ {+ Self {+ ai_plugin: local_ai,+ resource: local_ai_resource,+ current_chat_id: ArcSwapOption::default(),+ store_preferences,+ user_service,+ }}}#[instrument(level = "debug", skip_all)]@@ -307,18 +329,35 @@ impl LocalAIController {}pub async fn get_all_chat_local_models(&self) -> Vec<AIModel> {- self- .get_filtered_local_models(|name| !name.contains("embed"))- .await+ #[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]+ {+ self+ .get_filtered_local_models(|name| !name.contains("embed"))+ .await+ }++ #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]+ {+ vec![]+ }}pub async fn get_all_embedded_local_models(&self) -> Vec<AIModel> {- self- .get_filtered_local_models(|name| name.contains("embed"))- .await+ #[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]+ {+ self+ .get_filtered_local_models(|name| name.contains("embed"))+ .await+ }++ #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]+ {+ vec![]+ }}// Helper function to avoid code duplication in model retrieval+ #[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]async fn get_filtered_local_models<F>(&self, filter_fn: F) -> Vec<AIModel>whereF: Fn(&str) -> bool,@@ -344,35 +383,43 @@ impl LocalAIController {let mut conn = self.user_service.sqlite_connection(uid)?;match select_local_ai_model(&mut conn, model_name) {None => {- let ollama = self- .ollama- .load_full()- .ok_or_else(|| FlowyError::local_ai().with_context("ollama is not initialized"))?;-- let request = GenerateEmbeddingsRequest::new(- model_name.to_string(),- EmbeddingsInput::Single("Hello".to_string()),- );+ #[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]+ {+ let ollama = self+ .ollama+ .load_full()+ .ok_or_else(|| FlowyError::local_ai().with_context("ollama is not initialized"))?;++ let request = GenerateEmbeddingsRequest::new(+ model_name.to_string(),+ EmbeddingsInput::Single("Hello".to_string()),+ );- let model_type = match ollama.generate_embeddings(request).await {- Ok(value) => {- if value.embeddings.is_empty() {- ModelType::Chat- } else {- ModelType::Embedding- }- },- Err(_) => ModelType::Chat,- };+ let model_type = match ollama.generate_embeddings(request).await {+ Ok(value) => {+ if value.embeddings.is_empty() {+ ModelType::Chat+ } else {+ ModelType::Embedding+ }+ },+ Err(_) => ModelType::Chat,+ };++ upsert_local_ai_model(+ &mut conn,+ &LocalAIModelTable {+ name: model_name.to_string(),+ model_type: model_type as i16,+ },+ )?;+ Ok(model_type)+ }- upsert_local_ai_model(- &mut conn,- &LocalAIModelTable {- name: model_name.to_string(),- model_type: model_type as i16,- },- )?;- Ok(model_type)+ #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]+ {+ Ok(ModelType::Chat)+ }},Some(r) => Ok(ModelType::from(r.model_type)),}