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
@@ -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());
}
}