From 99079ba877cf488f3557b5ddde238e1593bc887e Mon Sep 17 00:00:00 2001 From: Your Name Date: Thu, 24 Sep 2026 18:22:27 +0200 Subject: [PATCH] After correcting the chat issue6 --- .../prediction/bloc/prediction_bloc.dart | 109 +++++++++------ .../utils/server_adjusted_countdown.dart | 19 +++ .../test/server_adjusted_countdown_test.dart | 127 ++++++++++++++++++ 3 files changed, 217 insertions(+), 38 deletions(-) create mode 100644 prediqo_mobile/test/server_adjusted_countdown_test.dart diff --git a/prediqo_mobile/lib/features/prediction/bloc/prediction_bloc.dart b/prediqo_mobile/lib/features/prediction/bloc/prediction_bloc.dart index 0465e990..c3b1b831 100644 --- a/prediqo_mobile/lib/features/prediction/bloc/prediction_bloc.dart +++ b/prediqo_mobile/lib/features/prediction/bloc/prediction_bloc.dart @@ -356,12 +356,32 @@ class PredictionBloc extends Bloc { final gameState = await stateFuture; _ensureRealtime(gameState.selectedIntervalMinutes); + // Apply the HTTP snapshot once, through stabilize. Later progressive + // emits must only patch candles / history / balances — re-applying this + // captured snapshot after WS has opened the next cycle is what caused + // 55s → 0s → 52s → 0s after the first-load optimization. + final applied = _stabilizeGameStateRound( + previous: state.gameState, + incoming: gameState, + ); if (state.gameState == null) { emit(_readyFromGameState( - gameState, + applied, candles: state.candles, isLoadingCandles: state.candles.isEmpty, )); + } else { + emit(state.copyWith( + status: PredictionStatus.ready, + gameState: applied, + selectedIntervalMinutes: applied.selectedIntervalMinutes, + wsConnected: _socket.isConnected, + realtimeStatus: _socket.isConnected + ? PredictionRealtimeStatus.live + : (_socket.isEnabled + ? PredictionRealtimeStatus.syncing + : PredictionRealtimeStatus.polling), + )); } final pageSize = gameState.interval.chartCandleLimit.clamp(20, 200); @@ -371,30 +391,32 @@ class PredictionBloc extends Bloc { ); final candlesPage = await candlesFuture; - emit(_readyFromGameState( - gameState, + emit(state.copyWith( + status: PredictionStatus.ready, candles: candlesPage.items, - hasMoreOlder: candlesPage.hasMore, - isLoadingCandles: false, + hasMoreOlderCandles: candlesPage.hasMore, + isLoadingOlderCandles: false, )); final history = await historyFuture; final labels = await balancesFuture; + final liveMulti = state.gameState?.userMultiBet; final historyItems = history == null ? state.history - : (gameState.userMultiBet != null - ? _historyWithMultiProgress(history.items, gameState.userMultiBet!) + : (liveMulti != null + ? _historyWithMultiProgress(history.items, liveMulti) : history.items); - emit(_readyFromGameState( - gameState, - candles: candlesPage.items, - hasMoreOlder: candlesPage.hasMore, - isLoadingCandles: false, + emit(state.copyWith( history: historyItems, historyPage: history?.page, historyTotalPages: history?.totalPages, - labels: labels, + mainBalanceLabel: labels?.mainLabel, + bonusBalanceLabel: labels?.bonusLabel, + testBalanceLabel: labels?.testLabel, + mainAvailable: labels?.main, + bonusAvailable: labels?.bonus, + testAvailable: labels?.test, )); _lastFullStateSyncMs = DateTime.now().millisecondsSinceEpoch; @@ -444,7 +466,10 @@ class PredictionBloc extends Bloc { : state.selectedStake; return state.copyWith( status: PredictionStatus.ready, - gameState: gameState, + gameState: _stabilizeGameStateRound( + previous: state.gameState, + incoming: gameState, + ), candles: candles, hasMoreOlderCandles: hasMoreOlder, isLoadingOlderCandles: isLoadingCandles, @@ -796,34 +821,38 @@ class PredictionBloc extends Bloc { } final round = msg['round']; if (round is Map) { - final parsed = mergeRound(gs.round, RoundModel.fromJson(round)); - final prevStatus = gs.round?.status; - final prevRoundId = gs.round?.id; - // Timer-only WS ticks must not remount countdown / overwrite UI state. - if (!roundUiChanged(gs.round, parsed)) { - break; - } - final nextBet = _userBetForRound(gs.userBet, parsed); - emit(state.copyWith( - gameState: gs.copyWith( - round: parsed, - userBet: nextBet, - clearUserBet: nextBet == null, - ), - )); - // New open window: clear stale lock + sync server state. - final openedBetting = parsed.status == 'betting' && prevStatus != 'betting'; - final roundChanged = prevRoundId != null && prevRoundId != parsed.id; - if (openedBetting || (roundChanged && parsed.status == 'betting')) { - add(const PredictionRefreshTick(forceGameState: true)); - if (gs.autoSettings?.enabled == true) { - add(const PredictionHistoryPageRequested(1)); + final incomingRound = RoundModel.fromJson(round); + if (!isIncomingRoundStale(gs.round, incomingRound)) { + final parsed = mergeRound(gs.round, incomingRound); + final prevStatus = gs.round?.status; + final prevRoundId = gs.round?.id; + // Timer-only WS ticks must not remount countdown / overwrite UI state. + if (roundUiChanged(gs.round, parsed)) { + final nextBet = _userBetForRound(gs.userBet, parsed); + emit(state.copyWith( + gameState: gs.copyWith( + round: parsed, + userBet: nextBet, + clearUserBet: nextBet == null, + ), + )); + // New open window: clear stale lock + sync server state. + final openedBetting = parsed.status == 'betting' && prevStatus != 'betting'; + final roundChanged = prevRoundId != null && prevRoundId != parsed.id; + if (openedBetting || (roundChanged && parsed.status == 'betting')) { + add(const PredictionRefreshTick(forceGameState: true)); + if (gs.autoSettings?.enabled == true) { + add(const PredictionHistoryPageRequested(1)); + } + } } } } if (type == 'round.settled') { + // Candle + next window arrive via candle.append / round.updated. + // A full Load would re-apply a stale HTTP snapshot mid-countdown. add(const PredictionBalancesRefreshRequested()); - add(const PredictionLoadRequested()); + add(const PredictionHistoryPageRequested(1)); } break; case 'multi.updated': @@ -1097,7 +1126,8 @@ class PredictionBloc extends Bloc { return config.minStakeAmount; } - /// Keep countdown stable: merge absolute deadlines and ignore timer-only round ticks. + /// Keep countdown stable: reject older cycles, merge absolute deadlines, + /// and ignore timer-only round ticks. GameStateModel _stabilizeGameStateRound({ required GameStateModel? previous, required GameStateModel incoming, @@ -1105,6 +1135,9 @@ class PredictionBloc extends Bloc { }) { final incomingRound = incoming.round; if (incomingRound == null) return incoming; + if (isIncomingRoundStale(previous?.round, incomingRound)) { + return incoming.copyWith(round: previous!.round); + } final merged = mergeRound(previous?.round, incomingRound); if (!forceRound && previous?.round != null && diff --git a/prediqo_mobile/lib/features/prediction/utils/server_adjusted_countdown.dart b/prediqo_mobile/lib/features/prediction/utils/server_adjusted_countdown.dart index 00023389..c505b902 100644 --- a/prediqo_mobile/lib/features/prediction/utils/server_adjusted_countdown.dart +++ b/prediqo_mobile/lib/features/prediction/utils/server_adjusted_countdown.dart @@ -114,3 +114,22 @@ RoundModel mergeRound(RoundModel? prev, RoundModel incoming) { incoming.bettingStartMs ?? (sameRound ? prev.bettingStartMs : null), ); } + +/// True when [incoming] is an older cycle than the one already on screen. +/// +/// Progressive HTTP emits and late `round.settled` payloads can arrive *after* +/// WS has already opened the next betting window. Applying them produces the +/// `55→0→52→0` flap (new countdown clobbered by a settled/locked snapshot). +bool isIncomingRoundStale(RoundModel? current, RoundModel incoming) { + if (current == null || current.id == incoming.id) return false; + + final currentOpen = current.candleOpenMs; + final incomingOpen = incoming.candleOpenMs; + if (currentOpen != null && incomingOpen != null) { + return incomingOpen < currentOpen; + } + + // No comparable candle time: never replace a live betting window with a + // late non-betting snapshot of a previous cycle. + return current.status == 'betting' && incoming.status != 'betting'; +} diff --git a/prediqo_mobile/test/server_adjusted_countdown_test.dart b/prediqo_mobile/test/server_adjusted_countdown_test.dart new file mode 100644 index 00000000..a28a4104 --- /dev/null +++ b/prediqo_mobile/test/server_adjusted_countdown_test.dart @@ -0,0 +1,127 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:prediqo_mobile/data/models/prediction_models.dart'; +import 'package:prediqo_mobile/features/prediction/utils/server_adjusted_countdown.dart'; + +RoundModel _round({ + required String id, + required String status, + int secondsToBettingEnd = 0, + int secondsToBettingStart = 0, + int secondsToClose = 0, + int? serverNowMs, + int? candleOpenMs, +}) { + return RoundModel( + id: id, + status: status, + secondsToBettingEnd: secondsToBettingEnd, + secondsToBettingStart: secondsToBettingStart, + secondsToClose: secondsToClose, + serverNowMs: serverNowMs, + candleOpenMs: candleOpenMs, + bettingEndMs: candleOpenMs, + ); +} + +void main() { + group('isIncomingRoundStale', () { + test('keeps the live betting window over a late settled HTTP snapshot', () { + final live = _round( + id: 'next', + status: 'betting', + secondsToBettingEnd: 55, + serverNowMs: 1_000_000, + candleOpenMs: 1_055_000, + ); + final lateHttp = _round( + id: 'prev', + status: 'settled', + serverNowMs: 990_000, + candleOpenMs: 995_000, + ); + expect(isIncomingRoundStale(live, lateHttp), isTrue); + }); + + test('accepts the next cycle when candleOpenMs is newer', () { + final current = _round( + id: 'prev', + status: 'settled', + candleOpenMs: 995_000, + ); + final next = _round( + id: 'next', + status: 'betting', + secondsToBettingEnd: 55, + candleOpenMs: 1_055_000, + ); + expect(isIncomingRoundStale(current, next), isFalse); + }); + + test('same round id is never stale', () { + final current = _round( + id: 'same', + status: 'betting', + secondsToBettingEnd: 40, + candleOpenMs: 1_055_000, + ); + final tick = _round( + id: 'same', + status: 'betting', + secondsToBettingEnd: 39, + candleOpenMs: 1_055_000, + ); + expect(isIncomingRoundStale(current, tick), isFalse); + }); + + test('rejects a non-betting snapshot when live betting has no candle time', () { + final live = _round(id: 'next', status: 'betting', secondsToBettingEnd: 52); + final late = _round(id: 'prev', status: 'settled'); + expect(isIncomingRoundStale(live, late), isTrue); + }); + }); + + group('mergeRound', () { + test('keeps previous timing when WS omits serverNowMs on the same round', () { + final prev = _round( + id: 'r1', + status: 'betting', + secondsToBettingEnd: 55, + serverNowMs: 1_000_000, + candleOpenMs: 1_055_000, + ); + final incoming = _round( + id: 'r1', + status: 'betting', + secondsToBettingEnd: 40, + candleOpenMs: 1_055_000, + ); + final merged = mergeRound(prev, incoming); + expect(merged.secondsToBettingEnd, 55); + expect(merged.serverNowMs, 1_000_000); + }); + }); + + group('serverAdjustedCountdown', () { + test('counts down locally from one frozen snapshot', () { + final snap = _round( + id: 'r1', + status: 'betting', + secondsToBettingEnd: 55, + serverNowMs: 1_000_000, + candleOpenMs: 1_055_000, + ); + expect( + serverAdjustedCountdown(snap, clientNowMs: 1_000_000).secondsToBettingEnd, + 55, + ); + expect( + serverAdjustedCountdown(snap, clientNowMs: 1_003_000).secondsToBettingEnd, + 52, + ); + expect( + serverAdjustedCountdown(snap, clientNowMs: 1_055_000).secondsToBettingEnd, + 0, + ); + }); + }); +}