refactor: 重构聊天模块支持 SSE 断线重连及用户上下文隔离

This commit is contained in:
zl-q
2026-03-30 09:06:10 +08:00
parent 1aac62f39e
commit 4285b4ec80
28 changed files with 1624 additions and 658 deletions
@@ -25,16 +25,16 @@ class ChatApiImpl implements ChatApi {
@override
Future<Stream<String>> streamRunEvents(
String threadId, {
required String runId,
String? lastEventId,
}) {
final headers = <String, String>{'Accept': 'text/event-stream'};
if (lastEventId != null && lastEventId.isNotEmpty) {
headers['Last-Event-ID'] = lastEventId;
}
return _apiClient.getSseLines(
'/api/v1/agent/runs/$threadId/events',
headers: headers,
);
final encodedRunId = Uri.encodeQueryComponent(runId);
final path = '/api/v1/agent/runs/$threadId/events?runId=$encodedRunId';
return _apiClient.getSseLines(path, headers: headers);
}
@override
@@ -9,7 +9,14 @@ import 'package:social_app/core/chat/ag_ui_service.dart';
import 'package:social_app/core/chat/chat_list_item.dart';
import 'package:social_app/core/chat/chat_orchestrator.dart';
import 'package:social_app/core/chat/chat_history_repository.dart';
import 'package:social_app/core/chat/chat_timeline_reconciler.dart';
import 'package:social_app/core/l10n/l10n.dart';
import 'chat_bloc_recovery_utils.dart';
part 'chat_bloc_events.dart';
part 'chat_bloc_send.dart';
part 'chat_bloc_history.dart';
part 'chat_bloc_attachments.dart';
class ChatState implements ChatOrchestratorState {
@override
@@ -34,6 +41,7 @@ class ChatState implements ChatOrchestratorState {
final bool hasEarlierHistory;
@override
final AgentStage? currentStage;
final bool hasSeenStep;
const ChatState({
this.items = const [],
@@ -47,6 +55,7 @@ class ChatState implements ChatOrchestratorState {
this.oldestLoadedDate,
this.hasEarlierHistory = false,
this.currentStage,
this.hasSeenStep = false,
});
@override
@@ -71,6 +80,7 @@ class ChatState implements ChatOrchestratorState {
Object? oldestLoadedDate = _unset,
bool? hasEarlierHistory,
Object? currentStage = _unset,
bool? hasSeenStep,
}) {
return ChatState(
items: items ?? this.items,
@@ -90,6 +100,7 @@ class ChatState implements ChatOrchestratorState {
currentStage: currentStage == _unset
? this.currentStage
: currentStage as AgentStage?,
hasSeenStep: hasSeenStep ?? this.hasSeenStep,
);
}
}
@@ -99,14 +110,22 @@ class ChatBloc extends Cubit<ChatState> implements ChatOrchestrator {
AgUiService? service,
required ChatApi chatApi,
ChatHistoryRepository? historyRepository,
Duration recoveryPollInterval = const Duration(milliseconds: 700),
Duration recoveryTimeout = const Duration(seconds: 20),
}) : _service =
service ??
AgUiService(chatApi: chatApi, historyRepository: historyRepository),
_recoveryPollInterval = recoveryPollInterval,
_recoveryTimeout = recoveryTimeout,
super(const ChatState()) {
_service.onEvent = _handleEvent;
}
final AgUiService _service;
final Duration _recoveryPollInterval;
final Duration _recoveryTimeout;
String? _activeUserId;
int _sessionEpoch = 0;
final Map<String, Uint8List> _attachmentPreviewCache = <String, Uint8List>{};
final Map<String, Future<Uint8List?>> _attachmentPreviewInflight =
<String, Future<Uint8List?>>{};
@@ -121,501 +140,23 @@ class ChatBloc extends Cubit<ChatState> implements ChatOrchestrator {
currentMessageId: currentMessageId,
error: error,
currentStage: null,
hasSeenStep: false,
);
}
void _handleEvent(AgUiEvent event) {
switch (event.type) {
case AgUiEventType.runStarted:
emit(
state.copyWith(
isSending: false,
isWaitingFirstToken: true,
isCancelling: false,
error: null,
currentStage: null,
),
);
case AgUiEventType.runFinished:
emit(
_resetRunState().copyWith(items: _removeToolCallItems(state.items)),
);
case AgUiEventType.runError:
final errorEvent = event as RunErrorEvent;
final isCanceledByUser = errorEvent.code == 'RUN_CANCELED';
emit(
_resetRunState(
error: isCanceledByUser ? null : errorEvent.message,
).copyWith(
items: _markActiveToolCallsFailed(
state.items,
reason: isCanceledByUser
? L10n.current.chatRunCanceled
: L10n.current.chatRunFailed,
),
),
);
case AgUiEventType.stepStarted:
_handleStepStarted(event as StepStartedEvent);
case AgUiEventType.stepFinished:
_handleStepFinished(event as StepFinishedEvent);
case AgUiEventType.textMessageEnd:
_handleTextMessageEnd(event as TextMessageEndEvent);
case AgUiEventType.toolCallStart:
_handleToolCallStart(event as ToolCallStartEvent);
case AgUiEventType.toolCallArgs:
_handleToolCallArgs(event as ToolCallArgsEvent);
case AgUiEventType.toolCallEnd:
_handleToolCallEnd(event as ToolCallEndEvent);
case AgUiEventType.toolCallResult:
_handleToolCallResult(event as ToolCallResultEvent);
case AgUiEventType.toolCallError:
_handleToolCallError(event as ToolCallErrorEvent);
case AgUiEventType.unknown:
break;
}
}
void _handleStepStarted(StepStartedEvent event) {
emit(state.copyWith(currentStage: stageFromStepName(event.stepName)));
}
void _handleStepFinished(StepFinishedEvent event) {
if (state.currentStage == stageFromStepName(event.stepName)) {
emit(state.copyWith(currentStage: null));
}
}
void _handleTextMessageEnd(TextMessageEndEvent event) {
final timestamp = DateTime.now();
final items = _updateOrAddMessage(
state.items,
event.messageId,
event.answer,
timestamp,
);
final uiSchema = event.uiSchema;
if (uiSchema != null) {
_upsertUiSchema(items, event.messageId, uiSchema, timestamp);
}
final withoutToolCalls = _removeToolCallItems(items);
emit(
state.copyWith(
items: withoutToolCalls,
currentMessageId: null,
isWaitingFirstToken: false,
isStreaming: false,
),
);
}
List<ChatListItem> _updateOrAddMessage(
List<ChatListItem> items,
String messageId,
String content,
DateTime timestamp,
) {
final result = List<ChatListItem>.from(items);
final index = result.indexWhere(
(item) => item.id == messageId && item is TextMessageItem,
);
if (index >= 0) {
final existing = result[index] as TextMessageItem;
result[index] = existing.copyWith(content: content, isStreaming: false);
} else {
result.add(
TextMessageItem(
id: messageId,
content: content,
timestamp: timestamp,
sender: MessageSender.ai,
isStreaming: false,
),
);
}
return result;
}
void _upsertUiSchema(
List<ChatListItem> items,
String messageId,
Map<String, dynamic> uiSchema,
DateTime timestamp,
) {
final uiItemId = '$messageId-ui';
final existingIndex = items.indexWhere((item) => item.id == uiItemId);
final uiItem = ToolResultItem(
id: uiItemId,
callId: messageId,
uiSchema: uiSchema,
timestamp: timestamp,
sender: MessageSender.ai,
);
if (existingIndex >= 0) {
items[existingIndex] = uiItem;
} else {
items.add(uiItem);
}
}
void _handleToolCallStart(ToolCallStartEvent event) {
final items = List<ChatListItem>.from(state.items)
..add(
ToolCallItem(
id: event.toolCallId,
callId: event.toolCallId,
toolName: event.toolCallName,
args: const {},
status: ToolCallStatus.pending,
timestamp: DateTime.now(),
sender: MessageSender.ai,
),
);
emit(state.copyWith(items: items));
}
void _handleToolCallArgs(ToolCallArgsEvent event) {
final items = state.items.map((item) {
if (item is ToolCallItem && item.id == event.toolCallId) {
return item.copyWith(args: event.args);
}
return item;
}).toList();
emit(state.copyWith(items: items));
}
void _handleToolCallEnd(ToolCallEndEvent event) {
final items = state.items.map((item) {
if (item is ToolCallItem && item.id == event.toolCallId) {
return item.copyWith(status: ToolCallStatus.executing);
}
return item;
}).toList();
emit(state.copyWith(items: items));
}
void _handleToolCallResult(ToolCallResultEvent event) {
final items = state.items.map((item) {
if (item is ToolCallItem && item.id == event.toolCallId) {
return item.copyWith(status: ToolCallStatus.completed);
}
return item;
}).toList();
emit(state.copyWith(items: items));
}
List<ChatListItem> _removeToolCallItems(List<ChatListItem> items) {
return items.where((item) => item is! ToolCallItem).toList();
}
List<ChatListItem> _markActiveToolCallsFailed(
List<ChatListItem> items, {
required String reason,
}) {
return items.map((item) {
if (item is! ToolCallItem) {
return item;
}
if (item.status == ToolCallStatus.error) {
return item;
}
if (item.status == ToolCallStatus.completed) {
return item;
}
return item.copyWith(status: ToolCallStatus.error, errorMessage: reason);
}).toList();
}
void _handleToolCallError(ToolCallErrorEvent event) {
final items = state.items.map((item) {
if (item is ToolCallItem && item.id == event.toolCallId) {
return item.copyWith(
status: ToolCallStatus.error,
errorMessage: event.error,
);
}
return item;
}).toList();
emit(state.copyWith(items: items));
}
List<ChatListItem> _convertHistoryMessages(List<HistoryMessage> messages) {
final converted = <ChatListItem>[];
for (final msg in messages) {
final normalizedRole = msg.role.toLowerCase();
final isUser = normalizedRole == 'user';
final isTool = normalizedRole == 'tool' || normalizedRole == 'tools';
final sender = isUser ? MessageSender.user : MessageSender.ai;
final attachments = msg.attachments
.map(
(attachment) => <String, dynamic>{
'url': attachment.url,
'mimeType': attachment.mimeType,
},
)
.toList();
if (!isTool && (msg.content.isNotEmpty || isUser)) {
converted.add(
TextMessageItem(
id: msg.id,
content: msg.content,
timestamp: msg.timestamp,
sender: sender,
attachments: attachments,
),
);
}
if (!isTool && msg.uiSchema != null) {
converted.add(
ToolResultItem(
id: '${msg.id}-ui',
callId: msg.id,
uiSchema: msg.uiSchema!,
timestamp: msg.timestamp,
sender: MessageSender.ai,
),
);
}
}
return converted;
}
DateTime? _extractDateFromItems(List<ChatListItem> items) {
if (items.isEmpty) return null;
return items
.map(
(item) => DateTime(
item.timestamp.year,
item.timestamp.month,
item.timestamp.day,
),
)
.reduce((a, b) => a.isBefore(b) ? a : b);
}
@override
Future<void> sendMessage(String content, {List<XFile>? images}) async {
final messageId = 'user-${DateTime.now().millisecondsSinceEpoch}';
final attachments = (images ?? const <XFile>[])
.map(
(image) => <String, dynamic>{
'path': image.path,
'mimeType': image.mimeType ?? 'image/jpeg',
'uploading': true,
},
)
.toList();
final userMessage = TextMessageItem(
id: messageId,
content: content,
timestamp: DateTime.now(),
sender: MessageSender.user,
attachments: attachments,
);
emit(
state.copyWith(
items: [...state.items, userMessage],
isSending: true,
isWaitingFirstToken: true,
isStreaming: false,
isCancelling: false,
error: null,
),
);
try {
final uploadInputs = await Future.wait(
(images ?? const <XFile>[]).map(
(image) async => AttachmentUploadInput(
name: image.name,
mimeType: image.mimeType ?? 'image/jpeg',
bytes: await image.readAsBytes(),
localPath: image.path,
),
),
);
final sendResult = await _service.sendMessage(
content,
attachments: uploadInputs,
);
_syncUploadedAttachments(
messageId: messageId,
uploadedAttachments: sendResult.uploadedAttachments,
);
} catch (error) {
final sseClosedBeforeTerminal = _isSseClosedBeforeTerminalError(error);
var recoveredFromHistory = false;
if (sseClosedBeforeTerminal) {
recoveredFromHistory = await _recoverFromAbnormalSseClose();
}
_markAttachmentUploadDone(messageId);
emit(
state.copyWith(
isSending: false,
isWaitingFirstToken: false,
isStreaming: false,
isCancelling: false,
currentStage: null,
error: sseClosedBeforeTerminal
? (recoveredFromHistory
? null
: L10n.current.chatSseInterruptedRetry)
: error.toString(),
),
);
}
}
bool _isSseClosedBeforeTerminalError(Object error) {
final text = error.toString().toLowerCase();
return text.contains('sse closed before terminal event');
}
Future<bool> _recoverFromAbnormalSseClose() async {
try {
final snapshot = await _service.loadHistory();
final historyItems = _convertHistoryMessages(snapshot.messages);
final mergedById = <String, ChatListItem>{
for (final item in historyItems) item.id: item,
};
for (final item in state.items) {
mergedById[item.id] = item;
}
final merged = mergedById.values.toList()
..sort((a, b) => a.timestamp.compareTo(b.timestamp));
emit(
state.copyWith(
items: merged,
oldestLoadedDate: _extractDateFromItems(merged),
hasEarlierHistory: snapshot.hasMore,
),
);
return true;
} catch (_) {
return false;
}
}
void _syncUploadedAttachments({
required String messageId,
required List<UploadedAttachment> uploadedAttachments,
}) {
if (uploadedAttachments.isEmpty) {
_markAttachmentUploadDone(messageId);
return;
}
final items = state.items.map((item) {
if (item is! TextMessageItem || item.id != messageId) {
return item;
}
final synced = item.attachments.map((attachment) {
final localPath = attachment['path'];
if (localPath is! String || localPath.isEmpty) {
return <String, dynamic>{...attachment, 'uploading': false};
}
UploadedAttachment? matched;
for (final candidate in uploadedAttachments) {
if (candidate.localPath == localPath) {
matched = candidate;
break;
}
}
if (matched == null) {
return <String, dynamic>{...attachment, 'uploading': false};
}
return <String, dynamic>{
...attachment,
'url': matched.url,
'mimeType': matched.mimeType,
'uploading': false,
};
}).toList();
return item.copyWith(attachments: synced);
}).toList();
emit(state.copyWith(items: items));
}
void _markAttachmentUploadDone(String messageId) {
final items = state.items.map((item) {
if (item is! TextMessageItem || item.id != messageId) {
return item;
}
final done = item.attachments
.map(
(attachment) => <String, dynamic>{
...attachment,
'uploading': false,
},
)
.toList();
return item.copyWith(attachments: done);
}).toList();
emit(state.copyWith(items: items));
Future<void> sendMessage(String content, {List<XFile>? images}) {
return _sendMessage(content, images: images);
}
@override
Future<void> loadHistory() async {
if (state.isLoadingHistory) return;
emit(state.copyWith(isLoadingHistory: true));
try {
final snapshot = await _service.loadHistory();
final newItems = _convertHistoryMessages(snapshot.messages);
final mergedById = <String, ChatListItem>{
for (final item in newItems) item.id: item,
};
for (final item in state.items) {
mergedById[item.id] = item;
}
final merged = mergedById.values.toList()
..sort((a, b) => a.timestamp.compareTo(b.timestamp));
final oldestDate = _extractDateFromItems(merged);
emit(
state.copyWith(
items: merged,
oldestLoadedDate: oldestDate,
hasEarlierHistory: snapshot.hasMore,
),
);
} finally {
emit(state.copyWith(isLoadingHistory: false));
}
Future<void> loadHistory() {
return _loadHistory();
}
@override
Future<void> loadMoreHistory() async {
if (state.isLoadingHistory || !state.hasEarlierHistory) return;
if (state.oldestLoadedDate == null) return;
emit(state.copyWith(isLoadingHistory: true));
try {
final snapshot = await _service.loadHistory(
beforeDate: state.oldestLoadedDate,
);
final newItems = _convertHistoryMessages(snapshot.messages);
final mergedById = <String, ChatListItem>{
for (final item in state.items) item.id: item,
};
for (final item in newItems) {
mergedById[item.id] = item;
}
final merged = mergedById.values.toList()
..sort((a, b) => a.timestamp.compareTo(b.timestamp));
final oldestDate = _extractDateFromItems(merged);
emit(
state.copyWith(
items: merged,
oldestLoadedDate: oldestDate,
hasEarlierHistory: snapshot.hasMore,
),
);
} finally {
emit(state.copyWith(isLoadingHistory: false));
}
Future<void> loadMoreHistory() {
return _loadMoreHistory();
}
@override
@@ -649,32 +190,29 @@ class ChatBloc extends Cubit<ChatState> implements ChatOrchestrator {
}
}
Future<Uint8List?> loadAttachmentPreview(String previewPath) async {
final cached = _attachmentPreviewCache[previewPath];
if (cached != null) {
return cached;
}
final pending = _attachmentPreviewInflight[previewPath];
if (pending != null) {
return pending;
}
final future = (() async {
try {
final bytes = await _service.fetchAttachmentPreview(previewPath);
_attachmentPreviewCache[previewPath] = bytes;
return bytes;
} catch (_) {
return null;
} finally {
_attachmentPreviewInflight.remove(previewPath);
}
})();
_attachmentPreviewInflight[previewPath] = future;
return future;
}
@override
void clearError() {
emit(state.copyWith(error: null));
}
Future<Uint8List?> loadAttachmentPreview(String previewPath) {
return _loadAttachmentPreview(previewPath);
}
Future<void> switchUser(String? userId) async {
final normalizedUserId = userId?.trim();
if (_activeUserId == normalizedUserId) {
return;
}
final epoch = ++_sessionEpoch;
_activeUserId = normalizedUserId;
await _service.setUserContext(normalizedUserId);
if (epoch != _sessionEpoch) {
return;
}
_attachmentPreviewCache.clear();
_attachmentPreviewInflight.clear();
emit(const ChatState());
}
}
@@ -0,0 +1,88 @@
// ignore_for_file: invalid_use_of_protected_member, invalid_use_of_visible_for_testing_member
part of 'chat_bloc.dart';
extension _ChatBlocAttachments on ChatBloc {
void _syncUploadedAttachments({
required String messageId,
required List<UploadedAttachment> uploadedAttachments,
}) {
if (uploadedAttachments.isEmpty) {
_markAttachmentUploadDone(messageId);
return;
}
final items = state.items.map((item) {
if (item is! TextMessageItem || item.id != messageId) {
return item;
}
final synced = item.attachments.map((attachment) {
final localPath = attachment['path'];
if (localPath is! String || localPath.isEmpty) {
return <String, dynamic>{...attachment, 'uploading': false};
}
UploadedAttachment? matched;
for (final candidate in uploadedAttachments) {
if (candidate.localPath == localPath) {
matched = candidate;
break;
}
}
if (matched == null) {
return <String, dynamic>{...attachment, 'uploading': false};
}
return <String, dynamic>{
...attachment,
'url': matched.url,
'mimeType': matched.mimeType,
'uploading': false,
};
}).toList();
return item.copyWith(attachments: synced);
}).toList();
emit(state.copyWith(items: items));
}
void _markAttachmentUploadDone(String messageId) {
final items = state.items.map((item) {
if (item is! TextMessageItem || item.id != messageId) {
return item;
}
final done = item.attachments
.map(
(attachment) => <String, dynamic>{
...attachment,
'uploading': false,
},
)
.toList();
return item.copyWith(attachments: done);
}).toList();
emit(state.copyWith(items: items));
}
Future<Uint8List?> _loadAttachmentPreview(String previewPath) async {
final cached = _attachmentPreviewCache[previewPath];
if (cached != null) {
return cached;
}
final pending = _attachmentPreviewInflight[previewPath];
if (pending != null) {
return pending;
}
final future = (() async {
try {
final bytes = await _service.fetchAttachmentPreview(previewPath);
_attachmentPreviewCache[previewPath] = bytes;
return bytes;
} catch (_) {
return null;
} finally {
_attachmentPreviewInflight.remove(previewPath);
}
})();
_attachmentPreviewInflight[previewPath] = future;
return future;
}
}
@@ -0,0 +1,305 @@
// ignore_for_file: invalid_use_of_protected_member, invalid_use_of_visible_for_testing_member
part of 'chat_bloc.dart';
extension _ChatBlocEvents on ChatBloc {
void _handleEvent(AgUiEvent event) {
switch (event.type) {
case AgUiEventType.runStarted:
emit(
state.copyWith(
isSending: false,
isWaitingFirstToken: true,
isCancelling: false,
error: null,
currentStage: null,
hasSeenStep: false,
),
);
case AgUiEventType.runFinished:
emit(
_resetRunState().copyWith(items: _removeToolCallItems(state.items)),
);
case AgUiEventType.runError:
final errorEvent = event as RunErrorEvent;
final isCanceledByUser = errorEvent.code == 'RUN_CANCELED';
emit(
_resetRunState(
error: isCanceledByUser ? null : errorEvent.message,
).copyWith(
items: _markActiveToolCallsFailed(
state.items,
reason: isCanceledByUser
? L10n.current.chatRunCanceled
: L10n.current.chatRunFailed,
),
),
);
case AgUiEventType.stepStarted:
_handleStepStarted(event as StepStartedEvent);
case AgUiEventType.stepFinished:
_handleStepFinished(event as StepFinishedEvent);
case AgUiEventType.textMessageEnd:
_handleTextMessageEnd(event as TextMessageEndEvent);
case AgUiEventType.toolCallStart:
_handleToolCallStart(event as ToolCallStartEvent);
case AgUiEventType.toolCallArgs:
_handleToolCallArgs(event as ToolCallArgsEvent);
case AgUiEventType.toolCallEnd:
_handleToolCallEnd(event as ToolCallEndEvent);
case AgUiEventType.toolCallResult:
_handleToolCallResult(event as ToolCallResultEvent);
case AgUiEventType.toolCallError:
_handleToolCallError(event as ToolCallErrorEvent);
case AgUiEventType.unknown:
break;
}
}
void _handleStepStarted(StepStartedEvent event) {
emit(
state.copyWith(
currentStage: stageFromStepName(event.stepName),
hasSeenStep: true,
),
);
}
void _handleStepFinished(StepFinishedEvent event) {
if (state.currentStage == stageFromStepName(event.stepName)) {
emit(state.copyWith(currentStage: null));
}
}
void _handleTextMessageEnd(TextMessageEndEvent event) {
final timestamp = DateTime.now();
final items = _updateOrAddMessage(
state.items,
event.messageId,
event.answer,
timestamp,
);
final uiSchema = event.uiSchema;
if (uiSchema != null) {
_upsertUiSchema(items, event.messageId, uiSchema, timestamp);
}
emit(
state.copyWith(
items: _removeToolCallItems(items),
currentMessageId: null,
isWaitingFirstToken: false,
isStreaming: false,
),
);
}
List<ChatListItem> _updateOrAddMessage(
List<ChatListItem> items,
String messageId,
String content,
DateTime timestamp,
) {
final result = List<ChatListItem>.from(items);
final index = result.indexWhere(
(item) => item.id == messageId && item is TextMessageItem,
);
if (index >= 0) {
final existing = result[index] as TextMessageItem;
result[index] = existing.copyWith(content: content, isStreaming: false);
return result;
}
result.add(
TextMessageItem(
id: messageId,
content: content,
timestamp: timestamp,
sender: MessageSender.ai,
isStreaming: false,
),
);
return result;
}
void _upsertUiSchema(
List<ChatListItem> items,
String messageId,
Map<String, dynamic> uiSchema,
DateTime timestamp,
) {
final uiItemId = '$messageId-ui';
final uiItem = ToolResultItem(
id: uiItemId,
callId: messageId,
uiSchema: uiSchema,
timestamp: timestamp,
sender: MessageSender.ai,
);
final existingIndex = items.indexWhere((item) => item.id == uiItemId);
if (existingIndex >= 0) {
items[existingIndex] = uiItem;
return;
}
items.add(uiItem);
}
void _handleToolCallStart(ToolCallStartEvent event) {
final exists = state.items.any(
(item) => item is ToolCallItem && item.id == event.toolCallId,
);
if (exists) {
return;
}
emit(
state.copyWith(
items: [
...state.items,
ToolCallItem(
id: event.toolCallId,
callId: event.toolCallId,
toolName: event.toolCallName,
args: const {},
status: ToolCallStatus.pending,
timestamp: DateTime.now(),
sender: MessageSender.ai,
),
],
),
);
}
void _handleToolCallArgs(ToolCallArgsEvent event) {
emit(
state.copyWith(
items: state.items.map((item) {
if (item is ToolCallItem && item.id == event.toolCallId) {
return item.copyWith(args: event.args);
}
return item;
}).toList(),
),
);
}
void _handleToolCallEnd(ToolCallEndEvent event) {
emit(
state.copyWith(
items: state.items.map((item) {
if (item is ToolCallItem && item.id == event.toolCallId) {
return item.copyWith(status: ToolCallStatus.executing);
}
return item;
}).toList(),
),
);
}
void _handleToolCallResult(ToolCallResultEvent event) {
emit(
state.copyWith(
items: state.items.map((item) {
if (item is ToolCallItem && item.id == event.toolCallId) {
return item.copyWith(status: ToolCallStatus.completed);
}
return item;
}).toList(),
),
);
}
void _handleToolCallError(ToolCallErrorEvent event) {
emit(
state.copyWith(
items: state.items.map((item) {
if (item is ToolCallItem && item.id == event.toolCallId) {
return item.copyWith(
status: ToolCallStatus.error,
errorMessage: event.error,
);
}
return item;
}).toList(),
),
);
}
List<ChatListItem> _removeToolCallItems(List<ChatListItem> items) {
return items.where((item) => item is! ToolCallItem).toList();
}
List<ChatListItem> _markActiveToolCallsFailed(
List<ChatListItem> items, {
required String reason,
}) {
return items.map((item) {
if (item is! ToolCallItem ||
item.status == ToolCallStatus.error ||
item.status == ToolCallStatus.completed) {
return item;
}
return item.copyWith(status: ToolCallStatus.error, errorMessage: reason);
}).toList();
}
List<ChatListItem> _convertHistoryMessages(List<HistoryMessage> messages) {
final converted = <ChatListItem>[];
for (final msg in messages) {
final normalizedRole = msg.role.toLowerCase();
final isUser = normalizedRole == 'user';
final isTool = normalizedRole == 'tool' || normalizedRole == 'tools';
final sender = isUser ? MessageSender.user : MessageSender.ai;
final attachments = msg.attachments
.map(
(attachment) => <String, dynamic>{
'url': attachment.url,
'mimeType': attachment.mimeType,
},
)
.toList();
if (!isTool && (msg.content.isNotEmpty || isUser)) {
converted.add(
TextMessageItem(
id: msg.id,
content: msg.content,
timestamp: msg.timestamp,
sender: sender,
isLocalEcho: false,
attachments: attachments,
),
);
}
if (!isTool && msg.uiSchema != null) {
converted.add(
ToolResultItem(
id: '${msg.id}-ui',
callId: msg.id,
uiSchema: msg.uiSchema!,
timestamp: msg.timestamp,
sender: MessageSender.ai,
),
);
}
}
return converted;
}
DateTime? _extractDateFromItems(List<ChatListItem> items) {
if (items.isEmpty) {
return null;
}
return items
.map(
(item) => DateTime(
item.timestamp.year,
item.timestamp.month,
item.timestamp.day,
),
)
.reduce((a, b) => a.isBefore(b) ? a : b);
}
}
@@ -0,0 +1,62 @@
// ignore_for_file: invalid_use_of_protected_member, invalid_use_of_visible_for_testing_member
part of 'chat_bloc.dart';
extension _ChatBlocHistory on ChatBloc {
Future<void> _loadHistory() async {
if (state.isLoadingHistory) {
return;
}
final epoch = _sessionEpoch;
emit(state.copyWith(isLoadingHistory: true));
try {
final snapshot = await _service.loadHistory();
if (epoch != _sessionEpoch) {
return;
}
final merged = _mergeWithHistory(state.items, snapshot.messages);
emit(
state.copyWith(
items: merged,
oldestLoadedDate: _extractDateFromItems(merged),
hasEarlierHistory: snapshot.hasMore,
),
);
} finally {
if (epoch == _sessionEpoch) {
emit(state.copyWith(isLoadingHistory: false));
}
}
}
Future<void> _loadMoreHistory() async {
if (state.isLoadingHistory || !state.hasEarlierHistory) {
return;
}
if (state.oldestLoadedDate == null) {
return;
}
final epoch = _sessionEpoch;
emit(state.copyWith(isLoadingHistory: true));
try {
final snapshot = await _service.loadHistory(
beforeDate: state.oldestLoadedDate,
);
if (epoch != _sessionEpoch) {
return;
}
final merged = _mergeWithHistory(state.items, snapshot.messages);
emit(
state.copyWith(
items: merged,
oldestLoadedDate: _extractDateFromItems(merged),
hasEarlierHistory: snapshot.hasMore,
),
);
} finally {
if (epoch == _sessionEpoch) {
emit(state.copyWith(isLoadingHistory: false));
}
}
}
}
@@ -0,0 +1,76 @@
import 'package:social_app/core/chat/chat_list_item.dart';
import 'package:social_app/core/chat/chat_timeline_reconciler.dart';
bool chatBlocIsSseClosedBeforeTerminalError(Object error) {
final text = error.toString().toLowerCase();
return text.contains('sse closed before terminal event');
}
DateTime? chatBlocLatestAssistantTimestamp(List<ChatListItem> items) {
DateTime? latest;
for (final item in items) {
if (item is! TextMessageItem) {
continue;
}
if (item.sender != MessageSender.ai || item.content.trim().isEmpty) {
continue;
}
if (latest == null || item.timestamp.isAfter(latest)) {
latest = item.timestamp;
}
}
return latest;
}
DateTime? chatBlocFindPersistedUserTimestamp(
List<ChatListItem> items,
TextMessageItem localEcho,
DateTime sendStartedAt,
) {
DateTime? matched;
final earliestAccepted = sendStartedAt.subtract(const Duration(seconds: 5));
final latestAccepted = sendStartedAt.add(const Duration(minutes: 2));
for (final item in items) {
if (item is! TextMessageItem) {
continue;
}
if (item.sender != MessageSender.user || item.isLocalEcho) {
continue;
}
if (!ChatTimelineReconciler.isLikelySameUserMessage(localEcho, item)) {
continue;
}
if (item.timestamp.isBefore(earliestAccepted)) {
continue;
}
if (item.timestamp.isAfter(latestAccepted)) {
continue;
}
if (matched == null || item.timestamp.isBefore(matched)) {
matched = item.timestamp;
}
}
return matched;
}
bool chatBlocHasAssistantAfterBaseline(
List<ChatListItem> items,
DateTime? baseline, {
required DateTime notBefore,
}) {
for (final item in items) {
if (item is! TextMessageItem) {
continue;
}
if (item.sender != MessageSender.ai || item.content.trim().isEmpty) {
continue;
}
if (!item.timestamp.isAfter(notBefore)) {
continue;
}
if (baseline == null || item.timestamp.isAfter(baseline)) {
return true;
}
}
return false;
}
@@ -0,0 +1,163 @@
// ignore_for_file: invalid_use_of_protected_member, invalid_use_of_visible_for_testing_member
part of 'chat_bloc.dart';
extension _ChatBlocSend on ChatBloc {
Future<void> _sendMessage(String content, {List<XFile>? images}) async {
final epoch = _sessionEpoch;
final assistantBaselineAtSend = chatBlocLatestAssistantTimestamp(
state.items,
);
final sendStartedAt = DateTime.now();
final messageId = 'user-${sendStartedAt.millisecondsSinceEpoch}';
final localEchoAttachments = (images ?? const <XFile>[])
.map(
(image) => <String, dynamic>{
'path': image.path,
'mimeType': image.mimeType ?? 'image/jpeg',
'uploading': true,
},
)
.toList();
final localEcho = TextMessageItem(
id: messageId,
content: content,
timestamp: sendStartedAt,
sender: MessageSender.user,
isLocalEcho: true,
attachments: localEchoAttachments,
);
emit(
state.copyWith(
items: [...state.items, localEcho],
isSending: true,
isWaitingFirstToken: true,
isStreaming: false,
isCancelling: false,
error: null,
),
);
try {
final uploadInputs = await Future.wait(
(images ?? const <XFile>[]).map(
(image) async => AttachmentUploadInput(
name: image.name,
mimeType: image.mimeType ?? 'image/jpeg',
bytes: await image.readAsBytes(),
localPath: image.path,
),
),
);
final sendResult = await _service.sendMessage(
content,
attachments: uploadInputs,
);
if (epoch != _sessionEpoch) {
return;
}
_syncUploadedAttachments(
messageId: messageId,
uploadedAttachments: sendResult.uploadedAttachments,
);
} catch (error) {
if (epoch != _sessionEpoch) {
return;
}
final sseClosedBeforeTerminal = chatBlocIsSseClosedBeforeTerminalError(
error,
);
var recoveredFromHistory = false;
if (sseClosedBeforeTerminal) {
recoveredFromHistory = await _recoverFromAbnormalSseClose(
epoch: epoch,
localEchoMessage: localEcho,
sendStartedAt: sendStartedAt,
assistantBaselineAtSend: assistantBaselineAtSend,
);
}
if (epoch != _sessionEpoch) {
return;
}
_markAttachmentUploadDone(messageId);
emit(
state.copyWith(
isSending: false,
isWaitingFirstToken: false,
isStreaming: false,
isCancelling: false,
currentStage: null,
error: sseClosedBeforeTerminal
? (recoveredFromHistory
? null
: L10n.current.chatSseInterruptedRetry)
: error.toString(),
),
);
}
}
Future<bool> _recoverFromAbnormalSseClose({
required int epoch,
required TextMessageItem localEchoMessage,
required DateTime sendStartedAt,
required DateTime? assistantBaselineAtSend,
}) async {
try {
final deadline = DateTime.now().add(_recoveryTimeout);
while (DateTime.now().isBefore(deadline)) {
final snapshot = await _service.loadHistory(forceRefresh: true);
if (epoch != _sessionEpoch) {
return false;
}
final merged = _mergeWithHistory(state.items, snapshot.messages);
emit(
state.copyWith(
items: merged,
oldestLoadedDate: _extractDateFromItems(merged),
hasEarlierHistory: snapshot.hasMore,
),
);
final persistedUserTimestamp = chatBlocFindPersistedUserTimestamp(
merged,
localEchoMessage,
sendStartedAt,
);
final assistantCaughtUp = chatBlocHasAssistantAfterBaseline(
merged,
assistantBaselineAtSend,
notBefore: persistedUserTimestamp ?? sendStartedAt,
);
if (persistedUserTimestamp != null && assistantCaughtUp) {
return true;
}
final remaining = deadline.difference(DateTime.now());
if (remaining <= Duration.zero) {
break;
}
await Future<void>.delayed(
remaining < _recoveryPollInterval ? remaining : _recoveryPollInterval,
);
}
return false;
} catch (_) {
return false;
}
}
List<ChatListItem> _mergeWithHistory(
List<ChatListItem> localItems,
List<HistoryMessage> historyMessages,
) {
final historyItems = _convertHistoryMessages(historyMessages);
return ChatTimelineReconciler.merge(
localItems: localItems,
remoteItems: historyItems,
);
}
}
@@ -10,14 +10,15 @@ import '../../../../core/utils/tool_name_localizer.dart';
import '../../../../shared/widgets/app_loading_indicator.dart';
import '../../../../shared/widgets/ui_schema/ui_schema_renderer.dart';
const _messagePaddingH = 13.0;
const _messagePaddingV = 9.0;
const _cornerRadius = 12.0;
const _attachmentPreviewSize = 88.0;
const _attachmentPreviewRadius = 10.0;
const _attachmentPreviewGap = 8.0;
const _toolResultWidthFactor = 0.9;
const _iconSize = 24.0;
const _messageMaxWidthFactor = 0.82;
const _messagePaddingH = AppSpacing.md;
const _messagePaddingV = AppSpacing.sm;
const _cornerRadius = AppRadius.lg;
const _attachmentPreviewSize = AppSpacing.xxl * 3 + AppSpacing.xs;
const _attachmentPreviewRadius = AppRadius.md;
const _attachmentPreviewGap = AppSpacing.sm;
const _toolResultWidthFactor = 0.88;
const _iconSize = AppSpacing.xxl;
class HomeChatItemRenderer {
static Widget build(BuildContext context, ChatListItem item) {
@@ -34,6 +35,8 @@ class HomeChatItemRenderer {
static Widget _buildMessageItem(BuildContext context, TextMessageItem item) {
final colorScheme = Theme.of(context).colorScheme;
final isUser = item.sender == MessageSender.user;
final maxMessageWidth =
MediaQuery.sizeOf(context).width * _messageMaxWidthFactor;
final imageAttachments = _collectRenderableImageAttachments(
item.attachments,
);
@@ -49,7 +52,8 @@ class HomeChatItemRenderer {
: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Flexible(
ConstrainedBox(
constraints: BoxConstraints(maxWidth: maxMessageWidth),
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: _messagePaddingH,
@@ -58,21 +62,24 @@ class HomeChatItemRenderer {
decoration: BoxDecoration(
color: isUser
? colorScheme.primaryContainer
: colorScheme.surface,
: colorScheme.surfaceContainerLow,
borderRadius: BorderRadius.only(
topLeft: const Radius.circular(_cornerRadius),
topRight: const Radius.circular(_cornerRadius),
bottomLeft: Radius.circular(isUser ? _cornerRadius : 0),
bottomRight: Radius.circular(isUser ? 0 : _cornerRadius),
),
border: isUser
? null
: Border.all(color: colorScheme.outlineVariant),
border: Border.all(
color: isUser
? colorScheme.primary.withValues(alpha: 0.12)
: colorScheme.outlineVariant,
),
),
child: Text(
item.content,
style: TextStyle(
fontSize: 14,
fontSize: AppSpacing.md,
height: 1.45,
color: isUser
? colorScheme.onPrimaryContainer
: colorScheme.onSurface,
@@ -302,6 +309,7 @@ class HomeChatItemRenderer {
: null;
final needsOuterCard = appearance == null || appearance == 'plain';
final schemaContent = UiSchemaRenderer(
context,
colorScheme,
).renderSchema(item.uiSchema);
final wrappedContent = needsOuterCard
@@ -309,9 +317,11 @@ class HomeChatItemRenderer {
width: double.infinity,
padding: const EdgeInsets.all(AppSpacing.md),
decoration: BoxDecoration(
color: colorScheme.surface,
color: colorScheme.surfaceContainerLow.withValues(alpha: 0.65),
borderRadius: BorderRadius.circular(AppRadius.lg),
border: Border.all(color: colorScheme.outlineVariant),
border: Border.all(
color: colorScheme.outlineVariant.withValues(alpha: 0.25),
),
),
child: schemaContent,
)