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 <noreply@anthropic.com>
feat/966-clear-stale-history
diffwireauto 1 month ago
parent bf936068b7
commit 67f9bf902b

@ -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 |

@ -0,0 +1,168 @@
<!doctype html>
<html lang="en"><head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Storage card mockups</title>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&amp;family=JetBrains+Mono:wght@400;600&amp;display=swap" rel="stylesheet">
<style>
/* Material 3, light scheme, blue seed, as main.dart actually configures it
(useMaterial3, ThemeMode.system, seed blue). Dark follows automatically and
is not drawn. Phone pane shown at 360 wide, the narrowest real target. */
:root{
--surf:#FDFCFF; --surfC:#FFFFFF; --surfCHigh:#F3F3FA; --surfCHighest:#E5E2EA;
--onSurf:#1B1B1F; --onSurfVar:#45464F; --outline:#767680; --outlineVar:#C7C5D0;
--prim:#0B57D0; --onPrim:#FFFFFF; --primCont:#D8E2FF; --onPrimCont:#001849;
--err:#BA1A1A; --errCont:#FFDAD6; --onErrCont:#410002;
--okCont:#C4EED0; --onOkCont:#002110;
--warnCont:#FFDEA6; --onWarnCont:#2A1800;
--page:#15151A; --pageInk:#D8D8E0; --pageDim:#8E8E99;
--sans:'Roboto',system-ui,sans-serif; --mono:'JetBrains Mono',monospace;
}
*{box-sizing:border-box;margin:0;padding:0}
body{background:var(--page);color:var(--pageInk);font-family:var(--sans);padding:24px 16px 48px}
h1{font-size:26px;font-weight:500;color:#fff}
h3{font-size:18px;font-weight:500;color:#9FC2FF;margin:30px 0 10px}
.lede{font-size:15px;color:var(--pageDim);margin:8px 0 10px;max-width:980px;line-height:1.5}
.lede b{color:var(--pageInk);font-weight:500}
.grid{display:flex;flex-wrap:wrap;gap:28px}
.card{width:360px}
.card h2{font-size:17px;font-weight:500;color:#fff}
.card .n{font-family:var(--mono);font-size:12px;color:#9FC2FF;margin-right:6px}
.card p{font-size:14px;color:var(--pageInk);margin:4px 0 10px;line-height:1.35;min-height:60px}
.card ul{font-size:13px;color:var(--pageDim);margin:10px 0 0 16px;line-height:1.4}
.card ul b{color:var(--pageInk);font-weight:500}
/* phone pane */
.dev{width:360px;border:1px solid #2c2c33;border-radius:12px;overflow:hidden;background:var(--surf)}
.appbar{height:56px;display:flex;align-items:center;gap:16px;padding:0 16px;background:var(--surfCHigh);color:var(--onSurf)}
.appbar .bk{font-size:20px;color:var(--onSurfVar)}
.appbar .t{font-size:20px;font-weight:400}
.pane{padding:16px;display:flex;flex-direction:column;gap:16px;background:var(--surf)}
.mc{background:var(--surfC);border-radius:12px;padding:16px 20px;color:var(--onSurf);border:1px solid var(--outlineVar)}
.mc .ct{font-size:16px;font-weight:500;margin-bottom:8px}
.mc .size{font-size:16px;margin-bottom:8px}
.mc .hint{font-size:12px;color:var(--onSurfVar);line-height:1.45;margin-bottom:12px}
.mc .res{font-size:14px;margin-top:12px;line-height:1.5}
.mc .res.kept{color:var(--onWarnCont);background:var(--warnCont);border-radius:8px;padding:8px 10px;margin-top:8px}
.mc .res.bad{color:var(--onErrCont);background:var(--errCont);border-radius:8px;padding:8px 10px}
.btn{display:inline-flex;align-items:center;justify-content:center;height:40px;padding:0 20px;border-radius:20px;
font-size:14px;font-weight:500;background:var(--primCont);color:var(--onPrimCont);border:none}
.btn.off{background:var(--surfCHighest);color:var(--outline)}
.btn.txt{background:none;color:var(--prim);padding:0 12px}
.btn.dang{background:var(--errCont);color:var(--onErrCont)}
.ghost{font-size:14px;color:var(--onSurfVar)}
/* dialog */
.scrim{background:rgba(0,0,0,.45);padding:28px 16px;display:flex;justify-content:center}
.dlg{background:var(--surfCHigh);border-radius:28px;padding:24px;max-width:312px;width:100%;color:var(--onSurf)}
.dlg .dt{font-size:24px;font-weight:400;line-height:1.25;margin-bottom:16px}
.dlg .db{font-size:14px;color:var(--onSurfVar);line-height:1.5;margin-bottom:12px}
.dlg .db b{color:var(--onSurf);font-weight:500}
.dlg .note{font-size:13px;border-radius:8px;padding:10px 12px;margin-bottom:12px;line-height:1.45}
.dlg .note.ok{background:var(--okCont);color:var(--onOkCont)}
.dlg .note.warn{background:var(--warnCont);color:var(--onWarnCont)}
.dlg .acts{display:flex;justify-content:flex-end;gap:8px;margin-top:8px}
.spin{display:inline-block;width:14px;height:14px;border:2px solid var(--outline);border-top-color:transparent;border-radius:50%;margin-right:8px;vertical-align:-2px}
.tag{font-family:var(--mono);font-size:11px;color:#9FC2FF}
</style>
</head>
<body>
<h1>Storage card and clear confirmation (Epic B, #966)</h1>
<p class="lede">Material 3, light scheme, blue seed, as <span class="tag">main.dart</span> 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: <b>70.9 MB database, 47 migrated keys, 40 with a stale copy, 29,975 messages, about 16.6 MB reclaimable</b>. Bullets under each card are the behaviour to build. <b>Owner-approved 2026-10-23:</b> all variants as drawn, and the label stays <b>Clear Stale History Now</b> rather than "Compact" &mdash; 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.</p>
<h3>Where it lives</h3>
<div class="grid">
<div class="card"><h2><span class="n">1</span>App Settings, bottom of the pane</h2><p>A new <b>Storage</b> 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.</p>
<div class="dev"><div class="appbar"><span class="bk">&#8249;</span><span class="t">App Settings</span></div>
<div class="pane">
<div class="mc"><div class="ct">Cyrillic to Latin</div><div class="hint" style="margin:0">Transliterate incoming Cyrillic text.</div></div>
<div class="mc"><div class="ct">Storage</div><div class="size">Message database: 70.9 MB</div>
<div class="hint">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.</div>
<span class="btn">Clear Stale History Now</span></div>
</div></div>
<ul><li>Last card, so a destructive action is never the first thing under a thumb.</li><li>Size is read on build and after any clear. A failure to read it hides the row, never blocks the button (variant 7).</li><li>Same widget on Windows; only the column width differs.</li></ul></div>
</div>
<h3>The card's states, as built today</h3>
<div class="grid">
<div class="card"><h2><span class="n">2</span>Working</h2><p>The button disables and relabels while the sweep runs. A second tap in the same frame is also refused in code, because <span class="tag">setState</span> only schedules a rebuild.</p>
<div class="dev"><div class="pane"><div class="mc"><div class="ct">Storage</div><div class="size">Message database: 70.9 MB</div>
<div class="hint">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.</div>
<span class="btn off"><span class="spin"></span>Clearing...</span></div></div></div>
<ul><li>Two concurrent sweeps would mean two concurrent <span class="tag">VACUUM</span>s.</li><li>Re-enables on success and on failure, or the action works exactly once per launch.</li></ul></div>
<div class="card"><h2><span class="n">3</span>Cleared</h2><p>Count and bytes returned, and the size row updates to what the sweep actually left behind rather than the number it started with.</p>
<div class="dev"><div class="pane"><div class="mc"><div class="ct">Storage</div><div class="size">Message database: 54.3 MB</div>
<div class="hint">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.</div>
<span class="btn">Clear Stale History Now</span>
<div class="res">Cleared 40 old copies, 16.6 MB returned.</div></div></div></div>
<ul><li>Bytes come from SQLite either side of the sweep, not from adding up blob lengths.</li><li>Pressing again is harmless: those keys have no copy left, so it reports nothing to clear.</li></ul></div>
<div class="card"><h2><span class="n">4</span>Cleared, with something kept back</h2><p>A key whose rows could not be verified keeps its copy and is <b>reported</b>, not merely logged. This is the case the Epic exists for.</p>
<div class="dev"><div class="pane"><div class="mc"><div class="ct">Storage</div><div class="size">Message database: 54.3 MB</div>
<div class="hint">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.</div>
<span class="btn">Clear Stale History Now</span>
<div class="res">Cleared 39 old copies, 16.2 MB returned.</div>
<div class="res kept">Kept 1 that could not be verified. Your messages are intact; nothing was deleted for those.</div></div></div></div>
<ul><li>Shown even when a refusal is the reason <b>nothing</b> was cleared, which is the most important case to surface, not the least.</li><li>The automatic 30-day sweep stays log-only: nobody is watching it.</li><li>Which keys and which records are named in the durable audit, not on screen.</li></ul></div>
<div class="card"><h2><span class="n">5</span>Nothing to clear</h2><p>The ordinary state for anyone who has already swept, or who has no migrated history yet.</p>
<div class="dev"><div class="pane"><div class="mc"><div class="ct">Storage</div><div class="size">Message database: 54.3 MB</div>
<div class="hint">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.</div>
<span class="btn">Clear Stale History Now</span>
<div class="res">Nothing to clear.</div></div></div></div>
<ul><li>Says so plainly rather than showing a zero-byte success.</li></ul></div>
<div class="card"><h2><span class="n">6</span>Failed</h2><p>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.</p>
<div class="dev"><div class="pane"><div class="mc"><div class="ct">Storage</div><div class="size">Message database: 70.9 MB</div>
<div class="hint">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.</div>
<span class="btn">Clear Stale History Now</span>
<div class="res bad">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.</div></div></div></div>
<ul><li>No exception text on screen; the reason goes to the log and the audit.</li></ul></div>
<div class="card"><h2><span class="n">7</span>Size unreadable</h2><p>A size we cannot read is not a reason to block clearing, so the row is left out and the action stays live.</p>
<div class="dev"><div class="pane"><div class="mc"><div class="ct">Storage</div>
<div class="hint">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.</div>
<span class="btn">Clear Stale History Now</span></div></div></div>
<ul><li>Logged as a warning, never surfaced as an error.</li></ul></div>
</div>
<h3>Proposed: confirm before deleting</h3>
<p class="lede">None of this exists. It needs a <b>preview pass</b> 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.</p>
<div class="grid">
<div class="card"><h2><span class="n">8</span>Confirm, the normal case</h2><p>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.</p>
<div class="dev"><div class="scrim"><div class="dlg">
<div class="dt">Clear stale history?</div>
<div class="db">This removes <b>40 old copies</b> of history that has already moved to the new format, freeing about <b>16.6 MB</b>.</div>
<div class="note ok">Your messages are not affected. All 29,975 stay.</div>
<div class="note warn">This cannot be undone.</div>
<div class="acts"><span class="btn txt">Cancel</span><span class="btn dang">Clear 40 copies</span></div>
</div></div></div>
<ul><li>Counts come from a real preview pass, not an estimate.</li><li>Cancel is the plain text button and sits left, so the destructive one is never the default target.</li><li>Dismissing by tapping outside or back cancels.</li></ul></div>
<div class="card"><h2><span class="n">9</span>Confirm, with a forecast refusal</h2><p>If the preview already knows a key cannot be verified, say so <b>before</b> the press rather than reporting it afterwards.</p>
<div class="dev"><div class="scrim"><div class="dlg">
<div class="dt">Clear stale history?</div>
<div class="db">This removes <b>39 old copies</b> of history that has already moved to the new format, freeing about <b>16.2 MB</b>.</div>
<div class="note ok">Your messages are not affected. All 29,975 stay.</div>
<div class="note warn">1 copy will be kept back because its messages could not be verified. This cannot be undone.</div>
<div class="acts"><span class="btn txt">Cancel</span><span class="btn dang">Clear 39 copies</span></div>
</div></div></div>
<ul><li>The count in the button excludes what will be kept, so it matches what actually goes.</li><li>A refusal discovered only at delete time still reports after the fact, as variant 4.</li></ul></div>
<div class="card"><h2><span class="n">10</span>Nothing eligible, no dialog</h2><p>With nothing to clear there is nothing to confirm, so the press reports straight away rather than opening a dialog to say "zero".</p>
<div class="dev"><div class="pane"><div class="mc"><div class="ct">Storage</div><div class="size">Message database: 54.3 MB</div>
<div class="hint">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.</div>
<span class="btn">Clear Stale History Now</span>
<div class="res">Nothing to clear.</div></div></div></div>
<ul><li>The preview runs on the press. Empty result means no dialog at all.</li><li>So the preview must be cheap enough to run on a tap: it reads and verifies, it does not write.</li></ul></div>
<div class="card"><h2><span class="n">11</span>Label: the open question</h2><p>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.</p>
<div class="dev"><div class="pane"><div class="mc"><div class="ct">Storage</div><div class="size">Message database: 70.9 MB</div>
<div class="hint">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.</div>
<span class="btn">Compact now</span></div></div></div>
<ul><li>"Compact" is what <span class="tag">VACUUM</span> does and reads less alarming; "Clear Stale History" says what is removed.</li><li>Owner's call. Either way the dialog in variant 8 states the scope.</li></ul></div>
</div>
</body></html>

@ -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)."

@ -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:

@ -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.';

@ -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.';

@ -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.';

@ -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.';

@ -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.';

@ -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.';

@ -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.';

@ -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.';

@ -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.';

@ -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.';

@ -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.';

@ -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.';

@ -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.';

@ -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.';

@ -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.';

@ -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.';

@ -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.';

@ -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.';

@ -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<String> eligible;
/// Keys already known to be unverifiable, so they would be kept. Saying so
/// before the press beats reporting it afterwards.
final List<String> 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<StaleHistoryPreview> preview({
Duration? olderThan,
DateTime? now,
bool includeNewlyStamped = false,
}) async {
final window = olderThan ?? staleHistoryWindow;
final at = now ?? DateTime.now();
final eligible = <String>[];
final refused = <String>[];
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<StaleHistoryOutcome> 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<StaleHistoryOutcome> 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

@ -350,6 +350,18 @@ class BlobStore {
/// through hash-identical, with the row count unchanged.
Future<void> 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<int> 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<int> messageRowCount(String storeKey) async {
final count = _db.messageRecords.mergeKey.count();

@ -22,15 +22,20 @@ class StorageReclaimCard extends StatefulWidget {
const StorageReclaimCard({
super.key,
BlobStore? blobs,
Future<StaleHistoryPreview> Function()? runPreview,
Future<StaleHistoryOutcome> Function()? runSweep,
Future<int> 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<StaleHistoryPreview> 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<StorageReclaimCard> {
_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<StorageReclaimCard> {
}
}
Future<StaleHistoryPreview> _defaultPreview() => StaleHistorySweep(
_blobs,
).preview(olderThan: Duration.zero, includeNewlyStamped: true);
Future<StaleHistoryOutcome> _defaultSweep() => StaleHistorySweep(
_blobs,
).run(olderThan: Duration.zero, includeNewlyStamped: true);
/// The confirmation. Returns false on Cancel, on a tap outside, and on back.
Future<bool> _confirm(StaleHistoryPreview p) async {
final l10n = context.l10n;
final scheme = Theme.of(context).colorScheme;
final count = p.eligible.length;
final ok = await showDialog<bool>(
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';

@ -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

@ -31,9 +31,22 @@ void main() {
bytesAfter: after,
);
StaleHistoryPreview preview({
List<String> eligible = const ['a'],
List<String> refused = const [],
int bytes = 16 * 1024 * 1024,
int messagesKept = 29975,
}) => StaleHistoryPreview(
eligible: eligible,
refused: refused,
approximateBytes: bytes,
messagesKept: messagesKept,
);
Future<void> pump(
WidgetTester tester, {
required Future<StaleHistoryOutcome> Function() runSweep,
Future<StaleHistoryPreview> Function()? runPreview,
Future<int> 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<void> confirm(WidgetTester tester) async {
await tester.tap(find.textContaining('Clear 1 copies'));
await tester.pumpAndSettle();
}
Future<void> 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<FilledButton>(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<FilledButton>(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<StaleHistoryOutcome>();
// 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<StaleHistoryPreview>();
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<StaleHistoryOutcome>();
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(

@ -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"
]
}

Loading…
Cancel
Save

Powered by TurnKey Linux.