Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions apps/client/lib/features/ai_hub/data/ai_thread_repository.dart
Original file line number Diff line number Diff line change
@@ -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<ConversationModel>> list() async {
final response = await _dio.get('/api/ai-threads');
final data = response.data as List<dynamic>? ?? [];
return data
.map((e) => ConversationModel.fromJson(e as Map<String, dynamic>))
.toList();
}

/// A new, untitled thread (`name` null until auto-title / rename).
Future<ConversationModel> create() async {
final response = await _dio.post('/api/ai-threads');
return ConversationModel.fromJson(response.data as Map<String, dynamic>);
}

/// 400 `AI_THREAD_NAME_INVALID` unless 1-80 chars after trim; 404 not mine.
Future<ConversationModel> 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<String, dynamic>);
}
}

final aiThreadRepositoryProvider = Provider<AiThreadRepository>((ref) {
const storage = FlutterSecureStorage();
return AiThreadRepository(
DioClient.createChatDio(
storage,
onForceLogout: () =>
ref.read(authNotifierProvider.notifier).forceLogout(),
),
);
});
191 changes: 191 additions & 0 deletions apps/client/lib/features/ai_hub/domain/ai_threads_provider.dart
Original file line number Diff line number Diff line change
@@ -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<bool Function(String id)>((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, List<ConversationModel>>(
AiThreadsNotifier.new);

class AiThreadsNotifier extends AsyncNotifier<List<ConversationModel>> {
@override
Future<List<ConversationModel>> build() async {
final stomp = ref.read(stompServiceProvider.notifier);
final subs = <StreamSubscription<Object?>>[
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<ConversationModel> 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<ConversationModel> 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<void> 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<void> 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<ConversationModel> 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<ConversationModel> Function(List<ConversationModel>) fn) {
final current = state.valueOrNull;
if (current == null) return;
state = AsyncData(fn(current));
}

Future<void> _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<String, dynamic> 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);
}
}
23 changes: 16 additions & 7 deletions apps/client/lib/features/ai_hub/ui/ai_hub_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> 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.
Expand Down Expand Up @@ -58,7 +59,7 @@ class _AiHubScreenState extends ConsumerState<AiHubScreen> {
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(
Expand All @@ -79,6 +80,14 @@ class _AiHubScreenState extends ConsumerState<AiHubScreen> {
_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(),
],
),
),
Expand Down
Original file line number Diff line number Diff line change
@@ -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<AiNewChatButton> createState() => _AiNewChatButtonState();
}

class _AiNewChatButtonState extends ConsumerState<AiNewChatButton> {
bool _creating = false;

Future<void> _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,
);
}
Loading
Loading