refactor: debug logs

This commit is contained in:
cogwheel0
2025-08-20 22:15:26 +05:30
parent 9a5c5a573f
commit 4dc9ce1762
27 changed files with 1965 additions and 2195 deletions

View File

@@ -12,10 +12,11 @@ import 'dart:async';
import 'package:path/path.dart' as path;
import '../../../core/providers/app_providers.dart';
import '../providers/chat_providers.dart';
import '../../../core/utils/debug_logger.dart';
import '../widgets/modern_chat_input.dart';
import '../widgets/modern_message_bubble.dart';
import '../widgets/documentation_message_widget.dart';
import '../widgets/user_message_bubble.dart';
import '../widgets/assistant_message_widget.dart' as assistant;
import '../widgets/file_attachment_widget.dart';
import '../services/voice_input_service.dart';
import '../services/file_attachment_service.dart';
@@ -72,7 +73,7 @@ class _ChatPageState extends ConsumerState<ChatPage> {
// Clear current conversation
ref.read(chatMessagesProvider.notifier).clearMessages();
ref.read(activeConversationProvider.notifier).state = null;
// Scroll to top
if (_scrollController.hasClients) {
_scrollController.jumpTo(0);
@@ -83,45 +84,47 @@ class _ChatPageState extends ConsumerState<ChatPage> {
// Check if a model is already selected
final selectedModel = ref.read(selectedModelProvider);
if (selectedModel != null) {
debugPrint('DEBUG: Model already selected: ${selectedModel.name}');
DebugLogger.log('Model already selected: ${selectedModel.name}');
return;
}
debugPrint('DEBUG: No model selected, attempting auto-selection');
DebugLogger.log('No model selected, attempting auto-selection');
try {
// First ensure models are loaded
final modelsAsync = ref.read(modelsProvider);
List<Model> models;
if (modelsAsync.hasValue) {
models = modelsAsync.value!;
} else {
debugPrint('DEBUG: Models not loaded yet, fetching...');
DebugLogger.log('Models not loaded yet, fetching...');
models = await ref.read(modelsProvider.future);
}
debugPrint('DEBUG: Found ${models.length} models available');
DebugLogger.log('Found ${models.length} models available');
if (models.isEmpty) {
debugPrint('DEBUG: No models available for selection');
DebugLogger.log('No models available for selection');
return;
}
// Try to use the default model provider
try {
final Model? model = await ref.read(defaultModelProvider.future);
if (model != null) {
debugPrint('DEBUG: Model auto-selected via provider: ${model.name}');
DebugLogger.log('Model auto-selected via provider: ${model.name}');
}
} catch (e) {
debugPrint('DEBUG: Default provider failed, selecting first model directly');
DebugLogger.log(
'Default provider failed, selecting first model directly',
);
// Fallback: select the first available model
ref.read(selectedModelProvider.notifier).state = models.first;
debugPrint('DEBUG: Fallback model selected: ${models.first.name}');
DebugLogger.log('Fallback model selected: ${models.first.name}');
}
} catch (e) {
debugPrint('DEBUG: Failed to auto-select model: $e');
DebugLogger.error('Failed to auto-select model', e);
}
}
@@ -130,20 +133,20 @@ class _ChatPageState extends ConsumerState<ChatPage> {
// Check if onboarding has been seen
final storage = ref.read(optimizedStorageServiceProvider);
final seen = await storage.getOnboardingSeen();
debugPrint('DEBUG: Chat page - Onboarding seen status: $seen');
DebugLogger.log('Chat page - Onboarding seen status: $seen');
if (!seen && mounted) {
// Small delay to ensure navigation has settled
await Future.delayed(const Duration(milliseconds: 500));
if (!mounted) return;
debugPrint('DEBUG: Showing onboarding from chat page');
DebugLogger.log('Showing onboarding from chat page');
_showOnboarding();
await storage.setOnboardingSeen(true);
debugPrint('DEBUG: Onboarding marked as seen');
DebugLogger.log('Onboarding marked as seen');
}
} catch (e) {
debugPrint('DEBUG: Error checking onboarding status: $e');
DebugLogger.error('Error checking onboarding status', e);
}
}
@@ -168,43 +171,45 @@ class _ChatPageState extends ConsumerState<ChatPage> {
Future<void> _checkAndLoadDemoConversation() async {
final isReviewerMode = ref.read(reviewerModeProvider);
if (!isReviewerMode) return;
// Check if there's already an active conversation
final activeConversation = ref.read(activeConversationProvider);
if (activeConversation != null) {
debugPrint('Conversation already active: ${activeConversation.title}');
DebugLogger.log(
'Conversation already active: ${activeConversation.title}',
);
return;
}
// Force refresh conversations provider to ensure we get the demo conversations
ref.invalidate(conversationsProvider);
// Try to load demo conversation
for (int i = 0; i < 10; i++) {
final conversationsAsync = ref.read(conversationsProvider);
if (conversationsAsync.hasValue && conversationsAsync.value!.isNotEmpty) {
// Find and load the welcome conversation
final welcomeConv = conversationsAsync.value!.firstWhere(
(conv) => conv.id == 'demo-conv-1',
orElse: () => conversationsAsync.value!.first,
);
ref.read(activeConversationProvider.notifier).state = welcomeConv;
debugPrint('Auto-loaded demo conversation: ${welcomeConv.title}');
return;
}
// If conversations are still loading, wait a bit and retry
if (conversationsAsync.isLoading || i == 0) {
await Future.delayed(const Duration(milliseconds: 200));
continue;
}
// If there was an error or no conversations, break
break;
}
debugPrint('Failed to auto-load demo conversation');
}
@@ -214,15 +219,15 @@ class _ChatPageState extends ConsumerState<ChatPage> {
// Listen to scroll events to show/hide scroll to bottom button
_scrollController.addListener(_onScroll);
// Initialize chat page components
WidgetsBinding.instance.addPostFrameCallback((_) async {
// First, ensure a model is selected
await _checkAndAutoSelectModel();
// Then check for demo conversation in reviewer mode
await _checkAndLoadDemoConversation();
// Finally, show onboarding if needed
await _checkAndShowOnboarding();
});
@@ -252,7 +257,9 @@ class _ChatPageState extends ConsumerState<ChatPage> {
final isOnline = ref.read(isOnlineProvider);
final isReviewerMode = ref.read(reviewerModeProvider);
debugPrint('DEBUG: Online status: $isOnline, Reviewer mode: $isReviewerMode');
debugPrint(
'DEBUG: Online status: $isOnline, Reviewer mode: $isReviewerMode',
);
if (!isOnline && !isReviewerMode) {
debugPrint('DEBUG: Offline - cannot send message');
if (mounted) {
@@ -324,7 +331,9 @@ class _ChatPageState extends ConsumerState<ChatPage> {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: const Text('Message failed to send. Check your connection and try again.'),
content: const Text(
'Message failed to send. Check your connection and try again.',
),
backgroundColor: context.conduitTheme.error,
action: SnackBarAction(
label: 'Retry',
@@ -852,7 +861,7 @@ class _ChatPageState extends ConsumerState<ChatPage> {
controller: _scrollController,
padding: const EdgeInsets.fromLTRB(
Spacing.lg,
Spacing.xl,
Spacing.md,
Spacing.lg,
Spacing.lg,
),
@@ -928,7 +937,7 @@ class _ChatPageState extends ConsumerState<ChatPage> {
items: messages,
padding: const EdgeInsets.fromLTRB(
Spacing.lg,
Spacing.xl,
Spacing.md,
Spacing.lg,
Spacing.lg,
),
@@ -943,7 +952,7 @@ class _ChatPageState extends ConsumerState<ChatPage> {
// Use documentation style for assistant messages, bubble for user messages
if (isUser) {
messageWidget = ModernMessageBubble(
messageWidget = UserMessageBubble(
key: ValueKey('user-${message.id}'),
message: message,
isUser: isUser,
@@ -956,14 +965,12 @@ class _ChatPageState extends ConsumerState<ChatPage> {
onDislike: () => _dislikeMessage(message),
);
} else {
messageWidget = DocumentationMessageWidget(
messageWidget = assistant.AssistantMessageWidget(
key: ValueKey('assistant-${message.id}'),
message: message,
isUser: isUser,
isStreaming: isStreaming,
modelName: message.model,
onCopy: () => _copyMessage(message.content),
onEdit: () => _editMessage(message),
onRegenerate: () => _regenerateMessage(message),
onLike: () => _likeMessage(message),
onDislike: () => _dislikeMessage(message),
@@ -1032,7 +1039,11 @@ class _ChatPageState extends ConsumerState<ChatPage> {
// Regenerate response for the previous user message (without duplicating it)
final userMessage = messages[messageIndex - 1];
await regenerateMessage(ref, userMessage.content, userMessage.attachmentIds);
await regenerateMessage(
ref,
userMessage.content,
userMessage.attachmentIds,
);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
@@ -1046,7 +1057,9 @@ class _ChatPageState extends ConsumerState<ChatPage> {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Failed to regenerate message. Try again or check your connection.'),
content: Text(
'Failed to regenerate message. Try again or check your connection.',
),
backgroundColor: context.conduitTheme.error,
action: SnackBarAction(
label: 'Retry',
@@ -1245,10 +1258,10 @@ class _ChatPageState extends ConsumerState<ChatPage> {
final selectedModel = ref.watch(
selectedModelProvider.select((model) => model),
);
// Watch reviewer mode and auto-select model if needed
final isReviewerMode = ref.watch(reviewerModeProvider);
// Auto-select model when in reviewer mode with no selection
if (isReviewerMode && selectedModel == null) {
WidgetsBinding.instance.addPostFrameCallback((_) {
@@ -1267,12 +1280,12 @@ class _ChatPageState extends ConsumerState<ChatPage> {
if (messages.isNotEmpty) {
// Check if currently streaming
final isStreaming = messages.any((msg) => msg.isStreaming);
final shouldPop = await NavigationService.confirmNavigation(
title: 'Leave Chat?',
message: isStreaming
? 'The AI is still responding. Leave anyway?'
: 'Your conversation will be saved.',
message: isStreaming
? 'The AI is still responding. Leave anyway?'
: 'Your conversation will be saved.',
confirmText: 'Leave',
cancelText: 'Stay',
);
@@ -1281,10 +1294,10 @@ class _ChatPageState extends ConsumerState<ChatPage> {
if (isStreaming) {
ref.read(chatMessagesProvider.notifier).finishStreaming();
}
// Save the conversation before leaving
await _saveConversationBeforeLeaving(ref);
if (context.mounted) {
final canPopNavigator = Navigator.of(context).canPop();
if (canPopNavigator) {
@@ -1365,10 +1378,11 @@ class _ChatPageState extends ConsumerState<ChatPage> {
Flexible(
child: Text(
_formatModelDisplayName(selectedModel.name),
style: AppTypography.headlineSmallStyle.copyWith(
color: context.conduitTheme.textPrimary,
fontWeight: FontWeight.w400,
),
style: AppTypography.headlineSmallStyle
.copyWith(
color: context.conduitTheme.textPrimary,
fontWeight: FontWeight.w400,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
@@ -1409,10 +1423,15 @@ class _ChatPageState extends ConsumerState<ChatPage> {
vertical: 1.0,
),
decoration: BoxDecoration(
color: context.conduitTheme.success.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(AppBorderRadius.badge),
color: context.conduitTheme.success.withValues(
alpha: 0.1,
),
borderRadius: BorderRadius.circular(
AppBorderRadius.badge,
),
border: Border.all(
color: context.conduitTheme.success.withValues(alpha: 0.3),
color: context.conduitTheme.success
.withValues(alpha: 0.3),
width: BorderWidth.thin,
),
),
@@ -1446,10 +1465,11 @@ class _ChatPageState extends ConsumerState<ChatPage> {
Flexible(
child: Text(
'Choose Model',
style: AppTypography.headlineSmallStyle.copyWith(
color: context.conduitTheme.textPrimary,
fontWeight: FontWeight.w400,
),
style: AppTypography.headlineSmallStyle
.copyWith(
color: context.conduitTheme.textPrimary,
fontWeight: FontWeight.w400,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
@@ -1491,10 +1511,15 @@ class _ChatPageState extends ConsumerState<ChatPage> {
vertical: 1.0,
),
decoration: BoxDecoration(
color: context.conduitTheme.success.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(AppBorderRadius.badge),
color: context.conduitTheme.success.withValues(
alpha: 0.1,
),
borderRadius: BorderRadius.circular(
AppBorderRadius.badge,
),
border: Border.all(
color: context.conduitTheme.success.withValues(alpha: 0.3),
color: context.conduitTheme.success
.withValues(alpha: 0.3),
width: BorderWidth.thin,
),
),
@@ -1540,8 +1565,6 @@ class _ChatPageState extends ConsumerState<ChatPage> {
children: [
Column(
children: [
// Messages Area with pull-to-refresh
Expanded(
child: ConduitRefreshIndicator(
@@ -1557,7 +1580,9 @@ class _ChatPageState extends ConsumerState<ChatPage> {
.state =
full;
} catch (e) {
debugPrint('DEBUG: Failed to refresh conversation: $e');
debugPrint(
'DEBUG: Failed to refresh conversation: $e',
);
// Could show a snackbar here if needed
}
}
@@ -1581,7 +1606,9 @@ class _ChatPageState extends ConsumerState<ChatPage> {
// Modern Input (root matches input background including safe area)
ModernChatInput(
enabled: selectedModel != null && (isOnline || ref.watch(reviewerModeProvider)),
enabled:
selectedModel != null &&
(isOnline || ref.watch(reviewerModeProvider)),
onSendMessage: (text) =>
_handleMessageSend(text, selectedModel),
onVoiceInput: _handleVoiceInput,
@@ -1643,7 +1670,8 @@ class _ChatPageState extends ConsumerState<ChatPage> {
// Check if the last message (assistant) has content
final lastMessage = messages.last;
if (lastMessage.role == 'assistant' && lastMessage.content.trim().isEmpty) {
if (lastMessage.role == 'assistant' &&
lastMessage.content.trim().isEmpty) {
// Remove empty assistant message before saving
messages.removeLast();
if (messages.isEmpty) return;
@@ -1836,8 +1864,6 @@ class _ModelSelectorSheetState extends ConsumerState<_ModelSelectorSheet> {
),
),
// Search field
Padding(
padding: const EdgeInsets.only(bottom: Spacing.md),
@@ -2691,6 +2717,4 @@ class _SelectableMessageWrapper extends StatelessWidget {
}
// Extension on _ChatPageState for utility methods
extension on _ChatPageState {
}
extension on _ChatPageState {}

View File

@@ -0,0 +1,537 @@
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'dart:async';
import 'dart:io' show Platform;
import '../../../shared/theme/theme_extensions.dart';
import '../../../shared/widgets/markdown/streaming_markdown_widget.dart';
import '../../../core/utils/reasoning_parser.dart';
import 'enhanced_image_attachment.dart';
class AssistantMessageWidget extends ConsumerStatefulWidget {
final dynamic message;
final bool isStreaming;
final String? modelName;
final VoidCallback? onCopy;
final VoidCallback? onRegenerate;
final VoidCallback? onLike;
final VoidCallback? onDislike;
const AssistantMessageWidget({
super.key,
required this.message,
this.isStreaming = false,
this.modelName,
this.onCopy,
this.onRegenerate,
this.onLike,
this.onDislike,
});
@override
ConsumerState<AssistantMessageWidget> createState() =>
_AssistantMessageWidgetState();
}
class _AssistantMessageWidgetState extends ConsumerState<AssistantMessageWidget>
with TickerProviderStateMixin {
bool _showReasoning = false;
late AnimationController _fadeController;
late AnimationController _slideController;
ReasoningContent? _reasoningContent;
String _renderedContent = '';
Timer? _throttleTimer;
String? _pendingContent;
Widget? _cachedAvatar;
@override
void initState() {
super.initState();
_renderedContent = widget.message.content ?? '';
_fadeController = AnimationController(
duration: const Duration(milliseconds: 200),
vsync: this,
);
_slideController = AnimationController(
duration: const Duration(milliseconds: 300),
vsync: this,
);
// Parse reasoning content if present
_updateReasoningContent();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
// Build cached avatar when theme context is available
_buildCachedAvatar();
}
@override
void didUpdateWidget(AssistantMessageWidget oldWidget) {
super.didUpdateWidget(oldWidget);
// Re-parse reasoning content when message content changes
if (oldWidget.message.content != widget.message.content) {
// Throttle markdown re-rendering for smoother streaming
_scheduleRenderUpdate(widget.message.content ?? '');
_updateReasoningContent();
}
// Rebuild cached avatar if model name changes
if (oldWidget.modelName != widget.modelName) {
_buildCachedAvatar();
}
}
void _updateReasoningContent() {
if (widget.message.content != null) {
final newReasoningContent = ReasoningParser.parseReasoningContent(
widget.message.content!,
);
if (newReasoningContent != _reasoningContent) {
setState(() {
_reasoningContent = newReasoningContent;
});
}
}
}
void _scheduleRenderUpdate(String rawContent) {
final safe = _safeForStreaming(rawContent);
if (_throttleTimer != null && _throttleTimer!.isActive) {
_pendingContent = safe;
return;
}
if (mounted) {
setState(() => _renderedContent = safe);
} else {
_renderedContent = safe;
}
_throttleTimer = Timer(const Duration(milliseconds: 80), () {
if (!mounted) return;
if (_pendingContent != null) {
setState(() {
_renderedContent = _pendingContent!;
_pendingContent = null;
});
}
});
}
String _safeForStreaming(String content) {
if (content.isEmpty) return content;
// Auto-close an unbalanced triple backtick fence during streaming so markdown stays valid
final fenceCount = '```'.allMatches(content).length;
if (fenceCount.isOdd) {
return '$content\n```';
}
return content;
}
void _buildCachedAvatar() {
_cachedAvatar = Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Row(
children: [
Container(
width: 20,
height: 20,
decoration: BoxDecoration(
color: context.conduitTheme.buttonPrimary,
borderRadius: BorderRadius.circular(AppBorderRadius.small),
),
child: Icon(
Icons.auto_awesome,
color: context.conduitTheme.buttonPrimaryText,
size: 12,
),
),
const SizedBox(width: Spacing.xs),
Text(
widget.modelName ?? 'Assistant',
style: TextStyle(
color: context.conduitTheme.textSecondary,
fontSize: AppTypography.bodySmall,
fontWeight: FontWeight.w500,
letterSpacing: 0.1,
),
),
],
),
);
}
@override
void dispose() {
_fadeController.dispose();
_slideController.dispose();
_throttleTimer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return _buildDocumentationMessage();
}
Widget _buildDocumentationMessage() {
return Container(
width: double.infinity,
margin: const EdgeInsets.only(bottom: 16, left: 12, right: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Cached AI Name and Avatar to prevent flashing
_cachedAvatar ?? const SizedBox.shrink(),
// Reasoning Section (if present)
if (_reasoningContent != null) ...[
InkWell(
onTap: () => setState(() => _showReasoning = !_showReasoning),
borderRadius: BorderRadius.circular(AppBorderRadius.md),
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: Spacing.sm,
vertical: Spacing.xs,
),
decoration: BoxDecoration(
color: context.conduitTheme.surfaceContainer.withValues(
alpha: 0.5,
),
borderRadius: BorderRadius.circular(AppBorderRadius.md),
border: Border.all(
color: context.conduitTheme.dividerColor,
width: BorderWidth.thin,
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
_showReasoning
? Icons.expand_less_rounded
: Icons.expand_more_rounded,
size: 16,
color: context.conduitTheme.textSecondary,
),
const SizedBox(width: Spacing.xs),
Icon(
Icons.psychology_outlined,
size: 14,
color: context.conduitTheme.buttonPrimary,
),
const SizedBox(width: Spacing.xs),
Text(
_reasoningContent!.summary.isNotEmpty
? _reasoningContent!.summary
: 'Thought for ${_reasoningContent!.formattedDuration}',
style: TextStyle(
fontSize: AppTypography.bodySmall,
color: context.conduitTheme.textSecondary,
fontWeight: FontWeight.w500,
),
),
],
),
),
),
// Expandable reasoning content
AnimatedCrossFade(
firstChild: const SizedBox.shrink(),
secondChild: Container(
margin: const EdgeInsets.only(top: Spacing.sm),
padding: const EdgeInsets.all(Spacing.sm),
decoration: BoxDecoration(
color: context.conduitTheme.surfaceContainer.withValues(
alpha: 0.3,
),
borderRadius: BorderRadius.circular(AppBorderRadius.md),
border: Border.all(
color: context.conduitTheme.dividerColor,
width: BorderWidth.thin,
),
),
child: SelectableText(
_reasoningContent!.cleanedReasoning,
style: TextStyle(
fontSize: AppTypography.bodySmall,
color: context.conduitTheme.textSecondary,
fontFamily: 'monospace',
height: 1.4,
),
),
),
crossFadeState: _showReasoning
? CrossFadeState.showSecond
: CrossFadeState.showFirst,
duration: const Duration(milliseconds: 200),
),
const SizedBox(height: Spacing.md),
],
// Documentation-style content without heavy bubble; premium markdown
SizedBox(
width: double.infinity,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Display attachment images if any (for user uploaded images)
if (widget.message.attachmentIds != null &&
widget.message.attachmentIds!.isNotEmpty) ...[
_buildAttachmentImages(),
const SizedBox(height: Spacing.md),
],
if (widget.isStreaming &&
(widget.message.content.trim().isEmpty ||
widget.message.content == '[TYPING_INDICATOR]'))
_buildTypingIndicator()
else if (widget.isStreaming &&
widget.message.content.isNotEmpty &&
widget.message.content != '[TYPING_INDICATOR]')
// While streaming, render markdown with throttling and safety fixes
_buildEnhancedMarkdownContent(_renderedContent)
else
// After streaming finishes (or static content), render full markdown
_buildEnhancedMarkdownContent(
_reasoningContent?.mainContent ??
widget.message.content,
),
],
),
),
// Action buttons below the message content (always visible)
const SizedBox(height: Spacing.sm),
_buildActionButtons(),
],
),
)
.animate()
.fadeIn(duration: const Duration(milliseconds: 300))
.slideY(
begin: 0.1,
end: 0,
duration: const Duration(milliseconds: 300),
curve: Curves.easeOutCubic,
);
}
Widget _buildEnhancedMarkdownContent(String content) {
if (content.trim().isEmpty) {
return const SizedBox.shrink();
}
// Process content to ensure proper image rendering
final processedContent = _processContentForImages(content);
return StreamingMarkdownWidget(
staticContent: processedContent,
isStreaming: widget.isStreaming,
);
}
String _processContentForImages(String content) {
// Check if content contains image markdown or base64 data URLs
// This ensures images generated by AI are properly formatted
// Pattern to detect base64 images that might not be in markdown format
final base64Pattern = RegExp(r'data:image/[^;]+;base64,[A-Za-z0-9+/]+=*');
// If we find base64 images not wrapped in markdown, wrap them
if (base64Pattern.hasMatch(content) && !content.contains('![')) {
content = content.replaceAllMapped(base64Pattern, (match) {
final imageData = match.group(0)!;
// Check if this image is already in markdown format
final markdownCheck = RegExp(
r'!\[.*?\]\(' + RegExp.escape(imageData) + r'\)',
);
if (!markdownCheck.hasMatch(content)) {
return '\n![Generated Image]($imageData)\n';
}
return imageData;
});
}
return content;
}
Widget _buildAttachmentImages() {
if (widget.message.attachmentIds == null ||
widget.message.attachmentIds!.isEmpty) {
return const SizedBox.shrink();
}
final imageCount = widget.message.attachmentIds!.length;
// Display images in a clean, modern layout for assistant messages
if (imageCount == 1) {
return ClipRRect(
borderRadius: BorderRadius.circular(AppBorderRadius.md),
child: EnhancedImageAttachment(
attachmentId: widget.message.attachmentIds![0],
isMarkdownFormat: true,
constraints: const BoxConstraints(maxWidth: 500, maxHeight: 400),
),
);
} else {
return Wrap(
spacing: Spacing.sm,
runSpacing: Spacing.sm,
children: widget.message.attachmentIds!.map<Widget>((attachmentId) {
return ClipRRect(
borderRadius: BorderRadius.circular(AppBorderRadius.md),
child: EnhancedImageAttachment(
attachmentId: attachmentId,
isMarkdownFormat: true,
constraints: BoxConstraints(
maxWidth: imageCount == 2 ? 245 : 160,
maxHeight: imageCount == 2 ? 245 : 160,
),
),
);
}).toList(),
);
}
}
Widget _buildTypingIndicator() {
return Consumer(
builder: (context, ref, child) {
const statusText = 'Thinking about your question...';
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
statusText,
style: TextStyle(
color: context.conduitTheme.textSecondary.withValues(
alpha: 0.7,
),
fontSize: AppTypography.bodyMedium,
fontStyle: FontStyle.italic,
),
),
const SizedBox(height: Spacing.xs),
Row(
children: [
_buildTypingDot(0),
const SizedBox(width: Spacing.xs),
_buildTypingDot(200),
const SizedBox(width: Spacing.xs),
_buildTypingDot(400),
],
),
],
);
},
);
}
Widget _buildTypingDot(int delay) {
return Container(
width: 8,
height: 8,
decoration: BoxDecoration(
color: context.conduitTheme.textSecondary.withValues(alpha: 0.6),
borderRadius: BorderRadius.circular(AppBorderRadius.xs),
),
)
.animate(onPlay: (controller) => controller.repeat())
.scale(
duration: const Duration(milliseconds: 1000),
begin: const Offset(1, 1),
end: const Offset(1.3, 1.3),
)
.then(delay: Duration(milliseconds: delay))
.scale(
duration: const Duration(milliseconds: 1000),
begin: const Offset(1.3, 1.3),
end: const Offset(1, 1),
);
}
Widget _buildActionButtons() {
final isErrorMessage =
widget.message.content.contains('⚠️') ||
widget.message.content.contains('Error') ||
widget.message.content.contains('timeout') ||
widget.message.content.contains('retry options');
return Wrap(
spacing: 8,
runSpacing: 8,
children: [
_buildActionButton(
icon: Platform.isIOS
? CupertinoIcons.doc_on_clipboard
: Icons.content_copy,
label: 'Copy',
onTap: widget.onCopy,
),
if (isErrorMessage) ...[
_buildActionButton(
icon: Platform.isIOS
? CupertinoIcons.arrow_clockwise
: Icons.refresh,
label: 'Retry',
onTap: widget.onRegenerate,
),
] else ...[
_buildActionButton(
icon: Platform.isIOS ? CupertinoIcons.refresh : Icons.refresh,
label: 'Regenerate',
onTap: widget.onRegenerate,
),
],
],
);
}
Widget _buildActionButton({
required IconData icon,
required String label,
VoidCallback? onTap,
}) {
return GestureDetector(
onTap: onTap,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: context.conduitTheme.textPrimary.withValues(alpha: 0.04),
borderRadius: BorderRadius.circular(AppBorderRadius.lg),
border: Border.all(
color: context.conduitTheme.textPrimary.withValues(alpha: 0.08),
width: BorderWidth.regular,
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
icon,
size: IconSize.sm,
color: context.conduitTheme.textPrimary.withValues(alpha: 0.8),
),
const SizedBox(width: Spacing.xs),
Text(
label,
style: TextStyle(
fontSize: AppTypography.labelMedium,
color: context.conduitTheme.textPrimary.withValues(alpha: 0.8),
fontWeight: FontWeight.w500,
letterSpacing: 0.2,
),
),
],
),
),
);
}
}

View File

@@ -11,6 +11,7 @@ import '../../../shared/widgets/empty_states.dart';
import '../../../shared/utils/platform_utils.dart';
import '../services/conversation_search_service.dart';
import '../../../core/providers/app_providers.dart';
import '../../../core/utils/debug_logger.dart';
/// Advanced conversation search widget with filters and results
class ConversationSearchWidget extends ConsumerStatefulWidget {
@@ -87,7 +88,7 @@ class _ConversationSearchWidgetState
ref.read(conversationSearchResultsProvider.notifier).state = results;
} catch (e) {
debugPrint('Search error: $e');
DebugLogger.error('Search error', e);
} finally {
if (mounted) {
setState(() {

View File

@@ -1,752 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'dart:async';
import 'dart:io' show Platform;
import '../../../shared/theme/theme_extensions.dart';
import '../../../shared/widgets/markdown/streaming_markdown_widget.dart';
import '../../../core/utils/reasoning_parser.dart';
import 'enhanced_image_attachment.dart';
class DocumentationMessageWidget extends ConsumerStatefulWidget {
final dynamic message;
final bool isUser;
final bool isStreaming;
final String? modelName;
final VoidCallback? onCopy;
final VoidCallback? onEdit;
final VoidCallback? onRegenerate;
final VoidCallback? onLike;
final VoidCallback? onDislike;
const DocumentationMessageWidget({
super.key,
required this.message,
required this.isUser,
this.isStreaming = false,
this.modelName,
this.onCopy,
this.onEdit,
this.onRegenerate,
this.onLike,
this.onDislike,
});
@override
ConsumerState<DocumentationMessageWidget> createState() =>
_DocumentationMessageWidgetState();
}
class _DocumentationMessageWidgetState
extends ConsumerState<DocumentationMessageWidget>
with TickerProviderStateMixin {
bool _showActions = false;
bool _showReasoning = false;
late AnimationController _fadeController;
late AnimationController _slideController;
ReasoningContent? _reasoningContent;
String _renderedContent = '';
Timer? _throttleTimer;
String? _pendingContent;
Widget? _cachedAvatar;
@override
void initState() {
super.initState();
_renderedContent = widget.message.content ?? '';
_fadeController = AnimationController(
duration: const Duration(milliseconds: 200),
vsync: this,
);
_slideController = AnimationController(
duration: const Duration(milliseconds: 300),
vsync: this,
);
// Parse reasoning content if present
_updateReasoningContent();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
// Build cached avatar when theme context is available
_buildCachedAvatar();
}
@override
void didUpdateWidget(DocumentationMessageWidget oldWidget) {
super.didUpdateWidget(oldWidget);
// Re-parse reasoning content when message content changes
if (oldWidget.message.content != widget.message.content) {
// Throttle markdown re-rendering for smoother streaming
_scheduleRenderUpdate(widget.message.content ?? '');
_updateReasoningContent();
}
// Rebuild cached avatar if model name changes
if (oldWidget.modelName != widget.modelName) {
_buildCachedAvatar();
}
}
void _updateReasoningContent() {
if (!widget.isUser && widget.message.content != null) {
final newReasoningContent = ReasoningParser.parseReasoningContent(
widget.message.content!,
);
if (newReasoningContent != _reasoningContent) {
setState(() {
_reasoningContent = newReasoningContent;
});
}
}
}
void _scheduleRenderUpdate(String rawContent) {
final safe = _safeForStreaming(rawContent);
if (_throttleTimer != null && _throttleTimer!.isActive) {
_pendingContent = safe;
return;
}
if (mounted) {
setState(() => _renderedContent = safe);
} else {
_renderedContent = safe;
}
_throttleTimer = Timer(const Duration(milliseconds: 80), () {
if (!mounted) return;
if (_pendingContent != null) {
setState(() {
_renderedContent = _pendingContent!;
_pendingContent = null;
});
}
});
}
String _safeForStreaming(String content) {
if (content.isEmpty) return content;
// Auto-close an unbalanced triple backtick fence during streaming so markdown stays valid
final fenceCount = '```'.allMatches(content).length;
if (fenceCount.isOdd) {
return '$content\n```';
}
return content;
}
void _buildCachedAvatar() {
_cachedAvatar = Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Row(
children: [
Container(
width: 20,
height: 20,
decoration: BoxDecoration(
color: context.conduitTheme.buttonPrimary,
borderRadius: BorderRadius.circular(
AppBorderRadius.small,
),
),
child: Icon(
Icons.auto_awesome,
color: context.conduitTheme.buttonPrimaryText,
size: 12,
),
),
const SizedBox(width: Spacing.xs),
Text(
widget.modelName ?? 'Assistant',
style: TextStyle(
color: context.conduitTheme.textSecondary,
fontSize: AppTypography.bodySmall,
fontWeight: FontWeight.w500,
letterSpacing: 0.1,
),
),
],
),
);
}
@override
void dispose() {
_fadeController.dispose();
_slideController.dispose();
_throttleTimer?.cancel();
super.dispose();
}
void _toggleActions() {
setState(() {
_showActions = !_showActions;
});
if (_showActions) {
_fadeController.forward();
_slideController.forward();
} else {
_fadeController.reverse();
_slideController.reverse();
}
}
@override
Widget build(BuildContext context) {
if (widget.isUser) {
return _buildUserMessage();
} else {
return _buildDocumentationMessage();
}
}
Widget _buildUserMessage() {
final hasImages = widget.message.attachmentIds != null &&
widget.message.attachmentIds!.isNotEmpty;
final hasText = widget.message.content.isNotEmpty;
return GestureDetector(
onLongPress: () => _toggleActions(),
behavior: HitTestBehavior.translucent,
child: Container(
width: double.infinity,
margin: const EdgeInsets.only(bottom: 12, left: 50, right: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
// Display images outside and above the text bubble
if (hasImages) ...[
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Flexible(
child: _buildUserAttachmentImages(),
),
],
),
if (hasText) const SizedBox(height: Spacing.xs),
],
// Display text bubble if there's text content
if (hasText)
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Flexible(
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 8,
),
decoration: BoxDecoration(
color: context.conduitTheme.chatBubbleUser,
borderRadius: BorderRadius.circular(AppBorderRadius.lg),
border: Border.all(
color: context.conduitTheme.chatBubbleUserBorder,
width: BorderWidth.regular,
),
),
child: Text(
widget.message.content,
style: TextStyle(
color: context.conduitTheme.chatBubbleUserText,
fontSize: AppTypography.bodyMedium,
height: 1.3,
letterSpacing: 0.1,
),
),
),
),
],
),
// Action buttons below the message bubble
if (_showActions) ...[
const SizedBox(height: Spacing.sm),
_buildUserActionButtons(),
],
],
),
),
)
.animate()
.fadeIn(duration: const Duration(milliseconds: 400))
.slideX(
begin: 0.2,
end: 0,
duration: const Duration(milliseconds: 400),
curve: Curves.easeOutCubic,
);
}
Widget _buildDocumentationMessage() {
return GestureDetector(
onLongPress: () => _toggleActions(),
behavior: HitTestBehavior.translucent,
child: Container(
width: double.infinity,
margin: const EdgeInsets.only(bottom: 16, left: 12, right: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Cached AI Name and Avatar to prevent flashing
_cachedAvatar ?? const SizedBox.shrink(),
// Reasoning Section (if present)
if (_reasoningContent != null) ...[
InkWell(
onTap: () => setState(() => _showReasoning = !_showReasoning),
borderRadius: BorderRadius.circular(AppBorderRadius.md),
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: Spacing.sm,
vertical: Spacing.xs,
),
decoration: BoxDecoration(
color: context.conduitTheme.surfaceContainer.withValues(
alpha: 0.5,
),
borderRadius: BorderRadius.circular(AppBorderRadius.md),
border: Border.all(
color: context.conduitTheme.dividerColor,
width: BorderWidth.thin,
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
_showReasoning
? Icons.expand_less_rounded
: Icons.expand_more_rounded,
size: 16,
color: context.conduitTheme.textSecondary,
),
const SizedBox(width: Spacing.xs),
Icon(
Icons.psychology_outlined,
size: 14,
color: context.conduitTheme.buttonPrimary,
),
const SizedBox(width: Spacing.xs),
Text(
_reasoningContent!.summary.isNotEmpty
? _reasoningContent!.summary
: 'Thought for ${_reasoningContent!.formattedDuration}',
style: TextStyle(
fontSize: AppTypography.bodySmall,
color: context.conduitTheme.textSecondary,
fontWeight: FontWeight.w500,
),
),
],
),
),
),
// Expandable reasoning content
AnimatedCrossFade(
firstChild: const SizedBox.shrink(),
secondChild: Container(
margin: const EdgeInsets.only(top: Spacing.sm),
padding: const EdgeInsets.all(Spacing.sm),
decoration: BoxDecoration(
color: context.conduitTheme.surfaceContainer.withValues(
alpha: 0.3,
),
borderRadius: BorderRadius.circular(AppBorderRadius.md),
border: Border.all(
color: context.conduitTheme.dividerColor,
width: BorderWidth.thin,
),
),
child: SelectableText(
_reasoningContent!.cleanedReasoning,
style: TextStyle(
fontSize: AppTypography.bodySmall,
color: context.conduitTheme.textSecondary,
fontFamily: 'monospace',
height: 1.4,
),
),
),
crossFadeState: _showReasoning
? CrossFadeState.showSecond
: CrossFadeState.showFirst,
duration: const Duration(milliseconds: 200),
),
const SizedBox(height: Spacing.md),
],
// Documentation-style content without heavy bubble; premium markdown
SizedBox(
width: double.infinity,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Display attachment images if any (for user uploaded images)
if (widget.message.attachmentIds != null &&
widget.message.attachmentIds!.isNotEmpty) ...[
_buildAttachmentImages(),
const SizedBox(height: Spacing.md),
],
if (widget.isStreaming &&
(widget.message.content.trim().isEmpty ||
widget.message.content == '[TYPING_INDICATOR]'))
_buildTypingIndicator()
else if (widget.isStreaming &&
widget.message.content.isNotEmpty &&
widget.message.content != '[TYPING_INDICATOR]')
// While streaming, render markdown with throttling and safety fixes
_buildEnhancedMarkdownContent(_renderedContent)
else
// After streaming finishes (or static content), render full markdown
_buildEnhancedMarkdownContent(
_reasoningContent?.mainContent ??
widget.message.content,
),
],
),
),
// Action buttons below the message content
if (_showActions) ...[
const SizedBox(height: Spacing.sm),
_buildActionButtons(),
],
],
),
),
)
.animate()
.fadeIn(duration: const Duration(milliseconds: 300))
.slideY(
begin: 0.1,
end: 0,
duration: const Duration(milliseconds: 300),
curve: Curves.easeOutCubic,
);
}
Widget _buildEnhancedMarkdownContent(String content) {
if (content.trim().isEmpty) {
return const SizedBox.shrink();
}
// Process content to ensure proper image rendering
final processedContent = _processContentForImages(content);
return StreamingMarkdownWidget(
staticContent: processedContent,
isStreaming: widget.isStreaming,
);
}
String _processContentForImages(String content) {
// Check if content contains image markdown or base64 data URLs
// This ensures images generated by AI are properly formatted
// Pattern to detect base64 images that might not be in markdown format
final base64Pattern = RegExp(r'data:image/[^;]+;base64,[A-Za-z0-9+/]+=*');
// If we find base64 images not wrapped in markdown, wrap them
if (base64Pattern.hasMatch(content) && !content.contains('![')) {
content = content.replaceAllMapped(base64Pattern, (match) {
final imageData = match.group(0)!;
// Check if this image is already in markdown format
final markdownCheck = RegExp(r'!\[.*?\]\(' + RegExp.escape(imageData) + r'\)');
if (!markdownCheck.hasMatch(content)) {
return '\n![Generated Image]($imageData)\n';
}
return imageData;
});
}
return content;
}
Widget _buildUserAttachmentImages() {
if (widget.message.attachmentIds == null ||
widget.message.attachmentIds!.isEmpty) {
return const SizedBox.shrink();
}
final imageCount = widget.message.attachmentIds!.length;
// Similar to iMessage style but adapted for documentation widget
if (imageCount == 1) {
return ClipRRect(
borderRadius: BorderRadius.circular(AppBorderRadius.lg),
child: EnhancedImageAttachment(
attachmentId: widget.message.attachmentIds![0],
isUserMessage: true,
constraints: const BoxConstraints(
maxWidth: 280,
maxHeight: 350,
),
),
);
} else if (imageCount == 2) {
return Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.end,
children: widget.message.attachmentIds!.map((attachmentId) {
return Padding(
padding: EdgeInsets.only(
left: attachmentId == widget.message.attachmentIds!.first
? 0
: Spacing.xs,
),
child: ClipRRect(
borderRadius: BorderRadius.circular(AppBorderRadius.lg),
child: EnhancedImageAttachment(
attachmentId: attachmentId,
isUserMessage: true,
constraints: const BoxConstraints(
maxWidth: 135,
maxHeight: 180,
),
),
),
);
}).toList(),
);
} else {
return Container(
constraints: const BoxConstraints(maxWidth: 280),
child: Wrap(
alignment: WrapAlignment.end,
spacing: Spacing.xs,
runSpacing: Spacing.xs,
children: widget.message.attachmentIds!.map((attachmentId) {
return ClipRRect(
borderRadius: BorderRadius.circular(AppBorderRadius.md),
child: EnhancedImageAttachment(
attachmentId: attachmentId,
isUserMessage: true,
constraints: BoxConstraints(
maxWidth: imageCount == 3 ? 135 : 90,
maxHeight: imageCount == 3 ? 135 : 90,
),
),
);
}).toList(),
),
);
}
}
Widget _buildAttachmentImages() {
if (widget.message.attachmentIds == null ||
widget.message.attachmentIds!.isEmpty) {
return const SizedBox.shrink();
}
final imageCount = widget.message.attachmentIds!.length;
// Display images in a clean, modern layout for assistant messages
if (imageCount == 1) {
return ClipRRect(
borderRadius: BorderRadius.circular(AppBorderRadius.md),
child: EnhancedImageAttachment(
attachmentId: widget.message.attachmentIds![0],
isMarkdownFormat: true,
constraints: const BoxConstraints(
maxWidth: 500,
maxHeight: 400,
),
),
);
} else {
return Wrap(
spacing: Spacing.sm,
runSpacing: Spacing.sm,
children: widget.message.attachmentIds!.map<Widget>((attachmentId) {
return ClipRRect(
borderRadius: BorderRadius.circular(AppBorderRadius.md),
child: EnhancedImageAttachment(
attachmentId: attachmentId,
isMarkdownFormat: true,
constraints: BoxConstraints(
maxWidth: imageCount == 2 ? 245 : 160,
maxHeight: imageCount == 2 ? 245 : 160,
),
),
);
}).toList(),
);
}
}
Widget _buildTypingIndicator() {
return Consumer(
builder: (context, ref, child) {
const statusText = 'Thinking about your question...';
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
statusText,
style: TextStyle(
color: context.conduitTheme.textSecondary.withValues(
alpha: 0.7,
),
fontSize: AppTypography.bodyMedium,
fontStyle: FontStyle.italic,
),
),
const SizedBox(height: Spacing.xs),
Row(
children: [
_buildTypingDot(0),
const SizedBox(width: Spacing.xs),
_buildTypingDot(200),
const SizedBox(width: Spacing.xs),
_buildTypingDot(400),
],
),
],
);
},
);
}
Widget _buildTypingDot(int delay) {
return Container(
width: 8,
height: 8,
decoration: BoxDecoration(
color: context.conduitTheme.textSecondary.withValues(alpha: 0.6),
borderRadius: BorderRadius.circular(AppBorderRadius.xs),
),
)
.animate(onPlay: (controller) => controller.repeat())
.scale(
duration: const Duration(milliseconds: 1000),
begin: const Offset(1, 1),
end: const Offset(1.3, 1.3),
)
.then(delay: Duration(milliseconds: delay))
.scale(
duration: const Duration(milliseconds: 1000),
begin: const Offset(1.3, 1.3),
end: const Offset(1, 1),
);
}
Widget _buildActionButtons() {
final isErrorMessage = widget.message.content.contains('⚠️') ||
widget.message.content.contains('Error') ||
widget.message.content.contains('timeout') ||
widget.message.content.contains('retry options');
return Wrap(
spacing: 8,
runSpacing: 8,
children: [
_buildActionButton(
icon: Platform.isIOS
? CupertinoIcons.doc_on_clipboard
: Icons.content_copy,
label: 'Copy',
onTap: widget.onCopy,
),
if (isErrorMessage) ...[
_buildActionButton(
icon: Platform.isIOS ? CupertinoIcons.arrow_clockwise : Icons.refresh,
label: 'Retry',
onTap: widget.onRegenerate,
),
] else ...[
_buildActionButton(
icon: Platform.isIOS
? CupertinoIcons.hand_thumbsup
: Icons.thumb_up_outlined,
label: 'Like',
onTap: widget.onLike,
),
_buildActionButton(
icon: Platform.isIOS
? CupertinoIcons.hand_thumbsdown
: Icons.thumb_down_outlined,
label: 'Dislike',
onTap: widget.onDislike,
),
_buildActionButton(
icon: Platform.isIOS ? CupertinoIcons.refresh : Icons.refresh,
label: 'Regenerate',
onTap: widget.onRegenerate,
),
],
],
);
}
Widget _buildActionButton({
required IconData icon,
required String label,
VoidCallback? onTap,
}) {
return GestureDetector(
onTap: onTap,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: context.conduitTheme.textPrimary.withValues(alpha: 0.04),
borderRadius: BorderRadius.circular(AppBorderRadius.lg),
border: Border.all(
color: context.conduitTheme.textPrimary.withValues(alpha: 0.08),
width: BorderWidth.regular,
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
icon,
size: IconSize.sm,
color: context.conduitTheme.textPrimary.withValues(alpha: 0.8),
),
const SizedBox(width: Spacing.xs),
Text(
label,
style: TextStyle(
fontSize: AppTypography.labelMedium,
color: context.conduitTheme.textPrimary.withValues(alpha: 0.8),
fontWeight: FontWeight.w500,
letterSpacing: 0.2,
),
),
],
),
),
);
}
Widget _buildUserActionButtons() {
return Wrap(
spacing: 8,
runSpacing: 8,
children: [
_buildActionButton(
icon: Platform.isIOS ? CupertinoIcons.pencil : Icons.edit_outlined,
label: 'Edit',
onTap: widget.onEdit,
),
_buildActionButton(
icon: Platform.isIOS
? CupertinoIcons.doc_on_clipboard
: Icons.content_copy,
label: 'Copy',
onTap: widget.onCopy,
),
],
);
}
}

View File

@@ -1,621 +0,0 @@
import 'package:flutter/material.dart';
import '../../../shared/theme/theme_extensions.dart';
import '../../../shared/widgets/markdown/streaming_markdown_widget.dart';
import 'enhanced_image_attachment.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'dart:io' show Platform;
class ModernMessageBubble extends ConsumerStatefulWidget {
final dynamic message;
final bool isUser;
final bool isStreaming;
final String? modelName;
final VoidCallback? onCopy;
final VoidCallback? onEdit;
final VoidCallback? onRegenerate;
final VoidCallback? onLike;
final VoidCallback? onDislike;
const ModernMessageBubble({
super.key,
required this.message,
required this.isUser,
this.isStreaming = false,
this.modelName,
this.onCopy,
this.onEdit,
this.onRegenerate,
this.onLike,
this.onDislike,
});
@override
ConsumerState<ModernMessageBubble> createState() =>
_ModernMessageBubbleState();
}
class _ModernMessageBubbleState extends ConsumerState<ModernMessageBubble>
with TickerProviderStateMixin {
bool _showActions = false;
late AnimationController _fadeController;
late AnimationController _slideController;
@override
void initState() {
super.initState();
_fadeController = AnimationController(
duration: AnimationDuration.microInteraction,
vsync: this,
);
_slideController = AnimationController(
duration: AnimationDuration.messageSlide,
vsync: this,
);
}
Widget _buildUserAttachmentImages() {
if (widget.message.attachmentIds == null ||
widget.message.attachmentIds!.isEmpty) {
return const SizedBox.shrink();
}
final imageCount = widget.message.attachmentIds!.length;
// iMessage-style image layout
if (imageCount == 1) {
// Single image - larger display
return Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(AppBorderRadius.messageBubble),
child: EnhancedImageAttachment(
attachmentId: widget.message.attachmentIds![0],
isUserMessage: true,
constraints: const BoxConstraints(
maxWidth: 280,
maxHeight: 350,
),
),
),
],
);
} else if (imageCount == 2) {
// Two images side by side
return Row(
mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: Row(
mainAxisSize: MainAxisSize.min,
children: widget.message.attachmentIds!.map((attachmentId) {
return Padding(
padding: EdgeInsets.only(
left: attachmentId == widget.message.attachmentIds!.first
? 0
: Spacing.xs,
),
child: ClipRRect(
borderRadius: BorderRadius.circular(AppBorderRadius.messageBubble),
child: EnhancedImageAttachment(
attachmentId: attachmentId,
isUserMessage: true,
constraints: const BoxConstraints(
maxWidth: 135,
maxHeight: 180,
),
),
),
);
}).toList(),
),
),
],
);
} else {
// Grid layout for 3+ images
return Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Flexible(
child: Container(
constraints: const BoxConstraints(maxWidth: 280),
child: Wrap(
alignment: WrapAlignment.end,
spacing: Spacing.xs,
runSpacing: Spacing.xs,
children: widget.message.attachmentIds!.map((attachmentId) {
return ClipRRect(
borderRadius: BorderRadius.circular(AppBorderRadius.md),
child: EnhancedImageAttachment(
attachmentId: attachmentId,
isUserMessage: true,
constraints: BoxConstraints(
maxWidth: imageCount == 3 ? 135 : 90,
maxHeight: imageCount == 3 ? 135 : 90,
),
),
);
}).toList(),
),
),
),
],
);
}
}
Widget _buildAssistantAttachmentImages() {
if (widget.message.attachmentIds == null ||
widget.message.attachmentIds!.isEmpty) {
return const SizedBox.shrink();
}
// Assistant images - similar style but left-aligned
return Wrap(
spacing: Spacing.sm,
runSpacing: Spacing.sm,
children: widget.message.attachmentIds!.map<Widget>((attachmentId) {
return ClipRRect(
borderRadius: BorderRadius.circular(AppBorderRadius.messageBubble),
child: EnhancedImageAttachment(
attachmentId: attachmentId,
constraints: const BoxConstraints(
maxWidth: 300,
maxHeight: 350,
),
),
);
}).toList(),
);
}
@override
void dispose() {
_fadeController.dispose();
_slideController.dispose();
super.dispose();
}
void _toggleActions() {
setState(() {
_showActions = !_showActions;
});
if (_showActions) {
_fadeController.forward();
_slideController.forward();
} else {
_fadeController.reverse();
_slideController.reverse();
}
}
@override
Widget build(BuildContext context) {
if (widget.isUser) {
return _buildUserMessage();
} else {
return _buildAssistantMessage();
}
}
Widget _buildUserMessage() {
final hasImages = widget.message.attachmentIds != null &&
widget.message.attachmentIds!.isNotEmpty;
final hasText = widget.message.content.isNotEmpty;
return GestureDetector(
onLongPress: () => _toggleActions(),
behavior: HitTestBehavior.translucent,
child: Container(
width: double.infinity,
margin: const EdgeInsets.only(
bottom: Spacing.sm,
left: Spacing.xxxl,
right: Spacing.xs,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
// Display images outside and above the text bubble (iMessage style)
if (hasImages) ...[
_buildUserAttachmentImages(),
if (hasText) const SizedBox(height: Spacing.xs),
],
// Display text bubble if there's text content
if (hasText)
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Flexible(
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: Spacing.messagePadding,
vertical: Spacing.xs,
),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
context.conduitTheme.chatBubbleUser.withValues(
alpha: 0.95,
),
context.conduitTheme.chatBubbleUser,
],
),
borderRadius: BorderRadius.circular(
AppBorderRadius.messageBubble,
),
border: Border.all(
color: context.conduitTheme.chatBubbleUserBorder,
width: BorderWidth.regular,
),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.08),
blurRadius: 4,
offset: const Offset(0, 2),
),
],
),
child: _buildCustomText(
widget.message.content,
context.conduitTheme.chatBubbleUserText,
),
),
),
],
),
// Action buttons below the message
if (_showActions) ...[
const SizedBox(height: Spacing.sm),
_buildUserActionButtons(),
],
],
),
),
)
.animate()
.fadeIn(duration: AnimationDuration.messageAppear)
.slideX(
begin: AnimationValues.messageSlideDistance,
end: 0,
duration: AnimationDuration.messageSlide,
curve: AnimationCurves.messageSlide,
);
}
Widget _buildAssistantMessage() {
final hasImages = widget.message.attachmentIds != null &&
widget.message.attachmentIds!.isNotEmpty;
final hasContent = widget.message.content.isNotEmpty &&
widget.message.content != '[TYPING_INDICATOR]';
final showTyping = (widget.message.content.isEmpty ||
widget.message.content == '[TYPING_INDICATOR]') &&
widget.isStreaming;
return GestureDetector(
onLongPress: () => _toggleActions(),
behavior: HitTestBehavior.translucent,
child: Container(
width: double.infinity,
margin: const EdgeInsets.only(
bottom: Spacing.md,
left: Spacing.xs,
right: Spacing.xxxl,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Simplified AI Name and Avatar
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Row(
children: [
Container(
width: 20,
height: 20,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
context.conduitTheme.buttonPrimary.withValues(
alpha: 0.9,
),
context.conduitTheme.buttonPrimary,
],
),
borderRadius: BorderRadius.circular(
AppBorderRadius.small,
),
),
child: Icon(
Icons.auto_awesome,
color: context.conduitTheme.buttonPrimaryText,
size: 12,
),
),
const SizedBox(width: Spacing.xs),
Text(
widget.modelName ?? 'Assistant',
style: TextStyle(
color: context.conduitTheme.textSecondary,
fontSize: AppTypography.bodySmall,
fontWeight: FontWeight.w500,
letterSpacing: 0.1,
),
),
],
),
),
// Display images outside the bubble if any
if (hasImages) ...[
_buildAssistantAttachmentImages(),
if (hasContent || showTyping) const SizedBox(height: Spacing.xs),
],
// Message Content Bubble
if (hasContent || showTyping)
Container(
padding: EdgeInsets.symmetric(
horizontal: Spacing.messagePadding,
vertical: Spacing.xs,
),
decoration: BoxDecoration(
color: context.conduitTheme.chatBubbleAssistant,
borderRadius: BorderRadius.circular(
AppBorderRadius.messageBubble,
),
border: Border.all(
color: context.conduitTheme.chatBubbleAssistantBorder,
width: BorderWidth.regular,
),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.05),
blurRadius: 3,
offset: const Offset(0, 1),
),
],
),
child: showTyping
? _buildTypingIndicator()
: _buildCustomText(
widget.message.content,
context.conduitTheme.chatBubbleAssistantText,
),
),
// Action buttons below the message content
if (_showActions) ...[
const SizedBox(height: Spacing.sm),
_buildActionButtons(),
],
],
),
),
)
.animate()
.fadeIn(duration: AnimationDuration.messageAppear)
.slideX(
begin: -AnimationValues.messageSlideDistance,
end: 0,
duration: AnimationDuration.messageSlide,
curve: AnimationCurves.messageSlide,
);
}
Widget _buildCustomText(String text, [Color? textColor]) {
// Use the new markdown widget for rich text rendering
return StreamingMarkdownWidget(
staticContent: text,
isStreaming: widget.isStreaming,
);
}
Widget _buildTypingIndicator() {
return Consumer(
builder: (context, ref, child) {
// Show only animated dots, no text
return _buildTypingDots();
},
);
}
Widget _buildTypingDots() {
return Row(
children: List.generate(3, (index) {
return Container(
margin: EdgeInsets.only(right: index < 2 ? Spacing.xs : 0),
width: 6,
height: 6,
decoration: BoxDecoration(
color: context.conduitTheme.loadingIndicator,
borderRadius: BorderRadius.circular(3),
),
)
.animate(onPlay: (controller) => controller.repeat())
.scale(
duration: AnimationDuration.typingIndicator,
begin: const Offset(
AnimationValues.typingIndicatorScale,
AnimationValues.typingIndicatorScale,
),
end: const Offset(1.0, 1.0),
curve: AnimationCurves.typingIndicator,
delay: Duration(
milliseconds: index * 200,
), // Stagger the animation
);
}),
);
}
Widget _buildActionButtons() {
final isErrorMessage = widget.message.content.contains('⚠️') ||
widget.message.content.contains('Error') ||
widget.message.content.contains('timeout') ||
widget.message.content.contains('retry options');
return Wrap(
spacing: Spacing.sm,
runSpacing: Spacing.sm,
children: [
_buildActionButton(
icon: Platform.isIOS
? CupertinoIcons.doc_on_clipboard
: Icons.content_copy,
label: 'Copy',
onTap: widget.onCopy,
),
if (isErrorMessage) ...[
_buildActionButton(
icon: Platform.isIOS ? CupertinoIcons.arrow_clockwise : Icons.refresh,
label: 'Retry',
onTap: widget.onRegenerate,
),
] else ...[
_buildActionButton(
icon: Platform.isIOS ? CupertinoIcons.pencil : Icons.edit_outlined,
label: 'Edit',
onTap: widget.onEdit,
),
_buildActionButton(
icon: Platform.isIOS
? CupertinoIcons.speaker_1
: Icons.volume_up_outlined,
label: 'Read',
onTap: () => _handleTextToSpeech(context),
),
_buildActionButton(
icon: Platform.isIOS
? CupertinoIcons.hand_thumbsup
: Icons.thumb_up_outlined,
label: 'Like',
onTap: widget.onLike,
),
_buildActionButton(
icon: Platform.isIOS
? CupertinoIcons.hand_thumbsdown
: Icons.thumb_down_outlined,
label: 'Dislike',
onTap: widget.onDislike,
),
_buildActionButton(
icon: Platform.isIOS ? CupertinoIcons.refresh : Icons.refresh,
label: 'Regenerate',
onTap: widget.onRegenerate,
),
],
],
);
}
Widget _buildActionButton({
required IconData icon,
required String label,
VoidCallback? onTap,
}) {
return GestureDetector(
onTap: onTap,
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: Spacing.actionButtonPadding,
vertical: Spacing.xs,
),
decoration: BoxDecoration(
color: context.conduitTheme.surfaceBackground.withValues(
alpha: Alpha.buttonHover,
),
borderRadius: BorderRadius.circular(AppBorderRadius.actionButton),
border: Border.all(
color: context.conduitTheme.textPrimary.withValues(
alpha: Alpha.subtle,
),
width: BorderWidth.regular,
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
icon,
size: IconSize.small,
color: context.conduitTheme.iconSecondary,
),
const SizedBox(width: Spacing.xs),
Text(
label,
style: AppTypography.labelStyle.copyWith(
color: context.conduitTheme.textSecondary,
),
),
],
),
),
).animate().scale(
duration: AnimationDuration.buttonPress,
curve: AnimationCurves.buttonPress,
);
}
Widget _buildUserActionButtons() {
return Wrap(
spacing: Spacing.sm,
runSpacing: Spacing.sm,
children: [
_buildActionButton(
icon: Platform.isIOS ? CupertinoIcons.pencil : Icons.edit_outlined,
label: 'Edit',
onTap: widget.onEdit,
),
_buildActionButton(
icon: Platform.isIOS
? CupertinoIcons.doc_on_clipboard
: Icons.content_copy,
label: 'Copy',
onTap: widget.onCopy,
),
_buildActionButton(
icon: Platform.isIOS
? CupertinoIcons.speaker_1
: Icons.volume_up_outlined,
label: 'Read',
onTap: () => _handleTextToSpeech(context),
),
],
);
}
void _handleTextToSpeech(BuildContext context) {
// Implementation for text-to-speech functionality
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Text-to-speech feature coming soon!'),
backgroundColor: context.conduitTheme.info,
behavior: SnackBarBehavior.floating,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(AppBorderRadius.snackbar),
),
),
);
}
}

