feat: implement mobile AI chat feature and fix duplicate response issue (#610)

Backend fixes:
- Fix duplicate AssistantResponseJob triggering causing duplicate AI responses
- UserMessage model already handles job triggering via after_create_commit callback
- Remove redundant job enqueue in chats_controller and messages_controller

Mobile app features:
- Implement complete AI chat interface and conversation management
- Add Chat, Message, and ToolCall data models
- Add ChatProvider for state management with polling mechanism
- Add ChatService to handle all chat-related API requests
- Add chat list screen (ChatListScreen)
- Add conversation detail screen (ChatConversationScreen)
- Refactor navigation structure with bottom navigation bar (MainNavigationScreen)
- Add settings screen (SettingsScreen)
- Optimize TransactionsProvider to support account filtering

Technical details:
- Implement message polling mechanism for real-time AI responses
- Support chat creation, deletion, retry and other operations
- Integrate Material Design 3 design language
- Improve user experience and error handling

Co-authored-by: dwvwdv <dwvwdv@protonmail.com>
This commit is contained in:
Lazy Bone
2026-01-11 19:45:33 +08:00
committed by GitHub
parent 38f4c2222c
commit f52b3fceb6
13 changed files with 1869 additions and 8 deletions

View File

@@ -0,0 +1,436 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/auth_provider.dart';
import '../providers/chat_provider.dart';
import '../models/message.dart';
class ChatConversationScreen extends StatefulWidget {
final String chatId;
const ChatConversationScreen({
super.key,
required this.chatId,
});
@override
State<ChatConversationScreen> createState() => _ChatConversationScreenState();
}
class _ChatConversationScreenState extends State<ChatConversationScreen> {
final TextEditingController _messageController = TextEditingController();
final ScrollController _scrollController = ScrollController();
@override
void initState() {
super.initState();
_loadChat();
}
@override
void dispose() {
_messageController.dispose();
_scrollController.dispose();
super.dispose();
}
Future<void> _loadChat() async {
final authProvider = Provider.of<AuthProvider>(context, listen: false);
final chatProvider = Provider.of<ChatProvider>(context, listen: false);
final accessToken = await authProvider.getValidAccessToken();
if (accessToken == null) {
await authProvider.logout();
return;
}
await chatProvider.fetchChat(
accessToken: accessToken,
chatId: widget.chatId,
);
// Scroll to bottom after loading
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scrollController.hasClients) {
_scrollController.jumpTo(_scrollController.position.maxScrollExtent);
}
});
}
Future<void> _sendMessage() async {
final content = _messageController.text.trim();
if (content.isEmpty) return;
final authProvider = Provider.of<AuthProvider>(context, listen: false);
final chatProvider = Provider.of<ChatProvider>(context, listen: false);
final accessToken = await authProvider.getValidAccessToken();
if (accessToken == null) {
await authProvider.logout();
return;
}
// Clear input field immediately
_messageController.clear();
await chatProvider.sendMessage(
accessToken: accessToken,
chatId: widget.chatId,
content: content,
);
// Scroll to bottom after sending
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scrollController.hasClients) {
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 300),
curve: Curves.easeOut,
);
}
});
}
Future<void> _editTitle() async {
final chatProvider = Provider.of<ChatProvider>(context, listen: false);
final currentTitle = chatProvider.currentChat?.title ?? '';
final newTitle = await showDialog<String>(
context: context,
builder: (context) {
final controller = TextEditingController(text: currentTitle);
return AlertDialog(
title: const Text('Edit Title'),
content: TextField(
controller: controller,
decoration: const InputDecoration(
labelText: 'Chat Title',
border: OutlineInputBorder(),
),
autofocus: true,
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.pop(context, controller.text.trim()),
child: const Text('Save'),
),
],
);
},
);
if (newTitle != null && newTitle.isNotEmpty && newTitle != currentTitle && mounted) {
final authProvider = Provider.of<AuthProvider>(context, listen: false);
final accessToken = await authProvider.getValidAccessToken();
if (accessToken != null) {
await chatProvider.updateChatTitle(
accessToken: accessToken,
chatId: widget.chatId,
title: newTitle,
);
}
}
}
String _formatTime(DateTime dateTime) {
final hour = dateTime.hour.toString().padLeft(2, '0');
final minute = dateTime.minute.toString().padLeft(2, '0');
return '$hour:$minute';
}
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Scaffold(
appBar: AppBar(
title: Consumer<ChatProvider>(
builder: (context, chatProvider, _) {
return GestureDetector(
onTap: _editTitle,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: Text(
chatProvider.currentChat?.title ?? 'Chat',
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: 4),
const Icon(Icons.edit, size: 18),
],
),
);
},
),
actions: [
IconButton(
icon: const Icon(Icons.refresh),
onPressed: _loadChat,
tooltip: 'Refresh',
),
],
),
body: Consumer<ChatProvider>(
builder: (context, chatProvider, _) {
if (chatProvider.isLoading && chatProvider.currentChat == null) {
return const Center(
child: CircularProgressIndicator(),
);
}
if (chatProvider.errorMessage != null && chatProvider.currentChat == null) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.error_outline,
size: 64,
color: colorScheme.error,
),
const SizedBox(height: 16),
Text(
'Failed to load chat',
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 8),
Text(
chatProvider.errorMessage!,
style: TextStyle(color: colorScheme.onSurfaceVariant),
textAlign: TextAlign.center,
),
const SizedBox(height: 24),
ElevatedButton.icon(
onPressed: _loadChat,
icon: const Icon(Icons.refresh),
label: const Text('Try Again'),
),
],
),
),
);
}
final messages = chatProvider.currentChat?.messages ?? [];
return Column(
children: [
// Messages list
Expanded(
child: messages.isEmpty
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.chat_bubble_outline,
size: 64,
color: colorScheme.onSurfaceVariant,
),
const SizedBox(height: 16),
Text(
'Start a conversation',
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 8),
Text(
'Send a message to begin chatting with the AI assistant.',
style: TextStyle(color: colorScheme.onSurfaceVariant),
textAlign: TextAlign.center,
),
],
),
)
: ListView.builder(
controller: _scrollController,
padding: const EdgeInsets.all(16),
itemCount: messages.length,
itemBuilder: (context, index) {
final message = messages[index];
return _MessageBubble(
message: message,
formatTime: _formatTime,
);
},
),
),
// Loading indicator when sending
if (chatProvider.isSendingMessage)
Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Row(
children: [
const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
),
const SizedBox(width: 12),
Text(
'AI is thinking...',
style: TextStyle(
color: colorScheme.onSurfaceVariant,
fontStyle: FontStyle.italic,
),
),
],
),
),
// Message input
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: colorScheme.surface,
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.05),
blurRadius: 10,
offset: const Offset(0, -2),
),
],
),
child: Row(
children: [
Expanded(
child: TextField(
controller: _messageController,
decoration: InputDecoration(
hintText: 'Type a message...',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(24),
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 12,
),
),
maxLines: null,
textCapitalization: TextCapitalization.sentences,
onSubmitted: (_) => _sendMessage(),
),
),
const SizedBox(width: 8),
IconButton(
icon: const Icon(Icons.send),
onPressed: chatProvider.isSendingMessage ? null : _sendMessage,
color: colorScheme.primary,
iconSize: 28,
),
],
),
),
],
);
},
),
);
}
}
class _MessageBubble extends StatelessWidget {
final Message message;
final String Function(DateTime) formatTime;
const _MessageBubble({
required this.message,
required this.formatTime,
});
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final isUser = message.isUser;
return Padding(
padding: const EdgeInsets.only(bottom: 16),
child: Row(
mainAxisAlignment: isUser ? MainAxisAlignment.end : MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (!isUser)
CircleAvatar(
radius: 16,
backgroundColor: colorScheme.primaryContainer,
child: Icon(
Icons.smart_toy,
size: 18,
color: colorScheme.onPrimaryContainer,
),
),
const SizedBox(width: 8),
Flexible(
child: Column(
crossAxisAlignment: isUser ? CrossAxisAlignment.end : CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
decoration: BoxDecoration(
color: isUser ? colorScheme.primary : colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(16),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
message.content,
style: TextStyle(
color: isUser ? colorScheme.onPrimary : colorScheme.onSurfaceVariant,
),
),
if (message.toolCalls != null && message.toolCalls!.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Wrap(
spacing: 4,
runSpacing: 4,
children: message.toolCalls!.map((toolCall) {
return Chip(
label: Text(
toolCall.functionName,
style: const TextStyle(fontSize: 11),
),
padding: EdgeInsets.zero,
visualDensity: VisualDensity.compact,
);
}).toList(),
),
),
],
),
),
const SizedBox(height: 4),
Text(
formatTime(message.createdAt),
style: TextStyle(
fontSize: 11,
color: colorScheme.onSurfaceVariant,
),
),
],
),
),
const SizedBox(width: 8),
if (isUser)
CircleAvatar(
radius: 16,
backgroundColor: colorScheme.primary,
child: Icon(
Icons.person,
size: 18,
color: colorScheme.onPrimary,
),
),
],
),
);
}
}

