diff --git a/backend/internal/account/account.go b/backend/internal/account/account.go index 515294d..8fee67a 100644 --- a/backend/internal/account/account.go +++ b/backend/internal/account/account.go @@ -112,17 +112,19 @@ func (s *Store) ProvisionByIdentity(ctx context.Context, kind, externalID string } // ProvisionRobot provisions (or finds) the durable account backing a robot pool -// member: a KindRobot identity carrying displayName, with chat and friend requests -// blocked so the robot never engages socially. Robot names are system-generated, not -// player-edited, so they bypass the editable display-name validation and may carry -// forms the editor rejects (an abbreviated surname like "Peter J."). It is idempotent: -// repeated calls converge the display name and both block flags. +// member: a KindRobot identity carrying displayName, with chat blocked but friend +// requests NOT blocked — a request to a robot is accepted as pending and, since the +// robot never responds, simply expires (friendRequestTTL), exactly mirroring a human +// who ignores the request. Robot names are system-generated, not player-edited, so they +// bypass the editable display-name validation and may carry forms the editor rejects (an +// abbreviated surname like "Peter J."). It is idempotent: repeated calls converge the +// display name and both block flags. func (s *Store) ProvisionRobot(ctx context.Context, externalID, displayName string) (Account, error) { acc, err := s.provision(ctx, KindRobot, externalID, provisionSeed{displayName: displayName}) if err != nil { return Account{}, err } - if acc.DisplayName == displayName && acc.BlockChat && acc.BlockFriendRequests { + if acc.DisplayName == displayName && acc.BlockChat && !acc.BlockFriendRequests { return acc, nil } stmt := table.Accounts.UPDATE( @@ -130,7 +132,7 @@ func (s *Store) ProvisionRobot(ctx context.Context, externalID, displayName stri table.Accounts.BlockFriendRequests, table.Accounts.UpdatedAt, ).SET( postgres.String(displayName), postgres.Bool(true), - postgres.Bool(true), postgres.TimestampzT(time.Now().UTC()), + postgres.Bool(false), postgres.TimestampzT(time.Now().UTC()), ).WHERE(table.Accounts.AccountID.EQ(postgres.UUID(acc.ID))). RETURNING(table.Accounts.AllColumns) diff --git a/backend/internal/engine/game.go b/backend/internal/engine/game.go index 4b55e5c..ecbe5d0 100644 --- a/backend/internal/engine/game.go +++ b/backend/internal/engine/game.go @@ -248,17 +248,29 @@ func (g *Game) Exchange(tiles []byte) (MoveRecord, error) { // winning regardless of score. A missed-turn timeout reuses Resign in the game // domain, so it inherits this win/loss. func (g *Game) Resign() (MoveRecord, error) { + return g.ResignSeat(g.toMove) +} + +// ResignSeat resigns a specific seat regardless of whose turn it is, so a player +// may forfeit on the opponent's turn. The resigning seat always loses (winner() +// skips resigned seats). The turn cursor only advances when the seat that resigned +// was the one to move; resigning an off-turn seat leaves the current player's turn +// intact. It returns ErrGameOver on a finished game or for an out-of-range or +// already-resigned seat. +func (g *Game) ResignSeat(seat int) (MoveRecord, error) { if g.over { return MoveRecord{}, ErrGameOver } - player := g.toMove - g.resigned[player] = true - g.disposeHand(player) - rec := MoveRecord{Player: player, Action: ActionResign, Total: g.scores[player]} + if seat < 0 || seat >= len(g.hands) || g.resigned[seat] { + return MoveRecord{}, ErrGameOver + } + g.resigned[seat] = true + g.disposeHand(seat) + rec := MoveRecord{Player: seat, Action: ActionResign, Total: g.scores[seat]} g.log = append(g.log, rec) if g.activeCount() <= 1 { g.finish(EndResign) - } else { + } else if seat == g.toMove { g.advance() } return rec, nil diff --git a/backend/internal/engine/resign_test.go b/backend/internal/engine/resign_test.go index 1df334a..8c08b44 100644 --- a/backend/internal/engine/resign_test.go +++ b/backend/internal/engine/resign_test.go @@ -69,6 +69,39 @@ func TestResignTrailingPlayerLoses(t *testing.T) { } } +// TestResignSeatOffTurn covers a forfeit on the opponent's turn: after player 0 +// moves it is player 1's turn, yet player 0 resigns its own seat — the resigner +// loses, the opponent wins, and the game ends. +func TestResignSeatOffTurn(t *testing.T) { + g := openingGame(t) + + hint, ok := g.HintView() + if !ok { + t.Fatal("opening game has no hint") + } + if _, err := g.SubmitPlay(hint.Dir, hint.Tiles); err != nil { // player 0 moves + t.Fatalf("player 0 play: %v", err) + } + if g.ToMove() != 1 { + t.Fatalf("after player 0's move, toMove = %d, want 1", g.ToMove()) + } + + // Player 0 resigns although it is player 1's turn. + rec, err := g.ResignSeat(0) + if err != nil { + t.Fatalf("player 0 off-turn resign: %v", err) + } + if rec.Player != 0 || rec.Action != ActionResign { + t.Errorf("resign record = seat %d action %v, want seat 0 resign", rec.Player, rec.Action) + } + if !g.Over() || g.Reason() != EndResign { + t.Fatalf("game over=%v reason=%v, want over with resign", g.Over(), g.Reason()) + } + if res := g.Result(); res.Winner != 1 { + t.Errorf("winner = %d, want 1 (the non-resigner)", res.Winner) + } +} + // TestResignOnFinishedGame rejects a second transition. func TestResignOnFinishedGame(t *testing.T) { g := newEnglishGame(t, 1) diff --git a/backend/internal/game/service.go b/backend/internal/game/service.go index 780bf8e..e109929 100644 --- a/backend/internal/game/service.go +++ b/backend/internal/game/service.go @@ -171,11 +171,46 @@ func (svc *Service) Exchange(ctx context.Context, gameID, accountID uuid.UUID, t } // Resign ends the game on the player's turn; the remaining player wins. +// Resign forfeits the game for the acting account. Unlike a play/exchange/pass it is +// allowed on the opponent's turn (a resignation is not a turn-scoped move), so it does +// not go through transition's turn check: it resigns the actor's own seat, whoever is to +// move. The resigning seat always loses (docs/ARCHITECTURE.md §7). func (svc *Service) Resign(ctx context.Context, gameID, accountID uuid.UUID) (MoveResult, error) { - return svc.transition(ctx, gameID, accountID, func(g *engine.Game) (engine.MoveRecord, []string, error) { - rec, err := g.Resign() - return rec, nil, err - }) + pre, err := svc.store.GetGame(ctx, gameID) + if err != nil { + return MoveResult{}, err + } + seat, ok := pre.seatOf(accountID) + if !ok { + return MoveResult{}, ErrNotAPlayer + } + if pre.Status != StatusActive { + return MoveResult{}, ErrFinished + } + + unlock := svc.locks.lock(gameID) + defer unlock() + + g, err := svc.liveGame(ctx, pre) + if err != nil { + return MoveResult{}, err + } + if g.Over() { + return MoveResult{}, ErrFinished + } + + rackBefore := g.Hand(seat) + rec, err := g.ResignSeat(seat) + if err != nil { + return MoveResult{}, err + } + post, err := svc.commit(ctx, gameID, g, rec, rec.Action.String(), rackBefore, nil, pre.Seats) + if err != nil { + return MoveResult{}, err + } + // A resignation carries no think time (it can happen on the opponent's turn), so it + // is intentionally excluded from the move-duration metric. + return MoveResult{Move: rec, Game: post}, nil } // GameVariant returns just a game's variant. The edge layer uses it to map wire alphabet diff --git a/backend/internal/inttest/game_test.go b/backend/internal/inttest/game_test.go index 0ce8914..9706f13 100644 --- a/backend/internal/inttest/game_test.go +++ b/backend/internal/inttest/game_test.go @@ -299,6 +299,42 @@ func TestResignWinnerAndStats(t *testing.T) { } } +// TestResignOnOpponentTurn checks the Stage 17 fix: a player can forfeit on the +// opponent's turn. Seat 0 plays (so it is seat 1's turn), then seat 0 resigns its own +// seat while it is not its turn — no ErrNotYourTurn, the game ends, and seat 0 loses +// despite leading on score. +func TestResignOnOpponentTurn(t *testing.T) { + ctx := context.Background() + svc := newGameService() + seats := []uuid.UUID{provisionAccount(t), provisionAccount(t)} + seed := openingSeed(t) + g, err := svc.Create(ctx, game.CreateParams{ + Variant: engine.VariantEnglish, Seats: seats, TurnTimeout: 24 * time.Hour, Seed: seed, + }) + if err != nil { + t.Fatalf("create: %v", err) + } + + hint, ok := newMirror(t, seed, 2).HintView() + if !ok { + t.Fatal("no opening move") + } + if _, err := svc.SubmitPlay(ctx, g.ID, seats[0], hint.Dir, hint.Tiles); err != nil { // p0 scores, now p1's turn + t.Fatalf("p0 play: %v", err) + } + + res, err := svc.Resign(ctx, g.ID, seats[0]) // p0 resigns OFF turn + if err != nil { + t.Fatalf("off-turn resign = %v, want nil", err) + } + if res.Game.Status != game.StatusFinished || res.Game.EndReason != "resign" { + t.Fatalf("after off-turn resign: %+v", res.Game) + } + if res.Game.Seats[0].IsWinner || !res.Game.Seats[1].IsWinner { + t.Errorf("winner flags wrong (resigner must lose): %+v", res.Game.Seats) + } +} + // TestTimeoutSweep auto-resigns an overdue game and records it as a timeout. func TestTimeoutSweep(t *testing.T) { ctx := context.Background() diff --git a/backend/internal/inttest/social_test.go b/backend/internal/inttest/social_test.go index 5de9c3d..0317996 100644 --- a/backend/internal/inttest/social_test.go +++ b/backend/internal/inttest/social_test.go @@ -40,6 +40,38 @@ func newGameWithSeats(t *testing.T, n int) (uuid.UUID, []uuid.UUID) { return g.ID, seats } +// TestFriendRequestToRobotStaysPending checks a friend request to a robot is accepted as +// pending rather than blocked: robots no longer block friend requests, so the request +// just sits unanswered and later expires — mirroring a human who ignores it (Stage 17). +func TestFriendRequestToRobotStaysPending(t *testing.T) { + ctx := context.Background() + svc := newSocialService() + accs := account.NewStore(testDB) + + human := provisionAccount(t) + robot, err := accs.ProvisionRobot(ctx, "robot-friend-"+uuid.NewString(), "Robbie") + if err != nil { + t.Fatalf("provision robot: %v", err) + } + if robot.BlockFriendRequests { + t.Fatal("robot must not block friend requests") + } + // A request is only allowed between players who share a game. + if _, err := newGameService().Create(ctx, game.CreateParams{ + Variant: engine.VariantEnglish, Seats: []uuid.UUID{human, robot.ID}, + TurnTimeout: 24 * time.Hour, Seed: openingSeed(t), + }); err != nil { + t.Fatalf("create game: %v", err) + } + + if err := svc.SendFriendRequest(ctx, human, robot.ID); err != nil { + t.Fatalf("request to robot = %v, want nil (accepted as pending)", err) + } + if got, _ := svc.ListIncomingRequests(ctx, robot.ID); len(got) != 1 || got[0] != human { + t.Fatalf("robot incoming = %v, want [human]", got) + } +} + func TestFriendRequestLifecycle(t *testing.T) { ctx := context.Background() svc := newSocialService() diff --git a/backend/internal/lobby/matchmaker.go b/backend/internal/lobby/matchmaker.go index 48da0dd..2342291 100644 --- a/backend/internal/lobby/matchmaker.go +++ b/backend/internal/lobby/matchmaker.go @@ -142,11 +142,14 @@ func (m *Matchmaker) Poll(_ context.Context, accountID uuid.UUID) (EnqueueResult return EnqueueResult{}, nil } -// Cancel removes accountID from whatever pool it waits in, reporting whether it -// was queued. +// Cancel removes accountID from whatever pool it waits in and drops any pending +// matched result, reporting whether it was queued. Clearing the result closes the +// race where the reaper substituted a robot just before the player cancelled: the +// stale game must not later surface through Poll as a game the player did not want. func (m *Matchmaker) Cancel(_ context.Context, accountID uuid.UUID) bool { m.mu.Lock() defer m.mu.Unlock() + delete(m.results, accountID) variant, ok := m.queued[accountID] if !ok { return false diff --git a/backend/internal/lobby/matchmaker_test.go b/backend/internal/lobby/matchmaker_test.go index e2d145c..4092e57 100644 --- a/backend/internal/lobby/matchmaker_test.go +++ b/backend/internal/lobby/matchmaker_test.go @@ -240,6 +240,27 @@ func TestMatchmakerReaperSkipsCancelled(t *testing.T) { } } +// TestMatchmakerCancelClearsPendingResult covers the race where the reaper substitutes a +// robot just before the player cancels: Cancel must drop the pending result so the +// abandoned game never surfaces through Poll (Stage 17). +func TestMatchmakerCancelClearsPendingResult(t *testing.T) { + creator := &fakeCreator{} + mm := newTestMatchmaker(creator, uuid.New()) + base := time.Now() + mm.clock = func() time.Time { return base } + ctx := context.Background() + a := uuid.New() + + if _, err := mm.Enqueue(ctx, a, engine.VariantEnglish); err != nil { + t.Fatalf("enqueue: %v", err) + } + mm.Reap(ctx, base.Add(testWaitDelay+time.Second)) // substitution stores a pending result + mm.Cancel(ctx, a) // ... then the player cancels + if got, _ := mm.Poll(ctx, a); got.Matched { + t.Error("cancel must drop the pending substituted game; Poll still matched") + } +} + func TestMatchmakerReaperDefersWithoutRobot(t *testing.T) { creator := &fakeCreator{} mm := NewMatchmaker(creator, &fakeRobots{err: errors.New("empty pool")}, testWaitDelay, zap.NewNop()) diff --git a/backend/internal/server/dto_test.go b/backend/internal/server/dto_test.go index 517c8fc..619a3dc 100644 --- a/backend/internal/server/dto_test.go +++ b/backend/internal/server/dto_test.go @@ -47,6 +47,7 @@ func TestStatusForError(t *testing.T) { "not a player": {game.ErrNotAPlayer, http.StatusForbidden, "not_a_player"}, "not your turn": {game.ErrNotYourTurn, http.StatusConflict, "not_your_turn"}, "nudge own turn": {social.ErrNudgeOnOwnTurn, http.StatusConflict, "nudge_own_turn"}, + "nudge too soon": {social.ErrNudgeTooSoon, http.StatusConflict, "nudge_too_soon"}, "illegal play": {engine.ErrIllegalPlay, http.StatusUnprocessableEntity, "illegal_play"}, "email taken": {account.ErrEmailTaken, http.StatusConflict, "email_taken"}, "code mismatch": {account.ErrCodeMismatch, http.StatusUnauthorized, "code_invalid"}, diff --git a/backend/internal/server/handlers.go b/backend/internal/server/handlers.go index f4e64f9..e4238f3 100644 --- a/backend/internal/server/handlers.go +++ b/backend/internal/server/handlers.go @@ -69,6 +69,7 @@ func (s *Server) registerRoutes() { } if s.matchmaker != nil { u.POST("/lobby/enqueue", s.handleEnqueue) + u.POST("/lobby/cancel", s.handleCancel) u.GET("/lobby/poll", s.handlePoll) } if s.invitations != nil { @@ -200,9 +201,12 @@ func statusForError(err error) (int, string) { case errors.Is(err, session.ErrNotFound): return http.StatusUnauthorized, "session_invalid" case errors.Is(err, social.ErrChatBlocked), errors.Is(err, social.ErrMessageTooLong), - errors.Is(err, social.ErrEmptyMessage), errors.Is(err, social.ErrForbiddenContent), - errors.Is(err, social.ErrNudgeTooSoon): + errors.Is(err, social.ErrEmptyMessage), errors.Is(err, social.ErrForbiddenContent): return http.StatusUnprocessableEntity, "chat_rejected" + case errors.Is(err, social.ErrNudgeTooSoon): + // A too-frequent nudge is a distinct, non-content rejection — the UI must say + // "don't rush the player so often", not the chat content-rejection message. + return http.StatusConflict, "nudge_too_soon" case errors.Is(err, social.ErrSelfRelation): return http.StatusBadRequest, "self_relation" case errors.Is(err, social.ErrRequestExists): diff --git a/backend/internal/server/handlers_user.go b/backend/internal/server/handlers_user.go index 7e181fc..180335a 100644 --- a/backend/internal/server/handlers_user.go +++ b/backend/internal/server/handlers_user.go @@ -153,6 +153,20 @@ func (s *Server) handleEnqueue(c *gin.Context) { c.JSON(http.StatusOK, dto) } +// handleCancel removes the caller from the auto-match pool (and drops any pending +// matched result), so a cancelled quick-match neither blocks a re-queue nor later +// surfaces a robot-substituted game the player abandoned. It is idempotent: cancelling +// when not queued is a no-op success. +func (s *Server) handleCancel(c *gin.Context) { + uid, ok := userID(c) + if !ok { + abortBadRequest(c, "missing identity") + return + } + s.matchmaker.Cancel(c.Request.Context(), uid) + c.Status(http.StatusNoContent) +} + // handlePoll reports whether the caller has been paired since queueing. func (s *Server) handlePoll(c *gin.Context) { uid, ok := userID(c) diff --git a/gateway/internal/backendclient/api.go b/gateway/internal/backendclient/api.go index 5eb17e1..4320517 100644 --- a/gateway/internal/backendclient/api.go +++ b/gateway/internal/backendclient/api.go @@ -255,6 +255,11 @@ func (c *Client) Poll(ctx context.Context, userID string) (MatchResp, error) { return out, err } +// Cancel removes the caller from the auto-match pool (idempotent; 204 No Content). +func (c *Client) Cancel(ctx context.Context, userID string) error { + return c.do(ctx, http.MethodPost, "/api/v1/user/lobby/cancel", userID, "", nil, nil) +} + // ChatPost stores a chat message, forwarding the client IP for moderation. func (c *Client) ChatPost(ctx context.Context, userID, gameID, body, clientIP string) (ChatResp, error) { var out ChatResp diff --git a/gateway/internal/transcode/transcode.go b/gateway/internal/transcode/transcode.go index 6cf0ca4..60a77f2 100644 --- a/gateway/internal/transcode/transcode.go +++ b/gateway/internal/transcode/transcode.go @@ -24,6 +24,7 @@ const ( MsgGameSubmitPlay = "game.submit_play" MsgGameState = "game.state" MsgLobbyEnqueue = "lobby.enqueue" + MsgLobbyCancel = "lobby.cancel" MsgLobbyPoll = "lobby.poll" MsgChatPost = "chat.post" MsgGamesList = "games.list" @@ -93,6 +94,7 @@ func NewRegistry(backend *backendclient.Client, tg TelegramValidator, defaultLan r.ops[MsgGameSubmitPlay] = Op{Handler: submitPlayHandler(backend), Auth: true} r.ops[MsgGameState] = Op{Handler: gameStateHandler(backend), Auth: true} r.ops[MsgLobbyEnqueue] = Op{Handler: enqueueHandler(backend), Auth: true} + r.ops[MsgLobbyCancel] = Op{Handler: cancelHandler(backend), Auth: true} r.ops[MsgLobbyPoll] = Op{Handler: pollHandler(backend), Auth: true} r.ops[MsgChatPost] = Op{Handler: chatPostHandler(backend), Auth: true} r.ops[MsgGamesList] = Op{Handler: gamesListHandler(backend), Auth: true} @@ -233,6 +235,17 @@ func pollHandler(backend *backendclient.Client) Handler { } } +// cancelHandler removes the caller from the auto-match pool. It carries no result; +// it echoes an empty (unmatched) Match so the client has a well-formed payload. +func cancelHandler(backend *backendclient.Client) Handler { + return func(ctx context.Context, req Request) ([]byte, error) { + if err := backend.Cancel(ctx, req.UserID); err != nil { + return nil, err + } + return encodeMatch(backendclient.MatchResp{}), nil + } +} + func chatPostHandler(backend *backendclient.Client) Handler { return func(ctx context.Context, req Request) ([]byte, error) { in := fb.GetRootAsChatPostRequest(req.Payload, 0) diff --git a/ui/src/game/Chat.svelte b/ui/src/game/Chat.svelte index 0afbffe..7d12318 100644 --- a/ui/src/game/Chat.svelte +++ b/ui/src/game/Chat.svelte @@ -51,7 +51,7 @@ onkeydown={(e) => e.key === 'Enter' && send()} /> - + diff --git a/ui/src/game/Game.svelte b/ui/src/game/Game.svelte index 6b438cc..2e21877 100644 --- a/ui/src/game/Game.svelte +++ b/ui/src/game/Game.svelte @@ -89,6 +89,20 @@ const isMyTurn = $derived(!!view && view.game.status === 'active' && view.game.toMove === view.seat); const gameOver = $derived(!!view && view.game.status !== 'active'); const bagEmpty = $derived((view?.bagLen ?? 0) === 0); + // Nudge cooldown (one per hour per game, mirrored from the backend): the control is + // disabled for an hour after the player's own last nudge. nudgeTick re-evaluates it on a + // timer while the chat is open, so it re-enables without waiting for a new message. + const nudgeCooldownSecs = 3600; + let nudgeTick = $state(0); + const nudgeOnCooldown = $derived.by(() => { + void nudgeTick; + const mine = app.session?.userId ?? ''; + const last = messages.reduce( + (mx, m) => (m.kind === 'nudge' && m.senderId === mine ? Math.max(mx, m.createdAtUnix) : mx), + 0, + ); + return last > 0 && Date.now() / 1000 - last < nudgeCooldownSecs; + }); async function load() { try { @@ -145,6 +159,13 @@ else if (e.kind === 'nudge' && e.gameId === id && panel === 'chat') void loadChat(); }); + // Tick the nudge cooldown while the chat is open so the control re-enables on time. + $effect(() => { + if (panel !== 'chat') return; + const h = setInterval(() => (nudgeTick += 1), 20000); + return () => clearInterval(h); + }); + function isCoarse(): boolean { return typeof matchMedia !== 'undefined' && matchMedia('(pointer: coarse)').matches; } @@ -708,7 +729,7 @@ {#if panel === 'chat'} (panel = 'none')}> - + {/if} diff --git a/ui/src/lib/client.ts b/ui/src/lib/client.ts index 49bfb9f..80f3543 100644 --- a/ui/src/lib/client.ts +++ b/ui/src/lib/client.ts @@ -65,6 +65,8 @@ export interface GatewayClient { // --- lobby --- lobbyEnqueue(variant: Variant): Promise; lobbyPoll(): Promise; + /** Leave the auto-match pool (idempotent); a cancelled quick-match must not stay queued. */ + lobbyCancel(): Promise; // --- game --- // Stage 13: the play loop exchanges alphabet indices, so submit/evaluate/exchange/ diff --git a/ui/src/lib/i18n/en.ts b/ui/src/lib/i18n/en.ts index dfa075f..63e67c5 100644 --- a/ui/src/lib/i18n/en.ts +++ b/ui/src/lib/i18n/en.ts @@ -94,7 +94,8 @@ export const en = { 'chat.placeholder': 'Quick message…', 'chat.send': 'Send', - 'chat.nudge': 'Nudge', + 'chat.nudge': 'Waiting for your move!', + 'chat.nudgeAction': 'Nudge', 'chat.empty': 'No messages yet.', 'chat.nudged': '{name} nudged you', @@ -155,6 +156,7 @@ export const en = { 'error.hint_unavailable': 'No hints available.', 'error.no_hint_available': 'No options with your letters.', 'error.chat_rejected': 'Message rejected (too long or contains contact info).', + 'error.nudge_too_soon': "Please don't rush your opponent so often.", 'error.game_finished': 'This game is finished.', 'error.not_a_player': 'You are not a player in this game.', 'error.already_queued': 'You are already in the queue.', diff --git a/ui/src/lib/i18n/ru.ts b/ui/src/lib/i18n/ru.ts index ba15548..319c606 100644 --- a/ui/src/lib/i18n/ru.ts +++ b/ui/src/lib/i18n/ru.ts @@ -95,7 +95,8 @@ export const ru: Record = { 'chat.placeholder': 'Короткое сообщение…', 'chat.send': 'Отправить', - 'chat.nudge': 'Поторопить', + 'chat.nudge': 'Жду вашего хода!', + 'chat.nudgeAction': 'Поторопить', 'chat.empty': 'Сообщений пока нет.', 'chat.nudged': '{name} торопит вас', @@ -156,6 +157,7 @@ export const ru: Record = { 'error.hint_unavailable': 'Подсказки недоступны.', 'error.no_hint_available': 'Нет вариантов с вашим набором.', 'error.chat_rejected': 'Сообщение отклонено (слишком длинное или содержит контакты).', + 'error.nudge_too_soon': 'Не стоит торопить соперника так часто.', 'error.game_finished': 'Эта игра уже завершена.', 'error.not_a_player': 'Вы не участник этой игры.', 'error.already_queued': 'Вы уже в очереди.', diff --git a/ui/src/lib/mock/client.ts b/ui/src/lib/mock/client.ts index ef4a1c7..9de0d4d 100644 --- a/ui/src/lib/mock/client.ts +++ b/ui/src/lib/mock/client.ts @@ -180,6 +180,11 @@ export class MockGateway implements GatewayClient { return { matched: false }; } + async lobbyCancel(): Promise { + // Dequeue: drop the pending substitution so a cancelled quick-match never arrives. + this.pendingMatch = null; + } + // --- game --- async gameState(gameId: string, _includeAlphabet: boolean): Promise { const g = this.game(gameId); diff --git a/ui/src/lib/result.test.ts b/ui/src/lib/result.test.ts index f131354..3a92bb0 100644 --- a/ui/src/lib/result.test.ts +++ b/ui/src/lib/result.test.ts @@ -48,6 +48,15 @@ describe('resultBadge', () => { }); }); + it('finished two-player: a 0-0 resignation is a defeat, not a score-tied win', () => { + // The opponent won by resignation (isWinner) although neither side scored — the lobby + // must read this as a loss, matching the game-detail screen (Stage 17 regression). + expect(resultBadge(game([seat(0, 'me', 0), seat(1, 'a', 0, true)]), 'me')).toEqual({ + key: 'result.defeat', + emoji: '🥈', + }); + }); + it('finished four-player: places by score', () => { const last = game([seat(0, 'me', 100), seat(1, 'a', 400, true), seat(2, 'b', 300), seat(3, 'c', 200)]); expect(resultBadge(last, 'me')).toEqual({ key: 'result.place4', emoji: '🏅' }); diff --git a/ui/src/lib/result.ts b/ui/src/lib/result.ts index 479db04..d177b94 100644 --- a/ui/src/lib/result.ts +++ b/ui/src/lib/result.ts @@ -21,9 +21,11 @@ export function resultBadge(game: GameView, myId: string): ResultBadge { if (me?.isWinner) return { key: 'result.victory', emoji: '🏆' }; if (!game.seats.some((s) => s.isWinner)) return { key: 'result.draw', emoji: '🏅' }; - // Someone else won — place the viewer by score (1 + number of higher scores). - const rank = 1 + game.seats.filter((s) => s.score > (me?.score ?? 0)).length; - if (rank <= 1) return { key: 'result.victory', emoji: '🏆' }; + // Someone else won and it is not me, so I did not win — even when scores are level (a + // win by resignation or timeout can leave the winner at or below my score). The winner + // takes rank 1; place me among the remaining seats by score, starting at rank 2. + const ahead = game.seats.filter((s) => !s.isWinner && s.accountId !== myId && s.score > (me?.score ?? 0)).length; + const rank = 2 + ahead; if (rank === 2) return game.players === 2 ? { key: 'result.defeat', emoji: '🥈' } : { key: 'result.place2', emoji: '🥈' }; if (rank === 3) return { key: 'result.place3', emoji: '🥉' }; return { key: 'result.place4', emoji: '🏅' }; diff --git a/ui/src/lib/transport.ts b/ui/src/lib/transport.ts index ae40b6d..23cec7a 100644 --- a/ui/src/lib/transport.ts +++ b/ui/src/lib/transport.ts @@ -80,6 +80,9 @@ export function createTransport(baseUrl: string): GatewayClient { async lobbyPoll() { return codec.decodeMatchResult(await exec('lobby.poll', codec.empty())); }, + async lobbyCancel() { + await exec('lobby.cancel', codec.empty()); + }, async gameState(id, includeAlphabet) { return codec.decodeStateView(await exec('game.state', codec.encodeStateRequest(id, includeAlphabet))); diff --git a/ui/src/screens/NewGame.svelte b/ui/src/screens/NewGame.svelte index 85ff550..0b64511 100644 --- a/ui/src/screens/NewGame.svelte +++ b/ui/src/screens/NewGame.svelte @@ -31,12 +31,22 @@ poll = null; } } + // cancelSearch leaves the auto-match pool on the backend too, so a cancelled quick-match + // is actually dequeued — otherwise the account stays queued (blocking a re-queue) and the + // reaper later substitutes a robot for a game the player abandoned (Stage 17 fix). + function cancelSearch() { + stop(); + searching = false; + void gateway.lobbyCancel().catch(() => {}); + navigate('/'); + } async function find(v: Variant) { searching = true; try { const r = await gateway.lobbyEnqueue(v); if (r.matched && r.game) { + searching = false; navigate(`/game/${r.game.id}`); return; } @@ -45,6 +55,7 @@ const p = await gateway.lobbyPoll(); if (p.matched && p.game) { stop(); + searching = false; navigate(`/game/${p.game.id}`); } } catch (e) { @@ -103,7 +114,11 @@ } } - onDestroy(stop); + onDestroy(() => { + stop(); + // Abandoned mid-search (navigated away without Cancel): dequeue so we don't linger. + if (searching) void gateway.lobbyCancel().catch(() => {}); + }); @@ -112,7 +127,7 @@

{t('new.searching')}

- +
{:else} {#if !guest}