From 25381f70a363663af94360a6403bf2096f4cba0f Mon Sep 17 00:00:00 2001 From: Ilia Denisov Date: Tue, 14 Jul 2026 08:27:38 +0200 Subject: [PATCH 1/7] fix(net): detect a silently-dead live stream via a heartbeat watchdog MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An idle live stream whose connection dies without an error (airplane mode cutting the radio) left the net-state machine stuck "online": the streaming fetch neither errored nor delivered, no unary call was made, and the OS `navigator` offline hint is unreliable in the Telegram/VK WebViews — so the "Connecting…"/offline state only surfaced on the next foreground resync, not while idle. The gateway already pushes a keep-alive `heartbeat` every 10s, so add a client-side watchdog (streamwatchdog.ts) that resets on every delivered event and, after ~25s of silence, treats the stream as dropped (reportOffline + reconnect). It is background-aware (paused while suspended) so a throttled foreground return does not false-trip. The mock client mirrors the heartbeat so an idle e2e session stays online. --- docs/ARCHITECTURE.md | 6 ++- ui/src/lib/app.svelte.ts | 29 +++++++++++ ui/src/lib/mock/client.ts | 9 +++- ui/src/lib/streamwatchdog.test.ts | 82 +++++++++++++++++++++++++++++++ ui/src/lib/streamwatchdog.ts | 63 ++++++++++++++++++++++++ 5 files changed, 186 insertions(+), 3 deletions(-) create mode 100644 ui/src/lib/streamwatchdog.test.ts create mode 100644 ui/src/lib/streamwatchdog.ts diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 3e4d037..23c8f9c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -107,8 +107,10 @@ dropped). Horizontal scaling is explicit future work. the header **"Connecting…"** spinner, chrome stays online); `offlineNoNetwork` (sustained loss — blue chrome, a local-only lobby, the transport **kill switch**); and `offlineVersionLocked` (the gateway is reachable but the build is below the hard minimum — the *update* notice, the client-version gate below). **Offline is - implicit** — detected from failed calls, a reachability probe and the OS hint (`navigator` / - `@capacitor/network`), **never a user toggle** — with **hysteresis** so a brief blip lives entirely in + implicit** — detected from failed calls, a reachability probe, a **live-stream heartbeat watchdog** + (a silence past ~25 s of the gateway's 10 s keep-alive `heartbeat` means a silently-dead stream — e.g. + the radio was cut with no stream error; `ui/src/lib/streamwatchdog.ts`, background-aware) and the OS hint + (`navigator` / `@capacitor/network`), **never a user toggle** — with **hysteresis** so a brief blip lives entirely in `connecting` (K consecutive probe failures *or* a debounce window trips `offlineNoNetwork`; the first probe/call success heals back, with a toast). The transport **auto-retries with capped exponential backoff** — every op on a rate-limit (the gateway rejected it before processing, so it is safe), but diff --git a/ui/src/lib/app.svelte.ts b/ui/src/lib/app.svelte.ts index bf5c7ab..d57885c 100644 --- a/ui/src/lib/app.svelte.ts +++ b/ui/src/lib/app.svelte.ts @@ -10,6 +10,7 @@ import { navigate, router } from './router.svelte'; import { errorKey, localeFrom, setLocale, t, type Locale } from './i18n/index.svelte'; import { languageNeedsServerSync } from './language'; import { startLocalEvalMetrics } from './localeval-metrics'; +import { createStreamWatchdog } from './streamwatchdog'; import { applyReduceMotion, applyTelegramTheme, applyTheme, type ThemePref, type TelegramThemeParams } from './theme'; import { insideTelegram, @@ -215,6 +216,7 @@ function bannerSuppressed(): boolean { function goBackground(): void { backgrounded = true; + streamWatchdog.pause(); // do not count silence against a suspended (throttled) stream } function goForeground(): void { @@ -227,6 +229,7 @@ function goForeground(): void { // The stream stayed alive across the suspend, so the reconnect refetch will not fire — but an // event may have been shed from a full hub buffer while away; nudge an open game to refetch. app.resync++; + streamWatchdog.resume(); // resume liveness watching paused on the way to the background } void refreshNotifications(); } @@ -353,12 +356,35 @@ function viewingGame(gameId: string): boolean { return router.route.name === 'game' && router.route.params.id === gameId; } +// The live stream carries a heartbeat every GATEWAY_PUSH_HEARTBEAT_INTERVAL (10 s by default), so a +// healthy stream delivers an event well inside this window even when the game is idle. A silence +// past it means the stream died without erroring (e.g. airplane mode cut the radio): tear the dead +// subscription down and drop, so the machine leaves "online" instead of waiting for the next call. +// 25 s tolerates a couple of missed heartbeats; it must stay above the server interval + slack. +const STREAM_IDLE_TIMEOUT_MS = 25000; +const streamWatchdog = createStreamWatchdog({ + timeoutMs: STREAM_IDLE_TIMEOUT_MS, + onDead: () => { + // Do not trip while suspended: timers are throttled and a backgrounded stream is legitimately + // silent (the reopen on resume covers a genuine drop). + if (backgrounded || documentHidden()) return; + // Abort the dead subscription explicitly — an aborted stream skips onError (transport gates on + // signal.aborted) — then follow the same drop path as an error close. + unsubscribeStream?.(); + unsubscribeStream = null; + app.streamAlive = false; + if (!bannerSuppressed()) reportOffline(); + scheduleReconnect(); + }, +}); + function openStream(): void { closeStream(); app.streamAlive = true; unsubscribeStream = gateway.subscribe( (e) => { reportOnline(); // a delivered event proves the gateway is reachable + streamWatchdog.reset(); // any event (incl. the heartbeat) proves the stream is still live app.lastEvent = e; if (e.kind === 'chat_message' && e.message.senderId !== app.session?.userId) { // While the player is in that game's comms hub (chat or dictionary tab), neither @@ -457,6 +483,7 @@ function openStream(): void { } }, () => { + streamWatchdog.clear(); app.streamAlive = false; // A background suspend drops the single-shot stream. Keep the indicator hidden while // backgrounded or just-resumed (bannerSuppressed); otherwise show "Connecting…" (the @@ -465,6 +492,7 @@ function openStream(): void { scheduleReconnect(); }, ); + streamWatchdog.reset(); // start the liveness watch for this stream (armed by the first heartbeat) } /** scheduleReconnect reopens a dropped stream once, after a short delay, while the @@ -529,6 +557,7 @@ export async function refreshFeedbackBadge(): Promise { } function closeStream(): void { + streamWatchdog.clear(); if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; diff --git a/ui/src/lib/mock/client.ts b/ui/src/lib/mock/client.ts index 84b0e4e..4658a3c 100644 --- a/ui/src/lib/mock/client.ts +++ b/ui/src/lib/mock/client.ts @@ -829,7 +829,14 @@ export class MockGateway implements GatewayClient { // --- live stream --- subscribe(onEvent: (e: PushEvent) => void): Unsubscribe { this.subs.add(onEvent); - return () => this.subs.delete(onEvent); + // Mirror the gateway's idle keep-alive (an immediate heartbeat, then one every 10 s) so the + // client's stream watchdog sees a live stream through an idle mock session, as in production. + onEvent({ kind: 'heartbeat' }); + const hb = setInterval(() => onEvent({ kind: 'heartbeat' }), 10000); + return () => { + clearInterval(hb); + this.subs.delete(onEvent); + }; } // Fabricate an opponent reply shortly after the human moves, then hand the turn back. diff --git a/ui/src/lib/streamwatchdog.test.ts b/ui/src/lib/streamwatchdog.test.ts new file mode 100644 index 0000000..470781e --- /dev/null +++ b/ui/src/lib/streamwatchdog.test.ts @@ -0,0 +1,82 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { createStreamWatchdog } from './streamwatchdog'; + +describe('createStreamWatchdog', () => { + beforeEach(() => vi.useFakeTimers()); + afterEach(() => vi.useRealTimers()); + + it('fires onDead after the timeout with no activity', () => { + const onDead = vi.fn(); + const w = createStreamWatchdog({ timeoutMs: 25000, onDead }); + w.reset(); + vi.advanceTimersByTime(24999); + expect(onDead).not.toHaveBeenCalled(); + vi.advanceTimersByTime(1); + expect(onDead).toHaveBeenCalledTimes(1); + }); + + it('reset before the timeout re-arms and prevents the fire', () => { + const onDead = vi.fn(); + const w = createStreamWatchdog({ timeoutMs: 25000, onDead }); + w.reset(); + vi.advanceTimersByTime(20000); + w.reset(); // a fresh event arrived; the deadline moves out + vi.advanceTimersByTime(20000); + expect(onDead).not.toHaveBeenCalled(); + vi.advanceTimersByTime(5000); + expect(onDead).toHaveBeenCalledTimes(1); + }); + + it('a steady heartbeat keeps it from ever firing', () => { + const onDead = vi.fn(); + const w = createStreamWatchdog({ timeoutMs: 25000, onDead }); + w.reset(); + // A 10 s server heartbeat resets it well inside the 25 s window, indefinitely. + for (let i = 0; i < 20; i++) { + vi.advanceTimersByTime(10000); + w.reset(); + } + expect(onDead).not.toHaveBeenCalled(); + }); + + it('pause clears the pending timer so it cannot fire', () => { + const onDead = vi.fn(); + const w = createStreamWatchdog({ timeoutMs: 25000, onDead }); + w.reset(); + w.pause(); + vi.advanceTimersByTime(60000); + expect(onDead).not.toHaveBeenCalled(); + }); + + it('resume re-arms after a pause and then fires on continued silence', () => { + const onDead = vi.fn(); + const w = createStreamWatchdog({ timeoutMs: 25000, onDead }); + w.reset(); + w.pause(); + vi.advanceTimersByTime(60000); // stayed silent while paused: no fire + expect(onDead).not.toHaveBeenCalled(); + w.resume(); + vi.advanceTimersByTime(24999); + expect(onDead).not.toHaveBeenCalled(); + vi.advanceTimersByTime(1); + expect(onDead).toHaveBeenCalledTimes(1); + }); + + it('clear stops a pending fire and does not re-arm', () => { + const onDead = vi.fn(); + const w = createStreamWatchdog({ timeoutMs: 25000, onDead }); + w.reset(); + w.clear(); + vi.advanceTimersByTime(60000); + expect(onDead).not.toHaveBeenCalled(); + }); + + it('reset after a pause resumes watching (unpauses)', () => { + const onDead = vi.fn(); + const w = createStreamWatchdog({ timeoutMs: 25000, onDead }); + w.pause(); + w.reset(); // a reopen after a suspend must start watching again + vi.advanceTimersByTime(25000); + expect(onDead).toHaveBeenCalledTimes(1); + }); +}); diff --git a/ui/src/lib/streamwatchdog.ts b/ui/src/lib/streamwatchdog.ts new file mode 100644 index 0000000..e610da7 --- /dev/null +++ b/ui/src/lib/streamwatchdog.ts @@ -0,0 +1,63 @@ +// A liveness watchdog for the live event stream. The gateway pushes a `heartbeat` event on a +// fixed cadence (GATEWAY_PUSH_HEARTBEAT_INTERVAL, default 10 s), so a healthy stream delivers at +// least one event well inside the timeout even when the game itself is idle. A network that dies +// silently — e.g. airplane mode cutting the radio — leaves the streaming fetch neither erroring +// nor delivering; without this watchdog the machine would stay "online" until the next active +// call fails (often only on a foreground resync). The watchdog resets on every delivered event +// and fires onDead once the stream has been silent for the whole timeout, so the app can report +// the drop and reconnect. + +/** StreamWatchdog is the control surface returned by {@link createStreamWatchdog}. */ +export interface StreamWatchdog { + /** reset (re)starts the countdown; call on stream open and on every delivered event. It also + * clears a prior pause, so a reopen after a suspend resumes watching. */ + reset(): void; + /** pause stops the countdown while the app is backgrounded (timers are throttled while hidden, + * and a suspended stream legitimately delivers nothing — neither should trip a false drop). */ + pause(): void; + /** resume restarts the countdown after a pause (on returning to the foreground). */ + resume(): void; + /** clear stops the countdown without re-arming; call when the stream is closed or has errored. */ + clear(): void; +} + +/** + * createStreamWatchdog builds a watchdog that calls onDead once no reset has happened for + * timeoutMs. timeoutMs must exceed the server heartbeat interval plus proxy/jitter slack, or a + * healthy but idle stream would trip it. + */ +export function createStreamWatchdog(opts: { timeoutMs: number; onDead: () => void }): StreamWatchdog { + let timer: ReturnType | null = null; + let paused = false; + + function stop(): void { + if (timer !== null) { + clearTimeout(timer); + timer = null; + } + } + function arm(): void { + stop(); + timer = setTimeout(opts.onDead, opts.timeoutMs); + } + + return { + reset(): void { + paused = false; + arm(); + }, + pause(): void { + paused = true; + stop(); + }, + resume(): void { + if (paused) { + paused = false; + arm(); + } + }, + clear(): void { + stop(); + }, + }; +} From 28afcff5516bc5ea41c19a31d7c1a7733cbf6fcb Mon Sep 17 00:00:00 2001 From: Ilia Denisov Date: Tue, 14 Jul 2026 08:53:18 +0200 Subject: [PATCH 2/7] feat(ui): explicit offline state inside an online game (+ offline word check) When an online game loses the connection the game screen now says so and freezes instead of silently greying out: a "connection lost" banner appears and the rack, the move controls, the add-friend/block controls and the chat/dictionary entry all disable (a started move stays a draft, committed by the player on reconnect). It is driven off the net-state machine (netState.offline), so it also covers the Telegram/VK mini-apps, where a lost connection was previously mute in-game. If the player is already in the dictionary when the drop happens, the word check falls back to the game's pinned on-device dictionary (exact when that dawg is cached; "unavailable offline" otherwise) and the network-only complaint + external look-up hide. Chat, when already open, keeps its existing read-only degrade (send/nudge disable). New pure helper localWordCheck is unit-tested; the in-game gating gets an e2e. --- docs/ARCHITECTURE.md | 15 ++++++++--- docs/FUNCTIONAL.md | 15 ++++++++++- docs/FUNCTIONAL_ru.md | 13 ++++++++- ui/e2e/ingame-ux.spec.ts | 35 ++++++++++++++++++++++++ ui/src/game/CheckScreen.svelte | 31 ++++++++++++++++++--- ui/src/game/Game.svelte | 25 +++++++++++++++-- ui/src/game/Rack.svelte | 10 +++++++ ui/src/lib/dict/check.test.ts | 49 ++++++++++++++++++++++++++++++++++ ui/src/lib/dict/check.ts | 26 ++++++++++++++++++ ui/src/lib/i18n/en.ts | 2 ++ ui/src/lib/i18n/ru.ts | 2 ++ 11 files changed, 212 insertions(+), 11 deletions(-) create mode 100644 ui/src/lib/dict/check.test.ts create mode 100644 ui/src/lib/dict/check.ts diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 23c8f9c..610c987 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -118,10 +118,17 @@ dropped). Horizontal scaling is explicit future work. one whose response was lost — its button is disabled while offline and re-issued on reconnect). A reachability watcher (a lightweight `profile.get` probe; a session-less native guest reconciles a server guest instead — that reconcile IS the probe) drives recovery, and the live `Subscribe` stream's - drop/recovery feeds the same machine. **Telegram/VK are exempt** — always online: they are never fed an - offline signal, and `offlineMode.active` is additionally hard-gated on `offlineCapable()` (false in - those mini-apps), so nothing — not even a version lock — puts them in offline mode: no blue chrome, no - local lobby, no transport kill switch and no device-local create paths. + drop/recovery feeds the same machine. **Telegram/VK are exempt from the offline-*play* model** — + `offlineMode.active` is hard-gated on `offlineCapable()` (false in those mini-apps), so nothing — not + even a version lock — puts them in offline mode: no blue chrome, no local lobby, no transport kill + switch and no device-local create paths. The machine still tracks reachability there, though: a + connection lost **inside an online game** is surfaced on **every platform**, driven off the machine's + confirmed-offline state (`netState.offline`, not `offlineMode.active`) — the game screen shows a + *connection lost* banner and **freezes** the tray, the move controls, the add-friend/block controls and + the chat/dictionary entry (a started move stays a draft, re-committed by the player on reconnect), and + the word-check tool falls back to the game's pinned on-device dictionary (`ui/src/lib/dict/check.ts`, + exact when that dawg is cached, else *unavailable*) with its network-only complaint and external + look-up hidden. **Edge hardening:** every request body on the public listener is capped at `GATEWAY_MAX_BODY_BYTES` (default 1 MiB — far above any legitimate payload), both at the HTTP layer (`http.MaxBytesReader`) and as the Connect per-message read limit, so an oversized diff --git a/docs/FUNCTIONAL.md b/docs/FUNCTIONAL.md index 2f1a744..f5a7951 100644 --- a/docs/FUNCTIONAL.md +++ b/docs/FUNCTIONAL.md @@ -229,7 +229,10 @@ brief warm-up shows on the first open otherwise — and falls back to the server local dictionary is unavailable. The dictionary check tool is unlimited and offers a complaint on any result; for a word it finds, it also links out to an external reference dictionary (gramota.ru for Russian games, scrabblewordfinder.org for -English) to look it up. Hints are governed per game — +English) to look it up. While offline in an online game the check runs against the game's own +dictionary on the device — the same verdict as the server when that dictionary is available, +otherwise it reads *unavailable offline* — and the complaint and the external look-up, which both +need the network, are hidden. Hints are governed per game — whether they are allowed and how many each player starts with — and draw on a personal hint wallet once the per-game allowance is spent. Against the robot (**vs_ai**) hints are instead **unlimited and wallet-free**, but idle-gated as an @@ -322,6 +325,16 @@ offline on its own, and restoring the network returns it online by itself. There switch to remember: a brief drop is ridden out quietly and only a sustained loss turns the chrome offline, so you are never interrupted for a hiccup. +**Losing the connection while inside an online game** is surfaced on **every platform, including the +Telegram/VK mini-apps** — unlike the offline-play mode above, which is web/native only — because an +online game needs the server for every move. A slim *connection lost* banner appears at the top of the +board and the play area **freezes**: the rack, the move controls, the add-friend/block controls and the +chat/dictionary entry all disable, while a move you had started stays on the board as a draft. Nothing +is sent; when the connection returns the banner clears, the controls come back and you commit the move +yourself. If you were already in the chat or the dictionary when the drop happened you stay there — chat +becomes read-only (send and nudge disable) and the dictionary keeps checking words against the game's +on-device dictionary. + ### Staying up to date When a new client version is required, the app does not lock you out. On the **native** app a too-old build shows a notice with **Update** (opens the store) and **Play offline** (dismiss and keep diff --git a/docs/FUNCTIONAL_ru.md b/docs/FUNCTIONAL_ru.md index c4d7f4d..1d8cf7a 100644 --- a/docs/FUNCTIONAL_ru.md +++ b/docs/FUNCTIONAL_ru.md @@ -236,7 +236,9 @@ e-mail) либо ввод фразы. Активные игры форфейтя короткий прогрев, — и уходит на сервер, если локальный словарь недоступен. Инструмент проверки слова безлимитный и предлагает пожаловаться на любой результат; для найденного слова он также даёт ссылку на внешний справочный словарь (gramota.ru для русских игр, scrabblewordfinder.org для английских), -чтобы его посмотреть. Подсказки управляются настройками +чтобы его посмотреть. В офлайне в онлайн-партии проверка идёт по собственному словарю партии на +устройстве — тот же вердикт, что и на сервере, если этот словарь доступен, иначе показывается +*недоступно офлайн*, — а жалоба и внешняя ссылка, которым нужна сеть, скрываются. Подсказки управляются настройками партии — разрешены ли они и сколько их у каждого игрока на старте — и расходуют личный кошелёк подсказок после исчерпания внутриигрового лимита. Против робота (**vs_ai**) подсказки, наоборот, **безлимитны и без кошелька**, но с idle-гейтом как @@ -327,6 +329,15 @@ e-mail) либо ввод фразы. Активные игры форфейтя кратковременный сбой пережидается тихо, и только устойчивая потеря переводит интерфейс в офлайн, так что вас не прерывают из-за короткой икоты. +**Потеря связи внутри онлайн-партии** показывается на **всех платформах, включая мини-приложения +Telegram/VK** — в отличие от офлайн-режима игры выше, который только для веба и нативного приложения, — +потому что онлайн-партии сервер нужен на каждый ход. Сверху доски появляется тонкий баннер *связь +потеряна*, и игровая область **замораживается**: рэк, ходовые кнопки, кнопки «в друзья»/«заблокировать» +и вход в чат/словарь отключаются, а начатый ход остаётся на доске черновиком. Ничего не отправляется; +когда связь возвращается, баннер исчезает, кнопки оживают, и ход отправляешь ты сам. Если связь упала, +когда ты уже был в чате или словаре, ты там и остаёшься — чат становится «только для чтения» (отправка +и nudge отключаются), а словарь продолжает проверять слова по словарю партии на устройстве. + ### Актуальная версия Когда требуется новая версия клиента, приложение не блокирует вас наглухо. В **нативном** приложении слишком старая сборка показывает уведомление с **Обновить** (открывает магазин) и **Играть офлайн** diff --git a/ui/e2e/ingame-ux.spec.ts b/ui/e2e/ingame-ux.spec.ts index d91c073..85f005c 100644 --- a/ui/e2e/ingame-ux.spec.ts +++ b/ui/e2e/ingame-ux.spec.ts @@ -39,3 +39,38 @@ test('in-game UX: turn strip, bag badge + table footer, staged-play highlight an await expect(page.locator('.scorebadge')).toBeVisible(); await expect(page.locator('.make')).toBeVisible(); }); + +test('online game offline: banner shows, the tray and comms entry freeze, and it thaws on recovery', async ({ page }) => { + await page.goto('/'); + await page.getByRole('button', { name: /guest/i }).click(); + await page.getByRole('button', { name: /🎲/ }).click(); + await page.getByRole('button', { name: 'Random player' }).click(); + await page.locator('.variant').first().click(); + await page.getByRole('button', { name: /Start game/i }).click(); + await page.evaluate(() => (window as unknown as { __mock: { joinOpponent(): void } }).__mock.joinOpponent()); + await expect(page.getByText('Robo')).toBeVisible(); + + // Baseline online: no banner, the tray is interactive, the comms (chat/dictionary) entry is enabled. + await expect(page.locator('.offline-banner')).toHaveCount(0); + await expect(page.locator('.rack .tile').first()).toBeEnabled(); + + // The connection drops (the net hook rides past the hysteresis straight to offline). + await page.evaluate(() => (window as unknown as { __net: { offline(): void } }).__net.offline()); + + // The explicit "connection lost" banner appears and every rack tile freezes (cannot compose a move). + await expect(page.locator('.offline-banner')).toBeVisible({ timeout: 15000 }); + const tiles = page.locator('.rack .tile'); + const n = await tiles.count(); + expect(n).toBeGreaterThan(0); + for (let i = 0; i < n; i++) await expect(tiles.nth(i)).toBeDisabled(); + + // The comms entry (💬 — chat + dictionary) is disabled; it lives in the history drawer, so open it. + await page.locator('.scoreboard').click(); + await expect(page.locator('button:has(.chat-ico)')).toBeDisabled(); + + // Recovery: the network returns, the banner clears and the tray is interactive again. + await page.evaluate(() => (window as unknown as { __net: { online(): void } }).__net.online()); + await expect(page.locator('.offline-banner')).toHaveCount(0, { timeout: 15000 }); + await expect(page.locator('.rack .tile').first()).toBeEnabled(); + await expect(page.locator('button:has(.chat-ico)')).toBeEnabled(); +}); diff --git a/ui/src/game/CheckScreen.svelte b/ui/src/game/CheckScreen.svelte index b16d471..c07aff5 100644 --- a/ui/src/game/CheckScreen.svelte +++ b/ui/src/game/CheckScreen.svelte @@ -2,6 +2,8 @@ import { onMount } from 'svelte'; import { gateway } from '../lib/gateway'; import { gameSource, isLocalGameId } from '../lib/gamesource'; + import { connection } from '../lib/connection.svelte'; + import { localWordCheck } from '../lib/dict/check'; import { handleError, showToast } from '../lib/app.svelte'; import { t } from '../lib/i18n/index.svelte'; import { alphabetLetters } from '../lib/alphabet'; @@ -14,8 +16,12 @@ let { id }: { id: string } = $props(); let variant = $state('scrabble_en'); + let dictVersion = $state(''); let word = $state(''); let result = $state<{ word: string; legal: boolean } | null>(null); + // unavailable is set when an offline check cannot run because the game's pinned dictionary is not + // on the device (not cached/bundled); the panel then shows a neutral "offline" note. + let unavailable = $state(false); let cooling = $state(false); const checked = new Map(); @@ -26,6 +32,7 @@ // network. const st = await gameSource(id).gameState(id, true); variant = st.game.variant; + dictVersion = st.game.dictVersion; } catch (e) { handleError(e); } @@ -33,6 +40,7 @@ function onInput(e: Event) { word = sanitizeCheckWord((e.target as HTMLInputElement).value, alphabetLetters(variant)); + unavailable = false; } // Disabled while cooling, for an already-checked word, or an out-of-range length. function canCheck(): boolean { @@ -43,7 +51,22 @@ const w = word.trim().toUpperCase(); cooling = true; setTimeout(() => (cooling = false), 5000); + unavailable = false; try { + // Offline in an online game the network check_word would fail, so fall back to the game's own + // pinned dictionary read on-device: exact when that dawg is cached/bundled, otherwise the check + // is unavailable. A local game already resolves checkWord on-device, so it keeps that path. + if (!isLocalGameId(id) && !connection.online) { + const legal = await localWordCheck(variant, dictVersion, w); + if (legal === null) { + result = null; + unavailable = true; + return; + } + checked.set(w, legal); + result = { word: w, legal }; + return; + } const r = await gameSource(id).checkWord(id, w, variant); checked.set(w, r.legal); result = { word: w, legal: r.legal }; @@ -73,7 +96,9 @@ /> - {#if result} + {#if unavailable} +

{t('game.checkOffline')}

+ {:else if result}

{result.legal ? t('game.wordLegal', { word: result.word }) @@ -82,10 +107,10 @@

- {#if !isLocalGameId(id)} + {#if !isLocalGameId(id) && connection.online} {/if} - {#if result.legal} + {#if result.legal && connection.online} void) | null = null; @@ -1463,6 +1468,7 @@ // a local (offline) game, whose seats are account-less: vs_ai, and hotseat's synthetic seat ids. if (view?.game.vsAi || isLocalGameId(id)) return false; return ( + netReady && !!s.accountId && !app.profile?.isGuest && s.accountId !== app.session?.userId && @@ -1476,7 +1482,7 @@ // An already-blocked opponent hides it (both controls go, and the name is struck). function canBlock(s: { accountId: string; seat: number }): boolean { if (view?.game.vsAi || isLocalGameId(id)) return false; - return !!s.accountId && !app.profile?.isGuest && s.accountId !== app.session?.userId && !seatBlocked(s); + return netReady && !!s.accountId && !app.profile?.isGuest && s.accountId !== app.session?.userId && !seatBlocked(s); } @@ -1490,6 +1496,9 @@ selfInset={landscape} > {#if view} + {#if offlineInGame} +
{t('game.offlineBanner')}
+ {/if} {#if landscape}
@@ -1607,7 +1616,7 @@ — so drop the entry only when a local game is finished; an active local game keeps it for the Dictionary. An online game always keeps it (chat outlives the game). --> {#if !(gameOver && (view.game.vsAi || view.game.hotseat))} - {/if} @@ -1694,6 +1703,7 @@ draggingId={reorderDragId} dropIndex={reorderTo} confirm={!gameOver && placement.pending.length > 0 && !recallOverRack ? confirmBtn : undefined} + frozen={!netReady} ondown={onRackDown} /> {/if} @@ -2178,6 +2188,17 @@ color: var(--text-muted); padding: 40px; } + /* An online game that lost the connection: a slim, non-blocking strip at the top of the play area. + A solid token background (not color-mix) keeps it visible on the old-WebView floor. */ + .offline-banner { + padding: 7px var(--pad); + text-align: center; + font-size: 0.85rem; + line-height: 1.25; + color: var(--text); + background: var(--surface-2); + border-bottom: 1px solid var(--border); + } .ghost { position: fixed; width: 40px; diff --git a/ui/src/game/Rack.svelte b/ui/src/game/Rack.svelte index ebca3d6..28d6c13 100644 --- a/ui/src/game/Rack.svelte +++ b/ui/src/game/Rack.svelte @@ -13,6 +13,7 @@ shuffling = false, draggingId = null, dropIndex = null, + frozen = false, confirm, ondown, }: { @@ -26,6 +27,10 @@ // the drag ghost stands in) and dropIndex is the slot where a gap opens. draggingId?: number | null; dropIndex?: number | null; + /** frozen disables tile interaction (offline in an online game): tiles cannot be picked up to + * compose or reorder a move until the connection returns. The confirm control is gated + * separately by the parent. */ + frozen?: boolean; /** The confirm-move control, rendered as the fixed 7th slot of the rack while a play is staged * (the parent owns the button and its enablement; the rack only positions it). */ confirm?: Snippet; @@ -65,6 +70,7 @@ class:selected={selected === slot.index} class:shift={dropIndex != null && i >= dropIndex} data-rack-index={slot.index} + disabled={frozen} animate:hop={shuffling} onpointerdown={(e) => ondown(e, slot.index)} > @@ -114,6 +120,10 @@ outline: 3px solid var(--accent); outline-offset: -3px; } + /* Frozen (offline in an online game): the tray is inert until the connection returns. */ + .tile:disabled { + opacity: 0.5; + } /* While reordering, tiles at/after the drop slot slide right to open a gap there (one tile width plus the rack gap), so the drop position is visible. */ .rack.reordering .tile { diff --git a/ui/src/lib/dict/check.test.ts b/ui/src/lib/dict/check.test.ts new file mode 100644 index 0000000..e51758f --- /dev/null +++ b/ui/src/lib/dict/check.test.ts @@ -0,0 +1,49 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { setAlphabet } from '../alphabet'; + +// getDawg is the only side-effecting dependency; stub it so the test exercises localWordCheck's +// own logic (load -> encode -> membership -> null handling) against a fake reader, not a real DAWG. +vi.mock('./loader', () => ({ getDawg: vi.fn() })); +import { getDawg } from './loader'; +import { localWordCheck } from './check'; + +const mockedGetDawg = vi.mocked(getDawg); + +// A tiny cached alphabet so indexForLetter can encode the test words. +setAlphabet('scrabble_en', [ + { index: 0, letter: 'A', value: 1 }, + { index: 1, letter: 'B', value: 3 }, + { index: 2, letter: 'C', value: 3 }, +]); + +describe('localWordCheck', () => { + afterEach(() => vi.clearAllMocks()); + + it('returns true when the dawg contains the word', async () => { + mockedGetDawg.mockResolvedValue({ indexOf: () => 5 } as never); + expect(await localWordCheck('scrabble_en', 'v1', 'AB')).toBe(true); + }); + + it('returns false when the dawg does not contain the word', async () => { + mockedGetDawg.mockResolvedValue({ indexOf: () => -1 } as never); + expect(await localWordCheck('scrabble_en', 'v1', 'AB')).toBe(false); + }); + + it('returns null when the dawg is unavailable (offline and uncached)', async () => { + mockedGetDawg.mockResolvedValue(null); + expect(await localWordCheck('scrabble_en', 'v1', 'AB')).toBe(null); + }); + + it('encodes the word to alphabet indices for the membership test', async () => { + const indexOf = vi.fn(() => 0); + mockedGetDawg.mockResolvedValue({ indexOf } as never); + await localWordCheck('scrabble_en', 'v1', 'CAB'); + expect(indexOf).toHaveBeenCalledWith([2, 0, 1]); + }); + + it('loads the dawg for the pinned (variant, version)', async () => { + mockedGetDawg.mockResolvedValue({ indexOf: () => 1 } as never); + await localWordCheck('scrabble_en', 'v1.3.0', 'AB'); + expect(mockedGetDawg).toHaveBeenCalledWith('scrabble_en', 'v1.3.0'); + }); +}); diff --git a/ui/src/lib/dict/check.ts b/ui/src/lib/dict/check.ts new file mode 100644 index 0000000..3d0430c --- /dev/null +++ b/ui/src/lib/dict/check.ts @@ -0,0 +1,26 @@ +// Offline word-check fallback for an online game. An online game's dictionary check normally goes to +// the gateway (game.check_word); while disconnected that call fails, so the check falls back to the +// game's own pinned dictionary read locally. Using the game's pinned (variant, version) means the +// answer matches the server's — no divergence — as long as that dawg is available on-device; if it +// is not cached/bundled offline, the check is simply unavailable (null). The membership test mirrors +// the local engine's dictionaryHas (encode to alphabet indices, then Dawg.indexOf). + +import { getDawg } from './loader'; +import { indexForLetter } from '../alphabet'; +import type { Variant } from '../model'; + +/** + * localWordCheck reports whether word is in the (variant, version) dictionary using the on-device + * dawg, or null when that dawg cannot be obtained (offline and neither cached nor bundled). word + * must already be sanitised to the variant's alphabet (as the check panel does). + */ +export async function localWordCheck( + variant: Variant, + version: string, + word: string, +): Promise { + const dawg = await getDawg(variant, version); + if (!dawg) return null; + const idx = Array.from(word, (ch) => indexForLetter(variant, ch)); + return dawg.indexOf(idx) >= 0; +} diff --git a/ui/src/lib/i18n/en.ts b/ui/src/lib/i18n/en.ts index 6590022..81786f2 100644 --- a/ui/src/lib/i18n/en.ts +++ b/ui/src/lib/i18n/en.ts @@ -133,6 +133,8 @@ export const en = { 'game.complaintSent': 'Thanks, sent for review.', 'game.check': 'Check', 'game.checkWait': 'Please wait a moment.', + 'game.checkOffline': 'Word check is unavailable offline.', + 'game.offlineBanner': 'Connection lost — your move will send once you’re back online.', 'game.noHintOptions': 'No options with your letters.', 'game.thinking': 'thinking…', diff --git a/ui/src/lib/i18n/ru.ts b/ui/src/lib/i18n/ru.ts index 0660455..75871c2 100644 --- a/ui/src/lib/i18n/ru.ts +++ b/ui/src/lib/i18n/ru.ts @@ -133,6 +133,8 @@ export const ru: Record = { 'game.complaintSent': 'Спасибо, отправлено на проверку.', 'game.check': 'Проверить', 'game.checkWait': 'Секунду, пожалуйста.', + 'game.checkOffline': 'Проверка недоступна офлайн.', + 'game.offlineBanner': 'Связь потеряна — ход отправится, когда вернётся сеть.', 'game.noHintOptions': 'Нет вариантов с вашим набором.', 'game.thinking': 'думает…', From c522e77599b714f9cd390e9e6e1da341ddcbb6cb Mon Sep 17 00:00:00 2001 From: Ilia Denisov Date: Tue, 14 Jul 2026 08:59:41 +0200 Subject: [PATCH 3/7] fix(ui): lazy-load the offline word-check helper to keep it out of the entry bundle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CheckScreen's static import of dict/check pulled the dawg loader/reader into the app entry bundle, pushing it 0.8 KB over the 130 KB budget (CI bundle-size gate). The dict subsystem is lazy everywhere else, so import localWordCheck dynamically in the offline branch — it loads only when an offline check actually runs. Main entry back to 129.0 KB. --- ui/src/game/CheckScreen.svelte | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ui/src/game/CheckScreen.svelte b/ui/src/game/CheckScreen.svelte index c07aff5..e1b2211 100644 --- a/ui/src/game/CheckScreen.svelte +++ b/ui/src/game/CheckScreen.svelte @@ -3,7 +3,6 @@ import { gateway } from '../lib/gateway'; import { gameSource, isLocalGameId } from '../lib/gamesource'; import { connection } from '../lib/connection.svelte'; - import { localWordCheck } from '../lib/dict/check'; import { handleError, showToast } from '../lib/app.svelte'; import { t } from '../lib/i18n/index.svelte'; import { alphabetLetters } from '../lib/alphabet'; @@ -57,6 +56,9 @@ // pinned dictionary read on-device: exact when that dawg is cached/bundled, otherwise the check // is unavailable. A local game already resolves checkWord on-device, so it keeps that path. if (!isLocalGameId(id) && !connection.online) { + // Dynamically imported so the dawg reader/loader stays out of the app entry bundle (the dict + // subsystem is lazy everywhere else too); it loads only when an offline check actually runs. + const { localWordCheck } = await import('../lib/dict/check'); const legal = await localWordCheck(variant, dictVersion, w); if (legal === null) { result = null; From 564abdcf88c3706b8db8076dfda134a5f4e393da Mon Sep 17 00:00:00 2001 From: Ilia Denisov Date: Tue, 14 Jul 2026 09:06:03 +0200 Subject: [PATCH 4/7] chore: fix broken telegram links --- deploy/.env.example | 2 +- deploy/README.md | 4 ++-- .../telegram/internal/botlink/executor_test.go | 4 ++-- platform/telegram/internal/config/config.go | 2 +- platform/telegram/internal/config/config_test.go | 4 ++-- .../telegram/internal/promobot/promobot_test.go | 16 ++++++++-------- ui/README.md | 2 +- ui/e2e/landing.spec.ts | 2 +- ui/legal/eula_en.md | 10 +++++----- ui/legal/eula_ru.md | 10 +++++----- ui/legal/offer_en.md | 2 +- ui/legal/offer_ru.md | 2 +- ui/legal/privacy_en.md | 2 +- ui/legal/privacy_ru.md | 2 +- ui/src/Landing.svelte | 2 +- ui/src/components/StaleInviteModal.svelte | 2 +- ui/src/components/WelcomeRedeemModal.svelte | 2 +- ui/src/lib/deeplink.test.ts | 6 +++--- ui/src/lib/deeplink.ts | 4 ++-- ui/src/lib/landing.test.ts | 2 +- ui/src/lib/landing.ts | 2 +- ui/src/lib/links.test.ts | 8 ++++---- ui/src/lib/telegram.test.ts | 2 +- ui/src/lib/telegram.ts | 6 +++--- 24 files changed, 50 insertions(+), 50 deletions(-) diff --git a/deploy/.env.example b/deploy/.env.example index 2a14e92..7846f75 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -86,7 +86,7 @@ GM_BASICAUTH_HASH= # required; `caddy hash-password` bcrypt # --- UI build args (baked into the gateway image) --------------------------- VITE_TELEGRAM_BOT_ID= -VITE_TELEGRAM_LINK= # friend-invite Mini App link (full URL, e.g. https://t.me//) +VITE_TELEGRAM_LINK= # friend-invite Mini App link (full URL, e.g. https://telegram.me//) VITE_TELEGRAM_GAME_CHANNEL_NAME= # landing "Play in Telegram" link, the bot's game channel VITE_VK_APP_LINK= # landing "Play on VK" link (full URL, https://vk.com/app) VITE_VK_APP_ID= # VK ID "Web" app id (client_id) for VK web-login linking; also the gateway's GATEWAY_VK_ID_APP_ID diff --git a/deploy/README.md b/deploy/README.md index f95f3f4..06e5d06 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -107,8 +107,8 @@ without it Docker's resolver handles `otelcol`, `gateway` and `api.telegram.org` | `TELEGRAM_TEST_ENV` | _pinned_ | `false` | `true` routes the bot through Telegram's test environment (`.../bot/test/METHOD`). **The CI test contour pins this to `true` in `ci.yaml`** (the contour is the test environment) — it is not a Gitea variable. Set it in `.env` for a local run; prod leaves it `false`. | | `TELEGRAM_API_BASE_URL` | variable | _(empty)_ | Override the Bot API host (a mock/self-hosted server); empty = `https://api.telegram.org`. | | `VITE_TELEGRAM_BOT_ID` | variable | _(empty)_ | UI build-arg: numeric bot id for the web Login Widget. | -| `VITE_TELEGRAM_LINK` | variable | _(empty)_ | UI build-arg: friend-invite Mini App link (full URL, `https://t.me//` — `` is the Mini App short name from BotFather). | -| `VITE_TELEGRAM_GAME_CHANNEL_NAME` | variable | _(empty)_ | UI build-arg: the landing "Play in Telegram" link, the bot's game channel (e.g. `https://t.me/Erudit_Game`). | +| `VITE_TELEGRAM_LINK` | variable | _(empty)_ | UI build-arg: friend-invite Mini App link (full URL, `https://telegram.me//` — `` is the Mini App short name from BotFather). | +| `VITE_TELEGRAM_GAME_CHANNEL_NAME` | variable | _(empty)_ | UI build-arg: the landing "Play in Telegram" link, the bot's game channel (e.g. `https://telegram.me/Erudit_Game`). | | `VITE_VK_APP_LINK` | variable (shared) | _(empty)_ | UI build-arg: the landing "Play on VK" link, the VK Mini App (full URL, `https://vk.com/app`). One VK Mini App for all contours. | | `VITE_VK_APP_ID` | variable (shared) | _(empty)_ | VK ID "Web" app id (`client_id`) for VK web-login linking. Baked into the SPA authorize URL and reused as the gateway's `GATEWAY_VK_ID_APP_ID`. Empty disables the `link.vk.*` ops. One VK ID "Web" app for all contours. | | `VITE_VK_ID_REDIRECT_URL` | derived | _(empty)_ | VK ID trusted redirect URL — must match the app's registered redirect exactly. The deploy derives `PUBLIC_BASE_URL + /app/` (used by the SPA and as the gateway's exchange `redirect_uri`); set it only for a local run. | diff --git a/platform/telegram/internal/botlink/executor_test.go b/platform/telegram/internal/botlink/executor_test.go index 1fc7258..a520313 100644 --- a/platform/telegram/internal/botlink/executor_test.go +++ b/platform/telegram/internal/botlink/executor_test.go @@ -169,7 +169,7 @@ func TestExecutorChatGateInvalidExternalID(t *testing.T) { } func TestExecutorCreateInvoice(t *testing.T) { - sender := &fakeSender{invoiceLink: "https://t.me/$abc"} + sender := &fakeSender{invoiceLink: "https://telegram.me/$abc"} exec := NewExecutor(sender, 0, nil) cmd := &botlinkv1.Command{Payload: &botlinkv1.Command_CreateInvoice{CreateInvoice: &botlinkv1.CreateInvoiceCommand{ Title: "50 chips", Description: "50 chips", Payload: "order-1", Amount: 40, @@ -178,7 +178,7 @@ func TestExecutorCreateInvoice(t *testing.T) { if err != nil { t.Fatalf("handle: %v", err) } - if !delivered || result != "https://t.me/$abc" { + if !delivered || result != "https://telegram.me/$abc" { t.Errorf("create invoice = %v / %q, want true / the link", delivered, result) } if len(sender.invoice) != 1 || sender.invoice[0].payload != "order-1" || sender.invoice[0].amount != 40 { diff --git a/platform/telegram/internal/config/config.go b/platform/telegram/internal/config/config.go index b82d5ec..7610ea0 100644 --- a/platform/telegram/internal/config/config.go +++ b/platform/telegram/internal/config/config.go @@ -66,7 +66,7 @@ type BotConfig struct { // bot's message text (TELEGRAM_BOT_USERNAME; required when the promo bot runs). BotUsername string // BotLinkURL is the main bot's Mini App direct link — the same value the UI builds - // share links from (VITE_TELEGRAM_LINK), e.g. https://t.me//. The promo + // share links from (VITE_TELEGRAM_LINK), e.g. https://telegram.me//. The promo // button appends ?startapp= to it (TELEGRAM_BOT_LINK; required when the // promo bot runs). It is distinct from the BotLink mTLS dial config below. BotLinkURL string diff --git a/platform/telegram/internal/config/config_test.go b/platform/telegram/internal/config/config_test.go index d90c706..f28e17c 100644 --- a/platform/telegram/internal/config/config_test.go +++ b/platform/telegram/internal/config/config_test.go @@ -112,7 +112,7 @@ func TestLoadBotChatAndPromo(t *testing.T) { t.Setenv("TELEGRAM_CHAT_ID", "-100222") t.Setenv("TELEGRAM_PROMO_BOT_TOKEN", "promo-token") t.Setenv("TELEGRAM_BOT_USERNAME", "@ScrabbleBot") - t.Setenv("TELEGRAM_BOT_LINK", "https://t.me/ScrabbleBot/app") + t.Setenv("TELEGRAM_BOT_LINK", "https://telegram.me/ScrabbleBot/app") c, err := LoadBot() if err != nil { t.Fatalf("LoadBot: %v", err) @@ -126,7 +126,7 @@ func TestLoadBotChatAndPromo(t *testing.T) { if c.BotUsername != "ScrabbleBot" { t.Errorf("BotUsername = %q, want the leading @ stripped", c.BotUsername) } - if c.BotLinkURL != "https://t.me/ScrabbleBot/app" { + if c.BotLinkURL != "https://telegram.me/ScrabbleBot/app" { t.Errorf("BotLinkURL = %q", c.BotLinkURL) } }) diff --git a/platform/telegram/internal/promobot/promobot_test.go b/platform/telegram/internal/promobot/promobot_test.go index 4e719d4..c748068 100644 --- a/platform/telegram/internal/promobot/promobot_test.go +++ b/platform/telegram/internal/promobot/promobot_test.go @@ -13,7 +13,7 @@ import ( ) func TestPromoTextLocalization(t *testing.T) { - const url = "https://t.me/bot/app?startapp=verudit_ru-scrabble_en" + const url = "https://telegram.me/bot/app?startapp=verudit_ru-scrabble_en" // The @username is rendered as a clickable deep link (the same target as the button), // not a plain mention, so tapping it opens the seeded Mini App. wantLink := `@ScrabbleBot` @@ -41,17 +41,17 @@ func TestPromoTextLocalization(t *testing.T) { } func TestLaunchURLAppendsStartapp(t *testing.T) { - b := &Bot{linkURL: "https://t.me/bot/app"} - if got := b.launchURL(""); got != "https://t.me/bot/app" { + b := &Bot{linkURL: "https://telegram.me/bot/app"} + if got := b.launchURL(""); got != "https://telegram.me/bot/app" { t.Errorf("empty payload = %q, want the base link unchanged", got) } - if got := b.launchURL("g123"); got != "https://t.me/bot/app?startapp=g123" { + if got := b.launchURL("g123"); got != "https://telegram.me/bot/app?startapp=g123" { t.Errorf("launchURL = %q, want startapp=g123 appended", got) } } func TestLaunchMarkupIsURLButton(t *testing.T) { - b := &Bot{linkURL: "https://t.me/bot/app"} + b := &Bot{linkURL: "https://telegram.me/bot/app"} btn := b.launchMarkup("Play", "f99").InlineKeyboard[0][0] if btn.WebApp != nil { t.Error("the promo button must not be a web_app button (it would sign initData with the promo token, which the main bot rejects)") @@ -84,7 +84,7 @@ func TestHandleStartReplies(t *testing.T) { api := &fakeAPI{} srv := httptest.NewServer(api) t.Cleanup(srv.Close) - b, err := New(Config{Token: "1:2", APIBaseURL: srv.URL, BotUsername: "ScrabbleBot", BotLinkURL: "https://t.me/bot/app"}, zap.NewNop()) + b, err := New(Config{Token: "1:2", APIBaseURL: srv.URL, BotUsername: "ScrabbleBot", BotLinkURL: "https://telegram.me/bot/app"}, zap.NewNop()) if err != nil { t.Fatalf("new: %v", err) } @@ -98,7 +98,7 @@ func TestHandleStartReplies(t *testing.T) { if api.chatID != "42" { t.Errorf("chat_id = %q, want 42", api.chatID) } - if !strings.Contains(api.text, `@ScrabbleBot`) { + if !strings.Contains(api.text, `@ScrabbleBot`) { t.Errorf("text = %q, want the @mention linked to the startapp deep link", api.text) } if strings.Contains(api.replyMarkup, "web_app") { @@ -113,7 +113,7 @@ func TestHandleStartIgnoresGroup(t *testing.T) { api := &fakeAPI{} srv := httptest.NewServer(api) t.Cleanup(srv.Close) - b, err := New(Config{Token: "1:2", APIBaseURL: srv.URL, BotUsername: "B", BotLinkURL: "https://t.me/b/a"}, zap.NewNop()) + b, err := New(Config{Token: "1:2", APIBaseURL: srv.URL, BotUsername: "B", BotLinkURL: "https://telegram.me/b/a"}, zap.NewNop()) if err != nil { t.Fatalf("new: %v", err) } diff --git a/ui/README.md b/ui/README.md index 80d88db..625c7c2 100644 --- a/ui/README.md +++ b/ui/README.md @@ -29,7 +29,7 @@ pnpm codegen # regenerate src/gen from edge.proto + scrabble.fbs (dev-time) gateway origin for a packaged (non-proxied) build. `VITE_TELEGRAM_BOT_ID` enables the "Link Telegram" web sign-in (the Login Widget) — inert until the site domain is registered with BotFather (`/setdomain`); `VITE_TELEGRAM_LINK` is the -friend-invite Mini App link for the single bot (full URL `https://t.me//`). +friend-invite Mini App link for the single bot (full URL `https://telegram.me//`). `VITE_TELEGRAM_GAME_CHANNEL_NAME` is the "Play in Telegram" link shown on the landing page. The **native (Capacitor) build** additionally reads `VITE_DICT_VERSION` (the bundled-dictionary version the offline path requests, matching the packaged DAWGs), `VITE_PAYMENTS_DISABLED=1` (hide in-app purchases diff --git a/ui/e2e/landing.spec.ts b/ui/e2e/landing.spec.ts index 848af7e..88128f6 100644 --- a/ui/e2e/landing.spec.ts +++ b/ui/e2e/landing.spec.ts @@ -70,7 +70,7 @@ test('the landing footer links to the legal documents and the feedback bot', asy ['Пользовательское соглашение', '/eula/'], ['Политика конфиденциальности', '/privacy/'], ['Публичная оферта', '/offer/'], - ['Обратная связь', 'https://t.me/Erudit_GameBot'], + ['Обратная связь', 'https://telegram.me/Erudit_GameBot'], ]; for (const [name, href] of links) { const link = page.getByRole('link', { name }); diff --git a/ui/legal/eula_en.md b/ui/legal/eula_en.md index 15221e3..5258d2a 100644 --- a/ui/legal/eula_en.md +++ b/ui/legal/eula_en.md @@ -207,7 +207,7 @@ If the limitation or exclusion of liability is prohibited by applicable law, the The Company cares about the protection of personal data. Personal data collected by the Company in the context of this document is subject to automated processing in accordance with applicable law. All information collected as part of providing the service is registered by the Company, which is the data controller. This is very important for the functioning of the services offered by the Company. -To exercise one or more of their rights, the User must provide an identity document and contact the person responsible for data protection at the Company (via service support on Telegram: [@Erudit_GameBot](https://t.me/Erudit_GameBot), or send us your request in writing to: 236020, Kaliningrad, Pribrezhny district, Parkovaya St. 1, recipient — Ilya Arkadyevich Denisov). +To exercise one or more of their rights, the User must provide an identity document and contact the person responsible for data protection at the Company (via service support on Telegram: [@Erudit_GameBot](https://telegram.me/Erudit_GameBot), or send us your request in writing to: 236020, Kaliningrad, Pribrezhny district, Parkovaya St. 1, recipient — Ilya Arkadyevich Denisov). In the event of a complaint, the User may contact the personal-data supervisory authority of their country of residence. @@ -247,7 +247,7 @@ Although the Company does everything possible to ensure data confidentiality and **15.8.** The Company reserves the right to revise the terms of this Licence Agreement, in particular, the Game Rules and/or the Forum Rules, by updating the Licence Agreement at [`erudit-game.ru/eula/`](/eula/) or by notifying the User by email. The revised Licence Agreement enters into force from the day of its publication. The User is advised to check the aforementioned website periodically for notices of such changes. The User's failure to take steps to review does not serve as grounds for the User's failure to perform their obligations and non-compliance with the restrictions established by this Licence Agreement. The User's continued use of the Game is deemed acceptance of any revised terms. -**15.9.** On matters related to the performance of this Licence Agreement and/or the use of the Game, the User may contact the Company on Telegram: [@Erudit_GameBot](https://t.me/Erudit_GameBot) and at ilia.denissov@gmail.com. +**15.9.** On matters related to the performance of this Licence Agreement and/or the use of the Game, the User may contact the Company on Telegram: [@Erudit_GameBot](https://telegram.me/Erudit_GameBot) and at ilia.denissov@gmail.com. Denisov I.A. | 2026 @@ -312,7 +312,7 @@ The Company reserves the right to identify and locate all of the User's Accounts **5.4.** The User is prohibited from attempting to benefit from deliberate (or repeated) participation in the game process as part of a game group (team) with other Users who have violated paragraphs 5.1, 5.5 and/or 5.6 of the Game Rules. -**5.5.** The User is prohibited from using and distributing information, calling for the use of and publicly distributing any errors, both within the Game and in any other software. A User who discovers such errors in the Game must stop using it and report them to the Company on Telegram: [@Erudit_GameBot](https://t.me/Erudit_GameBot) and at ilia.denissov@gmail.com, setting out in detail and truthfully all the circumstances of such discovery and use. If the User has any doubts as to whether the functioning of any particular game process, In-game items or In-game currency is currently normal or has deviations, malfunctions or errors, the User must stop using such process, In-game items or In-game currency and contact the Company at ilia.denissov@gmail.com for the relevant explanations. +**5.5.** The User is prohibited from using and distributing information, calling for the use of and publicly distributing any errors, both within the Game and in any other software. A User who discovers such errors in the Game must stop using it and report them to the Company on Telegram: [@Erudit_GameBot](https://telegram.me/Erudit_GameBot) and at ilia.denissov@gmail.com, setting out in detail and truthfully all the circumstances of such discovery and use. If the User has any doubts as to whether the functioning of any particular game process, In-game items or In-game currency is currently normal or has deviations, malfunctions or errors, the User must stop using such process, In-game items or In-game currency and contact the Company at ilia.denissov@gmail.com for the relevant explanations. **5.6.** The User is prohibited from decompiling, decoding and reconstructing data, bypassing data-protection systems, hacking or attempting to hack the software components of the Game or its services, and/or intercepting data coming to or from the server. Prohibited are: (in particular) any modification, alteration, decompilation, decoding, sale or distribution of modified materials of the Game in whole or in part (or the means and materials necessary to perform such actions), the use of programming errors, making changes to the program code and obtaining unauthorised access to the server and database of the Game. In certain special cases, the Company has the right to immediately suspend the User's access to the Game and send a request to the relevant authorities to prevent any violation of the Licence Agreement and/or provisions of applicable law. @@ -350,7 +350,7 @@ The Company reserves the right to identify and locate all of the User's Accounts **8.2.** The User is prohibited from offering such arguments as "in accordance with the role"/"role-play" in defence of unlawful actions of any kind. -**8.3.** The User is prohibited from deliberately providing false information when contacting the Company on Telegram: [@Erudit_GameBot](https://t.me/Erudit_GameBot) or at ilia.denissov@gmail.com, as well as from falsifying the data provided. +**8.3.** The User is prohibited from deliberately providing false information when contacting the Company on Telegram: [@Erudit_GameBot](https://telegram.me/Erudit_GameBot) or at ilia.denissov@gmail.com, as well as from falsifying the data provided. --- @@ -406,7 +406,7 @@ The Company reserves the right to identify and locate all of the User's forum ac **3.9.** Trading (discussion of trading) in game characters, In-game items, In-game currency, forum accounts, character level boosting. -**3.10.** Discussion of vulnerabilities or shortcomings of the Game, as well as any actions that in any way violate the Game Rules, or their discussion. Upon discovering vulnerabilities or shortcomings, the User must report them to the Company on Telegram: [@Erudit_GameBot](https://t.me/Erudit_GameBot) or at ilia.denissov@gmail.com. +**3.10.** Discussion of vulnerabilities or shortcomings of the Game, as well as any actions that in any way violate the Game Rules, or their discussion. Upon discovering vulnerabilities or shortcomings, the User must report them to the Company on Telegram: [@Erudit_GameBot](https://telegram.me/Erudit_GameBot) or at ilia.denissov@gmail.com. **3.11.** Publication of messages causing negative consequences for the game process; provocation of Users to violate the Game Rules. diff --git a/ui/legal/eula_ru.md b/ui/legal/eula_ru.md index 5c4069f..20dd6f8 100644 --- a/ui/legal/eula_ru.md +++ b/ui/legal/eula_ru.md @@ -207,7 +207,7 @@ Компания заботится о защите персональных данных. Персональные данные, собранные Компанией в контексте настоящего документа, подлежат автоматизированной обработке в соответствии с действующим законодательством. Вся информация, собранная в рамках предоставления услуги, регистрируется Компанией, которая является контролером данных. Это очень важно для функционирования предлагаемых Компанией услуг. -Для осуществления одного или нескольких своих прав Пользователь должен предоставить документ, удостоверяющий личность, и связаться с лицом, ответственным за защиту данных в Компании (через сервисную поддержку в Telegram: [@Erudit_GameBot](https://t.me/Erudit_GameBot), либо отправьте нам свой запрос в письменном виде по адресу: 236020, г. Калининград, мкр. Прибрежный, ул. Парковая, д. 1, получатель — Денисов Илья Аркадьевич). +Для осуществления одного или нескольких своих прав Пользователь должен предоставить документ, удостоверяющий личность, и связаться с лицом, ответственным за защиту данных в Компании (через сервисную поддержку в Telegram: [@Erudit_GameBot](https://telegram.me/Erudit_GameBot), либо отправьте нам свой запрос в письменном виде по адресу: 236020, г. Калининград, мкр. Прибрежный, ул. Парковая, д. 1, получатель — Денисов Илья Аркадьевич). В случае возникновения жалобы Пользователь может обратиться в надзорный орган по защите персональных данных страны своего проживания. @@ -247,7 +247,7 @@ **15.8.** Компания оставляет за собой право пересматривать условия настоящего Лицензионного соглашения, в частности, Правила Игры и/или Правила форума, обновляя Лицензионное соглашение на странице [`erudit-game.ru/eula/`](/eula/) или уведомляя Пользователя по электронной почте. Пересмотренное Лицензионное соглашение вступает в силу со дня его опубликования. Пользователю рекомендуется периодически проверять вышеуказанный веб-сайт на наличие уведомлений о таких изменениях. Отказ Пользователя от действий по ознакомлению не может служить основанием для невыполнения обязательств Пользователя и несоблюдения Пользователем ограничений, установленных настоящим Лицензионным соглашением. Продолжение использования Игры Пользователем считается принятием любых пересмотренных условий. -**15.9.** По вопросам, связанным с исполнением настоящего Лицензионного соглашения и/или использованием Игры, Пользователь может связаться с Компанией через Telegram: [@Erudit_GameBot](https://t.me/Erudit_GameBot) и по адресу ilia.denissov@gmail.com. +**15.9.** По вопросам, связанным с исполнением настоящего Лицензионного соглашения и/или использованием Игры, Пользователь может связаться с Компанией через Telegram: [@Erudit_GameBot](https://telegram.me/Erudit_GameBot) и по адресу ilia.denissov@gmail.com. Денисов И.А. | 2026 @@ -312,7 +312,7 @@ **5.4.** Пользователю запрещается пытаться извлечь выгоду из преднамеренного (или неоднократного) участия в игровом процессе в составе игровой группы (команды) с другими Пользователями, нарушившими пункты 5.1, 5.5 и/или 5.6 Правил Игры. -**5.5.** Пользователю запрещается использовать и распространять информацию, призывать к использованию и публично распространять любые ошибки, как внутри Игры, так и в любом другом программном обеспечении. Пользователь, обнаруживший такие ошибки в Игре, должен прекратить её использование и сообщить о них Компании через Telegram: [@Erudit_GameBot](https://t.me/Erudit_GameBot) и по адресу ilia.denissov@gmail.com, подробно и достоверно изложив все обстоятельства такого обнаружения и использования. В случае возникновения у Пользователя каких-либо сомнений в том, является ли такое функционирование какого-либо конкретного игрового процесса, Внутриигровых предметов или Внутриигровой валюты в настоящий момент нормальным или имеет отклонения, сбои, ошибки, Пользователь должен прекратить использование таких процесса, Внутриигровых предметов или Внутриигровой валюты и обратиться к Компании через ilia.denissov@gmail.com для получения соответствующих разъяснений. +**5.5.** Пользователю запрещается использовать и распространять информацию, призывать к использованию и публично распространять любые ошибки, как внутри Игры, так и в любом другом программном обеспечении. Пользователь, обнаруживший такие ошибки в Игре, должен прекратить её использование и сообщить о них Компании через Telegram: [@Erudit_GameBot](https://telegram.me/Erudit_GameBot) и по адресу ilia.denissov@gmail.com, подробно и достоверно изложив все обстоятельства такого обнаружения и использования. В случае возникновения у Пользователя каких-либо сомнений в том, является ли такое функционирование какого-либо конкретного игрового процесса, Внутриигровых предметов или Внутриигровой валюты в настоящий момент нормальным или имеет отклонения, сбои, ошибки, Пользователь должен прекратить использование таких процесса, Внутриигровых предметов или Внутриигровой валюты и обратиться к Компании через ilia.denissov@gmail.com для получения соответствующих разъяснений. **5.6.** Пользователю запрещается декомпилировать, декодировать и реконструировать данные, обходить системы защиты данных, взламывать или пытаться взломать программные компоненты Игры или её сервисов, и/или перехватывать данные, поступающие на сервер или с него. Запрещается: (в частности) любое модифицирование, изменение, декомпиляция, декодирование, продажа или распространение модифицированных материалов Игры в целом или по частям (или средств и материалов, необходимых для выполнения таких действий), использование ошибок программирования, внесение изменений в программный код и получение несанкционированного доступа к серверу и базе данных Игры. В определённых особых случаях Компания имеет право немедленно приостановить доступ Пользователя к Игре и направить запрос в соответствующие органы о предотвращении любого нарушения Лицензионного соглашения и/или положений применимого законодательства. @@ -350,7 +350,7 @@ **8.2.** Пользователю запрещается предлагать такие аргументы, как «в соответствии с ролью»/«отыгрыш роли», в защиту неправомерных действий любого рода. -**8.3.** Пользователю запрещается преднамеренно предоставлять ложную информацию в случае обращения к Компании через Telegram: [@Erudit_GameBot](https://t.me/Erudit_GameBot) или по адресу ilia.denissov@gmail.com, а также фальсифицировать предоставленные данные. +**8.3.** Пользователю запрещается преднамеренно предоставлять ложную информацию в случае обращения к Компании через Telegram: [@Erudit_GameBot](https://telegram.me/Erudit_GameBot) или по адресу ilia.denissov@gmail.com, а также фальсифицировать предоставленные данные. --- @@ -406,7 +406,7 @@ **3.9.** Торговля (обсуждение торговли) игровыми персонажами, Внутриигровыми предметами, Внутриигровой валютой, учётными записями на форумах, повышение уровня персонажа. -**3.10.** Обсуждение уязвимостей или недоработок Игры, а также любые действия, каким-либо образом нарушающие Правила Игры, или их обсуждение. При обнаружении уязвимостей или недоработок Пользователь должен сообщить об этом Компании через Telegram: [@Erudit_GameBot](https://t.me/Erudit_GameBot) или по адресу ilia.denissov@gmail.com. +**3.10.** Обсуждение уязвимостей или недоработок Игры, а также любые действия, каким-либо образом нарушающие Правила Игры, или их обсуждение. При обнаружении уязвимостей или недоработок Пользователь должен сообщить об этом Компании через Telegram: [@Erudit_GameBot](https://telegram.me/Erudit_GameBot) или по адресу ilia.denissov@gmail.com. **3.11.** Публикация сообщений, вызывающих негативные последствия для игрового процесса; провокация нарушения Пользователями Правил Игры. diff --git a/ui/legal/offer_en.md b/ui/legal/offer_en.md index e916d6d..c0fca9a 100644 --- a/ui/legal/offer_en.md +++ b/ui/legal/offer_en.md @@ -152,4 +152,4 @@ Disputes or disagreements on which the Parties have not reached agreement are su Ilya Arkadyevich Denisov, TIN 290210610742. -Feedback on Telegram: [@Erudit_GameBot](https://t.me/Erudit_GameBot). +Feedback on Telegram: [@Erudit_GameBot](https://telegram.me/Erudit_GameBot). diff --git a/ui/legal/offer_ru.md b/ui/legal/offer_ru.md index 1763d65..8863d86 100644 --- a/ui/legal/offer_ru.md +++ b/ui/legal/offer_ru.md @@ -152,4 +152,4 @@ Денисов Илья Аркадьевич, ИНН 290210610742. -Обратная связь в Telegram: [@Erudit_GameBot](https://t.me/Erudit_GameBot). +Обратная связь в Telegram: [@Erudit_GameBot](https://telegram.me/Erudit_GameBot). diff --git a/ui/legal/privacy_en.md b/ui/legal/privacy_en.md index 07e1a33..6280f63 100644 --- a/ui/legal/privacy_en.md +++ b/ui/legal/privacy_en.md @@ -133,7 +133,7 @@ The transfer of personal data to recipients (regardless of their legal status) i ## 11. Contact us -**11.1.** If you have any questions, please contact Support on Telegram: [@Erudit_GameBot](https://t.me/Erudit_GameBot), or send us your request in writing to: 236020, Kaliningrad, Pribrezhny district, Parkovaya St. 1, recipient — Ilya Arkadyevich Denisov. Please refer to this Privacy Policy so that we can process your request effectively. We will try to respond to you within 30 days of receiving your request. +**11.1.** If you have any questions, please contact Support on Telegram: [@Erudit_GameBot](https://telegram.me/Erudit_GameBot), or send us your request in writing to: 236020, Kaliningrad, Pribrezhny district, Parkovaya St. 1, recipient — Ilya Arkadyevich Denisov. Please refer to this Privacy Policy so that we can process your request effectively. We will try to respond to you within 30 days of receiving your request. **11.2.** All correspondence we receive from you (written or electronic requests) is classified as restricted-access information and may not be disclosed without your written consent. Personal data and other information about you may not be used without your consent for any purpose other than responding to the request, except in cases expressly provided for by law. diff --git a/ui/legal/privacy_ru.md b/ui/legal/privacy_ru.md index e2c9b58..4d63ff6 100644 --- a/ui/legal/privacy_ru.md +++ b/ui/legal/privacy_ru.md @@ -133,7 +133,7 @@ ## 11. Связаться с нами -**11.1.** Если у вас есть какие-либо вопросы, пожалуйста, свяжитесь со Службой поддержки в Telegram: [@Erudit_GameBot](https://t.me/Erudit_GameBot), либо отправьте нам свой запрос в письменном виде по адресу: 236020, г. Калининград, мкр. Прибрежный, ул. Парковая, д. 1, получатель — Денисов Илья Аркадьевич. Пожалуйста, ссылайтесь на настоящую Политику конфиденциальности, чтобы мы смогли эффективно обработать ваш запрос. Мы постараемся ответить вам в течение 30 дней с момента получения запроса. +**11.1.** Если у вас есть какие-либо вопросы, пожалуйста, свяжитесь со Службой поддержки в Telegram: [@Erudit_GameBot](https://telegram.me/Erudit_GameBot), либо отправьте нам свой запрос в письменном виде по адресу: 236020, г. Калининград, мкр. Прибрежный, ул. Парковая, д. 1, получатель — Денисов Илья Аркадьевич. Пожалуйста, ссылайтесь на настоящую Политику конфиденциальности, чтобы мы смогли эффективно обработать ваш запрос. Мы постараемся ответить вам в течение 30 дней с момента получения запроса. **11.2.** Вся полученная нами от вас корреспонденция (письменные или электронные запросы) классифицируется как информация с ограниченным доступом и не может быть разглашена без вашего письменного согласия. Персональные данные и другая информация о вас не могут быть использованы без вашего согласия для каких-либо целей, кроме как для ответа на запрос, за исключением случаев, прямо предусмотренных законом. diff --git a/ui/src/Landing.svelte b/ui/src/Landing.svelte index b7c9e67..28e393c 100644 --- a/ui/src/Landing.svelte +++ b/ui/src/Landing.svelte @@ -134,7 +134,7 @@ - {t('landing.feedback')} + {t('landing.feedback')} {t('about.version', { v: __APP_VERSION__ })} diff --git a/ui/src/components/StaleInviteModal.svelte b/ui/src/components/StaleInviteModal.svelte index b06579b..d7cf115 100644 --- a/ui/src/components/StaleInviteModal.svelte +++ b/ui/src/components/StaleInviteModal.svelte @@ -15,7 +15,7 @@ function openBot() { if (username) { - const url = `https://t.me/${username}`; + const url = `https://telegram.me/${username}`; // Inside Telegram, openTelegramLink navigates to the bot chat natively; elsewhere fall // back to a new tab (routed out of the Android VK WebView by openExternalUrl). if (!telegramOpenLink(url)) openExternalUrl(url); diff --git a/ui/src/components/WelcomeRedeemModal.svelte b/ui/src/components/WelcomeRedeemModal.svelte index 3bd0c29..6dbd701 100644 --- a/ui/src/components/WelcomeRedeemModal.svelte +++ b/ui/src/components/WelcomeRedeemModal.svelte @@ -18,7 +18,7 @@ function openBot() { if (username) { - const url = `https://t.me/${username}`; + const url = `https://telegram.me/${username}`; // Inside Telegram, openTelegramLink navigates to the bot chat natively; elsewhere fall // back to a new tab (routed out of the Android VK WebView by openExternalUrl). if (!telegramOpenLink(url)) openExternalUrl(url); diff --git a/ui/src/lib/deeplink.test.ts b/ui/src/lib/deeplink.test.ts index becb5f1..ec17aee 100644 --- a/ui/src/lib/deeplink.test.ts +++ b/ui/src/lib/deeplink.test.ts @@ -32,8 +32,8 @@ describe('shareLink', () => { }); it('wraps a payload in a startapp link', () => { - vi.stubEnv('VITE_TELEGRAM_LINK', 'https://t.me/bot/app'); - expect(shareLink('f123456')).toBe('https://t.me/bot/app?startapp=f123456'); + vi.stubEnv('VITE_TELEGRAM_LINK', 'https://telegram.me/bot/app'); + expect(shareLink('f123456')).toBe('https://telegram.me/bot/app?startapp=f123456'); }); }); @@ -60,7 +60,7 @@ describe('botUsername', () => { }); it('extracts the bot handle from the Mini App link', () => { - vi.stubEnv('VITE_TELEGRAM_LINK', 'https://t.me/bot/app'); + vi.stubEnv('VITE_TELEGRAM_LINK', 'https://telegram.me/bot/app'); expect(botUsername()).toBe('bot'); }); }); diff --git a/ui/src/lib/deeplink.ts b/ui/src/lib/deeplink.ts index 19a2e5b..bd28dae 100644 --- a/ui/src/lib/deeplink.ts +++ b/ui/src/lib/deeplink.ts @@ -43,7 +43,7 @@ function envVar(name: string): string | undefined { } /** - * telegramBase returns the single bot's Mini App link base (e.g. https://t.me//) + * telegramBase returns the single bot's Mini App link base (e.g. https://telegram.me//) * from VITE_TELEGRAM_LINK, or null when it is not configured. */ function telegramBase(): string | null { @@ -52,7 +52,7 @@ function telegramBase(): string | null { /** * botUsername extracts the bot's @username (without the @) from the configured Mini App - * link: the first path segment of https://t.me//. Returns null when no base is + * link: the first path segment of https://telegram.me//. Returns null when no base is * configured or the link carries no path. */ export function botUsername(): string | null { diff --git a/ui/src/lib/landing.test.ts b/ui/src/lib/landing.test.ts index 803ff14..25a6a1f 100644 --- a/ui/src/lib/landing.test.ts +++ b/ui/src/lib/landing.test.ts @@ -6,7 +6,7 @@ describe('telegramChannelLink', () => { it('builds the t.me link from the channel name', () => { vi.stubEnv('VITE_TELEGRAM_GAME_CHANNEL_NAME', '@Erudit_Game'); // a leading @ is tolerated - expect(telegramChannelLink()).toBe('https://t.me/Erudit_Game'); + expect(telegramChannelLink()).toBe('https://telegram.me/Erudit_Game'); }); it('returns null when the channel name is unset or blank', () => { diff --git a/ui/src/lib/landing.ts b/ui/src/lib/landing.ts index 2943705..a2d9cb6 100644 --- a/ui/src/lib/landing.ts +++ b/ui/src/lib/landing.ts @@ -11,7 +11,7 @@ export function telegramChannelLink(): string | null { const raw = import.meta.env.VITE_TELEGRAM_GAME_CHANNEL_NAME; const name = (raw as string | undefined)?.trim().replace(/^@/, ''); - return name ? `https://t.me/${name}` : null; + return name ? `https://telegram.me/${name}` : null; } /** diff --git a/ui/src/lib/links.test.ts b/ui/src/lib/links.test.ts index 895c5f9..cb72f30 100644 --- a/ui/src/lib/links.test.ts +++ b/ui/src/lib/links.test.ts @@ -13,9 +13,9 @@ describe('openExternalUrl', () => { origin: 'https://app.example', }); vi.stubGlobal('window', { open }); - openExternalUrl('https://t.me/some_bot'); + openExternalUrl('https://telegram.me/some_bot'); expect(open).toHaveBeenCalledWith( - `https://vk.com/away.php?to=${encodeURIComponent('https://t.me/some_bot')}`, + `https://vk.com/away.php?to=${encodeURIComponent('https://telegram.me/some_bot')}`, '_blank', ); }); @@ -23,7 +23,7 @@ describe('openExternalUrl', () => { it('opens a plain new tab elsewhere', () => { const open = vi.fn(); vi.stubGlobal('window', { open }); - openExternalUrl('https://t.me/some_bot'); - expect(open).toHaveBeenCalledWith('https://t.me/some_bot', '_blank'); + openExternalUrl('https://telegram.me/some_bot'); + expect(open).toHaveBeenCalledWith('https://telegram.me/some_bot', '_blank'); }); }); diff --git a/ui/src/lib/telegram.test.ts b/ui/src/lib/telegram.test.ts index eb53b7c..688a2e0 100644 --- a/ui/src/lib/telegram.test.ts +++ b/ui/src/lib/telegram.test.ts @@ -148,7 +148,7 @@ describe('routeExternalLinkInTelegram', () => { it('leaves a t.me link to the native handler (openTelegramLink owns those)', () => { const openLink = stubInside(); - expect(routeExternalLinkInTelegram({ href: 'https://t.me/some_bot', target: '_blank' })).toBe(false); + expect(routeExternalLinkInTelegram({ href: 'https://telegram.me/some_bot', target: '_blank' })).toBe(false); expect(openLink).not.toHaveBeenCalled(); }); diff --git a/ui/src/lib/telegram.ts b/ui/src/lib/telegram.ts index 50b0772..01b0117 100644 --- a/ui/src/lib/telegram.ts +++ b/ui/src/lib/telegram.ts @@ -226,19 +226,19 @@ export function isExternalHttpUrl(href: string): boolean { export function routeExternalLinkInTelegram(anchor: { href: string; target: string }): boolean { if (!insideTelegram()) return false; if (anchor.target !== '_blank') return false; - if (anchor.href.startsWith('https://t.me/')) return false; + if (anchor.href.startsWith('https://telegram.me/')) return false; if (!isExternalHttpUrl(anchor.href)) return false; return telegramOpenExternalLink(anchor.href); } /** * shareTelegramLink opens Telegram's native "share to a chat" picker for url with a - * caption, through the Mini App SDK (https://t.me/share/url). Returns false outside + * caption, through the Mini App SDK (https://telegram.me/share/url). Returns false outside * Telegram or when the SDK lacks the method, so the caller can fall back to the Web * Share API. Works consistently on iOS and Android within Telegram. */ export function shareTelegramLink(url: string, text: string): boolean { - return telegramOpenLink(`https://t.me/share/url?url=${encodeURIComponent(url)}&text=${encodeURIComponent(text)}`); + return telegramOpenLink(`https://telegram.me/share/url?url=${encodeURIComponent(url)}&text=${encodeURIComponent(text)}`); } /** TelegramLaunch is the data a Mini App launch carries. */ From 471fadc6a45450e1c4718f51f0b366a997fceaf7 Mon Sep 17 00:00:00 2001 From: Ilia Denisov Date: Tue, 14 Jul 2026 09:38:42 +0200 Subject: [PATCH 5/7] =?UTF-8?q?fix(ui):=20offline=20in-game=20=E2=80=94=20?= =?UTF-8?q?usable=20dictionary=20check=20+=20hide=20(not=20disable)=20resi?= =?UTF-8?q?gn/chat?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two fixes from contour testing of the offline-in-game UX: - The dictionary word check was unusable offline (Check button disabled) when the panel was reached while already offline: CheckScreen fetched the variant + pinned version over the network in onMount, which fails offline, leaving the default variant so input sanitising stripped every letter. Seed both from the cached game (present once the board has opened) so the input and the on-device dawg fallback work without a round-trip; the network refresh still runs when online and on a cold deep-link. - The resign and chat controls were only functionally disabled (chat) or not gated at all (resign) offline, so they still looked active. Hide both while offline, matching the frozen social controls. Tests: the in-game offline e2e now asserts the drawer action icons are hidden (not disabled); a new e2e guards the offline dictionary flow. Docs updated. --- docs/ARCHITECTURE.md | 4 +-- docs/FUNCTIONAL.md | 5 ++-- docs/FUNCTIONAL_ru.md | 5 ++-- ui/e2e/ingame-ux.spec.ts | 47 +++++++++++++++++++++++++++++++--- ui/src/game/CheckScreen.svelte | 18 ++++++++++--- ui/src/game/Game.svelte | 8 ++++-- 6 files changed, 71 insertions(+), 16 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 610c987..25de66e 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -124,8 +124,8 @@ dropped). Horizontal scaling is explicit future work. switch and no device-local create paths. The machine still tracks reachability there, though: a connection lost **inside an online game** is surfaced on **every platform**, driven off the machine's confirmed-offline state (`netState.offline`, not `offlineMode.active`) — the game screen shows a - *connection lost* banner and **freezes** the tray, the move controls, the add-friend/block controls and - the chat/dictionary entry (a started move stays a draft, re-committed by the player on reconnect), and + *connection lost* banner, **freezes** the tray and move controls, and hides the resign, add-friend/block + and chat/dictionary controls (a started move stays a draft, re-committed by the player on reconnect), and the word-check tool falls back to the game's pinned on-device dictionary (`ui/src/lib/dict/check.ts`, exact when that dawg is cached, else *unavailable*) with its network-only complaint and external look-up hidden. diff --git a/docs/FUNCTIONAL.md b/docs/FUNCTIONAL.md index f5a7951..1521ed4 100644 --- a/docs/FUNCTIONAL.md +++ b/docs/FUNCTIONAL.md @@ -328,8 +328,9 @@ offline, so you are never interrupted for a hiccup. **Losing the connection while inside an online game** is surfaced on **every platform, including the Telegram/VK mini-apps** — unlike the offline-play mode above, which is web/native only — because an online game needs the server for every move. A slim *connection lost* banner appears at the top of the -board and the play area **freezes**: the rack, the move controls, the add-friend/block controls and the -chat/dictionary entry all disable, while a move you had started stays on the board as a draft. Nothing +board and the play area **freezes**: the rack and the move controls disable, and the resign, the +add-friend/block and the chat/dictionary controls are hidden, while a move you had started stays on the +board as a draft. Nothing is sent; when the connection returns the banner clears, the controls come back and you commit the move yourself. If you were already in the chat or the dictionary when the drop happened you stay there — chat becomes read-only (send and nudge disable) and the dictionary keeps checking words against the game's diff --git a/docs/FUNCTIONAL_ru.md b/docs/FUNCTIONAL_ru.md index 1d8cf7a..8901aeb 100644 --- a/docs/FUNCTIONAL_ru.md +++ b/docs/FUNCTIONAL_ru.md @@ -332,8 +332,9 @@ e-mail) либо ввод фразы. Активные игры форфейтя **Потеря связи внутри онлайн-партии** показывается на **всех платформах, включая мини-приложения Telegram/VK** — в отличие от офлайн-режима игры выше, который только для веба и нативного приложения, — потому что онлайн-партии сервер нужен на каждый ход. Сверху доски появляется тонкий баннер *связь -потеряна*, и игровая область **замораживается**: рэк, ходовые кнопки, кнопки «в друзья»/«заблокировать» -и вход в чат/словарь отключаются, а начатый ход остаётся на доске черновиком. Ничего не отправляется; +потеряна*, и игровая область **замораживается**: рэк и ходовые кнопки отключаются, а «сдаться», +«в друзья»/«заблокировать» и вход в чат/словарь скрываются; начатый ход остаётся на доске черновиком. +Ничего не отправляется; когда связь возвращается, баннер исчезает, кнопки оживают, и ход отправляешь ты сам. Если связь упала, когда ты уже был в чате или словаре, ты там и остаёшься — чат становится «только для чтения» (отправка и nudge отключаются), а словарь продолжает проверять слова по словарю партии на устройстве. diff --git a/ui/e2e/ingame-ux.spec.ts b/ui/e2e/ingame-ux.spec.ts index 85f005c..2bad7a6 100644 --- a/ui/e2e/ingame-ux.spec.ts +++ b/ui/e2e/ingame-ux.spec.ts @@ -64,13 +64,52 @@ test('online game offline: banner shows, the tray and comms entry freeze, and it expect(n).toBeGreaterThan(0); for (let i = 0; i < n; i++) await expect(tiles.nth(i)).toBeDisabled(); - // The comms entry (💬 — chat + dictionary) is disabled; it lives in the history drawer, so open it. + // The comms entry (💬) and the resign control are HIDDEN offline (like the frozen social controls); + // both live in the history drawer, so open it and assert no action icons remain in its header. await page.locator('.scoreboard').click(); - await expect(page.locator('button:has(.chat-ico)')).toBeDisabled(); + await expect(page.locator('.hhead button.hicon')).toHaveCount(0); - // Recovery: the network returns, the banner clears and the tray is interactive again. + // Recovery: the network returns, the banner clears, the tray is interactive and the comms entry returns. await page.evaluate(() => (window as unknown as { __net: { online(): void } }).__net.online()); await expect(page.locator('.offline-banner')).toHaveCount(0, { timeout: 15000 }); await expect(page.locator('.rack .tile').first()).toBeEnabled(); - await expect(page.locator('button:has(.chat-ico)')).toBeEnabled(); + await expect(page.locator('button:has(.chat-ico)')).toBeVisible(); +}); + +test('online game offline: the dictionary still accepts input and checks (variant seeded from cache)', async ({ page }) => { + await page.goto('/'); + await page.getByRole('button', { name: /guest/i }).click(); + // A Russian (erudit_ru — first in the mock's variant preferences) game, so the offline dictionary is + // exercised with a non-Latin alphabet that differs from the panel's default 'scrabble_en'. The panel + // seeds its variant + pinned version from the cached game; the mock resolves gameState even offline + // (no kill switch), so on the real backend — where that fetch fails offline — the seed is what keeps + // the input and the dawg fallback working. This guards the offline dictionary flow end-to-end. + await page.getByRole('button', { name: /🎲/ }).click(); + await page.getByRole('button', { name: 'Random player' }).click(); + await page.locator('.variant').first().click(); + await page.getByRole('button', { name: /Start game/i }).click(); + await page.evaluate(() => (window as unknown as { __mock: { joinOpponent(): void } }).__mock.joinOpponent()); + await expect(page.getByText('Robo')).toBeVisible(); + + // Go offline, then open the dictionary directly (its in-game entry is hidden offline) so CheckScreen + // mounts with no network and must seed the variant/version from the cached game, not a failed fetch. + await page.evaluate(() => (window as unknown as { __net: { offline(): void } }).__net.offline()); + await expect(page.locator('.offline-banner')).toBeVisible({ timeout: 15000 }); + await page.evaluate(() => { + const route = location.hash.slice(1); // /game/ + (window as unknown as { __router: { navigate(p: string): void } }).__router.navigate(route + '/check'); + }); + + // The check input keeps the Cyrillic word (the variant is known) and the Check button is usable — + // the outcome the cache seed guarantees on the real backend where the offline gameState fetch fails. + const input = page.locator('.check input'); + await expect(input).toBeVisible(); + await input.fill('СЛОВО'); + await expect(input).toHaveValue('СЛОВО'); + await expect(page.locator('.check button')).toBeEnabled(); + + // Running the check resolves to a verdict (or the neutral offline note), proving the fallback path + // executes rather than hanging. + await page.locator('.check button').click(); + await expect(page.locator('.verdict')).toBeVisible(); }); diff --git a/ui/src/game/CheckScreen.svelte b/ui/src/game/CheckScreen.svelte index e1b2211..5d4e48f 100644 --- a/ui/src/game/CheckScreen.svelte +++ b/ui/src/game/CheckScreen.svelte @@ -8,6 +8,7 @@ import { alphabetLetters } from '../lib/alphabet'; import { canCheckWord, dictionaryLookupUrl, sanitizeCheckWord } from '../lib/checkword'; import { onExternalLinkClick } from '../lib/links'; + import { getCachedGame } from '../lib/gamecache'; import type { Variant } from '../lib/model'; // Word-check on its own screen: unlimited dictionary lookups, each with a @@ -25,15 +26,24 @@ const checked = new Map(); onMount(async () => { + // Seed the variant + pinned version from the cached game first (present once the board has opened, + // and preloaded for ongoing games): an online game's dictionary must keep working while offline, + // where the gameState call below cannot run. The variant's alphabet is already cached from opening + // the board, so input sanitising and the offline dawg fallback work off the seed alone. + const cached = getCachedGame(id)?.view.game; + if (cached) { + variant = cached.variant; + dictVersion = cached.dictVersion; + } try { - // Include the alphabet so input sanitising + the check accept the variant's letters. Routed - // through gameSource so an offline (local) game resolves its state from the device, not the - // network. + // Refresh over the network (and cache the alphabet on a cold deep-link that skipped the board). const st = await gameSource(id).gameState(id, true); variant = st.game.variant; dictVersion = st.game.dictVersion; } catch (e) { - handleError(e); + // Offline or a transient failure: the cache seed already set variant + version, so only surface + // an error when there was nothing cached to fall back to. + if (!cached) handleError(e); } }); diff --git a/ui/src/game/Game.svelte b/ui/src/game/Game.svelte index dfdd4b2..021945f 100644 --- a/ui/src/game/Game.svelte +++ b/ui/src/game/Game.svelte @@ -1607,6 +1607,10 @@ {:else if view.game.hotseat} + {:else if !netReady} + + {:else} {/if} @@ -1615,8 +1619,8 @@ chat, so its hub is Dictionary-only (CommsHub), and once finished the dictionary closes too — so drop the entry only when a local game is finished; an active local game keeps it for the Dictionary. An online game always keeps it (chat outlives the game). --> - {#if !(gameOver && (view.game.vsAi || view.game.hotseat))} - {/if} From b6af682381eb1e884e740ea85221a626e259bbc0 Mon Sep 17 00:00:00 2001 From: Ilia Denisov Date: Tue, 14 Jul 2026 10:23:42 +0200 Subject: [PATCH 6/7] refactor(payments): one canonical catalog order for storefront, offer, admin; admin active/all toggle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The wallet storefront listed products in creation order — its purchases and its chip-exchange values were unsorted, unlike the admin console and the public offer. Extract the ordering (chip packs first by rouble price, then chip-priced values grouped hints → no-ads → combo → tournament and by chip price) into one comparator, compareCatalogRank over a small rank key, and apply it at all three sites (projectCatalog, projectOfferPricing, SortAdminCatalog) — so the subgroup ranking (valueGroup) and the full order now live in one place. The rewarded "watch for chips" CTA is a wallet-driven element rendered above the packs, so it is unaffected and stays on top. Also add the admin catalog active/all toggle: AdminCatalog takes includeInactive, the console shows active products by default and ?all=1 lists archived ones too (the detail and grant forms keep loading all products). Tests: a storefront canonical-order unit test (reproduced the unsorted bug first); an integration test for the active/all toggle. Existing offer/admin order tests unchanged — behaviour preserved. --- .../templates/pages/catalog.gohtml | 1 + backend/internal/adminconsole/views.go | 3 + .../internal/inttest/catalog_editor_test.go | 33 +++++++++- backend/internal/payments/catalog.go | 5 ++ backend/internal/payments/catalog_admin.go | 24 +++----- backend/internal/payments/catalog_order.go | 61 +++++++++++++++++++ backend/internal/payments/catalog_test.go | 50 +++++++++++++++ backend/internal/payments/offer.go | 20 ++---- .../internal/payments/store_catalog_admin.go | 10 ++- .../internal/server/handlers_admin_catalog.go | 14 +++-- 10 files changed, 180 insertions(+), 41 deletions(-) create mode 100644 backend/internal/payments/catalog_order.go diff --git a/backend/internal/adminconsole/templates/pages/catalog.gohtml b/backend/internal/adminconsole/templates/pages/catalog.gohtml index a738175..42d081b 100644 --- a/backend/internal/adminconsole/templates/pages/catalog.gohtml +++ b/backend/internal/adminconsole/templates/pages/catalog.gohtml @@ -22,6 +22,7 @@

Products

+

Showing {{if .ShowAll}}all products (active + archived) — active only{{else}}active products — show all (incl. archived){{end}}.

diff --git a/backend/internal/adminconsole/views.go b/backend/internal/adminconsole/views.go index cdc8676..d39619d 100644 --- a/backend/internal/adminconsole/views.go +++ b/backend/internal/adminconsole/views.go @@ -677,6 +677,9 @@ type FeedbackDetailView struct { // CatalogView is the product-catalog list page. type CatalogView struct { Products []ProductRow + // ShowAll reports whether archived products are listed alongside active ones (the active/all + // toggle); it drives the toggle link and the list heading. + ShowAll bool } // ProductRow is one product in the catalog list: its composition, prices, the archived flag diff --git a/backend/internal/inttest/catalog_editor_test.go b/backend/internal/inttest/catalog_editor_test.go index 02379a7..12c7666 100644 --- a/backend/internal/inttest/catalog_editor_test.go +++ b/backend/internal/inttest/catalog_editor_test.go @@ -16,7 +16,7 @@ import ( // productByTitle finds a catalog product by its (unique in the test) title. func productByTitle(t *testing.T, pay *payments.Service, title string) payments.AdminProduct { t.Helper() - all, err := pay.AdminCatalog(context.Background()) + all, err := pay.AdminCatalog(context.Background(), true) if err != nil { t.Fatalf("admin catalog: %v", err) } @@ -57,7 +57,7 @@ func TestConsoleCatalogEditor(t *testing.T) { if code, body := consoleDo(h, http.MethodPost, catalog, "title=cat-bad&chips=100&active=true", origin); code != http.StatusOK || !strings.Contains(body, "Invalid product") { t.Fatalf("bad pack = %d, has 'Invalid product' = %v", code, strings.Contains(body, "Invalid product")) } - if _, err := pay.AdminCatalog(ctx); err != nil { + if _, err := pay.AdminCatalog(ctx, true); err != nil { t.Fatalf("catalog: %v", err) } @@ -95,3 +95,32 @@ func TestConsoleCatalogEditor(t *testing.T) { t.Fatalf("delete transacted = %d, has 'Cannot delete' = %v", code, strings.Contains(body, "Cannot delete")) } } + +// TestConsoleCatalogActiveToggle checks the catalog console lists only active products by default and +// includes the archived ones under ?all=1 (the active/all toggle). +func TestConsoleCatalogActiveToggle(t *testing.T) { + srv, _, _ := bannerServer(t) + h := srv.Handler() + const origin = "http://admin.test" + const catalog = "http://admin.test/_gm/catalog" + + // An active value and an archived one (created without the active flag). + if code, _ := consoleDo(h, http.MethodPost, catalog, "title=toggle-active&hints=5&price_chip=50&active=true", origin); code != http.StatusOK { + t.Fatal("create active failed") + } + if code, _ := consoleDo(h, http.MethodPost, catalog, "title=toggle-archived&hints=9&price_chip=90", origin); code != http.StatusOK { + t.Fatal("create archived failed") + } + + // Default view: active only. + if _, body := consoleDo(h, http.MethodGet, catalog, "", ""); !strings.Contains(body, "toggle-active") || strings.Contains(body, "toggle-archived") { + t.Errorf("default view: active listed=%v, archived listed=%v (want true/false)", + strings.Contains(body, "toggle-active"), strings.Contains(body, "toggle-archived")) + } + + // ?all=1: active and archived. + if _, body := consoleDo(h, http.MethodGet, catalog+"?all=1", "", ""); !strings.Contains(body, "toggle-active") || !strings.Contains(body, "toggle-archived") { + t.Errorf("all view: active listed=%v, archived listed=%v (want true/true)", + strings.Contains(body, "toggle-active"), strings.Contains(body, "toggle-archived")) + } +} diff --git a/backend/internal/payments/catalog.go b/backend/internal/payments/catalog.go index abebfff..46da876 100644 --- a/backend/internal/payments/catalog.go +++ b/backend/internal/payments/catalog.go @@ -38,6 +38,11 @@ const atomChips = "chips" // method are omitted (misconfigured or unavailable there). An untrusted context (empty Kind) has // no method, so only values show; buying is gated server-side regardless. func projectCatalog(entries []catalogEntry, cxt Context) CatalogView { + // Present products in the canonical listing order shared with the offer and the admin console + // (packs first by rouble price, then values grouped hints → no-ads → combo and by chip price); the + // client renders them as received. Ordered in place — the caller passes a fresh loadCatalog result + // it does not reuse. + sortCatalogEntries(entries) var out CatalogView for _, e := range entries { isPack := false diff --git a/backend/internal/payments/catalog_admin.go b/backend/internal/payments/catalog_admin.go index e2d351c..ef4c850 100644 --- a/backend/internal/payments/catalog_admin.go +++ b/backend/internal/payments/catalog_admin.go @@ -1,7 +1,6 @@ package payments import ( - "cmp" "context" "errors" "fmt" @@ -144,10 +143,12 @@ func validateProduct(in ProductInput, sellable bool) error { return nil } -// AdminCatalog lists every product (active and archived) with its composition, prices and whether it -// has been transacted, for the admin editor. Read uncached, straight from the catalog tables. -func (s *Service) AdminCatalog(ctx context.Context) ([]AdminProduct, error) { - return s.store.adminCatalog(ctx) +// AdminCatalog lists products with their composition, prices and whether each has been transacted, +// for the admin editor. includeInactive adds the archived products to the active ones (the console's +// active/all toggle); with it false only active products are returned. Read uncached, straight from +// the catalog tables. +func (s *Service) AdminCatalog(ctx context.Context, includeInactive bool) ([]AdminProduct, error) { + return s.store.adminCatalog(ctx, includeInactive) } // SortAdminCatalog orders an admin catalog list in place the same way the public offer lists products @@ -157,18 +158,7 @@ func (s *Service) AdminCatalog(ctx context.Context) ([]AdminProduct, error) { // products the same as active ones (the admin list shows both). func SortAdminCatalog(products []AdminProduct) { slices.SortStableFunc(products, func(a, b AdminProduct) int { - if pa, pb := adminIsPack(a), adminIsPack(b); pa != pb { - if pa { - return -1 // packs (sales) before values (chip exchange) - } - return 1 - } else if pa { - return cmp.Compare(adminPriceAmount(a, string(SourceDirect), CurrencyRUB), adminPriceAmount(b, string(SourceDirect), CurrencyRUB)) - } - if d := cmp.Compare(adminValueGroup(a), adminValueGroup(b)); d != 0 { - return d - } - return cmp.Compare(adminPriceAmount(a, "", CurrencyChip), adminPriceAmount(b, "", CurrencyChip)) + return compareCatalogRank(adminRank(a), adminRank(b)) }) } diff --git a/backend/internal/payments/catalog_order.go b/backend/internal/payments/catalog_order.go new file mode 100644 index 0000000..4e93e4f --- /dev/null +++ b/backend/internal/payments/catalog_order.go @@ -0,0 +1,61 @@ +package payments + +import ( + "cmp" + "slices" +) + +// catalogRank is the canonical listing key for a catalog product: whether it is a chip pack, its +// value subgroup (see [valueGroup]; unused for a pack) and the minor-unit amount its section sorts by +// (a pack's direct rouble price, a value's chip price; math.MaxInt64 when absent, so a misconfigured +// row sorts last rather than leading). +type catalogRank struct { + pack bool + group int + amount int64 +} + +// compareCatalogRank is the single canonical product order, shared by the storefront ([projectCatalog]), +// the public offer ([projectOfferPricing]) and the admin catalog ([SortAdminCatalog]): chip packs +// first, ascending by rouble price; then chip-priced values grouped hints → no-ads → combo → +// tournament and, within a group, ascending by chip price. A pack's group is unused (all packs share +// one section). Callers use it through [entryRank] / [adminRank], which build the key from each +// product shape, so the subgroup and ordering rules live in exactly one place. +func compareCatalogRank(a, b catalogRank) int { + if a.pack != b.pack { + if a.pack { + return -1 // packs (sales) before values (chip exchange) + } + return 1 + } + if !a.pack { + if d := cmp.Compare(a.group, b.group); d != 0 { + return d + } + } + return cmp.Compare(a.amount, b.amount) +} + +// entryRank builds the canonical rank of a storefront / offer catalog entry. +func entryRank(e catalogEntry) catalogRank { + if isPackEntry(e) { + return catalogRank{pack: true, amount: offerSortAmount(e, string(SourceDirect), CurrencyRUB)} + } + return catalogRank{group: offerValueGroup(e), amount: offerSortAmount(e, "", CurrencyChip)} +} + +// adminRank builds the canonical rank of an admin catalog product. +func adminRank(p AdminProduct) catalogRank { + if adminIsPack(p) { + return catalogRank{pack: true, amount: adminPriceAmount(p, string(SourceDirect), CurrencyRUB)} + } + return catalogRank{group: adminValueGroup(p), amount: adminPriceAmount(p, "", CurrencyChip)} +} + +// sortCatalogEntries orders storefront / offer entries in place into the canonical listing order +// ([compareCatalogRank]). Stable, so equal-keyed products keep their incoming (creation) order. +func sortCatalogEntries(entries []catalogEntry) { + slices.SortStableFunc(entries, func(a, b catalogEntry) int { + return compareCatalogRank(entryRank(a), entryRank(b)) + }) +} diff --git a/backend/internal/payments/catalog_test.go b/backend/internal/payments/catalog_test.go index 132fa9a..d751857 100644 --- a/backend/internal/payments/catalog_test.go +++ b/backend/internal/payments/catalog_test.go @@ -135,6 +135,56 @@ func TestProjectCatalog_Empty(t *testing.T) { } } +// TestProjectCatalog_CanonicalOrder checks the storefront lists products in the shared canonical order +// (compareCatalogRank): chip packs first ascending by rouble price, then chip-priced values grouped +// hints → no-ads → combo and ascending by chip price — the same order as the offer and the admin +// console, regardless of catalog creation order. +func TestProjectCatalog_CanonicalOrder(t *testing.T) { + pack := func(title string, rub int64) catalogEntry { + return catalogEntry{ + id: uuid.New(), + title: title, + atoms: []atomQty{{atomType: atomChips, quantity: 1}}, + prices: []priceRow{{method: "direct", currency: CurrencyRUB, amount: rub}}, + } + } + value := func(title string, chips int64, atoms ...string) catalogEntry { + e := catalogEntry{id: uuid.New(), title: title, prices: []priceRow{{method: "", currency: CurrencyChip, amount: chips}}} + for _, a := range atoms { + e.atoms = append(e.atoms, atomQty{atomType: a, quantity: 1}) + } + return e + } + // Deliberately shuffled on input; the projection must impose the canonical order. + entries := []catalogEntry{ + pack("packDear", 30000), + value("bundle", 500, "hints", "noads_days"), + pack("packCheap", 10000), + value("adsOnly", 150, "noads_days"), + value("hintsBig", 200, "hints"), + value("hintsSmall", 50, "hints"), + } + got := projectCatalog(entries, Context{Kind: SourceDirect}) + want := []string{"packCheap", "packDear", "hintsSmall", "hintsBig", "adsOnly", "bundle"} + if len(got.Products) != len(want) { + t.Fatalf("projected %d products, want %d", len(got.Products), len(want)) + } + for i, p := range got.Products { + if p.Title != want[i] { + t.Fatalf("order[%d] = %q, want %q (full: %v)", i, p.Title, want[i], productTitles(got.Products)) + } + } +} + +// productTitles extracts the projected product titles for a failure message. +func productTitles(products []CatalogProduct) []string { + out := make([]string, len(products)) + for i, p := range products { + out[i] = p.Title + } + return out +} + // TestSortAdminCatalog checks the admin list is ordered like the public offer: chip packs first, // ascending by rouble price; then values, grouped (hints only -> no-ads only -> no-ads + hints) and // ascending by chip price within a group. Stable and applied to active + archived alike. diff --git a/backend/internal/payments/offer.go b/backend/internal/payments/offer.go index f4c6392..c89b36e 100644 --- a/backend/internal/payments/offer.go +++ b/backend/internal/payments/offer.go @@ -1,7 +1,6 @@ package payments import ( - "cmp" "context" "fmt" "math" @@ -60,8 +59,13 @@ func (s *Service) buildOfferPricing(ctx context.Context) (string, error) { // omitted. Amounts are rendered through [Money] so no floating point ever reaches the page (roubles // show kopecks as "200.00", whole-unit rails as integers); a missing rail price shows an em dash. func projectOfferPricing(entries []catalogEntry) string { + // Order the whole catalog once by the shared canonical rank, then split it into the two offer + // tables (packs first, then the chip-exchange values); each keeps that order. Sort a copy so the + // caller's slice is left untouched. + sorted := slices.Clone(entries) + sortCatalogEntries(sorted) var packs, values []catalogEntry - for _, e := range entries { + for _, e := range sorted { if isPackEntry(e) { packs = append(packs, e) } else { @@ -69,18 +73,6 @@ func projectOfferPricing(entries []catalogEntry) string { } } - // Packs: ascending by the rouble price (the offer's base currency); a pack with no rouble price - // sorts last. Values: by group, then ascending chip price. Stable, so the catalog order breaks ties. - slices.SortStableFunc(packs, func(a, b catalogEntry) int { - return cmp.Compare(offerSortAmount(a, string(SourceDirect), CurrencyRUB), offerSortAmount(b, string(SourceDirect), CurrencyRUB)) - }) - slices.SortStableFunc(values, func(a, b catalogEntry) int { - if d := cmp.Compare(offerValueGroup(a), offerValueGroup(b)); d != 0 { - return d - } - return cmp.Compare(offerSortAmount(a, "", CurrencyChip), offerSortAmount(b, "", CurrencyChip)) - }) - var b strings.Builder if len(packs) > 0 { b.WriteString("Приобретение внутриигровой валюты «Фишка»:\n\n") diff --git a/backend/internal/payments/store_catalog_admin.go b/backend/internal/payments/store_catalog_admin.go index c63f8c1..57a5ffe 100644 --- a/backend/internal/payments/store_catalog_admin.go +++ b/backend/internal/payments/store_catalog_admin.go @@ -19,11 +19,17 @@ import ( // row references — it must be archived instead, to keep the append-only ledger resolvable. var ErrProductTransacted = errors.New("payments: product has transactions; archive instead of delete") -// adminCatalog lists every product (active and archived) with its atoms, prices and transacted flag. -func (s *Store) adminCatalog(ctx context.Context) ([]AdminProduct, error) { +// adminCatalog lists products with their atoms, prices and transacted flag. includeInactive adds the +// archived products to the active ones; with it false only active products are returned. +func (s *Store) adminCatalog(ctx context.Context, includeInactive bool) ([]AdminProduct, error) { + where := table.Product.Active.IS_TRUE() + if includeInactive { + where = postgres.Bool(true) + } var prods []model.Product if err := postgres.SELECT(table.Product.AllColumns). FROM(table.Product). + WHERE(where). ORDER_BY(table.Product.CreatedAt.ASC()). QueryContext(ctx, s.db, &prods); err != nil { return nil, fmt.Errorf("payments: admin list products: %w", err) diff --git a/backend/internal/server/handlers_admin_catalog.go b/backend/internal/server/handlers_admin_catalog.go index 9912d08..732d72f 100644 --- a/backend/internal/server/handlers_admin_catalog.go +++ b/backend/internal/server/handlers_admin_catalog.go @@ -33,10 +33,12 @@ var priceFields = []struct { {"price_chip", "", payments.CurrencyChip}, } -// consoleCatalog lists every product (active and archived) with its composition, prices, transacted -// flag, and the inline create form. +// consoleCatalog lists the catalog products with their composition, prices, transacted flag, and the +// inline create form. It shows active products by default; ?all=1 also lists the archived ones (the +// active/all toggle). func (s *Server) consoleCatalog(c *gin.Context) { - products, err := s.payments.AdminCatalog(c.Request.Context()) + showAll := c.Query("all") == "1" + products, err := s.payments.AdminCatalog(c.Request.Context(), showAll) if err != nil { s.consoleError(c, err) return @@ -44,7 +46,7 @@ func (s *Server) consoleCatalog(c *gin.Context) { // Order the list like the public offer: sales (chip packs) first, then the chip-exchange values, // grouped and price-sorted the same way, so the console mirrors what a buyer sees. payments.SortAdminCatalog(products) - var view adminconsole.CatalogView + view := adminconsole.CatalogView{ShowAll: showAll} for _, p := range products { view.Products = append(view.Products, catalogRow(p)) } @@ -69,7 +71,7 @@ func (s *Server) consoleCatalogDetail(c *gin.Context) { if !ok { return } - products, err := s.payments.AdminCatalog(c.Request.Context()) + products, err := s.payments.AdminCatalog(c.Request.Context(), true) // include archived: the detail form edits any product if err != nil { s.consoleError(c, err) return @@ -242,7 +244,7 @@ func (s *Server) consoleGrantProduct(c *gin.Context) { // bundles, including archived ones — chips and tournament products are excluded). func (s *Server) grantForm(ctx context.Context) adminconsole.GrantFormView { fv := adminconsole.GrantFormView{Present: true, Origins: []string{"direct", "vk", "telegram"}} - products, err := s.payments.AdminCatalog(ctx) + products, err := s.payments.AdminCatalog(ctx, true) if err != nil { return fv } From eb7fa984268bd560ec184cd919dd4ae4299bd698 Mon Sep 17 00:00:00 2001 From: Ilia Denisov Date: Tue, 14 Jul 2026 10:40:27 +0200 Subject: [PATCH 7/7] feat(payments): edit the rewarded-ads config from the admin catalog page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The "watch for chips" rewarded payout and its per-day / per-hour caps live in the shared payments.config row and had no admin surface — they could only be changed by SQL, contrary to D32 (the rewarded rate is meant to be admin-configurable). Add a "Rewarded ads" form on the /_gm/catalog page: RewardConfig / SetRewardConfig on the service (non-negative validated), a setRewardConfig store writer (the singleton config row), the consoleSetReward handler + POST /_gm/catalog/reward route, and the form pre-filled from the current config. No migration — the columns already exist. The reward rate is a config value, not a sellable catalog atom (so a "no-ads forever" style product is still out of scope by D32/D33). Test: an integration test sets the config, checks the page pre-fill, and refuses a negative value. --- .../templates/pages/catalog.gohtml | 9 +++++++ backend/internal/adminconsole/views.go | 6 +++++ .../internal/inttest/catalog_editor_test.go | 27 +++++++++++++++++++ backend/internal/payments/service_intake.go | 16 +++++++++++ backend/internal/payments/store_intake.go | 12 +++++++++ .../internal/server/handlers_admin_catalog.go | 21 ++++++++++++++- .../internal/server/handlers_admin_console.go | 1 + docs/PAYMENTS_DECISIONS_ru.md | 4 ++- 8 files changed, 94 insertions(+), 2 deletions(-) diff --git a/backend/internal/adminconsole/templates/pages/catalog.gohtml b/backend/internal/adminconsole/templates/pages/catalog.gohtml index 42d081b..2c94452 100644 --- a/backend/internal/adminconsole/templates/pages/catalog.gohtml +++ b/backend/internal/adminconsole/templates/pages/catalog.gohtml @@ -21,6 +21,15 @@
+

Rewarded ads (watch for chips)

+

The chips a player earns per rewarded-video view (VK only), plus the per-day and per-hour caps that bound free chips — 0 payout turns rewarded off. This is the shared reward config, not a product.

+
+ + + +
+ +

Products

Showing {{if .ShowAll}}all products (active + archived) — active only{{else}}active products — show all (incl. archived){{end}}.

TitleStatusAtomsPrices
diff --git a/backend/internal/adminconsole/views.go b/backend/internal/adminconsole/views.go index d39619d..c60e6f3 100644 --- a/backend/internal/adminconsole/views.go +++ b/backend/internal/adminconsole/views.go @@ -680,6 +680,12 @@ type CatalogView struct { // ShowAll reports whether archived products are listed alongside active ones (the active/all // toggle); it drives the toggle link and the list heading. ShowAll bool + // RewardPayout / RewardDailyCap / RewardHourlyCap are the rewarded-video config (chips earned per + // view and the per-day / per-hour anti-abuse caps), shown in and edited from the page's + // rewarded-ads form. A 0 payout means rewarded is inert. + RewardPayout int + RewardDailyCap int + RewardHourlyCap int } // ProductRow is one product in the catalog list: its composition, prices, the archived flag diff --git a/backend/internal/inttest/catalog_editor_test.go b/backend/internal/inttest/catalog_editor_test.go index 12c7666..187baf6 100644 --- a/backend/internal/inttest/catalog_editor_test.go +++ b/backend/internal/inttest/catalog_editor_test.go @@ -124,3 +124,30 @@ func TestConsoleCatalogActiveToggle(t *testing.T) { strings.Contains(body, "toggle-active"), strings.Contains(body, "toggle-archived")) } } + +// TestConsoleRewardConfig checks the rewarded-ads config form on the catalog page: a POST updates the +// payout and caps, the page pre-fills the current values, and a negative value is refused. +func TestConsoleRewardConfig(t *testing.T) { + srv, _, pay := bannerServer(t) + h := srv.Handler() + const origin = "http://admin.test" + const reward = "http://admin.test/_gm/catalog/reward" + + // Set the payout and caps. + if code, body := consoleDo(h, http.MethodPost, reward, "reward_payout=7&reward_daily=40&reward_hourly=9", origin); code != http.StatusOK || !strings.Contains(body, "Saved") { + t.Fatalf("set reward = %d, has 'Saved' = %v", code, strings.Contains(body, "Saved")) + } + if payout, daily, hourly, err := pay.RewardConfig(context.Background()); err != nil || payout != 7 || daily != 40 || hourly != 9 { + t.Fatalf("reward config = %d/%d/%d (err %v), want 7/40/9", payout, daily, hourly, err) + } + + // The catalog page renders the form pre-filled with the current payout. + if _, body := consoleDo(h, http.MethodGet, "http://admin.test/_gm/catalog", "", ""); !strings.Contains(body, "reward_payout") || !strings.Contains(body, `value="7"`) { + t.Error("catalog page did not render the reward form with the current payout") + } + + // A negative value is refused (the service validates non-negativity). + if code, body := consoleDo(h, http.MethodPost, reward, "reward_payout=-1", origin); code != http.StatusOK || !strings.Contains(body, "non-negative") { + t.Errorf("negative payout = %d, has 'non-negative' = %v", code, strings.Contains(body, "non-negative")) + } +} diff --git a/backend/internal/payments/service_intake.go b/backend/internal/payments/service_intake.go index 2f9bedc..cf65f3e 100644 --- a/backend/internal/payments/service_intake.go +++ b/backend/internal/payments/service_intake.go @@ -157,6 +157,22 @@ func (s *Service) RewardPayout(ctx context.Context, cxt Context, present []Sourc return payout, err } +// RewardConfig reads the rewarded-video config for the admin editor: the payout (chips per view) and +// the per-day and per-hour caps. +func (s *Service) RewardConfig(ctx context.Context) (payout, dailyCap, hourlyCap int, err error) { + return s.store.rewardConfig(ctx) +} + +// SetRewardConfig updates the rewarded-video config (the payout and the two caps). All three must be +// non-negative; a 0 payout leaves rewarded inert. It is not a catalog product, so it does not mark the +// offer stale. +func (s *Service) SetRewardConfig(ctx context.Context, payout, dailyCap, hourlyCap int) error { + if payout < 0 || dailyCap < 0 || hourlyCap < 0 { + return errors.New("payments: reward payout and caps must be non-negative") + } + return s.store.setRewardConfig(ctx, payout, dailyCap, hourlyCap) +} + // CreditReward credits a rewarded-video view's chips to the VK segment, client-attested (VK Mini App // ads expose no server verify — the client's watch result is trusted for an honest user; a forger who // skips the ad and calls the endpoint is bounded by the config daily cap). It is idempotent on the diff --git a/backend/internal/payments/store_intake.go b/backend/internal/payments/store_intake.go index 3a219dd..b435226 100644 --- a/backend/internal/payments/store_intake.go +++ b/backend/internal/payments/store_intake.go @@ -413,6 +413,18 @@ func (s *Store) rewardConfig(ctx context.Context) (payout, dailyCap, hourlyCap i return int(cfg.RewardedPayoutChips), int(cfg.RewardDailyCap), int(cfg.RewardHourlyCap), nil } +// setRewardConfig updates the rewarded payout and the per-day and per-hour caps on the singleton +// config row (no WHERE — the table holds exactly one row). Non-negativity is validated by the caller +// and also enforced by the config CHECK constraints. +func (s *Store) setRewardConfig(ctx context.Context, payout, dailyCap, hourlyCap int) error { + if _, err := s.db.ExecContext(ctx, + `UPDATE payments.config SET rewarded_payout_chips=$1, reward_daily_cap=$2, reward_hourly_cap=$3`, + payout, dailyCap, hourlyCap); err != nil { + return fmt.Errorf("payments: set reward config: %w", err) + } + return nil +} + // creditReward credits a rewarded-video view's chips to the funded segment, client-attested (VK Mini // App ads expose no server verify). It reads the payout and daily cap from config: a 0 payout // (unconfigured) or a reached cap credits nothing. It is idempotent on the client nonce (dedup on the diff --git a/backend/internal/server/handlers_admin_catalog.go b/backend/internal/server/handlers_admin_catalog.go index 732d72f..a0d7686 100644 --- a/backend/internal/server/handlers_admin_catalog.go +++ b/backend/internal/server/handlers_admin_catalog.go @@ -46,13 +46,32 @@ func (s *Server) consoleCatalog(c *gin.Context) { // Order the list like the public offer: sales (chip packs) first, then the chip-exchange values, // grouped and price-sorted the same way, so the console mirrors what a buyer sees. payments.SortAdminCatalog(products) - view := adminconsole.CatalogView{ShowAll: showAll} + payout, daily, hourly, err := s.payments.RewardConfig(c.Request.Context()) + if err != nil { + s.consoleError(c, err) + return + } + view := adminconsole.CatalogView{ShowAll: showAll, RewardPayout: payout, RewardDailyCap: daily, RewardHourlyCap: hourly} for _, p := range products { view.Products = append(view.Products, catalogRow(p)) } s.renderConsole(c, "catalog", "catalog", "Catalog", view) } +// consoleSetReward updates the rewarded-video config (chips per view plus the per-day and per-hour +// caps) from the catalog page's rewarded-ads form. A blank field reads as 0; a negative value is +// refused by the service. +func (s *Server) consoleSetReward(c *gin.Context) { + payout, _ := strconv.Atoi(strings.TrimSpace(c.PostForm("reward_payout"))) + daily, _ := strconv.Atoi(strings.TrimSpace(c.PostForm("reward_daily"))) + hourly, _ := strconv.Atoi(strings.TrimSpace(c.PostForm("reward_hourly"))) + if err := s.payments.SetRewardConfig(c.Request.Context(), payout, daily, hourly); err != nil { + s.renderConsoleMessage(c, "Update failed", err.Error(), catalogBack) + return + } + s.renderConsoleMessage(c, "Saved", "the rewarded-ads config was updated", catalogBack) +} + // catalogRow projects a product into its list row. func catalogRow(p payments.AdminProduct) adminconsole.ProductRow { row := adminconsole.ProductRow{ID: p.ID.String(), Title: p.Title, Active: p.Active, Transacted: p.Transacted} diff --git a/backend/internal/server/handlers_admin_console.go b/backend/internal/server/handlers_admin_console.go index cfb72f9..dcf06c6 100644 --- a/backend/internal/server/handlers_admin_console.go +++ b/backend/internal/server/handlers_admin_console.go @@ -112,6 +112,7 @@ func (s *Server) registerConsole(router *gin.Engine) { if s.payments != nil { gm.GET("/catalog", s.consoleCatalog) gm.POST("/catalog", s.consoleCreateProduct) + gm.POST("/catalog/reward", s.consoleSetReward) gm.GET("/catalog/:id", s.consoleCatalogDetail) gm.POST("/catalog/:id", s.consoleUpdateProduct) gm.POST("/catalog/:id/archive", s.consoleArchiveProduct) diff --git a/docs/PAYMENTS_DECISIONS_ru.md b/docs/PAYMENTS_DECISIONS_ru.md index 5bbab57..089774e 100644 --- a/docs/PAYMENTS_DECISIONS_ru.md +++ b/docs/PAYMENTS_DECISIONS_ru.md @@ -201,7 +201,9 @@ web+PWA / native Android+iOS через Capacitor). Владелец (самоз начисления): Фишки, подсказки, дни-без-рекламы, участие-в-турнире. **Продукт = набор атомов + цена** (по одной ценности или комбо). «Пакет Фишек» — цена **per-метод** (мультивалютная: Голоса/Stars/руб — один продукт, D2). «Ценность за Фишки» — цена в - Фишках (единая). Курсы покупки Фишек и Фишки за rewarded — тоже в каталоге. + Фишках (единая). Курсы покупки Фишек и Фишки за rewarded — тоже в каталоге. (Ставка + rewarded + дневной/часовой потолки — строка общего конфига `payments.config`, правится в + секции «Rewarded ads» на странице каталога админки; это не продаваемый продукт-атом.) - **D33. Стекинг «без рекламы»:** `paid_until[origin] += срок` от `max(now, текущий конец)` (остаток не теряется, «плюсуются» как в документе). «Навсегда» — отдельный вечный флаг (перекрывает сроки). Бонусы «(+50)» — маркетинговая пометка владельца;