import 'dart:convert'; import 'package:flutter/foundation.dart'; import '../../../core/api_gateway.dart'; import '../../artifacts/actions/artifact_file.dart'; import '../../artifacts/actions/artifact_file_bridge.dart'; import '../../artifacts/actions/artifact_transfer.dart'; import '../data/chat_repository.dart'; import '../domain/chat_session_handoff.dart'; /// Exports one chat through `chat_export` and hands the file to the host the /// same way the artifact viewer does: a browser download on the web, the share /// sheet (which offers saving) on phones. One export runs at a time. class ChatExportController extends ChangeNotifier { ChatExportController({ required this.repository, required this.sessionId, this.bridge = const ArtifactFileBridge(), bool? share, }) : share = share ?? !kIsWeb; final ChatRepository repository; final String sessionId; final ArtifactFileBridge bridge; /// True hands the file to the share sheet; false downloads/saves it. final bool share; ChatExportFormat? _active; String? _status; bool _disposed = false; ChatExportFormat? get active => _active; bool get busy => _active != null; String? get status => _status; Future export(ChatExportFormat format) async { if (busy) return; final useShare = share && bridge.canShare; if (!useShare && !bridge.canDownload) { _set(null, bridge.downloadUnavailableMessage); return; } _set(format, 'Preparing export…'); final JsonMap file; try { file = await repository.export(sessionId, format.wire); } catch (error) { _set(null, 'Could not export the chat: $error'); return; } final artifact = ArtifactFile( name: '${file['name']}', mimeType: '${file['mime'] ?? ''}'.isEmpty ? 'text/plain' : '${file['mime']}', bytes: Uint8List.fromList(utf8.encode('${file['content'] ?? ''}')), ); ArtifactTransferResult result; try { result = useShare ? await bridge.shareFile(artifact) : await bridge.saveFile(artifact); } catch (error) { _set(null, 'Could not save ${artifact.name}: $error'); return; } final truncated = file['truncated'] == true ? ' Older messages were left out to fit the size limit.' : ''; final message = switch (result.state) { ArtifactTransferState.saved => 'Exported ${artifact.name}.$truncated', ArtifactTransferState.shared => 'Shared ${artifact.name}.$truncated', ArtifactTransferState.canceled => 'Export canceled.', _ => result.message.isEmpty ? 'Export failed.' : result.message, }; _set(null, message); } void _set(ChatExportFormat? active, String? status) { _active = active; _status = status; if (!_disposed) notifyListeners(); } @override void dispose() { _disposed = true; super.dispose(); } }