diff --git a/apps/client/lib/features/ai_hub/data/ai_thread_repository.dart b/apps/client/lib/features/ai_hub/data/ai_thread_repository.dart new file mode 100644 index 00000000..16e79441 --- /dev/null +++ b/apps/client/lib/features/ai_hub/data/ai_thread_repository.dart @@ -0,0 +1,50 @@ +import 'package:dio/dio.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import '../../../core/api/dio_client.dart'; +import '../../auth/domain/auth_provider.dart'; +import '../../chat/domain/chat_state.dart'; + +/// chat-service `/api/ai-threads`: each "new chat" with the AI is its own +/// conversation. Mirrors web `aiThreadsApi`. Delete reuses the per-user +/// `ChatRepository.deleteConversation`. +class AiThreadRepository { + final Dio _dio; + + const AiThreadRepository(this._dio); + + /// Caller's threads, newest activity first (max 100, hidden excluded). + Future> list() async { + final response = await _dio.get('/api/ai-threads'); + final data = response.data as List? ?? []; + return data + .map((e) => ConversationModel.fromJson(e as Map)) + .toList(); + } + + /// A new, untitled thread (`name` null until auto-title / rename). + Future create() async { + final response = await _dio.post('/api/ai-threads'); + return ConversationModel.fromJson(response.data as Map); + } + + /// 400 `AI_THREAD_NAME_INVALID` unless 1-80 chars after trim; 404 not mine. + Future rename(String id, String name) async { + final response = await _dio.patch( + '/api/ai-threads/${Uri.encodeComponent(id)}', + data: {'name': name}, + ); + return ConversationModel.fromJson(response.data as Map); + } +} + +final aiThreadRepositoryProvider = Provider((ref) { + const storage = FlutterSecureStorage(); + return AiThreadRepository( + DioClient.createChatDio( + storage, + onForceLogout: () => + ref.read(authNotifierProvider.notifier).forceLogout(), + ), + ); +}); diff --git a/apps/client/lib/features/ai_hub/domain/ai_threads_provider.dart b/apps/client/lib/features/ai_hub/domain/ai_threads_provider.dart new file mode 100644 index 00000000..07467346 --- /dev/null +++ b/apps/client/lib/features/ai_hub/domain/ai_threads_provider.dart @@ -0,0 +1,191 @@ +import 'dart:async'; + +import 'package:collection/collection.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../auth/domain/auth_provider.dart'; +import '../../auth/domain/auth_state.dart'; +import '../../chat/data/chat_repository.dart'; +import '../../chat/data/stomp_service.dart'; +import '../../chat/domain/chat_state.dart'; +import '../../chat/domain/conversation_list_ops.dart'; +import '../../../core/router/app_router.dart'; +import '../../home/domain/home_providers.dart'; +import '../data/ai_thread_repository.dart'; + +/// Whether the user is looking at conversation `id` right now (mobile route +/// or wide-layout detail pane). Overridable in tests. +final aiThreadViewingProvider = Provider((ref) { + return (id) { + final path = + ref.read(appRouterProvider).routeInformationProvider.value.uri.path; + return path == '/chat/$id' || ref.read(selectedConversationIdProvider) == id; + }; +}); + +/// The caller's AI threads, newest activity first. Kept current from realtime +/// (mirror of web `['ai-threads']` cache): the main conversation list never +/// holds them. +final aiThreadsProvider = + AsyncNotifierProvider>( + AiThreadsNotifier.new); + +class AiThreadsNotifier extends AsyncNotifier> { + @override + Future> build() async { + final stomp = ref.read(stompServiceProvider.notifier); + final subs = >[ + stomp.conversationUpdates.listen(_onConversationUpdate), + stomp.notifications.listen(_onNotification), + // Notifications fired during a socket gap were lost: catch up. + stomp.reconnects.listen((_) => unawaited(_silentRefetch())), + ]; + ref.onDispose(() { + for (final s in subs) { + s.cancel(); + } + }); + return ref.read(aiThreadRepositoryProvider).list(); + } + + String? get _currentUserId { + final auth = ref.read(authNotifierProvider).valueOrNull; + return auth is AuthAuthenticated ? auth.user.id : null; + } + + /// Creates a thread and puts it on top. + Future create() async { + final conv = await ref.read(aiThreadRepositoryProvider).create(); + // The initial load may still be running: wait so the thread isn't dropped. + try { + await future; + } catch (_) {} + _setList((l) => ConversationListOps.upsertFront(l, conv)); + return conv; + } + + /// Renames a thread in place (position kept). + Future rename(String id, String name) async { + final conv = await ref.read(aiThreadRepositoryProvider).rename(id, name); + _setList((l) => [for (final c in l) c.id == id ? conv : c]); + return conv; + } + + /// Hides a thread for me (existing per-user delete). Optimistic; on failure + /// the list is refetched and the error rethrown for the caller to show. + Future delete(String id) async { + _setList((l) => l.where((c) => c.id != id).toList()); + try { + await ref.read(chatRepositoryProvider).deleteConversation(id); + } catch (_) { + await _silentRefetch(); + rethrow; + } + } + + /// Server-side hide only; the list is untouched (rethrows on failure). + /// Pair with [drop] once the caller has navigated away from the thread. + Future deleteOnServer(String id) => + ref.read(chatRepositoryProvider).deleteConversation(id); + + /// Removes a thread from the list (after [deleteOnServer] succeeded). + void drop(String id) => _setList((l) => l.where((c) => c.id != id).toList()); + + /// Newest thread, creating the first one when there are none. Always asks + /// the server (a stale cache must not hide a thread made elsewhere). + Future newestOrCreate() async { + final threads = await ref.read(aiThreadRepositoryProvider).list(); + state = AsyncData(threads); + final first = threads.firstOrNull; + return first ?? await create(); + } + + /// Puts [conv] into the list (once loaded). + void upsert(ConversationModel conv) { + if (!conv.isAiConversation) return; + void apply() => _setList((l) => l.any((c) => c.id == conv.id) + ? [for (final c in l) c.id == conv.id ? conv : c] + : ConversationListOps.upsertFront(l, conv)); + if (state.hasValue) { + apply(); + } else { + // Not loaded yet (e.g. opened from a push before the hub): apply once + // it is; replace-or-insert is idempotent if the fetch already has it. + future.then((_) => apply(), onError: (_) {}); + } + } + + bool contains(String id) => + state.valueOrNull?.any((c) => c.id == id) ?? false; + + void _setList(List Function(List) fn) { + final current = state.valueOrNull; + if (current == null) return; + state = AsyncData(fn(current)); + } + + Future _silentRefetch() async { + final result = await AsyncValue.guard( + () => ref.read(aiThreadRepositoryProvider).list()); + if (result.hasValue) state = result; + } + + void _onConversationUpdate(ConversationUpdateEvent event) { + final id = event.conversationId; + final participants = event.json['participants']; + if (id == null || + participants is! List || + !isAiConversationJson(event.json)) { + return; + } + final me = _currentUserId; + if (me != null && !participants.contains(me)) { + _setList((l) => l.where((c) => c.id != id).toList()); + return; + } + final current = state.valueOrNull; + if (current == null) return; + final idx = current.indexWhere((c) => c.id == id); + if (idx < 0) { + if (event.personal) { + // A thread made on another device / by POST: insert at the top. + _setList((l) => ConversationListOps.upsertFront( + l, ConversationModel.fromJson(event.json))); + } else { + unawaited(_silentRefetch()); + } + return; + } + final merged = current[idx].mergeJson(event.json); + if (event.personal) { + _setList((l) => [for (final c in l) c.id == id ? merged : c]); + } else { + _setList((l) => ConversationListOps.upsertSorted( + l.where((c) => c.id != id).toList(), merged)); + } + } + + void _onNotification(Map notif) { + final type = notif['type']; + if (type != 'NEW_MESSAGE' && type != 'MENTIONED_YOU') return; + final notice = IncomingMessageNotice.fromJson(notif); + final current = state.valueOrNull; + if (notice == null || current == null) return; + final conv = current.firstWhereOrNull((c) => c.id == notice.conversationId); + if (conv == null) return; + if (notice.messageId != null && conv.lastMessage?.messageId == notice.messageId) { + return; + } + final updated = ConversationListOps.applyIncomingMessage( + current, + conversationId: notice.conversationId, + senderId: notice.senderId, + viewing: ref.read(aiThreadViewingProvider)(notice.conversationId), + content: notice.content, + messageType: notice.messageType, + messageId: notice.messageId, + createdAt: notice.createdAt, + ); + if (updated != null) state = AsyncData(updated); + } +} diff --git a/apps/client/lib/features/ai_hub/ui/ai_hub_screen.dart b/apps/client/lib/features/ai_hub/ui/ai_hub_screen.dart index 3a251618..0c444bee 100644 --- a/apps/client/lib/features/ai_hub/ui/ai_hub_screen.dart +++ b/apps/client/lib/features/ai_hub/ui/ai_hub_screen.dart @@ -4,22 +4,23 @@ import 'package:go_router/go_router.dart'; import '../../../core/l10n/l10n_ext.dart'; import '../../../core/theme/app_theme.dart'; import '../../../core/widgets/pon_widgets.dart'; -import '../../chat/data/chat_repository.dart'; -import '../../chat/domain/chat_state.dart' show kAiBotUserId; +import '../domain/ai_threads_provider.dart'; import 'widgets/ai_hub_tile.dart'; +import 'widgets/ai_thread_list.dart'; import '../../../core/utils/global_messenger.dart'; import '../../chat/utils/chat_error.dart'; -/// Opens (or creates) the conversation with the PON AI bot and navigates to it. +/// Opens the newest AI thread (creating the first one when there are none) +/// and navigates to it. /// /// Shared entry point for the AI chat: reused by [AiHubScreen]'s hero CTA and /// any other surface that previously called `_startAiChat`. Mirrors the web -/// `handleOpenAiChat` (create-or-get + navigate). Returns once navigation is +/// `useOpenAiChat`. Returns once navigation is /// issued; on failure it shows a localized error snackbar and stays put. Future startAiChat(BuildContext context, WidgetRef ref) async { try { - final repo = ref.read(chatRepositoryProvider); - final conv = await repo.getOrCreateConversation(kAiBotUserId); + final conv = + await ref.read(aiThreadsProvider.notifier).newestOrCreate(); if (context.mounted) context.go('/chat/${conv.id}'); } catch (e) { // The Hub keeps the user on-screen; say why so they can retry. @@ -58,7 +59,7 @@ class _AiHubScreenState extends ConsumerState { title: Text(l10n.aiHubTitle), leading: IconButton( icon: const Icon(Icons.arrow_back_ios_new_rounded, size: 20), - onPressed: () => context.pop(), + onPressed: () => context.canPop() ? context.pop() : context.go('/'), ), ), body: SafeArea( @@ -79,6 +80,14 @@ class _AiHubScreenState extends ConsumerState { _HeroCard(loading: _startingChat, onTap: _onStartChat), const SizedBox(height: 20), _HubGrid(), + const SizedBox(height: 20), + Text( + l10n.aiThreadsTitle, + style: const TextStyle( + fontSize: 16, fontWeight: FontWeight.w600), + ), + const SizedBox(height: 4), + const AiThreadList(), ], ), ), diff --git a/apps/client/lib/features/ai_hub/ui/widgets/ai_new_chat_button.dart b/apps/client/lib/features/ai_hub/ui/widgets/ai_new_chat_button.dart new file mode 100644 index 00000000..26918a2d --- /dev/null +++ b/apps/client/lib/features/ai_hub/ui/widgets/ai_new_chat_button.dart @@ -0,0 +1,41 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; +import '../../../../core/l10n/l10n_ext.dart'; +import '../../../../core/utils/global_messenger.dart'; +import '../../domain/ai_threads_provider.dart'; + +/// Chat header "new AI chat" action. Disabled while a create is pending so a +/// double tap cannot make two threads (web: `disabled={createThread.isPending}`). +class AiNewChatButton extends ConsumerStatefulWidget { + const AiNewChatButton({super.key}); + + @override + ConsumerState createState() => _AiNewChatButtonState(); +} + +class _AiNewChatButtonState extends ConsumerState { + bool _creating = false; + + Future _create() async { + if (_creating) return; + final router = GoRouter.of(context); + final failed = context.l10n.aiThreadCreateFailed; + setState(() => _creating = true); + try { + final c = await ref.read(aiThreadsProvider.notifier).create(); + router.go('/chat/${c.id}'); + } catch (_) { + showErrorSnackBar(failed); + } finally { + if (mounted) setState(() => _creating = false); + } + } + + @override + Widget build(BuildContext context) => IconButton( + tooltip: context.l10n.aiThreadNew, + icon: const Icon(Icons.add_comment_outlined, size: 22), + onPressed: _creating ? null : _create, + ); +} diff --git a/apps/client/lib/features/ai_hub/ui/widgets/ai_thread_item.dart b/apps/client/lib/features/ai_hub/ui/widgets/ai_thread_item.dart new file mode 100644 index 00000000..a0a62565 --- /dev/null +++ b/apps/client/lib/features/ai_hub/ui/widgets/ai_thread_item.dart @@ -0,0 +1,172 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart' show MaxLengthEnforcement; +import '../../../../core/l10n/l10n_ext.dart'; +import '../../../../core/theme/app_theme.dart'; +import '../../../chat/domain/chat_state.dart'; + +/// Display title of an AI thread: trimmed name, else the localized untitled +/// label (mirror of web `thread.name?.trim() || t('untitled')`). +String aiThreadTitle(BuildContext context, ConversationModel thread) { + final name = thread.name?.trim(); + return (name == null || name.isEmpty) + ? context.l10n.aiThreadUntitled + : name; +} + +/// One row of the AI thread list: tap to open, inline rename, delete. +class AiThreadItem extends StatefulWidget { + final ConversationModel thread; + final bool active; + final VoidCallback onOpen; + + /// Resolves to an error text to show under the editor, or null on success + /// (the editor then closes). + final Future Function(String id, String name) onRename; + final ValueChanged onDelete; + + const AiThreadItem({ + super.key, + required this.thread, + required this.active, + required this.onOpen, + required this.onRename, + required this.onDelete, + }); + + @override + State createState() => _AiThreadItemState(); +} + +class _AiThreadItemState extends State { + final _ctrl = TextEditingController(); + bool _editing = false; + bool _saving = false; + String? _error; + + @override + void dispose() { + _ctrl.dispose(); + super.dispose(); + } + + void _startEdit() { + _ctrl.text = widget.thread.name ?? ''; + setState(() { + _editing = true; + _error = null; + }); + } + + void _cancel() => setState(() { + _editing = false; + _error = null; + }); + + Future _save() async { + if (_saving) return; + final name = _ctrl.text.trim(); + if (name == (widget.thread.name ?? '')) return _cancel(); + setState(() => _saving = true); + final err = await widget.onRename(widget.thread.id, name); + if (!mounted) return; + setState(() { + _saving = false; + _error = err; + if (err == null) _editing = false; + }); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + if (_editing) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: TextField( + controller: _ctrl, + autofocus: true, + maxLength: 80, + maxLengthEnforcement: MaxLengthEnforcement.enforced, + textInputAction: TextInputAction.done, + onSubmitted: (_) => _save(), + decoration: InputDecoration( + isDense: true, + counterText: '', + errorText: _error, + errorMaxLines: 2, + ), + ), + ), + IconButton( + tooltip: l10n.aiThreadSave, + icon: const Icon(Icons.check_rounded, size: 20), + onPressed: _saving ? null : _save, + ), + IconButton( + tooltip: l10n.aiThreadCancel, + icon: const Icon(Icons.close_rounded, size: 20), + onPressed: _saving ? null : _cancel, + ), + ], + ), + ); + } + + final title = aiThreadTitle(context, widget.thread); + final scheme = Theme.of(context).colorScheme; + return Container( + key: widget.active + ? ValueKey('ai-thread-active-${widget.thread.id}') + : null, + margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: widget.active + ? AppTheme.accent(context).withValues(alpha: 0.12) + : null, + borderRadius: BorderRadius.circular(10), + ), + child: Row( + children: [ + Expanded( + child: InkWell( + borderRadius: BorderRadius.circular(10), + onTap: widget.onOpen, + child: Padding( + padding: + const EdgeInsets.symmetric(horizontal: 12, vertical: 12), + child: Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 14, + color: scheme.onSurface, + fontWeight: + widget.active ? FontWeight.w600 : FontWeight.w400, + ), + ), + ), + ), + ), + IconButton( + tooltip: l10n.aiThreadRename, + visualDensity: VisualDensity.compact, + icon: const Icon(Icons.edit_outlined, size: 18), + onPressed: _startEdit, + ), + IconButton( + tooltip: l10n.aiThreadDelete, + visualDensity: VisualDensity.compact, + icon: Icon(Icons.delete_outline_rounded, + size: 18, color: scheme.error), + onPressed: () => widget.onDelete(widget.thread), + ), + ], + ), + ); + } +} diff --git a/apps/client/lib/features/ai_hub/ui/widgets/ai_thread_list.dart b/apps/client/lib/features/ai_hub/ui/widgets/ai_thread_list.dart new file mode 100644 index 00000000..6ae35a1e --- /dev/null +++ b/apps/client/lib/features/ai_hub/ui/widgets/ai_thread_list.dart @@ -0,0 +1,150 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; +import '../../../../core/l10n/l10n_ext.dart'; +import '../../../../core/utils/global_messenger.dart'; +import '../../../chat/domain/chat_state.dart'; +import '../../../chat/ui/chat_screen_helpers.dart' show showConfirmDialog; +import '../../../chat/utils/chat_error.dart'; +import '../../domain/ai_threads_provider.dart'; +import 'ai_thread_item.dart'; + +/// ChatGPT-style list of the caller's AI threads with a "new conversation" +/// button, inline rename and confirmed delete. Mirror of web `AiThreadList`. +/// +/// [openId] is the thread currently open (highlighted; deleting it navigates +/// away first). [onNavigate] runs before any navigation (e.g. close a sheet). +class AiThreadList extends ConsumerStatefulWidget { + final String? openId; + final VoidCallback? onNavigate; + const AiThreadList({super.key, this.openId, this.onNavigate}); + + @override + ConsumerState createState() => _AiThreadListState(); +} + +class _AiThreadListState extends ConsumerState { + bool _creating = false; + + void _open(String id) { + widget.onNavigate?.call(); + context.go('/chat/$id'); + } + + Future _create() async { + if (_creating) return; + setState(() => _creating = true); + try { + final conv = await ref.read(aiThreadsProvider.notifier).create(); + if (mounted) _open(conv.id); + } catch (_) { + if (mounted) showErrorSnackBar(context.l10n.aiThreadCreateFailed); + } finally { + if (mounted) setState(() => _creating = false); + } + } + + /// Error text for the inline editor, or null on success. + Future _rename(String id, String name) async { + final l10n = context.l10n; + try { + await ref.read(aiThreadsProvider.notifier).rename(id, name); + return null; + } catch (e) { + return chatErrorCode(e) == 'AI_THREAD_NAME_INVALID' + ? l10n.aiThreadNameInvalid + : l10n.aiThreadRenameFailed; + } + } + + Future _delete(ConversationModel target) async { + final l10n = context.l10n; + final ok = await showConfirmDialog(context, + title: l10n.aiThreadDeleteTitle, body: l10n.aiThreadDeleteDesc); + if (ok != true || !mounted) return; + final list = ref.read(aiThreadsProvider).valueOrNull ?? const []; + final idx = list.indexWhere((c) => c.id == target.id); + final next = (idx >= 0 && idx + 1 < list.length) + ? list[idx + 1] + : (idx > 0 ? list[idx - 1] : null); + final notifier = ref.read(aiThreadsProvider.notifier); + try { + // Server first (web parity): on failure stay on the thread. + await notifier.deleteOnServer(target.id); + } catch (_) { + showErrorSnackBar(l10n.aiThreadDeleteFailed); + return; + } + // Navigate away BEFORE dropping the row (replace, so Back never returns + // to it): the chat screen still observes the open id otherwise. + if (mounted && widget.openId == target.id) { + widget.onNavigate?.call(); + context.go(next != null ? '/chat/${next.id}' : '/ai-hub'); + } + notifier.drop(target.id); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final threads = ref.watch(aiThreadsProvider); + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(12, 8, 12, 4), + child: OutlinedButton.icon( + onPressed: _creating ? null : _create, + icon: _creating + ? const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 2)) + : const Icon(Icons.add_rounded, size: 18), + label: Text(l10n.aiThreadNew), + ), + ), + threads.when( + loading: () => const Padding( + padding: EdgeInsets.all(24), + child: Center(child: CircularProgressIndicator(strokeWidth: 2)), + ), + error: (_, __) => Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + Text(l10n.aiThreadLoadFailed, textAlign: TextAlign.center), + TextButton( + onPressed: () => ref.invalidate(aiThreadsProvider), + child: Text(l10n.actionRetry), + ), + ], + ), + ), + data: (list) => list.isEmpty + ? Padding( + padding: const EdgeInsets.all(16), + child: Text(l10n.aiThreadEmpty, textAlign: TextAlign.center), + ) + : Flexible( + child: ListView( + shrinkWrap: true, + children: [ + for (final t in list) + AiThreadItem( + key: ValueKey('ai-thread-${t.id}'), + thread: t, + active: t.id == widget.openId, + onOpen: () => _open(t.id), + onRename: _rename, + onDelete: _delete, + ), + ], + ), + ), + ), + ], + ); + } +} diff --git a/apps/client/lib/features/auth/domain/session_reset.dart b/apps/client/lib/features/auth/domain/session_reset.dart index 4a41a9fe..3271a0d9 100644 --- a/apps/client/lib/features/auth/domain/session_reset.dart +++ b/apps/client/lib/features/auth/domain/session_reset.dart @@ -6,12 +6,12 @@ import '../../admin/state/capabilities_provider.dart'; import '../../admin/state/usage_dashboard_provider.dart'; import '../../ai_context/domain/ai_context_providers.dart'; import '../../assistant/state/assistant_provider.dart'; +import '../../ai_hub/domain/ai_threads_provider.dart'; import '../../chat/data/stomp_service.dart'; import '../../chat/domain/active_call_provider.dart'; import '../../chat/domain/ai_actions_provider.dart'; import '../../chat/domain/ai_memory_provider.dart'; import '../../chat/domain/ai_persona_provider.dart'; -import '../../chat/domain/ai_session_provider.dart'; import '../../chat/domain/chat_provider.dart'; import '../../chat/domain/group_call_signaling.dart'; import '../../chat/domain/kb_provider.dart'; @@ -40,6 +40,7 @@ void resetSessionState(Ref ref) { for (final invalidate in [ // Chat & people. () => ref.invalidate(conversationsNotifierProvider), + () => ref.invalidate(aiThreadsProvider), () => ref.invalidate(archivedConversationsProvider), () => ref.invalidate(blockedConversationsProvider), () => ref.invalidate(chatNotifierProvider), @@ -69,7 +70,6 @@ void resetSessionState(Ref ref) { () => ref.invalidate(assistantProvidersProvider), () => ref.invalidate(aiMemoriesProvider), () => ref.invalidate(aiPersonaProvider), - () => ref.invalidate(aiSessionsProvider), () => ref.invalidate(myAiContextProvider), () => ref.invalidate(kbDocumentsProvider), () => ref.invalidate(aiActionsProvider), diff --git a/apps/client/lib/features/chat/data/ai_session_repository.dart b/apps/client/lib/features/chat/data/ai_session_repository.dart deleted file mode 100644 index fcbbbd0b..00000000 --- a/apps/client/lib/features/chat/data/ai_session_repository.dart +++ /dev/null @@ -1,54 +0,0 @@ -import 'package:dio/dio.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:flutter_secure_storage/flutter_secure_storage.dart'; -import '../../../core/api/dio_client.dart'; -import '../../auth/domain/auth_provider.dart'; -import '../domain/ai_session_model.dart'; - -/// Talks to the ai-service (:3002) session endpoints. Mirrors the web -/// `aiSessionApi`. A conversation (chat-service) owns many AI sessions; this -/// repository lists them and switches the active one. -class AiSessionRepository { - final Dio _dio; - - const AiSessionRepository(this._dio); - - Future> listSessions(String conversationId) async { - final response = await _dio.get('/api/sessions/$conversationId'); - final data = response.data as List? ?? []; - return data - .map((e) => AiSessionModel.fromJson(e as Map)) - .toList(); - } - - Future createNew(String conversationId) async { - final response = await _dio.post('/api/sessions/$conversationId/new'); - return AiSessionModel.fromJson(response.data as Map); - } - - Future resume( - String conversationId, - String sessionId, - ) async { - final response = - await _dio.post('/api/sessions/$conversationId/resume/$sessionId'); - final data = response.data; - // Backend returns 404 when the session is missing/not owned; a null or - // otherwise empty body must not be blind-cast to a Map (would _CastError). - if (data is! Map) { - throw StateError('Session $sessionId not found or empty response'); - } - return AiSessionModel.fromJson(data); - } -} - -final aiSessionRepositoryProvider = Provider((ref) { - const storage = FlutterSecureStorage(); - return AiSessionRepository( - DioClient.createAiDio( - storage, - onForceLogout: () => - ref.read(authNotifierProvider.notifier).forceLogout(), - ), - ); -}); diff --git a/apps/client/lib/features/chat/data/chat_repository_conversation_ops.dart b/apps/client/lib/features/chat/data/chat_repository_conversation_ops.dart index 88a1fdae..0170a42d 100644 --- a/apps/client/lib/features/chat/data/chat_repository_conversation_ops.dart +++ b/apps/client/lib/features/chat/data/chat_repository_conversation_ops.dart @@ -5,12 +5,13 @@ part of 'chat_repository.dart'; mixin ChatRepositoryConversationOps { Dio get _dio; - /// The conversation list. One page of the server maximum (100) — a chat + /// The conversation list (AI threads excluded — they live in + /// `aiThreadsProvider`). One page of the server maximum (100) — a chat /// opened beyond it is fetched on demand (ConversationsNotifier.ensureLoaded). Future> listConversations() async { final response = await _dio.get( '/api/conversations', - queryParameters: {'size': 100}, + queryParameters: {'size': 100, 'excludeAi': true}, ); final data = response.data as Map; final content = data['content'] as List; @@ -23,7 +24,7 @@ mixin ChatRepositoryConversationOps { Future> listArchivedConversations() async { final response = await _dio.get( '/api/conversations', - queryParameters: {'archived': true, 'size': 100}, + queryParameters: {'archived': true, 'size': 100, 'excludeAi': true}, ); final data = response.data as Map; final content = data['content'] as List; diff --git a/apps/client/lib/features/chat/domain/ai_session_model.dart b/apps/client/lib/features/chat/domain/ai_session_model.dart deleted file mode 100644 index dbbd5ee4..00000000 --- a/apps/client/lib/features/chat/domain/ai_session_model.dart +++ /dev/null @@ -1,49 +0,0 @@ -/// Domain model for an AI conversation session (ai-service `ai_sessions`). -/// -/// Mirrors the web `AiSession` shape. The backend returns Mongo `_id`; we map -/// it to [id]. A conversation (chat-service) can own many sessions; exactly one -/// is [isActive] at a time. -class AiSessionModel { - final String id; - final String name; - final bool isActive; - final int totalTokens; - final String? summary; - final DateTime createdAt; - final DateTime updatedAt; - - const AiSessionModel({ - required this.id, - required this.name, - required this.isActive, - required this.totalTokens, - required this.summary, - required this.createdAt, - required this.updatedAt, - }); - - bool get hasSummary => summary != null && summary!.trim().isNotEmpty; - - factory AiSessionModel.fromJson(Map json) { - final rawSummary = json['summary'] as String?; - return AiSessionModel( - id: (json['id'] ?? json['_id'] ?? '').toString(), - // '' when unnamed — the UI shows the localized "New conversation". - name: (json['name'] as String?)?.trim() ?? '', - isActive: json['isActive'] as bool? ?? false, - totalTokens: (json['totalTokens'] as num?)?.toInt() ?? 0, - summary: (rawSummary != null && rawSummary.trim().isNotEmpty) - ? rawSummary - : null, - createdAt: _parseDate(json['createdAt']), - updatedAt: _parseDate(json['updatedAt']), - ); - } - - static DateTime _parseDate(dynamic value) { - if (value is String && value.isNotEmpty) { - return DateTime.tryParse(value)?.toLocal() ?? DateTime.now(); - } - return DateTime.now(); - } -} diff --git a/apps/client/lib/features/chat/domain/ai_session_provider.dart b/apps/client/lib/features/chat/domain/ai_session_provider.dart deleted file mode 100644 index 7a5d27e6..00000000 --- a/apps/client/lib/features/chat/domain/ai_session_provider.dart +++ /dev/null @@ -1,61 +0,0 @@ -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import '../data/ai_session_repository.dart'; -import 'ai_session_model.dart'; - -/// Sessions for a single AI conversation, keyed by conversationId. Newest / -/// active first (server already sorts). Exposes mutations that refresh the list -/// so the UI reflects the new active session. -class AiSessionsNotifier - extends FamilyAsyncNotifier, String> { - String get _conversationId => arg; - - @override - Future> build(String conversationId) async { - return ref - .read(aiSessionRepositoryProvider) - .listSessions(conversationId); - } - - Future _refresh() async { - state = const AsyncLoading>().copyWithPrevious(state); - state = await AsyncValue.guard( - () => ref.read(aiSessionRepositoryProvider).listSessions(_conversationId), - ); - } - - /// Deactivate the current session and start a fresh active one. Never - /// throws (it runs from a widget `onPressed`): the failure is RETURNED so - /// the caller can show a localized message, and the list still refreshes to - /// reflect server state. Null on success. - Future createNew() async { - Object? failure; - try { - await ref.read(aiSessionRepositoryProvider).createNew(_conversationId); - } catch (e) { - failure = e; - } - await _refresh(); - return failure; - } - - /// Switch the active session to [sessionId]. Like [createNew], a failure - /// (e.g. 404 when the session was deleted) is returned, not thrown, and the - /// refresh drops the stale entry. Null on success. - Future resume(String sessionId) async { - Object? failure; - try { - await ref - .read(aiSessionRepositoryProvider) - .resume(_conversationId, sessionId); - } catch (e) { - failure = e; - } - await _refresh(); - return failure; - } -} - -final aiSessionsProvider = AsyncNotifierProvider.family, String>( - AiSessionsNotifier.new, -); diff --git a/apps/client/lib/features/chat/domain/chat_misc_providers.dart b/apps/client/lib/features/chat/domain/chat_misc_providers.dart index 3994c8e5..796f55db 100644 --- a/apps/client/lib/features/chat/domain/chat_misc_providers.dart +++ b/apps/client/lib/features/chat/domain/chat_misc_providers.dart @@ -1,3 +1,4 @@ +import '../../ai_hub/domain/ai_threads_provider.dart'; import 'dart:async'; import 'package:collection/collection.dart'; @@ -33,12 +34,17 @@ final userProfileProvider = return ref.read(authRepositoryProvider).getUserProfile(userId); }); -/// The conversation [id] from the loaded list (null until loaded / when not a +/// The conversation [id] from the loaded main list or AI threads (null until loaded / when not a /// member). Screens call `ConversationsNotifier.ensureLoaded` so a /// conversation beyond the first page is fetched into the list too. final conversationProvider = Provider.autoDispose.family((ref, id) { - return ref.watch(conversationsNotifierProvider.select( + final main = ref.watch(conversationsNotifierProvider.select( + (s) => s.valueOrNull?.firstWhereOrNull((c) => c.id == id), + )); + if (main != null) return main; + // AI threads never live in the main list (see aiThreadsProvider). + return ref.watch(aiThreadsProvider.select( (s) => s.valueOrNull?.firstWhereOrNull((c) => c.id == id), )); }); diff --git a/apps/client/lib/features/chat/domain/conversation_list_ops.dart b/apps/client/lib/features/chat/domain/conversation_list_ops.dart index fcbf59f6..1b9611ea 100644 --- a/apps/client/lib/features/chat/domain/conversation_list_ops.dart +++ b/apps/client/lib/features/chat/domain/conversation_list_ops.dart @@ -136,6 +136,13 @@ class ConversationListOps { return [...rest.sublist(0, pos), conv, ...rest.sublist(pos)]; } + /// [conv] on top (replacing a copy with the same id). + static List upsertFront( + List list, + ConversationModel conv, + ) => + [conv, ...list.where((c) => c.id != conv.id)]; + static DateTime _activity(ConversationModel c) => c.lastMessageAt ?? c.lastMessage?.createdAt ?? c.createdAt; diff --git a/apps/client/lib/features/chat/domain/conversation_models.dart b/apps/client/lib/features/chat/domain/conversation_models.dart index 019535e8..f51484a2 100644 --- a/apps/client/lib/features/chat/domain/conversation_models.dart +++ b/apps/client/lib/features/chat/domain/conversation_models.dart @@ -138,6 +138,11 @@ class ConversationModel { bool get isDirectAi => !isGroup && participants.contains(kAiBotUserId); + /// Any non-group conversation the AI bot takes part in — including every AI + /// thread (ChatGPT-style "new chat"). A missing type counts as direct. Mirrors + /// web `isAiConversation` and the server's `isAiThread`. + bool get isAiConversation => !isGroup && participants.contains(kAiBotUserId); + /// Whether [userId] administers this group. Direct chats have no admins. bool isAdmin(String userId) => isGroup && admins.contains(userId); @@ -310,3 +315,13 @@ class UserStatus { ); } } + +/// Same rule as [ConversationModel.isAiConversation] on a raw conversation +/// payload: the AI bot is a participant of a non-group chat (missing type = +/// direct). Used to route STOMP updates between the main list and AI threads. +bool isAiConversationJson(Map json) { + final parts = json['participants']; + return parts is List && + parts.contains(kAiBotUserId) && + json['type'] != 'group'; +} diff --git a/apps/client/lib/features/chat/domain/conversations_notifier.dart b/apps/client/lib/features/chat/domain/conversations_notifier.dart index 918059a3..4fc39a7a 100644 --- a/apps/client/lib/features/chat/domain/conversations_notifier.dart +++ b/apps/client/lib/features/chat/domain/conversations_notifier.dart @@ -11,6 +11,7 @@ import '../../auth/domain/auth_state.dart'; import '../../home/domain/home_providers.dart'; import '../data/chat_repository.dart'; import '../data/stomp_service.dart'; +import '../../ai_hub/domain/ai_threads_provider.dart'; import '../../settings/ui/settings_screen.dart' show notificationsEnabledProvider; import 'active_call_provider.dart'; import 'chat_misc_providers.dart'; @@ -81,6 +82,8 @@ class ConversationsNotifier extends _$ConversationsNotifier { /// Merges a CONVERSATION_UPDATED (shared topic payload or the actor's own /// full view) into the list — never replacing it wholesale. void _onConversationUpdate(ConversationUpdateEvent event) { + // AI threads live in aiThreadsProvider only — never (re)insert them here. + if (isAiConversationJson(event.json)) return; final current = state.valueOrNull; if (current == null) return; final result = ConversationListOps.merge( @@ -129,6 +132,11 @@ class ConversationsNotifier extends _$ConversationsNotifier { if (latest == null) return; final me = _currentUserId; if (me != null && !conv.participants.contains(me)) return; + if (conv.isAiConversation) { + // Never in the main list: hand it to the AI threads list instead. + ref.read(aiThreadsProvider.notifier).upsert(conv); + return; + } state = AsyncData(ConversationListOps.upsertSorted(latest, conv)); } catch (_) { // Not accessible (removed / deleted) — nothing to add. @@ -136,7 +144,21 @@ class ConversationsNotifier extends _$ConversationsNotifier { } /// Hide a conversation locally + on the server. - Future deleteConversation(String conversationId) async { + /// + /// AI threads (web parity): server delete FIRST (failure rethrows, the row + /// stays), then [onDeleted] (navigate away), then the row is dropped from + /// aiThreadsProvider. For other conversations [onDeleted] runs after the + /// optimistic delete attempt (failures are rolled back silently). + Future deleteConversation(String conversationId, + {FutureOr Function(bool isAi)? onDeleted}) async { + if (ref.exists(aiThreadsProvider) && + ref.read(aiThreadsProvider.notifier).contains(conversationId)) { + final ai = ref.read(aiThreadsProvider.notifier); + await ai.deleteOnServer(conversationId); + await onDeleted?.call(true); + ai.drop(conversationId); + return; + } final current = state.valueOrNull; if (current != null) { state = AsyncData( @@ -148,6 +170,7 @@ class ConversationsNotifier extends _$ConversationsNotifier { // Roll back the optimistic removal without flashing the list to a spinner. await _silentRefetch(); } + await onDeleted?.call(false); } Future toggleMuteConversation(String conversationId, bool isMuted, @@ -346,7 +369,11 @@ class ConversationsNotifier extends _$ConversationsNotifier { createdAt: notice.createdAt, ); if (updated == null) { - unawaited(ensureLoaded(convId)); + // A known AI thread is handled by aiThreadsProvider; don't refetch it + // just to drop it again. + final knownAi = ref.exists(aiThreadsProvider) && + ref.read(aiThreadsProvider.notifier).contains(convId); + if (!knownAi) unawaited(ensureLoaded(convId)); return; } state = AsyncData(updated); diff --git a/apps/client/lib/features/chat/ui/chat_screen.dart b/apps/client/lib/features/chat/ui/chat_screen.dart index 4e981fe6..5c818117 100644 --- a/apps/client/lib/features/chat/ui/chat_screen.dart +++ b/apps/client/lib/features/chat/ui/chat_screen.dart @@ -10,6 +10,7 @@ import '../data/chat_repository.dart'; import '../domain/chat_provider.dart'; import '../domain/chat_state.dart'; import '../domain/staged_attachments_provider.dart'; +import '../../../core/utils/global_messenger.dart'; import '../utils/chat_error.dart'; import 'chat_screen_helpers.dart'; import 'widgets/active_call_banner.dart'; @@ -140,14 +141,24 @@ class _ChatScreenState extends ConsumerState { /// Closes the current chat. On the web/tablet split layout the chat is the /// right detail pane (not a pushed route), so we clear the selection rather /// than popping — popping would tear down the whole ResponsiveHomeLayout. - void _closeChat() { + /// + /// [isAi]: the closed chat was an AI thread, so leaving lands on the AI hub + /// (AI threads are opened with go(), there is nothing to pop to). Callers + /// that delete the thread must capture it BEFORE the row is dropped. + void _closeChat({bool isAi = false}) { if (MediaQuery.of(context).size.width >= kWebBreakpoint) { ref.read(selectedConversationIdProvider.notifier).state = null; + } else if (isAi) { + context.go('/ai-hub'); } else { context.pop(); } } + bool get _isAiThread => + ref.read(conversationProvider(widget.conversationId))?.isAiConversation ?? + false; + Future _jumpToSearchResult(String messageId) async { setState(() => _isSearching = false); await ref @@ -206,8 +217,8 @@ class _ChatScreenState extends ConsumerState { try { await ref .read(conversationsNotifierProvider.notifier) - .deleteConversation(widget.conversationId); - if (mounted) _closeChat(); + .deleteConversation(widget.conversationId, + onDeleted: (_) => mounted ? _closeChat() : null); } catch (e) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( @@ -255,10 +266,17 @@ class _ChatScreenState extends ConsumerState { body: context.l10n.deleteConversationConfirm, ); if (confirm != true) return; - await ref - .read(conversationsNotifierProvider.notifier) - .deleteConversation(widget.conversationId); - if (mounted) _closeChat(); + final wasAi = _isAiThread; + try { + await ref + .read(conversationsNotifierProvider.notifier) + .deleteConversation(widget.conversationId, onDeleted: (isAi) { + if (mounted) _closeChat(isAi: isAi || wasAi); + }); + } catch (e) { + // Failed: stay on the chat and say why. + if (mounted) showErrorSnackBar(chatErrorMessage(context.l10n, e)); + } } @override diff --git a/apps/client/lib/features/chat/ui/widgets/ai_session_panel.dart b/apps/client/lib/features/chat/ui/widgets/ai_session_panel.dart deleted file mode 100644 index 605320c3..00000000 --- a/apps/client/lib/features/chat/ui/widgets/ai_session_panel.dart +++ /dev/null @@ -1,202 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:intl/intl.dart'; - -import '../../../../core/l10n/l10n_ext.dart'; -import '../../../../core/theme/app_theme.dart'; -import '../../../../core/utils/app_error.dart'; -import '../../../../core/utils/global_messenger.dart'; -import '../../domain/ai_session_model.dart'; -import '../../domain/ai_session_provider.dart'; - -/// Session history for an AI conversation, rendered as an [ExpansionTile] inside -/// the conversation settings sidebar. Lists past sessions (newest/active first), -/// lets the user start a fresh session and resume an old one. -/// -/// Mirrors the web `AiSessionPanel` (plan 2026-07-02-ai-memory-sessions, 2c). -class AiSessionPanel extends ConsumerWidget { - final String conversationId; - - const AiSessionPanel({super.key, required this.conversationId}); - - @override - Widget build(BuildContext context, WidgetRef ref) { - final sessionsAsync = ref.watch(aiSessionsProvider(conversationId)); - - return ExpansionTile( - title: Text( - context.l10n.aiSessionHistory, - style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 14), - ), - leading: const Icon(Icons.history_rounded, size: 18), - children: [ - Align( - alignment: Alignment.centerRight, - child: Padding( - padding: const EdgeInsets.only(right: 8, bottom: 4), - child: TextButton.icon( - icon: const Icon(Icons.add_rounded, size: 16), - label: Text(context.l10n.aiNewSession), - style: TextButton.styleFrom(foregroundColor: AppTheme.accent(context)), - onPressed: () => reportAiSessionFailure(ref - .read(aiSessionsProvider(conversationId).notifier) - .createNew()), - ), - ), - ), - sessionsAsync.when( - data: (sessions) => _SessionList( - sessions: sessions, - conversationId: conversationId, - ), - loading: () => const Padding( - padding: EdgeInsets.all(16), - child: Center( - child: SizedBox( - width: 22, - height: 22, - child: CircularProgressIndicator(strokeWidth: 2), - ), - ), - ), - error: (_, __) => Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), - child: Row( - children: [ - Expanded( - child: Text( - context.l10n.aiSessionLoadError, - style: TextStyle(fontSize: 12, color: AppTheme.mutedText(context)), - ), - ), - TextButton( - onPressed: () => - ref.invalidate(aiSessionsProvider(conversationId)), - child: Text(context.l10n.actionRetry), - ), - ], - ), - ), - ), - ], - ); - } -} - -class _SessionList extends ConsumerWidget { - final List sessions; - final String conversationId; - - const _SessionList({ - required this.sessions, - required this.conversationId, - }); - - @override - Widget build(BuildContext context, WidgetRef ref) { - if (sessions.isEmpty) { - return Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), - child: Text( - context.l10n.aiSessionEmpty, - style: TextStyle(fontSize: 12, color: AppTheme.mutedText(context)), - ), - ); - } - - return ListView.builder( - shrinkWrap: true, - physics: const NeverScrollableScrollPhysics(), - itemCount: sessions.length, - itemBuilder: (context, index) => _SessionTile( - session: sessions[index], - conversationId: conversationId, - ), - ); - } -} - -/// Shows a localized error when a session create/resume failed (the notifier -/// returns the failure instead of throwing). -Future reportAiSessionFailure(Future action) async { - final failure = await action; - if (failure != null) showErrorSnackBar(friendlyError(failure)); -} - -class _SessionTile extends ConsumerWidget { - final AiSessionModel session; - final String conversationId; - - const _SessionTile({ - required this.session, - required this.conversationId, - }); - - @override - Widget build(BuildContext context, WidgetRef ref) { - final locale = Localizations.localeOf(context).toString(); - final dateStr = DateFormat.yMMMd(locale) - .add_Hm() - .format(session.updatedAt.toLocal()); - final subtitle = session.hasSummary - ? '$dateStr · ${context.l10n.aiSessionSummarized}' - : dateStr; - - return ListTile( - dense: true, - tileColor: session.isActive - ? AppTheme.accent(context).withValues(alpha: 0.10) - : null, - contentPadding: const EdgeInsets.symmetric(horizontal: 16), - title: Text( - session.name.isEmpty ? context.l10n.aiNewSession : session.name, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle( - fontSize: 14, - fontWeight: session.isActive ? FontWeight.w600 : FontWeight.w400, - ), - ), - subtitle: Text( - subtitle, - style: TextStyle(fontSize: 12, color: AppTheme.mutedText(context)), - ), - trailing: session.isActive - ? _ActiveChip() - : IconButton( - icon: const Icon(Icons.restore_rounded, size: 18), - tooltip: context.l10n.aiSessionResume, - onPressed: () => reportAiSessionFailure(ref - .read(aiSessionsProvider(conversationId).notifier) - .resume(session.id)), - ), - onTap: session.isActive - ? null - : () => reportAiSessionFailure(ref - .read(aiSessionsProvider(conversationId).notifier) - .resume(session.id)), - ); - } -} - -class _ActiveChip extends StatelessWidget { - @override - Widget build(BuildContext context) { - return Container( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), - decoration: BoxDecoration( - color: AppTheme.accent(context).withValues(alpha: 0.18), - borderRadius: BorderRadius.circular(10), - border: Border.all(color: AppTheme.accent(context).withValues(alpha: 0.4)), - ), - child: Text( - context.l10n.aiSessionActive, - style: TextStyle( - fontSize: 10, - fontWeight: FontWeight.w600, - color: AppTheme.accent(context), - ), - ), - ); - } -} diff --git a/apps/client/lib/features/chat/ui/widgets/chat_app_bar.dart b/apps/client/lib/features/chat/ui/widgets/chat_app_bar.dart index 3ccd0ef1..61425c2c 100644 --- a/apps/client/lib/features/chat/ui/widgets/chat_app_bar.dart +++ b/apps/client/lib/features/chat/ui/widgets/chat_app_bar.dart @@ -3,6 +3,9 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; import '../../../../core/l10n/l10n_ext.dart'; import '../../../../core/theme/app_theme.dart'; +import '../../../ai_hub/ui/widgets/ai_thread_item.dart'; +import '../../../ai_hub/ui/widgets/ai_thread_list.dart'; +import '../../../ai_hub/ui/widgets/ai_new_chat_button.dart'; import '../../../home/domain/home_providers.dart'; import '../../../profile/ui/widgets/user_profile_dialog.dart'; import '../../domain/chat_provider.dart'; @@ -61,7 +64,7 @@ class ChatScreenAppBar extends ConsumerWidget implements PreferredSizeWidget { final displayName = isGroup ? (conv?.name ?? context.l10n.conversationDefault) : isAiConversation - ? context.l10n.aiAssistant + ? (conv != null ? aiThreadTitle(context, conv) : context.l10n.aiAssistant) : (dmNickname != null && dmNickname.isNotEmpty ? dmNickname : (resolvedName ?? context.l10n.chatDefaultTitle)); @@ -90,6 +93,9 @@ class ChatScreenAppBar extends ConsumerWidget implements PreferredSizeWidget { onPressed: () { if (MediaQuery.of(context).size.width >= kWebBreakpoint) { ref.read(selectedConversationIdProvider.notifier).state = null; + } else if (isAiConversation) { + // AI threads are opened with go() (replace): back = the AI hub. + context.go('/ai-hub'); } else { context.pop(); } @@ -172,6 +178,26 @@ class ChatScreenAppBar extends ConsumerWidget implements PreferredSizeWidget { ), actions: [ if (isAiConversation) ...[ + const AiNewChatButton(), + IconButton( + tooltip: context.l10n.aiThreadsTitle, + icon: const Icon(Icons.forum_outlined, size: 22), + onPressed: () => showModalBottomSheet( + context: context, + isScrollControlled: true, + showDragHandle: true, + builder: (sheetCtx) => SafeArea( + child: ConstrainedBox( + constraints: BoxConstraints( + maxHeight: MediaQuery.of(sheetCtx).size.height * 0.7), + child: AiThreadList( + openId: conversationId, + onNavigate: () => Navigator.of(sheetCtx).pop(), + ), + ), + ), + ), + ), PopupMenuButton( icon: const Icon(Icons.more_vert_rounded, size: 22), onSelected: (value) { diff --git a/apps/client/lib/features/chat/ui/widgets/conversation_info_sidebar.dart b/apps/client/lib/features/chat/ui/widgets/conversation_info_sidebar.dart index 39447c6d..5e4972c6 100644 --- a/apps/client/lib/features/chat/ui/widgets/conversation_info_sidebar.dart +++ b/apps/client/lib/features/chat/ui/widgets/conversation_info_sidebar.dart @@ -10,8 +10,9 @@ import '../../../home/domain/home_providers.dart'; import '../../domain/chat_provider.dart'; import '../../domain/chat_state.dart'; import '../../utils/duration_text.dart'; +import '../../../../core/utils/global_messenger.dart'; +import '../../utils/chat_error.dart'; import '../chat_screen_helpers.dart'; -import 'ai_session_panel.dart'; import 'chat_wallpaper_dialog.dart'; import 'conversation_customisation_dialogs.dart'; import 'conversation_info_sidebar_parts.dart'; @@ -179,9 +180,6 @@ class ConversationInfoSidebar extends ConsumerWidget { ), ], ), - // AI session history — view/resume/start conversation sessions. - // Only for AI conversations. Mirrors web AiSessionPanel. - if (isAi) AiSessionPanel(conversationId: conversationId), // Issue 2: "Chat Details" (bio/DOB/member count) removed — the info // panel now shows only Customization, Shared Media, Pinned Messages // and Privacy. Mirrors web ConversationSettingsDrawer. @@ -343,14 +341,24 @@ class ConversationInfoSidebar extends ConsumerWidget { body: context.l10n.deleteConversationConfirm, ); if (confirm != true) return; - await ref - .read(conversationsNotifierProvider.notifier) - .deleteConversation(conversationId); - if (!context.mounted) return; - if (MediaQuery.of(context).size.width >= kWebBreakpoint) { - ref.read(selectedConversationIdProvider.notifier).state = null; - } else { - context.go('/'); + final wasAi = + ref.read(conversationProvider(conversationId))?.isAiConversation ?? + false; + void leave(bool isAi) { + if (!context.mounted) return; + if (MediaQuery.of(context).size.width >= kWebBreakpoint) { + ref.read(selectedConversationIdProvider.notifier).state = null; + } else { + context.go(isAi || wasAi ? '/ai-hub' : '/'); + } + } + + try { + await ref + .read(conversationsNotifierProvider.notifier) + .deleteConversation(conversationId, onDeleted: leave); + } catch (e) { + if (context.mounted) showErrorSnackBar(chatErrorMessage(context.l10n, e)); } } } diff --git a/apps/client/lib/l10n/app_en.arb b/apps/client/lib/l10n/app_en.arb index 65f9b6dc..499b9feb 100644 --- a/apps/client/lib/l10n/app_en.arb +++ b/apps/client/lib/l10n/app_en.arb @@ -1476,13 +1476,21 @@ "keepEditing": "Keep editing", "saveAndLeave": "Save and leave", "leaveWithoutSaving": "Leave without saving", - "aiSessionHistory": "Conversation history", - "aiNewSession": "New conversation", - "aiSessionActive": "Active", - "aiSessionSummarized": "Summarized", - "aiSessionEmpty": "No previous conversations", - "aiSessionResume": "Resume", - "aiSessionLoadError": "Couldn't load conversation history", + "aiThreadUntitled": "Chat with AI", + "aiThreadNew": "New conversation", + "aiThreadsTitle": "Conversations", + "aiThreadRename": "Rename", + "aiThreadSave": "Save", + "aiThreadCancel": "Cancel", + "aiThreadDelete": "Delete", + "aiThreadDeleteTitle": "Delete this conversation?", + "aiThreadDeleteDesc": "All messages in this AI conversation will be removed from your account. This can't be undone.", + "aiThreadEmpty": "No conversations yet. Start a new one.", + "aiThreadLoadFailed": "Couldn't load conversations. Please try again.", + "aiThreadCreateFailed": "Couldn't start a new conversation. Please try again.", + "aiThreadRenameFailed": "Couldn't rename. Please try again.", + "aiThreadNameInvalid": "Name must be 1 to 80 characters.", + "aiThreadDeleteFailed": "Couldn't delete the conversation. Please try again.", "multiSelectCount": "{count} selected", "@multiSelectCount": { "placeholders": { diff --git a/apps/client/lib/l10n/app_es.arb b/apps/client/lib/l10n/app_es.arb index 8194d9d8..7e4144a8 100644 --- a/apps/client/lib/l10n/app_es.arb +++ b/apps/client/lib/l10n/app_es.arb @@ -1100,13 +1100,21 @@ "keepEditing": "Seguir editando", "saveAndLeave": "Guardar y salir", "leaveWithoutSaving": "Salir sin guardar", - "aiSessionHistory": "Historial de conversaciones", - "aiNewSession": "Nueva conversación", - "aiSessionActive": "Activa", - "aiSessionSummarized": "Resumida", - "aiSessionEmpty": "No hay conversaciones anteriores", - "aiSessionResume": "Reanudar", - "aiSessionLoadError": "No se pudo cargar el historial de conversaciones", + "aiThreadUntitled": "Chatear con la IA", + "aiThreadNew": "Nueva conversación", + "aiThreadsTitle": "Conversaciones", + "aiThreadRename": "Renombrar", + "aiThreadSave": "Guardar", + "aiThreadCancel": "Cancelar", + "aiThreadDelete": "Eliminar", + "aiThreadDeleteTitle": "¿Eliminar esta conversación?", + "aiThreadDeleteDesc": "Todos los mensajes de esta conversación con la IA se eliminarán de tu cuenta. No se puede deshacer.", + "aiThreadEmpty": "Aún no hay conversaciones. Empieza una nueva.", + "aiThreadLoadFailed": "No se pudieron cargar las conversaciones. Inténtalo de nuevo.", + "aiThreadCreateFailed": "No se pudo crear la conversación. Inténtalo de nuevo.", + "aiThreadRenameFailed": "No se pudo renombrar. Inténtalo de nuevo.", + "aiThreadNameInvalid": "El nombre debe tener entre 1 y 80 caracteres.", + "aiThreadDeleteFailed": "No se pudo eliminar la conversación. Inténtalo de nuevo.", "multiSelectCount": "{count} seleccionados", "multiSelectEmpty": "Ningún mensaje seleccionado", "multiSelectCancel": "Cancelar", diff --git a/apps/client/lib/l10n/app_fr.arb b/apps/client/lib/l10n/app_fr.arb index aa981d61..8c4f685c 100644 --- a/apps/client/lib/l10n/app_fr.arb +++ b/apps/client/lib/l10n/app_fr.arb @@ -1100,13 +1100,21 @@ "keepEditing": "Continuer la modification", "saveAndLeave": "Enregistrer et quitter", "leaveWithoutSaving": "Quitter sans enregistrer", - "aiSessionHistory": "Historique des conversations", - "aiNewSession": "Nouvelle conversation", - "aiSessionActive": "Active", - "aiSessionSummarized": "Résumée", - "aiSessionEmpty": "Aucune conversation précédente", - "aiSessionResume": "Reprendre", - "aiSessionLoadError": "Impossible de charger l'historique des conversations", + "aiThreadUntitled": "Discuter avec l'IA", + "aiThreadNew": "Nouvelle conversation", + "aiThreadsTitle": "Conversations", + "aiThreadRename": "Renommer", + "aiThreadSave": "Enregistrer", + "aiThreadCancel": "Annuler", + "aiThreadDelete": "Supprimer", + "aiThreadDeleteTitle": "Supprimer cette conversation ?", + "aiThreadDeleteDesc": "Tous les messages de cette conversation avec l'IA seront supprimés de votre compte. Action irréversible.", + "aiThreadEmpty": "Aucune conversation pour le moment. Commencez-en une.", + "aiThreadLoadFailed": "Impossible de charger les conversations. Veuillez réessayer.", + "aiThreadCreateFailed": "Impossible de créer la conversation. Veuillez réessayer.", + "aiThreadRenameFailed": "Impossible de renommer. Veuillez réessayer.", + "aiThreadNameInvalid": "Le nom doit comporter entre 1 et 80 caractères.", + "aiThreadDeleteFailed": "Impossible de supprimer la conversation. Veuillez réessayer.", "multiSelectCount": "{count} sélectionné(s)", "multiSelectEmpty": "Aucun message sélectionné", "multiSelectCancel": "Annuler", diff --git a/apps/client/lib/l10n/app_ja.arb b/apps/client/lib/l10n/app_ja.arb index 11dbcddb..b4f0e1db 100644 --- a/apps/client/lib/l10n/app_ja.arb +++ b/apps/client/lib/l10n/app_ja.arb @@ -1100,13 +1100,21 @@ "keepEditing": "編集を続ける", "saveAndLeave": "保存して移動", "leaveWithoutSaving": "保存せずに移動", - "aiSessionHistory": "会話履歴", - "aiNewSession": "新しい会話", - "aiSessionActive": "使用中", - "aiSessionSummarized": "要約済み", - "aiSessionEmpty": "過去の会話はありません", - "aiSessionResume": "再開", - "aiSessionLoadError": "会話履歴を読み込めませんでした", + "aiThreadUntitled": "AIとチャット", + "aiThreadNew": "新しい会話", + "aiThreadsTitle": "会話", + "aiThreadRename": "名前を変更", + "aiThreadSave": "保存", + "aiThreadCancel": "キャンセル", + "aiThreadDelete": "削除", + "aiThreadDeleteTitle": "この会話を削除しますか?", + "aiThreadDeleteDesc": "このAIとの会話のメッセージはすべてアカウントから削除されます。元に戻せません。", + "aiThreadEmpty": "会話はまだありません。新しく始めましょう。", + "aiThreadLoadFailed": "会話を読み込めませんでした。もう一度お試しください。", + "aiThreadCreateFailed": "新しい会話を作成できませんでした。もう一度お試しください。", + "aiThreadRenameFailed": "名前を変更できませんでした。もう一度お試しください。", + "aiThreadNameInvalid": "名前は1〜80文字で入力してください。", + "aiThreadDeleteFailed": "会話を削除できませんでした。もう一度お試しください。", "multiSelectCount": "{count}件選択中", "multiSelectEmpty": "メッセージが選択されていません", "multiSelectCancel": "キャンセル", diff --git a/apps/client/lib/l10n/app_ko.arb b/apps/client/lib/l10n/app_ko.arb index a9962d37..8b4e3847 100644 --- a/apps/client/lib/l10n/app_ko.arb +++ b/apps/client/lib/l10n/app_ko.arb @@ -1100,13 +1100,21 @@ "keepEditing": "계속 편집", "saveAndLeave": "저장 후 나가기", "leaveWithoutSaving": "저장하지 않고 나가기", - "aiSessionHistory": "대화 기록", - "aiNewSession": "새 대화", - "aiSessionActive": "사용 중", - "aiSessionSummarized": "요약됨", - "aiSessionEmpty": "이전 대화가 없습니다", - "aiSessionResume": "다시 시작", - "aiSessionLoadError": "대화 기록을 불러올 수 없습니다", + "aiThreadUntitled": "AI와 채팅", + "aiThreadNew": "새 대화", + "aiThreadsTitle": "대화", + "aiThreadRename": "이름 변경", + "aiThreadSave": "저장", + "aiThreadCancel": "취소", + "aiThreadDelete": "삭제", + "aiThreadDeleteTitle": "이 대화를 삭제할까요?", + "aiThreadDeleteDesc": "이 AI 대화의 모든 메시지가 계정에서 삭제됩니다. 되돌릴 수 없습니다.", + "aiThreadEmpty": "아직 대화가 없습니다. 새로 시작하세요.", + "aiThreadLoadFailed": "대화를 불러오지 못했습니다. 다시 시도해 주세요.", + "aiThreadCreateFailed": "새 대화를 만들지 못했습니다. 다시 시도해 주세요.", + "aiThreadRenameFailed": "이름을 변경하지 못했습니다. 다시 시도해 주세요.", + "aiThreadNameInvalid": "이름은 1~80자여야 합니다.", + "aiThreadDeleteFailed": "대화를 삭제하지 못했습니다. 다시 시도해 주세요.", "multiSelectCount": "{count}개 선택됨", "multiSelectEmpty": "선택된 메시지가 없습니다", "multiSelectCancel": "취소", diff --git a/apps/client/lib/l10n/app_localizations.dart b/apps/client/lib/l10n/app_localizations.dart index d358bf71..2d4bb915 100644 --- a/apps/client/lib/l10n/app_localizations.dart +++ b/apps/client/lib/l10n/app_localizations.dart @@ -5899,47 +5899,95 @@ abstract class AppLocalizations { /// **'Leave without saving'** String get leaveWithoutSaving; - /// No description provided for @aiSessionHistory. + /// No description provided for @aiThreadUntitled. /// /// In en, this message translates to: - /// **'Conversation history'** - String get aiSessionHistory; + /// **'Chat with AI'** + String get aiThreadUntitled; - /// No description provided for @aiNewSession. + /// No description provided for @aiThreadNew. /// /// In en, this message translates to: /// **'New conversation'** - String get aiNewSession; + String get aiThreadNew; - /// No description provided for @aiSessionActive. + /// No description provided for @aiThreadsTitle. /// /// In en, this message translates to: - /// **'Active'** - String get aiSessionActive; + /// **'Conversations'** + String get aiThreadsTitle; - /// No description provided for @aiSessionSummarized. + /// No description provided for @aiThreadRename. /// /// In en, this message translates to: - /// **'Summarized'** - String get aiSessionSummarized; + /// **'Rename'** + String get aiThreadRename; - /// No description provided for @aiSessionEmpty. + /// No description provided for @aiThreadSave. /// /// In en, this message translates to: - /// **'No previous conversations'** - String get aiSessionEmpty; + /// **'Save'** + String get aiThreadSave; + + /// No description provided for @aiThreadCancel. + /// + /// In en, this message translates to: + /// **'Cancel'** + String get aiThreadCancel; + + /// No description provided for @aiThreadDelete. + /// + /// In en, this message translates to: + /// **'Delete'** + String get aiThreadDelete; + + /// No description provided for @aiThreadDeleteTitle. + /// + /// In en, this message translates to: + /// **'Delete this conversation?'** + String get aiThreadDeleteTitle; + + /// No description provided for @aiThreadDeleteDesc. + /// + /// In en, this message translates to: + /// **'All messages in this AI conversation will be removed from your account. This can\'t be undone.'** + String get aiThreadDeleteDesc; + + /// No description provided for @aiThreadEmpty. + /// + /// In en, this message translates to: + /// **'No conversations yet. Start a new one.'** + String get aiThreadEmpty; + + /// No description provided for @aiThreadLoadFailed. + /// + /// In en, this message translates to: + /// **'Couldn\'t load conversations. Please try again.'** + String get aiThreadLoadFailed; + + /// No description provided for @aiThreadCreateFailed. + /// + /// In en, this message translates to: + /// **'Couldn\'t start a new conversation. Please try again.'** + String get aiThreadCreateFailed; + + /// No description provided for @aiThreadRenameFailed. + /// + /// In en, this message translates to: + /// **'Couldn\'t rename. Please try again.'** + String get aiThreadRenameFailed; - /// No description provided for @aiSessionResume. + /// No description provided for @aiThreadNameInvalid. /// /// In en, this message translates to: - /// **'Resume'** - String get aiSessionResume; + /// **'Name must be 1 to 80 characters.'** + String get aiThreadNameInvalid; - /// No description provided for @aiSessionLoadError. + /// No description provided for @aiThreadDeleteFailed. /// /// In en, this message translates to: - /// **'Couldn\'t load conversation history'** - String get aiSessionLoadError; + /// **'Couldn\'t delete the conversation. Please try again.'** + String get aiThreadDeleteFailed; /// No description provided for @multiSelectCount. /// diff --git a/apps/client/lib/l10n/app_localizations_en.dart b/apps/client/lib/l10n/app_localizations_en.dart index 034b51c9..a956594a 100644 --- a/apps/client/lib/l10n/app_localizations_en.dart +++ b/apps/client/lib/l10n/app_localizations_en.dart @@ -3153,25 +3153,53 @@ class AppLocalizationsEn extends AppLocalizations { String get leaveWithoutSaving => 'Leave without saving'; @override - String get aiSessionHistory => 'Conversation history'; + String get aiThreadUntitled => 'Chat with AI'; @override - String get aiNewSession => 'New conversation'; + String get aiThreadNew => 'New conversation'; @override - String get aiSessionActive => 'Active'; + String get aiThreadsTitle => 'Conversations'; @override - String get aiSessionSummarized => 'Summarized'; + String get aiThreadRename => 'Rename'; @override - String get aiSessionEmpty => 'No previous conversations'; + String get aiThreadSave => 'Save'; @override - String get aiSessionResume => 'Resume'; + String get aiThreadCancel => 'Cancel'; @override - String get aiSessionLoadError => 'Couldn\'t load conversation history'; + String get aiThreadDelete => 'Delete'; + + @override + String get aiThreadDeleteTitle => 'Delete this conversation?'; + + @override + String get aiThreadDeleteDesc => + 'All messages in this AI conversation will be removed from your account. This can\'t be undone.'; + + @override + String get aiThreadEmpty => 'No conversations yet. Start a new one.'; + + @override + String get aiThreadLoadFailed => + 'Couldn\'t load conversations. Please try again.'; + + @override + String get aiThreadCreateFailed => + 'Couldn\'t start a new conversation. Please try again.'; + + @override + String get aiThreadRenameFailed => 'Couldn\'t rename. Please try again.'; + + @override + String get aiThreadNameInvalid => 'Name must be 1 to 80 characters.'; + + @override + String get aiThreadDeleteFailed => + 'Couldn\'t delete the conversation. Please try again.'; @override String multiSelectCount(int count) { diff --git a/apps/client/lib/l10n/app_localizations_es.dart b/apps/client/lib/l10n/app_localizations_es.dart index c8f562a5..ec6e0d8d 100644 --- a/apps/client/lib/l10n/app_localizations_es.dart +++ b/apps/client/lib/l10n/app_localizations_es.dart @@ -3179,26 +3179,55 @@ class AppLocalizationsEs extends AppLocalizations { String get leaveWithoutSaving => 'Salir sin guardar'; @override - String get aiSessionHistory => 'Historial de conversaciones'; + String get aiThreadUntitled => 'Chatear con la IA'; @override - String get aiNewSession => 'Nueva conversación'; + String get aiThreadNew => 'Nueva conversación'; @override - String get aiSessionActive => 'Activa'; + String get aiThreadsTitle => 'Conversaciones'; @override - String get aiSessionSummarized => 'Resumida'; + String get aiThreadRename => 'Renombrar'; @override - String get aiSessionEmpty => 'No hay conversaciones anteriores'; + String get aiThreadSave => 'Guardar'; @override - String get aiSessionResume => 'Reanudar'; + String get aiThreadCancel => 'Cancelar'; @override - String get aiSessionLoadError => - 'No se pudo cargar el historial de conversaciones'; + String get aiThreadDelete => 'Eliminar'; + + @override + String get aiThreadDeleteTitle => '¿Eliminar esta conversación?'; + + @override + String get aiThreadDeleteDesc => + 'Todos los mensajes de esta conversación con la IA se eliminarán de tu cuenta. No se puede deshacer.'; + + @override + String get aiThreadEmpty => 'Aún no hay conversaciones. Empieza una nueva.'; + + @override + String get aiThreadLoadFailed => + 'No se pudieron cargar las conversaciones. Inténtalo de nuevo.'; + + @override + String get aiThreadCreateFailed => + 'No se pudo crear la conversación. Inténtalo de nuevo.'; + + @override + String get aiThreadRenameFailed => + 'No se pudo renombrar. Inténtalo de nuevo.'; + + @override + String get aiThreadNameInvalid => + 'El nombre debe tener entre 1 y 80 caracteres.'; + + @override + String get aiThreadDeleteFailed => + 'No se pudo eliminar la conversación. Inténtalo de nuevo.'; @override String multiSelectCount(int count) { diff --git a/apps/client/lib/l10n/app_localizations_fr.dart b/apps/client/lib/l10n/app_localizations_fr.dart index 68f7c0ef..8862f4c6 100644 --- a/apps/client/lib/l10n/app_localizations_fr.dart +++ b/apps/client/lib/l10n/app_localizations_fr.dart @@ -3201,26 +3201,56 @@ class AppLocalizationsFr extends AppLocalizations { String get leaveWithoutSaving => 'Quitter sans enregistrer'; @override - String get aiSessionHistory => 'Historique des conversations'; + String get aiThreadUntitled => 'Discuter avec l\'IA'; @override - String get aiNewSession => 'Nouvelle conversation'; + String get aiThreadNew => 'Nouvelle conversation'; @override - String get aiSessionActive => 'Active'; + String get aiThreadsTitle => 'Conversations'; @override - String get aiSessionSummarized => 'Résumée'; + String get aiThreadRename => 'Renommer'; @override - String get aiSessionEmpty => 'Aucune conversation précédente'; + String get aiThreadSave => 'Enregistrer'; @override - String get aiSessionResume => 'Reprendre'; + String get aiThreadCancel => 'Annuler'; @override - String get aiSessionLoadError => - 'Impossible de charger l\'historique des conversations'; + String get aiThreadDelete => 'Supprimer'; + + @override + String get aiThreadDeleteTitle => 'Supprimer cette conversation ?'; + + @override + String get aiThreadDeleteDesc => + 'Tous les messages de cette conversation avec l\'IA seront supprimés de votre compte. Action irréversible.'; + + @override + String get aiThreadEmpty => + 'Aucune conversation pour le moment. Commencez-en une.'; + + @override + String get aiThreadLoadFailed => + 'Impossible de charger les conversations. Veuillez réessayer.'; + + @override + String get aiThreadCreateFailed => + 'Impossible de créer la conversation. Veuillez réessayer.'; + + @override + String get aiThreadRenameFailed => + 'Impossible de renommer. Veuillez réessayer.'; + + @override + String get aiThreadNameInvalid => + 'Le nom doit comporter entre 1 et 80 caractères.'; + + @override + String get aiThreadDeleteFailed => + 'Impossible de supprimer la conversation. Veuillez réessayer.'; @override String multiSelectCount(int count) { diff --git a/apps/client/lib/l10n/app_localizations_ja.dart b/apps/client/lib/l10n/app_localizations_ja.dart index 8dd52790..6f2a03c0 100644 --- a/apps/client/lib/l10n/app_localizations_ja.dart +++ b/apps/client/lib/l10n/app_localizations_ja.dart @@ -3089,25 +3089,49 @@ class AppLocalizationsJa extends AppLocalizations { String get leaveWithoutSaving => '保存せずに移動'; @override - String get aiSessionHistory => '会話履歴'; + String get aiThreadUntitled => 'AIとチャット'; @override - String get aiNewSession => '新しい会話'; + String get aiThreadNew => '新しい会話'; @override - String get aiSessionActive => '使用中'; + String get aiThreadsTitle => '会話'; @override - String get aiSessionSummarized => '要約済み'; + String get aiThreadRename => '名前を変更'; @override - String get aiSessionEmpty => '過去の会話はありません'; + String get aiThreadSave => '保存'; @override - String get aiSessionResume => '再開'; + String get aiThreadCancel => 'キャンセル'; @override - String get aiSessionLoadError => '会話履歴を読み込めませんでした'; + String get aiThreadDelete => '削除'; + + @override + String get aiThreadDeleteTitle => 'この会話を削除しますか?'; + + @override + String get aiThreadDeleteDesc => 'このAIとの会話のメッセージはすべてアカウントから削除されます。元に戻せません。'; + + @override + String get aiThreadEmpty => '会話はまだありません。新しく始めましょう。'; + + @override + String get aiThreadLoadFailed => '会話を読み込めませんでした。もう一度お試しください。'; + + @override + String get aiThreadCreateFailed => '新しい会話を作成できませんでした。もう一度お試しください。'; + + @override + String get aiThreadRenameFailed => '名前を変更できませんでした。もう一度お試しください。'; + + @override + String get aiThreadNameInvalid => '名前は1〜80文字で入力してください。'; + + @override + String get aiThreadDeleteFailed => '会話を削除できませんでした。もう一度お試しください。'; @override String multiSelectCount(int count) { diff --git a/apps/client/lib/l10n/app_localizations_ko.dart b/apps/client/lib/l10n/app_localizations_ko.dart index baf8f625..4fc9f052 100644 --- a/apps/client/lib/l10n/app_localizations_ko.dart +++ b/apps/client/lib/l10n/app_localizations_ko.dart @@ -3089,25 +3089,49 @@ class AppLocalizationsKo extends AppLocalizations { String get leaveWithoutSaving => '저장하지 않고 나가기'; @override - String get aiSessionHistory => '대화 기록'; + String get aiThreadUntitled => 'AI와 채팅'; @override - String get aiNewSession => '새 대화'; + String get aiThreadNew => '새 대화'; @override - String get aiSessionActive => '사용 중'; + String get aiThreadsTitle => '대화'; @override - String get aiSessionSummarized => '요약됨'; + String get aiThreadRename => '이름 변경'; @override - String get aiSessionEmpty => '이전 대화가 없습니다'; + String get aiThreadSave => '저장'; @override - String get aiSessionResume => '다시 시작'; + String get aiThreadCancel => '취소'; @override - String get aiSessionLoadError => '대화 기록을 불러올 수 없습니다'; + String get aiThreadDelete => '삭제'; + + @override + String get aiThreadDeleteTitle => '이 대화를 삭제할까요?'; + + @override + String get aiThreadDeleteDesc => '이 AI 대화의 모든 메시지가 계정에서 삭제됩니다. 되돌릴 수 없습니다.'; + + @override + String get aiThreadEmpty => '아직 대화가 없습니다. 새로 시작하세요.'; + + @override + String get aiThreadLoadFailed => '대화를 불러오지 못했습니다. 다시 시도해 주세요.'; + + @override + String get aiThreadCreateFailed => '새 대화를 만들지 못했습니다. 다시 시도해 주세요.'; + + @override + String get aiThreadRenameFailed => '이름을 변경하지 못했습니다. 다시 시도해 주세요.'; + + @override + String get aiThreadNameInvalid => '이름은 1~80자여야 합니다.'; + + @override + String get aiThreadDeleteFailed => '대화를 삭제하지 못했습니다. 다시 시도해 주세요.'; @override String multiSelectCount(int count) { diff --git a/apps/client/lib/l10n/app_localizations_vi.dart b/apps/client/lib/l10n/app_localizations_vi.dart index 199e2955..55c9bc9f 100644 --- a/apps/client/lib/l10n/app_localizations_vi.dart +++ b/apps/client/lib/l10n/app_localizations_vi.dart @@ -3157,25 +3157,54 @@ class AppLocalizationsVi extends AppLocalizations { String get leaveWithoutSaving => 'Thoát không lưu'; @override - String get aiSessionHistory => 'Lịch sử cuộc trò chuyện'; + String get aiThreadUntitled => 'Trò chuyện với AI'; @override - String get aiNewSession => 'Cuộc trò chuyện mới'; + String get aiThreadNew => 'Cuộc trò chuyện mới'; @override - String get aiSessionActive => 'Đang hoạt động'; + String get aiThreadsTitle => 'Cuộc trò chuyện'; @override - String get aiSessionSummarized => 'Đã tóm tắt'; + String get aiThreadRename => 'Đổi tên'; @override - String get aiSessionEmpty => 'Chưa có cuộc trò chuyện nào trước đây'; + String get aiThreadSave => 'Lưu'; @override - String get aiSessionResume => 'Tiếp tục'; + String get aiThreadCancel => 'Hủy'; @override - String get aiSessionLoadError => 'Không thể tải lịch sử cuộc trò chuyện'; + String get aiThreadDelete => 'Xóa'; + + @override + String get aiThreadDeleteTitle => 'Xóa cuộc trò chuyện này?'; + + @override + String get aiThreadDeleteDesc => + 'Toàn bộ tin nhắn trong cuộc trò chuyện với AI này sẽ bị xóa khỏi tài khoản của bạn. Hành động không thể hoàn tác.'; + + @override + String get aiThreadEmpty => + 'Chưa có cuộc trò chuyện nào. Bắt đầu một cuộc mới.'; + + @override + String get aiThreadLoadFailed => + 'Không tải được danh sách. Vui lòng thử lại.'; + + @override + String get aiThreadCreateFailed => + 'Không tạo được cuộc trò chuyện mới. Vui lòng thử lại.'; + + @override + String get aiThreadRenameFailed => 'Không đổi được tên. Vui lòng thử lại.'; + + @override + String get aiThreadNameInvalid => 'Tên phải từ 1 đến 80 ký tự.'; + + @override + String get aiThreadDeleteFailed => + 'Không xóa được cuộc trò chuyện. Vui lòng thử lại.'; @override String multiSelectCount(int count) { diff --git a/apps/client/lib/l10n/app_localizations_zh.dart b/apps/client/lib/l10n/app_localizations_zh.dart index 9d0ade27..215dc42b 100644 --- a/apps/client/lib/l10n/app_localizations_zh.dart +++ b/apps/client/lib/l10n/app_localizations_zh.dart @@ -3054,25 +3054,49 @@ class AppLocalizationsZh extends AppLocalizations { String get leaveWithoutSaving => '不保存离开'; @override - String get aiSessionHistory => '对话历史'; + String get aiThreadUntitled => '与 AI 聊天'; @override - String get aiNewSession => '新对话'; + String get aiThreadNew => '新对话'; @override - String get aiSessionActive => '使用中'; + String get aiThreadsTitle => '对话'; @override - String get aiSessionSummarized => '已摘要'; + String get aiThreadRename => '重命名'; @override - String get aiSessionEmpty => '暂无历史对话'; + String get aiThreadSave => '保存'; @override - String get aiSessionResume => '恢复'; + String get aiThreadCancel => '取消'; @override - String get aiSessionLoadError => '无法加载对话历史'; + String get aiThreadDelete => '删除'; + + @override + String get aiThreadDeleteTitle => '删除此对话?'; + + @override + String get aiThreadDeleteDesc => '此 AI 对话中的所有消息都将从你的账户中移除,且无法撤销。'; + + @override + String get aiThreadEmpty => '还没有对话。开始一个新的吧。'; + + @override + String get aiThreadLoadFailed => '无法加载对话,请重试。'; + + @override + String get aiThreadCreateFailed => '无法创建新对话,请重试。'; + + @override + String get aiThreadRenameFailed => '无法重命名,请重试。'; + + @override + String get aiThreadNameInvalid => '名称需为 1 到 80 个字符。'; + + @override + String get aiThreadDeleteFailed => '无法删除对话,请重试。'; @override String multiSelectCount(int count) { diff --git a/apps/client/lib/l10n/app_vi.arb b/apps/client/lib/l10n/app_vi.arb index 454bcc92..fcbc0413 100644 --- a/apps/client/lib/l10n/app_vi.arb +++ b/apps/client/lib/l10n/app_vi.arb @@ -1100,13 +1100,21 @@ "keepEditing": "Tiếp tục chỉnh sửa", "saveAndLeave": "Lưu và thoát", "leaveWithoutSaving": "Thoát không lưu", - "aiSessionHistory": "Lịch sử cuộc trò chuyện", - "aiNewSession": "Cuộc trò chuyện mới", - "aiSessionActive": "Đang hoạt động", - "aiSessionSummarized": "Đã tóm tắt", - "aiSessionEmpty": "Chưa có cuộc trò chuyện nào trước đây", - "aiSessionResume": "Tiếp tục", - "aiSessionLoadError": "Không thể tải lịch sử cuộc trò chuyện", + "aiThreadUntitled": "Trò chuyện với AI", + "aiThreadNew": "Cuộc trò chuyện mới", + "aiThreadsTitle": "Cuộc trò chuyện", + "aiThreadRename": "Đổi tên", + "aiThreadSave": "Lưu", + "aiThreadCancel": "Hủy", + "aiThreadDelete": "Xóa", + "aiThreadDeleteTitle": "Xóa cuộc trò chuyện này?", + "aiThreadDeleteDesc": "Toàn bộ tin nhắn trong cuộc trò chuyện với AI này sẽ bị xóa khỏi tài khoản của bạn. Hành động không thể hoàn tác.", + "aiThreadEmpty": "Chưa có cuộc trò chuyện nào. Bắt đầu một cuộc mới.", + "aiThreadLoadFailed": "Không tải được danh sách. Vui lòng thử lại.", + "aiThreadCreateFailed": "Không tạo được cuộc trò chuyện mới. Vui lòng thử lại.", + "aiThreadRenameFailed": "Không đổi được tên. Vui lòng thử lại.", + "aiThreadNameInvalid": "Tên phải từ 1 đến 80 ký tự.", + "aiThreadDeleteFailed": "Không xóa được cuộc trò chuyện. Vui lòng thử lại.", "multiSelectCount": "Đã chọn {count} tin nhắn", "multiSelectEmpty": "Chưa chọn tin nhắn nào", "multiSelectCancel": "Hủy", diff --git a/apps/client/lib/l10n/app_zh.arb b/apps/client/lib/l10n/app_zh.arb index 68aa7015..d6ae7e4c 100644 --- a/apps/client/lib/l10n/app_zh.arb +++ b/apps/client/lib/l10n/app_zh.arb @@ -1100,13 +1100,21 @@ "keepEditing": "继续编辑", "saveAndLeave": "保存并离开", "leaveWithoutSaving": "不保存离开", - "aiSessionHistory": "对话历史", - "aiNewSession": "新对话", - "aiSessionActive": "使用中", - "aiSessionSummarized": "已摘要", - "aiSessionEmpty": "暂无历史对话", - "aiSessionResume": "恢复", - "aiSessionLoadError": "无法加载对话历史", + "aiThreadUntitled": "与 AI 聊天", + "aiThreadNew": "新对话", + "aiThreadsTitle": "对话", + "aiThreadRename": "重命名", + "aiThreadSave": "保存", + "aiThreadCancel": "取消", + "aiThreadDelete": "删除", + "aiThreadDeleteTitle": "删除此对话?", + "aiThreadDeleteDesc": "此 AI 对话中的所有消息都将从你的账户中移除,且无法撤销。", + "aiThreadEmpty": "还没有对话。开始一个新的吧。", + "aiThreadLoadFailed": "无法加载对话,请重试。", + "aiThreadCreateFailed": "无法创建新对话,请重试。", + "aiThreadRenameFailed": "无法重命名,请重试。", + "aiThreadNameInvalid": "名称需为 1 到 80 个字符。", + "aiThreadDeleteFailed": "无法删除对话,请重试。", "multiSelectCount": "已选择 {count} 条", "multiSelectEmpty": "未选择任何消息", "multiSelectCancel": "取消", diff --git a/apps/client/test/features/ai_hub/ai_thread_list_test.dart b/apps/client/test/features/ai_hub/ai_thread_list_test.dart new file mode 100644 index 00000000..e93476ae --- /dev/null +++ b/apps/client/test/features/ai_hub/ai_thread_list_test.dart @@ -0,0 +1,282 @@ +import 'dart:async'; + +import 'package:dio/dio.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:go_router/go_router.dart'; +import 'package:platform_client/core/utils/global_messenger.dart'; +import 'package:platform_client/features/ai_hub/domain/ai_threads_provider.dart'; +import 'package:platform_client/features/ai_hub/ui/widgets/ai_new_chat_button.dart'; +import 'package:platform_client/features/ai_hub/ui/widgets/ai_thread_list.dart'; +import 'package:platform_client/features/chat/domain/chat_state.dart'; +import 'package:platform_client/l10n/app_localizations.dart'; + +ConversationModel _t(String id, {String? name}) => ConversationModel.fromJson({ + 'id': id, + 'type': 'direct', + 'name': name, + 'participants': const ['me', kAiBotUserId], + 'createdAt': '2026-01-01T00:00:00Z', + }); + +class _Fake extends AiThreadsNotifier { + _Fake(this.initial, this.log, this.router); + final List initial; + final List log; + final GoRouter Function() router; + Object? renameError; + Object? deleteError; + Future? createGate; + + @override + Future> build() async => initial; + + @override + Future create() async { + await createGate; + final c = _t('new'); + state = AsyncData([c, ...state.value!]); + log.add('create'); + return c; + } + + @override + Future rename(String id, String name) async { + log.add('rename:$id:$name'); + if (renameError != null) throw renameError!; + final c = _t(id, name: name); + state = AsyncData([for (final x in state.value!) x.id == id ? c : x]); + return c; + } + + @override + Future deleteOnServer(String id) async { + log.add('server-delete:$id@${router().routeInformationProvider.value.uri.path}'); + if (deleteError != null) throw deleteError!; + } + + @override + void drop(String id) { + log.add('drop:$id@${router().routeInformationProvider.value.uri.path}'); + state = AsyncData(state.value!.where((c) => c.id != id).toList()); + } +} + +DioException _nameInvalid() => DioException( + requestOptions: RequestOptions(path: '/x'), + response: Response( + requestOptions: RequestOptions(path: '/x'), + statusCode: 400, + data: {'code': 'AI_THREAD_NAME_INVALID'}, + ), + ); + +void main() { + late List log; + late GoRouter router; + late _Fake fake; + + Future pumpList(WidgetTester tester, List threads, + {String? openId, String start = '/'}) async { + log = []; + router = GoRouter(navigatorKey: rootNavigatorKey, initialLocation: start, routes: [ + GoRoute( + path: '/', + builder: (_, __) => + Scaffold(body: AiThreadList(openId: openId))), + GoRoute( + path: '/chat/:id', + builder: (_, s) => Scaffold( + body: AiThreadList(openId: s.pathParameters['id']))), + GoRoute( + path: '/ai-hub', builder: (_, __) => const Scaffold(body: Text('HUB'))), + ]); + fake = _Fake(threads, log, () => router); + await tester.pumpWidget(ProviderScope( + overrides: [aiThreadsProvider.overrideWith(() => fake)], + child: MaterialApp.router( + routerConfig: router, + locale: const Locale('en'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + ), + )); + await tester.pumpAndSettle(); + } + + String path() => router.routeInformationProvider.value.uri.path; + + testWidgets('renders titles in order, untitled fallback, active highlighted', + (tester) async { + await pumpList(tester, + [_t('a', name: ' Alpha '), _t('b'), _t('c', name: ' ')], + openId: 'a'); + expect(find.text('Alpha'), findsOneWidget); + expect(find.text('Chat with AI'), findsNWidgets(2)); + expect(tester.getTopLeft(find.text('Alpha')).dy, + lessThan(tester.getTopLeft(find.text('Chat with AI').first).dy)); + expect(find.byKey(const ValueKey('ai-thread-active-a')), findsOneWidget); + expect(find.byKey(const ValueKey('ai-thread-active-b')), findsNothing); + }); + + testWidgets('empty state', (tester) async { + await pumpList(tester, []); + expect(find.text('No conversations yet. Start a new one.'), findsOneWidget); + }); + + testWidgets('new chat creates and navigates', (tester) async { + await pumpList(tester, [_t('a')]); + await tester.tap(find.text('New conversation')); + await tester.pumpAndSettle(); + expect(log, ['create']); + expect(path(), '/chat/new'); + }); + + testWidgets('tap thread navigates', (tester) async { + await pumpList(tester, [_t('a', name: 'Alpha')]); + await tester.tap(find.text('Alpha')); + await tester.pumpAndSettle(); + expect(path(), '/chat/a'); + }); + + testWidgets('rename submit saves trimmed', (tester) async { + await pumpList(tester, [_t('a', name: 'Alpha')]); + await tester.tap(find.byTooltip('Rename')); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField), ' Beta '); + await tester.tap(find.byTooltip('Save')); + await tester.pumpAndSettle(); + expect(log, ['rename:a:Beta']); + expect(find.text('Beta'), findsOneWidget); + expect(find.byType(TextField), findsNothing); + }); + + testWidgets('rename cancel restores', (tester) async { + await pumpList(tester, [_t('a', name: 'Alpha')]); + await tester.tap(find.byTooltip('Rename')); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField), 'Zzz'); + await tester.tap(find.byTooltip('Cancel')); + await tester.pumpAndSettle(); + expect(log, isEmpty); + expect(find.text('Alpha'), findsOneWidget); + }); + + testWidgets('invalid name shows localized error and keeps editor', + (tester) async { + await pumpList(tester, [_t('a', name: 'Alpha')]); + fake.renameError = _nameInvalid(); + await tester.tap(find.byTooltip('Rename')); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField), 'x'); + await tester.tap(find.byTooltip('Save')); + await tester.pumpAndSettle(); + expect(find.text('Name must be 1 to 80 characters.'), findsOneWidget); + expect(find.byType(TextField), findsOneWidget); + }); + + testWidgets('delete confirm removes thread', (tester) async { + await pumpList(tester, [_t('a', name: 'Alpha'), _t('b', name: 'Bravo')]); + await tester.tap(find.byTooltip('Delete').last); + await tester.pumpAndSettle(); + expect(find.text('Delete this conversation?'), findsOneWidget); + await tester.tap(find.text('Confirm')); + await tester.pumpAndSettle(); + expect(log, ['server-delete:b@/', 'drop:b@/']); + expect(find.text('Bravo'), findsNothing); + }); + + testWidgets('delete cancel keeps thread', (tester) async { + await pumpList(tester, [_t('a', name: 'Alpha')]); + await tester.tap(find.byTooltip('Delete')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + expect(log, isEmpty); + expect(find.text('Alpha'), findsOneWidget); + }); + + testWidgets('deleting the open thread server-deletes, navigates to next, then drops', + (tester) async { + await pumpList( + tester, [_t('a', name: 'A'), _t('b', name: 'B'), _t('c', name: 'C')], + openId: 'b', start: '/chat/b'); + await tester.tap(find.byTooltip('Delete').at(1)); + await tester.pumpAndSettle(); + await tester.tap(find.text('Confirm')); + await tester.pumpAndSettle(); + expect(log, ['server-delete:b@/chat/b', 'drop:b@/chat/c']); + }); + + testWidgets('deleting the last open thread goes to previous', + (tester) async { + await pumpList(tester, [_t('a', name: 'A'), _t('b', name: 'B')], + openId: 'b', start: '/chat/b'); + await tester.tap(find.byTooltip('Delete').last); + await tester.pumpAndSettle(); + await tester.tap(find.text('Confirm')); + await tester.pumpAndSettle(); + expect(log, ['server-delete:b@/chat/b', 'drop:b@/chat/a']); + }); + + testWidgets('deleting the only open thread goes to the AI hub', + (tester) async { + await pumpList(tester, [_t('a', name: 'A')], + openId: 'a', start: '/chat/a'); + await tester.tap(find.byTooltip('Delete')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Confirm')); + await tester.pumpAndSettle(); + expect(log, ['server-delete:a@/chat/a', 'drop:a@/ai-hub']); + }); + + testWidgets('delete failure: error banner, stays on thread, still listed', + (tester) async { + await pumpList(tester, [_t('a', name: 'Alpha'), _t('b', name: 'Bravo')], + openId: 'a', start: '/chat/a'); + fake.deleteError = Exception('boom'); + await tester.tap(find.byTooltip('Delete').first); + await tester.pumpAndSettle(); + await tester.tap(find.text('Confirm')); + await tester.pumpAndSettle(); + expect(find.textContaining('boom'), findsNothing); + expect(find.text("Couldn't delete the conversation. Please try again."), + findsOneWidget); + expect(path(), '/chat/a'); + expect(log, ['server-delete:a@/chat/a']); + expect(find.text('Alpha'), findsOneWidget); + await tester.pump(const Duration(seconds: 10)); + }); + + testWidgets('header new-chat button disables while create is pending', + (tester) async { + final gate = Completer(); + log = []; + router = GoRouter(navigatorKey: rootNavigatorKey, routes: [ + GoRoute( + path: '/', + builder: (_, __) => const Scaffold(body: AiNewChatButton())), + GoRoute(path: '/chat/:id', builder: (_, __) => const Scaffold()), + ]); + fake = _Fake([_t('a')], log, () => router)..createGate = gate.future; + await tester.pumpWidget(ProviderScope( + overrides: [aiThreadsProvider.overrideWith(() => fake)], + child: MaterialApp.router( + routerConfig: router, + locale: const Locale('en'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + ), + )); + await tester.pumpAndSettle(); + await tester.tap(find.byType(IconButton)); + await tester.pump(); + await tester.tap(find.byType(IconButton), warnIfMissed: false); + await tester.pump(); + gate.complete(); + await tester.pumpAndSettle(); + expect(log.where((e) => e == 'create'), hasLength(1)); + expect(path(), '/chat/new'); + }); +} diff --git a/apps/client/test/features/ai_hub/ai_threads_test.dart b/apps/client/test/features/ai_hub/ai_threads_test.dart new file mode 100644 index 00000000..6b36bc82 --- /dev/null +++ b/apps/client/test/features/ai_hub/ai_threads_test.dart @@ -0,0 +1,319 @@ +// ignore_for_file: invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member + +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:dio/dio.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:platform_client/features/ai_hub/data/ai_thread_repository.dart'; +import 'package:platform_client/features/ai_hub/domain/ai_threads_provider.dart'; +import 'package:platform_client/features/chat/data/chat_repository.dart'; +import 'package:platform_client/features/chat/data/stomp_service.dart'; +import 'package:platform_client/features/chat/domain/chat_misc_providers.dart'; +import 'package:platform_client/features/chat/domain/chat_state.dart'; +import 'package:platform_client/features/chat/domain/conversations_notifier.dart'; + +class _Adapter implements HttpClientAdapter { + final requests = []; + @override + Future fetch(RequestOptions options, + Stream? requestStream, Future? cancelFuture) async { + requests.add(options); + final body = options.method == 'GET' + ? [_json('t1')] + : _json('t1', name: options.data is Map ? options.data['name'] as String? : null); + return ResponseBody.fromString(jsonEncode(body), 200, headers: { + Headers.contentTypeHeader: ['application/json'], + }); + } + + @override + void close({bool force = false}) {} +} + +Map _json(String id, + {String? name, List? participants, String? lastAt}) => + { + 'id': id, + 'type': 'direct', + 'name': name, + 'participants': participants ?? ['me', kAiBotUserId], + 'createdAt': '2026-01-01T00:00:00Z', + if (lastAt != null) 'lastMessageAt': lastAt, + }; + +ConversationModel _thread(String id, {String? lastAt, String? name}) => + ConversationModel.fromJson(_json(id, lastAt: lastAt, name: name)); + +class MockAiRepo extends Mock implements AiThreadRepository {} + +class MockChatRepo extends Mock implements ChatRepository {} + +class _EmptyConversations extends ConversationsNotifier { + @override + Future> build() async => []; +} + +class FakeStomp extends StompService { + final conv = StreamController.broadcast(); + final notif = StreamController>.broadcast(); + final reconn = StreamController.broadcast(); + @override + void build() {} + @override + Stream get conversationUpdates => conv.stream; + @override + Stream> get notifications => notif.stream; + @override + Stream get reconnects => reconn.stream; +} + +Future _pump() => Future.delayed(Duration.zero); + +void main() { + group('AiThreadRepository', () { + late _Adapter adapter; + late AiThreadRepository repo; + setUp(() { + adapter = _Adapter(); + repo = AiThreadRepository(Dio()..httpClientAdapter = adapter); + }); + + test('list GETs /api/ai-threads', () async { + final r = await repo.list(); + expect(r.single.id, 't1'); + expect(adapter.requests.single.path, '/api/ai-threads'); + }); + + test('create POSTs and parses', () async { + final c = await repo.create(); + expect(adapter.requests.single.method, 'POST'); + expect(c.name, isNull); + expect(c.isAiConversation, isTrue); + }); + + test('rename PATCHes name', () async { + final c = await repo.rename('t1', 'Hello'); + expect(adapter.requests.single.method, 'PATCH'); + expect(adapter.requests.single.path, '/api/ai-threads/t1'); + expect(adapter.requests.single.data, {'name': 'Hello'}); + expect(c.name, 'Hello'); + }); + }); + + group('AiThreadsNotifier', () { + late MockAiRepo aiRepo; + late MockChatRepo chatRepo; + late FakeStomp stomp; + late ProviderContainer container; + var viewing = ''; + + Future boot(List initial) async { + when(() => aiRepo.list()).thenAnswer((_) async => initial); + await container.read(aiThreadsProvider.future); + } + + List ids() => + container.read(aiThreadsProvider).value!.map((c) => c.id).toList(); + + setUp(() { + aiRepo = MockAiRepo(); + chatRepo = MockChatRepo(); + stomp = FakeStomp(); + viewing = ''; + container = ProviderContainer(overrides: [ + aiThreadRepositoryProvider.overrideWithValue(aiRepo), + chatRepositoryProvider.overrideWithValue(chatRepo), + stompServiceProvider.overrideWith(() => stomp), + conversationsNotifierProvider + .overrideWith(() => _EmptyConversations()), + aiThreadViewingProvider.overrideWithValue((id) => id == viewing), + ]); + }); + tearDown(() => container.dispose()); + + test('create puts the new thread on top', () async { + await boot([_thread('a')]); + when(() => aiRepo.create()).thenAnswer((_) async => _thread('n')); + await container.read(aiThreadsProvider.notifier).create(); + expect(ids(), ['n', 'a']); + }); + + test('create while the list is still loading is not dropped', () async { + final gate = Completer>(); + when(() => aiRepo.list()).thenAnswer((_) => gate.future); + when(() => aiRepo.create()).thenAnswer((_) async => _thread('n')); + container.listen(aiThreadsProvider, (_, __) {}); + final created = container.read(aiThreadsProvider.notifier).create(); + await _pump(); + gate.complete([_thread('a')]); + await created; + expect(ids(), ['n', 'a']); + }); + + test('conversationProvider falls back to the AI thread', () async { + await boot([_thread('a', name: 'Chat A')]); + final c = container.read(conversationProvider('a')); + expect(c?.name, 'Chat A'); + expect(container.read(conversationProvider('nope')), isNull); + }); + + test('rename keeps position', () async { + await boot([_thread('a'), _thread('b')]); + when(() => aiRepo.rename('b', 'X')) + .thenAnswer((_) async => _thread('b', name: 'X')); + await container.read(aiThreadsProvider.notifier).rename('b', 'X'); + expect(ids(), ['a', 'b']); + expect(container.read(aiThreadsProvider).value![1].name, 'X'); + }); + + test('delete removes optimistically and calls per-user delete', () async { + await boot([_thread('a'), _thread('b')]); + when(() => chatRepo.deleteConversation('a')).thenAnswer((_) async {}); + await container.read(aiThreadsProvider.notifier).delete('a'); + expect(ids(), ['b']); + verify(() => chatRepo.deleteConversation('a')).called(1); + }); + + test('delete failure refetches and rethrows', () async { + await boot([_thread('a')]); + when(() => chatRepo.deleteConversation('a')).thenThrow(Exception('x')); + await expectLater( + container.read(aiThreadsProvider.notifier).delete('a'), throwsException); + expect(ids(), ['a']); + }); + + test('newestOrCreate opens newest, creates when empty', () async { + await boot([_thread('a'), _thread('b')]); + final n = container.read(aiThreadsProvider.notifier); + expect((await n.newestOrCreate()).id, 'a'); + when(() => aiRepo.list()).thenAnswer((_) async => []); + when(() => aiRepo.create()).thenAnswer((_) async => _thread('n')); + expect((await n.newestOrCreate()).id, 'n'); + expect(ids(), ['n']); + }); + + test('personal update for unknown AI conversation inserts at top', + () async { + await boot([_thread('a')]); + stomp.conv.add(ConversationUpdateEvent( + json: _json('n'), personal: true)); + await _pump(); + expect(ids(), ['n', 'a']); + }); + + test('non-AI update is ignored', () async { + await boot([_thread('a')]); + stomp.conv.add(ConversationUpdateEvent( + json: _json('z', participants: ['me', 'bob']), personal: true)); + await _pump(); + expect(ids(), ['a']); + }); + + test('group containing the bot is not an AI thread update', () async { + await boot([_thread('a')]); + stomp.conv.add(ConversationUpdateEvent( + json: { + ..._json('g', participants: ['me', 'bob', kAiBotUserId]), + 'type': 'group', + }, + personal: true)); + await _pump(); + expect(ids(), ['a']); + }); + + test('shared update (auto-title) merges the name', () async { + await boot([_thread('a')]); + stomp.conv.add(ConversationUpdateEvent( + json: _json('a', name: 'Auto title'), personal: false)); + await _pump(); + expect(container.read(aiThreadsProvider).value!.single.name, 'Auto title'); + }); + + test('new message bumps thread to top with preview, unread unless viewing', + () async { + await boot([_thread('a'), _thread('b')]); + stomp.notif.add({ + 'type': 'NEW_MESSAGE', + 'conversationId': 'b', + 'senderId': kAiBotUserId, + 'content': 'hi', + 'messageId': 'm1', + 'createdAt': '2026-02-01T00:00:00Z', + }); + await _pump(); + final list = container.read(aiThreadsProvider).value!; + expect(list.first.id, 'b'); + expect(list.first.lastMessage?.content, 'hi'); + expect(list.first.unreadCount, 1); + + viewing = 'a'; + stomp.notif.add({ + 'type': 'NEW_MESSAGE', + 'conversationId': 'a', + 'senderId': kAiBotUserId, + 'content': 'yo', + 'messageId': 'm2', + 'createdAt': '2026-02-02T00:00:00Z', + }); + await _pump(); + final after = container.read(aiThreadsProvider).value!; + expect(after.first.id, 'a'); + expect(after.first.unreadCount, 0); + }); + + test('message for a non-thread conversation is ignored', () async { + await boot([_thread('a')]); + stomp.notif.add({'type': 'NEW_MESSAGE', 'conversationId': 'other', + 'senderId': 'bob', 'content': 'x'}); + await _pump(); + expect(ids(), ['a']); + }); + + test('reconnect refreshes threads', () async { + await boot([_thread('a')]); + when(() => aiRepo.list()) + .thenAnswer((_) async => [_thread('z'), _thread('a')]); + stomp.reconn.add(null); + await _pump(); + await _pump(); + expect(ids(), ['z', 'a']); + }); + }); + + group('isAiConversation', () { + test('a group containing the bot is NOT an AI thread', () { + final g = ConversationModel.fromJson({ + ..._json('g', participants: ['me', 'bob', kAiBotUserId]), + 'type': 'group', + }); + expect(g.isAiConversation, isFalse); + expect(isAiConversationJson({'type': 'group', 'participants': [kAiBotUserId]}), + isFalse); + }); + + test('missing type counts as direct', () { + final json = _json('x')..remove('type'); + expect(ConversationModel.fromJson(json).isAiConversation, isTrue); + expect(isAiConversationJson(json), isTrue); + }); + }); + + test('excludeAi is sent for main and archived lists', () async { + final adapter = _Adapter(); + final repo = ChatRepository(Dio()..httpClientAdapter = adapter); + try { + await repo.listConversations(); + } catch (_) {} + try { + await repo.listArchivedConversations(); + } catch (_) {} + expect(adapter.requests, hasLength(2)); + for (final r in adapter.requests) { + expect(r.queryParameters['excludeAi'], true); + } + }); +} diff --git a/apps/client/test/features/chat/conversations_notifier_test.dart b/apps/client/test/features/chat/conversations_notifier_test.dart index be3c47b1..e30dc971 100644 --- a/apps/client/test/features/chat/conversations_notifier_test.dart +++ b/apps/client/test/features/chat/conversations_notifier_test.dart @@ -6,6 +6,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; +import 'package:platform_client/features/ai_hub/domain/ai_threads_provider.dart'; import 'package:platform_client/features/chat/data/chat_repository.dart'; import 'package:platform_client/features/chat/data/stomp_service.dart'; import 'package:platform_client/features/chat/domain/chat_state.dart'; @@ -72,6 +73,13 @@ ConversationModel _fakeConversation(String id) => ConversationModel( createdAt: DateTime(2024), ); +class _FixedAiThreads extends AiThreadsNotifier { + _FixedAiThreads(this.initial); + final List initial; + @override + Future> build() async => initial; +} + void main() { late MockChatRepository mockRepo; late ProviderContainer container; @@ -150,6 +158,61 @@ void main() { verify(() => mockRepo.deleteConversation('conv-B')).called(1); }); + ConversationModel aiConv() => ConversationModel( + id: 'ai-1', + type: 'direct', + participants: const ['me', kAiBotUserId], + unreadCount: 0, + createdAt: DateTime(2024), + ); + + Future aiContainer() async { + when(() => mockRepo.listConversations()).thenAnswer((_) async => []); + final c = ProviderContainer(overrides: [ + chatRepositoryProvider.overrideWithValue(mockRepo), + stompServiceProvider.overrideWith(() => FakeStompService()), + conversationsNotifierProvider + .overrideWith(() => _TestableConversationsNotifier(mockRepo)), + aiThreadsProvider.overrideWith(() => _FixedAiThreads([aiConv()])), + ]); + addTearDown(c.dispose); + await c.read(conversationsNotifierProvider.future); + await c.read(aiThreadsProvider.future); + return c; + } + + test('AI thread delete: server first, then onDeleted(isAi), then drop', + () async { + final c = await aiContainer(); + final order = []; + when(() => mockRepo.deleteConversation(any())).thenAnswer((_) async { + order.add('server'); + }); + await c + .read(conversationsNotifierProvider.notifier) + .deleteConversation('ai-1', onDeleted: (isAi) { + // Row must still be present while the caller navigates away. + order.add('leave:$isAi:${c.read(aiThreadsProvider).value!.length}'); + }); + expect(order, ['server', 'leave:true:1']); + expect(c.read(aiThreadsProvider).value, isEmpty); + }); + + test('AI thread delete failure rethrows, keeps the row, never leaves', + () async { + final c = await aiContainer(); + var left = false; + when(() => mockRepo.deleteConversation(any())) + .thenAnswer((_) async => throw Exception('boom')); + await expectLater( + c.read(conversationsNotifierProvider.notifier).deleteConversation( + 'ai-1', + onDeleted: (_) => left = true), + throwsException); + expect(left, isFalse); + expect(c.read(aiThreadsProvider).value!.map((x) => x.id), ['ai-1']); + }); + // ------------------------------------------------------------------------- // Test 3 — deleteConversation rolls back on server error // ------------------------------------------------------------------------- diff --git a/apps/server/ai-service/src/scheduler/daily-digest.cron.spec.ts b/apps/server/ai-service/src/scheduler/daily-digest.cron.spec.ts index d2b8a566..23336944 100644 --- a/apps/server/ai-service/src/scheduler/daily-digest.cron.spec.ts +++ b/apps/server/ai-service/src/scheduler/daily-digest.cron.spec.ts @@ -1,3 +1,4 @@ +import { Types } from 'mongoose'; import { DailyDigestCron } from './daily-digest.cron'; import { ResolvedAiSettings } from '../settings/resolved-ai-settings'; @@ -22,17 +23,24 @@ interface Mocks { create: jest.Mock; deleteOne: jest.Mock; distinct: jest.Mock; + find: jest.Mock; generate: jest.Mock; } function makeCron(opts: { resolved: ResolvedAiSettings; activeIds?: string[]; + aiThreadIds?: string[]; createImpl?: jest.Mock; generateImpl?: jest.Mock; }): Mocks { const distinct = jest.fn().mockResolvedValue(opts.activeIds ?? ['conv-1']); - const connection = { collection: () => ({ distinct }) } as any; + const find = jest.fn().mockReturnValue({ + toArray: jest + .fn() + .mockResolvedValue((opts.aiThreadIds ?? []).map((id) => ({ _id: new Types.ObjectId(id) }))), + }); + const connection = { collection: () => ({ distinct, find }) } as any; const create = opts.createImpl ?? jest.fn().mockResolvedValue({}); const deleteOne = jest.fn().mockReturnValue({ exec: jest.fn().mockResolvedValue({}) }); @@ -47,7 +55,7 @@ function makeCron(opts: { ({ 'config.ai.timeZone': 'Asia/Ho_Chi_Minh', 'config.bot.userId': 'ai-bot-1' })[k], } as any; const cron = new DailyDigestCron(connection, digestLogModel, settingsService, generator, config); - return { cron, create, deleteOne, distinct, generate }; + return { cron, create, deleteOne, distinct, find, generate }; } // 08:00 in the workspace zone (Asia/Ho_Chi_Minh, +07:00) — 01:00 UTC. Absolute @@ -101,6 +109,28 @@ describe('DailyDigestCron (TASK-11)', () => { expect(deleteOne).not.toHaveBeenCalled(); }); + it('skips conversations whose participants include the AI bot (1-1 AI threads)', async () => { + const aiThread = new Types.ObjectId().toHexString(); + const group = new Types.ObjectId().toHexString(); + const { cron, find, create, generate } = makeCron({ + resolved: settings(), + activeIds: [aiThread, group], + aiThreadIds: [aiThread], + }); + await cron.run(AT_8); + expect(find).toHaveBeenCalledWith( + { + _id: { $in: [new Types.ObjectId(aiThread), new Types.ObjectId(group)] }, + participants: 'ai-bot-1', + type: { $ne: 'group' }, + }, + { projection: { _id: 1 } }, + ); + expect(create).toHaveBeenCalledTimes(1); + expect(create).toHaveBeenCalledWith({ conversationId: group, digestDate: '2026-06-22' }); + expect(generate).toHaveBeenCalledTimes(1); + }); + it('SKIPS generation on a duplicate-key (already digested ⇒ idempotent)', async () => { const dupErr = Object.assign(new Error('E11000 duplicate key'), { code: 11000 }); const create = jest.fn().mockRejectedValue(dupErr); diff --git a/apps/server/ai-service/src/scheduler/daily-digest.cron.ts b/apps/server/ai-service/src/scheduler/daily-digest.cron.ts index 37266dea..15d21206 100644 --- a/apps/server/ai-service/src/scheduler/daily-digest.cron.ts +++ b/apps/server/ai-service/src/scheduler/daily-digest.cron.ts @@ -8,6 +8,7 @@ import { DigestGeneratorService } from './digest-generator.service'; import { DigestLog, DigestLogDocument } from './digest-log.schema'; import { localHour, yesterdayWindow } from './digest-date.util'; import { safeTimeZone } from '../common/time-zone'; +import { toObjectIds } from '../common/object-id'; /** Mongo duplicate-key error code (unique-index idempotency guard). */ const DUP_KEY = 11000; @@ -122,6 +123,20 @@ export class DailyDigestCron { senderId: { $ne: this.botUserId }, recalled: { $ne: true }, }); - return (ids as unknown[]).map((id) => String(id)).filter(Boolean); + const activeIds = (ids as unknown[]).map((id) => String(id)).filter(Boolean); + + // 1-1 AI threads (direct/untyped conversation with the bot as participant) + // must never get a digest. Groups containing the bot are still digested. + const objectIds = toObjectIds(activeIds); + if (objectIds.length === 0) return activeIds; + const aiThreads = await this.connection + .collection('conversations') + .find( + { _id: { $in: objectIds }, participants: this.botUserId, type: { $ne: 'group' } }, + { projection: { _id: 1 } }, + ) + .toArray(); + const skip = new Set(aiThreads.map((c) => String(c._id))); + return activeIds.filter((id) => !skip.has(id)); } } diff --git a/apps/server/chat-service/src/main/java/com/platform/chatservice/controller/AiThreadController.java b/apps/server/chat-service/src/main/java/com/platform/chatservice/controller/AiThreadController.java new file mode 100644 index 00000000..251d400d --- /dev/null +++ b/apps/server/chat-service/src/main/java/com/platform/chatservice/controller/AiThreadController.java @@ -0,0 +1,56 @@ +package com.platform.chatservice.controller; + +import com.platform.chatservice.dto.ConversationResponse; +import com.platform.chatservice.dto.RenameAiThreadRequest; +import com.platform.chatservice.exception.UnauthorizedException; +import com.platform.chatservice.security.UserPrincipal; +import com.platform.chatservice.service.AiThreadService; +import com.platform.chatservice.service.ConversationEventPublisher; +import java.util.List; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.bind.annotation.*; + +/** + * ChatGPT-style AI threads. Deleting a thread is the existing {@code DELETE + * /api/conversations/{id}}. + */ +@RestController +@RequestMapping("/api/ai-threads") +@RequiredArgsConstructor +public class AiThreadController { + + private final AiThreadService aiThreadService; + private final ConversationEventPublisher events; + + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public ConversationResponse create() { + String userId = currentUserId(); + ConversationResponse created = aiThreadService.create(userId); + // The user's other devices learn about the new thread via their own notification queue. + events.publishToUser(userId, created); + return created; + } + + @GetMapping + public List list() { + return aiThreadService.list(currentUserId()); + } + + @PatchMapping("/{id}") + public ConversationResponse rename( + @PathVariable String id, @RequestBody RenameAiThreadRequest request) { + ConversationResponse updated = aiThreadService.rename(currentUserId(), id, request.name()); + events.publishShared(updated); + return updated; + } + + private String currentUserId() { + if (SecurityContextHolder.getContext().getAuthentication() instanceof UserPrincipal p) { + return p.getUserId(); + } + throw new UnauthorizedException("Not authenticated"); + } +} diff --git a/apps/server/chat-service/src/main/java/com/platform/chatservice/controller/ConversationController.java b/apps/server/chat-service/src/main/java/com/platform/chatservice/controller/ConversationController.java index eca86475..dd730120 100644 --- a/apps/server/chat-service/src/main/java/com/platform/chatservice/controller/ConversationController.java +++ b/apps/server/chat-service/src/main/java/com/platform/chatservice/controller/ConversationController.java @@ -64,20 +64,22 @@ public class ConversationController { /** * The caller's conversations. {@code archived=true} → only archived ones (default: archived ones - * excluded); {@code blocked=true} → the Blocked section. {@code size} is capped at 100. + * excluded); {@code blocked=true} → the Blocked section. {@code excludeAi=true} drops 1-1 chats + * with the AI bot (they live in the AI-thread list). {@code size} is capped at 100. */ @GetMapping public PageResponse listConversations( @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "20") int size, @RequestParam(defaultValue = "false") boolean archived, - @RequestParam(defaultValue = "false") boolean blocked) { + @RequestParam(defaultValue = "false") boolean blocked, + @RequestParam(defaultValue = "false") boolean excludeAi) { if (blocked) { return conversationQueryService.listBlockedConversations( currentUserId(), PageLimits.of(page, size, 20)); } return conversationQueryService.listConversations( - currentUserId(), PageLimits.of(page, size, 20), archived); + currentUserId(), PageLimits.of(page, size, 20), archived, excludeAi); } @PostMapping diff --git a/apps/server/chat-service/src/main/java/com/platform/chatservice/dto/RenameAiThreadRequest.java b/apps/server/chat-service/src/main/java/com/platform/chatservice/dto/RenameAiThreadRequest.java new file mode 100644 index 00000000..11412dc3 --- /dev/null +++ b/apps/server/chat-service/src/main/java/com/platform/chatservice/dto/RenameAiThreadRequest.java @@ -0,0 +1,4 @@ +package com.platform.chatservice.dto; + +/** Body of {@code PATCH /api/ai-threads/{id}}. */ +public record RenameAiThreadRequest(String name) {} diff --git a/apps/server/chat-service/src/main/java/com/platform/chatservice/exception/ErrorCodes.java b/apps/server/chat-service/src/main/java/com/platform/chatservice/exception/ErrorCodes.java index e7b8a0b0..8751b97e 100644 --- a/apps/server/chat-service/src/main/java/com/platform/chatservice/exception/ErrorCodes.java +++ b/apps/server/chat-service/src/main/java/com/platform/chatservice/exception/ErrorCodes.java @@ -57,6 +57,9 @@ public final class ErrorCodes { public static final String PUBLIC_DEPARTMENT_CHANNEL_NOT_ALLOWED = "PUBLIC_DEPARTMENT_CHANNEL_NOT_ALLOWED"; + /** 400 — an AI thread name is blank or longer than 80 characters after trimming. */ + public static final String AI_THREAD_NAME_INVALID = "AI_THREAD_NAME_INVALID"; + // ── Meetings (/api/meetings) ────────────────────────────────────────────── /** 404 — no meeting with this id / code. */ diff --git a/apps/server/chat-service/src/main/java/com/platform/chatservice/repository/ConversationRepository.java b/apps/server/chat-service/src/main/java/com/platform/chatservice/repository/ConversationRepository.java index 1763af2e..26866f1f 100644 --- a/apps/server/chat-service/src/main/java/com/platform/chatservice/repository/ConversationRepository.java +++ b/apps/server/chat-service/src/main/java/com/platform/chatservice/repository/ConversationRepository.java @@ -38,6 +38,15 @@ Page findByParticipantsContainingAndBlockedByContainingOrderByLast sort = "{ 'createdAt': 1, '_id': 1 }") List findOneOnOneConversations(List participants); + /** + * Two-member non-group conversations, tolerating legacy documents with no {@code type} field + * (used for AI threads; mirrors the {@code type != 'group'} rule of the list exclusion). + */ + @Query( + value = "{ 'participants': { $all: ?0, $size: 2 }, 'type': { $ne: 'group' } }", + sort = "{ 'createdAt': 1, '_id': 1 }") + List findTwoMemberNonGroupConversations(List participants); + /** Public group channels visible to all (Task 52). */ @Query("{ 'publicChannel': true, 'type': 'group' }") Page findPublicGroups(Pageable pageable); diff --git a/apps/server/chat-service/src/main/java/com/platform/chatservice/service/AiThreadService.java b/apps/server/chat-service/src/main/java/com/platform/chatservice/service/AiThreadService.java new file mode 100644 index 00000000..0bb5ffaa --- /dev/null +++ b/apps/server/chat-service/src/main/java/com/platform/chatservice/service/AiThreadService.java @@ -0,0 +1,151 @@ +package com.platform.chatservice.service; + +import com.platform.chatservice.dto.ConversationResponse; +import com.platform.chatservice.exception.BadRequestException; +import com.platform.chatservice.exception.ConversationNotFoundException; +import com.platform.chatservice.exception.ErrorCodes; +import com.platform.chatservice.model.AiPersona; +import com.platform.chatservice.model.Conversation; +import com.platform.chatservice.repository.AiPersonaRepository; +import com.platform.chatservice.repository.ConversationRepository; +import java.time.Instant; +import java.util.Comparator; +import java.util.List; +import lombok.RequiredArgsConstructor; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Update; +import org.springframework.stereotype.Service; + +/** + * ChatGPT-style AI threads: every "new chat" with the assistant is its own {@code direct} + * conversation between the user and the AI bot. {@link ConversationService#createConversation} + * keeps refusing a second DM for the same pair (older clients rely on that 409), so threads are + * created here instead. + */ +@Service +@RequiredArgsConstructor +public class AiThreadService { + + static final int MAX_LIST = 100; + static final int MAX_NAME_LENGTH = 80; + static final int TITLE_LENGTH = 60; + + private final ConversationRepository conversationRepository; + private final ConversationCacheService conversationCacheService; + private final AiPersonaRepository aiPersonaRepository; + private final ConversationWriteSupport support; + private final ConversationEventPublisher events; + + /** + * New thread {@code [user, AI_BOT]}; the persona of the most recently active thread is copied. + */ + public ConversationResponse create(String userId) { + List existing = threadsOf(userId); + Conversation saved = + conversationCacheService.save( + Conversation.builder() + .participants(List.of(userId, AiConstants.AI_BOT_USER_ID)) + .type(Conversation.TYPE_DIRECT) + .createdBy(userId) + .status(Conversation.STATUS_ACCEPTED) + .build()); + existing.stream() + .max(ACTIVITY) + .flatMap(latest -> aiPersonaRepository.findByConversationId(latest.getId())) + .ifPresent(source -> aiPersonaRepository.save(copyPersona(source, saved.getId(), userId))); + return support.view(saved, userId, 0L); + } + + /** The caller's visible AI threads, newest activity first (max {@value #MAX_LIST}). */ + public List list(String userId) { + return threadsOf(userId).stream() + .filter(c -> c.getHiddenFor() == null || !c.getHiddenFor().contains(userId)) + .filter(c -> c.getBlockedBy() == null || !c.getBlockedBy().contains(userId)) + .sorted(ACTIVITY.reversed()) + .limit(MAX_LIST) + .map(c -> support.view(c, userId, 0L)) + .toList(); + } + + /** Rename. 404 unless {@code id} is one of the caller's AI threads; 400 on a bad name. */ + public ConversationResponse rename(String userId, String id, String rawName) { + Conversation thread = support.requireParticipant(userId, id); + if (!isAiThread(thread)) { + throw new ConversationNotFoundException(id); + } + String name = rawName == null ? "" : rawName.trim(); + if (name.isEmpty() || name.length() > MAX_NAME_LENGTH) { + throw new BadRequestException( + ErrorCodes.AI_THREAD_NAME_INVALID, "Thread name must be 1-80 characters"); + } + Conversation updated = support.update(id, null, new Update().set("name", name)); + return support.view(updated != null ? updated : thread, userId, 0L); + } + + /** + * Title an untitled AI thread from the user's first message: first {@value #TITLE_LENGTH} + * characters, whitespace collapsed, {@code …} when cut. Never overwrites an existing name (the + * write is guarded atomically, so a concurrent rename wins) and ignores non-AI conversations. + */ + public void maybeAutoTitle(Conversation conversation, String userText) { + if (conversation == null + || userText == null + || !isAiThread(conversation) + || (conversation.getName() != null && !conversation.getName().isBlank())) { + return; + } + String title = toTitle(userText); + if (title.isEmpty()) { + return; + } + Criteria unnamed = + new Criteria().orOperator(Criteria.where("name").is(null), Criteria.where("name").is("")); + Conversation updated = + support.update(conversation.getId(), unnamed, new Update().set("name", title)); + if (updated != null) { + events.publishShared(support.view(updated, null, 0L)); + } + } + + static String toTitle(String text) { + String collapsed = text.trim().replaceAll("\\s+", " "); + if (collapsed.length() <= TITLE_LENGTH) { + return collapsed; + } + int end = TITLE_LENGTH - 1; + if (Character.isHighSurrogate(collapsed.charAt(end - 1))) { + end--; + } + return collapsed.substring(0, end) + "…"; + } + + static boolean isAiThread(Conversation c) { + return !c.isGroup() + && c.getParticipants() != null + && c.getParticipants().size() == 2 + && c.getParticipants().contains(AiConstants.AI_BOT_USER_ID); + } + + private List threadsOf(String userId) { + return conversationRepository.findTwoMemberNonGroupConversations( + List.of(userId, AiConstants.AI_BOT_USER_ID)); + } + + private static AiPersona copyPersona(AiPersona source, String conversationId, String userId) { + return AiPersona.builder() + .conversationId(conversationId) + .name(source.getName()) + .avatarUrl(source.getAvatarUrl()) + .tone(source.getTone()) + .systemPromptPrefix(source.getSystemPromptPrefix()) + .createdBy(userId) + .build(); + } + + /** {@code lastMessageAt}, falling back to {@code createdAt}. */ + private static final Comparator ACTIVITY = + Comparator.comparing( + (Conversation c) -> + c.getLastMessageAt() != null ? c.getLastMessageAt() : c.getCreatedAt(), + Comparator.nullsFirst(Comparator.naturalOrder())); +} diff --git a/apps/server/chat-service/src/main/java/com/platform/chatservice/service/ConversationQueryService.java b/apps/server/chat-service/src/main/java/com/platform/chatservice/service/ConversationQueryService.java index d45ab5d4..e18d1cce 100644 --- a/apps/server/chat-service/src/main/java/com/platform/chatservice/service/ConversationQueryService.java +++ b/apps/server/chat-service/src/main/java/com/platform/chatservice/service/ConversationQueryService.java @@ -53,6 +53,12 @@ public PageResponse listConversations(String userId, Pagea */ public PageResponse listConversations( String userId, Pageable pageable, boolean archived) { + return listConversations(userId, pageable, archived, false); + } + + /** As above; {@code excludeAi} also drops direct chats with the AI bot (AI threads). */ + public PageResponse listConversations( + String userId, Pageable pageable, boolean archived, boolean excludeAi) { Criteria criteria = Criteria.where("participants") .is(userId) @@ -65,6 +71,18 @@ public PageResponse listConversations( } else { criteria = criteria.and("archivedBy").ne(userId); } + if (excludeAi) { + criteria = + new Criteria() + .andOperator( + criteria, + new Criteria() + .norOperator( + Criteria.where("participants") + .is(AiConstants.AI_BOT_USER_ID) + .and("type") + .ne(Conversation.TYPE_GROUP))); + } Query query = new Query(criteria) .with( diff --git a/apps/server/chat-service/src/main/java/com/platform/chatservice/service/MessageService.java b/apps/server/chat-service/src/main/java/com/platform/chatservice/service/MessageService.java index 3805e32b..be780153 100644 --- a/apps/server/chat-service/src/main/java/com/platform/chatservice/service/MessageService.java +++ b/apps/server/chat-service/src/main/java/com/platform/chatservice/service/MessageService.java @@ -20,6 +20,7 @@ import java.util.ArrayList; import java.util.List; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.data.mongodb.core.FindAndModifyOptions; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; @@ -32,6 +33,7 @@ * creation. Reactions, delete-for-me and pins live in {@link MessageInteractionService}; read/query * concerns in {@link MessageQueryService}; AI-message persistence in {@link AiMessageService}. */ +@Slf4j @Service @RequiredArgsConstructor public class MessageService { @@ -46,6 +48,7 @@ public class MessageService { private final AiMessageService aiMessageService; private final ConversationCacheService conversationCacheService; private final UploadRefs uploadRefs; + private final AiThreadService aiThreadService; /** * Outcome of a recall / edit: the updated message, and whether it was the conversation's newest @@ -103,6 +106,15 @@ public MessageResponse sendMessage(String senderId, SendMessageRequest request) update.set("status", Conversation.STATUS_ACCEPTED); } bumpConversation(request.conversationId(), update); + // First user text in an untitled AI thread becomes its title (shared by STOMP + REST sends). + if (MessageTypePolicy.triggersAssistant(type) && !AiConstants.AI_BOT_USER_ID.equals(senderId)) { + try { + aiThreadService.maybeAutoTitle(conversation, request.content()); + } catch (RuntimeException e) { + // Best-effort: the message is already persisted, never fail the send over a title. + log.warn("Auto-title failed for conversation {}", request.conversationId(), e); + } + } return toResponse(message); } diff --git a/apps/server/chat-service/src/test/java/com/platform/chatservice/controller/AiThreadControllerTest.java b/apps/server/chat-service/src/test/java/com/platform/chatservice/controller/AiThreadControllerTest.java new file mode 100644 index 00000000..abfddeb8 --- /dev/null +++ b/apps/server/chat-service/src/test/java/com/platform/chatservice/controller/AiThreadControllerTest.java @@ -0,0 +1,140 @@ +package com.platform.chatservice.controller; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.platform.chatservice.dto.ConversationResponse; +import com.platform.chatservice.dto.PageResponse; +import com.platform.chatservice.dto.RenameAiThreadRequest; +import com.platform.chatservice.model.Conversation; +import com.platform.chatservice.repository.ConversationRepository; +import com.platform.chatservice.repository.MessageRepository; +import com.platform.chatservice.security.UserPrincipal; +import com.platform.chatservice.service.AiConstants; +import com.platform.chatservice.service.AiThreadService; +import com.platform.chatservice.service.ConversationCacheService; +import com.platform.chatservice.service.ConversationEventPublisher; +import com.platform.chatservice.service.ConversationMapper; +import com.platform.chatservice.service.ConversationQueryService; +import java.time.Instant; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.security.core.context.SecurityContextHolder; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class AiThreadControllerTest { + + private static final String ME = "user-001"; + + @Mock private AiThreadService aiThreadService; + @Mock private ConversationEventPublisher events; + @Mock private ConversationRepository conversationRepository; + @Mock private ConversationCacheService cache; + @Mock private MongoTemplate mongoTemplate; + @Mock private MessageRepository messageRepository; + + @InjectMocks private AiThreadController controller; + + @BeforeEach + void setUp() { + SecurityContextHolder.getContext().setAuthentication(new UserPrincipal(ME)); + } + + @AfterEach + void tearDown() { + SecurityContextHolder.clearContext(); + } + + private static ConversationResponse view(String id) { + return new ConversationResponse( + id, + "direct", + null, + null, + List.of(ME, AiConstants.AI_BOT_USER_ID), + null, + ME, + null, + null, + null, + 0L, + Instant.now(), + "accepted", + false, + List.of(), + null, + null, + null, + null, + null, + List.of(), + null, + null); + } + + @Test + void create_publishesToCreatorsOtherDevices() { + ConversationResponse v = view("c1"); + when(aiThreadService.create(ME)).thenReturn(v); + + assertThat(controller.create()).isSameAs(v); + verify(events).publishToUser(ME, v); + } + + @Test + void rename_broadcastsSharedUpdate() { + ConversationResponse v = view("c1"); + when(aiThreadService.rename(ME, "c1", "Plan")).thenReturn(v); + + assertThat(controller.rename("c1", new RenameAiThreadRequest("Plan"))).isSameAs(v); + verify(events).publishShared(v); + } + + /** GET /api/conversations?excludeAi=... against the real query service (mocked Mongo). */ + private String listQueryJson(boolean excludeAi) { + ConversationQueryService queries = + new ConversationQueryService( + conversationRepository, + cache, + mongoTemplate, + new ConversationMapper(messageRepository)); + ArgumentCaptor q = ArgumentCaptor.forClass(Query.class); + when(mongoTemplate.find(q.capture(), eq(Conversation.class))).thenReturn(List.of()); + when(mongoTemplate.count(any(Query.class), eq(Conversation.class))).thenReturn(0L); + PageResponse r = + queries.listConversations(ME, PageRequest.of(0, 20), false, excludeAi); + assertThat(r.content()).isEmpty(); + return q.getValue().getQueryObject().toJson(); + } + + @Test + void listConversations_excludeAi_addsNorOnDirectBotChats() { + assertThat(listQueryJson(true)) + .contains("$nor") + .contains(AiConstants.AI_BOT_USER_ID) + .contains("\"hiddenFor\""); + } + + @Test + void listConversations_withoutExcludeAi_hasNoBotFilter() { + assertThat(listQueryJson(false)) + .doesNotContain("$nor") + .doesNotContain(AiConstants.AI_BOT_USER_ID); + } +} diff --git a/apps/server/chat-service/src/test/java/com/platform/chatservice/service/AiThreadServiceTest.java b/apps/server/chat-service/src/test/java/com/platform/chatservice/service/AiThreadServiceTest.java new file mode 100644 index 00000000..068c9b05 --- /dev/null +++ b/apps/server/chat-service/src/test/java/com/platform/chatservice/service/AiThreadServiceTest.java @@ -0,0 +1,293 @@ +package com.platform.chatservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.platform.chatservice.dto.ConversationResponse; +import com.platform.chatservice.exception.BadRequestException; +import com.platform.chatservice.exception.ConversationNotFoundException; +import com.platform.chatservice.exception.ErrorCodes; +import com.platform.chatservice.model.AiPersona; +import com.platform.chatservice.model.Conversation; +import com.platform.chatservice.repository.AiPersonaRepository; +import com.platform.chatservice.repository.ConversationRepository; +import com.platform.chatservice.repository.MessageRepository; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import org.springframework.data.mongodb.core.FindAndModifyOptions; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.query.UpdateDefinition; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class AiThreadServiceTest { + + private static final String ME = "user-001"; + private static final String BOT = AiConstants.AI_BOT_USER_ID; + + @Mock private ConversationRepository conversationRepository; + @Mock private ConversationCacheService cache; + @Mock private AiPersonaRepository personaRepository; + @Mock private MongoTemplate mongoTemplate; + @Mock private MessageRepository messageRepository; + @Mock private ConversationEventPublisher events; + + private AiThreadService service; + private final AtomicInteger seq = new AtomicInteger(); + + @BeforeEach + void setUp() { + ConversationWriteSupport support = + new ConversationWriteSupport( + cache, mongoTemplate, messageRepository, new ConversationMapper(messageRepository)); + service = + new AiThreadService(conversationRepository, cache, personaRepository, support, events); + when(cache.save(any(Conversation.class))) + .thenAnswer( + inv -> { + Conversation c = inv.getArgument(0); + c.setId("new-" + seq.incrementAndGet()); + return c; + }); + when(conversationRepository.findTwoMemberNonGroupConversations(any())).thenReturn(List.of()); + } + + private static Conversation thread(String id, Instant lastAt, Instant createdAt) { + return Conversation.builder() + .id(id) + .type("direct") + .participants(List.of(ME, BOT)) + .lastMessageAt(lastAt) + .createdAt(createdAt) + .hiddenFor(new ArrayList<>()) + .build(); + } + + @Test + void create_makesNewConversationEvenWhenOneExists() { + when(conversationRepository.findTwoMemberNonGroupConversations(List.of(ME, BOT))) + .thenReturn(List.of(thread("old", null, Instant.now()))); + + ConversationResponse a = service.create(ME); + ConversationResponse b = service.create(ME); + + assertThat(a.id()).isNotEqualTo(b.id()); + for (ConversationResponse r : List.of(a, b)) { + assertThat(r.participants()).containsExactly(ME, BOT); + assertThat(r.status()).isEqualTo("accepted"); + assertThat(r.type()).isEqualTo("direct"); + assertThat(r.name()).isNull(); + } + } + + @Test + void create_copiesPersonaFromMostRecentThread() { + Instant now = Instant.now(); + when(conversationRepository.findTwoMemberNonGroupConversations(List.of(ME, BOT))) + .thenReturn( + List.of( + thread("stale", now.minusSeconds(500), now.minusSeconds(900)), + thread("fresh", now.minusSeconds(5), now.minusSeconds(800)), + thread("empty", null, now.minusSeconds(700)))); + AiPersona persona = + AiPersona.builder() + .id("p1") + .conversationId("fresh") + .name("Jarvis") + .tone("formal") + .avatarUrl("/a.png") + .systemPromptPrefix("Be brief") + .build(); + when(personaRepository.findByConversationId("fresh")).thenReturn(Optional.of(persona)); + + ConversationResponse created = service.create(ME); + + ArgumentCaptor saved = ArgumentCaptor.forClass(AiPersona.class); + verify(personaRepository).save(saved.capture()); + AiPersona copy = saved.getValue(); + assertThat(copy.getId()).isNull(); + assertThat(copy.getConversationId()).isEqualTo(created.id()); + assertThat(copy.getName()).isEqualTo("Jarvis"); + assertThat(copy.getTone()).isEqualTo("formal"); + assertThat(copy.getSystemPromptPrefix()).isEqualTo("Be brief"); + assertThat(copy.getAvatarUrl()).isEqualTo("/a.png"); + } + + @Test + void create_withoutAnyThreadOrPersona_savesNoPersona() { + service.create(ME); + when(conversationRepository.findTwoMemberNonGroupConversations(List.of(ME, BOT))) + .thenReturn(List.of(thread("t", null, Instant.now()))); + service.create(ME); // latest thread has no persona + verify(personaRepository, never()).save(any(AiPersona.class)); + } + + @Test + void list_returnsOnlyCallersAiThreads_newestFirst_skipsDeleted() { + Instant now = Instant.now(); + Conversation older = thread("older", now.minusSeconds(100), now.minusSeconds(900)); + Conversation newest = thread("newest", now.minusSeconds(1), now.minusSeconds(800)); + Conversation noMessages = thread("fresh", null, now.minusSeconds(50)); + Conversation deleted = thread("deleted", now, now); + deleted.setHiddenFor(new ArrayList<>(List.of(ME))); + Conversation blocked = thread("blocked", now, now); + blocked.setBlockedBy(new ArrayList<>(List.of(ME))); + // The repository query is already scoped to [me, bot] direct chats, so another user's thread + // and human DMs never come back; assert the exact query used. + when(conversationRepository.findTwoMemberNonGroupConversations(List.of(ME, BOT))) + .thenReturn(List.of(older, deleted, noMessages, newest, blocked)); + + List result = service.list(ME); + + assertThat(result) + .extracting(ConversationResponse::id) + .containsExactly("newest", "fresh", "older"); + verify(conversationRepository).findTwoMemberNonGroupConversations(List.of(ME, BOT)); + } + + @Test + void list_includesLegacyAiConversationWithNoTypeField() { + Instant now = Instant.now(); + Conversation legacy = thread("legacy", now, now); + legacy.setType(null); + when(conversationRepository.findTwoMemberNonGroupConversations(List.of(ME, BOT))) + .thenReturn(List.of(legacy)); + + assertThat(service.list(ME)).extracting(ConversationResponse::id).containsExactly("legacy"); + } + + private void updateReturns(Conversation c) { + when(mongoTemplate.findAndModify( + any(), + any(UpdateDefinition.class), + any(FindAndModifyOptions.class), + eq(Conversation.class))) + .thenReturn(c); + } + + @Test + void rename_rejectsBlankAndTooLong_andForeignThread() { + when(cache.findByIdOptional("mine")) + .thenReturn(Optional.of(thread("mine", null, Instant.now()))); + Conversation foreign = + Conversation.builder() + .id("foreign") + .type("direct") + .participants(List.of("other", BOT)) + .build(); + when(cache.findByIdOptional("foreign")).thenReturn(Optional.of(foreign)); + Conversation humanDm = + Conversation.builder() + .id("dm") + .type("direct") + .participants(List.of(ME, "user-002")) + .build(); + when(cache.findByIdOptional("dm")).thenReturn(Optional.of(humanDm)); + + assertThatThrownBy(() -> service.rename(ME, "mine", " ")) + .isInstanceOfSatisfying( + BadRequestException.class, + e -> assertThat(e.getCode()).isEqualTo(ErrorCodes.AI_THREAD_NAME_INVALID)); + assertThatThrownBy(() -> service.rename(ME, "mine", null)) + .isInstanceOf(BadRequestException.class); + assertThatThrownBy(() -> service.rename(ME, "mine", "x".repeat(81))) + .isInstanceOfSatisfying( + BadRequestException.class, + e -> assertThat(e.getCode()).isEqualTo(ErrorCodes.AI_THREAD_NAME_INVALID)); + assertThatThrownBy(() -> service.rename(ME, "foreign", "ok")) + .isInstanceOf(ConversationNotFoundException.class); + assertThatThrownBy(() -> service.rename(ME, "dm", "ok")) + .isInstanceOf(ConversationNotFoundException.class); + } + + @Test + void rename_trimsAndPersists() { + Conversation t = thread("mine", null, Instant.now()); + when(cache.findByIdOptional("mine")).thenReturn(Optional.of(t)); + Conversation renamed = thread("mine", null, Instant.now()); + renamed.setName("Plan"); + updateReturns(renamed); + + ConversationResponse r = service.rename(ME, "mine", " Plan "); + + assertThat(r.name()).isEqualTo("Plan"); + ArgumentCaptor u = ArgumentCaptor.forClass(UpdateDefinition.class); + verify(mongoTemplate) + .findAndModify(any(), u.capture(), any(FindAndModifyOptions.class), eq(Conversation.class)); + assertThat(u.getValue().getUpdateObject().toJson()).contains("\"name\": \"Plan\""); + } + + private String autoTitleWrites(Conversation c, String text) { + Conversation after = thread(c.getId(), null, Instant.now()); + updateReturns(after); + service.maybeAutoTitle(c, text); + ArgumentCaptor u = ArgumentCaptor.forClass(UpdateDefinition.class); + verify(mongoTemplate) + .findAndModify(any(), u.capture(), any(FindAndModifyOptions.class), eq(Conversation.class)); + return u.getValue().getUpdateObject().toJson(); + } + + @Test + void autoTitle_setsFirst60Chars_once() { + assertThat(autoTitleWrites(thread("t1", null, Instant.now()), " Xin chào\n bạn ")) + .contains("\"name\": \"Xin chào bạn\""); + } + + @Test + void autoTitle_cutsLongTextTo59CharsPlusEllipsis() { + String json = autoTitleWrites(thread("t2", null, Instant.now()), "a".repeat(70)); + assertThat(json).contains("\"name\": \"" + "a".repeat(59) + "…\""); + } + + @Test + void autoTitle_neverOverwrites_andIgnoresNonAiConversations() { + Conversation named = thread("t3", null, Instant.now()); + named.setName("My title"); + service.maybeAutoTitle(named, "second message"); + + Conversation group = + Conversation.builder().id("g").type("group").participants(List.of(ME, BOT)).build(); + service.maybeAutoTitle(group, "hello"); + + Conversation threeWay = + Conversation.builder().id("x").type("direct").participants(List.of(ME, "u2", BOT)).build(); + service.maybeAutoTitle(threeWay, "hello"); + + service.maybeAutoTitle(thread("t4", null, Instant.now()), " "); + + verify(mongoTemplate, never()) + .findAndModify( + any(), + any(UpdateDefinition.class), + any(FindAndModifyOptions.class), + eq(Conversation.class)); + } + + @Test + void autoTitle_publishesSharedEventOnlyWhenTitled() { + Conversation c = thread("t5", null, Instant.now()); + updateReturns(null); // a concurrent rename already won the guarded write + service.maybeAutoTitle(c, "hi"); + verify(events, never()).publishShared(any(ConversationResponse.class)); + + updateReturns(thread("t5", null, Instant.now())); + service.maybeAutoTitle(c, "hi"); + verify(events).publishShared(any(ConversationResponse.class)); + } +} diff --git a/apps/server/chat-service/src/test/java/com/platform/chatservice/service/MessagePinTest.java b/apps/server/chat-service/src/test/java/com/platform/chatservice/service/MessagePinTest.java index 945856d2..0c7b721a 100644 --- a/apps/server/chat-service/src/test/java/com/platform/chatservice/service/MessagePinTest.java +++ b/apps/server/chat-service/src/test/java/com/platform/chatservice/service/MessagePinTest.java @@ -70,7 +70,8 @@ void setUp() { messageMapper, aiMessageService, conversationCacheService, - uploadRefs); + uploadRefs, + org.mockito.Mockito.mock(AiThreadService.class)); interactionService = new MessageInteractionService( messageRepository, diff --git a/apps/server/chat-service/src/test/java/com/platform/chatservice/service/MessageSendTest.java b/apps/server/chat-service/src/test/java/com/platform/chatservice/service/MessageSendTest.java index a2529a16..fc8a3d75 100644 --- a/apps/server/chat-service/src/test/java/com/platform/chatservice/service/MessageSendTest.java +++ b/apps/server/chat-service/src/test/java/com/platform/chatservice/service/MessageSendTest.java @@ -44,6 +44,8 @@ class MessageSendTest { @Mock private ConversationCacheService conversationCacheService; @Mock private UploadRefs uploadRefs; + @Mock private AiThreadService aiThreadService; + private MessageService messageService; private static final String SENDER_ID = "user-001"; @@ -75,7 +77,8 @@ void setUp() { messageMapper, aiMessageService, conversationCacheService, - uploadRefs); + uploadRefs, + aiThreadService); conversation = Conversation.builder().id(CONV_ID).participants(List.of(SENDER_ID, OTHER_ID)).build(); @@ -153,6 +156,27 @@ void sendMessage_ByInitiatorOnPending_ShouldStayPending() { eq(Conversation.class)); } + @Test + void sendMessage_SucceedsWhenAutoTitleThrows() { + Conversation aiThread = + Conversation.builder() + .id(CONV_ID) + .type(Conversation.TYPE_DIRECT) + .participants(List.of(SENDER_ID, AiConstants.AI_BOT_USER_ID)) + .build(); + when(conversationRepository.findById(CONV_ID)).thenReturn(Optional.of(aiThread)); + when(messageRepository.save(any(Message.class))).thenReturn(savedMessage); + org.mockito.Mockito.doThrow(new IllegalStateException("boom")) + .when(aiThreadService) + .maybeAutoTitle(any(), any()); + + MessageResponse response = + messageService.sendMessage(SENDER_ID, new SendMessageRequest(CONV_ID, "Hello", "text")); + + assertThat(response.id()).isEqualTo(MSG_ID); + verify(aiThreadService).maybeAutoTitle(any(), any()); + } + @Test void sendMessage_ShouldDefaultTypeToText_WhenTypeIsNull() { when(conversationRepository.findById(CONV_ID)).thenReturn(Optional.of(conversation)); diff --git a/apps/server/chat-service/src/test/java/com/platform/chatservice/service/UploadRefsActorTest.java b/apps/server/chat-service/src/test/java/com/platform/chatservice/service/UploadRefsActorTest.java index 940eb120..4276017b 100644 --- a/apps/server/chat-service/src/test/java/com/platform/chatservice/service/UploadRefsActorTest.java +++ b/apps/server/chat-service/src/test/java/com/platform/chatservice/service/UploadRefsActorTest.java @@ -101,7 +101,8 @@ void setUp() { mapper, aiMessageService, cache, - refs); + refs, + org.mockito.Mockito.mock(AiThreadService.class)); ConversationWriteSupport support = new ConversationWriteSupport( cache, mongoTemplate, messageRepository, new ConversationMapper(messageRepository)); diff --git a/apps/web/app/(main)/ai-hub/page.tsx b/apps/web/app/(main)/ai-hub/page.tsx index c4f32954..0319d046 100644 --- a/apps/web/app/(main)/ai-hub/page.tsx +++ b/apps/web/app/(main)/ai-hub/page.tsx @@ -14,6 +14,7 @@ import { } from 'lucide-react' import { Button } from '@/components/ui/button' import { AiHubCard } from '@/components/ai/AiHubCard' +import { AiThreadList } from '@/components/ai/AiThreadList' import { useOpenAiChat } from '@/lib/hooks/use-open-ai-chat' export default function AiHubPage() { @@ -62,6 +63,12 @@ export default function AiHubPage() { + {/* Mobile: the aside is hidden, so the thread list (new chat, switch, + back to messages) lives here. Desktop shows it in the sidebar. */} +
+ +
+ {/* Destination cards */}
- {/* Horizontal presence row doesn't fit the compact rail — hide it. */} -
- -
- - + {showAiThreads ? ( + + ) : ( + <> + {/* Horizontal presence row doesn't fit the compact rail — hide it. */} +
+ +
+ + + + )}
{/* Bottom cluster — AI Hub launcher sits directly above the account anchor (desktop). */} @@ -219,7 +235,7 @@ function MainShell({ children }: { children: React.ReactNode }) { as="main" className={cn( 'flex-1 overflow-hidden flex-col', - showSidebar && !isConversationOpen ? 'hidden md:flex' : 'flex', + showSidebar && !isConversationOpen && !isAiHub ? 'hidden md:flex' : 'flex', )} > {children} diff --git a/apps/web/components/ai/AiThreadItem.tsx b/apps/web/components/ai/AiThreadItem.tsx new file mode 100644 index 00000000..dcb801c2 --- /dev/null +++ b/apps/web/components/ai/AiThreadItem.tsx @@ -0,0 +1,90 @@ +'use client' + +import { useState } from 'react' +import Link from 'next/link' +import { useTranslations } from 'next-intl' +import { Check, Pencil, Trash2, X } from 'lucide-react' +import { cn } from '@/lib/utils' +import type { Conversation } from '@/lib/api/types' + +interface Props { + thread: Conversation + active: boolean + /** Resolves when the rename succeeded (editor closes), rejects/returns false to stay open. */ + onRename: (id: string, name: string) => Promise + onDelete: (thread: Conversation) => void +} + +export function AiThreadItem({ thread, active, onRename, onDelete }: Props) { + const t = useTranslations('aiThreads') + const [editing, setEditing] = useState(false) + const [draft, setDraft] = useState('') + const title = thread.name?.trim() || t('untitled') + + const startEdit = () => { + setDraft(thread.name ?? '') + setEditing(true) + } + const save = async () => { + const name = draft.trim() + if (name === (thread.name ?? '')) return setEditing(false) + if (await onRename(thread.id, name)) setEditing(false) + } + + if (editing) { + return ( +
+ setDraft(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter') void save() + else if (e.key === 'Escape') setEditing(false) + }} + className="min-w-0 flex-1 rounded-md border border-border bg-background px-2 py-1 text-sm outline-none focus-visible:ring-2 focus-visible:ring-primary/50" + /> + + +
+ ) + } + + return ( +
+ + {title} + + {/* Touch has no hover: always visible below md, hover/focus-revealed on desktop. */} +
+ + +
+
+ ) +} diff --git a/apps/web/components/ai/AiThreadList.tsx b/apps/web/components/ai/AiThreadList.tsx new file mode 100644 index 00000000..40e264e7 --- /dev/null +++ b/apps/web/components/ai/AiThreadList.tsx @@ -0,0 +1,124 @@ +'use client' + +import { useState } from 'react' +import Link from 'next/link' +import { useRouter, usePathname } from 'next/navigation' +import { useQueryClient } from '@tanstack/react-query' +import { useTranslations } from 'next-intl' +import { toast } from 'sonner' +import { ArrowLeft, Loader2, Plus } from 'lucide-react' +import { ConfirmDialog } from '@/components/common/ConfirmDialog' +import { AiThreadItem } from '@/components/ai/AiThreadItem' +import { chatService } from '@/lib/api/chat' +import { parseChatError } from '@/lib/api/chat-errors' +import { useAiThreads, useCreateAiThread, useRenameAiThread } from '@/lib/hooks/use-ai-threads' +import { dropConversation } from '@/lib/realtime/conversation-cache' +import type { Conversation } from '@/lib/api/types' + +/** + * ChatGPT-style sidebar: every AI "new chat" is its own conversation. Replaces the + * normal conversation list while an AI thread (or the AI hub) is open. + */ +export function AiThreadList() { + const t = useTranslations('aiThreads') + const router = useRouter() + const pathname = usePathname() + const queryClient = useQueryClient() + const { data: threads, isLoading, isError } = useAiThreads() + const create = useCreateAiThread() + const rename = useRenameAiThread() + const [pendingDelete, setPendingDelete] = useState(null) + + const openId = /^\/conversations\/([^/]+)/.exec(pathname)?.[1] + + const handleCreate = async () => { + try { + const conv = await create.mutateAsync() + router.push(`/conversations/${conv.id}`) + } catch { + toast.error(t('createFailed')) + } + } + + const handleRename = async (id: string, name: string): Promise => { + try { + await rename.mutateAsync({ id, name }) + return true + } catch (err) { + toast.error(parseChatError(err).code === 'AI_THREAD_NAME_INVALID' ? t('nameInvalid') : t('renameFailed')) + return false + } + } + + const handleConfirmDelete = async () => { + const target = pendingDelete + if (!target) return + setPendingDelete(null) + const list = threads ?? [] + const idx = list.findIndex((c) => c.id === target.id) + const next = list[idx + 1] ?? list[idx - 1] + try { + await chatService.deleteConversation(target.id) + // Navigate away BEFORE dropping caches: the layout and conversation page still observe + // the open id, so dropping first flashes the normal list / refetches a deleted id (404). + // replace (not push) so Back never returns to the deleted thread. + if (openId === target.id) router.replace(next ? `/conversations/${next.id}` : '/ai-hub') + dropConversation(queryClient, target.id) + } catch { + toast.error(t('deleteFailed')) + } + } + + return ( +
+
+ + + {t('backToMessages')} + + +
+ + + + !o && setPendingDelete(null)} + title={t('deleteTitle')} + description={t('deleteDesc')} + confirmLabel={t('delete')} + onConfirm={() => void handleConfirmDelete()} + /> +
+ ) +} diff --git a/apps/web/components/ai/__tests__/AiThreadList.test.tsx b/apps/web/components/ai/__tests__/AiThreadList.test.tsx new file mode 100644 index 00000000..d92de12f --- /dev/null +++ b/apps/web/components/ai/__tests__/AiThreadList.test.tsx @@ -0,0 +1,165 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { render, screen, fireEvent, waitFor } from '@testing-library/react' +import React from 'react' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import axios from 'axios' +import { AiThreadList } from '@/components/ai/AiThreadList' +import type { Conversation } from '@/lib/api/types' +import * as cache from '@/lib/realtime/conversation-cache' + +const push = vi.fn() +const replace = vi.fn() +const order: string[] = [] +let pathname = '/conversations/t1' +vi.mock('next/navigation', () => ({ + useRouter: () => ({ push, replace }), + usePathname: () => pathname, +})) +vi.mock('next/link', () => ({ + default: ({ href, children, ...rest }: { href: string; children: React.ReactNode }) => ( + {children} + ), +})) +vi.mock('next-intl', () => ({ + useTranslations: () => (key: string) => key, +})) +vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } })) +vi.mock('@/components/common/ConfirmDialog', () => ({ + ConfirmDialog: ({ open, onConfirm, confirmLabel }: { open: boolean; onConfirm: () => void; confirmLabel: string }) => + open ? : null, +})) + +const threadsState: { data: Conversation[] | undefined } = { data: [] } +const createMutateAsync = vi.fn() +const renameMutateAsync = vi.fn() +vi.mock('@/lib/hooks/use-ai-threads', () => ({ + useAiThreads: () => ({ data: threadsState.data, isLoading: false, isError: false }), + useCreateAiThread: () => ({ mutateAsync: createMutateAsync, isPending: false }), + useRenameAiThread: () => ({ mutateAsync: renameMutateAsync, isPending: false }), +})) +const deleteConversation = vi.fn() +vi.mock('@/lib/api/chat', () => ({ + chatService: { deleteConversation: (id: string) => deleteConversation(id) }, +})) + +function thread(id: string, name: string | null): Conversation { + return { + id, participants: ['u1', 'ai-bot-000000000000000000000001'], type: 'direct', name, + avatarUrl: null, wallpaper: null, admins: [], createdBy: 'u1', isPublic: false, + status: 'accepted', isMuted: false, isArchived: false, pinnedMessages: [], + autoDeleteSeconds: null, lastMessage: null, lastMessageAt: null, unreadCount: 0, + } +} + +function renderList() { + const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + return render( + + + , + ) +} + +describe('AiThreadList', () => { + beforeEach(() => { + vi.clearAllMocks() + order.length = 0 + pathname = '/conversations/t1' + threadsState.data = [thread('t1', 'Báo cáo Q3'), thread('t2', null)] + }) + + it('renders titles in order, falling back to the untitled label, and highlights the active one', () => { + renderList() + const rows = screen.getAllByTestId('ai-thread-row') + expect(rows).toHaveLength(2) + expect(rows[0].textContent).toContain('Báo cáo Q3') + expect(rows[1].textContent).toContain('untitled') + expect(rows[0].getAttribute('aria-current')).toBe('page') + expect(rows[1].getAttribute('aria-current')).toBeNull() + }) + + it('links back to the normal conversation list', () => { + renderList() + expect(screen.getByText('backToMessages').closest('a')?.getAttribute('href')).toBe('/conversations') + }) + + it('creates a new thread and navigates to it', async () => { + createMutateAsync.mockResolvedValue(thread('t9', null)) + renderList() + fireEvent.click(screen.getByText('newThread')) + await waitFor(() => expect(push).toHaveBeenCalledWith('/conversations/t9')) + }) + + it('renames inline: Enter saves, Escape cancels', async () => { + renameMutateAsync.mockResolvedValue(thread('t1', 'Mới')) + renderList() + fireEvent.click(screen.getAllByLabelText('rename')[0]) + const input = screen.getByRole('textbox') as HTMLInputElement + fireEvent.change(input, { target: { value: ' Mới ' } }) + fireEvent.keyDown(input, { key: 'Enter' }) + await waitFor(() => expect(renameMutateAsync).toHaveBeenCalledWith({ id: 't1', name: 'Mới' })) + await waitFor(() => expect(screen.queryByRole('textbox')).toBeNull()) + + fireEvent.click(screen.getAllByLabelText('rename')[0]) + const input2 = screen.getByRole('textbox') + fireEvent.change(input2, { target: { value: 'Khác' } }) + fireEvent.keyDown(input2, { key: 'Escape' }) + expect(screen.queryByRole('textbox')).toBeNull() + expect(renameMutateAsync).toHaveBeenCalledTimes(1) + }) + + it('shows a localized message (never raw error text) on AI_THREAD_NAME_INVALID', async () => { + const err = new axios.AxiosError('raw english', '400', undefined, undefined, { + status: 400, data: { code: 'AI_THREAD_NAME_INVALID', message: 'raw english' }, + } as never) + renameMutateAsync.mockRejectedValue(err) + const { toast } = await import('sonner') + renderList() + fireEvent.click(screen.getAllByLabelText('rename')[0]) + const input = screen.getByRole('textbox') + fireEvent.change(input, { target: { value: 'x' } }) + fireEvent.keyDown(input, { key: 'Enter' }) + await waitFor(() => expect(toast.error).toHaveBeenCalledWith('nameInvalid')) + }) + + it('delete asks for confirmation, then navigates to the next thread when the open one is removed', async () => { + deleteConversation.mockResolvedValue({}) + renderList() + fireEvent.click(screen.getAllByLabelText('delete')[0]) + expect(deleteConversation).not.toHaveBeenCalled() + fireEvent.click(screen.getByText(/^confirm:/)) + await waitFor(() => expect(deleteConversation).toHaveBeenCalledWith('t1')) + await waitFor(() => expect(replace).toHaveBeenCalledWith('/conversations/t2')) + expect(push).not.toHaveBeenCalled() + }) + + it('goes to /ai-hub when the last open thread is deleted', async () => { + threadsState.data = [thread('t1', 'A')] + deleteConversation.mockResolvedValue({}) + renderList() + fireEvent.click(screen.getByLabelText('delete')) + fireEvent.click(screen.getByText(/^confirm:/)) + await waitFor(() => expect(replace).toHaveBeenCalledWith('/ai-hub')) + }) + + it('navigates away before dropping the deleted thread from the cache', async () => { + deleteConversation.mockResolvedValue({}) + replace.mockImplementation(() => order.push('replace')) + const spy = vi.spyOn(cache, 'dropConversation').mockImplementation(() => { order.push('drop') }) + renderList() + fireEvent.click(screen.getAllByLabelText('delete')[0]) + fireEvent.click(screen.getByText(/^confirm:/)) + await waitFor(() => expect(order).toEqual(['replace', 'drop'])) + spy.mockRestore() + }) + + it('does not navigate when a non-open thread is deleted', async () => { + deleteConversation.mockResolvedValue({}) + renderList() + fireEvent.click(screen.getAllByLabelText('delete')[1]) + fireEvent.click(screen.getByText(/^confirm:/)) + await waitFor(() => expect(deleteConversation).toHaveBeenCalledWith('t2')) + expect(push).not.toHaveBeenCalled() + expect(replace).not.toHaveBeenCalled() + }) +}) diff --git a/apps/web/components/chat/AiSessionPanel.tsx b/apps/web/components/chat/AiSessionPanel.tsx deleted file mode 100644 index be638b87..00000000 --- a/apps/web/components/chat/AiSessionPanel.tsx +++ /dev/null @@ -1,98 +0,0 @@ -'use client' - -import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' -import { Plus, RotateCcw } from 'lucide-react' -import { formatDistanceToNow } from 'date-fns' -import { useTranslations } from 'next-intl' -import { aiSessionApi, type AiSession } from '@/lib/api/ai-session' -import { Button } from '@/components/ui/button' -import { - AccordionContent, AccordionItem, AccordionTrigger, -} from '@/components/ui/accordion' - -/** - * Per-conversation AI session history. Lets the user see past sessions, resume - * an older one, or start a fresh session (equivalent to sending `/new`). - * Mirrors Flutter `ai_session_panel.dart`. AI conversations only. - */ -export function AiSessionPanel({ conversationId }: { conversationId: string }) { - const t = useTranslations('chat') - const qc = useQueryClient() - - const { data: sessions = [] } = useQuery({ - queryKey: ['ai-sessions', conversationId], - queryFn: () => aiSessionApi.listSessions(conversationId), - }) - - const invalidate = () => - qc.invalidateQueries({ queryKey: ['ai-sessions', conversationId] }) - - const newSession = useMutation({ - mutationFn: () => aiSessionApi.createNew(conversationId), - onSuccess: invalidate, - }) - - const resumeSession = useMutation({ - mutationFn: (sessionId: string) => aiSessionApi.resume(conversationId, sessionId), - onSuccess: invalidate, - }) - - const busy = newSession.isPending || resumeSession.isPending - - return ( - - - {t('aiSessionHistory')} - - - - -
- {sessions.map((s) => ( -
!s.isActive && !busy && resumeSession.mutate(s._id)} - onKeyDown={(e) => { - if (!s.isActive && !busy && (e.key === 'Enter' || e.key === ' ')) { - e.preventDefault() - resumeSession.mutate(s._id) - } - }} - > -
-

{s.name}

-

- {formatDistanceToNow(new Date(s.updatedAt), { addSuffix: true })} - {s.summary && ` · ${t('aiContextCompacted')}`} -

-
- {s.isActive ? ( - - {t('aiSessionActive')} - - ) : ( - - )} -
- ))} -
-
-
- ) -} diff --git a/apps/web/components/chat/ConversationHeader.tsx b/apps/web/components/chat/ConversationHeader.tsx index 07bc59de..c4680381 100644 --- a/apps/web/components/chat/ConversationHeader.tsx +++ b/apps/web/components/chat/ConversationHeader.tsx @@ -4,7 +4,7 @@ import { useState } from 'react' import { useRouter } from 'next/navigation' import { useTranslations } from 'next-intl' import { toast } from 'sonner' -import { ArrowLeft, Bot, Settings, Phone, Video, Users } from 'lucide-react' +import { ArrowLeft, Bot, Settings, Phone, Video, Users, SquarePen } from 'lucide-react' import { useQueryClient } from '@tanstack/react-query' import { useConversation } from '@/lib/hooks/use-conversation' import { useUserStatus } from '@/lib/hooks/use-user-status' @@ -12,10 +12,10 @@ import { useRelationship } from '@/lib/hooks/use-relationship' import { useAuthStore } from '@/lib/store/auth.store' import { useUser } from '@/lib/hooks/use-user' import { useAssistant } from '@/lib/hooks/use-assistant' -import { useAssistantName } from '@/lib/hooks/use-capabilities' import type { Conversation } from '@/lib/api/types' import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar' import { Button } from '@/components/ui/button' +import { useCreateAiThread } from '@/lib/hooks/use-ai-threads' import { PinnedMessagesBar } from './PinnedMessagesBar' import { ConversationSettingsDrawer } from './ConversationSettingsDrawer' import { GroupSettingsDrawer } from './GroupSettingsDrawer' @@ -78,6 +78,8 @@ export function ConversationHeader({ }: Props) { const t = useTranslations('chat') const tCall = useTranslations('call') + const tThreads = useTranslations('aiThreads') + const createThread = useCreateAiThread() const router = useRouter() const { data: conversation } = useConversation(conversationId) const queryClient = useQueryClient() @@ -105,17 +107,15 @@ export function ConversationHeader({ const blockedMe = relationship?.blockedMe ?? false const { data: otherUser } = useUser(otherUserId) const nickname = useNickname(conversationId, otherUserId) - const assistantName = useAssistantName() const { data: extBotAssistant } = useAssistant() - const displayName = - nickname ?? - conversation?.name ?? - (isAI - ? (assistantName ?? t('aiAssistant')) - : isExtBot + const displayName = isAI + ? conversation?.name?.trim() || tThreads('untitled') + : (nickname ?? + conversation?.name ?? + (isExtBot ? (extBotAssistant?.name ?? t('aiAssistant')) - : (otherUser?.displayName ?? t('conversationDefault'))) + : (otherUser?.displayName ?? t('conversationDefault')))) const avatarUrl = conversation?.avatarUrl ?? otherUser?.avatarUrl const isTyping = typingUserIds.length > 0 const pinnedMessages = conversation?.pinnedMessages ?? [] @@ -152,7 +152,7 @@ export function ConversationHeader({ variant="ghost" size="icon" className="md:hidden h-8 w-8 shrink-0 -ml-1" - onClick={() => router.push('/conversations')} + onClick={() => router.push(isAI ? '/ai-hub' : '/conversations')} title={t('backToList')} > @@ -221,6 +221,25 @@ export function ConversationHeader({ {/* Header action buttons */}
+ {/* New AI chat — starts a fresh thread (reachable on mobile, where the sidebar is hidden) */} + {isAI && ( + + )} {/* Group call — always visible for group conversations */} {isGroup && !isAI && (