diff --git a/lib/data/provider/ai/agent_chat_archive.dart b/lib/data/provider/ai/agent_chat_archive.dart index 32b0973f17..3c461d4091 100644 --- a/lib/data/provider/ai/agent_chat_archive.dart +++ b/lib/data/provider/ai/agent_chat_archive.dart @@ -3,6 +3,37 @@ import 'dart:convert'; import 'package:fl_pi_llm_ui/fl_pi_llm_ui.dart'; import 'package:server_box/data/provider/ai/agent_scope.dart'; +/// An import that failed part-way, with what landed before it did. +/// +/// Chats already written stay written — each chat's rollback is its own — so +/// the failure is not a reset, and the caller says how far it got rather than +/// leaving the user to find out by re-importing (which skips what landed, +/// making every count after that a mystery). +final class AgentChatImportPartial implements Exception { + const AgentChatImportPartial( + this.imported, + this.skipped, + this.cause, + this.stackTrace, + ); + + /// Chats written and published before the one that failed. + final int imported; + + /// Chats the plan had skipped as already here or duplicated. + final int skipped; + + /// The failure the chat that did not land threw. + final Object cause; + + /// The stack trace from [cause], before this wrapper was thrown. + final StackTrace stackTrace; + + @override + String toString() => 'AgentChatImportPartial(imported: $imported, ' + 'skipped: $skipped, cause: $cause)'; +} + /// One chat in an Agent conversation file: its [ChatMeta] (including [ChatMeta.scope]) /// and the session [Chats.exportChat] returns. final class AgentChatDump { @@ -221,6 +252,7 @@ abstract final class AgentChatArchive { final writeMeta = putMeta ?? LlmStores.chat.put; final writeSession = importSession ?? Chats.importChat; final removeSession = deleteSession ?? Llm.rt.deleteSession; + var imported = 0; for (final chat in decided.toImport) { // Not trashed: a file is something the user wants in the list. final meta = chat.meta.trashed ? chat.meta.copyWith(restore: true) : chat.meta; @@ -231,13 +263,18 @@ abstract final class AgentChatArchive { throw const FormatException('This file is not an Agent conversation export.'); } writeMeta(meta); - } catch (_) { + imported++; + } catch (e, s) { try { await removeSession(meta.id); } catch (_) {} - rethrow; + // Nothing had landed: the failure is the whole answer, as before. + // Something had: it stays written, and the caller says how far the + // import got instead of leaving the counts to be re-derived. + if (imported == 0 && decided.skipped.isEmpty) rethrow; + throw AgentChatImportPartial(imported, decided.skipped.length, e, s); } } - return (imported: decided.toImport.length, skipped: decided.skipped.length); + return (imported: imported, skipped: decided.skipped.length); } } diff --git a/lib/view/page/agent/history.dart b/lib/view/page/agent/history.dart index 233a4fd5bc..a1ae1c43c6 100644 --- a/lib/view/page/agent/history.dart +++ b/lib/view/page/agent/history.dart @@ -463,6 +463,26 @@ class _AgentHistoryPanelState extends State { child: Text(message), actions: [Btn.ok()], ); + } on AgentChatImportPartial catch (e) { + // What landed before the failure stays written — each chat's rollback + // is its own — so the error says how far the import got rather than + // leaving the counts to be re-derived by importing again (which skips + // what landed). + Loggers.app.warning('Import Agent chats', e.cause, e.stackTrace); + if (!mounted) return; + final summary = context.l10n.agentImportResult(e.imported, e.skipped); + await context.showSheet( + title: context.l10n.agentImport, + child: SelectableText('$summary\n${e.cause}'), + actions: [ + TextButton( + onPressed: () => + Pfs.copy('$summary\n${e.cause}\n${e.stackTrace}'), + child: Text(libL10n.copy), + ), + Btn.ok(), + ], + ); } catch (e, s) { Loggers.app.warning('Import Agent chats', e, s); if (mounted) context.showErrSheet(e, s, context.l10n.agentImport); diff --git a/test/unit/ai/agent_chat_archive_test.dart b/test/unit/ai/agent_chat_archive_test.dart index ac673515ea..914dee7d1b 100644 --- a/test/unit/ai/agent_chat_archive_test.dart +++ b/test/unit/ai/agent_chat_archive_test.dart @@ -276,4 +276,96 @@ void main() { expect(sessions.containsKey('broken-chat'), isFalse); }, ); + + group('partial import', () { + test('a chat that lands before the failure stays, and the failure says so', () async { + final stored = {}; + final sessions = > entries, String? tip})>{}; + final originTrace = StackTrace.fromString('session-write-origin'); + var calls = 0; + + Object? caught; + try { + await AgentChatArchive.import( + [ + _dump(_meta('first', title: 'Lands'), entries: [_msgEntry('u1')]), + _dump(_meta('second', title: 'Breaks'), entries: [_msgEntry('u2')]), + _dump(_meta('third', title: 'Never reached')), + ], + exists: stored.containsKey, + putMeta: (m) => stored[m.id] = m, + importSession: (id, entries, {tip}) async { + calls++; + if (calls == 2) { + Error.throwWithStackTrace( + StateError('session write failed'), + originTrace, + ); + } + sessions[id] = (entries: entries, tip: tip); + return (added: entries.length, orphans: {}); + }, + deleteSession: (id) async => sessions.remove(id), + ); + } on AgentChatImportPartial catch (e) { + caught = e; + } + + // The failure names what landed, not just what broke. + final e = caught as AgentChatImportPartial; + expect(e.imported, 1); + expect(e.skipped, 0); + expect(e.cause, isA()); + expect(e.stackTrace, same(originTrace)); + // The chat that landed stays written, session and metadata both. + expect(stored.containsKey('first'), isTrue); + expect(sessions.containsKey('first'), isTrue); + // The one that broke rolled back; the third was never reached. + expect(stored.containsKey('second'), isFalse); + expect(sessions.containsKey('second'), isFalse); + expect(stored.containsKey('third'), isFalse); + }); + + test('the first chat failing is the plain error, as before', () async { + final stored = {}; + + await expectLater( + AgentChatArchive.import( + [_dump(_meta('only', title: 'Breaks'), entries: [_msgEntry('u1')])], + exists: stored.containsKey, + putMeta: (m) => stored[m.id] = m, + importSession: (id, entries, {tip}) async => + throw StateError('session write failed'), + deleteSession: (id) async {}, + ), + throwsStateError, + ); + expect(stored, isEmpty); + }); + + test('skips are counted even when the first new chat fails', () async { + final stored = { + 'existing': _meta('existing', title: 'Keep me'), + }; + + Object? caught; + try { + await AgentChatArchive.import( + [ + _dump(_meta('existing', title: 'Skipped')), + _dump(_meta('new', title: 'Breaks'), entries: [_msgEntry('u1')]), + ], + exists: stored.containsKey, + putMeta: (m) => stored[m.id] = m, + importSession: (id, entries, {tip}) async => + throw StateError('session write failed'), + deleteSession: (id) async {}, + ); + } on AgentChatImportPartial catch (e) { + caught = e; + } + expect(caught, isA()); + expect((caught as AgentChatImportPartial).skipped, 1); + }); + }); }