View File

@@ -0,0 +1,346 @@
import 'package:flutter/material.dart';
import '../../../shared/theme/theme_extensions.dart';
import 'enhanced_image_attachment.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'dart:io' show Platform;
class UserMessageBubble extends ConsumerStatefulWidget {
final dynamic message;
final bool isUser;
final bool isStreaming;
final String? modelName;
final VoidCallback? onCopy;
final VoidCallback? onEdit;
final VoidCallback? onRegenerate;
final VoidCallback? onLike;
final VoidCallback? onDislike;
const UserMessageBubble({
super.key,
required this.message,
required this.isUser,
this.isStreaming = false,
this.modelName,
this.onCopy,
this.onEdit,
this.onRegenerate,
this.onLike,
this.onDislike,
});
@override
ConsumerState<UserMessageBubble> createState() => _UserMessageBubbleState();
}
class _UserMessageBubbleState extends ConsumerState<UserMessageBubble>
with TickerProviderStateMixin {
bool _showActions = false;
late AnimationController _fadeController;
late AnimationController _slideController;
@override
void initState() {
super.initState();
_fadeController = AnimationController(
duration: AnimationDuration.microInteraction,
vsync: this,
);
_slideController = AnimationController(
duration: AnimationDuration.messageSlide,
vsync: this,
);
}
Widget _buildUserAttachmentImages() {
if (widget.message.attachmentIds == null ||
widget.message.attachmentIds!.isEmpty) {
return const SizedBox.shrink();
}
final imageCount = widget.message.attachmentIds!.length;
// iMessage-style image layout
if (imageCount == 1) {
// Single image - larger display
return Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(AppBorderRadius.messageBubble),
child: EnhancedImageAttachment(
attachmentId: widget.message.attachmentIds![0],
isUserMessage: true,
constraints: const BoxConstraints(maxWidth: 280, maxHeight: 350),
),
),
],
);
} else if (imageCount == 2) {
// Two images side by side
return Row(
mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: Row(
mainAxisSize: MainAxisSize.min,
children: widget.message.attachmentIds!.map((attachmentId) {
return Padding(
padding: EdgeInsets.only(
left: attachmentId == widget.message.attachmentIds!.first
? 0
: Spacing.xs,
),
child: ClipRRect(
borderRadius: BorderRadius.circular(
AppBorderRadius.messageBubble,
),
child: EnhancedImageAttachment(
attachmentId: attachmentId,
isUserMessage: true,
constraints: const BoxConstraints(
maxWidth: 135,
maxHeight: 180,
),
),
),
);
}).toList(),
),
),
],
);
} else {
// Grid layout for 3+ images
return Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Flexible(
child: Container(
constraints: const BoxConstraints(maxWidth: 280),
child: Wrap(
alignment: WrapAlignment.end,
spacing: Spacing.xs,
runSpacing: Spacing.xs,
children: widget.message.attachmentIds!.map((attachmentId) {
return ClipRRect(
borderRadius: BorderRadius.circular(AppBorderRadius.md),
child: EnhancedImageAttachment(
attachmentId: attachmentId,
isUserMessage: true,
constraints: BoxConstraints(
maxWidth: imageCount == 3 ? 135 : 90,
maxHeight: imageCount == 3 ? 135 : 90,
),
),
);
}).toList(),
),
),
),
],
);
}
}
// Assistant-only helpers removed; this widget renders only user bubbles.
@override
void dispose() {
_fadeController.dispose();
_slideController.dispose();
super.dispose();
}
void _toggleActions() {
setState(() {
_showActions = !_showActions;
});
if (_showActions) {
_fadeController.forward();
_slideController.forward();
} else {
_fadeController.reverse();
_slideController.reverse();
}
}
@override
Widget build(BuildContext context) {
return _buildUserMessage();
}
Widget _buildUserMessage() {
final hasImages =
widget.message.attachmentIds != null &&
widget.message.attachmentIds!.isNotEmpty;
final hasText = widget.message.content.isNotEmpty;
return GestureDetector(
onLongPress: () => _toggleActions(),
behavior: HitTestBehavior.translucent,
child: Container(
width: double.infinity,
margin: const EdgeInsets.only(
bottom: Spacing.sm,
left: Spacing.xxxl,
right: Spacing.xs,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
// Display images outside and above the text bubble (iMessage style)
if (hasImages) ...[_buildUserAttachmentImages()],
// Display text bubble if there's text content
if (hasText) const SizedBox(height: Spacing.xs),
if (hasText)
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width * 0.82,
),
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: Spacing.chatBubblePadding,
vertical: Spacing.sm,
),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
context.conduitTheme.chatBubbleUser.withValues(
alpha: 0.95,
),
context.conduitTheme.chatBubbleUser,
],
),
borderRadius: BorderRadius.circular(
AppBorderRadius.messageBubble,
),
border: Border.all(
color: context.conduitTheme.chatBubbleUserBorder,
width: BorderWidth.regular,
),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.08),
blurRadius: 4,
offset: const Offset(0, 2),
),
],
),
child: Text(
widget.message.content,
style: AppTypography.chatMessageStyle.copyWith(
color: context.conduitTheme.chatBubbleUserText,
),
softWrap: true,
),
),
),
],
),
if (hasText) const SizedBox(height: Spacing.xs),
// Action buttons below the message
if (_showActions) ...[
const SizedBox(height: Spacing.sm),
_buildUserActionButtons(),
],
],
),
),
)
.animate()
.fadeIn(duration: AnimationDuration.messageAppear)
.slideX(
begin: AnimationValues.messageSlideDistance,
end: 0,
duration: AnimationDuration.messageSlide,
curve: AnimationCurves.messageSlide,
);
}
// Assistant-only message renderer removed.
// Markdown rendering and typing indicator helpers removed.
// Removed unused assistant action buttons builder.
Widget _buildActionButton({
required IconData icon,
required String label,
VoidCallback? onTap,
}) {
return GestureDetector(
onTap: onTap,
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: Spacing.actionButtonPadding,
vertical: Spacing.xs,
),
decoration: BoxDecoration(
color: context.conduitTheme.surfaceBackground.withValues(
alpha: Alpha.buttonHover,
),
borderRadius: BorderRadius.circular(AppBorderRadius.actionButton),
border: Border.all(
color: context.conduitTheme.textPrimary.withValues(
alpha: Alpha.subtle,
),
width: BorderWidth.regular,
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
icon,
size: IconSize.small,
color: context.conduitTheme.iconSecondary,
),
const SizedBox(width: Spacing.xs),
Text(
label,
style: AppTypography.labelStyle.copyWith(
color: context.conduitTheme.textSecondary,
),
),
],
),
),
).animate().scale(
duration: AnimationDuration.buttonPress,
curve: AnimationCurves.buttonPress,
);
}
Widget _buildUserActionButtons() {
return Wrap(
spacing: Spacing.sm,
runSpacing: Spacing.sm,
children: [
_buildActionButton(
icon: Platform.isIOS ? CupertinoIcons.pencil : Icons.edit_outlined,
label: 'Edit',
onTap: widget.onEdit,
),
_buildActionButton(
icon: Platform.isIOS
? CupertinoIcons.doc_on_clipboard
: Icons.content_copy,
label: 'Copy',
onTap: widget.onCopy,
),
],
);
}
}