♻️ Refactor the thought insight to support new API

This commit is contained in:
2025-11-15 16:59:22 +08:00
parent ea8e7ead2d
commit 645a6dca93
8 changed files with 1397 additions and 124 deletions

View File

@@ -38,6 +38,31 @@ class ThinkingChunkTypeConverter
int toJson(ThinkingChunkType object) => object.value; int toJson(ThinkingChunkType object) => object.value;
} }
enum ThinkingMessagePartType {
text(0),
functionCall(1),
functionResult(2);
const ThinkingMessagePartType(this.value);
final int value;
static ThinkingMessagePartType fromValue(int value) {
return values.firstWhere((e) => e.value == value, orElse: () => text);
}
}
class ThinkingMessagePartTypeConverter
implements JsonConverter<ThinkingMessagePartType, int> {
const ThinkingMessagePartTypeConverter();
@override
ThinkingMessagePartType fromJson(int json) =>
ThinkingMessagePartType.fromValue(json);
@override
int toJson(ThinkingMessagePartType object) => object.value;
}
@freezed @freezed
sealed class StreamThinkingRequest with _$StreamThinkingRequest { sealed class StreamThinkingRequest with _$StreamThinkingRequest {
const factory StreamThinkingRequest({ const factory StreamThinkingRequest({
@@ -77,6 +102,43 @@ sealed class SnThinkingChunk with _$SnThinkingChunk {
_$SnThinkingChunkFromJson(json); _$SnThinkingChunkFromJson(json);
} }
@freezed
sealed class SnFunctionCall with _$SnFunctionCall {
const factory SnFunctionCall({
required String id,
required String name,
required String arguments,
}) = _SnFunctionCall;
factory SnFunctionCall.fromJson(Map<String, dynamic> json) =>
_$SnFunctionCallFromJson(json);
}
@freezed
sealed class SnFunctionResult with _$SnFunctionResult {
const factory SnFunctionResult({
required String callId,
required dynamic result,
required bool isError,
}) = _SnFunctionResult;
factory SnFunctionResult.fromJson(Map<String, dynamic> json) =>
_$SnFunctionResultFromJson(json);
}
@freezed
sealed class SnThinkingMessagePart with _$SnThinkingMessagePart {
const factory SnThinkingMessagePart({
@ThinkingMessagePartTypeConverter() required ThinkingMessagePartType type,
String? text,
SnFunctionCall? functionCall,
SnFunctionResult? functionResult,
}) = _SnThinkingMessagePart;
factory SnThinkingMessagePart.fromJson(Map<String, dynamic> json) =>
_$SnThinkingMessagePartFromJson(json);
}
@freezed @freezed
sealed class SnThinkingSequence with _$SnThinkingSequence { sealed class SnThinkingSequence with _$SnThinkingSequence {
const factory SnThinkingSequence({ const factory SnThinkingSequence({
@@ -98,9 +160,8 @@ sealed class SnThinkingSequence with _$SnThinkingSequence {
sealed class SnThinkingThought with _$SnThinkingThought { sealed class SnThinkingThought with _$SnThinkingThought {
const factory SnThinkingThought({ const factory SnThinkingThought({
required String id, required String id,
String? content, @Default([]) List<SnThinkingMessagePart> parts,
@Default([]) List<SnCloudFile> files, @Default([]) List<SnCloudFile> files,
@Default([]) List<SnThinkingChunk> chunks,
@ThinkingThoughtRoleConverter() required ThinkingThoughtRole role, @ThinkingThoughtRoleConverter() required ThinkingThoughtRole role,
int? tokenCount, int? tokenCount,
String? modelName, String? modelName,

File diff suppressed because it is too large Load Diff

View File

@@ -50,6 +50,64 @@ Map<String, dynamic> _$SnThinkingChunkToJson(_SnThinkingChunk instance) =>
'data': instance.data, 'data': instance.data,
}; };
_SnFunctionCall _$SnFunctionCallFromJson(Map<String, dynamic> json) =>
_SnFunctionCall(
id: json['id'] as String,
name: json['name'] as String,
arguments: json['arguments'] as String,
);
Map<String, dynamic> _$SnFunctionCallToJson(_SnFunctionCall instance) =>
<String, dynamic>{
'id': instance.id,
'name': instance.name,
'arguments': instance.arguments,
};
_SnFunctionResult _$SnFunctionResultFromJson(Map<String, dynamic> json) =>
_SnFunctionResult(
callId: json['call_id'] as String,
result: json['result'],
isError: json['is_error'] as bool,
);
Map<String, dynamic> _$SnFunctionResultToJson(_SnFunctionResult instance) =>
<String, dynamic>{
'call_id': instance.callId,
'result': instance.result,
'is_error': instance.isError,
};
_SnThinkingMessagePart _$SnThinkingMessagePartFromJson(
Map<String, dynamic> json,
) => _SnThinkingMessagePart(
type: const ThinkingMessagePartTypeConverter().fromJson(
(json['type'] as num).toInt(),
),
text: json['text'] as String?,
functionCall:
json['function_call'] == null
? null
: SnFunctionCall.fromJson(
json['function_call'] as Map<String, dynamic>,
),
functionResult:
json['function_result'] == null
? null
: SnFunctionResult.fromJson(
json['function_result'] as Map<String, dynamic>,
),
);
Map<String, dynamic> _$SnThinkingMessagePartToJson(
_SnThinkingMessagePart instance,
) => <String, dynamic>{
'type': const ThinkingMessagePartTypeConverter().toJson(instance.type),
'text': instance.text,
'function_call': instance.functionCall?.toJson(),
'function_result': instance.functionResult?.toJson(),
};
_SnThinkingSequence _$SnThinkingSequenceFromJson(Map<String, dynamic> json) => _SnThinkingSequence _$SnThinkingSequenceFromJson(Map<String, dynamic> json) =>
_SnThinkingSequence( _SnThinkingSequence(
id: json['id'] as String, id: json['id'] as String,
@@ -80,17 +138,19 @@ Map<String, dynamic> _$SnThinkingSequenceToJson(_SnThinkingSequence instance) =>
_SnThinkingThought _$SnThinkingThoughtFromJson(Map<String, dynamic> json) => _SnThinkingThought _$SnThinkingThoughtFromJson(Map<String, dynamic> json) =>
_SnThinkingThought( _SnThinkingThought(
id: json['id'] as String, id: json['id'] as String,
content: json['content'] as String?, parts:
(json['parts'] as List<dynamic>?)
?.map(
(e) =>
SnThinkingMessagePart.fromJson(e as Map<String, dynamic>),
)
.toList() ??
const [],
files: files:
(json['files'] as List<dynamic>?) (json['files'] as List<dynamic>?)
?.map((e) => SnCloudFile.fromJson(e as Map<String, dynamic>)) ?.map((e) => SnCloudFile.fromJson(e as Map<String, dynamic>))
.toList() ?? .toList() ??
const [], const [],
chunks:
(json['chunks'] as List<dynamic>?)
?.map((e) => SnThinkingChunk.fromJson(e as Map<String, dynamic>))
.toList() ??
const [],
role: const ThinkingThoughtRoleConverter().fromJson( role: const ThinkingThoughtRoleConverter().fromJson(
(json['role'] as num).toInt(), (json['role'] as num).toInt(),
), ),
@@ -114,9 +174,8 @@ _SnThinkingThought _$SnThinkingThoughtFromJson(Map<String, dynamic> json) =>
Map<String, dynamic> _$SnThinkingThoughtToJson(_SnThinkingThought instance) => Map<String, dynamic> _$SnThinkingThoughtToJson(_SnThinkingThought instance) =>
<String, dynamic>{ <String, dynamic>{
'id': instance.id, 'id': instance.id,
'content': instance.content, 'parts': instance.parts.map((e) => e.toJson()).toList(),
'files': instance.files.map((e) => e.toJson()).toList(), 'files': instance.files.map((e) => e.toJson()).toList(),
'chunks': instance.chunks.map((e) => e.toJson()).toList(),
'role': const ThinkingThoughtRoleConverter().toJson(instance.role), 'role': const ThinkingThoughtRoleConverter().toJson(instance.role),
'token_count': instance.tokenCount, 'token_count': instance.tokenCount,
'model_name': instance.modelName, 'model_name': instance.modelName,

View File

@@ -10,7 +10,6 @@ import "package:hooks_riverpod/hooks_riverpod.dart";
import "package:island/models/thought.dart"; import "package:island/models/thought.dart";
import "package:island/pods/network.dart"; import "package:island/pods/network.dart";
import "package:island/pods/userinfo.dart"; import "package:island/pods/userinfo.dart";
import "package:island/widgets/alert.dart";
import "package:island/widgets/app_scaffold.dart"; import "package:island/widgets/app_scaffold.dart";
import "package:island/widgets/response.dart"; import "package:island/widgets/response.dart";
import "package:island/widgets/thought/thought_sequence_list.dart"; import "package:island/widgets/thought/thought_sequence_list.dart";
@@ -52,8 +51,7 @@ class ThoughtScreen extends HookConsumerWidget {
final messageController = useTextEditingController(); final messageController = useTextEditingController();
final scrollController = useScrollController(); final scrollController = useScrollController();
final isStreaming = useState(false); final isStreaming = useState(false);
final streamingText = useState<String>(''); final streamingParts = useState<List<SnThinkingMessagePart>>([]);
final functionCalls = useState<List<String>>([]);
final reasoningChunks = useState<List<String>>([]); final reasoningChunks = useState<List<String>>([]);
final listController = useMemoized(() => ListController(), []); final listController = useMemoized(() => ListController(), []);
@@ -114,7 +112,12 @@ class ThoughtScreen extends HookConsumerWidget {
final now = DateTime.now(); final now = DateTime.now();
final userThought = SnThinkingThought( final userThought = SnThinkingThought(
id: 'user-${DateTime.now().millisecondsSinceEpoch}', id: 'user-${DateTime.now().millisecondsSinceEpoch}',
content: userMessage, parts: [
SnThinkingMessagePart(
type: ThinkingMessagePartType.text,
text: userMessage,
),
],
files: [], files: [],
role: ThinkingThoughtRole.user, role: ThinkingThoughtRole.user,
sequenceId: selectedSequenceId.value ?? '', sequenceId: selectedSequenceId.value ?? '',
@@ -148,8 +151,7 @@ class ThoughtScreen extends HookConsumerWidget {
try { try {
isStreaming.value = true; isStreaming.value = true;
streamingText.value = ''; streamingParts.value = [];
functionCalls.value = [];
reasoningChunks.value = []; reasoningChunks.value = [];
final apiClient = ref.read(apiClientProvider); final apiClient = ref.read(apiClientProvider);
@@ -183,11 +185,39 @@ class ThoughtScreen extends HookConsumerWidget {
final type = event['type']; final type = event['type'];
final eventData = event['data']; final eventData = event['data'];
if (type == 'text') { if (type == 'text') {
streamingText.value += eventData; if (streamingParts.value.isNotEmpty &&
streamingParts.value.last.type ==
ThinkingMessagePartType.text) {
final last = streamingParts.value.last;
final newParts = [...streamingParts.value];
newParts[newParts.length - 1] = last.copyWith(
text: (last.text ?? '') + eventData,
);
streamingParts.value = newParts;
} else {
streamingParts.value = [
...streamingParts.value,
SnThinkingMessagePart(
type: ThinkingMessagePartType.text,
text: eventData,
),
];
}
} else if (type == 'function_call') { } else if (type == 'function_call') {
functionCalls.value = [ streamingParts.value = [
...functionCalls.value, ...streamingParts.value,
JsonEncoder.withIndent(' ').convert(eventData), SnThinkingMessagePart(
type: ThinkingMessagePartType.functionCall,
functionCall: SnFunctionCall.fromJson(eventData),
),
];
} else if (type == 'function_result') {
streamingParts.value = [
...streamingParts.value,
SnThinkingMessagePart(
type: ThinkingMessagePartType.functionResult,
functionResult: SnFunctionResult.fromJson(eventData),
),
]; ];
} else if (type == 'reasoning') { } else if (type == 'reasoning') {
reasoningChunks.value = [ reasoningChunks.value = [
@@ -218,16 +248,61 @@ class ThoughtScreen extends HookConsumerWidget {
onDone: () { onDone: () {
if (isStreaming.value) { if (isStreaming.value) {
isStreaming.value = false; isStreaming.value = false;
showErrorAlert('thoughtParseError'.tr()); // Add error thought to the list for incomplete response
final now = DateTime.now();
final errorThought = SnThinkingThought(
id: 'error-${DateTime.now().millisecondsSinceEpoch}',
parts: [
SnThinkingMessagePart(
type: ThinkingMessagePartType.text,
text: 'Error: ${'thoughtParseError'.tr()}',
),
],
files: [],
role: ThinkingThoughtRole.assistant,
sequenceId: selectedSequenceId.value ?? '',
createdAt: now,
updatedAt: now,
sequence: SnThinkingSequence(
id: selectedSequenceId.value ?? '',
accountId: '',
createdAt: now,
updatedAt: now,
),
);
localThoughts.value = [errorThought, ...localThoughts.value];
} }
}, },
onError: (error) { onError: (error) {
isStreaming.value = false; isStreaming.value = false;
if (error is DioException && error.response?.data is ResponseBody) {
showErrorAlert('toughtParseError'.tr()); // Add error thought to the list
} else { final now = DateTime.now();
showErrorAlert(error); final errorMessage =
} error is DioException && error.response?.data is ResponseBody
? 'toughtParseError'.tr()
: error.toString();
final errorThought = SnThinkingThought(
id: 'error-${DateTime.now().millisecondsSinceEpoch}',
parts: [
SnThinkingMessagePart(
type: ThinkingMessagePartType.text,
text: 'Error: $errorMessage',
),
],
files: [],
role: ThinkingThoughtRole.assistant,
sequenceId: selectedSequenceId.value ?? '',
createdAt: now,
updatedAt: now,
sequence: SnThinkingSequence(
id: selectedSequenceId.value ?? '',
accountId: '',
createdAt: now,
updatedAt: now,
),
);
localThoughts.value = [errorThought, ...localThoughts.value];
}, },
); );
@@ -235,7 +310,32 @@ class ThoughtScreen extends HookConsumerWidget {
FocusManager.instance.primaryFocus?.unfocus(); FocusManager.instance.primaryFocus?.unfocus();
} catch (error) { } catch (error) {
isStreaming.value = false; isStreaming.value = false;
showErrorAlert(error);
// Add error thought to the list for initial request errors
final now = DateTime.now();
final userInfo = ref.read(userInfoProvider);
final errorMessage = error.toString();
final errorThought = SnThinkingThought(
id: 'error-${DateTime.now().millisecondsSinceEpoch}',
parts: [
SnThinkingMessagePart(
type: ThinkingMessagePartType.text,
text: 'Error: $errorMessage',
),
],
files: [],
role: ThinkingThoughtRole.assistant,
sequenceId: selectedSequenceId.value ?? '',
createdAt: now,
updatedAt: now,
sequence: SnThinkingSequence(
id: selectedSequenceId.value ?? '',
accountId: userInfo.value!.id,
createdAt: now,
updatedAt: now,
),
);
localThoughts.value = [errorThought, ...localThoughts.value];
} }
} }
@@ -302,11 +402,36 @@ class ThoughtScreen extends HookConsumerWidget {
(isStreaming.value ? 1 : 0), (isStreaming.value ? 1 : 0),
itemBuilder: (context, index) { itemBuilder: (context, index) {
if (isStreaming.value && index == 0) { if (isStreaming.value && index == 0) {
final streamingText = streamingParts.value
.where(
(p) =>
p.type ==
ThinkingMessagePartType.text,
)
.map((p) => p.text ?? '')
.join('');
final streamingFunctionCalls =
streamingParts.value
.where(
(p) =>
p.type ==
ThinkingMessagePartType
.functionCall,
)
.map(
(p) => JsonEncoder.withIndent(
' ',
).convert(
p.functionCall?.toJson() ?? {},
),
)
.toList();
return ThoughtItem( return ThoughtItem(
isStreaming: true, isStreaming: true,
streamingText: streamingText.value, streamingText: streamingText,
reasoningChunks: reasoningChunks.value, reasoningChunks: reasoningChunks.value,
streamingFunctionCalls: functionCalls.value, streamingFunctionCalls:
streamingFunctionCalls,
); );
} }
final thoughtIndex = final thoughtIndex =

View File

@@ -8,7 +8,6 @@ import "package:hooks_riverpod/hooks_riverpod.dart";
import "package:island/models/thought.dart"; import "package:island/models/thought.dart";
import "package:island/pods/network.dart"; import "package:island/pods/network.dart";
import "package:island/pods/userinfo.dart"; import "package:island/pods/userinfo.dart";
import "package:island/widgets/alert.dart";
import "package:island/widgets/content/sheet.dart"; import "package:island/widgets/content/sheet.dart";
import "package:island/widgets/thought/thought_shared.dart"; import "package:island/widgets/thought/thought_shared.dart";
import "package:super_sliver_list/super_sliver_list.dart"; import "package:super_sliver_list/super_sliver_list.dart";
@@ -49,8 +48,7 @@ class ThoughtSheet extends HookConsumerWidget {
final messageController = useTextEditingController(); final messageController = useTextEditingController();
final scrollController = useScrollController(); final scrollController = useScrollController();
final isStreaming = useState(false); final isStreaming = useState(false);
final streamingText = useState<String>(''); final streamingParts = useState<List<SnThinkingMessagePart>>([]);
final functionCalls = useState<List<String>>([]);
final reasoningChunks = useState<List<String>>([]); final reasoningChunks = useState<List<String>>([]);
final listController = useMemoized(() => ListController(), []); final listController = useMemoized(() => ListController(), []);
@@ -96,7 +94,12 @@ class ThoughtSheet extends HookConsumerWidget {
final now = DateTime.now(); final now = DateTime.now();
final userThought = SnThinkingThought( final userThought = SnThinkingThought(
id: 'user-${DateTime.now().millisecondsSinceEpoch}', id: 'user-${DateTime.now().millisecondsSinceEpoch}',
content: userMessage, parts: [
SnThinkingMessagePart(
type: ThinkingMessagePartType.text,
text: userMessage,
),
],
files: [], files: [],
role: ThinkingThoughtRole.user, role: ThinkingThoughtRole.user,
sequenceId: sequenceId.value ?? '', sequenceId: sequenceId.value ?? '',
@@ -121,8 +124,7 @@ class ThoughtSheet extends HookConsumerWidget {
try { try {
isStreaming.value = true; isStreaming.value = true;
streamingText.value = ''; streamingParts.value = [];
functionCalls.value = [];
reasoningChunks.value = []; reasoningChunks.value = [];
final apiClient = ref.read(apiClientProvider); final apiClient = ref.read(apiClientProvider);
@@ -156,11 +158,39 @@ class ThoughtSheet extends HookConsumerWidget {
final type = event['type']; final type = event['type'];
final eventData = event['data']; final eventData = event['data'];
if (type == 'text') { if (type == 'text') {
streamingText.value += eventData; if (streamingParts.value.isNotEmpty &&
streamingParts.value.last.type ==
ThinkingMessagePartType.text) {
final last = streamingParts.value.last;
final newParts = [...streamingParts.value];
newParts[newParts.length - 1] = last.copyWith(
text: (last.text ?? '') + eventData,
);
streamingParts.value = newParts;
} else {
streamingParts.value = [
...streamingParts.value,
SnThinkingMessagePart(
type: ThinkingMessagePartType.text,
text: eventData,
),
];
}
} else if (type == 'function_call') { } else if (type == 'function_call') {
functionCalls.value = [ streamingParts.value = [
...functionCalls.value, ...streamingParts.value,
JsonEncoder.withIndent(' ').convert(eventData), SnThinkingMessagePart(
type: ThinkingMessagePartType.functionCall,
functionCall: SnFunctionCall.fromJson(eventData),
),
];
} else if (type == 'function_result') {
streamingParts.value = [
...streamingParts.value,
SnThinkingMessagePart(
type: ThinkingMessagePartType.functionResult,
functionResult: SnFunctionResult.fromJson(eventData),
),
]; ];
} else if (type == 'reasoning') { } else if (type == 'reasoning') {
reasoningChunks.value = [ reasoningChunks.value = [
@@ -191,16 +221,63 @@ class ThoughtSheet extends HookConsumerWidget {
onDone: () { onDone: () {
if (isStreaming.value) { if (isStreaming.value) {
isStreaming.value = false; isStreaming.value = false;
showErrorAlert('thoughtParseError'.tr()); // Add error thought to the list for incomplete response
final userInfo = ref.read(userInfoProvider);
final now = DateTime.now();
final errorThought = SnThinkingThought(
id: 'error-${DateTime.now().millisecondsSinceEpoch}',
parts: [
SnThinkingMessagePart(
type: ThinkingMessagePartType.text,
text: 'Error: ${'thoughtParseError'.tr()}',
),
],
files: [],
role: ThinkingThoughtRole.assistant,
sequenceId: sequenceId.value ?? '',
createdAt: now,
updatedAt: now,
sequence: SnThinkingSequence(
id: sequenceId.value ?? '',
accountId: userInfo.value!.id,
createdAt: now,
updatedAt: now,
),
);
localThoughts.value = [errorThought, ...localThoughts.value];
} }
}, },
onError: (error) { onError: (error) {
isStreaming.value = false; isStreaming.value = false;
if (error is DioException && error.response?.data is ResponseBody) {
showErrorAlert('toughtParseError'.tr()); // Add error thought to the list
} else { final userInfo = ref.read(userInfoProvider);
showErrorAlert(error); final now = DateTime.now();
} final errorMessage =
error is DioException && error.response?.data is ResponseBody
? 'toughtParseError'.tr()
: error.toString();
final errorThought = SnThinkingThought(
id: 'error-${DateTime.now().millisecondsSinceEpoch}',
parts: [
SnThinkingMessagePart(
type: ThinkingMessagePartType.text,
text: 'Error: $errorMessage',
),
],
files: [],
role: ThinkingThoughtRole.assistant,
sequenceId: sequenceId.value ?? '',
createdAt: now,
updatedAt: now,
sequence: SnThinkingSequence(
id: sequenceId.value ?? '',
accountId: userInfo.value!.id,
createdAt: now,
updatedAt: now,
),
);
localThoughts.value = [errorThought, ...localThoughts.value];
}, },
); );
@@ -208,7 +285,32 @@ class ThoughtSheet extends HookConsumerWidget {
FocusManager.instance.primaryFocus?.unfocus(); FocusManager.instance.primaryFocus?.unfocus();
} catch (error) { } catch (error) {
isStreaming.value = false; isStreaming.value = false;
showErrorAlert(error);
// Add error thought to the list for initial request errors
final userInfo = ref.read(userInfoProvider);
final now = DateTime.now();
final errorMessage = error.toString();
final errorThought = SnThinkingThought(
id: 'error-${DateTime.now().millisecondsSinceEpoch}',
parts: [
SnThinkingMessagePart(
type: ThinkingMessagePartType.text,
text: 'Error: $errorMessage',
),
],
files: [],
role: ThinkingThoughtRole.assistant,
sequenceId: sequenceId.value ?? '',
createdAt: now,
updatedAt: now,
sequence: SnThinkingSequence(
id: sequenceId.value ?? '',
accountId: userInfo.value!.id,
createdAt: now,
updatedAt: now,
),
);
localThoughts.value = [errorThought, ...localThoughts.value];
} }
} }
@@ -238,11 +340,30 @@ class ThoughtSheet extends HookConsumerWidget {
(isStreaming.value ? 1 : 0), (isStreaming.value ? 1 : 0),
itemBuilder: (context, index) { itemBuilder: (context, index) {
if (isStreaming.value && index == 0) { if (isStreaming.value && index == 0) {
final streamingText = streamingParts.value
.where(
(p) => p.type == ThinkingMessagePartType.text,
)
.map((p) => p.text ?? '')
.join('');
final streamingFunctionCalls =
streamingParts.value
.where(
(p) =>
p.type ==
ThinkingMessagePartType.functionCall,
)
.map(
(p) => JsonEncoder.withIndent(
' ',
).convert(p.functionCall?.toJson() ?? {}),
)
.toList();
return ThoughtItem( return ThoughtItem(
isStreaming: true, isStreaming: true,
streamingText: streamingText.value, streamingText: streamingText,
reasoningChunks: reasoningChunks.value, reasoningChunks: reasoningChunks.value,
streamingFunctionCalls: functionCalls.value, streamingFunctionCalls: streamingFunctionCalls,
); );
} }
final thoughtIndex = final thoughtIndex =

View File

@@ -30,9 +30,9 @@ class _FunctionCallsSectionState extends State<FunctionCallsSection> {
if (widget.isStreaming) { if (widget.isStreaming) {
return widget.streamingFunctionCalls.isNotEmpty; return widget.streamingFunctionCalls.isNotEmpty;
} else { } else {
return widget.thought!.chunks.isNotEmpty && return widget.thought!.parts.isNotEmpty &&
widget.thought!.chunks.any( widget.thought!.parts.any(
(chunk) => chunk.type == ThinkingChunkType.functionCall, (part) => part.type == ThinkingMessagePartType.functionCall,
); );
} }
} }
@@ -115,13 +115,14 @@ class _FunctionCallsSectionState extends State<FunctionCallsSection> {
), ),
), ),
] else ...[ ] else ...[
...widget.thought!.chunks ...widget.thought!.parts
.where( .where(
(chunk) => (part) =>
chunk.type == ThinkingChunkType.functionCall, part.type ==
ThinkingMessagePartType.functionCall,
) )
.map( .map(
(chunk) => Container( (part) => Container(
width: double.infinity, width: double.infinity,
padding: const EdgeInsets.all(8), padding: const EdgeInsets.all(8),
margin: const EdgeInsets.only(bottom: 4), margin: const EdgeInsets.only(bottom: 4),
@@ -138,7 +139,7 @@ class _FunctionCallsSectionState extends State<FunctionCallsSection> {
child: SelectableText( child: SelectableText(
JsonEncoder.withIndent( JsonEncoder.withIndent(
' ', ' ',
).convert(chunk.data), ).convert(part.functionCall?.toJson() ?? {}),
style: GoogleFonts.robotoMono( style: GoogleFonts.robotoMono(
fontSize: 11, fontSize: 11,
color: color:

View File

@@ -15,29 +15,62 @@ class ThoughtContent extends StatelessWidget {
final String streamingText; final String streamingText;
final SnThinkingThought? thought; final SnThinkingThought? thought;
bool get _isErrorMessage {
if (thought == null) return false;
// Check if this is an error thought by ID or content
if (thought!.id.startsWith('error-')) return true;
final textParts = thought!.parts
.where((p) => p.type == ThinkingMessagePartType.text)
.map((p) => p.text ?? '')
.join('');
return textParts.startsWith('Error:');
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (isStreaming) { if (isStreaming) {
// Streaming text with spinner // Streaming text with spinner
if (streamingText.isNotEmpty) { if (streamingText.isNotEmpty) {
final isStreamingError = streamingText.startsWith('Error:');
return Row( return Row(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Expanded( Expanded(
child: MarkdownTextContent( child: Container(
isSelectable: true, padding:
content: streamingText, isStreamingError
extraBlockSyntaxList: [ProposalBlockSyntax()], ? const EdgeInsets.all(8)
textStyle: Theme.of(context).textTheme.bodyMedium, : EdgeInsets.zero,
extraGenerators: [ decoration:
ProposalGenerator( isStreamingError
backgroundColor: ? BoxDecoration(
Theme.of(context).colorScheme.secondaryContainer, border: Border.all(
foregroundColor: color: Theme.of(context).colorScheme.error,
Theme.of(context).colorScheme.onSecondaryContainer, width: 1,
borderColor: Theme.of(context).colorScheme.outline, ),
borderRadius: BorderRadius.circular(8),
)
: null,
child: MarkdownTextContent(
isSelectable: true,
content: streamingText,
extraBlockSyntaxList: [ProposalBlockSyntax()],
textStyle: Theme.of(context).textTheme.bodyMedium!.copyWith(
color:
isStreamingError
? Theme.of(context).colorScheme.error
: null,
), ),
], extraGenerators: [
ProposalGenerator(
backgroundColor:
Theme.of(context).colorScheme.secondaryContainer,
foregroundColor:
Theme.of(context).colorScheme.onSecondaryContainer,
borderColor: Theme.of(context).colorScheme.outline,
),
],
),
), ),
), ),
const SizedBox(width: 8), const SizedBox(width: 8),
@@ -56,22 +89,53 @@ class ThoughtContent extends StatelessWidget {
} }
return const SizedBox.shrink(); return const SizedBox.shrink();
} else { } else {
// Regular thought content // Regular thought content - render parts
if (thought!.content != null && thought!.content!.isNotEmpty) { if (thought!.parts.isNotEmpty) {
return MarkdownTextContent( final textParts = thought!.parts
isSelectable: true, .where((p) => p.type == ThinkingMessagePartType.text)
content: thought!.content!, .map((p) => p.text ?? '')
extraBlockSyntaxList: [ProposalBlockSyntax()], .join('');
textStyle: Theme.of(context).textTheme.bodyMedium, if (textParts.isNotEmpty) {
extraGenerators: [ return Container(
ProposalGenerator( padding:
backgroundColor: Theme.of(context).colorScheme.secondaryContainer, _isErrorMessage
foregroundColor: ? const EdgeInsets.symmetric(horizontal: 12, vertical: 4)
Theme.of(context).colorScheme.onSecondaryContainer, : EdgeInsets.zero,
borderColor: Theme.of(context).colorScheme.outline, decoration:
_isErrorMessage
? BoxDecoration(
color: Theme.of(
context,
).colorScheme.error.withOpacity(0.1),
border: Border.all(
color: Theme.of(context).colorScheme.error,
width: 1,
),
borderRadius: BorderRadius.circular(8),
)
: null,
child: MarkdownTextContent(
isSelectable: true,
content: textParts,
extraBlockSyntaxList: [ProposalBlockSyntax()],
textStyle: Theme.of(context).textTheme.bodyMedium!.copyWith(
color:
_isErrorMessage
? Theme.of(context).colorScheme.error
: null,
),
extraGenerators: [
ProposalGenerator(
backgroundColor:
Theme.of(context).colorScheme.secondaryContainer,
foregroundColor:
Theme.of(context).colorScheme.onSecondaryContainer,
borderColor: Theme.of(context).colorScheme.outline,
),
],
), ),
], );
); }
} }
return const SizedBox.shrink(); return const SizedBox.shrink();
} }

View File

@@ -211,8 +211,13 @@ class ThoughtItem extends StatelessWidget {
(!isStreaming && thought!.role == ThinkingThoughtRole.assistant); (!isStreaming && thought!.role == ThinkingThoughtRole.assistant);
final List<Map<String, String>> proposals = final List<Map<String, String>> proposals =
!isStreaming && thought!.content != null !isStreaming
? _extractProposals(thought!.content!) ? _extractProposals(
thought!.parts
.where((p) => p.type == ThinkingMessagePartType.text)
.map((p) => p.text ?? '')
.join(''),
)
: []; : [];
return Container( return Container(
@@ -251,10 +256,10 @@ class ThoughtItem extends StatelessWidget {
// Function calls // Function calls
if (streamingFunctionCalls.isNotEmpty || if (streamingFunctionCalls.isNotEmpty ||
(thought?.chunks.isNotEmpty ?? false) && (thought?.parts.isNotEmpty ?? false) &&
thought!.chunks.any( thought!.parts.any(
(chunk) => (part) =>
chunk.type == ThinkingChunkType.functionCall, part.type == ThinkingMessagePartType.functionCall,
)) ))
FunctionCallsSection( FunctionCallsSection(
isStreaming: isStreaming, isStreaming: isStreaming,