From 67f9bf902b2f7e6a4212b713c4e326f7575d6ae7 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Fri, 23 Oct 2026 00:13:43 -0400 Subject: [PATCH] feat(#966): mock-ups, a confirmation that states the scope, and the eligibility bug it found The owner asked why there were no UI mock-ups to review. There was no good answer: this Epic's card was built and installed on both his machines without him ever seeing the design, and the plan had no step requiring otherwise. So the plan now has B0: mock-ups first, owner-approved before any of it is built, as a committed HTML file beside the plan in the format his firmware initiative already uses. epic-b-storage-mockups.html is that file: eleven numbered variants with real Material 3 tokens, a 360-wide pane, example values from his own install, and the behaviour to build as bullets under each. Owner-approved 2026-10-23. The confirmation (B1a, variants 8 to 10). It states how many copies, roughly how much space, how many messages are NOT affected, and that it cannot be undone, with the count on the action button so the scope is the last thing read. Cancel, a tap outside and back all decline. Nothing eligible opens no dialog at all, because a dialog that only says zero is not worth opening. That needed a preview pass: verify every eligible key and total it without deleting, so the numbers are real rather than estimated. Verification now runs twice for a confirmed clear, once to preview and once under the key lock. That is the cost of saying what will go before it goes. approximateBytes is named for what it is: the sum of blob lengths, not what VACUUM returns, because page rounding moves the real figure; the dialog says "about" and the result reports what actually changed. Writing the preview found a real bug, and it was about to bite him. The "skip anything stamped this pass" guard exists so installing an update never deletes a blob on sight, and it was being applied to the button as well. Every install that migrated before #962 has an empty __msgrows_migrated_at, so the first press stamped everything and cleared NOTHING. His install is exactly that: 47 migrated keys, none stamped. He would have pressed the button on a 70.9 MB database with 16.6 MB of reclaimable blobs and been told "nothing to clear". Fixed as eligibleByAge, one static rule both preview and run share, so the dialog cannot promise what the sweep will not do. An explicit press includes newly stamped keys; the automatic sweep still refuses them. Three tests on the rule directly, plus one proving the automatic path refuses while the press clears. Label stays "Clear Stale History Now" rather than "Compact", owner's call and the better argument: the name generalises to clearing stale history for other reasons later, such as #963's retention limit. 14 widget tests and 34 storage tests. Full suite 1,502 pass, 1 skipped. analyze clean, format clean. Task: meshcore-open-gan Agent Mail: TealGlen Co-Authored-By: Claude Opus 5 --- .../962-stale-blob-reclamation/PLAN.md | 12 +- .../epic-b-storage-mockups.html | 168 ++++++++++++++++++ lib/l10n/app_en.arb | 41 +++++ lib/l10n/app_localizations.dart | 36 ++++ lib/l10n/app_localizations_bg.dart | 26 +++ lib/l10n/app_localizations_de.dart | 26 +++ lib/l10n/app_localizations_en.dart | 26 +++ lib/l10n/app_localizations_es.dart | 26 +++ lib/l10n/app_localizations_fr.dart | 26 +++ lib/l10n/app_localizations_hu.dart | 26 +++ lib/l10n/app_localizations_it.dart | 26 +++ lib/l10n/app_localizations_ja.dart | 26 +++ lib/l10n/app_localizations_ko.dart | 26 +++ lib/l10n/app_localizations_nl.dart | 26 +++ lib/l10n/app_localizations_pl.dart | 26 +++ lib/l10n/app_localizations_pt.dart | 26 +++ lib/l10n/app_localizations_ru.dart | 26 +++ lib/l10n/app_localizations_sk.dart | 26 +++ lib/l10n/app_localizations_sl.dart | 26 +++ lib/l10n/app_localizations_sv.dart | 26 +++ lib/l10n/app_localizations_uk.dart | 26 +++ lib/l10n/app_localizations_zh.dart | 26 +++ lib/services/stale_history_sweep.dart | 134 +++++++++++++- lib/storage/drift/blob_store.dart | 12 ++ lib/widgets/storage_reclaim_card.dart | 120 ++++++++++++- test/storage/stale_history_sweep_test.dart | 142 +++++++++++++++ test/widgets/storage_reclaim_card_test.dart | 166 +++++++++++++++-- untranslated.json | 102 +++++++++++ 28 files changed, 1372 insertions(+), 29 deletions(-) create mode 100644 docs/initiatives/standalone/962-stale-blob-reclamation/epic-b-storage-mockups.html diff --git a/docs/initiatives/standalone/962-stale-blob-reclamation/PLAN.md b/docs/initiatives/standalone/962-stale-blob-reclamation/PLAN.md index 3289aeec..2f087abb 100644 --- a/docs/initiatives/standalone/962-stale-blob-reclamation/PLAN.md +++ b/docs/initiatives/standalone/962-stale-blob-reclamation/PLAN.md @@ -64,8 +64,10 @@ | Task | Pts | |---|---| +| **B0 · Mock-ups FIRST, owner-approved before any of it is built.** Every state of every new surface, as a committed HTML file beside this plan, in the format the firmware initiative uses: numbered variants, real chrome and tokens, example values from the owner's own install, and the behaviour to build as bullets under each. **Added 2026-10-23, after this Epic's UI was built and installed on both his machines without him ever seeing the design.** The plan had no such step, which is why that happened. | 2 | | **B1 · The action** in Settings, showing database size before and after and how many keys were cleared, with the same re-verify and refusal path as the sweep. Per decision 4 it **reports keys it refused** in the result, not just the log: "cleared 12, kept 1 that failed verification". | 3 | -| **B2 · Widget tests:** the action with nothing eligible, with eligible keys, and with a key whose re-verify fails (which must report a refusal rather than silence). | 3 | +| **B1a · A confirmation stating the scope** before anything is deleted: how many copies, roughly how much space, how many messages are *not* affected, and that it cannot be undone. Needs a **preview pass** in the sweep, verifying every eligible key and totalling it without deleting, so the numbers are real rather than estimated. Verification then runs twice for a confirmed clear, once to preview and once under the key lock. That is the price of saying what will go before it goes. Owner-required 2026-10-23. | 3 | +| **B2 · Widget tests:** the action with nothing eligible, with eligible keys, and with a key whose re-verify fails (which must report a refusal rather than silence). Plus the confirmation: it states the scope, Cancel deletes nothing and leaves the action usable, a forecast refusal is shown before the press, and nothing eligible opens no dialog at all. | 3 | | **B3 · Epic verification** | 1 | ### Epic C: Integration Testing @@ -156,6 +158,14 @@ Owner, 2026-10-22: *"X = 30, sweep once per launch, timestamps in separate blob, **30 days is a named constant, not a literal scattered through the sweep**, so changing it later is one edit and the tests can set it directly rather than manipulating clocks. +### Added 2026-10-23, after the mock-up review + +| # | Question | Decision | Why | +|---|---|---|---| +| 5 | Does the manual action confirm before deleting? | **Yes, stating the scope**: how many copies, roughly how much space, how many messages are not affected, and that it cannot be undone. | It deletes and cannot be undone. See B1a; it needs a preview pass, and the mock-up's variants 8 to 10 are the approved shape. | +| 6 | "Compact" or "Clear Stale History"? | **Clear Stale History Now** | Owner's reason, and the better argument: the name generalises, so the same action can later cover clearing stale history for other reasons, such as the retention limit in #963. "Compact" describes `VACUUM`, which is an implementation detail. | +| 7 | Does an explicit press clear a key that has no timestamp yet? | **Yes.** The automatic sweep still refuses. | Found while building the preview. The "skip anything stamped this pass" guard exists so installing an update never deletes on sight, and it was being applied to the button too. Every install that migrated before #962 has no stamps, so the button would have reported "nothing to clear" against real reclaimable blobs. The owner's install was exactly that: 47 migrated keys, none stamped. `eligibleByAge` is now the one rule both paths share. | + ## 10. Carried-in work | Item | Goes to | diff --git a/docs/initiatives/standalone/962-stale-blob-reclamation/epic-b-storage-mockups.html b/docs/initiatives/standalone/962-stale-blob-reclamation/epic-b-storage-mockups.html new file mode 100644 index 00000000..1aa65721 --- /dev/null +++ b/docs/initiatives/standalone/962-stale-blob-reclamation/epic-b-storage-mockups.html @@ -0,0 +1,168 @@ + + + + +Storage card mockups + + + + +

Storage card and clear confirmation (Epic B, #966)

+

Material 3, light scheme, blue seed, as main.dart configures it. Dark follows the same tokens and is not drawn. Phone pane at 360 wide, the narrowest real target; the Windows pane is the same widget in a wider column. Numbers are the owner's actual install on 2026-10-22: 70.9 MB database, 47 migrated keys, 40 with a stale copy, 29,975 messages, about 16.6 MB reclaimable. Bullets under each card are the behaviour to build. Owner-approved 2026-10-23: all variants as drawn, and the label stays Clear Stale History Now rather than "Compact" — his reason is that the name generalises, so the same action can later cover clearing stale history for other reasons, such as the retention limit in #963. Variants 1 to 10 are built; 11 is the rejected label alternative, kept for the record.

+ +

Where it lives

+
+

1App Settings, bottom of the pane

A new Storage card after Cyr2Lat, last in the list. It is a read-only status plus one action, so it sits below the preference cards rather than among them.

+
‹App Settings
+
+
Cyrillic to Latin
Transliterate incoming Cyrillic text.
+
Storage
Message database: 70.9 MB
+
When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.
+Clear Stale History Now
+
+
  • Last card, so a destructive action is never the first thing under a thumb.
  • Size is read on build and after any clear. A failure to read it hides the row, never blocks the button (variant 7).
  • Same widget on Windows; only the column width differs.
+
+ +

The card's states, as built today

+
+ +

2Working

The button disables and relabels while the sweep runs. A second tap in the same frame is also refused in code, because setState only schedules a rebuild.

+
Storage
Message database: 70.9 MB
+
When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.
+Clearing...
+
  • Two concurrent sweeps would mean two concurrent VACUUMs.
  • Re-enables on success and on failure, or the action works exactly once per launch.
+ +

3Cleared

Count and bytes returned, and the size row updates to what the sweep actually left behind rather than the number it started with.

+
Storage
Message database: 54.3 MB
+
When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.
+Clear Stale History Now +
Cleared 40 old copies, 16.6 MB returned.
+
  • Bytes come from SQLite either side of the sweep, not from adding up blob lengths.
  • Pressing again is harmless: those keys have no copy left, so it reports nothing to clear.
+ +

4Cleared, with something kept back

A key whose rows could not be verified keeps its copy and is reported, not merely logged. This is the case the Epic exists for.

+
Storage
Message database: 54.3 MB
+
When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.
+Clear Stale History Now +
Cleared 39 old copies, 16.2 MB returned.
+
Kept 1 that could not be verified. Your messages are intact; nothing was deleted for those.
+
  • Shown even when a refusal is the reason nothing was cleared, which is the most important case to surface, not the least.
  • The automatic 30-day sweep stays log-only: nobody is watching it.
  • Which keys and which records are named in the durable audit, not on screen.
+ +

5Nothing to clear

The ordinary state for anyone who has already swept, or who has no migrated history yet.

+
Storage
Message database: 54.3 MB
+
When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.
+Clear Stale History Now +
Nothing to clear.
+
  • Says so plainly rather than showing a zero-byte success.
+ +

6Failed

It must not read as "something was half-deleted", and it must not claim nothing happened either, because the sweep deletes per key and a throw can follow real deletes.

+
Storage
Message database: 70.9 MB
+
When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.
+Clear Stale History Now +
Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.
+
  • No exception text on screen; the reason goes to the log and the audit.
+ +

7Size unreadable

A size we cannot read is not a reason to block clearing, so the row is left out and the action stays live.

+
Storage
+
When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.
+Clear Stale History Now
+
  • Logged as a warning, never surfaced as an error.
+ +
+ +

Proposed: confirm before deleting

+

None of this exists. It needs a preview pass in the sweep: verify every eligible key and total it, without deleting, so the dialog can state real numbers rather than a guess. The verification then runs twice, once to preview and once under the key lock to delete, which is the cost of saying what will go before it goes.

+
+ +

8Confirm, the normal case

States what will be cleared, what is not affected, and that it cannot be undone. The action button carries the count so the last thing read is the scope.

+
+
Clear stale history?
+
This removes 40 old copies of history that has already moved to the new format, freeing about 16.6 MB.
+
Your messages are not affected. All 29,975 stay.
+
This cannot be undone.
+
CancelClear 40 copies
+
+
  • Counts come from a real preview pass, not an estimate.
  • Cancel is the plain text button and sits left, so the destructive one is never the default target.
  • Dismissing by tapping outside or back cancels.
+ +

9Confirm, with a forecast refusal

If the preview already knows a key cannot be verified, say so before the press rather than reporting it afterwards.

+
+
Clear stale history?
+
This removes 39 old copies of history that has already moved to the new format, freeing about 16.2 MB.
+
Your messages are not affected. All 29,975 stay.
+
1 copy will be kept back because its messages could not be verified. This cannot be undone.
+
CancelClear 39 copies
+
+
  • The count in the button excludes what will be kept, so it matches what actually goes.
  • A refusal discovered only at delete time still reports after the fact, as variant 4.
+ +

10Nothing eligible, no dialog

With nothing to clear there is nothing to confirm, so the press reports straight away rather than opening a dialog to say "zero".

+
Storage
Message database: 54.3 MB
+
When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.
+Clear Stale History Now +
Nothing to clear.
+
  • The preview runs on the press. Empty result means no dialog at all.
  • So the preview must be cheap enough to run on a tap: it reads and verifies, it does not write.
+ +

11Label: the open question

The owner said "Compact"; the button says "Clear Stale History Now". Drawn here with his word in the title and the plain description in the body.

+
Storage
Message database: 70.9 MB
+
Compacting removes the old copy of history that has already moved to the new format, and returns the space. It happens on its own 30 days after the move.
+Compact now
+
  • "Compact" is what VACUUM does and reads less alarming; "Clear Stale History" says what is removed.
  • Owner's call. Either way the dialog in variant 8 states the scope.
+ +
+ diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 22e097ac..6f63748d 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -3336,6 +3336,47 @@ } } }, + "storage_confirmTitle": "Clear stale history?", + "storage_confirmBody": "This removes {count} old copies of history that has already moved to the new format, freeing about {size}.", + "@storage_confirmBody": { + "description": "Body of the confirmation shown before clearing stale history. The size is approximate because VACUUM's real figure depends on page rounding (#962).", + "placeholders": { + "count": { + "type": "int" + }, + "size": { + "type": "String" + } + } + }, + "storage_confirmSafe": "Your messages are not affected. All {count} stay.", + "@storage_confirmSafe": { + "description": "Reassurance in the clear confirmation: this deletes duplicate copies, not history (#962).", + "placeholders": { + "count": { + "type": "int" + } + } + }, + "storage_confirmIrreversible": "This cannot be undone.", + "storage_confirmKeptBack": "{count} will be kept back because its messages could not be verified. This cannot be undone.", + "@storage_confirmKeptBack": { + "description": "Shown when the preview already knows a copy will be refused, so the user hears it before the press rather than after (#962).", + "placeholders": { + "count": { + "type": "int" + } + } + }, + "storage_confirmAction": "Clear {count} copies", + "@storage_confirmAction": { + "description": "Confirm button. Carries the count so the scope is the last thing read before the tap (#962).", + "placeholders": { + "count": { + "type": "int" + } + } + }, "storage_resultFailed": "Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.", "@storage_resultFailed": { "description": "Shown when the clear threw. It must not claim nothing happened, because the sweep deletes per key and may have cleared some before failing (#962)." diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 1106cb50..18a71223 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -9226,6 +9226,42 @@ abstract class AppLocalizations { /// **'Kept {count} that could not be verified. Your messages are intact; nothing was deleted for those.'** String storage_resultRefused(int count); + /// No description provided for @storage_confirmTitle. + /// + /// In en, this message translates to: + /// **'Clear stale history?'** + String get storage_confirmTitle; + + /// Body of the confirmation shown before clearing stale history. The size is approximate because VACUUM's real figure depends on page rounding (#962). + /// + /// In en, this message translates to: + /// **'This removes {count} old copies of history that has already moved to the new format, freeing about {size}.'** + String storage_confirmBody(int count, String size); + + /// Reassurance in the clear confirmation: this deletes duplicate copies, not history (#962). + /// + /// In en, this message translates to: + /// **'Your messages are not affected. All {count} stay.'** + String storage_confirmSafe(int count); + + /// No description provided for @storage_confirmIrreversible. + /// + /// In en, this message translates to: + /// **'This cannot be undone.'** + String get storage_confirmIrreversible; + + /// Shown when the preview already knows a copy will be refused, so the user hears it before the press rather than after (#962). + /// + /// In en, this message translates to: + /// **'{count} will be kept back because its messages could not be verified. This cannot be undone.'** + String storage_confirmKeptBack(int count); + + /// Confirm button. Carries the count so the scope is the last thing read before the tap (#962). + /// + /// In en, this message translates to: + /// **'Clear {count} copies'** + String storage_confirmAction(int count); + /// Shown when the clear threw. It must not claim nothing happened, because the sweep deletes per key and may have cleared some before failing (#962). /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 177cc3ea..5f4d750a 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -5456,6 +5456,32 @@ class AppLocalizationsBg extends AppLocalizations { return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.'; } + @override + String get storage_confirmTitle => 'Clear stale history?'; + + @override + String storage_confirmBody(int count, String size) { + return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.'; + } + + @override + String storage_confirmSafe(int count) { + return 'Your messages are not affected. All $count stay.'; + } + + @override + String get storage_confirmIrreversible => 'This cannot be undone.'; + + @override + String storage_confirmKeptBack(int count) { + return '$count will be kept back because its messages could not be verified. This cannot be undone.'; + } + + @override + String storage_confirmAction(int count) { + return 'Clear $count copies'; + } + @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 37c45011..96285e91 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -5473,6 +5473,32 @@ class AppLocalizationsDe extends AppLocalizations { return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.'; } + @override + String get storage_confirmTitle => 'Clear stale history?'; + + @override + String storage_confirmBody(int count, String size) { + return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.'; + } + + @override + String storage_confirmSafe(int count) { + return 'Your messages are not affected. All $count stay.'; + } + + @override + String get storage_confirmIrreversible => 'This cannot be undone.'; + + @override + String storage_confirmKeptBack(int count) { + return '$count will be kept back because its messages could not be verified. This cannot be undone.'; + } + + @override + String storage_confirmAction(int count) { + return 'Clear $count copies'; + } + @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 9a421213..6f9f7438 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -5379,6 +5379,32 @@ class AppLocalizationsEn extends AppLocalizations { return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.'; } + @override + String get storage_confirmTitle => 'Clear stale history?'; + + @override + String storage_confirmBody(int count, String size) { + return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.'; + } + + @override + String storage_confirmSafe(int count) { + return 'Your messages are not affected. All $count stay.'; + } + + @override + String get storage_confirmIrreversible => 'This cannot be undone.'; + + @override + String storage_confirmKeptBack(int count) { + return '$count will be kept back because its messages could not be verified. This cannot be undone.'; + } + + @override + String storage_confirmAction(int count) { + return 'Clear $count copies'; + } + @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 9231b7a8..880b6d03 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -5461,6 +5461,32 @@ class AppLocalizationsEs extends AppLocalizations { return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.'; } + @override + String get storage_confirmTitle => 'Clear stale history?'; + + @override + String storage_confirmBody(int count, String size) { + return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.'; + } + + @override + String storage_confirmSafe(int count) { + return 'Your messages are not affected. All $count stay.'; + } + + @override + String get storage_confirmIrreversible => 'This cannot be undone.'; + + @override + String storage_confirmKeptBack(int count) { + return '$count will be kept back because its messages could not be verified. This cannot be undone.'; + } + + @override + String storage_confirmAction(int count) { + return 'Clear $count copies'; + } + @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index f1081257..67eadce7 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -5489,6 +5489,32 @@ class AppLocalizationsFr extends AppLocalizations { return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.'; } + @override + String get storage_confirmTitle => 'Clear stale history?'; + + @override + String storage_confirmBody(int count, String size) { + return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.'; + } + + @override + String storage_confirmSafe(int count) { + return 'Your messages are not affected. All $count stay.'; + } + + @override + String get storage_confirmIrreversible => 'This cannot be undone.'; + + @override + String storage_confirmKeptBack(int count) { + return '$count will be kept back because its messages could not be verified. This cannot be undone.'; + } + + @override + String storage_confirmAction(int count) { + return 'Clear $count copies'; + } + @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index be57d319..f2dcb213 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -5478,6 +5478,32 @@ class AppLocalizationsHu extends AppLocalizations { return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.'; } + @override + String get storage_confirmTitle => 'Clear stale history?'; + + @override + String storage_confirmBody(int count, String size) { + return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.'; + } + + @override + String storage_confirmSafe(int count) { + return 'Your messages are not affected. All $count stay.'; + } + + @override + String get storage_confirmIrreversible => 'This cannot be undone.'; + + @override + String storage_confirmKeptBack(int count) { + return '$count will be kept back because its messages could not be verified. This cannot be undone.'; + } + + @override + String storage_confirmAction(int count) { + return 'Clear $count copies'; + } + @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index d9765386..c34f4c67 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -5466,6 +5466,32 @@ class AppLocalizationsIt extends AppLocalizations { return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.'; } + @override + String get storage_confirmTitle => 'Clear stale history?'; + + @override + String storage_confirmBody(int count, String size) { + return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.'; + } + + @override + String storage_confirmSafe(int count) { + return 'Your messages are not affected. All $count stay.'; + } + + @override + String get storage_confirmIrreversible => 'This cannot be undone.'; + + @override + String storage_confirmKeptBack(int count) { + return '$count will be kept back because its messages could not be verified. This cannot be undone.'; + } + + @override + String storage_confirmAction(int count) { + return 'Clear $count copies'; + } + @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 9271f9cd..5ff5bb6e 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -5232,6 +5232,32 @@ class AppLocalizationsJa extends AppLocalizations { return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.'; } + @override + String get storage_confirmTitle => 'Clear stale history?'; + + @override + String storage_confirmBody(int count, String size) { + return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.'; + } + + @override + String storage_confirmSafe(int count) { + return 'Your messages are not affected. All $count stay.'; + } + + @override + String get storage_confirmIrreversible => 'This cannot be undone.'; + + @override + String storage_confirmKeptBack(int count) { + return '$count will be kept back because its messages could not be verified. This cannot be undone.'; + } + + @override + String storage_confirmAction(int count) { + return 'Clear $count copies'; + } + @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 2a466483..5c872f0e 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -5233,6 +5233,32 @@ class AppLocalizationsKo extends AppLocalizations { return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.'; } + @override + String get storage_confirmTitle => 'Clear stale history?'; + + @override + String storage_confirmBody(int count, String size) { + return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.'; + } + + @override + String storage_confirmSafe(int count) { + return 'Your messages are not affected. All $count stay.'; + } + + @override + String get storage_confirmIrreversible => 'This cannot be undone.'; + + @override + String storage_confirmKeptBack(int count) { + return '$count will be kept back because its messages could not be verified. This cannot be undone.'; + } + + @override + String storage_confirmAction(int count) { + return 'Clear $count copies'; + } + @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 9ba517a1..4d92f65d 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -5441,6 +5441,32 @@ class AppLocalizationsNl extends AppLocalizations { return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.'; } + @override + String get storage_confirmTitle => 'Clear stale history?'; + + @override + String storage_confirmBody(int count, String size) { + return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.'; + } + + @override + String storage_confirmSafe(int count) { + return 'Your messages are not affected. All $count stay.'; + } + + @override + String get storage_confirmIrreversible => 'This cannot be undone.'; + + @override + String storage_confirmKeptBack(int count) { + return '$count will be kept back because its messages could not be verified. This cannot be undone.'; + } + + @override + String storage_confirmAction(int count) { + return 'Clear $count copies'; + } + @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 87f72c30..87ceeb1a 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -5478,6 +5478,32 @@ class AppLocalizationsPl extends AppLocalizations { return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.'; } + @override + String get storage_confirmTitle => 'Clear stale history?'; + + @override + String storage_confirmBody(int count, String size) { + return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.'; + } + + @override + String storage_confirmSafe(int count) { + return 'Your messages are not affected. All $count stay.'; + } + + @override + String get storage_confirmIrreversible => 'This cannot be undone.'; + + @override + String storage_confirmKeptBack(int count) { + return '$count will be kept back because its messages could not be verified. This cannot be undone.'; + } + + @override + String storage_confirmAction(int count) { + return 'Clear $count copies'; + } + @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 0e4a7910..1f3b0bbb 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -5454,6 +5454,32 @@ class AppLocalizationsPt extends AppLocalizations { return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.'; } + @override + String get storage_confirmTitle => 'Clear stale history?'; + + @override + String storage_confirmBody(int count, String size) { + return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.'; + } + + @override + String storage_confirmSafe(int count) { + return 'Your messages are not affected. All $count stay.'; + } + + @override + String get storage_confirmIrreversible => 'This cannot be undone.'; + + @override + String storage_confirmKeptBack(int count) { + return '$count will be kept back because its messages could not be verified. This cannot be undone.'; + } + + @override + String storage_confirmAction(int count) { + return 'Clear $count copies'; + } + @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 7da39ce6..4e654075 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -5472,6 +5472,32 @@ class AppLocalizationsRu extends AppLocalizations { return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.'; } + @override + String get storage_confirmTitle => 'Clear stale history?'; + + @override + String storage_confirmBody(int count, String size) { + return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.'; + } + + @override + String storage_confirmSafe(int count) { + return 'Your messages are not affected. All $count stay.'; + } + + @override + String get storage_confirmIrreversible => 'This cannot be undone.'; + + @override + String storage_confirmKeptBack(int count) { + return '$count will be kept back because its messages could not be verified. This cannot be undone.'; + } + + @override + String storage_confirmAction(int count) { + return 'Clear $count copies'; + } + @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 3fb0c77b..338b9254 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -5438,6 +5438,32 @@ class AppLocalizationsSk extends AppLocalizations { return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.'; } + @override + String get storage_confirmTitle => 'Clear stale history?'; + + @override + String storage_confirmBody(int count, String size) { + return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.'; + } + + @override + String storage_confirmSafe(int count) { + return 'Your messages are not affected. All $count stay.'; + } + + @override + String get storage_confirmIrreversible => 'This cannot be undone.'; + + @override + String storage_confirmKeptBack(int count) { + return '$count will be kept back because its messages could not be verified. This cannot be undone.'; + } + + @override + String storage_confirmAction(int count) { + return 'Clear $count copies'; + } + @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 970574ec..686c3fbf 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -5436,6 +5436,32 @@ class AppLocalizationsSl extends AppLocalizations { return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.'; } + @override + String get storage_confirmTitle => 'Clear stale history?'; + + @override + String storage_confirmBody(int count, String size) { + return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.'; + } + + @override + String storage_confirmSafe(int count) { + return 'Your messages are not affected. All $count stay.'; + } + + @override + String get storage_confirmIrreversible => 'This cannot be undone.'; + + @override + String storage_confirmKeptBack(int count) { + return '$count will be kept back because its messages could not be verified. This cannot be undone.'; + } + + @override + String storage_confirmAction(int count) { + return 'Clear $count copies'; + } + @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 38bc2f4d..54103872 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -5411,6 +5411,32 @@ class AppLocalizationsSv extends AppLocalizations { return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.'; } + @override + String get storage_confirmTitle => 'Clear stale history?'; + + @override + String storage_confirmBody(int count, String size) { + return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.'; + } + + @override + String storage_confirmSafe(int count) { + return 'Your messages are not affected. All $count stay.'; + } + + @override + String get storage_confirmIrreversible => 'This cannot be undone.'; + + @override + String storage_confirmKeptBack(int count) { + return '$count will be kept back because its messages could not be verified. This cannot be undone.'; + } + + @override + String storage_confirmAction(int count) { + return 'Clear $count copies'; + } + @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index e0de749f..9d542a44 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -5473,6 +5473,32 @@ class AppLocalizationsUk extends AppLocalizations { return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.'; } + @override + String get storage_confirmTitle => 'Clear stale history?'; + + @override + String storage_confirmBody(int count, String size) { + return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.'; + } + + @override + String storage_confirmSafe(int count) { + return 'Your messages are not affected. All $count stay.'; + } + + @override + String get storage_confirmIrreversible => 'This cannot be undone.'; + + @override + String storage_confirmKeptBack(int count) { + return '$count will be kept back because its messages could not be verified. This cannot be undone.'; + } + + @override + String storage_confirmAction(int count) { + return 'Clear $count copies'; + } + @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index d68664b8..60780c11 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -5106,6 +5106,32 @@ class AppLocalizationsZh extends AppLocalizations { return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.'; } + @override + String get storage_confirmTitle => 'Clear stale history?'; + + @override + String storage_confirmBody(int count, String size) { + return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.'; + } + + @override + String storage_confirmSafe(int count) { + return 'Your messages are not affected. All $count stay.'; + } + + @override + String get storage_confirmIrreversible => 'This cannot be undone.'; + + @override + String storage_confirmKeptBack(int count) { + return '$count will be kept back because its messages could not be verified. This cannot be undone.'; + } + + @override + String storage_confirmAction(int count) { + return 'Clear $count copies'; + } + @override String get storage_resultFailed => 'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'; diff --git a/lib/services/stale_history_sweep.dart b/lib/services/stale_history_sweep.dart index 09a9aea0..b6e9bcc1 100644 --- a/lib/services/stale_history_sweep.dart +++ b/lib/services/stale_history_sweep.dart @@ -38,6 +38,38 @@ class StaleHistoryOutcome { bool get didAnything => cleared.isNotEmpty; } +/// What a sweep WOULD do, for the confirmation dialog (#962). +class StaleHistoryPreview { + const StaleHistoryPreview({ + required this.eligible, + required this.refused, + required this.approximateBytes, + required this.messagesKept, + }); + + /// Keys whose stale copy is verified redundant and would be deleted. + final List eligible; + + /// Keys already known to be unverifiable, so they would be kept. Saying so + /// before the press beats reporting it afterwards. + final List refused; + + /// Blob bytes that would go. + /// + /// **Approximate on purpose.** It is the sum of the blob lengths, which is + /// not the same as what `VACUUM` returns to the filesystem: page rounding + /// and existing free pages both move the real figure. The dialog says + /// "about", and the result afterwards reports what actually changed. + final int approximateBytes; + + /// Total stored messages, so the dialog can say what is NOT affected. The + /// reassurance is the point: this action deletes, and the user needs to know + /// their history is not what is being deleted. + final int messagesKept; + + bool get hasWork => eligible.isNotEmpty; +} + /// Deletes the frozen pre-migration blob of a key that has been on rows long /// enough, and returns the space to the filesystem (#962). /// @@ -76,13 +108,95 @@ class StaleHistorySweep { ? channelHistoryToRows : dmHistoryToRows; + /// Whether a key is old enough to reclaim. The ONE age rule, shared by + /// [preview] and [run], so the dialog cannot promise what the sweep will not + /// do. + /// + /// A key with no timestamp, or one stamped during this pass, has no age to + /// judge. For the automatic sweep that means **not eligible**: the stamp + /// exists so installing an update never deletes a blob on sight. For an + /// explicit press it means **eligible**, because a user asking to clear now + /// is not an app update. Treating the two the same made the button report + /// "nothing to clear" on any install that migrated before #962, which is + /// every real install, since none of their keys carry a stamp yet. + static bool eligibleByAge({ + required DateTime? migratedAt, + required bool freshlyStamped, + required Duration window, + required DateTime at, + required bool includeNewlyStamped, + }) { + if (freshlyStamped || migratedAt == null) return includeNewlyStamped; + return at.difference(migratedAt) >= window; + } + + /// What a sweep would do, without doing any of it (#962). + /// + /// The confirmation dialog states real numbers rather than an estimate, so + /// the verification has to run before the delete rather than as part of it. + /// The cost is that it happens twice for a confirmed clear: once here, once + /// under the key lock in [run]. That is the price of saying what will go + /// before it goes. + /// + /// Writes nothing. In particular it does not stamp, so calling it never + /// changes what a later [run] does. + Future preview({ + Duration? olderThan, + DateTime? now, + bool includeNewlyStamped = false, + }) async { + final window = olderThan ?? staleHistoryWindow; + final at = now ?? DateTime.now(); + + final eligible = []; + final refused = []; + var bytes = 0; + + for (final key in (await _blobs.messageStoreKeys()).toList()..sort()) { + if (!isHistoryKey(key)) continue; + if (!await _blobs.isOnMessageRows(key)) continue; + if (!eligibleByAge( + migratedAt: await _blobs.messageRowsMigratedAt(key), + freshlyStamped: false, + window: window, + at: at, + includeNewlyStamped: includeNewlyStamped, + )) { + continue; + } + + final blob = await _blobs.read(key); + if (blob == null) continue; // already reclaimed + + final missing = await _blobs.missingFromRows(key, converterFor(key)); + if (missing == null || missing.isNotEmpty) { + refused.add(key); + continue; + } + eligible.add(key); + bytes += blob.length; + } + + return StaleHistoryPreview( + eligible: eligible, + refused: refused, + approximateBytes: bytes, + messagesKept: await _blobs.totalMessageRows(), + ); + } + /// Runs one sweep. /// /// [olderThan] defaults to [staleHistoryWindow]; [now] exists so tests can /// choose a moment rather than wait. Backfills a timestamp onto any - /// already-migrated key that has none, which never makes a key eligible on - /// the same pass: it starts that key's window instead. - Future run({Duration? olderThan, DateTime? now}) async { + /// already-migrated key that has none. [includeNewlyStamped] decides whether + /// such a key can be cleared on the same pass: false for the automatic + /// sweep, true for an explicit press. See [eligibleByAge]. + Future run({ + Duration? olderThan, + DateTime? now, + bool includeNewlyStamped = false, + }) async { final window = olderThan ?? staleHistoryWindow; final at = now ?? DateTime.now(); final bytesBefore = await _blobs.databaseSizeBytes(); @@ -97,11 +211,15 @@ class StaleHistorySweep { for (final key in (await _blobs.messageStoreKeys()).toList()..sort()) { if (!isHistoryKey(key)) continue; if (!await _blobs.isOnMessageRows(key)) continue; - if (stamped.contains(key)) continue; - - final migratedAt = await _blobs.messageRowsMigratedAt(key); - if (migratedAt == null) continue; // unstamped: nothing to age against - if (at.difference(migratedAt) < window) continue; + if (!eligibleByAge( + migratedAt: await _blobs.messageRowsMigratedAt(key), + freshlyStamped: stamped.contains(key), + window: window, + at: at, + includeNewlyStamped: includeNewlyStamped, + )) { + continue; + } // Verify and delete under the key's own lock, as one step. Deciding on // one call and deleting on another leaves a window, and a delete made on diff --git a/lib/storage/drift/blob_store.dart b/lib/storage/drift/blob_store.dart index 851dc462..e14662cc 100644 --- a/lib/storage/drift/blob_store.dart +++ b/lib/storage/drift/blob_store.dart @@ -350,6 +350,18 @@ class BlobStore { /// through hash-identical, with the row count unchanged. Future vacuum() => _db.customStatement('VACUUM'); + /// Every stored message, across every key. + /// + /// For the clear-confirmation dialog, which has to say what is NOT being + /// deleted (#962). + Future totalMessageRows() async { + final count = _db.messageRecords.mergeKey.count(); + final row = await (_db.selectOnly( + _db.messageRecords, + )..addColumns([count])).getSingle(); + return row.read(count) ?? 0; + } + /// How many messages are stored under [storeKey]. Future messageRowCount(String storeKey) async { final count = _db.messageRecords.mergeKey.count(); diff --git a/lib/widgets/storage_reclaim_card.dart b/lib/widgets/storage_reclaim_card.dart index d34cfd50..4e25a273 100644 --- a/lib/widgets/storage_reclaim_card.dart +++ b/lib/widgets/storage_reclaim_card.dart @@ -22,15 +22,20 @@ class StorageReclaimCard extends StatefulWidget { const StorageReclaimCard({ super.key, BlobStore? blobs, + Future Function()? runPreview, Future Function()? runSweep, Future Function()? readSize, }) : _blobs = blobs, + _runPreview = runPreview, _runSweep = runSweep, _readSize = readSize; /// Injectable for tests; production reads the singleton. final BlobStore? _blobs; + /// The preview, injectable for the same reason as the sweep. + final Future Function()? _runPreview; + /// The sweep, injectable. /// /// Not only for convenience: the real sweep uses `compute`, and an isolate @@ -85,12 +90,34 @@ class _StorageReclaimCardState extends State { _error = null; }); try { - // `olderThan: Duration.zero` is the whole point of the button: every - // migrated key is eligible immediately. The per-key verification is - // unchanged, so this skips the wait and not the safety. - final outcome = - await (widget._runSweep ?? - () => StaleHistorySweep(_blobs).run(olderThan: Duration.zero))(); + // Ask what WOULD go, then ask the user, then do it. Mockup variants 8 + // to 10, owner-approved 2026-10-23: a delete this size has to state its + // scope before it runs. + final preview = await (widget._runPreview ?? _defaultPreview)(); + if (!mounted) return; + + // Nothing to clear means nothing to confirm. Reporting straight away + // beats opening a dialog to say zero (variant 10). + if (!preview.hasWork) { + setState( + () => _result = StaleHistoryOutcome( + cleared: const [], + refused: preview.refused, + bytesBefore: _sizeBytes ?? 0, + bytesAfter: _sizeBytes ?? 0, + ), + ); + return; + } + + final go = await _confirm(preview); + if (!go || !mounted) return; + + // `olderThan: Duration.zero` with `includeNewlyStamped` is the whole + // point of the button: every migrated key is eligible immediately, even + // one stamped on this very pass. It skips the WAIT, not the safety; the + // per-key verification under the lock is unchanged. + final outcome = await (widget._runSweep ?? _defaultSweep)(); if (!mounted) return; setState(() { _result = outcome; @@ -105,6 +132,87 @@ class _StorageReclaimCardState extends State { } } + Future _defaultPreview() => StaleHistorySweep( + _blobs, + ).preview(olderThan: Duration.zero, includeNewlyStamped: true); + + Future _defaultSweep() => StaleHistorySweep( + _blobs, + ).run(olderThan: Duration.zero, includeNewlyStamped: true); + + /// The confirmation. Returns false on Cancel, on a tap outside, and on back. + Future _confirm(StaleHistoryPreview p) async { + final l10n = context.l10n; + final scheme = Theme.of(context).colorScheme; + final count = p.eligible.length; + + final ok = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text(l10n.storage_confirmTitle), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(l10n.storage_confirmBody(count, _mb(p.approximateBytes))), + const SizedBox(height: 12), + _note( + l10n.storage_confirmSafe(p.messagesKept), + Icons.check, + scheme.secondaryContainer, + scheme.onSecondaryContainer, + ), + const SizedBox(height: 8), + _note( + p.refused.isEmpty + ? l10n.storage_confirmIrreversible + : l10n.storage_confirmKeptBack(p.refused.length), + Icons.warning_amber, + scheme.tertiaryContainer, + scheme.onTertiaryContainer, + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: Text(l10n.common_cancel), + ), + FilledButton.tonal( + // Carries the count, so the last thing read before the tap is the + // scope of what it does. + onPressed: () => Navigator.of(context).pop(true), + style: FilledButton.styleFrom( + backgroundColor: scheme.errorContainer, + foregroundColor: scheme.onErrorContainer, + ), + child: Text(l10n.storage_confirmAction(count)), + ), + ], + ), + ); + return ok ?? false; + } + + Widget _note(String text, IconData icon, Color bg, Color fg) => Container( + width: double.infinity, + decoration: BoxDecoration( + color: bg, + borderRadius: BorderRadius.circular(8), + ), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(icon, size: 16, color: fg), + const SizedBox(width: 6), + Expanded( + child: Text(text, style: TextStyle(fontSize: 13, color: fg)), + ), + ], + ), + ); + static String _mb(int bytes) => '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB'; diff --git a/test/storage/stale_history_sweep_test.dart b/test/storage/stale_history_sweep_test.dart index 366e84c7..712a5b91 100644 --- a/test/storage/stale_history_sweep_test.dart +++ b/test/storage/stale_history_sweep_test.dart @@ -448,6 +448,148 @@ void main() { }); }); + group('the age rule, shared by preview and run', () { + final at = DateTime(2026, 10, 23, 12); + + test('an unstamped key is NOT eligible for the automatic sweep', () { + expect( + StaleHistorySweep.eligibleByAge( + migratedAt: null, + freshlyStamped: false, + window: staleHistoryWindow, + at: at, + includeNewlyStamped: false, + ), + isFalse, + reason: 'the stamp exists so an app update never deletes on sight', + ); + }); + + test('an unstamped key IS eligible for an explicit press', () { + expect( + StaleHistorySweep.eligibleByAge( + migratedAt: null, + freshlyStamped: true, + window: Duration.zero, + at: at, + includeNewlyStamped: true, + ), + isTrue, + reason: 'a user asking to clear now is not an app update', + ); + }); + + test('29 days out, 30 days in', () { + bool eligible(int days) => StaleHistorySweep.eligibleByAge( + migratedAt: at.subtract(Duration(days: days)), + freshlyStamped: false, + window: staleHistoryWindow, + at: at, + includeNewlyStamped: false, + ); + expect(eligible(29), isFalse); + expect(eligible(30), isTrue); + }); + }); + + group('the bug the preview exposed', () { + test('an install with NO stamps clears on the first press', () async { + // Every install that migrated before #962 has an empty + // __msgrows_migrated_at. The sweep stamps them all, and the old + // "skip anything stamped this pass" rule then skipped every one, so the + // button reported nothing to clear against real reclaimable blobs. That + // was the owner's install exactly: 47 migrated keys, none stamped. + await blobs.write(key, bigBlobWith(20)); + await blobs.ensureMessageRowsMigrated(key, toRows); + await blobs.write(BlobStore.migratedAtKey, '{}'); // nothing stamped + blobs.resetMigratedKeyCache(); + + // The automatic sweep still refuses, which is correct. + expect((await StaleHistorySweep(blobs).run()).cleared, isEmpty); + expect(await blobs.read(key), isNotNull); + + // The explicit press does not. + final outcome = await StaleHistorySweep( + blobs, + ).run(olderThan: Duration.zero, includeNewlyStamped: true); + expect(outcome.cleared, [key]); + expect(await blobs.read(key), isNull); + expect(await blobs.messageRowCount(key), 20); + }); + }); + + group('preview', () { + test('it reports what a press would clear, and writes nothing', () async { + await blobs.write(key, bigBlobWith(20)); + await blobs.ensureMessageRowsMigrated(key, toRows); + await blobs.write(BlobStore.migratedAtKey, '{}'); + blobs.resetMigratedKeyCache(); + + final p = await StaleHistorySweep( + blobs, + ).preview(olderThan: Duration.zero, includeNewlyStamped: true); + + expect(p.eligible, [key]); + expect(p.refused, isEmpty); + expect(p.hasWork, isTrue); + expect(p.approximateBytes, greaterThan(0)); + expect(p.messagesKept, 20); + + // Nothing was deleted and nothing was stamped, so a later run behaves + // exactly as if the preview had never happened. + expect(await blobs.read(key), isNotNull); + expect(await blobs.read(BlobStore.migratedAtKey), '{}'); + }); + + test('it forecasts a refusal instead of discovering it later', () async { + await migratedDaysAgo(key, 31); + await blobs.deleteMessageRow( + key, + (await blobs.messageMergeKeys(key)).first, + ); + + final p = await StaleHistorySweep(blobs).preview(); + + expect(p.eligible, isEmpty); + expect(p.refused, [key]); + expect( + p.hasWork, + isFalse, + reason: 'nothing to confirm, so the card reports without a dialog', + ); + }); + + test('preview and run agree on eligibility', () async { + // The dialog must not promise what the sweep will not do. Same inputs, + // same answer. + await migratedDaysAgo(key, 31); + const young = 'channel_messages_aaaaaaaaaapsk_young'; + await migratedDaysAgo(young, 2); + + final p = await StaleHistorySweep(blobs).preview(); + final outcome = await StaleHistorySweep(blobs).run(); + + expect(p.eligible, [key]); + expect(outcome.cleared, [key]); + expect(await blobs.read(young), isNotNull); + }); + + test('non-history and unmigrated keys never appear', () async { + await blobs.write('contacts', '[{"name":"a"}]'); + await blobs.upsertMessageRows('contacts', const [ + MessageRowInput(mergeKey: 'id:x', timestampMs: 1, payload: '{}'), + ]); + await blobs.write('channel_messages_bbbbbbbbbbpsk_un', bigBlobWith(5)); + + final p = await StaleHistorySweep( + blobs, + ).preview(olderThan: Duration.zero, includeNewlyStamped: true); + + expect(p.eligible, isEmpty); + expect(p.refused, isEmpty); + }); + }); + group('what the manual action relies on (#966)', () { test('olderThan zero makes a key migrated seconds ago eligible', () async { // The button passes Duration.zero, which is the whole point of it: no diff --git a/test/widgets/storage_reclaim_card_test.dart b/test/widgets/storage_reclaim_card_test.dart index c5d6f6b8..5a046d3f 100644 --- a/test/widgets/storage_reclaim_card_test.dart +++ b/test/widgets/storage_reclaim_card_test.dart @@ -31,9 +31,22 @@ void main() { bytesAfter: after, ); + StaleHistoryPreview preview({ + List eligible = const ['a'], + List refused = const [], + int bytes = 16 * 1024 * 1024, + int messagesKept = 29975, + }) => StaleHistoryPreview( + eligible: eligible, + refused: refused, + approximateBytes: bytes, + messagesKept: messagesKept, + ); + Future pump( WidgetTester tester, { required Future Function() runSweep, + Future Function()? runPreview, Future Function()? readSize, }) async { await tester.pumpWidget( @@ -42,6 +55,7 @@ void main() { supportedLocales: AppLocalizations.supportedLocales, home: Scaffold( body: StorageReclaimCard( + runPreview: runPreview ?? () async => preview(), runSweep: runSweep, readSize: readSize ?? () async => 70 * 1024 * 1024, ), @@ -51,6 +65,11 @@ void main() { await tester.pumpAndSettle(); } + Future confirm(WidgetTester tester) async { + await tester.tap(find.textContaining('Clear 1 copies')); + await tester.pumpAndSettle(); + } + Future tapClear(WidgetTester tester) async { await tester.tap(find.text('Clear Stale History Now')); await tester.pumpAndSettle(); @@ -65,13 +84,120 @@ void main() { expect(find.textContaining('70.0 MB'), findsOneWidget); }); - testWidgets('nothing eligible reports nothing to clear', (tester) async { - await pump(tester, runSweep: () async => outcome()); + group('the confirmation (variants 8 to 10)', () { + testWidgets('it states the scope before anything is deleted', ( + tester, + ) async { + await pump(tester, runSweep: () async => outcome(cleared: const ['a'])); - await tapClear(tester); + await tapClear(tester); - expect(find.text('Nothing to clear.'), findsOneWidget); - expect(find.textContaining('Kept'), findsNothing); + expect(find.text('Clear stale history?'), findsOneWidget); + expect(find.textContaining('1 old copies'), findsOneWidget); + expect(find.textContaining('16.0 MB'), findsOneWidget); + expect(find.textContaining('All 29975 stay'), findsOneWidget); + expect(find.text('This cannot be undone.'), findsOneWidget); + // The action carries the count, so the scope is the last thing read. + expect(find.textContaining('Clear 1 copies'), findsOneWidget); + }); + + testWidgets('Cancel deletes nothing and re-enables the button', ( + tester, + ) async { + var swept = false; + await pump( + tester, + runSweep: () async { + swept = true; + return outcome(cleared: const ['a']); + }, + ); + + await tapClear(tester); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + + expect(swept, isFalse, reason: 'Cancel must not run the sweep'); + expect(find.text('Clear stale history?'), findsNothing); + expect(find.textContaining('Cleared'), findsNothing); + expect( + tester.widget(find.byType(FilledButton)).onPressed, + isNotNull, + reason: 'cancelling must not leave the action dead for the session', + ); + }); + + testWidgets('a forecast refusal is shown BEFORE the press', (tester) async { + await pump( + tester, + runPreview: () async => preview(refused: const ['b']), + runSweep: () async => outcome(cleared: const ['a']), + ); + + await tapClear(tester); + + expect( + find.textContaining('1 will be kept back'), + findsOneWidget, + reason: 'knowing beforehand beats discovering it afterwards', + ); + expect(find.textContaining('cannot be undone'), findsOneWidget); + }); + + testWidgets('no eligible keys means no dialog at all', (tester) async { + await pump( + tester, + runPreview: () async => preview(eligible: const []), + runSweep: () async => outcome(), + ); + + await tapClear(tester); + + expect( + find.text('Clear stale history?'), + findsNothing, + reason: 'a dialog that only says zero is not worth opening', + ); + expect(find.text('Nothing to clear.'), findsOneWidget); + }); + + testWidgets('a refusal with nothing eligible still reports, no dialog', ( + tester, + ) async { + await pump( + tester, + runPreview: () async => + preview(eligible: const [], refused: const ['b']), + runSweep: () async => outcome(), + ); + + await tapClear(tester); + + expect(find.text('Clear stale history?'), findsNothing); + expect( + find.textContaining('Kept 1 that could not be verified'), + findsOneWidget, + ); + }); + + testWidgets('a preview failure reports and does not open a dialog', ( + tester, + ) async { + await pump( + tester, + runPreview: () async => throw StateError('no preview'), + runSweep: () async => outcome(cleared: const ['a']), + ); + + await tapClear(tester); + + expect(find.text('Clear stale history?'), findsNothing); + expect(find.textContaining('Could not finish'), findsOneWidget); + expect( + tester.widget(find.byType(FilledButton)).onPressed, + isNotNull, + ); + }); }); testWidgets('cleared keys report the count and the size returned', ( @@ -87,6 +213,7 @@ void main() { ); await tapClear(tester); + await confirm(tester); expect(find.textContaining('Cleared 3 old copies'), findsOneWidget); expect(find.textContaining('16.0 MB returned'), findsOneWidget); @@ -102,6 +229,7 @@ void main() { ); await tapClear(tester); + await confirm(tester); expect( find.textContaining('Kept 1 that could not be verified'), @@ -125,6 +253,7 @@ void main() { await pump(tester, runSweep: () async => outcome(refused: const ['b'])); await tapClear(tester); + await confirm(tester); expect(find.text('Nothing to clear.'), findsOneWidget); expect( @@ -142,6 +271,7 @@ void main() { await pump(tester, runSweep: () async => throw StateError('boom')); await tapClear(tester); + await confirm(tester); expect(find.textContaining('Could not finish'), findsOneWidget); expect(find.textContaining('messages are intact'), findsOneWidget); @@ -159,25 +289,32 @@ void main() { ) async { // The disabled button is not enough: setState only SCHEDULES a rebuild, // so two taps inside one frame both see a live onPressed. _clear guards - // on _running for that, and two concurrent sweeps would mean two - // concurrent VACUUMs. - var runs = 0; - final gate = Completer(); + // on _running for that. + // + // A tap now starts the PREVIEW, not the sweep, so that is what has to be + // counted. Two previews would also mean two dialogs stacked on each other. + var previews = 0; + final gate = Completer(); await pump( tester, - runSweep: () { - runs++; + runPreview: () { + previews++; return gate.future; }, + runSweep: () async => outcome(cleared: const ['a']), ); final button = find.text('Clear Stale History Now'); await tester.tap(button, warnIfMissed: false); await tester.tap(button, warnIfMissed: false); - expect(runs, 1, reason: 'the second tap in the same frame must be ignored'); + expect( + previews, + 1, + reason: 'the second tap in the same frame must be ignored', + ); - gate.complete(outcome()); + gate.complete(preview(eligible: const [])); await tester.pumpAndSettle(); }); @@ -185,7 +322,8 @@ void main() { final gate = Completer(); await pump(tester, runSweep: () => gate.future); - await tester.tap(find.text('Clear Stale History Now')); + await tapClear(tester); + await confirm(tester); await tester.pump(); expect( diff --git a/untranslated.json b/untranslated.json index 873a1bcb..a32d6d37 100644 --- a/untranslated.json +++ b/untranslated.json @@ -273,6 +273,12 @@ "storage_resultNothing", "storage_resultCleared", "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", "storage_resultFailed" ], @@ -550,6 +556,12 @@ "storage_resultNothing", "storage_resultCleared", "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", "storage_resultFailed" ], @@ -827,6 +839,12 @@ "storage_resultNothing", "storage_resultCleared", "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", "storage_resultFailed" ], @@ -1104,6 +1122,12 @@ "storage_resultNothing", "storage_resultCleared", "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", "storage_resultFailed" ], @@ -1381,6 +1405,12 @@ "storage_resultNothing", "storage_resultCleared", "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", "storage_resultFailed" ], @@ -1658,6 +1688,12 @@ "storage_resultNothing", "storage_resultCleared", "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", "storage_resultFailed" ], @@ -1935,6 +1971,12 @@ "storage_resultNothing", "storage_resultCleared", "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", "storage_resultFailed" ], @@ -2212,6 +2254,12 @@ "storage_resultNothing", "storage_resultCleared", "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", "storage_resultFailed" ], @@ -2489,6 +2537,12 @@ "storage_resultNothing", "storage_resultCleared", "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", "storage_resultFailed" ], @@ -2766,6 +2820,12 @@ "storage_resultNothing", "storage_resultCleared", "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", "storage_resultFailed" ], @@ -3043,6 +3103,12 @@ "storage_resultNothing", "storage_resultCleared", "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", "storage_resultFailed" ], @@ -3320,6 +3386,12 @@ "storage_resultNothing", "storage_resultCleared", "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", "storage_resultFailed" ], @@ -3597,6 +3669,12 @@ "storage_resultNothing", "storage_resultCleared", "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", "storage_resultFailed" ], @@ -3874,6 +3952,12 @@ "storage_resultNothing", "storage_resultCleared", "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", "storage_resultFailed" ], @@ -4151,6 +4235,12 @@ "storage_resultNothing", "storage_resultCleared", "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", "storage_resultFailed" ], @@ -4428,6 +4518,12 @@ "storage_resultNothing", "storage_resultCleared", "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", "storage_resultFailed" ], @@ -4705,6 +4801,12 @@ "storage_resultNothing", "storage_resultCleared", "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", "storage_resultFailed" ] }