View File

@@ -0,0 +1,298 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/auth_provider.dart';
import '../providers/chat_provider.dart';
import 'chat_conversation_screen.dart';
class ChatListScreen extends StatefulWidget {
const ChatListScreen({super.key});
@override
State<ChatListScreen> createState() => _ChatListScreenState();
}
class _ChatListScreenState extends State<ChatListScreen> {
@override
void initState() {
super.initState();
_loadChats();
}
Future<void> _loadChats() async {
final authProvider = Provider.of<AuthProvider>(context, listen: false);
final chatProvider = Provider.of<ChatProvider>(context, listen: false);
final accessToken = await authProvider.getValidAccessToken();
if (accessToken == null) {
await authProvider.logout();
return;
}
await chatProvider.fetchChats(accessToken: accessToken);
}
Future<void> _handleRefresh() async {
await _loadChats();
}
Future<void> _createNewChat() async {
final authProvider = Provider.of<AuthProvider>(context, listen: false);
final chatProvider = Provider.of<ChatProvider>(context, listen: false);
final accessToken = await authProvider.getValidAccessToken();
if (accessToken == null) {
await authProvider.logout();
return;
}
// Show loading dialog
if (mounted) {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => const Center(
child: CircularProgressIndicator(),
),
);
}
final chat = await chatProvider.createChat(
accessToken: accessToken,
title: 'New Chat',
);
// Close loading dialog
if (mounted) {
Navigator.pop(context);
}
if (chat != null && mounted) {
// Navigate to chat conversation
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChatConversationScreen(chatId: chat.id),
),
);
// Refresh list after returning
_loadChats();
} else if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(chatProvider.errorMessage ?? 'Failed to create chat'),
backgroundColor: Colors.red,
),
);
}
}
String _formatDateTime(DateTime dateTime) {
final now = DateTime.now();
final difference = now.difference(dateTime);
if (difference.inMinutes < 1) {
return 'Just now';
} else if (difference.inHours < 1) {
return '${difference.inMinutes}m ago';
} else if (difference.inDays < 1) {
return '${difference.inHours}h ago';
} else if (difference.inDays < 7) {
return '${difference.inDays}d ago';
} else {
return '${dateTime.day}/${dateTime.month}/${dateTime.year}';
}
}
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Scaffold(
appBar: AppBar(
title: const Text('AI Assistant'),
actions: [
IconButton(
icon: const Icon(Icons.refresh),
onPressed: _handleRefresh,
tooltip: 'Refresh',
),
],
),
body: Consumer<ChatProvider>(
builder: (context, chatProvider, _) {
if (chatProvider.isLoading && chatProvider.chats.isEmpty) {
return const Center(
child: CircularProgressIndicator(),
);
}
if (chatProvider.errorMessage != null && chatProvider.chats.isEmpty) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.error_outline,
size: 64,
color: colorScheme.error,
),
const SizedBox(height: 16),
Text(
'Failed to load chats',
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 8),
Text(
chatProvider.errorMessage!,
style: TextStyle(color: colorScheme.onSurfaceVariant),
textAlign: TextAlign.center,
),
const SizedBox(height: 24),
ElevatedButton.icon(
onPressed: _handleRefresh,
icon: const Icon(Icons.refresh),
label: const Text('Try Again'),
),
],
),
),
);
}
if (chatProvider.chats.isEmpty) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.chat_bubble_outline,
size: 64,
color: colorScheme.onSurfaceVariant,
),
const SizedBox(height: 16),
Text(
'No chats yet',
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 8),
Text(
'Start a new conversation with the AI assistant.',
style: TextStyle(color: colorScheme.onSurfaceVariant),
textAlign: TextAlign.center,
),
],
),
),
);
}
return RefreshIndicator(
onRefresh: _handleRefresh,
child: ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: chatProvider.chats.length,
itemBuilder: (context, index) {
final chat = chatProvider.chats[index];
return Dismissible(
key: Key(chat.id),
direction: DismissDirection.endToStart,
background: Container(
color: Colors.red,
alignment: Alignment.centerRight,
padding: const EdgeInsets.only(right: 16),
child: const Icon(
Icons.delete,
color: Colors.white,
),
),
confirmDismiss: (direction) async {
return await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Delete Chat'),
content: Text('Are you sure you want to delete "${chat.title}"?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
child: const Text('Delete', style: TextStyle(color: Colors.red)),
),
],
),
);
},
onDismissed: (direction) async {
final authProvider = Provider.of<AuthProvider>(context, listen: false);
final accessToken = await authProvider.getValidAccessToken();
if (accessToken != null) {
await chatProvider.deleteChat(
accessToken: accessToken,
chatId: chat.id,
);
}
},
child: ListTile(
leading: CircleAvatar(
backgroundColor: colorScheme.primaryContainer,
child: Icon(
Icons.chat,
color: colorScheme.onPrimaryContainer,
),
),
title: Text(
chat.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
subtitle: chat.lastMessageAt != null
? Text(_formatDateTime(chat.lastMessageAt!))
: null,
trailing: chat.messageCount != null
? Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: colorScheme.secondaryContainer,
borderRadius: BorderRadius.circular(12),
),
child: Text(
'${chat.messageCount}',
style: TextStyle(
color: colorScheme.onSecondaryContainer,
fontSize: 12,
fontWeight: FontWeight.bold,
),
),
)
: null,
onTap: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChatConversationScreen(chatId: chat.id),
),
);
_loadChats();
},
),
);
},
),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: _createNewChat,
tooltip: 'New Chat',
child: const Icon(Icons.add),
),
);
}
}

