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
fix: potential ai_repository not init (#6388)
Lucas5fbd07e96ace
diff --git a/frontend/appflowy_flutter/integration_test/cloud/appflowy_cloud_auth_test.dart b/frontend/appflowy_flutter/integration_test/cloud/appflowy_cloud_auth_test.dartindex dacc900103..f0982e044c 100644--- a/frontend/appflowy_flutter/integration_test/cloud/appflowy_cloud_auth_test.dart+++ b/frontend/appflowy_flutter/integration_test/cloud/appflowy_cloud_auth_test.dart@@ -86,10 +86,13 @@ void main() {// Open the setting page and sign outawait tester.openSettings();await tester.openSettingsPage(SettingsPage.cloud);+ await tester.pumpAndSettle();// the switch should be on by defaulttester.assertAppFlowyCloudEnableSyncSwitchValue(true);await tester.toggleEnableSync(AppFlowyCloudEnableSync);+ // wait for the switch animation+ await tester.wait(250);// the switch should be offtester.assertAppFlowyCloudEnableSyncSwitchValue(false);@@ -97,6 +100,7 @@ void main() {// the switch should be on after togglingawait tester.toggleEnableSync(AppFlowyCloudEnableSync);tester.assertAppFlowyCloudEnableSyncSwitchValue(true);+ await tester.wait(250);});});}diff --git a/frontend/appflowy_flutter/integration_test/cloud/document/document_delete_block_test.dart b/frontend/appflowy_flutter/integration_test/cloud/document/document_delete_block_test.dartnew file mode 100644index 0000000000..277f878fb5--- /dev/null+++ b/frontend/appflowy_flutter/integration_test/cloud/document/document_delete_block_test.dart@@ -0,0 +1,60 @@+import 'package:appflowy/env/cloud_env.dart';+import 'package:appflowy/generated/locale_keys.g.dart';+import 'package:appflowy/plugins/document/presentation/editor_plugins/actions/drag_to_reorder/draggable_option_button.dart';+import 'package:appflowy_editor/appflowy_editor.dart';+import 'package:easy_localization/easy_localization.dart';+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:integration_test/integration_test.dart';++import '../../shared/constants.dart';+import '../../shared/util.dart';++void main() {+ IntegrationTestWidgetsFlutterBinding.ensureInitialized();++ group('document delete block: ', () {+ testWidgets('hover on the block and delete it', (tester) async {+ await tester.initializeAppFlowy(+ cloudType: AuthenticatorType.appflowyCloudSelfHost,+ );+ await tester.tapGoogleLoginInButton();+ await tester.expectToSeeHomePageWithGetStartedPage();++ // open getting started page+ await tester.openPage(Constants.gettingStartedPageName);++ // before delete+ final path = [1];+ final beforeDeletedBlock = tester.editor.getNodeAtPath(path);++ // hover on the block and delete it+ final optionButton = find.byWidgetPredicate(+ (widget) =>+ widget is DraggableOptionButton &&+ widget.blockComponentContext.node.path.equals(path),+ );++ await tester.hoverOnWidget(+ optionButton,+ onHover: () async {+ // click the delete button+ await tester.tapButton(optionButton);+ },+ );+ await tester.pumpAndSettle(Durations.short1);++ // click the delete button+ final deleteButton =+ find.findTextInFlowyText(LocaleKeys.button_delete.tr());+ await tester.tapButton(deleteButton);++ // wait for the deletion+ await tester.pumpAndSettle(Durations.short1);++ // check if the block is deleted+ final afterDeletedBlock = tester.editor.getNodeAtPath([1]);+ expect(afterDeletedBlock.id, isNot(equals(beforeDeletedBlock.id)));+ });+ });+}diff --git a/frontend/appflowy_flutter/integration_test/cloud/document/document_drag_block_test.dart b/frontend/appflowy_flutter/integration_test/cloud/document/document_drag_block_test.dartindex 43b4c29dc5..e8d366060a 100644--- a/frontend/appflowy_flutter/integration_test/cloud/document/document_drag_block_test.dart+++ b/frontend/appflowy_flutter/integration_test/cloud/document/document_drag_block_test.dart@@ -1,33 +1,9 @@-// ignore_for_file: unused_import--import 'dart:io';-import 'package:appflowy/env/cloud_env.dart';-import 'package:appflowy/generated/locale_keys.g.dart';-import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/loading.dart';-import 'package:appflowy/shared/feature_flags.dart';-import 'package:appflowy/startup/startup.dart';-import 'package:appflowy/user/application/auth/af_cloud_mock_auth_service.dart';-import 'package:appflowy/user/application/auth/auth_service.dart';-import 'package:appflowy/workspace/application/settings/prelude.dart';-import 'package:appflowy/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_actions.dart';-import 'package:appflowy/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_menu.dart';-import 'package:appflowy/workspace/presentation/home/menu/sidebar/workspace/sidebar_workspace.dart';-import 'package:appflowy/workspace/presentation/settings/widgets/setting_appflowy_cloud.dart';-import 'package:appflowy/workspace/presentation/widgets/user_avatar.dart';-import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';-import 'package:easy_localization/easy_localization.dart';-import 'package:flowy_infra/uuid.dart';import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';import 'package:integration_test/integration_test.dart';-import 'package:path/path.dart' as p;import '../../shared/constants.dart';-import '../../shared/database_test_op.dart';-import '../../shared/dir.dart';-import '../../shared/emoji.dart';-import '../../shared/mock/mock_file_picker.dart';import '../../shared/util.dart';void main() {diff --git a/frontend/appflowy_flutter/integration_test/desktop/document/document_copy_and_paste_test.dart b/frontend/appflowy_flutter/integration_test/desktop/document/document_copy_and_paste_test.dartindex 457934dff4..d178f584b0 100644--- a/frontend/appflowy_flutter/integration_test/desktop/document/document_copy_and_paste_test.dart+++ b/frontend/appflowy_flutter/integration_test/desktop/document/document_copy_and_paste_test.dart@@ -207,7 +207,7 @@ void main() {final image = await rootBundle.load('assets/test/images/sample.png');final bytes = image.buffer.asUint8List();await tester.pasteContent(image: ('png', bytes), (editorState) {- expect(editorState.document.root.children.length, 2);+ expect(editorState.document.root.children.length, 1);final node = editorState.getNodeAtPath([0])!;expect(node.type, ImageBlockKeys.type);expect(node.attributes[ImageBlockKeys.url], isNotNull);@@ -218,7 +218,7 @@ void main() {final image = await rootBundle.load('assets/test/images/sample.jpeg');final bytes = image.buffer.asUint8List();await tester.pasteContent(image: ('jpeg', bytes), (editorState) {- expect(editorState.document.root.children.length, 2);+ expect(editorState.document.root.children.length, 1);final node = editorState.getNodeAtPath([0])!;expect(node.type, ImageBlockKeys.type);expect(node.attributes[ImageBlockKeys.url], isNotNull);@@ -280,7 +280,7 @@ void main() {html: html,image: ('png', bytes),(editorState) {- expect(editorState.document.root.children.length, 2);+ expect(editorState.document.root.children.length, 1);final node = editorState.getNodeAtPath([0])!;expect(node.type, ImageBlockKeys.type);},@@ -313,6 +313,7 @@ void main() {(tester) async {const url = 'https://appflowy.io';await tester.pasteContent(plainText: url, (editorState) {+ // the second one is the paragraph nodeexpect(editorState.document.root.children.length, 2);final node = editorState.getNodeAtPath([0])!;expect(node.type, LinkPreviewBlockKeys.type);diff --git a/frontend/appflowy_flutter/lib/plugins/document/application/document_bloc.dart b/frontend/appflowy_flutter/lib/plugins/document/application/document_bloc.dartindex dc6a3aeb42..48d1000880 100644--- a/frontend/appflowy_flutter/lib/plugins/document/application/document_bloc.dart+++ b/frontend/appflowy_flutter/lib/plugins/document/application/document_bloc.dart@@ -238,12 +238,24 @@ class DocumentBloc extends Bloc<DocumentEvent, DocumentState> {return;}+ if (enableDocumentInternalLog) {+ Log.debug(+ '[TransactionAdapter] 1. transaction before apply: ${transaction.hashCode}',+ );+ }+// apply transaction to backendawait _transactionAdapter.apply(transaction, editorState);// check if the document is empty.await _applyRules();+ if (enableDocumentInternalLog) {+ Log.debug(+ '[TransactionAdapter] 4. transaction after apply: ${transaction.hashCode}',+ );+ }+if (!isClosed) {// ignore: invalid_use_of_visible_for_testing_memberemit(state.copyWith(isDocumentEmpty: editorState.document.isEmpty));@@ -270,25 +282,9 @@ class DocumentBloc extends Bloc<DocumentEvent, DocumentState> {Future<void> _applyRules() async {await Future.wait([_ensureAtLeastOneParagraphExists(),- _ensureLastNodeIsEditable(),]);}- Future<void> _ensureLastNodeIsEditable() async {- final editorState = state.editorState;- if (editorState == null) {- return;- }- final document = editorState.document;- final lastNode = document.root.children.lastOrNull;- if (lastNode == null || lastNode.delta == null) {- final transaction = editorState.transaction;- transaction.insertNode([document.root.children.length], paragraphNode());- transaction.afterSelection = transaction.beforeSelection;- await editorState.apply(transaction);- }- }-Future<void> _ensureAtLeastOneParagraphExists() async {final editorState = state.editorState;if (editorState == null) {diff --git a/frontend/appflowy_flutter/lib/plugins/document/application/editor_transaction_adapter.dart b/frontend/appflowy_flutter/lib/plugins/document/application/editor_transaction_adapter.dartindex 1038bea043..057e06768d 100644--- a/frontend/appflowy_flutter/lib/plugins/document/application/editor_transaction_adapter.dart+++ b/frontend/appflowy_flutter/lib/plugins/document/application/editor_transaction_adapter.dart@@ -22,7 +22,6 @@ import 'package:appflowy_editor/appflowy_editor.dart'blockComponentDelta;import 'package:collection/collection.dart';import 'package:nanoid/nanoid.dart';-import 'package:synchronized/synchronized.dart';const _kExternalTextType = 'text';@@ -39,27 +38,20 @@ class TransactionAdapter {final DocumentService documentService;final String documentId;- // Controls the apply transaction flow- //- // Ensures transactions are applied in the correct order when dependencies exist.- // Example: If transaction B depends on transaction A, A must be applied first.- final Lock _applyLock = Lock();-Future<void> apply(Transaction transaction, EditorState editorState) async {- await _applyLock.synchronized(- () async {- if (enableDocumentInternalLog) {- Log.debug('apply transaction begin ${transaction.hashCode}');- }+ if (enableDocumentInternalLog) {+ Log.debug(+ '[TransactionAdapter] 2. apply transaction begin ${transaction.hashCode} in $hashCode',+ );+ }- await _applyInternal(transaction, editorState);+ await _applyInternal(transaction, editorState);- if (enableDocumentInternalLog) {- Log.debug('apply transaction end ${transaction.hashCode}');- }- },- timeout: const Duration(seconds: 5),- );+ if (enableDocumentInternalLog) {+ Log.debug(+ '[TransactionAdapter] 3. apply transaction end ${transaction.hashCode} in $hashCode',+ );+ }}Future<void> _applyInternal(diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/actions/block_action_option_button.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/actions/block_action_option_button.dartindex 41ce1e2b27..ea90a0b2d9 100644--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/actions/block_action_option_button.dart+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/actions/block_action_option_button.dart@@ -68,6 +68,9 @@ class _BlockOptionButtonState extends State<BlockOptionButton> {},onClosed: () {WidgetsBinding.instance.addPostFrameCallback((timeStamp) {+ if (!mounted) {+ return;+ }widget.editorState.selectionType = null;widget.editorState.selection = null;widget.blockComponentState.alwaysShowActions = false;diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/copy_and_paste/paste_from_image.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/copy_and_paste/paste_from_image.dartindex 73a1837890..4e932ee2f2 100644--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/copy_and_paste/paste_from_image.dart+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/copy_and_paste/paste_from_image.dart@@ -8,6 +8,7 @@ import 'package:appflowy/plugins/document/presentation/editor_plugins/image/custimport 'package:appflowy/plugins/document/presentation/editor_plugins/image/image_util.dart';import 'package:appflowy/shared/patterns/file_type_patterns.dart';import 'package:appflowy/startup/startup.dart';+import 'package:appflowy/util/default_extensions.dart';import 'package:appflowy/workspace/application/settings/application_data_storage.dart';import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';import 'package:appflowy_backend/log.dart';@@ -20,13 +21,6 @@ import 'package:provider/provider.dart';import 'package:universal_platform/universal_platform.dart';extension PasteFromImage on EditorState {- static final supportedImageFormats = [- 'png',- 'jpeg',- 'gif',- 'webp',- ];-Future<void> dropImages(Node dropNode,List<XFile> files,@@ -75,7 +69,7 @@ extension PasteFromImage on EditorState {return false;}- if (!supportedImageFormats.contains(format)) {+ if (!defaultImageExtensions.contains(format)) {Log.info('unsupported format: $format');if (UniversalPlatform.isMobile) {showToastNotification(@@ -129,7 +123,6 @@ extension PasteFromImage on EditorState {await insertImageNode(path, selection: selection);}- await File(copyToPath).delete();return true;} catch (e) {Log.error('cannot copy image file', e);diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_bloc.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_bloc.dartindex 18c0c4f3a0..55e450141b 100644--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_bloc.dart+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_bloc.dart@@ -1,7 +1,8 @@+import 'dart:async';+import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/ai_client.dart';import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_action.dart';import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';-import 'package:appflowy/startup/startup.dart';import 'package:appflowy/user/application/ai_service.dart';import 'package:appflowy_backend/log.dart';import 'package:appflowy_editor/appflowy_editor.dart';@@ -16,13 +17,15 @@ class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {required this.node,required this.editorState,required this.action,+ this.enableLogging = true,}) : super(SmartEditState.initial(action),) {on<SmartEditEvent>((event, emit) async {await event.when(- initial: () async {- aiRepository = await getIt.getAsync<AIRepository>();+ initial: (aiRepositoryProvider) async {+ aiRepository = await aiRepositoryProvider;+ aiRepositoryCompleter.complete();},started: () async {await _requestCompletions();@@ -57,7 +60,9 @@ class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {final Node node;final EditorState editorState;final SmartEditAction action;-+ final bool enableLogging;+ // used to wait for the aiRepository to be initialized+ final aiRepositoryCompleter = Completer();late final AIRepository aiRepository;bool isCanceled = false;@@ -65,11 +70,15 @@ class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {Future<void> _requestCompletions({bool rewrite = false,}) async {+ await aiRepositoryCompleter.future;+if (rewrite) {add(const SmartEditEvent.update('', true));}- Log.info('[smart_edit] request completions');+ if (enableLogging) {+ Log.info('[smart_edit] request completions');+ }final content = node.attributes[SmartEditBlockKeys.content] as String;await aiRepository.streamCompletion(@@ -79,7 +88,9 @@ class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {if (isCanceled) {return;}- Log.info('[smart_edit] start generating');+ if (enableLogging) {+ Log.info('[smart_edit] start generating');+ }add(const SmartEditEvent.update('', true));},onProcess: (text) async {@@ -87,7 +98,7 @@ class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {return;}// only display the log in debug mode- if (kDebugMode) {+ if (enableLogging) {Log.debug('[smart_edit] onProcess: $text');}final newResult = state.result + text;@@ -97,14 +108,18 @@ class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {if (isCanceled) {return;}- Log.info('[smart_edit] end generating');+ if (enableLogging) {+ Log.info('[smart_edit] end generating');+ }add(SmartEditEvent.update('${state.result}\n', false));},onError: (error) async {if (isCanceled) {return;}- Log.info('[smart_edit] onError: $error');+ if (enableLogging) {+ Log.info('[smart_edit] onError: $error');+ }await _exit();},);@@ -196,7 +211,9 @@ class SmartEditBloc extends Bloc<SmartEditEvent, SmartEditState> {@freezedclass SmartEditEvent with _$SmartEditEvent {- const factory SmartEditEvent.initial() = _Initial;+ const factory SmartEditEvent.initial(+ Future<AIRepository> aiRepositoryProvider,+ ) = _Initial;const factory SmartEditEvent.started() = _Started;const factory SmartEditEvent.rewrite() = _Rewrite;const factory SmartEditEvent.replace() = _Replace;diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_node_widget.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_node_widget.dartindex 99b23008c4..ff0124aaf7 100644--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_node_widget.dart+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_node_widget.dart@@ -1,8 +1,10 @@import 'dart:async';import 'package:appflowy/generated/locale_keys.g.dart';+import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/ai_client.dart';import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_action.dart';import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_bloc.dart';+import 'package:appflowy/startup/startup.dart';import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';import 'package:appflowy_editor/appflowy_editor.dart';import 'package:appflowy_popover/appflowy_popover.dart';@@ -98,7 +100,7 @@ class _SmartEditBlockComponentWidgetStatenode: widget.node,editorState: editorState,action: action,- )..add(const SmartEditEvent.initial());+ )..add(SmartEditEvent.initial(getIt.getAsync<AIRepository>()));}@overridediff --git a/frontend/appflowy_flutter/test/bloc_test/smart_edit_test/smart_editor_bloc_test.dart b/frontend/appflowy_flutter/test/bloc_test/smart_edit_test/smart_editor_bloc_test.dartnew file mode 100644index 0000000000..bc81d388cc--- /dev/null+++ b/frontend/appflowy_flutter/test/bloc_test/smart_edit_test/smart_editor_bloc_test.dart@@ -0,0 +1,94 @@+import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/ai_client.dart';+import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/service/error.dart';+import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_action.dart';+import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/smart_edit_bloc.dart';+import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';+import 'package:appflowy_backend/protobuf/flowy-ai/entities.pb.dart';+import 'package:appflowy_editor/appflowy_editor.dart';+import 'package:bloc_test/bloc_test.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:mocktail/mocktail.dart';++class MockAIRepository extends Mock implements AIRepository {+ @override+ Future<void> streamCompletion({+ required String text,+ required CompletionTypePB completionType,+ required Future<void> Function() onStart,+ required Future<void> Function(String text) onProcess,+ required Future<void> Function() onEnd,+ required void Function(AIError error) onError,+ }) async {+ await onStart();+ final lines = text.split('\n\n');+ for (var i = 0; i < lines.length; i++) {+ await onProcess('UPDATED: ${lines[i]}\n\n');+ }+ await onEnd();+ }+}++void main() {+ group('SmartEditorBloc: ', () {+ blocTest<SmartEditBloc, SmartEditState>(+ 'send request before the bloc is initialized',+ build: () {+ const text1 = '1. Select text to style using the toolbar menu.';+ const text2 = '2. Discover more styling options in Aa.';+ const text3 =+ '3. AppFlowy empowers you to beautifully and effortlessly style your content.';+ final document = Document(+ root: pageNode(+ children: [+ paragraphNode(text: text1),+ paragraphNode(text: text2),+ paragraphNode(text: text3),+ ],+ ),+ );+ final editorState = EditorState(document: document);+ editorState.selection = Selection(+ start: Position(path: [0]),+ end: Position(path: [2], offset: text3.length),+ );++ final node = smartEditNode(+ action: SmartEditAction.makeItLonger,+ content: [text1, text2, text3].join('\n'),+ );+ return SmartEditBloc(+ node: node,+ editorState: editorState,+ action: SmartEditAction.makeItLonger,+ enableLogging: false,+ );+ },+ act: (bloc) {+ bloc.add(SmartEditEvent.initial(Future.value(MockAIRepository())));+ bloc.add(const SmartEditEvent.rewrite());+ },+ expect: () => [+ isA<SmartEditState>()+ .having((s) => s.loading, 'loading', true)+ .having((s) => s.result, 'result', isEmpty),+ isA<SmartEditState>()+ .having((s) => s.loading, 'loading', false)+ .having((s) => s.result, 'result', isNotEmpty)+ .having((s) => s.result, 'result', contains('UPDATED:')),+ isA<SmartEditState>().having((s) => s.loading, 'loading', false),+ ],+ );+ });+}+++// [+// _$SmartEditStateImpl:SmartEditState(loading: true, result: , action: SmartEditAction.makeItLonger),+// _$SmartEditStateImpl:SmartEditState(loading: false, result: UPDATED: 1. Select text to style using the toolbar menu.+// 2. Discover more styling options in Aa.+// 3. AppFlowy empowers you to beautifully and effortlessly style your content.++// , action: SmartEditAction.makeItLonger),+// _$SmartEditStateImpl:SmartEditState(loading: false, result:+// , action: SmartEditAction.makeItLonger)+// ]\ No newline at end of file