fix(alarmas,auto): guard the last unguarded snooze path, surface car progress

Continuation of 7054a4c: the native anchor guard alone did not fix the
reported ~1444-minute snooze, because Dart runs AFTERWARDS on the
pre-notice path and had no guard at all.

1. Snooze from the pre-notice notification, root cause.

app.dart dispatches AFTER the receiver's postponeNext already ran and
after startActivity, and EstadoAlarmas.posponerProximaDesdePreaviso took
whatever occurrence it was handed on faith, then persisted and
rescheduled from it -- the last snooze path in the codebase with no
occurrence guard. The occurrence itself is not trustworthy either:
app.dart falls back to alarma.proximaEjecucion when the native event
carries none, and that field can already point at tomorrow.

_ocurrenciaSonando is generalized into _ocurrenciaValida with a caller-
supplied forward allowance and an externally-proposed occurrence that
still has to survive the same check. The pre-notice path gets a
ventanaPreaviso (30 min, matching AlarmScheduler.PRE_NOTICE_MILLIS) --
unlike the ringing-screen guard, this occurrence legitimately has not
happened yet, which is exactly why the existing helper could not just be
reused here.

Also heals state already poisoned by the missing guard: a snoozeHasta
parked past a 3-hour ceiling (posponerEjecucion clamps to 120 minutes,
so anything beyond that is corruption, not a long real snooze) is
dropped on recalculation. Without it, an alarm poisoned on a build
before this fix keeps reporting tomorrow after updating, and the user
reasonably concludes nothing changed.

2. Android Auto: no progress bar or time labels on a local track.

updatePosition was never set anywhere in the handler, so it sat at its
Duration.zero default while copyWith refreshed updateTime to now on every
push -- the car was told "position 0, as of right now" on every event, a
bar pinned at the start regardless of what was actually playing. Now set
from _player.position on both the player-state and buffered-position
listeners (the latter ticks ~2/s, which is what keeps the car's bar
smooth between player-state events). Also stream the MediaItem's
duration once the source reports it -- Auto draws no bar at all without
one, and radio streams correctly keep reporting none (live audio has no
length).

3. Android Auto: drop the Ecualizador browsable folder.

Owner decision after driving with it: a browsable six-preset list is
more interaction than a driver wants, and on/off from all three player
views (already fixed in 7054a4c to win the custom-action slot) is the
only equalizer control that belongs in the car. Preset selection stays on
the phone. This lands back on the redesign mockup's original rule ("sin
carpeta de ecualizador"), now for a road-tested reason. getChildren keeps
answering the folder's id transitionally, since a head unit can have the
old tree cached for a session or two.

The two "raiz always includes/ends with Ecualizador" tests are replaced,
not regressed -- same move the codebase already made once in the other
direction for the same folder.

