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: ai writer block (#7406)
Richard Shiuefe6217bd8290
diff --git a/frontend/appflowy_flutter/integration_test/desktop/cloud/document/document_ai_writer_test.dart b/frontend/appflowy_flutter/integration_test/desktop/cloud/document/document_ai_writer_test.dartindex 32737a23d1..f163608ccb 100644--- a/frontend/appflowy_flutter/integration_test/desktop/cloud/document/document_ai_writer_test.dart+++ b/frontend/appflowy_flutter/integration_test/desktop/cloud/document/document_ai_writer_test.dart@@ -33,7 +33,7 @@ void main() {await tester.editor.tapSlashMenuItemWithName(LocaleKeys.document_slashMenu_name_aiWriter.tr(),);- expect(find.byType(AIWriterBlockComponent), findsOneWidget);+ expect(find.byType(AiWriterBlockComponent), findsOneWidget);// switch to another pageawait tester.openPage(Constants.gettingStartedPageName);@@ -41,7 +41,7 @@ void main() {await tester.openPage(pageName);// expect the ai writer block is not in the document- expect(find.byType(AIWriterBlockComponent), findsNothing);+ expect(find.byType(AiWriterBlockComponent), findsNothing);});});}diff --git a/frontend/appflowy_flutter/integration_test/shared/mock/mock_openai_repository.dart b/frontend/appflowy_flutter/integration_test/shared/mock/mock_openai_repository.dartdeleted file mode 100644index ec1891dea8..0000000000--- a/frontend/appflowy_flutter/integration_test/shared/mock/mock_openai_repository.dart+++ /dev/null@@ -1,81 +0,0 @@-import 'dart:async';-import 'dart:convert';--import 'package:appflowy/ai/service/error.dart';-import 'package:appflowy/ai/service/openai_client.dart';-import 'package:appflowy/ai/service/text_completion.dart';-import 'package:http/http.dart' as http;-import 'package:mocktail/mocktail.dart';--class MyMockClient extends Mock implements http.Client {- @override- Future<http.StreamedResponse> send(http.BaseRequest request) async {- final requestType = request.method;- final requestUri = request.url;-- if (requestType == 'POST' &&- requestUri == OpenAIRequestType.textCompletion.uri) {- final responseHeaders = <String, String>{- 'content-type': 'text/event-stream',- };- final responseBody = Stream.fromIterable([- utf8.encode(- '{ "choices": [{"text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula ", "index": 0, "logprobs": null, "finish_reason": null}]}',- ),- utf8.encode('\n'),- utf8.encode('[DONE]'),- ]);-- // Return a mocked response with the expected data- return http.StreamedResponse(responseBody, 200, headers: responseHeaders);- }-- // Return an error response for any other request- return http.StreamedResponse(const Stream.empty(), 404);- }-}--class MockOpenAIRepository extends HttpOpenAIRepository {- MockOpenAIRepository() : super(apiKey: 'dummyKey', client: MyMockClient());-- @override- Future<void> getStreamedCompletions({- required String prompt,- required Future<void> Function() onStart,- required Future<void> Function(TextCompletionResponse response) onProcess,- required Future<void> Function() onEnd,- required void Function(AIError error) onError,- String? suffix,- int maxTokens = 2048,- double temperature = 0.3,- bool useAction = false,- }) async {- final request = http.Request('POST', OpenAIRequestType.textCompletion.uri);- final response = await client.send(request);-- String previousSyntax = '';- if (response.statusCode == 200) {- await for (final chunk in response.stream- .transform(const Utf8Decoder())- .transform(const LineSplitter())) {- await onStart();- final data = chunk.trim().split('data: ');- if (data[0] != '[DONE]') {- final response = TextCompletionResponse.fromJson(- json.decode(data[0]),- );- if (response.choices.isNotEmpty) {- final text = response.choices.first.text;- if (text == previousSyntax && text == '\n') {- continue;- }- await onProcess(response);- previousSyntax = response.choices.first.text;- }- } else {- await onEnd();- }- }- }- }-}diff --git a/frontend/appflowy_flutter/lib/ai/ai.dart b/frontend/appflowy_flutter/lib/ai/ai.dartindex a6fa49ef68..e3f52a8168 100644--- a/frontend/appflowy_flutter/lib/ai/ai.dart+++ b/frontend/appflowy_flutter/lib/ai/ai.dart@@ -1,6 +1,10 @@+export 'service/ai_entities.dart';+export 'service/ai_prompt_input_bloc.dart';+export 'service/appflowy_ai_service.dart';+export 'service/error.dart';export 'widgets/loading_indicator.dart';export 'widgets/prompt_input/action_buttons.dart';-export 'widgets/prompt_input/desktop_input_text_field.dart';+export 'widgets/prompt_input/desktop_prompt_text_field.dart';export 'widgets/prompt_input/file_attachment_list.dart';export 'widgets/prompt_input/layout_define.dart';export 'widgets/prompt_input/mention_page_bottom_sheet.dart';diff --git a/frontend/appflowy_flutter/lib/ai/service/ai_client.dart b/frontend/appflowy_flutter/lib/ai/service/ai_client.dartdeleted file mode 100644index a5c40c0569..0000000000--- a/frontend/appflowy_flutter/lib/ai/service/ai_client.dart+++ /dev/null@@ -1,34 +0,0 @@-import 'package:appflowy_backend/protobuf/flowy-ai/protobuf.dart';-import 'package:appflowy_result/appflowy_result.dart';--import 'error.dart';-import 'text_completion.dart';--abstract class AIRepository {- Future<void> getStreamedCompletions({- required String prompt,- required Future<void> Function() onStart,- required Future<void> Function(TextCompletionResponse response) onProcess,- required Future<void> Function() onEnd,- required void Function(AIError error) onError,- String? suffix,- int maxTokens = 2048,- double temperature = 0.3,- bool useAction = false,- });-- Future<void> streamCompletion({- String? objectId,- 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,- });-- Future<FlowyResult<List<String>, AIError>> generateImage({- required String prompt,- int n = 1,- });-}diff --git a/frontend/appflowy_flutter/lib/ai/service/ai_entities.dart b/frontend/appflowy_flutter/lib/ai/service/ai_entities.dartnew file mode 100644index 0000000000..b8592bc32b--- /dev/null+++ b/frontend/appflowy_flutter/lib/ai/service/ai_entities.dart@@ -0,0 +1,85 @@+import 'package:appflowy/generated/flowy_svgs.g.dart';+import 'package:appflowy/generated/locale_keys.g.dart';+import 'package:appflowy_backend/protobuf/flowy-ai/protobuf.dart';+import 'package:easy_localization/easy_localization.dart';+import 'package:equatable/equatable.dart';++class PredefinedFormat extends Equatable {+ const PredefinedFormat({+ required this.imageFormat,+ required this.textFormat,+ });++ final ImageFormat imageFormat;+ final TextFormat? textFormat;++ PredefinedFormatPB toPB() {+ return PredefinedFormatPB(+ imageFormat: switch (imageFormat) {+ ImageFormat.text => ResponseImageFormatPB.TextOnly,+ ImageFormat.image => ResponseImageFormatPB.ImageOnly,+ ImageFormat.textAndImage => ResponseImageFormatPB.TextAndImage,+ },+ textFormat: switch (textFormat) {+ TextFormat.paragraph => ResponseTextFormatPB.Paragraph,+ TextFormat.bulletList => ResponseTextFormatPB.BulletedList,+ TextFormat.numberedList => ResponseTextFormatPB.NumberedList,+ TextFormat.table => ResponseTextFormatPB.Table,+ _ => null,+ },+ );+ }++ @override+ List<Object?> get props => [imageFormat, textFormat];+}++enum ImageFormat {+ text,+ image,+ textAndImage;++ bool get hasText => this == text || this == textAndImage;++ FlowySvgData get icon {+ return switch (this) {+ ImageFormat.text => FlowySvgs.ai_text_s,+ ImageFormat.image => FlowySvgs.ai_image_s,+ ImageFormat.textAndImage => FlowySvgs.ai_text_image_s,+ };+ }++ String get i18n {+ return switch (this) {+ ImageFormat.text => LocaleKeys.chat_changeFormat_textOnly.tr(),+ ImageFormat.image => LocaleKeys.chat_changeFormat_imageOnly.tr(),+ ImageFormat.textAndImage =>+ LocaleKeys.chat_changeFormat_textAndImage.tr(),+ };+ }+}++enum TextFormat {+ paragraph,+ bulletList,+ numberedList,+ table;++ FlowySvgData get icon {+ return switch (this) {+ TextFormat.paragraph => FlowySvgs.ai_paragraph_s,+ TextFormat.bulletList => FlowySvgs.ai_list_s,+ TextFormat.numberedList => FlowySvgs.ai_number_list_s,+ TextFormat.table => FlowySvgs.ai_table_s,+ };+ }++ String get i18n {+ return switch (this) {+ TextFormat.paragraph => LocaleKeys.chat_changeFormat_text.tr(),+ TextFormat.bulletList => LocaleKeys.chat_changeFormat_bullet.tr(),+ TextFormat.numberedList => LocaleKeys.chat_changeFormat_number.tr(),+ TextFormat.table => LocaleKeys.chat_changeFormat_table.tr(),+ };+ }+}diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/application/ai_prompt_input_bloc.dart b/frontend/appflowy_flutter/lib/ai/service/ai_prompt_input_bloc.dartsimilarity index 84%rename from frontend/appflowy_flutter/lib/plugins/ai_chat/application/ai_prompt_input_bloc.dartrename to frontend/appflowy_flutter/lib/ai/service/ai_prompt_input_bloc.dartindex fdbcbb4cc0..e80b196db6 100644--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/application/ai_prompt_input_bloc.dart+++ b/frontend/appflowy_flutter/lib/ai/service/ai_prompt_input_bloc.dart@@ -10,12 +10,15 @@ import 'package:appflowy_result/appflowy_result.dart';import 'package:flutter_bloc/flutter_bloc.dart';import 'package:freezed_annotation/freezed_annotation.dart';+import 'ai_entities.dart';+part 'ai_prompt_input_bloc.freezed.dart';class AIPromptInputBloc extends Bloc<AIPromptInputEvent, AIPromptInputState> {- AIPromptInputBloc()- : _listener = LocalLLMListener(),- super(AIPromptInputState.initial()) {+ AIPromptInputBloc({+ required PredefinedFormat? predefinedFormat,+ }) : _listener = LocalLLMListener(),+ super(AIPromptInputState.initial(predefinedFormat)) {_dispatch();_startListening();_init();@@ -65,6 +68,16 @@ class AIPromptInputBloc extends Bloc<AIPromptInputEvent, AIPromptInputState> {),);},+ toggleShowPredefinedFormat: () {+ emit(+ state.copyWith(+ showPredefinedFormats: !state.showPredefinedFormats,+ ),+ );+ },+ updatePredefinedFormat: (format) {+ emit(state.copyWith(predefinedFormat: format));+ },attachFile: (filePath, fileName) {final newFile = ChatFile.fromFilePath(filePath);if (newFile != null) {@@ -152,6 +165,11 @@ class AIPromptInputEvent with _$AIPromptInputEvent {const factory AIPromptInputEvent.updatePluginState(LocalAIPluginStatePB chatState,) = _UpdatePluginState;+ const factory AIPromptInputEvent.toggleShowPredefinedFormat() =+ _ToggleShowPredefinedFormat;+ const factory AIPromptInputEvent.updatePredefinedFormat(+ PredefinedFormat format,+ ) = _UpdatePredefinedFormat;const factory AIPromptInputEvent.attachFile(String filePath,String fileName,@@ -167,14 +185,19 @@ class AIPromptInputState with _$AIPromptInputState {const factory AIPromptInputState({required AIType aiType,required bool supportChatWithFile,+ required bool showPredefinedFormats,+ required PredefinedFormat? predefinedFormat,required LocalAIChatPB? chatState,required List<ChatFile> attachedFiles,required List<ViewPB> mentionedPages,}) = _AIPromptInputState;- factory AIPromptInputState.initial() => const AIPromptInputState(+ factory AIPromptInputState.initial(PredefinedFormat? format) =>+ AIPromptInputState(aiType: AIType.appflowyAI,supportChatWithFile: false,+ showPredefinedFormats: format != null,+ predefinedFormat: format,chatState: null,attachedFiles: [],mentionedPages: [],diff --git a/frontend/appflowy_flutter/lib/ai/service/appflowy_ai_service.dart b/frontend/appflowy_flutter/lib/ai/service/appflowy_ai_service.dartindex 540e9f2804..2709b1d59c 100644--- a/frontend/appflowy_flutter/lib/ai/service/appflowy_ai_service.dart+++ b/frontend/appflowy_flutter/lib/ai/service/appflowy_ai_service.dart@@ -3,137 +3,109 @@ import 'dart:ffi';import 'dart:isolate';import 'package:appflowy/generated/locale_keys.g.dart';+import 'package:appflowy/shared/list_extension.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:easy_localization/easy_localization.dart';import 'package:fixnum/fixnum.dart' as fixnum;-import 'ai_client.dart';+import 'ai_entities.dart';import 'error.dart';-import 'text_completion.dart';--enum AskAIAction {- summarize,- fixSpelling,- improveWriting,- makeItLonger;-- String get toInstruction => switch (this) {- summarize => 'Tl;dr',- fixSpelling => 'Correct this to standard English:',- improveWriting => 'Rewrite this in your own words:',- makeItLonger => 'Make this text longer:',- };-- String prompt(String input) => switch (this) {- summarize => '$input\n\n$toInstruction',- _ => "$toInstruction\n\n$input",- };-- static AskAIAction from(int index) => switch (index) {- 0 => summarize,- 1 => fixSpelling,- 2 => improveWriting,- 3 => makeItLonger,- _ => fixSpelling- };-- String get name => switch (this) {- summarize => LocaleKeys.document_plugins_smartEditSummarize.tr(),- fixSpelling => LocaleKeys.document_plugins_smartEditFixSpelling.tr(),- improveWriting =>- LocaleKeys.document_plugins_smartEditImproveWriting.tr(),- makeItLonger => LocaleKeys.document_plugins_smartEditMakeLonger.tr(),- };-}-class AppFlowyAIService implements AIRepository {- @override- Future<FlowyResult<List<String>, AIError>> generateImage({- required String prompt,- int n = 1,- }) {- throw UnimplementedError();- }-- @override- Future<void> getStreamedCompletions({- required String prompt,+abstract class AIRepository {+ Future<void> streamCompletion({+ String? objectId,+ required String text,+ PredefinedFormat? format,+ required CompletionTypePB completionType,required Future<void> Function() onStart,- required Future<void> Function(TextCompletionResponse response) onProcess,+ required Future<void> Function(String text) onProcess,required Future<void> Function() onEnd,required void Function(AIError error) onError,- String? suffix,- int maxTokens = 2048,- double temperature = 0.3,- bool useAction = false,- }) {- throw UnimplementedError();- }+ });+}+class AppFlowyAIService implements AIRepository {@override- Future<CompletionStream> streamCompletion({+ Future<(String, CompletionStream)?> streamCompletion({String? objectId,required String text,+ PredefinedFormat? format,+ List<String> sourceIds = const [],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 {- final stream = CompletionStream(- onStart,- onProcess,- onEnd,- onError,+ final stream = AppFlowyCompletionStream(+ onStart: onStart,+ onProcess: onProcess,+ onEnd: onEnd,+ onError: onError,);- final List<String> ragIds = [];- if (objectId != null) {- ragIds.add(objectId);- }final payload = CompleteTextPB(text: text,completionType: completionType,+ format: format?.toPB(),streamPort: fixnum.Int64(stream.nativePort),- objectId: objectId ?? "",- ragIds: ragIds,+ objectId: objectId ?? '',+ ragIds: [+ if (objectId != null) objectId,+ ...sourceIds,+ ].unique(),);- // ignore: unawaited_futures- AIEventCompleteText(payload).send();- return stream;+ return AIEventCompleteText(payload).send().fold(+ (task) => (task.taskId, stream),+ (error) {+ Log.error(error);+ return null;+ },+ );}}-CompletionTypePB completionTypeFromInt(AskAIAction action) {- switch (action) {- case AskAIAction.summarize:- return CompletionTypePB.MakeShorter;- case AskAIAction.fixSpelling:- return CompletionTypePB.SpellingAndGrammar;- case AskAIAction.improveWriting:- return CompletionTypePB.ImproveWriting;- case AskAIAction.makeItLonger:- return CompletionTypePB.MakeLonger;- }+abstract class CompletionStream {+ CompletionStream({+ required this.onStart,+ required this.onProcess,+ required this.onEnd,+ required this.onError,+ });++ final Future<void> Function() onStart;+ final Future<void> Function(String text) onProcess;+ final Future<void> Function() onEnd;+ final void Function(AIError error) onError;}-class CompletionStream {- CompletionStream(- Future<void> Function() onStart,- Future<void> Function(String text) onProcess,- Future<void> Function() onEnd,- void Function(AIError error) onError,- ) {+class AppFlowyCompletionStream extends CompletionStream {+ AppFlowyCompletionStream({+ required super.onStart,+ required super.onProcess,+ required super.onEnd,+ required super.onError,+ }) {+ _startListening();+ }++ final RawReceivePort _port = RawReceivePort();+ final StreamController<String> _controller = StreamController.broadcast();+ late StreamSubscription<String> _subscription;+ int get nativePort => _port.sendPort.nativePort;++ void _startListening() {_port.handler = _controller.add;_subscription = _controller.stream.listen((event) async {if (event == "AI_RESPONSE_LIMIT") {onError(AIError(- message: LocaleKeys.sideBar_aiResponseLimit.tr(),+ message: LocaleKeys.ai_textLimitReachedDescription.tr(),code: AIErrorCode.aiResponseLimitExceeded,),);@@ -142,7 +114,7 @@ class CompletionStream {if (event == "AI_IMAGE_RESPONSE_LIMIT") {onError(AIError(- message: LocaleKeys.sideBar_aiImageResponseLimit.tr(),+ message: LocaleKeys.ai_imageLimitReachedDescription.tr(),code: AIErrorCode.aiImageResponseLimitExceeded,),);@@ -153,6 +125,7 @@ class CompletionStream {onError(AIError(message: msg,+ code: AIErrorCode.other,),);}@@ -170,26 +143,17 @@ class CompletionStream {}if (event.startsWith("error:")) {- onError(AIError(message: event.substring(6)));+ onError(+ AIError(message: event.substring(6), code: AIErrorCode.other),+ );}},);}- final RawReceivePort _port = RawReceivePort();- final StreamController<String> _controller = StreamController.broadcast();- late StreamSubscription<String> _subscription;- int get nativePort => _port.sendPort.nativePort;-Future<void> dispose() async {await _controller.close();await _subscription.cancel();_port.close();}-- StreamSubscription<String> listen(- void Function(String event)? onData,- ) {- return _controller.stream.listen(onData);- }}diff --git a/frontend/appflowy_flutter/lib/ai/service/error.dart b/frontend/appflowy_flutter/lib/ai/service/error.dartindex 866a383e0b..0c98e83172 100644--- a/frontend/appflowy_flutter/lib/ai/service/error.dart+++ b/frontend/appflowy_flutter/lib/ai/service/error.dart@@ -7,7 +7,7 @@ part 'error.g.dart';class AIError with _$AIError {const factory AIError({required String message,- @Default(AIErrorCode.other) AIErrorCode code,+ required AIErrorCode code,}) = _AIError;factory AIError.fromJson(Map<String, Object?> json) =>diff --git a/frontend/appflowy_flutter/lib/ai/service/openai_client.dart b/frontend/appflowy_flutter/lib/ai/service/openai_client.dartdeleted file mode 100644index f29024a914..0000000000--- a/frontend/appflowy_flutter/lib/ai/service/openai_client.dart+++ /dev/null@@ -1,173 +0,0 @@-import 'dart:async';-import 'dart:convert';--import 'package:appflowy_backend/protobuf/flowy-ai/entities.pbenum.dart';-import 'package:appflowy_result/appflowy_result.dart';-import 'package:http/http.dart' as http;--import 'ai_client.dart';-import 'error.dart';-import 'text_completion.dart';--enum OpenAIRequestType {- textCompletion,- textEdit,- imageGenerations;-- Uri get uri {- switch (this) {- case OpenAIRequestType.textCompletion:- return Uri.parse('https://api.openai.com/v1/completions');- case OpenAIRequestType.textEdit:- return Uri.parse('https://api.openai.com/v1/chat/completions');- case OpenAIRequestType.imageGenerations:- return Uri.parse('https://api.openai.com/v1/images/generations');- }- }-}--class HttpOpenAIRepository implements AIRepository {- const HttpOpenAIRepository({- required this.client,- required this.apiKey,- });-- final http.Client client;- final String apiKey;-- Map<String, String> get headers => {- 'Authorization': 'Bearer $apiKey',- 'Content-Type': 'application/json',- };-- @override- Future<void> getStreamedCompletions({- required String prompt,- required Future<void> Function() onStart,- required Future<void> Function(TextCompletionResponse response) onProcess,- required Future<void> Function() onEnd,- required void Function(AIError error) onError,- String? suffix,- int maxTokens = 2048,- double temperature = 0.3,- bool useAction = false,- }) async {- final parameters = {- 'model': 'gpt-3.5-turbo-instruct',- 'prompt': prompt,- 'suffix': suffix,- 'max_tokens': maxTokens,- 'temperature': temperature,- 'stream': true,- };-- final request = http.Request('POST', OpenAIRequestType.textCompletion.uri);- request.headers.addAll(headers);- request.body = jsonEncode(parameters);-- final response = await client.send(request);-- // NEED TO REFACTOR.- // WHY OPENAI USE TWO LINES TO INDICATE THE START OF THE STREAMING RESPONSE?- // AND WHY OPENAI USE [DONE] TO INDICATE THE END OF THE STREAMING RESPONSE?- int syntax = 0;- var previousSyntax = '';- if (response.statusCode == 200) {- await for (final chunk in response.stream- .transform(const Utf8Decoder())- .transform(const LineSplitter())) {- syntax += 1;- if (!useAction) {- if (syntax == 3) {- await onStart();- continue;- } else if (syntax < 3) {- continue;- }- } else {- if (syntax == 2) {- await onStart();- continue;- } else if (syntax < 2) {- continue;- }- }- final data = chunk.trim().split('data: ');- if (data.length > 1) {- if (data[1] != '[DONE]') {- final response = TextCompletionResponse.fromJson(- json.decode(data[1]),- );- if (response.choices.isNotEmpty) {- final text = response.choices.first.text;- if (text == previousSyntax && text == '\n') {- continue;- }- await onProcess(response);- previousSyntax = response.choices.first.text;- }- } else {- await onEnd();- }- }- }- } else {- final body = await response.stream.bytesToString();- onError(- AIError.fromJson(json.decode(body)['error']),- );- }- return;- }-- @override- Future<FlowyResult<List<String>, AIError>> generateImage({- required String prompt,- int n = 1,- }) async {- final parameters = {- 'prompt': prompt,- 'n': n,- 'size': '512x512',- };-- try {- final response = await client.post(- OpenAIRequestType.imageGenerations.uri,- headers: headers,- body: json.encode(parameters),- );-- if (response.statusCode == 200) {- final data = json.decode(- utf8.decode(response.bodyBytes),- )['data'] as List;- final urls = data- .map((e) => e.values)- .expand((e) => e)- .map((e) => e.toString())- .toList();- return FlowyResult.success(urls);- } else {- return FlowyResult.failure(- AIError.fromJson(json.decode(response.body)['error']),- );- }- } catch (error) {- return FlowyResult.failure(AIError(message: error.toString()));- }- }-- @override- Future<void> streamCompletion({- String? objectId,- 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,- }) {- throw UnimplementedError();- }-}diff --git a/frontend/appflowy_flutter/lib/ai/service/text_completion.dart b/frontend/appflowy_flutter/lib/ai/service/text_completion.dartdeleted file mode 100644index 4c22325588..0000000000--- a/frontend/appflowy_flutter/lib/ai/service/text_completion.dart+++ /dev/null@@ -1,27 +0,0 @@-import 'package:freezed_annotation/freezed_annotation.dart';--part 'text_completion.freezed.dart';-part 'text_completion.g.dart';--@freezed-class TextCompletionChoice with _$TextCompletionChoice {- factory TextCompletionChoice({- required String text,- required int index,- // ignore: invalid_annotation_target- @JsonKey(name: 'finish_reason') String? finishReason,- }) = _TextCompletionChoice;-- factory TextCompletionChoice.fromJson(Map<String, Object?> json) =>- _$TextCompletionChoiceFromJson(json);-}--@freezed-class TextCompletionResponse with _$TextCompletionResponse {- const factory TextCompletionResponse({- required List<TextCompletionChoice> choices,- }) = _TextCompletionResponse;-- factory TextCompletionResponse.fromJson(Map<String, Object?> json) =>- _$TextCompletionResponseFromJson(json);-}diff --git a/frontend/appflowy_flutter/lib/ai/widgets/loading_indicator.dart b/frontend/appflowy_flutter/lib/ai/widgets/loading_indicator.dartindex f1c5cf0cfb..e21ea95ac1 100644--- a/frontend/appflowy_flutter/lib/ai/widgets/loading_indicator.dart+++ b/frontend/appflowy_flutter/lib/ai/widgets/loading_indicator.dart@@ -16,51 +16,48 @@ class AILoadingIndicator extends StatelessWidget {@overrideWidget build(BuildContext context) {final slice = Duration(milliseconds: duration.inMilliseconds ~/ 5);- return Padding(- padding: const EdgeInsets.only(top: 8.0),- child: SizedBox(- height: 20,- child: SeparatedRow(- separatorBuilder: () => const HSpace(4),- children: [- Padding(- padding: const EdgeInsetsDirectional.only(end: 4.0),- child: FlowyText(- text,- color: Theme.of(context).hintColor,- ),+ return SizedBox(+ height: 20,+ child: SeparatedRow(+ separatorBuilder: () => const HSpace(4),+ children: [+ Padding(+ padding: const EdgeInsetsDirectional.only(end: 4.0),+ child: FlowyText(+ text,+ color: Theme.of(context).hintColor,),- buildDot(const Color(0xFF9327FF))- .animate(onPlay: (controller) => controller.repeat())- .slideY(duration: slice, begin: 0, end: -1)- .then()- .slideY(begin: -1, end: 1)- .then()- .slideY(begin: 1, end: 0)- .then()- .slideY(duration: slice * 2, begin: 0, end: 0),- buildDot(const Color(0xFFFB006D))- .animate(onPlay: (controller) => controller.repeat())- .slideY(duration: slice, begin: 0, end: 0)- .then()- .slideY(begin: 0, end: -1)- .then()- .slideY(begin: -1, end: 1)- .then()- .slideY(begin: 1, end: 0)- .then()- .slideY(begin: 0, end: 0),- buildDot(const Color(0xFFFFCE00))- .animate(onPlay: (controller) => controller.repeat())- .slideY(duration: slice * 2, begin: 0, end: 0)- .then()- .slideY(duration: slice, begin: 0, end: -1)- .then()- .slideY(begin: -1, end: 1)- .then()- .slideY(begin: 1, end: 0),- ],- ),+ ),+ buildDot(const Color(0xFF9327FF))+ .animate(onPlay: (controller) => controller.repeat())+ .slideY(duration: slice, begin: 0, end: -1)+ .then()+ .slideY(begin: -1, end: 1)+ .then()+ .slideY(begin: 1, end: 0)+ .then()+ .slideY(duration: slice * 2, begin: 0, end: 0),+ buildDot(const Color(0xFFFB006D))+ .animate(onPlay: (controller) => controller.repeat())+ .slideY(duration: slice, begin: 0, end: 0)+ .then()+ .slideY(begin: 0, end: -1)+ .then()+ .slideY(begin: -1, end: 1)+ .then()+ .slideY(begin: 1, end: 0)+ .then()+ .slideY(begin: 0, end: 0),+ buildDot(const Color(0xFFFFCE00))+ .animate(onPlay: (controller) => controller.repeat())+ .slideY(duration: slice * 2, begin: 0, end: 0)+ .then()+ .slideY(duration: slice, begin: 0, end: -1)+ .then()+ .slideY(begin: -1, end: 1)+ .then()+ .slideY(begin: 1, end: 0),+ ],),);}diff --git a/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/desktop_input_text_field.dart b/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/desktop_input_text_field.dartdeleted file mode 100644index ed95da1509..0000000000--- a/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/desktop_input_text_field.dart+++ /dev/null@@ -1,53 +0,0 @@-import 'package:appflowy/plugins/ai_chat/application/chat_input_control_cubit.dart';-import 'package:appflowy/plugins/ai_chat/presentation/layout_define.dart';-import 'package:extended_text_field/extended_text_field.dart';-import 'package:flutter/material.dart';--import 'mentioned_page_text_span.dart';--class PromptInputTextField extends StatelessWidget {- const PromptInputTextField({- super.key,- required this.cubit,- required this.textController,- required this.textFieldFocusNode,- required this.contentPadding,- this.hintText = "",- });-- final ChatInputControlCubit cubit;- final TextEditingController textController;- final FocusNode textFieldFocusNode;- final EdgeInsetsGeometry contentPadding;- final String hintText;-- @override- Widget build(BuildContext context) {- return ExtendedTextField(- controller: textController,- focusNode: textFieldFocusNode,- decoration: InputDecoration(- border: InputBorder.none,- enabledBorder: InputBorder.none,- focusedBorder: InputBorder.none,- contentPadding: contentPadding,- hintText: hintText,- hintStyle: AIChatUILayout.inputHintTextStyle(context),- isCollapsed: true,- isDense: true,- ),- keyboardType: TextInputType.multiline,- textCapitalization: TextCapitalization.sentences,- minLines: 1,- maxLines: null,- style: Theme.of(context).textTheme.bodyMedium,- specialTextSpanBuilder: PromptInputTextSpanBuilder(- inputControlCubit: cubit,- specialTextStyle: Theme.of(context).textTheme.bodyMedium?.copyWith(- color: Theme.of(context).colorScheme.primary,- fontWeight: FontWeight.w600,- ),- ),- );- }-}diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/desktop_chat_input.dart b/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/desktop_prompt_text_field.dartsimilarity index 67%rename from frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/desktop_chat_input.dartrename to frontend/appflowy_flutter/lib/ai/widgets/prompt_input/desktop_prompt_text_field.dartindex 375fb79e12..e2eeb80434 100644--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/desktop_chat_input.dart+++ b/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/desktop_prompt_text_field.dart@@ -1,41 +1,42 @@import 'package:appflowy/ai/ai.dart';import 'package:appflowy/generated/locale_keys.g.dart';-import 'package:appflowy/plugins/ai_chat/application/ai_prompt_input_bloc.dart';-import 'package:appflowy/plugins/ai_chat/application/chat_entity.dart';import 'package:appflowy/plugins/ai_chat/application/chat_input_control_cubit.dart';+import 'package:appflowy/plugins/ai_chat/presentation/layout_define.dart';import 'package:appflowy/startup/startup.dart';+import 'package:appflowy/util/theme_extension.dart';import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';import 'package:easy_localization/easy_localization.dart';+import 'package:extended_text_field/extended_text_field.dart';import 'package:flowy_infra/file_picker/file_picker_service.dart';import 'package:flowy_infra_ui/flowy_infra_ui.dart';import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:flutter_bloc/flutter_bloc.dart';-import '../layout_define.dart';--class DesktopChatInput extends StatefulWidget {- const DesktopChatInput({+class DesktopPromptInput extends StatefulWidget {+ const DesktopPromptInput({super.key,- required this.chatId,required this.isStreaming,required this.onStopStreaming,required this.onSubmitted,+ required this.selectedSourcesNotifier,required this.onUpdateSelectedSources,+ this.hideDecoration = false,});- final String chatId;final bool isStreaming;final void Function() onStopStreaming;final void Function(String, PredefinedFormat?, Map<String, dynamic>)onSubmitted;+ final ValueNotifier<List<String>> selectedSourcesNotifier;final void Function(List<String>) onUpdateSelectedSources;+ final bool hideDecoration;@override- State<DesktopChatInput> createState() => _DesktopChatInputState();+ State<DesktopPromptInput> createState() => _DesktopPromptInputState();}-class _DesktopChatInputState extends State<DesktopChatInput> {+class _DesktopPromptInputState extends State<DesktopPromptInput> {final textFieldKey = GlobalKey();final layerLink = LayerLink();final overlayController = OverlayPortalController();@@ -43,11 +44,6 @@ class _DesktopChatInputState extends State<DesktopChatInput> {final focusNode = FocusNode();final textController = TextEditingController();- bool showPredefinedFormatSection = true;- PredefinedFormat predefinedFormat = const PredefinedFormat(- imageFormat: ImageFormat.text,- textFormat: TextFormat.bulletList,- );late SendButtonState sendButtonState;bool isComposing = false;@@ -57,13 +53,15 @@ class _DesktopChatInputState extends State<DesktopChatInput> {textController.addListener(handleTextControllerChanged);- // refresh border color on focus change and hide menu when lost focusfocusNode.addListener(- () => setState(() {+ () {+ if (!widget.hideDecoration) {+ setState(() {}); // refresh border color+ }if (!focusNode.hasFocus) {- cancelMentionPage();+ cancelMentionPage(); // hide menu when lost focus}- }),+ },);updateSendButtonState();@@ -112,15 +110,7 @@ class _DesktopChatInputState extends State<DesktopChatInput> {);},child: DecoratedBox(- decoration: BoxDecoration(- border: Border.all(- color: focusNode.hasFocus- ? Theme.of(context).colorScheme.primary- : Theme.of(context).colorScheme.outline,- width: focusNode.hasFocus ? 1.5 : 1.0,- ),- borderRadius: const BorderRadius.all(Radius.circular(12.0)),- ),+ decoration: decoration(context),child: Column(mainAxisSize: MainAxisSize.min,children: [@@ -132,7 +122,6 @@ class _DesktopChatInputState extends State<DesktopChatInput> {),child: TextFieldTapRegion(child: PromptInputFile(- chatId: widget.chatId,onDeleted: (file) => context.read<AIPromptInputBloc>().add(AIPromptInputEvent.removeFile(file)),@@ -140,53 +129,63 @@ class _DesktopChatInputState extends State<DesktopChatInput> {),),const VSpace(4.0),- Stack(- children: [- Container(- constraints: getTextFieldConstraints(),- child: inputTextField(),- ),- if (showPredefinedFormatSection)- Positioned.fill(- bottom: null,- child: TextFieldTapRegion(- child: Padding(- padding:- const EdgeInsetsDirectional.only(start: 8.0),- child: ChangeFormatBar(- predefinedFormat: predefinedFormat,- spacing: 4.0,- onSelectPredefinedFormat: (format) {- setState(() => predefinedFormat = format);- },- ),+ BlocBuilder<AIPromptInputBloc, AIPromptInputState>(+ builder: (context, state) {+ return Stack(+ children: [+ ConstrainedBox(+ constraints: getTextFieldConstraints(+ state.showPredefinedFormats,),+ child: inputTextField(),),- ),- Positioned.fill(- top: null,- child: TextFieldTapRegion(- child: _PromptBottomActions(- textController: textController,- overlayController: overlayController,- focusNode: focusNode,- showPredefinedFormats: showPredefinedFormatSection,- predefinedFormat: predefinedFormat,- onTogglePredefinedFormatSection: () {- setState(() {- showPredefinedFormatSection =- !showPredefinedFormatSection;- });- },- sendButtonState: sendButtonState,- onSendPressed: handleSend,- onStopStreaming: widget.onStopStreaming,- onUpdateSelectedSources:- widget.onUpdateSelectedSources,+ if (state.showPredefinedFormats)+ Positioned.fill(+ bottom: null,+ child: TextFieldTapRegion(+ child: Padding(+ padding: const EdgeInsetsDirectional.only(+ start: 8.0,+ ),+ child: ChangeFormatBar(+ predefinedFormat: state.predefinedFormat,+ spacing: 4.0,+ onSelectPredefinedFormat: (format) =>+ context.read<AIPromptInputBloc>().add(+ AIPromptInputEvent+ .updatePredefinedFormat(+ format,+ ),+ ),+ ),+ ),+ ),+ ),+ Positioned.fill(+ top: null,+ child: TextFieldTapRegion(+ child: _PromptBottomActions(+ showPredefinedFormats:+ state.showPredefinedFormats,+ onTogglePredefinedFormatSection: () =>+ context.read<AIPromptInputBloc>().add(+ AIPromptInputEvent+ .toggleShowPredefinedFormat(),+ ),+ onStartMention: startMentionPageFromButton,+ sendButtonState: sendButtonState,+ onSendPressed: handleSend,+ onStopStreaming: widget.onStopStreaming,+ selectedSourcesNotifier:+ widget.selectedSourcesNotifier,+ onUpdateSelectedSources:+ widget.onUpdateSelectedSources,+ ),+ ),),- ),- ),- ],+ ],+ );+ },),],),@@ -196,6 +195,40 @@ class _DesktopChatInputState extends State<DesktopChatInput> {);}+ BoxDecoration decoration(BuildContext context) {+ if (widget.hideDecoration) {+ return BoxDecoration();+ }+ return BoxDecoration(+ color: Theme.of(context).colorScheme.surface,+ border: Border.all(+ color: focusNode.hasFocus+ ? Theme.of(context).colorScheme.primary+ : Theme.of(context).colorScheme.outline,+ width: focusNode.hasFocus ? 1.5 : 1.0,+ ),+ borderRadius: const BorderRadius.all(Radius.circular(12.0)),+ );+ }++ void startMentionPageFromButton() {+ if (overlayController.isShowing) {+ return;+ }+ if (!focusNode.hasFocus) {+ focusNode.requestFocus();+ }+ textController.text += '@';+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (context.mounted) {+ context+ .read<ChatInputControlCubit>()+ .startSearching(textController.value);+ overlayController.show();+ }+ });+ }+void cancelMentionPage() {if (overlayController.isShowing) {inputControlCubit.reset();@@ -228,9 +261,13 @@ class _DesktopChatInputState extends State<DesktopChatInput> {// get the attached files and mentioned pagesfinal metadata = context.read<AIPromptInputBloc>().consumeMetadata();+ final bloc = context.read<AIPromptInputBloc>();+ final showPredefinedFormats = bloc.state.showPredefinedFormats;+ final predefinedFormat = bloc.state.predefinedFormat;+widget.onSubmitted(trimmedText,- showPredefinedFormatSection ? predefinedFormat : null,+ showPredefinedFormats ? predefinedFormat : null,metadata,);}@@ -330,18 +367,6 @@ class _DesktopChatInputState extends State<DesktopChatInput> {overlayController.hide();}- BoxConstraints getTextFieldConstraints() {- double minHeight = DesktopAIPromptSizes.textFieldMinHeight +- DesktopAIPromptSizes.actionBarSendButtonSize +- DesktopAIChatSizes.inputActionBarMargin.vertical;- double maxHeight = 300;- if (showPredefinedFormatSection) {- minHeight += DesktopAIPromptSizes.predefinedFormatButtonHeight;- maxHeight += DesktopAIPromptSizes.predefinedFormatButtonHeight;- }- return BoxConstraints(minHeight: minHeight, maxHeight: maxHeight);- }-Widget inputTextField() {return Shortcuts(shortcuts: buildShortcuts(),@@ -356,7 +381,8 @@ class _DesktopChatInputState extends State<DesktopChatInput> {cubit: inputControlCubit,textController: textController,textFieldFocusNode: focusNode,- contentPadding: calculateContentPadding(),+ contentPadding:+ calculateContentPadding(state.showPredefinedFormats),hintText: switch (state.aiType) {AIType.appflowyAI => LocaleKeys.chat_inputMessageHint.tr(),AIType.localAI => LocaleKeys.chat_inputLocalAIMessageHint.tr()@@ -369,8 +395,20 @@ class _DesktopChatInputState extends State<DesktopChatInput> {);}- EdgeInsetsGeometry calculateContentPadding() {- final top = showPredefinedFormatSection+ BoxConstraints getTextFieldConstraints(bool showPredefinedFormats) {+ double minHeight = DesktopAIPromptSizes.textFieldMinHeight ++ DesktopAIPromptSizes.actionBarSendButtonSize ++ DesktopAIChatSizes.inputActionBarMargin.vertical;+ double maxHeight = 300;+ if (showPredefinedFormats) {+ minHeight += DesktopAIPromptSizes.predefinedFormatButtonHeight;+ maxHeight += DesktopAIPromptSizes.predefinedFormatButtonHeight;+ }+ return BoxConstraints(minHeight: minHeight, maxHeight: maxHeight);+ }++ EdgeInsetsGeometry calculateContentPadding(bool showPredefinedFormats) {+ final top = showPredefinedFormats? DesktopAIPromptSizes.predefinedFormatButtonHeight: 0.0;final bottom = DesktopAIPromptSizes.actionBarSendButtonSize +@@ -451,29 +489,80 @@ class _FocusNextItemIntent extends Intent {const _FocusNextItemIntent();}+class PromptInputTextField extends StatelessWidget {+ const PromptInputTextField({+ super.key,+ required this.cubit,+ required this.textController,+ required this.textFieldFocusNode,+ required this.contentPadding,+ this.hintText = "",+ });++ final ChatInputControlCubit cubit;+ final TextEditingController textController;+ final FocusNode textFieldFocusNode;+ final EdgeInsetsGeometry contentPadding;+ final String hintText;++ @override+ Widget build(BuildContext context) {+ return ExtendedTextField(+ controller: textController,+ focusNode: textFieldFocusNode,+ decoration: InputDecoration(+ border: InputBorder.none,+ enabledBorder: InputBorder.none,+ focusedBorder: InputBorder.none,+ contentPadding: contentPadding,+ hintText: hintText,+ hintStyle: inputHintTextStyle(context),+ isCollapsed: true,+ isDense: true,+ ),+ keyboardType: TextInputType.multiline,+ textCapitalization: TextCapitalization.sentences,+ minLines: 1,+ maxLines: null,+ style: Theme.of(context).textTheme.bodyMedium,+ specialTextSpanBuilder: PromptInputTextSpanBuilder(+ inputControlCubit: cubit,+ specialTextStyle: Theme.of(context).textTheme.bodyMedium?.copyWith(+ color: Theme.of(context).colorScheme.primary,+ fontWeight: FontWeight.w600,+ ),+ ),+ );+ }++ TextStyle? inputHintTextStyle(BuildContext context) {+ return Theme.of(context).textTheme.bodyMedium?.copyWith(+ color: Theme.of(context).isLightMode+ ? const Color(0xFFBDC2C8)+ : const Color(0xFF3C3E51),+ );+ }+}+class _PromptBottomActions extends StatelessWidget {const _PromptBottomActions({- required this.textController,- required this.overlayController,- required this.focusNode,required this.sendButtonState,- required this.predefinedFormat,- required this.onTogglePredefinedFormatSection,required this.showPredefinedFormats,+ required this.onTogglePredefinedFormatSection,+ required this.onStartMention,required this.onSendPressed,required this.onStopStreaming,+ required this.selectedSourcesNotifier,required this.onUpdateSelectedSources,});- final TextEditingController textController;- final OverlayPortalController overlayController;- final FocusNode focusNode;final bool showPredefinedFormats;- final PredefinedFormat predefinedFormat;final void Function() onTogglePredefinedFormatSection;+ final void Function() onStartMention;final SendButtonState sendButtonState;final void Function() onSendPressed;final void Function() onStopStreaming;+ final ValueNotifier<List<String>> selectedSourcesNotifier;final void Function(List<String>) onUpdateSelectedSources;@override@@ -520,7 +609,6 @@ class _PromptBottomActions extends StatelessWidget {Widget _predefinedFormatButton() {return PromptInputDesktopToggleFormatButton(showFormatBar: showPredefinedFormats,- predefinedFormat: predefinedFormat,onTap: onTogglePredefinedFormatSection,);}@@ -528,6 +616,7 @@ class _PromptBottomActions extends StatelessWidget {Widget _selectSourcesButton(BuildContext context) {return PromptInputDesktopSelectSourcesButton(onUpdateSelectedSources: onUpdateSelectedSources,+ selectedSourcesNotifier: selectedSourcesNotifier,);}@@ -535,21 +624,7 @@ class _PromptBottomActions extends StatelessWidget {// return PromptInputMentionButton(// iconSize: DesktopAIPromptSizes.actionBarIconSize,// buttonSize: DesktopAIPromptSizes.actionBarButtonSize,- // onTap: () {- // if (overlayController.isShowing) {- // return;- // }- // if (!focusNode.hasFocus) {- // focusNode.requestFocus();- // }- // textController.text += '@';- // Future.delayed(Duration.zero, () {- // context- // .read<ChatInputControlCubit>()- // .startSearching(textController.value);- // overlayController.show();- // });- // },+ // onTap: onStartMention,// );// }diff --git a/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/file_attachment_list.dart b/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/file_attachment_list.dartindex fddde4dc69..cd68205506 100644--- a/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/file_attachment_list.dart+++ b/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/file_attachment_list.dart@@ -1,5 +1,5 @@import 'package:appflowy/generated/flowy_svgs.g.dart';-import 'package:appflowy/plugins/ai_chat/application/ai_prompt_input_bloc.dart';+import 'package:appflowy/ai/service/ai_prompt_input_bloc.dart';import 'package:appflowy/plugins/ai_chat/application/chat_entity.dart';import 'package:appflowy/plugins/ai_chat/application/chat_input_file_bloc.dart';import 'package:flowy_infra/theme_extension.dart';@@ -13,11 +13,9 @@ import 'layout_define.dart';class PromptInputFile extends StatelessWidget {const PromptInputFile({super.key,- required this.chatId,required this.onDeleted,});- final String chatId;final void Function(ChatFile) onDeleted;@override@@ -37,7 +35,6 @@ class PromptInputFile extends StatelessWidget {),itemCount: files.length,itemBuilder: (context, index) => ChatFilePreview(- chatId: chatId,file: files[index],onDeleted: () => onDeleted(files[index]),),@@ -49,13 +46,11 @@ class PromptInputFile extends StatelessWidget {class ChatFilePreview extends StatefulWidget {const ChatFilePreview({- required this.chatId,required this.file,required this.onDeleted,super.key,});- final String chatId;final ChatFile file;final VoidCallback onDeleted;diff --git a/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/predefined_format_buttons.dart b/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/predefined_format_buttons.dartindex 13db6a0669..189882ae4d 100644--- a/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/predefined_format_buttons.dart+++ b/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/predefined_format_buttons.dart@@ -1,24 +1,22 @@import 'package:appflowy/generated/flowy_svgs.g.dart';import 'package:appflowy/generated/locale_keys.g.dart';-import 'package:appflowy/plugins/ai_chat/application/chat_entity.dart';import 'package:easy_localization/easy_localization.dart';import 'package:flowy_infra_ui/flowy_infra_ui.dart';import 'package:flowy_infra_ui/style_widget/hover.dart';import 'package:flutter/material.dart';import 'package:universal_platform/universal_platform.dart';+import '../../service/ai_entities.dart';import 'layout_define.dart';class PromptInputDesktopToggleFormatButton extends StatelessWidget {const PromptInputDesktopToggleFormatButton({super.key,required this.showFormatBar,- required this.predefinedFormat,required this.onTap,});final bool showFormatBar;- final PredefinedFormat predefinedFormat;final VoidCallback onTap;@overridediff --git a/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/select_sources_bottom_sheet.dart b/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/select_sources_bottom_sheet.dartindex b69a2210f2..1f1b2ddf4c 100644--- a/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/select_sources_bottom_sheet.dart+++ b/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/select_sources_bottom_sheet.dart@@ -2,7 +2,6 @@ import 'package:appflowy/generated/flowy_svgs.g.dart';import 'package:appflowy/generated/locale_keys.g.dart';import 'package:appflowy/mobile/presentation/base/flowy_search_text_field.dart';import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart';-import 'package:appflowy/plugins/ai_chat/application/chat_bloc.dart';import 'package:appflowy/plugins/ai_chat/application/chat_select_sources_cubit.dart';import 'package:appflowy/plugins/base/drag_handler.dart';import 'package:appflowy/workspace/application/sidebar/space/space_bloc.dart';@@ -19,9 +18,11 @@ import 'select_sources_menu.dart';class PromptInputMobileSelectSourcesButton extends StatefulWidget {const PromptInputMobileSelectSourcesButton({super.key,+ required this.selectedSourcesNotifier,required this.onUpdateSelectedSources,});+ final ValueNotifier<List<String>> selectedSourcesNotifier;final void Function(List<String>) onUpdateSelectedSources;@override@@ -36,15 +37,15 @@ class _PromptInputMobileSelectSourcesButtonState@overridevoid initState() {super.initState();+ widget.selectedSourcesNotifier.addListener(onSelectedSourcesChanged);WidgetsBinding.instance.addPostFrameCallback((_) {- cubit.updateSelectedSources(- context.read<ChatBloc>().state.selectedSourceIds,- );+ onSelectedSourcesChanged();});}@overridevoid dispose() {+ widget.selectedSourcesNotifier.removeListener(onSelectedSourcesChanged);cubit.close();super.dispose();}@@ -70,56 +71,49 @@ class _PromptInputMobileSelectSourcesButtonState],child: BlocBuilder<SpaceBloc, SpaceState>(builder: (context, state) {- return BlocListener<ChatBloc, ChatState>(- listener: (context, state) {- cubit- ..updateSelectedSources(state.selectedSourceIds)- ..updateSelectedStatus();- },- child: FlowyButton(- margin: const EdgeInsetsDirectional.fromSTEB(4, 6, 2, 6),- expandText: false,- text: Row(- mainAxisSize: MainAxisSize.min,- children: [- FlowySvg(- FlowySvgs.ai_page_s,- color: Theme.of(context).iconTheme.color,- size: const Size.square(20.0),- ),- FlowySvg(- FlowySvgs.ai_source_drop_down_s,- color: Theme.of(context).hintColor,- size: const Size.square(10),- ),- ],- ),- onTap: () async {- context- .read<ChatSettingsCubit>()- .refreshSources(state.spaces, state.currentSpace);- await showMobileBottomSheet<void>(- context,- backgroundColor: Theme.of(context).colorScheme.surface,- maxChildSize: 0.98,- enableDraggableScrollable: true,- scrollableWidgetBuilder: (_, scrollController) {- return Expanded(- child: BlocProvider.value(- value: cubit,- child: _MobileSelectSourcesSheetBody(- scrollController: scrollController,- ),- ),- );- },- builder: (context) => const SizedBox.shrink(),- );- if (context.mounted) {- widget.onUpdateSelectedSources(cubit.selectedSourceIds);- }- },+ return FlowyButton(+ margin: const EdgeInsetsDirectional.fromSTEB(4, 6, 2, 6),+ expandText: false,+ text: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ FlowySvg(+ FlowySvgs.ai_page_s,+ color: Theme.of(context).iconTheme.color,+ size: const Size.square(20.0),+ ),+ FlowySvg(+ FlowySvgs.ai_source_drop_down_s,+ color: Theme.of(context).hintColor,+ size: const Size.square(10),+ ),+ ],),+ onTap: () async {+ context+ .read<ChatSettingsCubit>()+ .refreshSources(state.spaces, state.currentSpace);+ await showMobileBottomSheet<void>(+ context,+ backgroundColor: Theme.of(context).colorScheme.surface,+ maxChildSize: 0.98,+ enableDraggableScrollable: true,+ scrollableWidgetBuilder: (_, scrollController) {+ return Expanded(+ child: BlocProvider.value(+ value: cubit,+ child: _MobileSelectSourcesSheetBody(+ scrollController: scrollController,+ ),+ ),+ );+ },+ builder: (context) => const SizedBox.shrink(),+ );+ if (context.mounted) {+ widget.onUpdateSelectedSources(cubit.selectedSourceIds);+ }+ },);},),@@ -127,6 +121,12 @@ class _PromptInputMobileSelectSourcesButtonState},);}++ void onSelectedSourcesChanged() {+ cubit+ ..updateSelectedSources(widget.selectedSourcesNotifier.value)+ ..updateSelectedStatus();+ }}class _MobileSelectSourcesSheetBody extends StatefulWidget {diff --git a/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/select_sources_menu.dart b/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/select_sources_menu.dartindex df521256d8..d7c920c49c 100644--- a/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/select_sources_menu.dart+++ b/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/select_sources_menu.dart@@ -2,8 +2,8 @@ import 'dart:math';import 'package:appflowy/generated/flowy_svgs.g.dart';import 'package:appflowy/generated/locale_keys.g.dart';-import 'package:appflowy/plugins/ai_chat/application/chat_bloc.dart';import 'package:appflowy/plugins/ai_chat/application/chat_select_sources_cubit.dart';+import 'package:appflowy/plugins/document/application/document_bloc.dart';import 'package:appflowy/workspace/application/sidebar/space/space_bloc.dart';import 'package:appflowy/workspace/application/user/user_workspace_bloc.dart';import 'package:appflowy/workspace/application/view/view_ext.dart';@@ -24,9 +24,11 @@ import 'mention_page_menu.dart';class PromptInputDesktopSelectSourcesButton extends StatefulWidget {const PromptInputDesktopSelectSourcesButton({super.key,+ required this.selectedSourcesNotifier,required this.onUpdateSelectedSources,});+ final ValueNotifier<List<String>> selectedSourcesNotifier;final void Function(List<String>) onUpdateSelectedSources;@override@@ -42,15 +44,15 @@ class _PromptInputDesktopSelectSourcesButtonState@overridevoid initState() {super.initState();+ widget.selectedSourcesNotifier.addListener(onSelectedSourcesChanged);WidgetsBinding.instance.addPostFrameCallback((_) {- cubit.updateSelectedSources(- context.read<ChatBloc>().state.selectedSourceIds,- );+ onSelectedSourcesChanged();});}@overridevoid dispose() {+ widget.selectedSourcesNotifier.removeListener(onSelectedSourcesChanged);cubit.close();super.dispose();}@@ -76,51 +78,53 @@ class _PromptInputDesktopSelectSourcesButtonState],child: BlocBuilder<SpaceBloc, SpaceState>(builder: (context, state) {- return BlocListener<ChatBloc, ChatState>(- listener: (context, state) {- cubit- ..updateSelectedSources(state.selectedSourceIds)- ..updateSelectedStatus();+ return AppFlowyPopover(+ constraints: BoxConstraints.loose(const Size(320, 380)),+ offset: const Offset(0.0, -10.0),+ direction: PopoverDirection.topWithCenterAligned,+ margin: EdgeInsets.zero,+ controller: popoverController,+ onOpen: () {+ context+ .read<ChatSettingsCubit>()+ .refreshSources(state.spaces, state.currentSpace);},- child: AppFlowyPopover(- constraints: BoxConstraints.loose(const Size(320, 380)),- offset: const Offset(0.0, -10.0),- direction: PopoverDirection.topWithCenterAligned,- margin: EdgeInsets.zero,- controller: popoverController,- onOpen: () {- context- .read<ChatSettingsCubit>()- .refreshSources(state.spaces, state.currentSpace);- },- onClose: () {- widget.onUpdateSelectedSources(cubit.selectedSourceIds);- context- .read<ChatSettingsCubit>()- .refreshSources(state.spaces, state.currentSpace);- },- popupBuilder: (_) {- return BlocProvider.value(- value: context.read<ChatSettingsCubit>(),- child: const _PopoverContent(),- );- },- child: _IndicatorButton(- onTap: () => popoverController.show(),- ),+ onClose: () {+ widget.onUpdateSelectedSources(cubit.selectedSourceIds);+ context+ .read<ChatSettingsCubit>()+ .refreshSources(state.spaces, state.currentSpace);+ },+ popupBuilder: (_) {+ return BlocProvider.value(+ value: context.read<ChatSettingsCubit>(),+ child: const _PopoverContent(),+ );+ },+ child: _IndicatorButton(+ selectedSourcesNotifier: widget.selectedSourcesNotifier,+ onTap: () => popoverController.show(),),);},),);}++ void onSelectedSourcesChanged() {+ cubit+ ..updateSelectedSources(widget.selectedSourcesNotifier.value)+ ..updateSelectedStatus();+ }}class _IndicatorButton extends StatelessWidget {const _IndicatorButton({+ required this.selectedSourcesNotifier,required this.onTap,});+ final ValueNotifier<List<String>> selectedSourcesNotifier;final VoidCallback onTap;@override@@ -144,11 +148,19 @@ class _IndicatorButton extends StatelessWidget {color: Theme.of(context).iconTheme.color,),const HSpace(2.0),- BlocBuilder<ChatBloc, ChatState>(- builder: (context, state) {+ ValueListenableBuilder(+ valueListenable: selectedSourcesNotifier,+ builder: (context, selectedSourceIds, _) {+ final documentId =+ context.read<DocumentBloc?>()?.documentId;+ final label = documentId != null &&+ selectedSourceIds.length == 1 &&+ selectedSourceIds[0] == documentId+ ? LocaleKeys.chat_currentPage.tr()+ : selectedSourceIds.length.toString();return FlowyText(- state.selectedSourceIds.length.toString(),- fontSize: 14,+ label,+ fontSize: 12,figmaLineHeight: 16,color: Theme.of(context).hintColor,);diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/application/chat_bloc.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/application/chat_bloc.dartindex 71bf7f63bf..e7aca346e0 100644--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/application/chat_bloc.dart+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/application/chat_bloc.dart@@ -1,6 +1,7 @@import 'dart:async';import 'dart:collection';+import 'package:appflowy/ai/ai.dart';import 'package:appflowy/util/int64_extension.dart';import 'package:appflowy_backend/dispatch/dispatch.dart';import 'package:appflowy_backend/log.dart';@@ -10,6 +11,7 @@ import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';import 'package:appflowy_result/appflowy_result.dart';import 'package:collection/collection.dart';import 'package:fixnum/fixnum.dart';+import 'package:flutter/widgets.dart';import 'package:flutter_bloc/flutter_bloc.dart';import 'package:flutter_chat_core/flutter_chat_core.dart';import 'package:freezed_annotation/freezed_annotation.dart';@@ -28,6 +30,7 @@ class ChatBloc extends Bloc<ChatEvent, ChatState> {required this.userId,}) : chatController = InMemoryChatController(),listener = ChatMessageListener(chatId: chatId),+ selectedSourcesNotifier = ValueNotifier([]),super(ChatState.initial()) {_startListening();_dispatch();@@ -38,7 +41,7 @@ class ChatBloc extends Bloc<ChatEvent, ChatState> {final String chatId;final String userId;final ChatMessageListener listener;-+ final ValueNotifier<List<String>> selectedSourcesNotifier;final ChatController chatController;/// The last streaming message id@@ -68,7 +71,7 @@ class ChatBloc extends Bloc<ChatEvent, ChatState> {await listener.stop();final request = ViewIdPB(value: chatId);unawaited(FolderEventCloseView(request).send());-+ selectedSourcesNotifier.dispose();return super.close();}@@ -251,12 +254,10 @@ class ChatBloc extends Bloc<ChatEvent, ChatState> {);},didReceiveChatSettings: (settings) {- emit(- state.copyWith(selectedSourceIds: settings.ragIds),- );+ selectedSourcesNotifier.value = settings.ragIds;},updateSelectedSources: (selectedSourcesIds) async {- emit(state.copyWith(selectedSourceIds: selectedSourcesIds));+ selectedSourcesNotifier.value = [...selectedSourcesIds];final payload = UpdateChatSettingsPB(chatId: ChatId(value: chatId),@@ -665,14 +666,12 @@ class ChatEvent with _$ChatEvent {@freezedclass ChatState with _$ChatState {const factory ChatState({- required List<String> selectedSourceIds,required LoadChatMessageStatus loadingState,required PromptResponseState promptResponseState,required bool clearErrorMessages,}) = _ChatState;factory ChatState.initial() => const ChatState(- selectedSourceIds: [],loadingState: LoadChatMessageStatus.loading,promptResponseState: PromptResponseState.ready,clearErrorMessages: false,diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/application/chat_entity.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/application/chat_entity.dartindex 7b16c597cd..41e2a6946d 100644--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/application/chat_entity.dart+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/application/chat_entity.dart@@ -1,11 +1,8 @@import 'dart:io';-import 'package:appflowy/generated/flowy_svgs.g.dart';-import 'package:appflowy/generated/locale_keys.g.dart';import 'package:appflowy_backend/protobuf/flowy-ai/protobuf.dart';import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';-import 'package:easy_localization/easy_localization.dart';import 'package:equatable/equatable.dart';import 'package:freezed_annotation/freezed_annotation.dart';import 'package:path/path.dart' as path;@@ -140,87 +137,3 @@ enum LoadChatMessageStatus {loadingRemote,ready,}--class PredefinedFormat extends Equatable {- const PredefinedFormat({- required this.imageFormat,- required this.textFormat,- });-- const PredefinedFormat.auto()- : imageFormat = ImageFormat.text,- textFormat = TextFormat.paragraph;-- final ImageFormat imageFormat;- final TextFormat? textFormat;-- PredefinedFormatPB toPB() {- return PredefinedFormatPB(- imageFormat: switch (imageFormat) {- ImageFormat.text => ResponseImageFormatPB.TextOnly,- ImageFormat.image => ResponseImageFormatPB.ImageOnly,- ImageFormat.textAndImage => ResponseImageFormatPB.TextAndImage,- },- textFormat: switch (textFormat) {- TextFormat.paragraph => ResponseTextFormatPB.Paragraph,- TextFormat.bulletList => ResponseTextFormatPB.BulletedList,- TextFormat.numberedList => ResponseTextFormatPB.NumberedList,- TextFormat.table => ResponseTextFormatPB.Table,- _ => null,- },- );- }-- @override- List<Object?> get props => [imageFormat, textFormat];-}--enum ImageFormat {- text,- image,- textAndImage;-- bool get hasText => this == text || this == textAndImage;-- FlowySvgData get icon {- return switch (this) {- ImageFormat.text => FlowySvgs.ai_text_s,- ImageFormat.image => FlowySvgs.ai_image_s,- ImageFormat.textAndImage => FlowySvgs.ai_text_image_s,- };- }-- String get i18n {- return switch (this) {- ImageFormat.text => LocaleKeys.chat_changeFormat_textOnly.tr(),- ImageFormat.image => LocaleKeys.chat_changeFormat_imageOnly.tr(),- ImageFormat.textAndImage =>- LocaleKeys.chat_changeFormat_textAndImage.tr(),- };- }-}--enum TextFormat {- paragraph,- bulletList,- numberedList,- table;-- FlowySvgData get icon {- return switch (this) {- TextFormat.paragraph => FlowySvgs.ai_paragraph_s,- TextFormat.bulletList => FlowySvgs.ai_list_s,- TextFormat.numberedList => FlowySvgs.ai_number_list_s,- TextFormat.table => FlowySvgs.ai_table_s,- };- }-- String get i18n {- return switch (this) {- TextFormat.paragraph => LocaleKeys.chat_changeFormat_text.tr(),- TextFormat.bulletList => LocaleKeys.chat_changeFormat_bullet.tr(),- TextFormat.numberedList => LocaleKeys.chat_changeFormat_number.tr(),- TextFormat.table => LocaleKeys.chat_changeFormat_table.tr(),- };- }-}diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/application/chat_select_sources_cubit.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/application/chat_select_sources_cubit.dartindex 7a9f790e63..76cbd69cdf 100644--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/application/chat_select_sources_cubit.dart+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/application/chat_select_sources_cubit.dart@@ -113,9 +113,8 @@ class ChatSettingsCubit extends Cubit<ChatSettingsState> {String filter = '';void updateSelectedSources(List<String> newSelectedSourceIds) {- selectedSourceIds- ..clear- ..addAll(newSelectedSourceIds);+ selectedSourceIds.clear();+ selectedSourceIds.addAll(newSelectedSourceIds);}void refreshSources(List<ViewPB> spaceViews, ViewPB? currentSpace) async {diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/chat_page.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/chat_page.dartindex 551a210d00..f7f22a3c93 100644--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/chat_page.dart+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/chat_page.dart@@ -1,5 +1,6 @@import 'dart:io';+import 'package:appflowy/ai/ai.dart';import 'package:appflowy/generated/locale_keys.g.dart';import 'package:appflowy/plugins/ai_chat/presentation/chat_message_selector_banner.dart';import 'package:appflowy/workspace/application/view/view_service.dart';@@ -19,14 +20,12 @@ import 'package:string_validator/string_validator.dart';import 'package:universal_platform/universal_platform.dart';import 'package:url_launcher/url_launcher.dart';-import 'application/ai_prompt_input_bloc.dart';import 'application/chat_bloc.dart';import 'application/chat_entity.dart';import 'application/chat_member_bloc.dart';import 'application/chat_select_message_bloc.dart';import 'application/chat_message_stream.dart';import 'presentation/animated_chat_list.dart';-import 'presentation/chat_input/desktop_chat_input.dart';import 'presentation/chat_input/mobile_chat_input.dart';import 'presentation/chat_related_question.dart';import 'presentation/chat_welcome_page.dart';@@ -71,7 +70,14 @@ class AIChatPage extends StatelessWidget {),/// [AIPromptInputBloc] is used to handle the user prompt- BlocProvider(create: (_) => AIPromptInputBloc()),+ BlocProvider(+ create: (_) => AIPromptInputBloc(+ predefinedFormat: PredefinedFormat(+ imageFormat: ImageFormat.text,+ textFormat: TextFormat.bulletList,+ ),+ ),+ ),BlocProvider(create: (_) => ChatMemberBloc()),],child: Builder(@@ -146,7 +152,7 @@ class _ChatContentPage extends StatelessWidget {),),_wrapConstraints(- _builtInput(context),+ _Input(view: view),),],),@@ -184,9 +190,16 @@ class _ChatContentPage extends StatelessWidget {return RelatedQuestionList(relatedQuestions: message.metadata!['questions'],onQuestionSelected: (question) {- context- .read<ChatBloc>()- .add(ChatEvent.sendMessage(message: question));+ final bloc = context.read<AIPromptInputBloc>();+ final showPredefinedFormats = bloc.state.showPredefinedFormats;+ final predefinedFormat = bloc.state.predefinedFormat;++ context.read<ChatBloc>().add(+ ChatEvent.sendMessage(+ message: question,+ format: showPredefinedFormats ? predefinedFormat : null,+ ),+ );},);}@@ -278,7 +291,16 @@ class _ChatContentPage extends StatelessWidget {return ChatWelcomePage(userProfile: userProfile,onSelectedQuestion: (question) {- bloc.add(ChatEvent.sendMessage(message: question));+ final aiPromptInputBloc = context.read<AIPromptInputBloc>();+ final showPredefinedFormats =+ aiPromptInputBloc.state.showPredefinedFormats;+ final predefinedFormat = aiPromptInputBloc.state.predefinedFormat;+ bloc.add(+ ChatEvent.sendMessage(+ message: question,+ format: showPredefinedFormats ? predefinedFormat : null,+ ),+ );},);}@@ -300,7 +322,42 @@ class _ChatContentPage extends StatelessWidget {);}- Widget _builtInput(BuildContext context) {+ void _onSelectMetadata(+ BuildContext context,+ ChatMessageRefSource metadata,+ ) async {+ if (isURL(metadata.name)) {+ late Uri uri;+ try {+ uri = Uri.parse(metadata.name);+ // `Uri` identifies `localhost` as a scheme+ if (!uri.hasScheme || uri.scheme == 'localhost') {+ uri = Uri.parse("http://${metadata.name}");+ await InternetAddress.lookup(uri.host);+ }+ await launchUrl(uri);+ } catch (err) {+ Log.error("failed to open url $err");+ }+ } else {+ final sidebarView =+ await ViewBackendService.getView(metadata.id).toNullable();+ if (context.mounted) {+ openPageFromMessage(context, sidebarView);+ }+ }+ }+}++class _Input extends StatelessWidget {+ const _Input({+ required this.view,+ });++ final ViewPB view;++ @override+ Widget build(BuildContext context) {return BlocSelector<ChatSelectMessageBloc, ChatSelectMessageState, bool>(selector: (state) => state.isSelectingMessages,builder: (context, isSelectingMessages) {@@ -326,8 +383,7 @@ class _ChatContentPage extends StatelessWidget {final chatBloc = context.read<ChatBloc>();return UniversalPlatform.isDesktop- ? DesktopChatInput(- chatId: view.id,+ ? DesktopPromptInput(isStreaming: !canSendMessage,onStopStreaming: () {chatBloc.add(const ChatEvent.stopStream());@@ -341,6 +397,8 @@ class _ChatContentPage extends StatelessWidget {),);},+ selectedSourcesNotifier:+ chatBloc.selectedSourcesNotifier,onUpdateSelectedSources: (ids) {chatBloc.add(ChatEvent.updateSelectedSources(@@ -350,7 +408,6 @@ class _ChatContentPage extends StatelessWidget {},): MobileChatInput(- chatId: view.id,isStreaming: !canSendMessage,onStopStreaming: () {chatBloc.add(const ChatEvent.stopStream());@@ -364,6 +421,8 @@ class _ChatContentPage extends StatelessWidget {),);},+ selectedSourcesNotifier:+ chatBloc.selectedSourcesNotifier,onUpdateSelectedSources: (ids) {chatBloc.add(ChatEvent.updateSelectedSources(@@ -379,30 +438,4 @@ class _ChatContentPage extends StatelessWidget {},);}-- void _onSelectMetadata(- BuildContext context,- ChatMessageRefSource metadata,- ) async {- if (isURL(metadata.name)) {- late Uri uri;- try {- uri = Uri.parse(metadata.name);- // `Uri` identifies `localhost` as a scheme- if (!uri.hasScheme || uri.scheme == 'localhost') {- uri = Uri.parse("http://${metadata.name}");- await InternetAddress.lookup(uri.host);- }- await launchUrl(uri);- } catch (err) {- Log.error("failed to open url $err");- }- } else {- final sidebarView =- await ViewBackendService.getView(metadata.id).toNullable();- if (context.mounted) {- openPageFromMessage(context, sidebarView);- }- }- }}diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/mobile_chat_input.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/mobile_chat_input.dartindex 06694e3aa3..4d5cd82098 100644--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/mobile_chat_input.dart+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/mobile_chat_input.dart@@ -1,8 +1,7 @@import 'package:appflowy/ai/ai.dart';import 'package:appflowy/generated/locale_keys.g.dart';-import 'package:appflowy/plugins/ai_chat/application/ai_prompt_input_bloc.dart';-import 'package:appflowy/plugins/ai_chat/application/chat_entity.dart';import 'package:appflowy/plugins/ai_chat/application/chat_input_control_cubit.dart';+import 'package:appflowy/util/theme_extension.dart';import 'package:appflowy/workspace/application/view/view_ext.dart';import 'package:easy_localization/easy_localization.dart';import 'package:extended_text_field/extended_text_field.dart';@@ -10,21 +9,19 @@ import 'package:flowy_infra_ui/flowy_infra_ui.dart';import 'package:flutter/material.dart';import 'package:flutter_bloc/flutter_bloc.dart';-import '../layout_define.dart';-class MobileChatInput extends StatefulWidget {const MobileChatInput({super.key,- required this.chatId,required this.isStreaming,required this.onStopStreaming,required this.onSubmitted,+ required this.selectedSourcesNotifier,required this.onUpdateSelectedSources,});- final String chatId;final bool isStreaming;final void Function() onStopStreaming;+ final ValueNotifier<List<String>> selectedSourcesNotifier;final void Function(String, PredefinedFormat?, Map<String, dynamic>)onSubmitted;final void Function(List<String>) onUpdateSelectedSources;@@ -38,11 +35,6 @@ class _MobileChatInputState extends State<MobileChatInput> {final focusNode = FocusNode();final textController = TextEditingController();- bool showPredefinedFormatSection = true;- PredefinedFormat predefinedFormat = const PredefinedFormat(- imageFormat: ImageFormat.text,- textFormat: TextFormat.bulletList,- );late SendButtonState sendButtonState;@override@@ -106,53 +98,62 @@ class _MobileChatInputState extends State<MobileChatInput> {borderRadius:const BorderRadius.vertical(top: Radius.circular(8.0)),),- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- ConstrainedBox(- constraints: BoxConstraints(- maxHeight:- MobileAIPromptSizes.attachedFilesBarPadding.vertical ++ child: BlocBuilder<AIPromptInputBloc, AIPromptInputState>(+ builder: (context, state) {+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ ConstrainedBox(+ constraints: BoxConstraints(+ maxHeight: MobileAIPromptSizes+ .attachedFilesBarPadding.vertical +MobileAIPromptSizes.attachedFilesPreviewHeight,- ),- child: PromptInputFile(- chatId: widget.chatId,- onDeleted: (file) => context- .read<AIPromptInputBloc>()- .add(AIPromptInputEvent.removeFile(file)),- ),- ),- if (showPredefinedFormatSection)- TextFieldTapRegion(- child: Padding(- padding: const EdgeInsets.all(8.0),- child: ChangeFormatBar(- predefinedFormat: predefinedFormat,- spacing: 8.0,- onSelectPredefinedFormat: (format) {- setState(() => predefinedFormat = format);- },+ ),+ child: PromptInputFile(+ onDeleted: (file) => context+ .read<AIPromptInputBloc>()+ .add(AIPromptInputEvent.removeFile(file)),),),- )- else- const VSpace(8.0),- inputTextField(context),- TextFieldTapRegion(- child: Container(- padding: const EdgeInsets.symmetric(vertical: 8.0),- child: Row(- children: [- const HSpace(8.0),- leadingButtons(context),- const Spacer(),- sendButton(),- const HSpace(12.0),- ],+ if (state.showPredefinedFormats)+ TextFieldTapRegion(+ child: Padding(+ padding: const EdgeInsets.all(8.0),+ child: ChangeFormatBar(+ predefinedFormat: state.predefinedFormat,+ spacing: 8.0,+ onSelectPredefinedFormat: (format) =>+ context.read<AIPromptInputBloc>().add(+ AIPromptInputEvent.updatePredefinedFormat(+ format,+ ),+ ),+ ),+ ),+ )+ else+ const VSpace(8.0),+ inputTextField(context),+ TextFieldTapRegion(+ child: Container(+ padding: const EdgeInsets.symmetric(vertical: 8.0),+ child: Row(+ children: [+ const HSpace(8.0),+ leadingButtons(+ context,+ state.showPredefinedFormats,+ ),+ const Spacer(),+ sendButton(),+ const HSpace(12.0),+ ],+ ),+ ),),- ),- ),- ],+ ],+ );+ },),),),@@ -185,9 +186,13 @@ class _MobileChatInputState extends State<MobileChatInput> {// get the attached files and mentioned pagesfinal metadata = context.read<AIPromptInputBloc>().consumeMetadata();+ final bloc = context.read<AIPromptInputBloc>();+ final showPredefinedFormats = bloc.state.showPredefinedFormats;+ final predefinedFormat = bloc.state.predefinedFormat;+widget.onSubmitted(trimmedText,- showPredefinedFormatSection ? predefinedFormat : null,+ showPredefinedFormats ? predefinedFormat : null,metadata,);}@@ -266,7 +271,7 @@ class _MobileChatInputState extends State<MobileChatInput> {AIType.appflowyAI => LocaleKeys.chat_inputMessageHint.tr(),AIType.localAI => LocaleKeys.chat_inputLocalAIMessageHint.tr()},- hintStyle: AIChatUILayout.inputHintTextStyle(context),+ hintStyle: inputHintTextStyle(context),isCollapsed: true,isDense: true,),@@ -289,7 +294,15 @@ class _MobileChatInputState extends State<MobileChatInput> {);}- Widget leadingButtons(BuildContext context) {+ TextStyle? inputHintTextStyle(BuildContext context) {+ return Theme.of(context).textTheme.bodyMedium?.copyWith(+ color: Theme.of(context).isLightMode+ ? const Color(0xFFBDC2C8)+ : const Color(0xFF3C3E51),+ );+ }++ Widget leadingButtons(BuildContext context, bool showPredefinedFormats) {return _LeadingActions(// onMention: () {// textController.text += '@';@@ -300,13 +313,13 @@ class _MobileChatInputState extends State<MobileChatInput> {// mentionPage(context);// });// },- showPredefinedFormatSection: showPredefinedFormatSection,- predefinedFormat: predefinedFormat,+ showPredefinedFormats: showPredefinedFormats,onTogglePredefinedFormatSection: () {- setState(() {- showPredefinedFormatSection = !showPredefinedFormatSection;- });+ context+ .read<AIPromptInputBloc>()+ .add(AIPromptInputEvent.toggleShowPredefinedFormat());},+ selectedSourcesNotifier: widget.selectedSourcesNotifier,onUpdateSelectedSources: widget.onUpdateSelectedSources,);}@@ -322,15 +335,15 @@ class _MobileChatInputState extends State<MobileChatInput> {class _LeadingActions extends StatelessWidget {const _LeadingActions({- required this.showPredefinedFormatSection,- required this.predefinedFormat,+ required this.showPredefinedFormats,required this.onTogglePredefinedFormatSection,+ required this.selectedSourcesNotifier,required this.onUpdateSelectedSources,});- final bool showPredefinedFormatSection;- final PredefinedFormat predefinedFormat;+ final bool showPredefinedFormats;final void Function() onTogglePredefinedFormatSection;+ final ValueNotifier<List<String>> selectedSourcesNotifier;final void Function(List<String>) onUpdateSelectedSources;@override@@ -342,10 +355,11 @@ class _LeadingActions extends StatelessWidget {separatorBuilder: () => const HSpace(4.0),children: [PromptInputMobileSelectSourcesButton(+ selectedSourcesNotifier: selectedSourcesNotifier,onUpdateSelectedSources: onUpdateSelectedSources,),PromptInputMobileToggleFormatButton(- showFormatBar: showPredefinedFormatSection,+ showFormatBar: showPredefinedFormats,onTap: onTogglePredefinedFormatSection,),],diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/layout_define.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/layout_define.dartindex eddf778e8a..611ff5d922 100644--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/layout_define.dart+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/layout_define.dart@@ -1,4 +1,3 @@-import 'package:appflowy/util/theme_extension.dart';import 'package:flutter/material.dart';import 'package:universal_platform/universal_platform.dart';@@ -20,14 +19,6 @@ class AIChatUILayout {static EdgeInsets get messageMargin => UniversalPlatform.isMobile? const EdgeInsets.symmetric(horizontal: 16): EdgeInsets.zero;-- static TextStyle? inputHintTextStyle(BuildContext context) {- return Theme.of(context).textTheme.bodyMedium?.copyWith(- color: Theme.of(context).isLightMode- ? const Color(0xFFBDC2C8)- : const Color(0xFF3C3E51),- );- }}class DesktopAIChatSizes {diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_change_format_bottom_sheet.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_change_format_bottom_sheet.dartindex f68453df75..5fa3b8f8a7 100644--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_change_format_bottom_sheet.dart+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_change_format_bottom_sheet.dart@@ -1,9 +1,9 @@+import 'package:appflowy/ai/ai.dart';import 'package:appflowy/generated/flowy_svgs.g.dart';import 'package:appflowy/generated/locale_keys.g.dart';import 'package:appflowy/mobile/presentation/base/app_bar/app_bar_actions.dart';import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart';import 'package:appflowy/mobile/presentation/widgets/widgets.dart';-import 'package:appflowy/plugins/ai_chat/application/chat_entity.dart';import 'package:easy_localization/easy_localization.dart';import 'package:flowy_infra_ui/flowy_infra_ui.dart';import 'package:flutter/material.dart';diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_message_action_bar.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_message_action_bar.dartindex bb79a6b2d3..48a8459598 100644--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_message_action_bar.dart+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_message_action_bar.dart@@ -1,14 +1,11 @@import 'dart:async';import 'dart:convert';-import 'package:appflowy/ai/widgets/prompt_input/layout_define.dart';-import 'package:appflowy/ai/widgets/prompt_input/predefined_format_buttons.dart';-import 'package:appflowy/ai/widgets/prompt_input/select_sources_menu.dart';+import 'package:appflowy/ai/ai.dart';import 'package:appflowy/generated/flowy_svgs.g.dart';import 'package:appflowy/generated/locale_keys.g.dart';import 'package:appflowy/plugins/ai_chat/application/chat_ai_message_bloc.dart';import 'package:appflowy/plugins/ai_chat/application/chat_edit_document_service.dart';-import 'package:appflowy/plugins/ai_chat/application/chat_entity.dart';import 'package:appflowy/plugins/ai_chat/application/chat_select_sources_cubit.dart';import 'package:appflowy/plugins/document/application/prelude.dart';import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/clipboard_service.dart';@@ -220,7 +217,7 @@ class RegenerateButton extends StatelessWidget {? DesktopAIChatSizes.messageHoverActionBarIconRadius: DesktopAIChatSizes.messageActionBarIconRadius,icon: FlowySvg(- FlowySvgs.ai_undo_s,+ FlowySvgs.ai_try_again_s,color: Theme.of(context).hintColor,size: const Size.square(16),),diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_message_bubble.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_message_bubble.dartindex 802b8d6142..a938c9094f 100644--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_message_bubble.dart+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_message_bubble.dart@@ -1,11 +1,11 @@import 'dart:convert';+import 'package:appflowy/ai/ai.dart';import 'package:appflowy/generated/flowy_svgs.g.dart';import 'package:appflowy/generated/locale_keys.g.dart';import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart';import 'package:appflowy/mobile/presentation/widgets/flowy_mobile_quick_action_button.dart';import 'package:appflowy/plugins/ai_chat/application/chat_edit_document_service.dart';-import 'package:appflowy/plugins/ai_chat/application/chat_entity.dart';import 'package:appflowy/plugins/ai_chat/application/chat_select_message_bloc.dart';import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/clipboard_service.dart';import 'package:appflowy/shared/markdown_to_document.dart';@@ -22,7 +22,6 @@ import 'package:go_router/go_router.dart';import 'package:universal_platform/universal_platform.dart';import '../chat_avatar.dart';-import '../../../../ai/widgets/prompt_input/mention_page_bottom_sheet.dart';import '../layout_define.dart';import 'ai_message_action_bar.dart';import 'ai_change_format_bottom_sheet.dart';@@ -377,7 +376,7 @@ class ChatAIMessagePopup extends StatelessWidget {onRegenerate?.call();Navigator.of(context).pop();},- icon: FlowySvgs.ai_undo_s,+ icon: FlowySvgs.ai_try_again_s,iconSize: const Size.square(20),text: LocaleKeys.chat_regenerate.tr(),);@@ -470,7 +469,9 @@ class _WrapIsSelectingMessage extends StatelessWidget {if (isSelectingMessages)ChatSelectMessageIndicator(isSelected: isSelected)else- const ChatAIAvatar(),+ SelectionContainer.disabled(+ child: const ChatAIAvatar(),+ ),const HSpace(DesktopAIChatSizes.avatarAndChatBubbleSpacing),Expanded(child: IgnorePointer(diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_text_message.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_text_message.dartindex a54d2b8044..d6b3c87903 100644--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_text_message.dart+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_text_message.dart@@ -1,4 +1,4 @@-import 'package:appflowy/ai/widgets/loading_indicator.dart';+import 'package:appflowy/ai/ai.dart';import 'package:appflowy/generated/locale_keys.g.dart';import 'package:appflowy/plugins/ai_chat/application/chat_ai_message_bloc.dart';import 'package:appflowy/plugins/ai_chat/application/chat_bloc.dart';@@ -84,14 +84,20 @@ class ChatAIMessageWidget extends StatelessWidget {loading: () => ChatAIMessageBubble(message: message,showActions: false,- child: AILoadingIndicator(text: loadingText),+ child: Padding(+ padding: const EdgeInsets.only(top: 8.0),+ child: AILoadingIndicator(text: loadingText),+ ),),ready: () {return state.text.isEmpty? ChatAIMessageBubble(message: message,showActions: false,- child: AILoadingIndicator(text: loadingText),+ child: Padding(+ padding: const EdgeInsets.only(top: 8.0),+ child: AILoadingIndicator(text: loadingText),+ ),): ChatAIMessageBubble(message: message,@@ -107,9 +113,11 @@ class ChatAIMessageWidget extends StatelessWidget {children: [AIMarkdownText(markdown: state.text),if (state.sources.isNotEmpty)- AIMessageMetadata(- sources: state.sources,- onSelectedMetadata: onSelectedMetadata,+ SelectionContainer.disabled(+ child: AIMessageMetadata(+ sources: state.sources,+ onSelectedMetadata: onSelectedMetadata,+ ),),if (state.sources.isNotEmpty && !isLastMessage)const VSpace(8.0),diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/user_message_bubble.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/user_message_bubble.dartindex 8f897fc8a1..8bd115ad0f 100644--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/user_message_bubble.dart+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/user_message_bubble.dart@@ -59,9 +59,11 @@ class ChatUserMessageBubble extends StatelessWidget {return BlocBuilder<ChatMemberBloc, ChatMemberState>(builder: (context, state) {final member = state.members[message.author.id];- return ChatUserAvatar(- iconUrl: member?.info.avatarUrl ?? "",- name: member?.info.name ?? "",+ return SelectionContainer.disabled(+ child: ChatUserAvatar(+ iconUrl: member?.info.avatarUrl ?? "",+ name: member?.info.name ?? "",+ ),);},);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 b789de3881..2094462d6d 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@@ -4,7 +4,7 @@ import 'dart:convert';import 'package:appflowy/plugins/document/application/document_bloc.dart';import 'package:appflowy/plugins/document/application/document_data_pb_extension.dart';import 'package:appflowy/plugins/document/application/document_service.dart';-import 'package:appflowy/plugins/document/presentation/editor_plugins/ai/ask_ai_block_component.dart';+import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';import 'package:appflowy_backend/log.dart';import 'package:appflowy_backend/protobuf/flowy-document/protobuf.dart';import 'package:appflowy_editor/appflowy_editor.dart';@@ -163,7 +163,7 @@ extension on InsertOperation {Path currentPath = path;final List<BlockActionWrapper> actions = [];for (final node in nodes) {- if (node.type == AskAIBlockKeys.type) {+ if (node.type == AiWriterBlockKeys.type) {continue;}diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_configuration.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_configuration.dartindex 2d6a52a58d..d5e44301ad 100644--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_configuration.dart+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_configuration.dart@@ -343,11 +343,7 @@ Map<String, BlockComponentBuilder> _buildBlockComponentBuilderMap(configuration,styleCustomizer,),- AIWriterBlockKeys.type: _buildAIWriterBlockComponentBuilder(- context,- configuration,- ),- AskAIBlockKeys.type: _buildAskAIBlockComponentBuilder(+ AiWriterBlockKeys.type: _buildAIWriterBlockComponentBuilder(context,configuration,),@@ -836,13 +832,6 @@ AIWriterBlockComponentBuilder _buildAIWriterBlockComponentBuilder(return AIWriterBlockComponentBuilder();}-AskAIBlockComponentBuilder _buildAskAIBlockComponentBuilder(- BuildContext context,- BlockComponentConfiguration configuration,-) {- return AskAIBlockComponentBuilder();-}-ToggleListBlockComponentBuilder _buildToggleListBlockComponentBuilder(BuildContext context,BlockComponentConfiguration configuration,diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_page.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_page.dartindex 1425c2867c..9d1119ecf1 100644--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_page.dart+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_page.dart@@ -80,7 +80,8 @@ class _AppFlowyEditorPageState extends State<AppFlowyEditorPage>];final List<ToolbarItem> toolbarItems = [- askAIItem..isActive = onlyShowInTextType,+ improveWritingItem..isActive = onlyShowInTextType,+ aiWriterItem..isActive = onlyShowInTextType,paragraphItem..isActive = onlyShowInSingleTextTypeSelectionAndExcludeTable,headingsToolbarItem..isActive = onlyShowInSingleTextTypeSelectionAndExcludeTable,diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/ai_writer_block_component.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/ai_writer_block_component.dartindex 51e8cf0276..fd1d0c4c82 100644--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/ai_writer_block_component.dart+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/ai_writer_block_component.dart@@ -1,49 +1,53 @@-import 'package:appflowy/ai/service/appflowy_ai_service.dart';-import 'package:appflowy/ai/service/error.dart';+import 'package:appflowy/ai/ai.dart';+import 'package:appflowy/generated/flowy_svgs.g.dart';import 'package:appflowy/generated/locale_keys.g.dart';+import 'package:appflowy/plugins/ai_chat/presentation/message/ai_markdown_text.dart';import 'package:appflowy/plugins/document/application/prelude.dart';-import 'package:appflowy/plugins/document/presentation/editor_plugins/base/build_context_extension.dart';-import 'package:appflowy/plugins/document/presentation/editor_plugins/base/markdown_text_robot.dart';+import 'package:appflowy/util/theme_extension.dart';+import 'package:appflowy/workspace/presentation/home/menu/sidebar/space/shared_widget.dart';import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';-import 'package:appflowy_backend/log.dart';-import 'package:appflowy_backend/protobuf/flowy-ai/entities.pb.dart';import 'package:appflowy_editor/appflowy_editor.dart';import 'package:easy_localization/easy_localization.dart';+import 'package:flowy_infra/colorscheme/default_colorscheme.dart';import 'package:flowy_infra_ui/flowy_infra_ui.dart';import 'package:flutter/material.dart';-import 'package:flutter/services.dart';-import 'package:provider/provider.dart';+import 'package:flutter_bloc/flutter_bloc.dart';import 'package:universal_platform/universal_platform.dart';-import 'widgets/ai_limit_dialog.dart';-import 'widgets/ai_writer_block_operations.dart';-import 'widgets/ai_writer_block_widgets.dart';-import 'widgets/discard_dialog.dart';-import 'widgets/barrier_dialog.dart';+import 'operations/ai_writer_cubit.dart';+import 'operations/ai_writer_entities.dart';+import 'operations/ai_writer_node_extension.dart';+import 'suggestion_action_bar.dart';-class AIWriterBlockKeys {- const AIWriterBlockKeys._();+class AiWriterBlockKeys {+ const AiWriterBlockKeys._();static const String type = 'ai_writer';- static const String prompt = 'prompt';- static const String startSelection = 'start_selection';- static const String generationCount = 'generation_count';- static String getRewritePrompt(String previousOutput, String prompt) {- return 'I am not satisfied with your previous response ($previousOutput) to the query ($prompt). Please provide an alternative response.';- }+ static const String isInitialized = 'is_initialized';+ static const String selection = 'selection';+ static const String command = 'command';++ /// Sample usage:+ ///+ /// `attributes: {+ /// 'ai_writer_delta_suggestion': 'original'+ /// }`+ static const String suggestion = 'ai_writer_delta_suggestion';+ static const String suggestionOriginal = 'original';+ static const String suggestionReplacement = 'replacement';}Node aiWriterNode({- String prompt = '',- required Selection start,+ required Selection? selection,+ required AiWriterCommand command,}) {return Node(- type: AIWriterBlockKeys.type,+ type: AiWriterBlockKeys.type,attributes: {- AIWriterBlockKeys.prompt: prompt,- AIWriterBlockKeys.startSelection: start.toJson(),- AIWriterBlockKeys.generationCount: 0,+ AiWriterBlockKeys.isInitialized: false,+ AiWriterBlockKeys.selection: selection?.toJson(),+ AiWriterBlockKeys.command: command.index,},);}@@ -54,7 +58,7 @@ class AIWriterBlockComponentBuilder extends BlockComponentBuilder {@overrideBlockComponentWidget build(BlockComponentContext blockComponentContext) {final node = blockComponentContext.node;- return AIWriterBlockComponent(+ return AiWriterBlockComponent(key: node.key,node: node,showActions: showActions(node),@@ -68,12 +72,13 @@ class AIWriterBlockComponentBuilder extends BlockComponentBuilder {@overrideBlockComponentValidate get validate => (node) =>node.children.isEmpty &&- node.attributes[AIWriterBlockKeys.prompt] is String &&- node.attributes[AIWriterBlockKeys.startSelection] is Map;+ node.attributes[AiWriterBlockKeys.isInitialized] is bool &&+ node.attributes[AiWriterBlockKeys.selection] is Map? &&+ node.attributes[AiWriterBlockKeys.command] is int;}-class AIWriterBlockComponent extends BlockComponentStatefulWidget {- const AIWriterBlockComponent({+class AiWriterBlockComponent extends BlockComponentStatefulWidget {+ const AiWriterBlockComponent({super.key,required super.node,super.showActions,@@ -82,51 +87,42 @@ class AIWriterBlockComponent extends BlockComponentStatefulWidget {});@override- State<AIWriterBlockComponent> createState() => _AIWriterBlockComponentState();+ State<AiWriterBlockComponent> createState() => _AIWriterBlockComponentState();}-class _AIWriterBlockComponentState extends State<AIWriterBlockComponent> {- final controller = TextEditingController();+class _AIWriterBlockComponentState extends State<AiWriterBlockComponent> {+ final key = GlobalKey();+ final textController = TextEditingController();final textFieldFocusNode = FocusNode();+ final overlayController = OverlayPortalController();+ final layerLink = LayerLink();late final editorState = context.read<EditorState>();- late final SelectionGestureInterceptor interceptor;- late final aiWriterOperations = AIWriterBlockOperations(+ late final aiWriterCubit = AiWriterCubit(+ documentId: context.read<DocumentBloc>().documentId,editorState: editorState,- aiWriterNode: widget.node,+ getAiWriterNode: () => widget.node,+ initialCommand: widget.node.aiWriterCommand,);- String get prompt => widget.node.attributes[AIWriterBlockKeys.prompt];- int get generationCount =>- widget.node.attributes[AIWriterBlockKeys.generationCount] ?? 0;- Selection? get startSelection {- final selection = widget.node.attributes[AIWriterBlockKeys.startSelection];- if (selection != null) {- return Selection.fromJson(selection);- }- return null;- }-- bool isGenerating = false;-@overridevoid initState() {super.initState();- _subscribeSelectionGesture();- WidgetsBinding.instance.addPostFrameCallback((timeStamp) {- editorState.selection = null;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ overlayController.show();textFieldFocusNode.requestFocus();+ if (!widget.node.isAiWriterInitialized) {+ aiWriterCubit.init();+ }});}@overridevoid dispose() {- _onExit();- _unsubscribeSelectionGesture();- controller.dispose();+ textController.dispose();textFieldFocusNode.dispose();-+ aiWriterCubit.close();super.dispose();}@@ -136,277 +132,479 @@ class _AIWriterBlockComponentState extends State<AIWriterBlockComponent> {return const SizedBox.shrink();}- final child = Focus(- onKeyEvent: (node, event) {- if (event is! KeyDownEvent) {- return KeyEventResult.ignored;- }- if (event.logicalKey == LogicalKeyboardKey.enter) {- if (!isGenerating) {- _onGenerate();- }- return KeyEventResult.handled;- }- return KeyEventResult.ignored;- },- child: Card(- elevation: 5,- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(10),+ return MultiBlocProvider(+ providers: [+ BlocProvider.value(+ value: aiWriterCubit,),- color: Theme.of(context).colorScheme.surface,- child: Container(- margin: const EdgeInsets.all(10),- child: Column(- mainAxisSize: MainAxisSize.min,- children: [- const AIWriterBlockHeader(),- const Space(0, 10),- if (prompt.isEmpty && generationCount < 1) ...[- _buildInputWidget(context),- const Space(0, 10),- AIWriterBlockInputField(- onGenerate: _onGenerate,- onExit: _onExit,- ),- ] else ...[- AIWriterBlockFooter(- onKeep: _onExit,- onRewrite: _onRewrite,- onDiscard: _onDiscard,- ),- ],- ],+ BlocProvider(+ create: (_) => AIPromptInputBloc(+ predefinedFormat: null,),),+ ],+ child: LayoutBuilder(+ builder: (context, constraints) {+ return BlocListener<AiWriterCubit, AiWriterState>(+ listener: (context, state) {+ if (state is SingleShotAiWriterState) {+ showConfirmDialog(+ context: context,+ title: state.title,+ description: state.description,+ onConfirm: state.onDismiss,+ );+ }+ },+ child: OverlayPortal(+ controller: overlayController,+ overlayChildBuilder: (context) {+ return Stack(+ children: [+ BlocBuilder<AiWriterCubit, AiWriterState>(+ builder: (context, state) {+ final hitTestBehavior = state is GeneratingAiWriterState+ ? HitTestBehavior.opaque+ : HitTestBehavior.translucent;+ return GestureDetector(+ behavior: hitTestBehavior,+ onTap: () => onTapOutside(),+ );+ },+ ),+ CompositedTransformFollower(+ link: layerLink,+ showWhenUnlinked: false,+ child: Container(+ padding: const EdgeInsets.only(+ left: 40.0,+ bottom: 16.0,+ ),+ width: constraints.maxWidth,+ child: OverlayContent(+ node: widget.node,+ ),+ ),+ ),+ ],+ );+ },+ child: CompositedTransformTarget(+ link: layerLink,+ child: BlocBuilder<AiWriterCubit, AiWriterState>(+ builder: (context, state) {+ return SizedBox(+ key: key,+ width: double.infinity,+ );+ },+ ),+ ),+ ),+ );+ },),);-- return Padding(- padding: const EdgeInsets.only(left: 40),- child: child,- );}- Widget _buildInputWidget(BuildContext context) {- return FlowyTextField(- hintText: LocaleKeys.document_plugins_autoGeneratorHintText.tr(),- controller: controller,- maxLines: 5,- focusNode: textFieldFocusNode,- autoFocus: false,- hintTextConstraints: const BoxConstraints(),- );- }-- Future<void> _onExit() async {- await aiWriterOperations.removeAIWriterNode(widget.node);- }-- Future<void> _onGenerate() async {- if (isGenerating) {- return;+ void onTapOutside() {+ if (aiWriterCubit.hasUnusedResponse()) {+ showConfirmDialog(+ context: context,+ title: LocaleKeys.button_discard.tr(),+ description: LocaleKeys.document_plugins_discardResponse.tr(),+ confirmLabel: LocaleKeys.button_discard.tr(),+ style: ConfirmPopupStyle.cancelAndOk,+ onConfirm: () => aiWriterCubit+ ..stopStream()+ ..exit(),+ onCancel: () {},+ );+ } else {+ aiWriterCubit+ ..stopStream()+ ..exit();}+ }+}- isGenerating = true;-- await aiWriterOperations.updatePromptText(controller.text);-- if (!_isAIWriterEnabled) {- Log.error('AI Writer is not enabled');- return;- }+class OverlayContent extends StatelessWidget {+ const OverlayContent({+ super.key,+ required this.node,+ });- final markdownTextRobot = MarkdownTextRobot(- editorState: editorState,- );+ final Node node;- BarrierDialog? barrierDialog;-- final aiRepository = AppFlowyAIService();- final objectId =- editorState.document.root.context?.read<DocumentBloc>().documentId ??- "";-- await aiRepository.streamCompletion(- objectId: objectId,- text: controller.text,- completionType: CompletionTypePB.ContinueWriting,- onStart: () async {- if (mounted) {- barrierDialog = BarrierDialog(context);- barrierDialog?.show();- await aiWriterOperations.ensurePreviousNodeIsEmptyParagraphNode();- markdownTextRobot.start();- }- },- onProcess: (text) async {- await markdownTextRobot.appendMarkdownText(text);- },- onEnd: () async {- barrierDialog?.dismiss();- await markdownTextRobot.stop();- editorState.service.keyboardService?.enable();- },- onError: (error) async {- barrierDialog?.dismiss();- _showAIWriterError(error);+ @override+ Widget build(BuildContext context) {+ return BlocBuilder<AiWriterCubit, AiWriterState>(+ builder: (context, state) {+ final selection = node.aiWriterSelection;+ final showSuggestionPopup =+ state is ReadyAiWriterState && !state.isFirstRun;+ final showActionPopup = state is ReadyAiWriterState && state.isFirstRun;+ final markdownText = switch (state) {+ final ReadyAiWriterState ready => ready.markdownText,+ final GeneratingAiWriterState generating => generating.markdownText,+ _ => '',+ };+ final hasSelection = selection != null && !selection.isCollapsed;++ final isLightMode = Theme.of(context).isLightMode;+ final darkBorderColor =+ isLightMode ? Color(0x1F1F2329) : Color(0xFF505469);+ final lightBorderColor =+ Theme.of(context).brightness == Brightness.light+ ? ColorSchemeConstants.lightBorderColor+ : ColorSchemeConstants.darkBorderColor;++ return Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ if (showSuggestionPopup &&+ state.command != AiWriterCommand.explain) ...[+ Container(+ padding: EdgeInsets.all(4.0),+ decoration: _getModalDecoration(+ context,+ color: Theme.of(context).colorScheme.surface,+ borderRadius: BorderRadius.all(Radius.circular(8.0)),+ borderColor: darkBorderColor,+ ),+ child: SuggestionActionBar(+ actions: _getSuggestedActions(+ currentCommand: state.command,+ hasSelection: hasSelection,+ ),+ onTap: (action) {+ context.read<AiWriterCubit>().runResponseAction(action);+ },+ ),+ ),+ const VSpace(4.0 + 1.0),+ ],+ DecoratedBox(+ decoration: _getModalDecoration(+ context,+ color: null,+ borderColor: darkBorderColor,+ borderRadius: BorderRadius.all(Radius.circular(12.0)),+ ),+ child: Column(+ children: [+ if (markdownText.isNotEmpty) ...[+ DecoratedBox(+ decoration: _getHelperChildDecoration(context),+ child: Container(+ constraints: BoxConstraints(maxHeight: 140),+ width: double.infinity,+ child: SingleChildScrollView(+ padding: EdgeInsets.all(8.0),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Container(+ height: 24.0,+ padding: EdgeInsets.symmetric(horizontal: 6.0),+ alignment: AlignmentDirectional.centerStart,+ child: FlowyText(+ state.command.i18n,+ fontSize: 12,+ fontWeight: FontWeight.w600,+ color: Color(0xFF666D76),+ ),+ ),+ const VSpace(4.0),+ Padding(+ padding: EdgeInsets.symmetric(horizontal: 6.0),+ child: AIMarkdownText(+ markdown: markdownText,+ ),+ ),+ if (showSuggestionPopup) ...[+ const VSpace(4.0),+ SuggestionActionBar(+ actions: _getSuggestedActions(+ currentCommand: state.command,+ hasSelection: hasSelection,+ ),+ onTap: (action) {+ context+ .read<AiWriterCubit>()+ .runResponseAction(action);+ },+ ),+ ],+ ],+ ),+ ),+ ),+ ),+ Divider(+ height: 1.0,+ ),+ ],+ DecoratedBox(+ decoration: markdownText.isNotEmpty+ ? _getInputChildDecoration(context)+ : _getSingleChildDeocoration(context),+ child: MainContentArea(),+ ),+ ],+ ),+ ),+ if (showActionPopup) ...[+ const VSpace(4.0 + 1.0),+ Container(+ padding: EdgeInsets.all(8.0),+ constraints: BoxConstraints(minWidth: 240.0),+ decoration: _getModalDecoration(+ context,+ color: Theme.of(context).colorScheme.surface,+ borderColor: lightBorderColor,+ borderRadius: BorderRadius.all(Radius.circular(8.0)),+ ),+ child: IntrinsicWidth(+ child: SeparatedColumn(+ separatorBuilder: () => const VSpace(4.0),+ crossAxisAlignment: CrossAxisAlignment.start,+ children: _getCommands(+ hasSelection: hasSelection,+ ),+ ),+ ),+ ),+ ],+ ],+ );},);-- await aiWriterOperations.updateGenerationCount(generationCount + 1);-- isGenerating = false;}- Future<void> _onDiscard() async {- await aiWriterOperations.discardCurrentResponse(- aiWriterNode: widget.node,- selection: startSelection,+ Widget _bottomButton(AiWriterCommand command) {+ return Builder(+ builder: (context) {+ return SizedBox(+ height: 30.0,+ child: FlowyButton(+ leftIcon: FlowySvg(+ command.icon,+ size: const Size.square(16),+ color: Theme.of(context).iconTheme.color,+ ),+ margin: const EdgeInsets.all(6.0),+ text: FlowyText(+ command.i18n,+ figmaLineHeight: 20,+ ),+ onTap: () {+ final aiInputBloc = context.read<AIPromptInputBloc>();+ final showPredefinedFormats =+ aiInputBloc.state.showPredefinedFormats;+ final predefinedFormat = aiInputBloc.state.predefinedFormat;++ context.read<AiWriterCubit>().runCommand(+ command,+ showPredefinedFormats ? predefinedFormat : null,+ );+ },+ ),+ );+ },);- return _onExit();}- Future<void> _onRewrite() async {- if (isGenerating) {- return;- }-- isGenerating = true;-- final previousOutput = _getPreviousOutput();- if (previousOutput == null) {- return;- }-- // discard the current response- await aiWriterOperations.discardCurrentResponse(- aiWriterNode: widget.node,- selection: startSelection,- );-- if (!_isAIWriterEnabled) {- return;- }-- final markdownTextRobot = MarkdownTextRobot(- editorState: editorState,- );- final aiService = AppFlowyAIService();- final objectId =- editorState.document.root.context?.read<DocumentBloc>().documentId ??- "";- await aiService.streamCompletion(- objectId: objectId,- text: AIWriterBlockKeys.getRewritePrompt(previousOutput, prompt),- completionType: CompletionTypePB.ContinueWriting,- onStart: () async {- await aiWriterOperations.ensurePreviousNodeIsEmptyParagraphNode();-- markdownTextRobot.start();- },- onProcess: (text) async {- await markdownTextRobot.appendMarkdownText(text);- },- onEnd: () async {- await markdownTextRobot.stop();- },- onError: (error) {- _showAIWriterError(error);- },+ BoxDecoration _getModalDecoration(+ BuildContext context, {+ required Color? color,+ required Color borderColor,+ required BorderRadius borderRadius,+ }) {+ return BoxDecoration(+ color: color,+ border: Border.all(+ color: borderColor,+ strokeAlign: BorderSide.strokeAlignOutside,+ ),+ borderRadius: borderRadius,+ boxShadow: const [+ BoxShadow(+ offset: Offset(0, 4),+ blurRadius: 20,+ color: Color(0x1A1F2329),+ ),+ ],);-- await aiWriterOperations.updateGenerationCount(generationCount + 1);-- isGenerating = false;}- String? _getPreviousOutput() {- final startSelection = this.startSelection;- if (startSelection != null) {- final end = widget.node.previous?.path;-- if (end != null) {- final result = editorState- .getNodesInSelection(- startSelection.copyWith(end: Position(path: end)),- )- .fold(- '',- (previousValue, element) {- final delta = element.delta;- if (delta != null) {- return "$previousValue\n${delta.toPlainText()}";- } else {- return previousValue;- }- },- );- return result.trim();- }- }- return null;+ BoxDecoration _getSingleChildDeocoration(BuildContext context) {+ return BoxDecoration(+ color: Theme.of(context).colorScheme.surface,+ borderRadius: BorderRadius.all(Radius.circular(12.0)),+ );}- void _subscribeSelectionGesture() {- interceptor = SelectionGestureInterceptor(- key: AIWriterBlockKeys.type,- canTap: (details) {- if (!context.isOffsetInside(details.globalPosition)) {- if (prompt.isNotEmpty || controller.text.isNotEmpty) {- // show dialog- showDialog(- context: context,- builder: (_) => DiscardDialog(- onConfirm: _onDiscard,- onCancel: () {},- ),- );- } else if (controller.text.isEmpty) {- _onExit();- }- }- editorState.service.keyboardService?.disable();- return false;- },- );- editorState.service.selectionService.registerGestureInterceptor(- interceptor,+ BoxDecoration _getHelperChildDecoration(BuildContext context) {+ return BoxDecoration(+ color: Theme.of(context).colorScheme.surfaceContainerHighest,+ borderRadius: BorderRadius.vertical(top: Radius.circular(12.0)),);}- void _unsubscribeSelectionGesture() {- editorState.service.selectionService.unregisterGestureInterceptor(- AIWriterBlockKeys.type,+ BoxDecoration _getInputChildDecoration(BuildContext context) {+ return BoxDecoration(+ color: Theme.of(context).colorScheme.surface,+ borderRadius: BorderRadius.vertical(bottom: Radius.circular(12.0)),);}- void _showAIWriterError(AIError error) {- if (mounted) {- if (error.isLimitExceeded) {- showAILimitDialog(context, error.message);- } else {- showToastNotification(- context,- message: error.message,- type: ToastificationType.error,- );- }+ List<Widget> _getCommands({required bool hasSelection}) {+ if (hasSelection) {+ return [+ _bottomButton(AiWriterCommand.improveWriting),+ _bottomButton(AiWriterCommand.fixSpellingAndGrammar),+ _bottomButton(AiWriterCommand.explain),+ const Divider(height: 1.0, thickness: 1.0),+ _bottomButton(AiWriterCommand.makeLonger),+ _bottomButton(AiWriterCommand.makeShorter),+ ];+ } else {+ return [+ _bottomButton(AiWriterCommand.continueWriting),+ ];}}- bool get _isAIWriterEnabled {- final userProfile = context.read<DocumentBloc>().state.userProfilePB;- final isAIWriterEnabled = userProfile != null;-- if (!isAIWriterEnabled) {- showToastNotification(- context,- message: LocaleKeys.document_plugins_autoGeneratorCantGetOpenAIKey.tr(),- type: ToastificationType.error,- );+ List<SuggestionAction> _getSuggestedActions({+ required AiWriterCommand currentCommand,+ required bool hasSelection,+ }) {+ if (hasSelection) {+ return switch (currentCommand) {+ AiWriterCommand.userQuestion || AiWriterCommand.continueWriting => [+ SuggestionAction.keep,+ SuggestionAction.discard,+ SuggestionAction.rewrite,+ ],+ AiWriterCommand.explain => [+ SuggestionAction.insertBelow,+ SuggestionAction.tryAgain,+ SuggestionAction.close,+ ],+ AiWriterCommand.fixSpellingAndGrammar ||+ AiWriterCommand.improveWriting ||+ AiWriterCommand.makeShorter ||+ AiWriterCommand.makeLonger =>+ [+ SuggestionAction.accept,+ SuggestionAction.discard,+ SuggestionAction.insertBelow,+ SuggestionAction.rewrite,+ ],+ };+ } else {+ return switch (currentCommand) {+ AiWriterCommand.userQuestion || AiWriterCommand.continueWriting => [+ SuggestionAction.keep,+ SuggestionAction.discard,+ SuggestionAction.rewrite,+ ],+ AiWriterCommand.explain => [+ SuggestionAction.insertBelow,+ SuggestionAction.tryAgain,+ SuggestionAction.close,+ ],+ _ => [+ SuggestionAction.keep,+ SuggestionAction.discard,+ SuggestionAction.rewrite,+ ],+ };}+ }+}- return isAIWriterEnabled;+class MainContentArea extends StatelessWidget {+ const MainContentArea({super.key});++ @override+ Widget build(BuildContext context) {+ return BlocBuilder<AiWriterCubit, AiWriterState>(+ builder: (context, state) {+ final cubit = context.read<AiWriterCubit>();++ if (state is ReadyAiWriterState) {+ return DesktopPromptInput(+ isStreaming: false,+ hideDecoration: true,+ onSubmitted: (message, format, _) => cubit.submit(message, format),+ onStopStreaming: () => cubit.stopStream(),+ selectedSourcesNotifier: cubit.selectedSourcesNotifier,+ onUpdateSelectedSources: (sources) {+ cubit.selectedSourcesNotifier.value = [+ ...sources,+ ];+ },+ );+ }+ if (state is GeneratingAiWriterState) {+ return Padding(+ padding: const EdgeInsets.all(8.0),+ child: Row(+ children: [+ const HSpace(6.0),+ Expanded(+ child: AILoadingIndicator(+ text: state.command == AiWriterCommand.explain+ ? LocaleKeys.ai_analyzing.tr()+ : LocaleKeys.ai_editing.tr(),+ ),+ ),+ const HSpace(8.0),+ PromptInputSendButton(+ state: SendButtonState.streaming,+ onSendPressed: () {},+ onStopStreaming: () => cubit.stopStream(),+ ),+ ],+ ),+ );+ }+ if (state is ErrorAiWriterState) {+ return Padding(+ padding: EdgeInsets.all(8.0),+ child: Row(+ children: [+ const FlowySvg(+ FlowySvgs.toast_error_filled_s,+ blendMode: null,+ ),+ const HSpace(8.0),+ Expanded(+ child: FlowyText(+ state.error.message,+ maxLines: null,+ ),+ ),+ const HSpace(8.0),+ FlowyIconButton(+ width: 32,+ hoverColor: Colors.transparent,+ icon: FlowySvg(+ FlowySvgs.toast_close_s,+ size: Size.square(20),+ ),+ onPressed: () => cubit.exit(),+ ),+ ],+ ),+ );+ }+ return const SizedBox.shrink();+ },+ );}}diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/ai_writer_toolbar_item.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/ai_writer_toolbar_item.dartnew file mode 100644index 0000000000..96fb8289d3--- /dev/null+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/ai_writer_toolbar_item.dart@@ -0,0 +1,241 @@+import 'package:appflowy/generated/flowy_svgs.g.dart';+import 'package:appflowy/generated/locale_keys.g.dart';+import 'package:appflowy/plugins/document/application/document_bloc.dart';+import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';+import 'package:appflowy_editor/appflowy_editor.dart';+import 'package:easy_localization/easy_localization.dart';+import 'package:flowy_infra_ui/flowy_infra_ui.dart';+import 'package:flutter/material.dart';+import 'package:flutter_bloc/flutter_bloc.dart';++import 'ai_writer_block_component.dart';+import 'operations/ai_writer_entities.dart';++const _improveWritingToolbarItemId = 'appflowy.editor.ai_improve_writing';+const _aiWriterToolbarItemId = 'appflowy.editor.ai_writer';++final ToolbarItem improveWritingItem = ToolbarItem(+ id: _improveWritingToolbarItemId,+ group: 0,+ isActive: onlyShowInSingleSelectionAndTextType,+ builder: (context, editorState, _, __, tooltipBuilder) =>+ ImproveWritingButton(+ editorState: editorState,+ tooltipBuilder: tooltipBuilder,+ ),+);++final ToolbarItem aiWriterItem = ToolbarItem(+ id: _aiWriterToolbarItemId,+ group: 0,+ isActive: onlyShowInSingleSelectionAndTextType,+ builder: (context, editorState, _, __, tooltipBuilder) =>+ AiWriterToolbarActionList(+ editorState: editorState,+ tooltipBuilder: tooltipBuilder,+ ),+);++class AiWriterToolbarActionList extends StatefulWidget {+ const AiWriterToolbarActionList({+ super.key,+ required this.editorState,+ this.tooltipBuilder,+ });++ final EditorState editorState;+ final ToolbarTooltipBuilder? tooltipBuilder;++ @override+ State<AiWriterToolbarActionList> createState() =>+ _AiWriterToolbarActionListState();+}++class _AiWriterToolbarActionListState extends State<AiWriterToolbarActionList> {+ final popoverController = PopoverController();++ @override+ Widget build(BuildContext context) {+ return AppFlowyPopover(+ controller: popoverController,+ direction: PopoverDirection.bottomWithLeftAligned,+ offset: const Offset(-8.0, 2.0),+ margin: const EdgeInsets.all(8.0),+ onOpen: () => keepEditorFocusNotifier.increase(),+ onClose: () => keepEditorFocusNotifier.decrease(),+ popupBuilder: (context) => buildPopoverContent(),+ child: buildChild(),+ );+ }++ Widget buildPopoverContent() {+ return SeparatedColumn(+ mainAxisSize: MainAxisSize.min,+ separatorBuilder: () => const VSpace(4.0),+ children: [+ actionWrapper(AiWriterCommand.improveWriting),+ actionWrapper(AiWriterCommand.userQuestion),+ actionWrapper(AiWriterCommand.fixSpellingAndGrammar),+ // actionWrapper(AiWriterCommand.summarize),+ actionWrapper(AiWriterCommand.explain),+ divider(),+ actionWrapper(AiWriterCommand.makeLonger),+ actionWrapper(AiWriterCommand.makeShorter),+ ],+ );+ }++ Widget actionWrapper(AiWriterCommand command) {+ return SizedBox(+ height: 30.0,+ child: FlowyButton(+ leftIcon: FlowySvg(+ command.icon,+ size: const Size.square(16),+ ),+ text: FlowyText(+ command.i18n,+ figmaLineHeight: 20,+ ),+ onTap: () {+ popoverController.close();+ _insertAiNode(widget.editorState, command);+ },+ ),+ );+ }++ Widget divider() {+ return const Divider(+ thickness: 1.0,+ height: 1.0,+ );+ }++ Widget buildChild() {+ final child = FlowyIconButton(+ hoverColor: Colors.transparent,+ width: 36,+ height: 24,+ icon: Row(+ children: [+ const FlowySvg(+ FlowySvgs.ai_sparks_s,+ size: Size.square(16.0),+ color: Color(0xFFD08EED),+ ),+ const FlowySvg(+ FlowySvgs.ai_source_drop_down_s,+ size: Size.square(12),+ color: Color(0xFF8F959E),+ ),+ ],+ ),+ iconPadding: const EdgeInsets.symmetric(+ horizontal: 4.0,+ vertical: 2.0,+ ),+ onPressed: () {+ if (_isAIEnabled(widget.editorState)) {+ keepEditorFocusNotifier.increase();+ popoverController.show();+ } else {+ showToastNotification(+ context,+ message: LocaleKeys.document_plugins_appflowyAIEditDisabled.tr(),+ );+ }+ },+ );++ return widget.tooltipBuilder?.call(+ context,+ _aiWriterToolbarItemId,+ _isAIEnabled(widget.editorState)+ ? LocaleKeys.document_plugins_aiWriter_userQuestion.tr()+ : LocaleKeys.document_plugins_appflowyAIEditDisabled.tr(),+ child,+ ) ??+ child;+ }+}++class ImproveWritingButton extends StatelessWidget {+ const ImproveWritingButton({+ super.key,+ required this.editorState,+ this.tooltipBuilder,+ });++ final EditorState editorState;+ final ToolbarTooltipBuilder? tooltipBuilder;++ @override+ Widget build(BuildContext context) {+ final child = FlowyIconButton(+ hoverColor: Colors.transparent,+ width: 24,+ icon: const FlowySvg(+ FlowySvgs.ai_improve_writing_s,+ size: Size.square(16.0),+ color: Color(0xFFD08EED),+ ),+ iconPadding: const EdgeInsets.symmetric(+ horizontal: 4.0,+ vertical: 2.0,+ ),+ onPressed: () {+ if (_isAIEnabled(editorState)) {+ keepEditorFocusNotifier.increase();+ } else {+ showToastNotification(+ context,+ message: LocaleKeys.document_plugins_appflowyAIEditDisabled.tr(),+ );+ }+ },+ );++ return tooltipBuilder?.call(+ context,+ _aiWriterToolbarItemId,+ _isAIEnabled(editorState)+ ? LocaleKeys.document_plugins_aiWriter_improveWriting.tr()+ : LocaleKeys.document_plugins_appflowyAIEditDisabled.tr(),+ child,+ ) ??+ child;+ }+}++void _insertAiNode(EditorState editorState, AiWriterCommand command) async {+ final selection = editorState.selection?.normalized;+ if (selection == null) {+ return;+ }++ final transaction = editorState.transaction+ ..insertNode(+ selection.end.path.next,+ aiWriterNode(+ selection: selection,+ command: command,+ ),+ )+ ..afterSelection = selection+ ..selectionExtraInfo = {selectionExtraInfoDisableToolbar: true};++ await editorState.apply(+ transaction,+ options: const ApplyOptions(+ recordUndo: false,+ inMemoryUpdate: true,+ ),+ );+}++bool _isAIEnabled(EditorState editorState) {+ final documentContext = editorState.document.root.context;+ return documentContext == null ||+ !documentContext.read<DocumentBloc>().isLocalMode;+}diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/ask_ai_block_component.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/ask_ai_block_component.dartdeleted file mode 100644index df3724f90e..0000000000--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/ask_ai_block_component.dart+++ /dev/null@@ -1,214 +0,0 @@-import 'dart:async';--import 'package:appflowy/ai/service/appflowy_ai_service.dart';-import 'package:appflowy/ai/service/error.dart';-import 'package:appflowy/generated/locale_keys.g.dart';-import 'package:appflowy/ai/service/ai_client.dart';-import 'package:appflowy/plugins/document/application/document_bloc.dart';-import 'package:appflowy/plugins/document/presentation/editor_plugins/ai/widgets/ai_limit_dialog.dart';-import 'package:appflowy/plugins/document/presentation/editor_plugins/ai/widgets/ask_ai_action_bloc.dart';-import 'package:appflowy/plugins/document/presentation/editor_plugins/ai/widgets/ask_ai_block_widgets.dart';-import 'package:appflowy/startup/startup.dart';-import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';-import 'package:appflowy_editor/appflowy_editor.dart';-import 'package:easy_localization/easy_localization.dart';-import 'package:flowy_infra_ui/flowy_infra_ui.dart';-import 'package:flutter/material.dart';-import 'package:flutter_bloc/flutter_bloc.dart';-import 'package:universal_platform/universal_platform.dart';--class AskAIBlockKeys {- const AskAIBlockKeys._();-- static const type = 'ask_ai';-- /// The instruction of the smart edit.- ///- /// It is a [AskAIAction] value.- static const action = 'action';-- /// The input of the smart edit.- ///- /// The content is a string that using '\n\n' as separator.- static const content = 'content';-}--Node askAINode({- required AskAIAction action,- required String content,-}) {- return Node(- type: AskAIBlockKeys.type,- attributes: {- AskAIBlockKeys.action: action.index,- AskAIBlockKeys.content: content,- },- );-}--class AskAIBlockComponentBuilder extends BlockComponentBuilder {- AskAIBlockComponentBuilder();-- @override- BlockComponentWidget build(BlockComponentContext blockComponentContext) {- final node = blockComponentContext.node;- return AskAIBlockComponentWidget(- key: node.key,- node: node,- showActions: showActions(node),- actionBuilder: (context, state) => actionBuilder(- blockComponentContext,- state,- ),- );- }-- @override- BlockComponentValidate get validate => (node) =>- node.attributes[AskAIBlockKeys.action] is int &&- node.attributes[AskAIBlockKeys.content] is String;-}--class AskAIBlockComponentWidget extends BlockComponentStatefulWidget {- const AskAIBlockComponentWidget({- super.key,- required super.node,- super.showActions,- super.actionBuilder,- super.configuration = const BlockComponentConfiguration(),- });-- @override- State<AskAIBlockComponentWidget> createState() =>- _AskAIBlockComponentWidgetState();-}--class _AskAIBlockComponentWidgetState extends State<AskAIBlockComponentWidget> {- final popoverController = PopoverController();-- late final editorState = context.read<EditorState>();- late final action =- AskAIAction.values[widget.node.attributes[AskAIBlockKeys.action] as int];- late AskAIActionBloc askAIBloc;-- @override- void initState() {- super.initState();-- WidgetsBinding.instance.addPostFrameCallback((timeStamp) {- popoverController.show();- });-- final objectId =- editorState.document.root.context?.read<DocumentBloc>().documentId ??- "";-- askAIBloc = AskAIActionBloc(- objectId: objectId,- node: widget.node,- editorState: editorState,- action: action,- )..add(AskAIEvent.initial(getIt.getAsync<AIRepository>()));- }-- @override- void dispose() {- askAIBloc.close();-- super.dispose();- }-- @override- void reassemble() {- super.reassemble();-- _removeNode();- }-- @override- Widget build(BuildContext context) {- if (UniversalPlatform.isMobile) {- return const SizedBox.shrink();- }-- final width = _getEditorWidth();-- return BlocProvider.value(- value: askAIBloc,- child: BlocListener<AskAIActionBloc, AskAIState>(- listener: _onListen,- child: AppFlowyPopover(- controller: popoverController,- direction: PopoverDirection.bottomWithLeftAligned,- triggerActions: PopoverTriggerFlags.none,- margin: EdgeInsets.zero,- offset: const Offset(40, 0), // align the editor block- windowPadding: EdgeInsets.zero,- constraints: BoxConstraints(maxWidth: width),- canClose: () async {- final completer = Completer<bool>();- final state = askAIBloc.state;- if (state.result.isEmpty) {- completer.complete(true);- } else {- await showCancelAndConfirmDialog(- context: context,- title: LocaleKeys.document_plugins_discardResponse.tr(),- description: '',- confirmLabel: LocaleKeys.button_discard.tr(),- onConfirm: () => completer.complete(true),- onCancel: () => completer.complete(false),- );- }- return completer.future;- },- onClose: _removeNode,- popupBuilder: (BuildContext popoverContext) {- return BlocProvider.value(- // request the result when opening the popover- value: askAIBloc..add(const AskAIEvent.started()),- child: const AskAIInputContent(),- );- },- child: const SizedBox(- width: double.infinity,- ),- ),- ),- );- }-- double _getEditorWidth() {- var width = double.infinity;- try {- final editorSize = editorState.renderBox?.size;- final editorWidth =- editorSize?.width.clamp(0, editorState.editorStyle.maxWidth ?? width);- final padding = editorState.editorStyle.padding;- if (editorWidth != null) {- width = editorWidth - padding.left - padding.right;- }- } catch (_) {}- return width;- }-- void _removeNode() {- final transaction = editorState.transaction..deleteNode(widget.node);- editorState.apply(transaction);- }-- void _onListen(BuildContext context, AskAIState state) {- final error = state.requestError;- if (error != null) {- if (error.isLimitExceeded) {- showAILimitDialog(context, error.message);- } else {- showToastNotification(- context,- message: error.message,- type: ToastificationType.error,- );- }- }- }-}diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/ask_ai_toolbar_item.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/ask_ai_toolbar_item.dartdeleted file mode 100644index 9b413e1270..0000000000--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/ask_ai_toolbar_item.dart+++ /dev/null@@ -1,146 +0,0 @@-import 'package:appflowy/ai/service/appflowy_ai_service.dart';-import 'package:appflowy/generated/flowy_svgs.g.dart';-import 'package:appflowy/generated/locale_keys.g.dart';-import 'package:appflowy/plugins/document/application/document_bloc.dart';-import 'package:appflowy/plugins/document/presentation/editor_plugins/ai/util/ask_ai_node_extension.dart';-import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';-import 'package:appflowy/workspace/presentation/widgets/pop_up_action.dart';-import 'package:appflowy_editor/appflowy_editor.dart';-import 'package:easy_localization/easy_localization.dart';-import 'package:flowy_infra_ui/flowy_infra_ui.dart';-import 'package:flutter/material.dart';-import 'package:flutter_bloc/flutter_bloc.dart';--import 'ask_ai_block_component.dart';-import 'widgets/ask_ai_action.dart';--const _kAskAIToolbarItemId = 'appflowy.editor.ask_ai';--final ToolbarItem askAIItem = ToolbarItem(- id: _kAskAIToolbarItemId,- group: 0,- isActive: onlyShowInSingleSelectionAndTextType,- builder: (context, editorState, _, __, tooltipBuilder) => AskAIActionList(- editorState: editorState,- tooltipBuilder: tooltipBuilder,- ),-);--class AskAIActionList extends StatefulWidget {- const AskAIActionList({- super.key,- required this.editorState,- this.tooltipBuilder,- });-- final EditorState editorState;- final ToolbarTooltipBuilder? tooltipBuilder;-- @override- State<AskAIActionList> createState() => _AskAIActionListState();-}--class _AskAIActionListState extends State<AskAIActionList> {- late bool isAIEnabled;-- EditorState get editorState => widget.editorState;-- @override- void initState() {- super.initState();- _updateIsAIEnabled();- }-- @override- Widget build(BuildContext context) {- return PopoverActionList<AskAIActionWrapper>(- offset: const Offset(-5, 5),- direction: PopoverDirection.bottomWithLeftAligned,- actions: AskAIAction.values- .map((action) => AskAIActionWrapper(action))- .toList(),- onClosed: () => keepEditorFocusNotifier.decrease(),- buildChild: (controller) {- keepEditorFocusNotifier.increase();- final child = FlowyButton(- text: FlowyText.regular(- LocaleKeys.document_plugins_smartEdit.tr(),- fontSize: 13.0,- figmaLineHeight: 16.0,- color: Colors.white,- ),- hoverColor: Colors.transparent,- useIntrinsicWidth: true,- leftIcon: const FlowySvg(- FlowySvgs.toolbar_item_ai_s,- size: Size.square(16.0),- color: Colors.white,- ),- onTap: () {- if (isAIEnabled) {- keepEditorFocusNotifier.increase();- controller.show();- } else {- showToastNotification(- context,- message:- LocaleKeys.document_plugins_appflowyAIEditDisabled.tr(),- );- }- },- );-- if (widget.tooltipBuilder != null) {- return widget.tooltipBuilder!(- context,- _kAskAIToolbarItemId,- isAIEnabled- ? LocaleKeys.document_plugins_smartEdit.tr()- : LocaleKeys.document_plugins_appflowyAIEditDisabled.tr(),- child,- );- }-- return child;- },- onSelected: (action, controller) {- controller.close();- _insertAskAINode(action);- },- );- }-- Future<void> _insertAskAINode(- AskAIActionWrapper actionWrapper,- ) async {- final selection = editorState.selection?.normalized;- if (selection == null) {- return;- }-- final markdown = await editorState.getMarkdownInSelection(selection);-- final transaction = editorState.transaction;- transaction.insertNode(- selection.normalized.end.path.next,- askAINode(- action: actionWrapper.inner,- content: markdown,- ),- );- await editorState.apply(- transaction,- options: const ApplyOptions(- recordUndo: false,- inMemoryUpdate: true,- ),- withUpdateSelection: false,- );- }-- void _updateIsAIEnabled() {- final documentContext = widget.editorState.document.root.context;- isAIEnabled = documentContext == null ||- !documentContext.read<DocumentBloc>().isLocalMode;- }-}diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/operations/ai_writer_block_operations.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/operations/ai_writer_block_operations.dartnew file mode 100644index 0000000000..c82b39e241--- /dev/null+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/operations/ai_writer_block_operations.dart@@ -0,0 +1,209 @@+import 'package:appflowy/shared/markdown_to_document.dart';+import 'package:appflowy_editor/appflowy_editor.dart';++import '../ai_writer_block_component.dart';+import 'ai_writer_entities.dart';++Future<void> removeAiWriterNode(EditorState editorState, Node node) async {+ final transaction = editorState.transaction..deleteNode(node);+ await editorState.apply(+ transaction,+ options: const ApplyOptions(recordUndo: false),+ withUpdateSelection: false,+ );+}++void formatSelection(+ EditorState editorState,+ Selection selection,+ Transaction transaction,+ ApplySuggestionFormatType formatType,+) {+ final nodes = editorState.getNodesInSelection(selection).toList();+ if (nodes.isEmpty) {+ return;+ }++ if (nodes.length == 1) {+ final node = nodes.removeAt(0);+ if (node.delta != null) {+ final delta = Delta()+ ..retain(selection.start.offset)+ ..retain(+ selection.length,+ attributes: formatType.attributes,+ );+ transaction.addDeltaToComposeMap(node, delta);+ }+ } else {+ final firstNode = nodes.removeAt(0);+ final lastNode = nodes.removeLast();++ if (firstNode.delta != null) {+ final text = firstNode.delta!.toPlainText();+ final remainderLength = text.length - selection.start.offset;+ final delta = Delta()+ ..retain(selection.start.offset)+ ..retain(remainderLength, attributes: formatType.attributes);+ transaction.addDeltaToComposeMap(firstNode, delta);+ }++ if (lastNode.delta != null) {+ final delta = Delta()+ ..retain(selection.end.offset, attributes: formatType.attributes);+ transaction.addDeltaToComposeMap(lastNode, delta);+ }++ for (final node in nodes) {+ if (node.delta == null) {+ continue;+ }+ final length = node.delta!.length;+ if (length != 0) {+ final delta = Delta()+ ..retain(length, attributes: formatType.attributes);+ transaction.addDeltaToComposeMap(node, delta);+ }+ }+ }++ transaction.compose();+}++Position ensurePreviousNodeIsEmptyParagraph(+ EditorState editorState,+ Node aiWriterNode,+ Transaction transaction,+) {+ final previous = aiWriterNode.previous;+ final needsEmptyParagraphNode = previous == null ||+ previous.type != ParagraphBlockKeys.type ||+ (previous.delta?.toPlainText().isNotEmpty ?? false);++ final Position position;+ if (needsEmptyParagraphNode) {+ position = Position(path: aiWriterNode.path);+ transaction.insertNode(aiWriterNode.path, paragraphNode());+ } else {+ position = Position(path: previous.path);+ }++ transaction.updateNode(aiWriterNode, {+ AiWriterBlockKeys.isInitialized: true,+ });++ return position;+}++extension SaveAIResponseExtension on EditorState {+ Future<void> insertBelow({+ required Node node,+ required String markdownText,+ }) async {+ final selection = this.selection?.normalized;+ if (selection == null) {+ return;+ }++ final nodes = customMarkdownToDocument(+ markdownText,+ tableWidth: 250.0,+ ).root.children.map((e) => e.deepCopy()).toList();+ if (nodes.isEmpty) {+ return;+ }++ final insertedPath = selection.end.path.next;+ final lastDeltaLength = nodes.lastOrNull?.delta?.length ?? 0;++ final transaction = this.transaction+ ..insertNodes(insertedPath, nodes)+ ..afterSelection = Selection(+ start: Position(path: insertedPath),+ end: Position(+ path: insertedPath.nextNPath(nodes.length - 1),+ offset: lastDeltaLength,+ ),+ );++ await apply(transaction);+ }++ Future<void> replace({+ required Selection selection,+ required String text,+ }) async {+ final trimmedText = text.trim();+ if (trimmedText.isEmpty) {+ return;+ }+ await switch (kdefaultReplacementType) {+ AskAIReplacementType.markdown =>+ _replaceWithMarkdown(selection, trimmedText),+ AskAIReplacementType.plainText =>+ _replaceWithPlainText(selection, trimmedText),+ };+ }++ Future<void> _replaceWithMarkdown(+ Selection selection,+ String markdownText,+ ) async {+ final nodes = customMarkdownToDocument(markdownText)+ .root+ .children+ .map((e) => e.deepCopy())+ .toList();+ if (nodes.isEmpty) {+ return;+ }++ final nodesInSelection = getNodesInSelection(selection);+ final newSelection = Selection(+ start: selection.start,+ end: Position(+ path: selection.start.path.nextNPath(nodes.length - 1),+ offset: nodes.lastOrNull?.delta?.length ?? 0,+ ),+ );++ final transaction = this.transaction+ ..insertNodes(selection.start.path, nodes)+ ..deleteNodes(nodesInSelection)+ ..afterSelection = newSelection;+ await apply(transaction);+ }++ Future<void> _replaceWithPlainText(+ Selection selection,+ String plainText,+ ) async {+ final nodes = getNodesInSelection(selection);+ if (nodes.isEmpty || nodes.any((element) => element.delta == null)) {+ return;+ }++ final replaceTexts = plainText.split('\n')+ ..removeWhere((element) => element.isEmpty);+ final transaction = this.transaction+ ..replaceTexts(+ nodes,+ selection,+ replaceTexts,+ );+ await apply(transaction);++ int endOffset = replaceTexts.last.length;+ if (replaceTexts.length == 1) {+ endOffset += selection.start.offset;+ }+ final end = Position(+ path: [selection.start.path.first + replaceTexts.length - 1],+ offset: endOffset,+ );+ this.selection = Selection(+ start: selection.start,+ end: end,+ );+ }+}diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/operations/ai_writer_cubit.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/operations/ai_writer_cubit.dartnew file mode 100644index 0000000000..e1c6efb337--- /dev/null+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/operations/ai_writer_cubit.dart@@ -0,0 +1,527 @@+import 'dart:async';++import 'package:appflowy/ai/ai.dart';+import 'package:appflowy/generated/locale_keys.g.dart';+import 'package:appflowy_backend/dispatch/dispatch.dart';+import 'package:appflowy_backend/protobuf/flowy-ai/protobuf.dart';+import 'package:appflowy_editor/appflowy_editor.dart';+import 'package:bloc/bloc.dart';+import 'package:easy_localization/easy_localization.dart';+import 'package:flutter/foundation.dart';++import '../../base/markdown_text_robot.dart';+import 'ai_writer_block_operations.dart';+import 'ai_writer_entities.dart';+import 'ai_writer_node_extension.dart';++class AiWriterCubit extends Cubit<AiWriterState> {+ AiWriterCubit({+ required this.documentId,+ required this.editorState,+ required this.getAiWriterNode,+ required this.initialCommand,+ AppFlowyAIService? aiService,+ }) : _aiService = aiService ?? AppFlowyAIService(),+ _textRobot = MarkdownTextRobot(editorState: editorState),+ selectedSourcesNotifier = ValueNotifier([documentId]),+ super(+ ReadyAiWriterState(+ initialCommand,+ isFirstRun: true,+ ),+ );++ final String documentId;+ final EditorState editorState;+ final Node Function() getAiWriterNode;+ final AiWriterCommand initialCommand;+ final AppFlowyAIService _aiService;+ final MarkdownTextRobot _textRobot;++ final ValueNotifier<List<String>> selectedSourcesNotifier;+ (String, PredefinedFormat?)? _previousPrompt;++ @override+ Future<void> close() async {+ selectedSourcesNotifier.dispose();+ await super.close();+ }++ void init() {+ runCommand(initialCommand, null, isImmediateRun: true);+ }++ void submit(+ String prompt,+ PredefinedFormat? format,+ ) async {+ final command = AiWriterCommand.userQuestion;+ final node = getAiWriterNode();+ _previousPrompt = (prompt, format);++ final stream = await _aiService.streamCompletion(+ objectId: documentId,+ text: prompt,+ format: format,+ sourceIds: selectedSourcesNotifier.value,+ completionType: command.toCompletionType(),+ onStart: () async {+ final transaction = editorState.transaction;+ final position =+ ensurePreviousNodeIsEmptyParagraph(editorState, node, transaction);+ transaction.afterSelection = null;+ await editorState.apply(+ transaction,+ options: ApplyOptions(+ inMemoryUpdate: true,+ recordUndo: false,+ ),+ );+ _textRobot.start(position: position);+ },+ onProcess: (text) async {+ await _textRobot.appendMarkdownText(+ text,+ attributes: ApplySuggestionFormatType.replace.attributes,+ );+ },+ onEnd: () async {+ await _textRobot.stop(+ attributes: ApplySuggestionFormatType.replace.attributes,+ );+ emit(ReadyAiWriterState(command, isFirstRun: false));+ },+ onError: (error) async {+ emit(ErrorAiWriterState(state.command, error: error));+ },+ );++ if (stream != null) {+ emit(+ GeneratingAiWriterState(+ command,+ taskId: stream.$1,+ ),+ );+ }+ }++ void runCommand(+ AiWriterCommand command,+ PredefinedFormat? predefinedFormat, {+ bool isImmediateRun = false,+ bool isRetry = false,+ }) async {+ switch (command) {+ case AiWriterCommand.continueWriting:+ await _startContinueWriting(+ command,+ predefinedFormat,+ isImmediateRun: isImmediateRun,+ );+ break;+ case AiWriterCommand.fixSpellingAndGrammar:+ case AiWriterCommand.improveWriting:+ case AiWriterCommand.makeLonger:+ case AiWriterCommand.makeShorter:+ await _startSuggestingEdits(command, predefinedFormat);+ break;+ case AiWriterCommand.explain:+ await _startInforming(command, predefinedFormat);+ break;+ case AiWriterCommand.userQuestion:+ if (isRetry && _previousPrompt != null) {+ submit(_previousPrompt!.$1, _previousPrompt!.$2);+ }+ break;+ }+ }++ void stopStream() async {+ if (state is! GeneratingAiWriterState) {+ return;+ }+ final generatingState = state as GeneratingAiWriterState;+ await AIEventStopCompleteText(+ CompleteTextTaskPB(+ taskId: generatingState.taskId,+ ),+ ).send();+ emit(+ ReadyAiWriterState(+ state.command,+ isFirstRun: false,+ markdownText: generatingState.markdownText,+ ),+ );+ }++ void exit() async {+ await _textRobot.discard();+ final selection = getAiWriterNode().aiWriterSelection;+ if (selection == null) {+ return;+ }+ final transaction = editorState.transaction;+ formatSelection(+ editorState,+ selection,+ transaction,+ ApplySuggestionFormatType.clear,+ );+ await editorState.apply(+ transaction,+ options: const ApplyOptions(+ inMemoryUpdate: true,+ recordUndo: false,+ ),+ withUpdateSelection: false,+ );+ await removeAiWriterNode(editorState, getAiWriterNode());+ }++ void runResponseAction(SuggestionAction action) async {+ if (action case SuggestionAction.rewrite || SuggestionAction.tryAgain) {+ await _textRobot.discard();+ _textRobot.reset();+ runCommand(state.command, null, isRetry: true);+ return;+ }++ final selection = getAiWriterNode().aiWriterSelection;+ if (selection == null) {+ return;+ }++ if (action case SuggestionAction.discard || SuggestionAction.close) {+ await _textRobot.discard();++ final transaction = editorState.transaction;+ formatSelection(+ editorState,+ selection,+ transaction,+ ApplySuggestionFormatType.clear,+ );+ await editorState.apply(+ transaction,+ options: const ApplyOptions(recordUndo: false),+ );+ }++ if (action case SuggestionAction.accept || SuggestionAction.keep) {+ await _textRobot.persist();++ if (state.command.acceptWillReplace) {+ final nodes = editorState.getNodesInSelection(selection);+ final transaction = editorState.transaction..deleteNodes(nodes);+ await editorState.apply(+ transaction,+ options: const ApplyOptions(recordUndo: false),+ withUpdateSelection: false,+ );+ }+ }++ if (action case SuggestionAction.insertBelow) {+ if (state case final ReadyAiWriterState readyState+ when readyState.markdownText.isNotEmpty) {+ final transaction = editorState.transaction;+ final position = ensurePreviousNodeIsEmptyParagraph(+ editorState,+ getAiWriterNode(),+ transaction,+ );+ transaction.afterSelection = null;+ await editorState.apply(+ transaction,+ options: ApplyOptions(+ inMemoryUpdate: true,+ recordUndo: false,+ ),+ );+ _textRobot.start(position: position);+ await _textRobot.persist(markdownText: readyState.markdownText);+ } else {+ await _textRobot.persist();+ }++ final transaction = editorState.transaction;+ formatSelection(+ editorState,+ selection,+ transaction,+ ApplySuggestionFormatType.clear,+ );+ await editorState.apply(+ transaction,+ options: const ApplyOptions(recordUndo: false),+ withUpdateSelection: false,+ );+ }++ await removeAiWriterNode(editorState, getAiWriterNode());+ }++ bool hasUnusedResponse() {+ return switch (state) {+ ReadyAiWriterState(+ isFirstRun: final isInitial,+ markdownText: final markdownText,+ ) =>+ !isInitial && (markdownText.isNotEmpty || _textRobot.hasAnyResult),+ GeneratingAiWriterState() => true,+ _ => false,+ };+ }++ Future<void> _startContinueWriting(+ AiWriterCommand command,+ PredefinedFormat? predefinedFormat, {+ required bool isImmediateRun,+ }) async {+ final node = getAiWriterNode();++ final cursorPosition = getAiWriterNode().aiWriterSelection?.start;+ if (cursorPosition == null) {+ return;+ }+ final selection = Selection(+ start: Position(path: [0]),+ end: cursorPosition,+ ).normalized;++ final text = await editorState.getMarkdownInSelection(selection);+ if (text.isEmpty) {+ if (state is! ReadyAiWriterState) {+ return;+ }+ final readyState = state as ReadyAiWriterState;+ emit(+ SingleShotAiWriterState(+ command,+ title: LocaleKeys.ai_continueWritingEmptyDocumentTitle.tr(),+ description:+ LocaleKeys.ai_continueWritingEmptyDocumentDescription.tr(),+ onDismiss: () {+ if (isImmediateRun) {+ removeAiWriterNode(editorState, node);+ }+ },+ ),+ );+ emit(readyState);+ return;+ }++ final stream = await _aiService.streamCompletion(+ objectId: documentId,+ text: await editorState.getMarkdownInSelection(selection),+ completionType: command.toCompletionType(),+ onStart: () async {+ final transaction = editorState.transaction;+ final position =+ ensurePreviousNodeIsEmptyParagraph(editorState, node, transaction);+ transaction.afterSelection = null;+ await editorState.apply(+ transaction,+ options: ApplyOptions(+ inMemoryUpdate: true,+ recordUndo: false,+ ),+ );+ _textRobot.start(position: position);+ },+ onProcess: (text) async {+ await _textRobot.appendMarkdownText(+ text,+ attributes: ApplySuggestionFormatType.replace.attributes,+ );+ },+ onEnd: () async {+ editorState.service.keyboardService?.enable();+ if (state case GeneratingAiWriterState _) {+ await _textRobot.stop(+ attributes: ApplySuggestionFormatType.replace.attributes,+ );+ emit(ReadyAiWriterState(command, isFirstRun: false));+ }+ },+ onError: (error) async {+ editorState.service.keyboardService?.enable();+ emit(ErrorAiWriterState(command, error: error));+ },+ );+ if (stream != null) {+ emit(+ GeneratingAiWriterState(command, taskId: stream.$1),+ );+ }+ }++ Future<void> _startSuggestingEdits(+ AiWriterCommand command,+ PredefinedFormat? predefinedFormat,+ ) async {+ final node = getAiWriterNode();+ final selection = node.aiWriterSelection;+ if (selection == null) {+ return;+ }++ final stream = await _aiService.streamCompletion(+ objectId: documentId,+ text: await editorState.getMarkdownInSelection(selection),+ completionType: command.toCompletionType(),+ onStart: () async {+ final transaction = editorState.transaction;+ formatSelection(+ editorState,+ selection,+ transaction,+ ApplySuggestionFormatType.original,+ );+ final position =+ ensurePreviousNodeIsEmptyParagraph(editorState, node, transaction);+ transaction.afterSelection = null;+ await editorState.apply(+ transaction,+ options: ApplyOptions(+ inMemoryUpdate: true,+ recordUndo: false,+ ),+ );+ _textRobot.start(position: position);+ },+ onProcess: (text) async {+ await _textRobot.appendMarkdownText(+ text,+ attributes: ApplySuggestionFormatType.replace.attributes,+ );+ },+ onEnd: () async {+ if (state is GeneratingAiWriterState) {+ await _textRobot.stop(+ attributes: ApplySuggestionFormatType.replace.attributes,+ );+ emit(+ ReadyAiWriterState(+ command,+ isFirstRun: false,+ ),+ );+ }+ },+ onError: (error) async {+ editorState.service.keyboardService?.enable();+ emit(ErrorAiWriterState(command, error: error));+ },+ );+ if (stream != null) {+ emit(+ GeneratingAiWriterState(command, taskId: stream.$1),+ );+ }+ }++ Future<void> _startInforming(+ AiWriterCommand command,+ PredefinedFormat? predefinedFormat,+ ) async {+ final node = getAiWriterNode();+ final selection = node.aiWriterSelection;+ if (selection == null) {+ return;+ }++ final stream = await _aiService.streamCompletion(+ objectId: documentId,+ text: await editorState.getMarkdownInSelection(selection),+ completionType: command.toCompletionType(),+ onStart: () async {},+ onProcess: (text) async {+ if (state case final GeneratingAiWriterState generatingState) {+ emit(+ GeneratingAiWriterState(+ command,+ taskId: generatingState.taskId,+ markdownText: generatingState.markdownText + text,+ ),+ );+ }+ },+ onEnd: () async {+ editorState.service.keyboardService?.enable();+ if (state case final GeneratingAiWriterState generatingState) {+ emit(+ ReadyAiWriterState(+ command,+ isFirstRun: false,+ markdownText: generatingState.markdownText,+ ),+ );+ }+ },+ onError: (error) async {+ emit(ErrorAiWriterState(command, error: error));+ },+ );+ if (stream != null) {+ emit(+ GeneratingAiWriterState(command, taskId: stream.$1),+ );+ }+ }+}++sealed class AiWriterState {+ const AiWriterState(this.command);++ final AiWriterCommand command;+}++class ReadyAiWriterState extends AiWriterState {+ const ReadyAiWriterState(+ super.command, {+ required this.isFirstRun,+ this.markdownText = '',+ });++ final bool isFirstRun;+ final String markdownText;+}++class GeneratingAiWriterState extends AiWriterState {+ const GeneratingAiWriterState(+ super.command, {+ required this.taskId,+ this.progress = '',+ this.markdownText = '',+ });++ final String taskId;+ final String progress;+ final String markdownText;+}++class ErrorAiWriterState extends AiWriterState {+ const ErrorAiWriterState(+ super.command, {+ required this.error,+ });++ final AIError error;+}++class SingleShotAiWriterState extends AiWriterState {+ const SingleShotAiWriterState(+ super.command, {+ required this.title,+ required this.description,+ required this.onDismiss,+ });++ final String title;+ final String description;+ final void Function() onDismiss;+}diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/operations/ai_writer_entities.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/operations/ai_writer_entities.dartnew file mode 100644index 0000000000..349d7cb419--- /dev/null+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/operations/ai_writer_entities.dart@@ -0,0 +1,131 @@+import 'package:appflowy/generated/flowy_svgs.g.dart';+import 'package:appflowy/generated/locale_keys.g.dart';+import 'package:appflowy_backend/protobuf/flowy-ai/protobuf.dart';+import 'package:easy_localization/easy_localization.dart';+import 'package:flutter/material.dart';++import '../ai_writer_block_component.dart';++const kdefaultReplacementType = AskAIReplacementType.markdown;++enum AskAIReplacementType {+ markdown,+ plainText,+}++enum SuggestionAction {+ accept,+ discard,+ close,+ tryAgain,+ rewrite,+ keep,+ insertBelow;++ String get i18n => switch (this) {+ accept => LocaleKeys.suggestion_accept.tr(),+ discard => LocaleKeys.suggestion_discard.tr(),+ close => LocaleKeys.suggestion_close.tr(),+ tryAgain => LocaleKeys.suggestion_tryAgain.tr(),+ rewrite => LocaleKeys.suggestion_rewrite.tr(),+ keep => LocaleKeys.suggestion_keep.tr(),+ insertBelow => LocaleKeys.suggestion_insertBelow.tr(),+ };++ FlowySvg buildIcon(BuildContext context) {+ final icon = switch (this) {+ accept || keep => FlowySvgs.ai_fix_spelling_grammar_s,+ discard || close => FlowySvgs.toast_close_s,+ tryAgain || rewrite => FlowySvgs.ai_try_again_s,+ insertBelow => FlowySvgs.suggestion_insert_below_s,+ };++ return FlowySvg(+ icon,+ size: Size.square(16.0),+ color: switch (this) {+ accept || keep => Color(0xFF278E42),+ discard || close => Color(0xFFC40055),+ _ => Theme.of(context).iconTheme.color,+ },+ );+ }+}++enum AiWriterCommand {+ userQuestion,+ explain,+ // summarize,+ continueWriting,+ fixSpellingAndGrammar,+ improveWriting,+ makeShorter,+ makeLonger;++ String defaultPrompt(String input) => switch (this) {+ userQuestion => input,+ explain => "Explain this phrase in a concise manner:\n\n$input",+ // summarize => '$input\n\nTl;dr',+ continueWriting =>+ 'Continue writing based on this existing text:\n\n$input',+ fixSpellingAndGrammar => 'Correct this to standard English:\n\n$input',+ improveWriting => 'Rewrite this in your own words:\n\n$input',+ makeShorter => 'Make this text shorter:\n\n$input',+ makeLonger => 'Make this text longer:\n\n$input',+ };++ String get i18n => switch (this) {+ userQuestion => LocaleKeys.document_plugins_aiWriter_userQuestion.tr(),+ explain => LocaleKeys.document_plugins_aiWriter_explain.tr(),+ // summarize => LocaleKeys.document_plugins_aiWriter_summarize.tr(),+ continueWriting =>+ LocaleKeys.document_plugins_aiWriter_continueWriting.tr(),+ fixSpellingAndGrammar =>+ LocaleKeys.document_plugins_aiWriter_fixSpelling.tr(),+ improveWriting =>+ LocaleKeys.document_plugins_smartEditImproveWriting.tr(),+ makeShorter => LocaleKeys.document_plugins_aiWriter_makeShorter.tr(),+ makeLonger => LocaleKeys.document_plugins_aiWriter_makeLonger.tr(),+ };++ FlowySvgData get icon => switch (this) {+ userQuestion => FlowySvgs.ai_sparks_s,+ explain => FlowySvgs.ai_explain_s,+ // summarize => FlowySvgs.ai_summarize_s,+ continueWriting || improveWriting => FlowySvgs.ai_improve_writing_s,+ fixSpellingAndGrammar => FlowySvgs.ai_fix_spelling_grammar_s,+ makeShorter => FlowySvgs.ai_make_shorter_s,+ makeLonger => FlowySvgs.ai_make_longer_s,+ };++ CompletionTypePB toCompletionType() => switch (this) {+ userQuestion => CompletionTypePB.UserQuestion,+ explain => CompletionTypePB.ExplainSelected,+ // summarize => CompletionTypePB.Summarize,+ continueWriting => CompletionTypePB.ContinueWriting,+ fixSpellingAndGrammar => CompletionTypePB.SpellingAndGrammar,+ improveWriting => CompletionTypePB.ImproveWriting,+ makeShorter => CompletionTypePB.MakeShorter,+ makeLonger => CompletionTypePB.MakeLonger,+ };++ bool get acceptWillReplace => switch (this) {+ AiWriterCommand.fixSpellingAndGrammar ||+ AiWriterCommand.improveWriting ||+ AiWriterCommand.makeLonger ||+ AiWriterCommand.makeShorter =>+ true,+ _ => false,+ };+}++enum ApplySuggestionFormatType {+ original(AiWriterBlockKeys.suggestionOriginal),+ replace(AiWriterBlockKeys.suggestionReplacement),+ clear(null);++ const ApplySuggestionFormatType(this.value);+ final String? value;++ Map<String, dynamic> get attributes => {AiWriterBlockKeys.suggestion: value};+}diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/util/ask_ai_node_extension.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/operations/ai_writer_node_extension.dartsimilarity index 74%rename from frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/util/ask_ai_node_extension.dartrename to frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/operations/ai_writer_node_extension.dartindex 9ed5b046b9..1335f51df5 100644--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/util/ask_ai_node_extension.dart+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/operations/ai_writer_node_extension.dart@@ -1,7 +1,29 @@import 'package:appflowy/shared/markdown_to_document.dart';import 'package:appflowy_editor/appflowy_editor.dart';-extension AskAINodeExtension on EditorState {+import '../ai_writer_block_component.dart';+import 'ai_writer_entities.dart';++extension AiWriterExtension on Node {+ bool get isAiWriterInitialized {+ return attributes[AiWriterBlockKeys.isInitialized];+ }++ Selection? get aiWriterSelection {+ final selection = attributes[AiWriterBlockKeys.selection];+ if (selection == null) {+ return null;+ }+ return Selection.fromJson(selection);+ }++ AiWriterCommand get aiWriterCommand {+ final index = attributes[AiWriterBlockKeys.command];+ return AiWriterCommand.values[index];+ }+}++extension AiWriterNodeExtension on EditorState {Future<String> getMarkdownInSelection(Selection? selection) async {selection ??= this.selection?.normalized;if (selection == null || selection.isCollapsed) {diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/suggestion_action_bar.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/suggestion_action_bar.dartnew file mode 100644index 0000000000..a16fc44641--- /dev/null+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/suggestion_action_bar.dart@@ -0,0 +1,63 @@+import 'package:flowy_infra_ui/flowy_infra_ui.dart';+import 'package:flutter/material.dart';++import 'operations/ai_writer_entities.dart';++class SuggestionActionBar extends StatelessWidget {+ const SuggestionActionBar({+ super.key,+ required this.actions,+ required this.onTap,+ });++ final List<SuggestionAction> actions;+ final void Function(SuggestionAction) onTap;++ @override+ Widget build(BuildContext context) {+ return SeparatedRow(+ mainAxisSize: MainAxisSize.min,+ separatorBuilder: () => const HSpace(4.0),+ children: actions+ .map(+ (action) => SuggestionActionButton(+ action: action,+ onTap: () => onTap(action),+ ),+ )+ .toList(),+ );+ }+}++class SuggestionActionButton extends StatelessWidget {+ const SuggestionActionButton({+ super.key,+ required this.action,+ required this.onTap,+ });++ final SuggestionAction action;+ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) {+ return SizedBox(+ height: 28,+ child: FlowyButton(+ text: FlowyText(+ action.i18n,+ figmaLineHeight: 20,+ ),+ leftIcon: action.buildIcon(context),+ iconPadding: 4.0,+ margin: const EdgeInsets.symmetric(+ horizontal: 6.0,+ vertical: 4.0,+ ),+ onTap: onTap,+ useIntrinsicWidth: true,+ ),+ );+ }+}diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/util/learn_more_action.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/util/learn_more_action.dartdeleted file mode 100644index 17e89b1bca..0000000000--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/util/learn_more_action.dart+++ /dev/null@@ -1,8 +0,0 @@-import 'package:appflowy/core/helpers/url_launcher.dart';--const String learnMoreUrl =- 'https://docs.appflowy.io/docs/appflowy/product/appflowy-x-openai';--Future<void> openLearnMorePage() async {- await afLaunchUrlString(learnMoreUrl);-}diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ai_limit_dialog.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ai_limit_dialog.dartdeleted file mode 100644index 3a57a7f49c..0000000000--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ai_limit_dialog.dart+++ /dev/null@@ -1,13 +0,0 @@-import 'package:flutter/material.dart';--import 'package:appflowy/generated/locale_keys.g.dart';-import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';-import 'package:easy_localization/easy_localization.dart';--void showAILimitDialog(BuildContext context, String message) {- showConfirmDialog(- context: context,- title: LocaleKeys.sideBar_aiResponseLimitDialogTitle.tr(),- description: message,- );-}diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ai_writer_block_operations.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ai_writer_block_operations.dartdeleted file mode 100644index 0c2fabfb50..0000000000--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ai_writer_block_operations.dart+++ /dev/null@@ -1,112 +0,0 @@-import 'package:appflowy/plugins/document/presentation/editor_plugins/ai/ai_writer_block_component.dart';-import 'package:appflowy_editor/appflowy_editor.dart';--/// Notes: All the operation related to the AI writer block will be applied-/// in memory.-class AIWriterBlockOperations {- AIWriterBlockOperations({- required this.editorState,- required this.aiWriterNode,- }) : assert(aiWriterNode.type == AIWriterBlockKeys.type);-- final EditorState editorState;- final Node aiWriterNode;-- /// Update the prompt text in the node.- Future<void> updatePromptText(String prompt) async {- final transaction = editorState.transaction;- transaction.updateNode(- aiWriterNode,- {AIWriterBlockKeys.prompt: prompt},- );- await editorState.apply(- transaction,- options: const ApplyOptions(- inMemoryUpdate: true,- recordUndo: false,- ),- );- }-- /// Update the generation count in the node.- Future<void> updateGenerationCount(int count) async {- final transaction = editorState.transaction;- transaction.updateNode(- aiWriterNode,- {AIWriterBlockKeys.generationCount: count},- );- await editorState.apply(- transaction,- options: const ApplyOptions(inMemoryUpdate: true),- );- }-- /// Ensure the previous node is a empty paragraph node without any styles.- Future<void> ensurePreviousNodeIsEmptyParagraphNode() async {- final previous = aiWriterNode.previous;- final Selection selection;-- // 1. previous node is null or- // 2. previous node is not a paragraph node or- // 3. previous node is a paragraph node but not empty- final isNotEmptyParagraphNode = previous == null ||- previous.type != ParagraphBlockKeys.type ||- (previous.delta?.toPlainText().isNotEmpty ?? false);-- if (isNotEmptyParagraphNode) {- final path = aiWriterNode.path;- final transaction = editorState.transaction;- selection = Selection.collapsed(Position(path: path));- transaction- ..insertNode(- path,- paragraphNode(),- )- ..afterSelection = selection;- await editorState.apply(transaction);- } else {- selection = Selection.collapsed(Position(path: previous.path));- }-- final transaction = editorState.transaction;- transaction.updateNode(aiWriterNode, {- AIWriterBlockKeys.startSelection: selection.toJson(),- });- transaction.afterSelection = selection;- await editorState.apply(- transaction,- options: const ApplyOptions(inMemoryUpdate: true),- );- }-- /// Discard the current response and delete the previous node.- Future<void> discardCurrentResponse({- required Node aiWriterNode,- Selection? selection,- }) async {- if (selection != null) {- final start = selection.start.path;- final end = aiWriterNode.previous?.path;- if (end != null) {- final transaction = editorState.transaction;- transaction.deleteNodesAtPath(- start,- end.last - start.last + 1,- );- await editorState.apply(transaction);- await ensurePreviousNodeIsEmptyParagraphNode();- }- }- }-- /// Remove the ai writer node from the editor.- Future<void> removeAIWriterNode(Node aiWriterNode) async {- final transaction = editorState.transaction;- transaction.deleteNode(aiWriterNode);- await editorState.apply(- transaction,- options: const ApplyOptions(inMemoryUpdate: true, recordUndo: false),- withUpdateSelection: false,- );- }-}diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ai_writer_block_widgets.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ai_writer_block_widgets.dartdeleted file mode 100644index b6681ed7fd..0000000000--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ai_writer_block_widgets.dart+++ /dev/null@@ -1,104 +0,0 @@-import 'package:appflowy/generated/locale_keys.g.dart';-import 'package:easy_localization/easy_localization.dart';-import 'package:flowy_infra_ui/flowy_infra_ui.dart';-import 'package:flutter/material.dart';--class AIWriterBlockHeader extends StatelessWidget {- const AIWriterBlockHeader({super.key});-- @override- Widget build(BuildContext context) {- return FlowyText.medium(- LocaleKeys.document_plugins_autoGeneratorTitleName.tr(),- fontSize: 14,- );- }-}--class AIWriterBlockInputField extends StatelessWidget {- const AIWriterBlockInputField({- super.key,- required this.onGenerate,- required this.onExit,- });-- final VoidCallback onGenerate;- final VoidCallback onExit;-- @override- Widget build(BuildContext context) {- return Row(- mainAxisSize: MainAxisSize.min,- children: [- PrimaryRoundedButton(- text: LocaleKeys.button_generate.tr(),- margin: const EdgeInsets.symmetric(- horizontal: 16.0,- vertical: 10.0,- ),- radius: 8.0,- onTap: onGenerate,- ),- const Space(10, 0),- OutlinedRoundedButton(- text: LocaleKeys.button_cancel.tr(),- margin: const EdgeInsets.symmetric(- horizontal: 16.0,- vertical: 10.0,- ),- onTap: onExit,- ),- Flexible(- child: Container(- alignment: Alignment.centerRight,- child: FlowyText.regular(- LocaleKeys.document_plugins_warning.tr(),- color: Theme.of(context).hintColor,- overflow: TextOverflow.ellipsis,- fontSize: 12,- ),- ),- ),- ],- );- }-}--class AIWriterBlockFooter extends StatelessWidget {- const AIWriterBlockFooter({- super.key,- required this.onKeep,- required this.onRewrite,- required this.onDiscard,- });-- final VoidCallback onKeep;- final VoidCallback onRewrite;- final VoidCallback onDiscard;-- @override- Widget build(BuildContext context) {- return Row(- children: [- PrimaryRoundedButton(- text: LocaleKeys.button_keep.tr(),- margin: const EdgeInsets.symmetric(- horizontal: 16.0,- vertical: 9.0,- ),- onTap: onKeep,- ),- const HSpace(10),- OutlinedRoundedButton(- text: LocaleKeys.document_plugins_autoGeneratorRewrite.tr(),- onTap: onRewrite,- ),- const HSpace(10),- OutlinedRoundedButton(- text: LocaleKeys.button_discard.tr(),- onTap: onDiscard,- ),- ],- );- }-}diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ask_ai_action.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ask_ai_action.dartdeleted file mode 100644index dfcec0318e..0000000000--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ask_ai_action.dart+++ /dev/null@@ -1,14 +0,0 @@-import 'package:appflowy/ai/service/appflowy_ai_service.dart';-import 'package:appflowy/workspace/presentation/widgets/pop_up_action.dart';-import 'package:flutter/material.dart';--class AskAIActionWrapper extends ActionCell {- AskAIActionWrapper(this.inner);-- final AskAIAction inner;-- Widget? icon(Color iconColor) => null;-- @override- String get name => inner.name;-}diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ask_ai_action_bloc.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ask_ai_action_bloc.dartdeleted file mode 100644index 1fcd8d65ed..0000000000--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ask_ai_action_bloc.dart+++ /dev/null@@ -1,299 +0,0 @@-import 'dart:async';--import 'package:appflowy/ai/service/ai_client.dart';-import 'package:appflowy/ai/service/error.dart';-import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';-import 'package:appflowy/shared/markdown_to_document.dart';-import 'package:appflowy/ai/service/appflowy_ai_service.dart';-import 'package:appflowy_backend/log.dart';-import 'package:appflowy_editor/appflowy_editor.dart';-import 'package:flutter_bloc/flutter_bloc.dart';-import 'package:freezed_annotation/freezed_annotation.dart';--part 'ask_ai_action_bloc.freezed.dart';--enum AskAIReplacementType {- markdown,- plainText,-}--const _defaultReplacementType = AskAIReplacementType.markdown;--class AskAIActionBloc extends Bloc<AskAIEvent, AskAIState> {- AskAIActionBloc({- required this.node,- required this.editorState,- required this.action,- required this.objectId,- this.enableLogging = true,- }) : super(- AskAIState.initial(action),- ) {- on<AskAIEvent>((event, emit) async {- await event.when(- initial: (aiRepositoryProvider) async {- aiRepository = await aiRepositoryProvider;- aiRepositoryCompleter.complete();- },- started: () async {- await _requestCompletions();- },- rewrite: () async {- await _requestCompletions(rewrite: true);- },- replace: () async {- await _replace();- await _exit();- },- insertBelow: () async {- await _insertBelow();- await _exit();- },- cancel: () async {- isCanceled = true;- await _exit();- },- update: (result, isLoading, aiError) {- emit(- state.copyWith(- result: result,- loading: isLoading,- requestError: aiError,- ),- );- },- );- });- }-- final Node node;- final EditorState editorState;- final AskAIAction action;- final bool enableLogging;- // used to wait for the aiRepository to be initialized- final aiRepositoryCompleter = Completer();- late final AIRepository aiRepository;- final String objectId;-- bool isCanceled = false;-- Future<void> _requestCompletions({- bool rewrite = false,- }) async {- await aiRepositoryCompleter.future;-- if (rewrite) {- add(const AskAIEvent.update('', true, null));- }-- if (enableLogging) {- Log.info('[smart_edit] request completions');- }-- final content = node.attributes[AskAIBlockKeys.content] as String;- await aiRepository.streamCompletion(- objectId: objectId,- text: content,- completionType: completionTypeFromInt(state.action),- onStart: () async {- if (isCanceled) {- return;- }- if (enableLogging) {- Log.info('[smart_edit] start generating');- }- add(const AskAIEvent.update('', true, null));- },- onProcess: (text) async {- if (isCanceled) {- return;- }- // only display the log in debug mode- if (enableLogging) {- Log.debug('[smart_edit] onProcess: $text');- }- final newResult = state.result + text;- add(AskAIEvent.update(newResult, false, null));- },- onEnd: () async {- if (isCanceled) {- return;- }- if (enableLogging) {- Log.info('[smart_edit] end generating');- }- add(AskAIEvent.update('${state.result}\n', false, null));- },- onError: (error) async {- if (isCanceled) {- return;- }- if (enableLogging) {- Log.info('[smart_edit] onError: $error');- }- add(AskAIEvent.update('', false, error));- await _exit();- await _clearSelection();- },- );- }-- Future<void> _insertBelow() async {- // check the selection is not empty- final selection = editorState.selection?.normalized;- if (selection == null) {- return;- }- final nodes = customMarkdownToDocument(state.result)- .root- .children- .map((e) => e.deepCopy())- .toList();- final insertedPath = selection.end.path.next;- final transaction = editorState.transaction;- transaction.insertNodes(- insertedPath,- nodes,- );- final lastDeltaLength = nodes.lastOrNull?.delta?.length ?? 0;- transaction.afterSelection = Selection(- start: Position(path: insertedPath),- end: Position(- path: insertedPath.nextNPath(nodes.length - 1),- offset: lastDeltaLength,- ),- );- await editorState.apply(transaction);- }-- Future<void> _replace() async {- switch (_defaultReplacementType) {- case AskAIReplacementType.markdown:- await _replaceWithMarkdown();- case AskAIReplacementType.plainText:- await _replaceWithPlainText();- }- }-- Future<void> _replaceWithMarkdown() async {- final selection = editorState.selection?.normalized;- if (selection == null) {- return;- }-- final nodes = customMarkdownToDocument(state.result)- .root- .children- .map((e) => e.deepCopy())- .toList();- if (nodes.isEmpty) {- return;- }-- final nodesInSelection = editorState.getNodesInSelection(selection);- final transaction = editorState.transaction;- transaction.insertNodes(- selection.start.path,- nodes,- );- transaction.deleteNodes(nodesInSelection);- transaction.afterSelection = Selection(- start: selection.start,- end: Position(- path: selection.start.path.nextNPath(nodes.length - 1),- offset: nodes.lastOrNull?.delta?.length ?? 0,- ),- );- await editorState.apply(transaction);- }-- Future<void> _replaceWithPlainText() async {- final result = state.result.trim();- if (result.isEmpty) {- return;- }-- final selection = editorState.selection?.normalized;- if (selection == null) {- return;- }- final nodes = editorState.getNodesInSelection(selection);- if (nodes.isEmpty || !nodes.every((element) => element.delta != null)) {- return;- }-- final replaceTexts = result.split('\n')- ..removeWhere((element) => element.isEmpty);- final transaction = editorState.transaction;- transaction.replaceTexts(- nodes,- selection,- replaceTexts,- );- await editorState.apply(transaction);-- int endOffset = replaceTexts.last.length;- if (replaceTexts.length == 1) {- endOffset += selection.start.offset;- }- final end = Position(- path: [selection.start.path.first + replaceTexts.length - 1],- offset: endOffset,- );- editorState.selection = Selection(- start: selection.start,- end: end,- );- }-- Future<void> _exit() async {- final transaction = editorState.transaction..deleteNode(node);- await editorState.apply(- transaction,- options: const ApplyOptions(- recordUndo: false,- ),- );- }-- Future<void> _clearSelection() async {- final selection = editorState.selection;- if (selection == null) {- return;- }- editorState.selection = null;- }-}--@freezed-class AskAIEvent with _$AskAIEvent {- const factory AskAIEvent.initial(- Future<AIRepository> aiRepositoryProvider,- ) = _Initial;- const factory AskAIEvent.started() = _Started;- const factory AskAIEvent.rewrite() = _Rewrite;- const factory AskAIEvent.replace() = _Replace;- const factory AskAIEvent.insertBelow() = _InsertBelow;- const factory AskAIEvent.cancel() = _Cancel;- const factory AskAIEvent.update(- String result,- bool isLoading,- AIError? error,- ) = _Update;-}--@freezed-class AskAIState with _$AskAIState {- const factory AskAIState({- required bool loading,- required String result,- required AskAIAction action,- @Default(null) AIError? requestError,- }) = _AskAIState;-- factory AskAIState.initial(AskAIAction action) => AskAIState(- loading: true,- action: action,- result: '',- );-}diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ask_ai_block_widgets.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ask_ai_block_widgets.dartdeleted file mode 100644index d28f416d1b..0000000000--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ask_ai_block_widgets.dart+++ /dev/null@@ -1,112 +0,0 @@-import 'package:appflowy/generated/locale_keys.g.dart';-import 'package:appflowy/plugins/ai_chat/presentation/message/ai_markdown_text.dart';-import 'package:appflowy/plugins/document/presentation/editor_plugins/ai/widgets/ask_ai_action_bloc.dart';-import 'package:easy_localization/easy_localization.dart';-import 'package:flowy_infra_ui/flowy_infra_ui.dart';-import 'package:flutter/material.dart';-import 'package:flutter_bloc/flutter_bloc.dart';--class AskAIInputContent extends StatelessWidget {- const AskAIInputContent({super.key});-- @override- Widget build(BuildContext context) {- return BlocBuilder<AskAIActionBloc, AskAIState>(- builder: (context, state) {- return Card(- elevation: 5,- color: Theme.of(context).colorScheme.surface,- margin: EdgeInsets.zero,- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(10),- ),- child: Container(- margin: const EdgeInsets.all(16),- child: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.start,- children: [- FlowyText.medium(- state.action.name,- fontSize: 14,- ),- const VSpace(16),- state.loading- ? _buildLoadingWidget(context)- : _buildResultWidget(context, state),- const VSpace(16),- const AskAIFooter(),- ],- ),- ),- );- },- );- }-- Widget _buildResultWidget(BuildContext context, AskAIState state) {- return Flexible(- child: AIMarkdownText(- markdown: state.result,- ),- );- }-- Widget _buildLoadingWidget(BuildContext context) {- return const Padding(- padding: EdgeInsets.symmetric(horizontal: 4.0),- child: SizedBox.square(- dimension: 14,- child: CircularProgressIndicator(- strokeWidth: 2.0,- ),- ),- );- }-}--class AskAIFooter extends StatelessWidget {- const AskAIFooter({super.key});-- @override- Widget build(BuildContext context) {- return Row(- children: [- OutlinedRoundedButton(- text: LocaleKeys.document_plugins_autoGeneratorRewrite.tr(),- onTap: () =>- context.read<AskAIActionBloc>().add(const AskAIEvent.rewrite()),- ),- const HSpace(10),- OutlinedRoundedButton(- text: LocaleKeys.button_replace.tr(),- onTap: () =>- context.read<AskAIActionBloc>().add(const AskAIEvent.replace()),- ),- const HSpace(10),- OutlinedRoundedButton(- text: LocaleKeys.button_insertBelow.tr(),- onTap: () => context- .read<AskAIActionBloc>()- .add(const AskAIEvent.insertBelow()),- ),- const HSpace(10),- OutlinedRoundedButton(- text: LocaleKeys.button_cancel.tr(),- onTap: () =>- context.read<AskAIActionBloc>().add(const AskAIEvent.cancel()),- ),- Expanded(- child: Container(- alignment: Alignment.centerRight,- child: Text(- LocaleKeys.document_plugins_warning.tr(),- style: TextStyle(color: Theme.of(context).hintColor),- overflow: TextOverflow.ellipsis,- ),- ),- ),- ],- );- }-}diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/barrier_dialog.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/barrier_dialog.dartdeleted file mode 100644index 69f453dcfc..0000000000--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/barrier_dialog.dart+++ /dev/null@@ -1,20 +0,0 @@-import 'package:flutter/material.dart';--class BarrierDialog {- BarrierDialog(this.context);-- late BuildContext loadingContext;- final BuildContext context;-- void show() => showDialog<void>(- context: context,- barrierDismissible: false,- barrierColor: Colors.transparent,- builder: (context) {- loadingContext = context;- return const SizedBox.shrink();- },- );-- void dismiss() => Navigator.of(loadingContext).pop();-}diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/discard_dialog.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/discard_dialog.dartdeleted file mode 100644index 4c0c2bc91a..0000000000--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/discard_dialog.dart+++ /dev/null@@ -1,28 +0,0 @@-import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';--import 'package:flutter/material.dart';-import 'package:appflowy/generated/locale_keys.g.dart';--import 'package:easy_localization/easy_localization.dart';--class DiscardDialog extends StatelessWidget {- const DiscardDialog({- super.key,- required this.onConfirm,- required this.onCancel,- });-- final VoidCallback onConfirm;- final VoidCallback onCancel;-- @override- Widget build(BuildContext context) {- return NavigatorOkCancelDialog(- message: LocaleKeys.document_plugins_discardResponse.tr(),- okTitle: LocaleKeys.button_discard.tr(),- cancelTitle: LocaleKeys.button_cancel.tr(),- onOkPressed: onConfirm,- onCancelPressed: onCancel,- );- }-}diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/base/markdown_text_robot.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/base/markdown_text_robot.dartindex 0cc9a50e5c..ac170fef00 100644--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/base/markdown_text_robot.dart+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/base/markdown_text_robot.dart@@ -3,127 +3,205 @@ import 'dart:convert';import 'package:appflowy/shared/markdown_to_document.dart';import 'package:appflowy_backend/log.dart';import 'package:appflowy_editor/appflowy_editor.dart';-import 'package:flutter/foundation.dart';import 'package:synchronized/synchronized.dart';+const _enableDebug = false;+class MarkdownTextRobot {MarkdownTextRobot({required this.editorState,- this.enableDebug = true,});final EditorState editorState;- final bool enableDebug;- final Lock lock = Lock();+ final Lock _lock = Lock();- // The selection before the text robot is ready.- Selection? _startSelection;+ /// The text position where new nodes will be inserted+ Position? _insertPosition;- // The markdown text to be inserted.+ /// The markdown text to be insertedString _markdownText = '';- // Only for debug. Enable by [enableDebug].- @visibleForTesting- final List<String> debugMarkdownTexts = [];+ /// The nodes inserted in the previous refresh.+ Iterable<Node> _insertedNodes = [];++ /// Only for debug via [_enableDebug].+ final List<String> _debugMarkdownTexts = [];++ bool get hasAnyResult => _markdownText.isNotEmpty;++ Selection? getInsertedSelection() {+ final position = _insertPosition;+ if (position == null) {+ Log.error("Expected non-null insert markdown text position");+ return null;+ }++ if (_insertedNodes.isEmpty) {+ return Selection.collapsed(position);+ }+ return Selection(+ start: position,+ end: Position(+ path: position.path.nextNPath(_insertedNodes.length - 1),+ ),+ );+ }- // The nodes inserted in the previous refresh.- Iterable<Node> _previousInsertedNodes = [];+ List<Node> getInsertedNodes() {+ final selection = getInsertedSelection();+ return selection == null ? [] : editorState.getNodesInSelection(selection);+ }- /// Start the text robot.- ///- /// Must call this function before using the text robot.- void start() {- _startSelection = editorState.selection;+ void start({+ Position? position,+ }) {+ _insertPosition ??= position ?? editorState.selection?.start;- if (enableDebug) {+ if (_enableDebug) {Log.info(- 'MarkdownTextRobot prepare, current selection: $_startSelection',+ 'MarkdownTextRobot start with insert text position: $_insertPosition',);}}- /// Append the markdown text to the text robot.- ///- /// The text will be inserted into document but not persisted until the text- /// robot is stopped.- Future<void> appendMarkdownText(String text) async {+ /// The text will be inserted into the document but only in memory+ Future<void> appendMarkdownText(+ String text, {+ Map<String, dynamic>? attributes,+ }) async {_markdownText += text;- await lock.synchronized(() async {- await _refresh();+ await _lock.synchronized(() async {+ await _refresh(+ inMemoryUpdate: true,+ attributes: attributes,+ );});- if (enableDebug) {- debugMarkdownTexts.add(text);- Log.info('debug markdown texts: ${jsonEncode(debugMarkdownTexts)}');+ if (_enableDebug) {+ _debugMarkdownTexts.add(text);+ Log.info(+ 'MarkdownTextRobot receive markdown: ${jsonEncode(_debugMarkdownTexts)}',+ );}}- /// Stop the text robot.- ///- /// The text will be persisted into document.- Future<void> stop() async {- // persist the markdown text- await lock.synchronized(() async {- await _refresh(inMemoryUpdate: false);+ Future<void> stop({+ Map<String, dynamic>? attributes,+ }) async {+ await _lock.synchronized(() async {+ await _refresh(+ inMemoryUpdate: true,+ updateSelection: false,+ attributes: attributes,+ );});+ }- _markdownText = '';+ /// Persist the text into the document+ Future<void> persist({String? markdownText}) async {+ if (markdownText != null) {+ _markdownText = markdownText;+ }+ await _lock.synchronized(() async {+ await _refresh(inMemoryUpdate: false);+ });- if (enableDebug) {- Log.info(- 'debug markdown texts: ${jsonEncode(debugMarkdownTexts)}',- );- debugMarkdownTexts.clear();+ if (_enableDebug) {+ Log.info('MarkdownTextRobot stop');+ _debugMarkdownTexts.clear();}}- /// Refreshes the editor state with the current markdown text by:- ///- /// 1. Converting markdown to document nodes- /// 2. Replacing previously inserted nodes with new nodes- /// 3. Updating selection position- Future<void> _refresh({bool inMemoryUpdate = true}) async {- final start = _startSelection?.start;+ /// Discard the inserted content+ Future<void> discard() async {+ final start = _insertPosition;if (start == null) {return;}+ if (_insertedNodes.isEmpty) {+ return;+ }++ // fallback to the calculated position if the selection is null.+ final end = Position(+ path: start.path.nextNPath(_insertedNodes.length - 1),+ );+ final deletedNodes = editorState.getNodesInSelection(+ Selection(start: start, end: end),+ );+ final transaction = editorState.transaction+ ..deleteNodes(deletedNodes)+ ..afterSelection = Selection.collapsed(start);++ await editorState.apply(+ transaction,+ options: const ApplyOptions(recordUndo: false),+ );++ if (_enableDebug) {+ Log.info('MarkdownTextRobot discard');+ }+ }++ void reset() {+ _markdownText = '';+ _insertedNodes = [];+ _insertPosition = null;+ }++ Future<void> _refresh({+ required bool inMemoryUpdate,+ bool updateSelection = true,+ Map<String, dynamic>? attributes,+ }) async {+ final position = _insertPosition;+ if (position == null) {+ Log.error("Expected non-null insert markdown text position");+ return;+ }- final transaction = editorState.transaction;+ final node = editorState.getNodeAtPath(position.path);+ if (node == null) {+ Log.error("Cannot find node at position: ${position.path}");+ return;+ }- // Convert markdown and deep copy nodes- final nodes = customMarkdownToDocument(_markdownText).root.children.map(- (node) => node.deepCopy(),- ); // deep copy the nodes to avoid the linked entities being changed.+ // Convert markdown and deep copy the nodes, prevent ing the linked+ // entities from being changed+ final documentNodes = customMarkdownToDocument(+ _markdownText,+ tableWidth: 250.0,+ ).root.children;- // Insert new nodes at selection start- transaction.insertNodes(start.path, nodes);+ final newNodes = attributes == null+ ? documentNodes+ : documentNodes+ .map((node) => _styleDelta(node: node, attributes: attributes))+ .toList();- // Remove previously inserted nodes if they exist- if (_previousInsertedNodes.isNotEmpty) {- // fallback to the calculated position if the selection is null.- final end = editorState.selection?.end ??- Position(- path: start.path.nextNPath(_previousInsertedNodes.length - 1),- );- final deletedNodes = editorState.getNodesInSelection(- Selection(start: start, end: end),- );- transaction.deleteNodes(deletedNodes);+ if (newNodes.isEmpty) {+ return;}+ final transaction = editorState.transaction+ ..insertNodes(position.path, newNodes)+ ..deleteNodes(getInsertedNodes());- // Update selection to end of inserted content if it contains text- final lastDelta = nodes.lastOrNull?.delta;+ final lastDelta = newNodes.lastOrNull?.delta;if (lastDelta != null) {transaction.afterSelection = Selection.collapsed(Position(- path: start.path.nextNPath(nodes.length - 1),+ path: position.path.nextNPath(newNodes.length - 1),offset: lastDelta.length,),);}+ if (!updateSelection) {+ transaction.afterSelection = null;+ }+await editorState.apply(transaction,options: ApplyOptions(@@ -132,6 +210,32 @@ class MarkdownTextRobot {),);- _previousInsertedNodes = nodes;+ _insertedNodes = newNodes;+ }++ Node _styleDelta({+ required Node node,+ required Map<String, dynamic> attributes,+ }) {+ if (node.delta != null) {+ final delta = node.delta!;+ final attributeDelta = Delta()+ ..retain(delta.length, attributes: attributes);+ final newDelta = delta.compose(attributeDelta);+ final newAttributes = node.attributes;+ newAttributes['delta'] = newDelta.toJson();+ node.updateAttributes(newAttributes);+ }++ List<Node>? children;+ if (node.children.isNotEmpty) {+ children = node.children+ .map((child) => _styleDelta(node: node, attributes: attributes))+ .toList();+ }++ return node.copyWith(+ children: children,+ );}}diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/plugins.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/plugins.dartindex c37a85260e..8a475fd5a0 100644--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/plugins.dart+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/plugins.dart@@ -1,8 +1,7 @@export 'actions/block_action_list.dart';export 'actions/option/option_actions.dart';export 'ai/ai_writer_block_component.dart';-export 'ai/ask_ai_block_component.dart';-export 'ai/ask_ai_toolbar_item.dart';+export 'ai/ai_writer_toolbar_item.dart';export 'align_toolbar_item/align_toolbar_item.dart';export 'base/backtick_character_command.dart';export 'base/cover_title_command.dart';diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/slash_menu/slash_menu_items/ai_writer_item.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/slash_menu/slash_menu_items/ai_writer_item.dartindex 4e3f455522..46d1b4eabb 100644--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/slash_menu/slash_menu_items/ai_writer_item.dart+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/slash_menu/slash_menu_items/ai_writer_item.dart@@ -1,5 +1,5 @@-import 'package:appflowy/generated/flowy_svgs.g.dart';import 'package:appflowy/generated/locale_keys.g.dart';+import 'package:appflowy/plugins/document/presentation/editor_plugins/ai/operations/ai_writer_entities.dart';import 'package:appflowy/plugins/document/presentation/editor_plugins/base/selectable_svg_widget.dart';import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';import 'package:appflowy_editor/appflowy_editor.dart';@@ -15,41 +15,67 @@ final _keywords = ['autogenerator',];-// auto generate menu itemSelectionMenuItem aiWriterSlashMenuItem = SelectionMenuItem(getName: LocaleKeys.document_slashMenu_name_aiWriter.tr,- keywords: _keywords,- handler: (editorState, _, __) async => editorState.insertAiWriter(),+ keywords: [+ ..._keywords,+ LocaleKeys.document_slashMenu_name_aiWriter.tr(),+ ],+ handler: (editorState, _, __) async =>+ _insertAiWriter(editorState, AiWriterCommand.userQuestion),icon: (_, isSelected, style) => SelectableSvgWidget(- data: FlowySvgs.slash_menu_icon_ai_writer_s,+ data: AiWriterCommand.userQuestion.icon,isSelected: isSelected,style: style,),nameBuilder: slashMenuItemNameBuilder,);-extension on EditorState {- Future<void> insertAiWriter() async {- final selection = this.selection;- if (selection == null || !selection.isCollapsed) {- return;- }- final node = getNodeAtPath(selection.end.path);- final delta = node?.delta;- if (node == null || delta == null) {- return;- }- final newNode = aiWriterNode(start: selection);-- final transaction = this.transaction;- //default insert after- final path = node.path.next;- transaction- ..insertNode(path, newNode)- ..afterSelection = null;- await apply(- transaction,- options: const ApplyOptions(inMemoryUpdate: true),- );+SelectionMenuItem continueWritingSlashMenuItem = SelectionMenuItem(+ getName: LocaleKeys.document_plugins_aiWriter_continueWriting.tr,+ keywords: [+ ..._keywords,+ LocaleKeys.document_plugins_aiWriter_continueWriting.tr(),+ ],+ handler: (editorState, _, __) async =>+ _insertAiWriter(editorState, AiWriterCommand.continueWriting),+ icon: (_, isSelected, style) => SelectableSvgWidget(+ data: AiWriterCommand.continueWriting.icon,+ isSelected: isSelected,+ style: style,+ ),+ nameBuilder: slashMenuItemNameBuilder,+);++Future<void> _insertAiWriter(+ EditorState editorState,+ AiWriterCommand action,+) async {+ final selection = editorState.selection;+ if (selection == null || !selection.isCollapsed) {+ return;+ }++ final node = editorState.getNodeAtPath(selection.end.path);+ if (node == null || node.delta == null) {+ return;}+ final newNode = aiWriterNode(+ selection: selection,+ command: action,+ );++ // default insert after+ final path = node.path.next;+ final transaction = editorState.transaction+ ..insertNode(path, newNode)+ ..afterSelection = null;++ await editorState.apply(+ transaction,+ options: const ApplyOptions(+ recordUndo: false,+ inMemoryUpdate: true,+ ),+ );}diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/slash_menu/slash_menu_items_builder.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/slash_menu/slash_menu_items_builder.dartindex eb4ce5946b..e953694966 100644--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/slash_menu/slash_menu_items_builder.dart+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/slash_menu/slash_menu_items_builder.dart@@ -50,8 +50,11 @@ List<SelectionMenuItem> _defaultSlashMenuItems({DocumentBloc? documentBloc,}) {return [- // disable ai writer in local mode- if (!isLocalMode) aiWriterSlashMenuItem,+ // ai+ if (!isLocalMode) ...[+ continueWritingSlashMenuItem,+ aiWriterSlashMenuItem,+ ],paragraphSlashMenuItem,diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_style.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_style.dartindex 1f32c94cf4..10a5e117af 100644--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_style.dart+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_style.dart@@ -10,6 +10,7 @@ import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.daimport 'package:appflowy/plugins/inline_actions/inline_actions_menu.dart';import 'package:appflowy/shared/google_fonts_extension.dart';import 'package:appflowy/util/font_family_extension.dart';+import 'package:appflowy/util/theme_extension.dart';import 'package:appflowy/workspace/application/appearance_defaults.dart';import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart';import 'package:appflowy/workspace/application/settings/appearance/base_appearance.dart';@@ -336,6 +337,11 @@ class EditorStyleCustomizer {return before;}+ final suggestion = attributes[AiWriterBlockKeys.suggestion] as String?;+ final newStyle = suggestion == null+ ? after.style+ : _styleSuggestion(after.style, suggestion);+if (attributes.backgroundColor != null) {final color = EditorFontColors.fromBuiltInColors(context,@@ -344,7 +350,7 @@ class EditorStyleCustomizer {if (color != null) {return TextSpan(text: before.text,- style: after.style?.merge(+ style: newStyle?.merge(TextStyle(backgroundColor: color),),);@@ -359,7 +365,7 @@ class EditorStyleCustomizer {} else {return TextSpan(text: before.text,- style: after.style?.merge(+ style: newStyle?.merge(getGoogleFontSafely(attributes.fontFamily!),),);@@ -376,7 +382,7 @@ class EditorStyleCustomizer {final type = mention[MentionBlockKeys.type];return WidgetSpan(alignment: PlaceholderAlignment.middle,- style: after.style,+ style: newStyle,child: MentionBlock(key: ValueKey(switch (type) {@@ -388,7 +394,7 @@ class EditorStyleCustomizer {node: node,index: index,mention: mention,- textStyle: after.style,+ textStyle: newStyle,),);}@@ -451,6 +457,13 @@ class EditorStyleCustomizer {);}+ if (suggestion != null) {+ return TextSpan(+ text: before.text,+ style: newStyle,+ );+ }+return defaultTextSpanDecoratorForAttribute(context,node,@@ -543,4 +556,34 @@ class EditorStyleCustomizer {return textSpan;}++ TextStyle? _styleSuggestion(TextStyle? style, String suggestion) {+ if (style == null) {+ return null;+ }+ final fontSize = style.fontSize ?? 14.0;+ final isLight = Theme.of(context).isLightMode;+ final textColor = isLight ? Color(0xFF007296) : Color(0xFF49CFF4);+ final underlineColor = isLight ? Color(0x33005A7A) : Color(0x3349CFF4);+ return switch (suggestion) {+ AiWriterBlockKeys.suggestionOriginal => style.copyWith(+ color: Theme.of(context).disabledColor,+ decoration: TextDecoration.lineThrough,+ ),+ AiWriterBlockKeys.suggestionReplacement => style.copyWith(+ color: Colors.transparent,+ decoration: TextDecoration.underline,+ decorationColor: underlineColor,+ decorationThickness: 1.0,+ // hack: https://jtmuller5.medium.com/the-ultimate-guide-to-underlining-text-in-flutter-57936f5c79bb+ shadows: [+ Shadow(+ color: textColor,+ offset: Offset(0, -fontSize * 0.2),+ ),+ ],+ ),+ _ => style,+ };+ }}diff --git a/frontend/appflowy_flutter/lib/startup/deps_resolver.dart b/frontend/appflowy_flutter/lib/startup/deps_resolver.dartindex 64747b4829..621ba988cf 100644--- a/frontend/appflowy_flutter/lib/startup/deps_resolver.dart+++ b/frontend/appflowy_flutter/lib/startup/deps_resolver.dart@@ -1,5 +1,3 @@-import 'package:appflowy/ai/service/ai_client.dart';-import 'package:appflowy/ai/service/appflowy_ai_service.dart';import 'package:appflowy/core/config/kv.dart';import 'package:appflowy/core/network_monitor.dart';import 'package:appflowy/env/cloud_env.dart';@@ -15,7 +13,6 @@ import 'package:appflowy/user/application/auth/auth_service.dart';import 'package:appflowy/user/application/prelude.dart';import 'package:appflowy/user/application/reminder/reminder_bloc.dart';import 'package:appflowy/user/application/user_listener.dart';-import 'package:appflowy/user/application/user_service.dart';import 'package:appflowy/user/presentation/router.dart';import 'package:appflowy/workspace/application/action_navigation/action_navigation_bloc.dart';import 'package:appflowy/workspace/application/edit_panel/edit_panel_bloc.dart';@@ -83,16 +80,6 @@ void _resolveCommonService(() => mode.isTest ? MockApplicationDataStorage() : ApplicationDataStorage(),);- getIt.registerFactoryAsync<AIRepository>(- () async {- final result = await UserBackendService.getCurrentUserProfile();- return result.fold(- (s) => AppFlowyAIService(),- (e) => throw Exception('Failed to get user profile: ${e.msg}'),- );- },- );-getIt.registerFactory<ClipboardService>(() => ClipboardService(),);diff --git a/frontend/appflowy_flutter/test/bloc_test/ai_writer_test/ai_writer_bloc_test.dart b/frontend/appflowy_flutter/test/bloc_test/ai_writer_test/ai_writer_bloc_test.dartnew file mode 100644index 0000000000..73ad2736a0--- /dev/null+++ b/frontend/appflowy_flutter/test/bloc_test/ai_writer_test/ai_writer_bloc_test.dart@@ -0,0 +1,411 @@+import 'dart:async';++import 'package:appflowy/ai/ai.dart';+import 'package:appflowy/plugins/document/presentation/editor_plugins/ai/operations/ai_writer_cubit.dart';+import 'package:appflowy/plugins/document/presentation/editor_plugins/ai/operations/ai_writer_entities.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';++import '../../util.dart';++const _aiResponse = 'UPDATED:';++class _MockCompletionStream extends Mock implements CompletionStream {}++class _MockAIRepository extends Mock implements AppFlowyAIService {+ @override+ Future<(String, CompletionStream)?> streamCompletion({+ String? objectId,+ required String text,+ PredefinedFormat? format,+ List<String> sourceIds = const [],+ 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 {+ final stream = _MockCompletionStream();+ unawaited(+ Future(() async {+ await onStart();+ final lines = text.split('\n');+ for (final line in lines) {+ if (line.isNotEmpty) {+ await onProcess('$_aiResponse $line\n\n');+ }+ }+ await onEnd();+ }),+ );+ return ('mock_id', stream);+ }+}++class _MockAIRepositoryLess extends Mock implements AppFlowyAIService {+ @override+ Future<(String, CompletionStream)?> streamCompletion({+ String? objectId,+ required String text,+ PredefinedFormat? format,+ List<String> sourceIds = const [],+ 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 {+ final stream = _MockCompletionStream();+ unawaited(+ Future(() async {+ await onStart();+ // only return 1 line.+ await onProcess('Hello World');+ await onEnd();+ }),+ );+ return ('mock_id', stream);+ }+}++class _MockAIRepositoryMore extends Mock implements AppFlowyAIService {+ @override+ Future<(String, CompletionStream)?> streamCompletion({+ String? objectId,+ required String text,+ PredefinedFormat? format,+ List<String> sourceIds = const [],+ 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 {+ final stream = _MockCompletionStream();+ unawaited(+ Future(() async {+ await onStart();+ // return 10 lines+ for (var i = 0; i < 10; i++) {+ await onProcess('Hello World\n\n');+ }+ await onEnd();+ }),+ );+ return ('mock_id', stream);+ }+}++class _MockErrorRepository extends Mock implements AppFlowyAIService {+ @override+ Future<(String, CompletionStream)?> streamCompletion({+ String? objectId,+ required String text,+ PredefinedFormat? format,+ List<String> sourceIds = const [],+ 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 {+ final stream = _MockCompletionStream();+ unawaited(+ Future(() async {+ await onStart();+ onError(+ const AIError(+ message: 'Error',+ code: AIErrorCode.aiResponseLimitExceeded,+ ),+ );+ }),+ );+ return ('mock_id', stream);+ }+}++void main() {+ group('AIWriterCubit:', () {+ 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.';++ setUp(() {+ TestWidgetsFlutterBinding.ensureInitialized();+ });++ blocTest<AiWriterCubit, AiWriterState>(+ 'send request before the bloc is initialized',+ build: () {+ final document = Document(+ root: pageNode(+ children: [+ paragraphNode(text: text1),+ paragraphNode(text: text2),+ paragraphNode(text: text3),+ ],+ ),+ );+ final selection = Selection(+ start: Position(path: [0]),+ end: Position(path: [2], offset: text3.length),+ );+ final editorState = EditorState(document: document)+ ..selection = selection;+ final command = AiWriterCommand.explain;+ final node = aiWriterNode(+ command: command,+ selection: selection,+ );+ return AiWriterCubit(+ documentId: '',+ getAiWriterNode: () => node,+ editorState: editorState,+ initialCommand: command,+ aiService: _MockAIRepository(),+ );+ },+ act: (bloc) => bloc.init(),+ expect: () => [+ isA<GeneratingAiWriterState>()+ .having((s) => s.markdownText, 'result', isEmpty),+ isA<GeneratingAiWriterState>()+ .having((s) => s.markdownText, 'result', isNotEmpty)+ .having((s) => s.markdownText, 'result', contains('UPDATED:')),+ isA<GeneratingAiWriterState>()+ .having((s) => s.markdownText, 'result', isNotEmpty)+ .having((s) => s.markdownText, 'result', contains('UPDATED:')),+ isA<GeneratingAiWriterState>()+ .having((s) => s.markdownText, 'result', isNotEmpty)+ .having((s) => s.markdownText, 'result', contains('UPDATED:')),+ isA<ReadyAiWriterState>()+ .having((s) => s.markdownText, 'result', isNotEmpty)+ .having((s) => s.markdownText, 'result', contains('UPDATED:')),+ ],+ );++ blocTest<AiWriterCubit, AiWriterState>(+ 'exceed the ai response limit',+ 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 selection = Selection(+ start: Position(path: [0]),+ end: Position(path: [2], offset: text3.length),+ );+ final editorState = EditorState(document: document)+ ..selection = selection;+ final node = aiWriterNode(+ command: AiWriterCommand.explain,+ selection: selection,+ );+ return AiWriterCubit(+ documentId: '',+ getAiWriterNode: () => node,+ editorState: editorState,+ initialCommand: AiWriterCommand.explain,+ aiService: _MockErrorRepository(),+ );+ },+ act: (bloc) => bloc.init(),+ expect: () => [+ isA<GeneratingAiWriterState>()+ .having((s) => s.markdownText, 'result', isEmpty),+ isA<ErrorAiWriterState>().having(+ (s) => s.error.code,+ 'error code',+ AIErrorCode.aiResponseLimitExceeded,+ ),+ ],+ );++ test('improve writing - the result contains the same number of paragraphs',+ () async {+ final selection = Selection(+ start: Position(path: [0]),+ end: Position(path: [2], offset: text3.length),+ );+ final document = Document(+ root: pageNode(+ children: [+ paragraphNode(text: text1),+ paragraphNode(text: text2),+ paragraphNode(text: text3),+ aiWriterNode(+ command: AiWriterCommand.improveWriting,+ selection: selection,+ ),+ ],+ ),+ );+ final editorState = EditorState(document: document)+ ..selection = selection;+ final aiNode = editorState.getNodeAtPath([3])!;+ final bloc = AiWriterCubit(+ documentId: '',+ getAiWriterNode: () => aiNode,+ editorState: editorState,+ initialCommand: AiWriterCommand.improveWriting,+ aiService: _MockAIRepository(),+ );+ bloc.init();+ await blocResponseFuture();+ bloc.runResponseAction(SuggestionAction.accept);+ await blocResponseFuture();+ expect(+ editorState.document.root.children.length,+ 3,+ );+ expect(+ editorState.getNodeAtPath([0])!.delta!.toPlainText(),+ '$_aiResponse $text1',+ );+ expect(+ editorState.getNodeAtPath([1])!.delta!.toPlainText(),+ '$_aiResponse $text2',+ );+ expect(+ editorState.getNodeAtPath([2])!.delta!.toPlainText(),+ '$_aiResponse $text3',+ );+ });++ test('improve writing - discard', () async {+ final selection = Selection(+ start: Position(path: [0]),+ end: Position(path: [2], offset: text3.length),+ );+ final document = Document(+ root: pageNode(+ children: [+ paragraphNode(text: text1),+ paragraphNode(text: text2),+ paragraphNode(text: text3),+ aiWriterNode(+ command: AiWriterCommand.improveWriting,+ selection: selection,+ ),+ ],+ ),+ );+ final editorState = EditorState(document: document)+ ..selection = selection;+ final aiNode = editorState.getNodeAtPath([3])!;+ final bloc = AiWriterCubit(+ documentId: '',+ getAiWriterNode: () => aiNode,+ editorState: editorState,+ initialCommand: AiWriterCommand.improveWriting,+ aiService: _MockAIRepository(),+ );+ bloc.init();+ await blocResponseFuture();+ bloc.runResponseAction(SuggestionAction.discard);+ await blocResponseFuture();+ expect(+ editorState.document.root.children.length,+ 3,+ );+ expect(editorState.getNodeAtPath([0])!.delta!.toPlainText(), text1);+ expect(editorState.getNodeAtPath([1])!.delta!.toPlainText(), text2);+ expect(editorState.getNodeAtPath([2])!.delta!.toPlainText(), text3);+ });++ test('improve writing - the result less than the original text', () async {+ final selection = Selection(+ start: Position(path: [0]),+ end: Position(path: [2], offset: text3.length),+ );+ final document = Document(+ root: pageNode(+ children: [+ paragraphNode(text: text1),+ paragraphNode(text: text2),+ paragraphNode(text: text3),+ aiWriterNode(+ command: AiWriterCommand.improveWriting,+ selection: selection,+ ),+ ],+ ),+ );+ final editorState = EditorState(document: document)+ ..selection = selection;+ final aiNode = editorState.getNodeAtPath([3])!;+ final bloc = AiWriterCubit(+ documentId: '',+ getAiWriterNode: () => aiNode,+ editorState: editorState,+ initialCommand: AiWriterCommand.improveWriting,+ aiService: _MockAIRepositoryLess(),+ );+ bloc.init();+ await blocResponseFuture();+ bloc.runResponseAction(SuggestionAction.accept);+ await blocResponseFuture();+ expect(editorState.document.root.children.length, 1);+ expect(+ editorState.getNodeAtPath([0])!.delta!.toPlainText(),+ 'Hello World',+ );+ });++ test('improve writing - the result more than the original text', () async {+ final selection = Selection(+ start: Position(path: [0]),+ end: Position(path: [2], offset: text3.length),+ );+ final document = Document(+ root: pageNode(+ children: [+ paragraphNode(text: text1),+ paragraphNode(text: text2),+ paragraphNode(text: text3),+ aiWriterNode(+ command: AiWriterCommand.improveWriting,+ selection: selection,+ ),+ ],+ ),+ );+ final editorState = EditorState(document: document)+ ..selection = selection;+ final aiNode = editorState.getNodeAtPath([3])!;+ final bloc = AiWriterCubit(+ documentId: '',+ getAiWriterNode: () => aiNode,+ editorState: editorState,+ initialCommand: AiWriterCommand.improveWriting,+ aiService: _MockAIRepositoryMore(),+ );+ bloc.init();+ await blocResponseFuture();+ bloc.runResponseAction(SuggestionAction.accept);+ await blocResponseFuture();+ expect(editorState.document.root.children.length, 10);+ for (var i = 0; i < 10; i++) {+ expect(+ editorState.getNodeAtPath([i])!.delta!.toPlainText(),+ 'Hello World',+ );+ }+ });+ });+}diff --git a/frontend/appflowy_flutter/test/bloc_test/ask_ai_test/ask_ai_action_bloc_test.dart b/frontend/appflowy_flutter/test/bloc_test/ask_ai_test/ask_ai_action_bloc_test.dartdeleted file mode 100644index 33e2b4c448..0000000000--- a/frontend/appflowy_flutter/test/bloc_test/ask_ai_test/ask_ai_action_bloc_test.dart+++ /dev/null@@ -1,331 +0,0 @@-import 'package:appflowy/ai/service/ai_client.dart';-import 'package:appflowy/ai/service/appflowy_ai_service.dart';-import 'package:appflowy/ai/service/error.dart';-import 'package:appflowy/plugins/document/presentation/editor_plugins/ai/widgets/ask_ai_action_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';--import '../../util.dart';--const _aiResponse = 'UPDATED:';--class _MockAIRepository extends Mock implements AIRepository {- @override- Future<void> streamCompletion({- String? objectId,- 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('$_aiResponse ${lines[i]}\n\n');- }- await onEnd();- }-}--class _MockAIRepositoryLess extends Mock implements AIRepository {- @override- Future<void> streamCompletion({- String? objectId,- 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();- // only return 1 line.- await onProcess('Hello World');- await onEnd();- }-}--class _MockAIRepositoryMore extends Mock implements AIRepository {- @override- Future<void> streamCompletion({- String? objectId,- 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();- // return 10 lines- for (var i = 0; i < 10; i++) {- await onProcess('Hello World\n\n');- }- await onEnd();- }-}--class _MockErrorRepository extends Mock implements AIRepository {- @override- Future<void> streamCompletion({- String? objectId,- 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();- onError(- const AIError(- message: 'Error',- code: AIErrorCode.aiResponseLimitExceeded,- ),- );- }-}--void main() {- group('AskAIActionBloc: ', () {- 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.';-- blocTest<AskAIActionBloc, AskAIState>(- 'send request before the bloc is initialized',- build: () {- 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 = askAINode(- action: AskAIAction.makeItLonger,- content: [text1, text2, text3].join('\n'),- );- return AskAIActionBloc(- objectId: "",- node: node,- editorState: editorState,- action: AskAIAction.makeItLonger,- enableLogging: false,- );- },- act: (bloc) {- bloc.add(AskAIEvent.initial(Future.value(_MockAIRepository())));- bloc.add(const AskAIEvent.rewrite());- },- expect: () => [- isA<AskAIState>()- .having((s) => s.loading, 'loading', true)- .having((s) => s.result, 'result', isEmpty),- isA<AskAIState>()- .having((s) => s.loading, 'loading', false)- .having((s) => s.result, 'result', isNotEmpty)- .having((s) => s.result, 'result', contains('UPDATED:')),- isA<AskAIState>().having((s) => s.loading, 'loading', false),- ],- );-- blocTest<AskAIActionBloc, AskAIState>(- 'exceed the ai response limit',- 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 = askAINode(- action: AskAIAction.makeItLonger,- content: [text1, text2, text3].join('\n'),- );- return AskAIActionBloc(- objectId: "",- node: node,- editorState: editorState,- action: AskAIAction.makeItLonger,- enableLogging: false,- );- },- act: (bloc) {- bloc.add(AskAIEvent.initial(Future.value(_MockErrorRepository())));- bloc.add(const AskAIEvent.rewrite());- },- expect: () => [- isA<AskAIState>()- .having((s) => s.loading, 'loading', true)- .having((s) => s.result, 'result', isEmpty),- isA<AskAIState>()- .having((s) => s.requestError, 'requestError', isNotNull)- .having(- (s) => s.requestError?.code,- 'requestError.code',- AIErrorCode.aiResponseLimitExceeded,- ),- ],- );-- test('summary - the result contains the same number of paragraphs',- () async {- 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 = askAINode(- action: AskAIAction.makeItLonger,- content: [text1, text2, text3].join('\n\n'),- );- final bloc = AskAIActionBloc(- objectId: "",- node: node,- editorState: editorState,- action: AskAIAction.summarize,- enableLogging: false,- );- bloc.add(AskAIEvent.initial(Future.value(_MockAIRepository())));- await blocResponseFuture();- bloc.add(const AskAIEvent.started());- await blocResponseFuture();- bloc.add(const AskAIEvent.replace());- await blocResponseFuture();- expect(editorState.document.root.children.length, 3);- expect(- editorState.getNodeAtPath([0])!.delta!.toPlainText(),- '$_aiResponse $text1',- );- expect(- editorState.getNodeAtPath([1])!.delta!.toPlainText(),- '$_aiResponse $text2',- );- expect(- editorState.getNodeAtPath([2])!.delta!.toPlainText(),- '$_aiResponse $text3',- );- });-- test('summary - the result less than the original text', () async {- 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 = askAINode(- action: AskAIAction.makeItLonger,- content: [text1, text2, text3].join('\n'),- );- final bloc = AskAIActionBloc(- objectId: "",- node: node,- editorState: editorState,- action: AskAIAction.summarize,- enableLogging: false,- );- bloc.add(AskAIEvent.initial(Future.value(_MockAIRepositoryLess())));- await blocResponseFuture();- bloc.add(const AskAIEvent.started());- await blocResponseFuture();- bloc.add(const AskAIEvent.replace());- await blocResponseFuture();- expect(editorState.document.root.children.length, 1);- expect(- editorState.getNodeAtPath([0])!.delta!.toPlainText(),- 'Hello World',- );- });-- test('summary - the result more than the original text', () async {- 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 = askAINode(- action: AskAIAction.makeItLonger,- content: [text1, text2, text3].join('\n'),- );- final bloc = AskAIActionBloc(- objectId: "",- node: node,- editorState: editorState,- action: AskAIAction.summarize,- enableLogging: false,- );- bloc.add(AskAIEvent.initial(Future.value(_MockAIRepositoryMore())));- await blocResponseFuture();- bloc.add(const AskAIEvent.started());- await blocResponseFuture();- bloc.add(const AskAIEvent.replace());- await blocResponseFuture();- expect(editorState.document.root.children.length, 10);- for (var i = 0; i < 10; i++) {- expect(- editorState.getNodeAtPath([i])!.delta!.toPlainText(),- 'Hello World',- );- }- });- });-}diff --git a/frontend/appflowy_flutter/test/bloc_test/chat_test/util.dart b/frontend/appflowy_flutter/test/bloc_test/chat_test/util.dartindex 29d98416b5..ece0c5e027 100644--- a/frontend/appflowy_flutter/test/bloc_test/chat_test/util.dart+++ b/frontend/appflowy_flutter/test/bloc_test/chat_test/util.dart@@ -34,11 +34,3 @@ class AppFlowyChatTest {});}}--Future<void> boardResponseFuture() {- return Future.delayed(boardResponseDuration());-}--Duration boardResponseDuration({int milliseconds = 200}) {- return Duration(milliseconds: milliseconds);-}diff --git a/frontend/appflowy_flutter/test/unit_test/document/text_robot/markdown_text_robot_test.dart b/frontend/appflowy_flutter/test/unit_test/document/text_robot/markdown_text_robot_test.dartindex ed60e53ae7..0b6289c784 100644--- a/frontend/appflowy_flutter/test/unit_test/document/text_robot/markdown_text_robot_test.dart+++ b/frontend/appflowy_flutter/test/unit_test/document/text_robot/markdown_text_robot_test.dart@@ -29,7 +29,7 @@ void main() {// mock the delay of the text robotawait Future.delayed(const Duration(milliseconds: 10));}- await markdownTextRobot.stop();+ await markdownTextRobot.persist();expect(editorState);}@@ -43,11 +43,10 @@ void main() {markdownTextRobot.start();await markdownTextRobot.appendMarkdownText(_sample1);- await markdownTextRobot.stop();+ await markdownTextRobot.persist();final nodes = editorState.document.root.children;- // 4 from the sample, 1 from the original empty paragraph node- expect(nodes.length, 5);+ expect(nodes.length, 4);final n1 = nodes[0];expect(n1.delta!.toPlainText(), 'The Curious Cat');@@ -116,7 +115,7 @@ void main() {_liveRefreshSample2,expect: (editorState) {final nodes = editorState.document.root.children;- expect(nodes.length, 5);+ expect(nodes.length, 4);final n1 = nodes[0];expect(n1.type, HeadingBlockKeys.type);@@ -164,7 +163,7 @@ void main() {_liveRefreshSample3,expect: (editorState) {final nodes = editorState.document.root.children;- expect(nodes.length, 6);+ expect(nodes.length, 5);final n1 = nodes[0];expect(n1.type, HeadingBlockKeys.type);@@ -275,7 +274,7 @@ void main() {_liveRefreshSample4,expect: (editorState) {final nodes = editorState.document.root.children;- expect(nodes.length, 3);+ expect(nodes.length, 2);final n1 = nodes[0];expect(n1.type, ParagraphBlockKeys.type);diff --git a/frontend/resources/flowy_icons/16x/ai_explain.svg b/frontend/resources/flowy_icons/16x/ai_explain.svgnew file mode 100644index 0000000000..173b35b543--- /dev/null+++ b/frontend/resources/flowy_icons/16x/ai_explain.svg@@ -0,0 +1,5 @@+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M1.75 8C1.75 9.6576 2.40848 11.2473 3.58058 12.4194C4.75268 13.5915 6.3424 14.25 8 14.25C9.6576 14.25 11.2473 13.5915 12.4194 12.4194C13.5915 11.2473 14.25 9.6576 14.25 8C14.25 6.3424 13.5915 4.75268 12.4194 3.58058C11.2473 2.40848 9.6576 1.75 8 1.75C6.3424 1.75 4.75268 2.40848 3.58058 3.58058C2.40848 4.75268 1.75 6.3424 1.75 8Z" stroke="black"/>+<path d="M6.82812 6.04688C6.82812 5.39967 7.35281 4.875 8 4.875C8.64719 4.875 9.17188 5.39967 9.17188 6.04688C9.17188 6.47653 8.94062 6.85219 8.59587 7.05619C8.29875 7.23194 8 7.49856 8 7.84375V8.625" stroke="black" stroke-linecap="round"/>+<path d="M7.375 10.5C7.375 10.6658 7.44085 10.8247 7.55806 10.9419C7.67527 11.0592 7.83424 11.125 8 11.125C8.16576 11.125 8.32473 11.0592 8.44194 10.9419C8.55915 10.8247 8.625 10.6658 8.625 10.5C8.625 10.3342 8.55915 10.1753 8.44194 10.0581C8.32473 9.94085 8.16576 9.875 8 9.875C7.83424 9.875 7.67527 9.94085 7.55806 10.0581C7.44085 10.1753 7.375 10.3342 7.375 10.5Z" fill="black"/>+</svg>diff --git a/frontend/resources/flowy_icons/16x/ai_fix_spelling_grammar.svg b/frontend/resources/flowy_icons/16x/ai_fix_spelling_grammar.svgnew file mode 100644index 0000000000..2f7df6c78a--- /dev/null+++ b/frontend/resources/flowy_icons/16x/ai_fix_spelling_grammar.svg@@ -0,0 +1,3 @@+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M13.3327 4L5.99935 11.3333L2.66602 8" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>+</svg>diff --git a/frontend/resources/flowy_icons/16x/ai_improve_writing.svg b/frontend/resources/flowy_icons/16x/ai_improve_writing.svgnew file mode 100644index 0000000000..9cff9e9875--- /dev/null+++ b/frontend/resources/flowy_icons/16x/ai_improve_writing.svg@@ -0,0 +1,6 @@+<svg width="17" height="16" viewBox="0 0 17 16" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M6.27221 14.1865C6.40487 14.1865 6.53208 14.1338 6.62586 14.04L14.5247 6.13678C14.7198 5.94154 14.7198 5.62512 14.5247 5.42987L12.4109 3.3148C12.2156 3.1194 11.8989 3.1194 11.7036 3.31479L3.80504 11.2177C3.71133 11.3115 3.65869 11.4386 3.65869 11.5712V13.6865C3.65869 13.9627 3.88255 14.1865 4.15869 14.1865H6.27221Z" stroke="#1F2329"/>+<path d="M10.0376 4.97949L12.8583 7.80188" stroke="#1F2329"/>+<path d="M6.44835 1.52132C6.48728 1.42647 6.62028 1.42649 6.65918 1.52136L6.70994 1.64515C6.78714 1.83341 6.93517 1.983 7.1215 2.06101L7.24319 2.11196C7.3371 2.15129 7.33708 2.2857 7.24315 2.32499L7.12064 2.37624C6.93411 2.45426 6.78593 2.60399 6.70873 2.79245L6.65864 2.91471C6.61975 3.00967 6.48662 3.00964 6.44775 2.91468L6.39732 2.79145C6.32013 2.60284 6.17185 2.45299 5.98519 2.37494L5.86382 2.3242C5.76986 2.28492 5.76984 2.15047 5.86378 2.11115L5.98633 2.05987C6.17263 1.9819 6.32067 1.83239 6.39791 1.6442L6.44835 1.52132Z" fill="#1F2329"/>+<path d="M4.18739 2.01949C4.28856 1.77289 4.63432 1.77295 4.73541 2.01958L4.93384 2.5037C5.18456 3.1154 5.66544 3.60147 6.27078 3.85504L6.75028 4.05591C6.99433 4.15814 6.99427 4.50742 6.75019 4.60957L6.27096 4.81012C5.665 5.06371 5.18365 5.55024 4.93291 6.16257L4.73526 6.64525C4.63418 6.8921 4.28808 6.89204 4.18708 6.64516L3.98871 6.16024C3.73801 5.54741 3.25636 5.06048 2.64994 4.80683L2.1724 4.60708C1.92826 4.50496 1.9282 4.15559 2.17231 4.05338L2.65258 3.85229C3.25783 3.59888 3.73873 3.11305 3.9896 2.50158L4.18739 2.01949Z" fill="#1F2329"/>+</svg>diff --git a/frontend/resources/flowy_icons/16x/ai_make_longer.svg b/frontend/resources/flowy_icons/16x/ai_make_longer.svgnew file mode 100644index 0000000000..9f61441f0f--- /dev/null+++ b/frontend/resources/flowy_icons/16x/ai_make_longer.svg@@ -0,0 +1,3 @@+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M4.00504 11.7381C3.87137 11.7381 3.75931 11.6939 3.66887 11.6054C3.57843 11.517 3.5332 11.4074 3.5332 11.2766C3.5332 11.1458 3.57843 11.0338 3.66887 10.9406C3.75931 10.8475 3.87137 10.8009 4.00504 10.8009H8.0332C8.15598 10.8009 8.25887 10.8427 8.34187 10.9263C8.42498 11.0099 8.46654 11.1135 8.46654 11.2371C8.46654 11.3589 8.42504 11.4621 8.34204 11.5469C8.25915 11.6316 8.15831 11.6739 8.03954 11.6739L4.00504 11.7381ZM3.97137 9.37659C3.8487 9.37659 3.74504 9.33537 3.66037 9.25292C3.57559 9.17048 3.5332 9.06837 3.5332 8.94659C3.5332 8.8247 3.5747 8.72142 3.6577 8.63675C3.7407 8.5522 3.84354 8.50992 3.9662 8.50992H12.0284C12.151 8.50992 12.2547 8.55114 12.3394 8.63359C12.4241 8.71603 12.4665 8.81814 12.4665 8.93992C12.4665 9.06181 12.425 9.16503 12.342 9.24959C12.259 9.33426 12.1562 9.37659 12.0335 9.37659H3.97137ZM3.97137 7.09192C3.8487 7.09192 3.74504 7.0507 3.66037 6.96825C3.57559 6.88581 3.5332 6.7837 3.5332 6.66192C3.5332 6.54003 3.5747 6.43681 3.6577 6.35226C3.7407 6.26759 3.84354 6.22526 3.9662 6.22526H12.0284C12.151 6.22526 12.2547 6.26648 12.3394 6.34892C12.4241 6.43137 12.4665 6.53348 12.4665 6.65526C12.4665 6.77714 12.425 6.88042 12.342 6.96509C12.259 7.04964 12.1562 7.09192 12.0335 7.09192H3.97137ZM4.00987 4.80092C3.87631 4.80092 3.76348 4.75603 3.67137 4.66625C3.57926 4.57648 3.5332 4.46526 3.5332 4.33259C3.5332 4.19992 3.57837 4.08753 3.6687 3.99542C3.75915 3.90342 3.87115 3.85742 4.0047 3.85742H11.9899C12.1234 3.85742 12.2363 3.90226 12.3284 3.99192C12.4205 4.0817 12.4665 4.19292 12.4665 4.32559C12.4665 4.45825 12.4214 4.57064 12.331 4.66276C12.2406 4.75487 12.1286 4.80092 11.995 4.80092H4.00987Z" fill="black"/>+</svg>diff --git a/frontend/resources/flowy_icons/16x/ai_make_shorter.svg b/frontend/resources/flowy_icons/16x/ai_make_shorter.svgnew file mode 100644index 0000000000..5f07c58fcc--- /dev/null+++ b/frontend/resources/flowy_icons/16x/ai_make_shorter.svg@@ -0,0 +1,3 @@+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M3.96654 9.83268C3.84376 9.83268 3.74087 9.79146 3.65787 9.70902C3.57476 9.62657 3.5332 9.52446 3.5332 9.40268C3.5332 9.28079 3.57476 9.17757 3.65787 9.09302C3.74087 9.00835 3.84376 8.96602 3.96654 8.96602H8.8332C8.95598 8.96602 9.05887 9.00724 9.14187 9.08968C9.22498 9.17213 9.26654 9.27424 9.26654 9.39602C9.26654 9.5179 9.22498 9.62113 9.14187 9.70568C9.05887 9.79035 8.95598 9.83268 8.8332 9.83268H3.96654ZM3.97137 7.03268C3.8487 7.03268 3.74504 6.99146 3.66037 6.90902C3.57559 6.82657 3.5332 6.72446 3.5332 6.60268C3.5332 6.48079 3.5747 6.37757 3.6577 6.29302C3.7407 6.20835 3.84354 6.16602 3.9662 6.16602H12.0284C12.151 6.16602 12.2547 6.20724 12.3394 6.28968C12.4241 6.37213 12.4665 6.47424 12.4665 6.59602C12.4665 6.7179 12.425 6.82113 12.342 6.90568C12.259 6.99035 12.1562 7.03268 12.0335 7.03268H3.97137Z" fill="black"/>+</svg>diff --git a/frontend/resources/flowy_icons/16x/ai_sparks.svg b/frontend/resources/flowy_icons/16x/ai_sparks.svgindex dc23a6c287..a419454f8e 100644--- a/frontend/resources/flowy_icons/16x/ai_sparks.svg+++ b/frontend/resources/flowy_icons/16x/ai_sparks.svg@@ -1,3 +1,4 @@-<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">-<path d="M13.2756 1.18518C13.1733 0.938319 12.8237 0.93826 12.7213 1.18508L12.5887 1.50482C12.3856 1.99453 11.9964 2.38357 11.5066 2.58646L11.1845 2.71991C10.9375 2.82221 10.9376 3.17207 11.1846 3.27429L11.5037 3.40634C11.9944 3.60942 12.3842 3.99934 12.5871 4.49014L12.7197 4.8108C12.8219 5.05791 13.1719 5.05797 13.2742 4.8109L13.4059 4.49274C13.6088 4.00235 13.9984 3.61274 14.4888 3.40971L14.8109 3.27635C15.0578 3.17411 15.0579 2.82435 14.811 2.72202L14.491 2.58944C14.0012 2.38643 13.612 1.99719 13.409 1.5073L13.2756 1.18518ZM7.03777 1.53065C7.33105 0.823135 8.3333 0.823306 8.62633 1.53092L9.20152 2.91991C9.92828 4.67492 11.3222 6.06949 13.0769 6.79701L14.4669 7.37331C15.1743 7.66662 15.1741 8.66875 14.4666 8.96181L13.0774 9.53723C11.3209 10.2648 9.92565 11.6607 9.19883 13.4175L8.6259 14.8024C8.3329 15.5106 7.32966 15.5104 7.03689 14.8021L6.46187 13.4108C5.73517 11.6526 4.33898 10.2555 2.58115 9.52777L1.19689 8.95468C0.489187 8.66168 0.489017 7.6593 1.19662 7.36606L2.5888 6.78913C4.34324 6.06207 5.73723 4.66819 6.46444 2.91382L7.03777 1.53065ZM7.99301 3.46585C7.93083 3.33103 7.7326 3.33098 7.67035 3.46577C6.72861 5.50464 5.17868 7.05429 3.13202 7.99873C2.9972 8.06095 2.99723 8.25919 3.13206 8.32139C5.18189 9.267 6.72982 10.8225 7.67032 12.8649C7.73247 12.9998 7.93091 12.9999 7.99313 12.8649C8.93402 10.8247 10.4843 9.27314 12.532 8.32853C12.6668 8.26635 12.6668 8.06817 12.532 8.00594C10.4909 7.06352 8.93832 5.51531 7.99301 3.46585Z" fill="black"/>+<svg width="17" height="16" viewBox="0 0 17 16" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M13.5491 4.17206C13.3043 3.65812 12.892 3.24292 12.3798 2.99709C12.8922 2.75182 13.3049 2.33713 13.5502 1.82359C13.7949 2.33773 14.2073 2.7531 14.7196 2.99902C14.2072 3.24416 13.7945 3.6587 13.5491 4.17206ZM7.8553 2.67116C7.94884 2.44317 8.26264 2.44322 8.35611 2.67125L8.87245 3.93101C9.57472 5.64439 10.9224 7.00747 12.6208 7.71895L13.8686 8.24163C14.0945 8.33625 14.0944 8.66539 13.8685 8.75993L12.6215 9.28181C10.9213 9.99333 9.57229 11.3577 8.86997 13.0729L8.35566 14.3289C8.2622 14.5571 7.94808 14.557 7.8547 14.3288L7.33851 13.0669C6.6363 11.3504 5.28646 9.9849 3.58499 9.2732L2.34236 8.75342L2.14941 9.2147L2.34236 8.75342C2.1164 8.65891 2.11633 8.32969 2.34227 8.23509L3.59203 7.71183C5.29021 7.00081 6.63792 5.6384 7.34062 3.92565L7.8553 2.67116Z" stroke="#1F2329"/>+<circle cx="13.5825" cy="2.9375" r="0.5" fill="#1F2329"/></svg>diff --git a/frontend/resources/flowy_icons/16x/ai_summarize.svg b/frontend/resources/flowy_icons/16x/ai_summarize.svgnew file mode 100644index 0000000000..761dae9dc0--- /dev/null+++ b/frontend/resources/flowy_icons/16x/ai_summarize.svg@@ -0,0 +1,3 @@+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M5.39559 5.93492C5.54326 5.93492 5.67009 5.88314 5.77609 5.77959C5.88198 5.67592 5.93492 5.55026 5.93492 5.40259C5.93492 5.25492 5.88314 5.12809 5.77959 5.02209C5.67592 4.9162 5.55026 4.86326 5.40259 4.86326C5.25492 4.86326 5.12809 4.91503 5.02209 5.01859C4.9162 5.12226 4.86326 5.24792 4.86326 5.39559C4.86326 5.54326 4.91503 5.67009 5.01859 5.77609C5.12226 5.88198 5.24792 5.93492 5.39559 5.93492ZM5.39559 8.53492C5.54326 8.53492 5.67009 8.48314 5.77609 8.37959C5.88198 8.27592 5.93492 8.15026 5.93492 8.00259C5.93492 7.85492 5.88314 7.72809 5.77959 7.62209C5.67592 7.5162 5.55026 7.46325 5.40259 7.46325C5.25492 7.46325 5.12809 7.51503 5.02209 7.61859C4.9162 7.72226 4.86326 7.84792 4.86326 7.99559C4.86326 8.14326 4.91503 8.27009 5.01859 8.37609C5.12226 8.48198 5.24792 8.53492 5.39559 8.53492ZM5.39559 11.1349C5.54326 11.1349 5.67009 11.0831 5.77609 10.9796C5.88198 10.8759 5.93492 10.7503 5.93492 10.6026C5.93492 10.4549 5.88314 10.3281 5.77959 10.2221C5.67592 10.1162 5.55026 10.0633 5.40259 10.0633C5.25492 10.0633 5.12809 10.115 5.02209 10.2186C4.9162 10.3223 4.86326 10.4479 4.86326 10.5956C4.86326 10.7433 4.91503 10.8701 5.01859 10.9761C5.12226 11.082 5.24792 11.1349 5.39559 11.1349ZM3.80426 13.2658C3.50414 13.2658 3.25048 13.1621 3.04326 12.9549C2.83603 12.7477 2.73242 12.494 2.73242 12.1939V3.80426C2.73242 3.50414 2.83603 3.25048 3.04326 3.04326C3.25048 2.83603 3.50414 2.73242 3.80426 2.73242H9.80926C9.95026 2.73242 10.0859 2.75809 10.2163 2.80942C10.3467 2.86064 10.4652 2.93959 10.5718 3.04626L12.9519 5.42642C13.0586 5.53298 13.1375 5.65148 13.1888 5.78192C13.2401 5.91225 13.2658 6.04792 13.2658 6.18892V12.1939C13.2658 12.494 13.1621 12.7477 12.9549 12.9549C12.7477 13.1621 12.494 13.2658 12.1939 13.2658H3.80426ZM3.80426 12.3991H12.1939C12.2538 12.3991 12.303 12.3799 12.3414 12.3414C12.3799 12.303 12.3991 12.2538 12.3991 12.1939V6.39909H10.1349C9.98203 6.39909 9.85453 6.34798 9.75242 6.24576C9.6502 6.14364 9.59909 6.01614 9.59909 5.86326V3.59909H3.80426C3.74437 3.59909 3.6952 3.61831 3.65676 3.65676C3.61831 3.6952 3.59909 3.74437 3.59909 3.80426V12.1939C3.59909 12.2538 3.61831 12.303 3.65676 12.3414C3.6952 12.3799 3.74437 12.3991 3.80426 12.3991Z" fill="black"/>+</svg>diff --git a/frontend/resources/flowy_icons/16x/ai_undo.svg b/frontend/resources/flowy_icons/16x/ai_try_again.svgsimilarity index 100%rename from frontend/resources/flowy_icons/16x/ai_undo.svgrename to frontend/resources/flowy_icons/16x/ai_try_again.svgdiff --git a/frontend/resources/flowy_icons/16x/suggestion_insert_below.svg b/frontend/resources/flowy_icons/16x/suggestion_insert_below.svgnew file mode 100644index 0000000000..aa071665c3--- /dev/null+++ b/frontend/resources/flowy_icons/16x/suggestion_insert_below.svg@@ -0,0 +1,3 @@+<svg width="17" height="16" viewBox="0 0 17 16" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M3 4H14.25M3 6.5H14.25M9.25 9H14.25M9.25 11.5H14.25M7.625 10.25L6.29167 11.5833M7.625 10.25L6.29167 8.91666M7.625 10.25L4.625 10.2503C3.125 10.2503 3.125 9.81634 3.125 8.74967" stroke="black" stroke-linecap="round" stroke-linejoin="round"/>+</svg>diff --git a/frontend/resources/translations/ar-SA.json b/frontend/resources/translations/ar-SA.jsonindex 1326fabad1..23b9d4abdc 100644--- a/frontend/resources/translations/ar-SA.json+++ b/frontend/resources/translations/ar-SA.json@@ -387,7 +387,6 @@"storageLimitDialogTitle": "لقد نفدت مساحة التخزين المجانية لديك. قم بالترقية لإلغاء تأمين مساحة تخزين غير محدودة","storageLimitDialogTitleIOS": "لقد نفدت مساحة التخزين المجانية.","aiResponseLimitTitle": "لقد نفدت منك استجابات الذكاء الاصطناعي المجانية. قم بالترقية إلى الخطة الاحترافية أو قم بشراء إضافة الذكاء الاصطناعي لفتح عدد غير محدود من الاستجابات",- "aiResponseLimitTitleIOS": "لقد نفدت استجابات الذكاء الاصطناعي المجانية.","aiResponseLimitDialogTitle": "تم الوصول إلى الحد الأقصى لاستجابات الذكاء الاصطناعي","aiResponseLimit": "لقد نفدت استجابات الذكاء الاصطناعي المجانية.<inlang-LineFeed>\nانتقل إلى الإعدادات -> الخطة -> انقر فوق AI Max أو Pro Plan للحصول على المزيد من استجابات الذكاء الاصطناعي","askOwnerToUpgradeToPro": "مساحة العمل الخاصة بك نفدت من مساحة التخزين المجانية. يرجى مطالبة مالك مساحة العمل الخاصة بك بالترقية إلى الخطة الاحترافية",diff --git a/frontend/resources/translations/de-DE.json b/frontend/resources/translations/de-DE.jsonindex f750139742..996ed03b7d 100644--- a/frontend/resources/translations/de-DE.json+++ b/frontend/resources/translations/de-DE.json@@ -338,7 +338,6 @@"storageLimitDialogTitle": "Dein freier Speicherplatz ist aufgebraucht. Upgrade deinen Plan, um unbegrenzten Speicherplatz freizuschalten.","storageLimitDialogTitleIOS": "Ihr freier Speicherplatz ist aufgebraucht.","aiResponseLimitTitle": "Du hast keine kostenlosen KI-Antworten mehr. Upgrade auf den Pro-Plan oder kaufe ein KI-Add-on, um unbegrenzte Antworten freizuschalten",- "aiResponseLimitTitleIOS": "Ihre kostenlosen KI-Antworten sind aufgebraucht.","aiResponseLimitDialogTitle": "Limit für KI-Antworten erreicht","aiResponseLimit": "Du hast keine kostenlosen KI-Antworten mehr zur Verfügung.\n\nGehe zu Einstellungen -> Plan -> Klicke auf KI Max oder Pro Plan, um mehr KI-Antworten zu erhalten","askOwnerToUpgradeToPro": "Dein Arbeitsbereich hat nicht mehr genügend freien Speicherplatz. Bitte den Eigentümer deines Arbeitsbereichs, auf den Pro-Plan hochzustufen.",diff --git a/frontend/resources/translations/en.json b/frontend/resources/translations/en.jsonindex b64fe35436..d2c9eaaf23 100644--- a/frontend/resources/translations/en.json+++ b/frontend/resources/translations/en.json@@ -214,7 +214,7 @@"indexFileSuccess": "Indexing file successfully","inputActionNoPages": "No page results","referenceSource": {- "zero": "0 sources gefunden",+ "zero": "0 sources found","one": "{count} source found","other": "{count} sources found"},@@ -224,6 +224,7 @@"indexingFile": "Indexing {}","generatingResponse": "Generating response","selectSources": "Select Sources",+ "currentPage": "Current page","sourcesLimitReached": "You can only select up to 3 top-level documents and its children","sourceUnsupported": "We don't support chatting with databases at this time","regenerate": "Try again",@@ -383,7 +384,6 @@"storageLimitDialogTitle": "You have run out of free storage. Upgrade to unlock unlimited storage","storageLimitDialogTitleIOS": "You have run out of free storage.","aiResponseLimitTitle": "You have run out of free AI responses. Upgrade to the Pro Plan or purchase an AI add-on to unlock unlimited responses",- "aiResponseLimitTitleIOS": "You have run out of free AI responses.","aiResponseLimitDialogTitle": "AI Responses limit reached","aiResponseLimit": "You have run out of free AI responses.\n\nGo to Settings -> Plan -> Click AI Max or Pro Plan to get more AI responses","askOwnerToUpgradeToPro": "Your workspace is running out of free storage. Please ask your workspace owner to upgrade to the Pro Plan",@@ -1733,7 +1733,7 @@"toggleHeading2": "Toggle heading 2","toggleHeading3": "Toggle heading 3","emoji": "Emoji",- "aiWriter": "AI Writer",+ "aiWriter": "Ask AI Anything","dateOrReminder": "Date or Reminder","photoGallery": "Photo Gallery","file": "File",@@ -1762,6 +1762,16 @@"referencedGrid": "Referenced Grid","referencedCalendar": "Referenced Calendar","referencedDocument": "Referenced Document",+ "aiWriter": {+ "userQuestion": "Ask AI anything",+ "continueWriting": "Continue writing",+ "fixSpelling": "Fix spelling & grammar",+ "improveWriting": "Improve writing",+ "summarize": "Summarize",+ "explain": "Explain",+ "makeShorter": "Make shorter",+ "makeLonger": "Make longer"+ },"autoGeneratorMenuItemName": "AI Writer","autoGeneratorTitleName": "AI: Ask AI to write anything...","autoGeneratorLearnMore": "Learn more",@@ -1780,7 +1790,7 @@"smartEditCouldNotFetchKey": "Could not fetch AI key","smartEditDisabled": "Connect AI in Settings","appflowyAIEditDisabled": "Sign in to enable AI features",- "discardResponse": "Do you want to discard the AI responses?",+ "discardResponse": "Are you sure you want to discard the AI response?","createInlineMathEquation": "Create equation","fonts": "Fonts","insertDate": "Insert date",@@ -3108,7 +3118,22 @@}},"ai": {- "contentPolicyViolation": "Image generation failed due to sensitive content. Please rephrase your input and try again"+ "contentPolicyViolation": "Image generation failed due to sensitive content. Please rephrase your input and try again",+ "textLimitReachedDescription": "Your workspace has run out of free AI responses. Upgrade to the Pro Plan or purchase an AI add-on to unlock unlimited responses",+ "imageLimitReachedDescription": "You've used up your free AI image quota. Please upgrade to the Pro Plan or purchase an AI add-on to unlock unlimited responses",+ "limitReachedAction": {+ "textDescription": "Your workspace has run out of free AI responses. To get more responses, please",+ "imageDescription": "You've used up your free AI image quota. Please",+ "upgrade": "upgrade",+ "toThe": "to the",+ "proPlan": "Pro Plan",+ "orPurchaseAn": "or purchase an",+ "aiAddon": "AI add-on"+ },+ "editing": "Editing",+ "analyzing": "Analyzing",+ "continueWritingEmptyDocumentTitle": "Continue writing error",+ "continueWritingEmptyDocumentDescription": "We are having trouble expanding on the content in your document. Write a small intro and we can take it from there!"},"autoUpdate": {"criticalUpdateTitle": "Update required to continue",@@ -3128,5 +3153,14 @@"lockTooltip": "Page locked to prevent accidental editing. Click to unlock.","pageLockedToast": "Page locked. Editing is disabled until someone unlocks it.","lockedOperationTooltip": "Page locked to prevent accidental editing."+ },+ "suggestion": {+ "accept": "Accept",+ "keep": "Keep",+ "discard": "Discard",+ "close": "Close",+ "tryAgain": "Try again",+ "rewrite": "Rewrite",+ "insertBelow": "Insert below"}}diff --git a/frontend/resources/translations/fr-FR.json b/frontend/resources/translations/fr-FR.jsonindex 326d2d044f..270b92d72f 100644--- a/frontend/resources/translations/fr-FR.json+++ b/frontend/resources/translations/fr-FR.json@@ -354,7 +354,6 @@"storageLimitDialogTitle": "Vous n'avez plus d'espace de stockage gratuit. Effectuez une mise à niveau pour débloquer un espace de stockage illimité","storageLimitDialogTitleIOS": "Vous n'avez plus d'espace de stockage gratuit.","aiResponseLimitTitle": "Vous n'avez plus de réponses d'IA gratuites. Passez au plan Pro ou achetez un module complémentaire d'IA pour débloquer des réponses illimitées",- "aiResponseLimitTitleIOS": "Vous n'avez plus de réponses IA gratuites.","aiResponseLimitDialogTitle": "La limite des réponses de l'IA a été atteinte","aiResponseLimit": "Vous n'avez plus de réponses IA gratuites.\n\nAccédez à Paramètres -> Plans -> Cliquez sur AI Max ou Pro Plan pour obtenir plus de réponses AI","askOwnerToUpgradeToPro": "Votre espace de stockage gratuit est presque plein. Demandez au propriétaire de votre espace de travail de passer au plan Pro",diff --git a/frontend/resources/translations/ja-JP.json b/frontend/resources/translations/ja-JP.jsonindex cf33c91e88..cd41f16530 100644--- a/frontend/resources/translations/ja-JP.json+++ b/frontend/resources/translations/ja-JP.json@@ -346,9 +346,7 @@"upgradeToPro": "Proプランにアップグレード","upgradeToAIMax": "無制限のAIを解放","storageLimitDialogTitle": "無料のストレージが不足しています。無制限のストレージを解放するにはアップグレードしてください",- "storageLimitDialogTitleIOS": "無料のストレージが不足しています。","aiResponseLimitTitle": "無料のAIレスポンスが不足しています。Proプランにアップグレードするか、AIアドオンを購入して無制限のレスポンスを解放してください",- "aiResponseLimitTitleIOS": "無料のAIレスポンスが不足しています。","aiResponseLimitDialogTitle": "AIレスポンスの制限に達しました","aiResponseLimit": "無料のAIレスポンスが不足しています。\n\n設定 -> プラン -> AI MaxまたはProプランをクリックして、さらにAIレスポンスを取得してください","askOwnerToUpgradeToPro": "ワークスペースの無料ストレージが不足しています。ワークスペースのオーナーにProプランへのアップグレードを依頼してください",diff --git a/frontend/resources/translations/th-TH.json b/frontend/resources/translations/th-TH.jsonindex 6bfa0c0ea0..0e888fdb9b 100644--- a/frontend/resources/translations/th-TH.json+++ b/frontend/resources/translations/th-TH.json@@ -333,7 +333,6 @@"storageLimitDialogTitle": "คุณใช้พื้นที่จัดเก็บฟรีหมดแล้ว กรุณาอัปเกรดเพื่อปลดล็อกพื้นที่จัดเก็บแบบไม่จำกัด","storageLimitDialogTitleIOS": "คุณใช้พื้นที่จัดเก็บฟรีหมดแล้ว","aiResponseLimitTitle": "คุณใช้จำนวนการตอบกลับ AI ฟรีหมดแล้ว กรุณาอัปเกรดเป็นแผน Pro หรือซื้อส่วนเสริม AI เพื่อปลดล็อกการตอบกลับไม่จำกัด",- "aiResponseLimitTitleIOS": "คุณใช้จำนวนการตอบกลับ AI ฟรีหมดแล้ว","aiResponseLimitDialogTitle": "ถึงขีดจำกัดการตอบกลับ AI แล้ว","aiResponseLimit": "คุณใช้จำนวนการตอบกลับ AI ฟรีหมดแล้ว\nไปที่ การตั้งค่า -> แผน -> คลิก AI Max หรือแผน Pro เพื่อรับการตอบกลับ AI เพิ่มเติม","askOwnerToUpgradeToPro": "พื้นที่จัดเก็บฟรีในพื้นที่ทำงานของคุณกำลังจะหมด กรุณาขอให้เจ้าของพื้นที่ทำงานของคุณอัปเกรดเป็นแผน Pro",diff --git a/frontend/resources/translations/tr-TR.json b/frontend/resources/translations/tr-TR.jsonindex d2d0c9eea6..d23566e512 100644--- a/frontend/resources/translations/tr-TR.json+++ b/frontend/resources/translations/tr-TR.json@@ -373,7 +373,6 @@"storageLimitDialogTitle": "Ücretsiz depolama alanınız bitti. Sınırsız depolama için yükseltin","storageLimitDialogTitleIOS": "Ücretsiz depolama alanınız bitti.","aiResponseLimitTitle": "Ücretsiz yapay zeka yanıtlarınız bitti. Sınırsız yanıt için Pro Plana yükseltin veya bir yapay zeka eklentisi satın alın",- "aiResponseLimitTitleIOS": "Ücretsiz yapay zeka yanıtlarınız bitti.","aiResponseLimitDialogTitle": "Yapay zeka yanıt limitine ulaşıldı","aiResponseLimit": "Ücretsiz yapay zeka yanıtlarınız bitti.\n\nDaha fazla yapay zeka yanıtı almak için Ayarlar -> Plan -> AI Max veya Pro Plan'a tıklayın","askOwnerToUpgradeToPro": "Çalışma alanınızın ücretsiz depolama alanı bitiyor. Lütfen çalışma alanı sahibinden Pro Plana yükseltmesini isteyin",diff --git a/frontend/resources/translations/vi-VN.json b/frontend/resources/translations/vi-VN.jsonindex 91ea6a32e8..a506a84db3 100644--- a/frontend/resources/translations/vi-VN.json+++ b/frontend/resources/translations/vi-VN.json@@ -308,7 +308,6 @@"storageLimitDialogTitle": "Bạn đã hết dung lượng lưu trữ miễn phí. Nâng cấp để mở khóa dung lượng lưu trữ không giới hạn","storageLimitDialogTitleIOS": "Bạn đã hết dung lượng lưu trữ miễn phí.","aiResponseLimitTitle": "Bạn đã hết phản hồi AI miễn phí. Nâng cấp lên Gói Pro hoặc mua tiện ích bổ sung AI để mở khóa phản hồi không giới hạn",- "aiResponseLimitTitleIOS": "Bạn đã hết lượt sử dụng AI miễn phí.","aiResponseLimitDialogTitle": "Đã đạt đến giới hạn sử dụng AI","aiResponseLimit": "Bạn đã hết lượt dùng AI miễn phí.\nVào Cài đặt -> Gói đăng ký -> Nhấp vào AI Max hoặc Gói Pro để có thêm lượt dùng AI","askOwnerToUpgradeToPro": "Không gian làm việc của bạn sắp hết dung lượng lưu trữ miễn phí. Vui lòng yêu cầu chủ sở hữu không gian làm việc của bạn nâng cấp lên Gói Pro",diff --git a/frontend/resources/translations/zh-CN.json b/frontend/resources/translations/zh-CN.jsonindex 5cac16a886..ce0c760f3d 100644--- a/frontend/resources/translations/zh-CN.json+++ b/frontend/resources/translations/zh-CN.json@@ -356,7 +356,6 @@"storageLimitDialogTitle": "你已用尽免费存储。升级以解锁无限制存储","storageLimitDialogTitleIOS": "你已用尽免费存储。","aiResponseLimitTitle": "你已用尽免费 AI 回应。升级到专业版或者购买 AI 插件来解锁无限制回应",- "aiResponseLimitTitleIOS": "你已用尽免费 AI 回应。","aiResponseLimitDialogTitle": "已达到 AI 回应限额","aiResponseLimit": "你已用尽了免费 AI 回应。\n\n转到“设置 -> 计划 -> 点击 AI Max 或 Pro 计划”获取更多 AI 回应","askOwnerToUpgradeToPro": "你的工作区即将用尽免费存储。请联系工作区所有者升级到专业版计划",diff --git a/frontend/resources/translations/zh-TW.json b/frontend/resources/translations/zh-TW.jsonindex 34f86cd383..fe66a58aa8 100644--- a/frontend/resources/translations/zh-TW.json+++ b/frontend/resources/translations/zh-TW.json@@ -297,7 +297,6 @@"storageLimitDialogTitle": "您的免費儲存空間已用完,升級以解鎖無限儲存空間","storageLimitDialogTitleIOS": "您的免費儲存空間已用完。","aiResponseLimitTitle": "您的免費 AI 回覆已用完,升級到 Pro 或購買 AI 附加方案以解鎖無限回覆",- "aiResponseLimitTitleIOS": "您的免費 AI 回覆已用完。","aiResponseLimitDialogTitle": "AI 回覆已達到限制","purchaseStorageSpace": "購買儲存空間","purchaseAIResponse": "購買"diff --git a/frontend/rust-lib/event-integration-test/src/chat_event.rs b/frontend/rust-lib/event-integration-test/src/chat_event.rsindex f1aafcd136..c5ac604397 100644--- a/frontend/rust-lib/event-integration-test/src/chat_event.rs+++ b/frontend/rust-lib/event-integration-test/src/chat_event.rs@@ -99,6 +99,7 @@ impl EventIntegrationTest {stream_port: 0,object_id: "".to_string(),rag_ids: vec![],+ format: None,};EventBuilder::new(self.clone()).event(AIEvent::CompleteText)diff --git a/frontend/rust-lib/flowy-ai/src/completion.rs b/frontend/rust-lib/flowy-ai/src/completion.rsindex 7ce7f79a2e..28c64d8a8f 100644--- a/frontend/rust-lib/flowy-ai/src/completion.rs+++ b/frontend/rust-lib/flowy-ai/src/completion.rs@@ -88,13 +88,13 @@ impl CompletionTask {if let Some(cloud_service) = self.cloud_service.upgrade() {let complete_type = match self.context.completion_type {- CompletionTypePB::UnknownCompletionType | CompletionTypePB::ImproveWriting => {- CompletionType::ImproveWriting- },+ CompletionTypePB::ImproveWriting => CompletionType::ImproveWriting,CompletionTypePB::SpellingAndGrammar => CompletionType::SpellingAndGrammar,CompletionTypePB::MakeShorter => CompletionType::MakeShorter,CompletionTypePB::MakeLonger => CompletionType::MakeLonger,CompletionTypePB::ContinueWriting => CompletionType::ContinueWriting,+ CompletionTypePB::ExplainSelected => CompletionType::Explain,+ _ => CompletionType::ContinueWriting,};let _ = sink.send("start:".to_string()).await;@@ -107,7 +107,7 @@ impl CompletionTask {workspace_id: None,rag_ids: Some(self.context.rag_ids),}),- format: Default::default(),+ format: self.context.format.map(Into::into).unwrap_or_default(),};info!("start completion: {:?}", params);@@ -146,6 +146,7 @@ impl CompletionTask {});}}+async fn handle_error(sink: &mut IsolateSink, error: FlowyError) {if error.is_ai_response_limit_exceeded() {let _ = sink.send("AI_RESPONSE_LIMIT".to_string()).await;diff --git a/frontend/rust-lib/flowy-ai/src/entities.rs b/frontend/rust-lib/flowy-ai/src/entities.rsindex 6a30a7dff7..7b1cb66593 100644--- a/frontend/rust-lib/flowy-ai/src/entities.rs+++ b/frontend/rust-lib/flowy-ai/src/entities.rs@@ -365,13 +365,16 @@ pub struct CompleteTextPB {#[pb(index = 2)]pub completion_type: CompletionTypePB,- #[pb(index = 3)]- pub stream_port: i64,+ #[pb(index = 3, one_of)]+ pub format: Option<PredefinedFormatPB>,#[pb(index = 4)]- pub object_id: String,+ pub stream_port: i64,#[pb(index = 5)]+ pub object_id: String,++ #[pb(index = 6)]pub rag_ids: Vec<String>,}@@ -383,13 +386,14 @@ pub struct CompleteTextTaskPB {#[derive(Clone, Debug, ProtoBuf_Enum, Default)]pub enum CompletionTypePB {- UnknownCompletionType = 0,#[default]- ImproveWriting = 1,- SpellingAndGrammar = 2,- MakeShorter = 3,- MakeLonger = 4,- ContinueWriting = 5,+ UserQuestion = 0,+ ExplainSelected = 1,+ ContinueWriting = 2,+ SpellingAndGrammar = 3,+ ImproveWriting = 4,+ MakeShorter = 5,+ MakeLonger = 6,}#[derive(Default, ProtoBuf, Clone, Debug)]