Compare commits
3 Commits
ea8e7ead2d
...
a9c8f49797
| Author | SHA1 | Date | |
|---|---|---|---|
|
a9c8f49797
|
|||
|
5e9341a19c
|
|||
|
645a6dca93
|
@@ -38,6 +38,31 @@ class ThinkingChunkTypeConverter
|
||||
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
|
||||
sealed class StreamThinkingRequest with _$StreamThinkingRequest {
|
||||
const factory StreamThinkingRequest({
|
||||
@@ -77,6 +102,43 @@ sealed class SnThinkingChunk with _$SnThinkingChunk {
|
||||
_$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
|
||||
sealed class SnThinkingSequence with _$SnThinkingSequence {
|
||||
const factory SnThinkingSequence({
|
||||
@@ -98,9 +160,8 @@ sealed class SnThinkingSequence with _$SnThinkingSequence {
|
||||
sealed class SnThinkingThought with _$SnThinkingThought {
|
||||
const factory SnThinkingThought({
|
||||
required String id,
|
||||
String? content,
|
||||
@Default([]) List<SnThinkingMessagePart> parts,
|
||||
@Default([]) List<SnCloudFile> files,
|
||||
@Default([]) List<SnThinkingChunk> chunks,
|
||||
@ThinkingThoughtRoleConverter() required ThinkingThoughtRole role,
|
||||
int? tokenCount,
|
||||
String? modelName,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -50,6 +50,64 @@ Map<String, dynamic> _$SnThinkingChunkToJson(_SnThinkingChunk instance) =>
|
||||
'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(
|
||||
id: json['id'] as String,
|
||||
@@ -80,17 +138,19 @@ Map<String, dynamic> _$SnThinkingSequenceToJson(_SnThinkingSequence instance) =>
|
||||
_SnThinkingThought _$SnThinkingThoughtFromJson(Map<String, dynamic> json) =>
|
||||
_SnThinkingThought(
|
||||
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:
|
||||
(json['files'] as List<dynamic>?)
|
||||
?.map((e) => SnCloudFile.fromJson(e as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
const [],
|
||||
chunks:
|
||||
(json['chunks'] as List<dynamic>?)
|
||||
?.map((e) => SnThinkingChunk.fromJson(e as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
const [],
|
||||
role: const ThinkingThoughtRoleConverter().fromJson(
|
||||
(json['role'] as num).toInt(),
|
||||
),
|
||||
@@ -114,9 +174,8 @@ _SnThinkingThought _$SnThinkingThoughtFromJson(Map<String, dynamic> json) =>
|
||||
Map<String, dynamic> _$SnThinkingThoughtToJson(_SnThinkingThought instance) =>
|
||||
<String, dynamic>{
|
||||
'id': instance.id,
|
||||
'content': instance.content,
|
||||
'parts': instance.parts.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),
|
||||
'token_count': instance.tokenCount,
|
||||
'model_name': instance.modelName,
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
import "dart:convert";
|
||||
import "dart:math" as math;
|
||||
import "package:dio/dio.dart";
|
||||
import "package:easy_localization/easy_localization.dart";
|
||||
import "package:flutter/material.dart";
|
||||
import "package:flutter_hooks/flutter_hooks.dart";
|
||||
@@ -9,15 +6,11 @@ import "package:riverpod_annotation/riverpod_annotation.dart";
|
||||
import "package:hooks_riverpod/hooks_riverpod.dart";
|
||||
import "package:island/models/thought.dart";
|
||||
import "package:island/pods/network.dart";
|
||||
import "package:island/pods/userinfo.dart";
|
||||
import "package:island/widgets/alert.dart";
|
||||
import "package:island/widgets/app_scaffold.dart";
|
||||
import "package:island/widgets/response.dart";
|
||||
import "package:island/widgets/thought/thought_sequence_list.dart";
|
||||
import "package:island/widgets/thought/thought_shared.dart";
|
||||
import "package:material_symbols_icons/material_symbols_icons.dart";
|
||||
import "package:super_sliver_list/super_sliver_list.dart";
|
||||
import "package:collection/collection.dart";
|
||||
|
||||
part 'think.g.dart';
|
||||
|
||||
@@ -46,203 +39,18 @@ class ThoughtScreen extends HookConsumerWidget {
|
||||
? ref.watch(thoughtSequenceProvider(selectedSequenceId.value!))
|
||||
: const AsyncValue<List<SnThinkingThought>>.data([]);
|
||||
|
||||
final localThoughts = useState<List<SnThinkingThought>>([]);
|
||||
final currentTopic = useState<String?>('aiThought'.tr());
|
||||
|
||||
final messageController = useTextEditingController();
|
||||
final scrollController = useScrollController();
|
||||
final isStreaming = useState(false);
|
||||
final streamingText = useState<String>('');
|
||||
final functionCalls = useState<List<String>>([]);
|
||||
final reasoningChunks = useState<List<String>>([]);
|
||||
|
||||
final listController = useMemoized(() => ListController(), []);
|
||||
|
||||
// Scroll animation notifiers
|
||||
final bottomGradientNotifier = useState(ValueNotifier<double>(0.0));
|
||||
|
||||
// Update local thoughts when provider data changes
|
||||
useEffect(() {
|
||||
thoughts.whenData((data) {
|
||||
// Server returns messages in DESC order (newest first), keep as-is for UI
|
||||
localThoughts.value = data;
|
||||
// Update topic from the first thought's sequence
|
||||
if (data.isNotEmpty && data.first.sequence?.topic != null) {
|
||||
currentTopic.value = data.first.sequence!.topic;
|
||||
} else {
|
||||
currentTopic.value = 'aiThought'.tr();
|
||||
}
|
||||
});
|
||||
return null;
|
||||
}, [thoughts]);
|
||||
|
||||
// Scroll to bottom when thoughts change or streaming state changes
|
||||
useEffect(() {
|
||||
if (localThoughts.value.isNotEmpty || isStreaming.value) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
scrollController.animateTo(
|
||||
0,
|
||||
duration: const Duration(milliseconds: 300),
|
||||
curve: Curves.easeOut,
|
||||
);
|
||||
});
|
||||
}
|
||||
return null;
|
||||
}, [localThoughts.value.length, isStreaming.value]);
|
||||
|
||||
// Add scroll listener for gradient animations
|
||||
useEffect(() {
|
||||
void onScroll() {
|
||||
// Update gradient animations
|
||||
final pixels = scrollController.position.pixels;
|
||||
|
||||
// Bottom gradient: appears when not at bottom (pixels > 0)
|
||||
bottomGradientNotifier.value.value = (pixels / 500.0).clamp(0.0, 1.0);
|
||||
}
|
||||
|
||||
scrollController.addListener(onScroll);
|
||||
return () => scrollController.removeListener(onScroll);
|
||||
}, [scrollController]);
|
||||
|
||||
void sendMessage() async {
|
||||
if (messageController.text.trim().isEmpty) return;
|
||||
|
||||
final userMessage = messageController.text.trim();
|
||||
|
||||
// Add user message to local thoughts
|
||||
final userInfo = ref.read(userInfoProvider);
|
||||
final now = DateTime.now();
|
||||
final userThought = SnThinkingThought(
|
||||
id: 'user-${DateTime.now().millisecondsSinceEpoch}',
|
||||
content: userMessage,
|
||||
files: [],
|
||||
role: ThinkingThoughtRole.user,
|
||||
sequenceId: selectedSequenceId.value ?? '',
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
sequence:
|
||||
selectedSequenceId.value != null
|
||||
? thoughts.value?.firstOrNull?.sequence ??
|
||||
SnThinkingSequence(
|
||||
id: selectedSequenceId.value!,
|
||||
accountId: '',
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
)
|
||||
: SnThinkingSequence(
|
||||
id: '',
|
||||
accountId: userInfo.value!.id,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
),
|
||||
);
|
||||
localThoughts.value = [userThought, ...localThoughts.value];
|
||||
|
||||
final request = StreamThinkingRequest(
|
||||
userMessage: userMessage,
|
||||
sequenceId: selectedSequenceId.value,
|
||||
accpetProposals: ['post_create'],
|
||||
attachedMessages: [], // Message datas
|
||||
attachedPosts: [], // ID list for posts
|
||||
);
|
||||
|
||||
try {
|
||||
isStreaming.value = true;
|
||||
streamingText.value = '';
|
||||
functionCalls.value = [];
|
||||
reasoningChunks.value = [];
|
||||
|
||||
final apiClient = ref.read(apiClientProvider);
|
||||
final response = await apiClient.post(
|
||||
'/insight/thought',
|
||||
data: request.toJson(),
|
||||
options: Options(
|
||||
responseType: ResponseType.stream,
|
||||
sendTimeout: Duration(minutes: 1),
|
||||
receiveTimeout: Duration(minutes: 1),
|
||||
),
|
||||
);
|
||||
|
||||
final stream = response.data.stream;
|
||||
final lineBuffer = StringBuffer();
|
||||
|
||||
stream.listen(
|
||||
(data) {
|
||||
final chunk = utf8.decode(data);
|
||||
lineBuffer.write(chunk);
|
||||
final lines = lineBuffer.toString().split('\n');
|
||||
lineBuffer.clear();
|
||||
lineBuffer.write(lines.last); // keep incomplete line
|
||||
|
||||
for (final line in lines.sublist(0, lines.length - 1)) {
|
||||
if (line.trim().isEmpty) continue;
|
||||
try {
|
||||
if (line.startsWith('data: ')) {
|
||||
final jsonStr = line.substring(6);
|
||||
final event = jsonDecode(jsonStr);
|
||||
final type = event['type'];
|
||||
final eventData = event['data'];
|
||||
if (type == 'text') {
|
||||
streamingText.value += eventData;
|
||||
} else if (type == 'function_call') {
|
||||
functionCalls.value = [
|
||||
...functionCalls.value,
|
||||
JsonEncoder.withIndent(' ').convert(eventData),
|
||||
];
|
||||
} else if (type == 'reasoning') {
|
||||
reasoningChunks.value = [
|
||||
...reasoningChunks.value,
|
||||
eventData,
|
||||
];
|
||||
}
|
||||
} else if (line.startsWith('topic: ')) {
|
||||
final jsonStr = line.substring(7);
|
||||
final event = jsonDecode(jsonStr);
|
||||
currentTopic.value = event['data'];
|
||||
} else if (line.startsWith('thought: ')) {
|
||||
final jsonStr = line.substring(9);
|
||||
final event = jsonDecode(jsonStr);
|
||||
final aiThought = SnThinkingThought.fromJson(event['data']);
|
||||
localThoughts.value = [aiThought, ...localThoughts.value];
|
||||
if (selectedSequenceId.value == null &&
|
||||
aiThought.sequenceId.isNotEmpty) {
|
||||
selectedSequenceId.value = aiThought.sequenceId;
|
||||
}
|
||||
isStreaming.value = false;
|
||||
}
|
||||
} catch (e) {
|
||||
// Ignore parsing errors for individual events
|
||||
}
|
||||
}
|
||||
},
|
||||
onDone: () {
|
||||
if (isStreaming.value) {
|
||||
isStreaming.value = false;
|
||||
showErrorAlert('thoughtParseError'.tr());
|
||||
}
|
||||
},
|
||||
onError: (error) {
|
||||
isStreaming.value = false;
|
||||
if (error is DioException && error.response?.data is ResponseBody) {
|
||||
showErrorAlert('toughtParseError'.tr());
|
||||
} else {
|
||||
showErrorAlert(error);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
messageController.clear();
|
||||
FocusManager.instance.primaryFocus?.unfocus();
|
||||
} catch (error) {
|
||||
isStreaming.value = false;
|
||||
showErrorAlert(error);
|
||||
}
|
||||
}
|
||||
// Get initial thoughts and topic from provider
|
||||
final initialThoughts = thoughts.valueOrNull;
|
||||
final initialTopic =
|
||||
(initialThoughts?.isNotEmpty ?? false) &&
|
||||
initialThoughts!.first.sequence?.topic != null
|
||||
? initialThoughts.first.sequence!.topic
|
||||
: 'aiThought'.tr();
|
||||
|
||||
return AppScaffold(
|
||||
isNoBackground: false,
|
||||
appBar: AppBar(
|
||||
title: Text(currentTopic.value ?? 'aiThought'.tr()),
|
||||
title: Text(initialTopic ?? 'aiThought'.tr()),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Symbols.history),
|
||||
@@ -259,137 +67,28 @@ class ThoughtScreen extends HookConsumerWidget {
|
||||
);
|
||||
},
|
||||
),
|
||||
if (localThoughts.value.isNotEmpty &&
|
||||
!isStreaming.value &&
|
||||
localThoughts.value.last.role == ThinkingThoughtRole.assistant)
|
||||
IconButton(
|
||||
icon: const Icon(Symbols.add),
|
||||
tooltip: 'thoughtNewConversation'.tr(),
|
||||
onPressed: () {
|
||||
// Clear current conversation and start new one
|
||||
selectedSequenceId.value = null;
|
||||
localThoughts.value = [];
|
||||
currentTopic.value = 'aiThought'.tr();
|
||||
messageController.clear();
|
||||
},
|
||||
),
|
||||
// TODO: Need to access chat state for actions
|
||||
const Gap(8),
|
||||
],
|
||||
),
|
||||
body: Stack(
|
||||
children: [
|
||||
// Thoughts list
|
||||
Center(
|
||||
child: Container(
|
||||
constraints: BoxConstraints(maxWidth: 640),
|
||||
child: Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: thoughts.when(
|
||||
data:
|
||||
(thoughtList) => SuperListView.builder(
|
||||
listController: listController,
|
||||
controller: scrollController,
|
||||
padding: EdgeInsets.only(
|
||||
top: 16,
|
||||
bottom:
|
||||
MediaQuery.of(context).padding.bottom +
|
||||
80, // Leave space for thought input
|
||||
),
|
||||
reverse: true,
|
||||
itemCount:
|
||||
localThoughts.value.length +
|
||||
(isStreaming.value ? 1 : 0),
|
||||
itemBuilder: (context, index) {
|
||||
if (isStreaming.value && index == 0) {
|
||||
return ThoughtItem(
|
||||
isStreaming: true,
|
||||
streamingText: streamingText.value,
|
||||
reasoningChunks: reasoningChunks.value,
|
||||
streamingFunctionCalls: functionCalls.value,
|
||||
);
|
||||
}
|
||||
final thoughtIndex =
|
||||
isStreaming.value ? index - 1 : index;
|
||||
final thought = localThoughts.value[thoughtIndex];
|
||||
return ThoughtItem(
|
||||
thought: thought,
|
||||
thoughtIndex: thoughtIndex,
|
||||
);
|
||||
},
|
||||
),
|
||||
loading:
|
||||
() =>
|
||||
const Center(child: CircularProgressIndicator()),
|
||||
error:
|
||||
(error, _) => ResponseErrorWidget(
|
||||
error: error,
|
||||
onRetry:
|
||||
() =>
|
||||
selectedSequenceId.value != null
|
||||
? ref.invalidate(
|
||||
thoughtSequenceProvider(
|
||||
selectedSequenceId.value!,
|
||||
),
|
||||
)
|
||||
: null,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: thoughts.when(
|
||||
data:
|
||||
(thoughtList) => ThoughtChatInterface(
|
||||
initialThoughts: thoughtList,
|
||||
initialTopic: initialTopic,
|
||||
),
|
||||
),
|
||||
// Bottom gradient - appears when scrolling towards newer thoughts (behind thought input)
|
||||
AnimatedBuilder(
|
||||
animation: bottomGradientNotifier.value,
|
||||
builder:
|
||||
(context, child) => Positioned(
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
child: Opacity(
|
||||
opacity: bottomGradientNotifier.value.value,
|
||||
child: Container(
|
||||
height: math.min(
|
||||
MediaQuery.of(context).size.height * 0.1,
|
||||
128,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.bottomCenter,
|
||||
end: Alignment.topCenter,
|
||||
colors: [
|
||||
Theme.of(
|
||||
context,
|
||||
).colorScheme.surfaceContainer.withOpacity(0.8),
|
||||
Theme.of(
|
||||
context,
|
||||
).colorScheme.surfaceContainer.withOpacity(0.0),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
// Thought Input positioned above gradient (higher z-index)
|
||||
Positioned(
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0, // At the very bottom, above gradient
|
||||
child: Center(
|
||||
child: Container(
|
||||
constraints: BoxConstraints(maxWidth: 640),
|
||||
child: ThoughtInput(
|
||||
messageController: messageController,
|
||||
isStreaming: isStreaming.value,
|
||||
onSend: sendMessage,
|
||||
),
|
||||
),
|
||||
loading: () => const Center(child: CircularProgressIndicator()),
|
||||
error:
|
||||
(error, _) => ResponseErrorWidget(
|
||||
error: error,
|
||||
onRetry:
|
||||
() =>
|
||||
selectedSequenceId.value != null
|
||||
? ref.invalidate(
|
||||
thoughtSequenceProvider(selectedSequenceId.value!),
|
||||
)
|
||||
: null,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,17 +1,8 @@
|
||||
import "dart:convert";
|
||||
import "dart:math" as math;
|
||||
import "package:dio/dio.dart";
|
||||
import "package:easy_localization/easy_localization.dart";
|
||||
import "package:flutter/material.dart";
|
||||
import "package:flutter_hooks/flutter_hooks.dart";
|
||||
import "package:hooks_riverpod/hooks_riverpod.dart";
|
||||
import "package:island/models/thought.dart";
|
||||
import "package:island/pods/network.dart";
|
||||
import "package:island/pods/userinfo.dart";
|
||||
import "package:island/widgets/alert.dart";
|
||||
import "package:island/widgets/content/sheet.dart";
|
||||
import "package:island/widgets/thought/thought_shared.dart";
|
||||
import "package:super_sliver_list/super_sliver_list.dart";
|
||||
|
||||
class ThoughtSheet extends HookConsumerWidget {
|
||||
final List<Map<String, dynamic>> attachedMessages;
|
||||
@@ -42,275 +33,17 @@ class ThoughtSheet extends HookConsumerWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final sequenceId = useState<String?>(null);
|
||||
final localThoughts = useState<List<SnThinkingThought>>([]);
|
||||
final currentTopic = useState<String?>('aiThought'.tr());
|
||||
|
||||
final messageController = useTextEditingController();
|
||||
final scrollController = useScrollController();
|
||||
final isStreaming = useState(false);
|
||||
final streamingText = useState<String>('');
|
||||
final functionCalls = useState<List<String>>([]);
|
||||
final reasoningChunks = useState<List<String>>([]);
|
||||
|
||||
final listController = useMemoized(() => ListController(), []);
|
||||
|
||||
// Scroll animation notifiers
|
||||
final bottomGradientNotifier = useState(ValueNotifier<double>(0.0));
|
||||
|
||||
// Scroll to bottom when thoughts change or streaming state changes
|
||||
useEffect(() {
|
||||
if (localThoughts.value.isNotEmpty || isStreaming.value) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
scrollController.animateTo(
|
||||
0,
|
||||
duration: const Duration(milliseconds: 300),
|
||||
curve: Curves.easeOut,
|
||||
);
|
||||
});
|
||||
}
|
||||
return null;
|
||||
}, [localThoughts.value.length, isStreaming.value]);
|
||||
|
||||
// Add scroll listener for gradient animations
|
||||
useEffect(() {
|
||||
void onScroll() {
|
||||
// Update gradient animations
|
||||
final pixels = scrollController.position.pixels;
|
||||
|
||||
// Bottom gradient: appears when not at bottom (pixels > 0)
|
||||
bottomGradientNotifier.value.value = (pixels / 500.0).clamp(0.0, 1.0);
|
||||
}
|
||||
|
||||
scrollController.addListener(onScroll);
|
||||
return () => scrollController.removeListener(onScroll);
|
||||
}, [scrollController]);
|
||||
|
||||
void sendMessage() async {
|
||||
if (messageController.text.trim().isEmpty) return;
|
||||
|
||||
final userMessage = messageController.text.trim();
|
||||
|
||||
// Add user message to local thoughts
|
||||
final userInfo = ref.read(userInfoProvider);
|
||||
final now = DateTime.now();
|
||||
final userThought = SnThinkingThought(
|
||||
id: 'user-${DateTime.now().millisecondsSinceEpoch}',
|
||||
content: userMessage,
|
||||
files: [],
|
||||
role: ThinkingThoughtRole.user,
|
||||
sequenceId: sequenceId.value ?? '',
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
sequence: SnThinkingSequence(
|
||||
id: sequenceId.value ?? '',
|
||||
accountId: userInfo.value!.id,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
),
|
||||
);
|
||||
localThoughts.value = [userThought, ...localThoughts.value];
|
||||
|
||||
final request = StreamThinkingRequest(
|
||||
userMessage: userMessage,
|
||||
sequenceId: sequenceId.value,
|
||||
accpetProposals: ['post_create'],
|
||||
attachedMessages: attachedMessages,
|
||||
attachedPosts: attachedPosts,
|
||||
);
|
||||
|
||||
try {
|
||||
isStreaming.value = true;
|
||||
streamingText.value = '';
|
||||
functionCalls.value = [];
|
||||
reasoningChunks.value = [];
|
||||
|
||||
final apiClient = ref.read(apiClientProvider);
|
||||
final response = await apiClient.post(
|
||||
'/insight/thought',
|
||||
data: request.toJson(),
|
||||
options: Options(
|
||||
responseType: ResponseType.stream,
|
||||
sendTimeout: Duration(minutes: 1),
|
||||
receiveTimeout: Duration(minutes: 1),
|
||||
),
|
||||
);
|
||||
|
||||
final stream = response.data.stream;
|
||||
final lineBuffer = StringBuffer();
|
||||
|
||||
stream.listen(
|
||||
(data) {
|
||||
final chunk = utf8.decode(data);
|
||||
lineBuffer.write(chunk);
|
||||
final lines = lineBuffer.toString().split('\n');
|
||||
lineBuffer.clear();
|
||||
lineBuffer.write(lines.last); // keep incomplete line
|
||||
|
||||
for (final line in lines.sublist(0, lines.length - 1)) {
|
||||
if (line.trim().isEmpty) continue;
|
||||
try {
|
||||
if (line.startsWith('data: ')) {
|
||||
final jsonStr = line.substring(6);
|
||||
final event = jsonDecode(jsonStr);
|
||||
final type = event['type'];
|
||||
final eventData = event['data'];
|
||||
if (type == 'text') {
|
||||
streamingText.value += eventData;
|
||||
} else if (type == 'function_call') {
|
||||
functionCalls.value = [
|
||||
...functionCalls.value,
|
||||
JsonEncoder.withIndent(' ').convert(eventData),
|
||||
];
|
||||
} else if (type == 'reasoning') {
|
||||
reasoningChunks.value = [
|
||||
...reasoningChunks.value,
|
||||
eventData,
|
||||
];
|
||||
}
|
||||
} else if (line.startsWith('topic: ')) {
|
||||
final jsonStr = line.substring(7);
|
||||
final event = jsonDecode(jsonStr);
|
||||
currentTopic.value = event['data'];
|
||||
} else if (line.startsWith('thought: ')) {
|
||||
final jsonStr = line.substring(9);
|
||||
final event = jsonDecode(jsonStr);
|
||||
final aiThought = SnThinkingThought.fromJson(event['data']);
|
||||
localThoughts.value = [aiThought, ...localThoughts.value];
|
||||
if (sequenceId.value == null &&
|
||||
aiThought.sequenceId.isNotEmpty) {
|
||||
sequenceId.value = aiThought.sequenceId;
|
||||
}
|
||||
isStreaming.value = false;
|
||||
}
|
||||
} catch (e) {
|
||||
// Ignore parsing errors for individual events
|
||||
}
|
||||
}
|
||||
},
|
||||
onDone: () {
|
||||
if (isStreaming.value) {
|
||||
isStreaming.value = false;
|
||||
showErrorAlert('thoughtParseError'.tr());
|
||||
}
|
||||
},
|
||||
onError: (error) {
|
||||
isStreaming.value = false;
|
||||
if (error is DioException && error.response?.data is ResponseBody) {
|
||||
showErrorAlert('toughtParseError'.tr());
|
||||
} else {
|
||||
showErrorAlert(error);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
messageController.clear();
|
||||
FocusManager.instance.primaryFocus?.unfocus();
|
||||
} catch (error) {
|
||||
isStreaming.value = false;
|
||||
showErrorAlert(error);
|
||||
}
|
||||
}
|
||||
final chatState = useThoughtChat(
|
||||
ref,
|
||||
attachedMessages: attachedMessages,
|
||||
attachedPosts: attachedPosts,
|
||||
);
|
||||
|
||||
return SheetScaffold(
|
||||
titleText: currentTopic.value ?? 'aiThought'.tr(),
|
||||
child: Stack(
|
||||
children: [
|
||||
// Thoughts list
|
||||
Center(
|
||||
child: Container(
|
||||
constraints: BoxConstraints(maxWidth: 640),
|
||||
child: Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: SuperListView.builder(
|
||||
listController: listController,
|
||||
controller: scrollController,
|
||||
padding: EdgeInsets.only(
|
||||
top: 16,
|
||||
bottom:
|
||||
MediaQuery.of(context).padding.bottom +
|
||||
80, // Leave space for thought input
|
||||
),
|
||||
reverse: true,
|
||||
itemCount:
|
||||
localThoughts.value.length +
|
||||
(isStreaming.value ? 1 : 0),
|
||||
itemBuilder: (context, index) {
|
||||
if (isStreaming.value && index == 0) {
|
||||
return ThoughtItem(
|
||||
isStreaming: true,
|
||||
streamingText: streamingText.value,
|
||||
reasoningChunks: reasoningChunks.value,
|
||||
streamingFunctionCalls: functionCalls.value,
|
||||
);
|
||||
}
|
||||
final thoughtIndex =
|
||||
isStreaming.value ? index - 1 : index;
|
||||
final thought = localThoughts.value[thoughtIndex];
|
||||
return ThoughtItem(
|
||||
thought: thought,
|
||||
thoughtIndex: thoughtIndex,
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
// Bottom gradient - appears when scrolling towards newer thoughts (behind thought input)
|
||||
AnimatedBuilder(
|
||||
animation: bottomGradientNotifier.value,
|
||||
builder:
|
||||
(context, child) => Positioned(
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
child: Opacity(
|
||||
opacity: bottomGradientNotifier.value.value,
|
||||
child: Container(
|
||||
height: math.min(
|
||||
MediaQuery.of(context).size.height * 0.1,
|
||||
128,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.bottomCenter,
|
||||
end: Alignment.topCenter,
|
||||
colors: [
|
||||
Theme.of(
|
||||
context,
|
||||
).colorScheme.surfaceContainer.withOpacity(0.8),
|
||||
Theme.of(
|
||||
context,
|
||||
).colorScheme.surfaceContainer.withOpacity(0.0),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
// Thought Input positioned above gradient (higher z-index)
|
||||
Positioned(
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0, // At the very bottom, above gradient
|
||||
child: Center(
|
||||
child: Container(
|
||||
constraints: BoxConstraints(maxWidth: 640),
|
||||
child: ThoughtInput(
|
||||
messageController: messageController,
|
||||
isStreaming: isStreaming.value,
|
||||
onSend: sendMessage,
|
||||
attachedMessages: attachedMessages,
|
||||
attachedPosts: attachedPosts,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
titleText: chatState.currentTopic.value ?? 'aiThought'.tr(),
|
||||
child: ThoughtChatInterface(
|
||||
attachedMessages: attachedMessages,
|
||||
attachedPosts: attachedPosts,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -608,26 +608,30 @@ class FileListView extends HookConsumerWidget {
|
||||
previewWidget = getFileIcon(file, size: 48);
|
||||
break;
|
||||
case 'text':
|
||||
previewWidget = FutureBuilder<String>(
|
||||
future: ref
|
||||
.read(apiClientProvider)
|
||||
.get(uri)
|
||||
.then((response) => response.data as String),
|
||||
builder:
|
||||
(context, snapshot) =>
|
||||
snapshot.hasData
|
||||
? SingleChildScrollView(
|
||||
child: Text(
|
||||
snapshot.data!,
|
||||
style: const TextStyle(
|
||||
fontSize: 8,
|
||||
fontFamily: 'monospace',
|
||||
previewWidget = Container(
|
||||
color: Theme.of(context).colorScheme.surfaceContainer,
|
||||
child: FutureBuilder<String>(
|
||||
future: ref
|
||||
.read(apiClientProvider)
|
||||
.get(uri)
|
||||
.then((response) => response.data as String),
|
||||
builder:
|
||||
(context, snapshot) =>
|
||||
snapshot.hasData
|
||||
? SingleChildScrollView(
|
||||
padding: EdgeInsets.all(24),
|
||||
child: Text(
|
||||
snapshot.data!,
|
||||
style: const TextStyle(
|
||||
fontSize: 9,
|
||||
fontFamily: 'monospace',
|
||||
),
|
||||
maxLines: 20,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
maxLines: 20,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
)
|
||||
: const Center(child: CircularProgressIndicator()),
|
||||
)
|
||||
: const Center(child: CircularProgressIndicator()),
|
||||
),
|
||||
);
|
||||
break;
|
||||
case 'application' when file.mimeType == 'application/pdf':
|
||||
|
||||
@@ -30,9 +30,9 @@ class _FunctionCallsSectionState extends State<FunctionCallsSection> {
|
||||
if (widget.isStreaming) {
|
||||
return widget.streamingFunctionCalls.isNotEmpty;
|
||||
} else {
|
||||
return widget.thought!.chunks.isNotEmpty &&
|
||||
widget.thought!.chunks.any(
|
||||
(chunk) => chunk.type == ThinkingChunkType.functionCall,
|
||||
return widget.thought!.parts.isNotEmpty &&
|
||||
widget.thought!.parts.any(
|
||||
(part) => part.type == ThinkingMessagePartType.functionCall,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -115,13 +115,14 @@ class _FunctionCallsSectionState extends State<FunctionCallsSection> {
|
||||
),
|
||||
),
|
||||
] else ...[
|
||||
...widget.thought!.chunks
|
||||
...widget.thought!.parts
|
||||
.where(
|
||||
(chunk) =>
|
||||
chunk.type == ThinkingChunkType.functionCall,
|
||||
(part) =>
|
||||
part.type ==
|
||||
ThinkingMessagePartType.functionCall,
|
||||
)
|
||||
.map(
|
||||
(chunk) => Container(
|
||||
(part) => Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(8),
|
||||
margin: const EdgeInsets.only(bottom: 4),
|
||||
@@ -138,7 +139,7 @@ class _FunctionCallsSectionState extends State<FunctionCallsSection> {
|
||||
child: SelectableText(
|
||||
JsonEncoder.withIndent(
|
||||
' ',
|
||||
).convert(chunk.data),
|
||||
).convert(part.functionCall?.toJson() ?? {}),
|
||||
style: GoogleFonts.robotoMono(
|
||||
fontSize: 11,
|
||||
color:
|
||||
|
||||
@@ -15,63 +15,104 @@ class ThoughtContent extends StatelessWidget {
|
||||
final String streamingText;
|
||||
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
|
||||
Widget build(BuildContext context) {
|
||||
if (isStreaming) {
|
||||
// Streaming text with spinner
|
||||
if (streamingText.isNotEmpty) {
|
||||
return Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: MarkdownTextContent(
|
||||
isSelectable: true,
|
||||
content: streamingText,
|
||||
extraBlockSyntaxList: [ProposalBlockSyntax()],
|
||||
textStyle: Theme.of(context).textTheme.bodyMedium,
|
||||
extraGenerators: [
|
||||
ProposalGenerator(
|
||||
backgroundColor:
|
||||
Theme.of(context).colorScheme.secondaryContainer,
|
||||
foregroundColor:
|
||||
Theme.of(context).colorScheme.onSecondaryContainer,
|
||||
borderColor: Theme.of(context).colorScheme.outline,
|
||||
),
|
||||
],
|
||||
),
|
||||
final isStreamingError = streamingText.startsWith('Error:');
|
||||
return Container(
|
||||
padding: isStreamingError ? const EdgeInsets.all(8) : EdgeInsets.zero,
|
||||
decoration:
|
||||
isStreamingError
|
||||
? BoxDecoration(
|
||||
border: Border.all(
|
||||
color: Theme.of(context).colorScheme.error,
|
||||
width: 1,
|
||||
),
|
||||
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,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(
|
||||
Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
extraGenerators: [
|
||||
ProposalGenerator(
|
||||
backgroundColor:
|
||||
Theme.of(context).colorScheme.secondaryContainer,
|
||||
foregroundColor:
|
||||
Theme.of(context).colorScheme.onSecondaryContainer,
|
||||
borderColor: Theme.of(context).colorScheme.outline,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
return const SizedBox.shrink();
|
||||
} else {
|
||||
// Regular thought content
|
||||
if (thought!.content != null && thought!.content!.isNotEmpty) {
|
||||
return MarkdownTextContent(
|
||||
isSelectable: true,
|
||||
content: thought!.content!,
|
||||
extraBlockSyntaxList: [ProposalBlockSyntax()],
|
||||
textStyle: Theme.of(context).textTheme.bodyMedium,
|
||||
extraGenerators: [
|
||||
ProposalGenerator(
|
||||
backgroundColor: Theme.of(context).colorScheme.secondaryContainer,
|
||||
foregroundColor:
|
||||
Theme.of(context).colorScheme.onSecondaryContainer,
|
||||
borderColor: Theme.of(context).colorScheme.outline,
|
||||
// Regular thought content - render parts
|
||||
if (thought!.parts.isNotEmpty) {
|
||||
final textParts = thought!.parts
|
||||
.where((p) => p.type == ThinkingMessagePartType.text)
|
||||
.map((p) => p.text ?? '')
|
||||
.join('');
|
||||
if (textParts.isNotEmpty) {
|
||||
return Container(
|
||||
padding:
|
||||
_isErrorMessage
|
||||
? const EdgeInsets.symmetric(horizontal: 12, vertical: 4)
|
||||
: EdgeInsets.zero,
|
||||
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();
|
||||
}
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:math' as math;
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:easy_localization/easy_localization.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:gap/gap.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:island/models/thought.dart';
|
||||
import 'package:island/pods/network.dart';
|
||||
import 'package:island/pods/userinfo.dart';
|
||||
import 'package:island/screens/posts/compose.dart';
|
||||
import 'package:island/widgets/alert.dart';
|
||||
import 'package:island/widgets/post/compose_sheet.dart';
|
||||
@@ -13,6 +19,475 @@ import 'package:island/widgets/thought/thought_content.dart';
|
||||
import 'package:island/widgets/thought/thought_header.dart';
|
||||
import 'package:island/widgets/thought/token_info.dart';
|
||||
import 'package:material_symbols_icons/material_symbols_icons.dart';
|
||||
import 'package:super_sliver_list/super_sliver_list.dart';
|
||||
|
||||
class ThoughtChatState {
|
||||
final ValueNotifier<String?> sequenceId;
|
||||
final ValueNotifier<List<SnThinkingThought>> localThoughts;
|
||||
final ValueNotifier<String?> currentTopic;
|
||||
final TextEditingController messageController;
|
||||
final ScrollController scrollController;
|
||||
final ValueNotifier<bool> isStreaming;
|
||||
final ValueNotifier<List<SnThinkingMessagePart>> streamingParts;
|
||||
final ValueNotifier<List<String>> reasoningChunks;
|
||||
final ListController listController;
|
||||
final ValueNotifier<ValueNotifier<double>> bottomGradientNotifier;
|
||||
final Future<void> Function() sendMessage;
|
||||
|
||||
ThoughtChatState({
|
||||
required this.sequenceId,
|
||||
required this.localThoughts,
|
||||
required this.currentTopic,
|
||||
required this.messageController,
|
||||
required this.scrollController,
|
||||
required this.isStreaming,
|
||||
required this.streamingParts,
|
||||
required this.reasoningChunks,
|
||||
required this.listController,
|
||||
required this.bottomGradientNotifier,
|
||||
required this.sendMessage,
|
||||
});
|
||||
}
|
||||
|
||||
ThoughtChatState useThoughtChat(
|
||||
WidgetRef ref, {
|
||||
String? initialSequenceId,
|
||||
List<SnThinkingThought>? initialThoughts,
|
||||
String? initialTopic,
|
||||
List<Map<String, dynamic>> attachedMessages = const [],
|
||||
List<String> attachedPosts = const [],
|
||||
VoidCallback? onSequenceIdChanged,
|
||||
}) {
|
||||
final sequenceId = useState<String?>(initialSequenceId);
|
||||
final localThoughts = useState<List<SnThinkingThought>>(
|
||||
initialThoughts ?? [],
|
||||
);
|
||||
final currentTopic = useState<String?>(initialTopic ?? 'aiThought'.tr());
|
||||
|
||||
final messageController = useTextEditingController();
|
||||
final scrollController = useScrollController();
|
||||
final isStreaming = useState(false);
|
||||
final streamingParts = useState<List<SnThinkingMessagePart>>([]);
|
||||
final reasoningChunks = useState<List<String>>([]);
|
||||
|
||||
final listController = useMemoized(() => ListController(), []);
|
||||
|
||||
// Scroll animation notifiers
|
||||
final bottomGradientNotifier = useState(ValueNotifier<double>(0.0));
|
||||
|
||||
// Scroll to bottom when thoughts change or streaming state changes
|
||||
useEffect(() {
|
||||
if (localThoughts.value.isNotEmpty || isStreaming.value) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
scrollController.animateTo(
|
||||
0,
|
||||
duration: const Duration(milliseconds: 300),
|
||||
curve: Curves.easeOut,
|
||||
);
|
||||
});
|
||||
}
|
||||
return null;
|
||||
}, [localThoughts.value.length, isStreaming.value]);
|
||||
|
||||
// Add scroll listener for gradient animations
|
||||
useEffect(() {
|
||||
void onScroll() {
|
||||
// Update gradient animations
|
||||
final pixels = scrollController.position.pixels;
|
||||
|
||||
// Bottom gradient: appears when not at bottom (pixels > 0)
|
||||
bottomGradientNotifier.value.value = (pixels / 500.0).clamp(0.0, 1.0);
|
||||
}
|
||||
|
||||
scrollController.addListener(onScroll);
|
||||
return () => scrollController.removeListener(onScroll);
|
||||
}, [scrollController]);
|
||||
|
||||
Future<void> sendMessage() async {
|
||||
if (messageController.text.trim().isEmpty) return;
|
||||
|
||||
final userMessage = messageController.text.trim();
|
||||
|
||||
// Add user message to local thoughts
|
||||
final userInfo = ref.read(userInfoProvider);
|
||||
final now = DateTime.now();
|
||||
final userThought = SnThinkingThought(
|
||||
id: 'user-${DateTime.now().millisecondsSinceEpoch}',
|
||||
parts: [
|
||||
SnThinkingMessagePart(
|
||||
type: ThinkingMessagePartType.text,
|
||||
text: userMessage,
|
||||
),
|
||||
],
|
||||
files: [],
|
||||
role: ThinkingThoughtRole.user,
|
||||
sequenceId: sequenceId.value ?? '',
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
sequence: SnThinkingSequence(
|
||||
id: sequenceId.value ?? '',
|
||||
accountId: userInfo.value!.id,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
),
|
||||
);
|
||||
localThoughts.value = [userThought, ...localThoughts.value];
|
||||
|
||||
final request = StreamThinkingRequest(
|
||||
userMessage: userMessage,
|
||||
sequenceId: sequenceId.value,
|
||||
accpetProposals: ['post_create'],
|
||||
attachedMessages: attachedMessages,
|
||||
attachedPosts: attachedPosts,
|
||||
);
|
||||
|
||||
try {
|
||||
isStreaming.value = true;
|
||||
streamingParts.value = [];
|
||||
reasoningChunks.value = [];
|
||||
|
||||
final apiClient = ref.read(apiClientProvider);
|
||||
final response = await apiClient.post(
|
||||
'/insight/thought',
|
||||
data: request.toJson(),
|
||||
options: Options(
|
||||
responseType: ResponseType.stream,
|
||||
sendTimeout: Duration(minutes: 1),
|
||||
receiveTimeout: Duration(minutes: 1),
|
||||
),
|
||||
);
|
||||
|
||||
final stream = response.data.stream;
|
||||
final lineBuffer = StringBuffer();
|
||||
|
||||
stream.listen(
|
||||
(data) {
|
||||
final chunk = utf8.decode(data);
|
||||
lineBuffer.write(chunk);
|
||||
final lines = lineBuffer.toString().split('\n');
|
||||
lineBuffer.clear();
|
||||
lineBuffer.write(lines.last); // keep incomplete line
|
||||
|
||||
for (final line in lines.sublist(0, lines.length - 1)) {
|
||||
if (line.trim().isEmpty) continue;
|
||||
try {
|
||||
if (line.startsWith('data: ')) {
|
||||
final jsonStr = line.substring(6);
|
||||
final event = jsonDecode(jsonStr);
|
||||
final type = event['type'];
|
||||
final eventData = event['data'];
|
||||
if (type == 'text') {
|
||||
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') {
|
||||
streamingParts.value = [
|
||||
...streamingParts.value,
|
||||
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') {
|
||||
reasoningChunks.value = [...reasoningChunks.value, eventData];
|
||||
}
|
||||
} else if (line.startsWith('topic: ')) {
|
||||
final jsonStr = line.substring(7);
|
||||
final event = jsonDecode(jsonStr);
|
||||
currentTopic.value = event['data'];
|
||||
} else if (line.startsWith('thought: ')) {
|
||||
final jsonStr = line.substring(9);
|
||||
final event = jsonDecode(jsonStr);
|
||||
final aiThought = SnThinkingThought.fromJson(event['data']);
|
||||
localThoughts.value = [aiThought, ...localThoughts.value];
|
||||
if (sequenceId.value == null &&
|
||||
aiThought.sequenceId.isNotEmpty) {
|
||||
sequenceId.value = aiThought.sequenceId;
|
||||
onSequenceIdChanged?.call();
|
||||
}
|
||||
isStreaming.value = false;
|
||||
}
|
||||
} catch (e) {
|
||||
// Ignore parsing errors for individual events
|
||||
}
|
||||
}
|
||||
},
|
||||
onDone: () {
|
||||
if (isStreaming.value) {
|
||||
isStreaming.value = false;
|
||||
// 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: sequenceId.value ?? '',
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
sequence: SnThinkingSequence(
|
||||
id: sequenceId.value ?? '',
|
||||
accountId: '',
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
),
|
||||
);
|
||||
localThoughts.value = [errorThought, ...localThoughts.value];
|
||||
}
|
||||
},
|
||||
onError: (error) {
|
||||
isStreaming.value = false;
|
||||
|
||||
// Add error thought to the list
|
||||
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: '',
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
),
|
||||
);
|
||||
localThoughts.value = [errorThought, ...localThoughts.value];
|
||||
},
|
||||
);
|
||||
|
||||
messageController.clear();
|
||||
FocusManager.instance.primaryFocus?.unfocus();
|
||||
} catch (error) {
|
||||
isStreaming.value = false;
|
||||
|
||||
// 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: sequenceId.value ?? '',
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
sequence: SnThinkingSequence(
|
||||
id: sequenceId.value ?? '',
|
||||
accountId: userInfo.value!.id,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
),
|
||||
);
|
||||
localThoughts.value = [errorThought, ...localThoughts.value];
|
||||
}
|
||||
}
|
||||
|
||||
return ThoughtChatState(
|
||||
sequenceId: sequenceId,
|
||||
localThoughts: localThoughts,
|
||||
currentTopic: currentTopic,
|
||||
messageController: messageController,
|
||||
scrollController: scrollController,
|
||||
isStreaming: isStreaming,
|
||||
streamingParts: streamingParts,
|
||||
reasoningChunks: reasoningChunks,
|
||||
listController: listController,
|
||||
bottomGradientNotifier: bottomGradientNotifier,
|
||||
sendMessage: sendMessage,
|
||||
);
|
||||
}
|
||||
|
||||
class ThoughtChatInterface extends HookConsumerWidget {
|
||||
final List<SnThinkingThought>? initialThoughts;
|
||||
final String? initialTopic;
|
||||
final List<Map<String, dynamic>> attachedMessages;
|
||||
final List<String> attachedPosts;
|
||||
|
||||
const ThoughtChatInterface({
|
||||
super.key,
|
||||
this.initialThoughts,
|
||||
this.initialTopic,
|
||||
this.attachedMessages = const [],
|
||||
this.attachedPosts = const [],
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final chatState = useThoughtChat(
|
||||
ref,
|
||||
initialThoughts: initialThoughts,
|
||||
initialTopic: initialTopic,
|
||||
attachedMessages: attachedMessages,
|
||||
attachedPosts: attachedPosts,
|
||||
);
|
||||
|
||||
return Stack(
|
||||
children: [
|
||||
// Thoughts list
|
||||
Center(
|
||||
child: Container(
|
||||
constraints: BoxConstraints(maxWidth: 640),
|
||||
child: Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: SuperListView.builder(
|
||||
listController: chatState.listController,
|
||||
controller: chatState.scrollController,
|
||||
padding: EdgeInsets.only(
|
||||
top: 16,
|
||||
bottom:
|
||||
MediaQuery.of(context).padding.bottom +
|
||||
80, // Leave space for thought input
|
||||
),
|
||||
reverse: true,
|
||||
itemCount:
|
||||
chatState.localThoughts.value.length +
|
||||
(chatState.isStreaming.value ? 1 : 0),
|
||||
itemBuilder: (context, index) {
|
||||
if (chatState.isStreaming.value && index == 0) {
|
||||
final streamingText = chatState.streamingParts.value
|
||||
.where(
|
||||
(p) => p.type == ThinkingMessagePartType.text,
|
||||
)
|
||||
.map((p) => p.text ?? '')
|
||||
.join('');
|
||||
final streamingFunctionCalls =
|
||||
chatState.streamingParts.value
|
||||
.where(
|
||||
(p) =>
|
||||
p.type ==
|
||||
ThinkingMessagePartType.functionCall,
|
||||
)
|
||||
.map(
|
||||
(p) => JsonEncoder.withIndent(
|
||||
' ',
|
||||
).convert(p.functionCall?.toJson() ?? {}),
|
||||
)
|
||||
.toList();
|
||||
return ThoughtItem(
|
||||
isStreaming: true,
|
||||
streamingText: streamingText,
|
||||
reasoningChunks: chatState.reasoningChunks.value,
|
||||
streamingFunctionCalls: streamingFunctionCalls,
|
||||
);
|
||||
}
|
||||
final thoughtIndex =
|
||||
chatState.isStreaming.value ? index - 1 : index;
|
||||
final thought =
|
||||
chatState.localThoughts.value[thoughtIndex];
|
||||
return ThoughtItem(
|
||||
thought: thought,
|
||||
thoughtIndex: thoughtIndex,
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
// Bottom gradient - appears when scrolling towards newer thoughts (behind thought input)
|
||||
AnimatedBuilder(
|
||||
animation: chatState.bottomGradientNotifier.value,
|
||||
builder:
|
||||
(context, child) => Positioned(
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
child: Opacity(
|
||||
opacity: chatState.bottomGradientNotifier.value.value,
|
||||
child: Container(
|
||||
height: math.min(
|
||||
MediaQuery.of(context).size.height * 0.1,
|
||||
128,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.bottomCenter,
|
||||
end: Alignment.topCenter,
|
||||
colors: [
|
||||
Theme.of(
|
||||
context,
|
||||
).colorScheme.surfaceContainer.withOpacity(0.8),
|
||||
Theme.of(
|
||||
context,
|
||||
).colorScheme.surfaceContainer.withOpacity(0.0),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
// Thought Input positioned above gradient (higher z-index)
|
||||
Positioned(
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0, // At the very bottom, above gradient
|
||||
child: Center(
|
||||
child: Container(
|
||||
constraints: BoxConstraints(maxWidth: 640),
|
||||
child: ThoughtInput(
|
||||
messageController: chatState.messageController,
|
||||
isStreaming: chatState.isStreaming.value,
|
||||
onSend: chatState.sendMessage,
|
||||
attachedMessages: attachedMessages,
|
||||
attachedPosts: attachedPosts,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
List<Map<String, String>> _extractProposals(String content) {
|
||||
final proposalRegex = RegExp(
|
||||
@@ -211,8 +686,13 @@ class ThoughtItem extends StatelessWidget {
|
||||
(!isStreaming && thought!.role == ThinkingThoughtRole.assistant);
|
||||
|
||||
final List<Map<String, String>> proposals =
|
||||
!isStreaming && thought!.content != null
|
||||
? _extractProposals(thought!.content!)
|
||||
!isStreaming
|
||||
? _extractProposals(
|
||||
thought!.parts
|
||||
.where((p) => p.type == ThinkingMessagePartType.text)
|
||||
.map((p) => p.text ?? '')
|
||||
.join(''),
|
||||
)
|
||||
: [];
|
||||
|
||||
return Container(
|
||||
@@ -239,10 +719,27 @@ class ThoughtItem extends StatelessWidget {
|
||||
spacing: 8,
|
||||
children: [
|
||||
// Main content
|
||||
ThoughtContent(
|
||||
isStreaming: isStreaming,
|
||||
streamingText: streamingText,
|
||||
thought: thought,
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Flexible(
|
||||
child: ThoughtContent(
|
||||
isStreaming: isStreaming,
|
||||
streamingText: streamingText,
|
||||
thought: thought,
|
||||
),
|
||||
),
|
||||
if (isStreaming && isAI)
|
||||
SizedBox(
|
||||
height: 20,
|
||||
width: 20,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2.5,
|
||||
padding: const EdgeInsets.all(4),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
// Reasoning chunks (streaming only)
|
||||
@@ -251,10 +748,10 @@ class ThoughtItem extends StatelessWidget {
|
||||
|
||||
// Function calls
|
||||
if (streamingFunctionCalls.isNotEmpty ||
|
||||
(thought?.chunks.isNotEmpty ?? false) &&
|
||||
thought!.chunks.any(
|
||||
(chunk) =>
|
||||
chunk.type == ThinkingChunkType.functionCall,
|
||||
(thought?.parts.isNotEmpty ?? false) &&
|
||||
thought!.parts.any(
|
||||
(part) =>
|
||||
part.type == ThinkingMessagePartType.functionCall,
|
||||
))
|
||||
FunctionCallsSection(
|
||||
isStreaming: isStreaming,
|
||||
@@ -263,7 +760,10 @@ class ThoughtItem extends StatelessWidget {
|
||||
),
|
||||
|
||||
// Token count and model name (for completed AI thoughts only)
|
||||
if (!isStreaming && isAI && thought != null)
|
||||
if (!isStreaming &&
|
||||
isAI &&
|
||||
thought != null &&
|
||||
!thought!.id.startsWith('error-'))
|
||||
TokenInfo(thought: thought!),
|
||||
|
||||
// Proposals (for completed AI thoughts only)
|
||||
@@ -272,8 +772,6 @@ class ThoughtItem extends StatelessWidget {
|
||||
proposals: proposals,
|
||||
onProposalAction: _handleProposalAction,
|
||||
),
|
||||
|
||||
if (isStreaming && isAI) LinearProgressIndicator(),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
Reference in New Issue
Block a user