Tests: 1127 -> 1132.
This commit is contained in:
2026-08-05 23:07:10 +02:00
parent 2bafc7e5ac
commit 80538900db
6 changed files with 326 additions and 59 deletions
@@ -0,0 +1,163 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pluriwave/estado/estado_alarmas.dart';
import 'package:pluriwave/modelos/alarma_musical.dart';
import 'package:pluriwave/servicios/servicio_alarmas.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../helpers/fakes_alarmas.dart';
/// Reported twice on-device: "Posponer" on the pre-notice notification left
/// the alarm snoozed 1400+ minutes — a whole day — instead of the configured
/// few minutes.
///
/// The first fix (7054a4c) guarded the NATIVE anchor, and it was not enough,
/// because Dart runs AFTERWARDS on this path: the receiver's `postponeNext`
/// fires, then `startActivity`, then `app.dart` dispatches here, and this
/// method persists and reschedules. Whatever Dart computes is the value that
/// survives. It was the last snooze path with no occurrence guard at all.
///
/// It also cannot simply reuse `_ocurrenciaSonando`: the pre-notice's
/// occurrence legitimately has NOT arrived yet (the reminder is armed 30 min
/// ahead), so the ringing-screen guard would reject a perfectly good anchor.
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() {
SharedPreferences.setMockInitialValues({});
});
AlarmaMusical diaria(String id) => AlarmaMusical(
id: id,
nombre: 'Mañana',
hora: 16,
minuto: 20,
tipoProgramacion: TipoProgramacionAlarma.diaria,
diasSemana: const [],
snoozeMinutos: 5,
);
({EstadoAlarmas estado, FakePuertoAlarmasAndroid android}) montar(
DateTime Function() reloj,
) {
final android = FakePuertoAlarmasAndroid();
final estado = EstadoAlarmas(
servicio: ServicioAlarmas(reloj: reloj),
android: android,
iniciarAutomaticamente: false,
);
addTearDown(estado.dispose);
addTearDown(android.dispose);
return (estado: estado, android: android);
}
test('una ocurrencia del DÍA SIGUIENTE se rechaza: pospone minutos, '
'no 24 horas', () async {
// The exact reported shape. The pre-notice for today's 16:20 is on
// screen at 16:16; the anchor handed in points at TOMORROW (either the
// native spec was already advanced, or app.dart fell back to a
// proximaEjecucion that had moved on).
var ahora = DateTime(2026, 8, 3, 16, 0);
final m = montar(() => ahora);
await m.estado.guardarAlarma(diaria('p1'));
ahora = DateTime(2026, 8, 3, 16, 16);
await m.estado.posponerProximaDesdePreaviso(
m.estado.alarmas.single,
5,
DateTime(2026, 8, 4, 16, 20), // <- tomorrow
);
final snooze = m.estado.alarmas.single.snoozeHasta!;
final minutos = snooze.difference(ahora).inMinutes;
expect(
minutos,
lessThan(60),
reason:
'la alarma quedó a $minutos min ($snooze). El reporte fue "más de '
'1400 minutos"; cualquier cosa por encima de una hora es el mismo bug',
);
expect(
m.estado.alarmas.single.snoozeOrigen,
isNot(DateTime(2026, 8, 4, 16, 20)),
reason:
'el ancla sin validar también se guarda como snoozeOrigen y como '
'ultimaEjecucionGestionada — envenenaría el estado que a9da855 y '
'0430059 existen para mantener limpio',
);
});
test('la ocurrencia REAL del preaviso se respeta aunque esté en el futuro: '
'ancla en la ocurrencia + N, no en ahora + N', () async {
// The whole reason this path needs its own guard instead of reusing
// _ocurrenciaSonando: 30 minutes ahead is legitimate here.
var ahora = DateTime(2026, 8, 3, 16, 0);
final m = montar(() => ahora);
await m.estado.guardarAlarma(diaria('p2'));
// Pre-notice fires at 15:50; the user taps at 15:52, 28 min before.
ahora = DateTime(2026, 8, 3, 15, 52);
await m.estado.posponerProximaDesdePreaviso(
m.estado.alarmas.single,
5,
DateTime(2026, 8, 3, 16, 20),
);
expect(m.estado.alarmas.single.snoozeHasta, DateTime(2026, 8, 3, 16, 25));
expect(m.estado.alarmas.single.snoozeOrigen, DateTime(2026, 8, 3, 16, 20));
});
test('un snooze ya envenenado en disco se cura al recalcular', () async {
// Devices that ran the buggy build carry snoozeHasta = tomorrow in
// SharedPreferences. Without healing it, the alarm keeps reporting
// tomorrow on every tick and the user sees no change after updating.
final ahora = DateTime(2026, 8, 3, 16, 0);
final servicio = ServicioAlarmas(reloj: () => ahora);
await servicio.guardarAlarma(
diaria('p4').copyWith(
snoozeHasta: DateTime(2026, 8, 4, 16, 25),
snoozeOrigen: DateTime(2026, 8, 4, 16, 20),
),
);
final alarma = (await servicio.recalcularTodas()).alarmas.single;
expect(alarma.snoozeHasta, isNull);
expect(alarma.proximaProgramable, DateTime(2026, 8, 3, 16, 20));
});
test('un snooze legítimo de 2 horas NO se toca', () async {
// posponerEjecucion clamps to 120 minutes, so the ceiling has to sit
// above that or the heal would eat real snoozes.
final ahora = DateTime(2026, 8, 3, 16, 0);
final servicio = ServicioAlarmas(reloj: () => ahora);
final hasta = DateTime(2026, 8, 3, 18, 0);
await servicio.guardarAlarma(
diaria('p5').copyWith(snoozeHasta: hasta, snoozeOrigen: ahora),
);
expect(
(await servicio.recalcularTodas()).alarmas.single.snoozeHasta,
hasta,
);
});
test('un ancla absurdamente lejana cae a la ocurrencia propia de la alarma, '
'no a un valor inventado', () async {
var ahora = DateTime(2026, 8, 3, 16, 0);
final m = montar(() => ahora);
await m.estado.guardarAlarma(diaria('p3'));
ahora = DateTime(2026, 8, 3, 16, 10);
await m.estado.posponerProximaDesdePreaviso(
m.estado.alarmas.single,
5,
DateTime(2027, 1, 1, 16, 20), // absurd
);
// proximaEjecucion (today 16:20) is inside the pre-notice window, so it
// is the right fallback and the snooze lands on 16:25.
expect(m.estado.alarmas.single.snoozeHasta, DateTime(2026, 8, 3, 16, 25));
});
}
+35 -37
View File
@@ -238,37 +238,10 @@ void main() {
});
group('ConstructorArbolAuto.raiz', () {
test('con incluirMusicaLocal: true devuelve exactamente 5 carpetas no '
'reproducibles con los ids esperados, terminando en Ecualizador', () {
test('con incluirMusicaLocal: true devuelve exactamente 4 carpetas no '
'reproducibles con los ids esperados', () {
final raiz = ConstructorArbolAuto().raiz(incluirMusicaLocal: true);
expect(raiz, hasLength(5));
final ids = raiz.map((item) => item.id).toSet();
expect(
ids,
equals({
ConstructorArbolAuto.idFavoritos,
ConstructorArbolAuto.idTodas,
ConstructorArbolAuto.idMisEmisoras,
ConstructorArbolAuto.idMusicaLocal,
ConstructorArbolAuto.idEcualizador,
}),
);
for (final item in raiz) {
expect(item.playable, isFalse);
expect(item.title, isNotEmpty);
}
// Decision `auto/ecualizador-diseno`: Ecualizador is always LAST,
// after Música Local when it is present.
expect(raiz[raiz.length - 2].id, ConstructorArbolAuto.idMusicaLocal);
expect(raiz.last.id, ConstructorArbolAuto.idEcualizador);
});
test('con incluirMusicaLocal: false devuelve exactamente 4 carpetas — '
'Música Local queda OCULTA, no vacía, y Ecualizador sigue presente y '
'al final', () {
final raiz = ConstructorArbolAuto().raiz(incluirMusicaLocal: false);
expect(raiz, hasLength(4));
final ids = raiz.map((item) => item.id).toSet();
expect(
@@ -277,25 +250,50 @@ void main() {
ConstructorArbolAuto.idFavoritos,
ConstructorArbolAuto.idTodas,
ConstructorArbolAuto.idMisEmisoras,
ConstructorArbolAuto.idEcualizador,
ConstructorArbolAuto.idMusicaLocal,
}),
);
for (final item in raiz) {
expect(item.playable, isFalse);
expect(item.title, isNotEmpty);
}
expect(raiz.last.id, ConstructorArbolAuto.idMusicaLocal);
});
test('con incluirMusicaLocal: false devuelve exactamente 3 carpetas — '
'Música Local queda OCULTA, no vacía', () {
final raiz = ConstructorArbolAuto().raiz(incluirMusicaLocal: false);
expect(raiz, hasLength(3));
final ids = raiz.map((item) => item.id).toSet();
expect(
ids,
equals({
ConstructorArbolAuto.idFavoritos,
ConstructorArbolAuto.idTodas,
ConstructorArbolAuto.idMisEmisoras,
}),
);
expect(ids, isNot(contains(ConstructorArbolAuto.idMusicaLocal)));
expect(raiz.last.id, ConstructorArbolAuto.idEcualizador);
});
test('la raíz ofrece la carpeta de ecualizador -- decisión '
'`auto/ecualizador-diseno` SUPERSEDE la regla anterior de "sin '
'carpeta de ecualizador" (commit `2403da3`); este test REEMPLAZA '
'deliberadamente al test homónimo previo que afirmaba lo contrario, '
'no es una regresión', () {
test('la raíz NO ofrece la carpeta de ecualizador -- decisión owner '
'tras conducir con ella: on/off en pantalla es el único control de '
'ecualizador que pertenece en el coche, la selección de preset se '
'queda en el móvil. Esto REEMPLAZA deliberadamente al test homónimo '
'previo que afirmaba lo contrario (que a su vez había reemplazado la '
'ausencia original en `2403da3`) -- no es una regresión, es la '
'segunda vuelta de la misma decisión con evidencia real de uso', () {
final ids =
ConstructorArbolAuto()
.raiz(incluirMusicaLocal: true)
.map((item) => item.id)
.toList();
expect(ids, contains(ConstructorArbolAuto.idEcualizador));
expect(ids, isNot(contains(ConstructorArbolAuto.idEcualizador)));
// The id constant itself is NOT deleted: getChildren still answers it
// transitionally for a head unit with a stale cached browse tree. See
// servicio_audio.dart's getChildren for that courtesy branch.
expect(ConstructorArbolAuto.idEcualizador, 'ecualizador');
});
});