feat(#966): Clear Stale History Now, with refusals reported
Epic B of #962. The manual trigger for Epic A's sweep, so a user does not wait 30 days. It passes olderThan: Duration.zero, which skips the WAIT and not the safety: the per-key verification inside reclaimVerifiedHistoryBlob is unchanged, proved by a test that Duration.zero still refuses a key whose rows cannot be verified. Its own widget rather than another card in app_settings_view.dart, which is already past a thousand lines, and so the tests can drive it without standing up the whole settings screen. Stateful against the repo's usual StatelessWidget-plus-Consumer habit, because the running flag and the last result are local to this card and belong to no service. The sweep is INJECTED, and that is a finding rather than a convenience. The first version of the widget test called the real sweep and hung past ten minutes instead of failing: the sweep uses compute, and an isolate deadlocks pumpAndSettle inside flutter_test's fake-async zone. A widget test should test the widget. So the card takes the sweep and the size read as parameters, the nine widget tests feed outcomes in directly, and the two new tests in stale_history_sweep_test.dart keep the injected semantic honest under plain test() where isolates work. Owner decision 2026-10-22, and the reason this Epic exists: the button REPORTS keys it refused, it does not only log them. "Cleared 1 old copies, 16.0 MB returned" and "Kept 1 that could not be verified" are both shown, including when a refusal is the reason nothing was cleared, which is the most important case to surface rather than the least. The automatic sweep stays log-only. Two Gemini findings, both fixed: - A fast double tap ran two sweeps. The disabled button is not enough on its own, because setState only SCHEDULES a rebuild, so two taps inside one frame both see a live onPressed. _clear now returns early on _running, and a test taps twice in one frame and asserts the sweep ran once. Two concurrent sweeps would have meant two concurrent VACUUMs. - A throw after real deletes was reported as a total failure. The honest fix was in the sweep, not the string: a successful sweep must not become an error because the closing size read threw, so that read now falls back to bytesBefore, which understates the reclaimed figure rather than inventing one. The failure string no longer claims nothing happened either. Strings are English-only, as everywhere else here: gen-l10n falls back to the template locale, and untranslated.json records the 9 keys across 17 locales, which is what that tracked file is for. 29 tests in the two files, full suite 1,483 pass, 1 skipped. analyze clean, format clean. Task: meshcore-open-gan Agent Mail: TealGlen Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>pull/990/head
parent
84c2dbd9da
commit
cc2fb23b2e
@ -0,0 +1,185 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../l10n/app_localizations.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import '../services/stale_history_sweep.dart';
|
||||
import '../storage/drift/blob_store.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
|
||||
/// "Clear Stale History Now": the manual trigger for the #962 sweep.
|
||||
///
|
||||
/// A migrated message key keeps a frozen copy of its history, which the sweep
|
||||
/// reclaims 30 days later on its own. This is for not waiting.
|
||||
///
|
||||
/// Its own widget rather than another card inside `app_settings_view.dart`,
|
||||
/// which is already past a thousand lines, and so that B2's tests can drive it
|
||||
/// without standing up the whole settings screen.
|
||||
///
|
||||
/// Stateful, against the repo's usual StatelessWidget-plus-Consumer habit,
|
||||
/// because the running flag and the last result are local to this card and
|
||||
/// belong to no service.
|
||||
class StorageReclaimCard extends StatefulWidget {
|
||||
const StorageReclaimCard({
|
||||
super.key,
|
||||
BlobStore? blobs,
|
||||
Future<StaleHistoryOutcome> Function()? runSweep,
|
||||
Future<int> Function()? readSize,
|
||||
}) : _blobs = blobs,
|
||||
_runSweep = runSweep,
|
||||
_readSize = readSize;
|
||||
|
||||
/// Injectable for tests; production reads the singleton.
|
||||
final BlobStore? _blobs;
|
||||
|
||||
/// The sweep, injectable.
|
||||
///
|
||||
/// Not only for convenience: the real sweep uses `compute`, and an isolate
|
||||
/// deadlocks `pumpAndSettle` inside `flutter_test`'s fake-async zone. The
|
||||
/// sweep's own behaviour is covered by Epic A's unit tests, which run under
|
||||
/// plain `test()` where isolates work. What is left to prove here is that
|
||||
/// this card reports each outcome correctly, and that is testable without
|
||||
/// re-running the engine.
|
||||
final Future<StaleHistoryOutcome> Function()? _runSweep;
|
||||
|
||||
/// The size read, injectable for the same reason.
|
||||
final Future<int> Function()? _readSize;
|
||||
|
||||
@override
|
||||
State<StorageReclaimCard> createState() => _StorageReclaimCardState();
|
||||
}
|
||||
|
||||
class _StorageReclaimCardState extends State<StorageReclaimCard> {
|
||||
BlobStore get _blobs => widget._blobs ?? BlobStore.instance;
|
||||
|
||||
bool _running = false;
|
||||
int? _sizeBytes;
|
||||
StaleHistoryOutcome? _result;
|
||||
Object? _error;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_refreshSize();
|
||||
}
|
||||
|
||||
Future<void> _refreshSize() async {
|
||||
try {
|
||||
final size = await (widget._readSize ?? _blobs.databaseSizeBytes)();
|
||||
if (mounted) setState(() => _sizeBytes = size);
|
||||
} catch (e) {
|
||||
// A size we cannot read is not worth an error state: the action below
|
||||
// still works, and the row simply shows nothing.
|
||||
appLogger.warn('Could not read the database size: $e', tag: 'Storage');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _clear() async {
|
||||
// The disabled button is not enough on its own. `setState` only schedules
|
||||
// a rebuild, so two taps inside one frame both see an `onPressed` that is
|
||||
// still non-null and both reach here, which would run two sweeps and two
|
||||
// VACUUMs concurrently (Gemini review).
|
||||
if (_running) return;
|
||||
setState(() {
|
||||
_running = true;
|
||||
_result = null;
|
||||
_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))();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_result = outcome;
|
||||
_sizeBytes = outcome.bytesAfter;
|
||||
});
|
||||
} catch (e, s) {
|
||||
appLogger.error('Clear stale history failed: $e\n$s', tag: 'Storage');
|
||||
if (!mounted) return;
|
||||
setState(() => _error = e);
|
||||
} finally {
|
||||
if (mounted) setState(() => _running = false);
|
||||
}
|
||||
}
|
||||
|
||||
static String _mb(int bytes) =>
|
||||
'${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = context.l10n;
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
l10n.storage_title,
|
||||
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
if (_sizeBytes != null)
|
||||
Text(l10n.storage_databaseSize(_mb(_sizeBytes!))),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
l10n.storage_staleHint,
|
||||
style: TextStyle(fontSize: 12, color: Colors.grey[600]),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: FilledButton.tonal(
|
||||
onPressed: _running ? null : _clear,
|
||||
child: Text(
|
||||
_running ? l10n.storage_working : l10n.storage_clearStaleNow,
|
||||
),
|
||||
),
|
||||
),
|
||||
?_resultLine(l10n),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget? _resultLine(AppLocalizations l10n) {
|
||||
if (_error != null) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(top: 12),
|
||||
child: Text(
|
||||
l10n.storage_resultFailed,
|
||||
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
||||
),
|
||||
);
|
||||
}
|
||||
final r = _result;
|
||||
if (r == null) return null;
|
||||
|
||||
final lines = <String>[
|
||||
if (r.cleared.isEmpty)
|
||||
l10n.storage_resultNothing
|
||||
else
|
||||
l10n.storage_resultCleared(
|
||||
r.cleared.length,
|
||||
_mb(r.bytesReclaimed < 0 ? 0 : r.bytesReclaimed),
|
||||
),
|
||||
// Owner decision 2026-10-22: the button reports what it refused, it does
|
||||
// not just log it. A key kept back because its rows could not be
|
||||
// verified is the single most useful thing this action can tell you, and
|
||||
// staying quiet about it is how #952 went unnoticed for days.
|
||||
if (r.refused.isNotEmpty) l10n.storage_resultRefused(r.refused.length),
|
||||
];
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(top: 12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [for (final line in lines) Text(line)],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,225 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/l10n/app_localizations.dart';
|
||||
import 'package:meshcore_open/services/stale_history_sweep.dart';
|
||||
import 'package:meshcore_open/widgets/storage_reclaim_card.dart';
|
||||
|
||||
/// Epic B of #962, task B2.
|
||||
///
|
||||
/// Tests the CARD, not the sweep. The sweep's behaviour is pinned by Epic A's
|
||||
/// 18 unit tests, which run under plain `test()`. It cannot be re-run here:
|
||||
/// it uses `compute`, and an isolate deadlocks `pumpAndSettle` inside
|
||||
/// `flutter_test`'s fake-async zone, which is what made the first version of
|
||||
/// this file hang past ten minutes rather than fail. So the sweep is injected
|
||||
/// and each outcome is fed in directly.
|
||||
///
|
||||
/// The case this task exists for is the third one: a key held back because its
|
||||
/// rows could not be verified must be REPORTED, not merely logged. Owner
|
||||
/// decision 2026-10-22.
|
||||
void main() {
|
||||
StaleHistoryOutcome outcome({
|
||||
List<String> cleared = const [],
|
||||
List<String> refused = const [],
|
||||
int before = 70 * 1024 * 1024,
|
||||
int after = 70 * 1024 * 1024,
|
||||
}) => StaleHistoryOutcome(
|
||||
cleared: cleared,
|
||||
refused: refused,
|
||||
bytesBefore: before,
|
||||
bytesAfter: after,
|
||||
);
|
||||
|
||||
Future<void> pump(
|
||||
WidgetTester tester, {
|
||||
required Future<StaleHistoryOutcome> Function() runSweep,
|
||||
Future<int> Function()? readSize,
|
||||
}) async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(
|
||||
body: StorageReclaimCard(
|
||||
runSweep: runSweep,
|
||||
readSize: readSize ?? () async => 70 * 1024 * 1024,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
Future<void> tapClear(WidgetTester tester) async {
|
||||
await tester.tap(find.text('Clear Stale History Now'));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
testWidgets('it shows the database size before anything is clicked', (
|
||||
tester,
|
||||
) async {
|
||||
await pump(tester, runSweep: () async => outcome());
|
||||
|
||||
expect(find.textContaining('Message database:'), findsOneWidget);
|
||||
expect(find.textContaining('70.0 MB'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('nothing eligible reports nothing to clear', (tester) async {
|
||||
await pump(tester, runSweep: () async => outcome());
|
||||
|
||||
await tapClear(tester);
|
||||
|
||||
expect(find.text('Nothing to clear.'), findsOneWidget);
|
||||
expect(find.textContaining('Kept'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('cleared keys report the count and the size returned', (
|
||||
tester,
|
||||
) async {
|
||||
await pump(
|
||||
tester,
|
||||
runSweep: () async => outcome(
|
||||
cleared: const ['a', 'b', 'c'],
|
||||
before: 70 * 1024 * 1024,
|
||||
after: 54 * 1024 * 1024,
|
||||
),
|
||||
);
|
||||
|
||||
await tapClear(tester);
|
||||
|
||||
expect(find.textContaining('Cleared 3 old copies'), findsOneWidget);
|
||||
expect(find.textContaining('16.0 MB returned'), findsOneWidget);
|
||||
// And the size row updates to what the sweep actually left behind, rather
|
||||
// than still showing the pre-sweep number.
|
||||
expect(find.textContaining('Message database: 54.0 MB'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('a refused key is REPORTED, not just logged', (tester) async {
|
||||
await pump(
|
||||
tester,
|
||||
runSweep: () async => outcome(cleared: const ['a'], refused: const ['b']),
|
||||
);
|
||||
|
||||
await tapClear(tester);
|
||||
|
||||
expect(
|
||||
find.textContaining('Kept 1 that could not be verified'),
|
||||
findsOneWidget,
|
||||
reason: 'silence here is how #952 went unnoticed for days',
|
||||
);
|
||||
expect(
|
||||
find.textContaining('messages are intact'),
|
||||
findsOneWidget,
|
||||
reason:
|
||||
'it has to say the history is safe, not only that something was '
|
||||
'held back',
|
||||
);
|
||||
// Both halves are shown: what went and what did not.
|
||||
expect(find.textContaining('Cleared 1 old copies'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('refusals show even when nothing at all was cleared', (
|
||||
tester,
|
||||
) async {
|
||||
await pump(tester, runSweep: () async => outcome(refused: const ['b']));
|
||||
|
||||
await tapClear(tester);
|
||||
|
||||
expect(find.text('Nothing to clear.'), findsOneWidget);
|
||||
expect(
|
||||
find.textContaining('Kept 1 that could not be verified'),
|
||||
findsOneWidget,
|
||||
reason:
|
||||
'a run that cleared nothing BECAUSE of a refusal is the most '
|
||||
'important case to surface, not the least',
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('a failure says the messages are intact', (tester) async {
|
||||
// "Could not finish" on a delete action otherwise reads as "something was
|
||||
// half-deleted".
|
||||
await pump(tester, runSweep: () async => throw StateError('boom'));
|
||||
|
||||
await tapClear(tester);
|
||||
|
||||
expect(find.textContaining('Could not finish'), findsOneWidget);
|
||||
expect(find.textContaining('messages are intact'), findsOneWidget);
|
||||
expect(
|
||||
find.textContaining('may already have been cleared'),
|
||||
findsOneWidget,
|
||||
reason:
|
||||
'the sweep deletes per key, so a throw can follow real deletes and '
|
||||
'the message must not claim nothing happened (Gemini review)',
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('a second tap in the same frame cannot start a second sweep', (
|
||||
tester,
|
||||
) 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>();
|
||||
await pump(
|
||||
tester,
|
||||
runSweep: () {
|
||||
runs++;
|
||||
return gate.future;
|
||||
},
|
||||
);
|
||||
|
||||
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');
|
||||
|
||||
gate.complete(outcome());
|
||||
await tester.pumpAndSettle();
|
||||
});
|
||||
|
||||
testWidgets('the button is disabled while it runs', (tester) async {
|
||||
final gate = Completer<StaleHistoryOutcome>();
|
||||
await pump(tester, runSweep: () => gate.future);
|
||||
|
||||
await tester.tap(find.text('Clear Stale History Now'));
|
||||
await tester.pump();
|
||||
|
||||
expect(
|
||||
tester.widget<FilledButton>(find.byType(FilledButton)).onPressed,
|
||||
isNull,
|
||||
reason: 'a second tap mid-sweep would run two VACUUMs at once',
|
||||
);
|
||||
expect(find.text('Clearing...'), findsOneWidget);
|
||||
|
||||
gate.complete(outcome(cleared: const ['a']));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(
|
||||
tester.widget<FilledButton>(find.byType(FilledButton)).onPressed,
|
||||
isNotNull,
|
||||
reason: 'and it must come back, or the action works exactly once',
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('an unreadable size leaves the row out rather than erroring', (
|
||||
tester,
|
||||
) async {
|
||||
await pump(
|
||||
tester,
|
||||
runSweep: () async => outcome(),
|
||||
readSize: () async => throw StateError('no size'),
|
||||
);
|
||||
|
||||
expect(find.textContaining('Message database:'), findsNothing);
|
||||
// The action is still usable: a size we cannot read is not a reason to
|
||||
// block clearing.
|
||||
expect(
|
||||
tester.widget<FilledButton>(find.byType(FilledButton)).onPressed,
|
||||
isNotNull,
|
||||
);
|
||||
});
|
||||
}
|
||||
Loading…
Reference in new issue