View File

@@ -0,0 +1,103 @@
import 'package:flutter/material.dart';
import 'dashboard_screen.dart';
import 'chat_list_screen.dart';
import 'settings_screen.dart';
class MainNavigationScreen extends StatefulWidget {
const MainNavigationScreen({super.key});
@override
State<MainNavigationScreen> createState() => _MainNavigationScreenState();
}
class _MainNavigationScreenState extends State<MainNavigationScreen> {
int _currentIndex = 0;
final List<Widget> _screens = [
const DashboardScreen(),
const ChatListScreen(),
const PlaceholderScreen(),
const SettingsScreen(),
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: IndexedStack(
index: _currentIndex,
children: _screens,
),
bottomNavigationBar: NavigationBar(
selectedIndex: _currentIndex,
onDestinationSelected: (index) {
setState(() {
_currentIndex = index;
});
},
destinations: const [
NavigationDestination(
icon: Icon(Icons.home_outlined),
selectedIcon: Icon(Icons.home),
label: 'Home',
),
NavigationDestination(
icon: Icon(Icons.chat_bubble_outline),
selectedIcon: Icon(Icons.chat_bubble),
label: 'AI Chat',
),
NavigationDestination(
icon: Icon(Icons.more_horiz),
selectedIcon: Icon(Icons.more_horiz),
label: 'More',
),
NavigationDestination(
icon: Icon(Icons.settings_outlined),
selectedIcon: Icon(Icons.settings),
label: 'Settings',
),
],
),
);
}
}
class PlaceholderScreen extends StatelessWidget {
const PlaceholderScreen({super.key});
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Scaffold(
appBar: AppBar(
title: const Text('More'),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.construction,
size: 64,
color: colorScheme.onSurfaceVariant,
),
const SizedBox(height: 16),
Text(
'Coming Soon',
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 8),
Text(
'This section is under development.',
style: TextStyle(color: colorScheme.onSurfaceVariant),
textAlign: TextAlign.center,
),
],
),
),
),
);
}
}

