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: load custom prompts from a database (#7894)

Richard Shiue680015ef66fd
diff --git a/frontend/appflowy_flutter/lib/ai/ai.dart b/frontend/appflowy_flutter/lib/ai/ai.dart
index de27a98210..ee4a87d974 100644
--- a/frontend/appflowy_flutter/lib/ai/ai.dart
+++ b/frontend/appflowy_flutter/lib/ai/ai.dart
@@ -7,6 +7,7 @@ export 'service/ai_model_state_notifier.dart';
export 'service/select_model_bloc.dart';
export 'service/view_selector_cubit.dart';
export 'widgets/loading_indicator.dart';
+export 'widgets/view_selector.dart';
export 'widgets/prompt_input/action_buttons.dart';
export 'widgets/prompt_input/desktop_prompt_input.dart';
export 'widgets/prompt_input/file_attachment_list.dart';
diff --git a/frontend/appflowy_flutter/lib/ai/service/ai_entities.dart b/frontend/appflowy_flutter/lib/ai/service/ai_entities.dart
index fb3646aeb0..6a2d1d4f4f 100644
--- a/frontend/appflowy_flutter/lib/ai/service/ai_entities.dart
+++ b/frontend/appflowy_flutter/lib/ai/service/ai_entities.dart
@@ -1,6 +1,7 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy_backend/protobuf/flowy-ai/protobuf.dart';
+import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
@@ -192,8 +193,23 @@ class AiPrompt extends Equatable {
required this.category,
required this.example,
required this.isFeatured,
+ required this.isCustom,
});
+ factory AiPrompt.fromPB(CustomPromptPB pb) {
+ return AiPrompt(
+ id: pb.id,
+ name: pb.name,
+ content: pb.content,
+ category: AiPromptCategory.values.firstWhere(
+ (e) => e.name == pb.category,
+ ),
+ example: pb.example,
+ isFeatured: false,
+ isCustom: true,
+ );
+ }
+
factory AiPrompt.fromJson(Map<String, dynamic> json) =>
_$AiPromptFromJson(json);
@@ -211,7 +227,10 @@ class AiPrompt extends Equatable {
final String example;
@JsonKey(defaultValue: false)
final bool isFeatured;
+ @JsonKey(defaultValue: false)
+ final bool isCustom;
@override
- List<Object?> get props => [id, name, content, category, example, isFeatured];
+ List<Object?> get props =>
+ [id, name, content, category, example, isFeatured, isCustom];
}
diff --git a/frontend/appflowy_flutter/lib/ai/service/ai_prompt_selector_cubit.dart b/frontend/appflowy_flutter/lib/ai/service/ai_prompt_selector_cubit.dart
index 9312e4f29a..298b25e981 100644
--- a/frontend/appflowy_flutter/lib/ai/service/ai_prompt_selector_cubit.dart
+++ b/frontend/appflowy_flutter/lib/ai/service/ai_prompt_selector_cubit.dart
@@ -1,3 +1,7 @@
+import 'package:appflowy_backend/dispatch/dispatch.dart';
+import 'package:appflowy_backend/log.dart';
+import 'package:appflowy_backend/protobuf/flowy-ai/protobuf.dart';
+import 'package:appflowy_result/appflowy_result.dart';
import 'package:bloc/bloc.dart';
import 'package:collection/collection.dart';
import 'package:flutter/widgets.dart';
@@ -14,7 +18,7 @@ class AiPromptSelectorCubit extends Cubit<AiPromptSelectorState> {
}) : _aiService = aiService ?? AppFlowyAIService(),
super(AiPromptSelectorState.loading()) {
filterTextController.addListener(_filterTextChanged);
- _loadPrompts();
+ _init();
}
final AppFlowyAIService _aiService;
@@ -27,33 +31,131 @@ class AiPromptSelectorCubit extends Cubit<AiPromptSelectorState> {
await super.close();
}
- void _loadPrompts() async {
+ void _init() async {
availablePrompts.addAll(await _aiService.getBuiltInPrompts());
+
final featuredPrompts =
availablePrompts.where((prompt) => prompt.isFeatured);
final visiblePrompts = _getFilteredPrompts(featuredPrompts);
+
emit(
AiPromptSelectorState.ready(
- visiblePrompts: visiblePrompts,
- showCustomPrompts: false,
- isFeaturedCategorySelected: true,
+ visiblePrompts: visiblePrompts.toList(),
+ isCustomPromptSectionSelected: false,
+ isFeaturedSectionSelected: true,
selectedPromptId: visiblePrompts.firstOrNull?.id,
+ customPromptDatabaseViewId: null,
+ isLoadingCustomPrompts: true,
selectedCategory: null,
favoritePrompts: [],
),
);
+
+ loadCustomPrompts();
+ }
+
+ void loadCustomPrompts() {
+ state.maybeMap(
+ ready: (readyState) async {
+ emit(
+ readyState.copyWith(isLoadingCustomPrompts: true),
+ );
+
+ String? databaseViewId = readyState.customPromptDatabaseViewId;
+ if (databaseViewId == null) {
+ final result =
+ await AIEventGetCustomPromptDatabaseViewId().send().toNullable();
+ databaseViewId = result?.id;
+ }
+
+ if (databaseViewId == null) {
+ emit(
+ readyState.copyWith(isLoadingCustomPrompts: false),
+ );
+ return;
+ }
+
+ availablePrompts.removeWhere((prompt) => prompt.isCustom);
+
+ final customPrompts =
+ await _aiService.getDatabasePrompts(databaseViewId);
+
+ if (customPrompts == null || customPrompts.isEmpty) {
+ final prompts = availablePrompts.where((prompt) => prompt.isFeatured);
+ final visiblePrompts = _getFilteredPrompts(prompts);
+ final selectedPromptId = _getVisibleSelectedPrompt(
+ visiblePrompts,
+ readyState.selectedPromptId,
+ );
+
+ emit(
+ readyState.copyWith(
+ visiblePrompts: visiblePrompts.toList(),
+ selectedPromptId: selectedPromptId,
+ customPromptDatabaseViewId: databaseViewId,
+ isLoadingCustomPrompts: false,
+ isFeaturedSectionSelected: true,
+ isCustomPromptSectionSelected: false,
+ selectedCategory: null,
+ ),
+ );
+ } else {
+ availablePrompts.addAll(customPrompts);
+
+ final prompts = _getPromptsByCategory(readyState);
+ final visiblePrompts = _getFilteredPrompts(prompts);
+ final selectedPromptId = _getVisibleSelectedPrompt(
+ visiblePrompts,
+ readyState.selectedPromptId,
+ );
+
+ emit(
+ readyState.copyWith(
+ visiblePrompts: visiblePrompts.toList(),
+ customPromptDatabaseViewId: databaseViewId,
+ isLoadingCustomPrompts: false,
+ selectedPromptId: selectedPromptId,
+ ),
+ );
+ }
+ },
+ orElse: () {},
+ );
+ }
+
+ void selectCustomSection() {
+ state.maybeMap(
+ ready: (readyState) {
+ final prompts = availablePrompts.where((prompt) => prompt.isCustom);
+ final visiblePrompts = _getFilteredPrompts(prompts);
+
+ emit(
+ readyState.copyWith(
+ visiblePrompts: visiblePrompts.toList(),
+ selectedPromptId: visiblePrompts.firstOrNull?.id,
+ isCustomPromptSectionSelected: true,
+ isFeaturedSectionSelected: false,
+ selectedCategory: null,
+ ),
+ );
+ },
+ orElse: () {},
+ );
}
- void selectFeaturedCategory() {
+ void selectFeaturedSection() {
state.maybeMap(
ready: (readyState) {
final prompts = availablePrompts.where((prompt) => prompt.isFeatured);
final visiblePrompts = _getFilteredPrompts(prompts);
+
emit(
readyState.copyWith(
- visiblePrompts: visiblePrompts,
- isFeaturedCategorySelected: true,
+ visiblePrompts: visiblePrompts.toList(),
selectedPromptId: visiblePrompts.firstOrNull?.id,
+ isFeaturedSectionSelected: true,
+ isCustomPromptSectionSelected: false,
+ selectedCategory: null,
),
);
},
@@ -64,24 +166,23 @@ class AiPromptSelectorCubit extends Cubit<AiPromptSelectorState> {
void selectCategory(AiPromptCategory? category) {
state.maybeMap(
ready: (readyState) {
- final unfilteredPrompts = category == null
+ final prompts = category == null
? availablePrompts
: availablePrompts.where((prompt) => prompt.category == category);
- final prompts = _getFilteredPrompts(unfilteredPrompts);
+ final visiblePrompts = _getFilteredPrompts(prompts);
- // Check if the selected prompt is still visible
- String? selectedPromptId = prompts.firstOrNull?.id;
- if (readyState.selectedPromptId != null &&
- prompts.any((prompt) => prompt.id == readyState.selectedPromptId)) {
- selectedPromptId = readyState.selectedPromptId;
- }
+ final selectedPromptId = _getVisibleSelectedPrompt(
+ visiblePrompts,
+ readyState.selectedPromptId,
+ );
emit(
readyState.copyWith(
- visiblePrompts: prompts,
- isFeaturedCategorySelected: false,
+ visiblePrompts: visiblePrompts.toList(),
selectedCategory: category,
selectedPromptId: selectedPromptId,
+ isFeaturedSectionSelected: false,
+ isCustomPromptSectionSelected: false,
),
);
},
@@ -116,8 +217,6 @@ class AiPromptSelectorCubit extends Cubit<AiPromptSelectorState> {
emit(
readyState.copyWith(favoritePrompts: favoritePrompts),
);
-
- // TODO(RS): Save the updated favorite prompts to local storage or database
},
orElse: () {},
);
@@ -130,7 +229,9 @@ class AiPromptSelectorCubit extends Cubit<AiPromptSelectorState> {
emit(
readyState.copyWith(
visiblePrompts: availablePrompts,
- selectedPromptId: null,
+ isCustomPromptSectionSelected: false,
+ isFeaturedSectionSelected: true,
+ selectedPromptId: availablePrompts.firstOrNull?.id,
selectedCategory: null,
),
);
@@ -139,27 +240,103 @@ class AiPromptSelectorCubit extends Cubit<AiPromptSelectorState> {
);
}
+ void updateCustomPromptDatabaseViewId(String viewId) async {
+ final stateCopy = state;
+ final newState = state.maybeMap(
+ ready: (readyState) {
+ return readyState.customPromptDatabaseViewId == viewId
+ ? null
+ : readyState.copyWith(isLoadingCustomPrompts: true);
+ },
+ orElse: () => null,
+ );
+
+ if (newState == null) {
+ return;
+ }
+ emit(newState);
+
+ await Future.delayed(const Duration(seconds: 1));
+
+ final customPrompts = await _aiService.getDatabasePrompts(viewId);
+ if (customPrompts == null) {
+ emit(AiPromptSelectorState.invalidDatabase());
+ emit(stateCopy);
+
+ return;
+ }
+
+ availablePrompts
+ ..removeWhere((prompt) => prompt.isCustom)
+ ..addAll(customPrompts);
+
+ await AIEventSetCustomPromptDatabaseViewId(
+ CustomPromptDatabaseViewIdPB()..id = viewId,
+ ).send().onFailure(Log.error);
+
+ emit(
+ state.maybeMap(
+ ready: (readyState) {
+ if (customPrompts.isEmpty) {
+ final prompts =
+ availablePrompts.where((prompt) => prompt.isFeatured);
+ final visiblePrompts = _getFilteredPrompts(prompts);
+ final selectedPromptId = _getVisibleSelectedPrompt(
+ visiblePrompts,
+ readyState.selectedPromptId,
+ );
+ return readyState.copyWith(
+ visiblePrompts: visiblePrompts.toList(),
+ selectedPromptId: selectedPromptId,
+ customPromptDatabaseViewId: viewId,
+ isLoadingCustomPrompts: false,
+ isFeaturedSectionSelected: true,
+ isCustomPromptSectionSelected: false,
+ selectedCategory: null,
+ );
+ } else {
+ final prompts = _getPromptsByCategory(readyState);
+ final visiblePrompts = _getFilteredPrompts(prompts);
+ final selectedPromptId = _getVisibleSelectedPrompt(
+ visiblePrompts,
+ readyState.selectedPromptId,
+ );
+ return readyState.copyWith(
+ visiblePrompts: visiblePrompts.toList(),
+ selectedPromptId: selectedPromptId,
+ customPromptDatabaseViewId: viewId,
+ isLoadingCustomPrompts: false,
+ );
+ }
+ },
+ orElse: () => state,
+ ),
+ );
+ }
+
void _filterTextChanged() {
state.maybeMap(
ready: (readyState) {
- final unfilteredPrompts = readyState.selectedCategory == null
- ? readyState.isFeaturedCategorySelected
- ? availablePrompts.where((prompt) => prompt.isFeatured)
- : availablePrompts
- : availablePrompts.where(
- (prompt) => prompt.category == readyState.selectedCategory,
- );
- final filteredPrompts = _getFilteredPrompts(unfilteredPrompts);
+ final prompts = _getPromptsByCategory(readyState);
+ final visiblePrompts = _getFilteredPrompts(prompts);
+
+ final selectedPromptId = _getVisibleSelectedPrompt(
+ visiblePrompts,
+ readyState.selectedPromptId,
+ );
emit(
- readyState.copyWith(visiblePrompts: filteredPrompts),
+ readyState.copyWith(
+ visiblePrompts: visiblePrompts.toList(),
+ selectedPromptId: selectedPromptId,
+ ),
);
},
orElse: () {},
);
}
- List<AiPrompt> _getFilteredPrompts(Iterable<AiPrompt> prompts) {
+ Iterable<AiPrompt> _getFilteredPrompts(Iterable<AiPrompt> prompts) {
final filterText = filterTextController.value.text.trim().toLowerCase();
return prompts.where((prompt) {
@@ -167,6 +344,33 @@ class AiPromptSelectorCubit extends Cubit<AiPromptSelectorState> {
return content.contains(filterText);
}).toList();
}
+
+ Iterable<AiPrompt> _getPromptsByCategory(_AiPromptSelectorReadyState state) {
+ return availablePrompts.where((prompt) {
+ if (state.selectedCategory != null) {
+ return prompt.category == state.selectedCategory;
+ }
+ if (state.isFeaturedSectionSelected) {
+ return prompt.isFeatured;
+ }
+ if (state.isCustomPromptSectionSelected) {
+ return prompt.isCustom;
+ }
+ return true;
+ });
+ }
+
+ String? _getVisibleSelectedPrompt(
+ Iterable<AiPrompt> visiblePrompts,
+ String? currentlySelectedPromptId,
+ ) {
+ if (visiblePrompts
+ .any((prompt) => prompt.id == currentlySelectedPromptId)) {
+ return currentlySelectedPromptId;
+ }
+
+ return visiblePrompts.firstOrNull?.id;
+ }
}
@freezed
@@ -175,13 +379,18 @@ class AiPromptSelectorState with _$AiPromptSelectorState {
const factory AiPromptSelectorState.loading() = _AiPromptSelectorLoadingState;
+ const factory AiPromptSelectorState.invalidDatabase() =
+ _AiPromptSelectorErrorState;
+
const factory AiPromptSelectorState.ready({
required List<AiPrompt> visiblePrompts,
required List<String> favoritePrompts,
- required bool showCustomPrompts,
- required bool isFeaturedCategorySelected,
+ required bool isCustomPromptSectionSelected,
+ required bool isFeaturedSectionSelected,
required AiPromptCategory? selectedCategory,
required String? selectedPromptId,
+ required bool isLoadingCustomPrompts,
+ required String? customPromptDatabaseViewId,
}) = _AiPromptSelectorReadyState;
bool get isLoading => this is _AiPromptSelectorLoadingState;
@@ -192,9 +401,4 @@ class AiPromptSelectorState with _$AiPromptSelectorState {
.firstWhereOrNull((prompt) => prompt.id == state.selectedPromptId),
orElse: () => null,
);
-
- AiPromptCategory? get selectedCategory => maybeMap(
- ready: (state) => state.selectedCategory,
- orElse: () => null,
- );
}
diff --git a/frontend/appflowy_flutter/lib/ai/service/appflowy_ai_service.dart b/frontend/appflowy_flutter/lib/ai/service/appflowy_ai_service.dart
index 0254222098..b846489d52 100644
--- a/frontend/appflowy_flutter/lib/ai/service/appflowy_ai_service.dart
+++ b/frontend/appflowy_flutter/lib/ai/service/appflowy_ai_service.dart
@@ -9,6 +9,7 @@ import 'package:appflowy/shared/list_extension.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-ai/entities.pb.dart';
+import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:fixnum/fixnum.dart' as fixnum;
@@ -41,6 +42,8 @@ abstract class AIRepository {
Future<List<AiPrompt>> getBuiltInPrompts();
+ Future<List<AiPrompt>?> getDatabasePrompts(String databaseViewId);
+
void updateFavoritePrompts(List<String> promptIds);
}
@@ -117,6 +120,23 @@ class AppFlowyAIService implements AIRepository {
return prompts;
}
+ @override
+ Future<List<AiPrompt>?> getDatabasePrompts(
+ String databaseViewId,
+ ) async {
+ return DatabaseEventGetDatabaseCustomPrompts(
+ DatabaseViewIdPB(value: databaseViewId),
+ ).send().fold(
+ (databasePromptsPB) {
+ return databasePromptsPB.items.map(AiPrompt.fromPB).toList();
+ },
+ (err) {
+ Log.error(err);
+ return null;
+ },
+ );
+ }
+
@override
void updateFavoritePrompts(List<String> promptIds) {}
}
diff --git a/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_category_list.dart b/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_category_list.dart
index 8ec983f8dc..70d4936954 100644
--- a/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_category_list.dart
+++ b/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_category_list.dart
@@ -8,11 +8,8 @@ import 'package:flutter_bloc/flutter_bloc.dart';
class AiPromptCategoryList extends StatefulWidget {
const AiPromptCategoryList({
super.key,
- required this.padding,
});
- final EdgeInsetsGeometry padding;
-
@override
State<AiPromptCategoryList> createState() => _AiPromptCategoryListState();
}
@@ -23,60 +20,59 @@ class _AiPromptCategoryListState extends State<AiPromptCategoryList> {
Widget build(BuildContext context) {
final theme = AppFlowyTheme.of(context);
- return Padding(
- padding: EdgeInsets.all(
- theme.spacing.l,
- ),
- child: TextFieldTapRegion(
- groupId: "ai_prompt_category_list",
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- spacing: theme.spacing.s,
- children: [
- _buildFeaturedCategory(context),
- const AFDivider(),
- Expanded(
- child: ListView(
- padding: EdgeInsets.zero,
- children: [
- _buildCategoryItem(context, null),
- _buildCategoryItem(context, AiPromptCategory.development),
- _buildCategoryItem(context, AiPromptCategory.writing),
- _buildCategoryItem(context, AiPromptCategory.business),
- _buildCategoryItem(context, AiPromptCategory.marketing),
- _buildCategoryItem(
- context,
- AiPromptCategory.healthAndFitness,
- ),
- _buildCategoryItem(context, AiPromptCategory.travel),
- _buildCategoryItem(context, AiPromptCategory.contentSeo),
- _buildCategoryItem(context, AiPromptCategory.emailMarketing),
- _buildCategoryItem(context, AiPromptCategory.paidAds),
- _buildCategoryItem(context, AiPromptCategory.prCommunication),
- _buildCategoryItem(context, AiPromptCategory.recruiting),
- _buildCategoryItem(context, AiPromptCategory.sales),
- _buildCategoryItem(context, AiPromptCategory.socialMedia),
- _buildCategoryItem(context, AiPromptCategory.strategy),
- _buildCategoryItem(context, AiPromptCategory.caseStudies),
- _buildCategoryItem(context, AiPromptCategory.salesCopy),
- _buildCategoryItem(context, AiPromptCategory.education),
- _buildCategoryItem(context, AiPromptCategory.work),
- _buildCategoryItem(
+ return TextFieldTapRegion(
+ groupId: "ai_prompt_category_list",
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: EdgeInsets.only(
+ right: theme.spacing.l,
+ ),
+ child: AiPromptFeaturedSection(),
+ ),
+ Padding(
+ padding: EdgeInsets.only(
+ right: theme.spacing.l,
+ ),
+ child: AiPromptCustomPromptSection(),
+ ),
+ Padding(
+ padding: EdgeInsets.only(
+ top: theme.spacing.s,
+ right: theme.spacing.l,
+ ),
+ child: AFDivider(),
+ ),
+ Expanded(
+ child: ListView(
+ padding: EdgeInsets.only(
+ top: theme.spacing.s,
+ right: theme.spacing.l,
+ ),
+ children: [
+ _buildCategoryItem(context, null),
+ ...sortedCategories.map(
+ (category) => _buildCategoryItem(
context,
- AiPromptCategory.podcastProduction,
+ category,
),
- _buildCategoryItem(context, AiPromptCategory.copyWriting),
- _buildCategoryItem(context, AiPromptCategory.customerSuccess),
- _buildCategoryItem(context, AiPromptCategory.other),
- ],
- ),
+ ),
+ ],
),
- ],
- ),
+ ),
+ ],
),
);
}
+ static Iterable<AiPromptCategory> get sortedCategories {
+ final categories = [...AiPromptCategory.values];
+ categories.sort((a, b) => a.i18n.compareTo(b.i18n));
+
+ return categories;
+ }
+
Widget _buildCategoryItem(
BuildContext context,
AiPromptCategory? category,
@@ -88,18 +84,25 @@ class _AiPromptCategoryListState extends State<AiPromptCategoryList> {
},
);
}
+}
- Widget _buildFeaturedCategory(BuildContext context) {
+class AiPromptFeaturedSection extends StatelessWidget {
+ const AiPromptFeaturedSection({
+ super.key,
+ });
+
+ @override
+ Widget build(BuildContext context) {
final theme = AppFlowyTheme.of(context);
final isSelected = context.watch<AiPromptSelectorCubit>().state.maybeMap(
- ready: (state) => state.isFeaturedCategorySelected,
+ ready: (state) => state.isFeaturedSectionSelected,
orElse: () => false,
);
return AFBaseButton(
onTap: () {
if (!isSelected) {
- context.read<AiPromptSelectorCubit>().selectFeaturedCategory();
+ context.read<AiPromptSelectorCubit>().selectFeaturedSection();
}
},
builder: (context, isHovering, disabled) {
@@ -131,6 +134,70 @@ class _AiPromptCategoryListState extends State<AiPromptCategoryList> {
}
}
+class AiPromptCustomPromptSection extends StatelessWidget {
+ const AiPromptCustomPromptSection({
+ super.key,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = AppFlowyTheme.of(context);
+
+ return BlocBuilder<AiPromptSelectorCubit, AiPromptSelectorState>(
+ builder: (context, state) {
+ return state.maybeMap(
+ ready: (readyState) {
+ final isSelected = readyState.isCustomPromptSectionSelected;
+ final isDisabled = context
+ .read<AiPromptSelectorCubit>()
+ .availablePrompts
+ .every((prompt) => !prompt.isCustom);
+ return AFBaseButton(
+ disabled: isDisabled,
+ onTap: () {
+ if (!isSelected) {
+ context.read<AiPromptSelectorCubit>().selectCustomSection();
+ }
+ },
+ builder: (context, isHovering, disabled) {
+ return Text(
+ LocaleKeys.ai_customPrompt_custom.tr(),
+ style: AppFlowyTheme.of(context).textStyle.body.standard(
+ color: disabled
+ ? theme.textColorScheme.tertiary
+ : theme.textColorScheme.primary,
+ ),
+ overflow: TextOverflow.ellipsis,
+ );
+ },
+ borderRadius: theme.borderRadius.m,
+ padding: EdgeInsets.symmetric(
+ vertical: theme.spacing.s,
+ horizontal: theme.spacing.m,
+ ),
+ borderColor: (context, isHovering, disabled, isFocused) =>
+ Colors.transparent,
+ backgroundColor: (context, isHovering, disabled) {
+ if (disabled) {
+ return Colors.transparent;
+ }
+ if (isSelected) {
+ return theme.fillColorScheme.themeSelect;
+ }
+ if (isHovering) {
+ return theme.fillColorScheme.primaryAlpha5;
+ }
+ return Colors.transparent;
+ },
+ );
+ },
+ orElse: () => const SizedBox.shrink(),
+ );
+ },
+ );
+ }
+}
+
class AiPromptCategoryItem extends StatelessWidget {
const AiPromptCategoryItem({
super.key,
@@ -143,41 +210,47 @@ class AiPromptCategoryItem extends StatelessWidget {
@override
Widget build(BuildContext context) {
- final theme = AppFlowyTheme.of(context);
- final isSelected = context.watch<AiPromptSelectorCubit>().state.maybeMap(
- ready: (state) =>
- !state.isFeaturedCategorySelected &&
- state.selectedCategory == category,
+ return BlocBuilder<AiPromptSelectorCubit, AiPromptSelectorState>(
+ builder: (context, state) {
+ final theme = AppFlowyTheme.of(context);
+ final isSelected = state.maybeMap(
+ ready: (state) {
+ return !state.isFeaturedSectionSelected &&
+ !state.isCustomPromptSectionSelected &&
+ state.selectedCategory == category;
+ },
orElse: () => false,
);
- return AFBaseButton(
- onTap: onSelect,
- builder: (context, isHovering, disabled) {
- return Text(
- category?.i18n ?? LocaleKeys.ai_customPrompt_all.tr(),
- style: AppFlowyTheme.of(context).textStyle.body.standard(
- color: theme.textColorScheme.primary,
- ),
- overflow: TextOverflow.ellipsis,
+ return AFBaseButton(
+ onTap: onSelect,
+ builder: (context, isHovering, disabled) {
+ return Text(
+ category?.i18n ?? LocaleKeys.ai_customPrompt_all.tr(),
+ style: AppFlowyTheme.of(context).textStyle.body.standard(
+ color: theme.textColorScheme.primary,
+ ),
+ overflow: TextOverflow.ellipsis,
+ );
+ },
+ borderRadius: theme.borderRadius.m,
+ padding: EdgeInsets.symmetric(
+ vertical: theme.spacing.s,
+ horizontal: theme.spacing.m,
+ ),
+ borderColor: (context, isHovering, disabled, isFocused) =>
+ Colors.transparent,
+ backgroundColor: (context, isHovering, disabled) {
+ if (isSelected) {
+ return theme.fillColorScheme.themeSelect;
+ }
+ if (isHovering) {
+ return theme.fillColorScheme.primaryAlpha5;
+ }
+ return Colors.transparent;
+ },
);
},
- borderRadius: theme.borderRadius.m,
- padding: EdgeInsets.symmetric(
- vertical: theme.spacing.s,
- horizontal: theme.spacing.m,
- ),
- borderColor: (context, isHovering, disabled, isFocused) =>
- Colors.transparent,
- backgroundColor: (context, isHovering, disabled) {
- if (isSelected) {
- return theme.fillColorScheme.themeSelect;
- }
- if (isHovering) {
- return theme.fillColorScheme.primaryAlpha5;
- }
- return Colors.transparent;
- },
);
}
}
diff --git a/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_database_selector.dart b/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_database_selector.dart
new file mode 100644
index 0000000000..ead4b21394
--- /dev/null
+++ b/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_database_selector.dart
@@ -0,0 +1,284 @@
+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/trash/application/trash_service.dart';
+import 'package:appflowy/workspace/application/sidebar/space/space_bloc.dart';
+import 'package:appflowy/workspace/application/view/prelude.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:appflowy_result/appflowy_result.dart';
+import 'package:appflowy_ui/appflowy_ui.dart';
+import 'package:collection/collection.dart';
+import 'package:easy_localization/easy_localization.dart';
+import 'package:flowy_infra_ui/flowy_infra_ui.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_bloc/flutter_bloc.dart';
+
+class CustomPromptDatabaseSelector extends StatefulWidget {
+ const CustomPromptDatabaseSelector({
+ super.key,
+ required this.databaseViewId,
+ required this.isLoading,
+ });
+
+ final String? databaseViewId;
+ final bool isLoading;
+
+ @override
+ State<CustomPromptDatabaseSelector> createState() =>
+ _CustomPromptDatabaseSelectorState();
+}
+
+class _CustomPromptDatabaseSelectorState
+ extends State<CustomPromptDatabaseSelector> {
+ final popoverController = PopoverController();
+
+ @override
+ Widget build(BuildContext context) {
+ return ViewSelector(
+ viewSelectorCubit: BlocProvider(
+ create: (context) => ViewSelectorCubit(
+ getIgnoreViewType: (view) {
+ if (view.layout.isDatabaseView || view.layout.isDocumentView) {
+ return IgnoreViewType.none;
+ }
+ return IgnoreViewType.hide;
+ },
+ ),
+ ),
+ child: BlocSelector<SpaceBloc, SpaceState, (List<ViewPB>, ViewPB?)>(
+ selector: (state) => (state.spaces, state.currentSpace),
+ builder: (context, state) {
+ return AppFlowyPopover(
+ controller: popoverController,
+ triggerActions: PopoverTriggerFlags.none,
+ margin: EdgeInsets.zero,
+ offset: const Offset(0, 2),
+ direction: PopoverDirection.bottomWithRightAligned,
+ constraints: const BoxConstraints.tightFor(width: 300, height: 400),
+ popupBuilder: (_) {
+ return BlocProvider.value(
+ value: context.read<ViewSelectorCubit>(),
+ child: _PopoverContent(
+ onSelectView: (view) {
+ if (view.layout.isDatabaseView) {
+ context
+ .read<AiPromptSelectorCubit>()
+ .updateCustomPromptDatabaseViewId(view.id);
+ popoverController.close();
+ }
+ },
+ ),
+ );
+ },
+ child: _Button(
+ selectedViewId: widget.databaseViewId,
+ isLoading: widget.isLoading,
+ onTap: () {
+ if (!widget.isLoading) {
+ context
+ .read<ViewSelectorCubit>()
+ .refreshSources(state.$1, state.$2);
+ popoverController.show();
+ }
+ },
+ ),
+ );
+ },
+ ),
+ );
+ }
+}
+
+class _Button extends StatelessWidget {
+ const _Button({
+ required this.selectedViewId,
+ required this.isLoading,
+ required this.onTap,
+ });
+
+ final String? selectedViewId;
+ final bool isLoading;
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = AppFlowyTheme.of(context);
+
+ return FutureBuilder<ViewPB?>(
+ future: getView(),
+ builder: (context, snapshot) {
+ final data = snapshot.data;
+
+ final String name;
+ final String? tooltip;
+ if (isLoading) {
+ tooltip = null;
+ name = LocaleKeys.ai_customPrompt_loading.tr();
+ } else if (!snapshot.hasData ||
+ snapshot.connectionState != ConnectionState.done ||
+ data == null) {
+ name = LocaleKeys.ai_customPrompt_selectDatabase.tr();
+ tooltip = LocaleKeys.ai_customPrompt_selectDatabase.tr();
+ } else {
+ name = tooltip = data.nameOrDefault;
+ }
+
+ return FlowyTooltip(
+ message: tooltip,
+ preferBelow: false,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(
+ maxWidth: 150,
+ ),
+ child: AFGhostButton.normal(
+ onTap: onTap,
+ padding: EdgeInsets.symmetric(
+ vertical: theme.spacing.xs,
+ horizontal: theme.spacing.m,
+ ),
+ builder: (context, isHovering, disabled) {
+ return Row(
+ spacing: theme.spacing.xs,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ buildLoadingIndicator(theme),
+ Flexible(
+ child: Text(
+ name,
+ maxLines: 1,
+ style: theme.textStyle.body.standard(
+ color: theme.textColorScheme.secondary,
+ ),
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ if (!isLoading)
+ FlowySvg(
+ FlowySvgs.toolbar_arrow_down_m,
+ color: theme.iconColorScheme.secondary,
+ ),
+ ],
+ );
+ },
+ ),
+ ),
+ );
+ },
+ );
+ }
+
+ Widget buildLoadingIndicator(AppFlowyThemeData theme) {
+ return isLoading
+ ? SizedBox.square(
+ dimension: 20,
+ child: Padding(
+ padding: EdgeInsets.all(2.5),
+ child: CircularProgressIndicator(
+ color: theme.iconColorScheme.tertiary,
+ strokeWidth: 2.0,
+ ),
+ ),
+ )
+ : const SizedBox.shrink();
+ }
+
+ Future<ViewPB?> getView() async {
+ if (selectedViewId == null) {
+ return null;
+ }
+ final view = await ViewBackendService.getView(selectedViewId!).toNullable();
+
+ if (view != null) {
+ return view;
+ }
+
+ final trashViews = await TrashService().readTrash().toNullable();
+ final trashedItem = trashViews?.items
+ .firstWhereOrNull((element) => element.id == selectedViewId);
+
+ if (trashedItem == null) {
+ return null;
+ }
+
+ return ViewPB()
+ ..id = trashedItem.id
+ ..name = trashedItem.name;
+ }
+}
+
+class _PopoverContent extends StatelessWidget {
+ const _PopoverContent({required this.onSelectView});
+
+ final void Function(ViewPB view) onSelectView;
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = AppFlowyTheme.of(context);
+
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ VSpace(theme.spacing.m),
+ Padding(
+ padding: EdgeInsets.symmetric(
+ horizontal: theme.spacing.l,
+ ),
+ child: Text(
+ LocaleKeys.ai_customPrompt_loadDatabasePromptsFrom.tr(),
+ style: theme.textStyle.caption
+ .standard(color: theme.textColorScheme.secondary),
+ ),
+ ),
+ VSpace(theme.spacing.m),
+ Padding(
+ padding: EdgeInsets.symmetric(
+ horizontal: theme.spacing.m,
+ ),
+ child: AFTextField(
+ size: AFTextFieldSize.m,
+ hintText: LocaleKeys.search_label.tr(),
+ controller: context.read<ViewSelectorCubit>().filterTextController,
+ ),
+ ),
+ VSpace(theme.spacing.m),
+ AFDivider(),
+ Expanded(
+ child: BlocBuilder<ViewSelectorCubit, ViewSelectorState>(
+ builder: (context, state) {
+ return ListView(
+ shrinkWrap: true,
+ padding: const EdgeInsets.fromLTRB(8, 4, 8, 12),
+ children: _buildVisibleSources(context, state).toList(),
+ );
+ },
+ ),
+ ),
+ ],
+ );
+ }
+
+ Iterable<Widget> _buildVisibleSources(
+ BuildContext context,
+ ViewSelectorState state,
+ ) {
+ return state.visibleSources.map(
+ (e) => ViewSelectorTreeItem(
+ key: ValueKey(
+ 'custom_prompt_database_tree_item_${e.view.id}',
+ ),
+ viewSelectorItem: e,
+ level: 0,
+ isDescendentOfSpace: e.view.isSpace,
+ isSelectedSection: false,
+ showCheckbox: false,
+ onSelected: (source) {
+ onSelectView(source.view);
+ },
+ height: 30.0,
+ ),
+ );
+ }
+}
diff --git a/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_modal.dart b/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_modal.dart
index 2f56bfaefb..f609d142d0 100644
--- a/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_modal.dart
+++ b/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_modal.dart
@@ -1,6 +1,8 @@
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/workspace/application/user/prelude.dart';
+import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy_ui/appflowy_ui.dart';
import 'package:collection/collection.dart';
import 'package:easy_localization/easy_localization.dart';
@@ -8,6 +10,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'ai_prompt_category_list.dart';
+import 'ai_prompt_database_selector.dart';
import 'ai_prompt_preview.dart';
import 'ai_prompt_visible_list.dart';
@@ -15,11 +18,20 @@ Future<AiPrompt?> showAiPromptModal(
BuildContext context, {
required AiPromptSelectorCubit aiPromptSelectorCubit,
}) async {
+ aiPromptSelectorCubit.loadCustomPrompts();
+
return showDialog<AiPrompt?>(
context: context,
- builder: (context) {
- return BlocProvider.value(
- value: aiPromptSelectorCubit,
+ builder: (_) {
+ return MultiBlocProvider(
+ providers: [
+ BlocProvider.value(
+ value: aiPromptSelectorCubit,
+ ),
+ BlocProvider.value(
+ value: context.read<UserWorkspaceBloc>(),
+ ),
+ ],
child: const AiPromptModal(),
);
},
@@ -38,91 +50,123 @@ class AiPromptModal extends StatelessWidget {
maxWidth: 1200,
maxHeight: 800,
),
- child: Column(
- children: [
- AFModalHeader(
- leading: Text(
- LocaleKeys.ai_customPrompt_browsePrompts.tr(),
- style: theme.textStyle.heading4.prominent(
- color: theme.textColorScheme.primary,
+ child: BlocListener<AiPromptSelectorCubit, AiPromptSelectorState>(
+ listener: (context, state) {
+ state.maybeMap(
+ invalidDatabase: (state) {
+ showToastNotification(
+ message: LocaleKeys.ai_customPrompt_invalidDatabase.tr(),
+ type: ToastificationType.error,
+ );
+ },
+ orElse: () {},
+ );
+ },
+ child: Column(
+ children: [
+ AFModalHeader(
+ leading: Text(
+ LocaleKeys.ai_customPrompt_browsePrompts.tr(),
+ style: theme.textStyle.heading4.prominent(
+ color: theme.textColorScheme.primary,
+ ),
),
+ trailing: [
+ BlocBuilder<AiPromptSelectorCubit, AiPromptSelectorState>(
+ buildWhen: (p, c) {
+ return p.maybeMap(
+ ready: (pr) => c.maybeMap(
+ ready: (cr) =>
+ pr.customPromptDatabaseViewId !=
+ cr.customPromptDatabaseViewId ||
+ pr.isLoadingCustomPrompts !=
+ cr.isLoadingCustomPrompts,
+ orElse: () => false,
+ ),
+ orElse: () => true,
+ );
+ },
+ builder: (context, state) {
+ return state.maybeMap(
+ ready: (readyState) => CustomPromptDatabaseSelector(
+ databaseViewId: readyState.customPromptDatabaseViewId,
+ isLoading: readyState.isLoadingCustomPrompts,
+ ),
+ orElse: () => const SizedBox.shrink(),
+ );
+ },
+ ),
+ AFGhostButton.normal(
+ onTap: () => Navigator.of(context).pop(),
+ padding: EdgeInsets.all(theme.spacing.s),
+ builder: (context, isHovering, disabled) {
+ return Center(
+ child: FlowySvg(
+ FlowySvgs.toast_close_s,
+ size: Size.square(20),
+ ),
+ );
+ },
+ ),
+ ],
),
- trailing: [
- AFGhostButton.normal(
- onTap: () => Navigator.of(context).pop(),
- padding: EdgeInsets.all(theme.spacing.s),
- builder: (context, isHovering, disabled) {
- return Center(
- child: FlowySvg(
- FlowySvgs.toast_close_s,
- size: Size.square(20),
- ),
- );
- },
- ),
- ],
- ),
- Expanded(
- child: AFModalBody(
- child: BlocBuilder<AiPromptSelectorCubit, AiPromptSelectorState>(
- builder: (context, state) {
- final theme = AppFlowyTheme.of(context);
-
- return state.map(
- loading: (_) {
- return const Center(
- child: CircularProgressIndicator(),
- );
- },
- ready: (_) {
- return Row(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Expanded(
- child: AiPromptCategoryList(
- padding: EdgeInsetsDirectional.only(
- top: theme.spacing.l,
- end: theme.spacing.l,
- ),
+ Expanded(
+ child: AFModalBody(
+ child:
+ BlocBuilder<AiPromptSelectorCubit, AiPromptSelectorState>(
+ builder: (context, state) {
+ return state.maybeMap(
+ loading: (_) {
+ return const Center(
+ child: CircularProgressIndicator(),
+ );
+ },
+ ready: (_) {
+ return Row(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ const Expanded(
+ child: AiPromptCategoryList(),
+ ),
+ const Expanded(
+ flex: 2,
+ child: AiPromptVisibleList(),
),
- ),
- Expanded(
- flex: 2,
- child: AiPromptVisibleList(),
- ),
- Expanded(
- flex: 3,
- child: BlocBuilder<AiPromptSelectorCubit,
- AiPromptSelectorState>(
- builder: (context, state) {
- final selectedPrompt = state.maybeMap(
- ready: (state) {
- return state.visiblePrompts
- .firstWhereOrNull(
- (prompt) =>
- prompt.id == state.selectedPromptId,
- );
- },
- orElse: () => null,
- );
- if (selectedPrompt == null) {
- return const SizedBox.shrink();
- }
- return AiPromptPreview(
- prompt: selectedPrompt,
- );
- },
+ Expanded(
+ flex: 3,
+ child: BlocBuilder<AiPromptSelectorCubit,
+ AiPromptSelectorState>(
+ builder: (context, state) {
+ final selectedPrompt = state.maybeMap(
+ ready: (state) {
+ return state.visiblePrompts
+ .firstWhereOrNull(
+ (prompt) =>
+ prompt.id == state.selectedPromptId,
+ );
+ },
+ orElse: () => null,
+ );
+ if (selectedPrompt == null) {
+ return const SizedBox.shrink();
+ }
+ return AiPromptPreview(
+ prompt: selectedPrompt,
+ );
+ },
+ ),
),
- ),
- ],
- );
- },
- );
- },
+ ],
+ );
+ },
+ orElse: () => const SizedBox.shrink(),
+ );
+ },
+ ),
),
),
- ),
- ],
+ ],
+ ),
),
);
}
diff --git a/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_preview.dart b/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_preview.dart
index a61570b548..7e08336124 100644
--- a/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_preview.dart
+++ b/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_preview.dart
@@ -22,10 +22,8 @@ class AiPromptPreview extends StatelessWidget {
child: Column(
children: [
Padding(
- padding: EdgeInsets.only(
- top: theme.spacing.l,
- left: theme.spacing.l,
- right: theme.spacing.l,
+ padding: EdgeInsets.symmetric(
+ horizontal: theme.spacing.l,
),
child: SelectionContainer.disabled(
child: Row(
diff --git a/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_visible_list.dart b/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_visible_list.dart
index 64b58cb4a1..1c817eb228 100644
--- a/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_visible_list.dart
+++ b/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_visible_list.dart
@@ -35,12 +35,12 @@ class _AiPromptVisibleListState extends State<AiPromptVisibleList> {
super.initState();
cubit = context.read<AiPromptSelectorCubit>();
final textController = cubit.filterTextController;
+ filterIsEmpty = textController.text.isEmpty;
+ textController.addListener(handleFilterTextChanged);
final prompts = cubit.state.maybeMap(
ready: (value) => value.visiblePrompts,
orElse: () => <AiPrompt>[],
);
- filterIsEmpty = textController.text.isEmpty;
- textController.addListener(handleFilterTextChanged);
oldList.addAll(prompts);
}
@@ -56,49 +56,56 @@ class _AiPromptVisibleListState extends State<AiPromptVisibleList> {
final spacing = AppFlowyTheme.of(context).spacing;
return BlocListener<AiPromptSelectorCubit, AiPromptSelectorState>(
listener: (context, state) {
- final list = state.maybeMap(
- ready: (state) => state.visiblePrompts,
- orElse: () => <AiPrompt>[],
+ state.maybeMap(
+ ready: (state) {
+ handleVisiblePromptListChanged(state.visiblePrompts);
+ },
+ orElse: () {},
);
- handleVisiblePromptListChanged(list);
},
child: Column(
children: [
- VSpace(spacing.l),
Padding(
padding: EdgeInsets.symmetric(horizontal: spacing.l),
child: buildSearchField(context),
),
VSpace(spacing.s),
Expanded(
- child: AnimatedList(
- controller: scrollController,
- padding: EdgeInsets.all(spacing.l),
- key: listKey,
- initialItemCount: oldList.length,
- itemBuilder: (context, index, animation) {
- final cubit = context.read<AiPromptSelectorCubit>();
+ child: TextFieldTapRegion(
+ groupId: "ai_prompt_category_list",
+ child: AnimatedList(
+ controller: scrollController,
+ padding: EdgeInsets.all(spacing.l),
+ key: listKey,
+ initialItemCount: oldList.length,
+ itemBuilder: (context, index, animation) {
+ return BlocBuilder<AiPromptSelectorCubit,
+ AiPromptSelectorState>(
+ builder: (context, state) {
+ return state.maybeMap(
+ ready: (state) {
+ final prompt = state.visiblePrompts[index];
- return cubit.state.maybeMap(
- ready: (state) {
- final prompt = state.visiblePrompts[index];
- return Padding(
- padding: EdgeInsets.only(
- top: index == 0 ? 0 : spacing.s,
- bottom: index == state.visiblePrompts.length - 1
- ? 0
- : spacing.s,
- ),
- child: _AiPromptListItem(
- animation: animation,
- prompt: prompt,
- isSelected: state.selectedPromptId == prompt.id,
- ),
- );
- },
- orElse: () => const SizedBox.shrink(),
- );
- },
+ return Padding(
+ padding: EdgeInsets.only(
+ top: index == 0 ? 0 : spacing.s,
+ bottom: index == state.visiblePrompts.length - 1
+ ? 0
+ : spacing.s,
+ ),
+ child: _AiPromptListItem(
+ animation: animation,
+ prompt: prompt,
+ isSelected: state.selectedPromptId == prompt.id,
+ ),
+ );
+ },
+ orElse: () => const SizedBox.shrink(),
+ );
+ },
+ );
+ },
+ ),
),
),
],
diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_message_selector_banner.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_message_selector_banner.dart
index 8c878acade..1f06be1b5f 100644
--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_message_selector_banner.dart
+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_message_selector_banner.dart
@@ -1,7 +1,6 @@
import 'dart:async';
import 'package:appflowy/ai/ai.dart';
-import 'package:appflowy/ai/widgets/view_selector.dart';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_edit_document_service.dart';
diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_message_action_bar.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_message_action_bar.dart
index 292c66f165..96c7d70a5d 100644
--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_message_action_bar.dart
+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/message/ai_message_action_bar.dart
@@ -2,7 +2,6 @@ import 'dart:async';
import 'dart:convert';
import 'package:appflowy/ai/ai.dart';
-import 'package:appflowy/ai/widgets/view_selector.dart';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_ai_message_bloc.dart';
diff --git a/frontend/resources/translations/en.json b/frontend/resources/translations/en.json
index c603952443..75ef45d7b1 100644
--- a/frontend/resources/translations/en.json
+++ b/frontend/resources/translations/en.json
@@ -3330,6 +3330,12 @@
"browsePrompts": "Browse prompts",
"usePrompt": "Use prompt",
"featured": "Featured",
+ "custom": "Custom",
+ "loadDatabasePrompts": "Custom prompts from your database",
+ "loadDatabasePromptsFrom": "Load custom prompts from...",
+ "selectDatabase": "Select database",
+ "loading": "Loading...",
+ "invalidDatabase": "Failed to load custom prompts from database",
"all": "All",
"development": "Development",
"writing": "Writing",
@@ -3386,4 +3392,4 @@
"rewrite": "Rewrite",
"insertBelow": "Insert below"
}
-}
\ No newline at end of file
+}
diff --git a/frontend/rust-lib/flowy-ai-pub/src/cloud.rs b/frontend/rust-lib/flowy-ai-pub/src/cloud.rs
index 19b185c9b0..8e2066640e 100644
--- a/frontend/rust-lib/flowy-ai-pub/src/cloud.rs
+++ b/frontend/rust-lib/flowy-ai-pub/src/cloud.rs
@@ -185,6 +185,7 @@ pub trait ChatCloudService: Send + Sync + 'static {
) -> Result<(), FlowyError>;
async fn get_available_models(&self, workspace_id: &Uuid) -> Result<ModelList, FlowyError>;
+
async fn get_workspace_default_model(&self, workspace_id: &Uuid) -> Result<String, FlowyError>;
async fn set_workspace_default_model(
&self,
diff --git a/frontend/rust-lib/flowy-ai/Cargo.toml b/frontend/rust-lib/flowy-ai/Cargo.toml
index 2080b56985..ea76bdbae6 100644
--- a/frontend/rust-lib/flowy-ai/Cargo.toml
+++ b/frontend/rust-lib/flowy-ai/Cargo.toml
@@ -76,4 +76,4 @@ default = []
dart = ["flowy-codegen/dart", "flowy-notification/dart"]
local_ai = []
file_reader = ["lopdf", "pulldown-cmark"]
-ai-tool = []
\ No newline at end of file
+ai-tool = []
diff --git a/frontend/rust-lib/flowy-ai/src/ai_manager.rs b/frontend/rust-lib/flowy-ai/src/ai_manager.rs
index cf1c500ea7..bbda3e75ad 100644
--- a/frontend/rust-lib/flowy-ai/src/ai_manager.rs
+++ b/frontend/rust-lib/flowy-ai/src/ai_manager.rs
@@ -722,6 +722,28 @@ impl AIManager {
sync_chat_documents(user_service, external_service, rag_ids).await?;
Ok(())
}
+
+ pub async fn get_custom_prompt_database_view_id(&self) -> FlowyResult<Option<String>> {
+ let view_id = self
+ .store_preferences
+ .get_object::<String>(CUSTOM_PROMPT_DATABASE_VIEW_ID_KEY);
+
+ Ok(view_id)
+ }
+
+ pub async fn set_custom_prompt_database_view_id(&self, view_id: String) -> FlowyResult<()> {
+ if let Err(err) = self
+ .store_preferences
+ .set_object(CUSTOM_PROMPT_DATABASE_VIEW_ID_KEY, &view_id)
+ {
+ error!(
+ "failed to set custom prompt database view id settings: {}",
+ err
+ );
+ }
+
+ Ok(())
+ }
}
async fn sync_chat_documents(
@@ -784,3 +806,5 @@ async fn refresh_chat_setting(
fn setting_store_key(chat_id: &Uuid) -> String {
format!("chat_settings_{}", chat_id)
}
+
+const CUSTOM_PROMPT_DATABASE_VIEW_ID_KEY: &str = "custom_prompt_database_view_id";
diff --git a/frontend/rust-lib/flowy-ai/src/entities.rs b/frontend/rust-lib/flowy-ai/src/entities.rs
index d4fcb15096..0364084e15 100644
--- a/frontend/rust-lib/flowy-ai/src/entities.rs
+++ b/frontend/rust-lib/flowy-ai/src/entities.rs
@@ -748,3 +748,9 @@ impl From<PendingResource> for LackOfAIResourcePB {
}
}
}
+
+#[derive(Default, ProtoBuf, Clone, Debug)]
+pub struct CustomPromptDatabaseViewIdPB {
+ #[pb(index = 1)]
+ pub id: String,
+}
diff --git a/frontend/rust-lib/flowy-ai/src/event_handler.rs b/frontend/rust-lib/flowy-ai/src/event_handler.rs
index 2de5ad96f1..675ee6b43a 100644
--- a/frontend/rust-lib/flowy-ai/src/event_handler.rs
+++ b/frontend/rust-lib/flowy-ai/src/event_handler.rs
@@ -362,3 +362,36 @@ pub(crate) async fn update_local_ai_setting_handler(
ai_manager.update_local_ai_setting(data.into()).await?;
Ok(())
}
+
+#[tracing::instrument(level = "debug", skip_all, err)]
+pub(crate) async fn get_custom_prompt_database_view_id_handler(
+ ai_manager: AFPluginState<Weak<AIManager>>,
+) -> DataResult<CustomPromptDatabaseViewIdPB, FlowyError> {
+ let ai_manager = upgrade_ai_manager(ai_manager)?;
+ let id = ai_manager
+ .get_custom_prompt_database_view_id()
+ .await?
+ .ok_or_else(|| {
+ FlowyError::new(
+ ErrorCode::RecordNotFound,
+ "Custom prompt database view id not found",
+ )
+ })?;
+
+ data_result_ok(CustomPromptDatabaseViewIdPB { id })
+}
+
+#[tracing::instrument(level = "debug", skip_all, err)]
+pub(crate) async fn set_custom_prompt_database_view_id_handler(
+ data: AFPluginData<CustomPromptDatabaseViewIdPB>,
+ ai_manager: AFPluginState<Weak<AIManager>>,
+) -> Result<(), FlowyError> {
+ let ai_manager = upgrade_ai_manager(ai_manager)?;
+ let view_id = data.into_inner().id;
+
+ ai_manager
+ .set_custom_prompt_database_view_id(view_id)
+ .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 df0721b361..eb72081467 100644
--- a/frontend/rust-lib/flowy-ai/src/event_map.rs
+++ b/frontend/rust-lib/flowy-ai/src/event_map.rs
@@ -50,6 +50,14 @@ pub fn init(ai_manager: Weak<AIManager>) -> AFPlugin {
get_setting_model_selection_handler,
)
.event(AIEvent::UpdateSelectedModel, update_selected_model_handler)
+ .event(
+ AIEvent::GetCustomPromptDatabaseViewId,
+ get_custom_prompt_database_view_id_handler,
+ )
+ .event(
+ AIEvent::SetCustomPromptDatabaseViewId,
+ set_custom_prompt_database_view_id_handler,
+ )
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Display, Hash, ProtoBuf_Enum, Flowy_Event)]
@@ -128,4 +136,10 @@ pub enum AIEvent {
#[event(input = "ModelSourcePB", output = "ModelSelectionPB")]
GetSourceModelSelection = 34,
+
+ #[event(output = "CustomPromptDatabaseViewIdPB")]
+ GetCustomPromptDatabaseViewId = 35,
+
+ #[event(input = "CustomPromptDatabaseViewIdPB")]
+ SetCustomPromptDatabaseViewId = 36,
}
diff --git a/frontend/rust-lib/flowy-database-pub/Cargo.toml b/frontend/rust-lib/flowy-database-pub/Cargo.toml
index 088c7b6465..483eeb894d 100644
--- a/frontend/rust-lib/flowy-database-pub/Cargo.toml
+++ b/frontend/rust-lib/flowy-database-pub/Cargo.toml
@@ -11,4 +11,4 @@ collab-entity = { workspace = true }
collab = { workspace = true }
client-api = { workspace = true }
flowy-error = { workspace = true }
-uuid.workspace = true
\ No newline at end of file
+uuid.workspace = true
diff --git a/frontend/rust-lib/flowy-database2/Cargo.toml b/frontend/rust-lib/flowy-database2/Cargo.toml
index ec0eb94210..990f426029 100644
--- a/frontend/rust-lib/flowy-database2/Cargo.toml
+++ b/frontend/rust-lib/flowy-database2/Cargo.toml
@@ -63,4 +63,4 @@ flowy-codegen.workspace = true
[features]
dart = ["flowy-codegen/dart", "flowy-notification/dart"]
-verbose_log = ["collab-database/verbose_log"]
\ No newline at end of file
+verbose_log = ["collab-database/verbose_log"]
diff --git a/frontend/rust-lib/flowy-database2/src/entities/database_entities.rs b/frontend/rust-lib/flowy-database2/src/entities/database_entities.rs
index 2562bd84f7..e2299fe8af 100644
--- a/frontend/rust-lib/flowy-database2/src/entities/database_entities.rs
+++ b/frontend/rust-lib/flowy-database2/src/entities/database_entities.rs
@@ -349,3 +349,27 @@ impl TryInto<RemoveCoverParams> for RemoveCoverPayloadPB {
})
}
}
+
+#[derive(Default, ProtoBuf, Clone, Debug)]
+pub struct RepeatedCustomPromptPB {
+ #[pb(index = 1)]
+ pub items: Vec<CustomPromptPB>,
+}
+
+#[derive(Default, ProtoBuf, Clone, Debug)]
+pub struct CustomPromptPB {
+ #[pb(index = 1)]
+ pub id: String,
+
+ #[pb(index = 2)]
+ pub name: String,
+
+ #[pb(index = 3)]
+ pub content: String,
+
+ #[pb(index = 4)]
+ pub example: String,
+
+ #[pb(index = 5)]
+ pub category: String,
+}
diff --git a/frontend/rust-lib/flowy-database2/src/event_handler.rs b/frontend/rust-lib/flowy-database2/src/event_handler.rs
index 63d6fdf2c3..47e280565e 100644
--- a/frontend/rust-lib/flowy-database2/src/event_handler.rs
+++ b/frontend/rust-lib/flowy-database2/src/event_handler.rs
@@ -1413,3 +1413,22 @@ pub(crate) async fn rename_media_cell_file_handler(
Ok(())
}
+
+#[tracing::instrument(level = "debug", skip(manager), err)]
+pub(crate) async fn get_database_custom_prompts_handler(
+ data: AFPluginData<DatabaseViewIdPB>,
+ manager: AFPluginState<Weak<DatabaseManager>>,
+) -> DataResult<RepeatedCustomPromptPB, FlowyError> {
+ let manager = upgrade_manager(manager)?;
+ let params: DatabaseViewIdPB = data.try_into_inner()?;
+ let database_editor = manager
+ .get_database_editor_with_view_id(params.as_ref())
+ .await?;
+ let custom_prompts = database_editor
+ .get_prompts_from_database(params.as_ref())
+ .await?;
+
+ data_result_ok(RepeatedCustomPromptPB {
+ items: custom_prompts,
+ })
+}
diff --git a/frontend/rust-lib/flowy-database2/src/event_map.rs b/frontend/rust-lib/flowy-database2/src/event_map.rs
index 824565e5b8..1053d8d910 100644
--- a/frontend/rust-lib/flowy-database2/src/event_map.rs
+++ b/frontend/rust-lib/flowy-database2/src/event_map.rs
@@ -98,6 +98,10 @@ pub fn init(database_manager: Weak<DatabaseManager>) -> AFPlugin {
// Media
.event(DatabaseEvent::UpdateMediaCell, update_media_cell_handler)
.event(DatabaseEvent::RenameMediaFile, rename_media_cell_file_handler)
+ .event(
+ DatabaseEvent::GetDatabaseCustomPrompts,
+ get_database_custom_prompts_handler,
+ )
}
/// [DatabaseEvent] defines events that are used to interact with the Grid. You could check [this](https://appflowy.gitbook.io/docs/essential-documentation/contribute-to-appflowy/architecture/backend/protobuf)
@@ -401,4 +405,7 @@ pub enum DatabaseEvent {
#[event(input = "RenameMediaChangesetPB")]
RenameMediaFile = 201,
+
+ #[event(input = "DatabaseViewIdPB", output = "RepeatedCustomPromptPB")]
+ GetDatabaseCustomPrompts = 500,
}
diff --git a/frontend/rust-lib/flowy-database2/src/services/database/database_editor.rs b/frontend/rust-lib/flowy-database2/src/services/database/database_editor.rs
index e9c8d3afdd..7d513274a9 100644
--- a/frontend/rust-lib/flowy-database2/src/services/database/database_editor.rs
+++ b/frontend/rust-lib/flowy-database2/src/services/database/database_editor.rs
@@ -1,7 +1,7 @@
use crate::entities::*;
use crate::notification::{database_notification_builder, DatabaseNotification};
use crate::services::calculations::Calculation;
-use crate::services::cell::{apply_cell_changeset, get_cell_protobuf, CellCache};
+use crate::services::cell::{apply_cell_changeset, get_cell_protobuf, stringify_cell, CellCache};
use crate::services::database::database_observe::*;
use crate::services::database::util::database_view_setting_pb_from_view;
use crate::services::database_view::{
@@ -1854,6 +1854,70 @@ impl DatabaseEditor {
}
}
+ pub async fn get_prompts_from_database(
+ &self,
+ view_id: &str,
+ ) -> Result<Vec<CustomPromptPB>, FlowyError> {
+ let fields = self.get_fields(view_id, None).await;
+ let primary_field = fields
+ .iter()
+ .find(|f| f.is_primary)
+ .ok_or(FlowyError::internal().with_context("Cannot find primary field"))?;
+ let content_field = fields
+ .iter()
+ .find(|f| f.name.to_lowercase() == "content" && f.field_type == FieldType::RichText.value())
+ .or_else(|| {
+ fields
+ .iter()
+ .find(|f| !f.is_primary && f.field_type == FieldType::RichText.value())
+ })
+ .ok_or(FlowyError::internal().with_context("Cannot find content field"))?;
+ let example_field = fields.iter().find(|f| f.name.to_lowercase() == "example");
+ let category_field = fields.iter().find(|f| f.name.to_lowercase() == "category");
+
+ fn extract_cell_value(row: &Row, field: &Field) -> Option<String> {
+ row
+ .cells
+ .get(&field.id)
+ .map(|cell| stringify_cell(cell, field))
+ }
+
+ let custom_prompts = self
+ .get_all_rows(view_id)
+ .await?
+ .into_iter()
+ .filter_map(|row| {
+ let id = row.id.to_string();
+
+ let primary_cell = row.cells.get(&primary_field.id);
+ let name = primary_cell
+ .map(|cell| stringify_cell(cell, primary_field))
+ .unwrap_or_default();
+
+ let content_cell = row.cells.get(&content_field.id);
+ let content = content_cell.map(|cell| stringify_cell(cell, content_field))?;
+
+ let example = example_field
+ .and_then(|field| extract_cell_value(&row, field))
+ .unwrap_or_default();
+
+ let category = category_field
+ .and_then(|field| extract_cell_value(&row, field))
+ .unwrap_or_else(|| "other".to_string());
+
+ Some(CustomPromptPB {
+ id,
+ name,
+ content,
+ example,
+ category,
+ })
+ })
+ .collect::<Vec<_>>();
+
+ Ok(custom_prompts)
+ }
+
async fn get_auto_updated_fields(&self, view_id: &str) -> Vec<Field> {
self
.database