After correcting the chat issue6

This commit is contained in:
Your Name 2026-09-24 18:22:27 +02:00
parent cec19ac03d
commit 99079ba877
3 changed files with 217 additions and 38 deletions

View File

@ -356,12 +356,32 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
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<PredictionEvent, PredictionState> {
);
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<PredictionEvent, PredictionState> {
: 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<PredictionEvent, PredictionState> {
}
final round = msg['round'];
if (round is Map<String, dynamic>) {
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<PredictionEvent, PredictionState> {
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<PredictionEvent, PredictionState> {
}) {
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 &&

View File

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

View File

@ -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,
);
});
});
}