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.

feat: select sources for ai prompt (#6975)

Richard Shiueb966e3ea0783
diff --git a/frontend/appflowy_flutter/lib/mobile/presentation/base/mobile_view_page.dart b/frontend/appflowy_flutter/lib/mobile/presentation/base/mobile_view_page.dart
index 4d4eecbc1d..760911394e 100644
--- a/frontend/appflowy_flutter/lib/mobile/presentation/base/mobile_view_page.dart
+++ b/frontend/appflowy_flutter/lib/mobile/presentation/base/mobile_view_page.dart
@@ -12,6 +12,7 @@ import 'package:appflowy/startup/plugin/plugin.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/user/application/reminder/reminder_bloc.dart';
import 'package:appflowy/workspace/application/favorite/favorite_bloc.dart';
+import 'package:appflowy/workspace/application/user/user_workspace_bloc.dart';
import 'package:appflowy/workspace/application/view/view_bloc.dart';
import 'package:appflowy/workspace/application/view/view_ext.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
@@ -105,6 +106,12 @@ class _MobileViewPageState extends State<MobileViewPage> {
create: (_) =>
ShareBloc(view: view)..add(const ShareEvent.initial()),
),
+ if (state.userProfilePB != null)
+ BlocProvider(
+ create: (_) =>
+ UserWorkspaceBloc(userProfile: state.userProfilePB!)
+ ..add(const UserWorkspaceEvent.initial()),
+ ),
if (view.layout.isDocumentView)
BlocProvider(
create: (_) => DocumentPageStyleBloc(view: view)
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.dart
index 09d7ed2417..5a3f705943 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
@@ -247,6 +247,22 @@ class ChatBloc extends Bloc<ChatEvent, ChatState> {
),
);
},
+ didReceiveChatSettings: (settings) {
+ emit(
+ state.copyWith(selectedSourceIds: settings.ragIds),
+ );
+ },
+ updateSelectedSources: (selectedSourcesIds) async {
+ emit(state.copyWith(selectedSourceIds: selectedSourcesIds));
+
+ final payload = UpdateChatSettingsPB(
+ chatId: ChatId(value: chatId),
+ ragIds: selectedSourcesIds,
+ );
+ await AIEventUpdateChatSettings(payload)
+ .send()
+ .onFailure(Log.error);
+ },
);
},
);
@@ -333,11 +349,23 @@ class ChatBloc extends Bloc<ChatEvent, ChatState> {
}
void _init() async {
- final payload = LoadNextChatMessagePB(
+ final getChatSettingsPayload =
+ AIEventGetChatSettings(ChatId(value: chatId));
+ final getChatSettingsFuture = getChatSettingsPayload.send().fold(
+ (settings) {
+ if (!isClosed) {
+ add(ChatEvent.didReceiveChatSettings(settings: settings));
+ }
+ },
+ Log.error,
+ );
+
+ final loadMessagesPayload = LoadNextChatMessagePB(
chatId: chatId,
limit: Int64(10),
);
- await AIEventLoadNextMessage(payload).send().fold(
+ final loadMessagesFuture =
+ AIEventLoadNextMessage(loadMessagesPayload).send().fold(
(list) {
if (!isClosed) {
final messages = list.messages.map(_createTextMessage).toList();
@@ -346,6 +374,8 @@ class ChatBloc extends Bloc<ChatEvent, ChatState> {
},
(err) => Log.error("Failed to load messages: $err"),
);
+
+ await Future.wait([getChatSettingsFuture, loadMessagesFuture]);
}
bool _isOneTimeMessage(Message message) {
@@ -492,6 +522,14 @@ class ChatBloc extends Bloc<ChatEvent, ChatState> {
@freezed
class ChatEvent with _$ChatEvent {
+ // chat settings
+ const factory ChatEvent.didReceiveChatSettings({
+ required ChatSettingsPB settings,
+ }) = _DidReceiveChatSettings;
+ const factory ChatEvent.updateSelectedSources({
+ required List<String> selectedSourcesIds,
+ }) = _UpdateSelectedSources;
+
// send message
const factory ChatEvent.sendMessage({
required String message,
@@ -528,11 +566,13 @@ class ChatEvent with _$ChatEvent {
@freezed
class ChatState with _$ChatState {
const factory ChatState({
+ required List<String> selectedSourceIds,
required ChatLoadingState loadingState,
required PromptResponseState promptResponseState,
}) = _ChatState;
factory ChatState.initial() => const ChatState(
+ selectedSourceIds: [],
loadingState: ChatLoadingState.loading(),
promptResponseState: PromptResponseState.ready,
);
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.dart
new file mode 100644
index 0000000000..ec6d536463
--- /dev/null
+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/application/chat_select_sources_cubit.dart
@@ -0,0 +1,330 @@
+import 'package:appflowy/workspace/application/view/view_ext.dart';
+import 'package:appflowy/workspace/application/view/view_service.dart';
+import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
+import 'package:appflowy_result/appflowy_result.dart';
+import 'package:bloc/bloc.dart';
+import 'package:flutter/foundation.dart';
+import 'package:freezed_annotation/freezed_annotation.dart';
+
+part 'chat_select_sources_cubit.freezed.dart';
+
+enum SourceSelectedStatus {
+ unselected,
+ selected,
+ partiallySelected;
+
+ bool get isUnselected => this == unselected;
+ bool get isSelected => this == selected;
+ bool get isPartiallySelected => this == partiallySelected;
+}
+
+class ChatSource {
+ ChatSource({
+ required this.view,
+ required this.parentView,
+ required this.children,
+ required bool isExpanded,
+ required SourceSelectedStatus selectedStatus,
+ }) : isExpandedNotifier = ValueNotifier(isExpanded),
+ selectedStatusNotifier = ValueNotifier(selectedStatus);
+
+ final ViewPB view;
+ final ViewPB? parentView;
+ final List<ChatSource> children;
+ final ValueNotifier<bool> isExpandedNotifier;
+ final ValueNotifier<SourceSelectedStatus> selectedStatusNotifier;
+
+ bool get isExpanded => isExpandedNotifier.value;
+ SourceSelectedStatus get selectedStatus => selectedStatusNotifier.value;
+
+ void toggleIsExpanded() {
+ isExpandedNotifier.value = !isExpanded;
+ }
+
+ ChatSource copy() {
+ return ChatSource(
+ view: view,
+ parentView: parentView,
+ children: children.map<ChatSource>((child) => child.copy()).toList(),
+ isExpanded: isExpanded,
+ selectedStatus: selectedStatus,
+ );
+ }
+
+ ChatSource? findChildBySourceId(String sourceId) {
+ if (view.id == sourceId) {
+ return this;
+ }
+ for (final child in children) {
+ final childResult = child.findChildBySourceId(sourceId);
+ if (childResult != null) {
+ return childResult;
+ }
+ }
+ return null;
+ }
+
+ void dispose() {
+ for (final child in children) {
+ child.dispose();
+ }
+ isExpandedNotifier.dispose();
+ selectedStatusNotifier.dispose();
+ }
+}
+
+class ChatSettingsCubit extends Cubit<ChatSettingsState> {
+ ChatSettingsCubit({required this.chatId})
+ : super(ChatSettingsState.initial());
+
+ final String chatId;
+ List<String> selectedSourceIds = [];
+ ChatSource? source;
+ List<ChatSource> selectedSources = [];
+ String filter = '';
+
+ void updateSelectedSources(List<String> newSelectedSourceIds) {
+ selectedSourceIds = [...newSelectedSourceIds];
+ }
+
+ void updateSelectedStatus() {
+ if (source == null) {
+ return;
+ }
+ if (source != null) {
+ _recursiveUpdateSelectedStatus(source!);
+ }
+ for (final source in state.visibleSources) {
+ _recursiveUpdateSelectedStatus(source);
+ }
+ final selected = _buildSelectedSources(source!).toList();
+ emit(state.copyWith(selectedSources: selected));
+ selectedSources
+ ..forEach((e) => e.dispose())
+ ..clear()
+ ..addAll(selected.map((e) => e.copy()));
+ }
+
+ SourceSelectedStatus _recursiveUpdateSelectedStatus(ChatSource chatSource) {
+ SourceSelectedStatus selectedStatus = SourceSelectedStatus.unselected;
+
+ int selectedCount = 0;
+ for (final childSource in chatSource.children) {
+ final childStatus = _recursiveUpdateSelectedStatus(childSource);
+ if (childStatus.isSelected) {
+ selectedCount++;
+ }
+ }
+
+ final isThisSourceSelected = selectedSourceIds.contains(chatSource.view.id);
+ final areAllChildrenSelectedOrNoChildren =
+ chatSource.children.length == selectedCount;
+ final isAnyChildNotUnselected =
+ chatSource.children.any((e) => !e.selectedStatus.isUnselected);
+
+ if (isThisSourceSelected && areAllChildrenSelectedOrNoChildren) {
+ selectedStatus = SourceSelectedStatus.selected;
+ } else if (isThisSourceSelected || isAnyChildNotUnselected) {
+ selectedStatus = SourceSelectedStatus.partiallySelected;
+ }
+
+ chatSource.selectedStatusNotifier.value = selectedStatus;
+ return selectedStatus;
+ }
+
+ void refreshSources(ViewPB view) async {
+ filter = "";
+ final newSource = await _recursiveBuild(view, null);
+ final selected = _buildSelectedSources(newSource).toList();
+
+ newSource.toggleIsExpanded();
+
+ emit(
+ state.copyWith(
+ selectedSources: selected,
+ visibleSources: [newSource],
+ ),
+ );
+
+ source?.dispose();
+ source = newSource.copy();
+
+ selectedSources
+ ..forEach((e) => e.dispose())
+ ..clear()
+ ..addAll(selected.map((e) => e.copy()));
+ }
+
+ Future<ChatSource> _recursiveBuild(ViewPB view, ViewPB? parentView) async {
+ SourceSelectedStatus selectedStatus = SourceSelectedStatus.unselected;
+ final isThisSourceSelected = selectedSourceIds.contains(view.id);
+
+ final childrenViews =
+ await ViewBackendService.getChildViews(viewId: view.id).toNullable();
+
+ int selectedCount = 0;
+ final children = <ChatSource>[];
+
+ if (childrenViews != null) {
+ for (final childView in childrenViews) {
+ final childChatSource = await _recursiveBuild(childView, view);
+ if (childChatSource.selectedStatus.isSelected) {
+ selectedCount++;
+ }
+ children.add(childChatSource);
+ }
+
+ final areAllChildrenSelectedOrNoChildren =
+ children.length == selectedCount;
+ final isAnyChildNotUnselected =
+ children.any((e) => !e.selectedStatus.isUnselected);
+
+ if (isThisSourceSelected && areAllChildrenSelectedOrNoChildren) {
+ selectedStatus = SourceSelectedStatus.selected;
+ } else if (isThisSourceSelected || isAnyChildNotUnselected) {
+ selectedStatus = SourceSelectedStatus.partiallySelected;
+ }
+ } else if (isThisSourceSelected) {
+ selectedStatus = SourceSelectedStatus.selected;
+ }
+
+ return ChatSource(
+ view: view,
+ parentView: parentView,
+ children: children,
+ isExpanded: false,
+ selectedStatus: selectedStatus,
+ );
+ }
+
+ void updateFilter(String filter) {
+ this.filter = filter;
+ for (final source in state.visibleSources) {
+ source.dispose();
+ }
+ if (source == null) {
+ emit(ChatSettingsState.initial());
+ } else {
+ final selected =
+ selectedSources.map(_buildSearchResults).nonNulls.toList();
+ final visible = [_buildSearchResults(source!)].nonNulls.toList();
+ emit(
+ state.copyWith(
+ selectedSources: selected,
+ visibleSources: visible,
+ ),
+ );
+ }
+ }
+
+ /// traverse tree to build up search query
+ ChatSource? _buildSearchResults(ChatSource chatSource) {
+ final isVisible = chatSource.view.nameOrDefault
+ .toLowerCase()
+ .contains(filter.toLowerCase());
+
+ final childrenResults = <ChatSource>[];
+ for (final childSource in chatSource.children) {
+ final childResult = _buildSearchResults(childSource);
+ if (childResult != null) {
+ childrenResults.add(childResult);
+ }
+ }
+
+ return isVisible || childrenResults.isNotEmpty
+ ? ChatSource(
+ view: chatSource.view,
+ parentView: chatSource.parentView,
+ children: childrenResults,
+ isExpanded: chatSource.isExpanded,
+ selectedStatus: chatSource.selectedStatus,
+ )
+ : null;
+ }
+
+ /// traverse tree to build up selected sources
+ Iterable<ChatSource> _buildSelectedSources(ChatSource chatSource) {
+ final children = <ChatSource>[];
+
+ for (final childSource in chatSource.children) {
+ children.addAll(_buildSelectedSources(childSource));
+ }
+
+ return chatSource.selectedStatus.isUnselected
+ ? children
+ : [
+ ChatSource(
+ view: chatSource.view,
+ parentView: chatSource.parentView,
+ children: children,
+ selectedStatus: chatSource.selectedStatus,
+ isExpanded: true,
+ ),
+ ];
+ }
+
+ void toggleSelectedStatus(ChatSource chatSource) {
+ final allIds = _recursiveGetSourceIds(chatSource);
+
+ if (chatSource.selectedStatus.isUnselected ||
+ chatSource.selectedStatus.isPartiallySelected &&
+ !chatSource.view.layout.isDocumentView) {
+ for (final id in allIds) {
+ if (!selectedSourceIds.contains(id)) {
+ selectedSourceIds.add(id);
+ }
+ }
+ } else {
+ for (final id in allIds) {
+ if (selectedSourceIds.contains(id)) {
+ selectedSourceIds.remove(id);
+ }
+ }
+ }
+ }
+
+ void toggleIsExpanded(ChatSource chatSource, bool isSelectedSection) {
+ chatSource.toggleIsExpanded();
+ if (isSelectedSection) {
+ for (final source in selectedSources) {
+ source.findChildBySourceId(chatSource.view.id)?.toggleIsExpanded();
+ }
+ } else {
+ source?.findChildBySourceId(chatSource.view.id)?.toggleIsExpanded();
+ }
+ }
+
+ List<String> _recursiveGetSourceIds(ChatSource chatSource) {
+ return [
+ if (chatSource.view.layout.isDocumentView && !chatSource.view.isSpace)
+ chatSource.view.id,
+ for (final childSource in chatSource.children)
+ ..._recursiveGetSourceIds(childSource),
+ ];
+ }
+
+ @override
+ Future<void> close() {
+ source?.dispose();
+ for (final child in state.selectedSources) {
+ child.dispose();
+ }
+ for (final child in state.visibleSources) {
+ child.dispose();
+ }
+ return super.close();
+ }
+}
+
+@freezed
+class ChatSettingsState with _$ChatSettingsState {
+ const factory ChatSettingsState({
+ required List<ChatSource> visibleSources,
+ required List<ChatSource> selectedSources,
+ }) = _ChatSettingsState;
+
+ factory ChatSettingsState.initial() => const ChatSettingsState(
+ visibleSources: [],
+ selectedSources: [],
+ );
+}
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 11f772c60a..ed9757e342 100644
--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/chat_page.dart
+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/chat_page.dart
@@ -3,11 +3,6 @@ import 'dart:io';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/mobile/application/mobile_router.dart';
-import 'package:appflowy/plugins/ai_chat/application/chat_bloc.dart';
-import 'package:appflowy/plugins/ai_chat/application/chat_entity.dart';
-import 'package:appflowy/plugins/ai_chat/application/ai_prompt_input_bloc.dart';
-import 'package:appflowy/plugins/ai_chat/application/chat_message_stream.dart';
-import 'package:appflowy/plugins/ai_chat/presentation/chat_related_question.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/application/tabs/tabs_bloc.dart';
import 'package:appflowy/workspace/application/view/view_ext.dart';
@@ -28,10 +23,15 @@ 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_message_stream.dart';
import 'presentation/animated_chat_list.dart';
import 'presentation/chat_input/desktop_ai_prompt_input.dart';
import 'presentation/chat_input/mobile_ai_prompt_input.dart';
+import 'presentation/chat_related_question.dart';
import 'presentation/chat_welcome_page.dart';
import 'presentation/layout_define.dart';
import 'presentation/message/ai_text_message.dart';
@@ -287,36 +287,52 @@ class _ChatContentPage extends StatelessWidget {
return state.promptResponseState == PromptResponseState.ready;
},
builder: (context, canSendMessage) {
+ final chatBloc = context.read<ChatBloc>();
+
return UniversalPlatform.isDesktop
? DesktopAIPromptInput(
chatId: view.id,
+ isStreaming: !canSendMessage,
+ onStopStreaming: () {
+ chatBloc.add(const ChatEvent.stopStream());
+ },
onSubmitted: (text, metadata) {
- context.read<ChatBloc>().add(
- ChatEvent.sendMessage(
- message: text,
- metadata: metadata,
- ),
- );
+ chatBloc.add(
+ ChatEvent.sendMessage(
+ message: text,
+ metadata: metadata,
+ ),
+ );
+ },
+ onUpdateSelectedSources: (ids) {
+ chatBloc.add(
+ ChatEvent.updateSelectedSources(
+ selectedSourcesIds: ids,
+ ),
+ );
},
- isStreaming: !canSendMessage,
- onStopStreaming: () => context
- .read<ChatBloc>()
- .add(const ChatEvent.stopStream()),
)
: MobileAIPromptInput(
chatId: view.id,
+ isStreaming: !canSendMessage,
+ onStopStreaming: () {
+ chatBloc.add(const ChatEvent.stopStream());
+ },
onSubmitted: (text, metadata) {
- context.read<ChatBloc>().add(
- ChatEvent.sendMessage(
- message: text,
- metadata: metadata,
- ),
- );
+ chatBloc.add(
+ ChatEvent.sendMessage(
+ message: text,
+ metadata: metadata,
+ ),
+ );
+ },
+ onUpdateSelectedSources: (ids) {
+ chatBloc.add(
+ ChatEvent.updateSelectedSources(
+ selectedSourcesIds: ids,
+ ),
+ );
},
- isStreaming: !canSendMessage,
- onStopStreaming: () => context
- .read<ChatBloc>()
- .add(const ChatEvent.stopStream()),
);
},
),
diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/desktop_ai_prompt_input.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/desktop_ai_prompt_input.dart
index b37d2e10d2..fd04be6a77 100644
--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/desktop_ai_prompt_input.dart
+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/desktop_ai_prompt_input.dart
@@ -10,13 +10,13 @@ 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 'package:universal_platform/universal_platform.dart';
-import 'chat_mention_page_menu.dart';
import '../layout_define.dart';
import 'ai_prompt_buttons.dart';
import 'chat_input_file.dart';
import 'chat_input_span.dart';
+import 'chat_mention_page_menu.dart';
+import 'select_sources_menu.dart';
class DesktopAIPromptInput extends StatefulWidget {
const DesktopAIPromptInput({
@@ -25,12 +25,14 @@ class DesktopAIPromptInput extends StatefulWidget {
required this.isStreaming,
required this.onStopStreaming,
required this.onSubmitted,
+ required this.onUpdateSelectedSources,
});
final String chatId;
final bool isStreaming;
final void Function() onStopStreaming;
final void Function(String, Map<String, dynamic>) onSubmitted;
+ final void Function(List<String>) onUpdateSelectedSources;
@override
State<DesktopAIPromptInput> createState() => _DesktopAIPromptInputState();
@@ -147,12 +149,15 @@ class _DesktopAIPromptInputState extends State<DesktopAIPromptInput> {
top: null,
child: TextFieldTapRegion(
child: _PromptBottomActions(
+ chatId: widget.chatId,
textController: textController,
overlayController: overlayController,
focusNode: focusNode,
sendButtonState: sendButtonState,
onSendPressed: handleSendPressed,
onStopStreaming: widget.onStopStreaming,
+ onUpdateSelectedSources:
+ widget.onUpdateSelectedSources,
),
),
),
@@ -207,6 +212,10 @@ class _DesktopAIPromptInputState extends State<DesktopAIPromptInput> {
setState(() => updateSendButtonState());
// handle text and selection changes ONLY when mentioning a page
+
+ // disable mention
+ return;
+ // ignore: dead_code
if (!overlayController.isShowing ||
inputControlCubit.filterStartPosition == -1) {
return;
@@ -292,12 +301,12 @@ class _DesktopAIPromptInputState extends State<DesktopAIPromptInput> {
AIType.appflowyAI => LocaleKeys.chat_inputMessageHint.tr(),
AIType.localAI => LocaleKeys.chat_inputLocalAIMessageHint.tr()
},
- onStartMentioningPage: () {
- WidgetsBinding.instance.addPostFrameCallback((_) {
- inputControlCubit.startSearching(textController.value);
- overlayController.show();
- });
- },
+ // onStartMentioningPage: () {
+ // WidgetsBinding.instance.addPostFrameCallback((_) {
+ // inputControlCubit.startSearching(textController.value);
+ // overlayController.show();
+ // });
+ // },
);
},
),
@@ -353,14 +362,14 @@ class _PromptTextField extends StatefulWidget {
required this.cubit,
required this.textController,
required this.textFieldFocusNode,
- required this.onStartMentioningPage,
+ // required this.onStartMentioningPage,
this.hintText = "",
});
final ChatInputControlCubit cubit;
final TextEditingController textController;
final FocusNode textFieldFocusNode;
- final void Function() onStartMentioningPage;
+ // final void Function() onStartMentioningPage;
final String hintText;
@override
@@ -373,13 +382,13 @@ class _PromptTextFieldState extends State<_PromptTextField> {
@override
void initState() {
super.initState();
- widget.textFieldFocusNode.onKeyEvent = handleKeyEvent;
+ // widget.textFieldFocusNode.onKeyEvent = handleKeyEvent;
widget.textController.addListener(onTextChanged);
}
@override
void dispose() {
- widget.textFieldFocusNode.onKeyEvent = null;
+ // widget.textFieldFocusNode.onKeyEvent = null;
widget.textController.removeListener(onTextChanged);
super.dispose();
}
@@ -424,12 +433,12 @@ class _PromptTextFieldState extends State<_PromptTextField> {
);
}
- KeyEventResult handleKeyEvent(FocusNode node, KeyEvent event) {
- if (event.character == '@') {
- widget.onStartMentioningPage();
- }
- return KeyEventResult.ignored;
- }
+ // KeyEventResult handleKeyEvent(FocusNode node, KeyEvent event) {
+ // if (event.character == '@') {
+ // widget.onStartMentioningPage();
+ // }
+ // return KeyEventResult.ignored;
+ // }
void onTextChanged() {
setState(
@@ -469,20 +478,24 @@ class _FocusNextItemIntent extends Intent {
class _PromptBottomActions extends StatelessWidget {
const _PromptBottomActions({
+ required this.chatId,
required this.textController,
required this.overlayController,
required this.focusNode,
required this.sendButtonState,
required this.onSendPressed,
required this.onStopStreaming,
+ required this.onUpdateSelectedSources,
});
+ final String chatId;
final TextEditingController textController;
final OverlayPortalController overlayController;
final FocusNode focusNode;
final SendButtonState sendButtonState;
final void Function() onSendPressed;
final void Function() onStopStreaming;
+ final void Function(List<String>) onUpdateSelectedSources;
@override
Widget build(BuildContext context) {
@@ -496,11 +509,17 @@ class _PromptBottomActions extends StatelessWidget {
children: [
// predefinedFormatButton(),
const Spacer(),
- _mentionButton(context),
- const HSpace(
- DesktopAIPromptSizes.actionBarButtonSpacing,
- ),
- if (UniversalPlatform.isDesktop && state.supportChatWithFile) ...[
+ if (state.aiType == AIType.appflowyAI) ...[
+ _selectSourcesButton(context),
+ const HSpace(
+ DesktopAIPromptSizes.actionBarButtonSpacing,
+ ),
+ ],
+ // _mentionButton(context),
+ // const HSpace(
+ // DesktopAIPromptSizes.actionBarButtonSpacing,
+ // ),
+ if (state.supportChatWithFile) ...[
_attachmentButton(context),
const HSpace(
DesktopAIPromptSizes.actionBarButtonSpacing,
@@ -514,28 +533,35 @@ class _PromptBottomActions extends StatelessWidget {
);
}
- Widget _mentionButton(BuildContext context) {
- 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();
- });
- },
+ Widget _selectSourcesButton(BuildContext context) {
+ return PromptInputDesktopSelectSourcesButton(
+ chatId: chatId,
+ onUpdateSelectedSources: onUpdateSelectedSources,
);
}
+ // Widget _mentionButton(BuildContext context) {
+ // 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();
+ // });
+ // },
+ // );
+ // }
+
Widget _attachmentButton(BuildContext context) {
return PromptInputAttachmentButton(
onTap: () async {
diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/mobile_ai_prompt_input.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/mobile_ai_prompt_input.dart
index e2ec9d5ab9..07f2860f00 100644
--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/mobile_ai_prompt_input.dart
+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/mobile_ai_prompt_input.dart
@@ -13,6 +13,7 @@ import 'ai_prompt_buttons.dart';
import 'chat_input_file.dart';
import 'chat_input_span.dart';
import 'chat_mention_page_bottom_sheet.dart';
+import 'select_sources_bottom_sheet.dart';
class MobileAIPromptInput extends StatefulWidget {
const MobileAIPromptInput({
@@ -21,12 +22,14 @@ class MobileAIPromptInput extends StatefulWidget {
required this.isStreaming,
required this.onStopStreaming,
required this.onSubmitted,
+ required this.onUpdateSelectedSources,
});
final String chatId;
final bool isStreaming;
final void Function() onStopStreaming;
final void Function(String, Map<String, dynamic>) onSubmitted;
+ final void Function(List<String>) onUpdateSelectedSources;
@override
State<MobileAIPromptInput> createState() => _MobileAIPromptInputState();
@@ -44,7 +47,7 @@ class _MobileAIPromptInputState extends State<MobileAIPromptInput> {
super.initState();
textController.addListener(handleTextControllerChange);
- focusNode.onKeyEvent = handleKeyEvent;
+ // focusNode.onKeyEvent = handleKeyEvent;
WidgetsBinding.instance.addPostFrameCallback((_) {
focusNode.requestFocus();
@@ -119,16 +122,16 @@ class _MobileAIPromptInputState extends State<MobileAIPromptInput> {
minHeight: MobileAIPromptSizes.textFieldMinHeight,
maxHeight: 220,
),
- padding:
- const EdgeInsetsDirectional.fromSTEB(0, 8.0, 12.0, 8.0),
child: IntrinsicHeight(
child: Row(
children: [
const HSpace(8.0),
- Expanded(child: inputTextField(context)),
- mentionButton(),
- const HSpace(6.0),
+ leadingButtons(context),
+ Expanded(
+ child: inputTextField(context),
+ ),
sendButton(),
+ const HSpace(12.0),
],
),
),
@@ -170,18 +173,18 @@ class _MobileAIPromptInputState extends State<MobileAIPromptInput> {
if (textController.value.isComposingRangeValid) {
return;
}
- inputControlCubit.updateInputText(textController.text);
+ // inputControlCubit.updateInputText(textController.text);
setState(() => updateSendButtonState());
}
- KeyEventResult handleKeyEvent(FocusNode node, KeyEvent event) {
- if (event.character == '@') {
- WidgetsBinding.instance.addPostFrameCallback((_) {
- mentionPage(context);
- });
- }
- return KeyEventResult.ignored;
- }
+ // KeyEventResult handleKeyEvent(FocusNode node, KeyEvent event) {
+ // if (event.character == '@') {
+ // WidgetsBinding.instance.addPostFrameCallback((_) {
+ // mentionPage(context);
+ // });
+ // }
+ // return KeyEventResult.ignored;
+ // }
Future<void> mentionPage(BuildContext context) async {
// if the focus node is on focus, unfocus it for better animation
@@ -259,28 +262,31 @@ class _MobileAIPromptInputState extends State<MobileAIPromptInput> {
);
}
- Widget mentionButton() {
- return Align(
+ Widget leadingButtons(BuildContext context) {
+ return Container(
alignment: Alignment.bottomCenter,
- child: PromptInputMentionButton(
- iconSize: MobileAIPromptSizes.mentionIconSize,
- buttonSize: MobileAIPromptSizes.sendButtonSize,
- onTap: () {
- textController.text += '@';
- if (!focusNode.hasFocus) {
- focusNode.requestFocus();
- }
- WidgetsBinding.instance.addPostFrameCallback((_) {
- mentionPage(context);
- });
- },
+ padding: const EdgeInsets.only(bottom: 8.0),
+ child: _LeadingActions(
+ chatId: widget.chatId,
+ textController: textController,
+ // onMention: () {
+ // textController.text += '@';
+ // if (!focusNode.hasFocus) {
+ // focusNode.requestFocus();
+ // }
+ // WidgetsBinding.instance.addPostFrameCallback((_) {
+ // mentionPage(context);
+ // });
+ // },
+ onUpdateSelectedSources: widget.onUpdateSelectedSources,
),
);
}
Widget sendButton() {
- return Align(
+ return Container(
alignment: Alignment.bottomCenter,
+ padding: const EdgeInsets.only(bottom: 8.0),
child: PromptInputSendButton(
buttonSize: MobileAIPromptSizes.sendButtonSize,
iconSize: MobileAIPromptSizes.sendButtonSize,
@@ -291,3 +297,26 @@ class _MobileAIPromptInputState extends State<MobileAIPromptInput> {
);
}
}
+
+class _LeadingActions extends StatelessWidget {
+ const _LeadingActions({
+ required this.chatId,
+ required this.textController,
+ required this.onUpdateSelectedSources,
+ });
+
+ final String chatId;
+ final TextEditingController textController;
+ final void Function(List<String>) onUpdateSelectedSources;
+
+ @override
+ Widget build(BuildContext context) {
+ return Material(
+ color: Theme.of(context).cardColor,
+ child: PromptInputMobileSelectSourcesButton(
+ chatId: chatId,
+ onUpdateSelectedSources: onUpdateSelectedSources,
+ ),
+ );
+ }
+}
diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/select_sources_bottom_sheet.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/select_sources_bottom_sheet.dart
new file mode 100644
index 0000000000..3cc35c0c4a
--- /dev/null
+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/select_sources_bottom_sheet.dart
@@ -0,0 +1,271 @@
+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';
+import 'package:appflowy/workspace/application/user/user_workspace_bloc.dart';
+import 'package:appflowy/workspace/application/view/view_ext.dart';
+import 'package:appflowy/workspace/presentation/home/menu/view/view_item.dart';
+import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.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 'select_sources_menu.dart';
+
+class PromptInputMobileSelectSourcesButton extends StatefulWidget {
+ const PromptInputMobileSelectSourcesButton({
+ super.key,
+ required this.chatId,
+ required this.onUpdateSelectedSources,
+ });
+
+ final String chatId;
+ final void Function(List<String>) onUpdateSelectedSources;
+
+ @override
+ State<PromptInputMobileSelectSourcesButton> createState() =>
+ _PromptInputMobileSelectSourcesButtonState();
+}
+
+class _PromptInputMobileSelectSourcesButtonState
+ extends State<PromptInputMobileSelectSourcesButton> {
+ late final cubit = ChatSettingsCubit(chatId: widget.chatId);
+
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ cubit.updateSelectedSources(
+ context.read<ChatBloc>().state.selectedSourceIds,
+ );
+ });
+ }
+
+ @override
+ void dispose() {
+ cubit.close();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return BlocBuilder<UserWorkspaceBloc, UserWorkspaceState>(
+ builder: (context, state) {
+ final userProfile = context.read<UserWorkspaceBloc>().userProfile;
+ final workspaceId = state.currentWorkspace?.workspaceId ?? '';
+ return MultiBlocProvider(
+ providers: [
+ BlocProvider(
+ key: ValueKey(workspaceId),
+ create: (context) => SpaceBloc(
+ userProfile: userProfile,
+ workspaceId: workspaceId,
+ )..add(const SpaceEvent.initial(openFirstPage: false)),
+ ),
+ BlocProvider.value(
+ value: cubit,
+ ),
+ ],
+ child: BlocSelector<SpaceBloc, SpaceState, ViewPB?>(
+ selector: (state) => state.currentSpace,
+ builder: (context, spaceView) {
+ 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: () {
+ if (spaceView != null) {
+ context
+ .read<ChatSettingsCubit>()
+ .refreshSources(spaceView);
+ }
+ 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,
+ onUpdateSelectedSources:
+ widget.onUpdateSelectedSources,
+ ),
+ ),
+ );
+ },
+ builder: (context) => const SizedBox.shrink(),
+ );
+ },
+ ),
+ );
+ },
+ ),
+ );
+ },
+ );
+ }
+}
+
+class _MobileSelectSourcesSheetBody extends StatefulWidget {
+ const _MobileSelectSourcesSheetBody({
+ required this.scrollController,
+ required this.onUpdateSelectedSources,
+ });
+
+ final ScrollController scrollController;
+ final void Function(List<String>) onUpdateSelectedSources;
+
+ @override
+ State<_MobileSelectSourcesSheetBody> createState() =>
+ _MobileSelectSourcesSheetBodyState();
+}
+
+class _MobileSelectSourcesSheetBodyState
+ extends State<_MobileSelectSourcesSheetBody> {
+ final textController = TextEditingController();
+
+ @override
+ void dispose() {
+ textController.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return CustomScrollView(
+ controller: widget.scrollController,
+ shrinkWrap: true,
+ slivers: [
+ SliverPersistentHeader(
+ pinned: true,
+ delegate: _Header(
+ child: ColoredBox(
+ color: Theme.of(context).cardColor,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ const DragHandle(),
+ SizedBox(
+ height: 44.0,
+ child: Center(
+ child: FlowyText.medium(
+ LocaleKeys.chat_selectSources.tr(),
+ fontSize: 16.0,
+ ),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 16.0,
+ vertical: 8.0,
+ ),
+ child: SizedBox(
+ height: 44.0,
+ child: FlowySearchTextField(
+ controller: textController,
+ onChanged: (value) => context
+ .read<ChatSettingsCubit>()
+ .updateFilter(value),
+ ),
+ ),
+ ),
+ const Divider(height: 0.5, thickness: 0.5),
+ ],
+ ),
+ ),
+ ),
+ ),
+ BlocBuilder<ChatSettingsCubit, ChatSettingsState>(
+ builder: (context, state) {
+ return SliverList(
+ delegate: SliverChildBuilderDelegate(
+ childCount: state.visibleSources.length,
+ (context, index) {
+ return ChatSourceTreeItem(
+ key: ValueKey(
+ 'visible_select_sources_tree_item_${state.visibleSources[index].view.id}',
+ ),
+ chatSource: state.visibleSources[index],
+ level: 0,
+ isSelectedSection: false,
+ onSelected: (chatSource) {
+ final cubit = context.read<ChatSettingsCubit>();
+ cubit.toggleSelectedStatus(chatSource);
+ widget.onUpdateSelectedSources(cubit.selectedSourceIds);
+ },
+ height: 40.0,
+ visibilityGetter: (view) {
+ if (view.id == context.read<ChatSettingsCubit>().chatId) {
+ return IgnoreViewType.hide;
+ }
+
+ return view.layout.isDocumentView
+ ? IgnoreViewType.none
+ : IgnoreViewType.disable;
+ },
+ );
+ },
+ ),
+ );
+ },
+ ),
+ ],
+ );
+ }
+}
+
+class _Header extends SliverPersistentHeaderDelegate {
+ const _Header({
+ required this.child,
+ });
+
+ final Widget child;
+
+ @override
+ Widget build(
+ BuildContext context,
+ double shrinkOffset,
+ bool overlapsContent,
+ ) {
+ return child;
+ }
+
+ @override
+ double get maxExtent => 120.5;
+
+ @override
+ double get minExtent => 120.5;
+
+ @override
+ bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) {
+ return false;
+ }
+}
diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/select_sources_menu.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/select_sources_menu.dart
new file mode 100644
index 0000000000..34a426884e
--- /dev/null
+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/select_sources_menu.dart
@@ -0,0 +1,521 @@
+import 'package:appflowy/generated/flowy_svgs.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/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';
+import 'package:appflowy/workspace/presentation/home/menu/sidebar/space/shared_widget.dart';
+import 'package:appflowy/workspace/presentation/home/menu/view/view_item.dart';
+import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
+import 'package:flowy_infra/theme_extension.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 'chat_mention_page_menu.dart';
+
+class PromptInputDesktopSelectSourcesButton extends StatefulWidget {
+ const PromptInputDesktopSelectSourcesButton({
+ super.key,
+ required this.chatId,
+ required this.onUpdateSelectedSources,
+ });
+
+ final String chatId;
+ final void Function(List<String>) onUpdateSelectedSources;
+
+ @override
+ State<PromptInputDesktopSelectSourcesButton> createState() =>
+ _PromptInputDesktopSelectSourcesButtonState();
+}
+
+class _PromptInputDesktopSelectSourcesButtonState
+ extends State<PromptInputDesktopSelectSourcesButton> {
+ late final cubit = ChatSettingsCubit(chatId: widget.chatId);
+ final popoverController = PopoverController();
+
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ cubit.updateSelectedSources(
+ context.read<ChatBloc>().state.selectedSourceIds,
+ );
+ });
+ }
+
+ @override
+ void dispose() {
+ cubit.close();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final userWorkspaceBloc = context.read<UserWorkspaceBloc>();
+ final userProfile = userWorkspaceBloc.userProfile;
+ final workspaceId =
+ userWorkspaceBloc.state.currentWorkspace?.workspaceId ?? '';
+
+ return MultiBlocProvider(
+ providers: [
+ BlocProvider(
+ create: (context) => SpaceBloc(
+ userProfile: userProfile,
+ workspaceId: workspaceId,
+ )..add(const SpaceEvent.initial(openFirstPage: false)),
+ ),
+ BlocProvider.value(
+ value: cubit,
+ ),
+ ],
+ child: BlocSelector<SpaceBloc, SpaceState, ViewPB?>(
+ selector: (state) => state.currentSpace,
+ builder: (context, spaceView) {
+ return BlocListener<ChatBloc, ChatState>(
+ listener: (context, state) {
+ cubit
+ ..updateSelectedSources(state.selectedSourceIds)
+ ..updateSelectedStatus();
+ },
+ 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: () {
+ if (spaceView != null) {
+ context.read<ChatSettingsCubit>().refreshSources(spaceView);
+ }
+ },
+ onClose: () {
+ if (spaceView != null) {
+ context.read<ChatSettingsCubit>().refreshSources(spaceView);
+ }
+ },
+ popupBuilder: (_) {
+ return BlocProvider.value(
+ value: context.read<ChatSettingsCubit>(),
+ child: _PopoverContent(
+ onUpdateSelectedSources: widget.onUpdateSelectedSources,
+ ),
+ );
+ },
+ child: _IndicatorButton(
+ onTap: () => popoverController.show(),
+ ),
+ ),
+ );
+ },
+ ),
+ );
+ }
+}
+
+class _IndicatorButton extends StatelessWidget {
+ const _IndicatorButton({
+ required this.onTap,
+ });
+
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ return GestureDetector(
+ onTap: onTap,
+ behavior: HitTestBehavior.opaque,
+ child: SizedBox(
+ height: 24,
+ child: FlowyHover(
+ style: const HoverStyle(
+ borderRadius: BorderRadius.all(Radius.circular(8)),
+ ),
+ child: Padding(
+ padding: const EdgeInsetsDirectional.fromSTEB(4, 4, 2, 4),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ FlowySvg(
+ FlowySvgs.ai_page_s,
+ color: Theme.of(context).iconTheme.color,
+ ),
+ const HSpace(2.0),
+ BlocBuilder<ChatBloc, ChatState>(
+ builder: (context, state) {
+ return FlowyText(
+ state.selectedSourceIds.length.toString(),
+ fontSize: 14,
+ figmaLineHeight: 16,
+ color: Theme.of(context).hintColor,
+ );
+ },
+ ),
+ const HSpace(2.0),
+ FlowySvg(
+ FlowySvgs.ai_source_drop_down_s,
+ color: Theme.of(context).hintColor,
+ size: const Size.square(10),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+class _PopoverContent extends StatelessWidget {
+ const _PopoverContent({
+ required this.onUpdateSelectedSources,
+ });
+
+ final void Function(List<String>) onUpdateSelectedSources;
+
+ @override
+ Widget build(BuildContext context) {
+ return BlocBuilder<ChatSettingsCubit, ChatSettingsState>(
+ builder: (context, state) {
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(8, 12, 8, 8),
+ child: SpaceSearchField(
+ width: 600,
+ onSearch: (context, value) =>
+ context.read<ChatSettingsCubit>().updateFilter(value),
+ ),
+ ),
+ _buildDivider(),
+ Flexible(
+ child: ListView(
+ shrinkWrap: true,
+ padding: const EdgeInsets.fromLTRB(8, 4, 8, 12),
+ children: [
+ ..._buildSelectedSources(context, state),
+ if (state.selectedSources.isNotEmpty &&
+ state.visibleSources.isNotEmpty)
+ Padding(
+ padding: const EdgeInsets.symmetric(vertical: 4.0),
+ child: _buildDivider(),
+ ),
+ ..._buildVisibleSources(context, state),
+ ],
+ ),
+ ),
+ ],
+ );
+ },
+ );
+ }
+
+ Widget _buildDivider() {
+ return const Divider(
+ height: 1.0,
+ thickness: 1.0,
+ indent: 8.0,
+ endIndent: 8.0,
+ );
+ }
+
+ Iterable<Widget> _buildSelectedSources(
+ BuildContext context,
+ ChatSettingsState state,
+ ) {
+ return state.selectedSources.map(
+ (e) => ChatSourceTreeItem(
+ key: ValueKey(
+ 'selected_select_sources_tree_item_${e.view.id}',
+ ),
+ chatSource: e,
+ level: 0,
+ isSelectedSection: true,
+ onSelected: (chatSource) {
+ final cubit = context.read<ChatSettingsCubit>();
+ cubit.toggleSelectedStatus(chatSource);
+ onUpdateSelectedSources(cubit.selectedSourceIds);
+ },
+ height: 30.0,
+ visibilityGetter: (view) {
+ if (view.id == context.read<ChatSettingsCubit>().chatId) {
+ return IgnoreViewType.hide;
+ }
+
+ return view.layout.isDocumentView
+ ? IgnoreViewType.none
+ : IgnoreViewType.disable;
+ },
+ ),
+ );
+ }
+
+ Iterable<Widget> _buildVisibleSources(
+ BuildContext context,
+ ChatSettingsState state,
+ ) {
+ return state.visibleSources.map(
+ (e) => ChatSourceTreeItem(
+ key: ValueKey(
+ 'visible_select_sources_tree_item_${e.view.id}',
+ ),
+ chatSource: e,
+ level: 0,
+ isSelectedSection: false,
+ onSelected: (chatSource) {
+ final cubit = context.read<ChatSettingsCubit>();
+ cubit.toggleSelectedStatus(chatSource);
+ onUpdateSelectedSources(cubit.selectedSourceIds);
+ },
+ height: 30.0,
+ visibilityGetter: (view) {
+ if (view.id == context.read<ChatSettingsCubit>().chatId) {
+ return IgnoreViewType.hide;
+ }
+
+ return view.layout.isDocumentView
+ ? IgnoreViewType.none
+ : IgnoreViewType.disable;
+ },
+ ),
+ );
+ }
+}
+
+class ChatSourceTreeItem extends StatefulWidget {
+ const ChatSourceTreeItem({
+ super.key,
+ required this.chatSource,
+ required this.level,
+ required this.isSelectedSection,
+ required this.onSelected,
+ required this.height,
+ this.visibilityGetter,
+ });
+
+ final ChatSource chatSource;
+
+ /// nested level of the view item
+ final int level;
+
+ final bool isSelectedSection;
+
+ final void Function(ChatSource chatSource) onSelected;
+
+ final double height;
+
+ final IgnoreViewType Function(ViewPB view)? visibilityGetter;
+
+ @override
+ State<ChatSourceTreeItem> createState() => _ChatSourceTreeItemState();
+}
+
+class _ChatSourceTreeItemState extends State<ChatSourceTreeItem> {
+ @override
+ Widget build(BuildContext context) {
+ final child = SizedBox(
+ height: widget.height,
+ child: ChatSourceTreeItemInner(
+ chatSource: widget.chatSource,
+ level: widget.level,
+ isSelectedSection: widget.isSelectedSection,
+ onSelected: widget.onSelected,
+ ),
+ );
+
+ final viewVisibility =
+ widget.visibilityGetter?.call(widget.chatSource.view) ??
+ IgnoreViewType.none;
+
+ final disabledEnabledChild = viewVisibility == IgnoreViewType.disable
+ ? Opacity(
+ opacity: 0.5,
+ child: MouseRegion(
+ cursor: SystemMouseCursors.forbidden,
+ child: IgnorePointer(child: child),
+ ),
+ )
+ : child;
+
+ return ValueListenableBuilder(
+ valueListenable: widget.chatSource.isExpandedNotifier,
+ builder: (context, isExpanded, child) {
+ // filter the child views that should be ignored
+ final childViews = [...widget.chatSource.children];
+ if (widget.visibilityGetter != null) {
+ childViews.retainWhere(
+ (v) => widget.visibilityGetter!(v.view) != IgnoreViewType.hide,
+ );
+ }
+
+ if (!isExpanded || childViews.isEmpty) {
+ return disabledEnabledChild;
+ }
+
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ disabledEnabledChild,
+ ...childViews.map(
+ (childSource) => ChatSourceTreeItem(
+ key: ValueKey(
+ 'select_sources_tree_item_${childSource.view.id}',
+ ),
+ chatSource: childSource,
+ level: widget.level + 1,
+ isSelectedSection: widget.isSelectedSection,
+ onSelected: widget.onSelected,
+ height: widget.height,
+ visibilityGetter: widget.visibilityGetter,
+ ),
+ ),
+ ],
+ );
+ },
+ );
+ }
+}
+
+class ChatSourceTreeItemInner extends StatelessWidget {
+ const ChatSourceTreeItemInner({
+ super.key,
+ required this.chatSource,
+ required this.level,
+ required this.isSelectedSection,
+ this.onSelected,
+ });
+
+ final ChatSource chatSource;
+ final int level;
+ final bool isSelectedSection;
+ final void Function(ChatSource)? onSelected;
+
+ @override
+ Widget build(BuildContext context) {
+ return FlowyHover(
+ style: HoverStyle(
+ hoverColor: AFThemeExtension.of(context).lightGreyHover,
+ ),
+ child: GestureDetector(
+ behavior: HitTestBehavior.translucent,
+ onTap: () => onSelected?.call(chatSource),
+ child: Row(
+ children: [
+ const HSpace(4.0),
+ HSpace(20.0 * level),
+ // builds the >, ^ or · button
+ ToggleIsExpandedButton(
+ chatSource: chatSource,
+ isSelectedSection: isSelectedSection,
+ ),
+ const HSpace(2.0),
+ // checkbox
+ SourceSelectedStatusCheckbox(
+ chatSource: chatSource,
+ ),
+ const HSpace(4.0),
+ // icon
+ MentionViewIcon(
+ view: chatSource.view,
+ ),
+ const HSpace(6.0),
+ // title
+ Expanded(
+ child: FlowyText(
+ chatSource.view.nameOrDefault,
+ overflow: TextOverflow.ellipsis,
+ fontSize: 14.0,
+ figmaLineHeight: 18.0,
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+class ToggleIsExpandedButton extends StatelessWidget {
+ const ToggleIsExpandedButton({
+ super.key,
+ required this.chatSource,
+ required this.isSelectedSection,
+ });
+
+ final ChatSource chatSource;
+ final bool isSelectedSection;
+
+ @override
+ Widget build(BuildContext context) {
+ if (isReferencedDatabaseView(chatSource.view, chatSource.parentView)) {
+ return const _DotIconWidget();
+ }
+
+ if (chatSource.children.isEmpty) {
+ return const SizedBox.square(dimension: 16.0);
+ }
+
+ return FlowyHover(
+ child: GestureDetector(
+ child: ValueListenableBuilder(
+ valueListenable: chatSource.isExpandedNotifier,
+ builder: (context, value, _) => FlowySvg(
+ value
+ ? FlowySvgs.view_item_expand_s
+ : FlowySvgs.view_item_unexpand_s,
+ size: const Size.square(16.0),
+ ),
+ ),
+ onTap: () => context
+ .read<ChatSettingsCubit>()
+ .toggleIsExpanded(chatSource, isSelectedSection),
+ ),
+ );
+ }
+}
+
+class _DotIconWidget extends StatelessWidget {
+ const _DotIconWidget();
+
+ @override
+ Widget build(BuildContext context) {
+ return Padding(
+ padding: const EdgeInsets.all(6.0),
+ child: Container(
+ width: 4,
+ height: 4,
+ decoration: BoxDecoration(
+ color: Theme.of(context).iconTheme.color,
+ borderRadius: BorderRadius.circular(2),
+ ),
+ ),
+ );
+ }
+}
+
+class SourceSelectedStatusCheckbox extends StatelessWidget {
+ const SourceSelectedStatusCheckbox({
+ super.key,
+ required this.chatSource,
+ });
+
+ final ChatSource chatSource;
+
+ @override
+ Widget build(BuildContext context) {
+ return ValueListenableBuilder(
+ valueListenable: chatSource.selectedStatusNotifier,
+ builder: (context, selectedStatus, _) => FlowySvg(
+ switch (selectedStatus) {
+ SourceSelectedStatus.unselected => FlowySvgs.uncheck_s,
+ SourceSelectedStatus.selected => FlowySvgs.check_filled_s,
+ SourceSelectedStatus.partiallySelected => FlowySvgs.check_partial_s,
+ },
+ size: const Size.square(18.0),
+ blendMode: null,
+ ),
+ );
+ }
+}
diff --git a/frontend/resources/flowy_icons/16x/ai_source_drop_down.svg b/frontend/resources/flowy_icons/16x/ai_source_drop_down.svg
new file mode 100644
index 0000000000..5fe1dc47eb
--- /dev/null
+++ b/frontend/resources/flowy_icons/16x/ai_source_drop_down.svg
@@ -0,0 +1,3 @@
+<svg width="10" height="10" viewBox="0 0 10 10" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M1.78805 4.37204C1.95077 4.20932 2.21459 4.20932 2.37731 4.37204L4.99935 6.99408L7.62139 4.37204C7.78411 4.20932 8.04792 4.20932 8.21064 4.37204C8.37336 4.53476 8.37336 4.79858 8.21064 4.96129L5.29398 7.87796C5.21584 7.9561 5.10986 8 4.99935 8C4.88884 8 4.78286 7.9561 4.70472 7.87796L1.78805 4.96129C1.62534 4.79858 1.62534 4.53476 1.78805 4.37204Z" fill="black"/>
+</svg>
diff --git a/frontend/resources/flowy_icons/16x/check_partial.svg b/frontend/resources/flowy_icons/16x/check_partial.svg
new file mode 100644
index 0000000000..528d630790
--- /dev/null
+++ b/frontend/resources/flowy_icons/16x/check_partial.svg
@@ -0,0 +1,4 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <rect x="2.5" y="2.5" width="11" height="11" rx="3.5" stroke="#BDBDBD" stroke-width="1"/>
+ <path d="M5.5 8H10.5" stroke="#00BCF0" stroke-width="1.5" stroke-linecap="round"/>
+</svg>
diff --git a/frontend/resources/translations/en.json b/frontend/resources/translations/en.json
index 2219f89c8b..2b2ea51b8f 100644
--- a/frontend/resources/translations/en.json
+++ b/frontend/resources/translations/en.json
@@ -204,7 +204,8 @@
"uploadFile": "Attach PDFs, text or markdown files",
"questionDetail": "Hi {}! How can I help you today?",
"indexingFile": "Indexing {}",
- "generatingResponse": "Generating response"
+ "generatingResponse": "Generating response",
+ "selectSources": "Select Sources"
},
"trash": {
"text": "Trash",
diff --git a/frontend/rust-lib/flowy-ai/src/ai_manager.rs b/frontend/rust-lib/flowy-ai/src/ai_manager.rs
index 6541052623..a0993c3a27 100644
--- a/frontend/rust-lib/flowy-ai/src/ai_manager.rs
+++ b/frontend/rust-lib/flowy-ai/src/ai_manager.rs
@@ -285,6 +285,17 @@ impl AIManager {
pub fn local_ai_purchased(&self) {}
+ pub async fn get_rag_ids(&self, chat_id: &str) -> FlowyResult<Vec<String>> {
+ let workspace_id = self.user_service.workspace_id()?;
+
+ let settings = self
+ .cloud_service_wm
+ .get_chat_settings(&workspace_id, chat_id)
+ .await?;
+
+ Ok(settings.rag_ids)
+ }
+
pub async fn update_rag_ids(&self, chat_id: &str, rag_ids: Vec<String>) -> FlowyResult<()> {
if !rag_ids.is_empty() {
let workspace_id = self.user_service.workspace_id()?;
diff --git a/frontend/rust-lib/flowy-ai/src/entities.rs b/frontend/rust-lib/flowy-ai/src/entities.rs
index 3f318797b9..aba82d4b85 100644
--- a/frontend/rust-lib/flowy-ai/src/entities.rs
+++ b/frontend/rust-lib/flowy-ai/src/entities.rs
@@ -525,3 +525,19 @@ pub struct CreateChatContextPB {
#[validate(custom(function = "required_not_empty_str"))]
pub chat_id: String,
}
+
+#[derive(Default, ProtoBuf, Clone, Debug)]
+pub struct ChatSettingsPB {
+ #[pb(index = 1)]
+ pub rag_ids: Vec<String>,
+}
+
+#[derive(Default, ProtoBuf, Clone, Debug, Validate)]
+pub struct UpdateChatSettingsPB {
+ #[pb(index = 1)]
+ #[validate(nested)]
+ pub chat_id: ChatId,
+
+ #[pb(index = 2)]
+ pub rag_ids: Vec<String>,
+}
diff --git a/frontend/rust-lib/flowy-ai/src/event_handler.rs b/frontend/rust-lib/flowy-ai/src/event_handler.rs
index ce2f1b878f..748b4231ca 100644
--- a/frontend/rust-lib/flowy-ai/src/event_handler.rs
+++ b/frontend/rust-lib/flowy-ai/src/event_handler.rs
@@ -420,3 +420,29 @@ pub(crate) async fn get_chat_info_handler(
let pb = ai_manager.get_chat_info(&chat_id).await?;
data_result_ok(pb)
}
+
+#[tracing::instrument(level = "debug", skip_all, err)]
+pub(crate) async fn get_chat_settings_handler(
+ data: AFPluginData<ChatId>,
+ ai_manager: AFPluginState<Weak<AIManager>>,
+) -> DataResult<ChatSettingsPB, FlowyError> {
+ let chat_id = data.try_into_inner()?.value;
+ let ai_manager = upgrade_ai_manager(ai_manager)?;
+ let rag_ids = ai_manager.get_rag_ids(&chat_id).await?;
+ let pb = ChatSettingsPB { rag_ids };
+ data_result_ok(pb)
+}
+
+#[tracing::instrument(level = "debug", skip_all, err)]
+pub(crate) async fn update_chat_settings_handler(
+ data: AFPluginData<UpdateChatSettingsPB>,
+ ai_manager: AFPluginState<Weak<AIManager>>,
+) -> FlowyResult<()> {
+ let params = data.try_into_inner()?;
+ let ai_manager = upgrade_ai_manager(ai_manager)?;
+ ai_manager
+ .update_rag_ids(&params.chat_id.value, params.rag_ids)
+ .await?;
+
+ Ok(())
+}
diff --git a/frontend/rust-lib/flowy-ai/src/event_map.rs b/frontend/rust-lib/flowy-ai/src/event_map.rs
index 109be1a253..a12e81dc13 100644
--- a/frontend/rust-lib/flowy-ai/src/event_map.rs
+++ b/frontend/rust-lib/flowy-ai/src/event_map.rs
@@ -57,6 +57,8 @@ pub fn init(ai_manager: Weak<AIManager>) -> AFPlugin {
.event(AIEvent::GetOfflineAIAppLink, get_offline_app_handler)
.event(AIEvent::CreateChatContext, create_chat_context_handler)
.event(AIEvent::GetChatInfo, create_chat_context_handler)
+ .event(AIEvent::GetChatSettings, get_chat_settings_handler)
+ .event(AIEvent::UpdateChatSettings, update_chat_settings_handler)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Display, Hash, ProtoBuf_Enum, Flowy_Event)]
@@ -142,4 +144,10 @@ pub enum AIEvent {
#[event(input = "ChatId", output = "ChatInfoPB")]
GetChatInfo = 24,
+
+ #[event(input = "ChatId", output = "ChatSettingsPB")]
+ GetChatSettings = 25,
+
+ #[event(input = "UpdateChatSettingsPB")]
+ UpdateChatSettings = 26,
}