View File

@@ -0,0 +1,122 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/auth_provider.dart';
class SettingsScreen extends StatelessWidget {
const SettingsScreen({super.key});
Future<void> _handleLogout(BuildContext context) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Sign Out'),
content: const Text('Are you sure you want to sign out?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
child: const Text('Sign Out'),
),
],
),
);
if (confirmed == true && context.mounted) {
final authProvider = Provider.of<AuthProvider>(context, listen: false);
await authProvider.logout();
}
}
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final authProvider = Provider.of<AuthProvider>(context);
return Scaffold(
appBar: AppBar(
title: const Text('Settings'),
),
body: ListView(
children: [
// User info section
Container(
padding: const EdgeInsets.all(16),
child: Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
CircleAvatar(
radius: 30,
backgroundColor: colorScheme.primary,
child: Text(
authProvider.user?.displayName[0].toUpperCase() ?? 'U',
style: TextStyle(
fontSize: 24,
color: colorScheme.onPrimary,
fontWeight: FontWeight.bold,
),
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
authProvider.user?.displayName ?? 'User',
style: Theme.of(context).textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Text(
authProvider.user?.email ?? '',
style: TextStyle(
color: colorScheme.onSurfaceVariant,
),
),
],
),
),
],
),
],
),
),
),
),
// App version
const ListTile(
leading: Icon(Icons.info_outline),
title: Text('App Version'),
subtitle: Text('1.0.0'),
),
const Divider(),
// Sign out button
Padding(
padding: const EdgeInsets.all(16),
child: ElevatedButton.icon(
onPressed: () => _handleLogout(context),
icon: const Icon(Icons.logout),
label: const Text('Sign Out'),
style: ElevatedButton.styleFrom(
backgroundColor: colorScheme.error,
foregroundColor: colorScheme.onError,
),
),
),
],
),
);
}
}