From 0dd77a3eb63f056ea91e263d366c5e40b0a33ed9 Mon Sep 17 00:00:00 2001 From: pwu2775-dev Date: Thu, 3 Dec 2026 22:12:43 +0800 Subject: [PATCH 1/2] fix: agent: an import that fails part-way says how far it got MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each chat in an import rolls back on its own, so a failure on chat N left chats 1..N-1 written and published — but the import rethrew the raw error, and the UI showed an error sheet about the failure alone. The user had no way to know the first chats had landed: re-importing the same file then skips them (the plan is idempotent by id), and every count from there on is a mystery. A chat that fails after others landed now throws AgentChatImportPartial carrying the counts (imported, skipped) and the cause; the history page catches it and shows the same result line the success path does, with the failure under it. A first-chat failure — nothing landed — rethrows the plain error exactly as before, so callers matching on FormatException and the like keep working. The skipped count travels too: an archive whose only new chat breaks after N chats were skipped as already present now says so, rather than reporting a bare failure over a file that was mostly a no-op. --- lib/data/provider/ai/agent_chat_archive.dart | 35 +++++++- lib/view/page/agent/history.dart | 16 ++++ test/unit/ai/agent_chat_archive_test.dart | 85 ++++++++++++++++++++ 3 files changed, 133 insertions(+), 3 deletions(-) diff --git a/lib/data/provider/ai/agent_chat_archive.dart b/lib/data/provider/ai/agent_chat_archive.dart index 32b0973f17..3645cea378 100644 --- a/lib/data/provider/ai/agent_chat_archive.dart +++ b/lib/data/provider/ai/agent_chat_archive.dart @@ -3,6 +3,29 @@ 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); + + /// 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; + + @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 +244,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 +255,18 @@ abstract final class AgentChatArchive { throw const FormatException('This file is not an Agent conversation export.'); } writeMeta(meta); - } catch (_) { + imported++; + } catch (e) { 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); } } - 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..3b2ea4503d 100644 --- a/lib/view/page/agent/history.dart +++ b/lib/view/page/agent/history.dart @@ -463,6 +463,22 @@ class _AgentHistoryPanelState extends State { child: Text(message), actions: [Btn.ok()], ); + } on AgentChatImportPartial catch (e, s) { + // 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, s); + if (!mounted) return; + await context.showSheet( + title: context.l10n.agentImport, + child: Text( + '${context.l10n.agentImportResult(e.imported, e.skipped)}\n' + '${e.cause}', + style: UIs.text13, + ), + actions: [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..2a494ca90b 100644 --- a/test/unit/ai/agent_chat_archive_test.dart +++ b/test/unit/ai/agent_chat_archive_test.dart @@ -276,4 +276,89 @@ 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})>{}; + 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) throw StateError('session write failed'); + 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()); + // 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); + }); + }); } From 662e35436e41d5aa5a35887ca27c1de48edfc461 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?lollipopkit=F0=9F=8F=B3=EF=B8=8F=E2=80=8D=E2=9A=A7?= =?UTF-8?q?=EF=B8=8F?= <10864310+lollipopkit@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:31:50 +0800 Subject: [PATCH 2/2] fix: preserve cause stack trace and selectable copyable error in partial import --- lib/data/provider/ai/agent_chat_archive.dart | 14 +++++++++++--- lib/view/page/agent/history.dart | 20 ++++++++++++-------- test/unit/ai/agent_chat_archive_test.dart | 9 ++++++++- 3 files changed, 31 insertions(+), 12 deletions(-) diff --git a/lib/data/provider/ai/agent_chat_archive.dart b/lib/data/provider/ai/agent_chat_archive.dart index 3645cea378..3c461d4091 100644 --- a/lib/data/provider/ai/agent_chat_archive.dart +++ b/lib/data/provider/ai/agent_chat_archive.dart @@ -10,7 +10,12 @@ import 'package:server_box/data/provider/ai/agent_scope.dart'; /// 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); + const AgentChatImportPartial( + this.imported, + this.skipped, + this.cause, + this.stackTrace, + ); /// Chats written and published before the one that failed. final int imported; @@ -21,6 +26,9 @@ final class AgentChatImportPartial implements Exception { /// 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)'; @@ -256,7 +264,7 @@ abstract final class AgentChatArchive { } writeMeta(meta); imported++; - } catch (e) { + } catch (e, s) { try { await removeSession(meta.id); } catch (_) {} @@ -264,7 +272,7 @@ abstract final class AgentChatArchive { // 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); + throw AgentChatImportPartial(imported, decided.skipped.length, e, s); } } return (imported: imported, skipped: decided.skipped.length); diff --git a/lib/view/page/agent/history.dart b/lib/view/page/agent/history.dart index 3b2ea4503d..a1ae1c43c6 100644 --- a/lib/view/page/agent/history.dart +++ b/lib/view/page/agent/history.dart @@ -463,21 +463,25 @@ class _AgentHistoryPanelState extends State { child: Text(message), actions: [Btn.ok()], ); - } on AgentChatImportPartial catch (e, s) { + } 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, s); + 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: Text( - '${context.l10n.agentImportResult(e.imported, e.skipped)}\n' - '${e.cause}', - style: UIs.text13, - ), - actions: [Btn.ok()], + 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); diff --git a/test/unit/ai/agent_chat_archive_test.dart b/test/unit/ai/agent_chat_archive_test.dart index 2a494ca90b..914dee7d1b 100644 --- a/test/unit/ai/agent_chat_archive_test.dart +++ b/test/unit/ai/agent_chat_archive_test.dart @@ -281,6 +281,7 @@ void main() { 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; @@ -295,7 +296,12 @@ void main() { putMeta: (m) => stored[m.id] = m, importSession: (id, entries, {tip}) async { calls++; - if (calls == 2) throw StateError('session write failed'); + if (calls == 2) { + Error.throwWithStackTrace( + StateError('session write failed'), + originTrace, + ); + } sessions[id] = (entries: entries, tip: tip); return (added: entries.length, orphans: {}); }, @@ -310,6 +316,7 @@ void main() { 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);