forked from RunanywhereAI/runanywhere-sdks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat_interface_view.dart
More file actions
950 lines (858 loc) · 29.5 KB
/
chat_interface_view.dart
File metadata and controls
950 lines (858 loc) · 29.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:runanywhere/runanywhere.dart' as sdk;
import 'package:runanywhere/public/runanywhere_tool_calling.dart';
import 'package:runanywhere/public/types/tool_calling_types.dart';
import 'package:runanywhere_ai/core/design_system/app_colors.dart';
import 'package:runanywhere_ai/core/design_system/app_spacing.dart';
import 'package:runanywhere_ai/core/design_system/typography.dart';
import 'package:runanywhere_ai/core/services/conversation_store.dart';
import 'package:runanywhere_ai/core/utilities/constants.dart';
import 'package:runanywhere_ai/features/chat/tool_call_views.dart';
import 'package:runanywhere_ai/features/models/model_selection_sheet.dart';
import 'package:runanywhere_ai/features/models/model_status_components.dart';
import 'package:runanywhere_ai/features/models/model_types.dart';
import 'package:runanywhere_ai/features/settings/tool_settings_view_model.dart';
import 'package:runanywhere_ai/features/structured_output/structured_output_view.dart';
import 'package:shared_preferences/shared_preferences.dart';
/// ChatInterfaceView (mirroring iOS ChatInterfaceView.swift)
///
/// Full chat interface with streaming, analytics, and model status.
class ChatInterfaceView extends StatefulWidget {
const ChatInterfaceView({super.key});
@override
State<ChatInterfaceView> createState() => _ChatInterfaceViewState();
}
class _ChatInterfaceViewState extends State<ChatInterfaceView> {
final TextEditingController _controller = TextEditingController();
final ScrollController _scrollController = ScrollController();
final FocusNode _focusNode = FocusNode();
// Messages
final List<ChatMessage> _messages = [];
String _currentStreamingContent = '';
String _currentThinkingContent = '';
// State
bool _isGenerating = false;
bool _useStreaming = true;
String? _errorMessage;
bool _isLoading = false;
// Model state (from SDK - matches Swift pattern)
String? _loadedModelName;
sdk.InferenceFramework? _loadedFramework;
// Analytics
DateTime? _generationStartTime;
double? _timeToFirstToken;
int _tokenCount = 0;
@override
void initState() {
super.initState();
unawaited(_loadSettings());
unawaited(_syncModelState());
}
@override
void dispose() {
_controller.dispose();
_scrollController.dispose();
_focusNode.dispose();
super.dispose();
}
Future<void> _loadSettings() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_useStreaming = prefs.getBool(PreferenceKeys.useStreaming) ?? true;
});
}
/// Sync model state from SDK (matches Swift pattern)
Future<void> _syncModelState() async {
final model = await sdk.RunAnywhere.currentLLMModel();
if (mounted) {
setState(() {
_loadedModelName = model?.name;
_loadedFramework = model?.framework;
});
}
}
bool get _canSend =>
_controller.text.isNotEmpty &&
!_isGenerating &&
sdk.RunAnywhere.isModelLoaded;
Future<void> _sendMessage() async {
if (!_canSend) return;
final userMessage = _controller.text;
_controller.clear();
setState(() {
_messages.add(ChatMessage(
id: DateTime.now().millisecondsSinceEpoch.toString(),
role: MessageRole.user,
content: userMessage,
timestamp: DateTime.now(),
));
_isGenerating = true;
_errorMessage = null;
_currentStreamingContent = '';
_currentThinkingContent = '';
_generationStartTime = DateTime.now();
_timeToFirstToken = null;
_tokenCount = 0;
});
_scrollToBottom();
try {
// Get generation options from settings
final prefs = await SharedPreferences.getInstance();
final temperature =
prefs.getDouble(PreferenceKeys.defaultTemperature) ?? 0.7;
final maxTokens = prefs.getInt(PreferenceKeys.defaultMaxTokens) ?? 500;
final systemPromptRaw =
prefs.getString(PreferenceKeys.defaultSystemPrompt) ?? '';
final systemPrompt = systemPromptRaw.isNotEmpty ? systemPromptRaw : null;
debugPrint('[PARAMS] App _sendMessage: temperature=$temperature, maxTokens=$maxTokens, systemPrompt=${systemPrompt != null ? "set(${systemPrompt.length} chars)" : "nil"}');
// Check if tool calling is enabled and has registered tools
final toolSettings = ToolSettingsViewModel.shared;
final useToolCalling = toolSettings.toolCallingEnabled &&
toolSettings.registeredTools.isNotEmpty;
if (useToolCalling) {
await _generateWithToolCalling(userMessage, maxTokens, temperature);
} else {
// Streaming now runs in a background isolate, so no ANR concerns
final options = sdk.LLMGenerationOptions(
maxTokens: maxTokens,
temperature: temperature,
systemPrompt: systemPrompt,
);
if (_useStreaming) {
await _generateStreaming(userMessage, options);
} else {
await _generateNonStreaming(userMessage, options);
}
}
} catch (e) {
setState(() {
_errorMessage = 'Generation failed: $e';
_isGenerating = false;
});
}
}
/// Determines the optimal tool calling format based on the model name/ID.
/// Different models are trained on different tool calling formats.
/// Returns format name string (C++ is single source of truth for valid formats).
String _detectToolCallFormat(String? modelName) {
if (modelName == null) return ToolCallFormatName.defaultFormat;
final name = modelName.toLowerCase();
// LFM2-Tool models use Pythonic format: <|tool_call_start|>[func(args)]<|tool_call_end|>
if (name.contains('lfm2') && name.contains('tool')) {
return ToolCallFormatName.lfm2;
}
// Default JSON format for general-purpose models
return ToolCallFormatName.defaultFormat;
}
Future<void> _generateWithToolCalling(
String prompt,
int maxTokens,
double temperature,
) async {
// Capture model name from local state (matches Swift pattern)
final modelName = _loadedModelName;
// Auto-detect the tool calling format based on the loaded model
final format = _detectToolCallFormat(modelName);
debugPrint('Using tool calling with format: $format for model: ${modelName ?? "unknown"}');
// Add empty assistant message
final assistantMessage = ChatMessage(
id: DateTime.now().millisecondsSinceEpoch.toString(),
role: MessageRole.assistant,
content: '',
timestamp: DateTime.now(),
);
setState(() {
_messages.add(assistantMessage);
});
final messageIndex = _messages.length - 1;
try {
final result = await RunAnywhereTools.generateWithTools(
prompt,
options: ToolCallingOptions(
maxToolCalls: 3,
autoExecute: true,
formatName: format,
maxTokens: maxTokens,
temperature: temperature,
),
);
final totalTime = _generationStartTime != null
? DateTime.now().difference(_generationStartTime!).inMilliseconds /
1000.0
: 0.0;
// Create ToolCallInfo from the result if tools were called
ToolCallInfo? toolCallInfo;
debugPrint('📊 Tool calling result: toolCalls=${result.toolCalls.length}, toolResults=${result.toolResults.length}');
if (result.toolCalls.isNotEmpty) {
final lastCall = result.toolCalls.last;
final lastResult = result.toolResults.isNotEmpty
? result.toolResults.last
: null;
debugPrint('📊 Creating ToolCallInfo for: ${lastCall.toolName}');
toolCallInfo = ToolCallInfo(
toolName: lastCall.toolName,
arguments: _formatToolValueMapToJson(lastCall.arguments),
result: lastResult?.result != null
? _formatToolValueMapToJson(lastResult!.result!)
: null,
success: lastResult?.success ?? false,
error: lastResult?.error,
);
debugPrint('📊 ToolCallInfo created: ${toolCallInfo.toolName}, success=${toolCallInfo.success}');
} else {
debugPrint('📊 No tool calls in result - badge will NOT show');
}
final analytics = MessageAnalytics(
messageId: assistantMessage.id,
modelName: modelName,
totalGenerationTime: totalTime,
);
if (!mounted) return;
setState(() {
_messages[messageIndex] = _messages[messageIndex].copyWith(
content: result.text,
analytics: analytics,
toolCallInfo: toolCallInfo,
);
_isGenerating = false;
});
_scrollToBottom();
} catch (e) {
if (!mounted) return;
setState(() {
_messages.removeLast();
_errorMessage = 'Tool calling failed: $e';
_isGenerating = false;
});
}
}
String _formatToolValueMapToJson(Map<String, ToolValue> map) {
try {
final jsonMap = <String, dynamic>{};
for (final entry in map.entries) {
jsonMap[entry.key] = _toolValueToJson(entry.value);
}
const encoder = JsonEncoder.withIndent(' ');
return encoder.convert(jsonMap);
} catch (e) {
return map.toString();
}
}
dynamic _toolValueToJson(ToolValue value) {
if (value is StringToolValue) return value.value;
if (value is NumberToolValue) return value.value;
if (value is BoolToolValue) return value.value;
if (value is NullToolValue) return null;
if (value is ArrayToolValue) {
return value.value.map((v) => _toolValueToJson(v)).toList();
}
if (value is ObjectToolValue) {
final result = <String, dynamic>{};
for (final entry in value.value.entries) {
result[entry.key] = _toolValueToJson(entry.value);
}
return result;
}
return value.toString();
}
Future<void> _generateStreaming(
String prompt,
sdk.LLMGenerationOptions options,
) async {
// Capture model name from local state (matches Swift pattern)
final modelName = _loadedModelName;
// Add empty assistant message for streaming
final assistantMessage = ChatMessage(
id: DateTime.now().millisecondsSinceEpoch.toString(),
role: MessageRole.assistant,
content: '',
timestamp: DateTime.now(),
);
setState(() {
_messages.add(assistantMessage);
});
final messageIndex = _messages.length - 1;
final contentBuffer = StringBuffer();
try {
final streamingResult =
await sdk.RunAnywhere.generateStream(prompt, options: options);
await for (final token in streamingResult.stream) {
if (_timeToFirstToken == null && _generationStartTime != null) {
_timeToFirstToken =
DateTime.now().difference(_generationStartTime!).inMilliseconds /
1000.0;
}
_tokenCount++;
contentBuffer.write(token);
_currentStreamingContent = contentBuffer.toString();
setState(() {
_messages[messageIndex] = _messages[messageIndex].copyWith(
content: _currentStreamingContent,
);
});
_scrollToBottom();
}
// Calculate final analytics
final totalTime = _generationStartTime != null
? DateTime.now().difference(_generationStartTime!).inMilliseconds /
1000.0
: 0.0;
final analytics = MessageAnalytics(
messageId: assistantMessage.id,
modelName: modelName,
timeToFirstToken: _timeToFirstToken,
totalGenerationTime: totalTime,
outputTokens: _tokenCount,
tokensPerSecond: totalTime > 0 ? _tokenCount / totalTime : 0,
);
if (!mounted) return;
setState(() {
_messages[messageIndex] = _messages[messageIndex].copyWith(
thinkingContent: _currentThinkingContent.isNotEmpty
? _currentThinkingContent
: null,
analytics: analytics,
);
_isGenerating = false;
});
} catch (e) {
if (!mounted) return;
setState(() {
_messages.removeLast();
_errorMessage = 'Streaming failed: $e';
_isGenerating = false;
});
}
}
Future<void> _generateNonStreaming(
String prompt,
sdk.LLMGenerationOptions options,
) async {
// Capture model name from local state (matches Swift pattern)
final modelName = _loadedModelName;
try {
final result = await sdk.RunAnywhere.generate(prompt, options: options);
final totalTime = _generationStartTime != null
? DateTime.now().difference(_generationStartTime!).inMilliseconds /
1000.0
: 0.0;
// Extract token counts from SDK result
final outputTokens = result.tokensUsed;
final tokensPerSecond = result.tokensPerSecond;
final analytics = MessageAnalytics(
messageId: DateTime.now().millisecondsSinceEpoch.toString(),
modelName: modelName,
totalGenerationTime: totalTime,
outputTokens: outputTokens,
tokensPerSecond: tokensPerSecond,
);
setState(() {
_messages.add(ChatMessage(
id: DateTime.now().millisecondsSinceEpoch.toString(),
role: MessageRole.assistant,
content: result.text,
thinkingContent: result.thinkingContent,
timestamp: DateTime.now(),
analytics: analytics,
));
_isGenerating = false;
});
_scrollToBottom();
} catch (e) {
setState(() {
_errorMessage = 'Generation failed: $e';
_isGenerating = false;
});
}
}
void _scrollToBottom() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scrollController.hasClients) {
unawaited(_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: AppLayout.animationFast,
curve: Curves.easeOut,
));
}
});
}
void _clearChat() {
setState(() {
_messages.clear();
_errorMessage = null;
_currentStreamingContent = '';
_currentThinkingContent = '';
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Chat'),
actions: [
IconButton(
icon: const Icon(Icons.data_object),
onPressed: () {
Navigator.of(context).push<void>(
MaterialPageRoute<void>(
builder: (context) => const StructuredOutputView(),
),
);
},
tooltip: 'Structured Output Examples',
),
if (_messages.isNotEmpty)
IconButton(
icon: const Icon(Icons.delete_outline),
onPressed: _clearChat,
tooltip: 'Clear chat',
),
],
),
body: Column(
children: [
// Model status banner (uses local state from SDK)
_buildModelStatusBanner(),
// Messages area - tap to dismiss keyboard
Expanded(
child: GestureDetector(
onTap: () => FocusScope.of(context).unfocus(),
behavior: HitTestBehavior.opaque,
child: _buildMessagesArea(),
),
),
// Error banner
if (_errorMessage != null) _buildErrorBanner(),
// Typing indicator
if (_isGenerating) _buildTypingIndicator(),
// Input area
_buildInputArea(),
],
),
);
}
void _showModelSelectionSheet() {
unawaited(showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
useSafeArea: true,
builder: (sheetContext) => ModelSelectionSheet(
context: ModelSelectionContext.llm,
onModelSelected: (model) async {
// Model loaded by ModelSelectionSheet via SDK
// Sync local state after model load
await _syncModelState();
},
),
));
}
/// Map SDK InferenceFramework enum to app framework enum
LLMFramework _mapInferenceFramework(sdk.InferenceFramework? framework) {
if (framework == null) return LLMFramework.llamaCpp;
switch (framework) {
case sdk.InferenceFramework.llamaCpp:
return LLMFramework.llamaCpp;
case sdk.InferenceFramework.foundationModels:
return LLMFramework.foundationModels;
case sdk.InferenceFramework.onnx:
return LLMFramework.onnxRuntime;
case sdk.InferenceFramework.systemTTS:
return LLMFramework.systemTTS;
default:
return LLMFramework.llamaCpp;
}
}
Widget _buildModelStatusBanner() {
// Use local state synced from SDK (matches Swift pattern)
LLMFramework? framework;
if (sdk.RunAnywhere.isModelLoaded && _loadedFramework != null) {
framework = _mapInferenceFramework(_loadedFramework);
}
return Padding(
padding: const EdgeInsets.all(AppSpacing.large),
child: ModelStatusBanner(
framework: framework,
modelName: _loadedModelName,
isLoading: _isLoading,
onSelectModel: _showModelSelectionSheet,
),
);
}
Widget _buildMessagesArea() {
if (_messages.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.psychology,
size: AppSpacing.iconXXLarge,
color: AppColors.textSecondary(context),
),
const SizedBox(height: AppSpacing.large),
Text(
'Start a conversation',
style: AppTypography.title2(context),
),
const SizedBox(height: AppSpacing.smallMedium),
Text(
'Type a message to begin',
style: AppTypography.subheadline(context).copyWith(
color: AppColors.textSecondary(context),
),
),
],
),
);
}
return ListView.builder(
controller: _scrollController,
padding: const EdgeInsets.all(AppSpacing.large),
itemCount: _messages.length,
itemBuilder: (context, index) {
final message = _messages[index];
return _MessageBubble(message: message);
},
);
}
Widget _buildErrorBanner() {
return Container(
margin: const EdgeInsets.all(AppSpacing.large),
padding: const EdgeInsets.all(AppSpacing.mediumLarge),
decoration: BoxDecoration(
color: AppColors.badgeRed,
borderRadius: BorderRadius.circular(AppSpacing.cornerRadiusRegular),
),
child: Row(
children: [
const Icon(Icons.error, color: Colors.red),
const SizedBox(width: AppSpacing.smallMedium),
Expanded(
child: Text(
_errorMessage!,
style: AppTypography.subheadline(context),
),
),
IconButton(
icon: const Icon(Icons.close),
onPressed: () {
setState(() {
_errorMessage = null;
});
},
),
],
),
);
}
Widget _buildTypingIndicator() {
return const TypingIndicatorView(
statusText: 'AI is thinking...',
);
}
Widget _buildInputArea() {
final toolSettings = ToolSettingsViewModel.shared;
final showToolBadge = toolSettings.toolCallingEnabled &&
toolSettings.registeredTools.isNotEmpty;
return Container(
padding: const EdgeInsets.all(AppSpacing.large),
decoration: BoxDecoration(
color: AppColors.backgroundPrimary(context),
boxShadow: [
BoxShadow(
color: AppColors.shadowLight,
blurRadius: AppSpacing.shadowLarge,
offset: const Offset(0, -2),
),
],
),
child: SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Tool calling badge (matches iOS)
if (showToolBadge) ...[
ToolCallingBadge(toolCount: toolSettings.registeredTools.length),
const SizedBox(height: AppSpacing.smallMedium),
],
Row(
children: [
Expanded(
child: TextField(
controller: _controller,
focusNode: _focusNode,
maxLines: 4,
minLines: 1,
textInputAction: TextInputAction.send,
decoration: InputDecoration(
hintText: 'Type a message...',
border: OutlineInputBorder(
borderRadius:
BorderRadius.circular(AppSpacing.cornerRadiusBubble),
),
contentPadding: const EdgeInsets.symmetric(
horizontal: AppSpacing.large,
vertical: AppSpacing.mediumLarge,
),
),
onSubmitted: (_) => _sendMessage(),
onChanged: (_) => setState(() {}),
),
),
const SizedBox(width: AppSpacing.smallMedium),
IconButton.filled(
onPressed: _canSend ? _sendMessage : null,
icon: _isGenerating
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
color: Colors.white,
strokeWidth: 2,
),
)
: const Icon(Icons.arrow_upward),
),
],
),
],
),
),
);
}
}
/// Message role enum
enum MessageRole { system, user, assistant }
/// Chat message model
class ChatMessage {
final String id;
final MessageRole role;
final String content;
final String? thinkingContent;
final DateTime timestamp;
final MessageAnalytics? analytics;
final ToolCallInfo? toolCallInfo;
const ChatMessage({
required this.id,
required this.role,
required this.content,
this.thinkingContent,
required this.timestamp,
this.analytics,
this.toolCallInfo,
});
ChatMessage copyWith({
String? id,
MessageRole? role,
String? content,
String? thinkingContent,
DateTime? timestamp,
MessageAnalytics? analytics,
ToolCallInfo? toolCallInfo,
}) {
return ChatMessage(
id: id ?? this.id,
role: role ?? this.role,
content: content ?? this.content,
thinkingContent: thinkingContent ?? this.thinkingContent,
timestamp: timestamp ?? this.timestamp,
analytics: analytics ?? this.analytics,
toolCallInfo: toolCallInfo ?? this.toolCallInfo,
);
}
}
/// Message bubble widget
class _MessageBubble extends StatefulWidget {
final ChatMessage message;
const _MessageBubble({required this.message});
@override
State<_MessageBubble> createState() => _MessageBubbleState();
}
class _MessageBubbleState extends State<_MessageBubble> {
bool _showThinking = false;
bool _showToolCallSheet = false;
@override
Widget build(BuildContext context) {
final isUser = widget.message.role == MessageRole.user;
return Align(
alignment: isUser ? Alignment.centerRight : Alignment.centerLeft,
child: Container(
margin: const EdgeInsets.only(bottom: AppSpacing.mediumLarge),
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width * 0.75,
),
child: Column(
crossAxisAlignment:
isUser ? CrossAxisAlignment.end : CrossAxisAlignment.start,
children: [
// Tool call indicator (if present, matches iOS toolCallSection)
if (widget.message.toolCallInfo != null && !isUser) ...[
ToolCallIndicator(
toolCallInfo: widget.message.toolCallInfo!,
onTap: () => _showToolCallDetails(context),
),
const SizedBox(height: AppSpacing.smallMedium),
],
// Thinking section (if present)
if (widget.message.thinkingContent != null &&
widget.message.thinkingContent!.isNotEmpty)
_buildThinkingSection(),
// Main message bubble
Container(
padding: const EdgeInsets.all(AppSpacing.mediumLarge),
decoration: BoxDecoration(
gradient: isUser
? LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
AppColors.userBubbleGradientStart,
AppColors.userBubbleGradientEnd,
],
)
: null,
color: isUser ? null : AppColors.backgroundGray5(context),
borderRadius:
BorderRadius.circular(AppSpacing.cornerRadiusBubble),
boxShadow: [
BoxShadow(
color: AppColors.shadowLight,
blurRadius: AppSpacing.shadowSmall,
offset: const Offset(0, 1),
),
],
),
child: isUser
? Text(
widget.message.content,
style: AppTypography.body(context).copyWith(
color: AppColors.textWhite,
),
)
: MarkdownBody(
data: widget.message.content,
styleSheet: MarkdownStyleSheet(
p: AppTypography.body(context),
code: AppTypography.monospaced.copyWith(
backgroundColor: AppColors.backgroundGray6(context),
),
),
),
),
// Analytics summary (if present)
if (widget.message.analytics != null && !isUser)
_buildAnalyticsSummary(),
],
),
),
);
}
void _showToolCallDetails(BuildContext context) {
showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (context) => DraggableScrollableSheet(
initialChildSize: 0.6,
minChildSize: 0.3,
maxChildSize: 0.9,
builder: (context, scrollController) =>
ToolCallDetailSheet(toolCallInfo: widget.message.toolCallInfo!),
),
);
}
Widget _buildThinkingSection() {
return Container(
margin: const EdgeInsets.only(bottom: AppSpacing.smallMedium),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
GestureDetector(
onTap: () {
setState(() {
_showThinking = !_showThinking;
});
},
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
Icons.lightbulb,
size: AppSpacing.iconRegular,
color: AppColors.primaryPurple,
),
const SizedBox(width: AppSpacing.xSmall),
Text(
_showThinking ? 'Hide reasoning' : 'Show reasoning',
style: AppTypography.caption(context).copyWith(
color: AppColors.primaryPurple,
),
),
Icon(
_showThinking
? Icons.keyboard_arrow_up
: Icons.keyboard_arrow_down,
size: AppSpacing.iconRegular,
color: AppColors.primaryPurple,
),
],
),
),
if (_showThinking)
Container(
margin: const EdgeInsets.only(top: AppSpacing.smallMedium),
padding: const EdgeInsets.all(AppSpacing.mediumLarge),
decoration: BoxDecoration(
color: AppColors.modelThinkingBg,
borderRadius:
BorderRadius.circular(AppSpacing.cornerRadiusRegular),
),
child: Text(
widget.message.thinkingContent!,
style: AppTypography.caption(context),
),
),
],
),
);
}
Widget _buildAnalyticsSummary() {
final analytics = widget.message.analytics!;
return Padding(
padding: const EdgeInsets.only(top: AppSpacing.xSmall),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (analytics.totalGenerationTime != null)
Text(
'${analytics.totalGenerationTime!.toStringAsFixed(1)}s',
style: AppTypography.caption(context).copyWith(
color: AppColors.textSecondary(context),
),
),
if (analytics.tokensPerSecond != null) ...[
const SizedBox(width: AppSpacing.smallMedium),
Text(
'${analytics.tokensPerSecond!.toStringAsFixed(1)} tok/s',
style: AppTypography.caption(context).copyWith(
color: AppColors.textSecondary(context),
),
),
],
if (analytics.wasThinkingMode) ...[
const SizedBox(width: AppSpacing.smallMedium),
const Icon(
Icons.lightbulb,
size: 12,
color: AppColors.primaryPurple,
),
],
],
),
);
}
}