Skip to content

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.

chore: pass ai writer context (#7596)

Richard Shiuedfb5a6629f8b
diff --git a/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/desktop_prompt_text_field.dart b/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/desktop_prompt_text_field.dart
index 2cd74b5944..0fbdeafee4 100644
--- a/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/desktop_prompt_text_field.dart
+++ b/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/desktop_prompt_text_field.dart
@@ -20,6 +20,7 @@ class DesktopPromptInput extends StatefulWidget {
const DesktopPromptInput({
super.key,
required this.isStreaming,
+ required this.textController,
required this.onStopStreaming,
required this.onSubmitted,
required this.selectedSourcesNotifier,
@@ -29,6 +30,7 @@ class DesktopPromptInput extends StatefulWidget {
});
final bool isStreaming;
+ final TextEditingController textController;
final void Function() onStopStreaming;
final void Function(String, PredefinedFormat?, Map<String, dynamic>)
onSubmitted;
@@ -47,7 +49,6 @@ class _DesktopPromptInputState extends State<DesktopPromptInput> {
final overlayController = OverlayPortalController();
final inputControlCubit = ChatInputControlCubit();
final focusNode = FocusNode();
- final textController = TextEditingController();
late SendButtonState sendButtonState;
bool isComposing = false;
@@ -56,7 +57,7 @@ class _DesktopPromptInputState extends State<DesktopPromptInput> {
void initState() {
super.initState();
- textController.addListener(handleTextControllerChanged);
+ widget.textController.addListener(handleTextControllerChanged);
focusNode.addListener(
() {
if (!widget.hideDecoration) {
@@ -84,7 +85,7 @@ class _DesktopPromptInputState extends State<DesktopPromptInput> {
@override
void dispose() {
focusNode.dispose();
- textController.dispose();
+ widget.textController.removeListener(handleTextControllerChanged);
inputControlCubit.close();
super.dispose();
}
@@ -109,7 +110,7 @@ class _DesktopPromptInputState extends State<DesktopPromptInput> {
overlayChildBuilder: (context) {
return PromptInputMentionPageMenu(
anchor: PromptInputAnchor(textFieldKey, layerLink),
- textController: textController,
+ textController: widget.textController,
onPageSelected: handlePageSelected,
);
},
@@ -224,12 +225,12 @@ class _DesktopPromptInputState extends State<DesktopPromptInput> {
if (!focusNode.hasFocus) {
focusNode.requestFocus();
}
- textController.text += '@';
+ widget.textController.text += '@';
WidgetsBinding.instance.addPostFrameCallback((_) {
if (context.mounted) {
context
.read<ChatInputControlCubit>()
- .startSearching(textController.value);
+ .startSearching(widget.textController.value);
overlayController.show();
}
});
@@ -245,7 +246,7 @@ class _DesktopPromptInputState extends State<DesktopPromptInput> {
void updateSendButtonState() {
if (widget.isStreaming) {
sendButtonState = SendButtonState.streaming;
- } else if (textController.text.trim().isEmpty) {
+ } else if (widget.textController.text.trim().isEmpty) {
sendButtonState = SendButtonState.disabled;
} else {
sendButtonState = SendButtonState.enabled;
@@ -257,9 +258,9 @@ class _DesktopPromptInputState extends State<DesktopPromptInput> {
return;
}
final trimmedText = inputControlCubit.formatIntputText(
- textController.text.trim(),
+ widget.textController.text.trim(),
);
- textController.clear();
+ widget.textController.clear();
if (trimmedText.isEmpty) {
return;
}
@@ -282,7 +283,7 @@ class _DesktopPromptInputState extends State<DesktopPromptInput> {
setState(() {
// update whether send button is clickable
updateSendButtonState();
- isComposing = !textController.value.composing.isCollapsed;
+ isComposing = !widget.textController.value.composing.isCollapsed;
});
if (isComposing) {
@@ -300,6 +301,7 @@ class _DesktopPromptInputState extends State<DesktopPromptInput> {
}
// handle cases where mention a page is cancelled
+ final textController = widget.textController;
final textSelection = textController.value.selection;
final isSelectingMultipleCharacters = !textSelection.isCollapsed;
final isCaretBeforeStartOfRange =
@@ -348,7 +350,7 @@ class _DesktopPromptInputState extends State<DesktopPromptInput> {
KeyEventResult handleKeyEvent(FocusNode node, KeyEvent event) {
if (event.character == '@') {
WidgetsBinding.instance.addPostFrameCallback((_) {
- inputControlCubit.startSearching(textController.value);
+ inputControlCubit.startSearching(widget.textController.value);
overlayController.show();
});
}
@@ -356,12 +358,12 @@ class _DesktopPromptInputState extends State<DesktopPromptInput> {
}
void handlePageSelected(ViewPB view) {
- final newText = textController.text.replaceRange(
+ final newText = widget.textController.text.replaceRange(
inputControlCubit.filterStartPosition,
inputControlCubit.filterEndPosition,
view.id,
);
- textController.value = TextEditingValue(
+ widget.textController.value = TextEditingValue(
text: newText,
selection: TextSelection.collapsed(
offset: inputControlCubit.filterStartPosition + view.id.length,
@@ -386,7 +388,7 @@ class _DesktopPromptInputState extends State<DesktopPromptInput> {
key: textFieldKey,
editable: state.editable,
cubit: inputControlCubit,
- textController: textController,
+ textController: widget.textController,
textFieldFocusNode: focusNode,
contentPadding:
calculateContentPadding(state.showPredefinedFormats),
diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/chat_page.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/chat_page.dart
index a666039ef2..cbc4929f56 100644
--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/chat_page.dart
+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/chat_page.dart
@@ -385,13 +385,26 @@ class _ChatContentPage extends StatelessWidget {
}
}
-class _Input extends StatelessWidget {
+class _Input extends StatefulWidget {
const _Input({
required this.view,
});
final ViewPB view;
+ @override
+ State<_Input> createState() => _InputState();
+}
+
+class _InputState extends State<_Input> {
+ final textController = TextEditingController();
+
+ @override
+ void dispose() {
+ textController.dispose();
+ super.dispose();
+ }
+
@override
Widget build(BuildContext context) {
return BlocSelector<ChatSelectMessageBloc, ChatSelectMessageState, bool>(
@@ -421,6 +434,7 @@ class _Input extends StatelessWidget {
return UniversalPlatform.isDesktop
? DesktopPromptInput(
isStreaming: !canSendMessage,
+ textController: textController,
onStopStreaming: () {
chatBloc.add(const ChatEvent.stopStream());
},
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.dart
index 0aa7465dfb..76d1af7134 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
@@ -41,7 +41,7 @@ class _MobileChatInputState extends State<MobileChatInput> {
void initState() {
super.initState();
- textController.addListener(handleTextControllerChange);
+ textController.addListener(handleTextControllerChanged);
// focusNode.onKeyEvent = handleKeyEvent;
WidgetsBinding.instance.addPostFrameCallback((_) {
@@ -197,7 +197,7 @@ class _MobileChatInputState extends State<MobileChatInput> {
);
}
- void handleTextControllerChange() {
+ void handleTextControllerChanged() {
if (textController.value.isComposingRangeValid) {
return;
}
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_page.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_page.dart
index f445e698aa..b14d930d65 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_page.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_page.dart
@@ -393,7 +393,7 @@ class _AppFlowyEditorPageState extends State<AppFlowyEditorPage>
},
child: SizedBox(
width: double.infinity,
- height: UniversalPlatform.isDesktopOrWeb ? 300 : 400,
+ height: UniversalPlatform.isDesktopOrWeb ? 600 : 400,
),
),
dropTargetStyle: AppFlowyDropTargetStyle(
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.dart
index 1d25723854..a35d0cfbf8 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
@@ -107,9 +107,7 @@ class _AIWriterBlockComponentState extends State<AiWriterBlockComponent> {
WidgetsBinding.instance.addPostFrameCallback((_) {
overlayController.show();
- if (!widget.node.isAiWriterInitialized) {
- context.read<AiWriterCubit>().register(widget.node);
- }
+ context.read<AiWriterCubit>().register(widget.node);
});
}
@@ -150,6 +148,7 @@ class _AIWriterBlockComponentState extends State<AiWriterBlockComponent> {
child: OverlayContent(
editorState: editorState,
node: widget.node,
+ textController: textController,
),
),
),
@@ -178,10 +177,12 @@ class OverlayContent extends StatefulWidget {
super.key,
required this.editorState,
required this.node,
+ required this.textController,
});
final EditorState editorState;
final Node node;
+ final TextEditingController textController;
@override
State<OverlayContent> createState() => _OverlayContentState();
@@ -200,31 +201,40 @@ class _OverlayContentState extends State<OverlayContent> {
Widget build(BuildContext context) {
return BlocBuilder<AiWriterCubit, AiWriterState>(
builder: (context, state) {
- if (state is IdleAiWriterState) {
+ if (state is IdleAiWriterState ||
+ state is DocumentContentEmptyAiWriterState) {
return const SizedBox.shrink();
}
+
+ final command = (state as RegisteredAiWriter).command;
+
final selection = widget.node.aiWriterSelection;
- final showSuggestionPopup =
- state is ReadyAiWriterState && !state.isFirstRun;
- final isInitialReadyState =
- state is ReadyAiWriterState && state.isFirstRun;
+ final hasSelection = selection != null && !selection.isCollapsed;
+
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 showSuggestedActions =
+ state is ReadyAiWriterState && !state.isFirstRun;
+ final isInitialReadyState =
+ state is ReadyAiWriterState && state.isFirstRun;
+ final showSuggestedActionsPopup =
+ showSuggestedActions && markdownText.isEmpty;
+ final showSuggestedActionsWithin =
+ showSuggestedActions && markdownText.isNotEmpty;
+
+ final darkBorderColor = Theme.of(context).isLightMode
+ ? Color(0x1F1F2329)
+ : Color(0xFF505469);
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- if (showSuggestionPopup &&
- state.command != AiWriterCommand.explain) ...[
+ if (showSuggestedActionsPopup) ...[
Container(
padding: EdgeInsets.all(4.0),
decoration: _getModalDecoration(
@@ -234,7 +244,7 @@ class _OverlayContentState extends State<OverlayContent> {
borderColor: darkBorderColor,
),
child: SuggestionActionBar(
- currentCommand: state.command,
+ currentCommand: command,
hasSelection: hasSelection,
onTap: (action) {
_onSelectSuggestionAction(context, action);
@@ -243,85 +253,40 @@ class _OverlayContentState extends State<OverlayContent> {
),
const VSpace(4.0 + 1.0),
],
- DecoratedBox(
+ Container(
decoration: _getModalDecoration(
context,
color: null,
borderColor: darkBorderColor,
borderRadius: BorderRadius.all(Radius.circular(12.0)),
),
+ constraints: BoxConstraints(maxHeight: 400),
child: Column(
+ mainAxisSize: MainAxisSize.min,
children: [
if (markdownText.isNotEmpty) ...[
- DecoratedBox(
- decoration: _getHelperChildDecoration(context),
- child: Container(
- constraints: BoxConstraints(maxHeight: 140),
- width: double.infinity,
- padding: EdgeInsets.symmetric(horizontal: 8.0),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Expanded(
- child: SingleChildScrollView(
- physics: ClampingScrollPhysics(),
- padding: EdgeInsets.only(top: 8.0),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- Container(
- height: 24.0,
- padding:
- EdgeInsets.symmetric(horizontal: 6.0),
- alignment:
- AlignmentDirectional.centerStart,
- child: FlowyText(
- (state as RegisteredAiWriter)
- .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 &&
- state.command == AiWriterCommand.explain) ...[
- const VSpace(4.0),
- SuggestionActionBar(
- currentCommand: state.command,
- hasSelection: hasSelection,
- onTap: (action) {
- _onSelectSuggestionAction(context, action);
- },
- ),
- ],
- const VSpace(8.0),
- ],
+ Flexible(
+ child: DecoratedBox(
+ decoration: _secondaryContentDecoration(context),
+ child: SecondaryContentArea(
+ markdownText: markdownText,
+ onSelectSuggestionAction: (action) {
+ _onSelectSuggestionAction(context, action);
+ },
+ command: command,
+ showSuggestionActions: showSuggestedActionsWithin,
+ hasSelection: hasSelection,
),
),
),
- Divider(
- height: 1.0,
- ),
+ Divider(height: 1.0),
],
DecoratedBox(
decoration: markdownText.isNotEmpty
- ? _getInputChildDecoration(context)
+ ? _mainContentDecoration(context)
: _getSingleChildDeocoration(context),
child: MainContentArea(
+ textController: widget.textController,
isDocumentEmpty: _isDocumentEmpty(),
isInitialReadyState: isInitialReadyState,
showCommandsToggle: showCommandsToggle,
@@ -338,21 +303,19 @@ class _OverlayContentState extends State<OverlayContent> {
}
return Align(
alignment: AlignmentDirectional.centerEnd,
- child: BottomCommandButtons(
+ child: MoreAiWriterCommands(
hasSelection: hasSelection,
editorState: widget.editorState,
onSelectCommand: (command) {
- final promptInputBloc = context.read<AIPromptInputBloc>();
- final showPredefinedFormats =
- promptInputBloc.state.showPredefinedFormats;
- final predefinedFormat =
- promptInputBloc.state.predefinedFormat;
+ final state = context.read<AIPromptInputBloc>().state;
+ final showPredefinedFormats = state.showPredefinedFormats;
+ final predefinedFormat = state.predefinedFormat;
+ final text = widget.textController.text;
context.read<AiWriterCubit>().runCommand(
command,
- predefinedFormat:
- showPredefinedFormats ? predefinedFormat : null,
- isFirstRun: true,
+ text,
+ showPredefinedFormats ? predefinedFormat : null,
);
},
),
@@ -395,14 +358,14 @@ class _OverlayContentState extends State<OverlayContent> {
);
}
- BoxDecoration _getHelperChildDecoration(BuildContext context) {
+ BoxDecoration _secondaryContentDecoration(BuildContext context) {
return BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.vertical(top: Radius.circular(12.0)),
);
}
- BoxDecoration _getInputChildDecoration(BuildContext context) {
+ BoxDecoration _mainContentDecoration(BuildContext context) {
return BoxDecoration(
color: Theme.of(context).colorScheme.surface,
borderRadius: BorderRadius.vertical(bottom: Radius.circular(12.0)),
@@ -436,14 +399,83 @@ class _OverlayContentState extends State<OverlayContent> {
}
}
+class SecondaryContentArea extends StatelessWidget {
+ const SecondaryContentArea({
+ super.key,
+ required this.command,
+ required this.markdownText,
+ required this.showSuggestionActions,
+ required this.hasSelection,
+ required this.onSelectSuggestionAction,
+ });
+
+ final AiWriterCommand command;
+ final String markdownText;
+ final bool showSuggestionActions;
+ final bool hasSelection;
+ final void Function(SuggestionAction) onSelectSuggestionAction;
+
+ @override
+ Widget build(BuildContext context) {
+ return SizedBox(
+ width: double.infinity,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Flexible(
+ child: SingleChildScrollView(
+ physics: ClampingScrollPhysics(),
+ padding: EdgeInsets.only(top: 8.0, left: 14.0, right: 14.0),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Container(
+ height: 24.0,
+ alignment: AlignmentDirectional.centerStart,
+ child: FlowyText(
+ command.i18n,
+ fontSize: 12,
+ fontWeight: FontWeight.w600,
+ color: Color(0xFF666D76),
+ ),
+ ),
+ const VSpace(4.0),
+ AIMarkdownText(
+ markdown: markdownText,
+ ),
+ ],
+ ),
+ ),
+ ),
+ if (showSuggestionActions) ...[
+ const VSpace(4.0),
+ Padding(
+ padding: EdgeInsets.symmetric(horizontal: 8.0),
+ child: SuggestionActionBar(
+ currentCommand: command,
+ hasSelection: hasSelection,
+ onTap: onSelectSuggestionAction,
+ ),
+ ),
+ ],
+ const VSpace(8.0),
+ ],
+ ),
+ );
+ }
+}
+
class MainContentArea extends StatelessWidget {
const MainContentArea({
super.key,
+ required this.textController,
required this.isInitialReadyState,
required this.isDocumentEmpty,
required this.showCommandsToggle,
});
+ final TextEditingController textController;
final bool isInitialReadyState;
final bool isDocumentEmpty;
final ValueNotifier<bool> showCommandsToggle;
@@ -458,7 +490,10 @@ class MainContentArea extends StatelessWidget {
return DesktopPromptInput(
isStreaming: false,
hideDecoration: true,
- onSubmitted: (message, format, _) => cubit.submit(message, format),
+ textController: textController,
+ onSubmitted: (message, format, _) {
+ cubit.runCommand(state.command, message, format);
+ },
onStopStreaming: () => cubit.stopStream(),
selectedSourcesNotifier: cubit.selectedSourcesNotifier,
onUpdateSelectedSources: (sources) {
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.dart
index c503042339..d48c655e56 100644
--- 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.dart
@@ -1,8 +1,11 @@
+import 'dart:async';
+
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';
+import 'ai_writer_node_extension.dart';
Future<void> setAiWriterNodeIsInitialized(
EditorState editorState,
@@ -11,13 +14,26 @@ Future<void> setAiWriterNodeIsInitialized(
final transaction = editorState.transaction
..updateNode(node, {
AiWriterBlockKeys.isInitialized: true,
- })
- ..afterSelection = null;
+ });
await editorState.apply(
transaction,
- options: const ApplyOptions(recordUndo: false),
+ options: const ApplyOptions(
+ recordUndo: false,
+ inMemoryUpdate: true,
+ ),
+ withUpdateSelection: false,
);
+
+ final selection = node.aiWriterSelection;
+ if (selection != null && !selection.isCollapsed) {
+ unawaited(
+ editorState.updateSelectionWithReason(
+ selection,
+ extraInfo: {selectionExtraInfoDisableToolbar: true},
+ ),
+ );
+ }
}
Future<void> removeAiWriterNode(
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.dart
index 3b0e04e828..079a3a2749 100644
--- 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.dart
@@ -1,14 +1,13 @@
import 'dart:async';
import 'package:appflowy/ai/ai.dart';
-import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/workspace/application/view/view_service.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:appflowy_result/appflowy_result.dart';
import 'package:bloc/bloc.dart';
-import 'package:easy_localization/easy_localization.dart';
+import 'package:collection/collection.dart';
import 'package:flutter/foundation.dart';
import '../../base/markdown_text_robot.dart';
@@ -41,8 +40,6 @@ class AiWriterCubit extends Cubit<AiWriterState> {
final List<AiWriterRecord> records = [];
final ValueNotifier<List<String>> selectedSourcesNotifier;
- (String, PredefinedFormat?)? _previousPrompt;
- bool acceptReplacesOriginal = false;
@override
Future<void> close() async {
@@ -50,31 +47,20 @@ class AiWriterCubit extends Cubit<AiWriterState> {
await super.close();
}
- void register(Node node) async {
- if (aiWriterNode != null && node.id != aiWriterNode!.id) {
- await removeAiWriterNode(editorState, node);
- return;
- }
- aiWriterNode = node;
- onCreateNode?.call();
-
- await setAiWriterNodeIsInitialized(editorState, node);
-
- final command = node.aiWriterCommand;
- if (command == AiWriterCommand.userQuestion) {
- emit(ReadyAiWriterState(AiWriterCommand.userQuestion, isFirstRun: true));
- } else {
- runCommand(command, isFirstRun: true);
+ Future<void> exit({
+ bool withDiscard = true,
+ bool withUnformat = true,
+ }) async {
+ if (withDiscard) {
+ await _textRobot.discard();
}
- }
-
- Future<void> exit() async {
- await _textRobot.discard();
_textRobot.reset();
onRemoveNode?.call();
+ records.clear();
+ selectedSourcesNotifier.value = [documentId];
emit(IdleAiWriterState());
- if (aiWriterNode != null) {
+ if (withUnformat) {
final selection = aiWriterNode!.aiWriterSelection;
if (selection == null) {
return;
@@ -94,43 +80,96 @@ class AiWriterCubit extends Cubit<AiWriterState> {
),
withUpdateSelection: false,
);
+ }
+ if (aiWriterNode != null) {
await removeAiWriterNode(editorState, aiWriterNode!);
aiWriterNode = null;
}
}
+ void register(Node node) async {
+ if (node.isAiWriterInitialized) {
+ return;
+ }
+ if (aiWriterNode != null && node.id != aiWriterNode!.id) {
+ await removeAiWriterNode(editorState, node);
+ return;
+ }
+
+ aiWriterNode = node;
+ onCreateNode?.call();
+
+ await setAiWriterNodeIsInitialized(editorState, node);
+
+ final command = node.aiWriterCommand;
+ final (run, prompt) = await _addSelectionTextToRecords(command);
+
+ if (!run) {
+ await exit();
+ return;
+ }
+
+ runCommand(command, prompt, null);
+ }
+
void runCommand(
- AiWriterCommand command, {
- required bool isFirstRun,
+ AiWriterCommand command,
+ String prompt,
PredefinedFormat? predefinedFormat,
- bool isRetry = false,
- }) async {
+ ) async {
+ if (aiWriterNode == null) {
+ return;
+ }
+
switch (command) {
case AiWriterCommand.continueWriting:
await _startContinueWriting(
command,
predefinedFormat,
- isImmediateRun: isFirstRun,
);
break;
case AiWriterCommand.fixSpellingAndGrammar:
case AiWriterCommand.improveWriting:
case AiWriterCommand.makeLonger:
case AiWriterCommand.makeShorter:
- await _startSuggestingEdits(command, predefinedFormat);
+ await _startSuggestingEdits(command, prompt, predefinedFormat);
break;
case AiWriterCommand.explain:
- await _startInforming(command, predefinedFormat);
+ await _startInforming(command, prompt, predefinedFormat);
+ break;
+ case AiWriterCommand.userQuestion when prompt.isNotEmpty:
+ _startAskingQuestion(prompt, predefinedFormat);
break;
case AiWriterCommand.userQuestion:
- if (isRetry && _previousPrompt != null) {
- submit(_previousPrompt!.$1, _previousPrompt!.$2);
- }
+ emit(
+ ReadyAiWriterState(AiWriterCommand.userQuestion, isFirstRun: true),
+ );
break;
}
}
+ void _retry({
+ required PredefinedFormat? predefinedFormat,
+ }) async {
+ final lastQuestion =
+ records.lastWhereOrNull((record) => record.role == AiRole.user);
+
+ if (lastQuestion != null && state is RegisteredAiWriter) {
+ await _textRobot.discard();
+ _textRobot.reset();
+ runCommand(
+ (state as RegisteredAiWriter).command,
+ lastQuestion.content,
+ lastQuestion.format,
+ );
+ }
+ }
+
Future<void> stopStream() async {
+ if (aiWriterNode == null) {
+ return;
+ }
+
if (state is GeneratingAiWriterState) {
final generatingState = state as GeneratingAiWriterState;
@@ -138,6 +177,10 @@ class AiWriterCubit extends Cubit<AiWriterState> {
attributes: ApplySuggestionFormatType.replace.attributes,
);
+ if (_textRobot.hasAnyResult) {
+ records.add(AiWriterRecord.ai(content: _textRobot.markdownText));
+ }
+
await AIEventStopCompleteText(
CompleteTextTaskPB(
taskId: generatingState.taskId,
@@ -162,31 +205,17 @@ class AiWriterCubit extends Cubit<AiWriterState> {
return;
}
- if (state is! RegisteredAiWriter) {
- return;
- }
-
- final command = (state as RegisteredAiWriter).command;
-
if (action case SuggestionAction.rewrite || SuggestionAction.tryAgain) {
- await _textRobot.discard();
- _textRobot.reset();
- runCommand(
- command,
- predefinedFormat: predefinedFormat,
- isRetry: true,
- isFirstRun: false,
- );
+ _retry(predefinedFormat: predefinedFormat);
return;
}
-
- final selection = aiWriterNode!.aiWriterSelection;
- if (selection == null) {
+ if (action case SuggestionAction.discard || SuggestionAction.close) {
+ await exit();
return;
}
- if (action case SuggestionAction.discard || SuggestionAction.close) {
- await exit();
+ final selection = aiWriterNode?.aiWriterSelection;
+ if (selection == null) {
return;
}
@@ -199,6 +228,8 @@ class AiWriterCubit extends Cubit<AiWriterState> {
options: const ApplyOptions(recordUndo: false),
withUpdateSelection: false,
);
+ await exit(withDiscard: false, withUnformat: false);
+ return;
}
if (action case SuggestionAction.keep) {
@@ -206,8 +237,12 @@ class AiWriterCubit extends Cubit<AiWriterState> {
}
if (action case SuggestionAction.insertBelow) {
- if (state case final ReadyAiWriterState readyState
- when readyState.markdownText.isNotEmpty) {
+ if (state is! ReadyAiWriterState) {
+ return;
+ }
+ final command = (state as ReadyAiWriterState).command;
+ final markdownText = (state as ReadyAiWriterState).markdownText;
+ if (command == AiWriterCommand.explain && markdownText.isNotEmpty) {
final transaction = editorState.transaction;
final position = ensurePreviousNodeIsEmptyParagraph(
editorState,
@@ -224,8 +259,8 @@ class AiWriterCubit extends Cubit<AiWriterState> {
withUpdateSelection: false,
);
_textRobot.start(position: position);
- await _textRobot.persist(markdownText: readyState.markdownText);
- } else {
+ await _textRobot.persist(markdownText: markdownText);
+ } else if (_textRobot.hasAnyResult) {
await _textRobot.persist();
}
@@ -243,9 +278,7 @@ class AiWriterCubit extends Cubit<AiWriterState> {
);
}
- await removeAiWriterNode(editorState, aiWriterNode!);
- aiWriterNode = null;
- emit(IdleAiWriterState());
+ await exit(withDiscard: false);
}
bool hasUnusedResponse() {
@@ -260,7 +293,56 @@ class AiWriterCubit extends Cubit<AiWriterState> {
};
}
- void submit(
+ Future<(bool, String)> _addSelectionTextToRecords(
+ AiWriterCommand command,
+ ) async {
+ final node = aiWriterNode;
+ if (node == null) {
+ return (false, '');
+ }
+ final selection = node.aiWriterSelection?.normalized;
+ if (selection == null) {
+ return (false, '');
+ }
+
+ if (command == AiWriterCommand.continueWriting) {
+ return (true, '');
+ } else {
+ if (selection.isCollapsed) {
+ return (true, '');
+ } else {
+ final selectionText =
+ await editorState.getMarkdownInSelection(selection);
+
+ if (command == AiWriterCommand.userQuestion) {
+ records.add(
+ AiWriterRecord.user(content: selectionText, format: null),
+ );
+ return (true, '');
+ } else {
+ return (true, selectionText);
+ }
+ }
+ }
+ }
+
+ Future<String> _getDocumentContentFromTopToPosition(Position position) async {
+ final beginningToCursorSelection = Selection(
+ start: Position(path: [0]),
+ end: position,
+ ).normalized;
+
+ final documentText =
+ (await editorState.getMarkdownInSelection(beginningToCursorSelection))
+ .trim();
+
+ final view = await ViewBackendService.getView(documentId).toNullable();
+ final viewName = view?.name ?? '';
+
+ return "$viewName\n$documentText".trim();
+ }
+
+ void _startAskingQuestion(
String prompt,
PredefinedFormat? format,
) async {
@@ -268,7 +350,6 @@ class AiWriterCubit extends Cubit<AiWriterState> {
return;
}
final command = AiWriterCommand.userQuestion;
- _previousPrompt = (prompt, format);
final stream = await _aiService.streamCompletion(
objectId: documentId,
@@ -294,7 +375,10 @@ class AiWriterCubit extends Cubit<AiWriterState> {
);
_textRobot.start(position: position);
records.add(
- AiWriterRecord.user(content: prompt),
+ AiWriterRecord.user(
+ content: prompt,
+ format: format,
+ ),
);
},
processMessage: (text) async {
@@ -353,43 +437,19 @@ class AiWriterCubit extends Cubit<AiWriterState> {
Future<void> _startContinueWriting(
AiWriterCommand command,
- PredefinedFormat? predefinedFormat, {
- required bool isImmediateRun,
- }) async {
- if (aiWriterNode == null) {
- return;
- }
- final cursorPosition = aiWriterNode?.aiWriterSelection?.start;
- if (cursorPosition == null) {
+ PredefinedFormat? predefinedFormat,
+ ) async {
+ final position = aiWriterNode?.aiWriterSelection?.start;
+ if (position == null) {
return;
}
- final selection = Selection(
- start: Position(path: [0]),
- end: cursorPosition,
- ).normalized;
+ final text = await _getDocumentContentFromTopToPosition(position);
- String text = (await editorState.getMarkdownInSelection(selection)).trim();
if (text.isEmpty) {
- final view = await ViewBackendService.getView(documentId).toNullable();
- if (view == null ||
- view.name.isEmpty ||
- view.name == LocaleKeys.menuAppHeader_defaultNewPageName.tr()) {
- final stateCopy = state;
- emit(
- DocumentContentEmptyAiWriterState(
- command,
- onConfirm: () {
- if (isImmediateRun) {
- removeAiWriterNode(editorState, aiWriterNode!);
- }
- },
- ),
- );
- emit(stateCopy);
- return;
- } else {
- text = view.name;
- }
+ final stateCopy = state;
+ emit(DocumentContentEmptyAiWriterState(command, onConfirm: exit));
+ emit(stateCopy);
+ return;
}
final stream = await _aiService.streamCompletion(
@@ -397,6 +457,7 @@ class AiWriterCubit extends Cubit<AiWriterState> {
text: text,
completionType: command.toCompletionType(),
history: records,
+ sourceIds: selectedSourcesNotifier.value,
onStart: () async {
final transaction = editorState.transaction;
final position = ensurePreviousNodeIsEmptyParagraph(
@@ -414,6 +475,12 @@ class AiWriterCubit extends Cubit<AiWriterState> {
withUpdateSelection: false,
);
_textRobot.start(position: position);
+ records.add(
+ AiWriterRecord.user(
+ content: text,
+ format: predefinedFormat,
+ ),
+ );
},
processMessage: (text) async {
await _textRobot.appendMarkdownText(
@@ -467,23 +534,23 @@ class AiWriterCubit extends Cubit<AiWriterState> {
Future<void> _startSuggestingEdits(
AiWriterCommand command,
+ String prompt,
PredefinedFormat? predefinedFormat,
) async {
- if (aiWriterNode == null) {
- return;
- }
final selection = aiWriterNode?.aiWriterSelection;
if (selection == null) {
return;
}
-
- acceptReplacesOriginal = true;
+ if (prompt.isEmpty) {
+ prompt = records.removeAt(0).content;
+ }
final stream = await _aiService.streamCompletion(
objectId: documentId,
- text: await editorState.getMarkdownInSelection(selection),
+ text: prompt,
completionType: command.toCompletionType(),
history: records,
+ sourceIds: selectedSourcesNotifier.value,
onStart: () async {
final transaction = editorState.transaction;
formatSelection(
@@ -507,6 +574,12 @@ class AiWriterCubit extends Cubit<AiWriterState> {
withUpdateSelection: false,
);
_textRobot.start(position: position);
+ records.add(
+ AiWriterRecord.user(
+ content: prompt,
+ format: predefinedFormat,
+ ),
+ );
},
processMessage: (text) async {
await _textRobot.appendMarkdownText(
@@ -560,22 +633,31 @@ class AiWriterCubit extends Cubit<AiWriterState> {
Future<void> _startInforming(
AiWriterCommand command,
+ String prompt,
PredefinedFormat? predefinedFormat,
) async {
- if (aiWriterNode == null) {
- return;
- }
final selection = aiWriterNode?.aiWriterSelection;
if (selection == null) {
return;
}
+ if (prompt.isEmpty) {
+ prompt = records.removeAt(0).content;
+ }
final stream = await _aiService.streamCompletion(
objectId: documentId,
- text: await editorState.getMarkdownInSelection(selection),
+ text: prompt,
completionType: command.toCompletionType(),
history: records,
- onStart: () async {},
+ sourceIds: selectedSourcesNotifier.value,
+ onStart: () async {
+ records.add(
+ AiWriterRecord.user(
+ content: prompt,
+ format: predefinedFormat,
+ ),
+ );
+ },
processMessage: (text) async {
if (state case final GeneratingAiWriterState generatingState) {
emit(
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.dart
index 7dc8ffc04e..f15c2e6d7f 100644
--- 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.dart
@@ -1,3 +1,4 @@
+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_backend/protobuf/flowy-ai/protobuf.dart';
@@ -129,24 +130,22 @@ enum AiRole {
}
class AiWriterRecord extends Equatable {
- const AiWriterRecord({
- required this.role,
- required this.content,
- });
-
const AiWriterRecord.user({
required this.content,
+ required this.format,
}) : role = AiRole.user;
const AiWriterRecord.ai({
required this.content,
- }) : role = AiRole.ai;
+ }) : role = AiRole.ai,
+ format = null;
final AiRole role;
final String content;
+ final PredefinedFormat? format;
@override
- List<Object> get props => [role, content];
+ List<Object?> get props => [role, content, format];
CompletionRecordPB toPB() {
return CompletionRecordPB(
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ai_writer_prompt_input_more_button.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ai_writer_prompt_input_more_button.dart
index 1e2641d796..eefb122a20 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ai_writer_prompt_input_more_button.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ai_writer_prompt_input_more_button.dart
@@ -1,14 +1,12 @@
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/document/presentation/editor_plugins/ai/operations/ai_writer_cubit.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:flowy_infra_ui/style_widget/hover.dart';
import 'package:flutter/material.dart';
-import 'package:flutter_bloc/flutter_bloc.dart';
import '../operations/ai_writer_entities.dart';
@@ -74,8 +72,8 @@ class AiWriterPromptMoreButton extends StatelessWidget {
}
}
-class BottomCommandButtons extends StatelessWidget {
- const BottomCommandButtons({
+class MoreAiWriterCommands extends StatelessWidget {
+ const MoreAiWriterCommands({
super.key,
required this.hasSelection,
required this.editorState,
@@ -155,19 +153,7 @@ class BottomCommandButtons extends StatelessWidget {
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,
- predefinedFormat:
- showPredefinedFormats ? predefinedFormat : null,
- isFirstRun: false,
- );
- },
+ onTap: () => onSelectCommand(command),
);
},
);
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ai_writer_scroll_wrapper.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ai_writer_scroll_wrapper.dart
index 4c04baf557..8a054de1c0 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ai_writer_scroll_wrapper.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/ai/widgets/ai_writer_scroll_wrapper.dart
@@ -145,19 +145,11 @@ class _AiWriterScrollWrapperState extends State<AiWriterScrollWrapper> {
description: LocaleKeys.document_plugins_discardResponse.tr(),
confirmLabel: LocaleKeys.button_discard.tr(),
style: ConfirmPopupStyle.cancelAndOk,
- onConfirm: () {
- Future(() async {
- await aiWriterCubit.stopStream();
- await aiWriterCubit.exit();
- });
- },
+ onConfirm: stopAndExit,
onCancel: () {},
);
} else {
- Future(() async {
- await aiWriterCubit.stopStream();
- await aiWriterCubit.exit();
- });
+ stopAndExit();
}
}
@@ -177,19 +169,11 @@ class _AiWriterScrollWrapperState extends State<AiWriterScrollWrapper> {
description: LocaleKeys.document_plugins_discardResponse.tr(),
confirmLabel: LocaleKeys.button_discard.tr(),
style: ConfirmPopupStyle.cancelAndOk,
- onConfirm: () {
- Future(() async {
- await aiWriterCubit.stopStream();
- await aiWriterCubit.exit();
- });
- },
+ onConfirm: stopAndExit,
onCancel: () {},
);
} else {
- Future(() async {
- await aiWriterCubit.stopStream();
- await aiWriterCubit.exit();
- });
+ stopAndExit();
}
return true;
case LogicalKeyboardKey.keyC
@@ -220,4 +204,11 @@ class _AiWriterScrollWrapperState extends State<AiWriterScrollWrapper> {
}
});
}
+
+ void stopAndExit() {
+ Future(() async {
+ await aiWriterCubit.stopStream();
+ await aiWriterCubit.exit();
+ });
+ }
}
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.dart
index 1904b10934..2eafb0af7c 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
@@ -140,7 +140,7 @@ class MarkdownTextRobot {
await editorState.apply(
transaction,
- options: const ApplyOptions(recordUndo: false),
+ options: const ApplyOptions(recordUndo: false, inMemoryUpdate: true),
);
if (_enableDebug) {