Compare commits
53 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f1b8769c89 | |||
| e6277dcd43 | |||
| 37070c3cb7 | |||
| 53d6883ffd | |||
| 93c57b3558 | |||
| 6f00c2f41d | |||
| 79766438a2 | |||
| 6aa5023b24 | |||
| b6f28a2423 | |||
| 508dc870ec | |||
| e3899d4755 | |||
| ae5090b851 | |||
| 0c5d3808d7 | |||
| e32ee9ce68 | |||
| 18db62e19d | |||
| d4e34efa80 | |||
| 12ff6dad86 | |||
| 5a80696fe8 | |||
| d6401bb76c | |||
| e0a5753f1a | |||
| dc946a1faf | |||
| ba57687430 | |||
| 6cb88b28c4 | |||
| 46d569720c | |||
| 9253b1bdca | |||
| 384bd143d0 | |||
| 9d1ca213d6 | |||
| 1f78bb274b | |||
| 81b716569f | |||
| aa330b726e | |||
| d5369a0188 | |||
| 170a6ae9ef | |||
| ef2c2d1eb9 | |||
| 004aca4e97 | |||
| b78ce42922 | |||
| 08c2c5f660 | |||
| 06cc4c1edc | |||
| 90f0424de2 | |||
| c36543e54e | |||
| c5d22fceca | |||
| be1627936f | |||
| 1ba52dd0b4 | |||
| bb0e3e17e5 | |||
| 1ef2bde395 | |||
| 62f66735a3 | |||
| 81680a1d5e | |||
| a393561d79 | |||
| e3e4cedc77 | |||
| deaa7a29c5 | |||
| 91de26d80b | |||
| 6b6362a629 | |||
| 8a06fbc3c7 | |||
| 48b06f4594 |
@@ -31,7 +31,7 @@ on:
|
||||
# unit/integration jobs inherit it. The deploy job overrides it per contour with
|
||||
# vars.TEST_DICT_VERSION (the seed for a fresh volume), see deploy/README.md.
|
||||
env:
|
||||
DICT_VERSION: v1.2.1
|
||||
DICT_VERSION: v1.3.0
|
||||
|
||||
jobs:
|
||||
# changes detects which areas a PR/push touched, so the test jobs can skip when
|
||||
|
||||
@@ -1,96 +1,97 @@
|
||||
# scrabble-game — project guide
|
||||
|
||||
Multiplatform Scrabble game. Read this first every session. The owner drives the
|
||||
project **one stage per session** (tariff constraint), so the repository — not
|
||||
conversation memory — is the source of continuity. Keep it that way.
|
||||
Multiplatform Scrabble game, **in production** at `https://erudit-game.ru`. Read this
|
||||
first every session. The repository — not conversation memory — is the source of
|
||||
continuity; keep it that way.
|
||||
|
||||
## Sources of truth (read before changing behaviour)
|
||||
|
||||
- [`PLAN.md`](PLAN.md) — staged plan + **stage tracker** + per-stage *open
|
||||
details to interview*.
|
||||
- [`PRERELEASE.md`](PRERELEASE.md) — pre-release hardening tracker (phases R1–R7
|
||||
before Stage 18); same per-phase *interview + bake-back* discipline as `PLAN.md`.
|
||||
- [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) — architecture, transport,
|
||||
security, the decision record. Always describes current state.
|
||||
- [`docs/FUNCTIONAL.md`](docs/FUNCTIONAL.md) (+ [`_ru`](docs/FUNCTIONAL_ru.md)
|
||||
mirror) — per-domain user stories. English authoritative.
|
||||
- [`docs/TESTING.md`](docs/TESTING.md) — test layers + the per-stage CI gate.
|
||||
- [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) — architecture, transport, security,
|
||||
the decision record. Always describes the current state.
|
||||
- [`docs/FUNCTIONAL.md`](docs/FUNCTIONAL.md) (+ [`_ru`](docs/FUNCTIONAL_ru.md) mirror)
|
||||
— per-domain user stories. English authoritative.
|
||||
- [`docs/TESTING.md`](docs/TESTING.md) — test layers + the CI gate.
|
||||
- [`docs/UI_DESIGN.md`](docs/UI_DESIGN.md) — the `ui` visual/interaction design system.
|
||||
- [`deploy/README.md`](deploy/README.md) — the deploy contour + the production
|
||||
rollout / rollback runbook.
|
||||
|
||||
## Mandatory per-stage workflow
|
||||
## How we work
|
||||
|
||||
**Start of a stage**
|
||||
1. Read `PLAN.md` (the stage's scope + *open details*) and the relevant `docs/`.
|
||||
2. Analyse what the stage actually requires against the current code.
|
||||
3. **Interview the owner** on every open detail and any fork not already fixed
|
||||
in the plan — do not silently pick borderline decisions. Offer options with
|
||||
brief pros/cons.
|
||||
4. Only then implement, strictly within the stage's scope.
|
||||
|
||||
**End of a stage**
|
||||
1. Bake every new agreement back into `PLAN.md`, `docs/ARCHITECTURE.md`,
|
||||
`docs/FUNCTIONAL.md` (+ `_ru`), the affected service `README`, and Go Doc
|
||||
comments — in the **same** PR. Correct earlier stages' docs/code if a new
|
||||
decision changes them.
|
||||
2. Update the stage tracker; add a line under *Refinements logged during
|
||||
implementation* for any plan deviation.
|
||||
3. Get CI green, then mark the stage done.
|
||||
|
||||
(The `stage-implementation` skill encodes this same loop and can be invoked.)
|
||||
- Inspect the relevant code path and the docs above before changing behaviour.
|
||||
- **Interview the owner on every fork** — do not silently pick borderline decisions;
|
||||
offer options with brief pros/cons.
|
||||
- Smallest correct diff. Prefer compact code; reuse before adding; do not add deps,
|
||||
seams or knobs until they are needed.
|
||||
- **Update or add tests for every functional change**, at the layers
|
||||
`docs/TESTING.md` calls out.
|
||||
- **Bake docs in the same PR**: update `docs/ARCHITECTURE.md`, `docs/FUNCTIONAL.md`
|
||||
(+`_ru`), the affected service `README` and Go Doc comments alongside the change.
|
||||
- Document added packages, types, funcs, consts and vars with Go Doc comments.
|
||||
|
||||
## Conventions
|
||||
|
||||
- All code, comments, identifiers, commits, docs, filenames in **English**.
|
||||
- Chat with the owner follows the user-level `~/.claude/CLAUDE.md` (Russian,
|
||||
the agreed persona and translation rules).
|
||||
- Mirror every point edit of `docs/FUNCTIONAL.md` into `docs/FUNCTIONAL_ru.md`
|
||||
in the same patch (translate only the touched paragraphs).
|
||||
- Prefer compact code; do not add deps, seams or knobs until a stage needs them.
|
||||
Reuse before adding. Document added packages/types/funcs with Go Doc comments.
|
||||
- Update or add tests for every functional change.
|
||||
- Chat with the owner follows the user-level `~/.claude/CLAUDE.md` (Russian, the
|
||||
agreed persona and translation rules).
|
||||
- Mirror every point edit of `docs/FUNCTIONAL.md` into `docs/FUNCTIONAL_ru.md` in the
|
||||
same patch (translate only the touched paragraphs).
|
||||
|
||||
## Branching & CI
|
||||
## Branching, CI & production
|
||||
|
||||
- **Two long-lived branches** (Stage 16 onward): **`development`** is the
|
||||
integration branch; **`master`** is the production trunk. Cut `feature/*`
|
||||
branches **from `development`** and PR them back into it. (Stages 0–15 used
|
||||
`master` as the trunk with `feature/* → master`; the genesis Stage 0 commit is
|
||||
on `master` by necessity.)
|
||||
- A commit to a `feature/*` branch triggers **nothing**. The single workflow
|
||||
`.gitea/workflows/ci.yaml` runs the full suite (`unit` + `integration` + `ui`)
|
||||
on a PR into `development` or `master`, and the gated **`deploy`** job auto-rolls
|
||||
the **test contour** on a PR into — or a push to — `development`
|
||||
(`docker compose up -d --build` on the runner host + a `GET /` probe). A PR into
|
||||
`master` is test-only.
|
||||
- Merge `development → master` only when CI is green; the **prod** deploy is then a
|
||||
**manual** workflow (Stage 18), never automatic. Secrets/variables are prefixed
|
||||
`TEST_` / `PROD_` per contour (Gitea 1.26 has no deployment environments).
|
||||
- After any push, watch the run to green before declaring a stage done — use the
|
||||
ready-made watcher, never an inline poll loop:
|
||||
`python3 ~/.claude/bin/gitea-ci-watch.py` (background). It reads `$GITEA_URL`
|
||||
/ `$GITEA_TOKEN`; `gitea.iliadenisov.ru` is allow-listed in
|
||||
`.claude/settings.json`. Remote: `origin git@gitea.iliadenisov.ru:developer/scrabble-game.git`.
|
||||
- **Two long-lived branches**: **`development`** is the integration branch; **`master`**
|
||||
is the production trunk. Cut `feature/*` from `development` and PR back into it;
|
||||
promote `development → master` via PR when ready to release. Both branches require
|
||||
one approval + the `CI / gate` check.
|
||||
- A commit to a `feature/*` branch triggers nothing. The single workflow
|
||||
`.gitea/workflows/ci.yaml` runs the full suite (`unit` + `integration` + `ui`) on a
|
||||
PR into `development` or `master`, and the gated **`deploy`** job auto-rolls the
|
||||
**test contour** on a PR into — or a push to — `development`
|
||||
(`docker compose up -d --build` on the runner host + landing/SPA/backend probes). A
|
||||
PR into `master` is test-only.
|
||||
- **Production is live on two hosts** (main + the Telegram bot host) and deploys
|
||||
**only manually** (`workflow_dispatch`), never automatically:
|
||||
- **`.gitea/workflows/prod-deploy.yaml`** (`confirm=deploy`, from `master`) builds +
|
||||
pushes the images to the registry, then SSH-deploys both hosts — rolling per
|
||||
service in dependency order, health-gated, **auto-rollback to the previous tag**;
|
||||
a schema migration adds a maintenance window + a consistent `pg_dump`. Four visible
|
||||
jobs: build → deploy-main → deploy-bot → verify.
|
||||
- **`.gitea/workflows/prod-rollback.yaml`** (`confirm=rollback`) re-deploys a prior
|
||||
release (blank `target_version` = the previous deployed version) — image-only,
|
||||
rolling, health-gated.
|
||||
- **Releases are git tags `vX.Y.Z` on `master`**; the deploy stamps `git describe
|
||||
--tags` into the image tag, every binary (`pkg/version` via `-ldflags` → the
|
||||
`service.version` telemetry attribute) and the SPA About screen. Tag the release
|
||||
before deploying.
|
||||
- Hosts are provisioned idempotently by **`deploy/ansible/`**. Per-contour
|
||||
secrets/variables use the `TEST_` / `PROD_` prefix (Gitea 1.26 has no deployment
|
||||
environments). Migrations must be **expand-contract** (backward-compatible) so
|
||||
image rollback stays DB-safe. Full runbook + variable list in `deploy/README.md`.
|
||||
- After any push, merge or deploy, **watch the run to green** before declaring done —
|
||||
use the ready-made watcher (run it in the background), never an inline poll loop:
|
||||
`python3 ~/.claude/bin/gitea-ci-watch.py`. It reads `$GITEA_URL` / `$GITEA_TOKEN`;
|
||||
`gitea.iliadenisov.ru` is allow-listed in `.claude/settings.json`. Remote:
|
||||
`origin git@gitea.iliadenisov.ru:developer/scrabble-game.git`.
|
||||
|
||||
## Stack
|
||||
|
||||
Go 1.26.3, `go.work` monorepo, module paths `scrabble/<name>`. Dependencies are
|
||||
added **when first used** (incremental): backend uses `gin` + `zap` +
|
||||
`pgx`/`go-jet`/`goose`/OTel (added in Stage 1). Client↔gateway is Connect-RPC +
|
||||
FlatBuffers (h2c); gateway↔backend is REST/JSON + `X-User-ID` plus a gRPC
|
||||
server-stream for live events. UI is pure HTML5/CSS on plain Svelte + Vite,
|
||||
packaged to native with Capacitor. Likely no Redis.
|
||||
Go 1.26.3, `go.work` monorepo, module paths `scrabble/<name>`. Backend uses `gin` +
|
||||
`zap` + `pgx`/`go-jet`/`goose`/OTel. Client↔gateway is Connect-RPC + FlatBuffers
|
||||
(h2c); gateway↔backend is REST/JSON + `X-User-ID` plus a gRPC server-stream for live
|
||||
events. UI is pure HTML5/CSS on plain Svelte + Vite, packaged to native with
|
||||
Capacitor. No Redis.
|
||||
|
||||
## Reused engine: `../scrabble-solver` (module `scrabble-solver`, Go 1.26.3)
|
||||
|
||||
Embedded **in-process as a library** — there is no per-game container. Public
|
||||
API to reuse (do not reimplement):
|
||||
Embedded **in-process as a library** (`replace scrabble-solver => ../scrabble-solver`
|
||||
in `go.work`; CI checks out the sibling from
|
||||
`https://gitea.iliadenisov.ru/.../scrabble-solver.git`). There is no per-game
|
||||
container. Public API to reuse (do not reimplement):
|
||||
|
||||
- `scrabble.NewSolver(rs, finder)` → `GenerateMoves(b, r, mode)` (ranked,
|
||||
highest score first), `ValidatePlay(b, dir, tiles)`, `ScorePlay(...)`;
|
||||
`scrabble.Apply(b, m)`; types `Move/Word/Placement/Direction/Mode`
|
||||
- `scrabble.NewSolver(rs, finder)` → `GenerateMoves(b, r, mode)` (ranked, highest
|
||||
score first), `ValidatePlay(b, dir, tiles)`, `ScorePlay(...)`; `scrabble.Apply(b, m)`;
|
||||
types `Move/Word/Placement/Direction/Mode`
|
||||
(`scrabble-solver/scrabble/{solver,move,apply}.go`).
|
||||
- `rules.English() / RussianScrabble() / Erudit()`
|
||||
(`scrabble-solver/rules/rules.go`).
|
||||
- `rules.English() / RussianScrabble() / Erudit()` (`scrabble-solver/rules/rules.go`).
|
||||
- `board.New / Parse / Clone / Transpose`; `rack.New / Add / Remove / Clone`;
|
||||
`selfplay.NewBag / Draw / Len` (bag pattern).
|
||||
- Load committed dictionaries with `dawg.Load(path)` from
|
||||
@@ -99,20 +100,17 @@ API to reuse (do not reimplement):
|
||||
|
||||
Constraints:
|
||||
- Words/tiles are **alphabet-index bytes**, meaningful only with the matching
|
||||
`rules.Ruleset` (`Alphabet.Decode`); blank flag carried separately. **Decode
|
||||
`rules.Ruleset` (`Alphabet.Decode`); the blank flag is carried separately. **Decode
|
||||
to real characters before persisting history** (history must be
|
||||
dictionary-independent — see `docs/ARCHITECTURE.md` §9.1).
|
||||
- The solver's `internal/*` is NOT importable from this sibling module.
|
||||
- **GCG is test-only** in the solver (no public writer) — we ship our own.
|
||||
- Wiring: add `replace scrabble-solver => ../scrabble-solver` to `go.work` in
|
||||
**Stage 2** (when `internal/engine` first imports it), and make CI check out
|
||||
the solver sibling (`https://gitea.iliadenisov.ru/.../scrabble-solver.git`).
|
||||
It uses published `github.com/iliadenisov/{alphabet,dafsa}` (no local replace).
|
||||
- The solver uses published `github.com/iliadenisov/{alphabet,dafsa}` (no local replace).
|
||||
|
||||
## Repository layout
|
||||
|
||||
```
|
||||
go.work # use the existing modules; grows per stage
|
||||
go.work # the go.work monorepo
|
||||
backend/ # module scrabble/backend
|
||||
cmd/backend/ # main: telemetry -> db+migrate -> cache -> server
|
||||
cmd/jetgen/ # dev tool: regenerate go-jet code (throwaway container)
|
||||
@@ -123,12 +121,14 @@ backend/ # module scrabble/backend
|
||||
internal/session/ # opaque tokens, sessions store, cache, service
|
||||
internal/server/ # gin engine, /api/v1 groups, X-User-ID, probes
|
||||
internal/inttest/ # //go:build integration Postgres-backed tests
|
||||
docs/ .gitea/workflows/ PLAN.md CLAUDE.md README.md
|
||||
gateway/ ui/ pkg/ # added by their stages
|
||||
platform/telegram/ # Telegram side-service, two binaries (Stage 9; split in phase TX): cmd/validator (HMAC, no VPN) + cmd/bot (Bot API; dials gateway over reverse mTLS bot-link)
|
||||
loadtest/ # module scrabble/loadtest: the pre-release stress harness (R2)
|
||||
backend/Dockerfile gateway/Dockerfile platform/telegram/Dockerfile loadtest/Dockerfile # multi-stage distroless (Stage 16; loadtest R2); gateway/Dockerfile has the `landing` target (R3), platform/telegram/Dockerfile has `validator`+`bot` targets (TX)
|
||||
deploy/ # docker-compose (per-service limits, R7) + caddy + landing + otelcol (OTLP + docker_stats per-container metrics) + prometheus/tempo/grafana + postgres_exporter
|
||||
gateway/ # module scrabble/gateway: Connect-RPC edge, embeds the SPA
|
||||
ui/ # Svelte + Vite SPA + landing (Node project, not in go.work)
|
||||
pkg/ # shared: telemetry, version, wire/FlatBuffers, proto, mtls
|
||||
platform/telegram/ # Telegram side-service: cmd/validator (HMAC, no VPN) + cmd/bot (Bot API; dials gateway over reverse mTLS bot-link)
|
||||
loadtest/ # module scrabble/loadtest: the load/stress harness
|
||||
docs/ .gitea/workflows/ CLAUDE.md README.md
|
||||
backend/Dockerfile gateway/Dockerfile platform/telegram/Dockerfile loadtest/Dockerfile # multi-stage distroless; gateway/Dockerfile has the `landing` target, platform/telegram/Dockerfile has `validator`+`bot` targets
|
||||
deploy/ # docker-compose (+ prod overlay + bot host) + ansible provisioning + caddy + landing + otelcol (OTLP + docker_stats) + prometheus/tempo/grafana + node_exporter + postgres_exporter; prod-deploy.sh
|
||||
```
|
||||
|
||||
## Build & test
|
||||
@@ -138,20 +138,19 @@ go build ./backend/... # per module ('./...' from the root won't span t
|
||||
go vet ./backend/...
|
||||
gofmt -l . # must print nothing
|
||||
go test -count=1 ./backend/...
|
||||
go build ./platform/telegram/... && go test ./platform/telegram/... # Telegram validator + bot (Stage 9; split in TX)
|
||||
go build ./platform/telegram/... && go test ./platform/telegram/... # Telegram validator + bot
|
||||
go run ./backend/cmd/backend # /healthz, /readyz on :8080
|
||||
|
||||
cd ui && pnpm install && pnpm check && pnpm test:unit && pnpm build # the UI (Stage 7+)
|
||||
cd ui && pnpm install && pnpm check && pnpm test:unit && pnpm build # the UI
|
||||
pnpm start # UI mock mode: lobby -> game, no backend
|
||||
|
||||
docker build -f backend/Dockerfile -t scrabble-backend . # images (Stage 16); gateway embeds the SPA
|
||||
docker build --build-arg DICT_VERSION=v1.3.0 -f backend/Dockerfile -t scrabble-backend . # DICT_VERSION required (no default); gateway embeds the SPA
|
||||
docker build -f gateway/Dockerfile --target gateway -t scrabble-gateway .
|
||||
docker build -f gateway/Dockerfile --target landing -t scrabble-landing . # static landing (R3)
|
||||
docker build -f gateway/Dockerfile --target landing -t scrabble-landing . # static landing
|
||||
docker compose -f deploy/docker-compose.yml config # validate the full contour
|
||||
```
|
||||
|
||||
The `ui` module is a Node project (pnpm), **not** in `go.work`; it is the `ui` job
|
||||
of the single `.gitea/workflows/ci.yaml` (Stage 16 folded the former go-unit /
|
||||
integration / ui-test workflows into it). Committed edge codegen under `ui/src/gen/`
|
||||
The `ui` module is a Node project (pnpm), **not** in `go.work`; it is the `ui` job of
|
||||
the single `.gitea/workflows/ci.yaml`. Committed edge codegen under `ui/src/gen/`
|
||||
(regenerate with `pnpm codegen`); pnpm build-script approval lives in
|
||||
`ui/pnpm-workspace.yaml` (`allowBuilds: esbuild: true`).
|
||||
|
||||
-632
@@ -1,632 +0,0 @@
|
||||
# Pre-release plan — hardening before Stage 18
|
||||
|
||||
Living tracker for the pre-release hardening pass that runs **before Stage 18** (the
|
||||
prod cutover). Same discipline as [`PLAN.md`](PLAN.md): one phase per session,
|
||||
**interview the owner on the open details** at the start of each phase, bake every
|
||||
decision back into `PLAN.md` / `docs/` / the affected `README`s / Go Doc comments in
|
||||
the **same** PR, get CI green, then mark the phase done. Phases run as
|
||||
`feature/* → development` PRs (the Stage 16 branch model); the owner approves+merges.
|
||||
|
||||
**Why now:** the system is feature-complete through Stage 17 and the test contour is
|
||||
green, but there is **no prod data yet** — schema, wire labels and the dictionary
|
||||
layout can still change for free. These phases spend that one-time freedom and harden
|
||||
the edge before prod. Each phase maps back to the owner's raw pre-release TODO list
|
||||
(numbers in the tracker).
|
||||
|
||||
## Phase tracker
|
||||
|
||||
| # | Phase | Raw TODOs | Status |
|
||||
|---|-------|-----------|--------|
|
||||
| R1 | Schema & naming reset | 1 + 10 | **done** |
|
||||
| R2 | Stress harness + contour observability + early run | 9a | **done** |
|
||||
| R3 | Edge hardening | 2 + 8 + 3 | **done** |
|
||||
| R4 | Push enrichment + kill the last poll | 4 + 5 | **done** |
|
||||
| R5 | Bundle slimming | 6 | **done** |
|
||||
| R6 | Refactor + docs reconciliation + de-staging | 7 | **done** |
|
||||
| R7 | Final stress run + tuning | 9b | **done** |
|
||||
| UI | Tab-bar navigation redesign (drop the hamburger) | owner ad-hoc | **done** |
|
||||
| MW | "Multiple words per turn" rule for Russian games (engine v1.1.0) | owner ad-hoc | **done** |
|
||||
| MW2 | Single-word rule connectivity fix: the word must run along its own line through an existing tile (perpendicular-only contact no longer connects); single-tile direction picks the best legal word (engine v1.1.1) | owner ad-hoc | **done** |
|
||||
| MW3 | Graceful replay degradation: a game whose journalled move became illegal under MW2 is closed as a draw (`end_reason='aborted'`) on open instead of erroring, with an impersonal organizer note in the history + GCG (migration `00002`) | owner ad-hoc | **done** |
|
||||
| OW | Open auto-match: enter the game at once and wait inside it (robot after 90–180 s) | owner ad-hoc | **done** |
|
||||
| DA | Dictionary admin: online release-archive upload → word-diff preview → install/activate; versioned dict volume; active version persisted in DB; resident label = release tag | owner ad-hoc | **done** |
|
||||
| AB | Manual account block (admin suspension): permanent/temporary with an editable en+ru reason picklist; a block forfeits the player's active games + cancels their open ones; a backend gate refuses a blocked account with **403 `account_blocked`**; the UI shows a terminal blocked screen and stops all push/poll; manual unblock; temporary blocks self-expire (migration `00003`) | owner ad-hoc | **done** |
|
||||
| AI | Honest AI opponent in quick game: an explicit 🤖 AI / 👤 random selector (AI default); the robot is seated and moves at once; 7-day inactivity loss (the per-turn timeout reused); chat/nudge disabled, no statistics; the opponent is shown as 🤖 everywhere | owner ad-hoc | **done** |
|
||||
| AD | Advertising banner ("ad network"): server-driven weighted campaigns (percent weight + validity window; the perpetual default fills the remainder up to 100%), bilingual messages shown by bot (`service_language`); eligibility = free account + empty hint wallet + no `no_banner` role (guests included); the resolved feed rides `profile.get` with a `notify` `banner` re-poll on eligibility change; `/_gm/banners` admin + global display timings; client smooth-weighted-round-robin rotation + fade-out/gap/fade-in UX. A single `app.load` bootstrap aggregator was considered and **deferred** (see ARCHITECTURE §10). | owner ad-hoc | **done** (PR1 backend+admin, PR2 UI rotation) |
|
||||
| GL | Simultaneous quick-game cap (10): grey "New Game" + a lobby notice at the cap; backend gate on quick enqueue + invitation creation (409 `game_limit_reached`), accepting invitations exempt; `at_game_limit` rides `games.list` | owner ad-hoc | **done** |
|
||||
| CR | In-game chat read receipts: per-message `unread_seats` bitmask (migration `00008`); a per-viewer unread **dot** in the lobby + game header (a nudge counts and clears when its recipient moves); reading = opening the move history (the 💬 fade-blinks twice) or the chat, acked (`chat.read`) only when unread; `chat_read_duration` + `chat_unread_messages` metrics + tracing + the **Scrabble — Messages** Grafana dashboard (follow-up PR); a message to a disguised robot opponent is born read; admin unread-only filter / read column / per-seat read card | owner ad-hoc | **done** |
|
||||
| BX | Asymmetric per-user block + in-game controls: a block now silently suppresses everything **from** the blocked user (chat, nudge, friend requests, invitations are kept but never delivered/surfaced, born-read) while they notice nothing, **without** deleting the friendship (unblock restores it); auto-match excludes a block-related pair (either direction); in-game opponent card gains a ✖️ **block** control (mirroring 🤝, red "Block?" confirm, mutual-hide, struck name + hidden chat composer when blocked); optimistic apply + `user_blocked`/`user_unblocked` event confirm + rollback; admin user card gains **blocks / blocked-by / friends** cross-linked lists. Blocking a disguised-robot opponent is recorded per-game in a separate **`robot_blocks`** table (migration `00011`), keyed on game+seat with the seen name — never the shared robot account — so the matchmaker keeps giving robots; it shows in the blocked list and re-marks the in-game card | owner ad-hoc | **done** |
|
||||
| FM | First-move tile draw (official rules): each seated player draws a tile, the one closest to "A" leads (a blank beats every letter), ties re-drawing until a single leader; **honest per-draw `crypto/rand` entropy**, not the bag seed, so the **record** (`game_setup_draws`, migration `00013`) — not a seed — is the only account of the outcome, kept for future **tournaments** (designed as a discrete per-tile "player N draws" step). Friend/AI draws at create; **auto-match draws at *open*** against a synthetic `uuid.Nil` opponent whose draw rows are back-filled on join, so the opener's seat is fixed up front and the existing open-game pre-move is preserved (no reseating, no play-gating). Admin `/_gm/games/:id` gains the recorded draw list + a simple **step-by-step board replay** (`ReplayTimeline`). | owner ad-hoc | **done** |
|
||||
| SB | Single Telegram bot + per-user variant preferences: the two per-language bots collapse into **one** (drop `accounts.service_language`, `supported_languages`, the `*_EN`/`*_RU` env vars and game-language push routing — the single bot renders in the recipient's `preferred_language`); New Game variant gating moves to a profile **`variant_preferences`** set (default Erudit only, Erudit-first, server-enforced on the caller's auto-match/vs-AI/invitation-create paths, an invited friend may accept any variant); env vars collapse to unsuffixed `TELEGRAM_BOT_TOKEN`/`TELEGRAM_GAME_CHANNEL_ID`/`VITE_TELEGRAM_LINK`/`VITE_TELEGRAM_GAME_CHANNEL_NAME` and `GATEWAY_DEFAULT_SUPPORTED_LANGUAGES` is removed; wire drops `service_language`/`supported_languages` (Session, ValidateInitDataResponse) + the push `language` routing field and adds `variant_preferences` to Profile/UpdateProfile. | owner ad-hoc | **done** |
|
||||
| DV | Dictionary version hygiene: CI + image/compose seed track the current release (`v1.2.1`); a **seed-drift guard** records the flat dir's seed in an authoritative `.seed_version` marker so a bumped build seed on a live volume is ignored (it can't relabel live bytes — which would mis-serve the dictionary + void games pinned to the prior label); `DICT_VERSION` is the fresh-volume seed only, a live contour migrates through the admin console | owner ad-hoc | **done** |
|
||||
| TX | Telegram egress off the main host: split the connector into a home **validator** (Mini App / Login-Widget HMAC, no VPN, no Bot API — so game login no longer depends on Telegram being reachable) and a remote **bot** (Bot API long-poll + `sendMessage`) that holds **no inbound port** and dials the gateway over a reverse **mTLS bot-link** (`pkg/proto/botlink/v1`); the gateway funnels out-of-app push (fire-and-forget, at-most-once) and the backend admin broadcasts (a relay that awaits the bot's ack) down the link. The bot is Telegram-rate-limited; **one bot now**, with seams (a bot registry + `owns_updates` + command ids) for N later; **no webhook** (rejected: one URL per token, adds inbound + a static address). The **unified test contour** runs the split (the bot keeps its VPN sidecar and dials the gateway by its internal name; certs from `deploy/gen-certs.sh`). The **prod** wiring — the bot on a separate host (no VPN), the gateway bot-link port published, `PROD_` certs, an SSH deploy of both hosts together — is **built in Stage 18** (the two-host registry rollout; first cutover pending the `erudit-game.ru` DNS). | owner ad-hoc | **done** (code + test contour; prod wiring built — Stage 18) |
|
||||
| AG | Anti-abuse IP ban + honeypot/honeytoken (prod-only): a fail2ban-style in-memory `ratelimit.Banlist` keyed by client IP, fed by sustained rate-limiter rejections (the IP-keyed public/email/admin classes — the user class stays the soft-flag's concern), a **honeypot** decoy path (the contour caddy tags `/.env`, `/.git`, `/wp-*`, … with `X-Scrabble-Honeypot` and routes them to the gateway), and a **honeytoken** (`GATEWAY_HONEYTOKEN`, a planted bearer). The `abuseGuard` edge middleware refuses a banned IP with **429** before any work — closing the R3 gap that the static SPA/landing was outside the token bucket. Off by default — it keys by the real client IP the shared-NAT test contour does not expose (detection still logs there); enabled in prod via `GATEWAY_ABUSE_BAN_ENABLED`. Operators see + lift bans on the console **Throttled** page; the gateway syncs its active set to the backend (`/api/v1/internal/bans/sync`, `internal/banview`) every 30 s and applies operator unbans. | owner ad-hoc | **done** (code + test contour; ban on in prod via Stage 18 — machinery built, cutover pending DNS) |
|
||||
| CM | Channel-chat moderation + promo bot: a second standalone bot in the bot container answers `/start` with a localized message + a **URL** button into the **main** bot's Mini App (`?startapp`; a `web_app` button would sign initData with the promo token, which the main validator rejects). The **main** bot gates write access in a channel's linked discussion chat. The chat **allows sending by default** and the bot only restricts (Telegram intersects the chat default with the per-user permission, so a per-user grant cannot exceed a deny-by-default group): it **mutes** a member who is not registered or is admin-suspended or holding a new **`chat_muted`** role, and **un-mutes** an eligible one it had muted, for a member currently in the chat (a `getChatMember` guard, since bots cannot list members). Eligibility = `registered AND NOT suspended AND NOT chat_muted` (the game suspension dominates), resolved once in the backend and reached two ways: the bot's `ResolveChatEligibility` on a `chat_member` event over the existing mTLS bot-link, and a backend `chat_access_changed` event → gateway → `ChatGate` command (emitted on block/unblock, a `chat_muted` change, a first registration, or a temporary-block expiry via a sweeper; idempotent). No schema change — `chat_muted` reuses `account_roles`. | owner ad-hoc | **done** |
|
||||
| → | Stage 18 — prod contour deploy | — | see [`PLAN.md`](PLAN.md) |
|
||||
|
||||
## Key findings (these reshaped the raw list — read before starting a phase)
|
||||
|
||||
- **R1 (TODO 1 + 10) is one cheap moment, now.** Squashing the 12 goose migrations is
|
||||
safe precisely because there is no prod data and the contour DB is wiped. Folding the
|
||||
new variant labels (`scrabble_ru`/`scrabble_en`/`erudit_ru`) into that single baseline
|
||||
makes the rename need **no data migration and no back-compat mapping**. Today's labels
|
||||
(`english`/`russian_scrabble`/`erudit`) are persisted in `games.variant`,
|
||||
`game_invitations.variant`, in `pkg/fbs` and the UI — ~100 files, but a mechanical sweep
|
||||
on a clean DB.
|
||||
- **R4 (TODO 4 + 5): the app is already push-first.** Game state refreshes on
|
||||
`your_turn`/`opponent_moved`, the lobby on `notify`, chat on `chat_message`. The **only**
|
||||
genuine periodic server poll is `lobby.poll` (matchmaking, 2.5 s,
|
||||
`ui/src/screens/NewGame.svelte`). What remains is killing that one poll **and** enriching
|
||||
push events to carry payloads so the UI stops re-fetching after each signal.
|
||||
- **R3 (TODO 2): identity forgery is already mitigated.** Identity is always derived from
|
||||
the session (`Authorization: Bearer` → `X-User-ID`); the client cannot inject identity,
|
||||
the backend re-validates resource ownership, Telegram initData is HMAC-checked. The real
|
||||
gaps are a missing **request-body size limit** (cheap DoS) and **invisible rate-limit
|
||||
rejections** (no log/metric/admin view — that is TODO 8). Static landing serving is **not**
|
||||
covered by the gateway token bucket (it only guards `Execute`).
|
||||
- **R6 (TODO 7) scale:** ~431 `Stage N` references across ~104 files (incl. the file name
|
||||
`backend/internal/inttest/stage6_test.go`). Code is the source of truth; `docs/` describe
|
||||
current state; `PLAN.md` keeps the decision history.
|
||||
|
||||
## Locked decisions (owner interview)
|
||||
|
||||
- **Stress test (TODO 9):** **early + final** runs. Driver = **edge protocol** (Connect/FB
|
||||
through the gateway, moves generated by the solver) **plus a separate gateway-hammer**
|
||||
saturation test. Pacing = **realistic (under limits) + saturation (ramp to the knee)**.
|
||||
Resource metrics = **add cAdvisor + postgres_exporter to the contour** (today only
|
||||
Go-runtime metrics exist). The harness stays in the repo for repeats.
|
||||
- **Push (TODO 4 + 5):** **both** — kill `lobby.poll` (use the existing `match_found`, keep
|
||||
poll as the ws-down fallback) **and** enrich push events with payloads.
|
||||
- **Refactor (TODO 7):** **hygiene + structural changes by a reviewed list** —
|
||||
behaviour-preserving, test-gated, contentious items surfaced to the owner before applying.
|
||||
- **Landing (TODO 3):** **separate static container** behind the project caddy
|
||||
(`/` → landing, `/app/` + `/telegram/` → gateway); drop `landing.html` from the gateway
|
||||
`go:embed`.
|
||||
- **Rate-abuse (TODO 8):** metric + Grafana + admin view **plus a conservative auto-flag** —
|
||||
a *soft, reversible* "suspected high-rate" marker for operator review, tunable threshold,
|
||||
**no auto-ban**.
|
||||
- **Anti-abuse IP ban (AG, owner ad-hoc):** a honeypot was considered and rejected as a *DDoS*
|
||||
defence — it detects/deceives but does not shed volumetric load, cannot cover the real
|
||||
endpoints, and a tarpit backfires under flood; volumetric L3/L4 is an upstream/CDN concern,
|
||||
out of scope. The effective layer is a **temporary IP ban** (fail2ban-style) that the honeypot
|
||||
and honeytoken merely *feed*. This does **not** reverse the TODO-8 "no auto-ban": that decision
|
||||
governs the **account** soft-flag (still never a gate); the IP ban is a separate, IP-keyed,
|
||||
**prod-only** layer with an **operator unban** in the console. Decisions: banlist lives in the
|
||||
existing `ratelimit` package (smallest surface); the decoy path list is a **single source of
|
||||
truth in the caddy** (it tags requests with a header — the gateway keeps no second list);
|
||||
bans are in-memory + single-instance (like `ratewatch`), auto-expiring, **plus** an admin
|
||||
console view + manual unban over a bidirectional 30 s sync (operator control = owner's choice).
|
||||
An active-bans Grafana **gauge** was trimmed (the console view + the `gateway_abuse_banned_total`
|
||||
counter cover it) to keep the diff focused.
|
||||
- **Open auto-match (owner ad-hoc):** a quick game **enters a real game at once and waits inside
|
||||
it** (status `open`, the opponent seat empty); a second human searching the same variant+rule
|
||||
joins it, or a robot fills it after a **90 s + random 0–90 s** wait, pushing the in-app
|
||||
**opponent_joined** event. While open, the starter may move on their turn but resign, chat and
|
||||
nudge are disabled, and the lobby + opponent card read "searching for opponent". Matchmaking is
|
||||
now **DB-backed open games** — the in-memory pool, `lobby.poll` and `lobby.cancel` are gone. The
|
||||
schema is edited in the baseline (no prod data); `game_players.account_id` is nullable for the
|
||||
empty seat.
|
||||
- **Telegram egress off-host (TX, owner ad-hoc):** the driver is **removing VPN/Telegram
|
||||
traffic from the main host** (OPSEC / one fewer analysis vector), not only notification
|
||||
resilience. Login is local HMAC, so it stays up regardless of the bot — confirmed in the
|
||||
code and made structural by the split. **Unified topology in code** (validator + bot, the
|
||||
bot dialing the gateway) in **both** contours, differing only in deployment; the test bot
|
||||
keeps its VPN sidecar. Transport = a **reverse gRPC bidi stream, mTLS, bot-dials-gateway**
|
||||
(no inbound/static IP on the bot), reusing the push-stream pattern; **webhook rejected**
|
||||
(one URL per token, adds inbound + a static address). Delivery **at-most-once** (a dropped
|
||||
nudge beats a duplicate). **One bot now**, seams (registry + `owns_updates` + command ids)
|
||||
for N later. **Cert rotation** by a scheduled CI job from a long-lived CA. **Prod deploy by
|
||||
SSH** (pull excluded), the bot rolled **together** with the main app (the bot-link protocol
|
||||
kept back-compatible by one version as the non-atomic-two-host-deploy safety net). The bot
|
||||
is monitored **from the gateway** (connection + ack metrics). The bot-host token-at-rest is
|
||||
**accepted**.
|
||||
|
||||
## Phases
|
||||
|
||||
Each phase: read this tracker + the relevant `docs/`, **interview the owner on the open
|
||||
details below**, implement within scope, then update the tracker + docs/code and get CI
|
||||
green before marking it done.
|
||||
|
||||
### R1 — Schema & naming reset *(TODO 1 + 10)* — first
|
||||
Squash `backend/internal/postgres/migrations/00001..00012` into one `00001_baseline.sql`
|
||||
(method: `pg_dump --schema-only` from a fully-migrated DB → wrap as the goose baseline →
|
||||
prove a fresh migrate yields a schema identical to the 12-migration chain via the
|
||||
integration suite → delete the old files; keep goose). Bake the new variant labels into the
|
||||
baseline. Propagate `scrabble_ru`/`scrabble_en`/`erudit_ru` through the backend
|
||||
(`engine.Variant`/`ParseVariant`, `registry.dictFiles`, the CHECK values), the wire
|
||||
(`pkg/fbs` `variant:string`, regenerate FB) and the UI (`lib/model.ts` union, `variants.ts`,
|
||||
fixtures, premium/alphabet keys, tests); i18n display keys stay display-only. Tidy
|
||||
`../scrabble-dictionary` to a single source→dawg build point and align the dawg artifact
|
||||
names to the new labels (crosses into `../scrabble-solver`'s committed fixtures — keep them
|
||||
byte-identical). After merge, **wipe the contour DB** (drop the volume) so it re-provisions
|
||||
on the next deploy.
|
||||
- Critical files: `backend/internal/postgres/migrations/`,
|
||||
`backend/internal/engine/{engine,registry}.go`, `pkg/fbs/scrabble.fbs`,
|
||||
`ui/src/lib/{model,variants}.ts`, `../scrabble-dictionary/{Makefile,cmd/builddict,…}`.
|
||||
- Open details to interview: the exact dawg filename scheme; whether the dict-repo tidy is
|
||||
one PR or split; how to script the contour DB wipe in the deploy.
|
||||
|
||||
### R2 — Stress harness + contour observability + early run *(TODO 9, part 1)*
|
||||
Build the reusable load harness as a new `loadtest` module in `go.work` (reuses `pkg/fbs`,
|
||||
`connect-go`, and `scrabble-solver` for legal-move generation): a seeder that inserts
|
||||
**1000 guest + 10000 durable** accounts with pre-created sessions (token hashes) directly in
|
||||
the DB and hands the plaintext tokens to the client; a driver that runs N virtual users,
|
||||
each in 3–5 concurrent 2–4-player games, exercising submit-play / pass / exchange / nudge /
|
||||
chat / check-word / draft-move / profile-save through the **edge protocol**, in
|
||||
**realistic** (under rate limits) and **saturation** (ramp) modes; plus a separate
|
||||
**gateway-hammer** that deliberately exceeds limits to verify the limiter holds and measure
|
||||
its cost. Add **cAdvisor + postgres_exporter** to `deploy/docker-compose.yml` and a Grafana
|
||||
resource dashboard. Run the **early pass** against the freshly-wiped contour; produce a
|
||||
**trip report** (logic/concurrency bugs + a resource baseline) that feeds R3 and R6.
|
||||
- Critical files: new `loadtest/`, `deploy/docker-compose.yml`, `deploy/observability/*`,
|
||||
`docs/TESTING.md`.
|
||||
- Open details: the scale ramp steps; the move-selection policy (a mid-ranked solver move
|
||||
for realistic game progress); run duration; the pass/fail bar.
|
||||
|
||||
### R3 — Edge hardening *(TODO 2 + 8 + 3)*
|
||||
Add a **request-body size cap** at the gateway h2c mux / `Execute` (e.g. ~1 MB). Add
|
||||
**rate-limit observability**: a `gateway_rate_limited_total{class}` counter + a structured
|
||||
log per rejection; an **aggregate** Grafana panel (request rate + rejection rate — spikes
|
||||
visible without per-user label cardinality, honouring the Stage 12/17 discipline); an
|
||||
**admin-console view** of recently throttled users/IPs (in-memory ring buffer, single-
|
||||
instance, reset-on-restart, like the `active_users` gauge). Add the **conservative
|
||||
auto-flag**: when a user is *sustained*-throttled past a tunable threshold, set a soft,
|
||||
reversible `account.flagged_high_rate_at` marker (baked into the R1 baseline) surfaced in the
|
||||
admin user list/detail — **no auto-ban**; the operator clears it. Split the **landing** into
|
||||
its own static container (`deploy/` + a Caddyfile route `/` → landing) and drop
|
||||
`landing.html` from the gateway `go:embed`.
|
||||
- Critical files: `gateway/internal/connectsrv/server.go`, `gateway/internal/ratelimit/`,
|
||||
`gateway/internal/connectsrv/metrics.go`, `backend/internal/adminconsole/`,
|
||||
`deploy/caddy/Caddyfile`, `deploy/docker-compose.yml`, `gateway/internal/webui/`.
|
||||
- Open details: the auto-flag threshold/window + whether the marker is persisted vs
|
||||
in-memory; the landing image base (caddy vs nginx).
|
||||
|
||||
### R4 — Push enrichment + kill the last poll *(TODO 4 + 5)*
|
||||
Replace `lobby.poll` with the existing `match_found` push (keep the poll as a ws-down
|
||||
fallback). Enrich `your_turn`/`opponent_moved`/`notify` to carry the state payload so the UI
|
||||
renders from the event without a follow-up `game.state` (removes the lobby↔game nav latency
|
||||
the owner noticed). Wire-contract change: `pkg/fbs` event payloads → backend `notify` emit →
|
||||
UI stream consumers (`ui/src/lib/app.svelte.ts`), with the per-game cache as the landing
|
||||
spot; regenerate FB.
|
||||
- Critical files: `pkg/fbs/scrabble.fbs`, `backend/internal/notify/events.go`,
|
||||
`ui/src/lib/{app.svelte,transport}.ts`, `ui/src/screens/NewGame.svelte`.
|
||||
- Open details: which events carry full vs delta payloads; the fallback-poll cadence when the
|
||||
stream is down.
|
||||
|
||||
### R5 — Bundle slimming *(TODO 6)* — done
|
||||
Analysed the bundle against the 100 KB-gzip budget; **no code slimming was warranted**, and the
|
||||
budget metric was retargeted to measure the app correctly. The build already minifies +
|
||||
tree-shakes; the dominant cost is the Connect/FlatBuffers transport runtime + generated bindings
|
||||
+ the Svelte runtime (≈⅔ of `main`'s source is third-party/generated) — irreducible within scope.
|
||||
**Lazy-loading was rejected**: `bundle-size.mjs` sums every emitted chunk, so code-splitting yields
|
||||
no total-size win and adds request latency (+N gateway fetches on first navigation to a split
|
||||
screen). i18n lazy-load was skipped (the catalogs are a sliver of a Svelte-runtime-dominated shared
|
||||
chunk, and `en` must stay bundled as the `MessageKey` type source + fallback). Instead,
|
||||
`bundle-size.mjs` now measures **per HTML entry**, with three independent gates on the natural chunk
|
||||
boundaries — **app entry ≤ 100 KB, the Svelte+i18n shared chunk ≤ 30 KB, the landing's own chunk
|
||||
≤ 5 KB** — since the app's real payload is its entry chunk plus the shared chunk (≈97 KB), while the
|
||||
landing (≈24 KB) is reported separately and kept minimal. Same CLI + exit-code contract, so the CI
|
||||
step is unchanged.
|
||||
- Critical files: `ui/scripts/bundle-size.mjs`; no app code changed.
|
||||
|
||||
### R6 — Refactor + docs reconciliation + de-staging *(TODO 7)* — done
|
||||
Behaviour-preserving only. Three separable, separately-committed passes: (a) mechanical
|
||||
**de-staging** — remove `Stage N`/`TODO-N` references from code, comments and service
|
||||
READMEs (rename `stage6_test.go`); (b) **docs↔code reconciliation** — reconcile
|
||||
`docs/ARCHITECTURE.md` / `docs/FUNCTIONAL.md`(+`_ru`) against the code-as-truth, fixing drift
|
||||
and Go Doc comments; (c) **structural changes by a reviewed list** — surface a list of
|
||||
proposed optimizations / test-suite consolidations to the owner, apply only the approved,
|
||||
behaviour-preserving, test-gated ones. The full suite + the final stress run (R7) are the
|
||||
regression gate. Incorporates the early-run (R2) bug fixes not already shipped.
|
||||
- Open details: the structural-changes list itself (owner-approved before applying); the test
|
||||
consolidation targets.
|
||||
|
||||
### R7 — Final stress run + tuning *(TODO 9, part 2)* — done
|
||||
Re-run the R2 harness against the final, refactored system on a clean contour; analyse
|
||||
resource consumption across **all** components (gateway, backend, Postgres, the
|
||||
metrics/observability stack, docker log volume) and agree the tuning (pool sizes, rate
|
||||
limits, cache TTLs, container limits, GOMAXPROCS, log levels). Apply the agreed tuning; record
|
||||
the methodology + results in the repo.
|
||||
|
||||
→ **Stage 18** (prod contour) then proceeds per [`PLAN.md`](PLAN.md).
|
||||
|
||||
## Sequencing rationale
|
||||
|
||||
`R1` first (cheapest now; everything builds on the final schema/naming and the stress test
|
||||
must run against it). `R2` builds the harness and runs the **early** pass to surface bugs and
|
||||
a resource baseline that feed `R3` and `R6`. `R3`/`R4`/`R5` harden and improve the system.
|
||||
`R6` (de-stage + reconcile + structural) runs near the end so it sweeps settled code once and
|
||||
benefits from all accumulated bug knowledge. `R7` validates the final system and tunes it.
|
||||
Then Stage 18.
|
||||
|
||||
## Regression-safety discipline (cross-cutting)
|
||||
|
||||
- Every phase is a `feature/* → development` PR; CI (`unit` + `integration` + `ui` behind the
|
||||
`CI / gate` check) must be green before the owner merges; watch the post-merge contour
|
||||
deploy with `gitea-ci-watch.py`.
|
||||
- `R6` structural changes are behaviour-preserving, test-gated, and split from the mechanical
|
||||
sweeps; contentious items are owner-approved first.
|
||||
- The two stress runs (`R2` early, `R7` final) are the system-level regression gate.
|
||||
|
||||
## Verification (per phase)
|
||||
|
||||
- `go build ./<module>/...`, `go vet`, `gofmt -l .` clean, `go test -count=1 ./<module>/...`;
|
||||
UI: `pnpm check && pnpm test:unit && pnpm build`; the integration suite
|
||||
(`-tags integration`) for DB/schema changes; `docker compose config` for deploy changes;
|
||||
green CI on the PR + a healthy contour deploy.
|
||||
- `R1`: prove the squashed baseline yields a schema identical to the 12-migration chain
|
||||
(integration suite on a fresh DB) **before** deleting the old files.
|
||||
- `R2`/`R7`: the harness runs end-to-end against the contour; the trip report lists concrete
|
||||
defects + a resource profile from the Grafana cAdvisor/postgres_exporter panels.
|
||||
|
||||
## Refinements logged during implementation
|
||||
|
||||
- **R1** (interview + implementation):
|
||||
- **Variant labels** `english`/`russian_scrabble`/`erudit` → **`scrabble_en`/`scrabble_ru`/`erudit_ru`**
|
||||
across the backend (`engine.Variant.String`/`ParseVariant`; the `games`/`game_invitations` `variant`
|
||||
CHECK in the baseline; GCG `#lexicon` and the `variant` metric attribute both flow from `String`),
|
||||
the wire (`pkg/fbs` `variant` is a `string` field — values change with **no FlatBuffers regen**) and
|
||||
the UI (`model.ts` union, `variants.ts` records, `codec`/`premiums`/mocks/tests, the admin
|
||||
`dictionary.gohtml`). **Kept:** the Go enum identifiers (`VariantEnglish`…, internal) and the i18n
|
||||
display keys (`new.english`/`new.russian`/`new.erudit`, display-only). `complaints.variant` stays
|
||||
free-text (no CHECK, as before).
|
||||
- **dawg filenames kept descriptive** (`en_sowpods`/`ru_scrabble`/`ru_erudit`) — only the registry's
|
||||
`Variant` key carries the rename, so `registry.go`, the published `scrabble-solver` fixtures and the
|
||||
dictionary release artifact are untouched (decouples the three repos).
|
||||
- **Migrations squashed** 12 → one hand-written `00001_baseline.sql`. Verified by a
|
||||
`pg_dump --schema-only` diff (the chain vs the baseline are **identical** but for the two intended
|
||||
variant-CHECK values) plus the green integration suite. **No data migration** (no production data).
|
||||
- **Done (cross-repo + contour):** the **`scrabble-dictionary` tidy** merged (PR #2) and was re-cut as
|
||||
the **byte-identical `v1.0.1`** release for clean provenance (the backend stays on `v1.0.0` — same
|
||||
bytes, no rewire; the backend pulls a version-pinned release artifact, not master). Post-merge the
|
||||
contour `backend` schema was wiped (`DROP SCHEMA backend CASCADE` + restart, not a volume drop) and
|
||||
re-migrated to the baseline — verified the new variant CHECK (`scrabble_en/scrabble_ru/erudit_ru`),
|
||||
`games`=0 and a clean boot.
|
||||
|
||||
- **R2** (interview + implementation):
|
||||
- **Locked decisions:** game assembly via **invitations** (real path, no robots; not direct game-row
|
||||
inserts); **moderate** ramp **50 → 200 → 500** at 10 min/step; **diagnostic** pass bar (no SLO gate);
|
||||
run as a **one-shot container on `scrabble-internal`** in this PR.
|
||||
- **Harness** = new `scrabble/loadtest` module (`use ./loadtest` + a `replace scrabble/gateway` for the
|
||||
dot-free edge-proto import). It seeds 1000 guest + 10000 durable accounts + sessions **directly in
|
||||
Postgres** (token hash mirrors `backend/internal/session`), drives players over the **edge protocol**,
|
||||
generates **mid-ranked legal moves locally** with the embedded `scrabble-solver` by replaying
|
||||
`game.history` (the edge carries no board — mirrors `engine.ReplayBoard` via the public API), and a
|
||||
**gateway-hammer**. Compact CLI (`run` / `cleanup`), distroless Dockerfile (DAWGs baked), Go unit tests.
|
||||
- **Adding the module broke the other images' builds** — backend/gateway/telegram Dockerfiles reduce the
|
||||
workspace but still referenced `./loadtest` (not in their context); each now also
|
||||
`-dropuse=./loadtest` (backend/telegram additionally `-dropreplace` the gateway replace). Caught by the
|
||||
first deploy run; verified by building all four images.
|
||||
- **Harness payload fixes found by the smoke pass:** the draft DTO's `rack_order` is a string (was sent
|
||||
as `[]` → `bad_request`); the display-name validator forbids digits/colons, so the cleanup marker
|
||||
became a letters-only `Zzloadtest` so `profile.update` resends the seeded name. `chat_not_your_turn` /
|
||||
`nudge_own_turn` are **by-design** turn gates, correctly exercised.
|
||||
- **Observability:** added **cAdvisor + postgres_exporter** + the **Scrabble — Resources** dashboard +
|
||||
two Prometheus jobs. **Finding:** cAdvisor yields only the root cgroup on the contour host (separate
|
||||
XFS `/var/lib/docker` breaks its layer-ID resolution — the existing galaxy deploy has the same limit),
|
||||
so per-container CPU/RSS for the early pass was captured via `docker stats`. **R7:** adopt the otelcol
|
||||
`docker_stats` receiver (already the contrib image) for per-container metrics in Grafana.
|
||||
- **Early run (2026-06-09):** ramped clean to 500 players, no crash/deadlock, cleanup removed all 11000
|
||||
accounts. 1.2 M edge calls, 48 870 plays, 2 798 games finished; the per-user limiter held under the
|
||||
hammer (99.97 % rejected, p99 2 ms). **Top finding:** ~14 % `transport_error` on `game.state` at 500
|
||||
players, under CPU saturation (backend/gateway/Postgres each ~1 core) and amplified by the harness's
|
||||
single shared `http2.Transport`; the harness itself peaked at 86 % of a core on the same host, so the
|
||||
figures are pessimistic. Full trip report in [`../loadtest/REPORT.md`](../loadtest/REPORT.md);
|
||||
it feeds R3 (h2c `MaxConcurrentStreams`/timeouts, body-size cap), R6 and R7 (per-player transports,
|
||||
separate hardware, pool/limit sizing).
|
||||
- **CI:** `./loadtest/...` added to the path filter + vet/build/test; `go.work.sum` carries the new deps.
|
||||
|
||||
- **R3** (interview + implementation):
|
||||
- **Locked decisions:** the flag column lands by **editing the R1 baseline** (+ a contour schema
|
||||
wipe after merge — no migration chain accrues before prod); auto-flag defaults **1000 rejected /
|
||||
10 min** (`BACKEND_HIGHRATE_FLAG_THRESHOLD`/`_WINDOW`, rolling window, set-once, operator clears,
|
||||
no auto-ban); landing image = **caddy:2-alpine**; throttle data flows **gateway → backend** (a
|
||||
30 s per-key summary POST to the new `/api/v1/internal/ratelimit/report`, the existing trusted
|
||||
direction) with the episode window + flag rule in the backend (`internal/ratewatch`); rejection
|
||||
logging = **Warn summary per key per window + Debug per rejection** — a deliberate deviation from
|
||||
the phase's "structured log per rejection" (the R2 hammer would have logged ~522k lines in
|
||||
minutes); all three R2-report tails included (explicit h2c sizing, the session-resolve failure
|
||||
cause at Warn, reviving the admin limiter).
|
||||
- **Body cap:** `GATEWAY_MAX_BODY_BYTES` (default 1 MiB) as both the Connect per-message read limit
|
||||
and an `http.MaxBytesReader` wrap of the public mux; an oversized Execute is `resource_exhausted`.
|
||||
- **Dead config found:** `AdminPerMinute`/`AdminBurst` were never wired — the gateway `/_gm` mount is
|
||||
now 429-guarded per IP ahead of its Basic-Auth. The caddy-fronted contour path stays unlimited
|
||||
(stock caddy has no limiter) — an accepted gap, recorded in `docs/ARCHITECTURE.md` §12.
|
||||
- **Landing split:** a `landing` target in `gateway/Dockerfile` (the UI build stage is shared;
|
||||
identical compose build args keep it one cached build); the gateway drops `landing.html` from the
|
||||
embed and 308-redirects `/` → `/app/`; the contour caddy routes `/app/`, `/telegram/` and the
|
||||
Connect path to the gateway and the catch-all to the landing container; the CI deploy probe now
|
||||
checks both `/` (landing) and `/app/` (gateway).
|
||||
- **Observability:** `gateway_rate_limited_total{class}` (user/public/email/admin, aggregate-only)
|
||||
+ a rate-vs-rejections panel on the Edge/UX dashboard; the admin console gains the **Throttled**
|
||||
page (the in-memory episode window, reset-on-restart like `active_users`, plus the flagged-account
|
||||
queue) and the flag badge / clear action on the user list / card.
|
||||
- The jet regen also restored the previously missing `game_drafts`/`game_hidden` generated models
|
||||
(their tables were added after the last jetgen run; no behaviour change).
|
||||
|
||||
- **R4** (interview + implementation):
|
||||
- **Locked decisions:** **delta-first**, not full snapshots — an event carries only the new move and
|
||||
the UI applies it to its per-game cache, keyed on `move_count` (idempotent + gap-safe: a gap or the
|
||||
actor's own move falls back to a `game.state` + `game.history` refetch). `match_found` /
|
||||
`game_started` carry the recipient's **initial `StateView`** (instant lobby→game); the fallback
|
||||
refetch stays the existing two calls (no merged endpoint); the matchmaking poll runs **only while
|
||||
the stream is down** (2.5 s); **all** UI-state-changing events carry their payload (incl. lobby `notify`).
|
||||
- **Enriched events** (`pkg/fbs` trailing fields — backward-compatible, no FB regen of *values*, only
|
||||
the schema): `opponent_moved` (+`move`/`game`/`bag_len`), `your_turn` (+`move_count`), `match_found`
|
||||
(+`state`), `game_over` (+`game`), `notify` (+`account`/`invitation`/`state`). The pre-R4
|
||||
`opponent_moved` scalars (`seat`/`action`/`score`/`total`) stay for wire back-compat, now redundant
|
||||
with `move`/`game` — slated for the R6 de-stage.
|
||||
- **Encoding placement:** the `notify` package keeps ownership of the FlatBuffers encoding (a new
|
||||
`encode.go` mirrors the gateway transcode but reads wire-agnostic `notify.*` input structs +
|
||||
`engine.MoveRecord`); the game/lobby/social services map their domain types to those structs, so the
|
||||
wire schema stays out of the domain. **Flagged for R6:** this partly duplicates the gateway encoders
|
||||
(different source types) — a candidate consolidation.
|
||||
- **Actor self-fetch killed too** (beyond literal "push"): the `submit_play`/`pass`/`exchange`/`resign`
|
||||
**response** (`MoveResult`) now returns the actor's refilled rack + bag size, so the mover renders the
|
||||
next turn from the response — `Game.svelte`'s `commit`/`pass`/`exchange`/`resign` drop their `await load()`.
|
||||
- **`match_found` enrichment** needs a per-seat initial state: `lobby.GameCreator` gained `InitialState`,
|
||||
and `game.Service.InitialState` builds the `notify.PlayerState` (rack re-encoded to wire indices, the
|
||||
variant alphabet embedded for a first-seen variant).
|
||||
- **UI:** a pure `lib/gamedelta.ts` reducer (`applyMoveDelta` / `applyGameOver` / `seedInitialState`,
|
||||
unit-tested) advances the cache; `app.svelte` seeds it on `match_found` / `game_started`; `Game.svelte`
|
||||
applies the delta (falling back to `load()` while composing, on a gap, or on its own move's new rack);
|
||||
`NewGame.svelte` polls only when `app.streamAlive` is false and guards its teardown so a push-delivered
|
||||
match is not cancelled.
|
||||
- **notify (friends/invitations) scope:** the backend carries the full account / invitation payload on the
|
||||
wire (per "all events → push"); the UI seeds the game cache from `game_started` but keeps its lightweight
|
||||
**authoritative** badge refresh (`refreshNotifications`, on the rare `notify` event + on foreground) rather
|
||||
than adding client-side friend/invitation caches — the per-move hot path is fully de-fetched, which was the
|
||||
goal. Deeper lobby-cache consumption is an easy follow-up.
|
||||
- **No schema change** (no migration); the contour needs no DB wipe. Tests: `notify` FB round-trips +
|
||||
`emitMove` delta + the `gamedelta` reducer; the e2e mock now emits the enriched delta.
|
||||
|
||||
- **R5** (interview + implementation):
|
||||
- **No code slimming — by analysis.** A gzip measure + sourcemap attribution of the real `dist` showed
|
||||
the app bundle is already minified + tree-shaken and dominated by the Connect/FlatBuffers transport
|
||||
runtime + generated FB/PB bindings (≈⅔ of `main`'s source) and the Svelte runtime — all
|
||||
third-party/generated, irreducible within R5's scope. App-authored code carries no hand-trimmable fat.
|
||||
- **Lazy-load rejected** (screens *and* i18n): `bundle-size.mjs` sums every emitted chunk, so
|
||||
code-splitting moves bytes between chunks for **zero total-size win** while adding request latency (+N
|
||||
gateway fetches on first navigation to a split screen). i18n lazy-load additionally buys ≤3 KB (en-only
|
||||
users) at the cost of an async `t()`, and `en` must stay bundled (it is the `MessageKey` type source +
|
||||
fallback). **Chunk-collapsing rejected** too — keeping the near-static Svelte runtime in its own
|
||||
cacheable chunk is the recommended practice (an app deploy then re-busts only `main`, not the runtime),
|
||||
and HTTP/2 makes the extra preload request negligible.
|
||||
- **Metric retargeted to the app.** The two-entry build (`index.html` app + `landing.html`) makes Rollup
|
||||
hoist the code shared by both (Svelte runtime + i18n + `aboutContent`) into one preloaded chunk, so the
|
||||
app actually loads its entry chunk **+ the shared chunk** (≈74 + ≈23 = **≈97 KB**), never `landing.js`
|
||||
(≈1.6 KB). The old script summed all three chunks (98.8 KB), over-counting the app by `landing.js`.
|
||||
`bundle-size.mjs` now parses each built HTML for the JS it eagerly loads and gates three parts
|
||||
independently — **app entry ≤ 100 KB, shared (Svelte+i18n) ≤ 30 KB, landing-own ≤ 5 KB** — reporting the
|
||||
app total (≈97) and landing total (≈24.5). Same CLI + exit-code contract, so the CI step is unchanged.
|
||||
- **No app/source/build change** (`App.svelte`, `lib/i18n/`, `vite.config.ts` untouched); no schema
|
||||
change, no contour wipe. The stale "~82 KB" figure was corrected in `bundle-size.mjs` and `ui/README.md`.
|
||||
|
||||
- **R6** (interview + implementation):
|
||||
- **Locked decisions:** apply **both** wire/code structural changes (**B** + **A**) and **only C1+C2** of
|
||||
the test consolidation (not C3/C5); strip the `*(Stage N)*` tags from **all current-state docs**
|
||||
(ARCHITECTURE / FUNCTIONAL+`_ru` / TESTING / UI_DESIGN), keeping PLAN.md / PRERELEASE.md / CLAUDE.md as
|
||||
history; **split `stage6_test.go`** by domain. The `h2cMaxConcurrentStreams` sizing stays an **R7**
|
||||
concern (tuning, not behaviour-preserving); the R2 early run forced no code fix, so nothing was carried in.
|
||||
- **(a) De-staging:** removed the `Stage N` / `TODO-N` / `(RN)` references across code, comments, service
|
||||
READMEs and the current-state docs, rewording narratives to present tense (no technical content lost).
|
||||
Renamed the only stage-named identifiers (`registerStage8`→`registerSocialOps`,
|
||||
`registerStage11`→`registerLinkOps`) and split `stage6_test.go` (`TestEmailLoginFlow`→`email_test.go`;
|
||||
`TestGuestAutoMatchLeavesNoStats`+`provisionGuest`→`account_test.go`). De-staged the `.fbs`/`.proto`
|
||||
comments and regenerated: only the `.proto`-derived Go docstrings (`*_grpc.pb.go`, `push.pb.go`) changed —
|
||||
flatc strips schema comments, so the FB Go/TS bindings were untouched.
|
||||
- **(b) Reconciliation:** the docs were accurate (each R-phase baked its own); the one drift was a stale
|
||||
"guest-reaping deferred (TODO-3)" note in `ARCHITECTURE.md` §3 — guest reaping is implemented, so the
|
||||
note was replaced with the current behaviour (FUNCTIONAL/TESTING already described it).
|
||||
- **(c) B — dead `opponent_moved` scalars:** removed `seat/action/score/total` from `OpponentMovedEvent`
|
||||
(`pkg/fbs/scrabble.fbs` + the `notify` emit + the round-trip test); regenerated FB Go + TS. No reader
|
||||
used them (the UI codec/mock take `move`/`game`/`bag_len`; the gateway forwards the payload verbatim).
|
||||
A pre-release wire-slot renumber — free with no prod data, no DB change.
|
||||
- **(c) A — shared FB builders:** new `scrabble/pkg/wire` holds the single definition of the nested wire
|
||||
tables (GameView / MoveRecord / StateView / AccountRef / Invitation) shared by the backend `notify`
|
||||
encoder and the gateway `transcode`; both map their own source types to neutral `wire.*` structs and
|
||||
delegate. **Honest tradeoff:** the verbose `Start/Add/End` + reverse-prepend boilerplate is now written
|
||||
once, but the field *set* is still mapped per side, and the new package makes the change net **+~145 LOC**
|
||||
— a single-source / anti-drift win for the fiddly mechanics rather than a line-count cut. Behaviour-
|
||||
preserving: the two sides' field sets were verified identical and the round-trip tests pass unchanged.
|
||||
- **(c) C1+C2 — inttest fixtures:** moved the cross-file service/game fixtures (`newGameService` was used by
|
||||
10 files) into `backend/internal/inttest/helpers.go`; single-file helpers stay local. Pure relocation.
|
||||
- **No schema change → no contour DB wipe.** Regression gate: the full unit + integration + UI suites plus
|
||||
the R7 stress run.
|
||||
|
||||
- **R7** (interview + implementation):
|
||||
- **Locked decisions:** run the harness **same-host** (one-shot container on `scrabble-internal`, capped
|
||||
`--cpus=3` so the contour keeps spare cores); **apply container limits + `GOMAXPROCS` now** (not just a
|
||||
prod recommendation); **replace cAdvisor with the otelcol `docker_stats` receiver** (it resolved only the
|
||||
root cgroup on this host); keep rate-limit / h2c knobs **compiled-in** (change values only if the data
|
||||
demands — it did not).
|
||||
- **Harness refinements (pre-run):** each virtual player builds its **own `edge.Client`** (its own h2c
|
||||
connection for its Subscribe stream + Execute calls) instead of all players sharing one `http2.Transport` —
|
||||
the R2 `transport_error` artifact; and `playTurn` now reports a **finished** game so the player drops it
|
||||
from rotation. Effect, measured: `game.state` `transport_error` 14 % (R2) → **2.49 %**; `game_finished` on
|
||||
chat ≈ 3 900 → **35**.
|
||||
- **Observability:** added the `docker_stats` receiver to `otelcol` (`api_version: "1.44"` — the daemon's
|
||||
minimum is 1.40; the receiver defaults to 1.25 and crash-looped until pinned), mounted the docker socket
|
||||
read-only with `group_add` (the contrib image runs as UID 10001), dropped the cAdvisor service + its
|
||||
Prometheus job, and retargeted the **Scrabble — Resources** dashboard to the docker_stats metric names
|
||||
(`container_cpu_utilization`/100 == cores). Cross-checked against `docker stats` within sampling error.
|
||||
- **Profile (final run, 500 players, limits in force):** the **gateway is the binding constraint** — with
|
||||
one connection per player it bursts into its 2-core cap (the residual 2.49 % `transport_error`); backend
|
||||
~0.85 core and postgres ~1.4 cores had headroom; **tempo reached its 1 GiB cap**; the backend pool sat at
|
||||
its `MaxOpenConns=25` cap (28 backends); docker logs were unbounded (~14 MiB / 30 min on the backend at
|
||||
info). Full write-up in [`../loadtest/REPORT.md`](../loadtest/REPORT.md). *(Superseded in part: a
|
||||
later pass modelling the `game.evaluate` hot path traced the gateway's CPU appetite to
|
||||
**gateway→backend connection churn** — the default 2-idle-connection HTTP transport — not proxying
|
||||
work. Pooling the connections cut peak gateway CPU ~7× (~1.75 → ~0.26 cores at 500 players) and
|
||||
removed the ephemeral-port-exhaustion cliff behind the residual `transport_error`, so the gateway is
|
||||
no longer the binding constraint — postgres is. The 3-core gateway cap below is now generous headroom.)*
|
||||
- **Round-2 tuning (owner-agreed, all in `deploy/docker-compose.yml`, no code change):** gateway **2 → 3
|
||||
cores + `GOMAXPROCS=3`**; tempo memory **1 → 2 GiB**; backend `MAX_OPEN_CONNS` **25 → 40**; a json-file
|
||||
**log-rotation** default (10m × 3) applied contour-wide via a YAML anchor (level stays info).
|
||||
backend/postgres kept at 2 cores / 512 MiB (headroom is cheap on the shared host).
|
||||
- **Validation:** the same gradual ramp on the tuned contour cut `game.state` `transport_error` to **0.72 %**
|
||||
(gateway ~2 cores, now under the 3-core cap, no throttle; tempo ~1.27 GiB, under 2 GiB). A separate
|
||||
**burst** run (a single 100 → 500 jump) pegged the gateway at 3 cores (≈296 % sustained, 9.27 % error),
|
||||
confirming it is **connection-CPU-bound** — a true arrival spike is a **horizontal-scaling** lever, not
|
||||
more cores per node (recorded in the prod-sizing recommendation).
|
||||
- **No schema change → no contour DB wipe.** Bake-back: `loadtest/REPORT.md`, `loadtest/README.md`,
|
||||
`docs/TESTING.md`, the telemetry/observability section of `docs/ARCHITECTURE.md`, the repo-layout line in `CLAUDE.md`.
|
||||
|
||||
- **UI — Tab-bar navigation redesign** (owner ad-hoc, not on the raw TODO list): drop the hamburger
|
||||
`Menu.svelte` everywhere (it fought the Telegram-fullscreen layout, where it had to be re-centred).
|
||||
- **Locked decisions (interview):** the in-Settings sub-nav is a **bottom TabBar with the active tab
|
||||
highlighted** (icon-only); **Export GCG** moves to the left slot of the move-history header (free in a
|
||||
finished game, where 🏁 *leave* does not apply); the lobby **⚙️ badge counts incoming friend requests
|
||||
only** (invitations keep their own lobby section); unread chat is badged on **the score bar and the 💬**.
|
||||
- **What shipped:** a ⚙️ **Settings hub** (`screens/SettingsHub.svelte`) over the existing
|
||||
Settings/Profile/Friends/About bodies and an in-game **comms hub** (`game/CommsHub.svelte`) over
|
||||
chat + dictionary, both with in-place tabs and a fixed back target; the game's menu items relocate into
|
||||
the open move history (🏁 leave / 📤 export + 💬 comms header) and the player cards (🤝 add-friend); a
|
||||
shared **TapConfirm** (`components/TapConfirm.svelte`, `lib/tapconfirm.ts`) — tap → fading ✅ → tap —
|
||||
replaces the Skip/Hint press-and-hold popovers and drives the add-friend confirm. Fixed the move-history
|
||||
"jump" bug (the slid board is now inert and the stage can't scroll, so a swipe up genuinely closes it).
|
||||
`Menu.svelte` + `HoldConfirm.svelte` removed.
|
||||
- **No schema/wire change → no contour DB wipe.** Bake-back: `docs/UI_DESIGN.md`, `docs/FUNCTIONAL.md`
|
||||
(+`_ru`). Regression gate: UI `check` + unit (`tapconfirm`) + build + bundle budget + e2e (Chromium &
|
||||
WebKit), all green.
|
||||
|
||||
- **UI — Merge Exchange/Pass; drop the dead Tournaments tab** (owner ad-hoc, not on the raw TODO
|
||||
list): the lobby's 🏆 *Tournaments* tab was an inert `lobby.soon` toast — removed (the lobby is back
|
||||
to three tabs, matching `docs/FUNCTIONAL.md`). In-game the separate 🥺 *Skip* (pass) tab folds into
|
||||
the 🔄 tab, now **Exchange/Pass**, whose dialog passes when no tile is selected and exchanges when
|
||||
tiles are.
|
||||
- **Decision — a pass is NOT an exchange of zero (verified against the rules + GCG):** the merge is
|
||||
**UI-only**. Pass and exchange stay distinct game actions end-to-end — wire (`GameActionRequest` vs
|
||||
`ExchangeRequest`), engine (`ActionPass` vs `ActionExchange`), and the GCG Poslfit dialect (a pass is
|
||||
a bare `-`, an exchange is `-TILES`). The engine forbids a zero-tile exchange (`ErrNothingToExchange`)
|
||||
and allows an exchange only with a full rack left in the bag (`ErrNotEnoughTilesToExchange`), while a
|
||||
pass is always legal — collapsing them would lose a real distinction. The dialog dispatches the
|
||||
existing `gateway.pass` / `gateway.exchange`.
|
||||
- **What shipped:** `Lobby.svelte` (tab removed); `Game.svelte` (one 🔄 Exchange/Pass tab no longer
|
||||
gated on an empty bag; the dialog disables tile selection while the bag is below a full rack
|
||||
(`bagLen >= RACK_SIZE`), its confirm button reading **Pass without exchanging** / **Exchange N**);
|
||||
i18n (`game.draw` → Exchange/Pass, new `game.passNoExchange`, dropped `game.skip` /
|
||||
`lobby.tournaments` / `lobby.soon`). No backend/wire/history/GCG change.
|
||||
- **No schema/wire change → no contour DB wipe.** Bake-back: `docs/UI_DESIGN.md`, `docs/FUNCTIONAL.md`
|
||||
(+`_ru`). Regression gate: UI `check` + unit + build + bundle budget + e2e (Chromium & WebKit).
|
||||
|
||||
- **AI — Honest AI opponent in quick game** (owner ad-hoc, not on the raw TODO list): a second quick-game
|
||||
opponent the player *knowingly* chooses, distinct from the disguised robot of the random/open path
|
||||
(which is kept as-is). New Game's quick-game mode replaces the "auto-match" subtitle with a two-button
|
||||
selector **🤖 AI / 👤 Random player** (the `.seg`/`.opt` segmented style, AI the default); for AI the
|
||||
move-clock line reads "Loss after 7 days of inactivity" and the "searching" hint is hidden.
|
||||
- **Locked decisions (interview):** AI move is **event-driven** (the robot replies the instant the
|
||||
player's move commits; the 30 s driver is the fallback); AI games **do not touch `account_stats`**
|
||||
(practice, like guests); the **Stage 5 strength logic is reused unchanged** (`playToWin` 40 % from the
|
||||
seed + margin band); **no per-move timeout — a 7-day inactivity loss** instead; the 7-day line lives on
|
||||
the New Game screen (the in-game screen has no move-clock line); chat + nudge **disabled**, word-check
|
||||
kept, add-friend never drawn, opponent shown as **🤖** everywhere.
|
||||
- **The 7-day rule reuses the existing per-turn timeout:** an AI game is created with
|
||||
`turn_timeout_secs = AIInactivityTimeout` (7 days) and the existing timeout sweeper resigns the overdue
|
||||
seat — since the robot moves at once, only the human is ever on the clock, so the per-turn timeout *is*
|
||||
the abandon rule (no new column, no new sweeper).
|
||||
- **One game flag drives everything:** `games.vs_ai` (edited into the R1 baseline — pre-release, so a
|
||||
contour DB wipe after merge). It is set **only** on AI-started games, so a robot-filled random game keeps
|
||||
`vs_ai=false` and the disguised opponent is never revealed; the UI derives 🤖 / the gates **from the flag,
|
||||
never from the opponent account**. New backend path `Matchmaker.StartVsAI` (picks a pooled robot via the
|
||||
existing `Pick`, creates an **active** seated game via `game.Service.Create`, random seat order) — the AI
|
||||
request never enters the open pool, so the open-game reaper never touches it. The robot driver gains a
|
||||
`vs_ai` branch (no sleep, no proactive nudge, zero delay) and a focused `DriveGame`/`TriggerMove` fast
|
||||
path wired from the game service's after-create/after-commit hook (`SetAITrigger`, a func value so the
|
||||
game package never imports the robot package). Chat/nudge gated by a new `social` `VsAI` check
|
||||
(`ErrGameVsAI` → 409 `ai_game`); statistics skipped in `commit` when `vs_ai`.
|
||||
- **Wire:** `EnqueueRequest` += `vs_ai`, `GameView` += `vs_ai` (trailing FB fields, regenerated Go + TS),
|
||||
threaded through the backend DTO, the gateway transcode and the `pkg/wire` + `notify` builders.
|
||||
- **Tests:** `lobby` unit (StartVsAI seats a robot + flags the game; empty pool leaves no game); backend
|
||||
integration (`ai_game_test.go`: active+seated+vs_ai+7-day clock, robot moves immediately, stats skipped,
|
||||
7-day timeout resigns the human, chat/nudge rejected); UI codec round-trip (`vs_ai` on enqueue + game
|
||||
view); e2e (an AI game shows 🤖, no "searching", chat disabled, the dictionary still works) + the
|
||||
existing quick-match e2e updated to pick **Random player** (the default is now AI).
|
||||
- **Schema/wire change → a contour DB wipe** after merge (`DROP SCHEMA backend CASCADE` + restart, the
|
||||
R1/R3 pattern). Bake-back: `docs/ARCHITECTURE.md`, `docs/FUNCTIONAL.md` (+`_ru`), `docs/UI_DESIGN.md`,
|
||||
`backend/README.md`, Go Doc comments.
|
||||
- **Post-review refinements (owner, same PR):** (1) the **GCG export labels the robot seat "AI"** rather
|
||||
than its human-like pool name (`ExportGCG` overrides the name via `accounts.IsRobot`; the in-app 🤖 is
|
||||
unchanged); (2) honest-AI games **emit no `your_turn`** — the robot replies instantly, so the signal
|
||||
would arrive with the move and be pointless; `opponent_moved` still advances the UI; (3) the **admin
|
||||
console surfaces the AI flag** — a **🤖 column** in `/games` and an "AI game" line on the game card
|
||||
(`GameRow`/`GameDetailView` gain `VsAI`); (4) `games_started_total` / `games_abandoned_total` gain a
|
||||
**`vs_ai`** attribute and the Grafana *Game domain* dashboard splits started/abandoned into **human**
|
||||
and **AI** panels.
|
||||
- **Follow-up (separate PR — strategy deviation):** the robot now plays **≈20%** of opening/midgame moves
|
||||
*against* its per-game `playToWin` intent (toward the opposite margin band — a winning robot eases off, a
|
||||
losing one surges ahead), tapering linearly to **0 over the last 14 bag tiles** and **0 once the bag is
|
||||
empty**, so the endgame follows the chosen strategy strictly while earlier outcomes can swing the human's
|
||||
way. Deterministic from the seed (`mix(seed,"deviate",moveCount)`), applied to **both** robot paths via
|
||||
the shared `selectMove`; the per-game intent (and the admin card) is unchanged. Tests: `robot` unit
|
||||
(taper bounds + monotonicity, never-in-endgame, determinism, ~20% distribution). Bake-back:
|
||||
`docs/ARCHITECTURE.md` §7, `docs/FUNCTIONAL.md` (+`_ru`), `backend/README.md`, `PLAN.md` Stage 5.
|
||||
|
||||
- **GL — Simultaneous quick-game cap** (owner ad-hoc, not on the raw TODO list): a player may hold at
|
||||
most **10** active quick games; at the cap the lobby greys **New Game** and shows a plain notice
|
||||
"Вы достигли лимита одновременных партий", both clearing automatically when an active game finishes.
|
||||
- **Locked decisions (interview):** what counts = active **+** open (searching) quick games, **including
|
||||
AI** (`vs_ai`); friend games (invitation-linked) **never** count. The backend gate refuses **all** new-game
|
||||
creation at the cap — `lobby/enqueue` **and** `invitations` — with **409 `game_limit_reached`**; **accepting**
|
||||
an invitation is never gated, so friend games are capped "from the other end". Delivery = a boolean
|
||||
**`at_game_limit`** on the existing `games.list` (no per-event payload: a turn change does not move the count,
|
||||
and the lobby already re-fetches `games.list` on entry + every game event); the first uncached lobby frame
|
||||
defaults the button **enabled** (the backend gate is the authority).
|
||||
- **What shipped:** `game.MaxActiveQuickGames` + `Store/Service.CountActiveQuickGames` (active/open seats, no
|
||||
`game_invitations` row; hidden games still count → a dedicated count, not a filter over the lobby list);
|
||||
`Server.atGameLimit`/`ensureUnderGameLimit` gating `handleEnqueue` + `handleCreateInvitation`;
|
||||
`gameListDTO.at_game_limit`; the FB `GameList` trailing `at_game_limit` (regenerated Go + TS) threaded through
|
||||
the gateway transcode + UI codec; `lib/model` + `lobbycache` snapshot + `Lobby.svelte` (disabled tab + a muted
|
||||
`.limit` notice); i18n `lobby.limitReached` (en authoritative + ru).
|
||||
- **Caveat (logged):** the gate is a pre-check, not transaction-atomic — concurrent creates from one account could
|
||||
momentarily exceed by 1–2 (harmless soft cap; the UI disables the button regardless). Strict atomicity was judged
|
||||
a disproportionate diff across the two create paths.
|
||||
- **No schema change → no contour DB wipe** (only a trailing FB field, no migration). Tests: backend integration
|
||||
(`game_limit_test.go`: count rule + HTTP gate 409 + accept bypass), server unit (error mapping), gateway
|
||||
transcode round-trip, UI codec + lobbycache unit, e2e (`gamelimit.spec.ts`). Bake-back: `docs/FUNCTIONAL.md`
|
||||
(+`_ru`), `docs/ARCHITECTURE.md` §8, `docs/UI_DESIGN.md`, `backend/README.md`.
|
||||
|
||||
- **CM — Channel-chat moderation + promo bot** (owner ad-hoc, not on the raw TODO list):
|
||||
- **Locked decisions (interview):** the promo bot is a **goroutine in `cmd/bot`** (its own token, no
|
||||
bot-link); the moderated chat's default-no-send is configured by a **human** in the group settings (the
|
||||
bot only grants, never `setChatPermissions`); a non-eligible joiner is **left muted silently**; a
|
||||
temporary-suspension expiry is handled by a **backend sweeper** that emits the re-evaluate event; and a new
|
||||
**`chat_muted` role** is a chat-only mute with the **game suspension dominating**
|
||||
(`eligible = registered AND NOT suspended AND NOT chat_muted`).
|
||||
- **Bot API reality (verified against the docs):** a cross-bot Mini App launch must be a **URL button** to the
|
||||
main bot's `t.me/<bot>?startapp` link — a `web_app` button signs initData with the *sending* bot's token,
|
||||
which the main validator rejects — so the promo button reuses the UI's `VITE_TELEGRAM_LINK`. `chat_member`
|
||||
updates arrive **only** when the bot is a chat **admin** with the "Ban users" right (the client label for the
|
||||
Bot API `can_restrict_members`) and `chat_member` is in `allowed_updates`; bots cannot list members but can
|
||||
`getChatMember` a single user, which is the membership guard on the block/unblock path.
|
||||
- **Wire:** `pkg/proto/botlink/v1` gains a `ChatGateCommand` in the `Command` oneof and a unary
|
||||
`ResolveChatEligibility`; the backend gains `notify.KindChatAccessChanged` (no payload, infra-only — never an
|
||||
out-of-app message) and an internal `POST /api/v1/internal/chat-access` resolver; the gateway resolves the
|
||||
join (by external_id) and the event (by user_id) through it and pushes the chat-gate command fire-and-forget
|
||||
(at-most-once, recovered by the next moderation action or a re-join).
|
||||
- **No schema change → no contour DB wipe:** `chat_muted` is a new `account.KnownRoles` entry (the
|
||||
`account_roles` table is data-driven). The suspension-expiry sweeper is a new `account.SuspensionSweeper`
|
||||
(a 1-minute window, idempotent) started in `cmd/backend`, alongside the guest reaper.
|
||||
- **Deploy:** new `TEST_`/`PROD_` `TELEGRAM_PROMO_BOT_TOKEN` (secret), `TELEGRAM_BOT_USERNAME` and
|
||||
`TELEGRAM_CHAT_ID` (variables); the promo link reuses the existing `*_VITE_TELEGRAM_LINK` variable as
|
||||
`TELEGRAM_BOT_LINK`. The bot must be promoted to admin in the real discussion group, and the group default
|
||||
set to no-send, as part of the Stage 18 prod cutover (the test contour exercises the code path).
|
||||
- **Bake-back:** `docs/ARCHITECTURE.md`, `docs/FUNCTIONAL.md` (+`_ru`), `platform/telegram/README.md`,
|
||||
`backend/README.md`, Go Doc comments. Tests: backend resolver truth table + publish on block/unblock/role +
|
||||
the sweeper window (unit + integration); gateway hub `ResolveChatEligibility` + the chat-gate command; bot
|
||||
`chat_member` grant + `ApplyChatGate` getChatMember-guard; promo `/start` localization + URL button; config
|
||||
parsing.
|
||||
- **Post-contour-test fixes (same PR):** a live test drove three corrections. (1) **Strategy
|
||||
inversion (the key one)** — the original "group default no-send, bot grants the eligible" cannot
|
||||
work: Telegram intersects the chat default with each user's permission, so a per-user grant never
|
||||
exceeds a deny-by-default group (the bot set `can_send=true` yet the user still could not write).
|
||||
The group now **allows sending by default** and the bot only **restricts** — it mutes an ineligible
|
||||
member (unregistered / admin-suspended / `chat_muted`) and un-mutes an eligible one it had muted,
|
||||
acting only when the current state differs (idempotent; the bot's own change is skipped by matching
|
||||
the actor id to the bot). A present member in a default-allow group can appear as `restricted` with
|
||||
`is_member`, so the gate reads both. (2) **Join-before-register** — a user who joins before
|
||||
registering is covered by no `chat_member` event, so `ProvisionTelegram` now reports first contact
|
||||
and the Telegram auth handler emits `chat_access_changed` on it. (3) **Observability** — a startup
|
||||
self-check logs whether the bot is an admin-with-restrict in the chat (it caught a misconfigured
|
||||
`TELEGRAM_CHAT_ID` set to a channel id, not the discussion-group id); the per-event trace is at
|
||||
Debug, the actual mute/unmute and warnings at Info.
|
||||
@@ -22,9 +22,8 @@ supports English Scrabble, Russian Scrabble and Эрудит.
|
||||
security, cross-service contracts.
|
||||
- [`docs/FUNCTIONAL.md`](docs/FUNCTIONAL.md) (+ [`_ru`](docs/FUNCTIONAL_ru.md)) —
|
||||
per-domain user stories.
|
||||
- [`docs/TESTING.md`](docs/TESTING.md) — test layers and the per-stage CI gate.
|
||||
- [`PLAN.md`](PLAN.md) — the staged implementation plan and stage tracker.
|
||||
- [`CLAUDE.md`](CLAUDE.md) — project guide and the mandatory per-stage workflow.
|
||||
- [`docs/TESTING.md`](docs/TESTING.md) — test layers and the CI gate.
|
||||
- [`CLAUDE.md`](CLAUDE.md) — project guide and development workflow.
|
||||
|
||||
## Build & test
|
||||
|
||||
@@ -90,7 +89,7 @@ observability stack (OTel Collector → Prometheus + Tempo → Grafana) + a fron
|
||||
services build from multi-stage distroless `*/Dockerfile`.
|
||||
|
||||
```sh
|
||||
docker build -f backend/Dockerfile -t scrabble-backend . # pulls the DAWG release artifact
|
||||
docker build --build-arg DICT_VERSION=v1.3.0 -f backend/Dockerfile -t scrabble-backend . # DICT_VERSION required; pulls that DAWG release artifact
|
||||
docker build -f gateway/Dockerfile -t scrabble-gateway . # node stage builds + embeds the UI
|
||||
docker compose -f deploy/docker-compose.yml config # validate (needs the TEST_/PROD_ env)
|
||||
```
|
||||
|
||||
+6
-4
@@ -7,12 +7,14 @@
|
||||
# (GOPRIVATE), so the build stage needs git and network.
|
||||
#
|
||||
# Build from the repository root so go.work, go.work.sum, pkg/ and backend/ are all
|
||||
# in the Docker context:
|
||||
# docker build -f backend/Dockerfile -t scrabble-backend .
|
||||
# in the Docker context. DICT_VERSION has no default — the caller supplies the
|
||||
# scrabble-dictionary release tag (compose/CI pass it; see deploy/README.md
|
||||
# "Bumping the dictionary version"):
|
||||
# docker build --build-arg DICT_VERSION=v1.3.0 -f backend/Dockerfile -t scrabble-backend .
|
||||
|
||||
# --- dictionary artifact -----------------------------------------------------
|
||||
FROM alpine:3.20 AS dawg
|
||||
ARG DICT_VERSION=v1.2.1
|
||||
ARG DICT_VERSION
|
||||
RUN apk add --no-cache curl tar
|
||||
RUN mkdir -p /dawg \
|
||||
&& curl -fsSL -o /tmp/dawg.tar.gz \
|
||||
@@ -42,7 +44,7 @@ FROM gcr.io/distroless/static-debian12:nonroot
|
||||
# Re-declare the build arg in this stage so it labels the seed dictionary. One
|
||||
# DICT_VERSION drives both the artifact the dawg stage downloads and the version
|
||||
# label the binary pins, so the resident version equals the release tag.
|
||||
ARG DICT_VERSION=v1.2.1
|
||||
ARG DICT_VERSION
|
||||
COPY --from=build /out/backend /usr/local/bin/backend
|
||||
# Own the seed dictionary as the nonroot runtime user (UID 65532): a named volume
|
||||
# mounted at /opt/dawg inherits this ownership on first use, so the admin console
|
||||
|
||||
+1
-1
@@ -228,7 +228,7 @@ internal/banview/ # gateway active-ban mirror: the console's Active IP bans p
|
||||
```sh
|
||||
docker run -d --name scrabble-pg -e POSTGRES_PASSWORD=dev -p 5432:5432 postgres:17-alpine
|
||||
# DAWGs: extract the dictionary release artifact (or point at a local scrabble-solver/dawg):
|
||||
mkdir -p /tmp/dawg && curl -fsSL https://gitea.iliadenisov.ru/developer/scrabble-dictionary/releases/download/v1.2.1/scrabble-dawg-v1.2.1.tar.gz | tar xz -C /tmp/dawg
|
||||
mkdir -p /tmp/dawg && curl -fsSL https://gitea.iliadenisov.ru/developer/scrabble-dictionary/releases/download/v1.3.0/scrabble-dawg-v1.3.0.tar.gz | tar xz -C /tmp/dawg
|
||||
BACKEND_POSTGRES_DSN='postgres://postgres:dev@localhost:5432/postgres?search_path=backend&sslmode=disable' \
|
||||
BACKEND_DICT_DIR=/tmp/dawg \
|
||||
GOPRIVATE='gitea.iliadenisov.ru/*' \
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
// loads the dictionaries into the engine registry, warms the session cache,
|
||||
// constructs the game domain and starts its turn-timeout sweeper, constructs the
|
||||
// lobby and social domains, then serves the HTTP listener with the infrastructure
|
||||
// probes and the /api/v1 route-group skeleton. Domain HTTP endpoints are added
|
||||
// with the gateway in a later stage described in PLAN.md.
|
||||
// probes and the /api/v1 route group, behind which the domains expose their HTTP
|
||||
// endpoints to the gateway.
|
||||
package main
|
||||
|
||||
import (
|
||||
|
||||
@@ -119,6 +119,16 @@ func (s *Store) ProvisionByIdentity(ctx context.Context, kind, externalID string
|
||||
return s.provision(ctx, kind, externalID, provisionSeed{})
|
||||
}
|
||||
|
||||
// ProvisionEmail returns the account owning the email identity externalID, creating
|
||||
// it (unconfirmed) on first contact with browserTZ — the client's detected "±HH:MM"
|
||||
// UTC offset — seeded into its time zone. Like ProvisionByIdentity it is race-safe
|
||||
// and leaves an existing account untouched, so a returning user's saved zone is never
|
||||
// overwritten. The email account is created here (the code-request step), not at the
|
||||
// later login, so this is where its zone is seeded.
|
||||
func (s *Store) ProvisionEmail(ctx context.Context, externalID, browserTZ string) (Account, error) {
|
||||
return s.provision(ctx, KindEmail, externalID, provisionSeed{timeZone: seedZone(browserTZ)})
|
||||
}
|
||||
|
||||
// ProvisionRobot provisions (or finds) the durable account backing a robot pool
|
||||
// member: a KindRobot identity carrying displayName, with chat blocked but friend
|
||||
// requests NOT blocked — a request to a robot is accepted as pending and, since the
|
||||
@@ -160,7 +170,7 @@ func (s *Store) ProvisionRobot(ctx context.Context, externalID, displayName stri
|
||||
// is never overwritten. The created flag lets the auth handler re-evaluate moderated-
|
||||
// chat write access on first registration — the path of a user who joined the chat
|
||||
// before registering, whom no chat_member event covers.
|
||||
func (s *Store) ProvisionTelegram(ctx context.Context, externalID, languageCode, username, firstName string) (Account, bool, error) {
|
||||
func (s *Store) ProvisionTelegram(ctx context.Context, externalID, languageCode, username, firstName, browserTZ string) (Account, bool, error) {
|
||||
// Pre-check whether the identity already exists so the caller can act on first
|
||||
// contact. A race with a concurrent create only over- or under-reports created for
|
||||
// that one call, which the idempotent chat-access re-evaluation tolerates.
|
||||
@@ -169,7 +179,9 @@ func (s *Store) ProvisionTelegram(ctx context.Context, externalID, languageCode,
|
||||
if err != nil && !created {
|
||||
return Account{}, false, err
|
||||
}
|
||||
acc, err := s.provision(ctx, KindTelegram, externalID, telegramSeed(languageCode, username, firstName))
|
||||
seed := telegramSeed(languageCode, username, firstName)
|
||||
seed.timeZone = seedZone(browserTZ)
|
||||
acc, err := s.provision(ctx, KindTelegram, externalID, seed)
|
||||
return acc, created, err
|
||||
}
|
||||
|
||||
@@ -197,20 +209,33 @@ func (s *Store) provision(ctx context.Context, kind, externalID string, seed pro
|
||||
}
|
||||
|
||||
// provisionSeed carries the optional create-time profile seed for a brand-new
|
||||
// account (Telegram first contact). Empty fields fall back to the accounts table
|
||||
// defaults, so an unknown language keeps the 'en' default and an empty name keeps
|
||||
// the ” default.
|
||||
// account (first contact). Empty fields fall back to the accounts table defaults,
|
||||
// so an unknown language keeps the 'en' default, an empty name keeps the ” default
|
||||
// and an empty time zone keeps the 'UTC' default.
|
||||
type provisionSeed struct {
|
||||
preferredLanguage string
|
||||
displayName string
|
||||
timeZone string
|
||||
}
|
||||
|
||||
// seedZone returns browserTZ when it is a well-formed zone to persist at account
|
||||
// creation (a "±HH:MM" offset or a loadable IANA name), else "" so the new account
|
||||
// falls back to the accounts table's 'UTC' default. The client reports the device's
|
||||
// detected offset deterministically; a bad value is dropped rather than guessed at.
|
||||
func seedZone(browserTZ string) string {
|
||||
if validZone(browserTZ) {
|
||||
return browserTZ
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// telegramSeed derives the create-time seed from Telegram launch fields: a
|
||||
// supported preferred language from languageCode (an ISO-639 code, possibly
|
||||
// region-tagged like "ru-RU"), and a display name sanitized from firstName or,
|
||||
// failing that, username (sanitizeDisplayName strips disallowed characters to the
|
||||
// editable format). When neither yields any letters, it falls back to a generated
|
||||
// placeholder in the seeded language (placeholderDisplayName).
|
||||
// region-tagged like "ru-RU"), and a display name. The name precedence is the real
|
||||
// name (firstName, sanitized to the editable format) → the @username taken verbatim
|
||||
// (already a valid handle, only trimmed and length-capped, never character-stripped)
|
||||
// → a generated placeholder in the seeded language (placeholderDisplayName), reached
|
||||
// only when firstName has no usable letters and no username is set.
|
||||
func telegramSeed(languageCode, username, firstName string) provisionSeed {
|
||||
var seed provisionSeed
|
||||
if lang, _, _ := strings.Cut(strings.ToLower(strings.TrimSpace(languageCode)), "-"); lang == "en" || lang == "ru" {
|
||||
@@ -218,7 +243,13 @@ func telegramSeed(languageCode, username, firstName string) provisionSeed {
|
||||
}
|
||||
name := sanitizeDisplayName(firstName)
|
||||
if name == "" {
|
||||
name = sanitizeDisplayName(username)
|
||||
// The real name yielded nothing usable: fall back to the @username verbatim
|
||||
// (Telegram guarantees a valid handle), only trimmed and capped to the column
|
||||
// width — never character-stripped like the real name.
|
||||
name = strings.TrimSpace(username)
|
||||
if r := []rune(name); len(r) > maxDisplayName {
|
||||
name = strings.TrimRight(string(r[:maxDisplayName]), " ")
|
||||
}
|
||||
}
|
||||
if name == "" {
|
||||
name = placeholderDisplayName(seed.preferredLanguage)
|
||||
@@ -361,16 +392,22 @@ func (s *Store) create(ctx context.Context, kind, externalID string, seed provis
|
||||
|
||||
var created Account
|
||||
err = withTx(ctx, s.db, func(tx *sql.Tx) error {
|
||||
// Seed the new row's display name and language (Telegram first contact); an
|
||||
// empty seed reproduces the table defaults ('' and 'en') the other callers
|
||||
// relied on, so their behaviour is unchanged.
|
||||
// Seed the new row's display name, language and time zone (first contact); an
|
||||
// empty seed reproduces the table defaults ('', 'en' and 'UTC') the other callers
|
||||
// relied on, so their behaviour is unchanged. time_zone is written explicitly (the
|
||||
// detected offset, or 'UTC' equal to the column default) so a seeded zone lands at
|
||||
// creation while an unseeded one stays UTC.
|
||||
lang := seed.preferredLanguage
|
||||
if lang == "" {
|
||||
lang = "en"
|
||||
}
|
||||
tz := seed.timeZone
|
||||
if tz == "" {
|
||||
tz = "UTC"
|
||||
}
|
||||
insertAccount := table.Accounts.
|
||||
INSERT(table.Accounts.AccountID, table.Accounts.DisplayName, table.Accounts.PreferredLanguage).
|
||||
VALUES(accountID, seed.displayName, lang).
|
||||
INSERT(table.Accounts.AccountID, table.Accounts.DisplayName, table.Accounts.PreferredLanguage, table.Accounts.TimeZone).
|
||||
VALUES(accountID, seed.displayName, lang, tz).
|
||||
RETURNING(table.Accounts.AllColumns)
|
||||
|
||||
var row model.Accounts
|
||||
@@ -409,15 +446,21 @@ const guestDisplayName = "Guest"
|
||||
// ProvisionGuest creates a fresh ephemeral guest account: a durable row carrying
|
||||
// no identity, flagged is_guest, so it can hold a session and a game seat (both
|
||||
// foreign-key the accounts table) while being excluded from statistics, friends
|
||||
// and history. Guests are not reused — each bootstrap mints a new account.
|
||||
func (s *Store) ProvisionGuest(ctx context.Context) (Account, error) {
|
||||
// and history. Guests are not reused — each bootstrap mints a new account. browserTZ
|
||||
// (the client's detected "±HH:MM" UTC offset) seeds the guest's time zone, falling
|
||||
// back to the 'UTC' default when empty or malformed.
|
||||
func (s *Store) ProvisionGuest(ctx context.Context, browserTZ string) (Account, error) {
|
||||
accountID, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return Account{}, fmt.Errorf("account: new guest id: %w", err)
|
||||
}
|
||||
tz := seedZone(browserTZ)
|
||||
if tz == "" {
|
||||
tz = "UTC"
|
||||
}
|
||||
stmt := table.Accounts.
|
||||
INSERT(table.Accounts.AccountID, table.Accounts.DisplayName, table.Accounts.IsGuest).
|
||||
VALUES(accountID, guestDisplayName, true).
|
||||
INSERT(table.Accounts.AccountID, table.Accounts.DisplayName, table.Accounts.IsGuest, table.Accounts.TimeZone).
|
||||
VALUES(accountID, guestDisplayName, true, tz).
|
||||
RETURNING(table.Accounts.AllColumns)
|
||||
|
||||
var row model.Accounts
|
||||
|
||||
@@ -131,13 +131,15 @@ func (s *EmailService) ConfirmCode(ctx context.Context, accountID uuid.UUID, ema
|
||||
// the unauthenticated email-login entry point and, unlike RequestCode,
|
||||
// does not refuse an already-confirmed email — that is the ordinary returning-user
|
||||
// login. The code is mailed to the address, so only its real owner can complete
|
||||
// the login. It returns the target account id for the subsequent LoginWithCode.
|
||||
func (s *EmailService) RequestLoginCode(ctx context.Context, email string) (uuid.UUID, error) {
|
||||
// the login. On first contact browserTZ (the client's detected "±HH:MM" UTC offset)
|
||||
// seeds the new account's time zone. It returns the target account id for the
|
||||
// subsequent LoginWithCode.
|
||||
func (s *EmailService) RequestLoginCode(ctx context.Context, email, browserTZ string) (uuid.UUID, error) {
|
||||
addr, err := normalizeEmail(email)
|
||||
if err != nil {
|
||||
return uuid.UUID{}, err
|
||||
}
|
||||
acc, err := s.store.ProvisionByIdentity(ctx, KindEmail, addr)
|
||||
acc, err := s.store.ProvisionEmail(ctx, addr, browserTZ)
|
||||
if err != nil {
|
||||
return uuid.UUID{}, err
|
||||
}
|
||||
|
||||
@@ -9,8 +9,9 @@ import (
|
||||
|
||||
// TestTelegramSeed covers the pure mapping from Telegram launch fields to the
|
||||
// create-time account seed: supported-language detection (bare and region-tagged),
|
||||
// the first-name / username display-name precedence, and the sanitization that
|
||||
// strips disallowed characters (emoji, digits, punctuation) to the editable format.
|
||||
// the real-name → @username (verbatim) → placeholder display-name precedence, and
|
||||
// the sanitization of the real name (emoji, digits, punctuation stripped to the
|
||||
// editable format). The username, when used, is kept verbatim.
|
||||
func TestTelegramSeed(t *testing.T) {
|
||||
cases := map[string]struct {
|
||||
languageCode, username, firstName string
|
||||
@@ -28,6 +29,7 @@ func TestTelegramSeed(t *testing.T) {
|
||||
"punct to space": {"en", "user", "John❤Doe", "en", "John Doe"},
|
||||
"digits dropped": {"ru", "user", "Маша123", "ru", "Маша"},
|
||||
"garbage to username": {"en", "good", "123!@#", "en", "good"},
|
||||
"username verbatim": {"en", "co_ol99", "🎮🎮", "en", "co_ol99"},
|
||||
}
|
||||
for name, tc := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
@@ -49,10 +51,10 @@ func TestTelegramSeedPlaceholder(t *testing.T) {
|
||||
languageCode, username, firstName string
|
||||
wantRe string
|
||||
}{
|
||||
"en empty": {"en", "", "", `^Player-\d{5}$`},
|
||||
"ru empty": {"ru", "", "", `^Игрок-\d{5}$`},
|
||||
"default en": {"fr", "", "", `^Player-\d{5}$`},
|
||||
"both garbage": {"ru", "123", "!!!", `^Игрок-\d{5}$`},
|
||||
"en empty": {"en", "", "", `^Player-\d{5}$`},
|
||||
"ru empty": {"ru", "", "", `^Игрок-\d{5}$`},
|
||||
"default en": {"fr", "", "", `^Player-\d{5}$`},
|
||||
"name garbage, no username": {"ru", "", "!!!", `^Игрок-\d{5}$`},
|
||||
}
|
||||
for name, tc := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
|
||||
@@ -7,8 +7,9 @@
|
||||
<li><b>From</b> <a href="/_gm/users/{{.AccountID}}">{{.SenderName}}</a> ({{.Source}})</li>
|
||||
<li><b>Channel</b> {{.Channel}}</li>
|
||||
<li><b>Interface language</b> {{.InterfaceLanguage}}</li>
|
||||
<li><b>App version</b> {{if .Version}}<code>{{.Version}}</code>{{else}}<span class="note">unknown</span>{{end}}</li>
|
||||
<li><b>IP</b> {{if .IP}}<code>{{.IP}}</code>{{else}}<span class="note">none</span>{{end}}</li>
|
||||
<li><b>Filed</b> {{.CreatedAt}}</li>
|
||||
<li><b>Filed</b> {{.CreatedAt}} UTC · browser {{if .CreatedAtBrowser}}{{.CreatedAtBrowser}} ({{.BrowserTZ}}){{else}}<span class="note">N/A</span>{{end}} · user {{if .CreatedAtUser}}{{.CreatedAtUser}} ({{.UserTZ}}){{else}}<span class="note">N/A</span>{{end}}</li>
|
||||
<li><b>State</b> {{if .Archived}}archived{{else if .Read}}read{{else}}<span class="warn">unread</span>{{end}}</li>
|
||||
{{if .Banned}}<li><b>Feedback</b> <span class="warn">sender is banned from feedback</span></li>{{end}}
|
||||
</ul>
|
||||
|
||||
@@ -554,5 +554,17 @@ type FeedbackDetailView struct {
|
||||
ReplyBody string
|
||||
RepliedAt string
|
||||
CreatedAt string
|
||||
Banned bool
|
||||
// Version is the client app build the report was sent from (empty for rows that predate it).
|
||||
Version string
|
||||
// The Filed time is shown in three zones so the operator can tell what is certainly known from
|
||||
// what is merely defaulted. CreatedAt is the authoritative UTC time. CreatedAtBrowser is that
|
||||
// instant in the client's UTC offset detected at submit (BrowserTZ its "±HH:MM" label), empty
|
||||
// when the client reported none (an older build). CreatedAtUser is that instant in the sender's
|
||||
// saved profile zone (UserTZ its label), empty when the account has no zone beyond the UTC
|
||||
// default — the template then shows "N/A" so the missing datum is explicit.
|
||||
CreatedAtBrowser string
|
||||
BrowserTZ string
|
||||
CreatedAtUser string
|
||||
UserTZ string
|
||||
Banned bool
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ const (
|
||||
// ActionResign abandons the game.
|
||||
ActionResign
|
||||
// ActionTimeout is the auto-resignation a missed turn becomes; recorded by
|
||||
// the game domain in a later stage, never produced by the engine itself.
|
||||
// the game domain, never produced by the engine itself.
|
||||
ActionTimeout
|
||||
)
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
// characters (see decode.go and docs/ARCHITECTURE.md §9.1), so archived games
|
||||
// replay independently of any dictionary. Second, the engine owns rules and
|
||||
// scoring only: turn scheduling, the 24-hour timeout, persistence and transport
|
||||
// belong to the game domain in a later stage.
|
||||
// belong to the game domain.
|
||||
package engine
|
||||
|
||||
import (
|
||||
|
||||
@@ -31,7 +31,7 @@ type entry struct {
|
||||
// Registry holds the dictionaries resident in memory, addressed by variant and
|
||||
// dictionary version, and the solvers built over them. Several versions of a
|
||||
// variant may be resident at once; a game pins the version it started on. The
|
||||
// admin reload flow (a later stage) registers a new version through Load.
|
||||
// admin reload flow registers a new version through Load.
|
||||
// Registry is safe for concurrent use.
|
||||
type Registry struct {
|
||||
mu sync.RWMutex
|
||||
|
||||
@@ -72,7 +72,7 @@ func (svc *Service) SetNotifier(p notify.Publisher) {
|
||||
// validates the body (non-empty, within the rune limit) and the optional
|
||||
// attachment (size and extension allow-list). senderIP is the gateway-forwarded
|
||||
// client IP (validated); channel is the submitting platform.
|
||||
func (svc *Service) Submit(ctx context.Context, accountID uuid.UUID, body string, attachment []byte, attachmentName, channel, senderIP string) error {
|
||||
func (svc *Service) Submit(ctx context.Context, accountID uuid.UUID, body string, attachment []byte, attachmentName, channel, version, browserTZ, senderIP string) error {
|
||||
acc, err := svc.accounts.GetByID(ctx, accountID)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -112,9 +112,10 @@ func (svc *Service) Submit(ctx context.Context, accountID uuid.UUID, body string
|
||||
attachmentName = "" // a name without bytes carries no attachment
|
||||
}
|
||||
ch := normalizeChannel(channel)
|
||||
// Snapshot the sender's interface language at submit time (acc is already loaded
|
||||
// for the guest check) so the operator later sees the state as it was.
|
||||
_, err = svc.store.Insert(ctx, accountID, body, attachment, attachmentName, ch, acc.PreferredLanguage, parseIP(senderIP))
|
||||
// Snapshot the sender's interface language, the client app version and the client's
|
||||
// detected UTC offset at submit time (acc is already loaded for the guest check) so the
|
||||
// operator later sees the state as it was.
|
||||
_, err = svc.store.Insert(ctx, accountID, body, attachment, attachmentName, ch, acc.PreferredLanguage, version, browserTZ, parseIP(senderIP))
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -34,10 +34,10 @@ func NewStore(db *sql.DB) *Store {
|
||||
|
||||
// Insert stores one feedback message from accountID and returns its id. attachment
|
||||
// is the raw file bytes (nil for none); attachmentName, ip and a non-default
|
||||
// channel are stored as given. lang (the sender's interface language) is a snapshot
|
||||
// taken now, so the operator later sees the state at submit time. created_at defaults
|
||||
// to now() in the database.
|
||||
func (s *Store) Insert(ctx context.Context, accountID uuid.UUID, body string, attachment []byte, attachmentName, channel, lang string, ip *string) (uuid.UUID, error) {
|
||||
// channel are stored as given. lang (interface language), version (client app build) and
|
||||
// browserTZ (the client's detected "±HH:MM" UTC offset) are snapshots taken now, so the operator
|
||||
// later sees the state at submit time. created_at defaults to now() in the database.
|
||||
func (s *Store) Insert(ctx context.Context, accountID uuid.UUID, body string, attachment []byte, attachmentName, channel, lang, version, browserTZ string, ip *string) (uuid.UUID, error) {
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("feedback: new message id: %w", err)
|
||||
@@ -48,9 +48,9 @@ func (s *Store) Insert(ctx context.Context, accountID uuid.UUID, body string, at
|
||||
}
|
||||
if _, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO backend.feedback_messages
|
||||
(message_id, account_id, body, attachment, attachment_name, channel, lang, sender_ip)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
|
||||
id, accountID, body, att, nullStr(attachmentName), channel, nullStr(lang), ip); err != nil {
|
||||
(message_id, account_id, body, attachment, attachment_name, channel, lang, app_version, browser_tz, sender_ip)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
|
||||
id, accountID, body, att, nullStr(attachmentName), channel, nullStr(lang), nullStr(version), nullStr(browserTZ), ip); err != nil {
|
||||
return uuid.Nil, fmt.Errorf("feedback: insert: %w", err)
|
||||
}
|
||||
return id, nil
|
||||
@@ -228,7 +228,15 @@ type AdminMessage struct {
|
||||
Body string
|
||||
Channel string
|
||||
// Lang is the sender's interface language, snapshotted at submit time.
|
||||
Lang string
|
||||
Lang string
|
||||
// Version is the client app build the report was sent from, snapshotted at submit time.
|
||||
Version string
|
||||
// BrowserTZ is the client's detected "±HH:MM" UTC offset at submit time, snapshotted so the
|
||||
// filed time can be shown in the sender's browser-local zone even before they save a profile.
|
||||
BrowserTZ string
|
||||
// TimeZone is the sender account's stored zone ("±HH:MM" offset, IANA name, or ""), for
|
||||
// rendering CreatedAt in the sender's own configured time alongside UTC.
|
||||
TimeZone string
|
||||
SenderIP string
|
||||
HasAttachment bool
|
||||
AttachmentName string
|
||||
@@ -343,7 +351,7 @@ func (s *Store) AdminGet(ctx context.Context, id uuid.UUID) (AdminMessage, error
|
||||
var m AdminMessage
|
||||
var repliedAt sql.NullTime
|
||||
q := `SELECT m.message_id, m.account_id, a.display_name, ` + feedbackSource + ` AS source, m.body, m.channel,
|
||||
COALESCE(m.lang, ''),
|
||||
COALESCE(m.lang, ''), COALESCE(m.app_version, ''), COALESCE(m.browser_tz, ''), a.time_zone,
|
||||
COALESCE(m.sender_ip, ''), (m.attachment IS NOT NULL), COALESCE(m.attachment_name, ''),
|
||||
(m.read_at IS NOT NULL), (m.archived_at IS NOT NULL), (m.reply_body IS NOT NULL),
|
||||
COALESCE(m.reply_body, ''), m.replied_at, m.created_at
|
||||
@@ -352,7 +360,7 @@ func (s *Store) AdminGet(ctx context.Context, id uuid.UUID) (AdminMessage, error
|
||||
WHERE m.message_id = $1`
|
||||
err := s.db.QueryRowContext(ctx, q, id).Scan(
|
||||
&m.ID, &m.AccountID, &m.SenderName, &m.Source, &m.Body, &m.Channel,
|
||||
&m.Lang,
|
||||
&m.Lang, &m.Version, &m.BrowserTZ, &m.TimeZone,
|
||||
&m.SenderIP, &m.HasAttachment, &m.AttachmentName,
|
||||
&m.Read, &m.Archived, &m.Replied, &m.ReplyBody, &repliedAt, &m.CreatedAt)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
|
||||
@@ -16,5 +16,5 @@
|
||||
// word-check tool with complaint capture, per-player game state, history and GCG
|
||||
// export, and the per-game turn-timeout sweeper that auto-resigns an overdue
|
||||
// player (honouring their daily away window). The HTTP surface that fronts these
|
||||
// operations is added with the gateway in a later stage.
|
||||
// operations is exposed to the gateway.
|
||||
package game
|
||||
|
||||
@@ -105,7 +105,7 @@ const MaxActiveQuickGames = 10
|
||||
const aiPlayerName = "AI"
|
||||
|
||||
// CreateParams describes a new game. Seats lists the seated accounts in turn
|
||||
// order (seat 0 moves first); lobby/matchmaking assembles it in a later stage.
|
||||
// order (seat 0 moves first); lobby/matchmaking assembles it.
|
||||
type CreateParams struct {
|
||||
Variant engine.Variant
|
||||
Seats []uuid.UUID
|
||||
|
||||
@@ -110,15 +110,15 @@ func identityConfirmed(t *testing.T, kind, externalID string) bool {
|
||||
}
|
||||
|
||||
// TestProvisionTelegramSeedsNewAccountOnly checks that Telegram first contact
|
||||
// seeds the new account's language and display name from the launch fields,
|
||||
// defaults the in-app-only flag on, and never overwrites an existing account on a
|
||||
// later login (language seeding).
|
||||
// seeds the new account's language, display name and time zone from the launch
|
||||
// fields / detected offset, defaults the in-app-only flag on, and never overwrites
|
||||
// an existing account on a later login (language and zone seeding).
|
||||
func TestProvisionTelegramSeedsNewAccountOnly(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := account.NewStore(testDB)
|
||||
ext := "tg-" + uuid.NewString()
|
||||
|
||||
acc, created, err := store.ProvisionTelegram(ctx, ext, "ru-RU", "thehandle", "Иван")
|
||||
acc, created, err := store.ProvisionTelegram(ctx, ext, "ru-RU", "thehandle", "Иван", "+03:00")
|
||||
if err != nil {
|
||||
t.Fatalf("provision telegram: %v", err)
|
||||
}
|
||||
@@ -131,12 +131,15 @@ func TestProvisionTelegramSeedsNewAccountOnly(t *testing.T) {
|
||||
if acc.DisplayName != "Иван" {
|
||||
t.Errorf("DisplayName = %q, want Иван", acc.DisplayName)
|
||||
}
|
||||
if acc.TimeZone != "+03:00" {
|
||||
t.Errorf("TimeZone = %q, want the seeded +03:00", acc.TimeZone)
|
||||
}
|
||||
if !acc.NotificationsInAppOnly {
|
||||
t.Error("NotificationsInAppOnly should default to true")
|
||||
}
|
||||
|
||||
// A later login with different fields returns the same account, unchanged.
|
||||
again, created, err := store.ProvisionTelegram(ctx, ext, "en", "other", "Other")
|
||||
again, created, err := store.ProvisionTelegram(ctx, ext, "en", "other", "Other", "+09:00")
|
||||
if err != nil {
|
||||
t.Fatalf("re-provision telegram: %v", err)
|
||||
}
|
||||
@@ -146,8 +149,53 @@ func TestProvisionTelegramSeedsNewAccountOnly(t *testing.T) {
|
||||
if again.ID != acc.ID {
|
||||
t.Errorf("re-provision id = %s, want %s", again.ID, acc.ID)
|
||||
}
|
||||
if again.PreferredLanguage != "ru" || again.DisplayName != "Иван" {
|
||||
t.Errorf("existing account overwritten: lang=%q name=%q", again.PreferredLanguage, again.DisplayName)
|
||||
if again.PreferredLanguage != "ru" || again.DisplayName != "Иван" || again.TimeZone != "+03:00" {
|
||||
t.Errorf("existing account overwritten: lang=%q name=%q tz=%q", again.PreferredLanguage, again.DisplayName, again.TimeZone)
|
||||
}
|
||||
}
|
||||
|
||||
// TestProvisionSeedsTimeZone checks the create-time time-zone seed across paths: a
|
||||
// valid detected offset is stored verbatim (even "+00:00", which is deliberately
|
||||
// distinct from the unset "UTC" default), a guest is seeded the same way, and a
|
||||
// missing or malformed offset falls back to the "UTC" column default rather than
|
||||
// being guessed at.
|
||||
func TestProvisionSeedsTimeZone(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := account.NewStore(testDB)
|
||||
|
||||
// A detected zero offset is written as "+00:00" — we record that the zone was
|
||||
// detected (and equals UTC), distinct from the "UTC" default meaning "unknown".
|
||||
utcDetected, _, err := store.ProvisionTelegram(ctx, "tg-"+uuid.NewString(), "en", "", "Zero", "+00:00")
|
||||
if err != nil {
|
||||
t.Fatalf("provision telegram +00:00: %v", err)
|
||||
}
|
||||
if utcDetected.TimeZone != "+00:00" {
|
||||
t.Errorf("TimeZone = %q, want the seeded +00:00", utcDetected.TimeZone)
|
||||
}
|
||||
|
||||
// A malformed offset is dropped: the account keeps the UTC default.
|
||||
bad, _, err := store.ProvisionTelegram(ctx, "tg-"+uuid.NewString(), "en", "", "Bad", "not-a-zone")
|
||||
if err != nil {
|
||||
t.Fatalf("provision telegram bad tz: %v", err)
|
||||
}
|
||||
if bad.TimeZone != "UTC" {
|
||||
t.Errorf("TimeZone = %q, want UTC fallback for a malformed offset", bad.TimeZone)
|
||||
}
|
||||
|
||||
// A guest is seeded its detected offset; an empty one keeps the UTC default.
|
||||
guest, err := store.ProvisionGuest(ctx, "-05:30")
|
||||
if err != nil {
|
||||
t.Fatalf("provision guest: %v", err)
|
||||
}
|
||||
if guest.TimeZone != "-05:30" {
|
||||
t.Errorf("guest TimeZone = %q, want the seeded -05:30", guest.TimeZone)
|
||||
}
|
||||
plainGuest, err := store.ProvisionGuest(ctx, "")
|
||||
if err != nil {
|
||||
t.Fatalf("provision plain guest: %v", err)
|
||||
}
|
||||
if plainGuest.TimeZone != "UTC" {
|
||||
t.Errorf("plain guest TimeZone = %q, want UTC default", plainGuest.TimeZone)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,7 +204,7 @@ func TestProvisionTelegramSeedsNewAccountOnly(t *testing.T) {
|
||||
// language CHECK.
|
||||
func TestProvisionTelegramUnknownLanguageDefaults(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
acc, _, err := account.NewStore(testDB).ProvisionTelegram(ctx, "tg-"+uuid.NewString(), "fr", "", "")
|
||||
acc, _, err := account.NewStore(testDB).ProvisionTelegram(ctx, "tg-"+uuid.NewString(), "fr", "", "", "")
|
||||
if err != nil {
|
||||
t.Fatalf("provision telegram: %v", err)
|
||||
}
|
||||
@@ -172,7 +220,7 @@ func TestProvisionTelegramUnknownLanguageDefaults(t *testing.T) {
|
||||
func TestHighRateFlagRoundTrip(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := account.NewStore(testDB)
|
||||
acc, _, err := store.ProvisionTelegram(ctx, "tg-"+uuid.NewString(), "en", "", "Player")
|
||||
acc, _, err := store.ProvisionTelegram(ctx, "tg-"+uuid.NewString(), "en", "", "Player", "")
|
||||
if err != nil {
|
||||
t.Fatalf("provision telegram: %v", err)
|
||||
}
|
||||
@@ -228,7 +276,7 @@ func TestIdentityExternalID(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := account.NewStore(testDB)
|
||||
ext := "tg-" + uuid.NewString()
|
||||
acc, _, err := store.ProvisionTelegram(ctx, ext, "en", "", "Tg User")
|
||||
acc, _, err := store.ProvisionTelegram(ctx, ext, "en", "", "Tg User", "")
|
||||
if err != nil {
|
||||
t.Fatalf("provision telegram: %v", err)
|
||||
}
|
||||
@@ -253,7 +301,7 @@ func TestIdentityExternalID(t *testing.T) {
|
||||
func TestNotificationsInAppOnlyRoundTrip(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := account.NewStore(testDB)
|
||||
acc, _, err := store.ProvisionTelegram(ctx, "tg-"+uuid.NewString(), "en", "", "Player")
|
||||
acc, _, err := store.ProvisionTelegram(ctx, "tg-"+uuid.NewString(), "en", "", "Player", "")
|
||||
if err != nil {
|
||||
t.Fatalf("provision telegram: %v", err)
|
||||
}
|
||||
|
||||
@@ -222,7 +222,7 @@ func TestConsoleGameDetailRobotSchedule(t *testing.T) {
|
||||
func TestConsoleThrottledViewAndFlagClear(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
accounts := account.NewStore(testDB)
|
||||
acc, _, err := accounts.ProvisionTelegram(ctx, "tg-"+uuid.NewString(), "en", "", "Throttled Player")
|
||||
acc, _, err := accounts.ProvisionTelegram(ctx, "tg-"+uuid.NewString(), "en", "", "Throttled Player", "")
|
||||
if err != nil {
|
||||
t.Fatalf("provision: %v", err)
|
||||
}
|
||||
|
||||
@@ -55,7 +55,7 @@ func TestChatAccessResolver(t *testing.T) {
|
||||
srv := server.New(":0", server.Deps{Logger: zaptest.NewLogger(t), DB: testDB, Accounts: accounts})
|
||||
|
||||
ext := "tg-" + uuid.NewString()
|
||||
acc, _, err := accounts.ProvisionTelegram(ctx, ext, "en", "", "Chatter")
|
||||
acc, _, err := accounts.ProvisionTelegram(ctx, ext, "en", "", "Chatter", "")
|
||||
if err != nil {
|
||||
t.Fatalf("provision: %v", err)
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ func TestEmailConfirmFlow(t *testing.T) {
|
||||
}
|
||||
|
||||
// TestEmailAlreadyTakenByAnotherAccount refuses to bind an email confirmed by a
|
||||
// different account (merge is a later stage).
|
||||
// different account (combining two accounts is the separate link/merge flow).
|
||||
func TestEmailAlreadyTakenByAnotherAccount(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := account.NewStore(testDB)
|
||||
@@ -206,7 +206,7 @@ func TestEmailLoginFlow(t *testing.T) {
|
||||
svc := account.NewEmailService(account.NewStore(testDB), mailer)
|
||||
email := "login-" + uuid.NewString() + "@example.com"
|
||||
|
||||
accountID, err := svc.RequestLoginCode(ctx, email)
|
||||
accountID, err := svc.RequestLoginCode(ctx, email, "+02:00")
|
||||
if err != nil {
|
||||
t.Fatalf("request login code: %v", err)
|
||||
}
|
||||
@@ -225,12 +225,15 @@ func TestEmailLoginFlow(t *testing.T) {
|
||||
if acc.IsGuest {
|
||||
t.Error("an email account must be durable, not a guest")
|
||||
}
|
||||
if acc.TimeZone != "+02:00" {
|
||||
t.Errorf("TimeZone = %q, want the +02:00 seeded at the request step", acc.TimeZone)
|
||||
}
|
||||
if !identityConfirmed(t, account.KindEmail, email) {
|
||||
t.Error("the email identity must be confirmed after login")
|
||||
}
|
||||
|
||||
// A second login for the same email is the returning user: same account.
|
||||
if _, err := svc.RequestLoginCode(ctx, email); err != nil {
|
||||
if _, err := svc.RequestLoginCode(ctx, email, ""); err != nil {
|
||||
t.Fatalf("second request: %v", err)
|
||||
}
|
||||
acc2, err := svc.LoginWithCode(ctx, email, sixDigit.FindString(mailer.lastBody))
|
||||
|
||||
@@ -38,7 +38,7 @@ func latestFeedbackID(t *testing.T, svc *feedback.Service, acc uuid.UUID) uuid.U
|
||||
func TestFeedbackGuestRejected(t *testing.T) {
|
||||
svc := newFeedbackService()
|
||||
guest := provisionGuest(t)
|
||||
if err := svc.Submit(context.Background(), guest, "hi", nil, "", "web", "1.2.3.4"); !errors.Is(err, feedback.ErrGuestForbidden) {
|
||||
if err := svc.Submit(context.Background(), guest, "hi", nil, "", "web", "v1", "+05:00", "1.2.3.4"); !errors.Is(err, feedback.ErrGuestForbidden) {
|
||||
t.Fatalf("guest submit err = %v, want ErrGuestForbidden", err)
|
||||
}
|
||||
}
|
||||
@@ -48,11 +48,11 @@ func TestFeedbackSubmitGateAndReplyLifecycle(t *testing.T) {
|
||||
svc := newFeedbackService()
|
||||
acc := provisionAccount(t)
|
||||
|
||||
if err := svc.Submit(ctx, acc, " please fix the board ", []byte("PNGDATA"), "shot.png", "ios", "9.9.9.9"); err != nil {
|
||||
if err := svc.Submit(ctx, acc, " please fix the board ", []byte("PNGDATA"), "shot.png", "ios", "v1.2.0", "+03:00", "9.9.9.9"); err != nil {
|
||||
t.Fatalf("submit: %v", err)
|
||||
}
|
||||
// Anti-spam gate: a second message is refused while the first is unreviewed.
|
||||
if err := svc.Submit(ctx, acc, "again", nil, "", "web", ""); !errors.Is(err, feedback.ErrPendingReview) {
|
||||
if err := svc.Submit(ctx, acc, "again", nil, "", "web", "", "", ""); !errors.Is(err, feedback.ErrPendingReview) {
|
||||
t.Fatalf("second submit err = %v, want ErrPendingReview", err)
|
||||
}
|
||||
if st, err := svc.State(ctx, acc); err != nil {
|
||||
@@ -69,7 +69,7 @@ func TestFeedbackSubmitGateAndReplyLifecycle(t *testing.T) {
|
||||
if m.Body != "please fix the board" { // trimmed
|
||||
t.Fatalf("body = %q, want trimmed", m.Body)
|
||||
}
|
||||
if !m.HasAttachment || m.AttachmentName != "shot.png" || m.Channel != "ios" || m.SenderIP != "9.9.9.9" {
|
||||
if !m.HasAttachment || m.AttachmentName != "shot.png" || m.Channel != "ios" || m.SenderIP != "9.9.9.9" || m.Version != "v1.2.0" || m.BrowserTZ != "+03:00" {
|
||||
t.Fatalf("admin message = %+v", m)
|
||||
}
|
||||
if name, data, ok, err := svc.Attachment(ctx, id); err != nil || !ok || name != "shot.png" || string(data) != "PNGDATA" {
|
||||
@@ -116,7 +116,7 @@ func TestFeedbackReplyHiddenAfterNewMessage(t *testing.T) {
|
||||
acc := provisionAccount(t)
|
||||
|
||||
// msg1, replied → the player can send again and currently sees the reply.
|
||||
if err := svc.Submit(ctx, acc, "first", nil, "", "web", ""); err != nil {
|
||||
if err := svc.Submit(ctx, acc, "first", nil, "", "web", "", "", ""); err != nil {
|
||||
t.Fatalf("submit msg1: %v", err)
|
||||
}
|
||||
if err := svc.Reply(ctx, latestFeedbackID(t, svc, acc), "the answer"); err != nil {
|
||||
@@ -130,7 +130,7 @@ func TestFeedbackReplyHiddenAfterNewMessage(t *testing.T) {
|
||||
|
||||
// Sending a new message immediately drops the previous reply (it now belongs to an
|
||||
// older message), even though it is well within the one-week window.
|
||||
if err := svc.Submit(ctx, acc, "second", nil, "", "web", ""); err != nil {
|
||||
if err := svc.Submit(ctx, acc, "second", nil, "", "web", "", "", ""); err != nil {
|
||||
t.Fatalf("submit msg2: %v", err)
|
||||
}
|
||||
st, err := svc.State(ctx, acc)
|
||||
@@ -154,7 +154,7 @@ func TestFeedbackSnapshotsLanguage(t *testing.T) {
|
||||
t.Fatalf("set language: %v", err)
|
||||
}
|
||||
// A message snapshots the sender's interface language at submit time.
|
||||
if err := svc.Submit(ctx, acc, "from telegram", nil, "", "telegram", ""); err != nil {
|
||||
if err := svc.Submit(ctx, acc, "from telegram", nil, "", "telegram", "", "", ""); err != nil {
|
||||
t.Fatalf("submit: %v", err)
|
||||
}
|
||||
id := latestFeedbackID(t, svc, acc)
|
||||
@@ -184,7 +184,7 @@ func TestFeedbackBanRole(t *testing.T) {
|
||||
if err := accounts.GrantRole(ctx, acc, account.RoleFeedbackBanned); err != nil {
|
||||
t.Fatalf("grant role: %v", err)
|
||||
}
|
||||
if err := svc.Submit(ctx, acc, "hi", nil, "", "web", ""); !errors.Is(err, feedback.ErrBanned) {
|
||||
if err := svc.Submit(ctx, acc, "hi", nil, "", "web", "", "", ""); !errors.Is(err, feedback.ErrBanned) {
|
||||
t.Fatalf("banned submit err = %v, want ErrBanned", err)
|
||||
}
|
||||
if st, err := svc.State(ctx, acc); err != nil {
|
||||
@@ -196,7 +196,7 @@ func TestFeedbackBanRole(t *testing.T) {
|
||||
if err := accounts.RevokeRole(ctx, acc, account.RoleFeedbackBanned); err != nil {
|
||||
t.Fatalf("revoke role: %v", err)
|
||||
}
|
||||
if err := svc.Submit(ctx, acc, "hi again", nil, "", "web", ""); err != nil {
|
||||
if err := svc.Submit(ctx, acc, "hi again", nil, "", "web", "", "", ""); err != nil {
|
||||
t.Fatalf("submit after unban: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -219,7 +219,7 @@ func TestFeedbackValidation(t *testing.T) {
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
acc := provisionAccount(t) // fresh account so the pending gate never fires first
|
||||
if err := svc.Submit(ctx, acc, tt.body, tt.attachment, tt.attachmentName, "web", ""); !errors.Is(err, tt.want) {
|
||||
if err := svc.Submit(ctx, acc, tt.body, tt.attachment, tt.attachmentName, "web", "", "", ""); !errors.Is(err, tt.want) {
|
||||
t.Fatalf("submit err = %v, want %v", err, tt.want)
|
||||
}
|
||||
})
|
||||
@@ -231,7 +231,7 @@ func TestFeedbackAdminLifecycle(t *testing.T) {
|
||||
svc := newFeedbackService()
|
||||
acc := provisionAccount(t)
|
||||
|
||||
if err := svc.Submit(ctx, acc, "first report", nil, "", "web", ""); err != nil {
|
||||
if err := svc.Submit(ctx, acc, "first report", nil, "", "web", "", "", ""); err != nil {
|
||||
t.Fatalf("submit: %v", err)
|
||||
}
|
||||
id := latestFeedbackID(t, svc, acc)
|
||||
@@ -276,7 +276,7 @@ func TestFeedbackDeleteAllByAccount(t *testing.T) {
|
||||
svc := newFeedbackService()
|
||||
acc := provisionAccount(t)
|
||||
|
||||
if err := svc.Submit(ctx, acc, "one", nil, "", "web", ""); err != nil {
|
||||
if err := svc.Submit(ctx, acc, "one", nil, "", "web", "", "", ""); err != nil {
|
||||
t.Fatalf("submit: %v", err)
|
||||
}
|
||||
if err := svc.DeleteAllByAccount(ctx, acc); err != nil {
|
||||
@@ -286,7 +286,7 @@ func TestFeedbackDeleteAllByAccount(t *testing.T) {
|
||||
if has, err := svc.ReplyUnread(ctx, acc); err != nil || has {
|
||||
t.Fatalf("reply unread after delete-all = %v (err %v)", has, err)
|
||||
}
|
||||
if err := svc.Submit(ctx, acc, "fresh", nil, "", "web", ""); err != nil {
|
||||
if err := svc.Submit(ctx, acc, "fresh", nil, "", "web", "", "", ""); err != nil {
|
||||
t.Fatalf("submit after delete-all: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,7 +120,7 @@ func provisionAccount(t *testing.T) uuid.UUID {
|
||||
// provisionGuest creates a fresh ephemeral guest account and returns its id.
|
||||
func provisionGuest(t *testing.T) uuid.UUID {
|
||||
t.Helper()
|
||||
acc, err := account.NewStore(testDB).ProvisionGuest(context.Background())
|
||||
acc, err := account.NewStore(testDB).ProvisionGuest(context.Background(), "")
|
||||
if err != nil {
|
||||
t.Fatalf("provision guest: %v", err)
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ func TestSuspensionGate(t *testing.T) {
|
||||
Accounts: accounts,
|
||||
})
|
||||
|
||||
acc, _, err := accounts.ProvisionTelegram(ctx, "tg-"+uuid.NewString(), "ru", "", "Blocked")
|
||||
acc, _, err := accounts.ProvisionTelegram(ctx, "tg-"+uuid.NewString(), "ru", "", "Blocked", "")
|
||||
if err != nil {
|
||||
t.Fatalf("provision: %v", err)
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ func TestUserListFilter(t *testing.T) {
|
||||
st := account.NewStore(testDB)
|
||||
uniq := uuid.NewString()
|
||||
|
||||
human, _, err := st.ProvisionTelegram(ctx, "tg-"+uniq, "en", "", "Zzqxhuman")
|
||||
human, _, err := st.ProvisionTelegram(ctx, "tg-"+uniq, "en", "", "Zzqxhuman", "")
|
||||
if err != nil {
|
||||
t.Fatalf("provision human: %v", err)
|
||||
}
|
||||
@@ -26,7 +26,7 @@ func TestUserListFilter(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("provision robot: %v", err)
|
||||
}
|
||||
guest, err := st.ProvisionGuest(ctx)
|
||||
guest, err := st.ProvisionGuest(ctx, "")
|
||||
if err != nil {
|
||||
t.Fatalf("provision guest: %v", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
-- Replace the default (house) ad campaign's single seed tip with the curated,
|
||||
-- language-agnostic Scrabble tip set (one bilingual row per tip; the client picks the
|
||||
-- column for the viewer's language). Data-only — the ad_messages schema is unchanged, so
|
||||
-- a backend image rollback stays DB-safe. The default campaign is the fixed house id seeded
|
||||
-- in 00001; ON DELETE CASCADE is irrelevant here (we only touch its messages).
|
||||
|
||||
-- +goose Up
|
||||
DELETE FROM backend.ad_messages WHERE campaign_id = '00000000-0000-0000-0000-0000000000ad';
|
||||
INSERT INTO backend.ad_messages (message_id, campaign_id, "position", body_en, body_ru) VALUES
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 0, 'Keep a balanced rack — a slight edge of consonants over vowels.', 'Держи на руках баланс — с лёгким перевесом согласных над гласными.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 1, 'Your "leave" (the tiles you keep) sets up your next turn — value it.', '«Остаток» (что оставляешь на руках) готовит следующий ход — цени его.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 2, 'Shed duplicate tiles — repeats clog your options.', 'Сбрасывай дубли фишек — повторы забивают возможности.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 3, 'A slightly consonant-heavy rack builds full-rack plays more easily.', 'Лёгкий перевес согласных проще складывается в выкладку всех фишек.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 4, 'Play several tiles per turn to keep your rack cycling.', 'Выкладывай по нескольку фишек за ход, чтобы рука обновлялась.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 5, 'Don''t hoard hard-to-place duplicates or a lone high-value tile.', 'Не копи труднопристраиваемые дубли или одинокую дорогую фишку.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 6, 'Using all your rack tiles in one move scores a large bonus — chase it.', 'Выкладка всех фишек с рук за ход даёт крупный бонус — стремись к ней.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 7, 'Learn common prefixes and suffixes — they extend words to use every tile.', 'Учи частые приставки и суффиксы — они растягивают слово на все фишки.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 8, '"Fish": play few tiles to keep a near-complete rack when you''re ahead.', '«Рыбачь»: сыграй мало фишек, сохранив почти всю руку, когда ведёшь.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 9, 'Don''t hoard high-value tiles — play them in good time, not at the very end.', 'Не копи дорогие фишки — играй их вовремя, а не под самый конец.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 10, 'Don''t hold a high-value tile waiting for a rare partner — usually a loss.', 'Не держи дорогую фишку ради редкого партнёра — обычно это проигрыш.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 11, 'Land your priciest tile on a premium square for a big single score.', 'Сажай самую дорогую фишку на бонусную клетку ради крупных очков.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 12, 'High-value tiles shine in parallel plays through short words.', 'Дорогие фишки сильны в параллельных выкладках через короткие слова.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 13, 'Stuck with an unplayable high-value tile late? Exchange it.', 'Завис с неиграбельной дорогой фишкой под конец? Обменяй её.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 14, 'The blanks are the most valuable tiles in the bag — guard them.', 'Пустышки — самые ценные фишки в мешке; береги их.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 15, 'Save a blank for a full-rack play or a key premium square.', 'Береги пустышку для выкладки всех фишек или важной бонусной клетки.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 16, 'Don''t spend a blank cheaply — hold it for a much bigger gain.', 'Не трать пустышку по мелочи — придержи ради куда большей выгоды.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 17, 'Put high-value tiles on letter-bonus or word-bonus squares.', 'Клади дорогие фишки на бонус буквы или слова.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 18, 'Stack bonuses — a letter bonus under a word bonus multiplies both.', 'Совмещай бонусы — бонус буквы под бонусом слова умножает оба.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 19, 'Parallel plays can earn nearly half your points — look for them.', 'Параллельные выкладки могут давать почти половину очков — ищи их.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 20, 'A hook adds one tile to an existing word to make a new one.', '«Крючок» — одна фишка к готовому слову, образующая новое.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 21, 'Hooks work at the front or the back of a word.', 'Крючки работают спереди и сзади слова.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 22, 'Short words are the keys to tight parallel plays — memorize them.', 'Короткие слова — ключ к плотным параллелям; выучи их.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 23, 'Your opening word crosses the centre — keep it compact, don''t open up.', 'Первое слово идёт через центр — держи компактным, не раскрывайся.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 24, 'It''s not only your score — limit your opponent''s options too.', 'Это не только твои очки — ограничивай и возможности соперника.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 25, 'Denying a big reply often beats squeezing a few more points yourself.', 'Закрыть крупный ответ часто важнее, чем добрать пару своих очков.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 26, 'When ahead, keep the board tight and closed; avoid open lanes.', 'Ведёшь — держи доску плотной и закрытой, не открывай линии.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 27, 'When behind, open the board up to create high-scoring chances.', 'Отстаёшь — раскрывай доску ради шансов на крупный ход.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 28, 'Don''t leave a word-bonus square open right beside your word.', 'Не оставляй клетку бонуса слова открытой рядом со своим словом.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 29, 'Block a hot square even with a weak word to deny a big play.', 'Закрывай опасную клетку даже слабым словом, чтобы срубить крупный ход.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 30, 'Know words that take no hooks — use them to seal off lines.', 'Знай слова, не берущие крючков — ими запирай линии.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 31, 'Track the tiles played to judge what is still left in the bag.', 'Считай сыгранные фишки — так поймёшь, что осталось в мешке.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 32, 'Exchange when your rack is unbalanced or can only score low.', 'Меняй фишки, когда рука несбалансированна или тянет мало.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 33, 'A good exchange beats a bad play — a clean rack is worth a turn.', 'Хороший обмен лучше плохого хода — чистая рука стоит хода.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 34, 'Swap away a surplus of vowels or consonants to rebalance.', 'Сбрасывай в обмен избыток гласных или согласных, чтобы выровняться.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 35, 'Rare high-value tiles are gone once seen — note them as they appear.', 'Редкие дорогие фишки исчезают, едва мелькнув — отмечай их.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 36, 'Once the bag is empty, deduce your opponent''s remaining tiles.', 'Когда мешок пуст, вычисли оставшиеся фишки соперника.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 37, 'Shed high-value tiles before the bag empties — don''t get stuck with them.', 'Сбрось дорогие фишки до опустения мешка — не зависай с ними.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 38, 'Unplayed tiles count against you at the end — try to go out first.', 'Несыгранные фишки минусуют очки в конце — старайся выйти первым.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 39, 'Going out first adds your opponent''s leftover tiles to your score.', 'Кто вышел первым, добирает очки за оставшиеся фишки соперника.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 40, 'Sometimes leaving one tile in the bag buys you an extra turn.', 'Иногда оставить одну фишку в мешке — это лишний ход.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 41, 'In the endgame, block the exact squares your opponent needs.', 'В эндшпиле блокируй именно те клетки, что нужны сопернику.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 42, 'Shuffle your rack to spot new patterns.', 'Перемешивай фишки на руках — так замечаешь новые сочетания.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 43, 'Separate prefix, suffix and middle tiles to anagram faster.', 'Разнеси приставку, суффикс и середину — анаграммы решаются быстрее.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 44, 'Value board position and future turns over raw points this turn.', 'Цени позицию и будущие ходы выше сиюминутных очков.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 45, 'Early game build position; midgame maximize score; endgame defend.', 'В начале — позиция, в середине — очки, в конце — защита.'),
|
||||
(gen_random_uuid(), '00000000-0000-0000-0000-0000000000ad', 46, 'Learn the short-word lists first — they pay off in every game.', 'Сначала учи списки коротких слов — окупаются в каждой партии.');
|
||||
|
||||
-- +goose Down
|
||||
-- Restore the original single house tip seeded by the baseline.
|
||||
DELETE FROM backend.ad_messages WHERE campaign_id = '00000000-0000-0000-0000-0000000000ad';
|
||||
INSERT INTO backend.ad_messages (message_id, campaign_id, "position", body_en, body_ru)
|
||||
VALUES ('00000000-0000-0000-0000-0000000000a1', '00000000-0000-0000-0000-0000000000ad', 0,
|
||||
'Tip: a play using all 7 tiles earns a +50 bonus.',
|
||||
'Совет: ход всеми 7 фишками приносит бонус +50 очков.');
|
||||
@@ -0,0 +1,10 @@
|
||||
-- Capture the client app version (the build a report was sent from) with each feedback
|
||||
-- message, so the operator console can show which version a player was on. Nullable, so the
|
||||
-- rows that predate this keep working — additive and backward-compatible, so a backend image
|
||||
-- rollback stays DB-safe (older code simply ignores the column).
|
||||
|
||||
-- +goose Up
|
||||
ALTER TABLE backend.feedback_messages ADD COLUMN app_version text;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE backend.feedback_messages DROP COLUMN app_version;
|
||||
@@ -0,0 +1,11 @@
|
||||
-- Capture the client's detected UTC offset ("±HH:MM") with each feedback message, so the
|
||||
-- operator console can show the filed time in the sender's browser-local zone even before that
|
||||
-- player has ever saved a profile (the account zone defaults to UTC until then). Nullable, so the
|
||||
-- rows that predate this keep working — additive and backward-compatible, so a backend image
|
||||
-- rollback stays DB-safe (older code simply ignores the column).
|
||||
|
||||
-- +goose Up
|
||||
ALTER TABLE backend.feedback_messages ADD COLUMN browser_tz text;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE backend.feedback_messages DROP COLUMN browser_tz;
|
||||
@@ -1198,6 +1198,17 @@ func fmtTime(t time.Time) string {
|
||||
return t.UTC().Format("2006-01-02 15:04")
|
||||
}
|
||||
|
||||
// fmtTimeIn formats a timestamp in the given zone — a "±HH:MM" offset or an IANA name, resolved
|
||||
// by account.ResolveZone (falling back to UTC when empty or unknown) — or "" when zero. Used to
|
||||
// show a time in a user's local zone beside UTC; the offset form is what the profile editor and
|
||||
// the feedback browser-tz snapshot store, so it must not go through time.LoadLocation alone.
|
||||
func fmtTimeIn(t time.Time, tz string) string {
|
||||
if t.IsZero() {
|
||||
return ""
|
||||
}
|
||||
return t.In(account.ResolveZone(tz)).Format("2006-01-02 15:04")
|
||||
}
|
||||
|
||||
// fmtTimePtr formats an optional timestamp for display, or "" when nil.
|
||||
func fmtTimePtr(t *time.Time) string {
|
||||
if t == nil {
|
||||
|
||||
@@ -77,6 +77,17 @@ func (s *Server) consoleFeedbackDetail(c *gin.Context) {
|
||||
s.consoleError(c, err)
|
||||
return
|
||||
}
|
||||
// Filed time in three zones so the operator can tell what is certainly known from what is
|
||||
// merely defaulted: always UTC; the client's offset detected at submit (when the build
|
||||
// reported one); and the sender's saved profile zone (when set beyond the UTC default). An
|
||||
// empty rendered time makes the template show "N/A" for that line.
|
||||
browserCreated, userCreated := "", ""
|
||||
if m.BrowserTZ != "" {
|
||||
browserCreated = fmtTimeIn(m.CreatedAt, m.BrowserTZ)
|
||||
}
|
||||
if m.TimeZone != "" && m.TimeZone != "UTC" {
|
||||
userCreated = fmtTimeIn(m.CreatedAt, m.TimeZone)
|
||||
}
|
||||
view := adminconsole.FeedbackDetailView{
|
||||
ID: m.ID.String(), AccountID: m.AccountID.String(), SenderName: m.SenderName,
|
||||
Source: m.Source, Channel: m.Channel, InterfaceLanguage: m.Lang,
|
||||
@@ -84,6 +95,9 @@ func (s *Server) consoleFeedbackDetail(c *gin.Context) {
|
||||
HasAttachment: m.HasAttachment, AttachmentName: m.AttachmentName, IsImage: feedback.IsImage(m.AttachmentName),
|
||||
Read: m.Read, Archived: m.Archived, Replied: m.Replied, ReplyBody: m.ReplyBody,
|
||||
RepliedAt: fmtTime(m.RepliedAt), CreatedAt: fmtTime(m.CreatedAt),
|
||||
Version: m.Version,
|
||||
CreatedAtBrowser: browserCreated, BrowserTZ: m.BrowserTZ,
|
||||
CreatedAtUser: userCreated, UserTZ: m.TimeZone,
|
||||
}
|
||||
if banned, err := s.accounts.HasRole(ctx, m.AccountID, account.RoleFeedbackBanned); err == nil {
|
||||
view.Banned = banned
|
||||
|
||||
@@ -18,12 +18,14 @@ import (
|
||||
|
||||
// telegramAuthRequest carries the identity the connector extracted from a
|
||||
// validated initData payload. Username, FirstName and LanguageCode seed a
|
||||
// brand-new account's display name and language (first contact only).
|
||||
// brand-new account's display name and language; BrowserTZ (the client's detected
|
||||
// "±HH:MM" UTC offset) seeds its time zone (first contact only).
|
||||
type telegramAuthRequest struct {
|
||||
ExternalID string `json:"external_id"`
|
||||
Username string `json:"username"`
|
||||
FirstName string `json:"first_name"`
|
||||
LanguageCode string `json:"language_code"`
|
||||
BrowserTZ string `json:"browser_tz"`
|
||||
}
|
||||
|
||||
// handleTelegramAuth provisions (or finds) the account bound to a Telegram
|
||||
@@ -35,7 +37,7 @@ func (s *Server) handleTelegramAuth(c *gin.Context) {
|
||||
abortBadRequest(c, "external_id is required")
|
||||
return
|
||||
}
|
||||
acc, created, err := s.accounts.ProvisionTelegram(c.Request.Context(), req.ExternalID, req.LanguageCode, req.Username, req.FirstName)
|
||||
acc, created, err := s.accounts.ProvisionTelegram(c.Request.Context(), req.ExternalID, req.LanguageCode, req.Username, req.FirstName, req.BrowserTZ)
|
||||
if err != nil {
|
||||
s.abortErr(c, err)
|
||||
return
|
||||
@@ -97,9 +99,21 @@ func (s *Server) handlePushTarget(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// handleGuestAuth provisions a fresh ephemeral guest account and mints a session.
|
||||
// guestAuthRequest carries the guest bootstrap's optional time-zone seed: BrowserTZ
|
||||
// (the client's detected "±HH:MM" UTC offset) is written to the new guest account's
|
||||
// time zone, so robot timing is anchored to the player's zone from the first game.
|
||||
type guestAuthRequest struct {
|
||||
BrowserTZ string `json:"browser_tz"`
|
||||
}
|
||||
|
||||
// handleGuestAuth provisions a fresh ephemeral guest account and mints a session,
|
||||
// seeding its time zone from the optional detected browser offset.
|
||||
func (s *Server) handleGuestAuth(c *gin.Context) {
|
||||
acc, err := s.accounts.ProvisionGuest(c.Request.Context())
|
||||
// The body is optional: an absent or malformed one simply yields no time-zone seed
|
||||
// (the account keeps the UTC default), so a bind error must not fail the bootstrap.
|
||||
var req guestAuthRequest
|
||||
_ = c.ShouldBindJSON(&req)
|
||||
acc, err := s.accounts.ProvisionGuest(c.Request.Context(), req.BrowserTZ)
|
||||
if err != nil {
|
||||
s.abortErr(c, err)
|
||||
return
|
||||
@@ -107,9 +121,12 @@ func (s *Server) handleGuestAuth(c *gin.Context) {
|
||||
s.mintSession(c, acc)
|
||||
}
|
||||
|
||||
// emailRequest is an email-login code request.
|
||||
// emailRequest is an email-login code request. BrowserTZ (the client's detected
|
||||
// "±HH:MM" UTC offset) seeds the time zone of an account provisioned here on first
|
||||
// contact (the email account is created at the request step, not at login).
|
||||
type emailRequest struct {
|
||||
Email string `json:"email"`
|
||||
Email string `json:"email"`
|
||||
BrowserTZ string `json:"browser_tz"`
|
||||
}
|
||||
|
||||
// handleEmailRequest issues a login confirm-code to the email. It always reports
|
||||
@@ -121,7 +138,7 @@ func (s *Server) handleEmailRequest(c *gin.Context) {
|
||||
abortBadRequest(c, "email is required")
|
||||
return
|
||||
}
|
||||
if _, err := s.emails.RequestLoginCode(c.Request.Context(), req.Email); err != nil {
|
||||
if _, err := s.emails.RequestLoginCode(c.Request.Context(), req.Email, req.BrowserTZ); err != nil {
|
||||
s.abortErr(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -16,6 +16,12 @@ type feedbackSubmitRequest struct {
|
||||
Attachment string `json:"attachment"`
|
||||
AttachmentName string `json:"attachment_name"`
|
||||
Channel string `json:"channel"`
|
||||
// Version is the client's app version (pkg/version / the SPA build), snapshotted so the
|
||||
// operator sees which build a report came from.
|
||||
Version string `json:"version"`
|
||||
// BrowserTZ is the client's detected UTC offset ("±HH:MM") at submit, so the operator can
|
||||
// see the filed time in the sender's local zone even before they save a profile.
|
||||
BrowserTZ string `json:"browser_tz"`
|
||||
}
|
||||
|
||||
// feedbackReplyDTO is the operator's reply shown back to the player.
|
||||
@@ -61,7 +67,7 @@ func (s *Server) handleFeedbackSubmit(c *gin.Context) {
|
||||
}
|
||||
attachment = data
|
||||
}
|
||||
if err := s.feedback.Submit(c.Request.Context(), uid, req.Body, attachment, req.AttachmentName, req.Channel, clientIP(c)); err != nil {
|
||||
if err := s.feedback.Submit(c.Request.Context(), uid, req.Body, attachment, req.AttachmentName, req.Channel, req.Version, req.BrowserTZ, clientIP(c)); err != nil {
|
||||
s.abortErr(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
// Package server wires the backend's HTTP listener: the gin engine, its route
|
||||
// groups, the per-request telemetry middleware and the start/stop lifecycle.
|
||||
//
|
||||
// The /api/v1 route groups (public, user, internal, admin) are created here so
|
||||
// later stages attach their endpoints to a stable structure; the /user group
|
||||
// requires the X-User-ID identity header. The probes /healthz (liveness) and
|
||||
// /readyz (database + session-cache readiness) are unauthenticated.
|
||||
// The /api/v1 route groups (public, user, internal, admin) attach their endpoints
|
||||
// to a stable structure; the /user group requires the X-User-ID identity header.
|
||||
// The probes /healthz (liveness) and /readyz (database + session-cache readiness)
|
||||
// are unauthenticated.
|
||||
package server
|
||||
|
||||
import (
|
||||
@@ -245,7 +245,7 @@ func (s *Server) Invitations() *lobby.InvitationService { return s.invitations }
|
||||
func (s *Server) Emails() *account.EmailService { return s.emails }
|
||||
|
||||
// Handler returns the underlying HTTP handler. It lets tests drive the server
|
||||
// without binding a socket and lets later stages compose the backend behind
|
||||
// without binding a socket and lets callers compose the backend behind
|
||||
// another listener.
|
||||
func (s *Server) Handler() http.Handler { return s.http.Handler }
|
||||
|
||||
|
||||
@@ -8,8 +8,7 @@ import (
|
||||
)
|
||||
|
||||
// Service mints, resolves, and revokes sessions over the store and the
|
||||
// write-through cache. The gateway is its only caller (from a later stage); the
|
||||
// HTTP surface is wired then.
|
||||
// write-through cache. The gateway is its only caller.
|
||||
type Service struct {
|
||||
store *Store
|
||||
cache *Cache
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
// in as a message kind. It owns the friendships, blocks and chat_messages tables,
|
||||
// reads the account-level block toggles through account.Store, and gates chat and
|
||||
// nudge on game state through a GameReader so it never imports the engine. The
|
||||
// live delivery of chat and nudges (push / in-app stream) belongs to the gateway
|
||||
// in a later stage; this package only persists and reads them.
|
||||
// live delivery of chat and nudges (push / in-app stream) belongs to the gateway;
|
||||
// this package only persists and reads them.
|
||||
package social
|
||||
|
||||
import (
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@ POSTGRES_PASSWORD=change-me # required
|
||||
# the active version lives in the DB. On a live volume a changed value is ignored (the
|
||||
# recorded .seed_version marker wins — the seed-drift guard); change a running
|
||||
# contour's dictionary through /_gm/dictionary (ARCHITECTURE.md §5).
|
||||
DICT_VERSION=v1.2.1
|
||||
DICT_VERSION=v1.3.0
|
||||
|
||||
# --- Logging ----------------------------------------------------------------
|
||||
LOG_LEVEL=info
|
||||
|
||||
+26
-2
@@ -80,7 +80,7 @@ without it Docker's resolver handles `otelcol`, `gateway` and `api.telegram.org`
|
||||
| --- | --- | --- | --- |
|
||||
| `POSTGRES_DB` | variable | `scrabble` | Database name. |
|
||||
| `POSTGRES_USER` | variable | `scrabble` | Database user. |
|
||||
| `DICT_VERSION` | variable | `v1.2.1` | `scrabble-dictionary` release tag baked into the backend image as the **seed for a fresh volume** (build-arg). A live contour changes dictionary through the admin console, not this; on a seeded volume a changed value is ignored (the recorded `.seed_version` marker wins — the seed-drift guard, ARCHITECTURE.md §5). Set per contour as `TEST_`/`PROD_DICT_VERSION`. |
|
||||
| `DICT_VERSION` | variable | `v1.3.0` | `scrabble-dictionary` release tag baked into the backend image as the **seed for a fresh volume** (build-arg). A live contour changes dictionary through the admin console, not this; on a seeded volume a changed value is ignored (the recorded `.seed_version` marker wins — the seed-drift guard, ARCHITECTURE.md §5). Set per contour as `TEST_`/`PROD_DICT_VERSION`. |
|
||||
| `LOG_LEVEL` | variable | `info` | Shared log level for backend / gateway / validator / bot (`debug\|info\|warn\|error`). |
|
||||
| `CADDY_SITE_ADDRESS` | variable | `:80` | Caddy site address. Test: `:80` (host caddy terminates TLS). Prod: a domain, so caddy does its own ACME. |
|
||||
| `GM_BASICAUTH_USER` | variable | `gm` | Username for the `/_gm` Basic-Auth. |
|
||||
@@ -117,6 +117,28 @@ collector's / gateway's internal IP is fine (connected route), but its `AWG_CONF
|
||||
which resolves `otelcol`, `gateway` and `api.telegram.org`. `GATEWAY_ADMIN_*` is
|
||||
intentionally **unset** — caddy owns `/_gm` in the contour.
|
||||
|
||||
## Bumping the dictionary version
|
||||
|
||||
The dictionary ships as a versioned **release artifact** (`scrabble-dawg-vX.Y.Z.tar.gz`) from
|
||||
[`scrabble-dictionary`](https://gitea.iliadenisov.ru/developer/scrabble-dictionary). The tag is
|
||||
a build-time input with **no default** in the images, so it is set in exactly two places to
|
||||
move the whole stack — change both to a new release:
|
||||
|
||||
1. **CI tests** — `.gitea/workflows/ci.yaml` `env.DICT_VERSION` (the unit/integration jobs
|
||||
download that dawg).
|
||||
2. **Deploy seed** — the Gitea repo variables `TEST_DICT_VERSION` / `PROD_DICT_VERSION` (the tag
|
||||
the deploy bakes into a **fresh** volume's image; the deploy job feeds it to `compose` as
|
||||
`DICT_VERSION`).
|
||||
|
||||
For local builds set `DICT_VERSION` in `deploy/.env` (template: `.env.example`); a bare
|
||||
`docker build` needs `--build-arg DICT_VERSION=vX.Y.Z`. The Dockerfiles and `compose` carry no
|
||||
default — a missing value fails loudly instead of baking a stale tag.
|
||||
|
||||
Bumping the seed is a **no-op on a live volume** (the `.seed_version` marker wins — the
|
||||
seed-drift guard). A running contour/prod moves to a new release **through the admin console**
|
||||
`/_gm/dictionary` (upload the tarball, preview the per-variant diff, confirm); in-flight games
|
||||
keep their pinned version, new games use the new one (ARCHITECTURE.md §5).
|
||||
|
||||
## Production rollout
|
||||
|
||||
Prod runs on **two hosts** (main = full stack + ACME on the domain; tg = the bot only,
|
||||
@@ -128,7 +150,9 @@ Re-run `ansible/` after a host resize — it is idempotent.
|
||||
workflow manually (Gitea → Actions → prod-deploy → run from `master`, input
|
||||
`confirm=deploy`). It builds + pushes the images to the registry, ships the
|
||||
compose/config/certs/env over SSH, deploys the main host with `prod-deploy.sh` (rolling,
|
||||
health-gated, **auto-rollback to the previous tag**), then the bot host, then probes the
|
||||
health-gated, **auto-rollback to the previous tag**; caddy is force-recreated on its roll so
|
||||
a bind-mounted `Caddyfile` change applies — its image is pinned and admin is off, so neither a
|
||||
new tag nor a hot reload would pick it up), then the bot host, then probes the
|
||||
public site. After `master` is green this workflow is the **only** thing that touches
|
||||
prod — nothing auto-deploys there. It runs four visible jobs: **build → deploy-main →
|
||||
deploy-bot → verify** (the per-service rolling shows in the deploy-main log).
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Prod host provisioning (Stage 18)
|
||||
# Prod host provisioning
|
||||
|
||||
Idempotent Ansible that prepares the two production hosts. It installs Docker, a
|
||||
non-sudo `deploy` service account, SSH hardening, a default-deny firewall,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
# Stage 18 host provisioning. Idempotent: safe to re-run after a host resize.
|
||||
# Production host provisioning. Idempotent: safe to re-run after a host resize.
|
||||
# Prepares hosts only (docker, hardening, service account, firewall); the
|
||||
# application is deployed separately by .gitea/workflows/prod-deploy.yaml.
|
||||
|
||||
|
||||
@@ -21,6 +21,18 @@
|
||||
}
|
||||
|
||||
{$CADDY_SITE_ADDRESS::80} {
|
||||
# HTTP/3 is advertised by default whenever this caddy terminates TLS (prod:
|
||||
# CADDY_SITE_ADDRESS is the domain). But UDP/443 is never reachable — the prod
|
||||
# compose maps only "443:443" (TCP) and ufw opens 443/tcp — so a client that cached
|
||||
# the `Alt-Svc: h3` advert (sticky for ma=2592000s) stalls on the dead QUIC path
|
||||
# before falling back to h2, which surfaced as the Telegram Mini App intermittently
|
||||
# hanging on load. `Alt-Svc: clear` actively drops any cached alternative and pins
|
||||
# clients to h2/h1; it is applied site-wide so every route is covered. In the test
|
||||
# contour this caddy serves plain :80 (no h3 to advertise) and the host caddy
|
||||
# re-stamps its own Alt-Svc, so the live test fix lives in the host caddy — here it
|
||||
# is the prod fix. Background + alternatives (incl. serving h3 for real): docs/EDGE_HTTP3.md.
|
||||
header Alt-Svc clear
|
||||
|
||||
# Operator surfaces under /_gm: a single shared Basic-Auth, then route.
|
||||
@gm path /_gm /_gm/*
|
||||
handle @gm {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
#
|
||||
# It (1) publishes caddy 80/443 — there is no host caddy in prod, so the contour caddy
|
||||
# owns the edge and does its own ACME on CADDY_SITE_ADDRESS — and the gateway bot-link
|
||||
# :9443 the remote bot dials in over mTLS; and (2) retunes the R7 limits down for the
|
||||
# :9443 the remote bot dials in over mTLS; and (2) retunes the baseline limits down for the
|
||||
# 2 vCPU / 1.9 GiB host (GOMAXPROCS=2, smaller memory caps, shorter Prometheus
|
||||
# retention). The contour launches deliberately undersized at zero players; the added
|
||||
# node_exporter + Grafana watch host memory so it can be resized at Selectel when
|
||||
@@ -29,7 +29,7 @@ services:
|
||||
ports:
|
||||
- "9443:9443"
|
||||
environment:
|
||||
# 2 vCPU host: align the Go scheduler with the cgroup quota (R7's 3 needs 3 cores).
|
||||
# 2 vCPU host: align the Go scheduler with the cgroup quota (the baseline's 3-core gateway needs 3 cores).
|
||||
GOMAXPROCS: "2"
|
||||
deploy:
|
||||
resources:
|
||||
|
||||
+17
-15
@@ -25,9 +25,9 @@
|
||||
# backend admin relay reaches the gateway at `gateway:9092` (plaintext).
|
||||
name: scrabble
|
||||
|
||||
# Bound every container's json-file logs. R7 measured the backend emitting a
|
||||
# per-request latency line at info (~14 MiB / 30 min under the 500-player stress
|
||||
# peak); without rotation the volume grows unbounded. 10 MiB x 3 files caps each
|
||||
# Bound every container's json-file logs. The backend emits a per-request latency
|
||||
# line at info (~14 MiB / 30 min under the 500-player peak); without rotation the
|
||||
# volume grows unbounded. 10 MiB x 3 files caps each
|
||||
# container at 30 MiB. Applied to every service via the *default-logging alias.
|
||||
x-logging: &default-logging
|
||||
driver: json-file
|
||||
@@ -52,8 +52,8 @@ services:
|
||||
retries: 30
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql/data
|
||||
# R7 starting limits: 512M leaves headroom over the default 128 MB shared_buffers +
|
||||
# per-connection memory (R2 peaked at 28 backends / 69 MiB RSS); tighten after the run.
|
||||
# 512M leaves headroom over the default 128 MB shared_buffers + per-connection
|
||||
# memory (the load harness peaked at 28 backends / 69 MiB RSS).
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
@@ -68,9 +68,11 @@ services:
|
||||
context: ..
|
||||
dockerfile: backend/Dockerfile
|
||||
args:
|
||||
# Seed dictionary for a FRESH volume; the per-contour value comes from the
|
||||
# deploy env (Gitea TEST_/PROD_DICT_VERSION). See the volume note below.
|
||||
DICT_VERSION: ${DICT_VERSION:-v1.2.1}
|
||||
# Seed dictionary for a FRESH volume; required (no default) so the release tag is
|
||||
# set in exactly one place per context — the deploy env (Gitea TEST_/PROD_DICT_VERSION)
|
||||
# or .env for local builds. See the volume note below + deploy/README.md "Bumping the
|
||||
# dictionary version".
|
||||
DICT_VERSION: ${DICT_VERSION:?set DICT_VERSION — the scrabble-dictionary release tag, e.g. in deploy/.env}
|
||||
# Build version stamped into the binary (git tag; see pkg/version).
|
||||
VERSION: ${APP_VERSION:-dev}
|
||||
restart: unless-stopped
|
||||
@@ -81,8 +83,8 @@ services:
|
||||
environment:
|
||||
# search_path=backend matches the migrations (00001 creates the schema).
|
||||
BACKEND_POSTGRES_DSN: postgres://${POSTGRES_USER:-scrabble}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB:-scrabble}?sslmode=disable&search_path=backend
|
||||
# R7 tuned: the pool sat at its 25-conn cap (28 backends total) at 500 players;
|
||||
# 40 gives headroom for bursts. Postgres (2 cores / 512 MiB) handles it.
|
||||
# The pool caps at 25 conns (~28 backends) around 500 players; 40 gives headroom
|
||||
# for bursts. Postgres (2 cores / 512 MiB) handles it.
|
||||
BACKEND_POSTGRES_MAX_OPEN_CONNS: "40"
|
||||
BACKEND_HTTP_ADDR: ":8080"
|
||||
BACKEND_GRPC_ADDR: ":9090"
|
||||
@@ -111,8 +113,8 @@ services:
|
||||
- dawg-data:/opt/dawg
|
||||
# No container healthcheck: the distroless image has no shell/wget. Readiness
|
||||
# is covered by the CI post-deploy probe (GET / through caddy).
|
||||
# R7 starting limits (generous over the R2 ~1-core / <=100 MiB peak); tightened to
|
||||
# the agreed prod values after the final stress run. deploy.resources.limits is
|
||||
# Generous over the ~1-core / <=100 MiB measured peak; the prod overlay trims these
|
||||
# to the launch-host values. deploy.resources.limits is
|
||||
# honoured by `docker compose up` (Compose v2), not only by swarm.
|
||||
deploy:
|
||||
resources:
|
||||
@@ -175,7 +177,7 @@ services:
|
||||
# deploy/gen-certs.sh for the test contour; supplied from PROD_ secrets in prod.
|
||||
volumes:
|
||||
- ${SCRABBLE_CONFIG_DIR:-.}/certs:/certs:ro
|
||||
# R7 tuned: the gateway holds one h2c connection per player, so at 500 players it
|
||||
# The gateway holds one h2c connection per player, so at 500 players it
|
||||
# bursts into a 2-core cap (~2.49% transport_error on game.state); 3 cores absorbs
|
||||
# the bursts. Per-connection overhead is the realistic prod cost — size for it.
|
||||
deploy:
|
||||
@@ -402,8 +404,8 @@ services:
|
||||
volumes:
|
||||
- ${SCRABBLE_CONFIG_DIR:-.}/tempo/tempo.yaml:/etc/tempo/tempo.yaml:ro
|
||||
- tempo-data:/var/tempo
|
||||
# R7 tuned: tempo reached the 1 GiB cap during the final run (446 MiB in R2);
|
||||
# raised to 2 GiB for headroom against OOM under sustained tracing load.
|
||||
# Tempo reached the 1 GiB cap under sustained load (446 MiB in earlier runs);
|
||||
# raised to 2 GiB for headroom against OOM.
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
|
||||
@@ -36,7 +36,21 @@
|
||||
"type": "stat",
|
||||
"title": "Database size",
|
||||
"gridPos": { "h": 5, "w": 6, "x": 18, "y": 0 },
|
||||
"fieldConfig": { "defaults": { "unit": "bytes" }, "overrides": [] },
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "bytes",
|
||||
"color": { "mode": "thresholds" },
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{ "color": "green", "value": null },
|
||||
{ "color": "yellow", "value": 8589934592 },
|
||||
{ "color": "red", "value": 17179869184 }
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"datasource": { "type": "prometheus", "uid": "prometheus" },
|
||||
"targets": [{ "refId": "A", "expr": "max(pg_database_size_bytes{datname=\"scrabble\"})" }]
|
||||
},
|
||||
|
||||
@@ -74,7 +74,13 @@ health_running() { # health_running <container>: running, not restarting, stable
|
||||
roll() { # roll <service> <health-cmd...>
|
||||
local svc="$1"; shift
|
||||
echo ">>> rolling $svc -> $TAG"
|
||||
dc up -d --no-build --no-deps "$svc" || return 1
|
||||
# caddy's image is pinned (caddy:2-alpine, no $TAG) and its Caddyfile is bind-mounted, so a
|
||||
# config-only change leaves the compose definition unchanged: `up -d` treats the container as
|
||||
# current and does not recreate it, and admin is off so there is no hot reload — the new
|
||||
# Caddyfile would never load. Force a recreate for caddy so config changes always apply; every
|
||||
# other service already recreates on its new $TAG image.
|
||||
local recreate=(); [ "$svc" = caddy ] && recreate=(--force-recreate)
|
||||
dc up -d --no-build --no-deps "${recreate[@]}" "$svc" || return 1
|
||||
"$@" || { echo "!!! $svc failed health check"; return 1; }
|
||||
echo "<<< $svc healthy"
|
||||
}
|
||||
|
||||
+32
-16
@@ -2,10 +2,8 @@
|
||||
|
||||
Source of truth for the platform architecture, transport, security model and
|
||||
cross-service contracts. User-visible behaviour per domain lives in
|
||||
[`FUNCTIONAL.md`](FUNCTIONAL.md); the staged build order lives in
|
||||
[`../PLAN.md`](../PLAN.md). This document always describes the **current**
|
||||
design, not the history of how it was reached. Sections describing
|
||||
not-yet-implemented components are marked *(planned)*.
|
||||
[`FUNCTIONAL.md`](FUNCTIONAL.md). This document always describes the **current**
|
||||
design, not the history of how it was reached.
|
||||
|
||||
## 1. Overview
|
||||
|
||||
@@ -160,7 +158,12 @@ arrive from a platform rather than completing a mandatory registration).
|
||||
rendered in the recipient's **interface language** (`preferred_language`, en/ru), not in
|
||||
any bot-scoped language, and the friend-invite **share link** (and its caption) point at
|
||||
that one bot. First Telegram contact seeds the new account's `preferred_language` from the
|
||||
launch `language_code` (§4); the interface language is otherwise edited in Settings.
|
||||
launch `language_code` (§4), but the **interface language follows the device** — the system
|
||||
guess, or an explicit Settings choice saved locally — and the bot never dictates the UI.
|
||||
`preferred_language` is then **reconciled to the active interface locale on every session
|
||||
adopt** (not only on a Settings change; a no-op for guests and when already equal), so the
|
||||
server-rendered language surfaces — this push and the ad banner — always match the UI rather
|
||||
than stranding a user who never opened Settings on the creation-time seed.
|
||||
- **Variant preferences (New Game gating).** Which variants a player may be matched into is a
|
||||
per-user **profile** setting — `variant_preferences`, a set of `engine.Variant` labels
|
||||
(`scrabble_en`, `scrabble_ru`, `erudit_ru`) edited on the Settings/Profile screen. New
|
||||
@@ -642,7 +645,7 @@ in either direction (the enqueue excludes the caller's `BlockedWith` set);
|
||||
**floats games with any unread entry to the top** of the your-turn and opponent-turn
|
||||
sections (the finished section keeps its activity order). On each clear the publish-to-read
|
||||
latency is recorded; the read time itself is not retained.
|
||||
- **Profile**: `preferred_language` (en/ru, edited in Settings), display name, email
|
||||
- **Profile**: `preferred_language` (en/ru; tracks the interface language — §4), display name, email
|
||||
(confirm-code binding, see §4), **timezone**, the daily **away window**, the
|
||||
**variant preferences** (`variant_preferences`, the matchable-variant set that gates New
|
||||
Game — §3, defaulting to Erudit only, at least one enforced) and the
|
||||
@@ -651,7 +654,11 @@ in either direction (the enqueue excludes the caller's `BlockedWith` set);
|
||||
separators (no leading/trailing/adjacent separators, ≤ 32 runes); the timezone is a
|
||||
fixed `±HH:MM` **UTC offset** (or a legacy IANA name) resolved by `account.ResolveZone`
|
||||
for the sweeper and the robot's sleep (a fixed offset trades DST for a simple
|
||||
picker); the away window is at most **12 h** (midnight-wrap aware). Linked platform
|
||||
picker), and is **seeded at account creation** from the client's detected offset — sent
|
||||
on the Telegram / guest / email first-contact request — so the robot's sleep and the
|
||||
away-window sweeper are anchored to the player's real zone from the first game rather
|
||||
than the `UTC` default (an undetected or malformed offset keeps the default); the away
|
||||
window is at most **12 h** (midnight-wrap aware). Linked platform
|
||||
accounts and merge are covered in §4.
|
||||
|
||||
## 9. Persistence
|
||||
@@ -1033,8 +1040,9 @@ a dedicated redeem sub-limit or a longer code is the hardening step if abuse app
|
||||
Single public origin, path-routed. The Vite build has two entries: a lightweight
|
||||
**landing page** and the game **SPA**. The gateway **embeds** the SPA build
|
||||
(`go:embed`, baked in by a node stage in `gateway/Dockerfile`) and serves it at
|
||||
`/app/` (web) and `/telegram/` (the Telegram Mini App; outside Telegram that path
|
||||
redirects to the root — the client-side guard); a stray hit on the gateway's `/`
|
||||
`/app/` (web) and `/telegram/` (the Telegram Mini App; on that path without sign-in data
|
||||
— no `initData` — the client renders a compact, shareable launch-diagnostic screen instead
|
||||
of redirecting away); a stray hit on the gateway's `/`
|
||||
308-redirects to `/app/`. The **landing** ships in its own static container: the
|
||||
`landing` target of `gateway/Dockerfile` (caddy:2-alpine + the same Vite build,
|
||||
`deploy/landing/Caddyfile`) serves it at `/`, so stray public traffic is absorbed by
|
||||
@@ -1091,7 +1099,10 @@ Two contours, two secret/variable prefixes (`TEST_` / `PROD_`):
|
||||
the **main host** runs the full stack (`docker-compose.yml` + `docker-compose.prod.yml`),
|
||||
the **bot host** runs only the bot (`docker-compose.bot.yml`, no VPN — native Bot API
|
||||
egress, telemetry off). There is no host caddy, so the contour caddy terminates TLS —
|
||||
`CADDY_SITE_ADDRESS` is the domain and caddy does its own ACME. The gateway **publishes**
|
||||
`CADDY_SITE_ADDRESS` is the domain and caddy does its own ACME. Caddy advertises HTTP/3 by default, but UDP/443 is not exposed (the
|
||||
compose maps only TCP and ufw opens 443/tcp), so the edge emits `Alt-Svc: clear` to keep
|
||||
clients on h2/h1 rather than stall on a dead QUIC path — see [`EDGE_HTTP3.md`](EDGE_HTTP3.md).
|
||||
The gateway **publishes**
|
||||
the bot-link `:9443`; the remote bot dials it over mTLS (certs from `PROD_BOTLINK_*`,
|
||||
ServerName `gateway`, so TLS validation is independent of the public dial address), holds
|
||||
no inbound port, and login is unaffected if that host or the link is down.
|
||||
@@ -1107,7 +1118,7 @@ Two contours, two secret/variable prefixes (`TEST_` / `PROD_`):
|
||||
**`prod-rollback`** workflow re-deploys any prior release tag (blank input = the previous
|
||||
deployed version, tracked on the host) over the same rolling, health-gated path — image-only,
|
||||
no DB migration. The main host is
|
||||
intentionally **launch-sized** (2 vCPU / 1.9 GiB): the prod overlay trims the R7 limits
|
||||
intentionally **launch-sized** (2 vCPU / 1.9 GiB): the prod overlay trims the baseline limits
|
||||
(`GOMAXPROCS=2`, smaller caps, 7d Prometheus retention) and a **node_exporter** feeds
|
||||
host-memory metrics to Grafana so it can be resized reactively as players arrive.
|
||||
`GATEWAY_ABUSE_BAN_ENABLED=true` in prod (the per-IP ban is meaningful only with real
|
||||
@@ -1151,9 +1162,11 @@ Two contours, two secret/variable prefixes (`TEST_` / `PROD_`):
|
||||
|
||||
Players reach the operators through a **Feedback** screen (Settings → Info, registered accounts
|
||||
only). A message (≤1024 runes) plus an optional single attachment is stored in
|
||||
`feedback_messages`; the sender's IP (gateway-forwarded, as for chat) and the submitting
|
||||
**channel** (telegram/ios/android/web, client-reported and validated) are recorded. The domain
|
||||
is `internal/feedback` (store + service), modelled on the admin chat-moderation surface.
|
||||
`feedback_messages`; the sender's IP (gateway-forwarded, as for chat), the submitting
|
||||
**channel** (telegram/ios/android/web, client-reported and validated), the **client app version**
|
||||
(`__APP_VERSION__`, the build a report was sent from), the client's **detected UTC offset** at
|
||||
submit (`browser_tz`, `±HH:MM`) and a snapshot of the sender's interface language are recorded. The domain is `internal/feedback` (store + service), modelled on the admin
|
||||
chat-moderation surface.
|
||||
|
||||
**Anti-spam.** A player with an unreviewed message (`read_at IS NULL`) cannot submit another; the
|
||||
gate is server-side. Because the operator must act before the next message, this is itself the
|
||||
@@ -1161,8 +1174,11 @@ rate limit — there is no separate per-user feedback limiter.
|
||||
|
||||
**Operator review** happens in the server-rendered console (`/_gm/feedback`): an
|
||||
unread / read / archived queue with per-user search (the `/users` glob masks), a detail card
|
||||
(user content rendered as auto-escaped `html/template` text), and the read / reply / archive /
|
||||
delete / delete-all actions — each marks the message read; merely opening the detail does not.
|
||||
(user content rendered as auto-escaped `html/template` text; it shows the channel, interface
|
||||
language and app version, and the filed time in three zones — UTC, the browser offset detected at
|
||||
submit, and the sender's saved profile zone, each `N/A` when not known), and the read /
|
||||
reply / archive / delete / delete-all actions — each marks the message read; merely opening the
|
||||
detail does not.
|
||||
The attachment is served from `/_gm/feedback/:id/attachment` with `X-Content-Type-Options:
|
||||
nosniff`: images inline (loaded only via `<img>`, which never executes — a renamed non-image is
|
||||
inert), everything else as an `application/octet-stream` download. The UI gates the attachment by
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
# Edge HTTP/3 (`Alt-Svc`) policy
|
||||
|
||||
## TL;DR
|
||||
|
||||
The edge **advertises HTTP/3 but does not actually serve it** (UDP/443 is not exposed),
|
||||
so we suppress the advert with `Alt-Svc: clear`. Advertising QUIC on `:443/udp` while
|
||||
that port is unreachable makes clients — notably the Telegram Mini App webview — stall
|
||||
on a dead QUIC connection before falling back to h2, which shows up as the app "hanging
|
||||
on load".
|
||||
|
||||
## Symptom
|
||||
|
||||
Opening the Mini App intermittently hangs on load: from a barely-noticeable pause to
|
||||
several seconds, sometimes a blank window that never finishes downloading `index.html`.
|
||||
Intermittent, worse after the first successful visit, reproduced on both the test
|
||||
contour and prod.
|
||||
|
||||
## Root cause
|
||||
|
||||
Caddy enables HTTP/3 by default on any TLS listener and emits
|
||||
`Alt-Svc: h3=":443"; ma=2592000` — telling every client "reach me over QUIC/UDP 443"
|
||||
and to cache that for 30 days. But UDP/443 is **never reachable end to end**:
|
||||
|
||||
- **Test contour**: the host caddy publishes only `:443/tcp` (`docker port caddy` shows
|
||||
no `udp`); QUIC packets from the internet are dropped.
|
||||
- **Prod**: `deploy/docker-compose.prod.yml` maps `"443:443"` (Docker = **TCP only**)
|
||||
and `deploy/ansible/roles/main/tasks/main.yml` opens 443 `proto: tcp`. UDP/443 is
|
||||
dropped at both the publish and the firewall.
|
||||
|
||||
Caddy *does* bind `udp/443` inside the container and h3 works container-to-container
|
||||
(verified `http=3 code=200`), so the listener is healthy — it is simply not exposed.
|
||||
|
||||
A client that cached the advert tries QUIC first on later opens, gets no response, and
|
||||
waits for the QUIC attempt to time out before falling back to TCP/h2. That wait is the
|
||||
stall. The very first visit (no cached `Alt-Svc`) uses h2 and is fast.
|
||||
|
||||
The h2/TCP serving path itself is healthy: 30 fresh-TLS requests through the full path
|
||||
(host caddy -> contour caddy -> gateway) measured TTFB ~9.5 ms, total ~9.8 ms, no tail;
|
||||
`index.html` is ~1 KB.
|
||||
|
||||
## Fix in place (option A — suppress the advert)
|
||||
|
||||
Emit `Alt-Svc: clear`, which actively drops any cached alternative (better than merely
|
||||
deleting the header, which leaves the sticky 30-day cache in place):
|
||||
|
||||
- **Prod / repo**: `deploy/caddy/Caddyfile` — a site-level `header Alt-Svc clear` (this
|
||||
caddy terminates TLS in prod).
|
||||
- **Test contour**: the host caddy terminates TLS, so the fix lives there (homelab
|
||||
config, outside this repo): `header Alt-Svc clear` on the `scrabble.*` site. The
|
||||
in-compose caddy serves plain `:80` in test and never advertises h3, so the repo
|
||||
directive is a harmless no-op there (the host caddy re-stamps the header).
|
||||
|
||||
`header Alt-Svc clear` overrides Caddy's auto-advert (verified) and is site-scoped.
|
||||
|
||||
### Verify
|
||||
|
||||
The runner/prod host shell cannot reach the Docker bridge IPs directly, so probe from a
|
||||
container on the relevant network, using `--resolve` to hit the TLS-terminating caddy by
|
||||
its bridge IP (this also bypasses the public-IP NAT hairpin):
|
||||
|
||||
```sh
|
||||
# <edge-ip> = the TLS-terminating caddy's IP on its network (docker inspect ... )
|
||||
docker run --rm --network edge curlimages/curl:latest -sS -D - -o /dev/null \
|
||||
--resolve <host>:443:<edge-ip> https://<host>/telegram/ | grep -iE '^HTTP|^alt-svc'
|
||||
# expect: HTTP/2 200, and NO `alt-svc: h3=...` (the header is absent or `alt-svc: clear`)
|
||||
```
|
||||
|
||||
## If it recurs — alternatives to try
|
||||
|
||||
So we do not re-derive the diagnosis from scratch:
|
||||
|
||||
1. **Re-confirm the advert is actually suppressed** with the verify command above. A
|
||||
redeploy or a Caddy upgrade could regress it, or a client may still hold a cached
|
||||
`h3` entry that has not yet been replaced by a `clear` (it needs one successful h2
|
||||
response to receive the `clear`).
|
||||
2. **Option B — serve HTTP/3 for real** instead of suppressing it. Worth it only if we
|
||||
actually want QUIC (the benefit is marginal for a ~1 KB shell plus hash-immutable
|
||||
cached assets, and it adds UDP/QUIC attack surface):
|
||||
- Publish UDP: add `"443:443/udp"` next to the TCP map in
|
||||
`deploy/docker-compose.prod.yml` (and publish udp/443 on the test host caddy too).
|
||||
- Open the firewall: add a `443 proto: udp` rule in
|
||||
`deploy/ansible/roles/main/tasks/main.yml`.
|
||||
- Drop the `header Alt-Svc clear` so Caddy advertises h3 again.
|
||||
- Verify with an h3 client from inside the network:
|
||||
`docker run --rm --network edge ymuski/curl-http3 curl --http3-only ...` should
|
||||
return `http=3 code=200`.
|
||||
3. **Look past the edge** if the advert is suppressed and stalls persist. The h2 path is
|
||||
fast server-side, so a remaining stall is most likely the client network / RTT / the
|
||||
provider, not our stack. Re-run the timing loop (below) to confirm the server is
|
||||
still <~10 ms TTFB before chasing the client side.
|
||||
|
||||
## How this was diagnosed (method, to repeat)
|
||||
|
||||
- The runner/prod host shell cannot reach the Docker bridge subnets, so all probing runs
|
||||
from a throwaway container on the target network (`docker run --network <net>
|
||||
curlimages/curl`), using `--resolve <host>:443:<edge-ip>` to bypass the public-IP NAT
|
||||
hairpin and exercise the real TLS path.
|
||||
- Compare a fresh-connection timing loop (worst case, full TLS each time) against a
|
||||
keepalive batch to separate handshake cost from serving cost:
|
||||
|
||||
```sh
|
||||
docker run --rm --network edge curlimages/curl:latest sh -c '
|
||||
for i in $(seq 1 30); do
|
||||
curl -sS -o /dev/null --resolve <host>:443:<edge-ip> \
|
||||
-w "http=%{http_version} code=%{http_code} tls=%{time_appconnect} ttfb=%{time_starttransfer} total=%{time_total}\n" \
|
||||
https://<host>/telegram/
|
||||
done'
|
||||
```
|
||||
|
||||
- `docker port <caddy>` shows whether `udp/443` is actually published; the response
|
||||
`Alt-Svc` header shows what the edge advertises. The two disagreeing is the bug.
|
||||
+8
-2
@@ -213,6 +213,9 @@ block **overrides but does not delete** an existing friendship (so you may block
|
||||
they keep seeing you as one); active games are never interrupted — you can finish them, with
|
||||
the blocked opponent's chat composer hidden (only the log remains). Blocking from a game card
|
||||
mirrors the block in **Settings → Friends**; **unblock** and **unfriend** live there only.
|
||||
On Settings → Friends each friend is a one-line row whose right-hand kebab (⋮) slides open
|
||||
**block 🚫** and **remove ✖️** icon actions, and each action is gated by a confirmation
|
||||
that names the friend (*Block this player?* / *Remove from friends?*).
|
||||
Blocking an **auto-match opponent who is secretly a robot** behaves the same in that game
|
||||
(struck name, hidden composer) and lists the blocked opponent under the name you saw, but is
|
||||
recorded only against that game — the disguise holds, the shared robot is never globally
|
||||
@@ -241,7 +244,8 @@ also clears the moment its recipient **takes their move**.
|
||||
Edit the display name (letters joined by a single space / "." / "_" separator, with an
|
||||
optional trailing "." or a trailing run of up to five digits, up to 32 characters and at most
|
||||
5 special characters — the "." / "_" punctuation, spaces and digits aside), the timezone
|
||||
(chosen as a UTC offset), the
|
||||
(chosen as a UTC offset, and pre-filled from your device's detected offset when the account
|
||||
is first created — so robot games are timed correctly before you ever open this form), the
|
||||
daily away window (on a 10-minute grid, at most 12 hours, wrapping midnight) and the
|
||||
block toggles. The profile form is edited inline (no separate edit mode). Linking
|
||||
an email or Telegram and merging accounts are covered under "Accounts, linking &
|
||||
@@ -346,7 +350,9 @@ over-grant cannot be reversed there.
|
||||
The console works a **feedback** queue too (`/_gm/feedback`): the messages players sent, filtered
|
||||
**unread / read / archived** with per-user search, each shown with its sender, source, channel
|
||||
(with the bot language — en/ru — for a Telegram message), the sender's interface
|
||||
language, IP and any attachment. The operator can mark a message read, **reply** to the player (delivered
|
||||
language, the **app version** it was sent from, IP, the filed time (in three zones — UTC, the
|
||||
browser zone detected at submit, and the sender's saved zone, each shown `N/A` when not known) and
|
||||
any attachment. The operator can mark a message read, **reply** to the player (delivered
|
||||
in-app), archive it, delete it, or delete every message from that player — and, alongside a delete,
|
||||
**bar the player from feedback** (a `feedback_banned` role, distinct from a full account block: it
|
||||
stops only feedback submission). Roles are listed and granted/revoked on the user card. Opening a
|
||||
|
||||
@@ -218,6 +218,9 @@ _Вход сейчас только через провайдера, поэто
|
||||
заблокированного соперника «подвал» чата скрыт (остаётся только лог). Блокировка с карточки в
|
||||
партии повторяет блокировку в **Настройках → Друзья**; **разблокировка** и **удаление из друзей**
|
||||
есть только там.
|
||||
В **Настройках → Друзья** каждый друг — однострочник, чей правый кебаб (⋮) выдвигает
|
||||
иконки-действия **заблокировать 🚫** и **удалить ✖️**, и каждое действие подтверждается
|
||||
диалогом с именем друга (*Заблокировать?* / *Удалить из друзей?*).
|
||||
Блокировка **авто-матч соперника, который втайне робот**, в этой партии ведёт себя так же
|
||||
(зачёркнутое имя, скрытый «подвал») и в списке заблокированных показывается под тем именем,
|
||||
которое ты видел, но записывается только для этой партии — маскировка сохраняется, общий
|
||||
@@ -248,8 +251,9 @@ _Вход сейчас только через провайдера, поэто
|
||||
Редактирование отображаемого имени (буквы, разделённые одиночным пробелом / «.» /
|
||||
«_», с необязательной завершающей «.» или хвостом до пяти цифр, до 32 символов и не
|
||||
более 5 спецсимволов — пунктуации «.» / «_», пробелы и цифры не в счёт), таймзоны (выбор смещения от
|
||||
UTC), суточного окна отсутствия (away; сетка по 10 минут, не более 12 часов, с
|
||||
переходом через полночь) и переключателей блокировок. Форма профиля редактируется
|
||||
UTC; при создании аккаунта она подставляется из определённого смещения устройства — чтобы
|
||||
игры с роботом таймились правильно ещё до открытия этой формы), суточного окна отсутствия
|
||||
(away; сетка по 10 минут, не более 12 часов, с переходом через полночь) и переключателей блокировок. Форма профиля редактируется
|
||||
сразу (без отдельного режима редактирования). Привязка email и Telegram, а также
|
||||
слияние аккаунтов вынесены в раздел «Аккаунты, привязка и слияние».
|
||||
|
||||
@@ -356,7 +360,8 @@ high-rate флага. С карточки пользователя операт
|
||||
Консоль ведёт и очередь **обратной связи** (`/_gm/feedback`): присланные игроками сообщения с фильтром
|
||||
**непрочитанные / прочитанные / архив** и поиском по пользователю, каждое — с отправителем, источником,
|
||||
каналом (и языком бота — en/ru — для сообщения из Telegram), языком интерфейса отправителя,
|
||||
IP и вложением. Оператор может пометить сообщение прочитанным, **ответить** игроку (доставка
|
||||
**версией приложения**, с которой отправлено, IP, временем подачи (в трёх зонах — UTC, зоне браузера
|
||||
на момент отправки и сохранённой зоне отправителя, каждая — «N/A», если неизвестна) и вложением. Оператор может пометить сообщение прочитанным, **ответить** игроку (доставка
|
||||
в приложение), отправить в архив, удалить или удалить все сообщения этого игрока — и вместе с удалением
|
||||
**запретить игроку обратную связь** (роль `feedback_banned`, отличная от полной блокировки аккаунта:
|
||||
останавливает только отправку обратной связи). Роли перечислены и выдаются/снимаются на карточке
|
||||
|
||||
+5
-6
@@ -121,7 +121,7 @@ tests or touching CI.
|
||||
Postgres-backed `inttest` drives the **guest reaper** end to end (an abandoned guest is
|
||||
reaped; a too-young guest, a seated guest and a durable account are kept).
|
||||
- **Load test & resource baseline** — a reusable `loadtest/` module
|
||||
(`scrabble/loadtest`) is the pre-release stress harness. It **seeds** a large account
|
||||
(`scrabble/loadtest`) is the stress/load harness. It **seeds** a large account
|
||||
population with pre-created sessions directly in Postgres (token hashes matching
|
||||
`backend/internal/session`), **drives** virtual players through the edge protocol —
|
||||
real games assembled via invitations, **mid-ranked** legal moves generated locally by
|
||||
@@ -154,13 +154,12 @@ tests or touching CI.
|
||||
- No network or real platform calls in unit tests; validate platform
|
||||
credentials behind an interface seam and test with fixtures.
|
||||
|
||||
## Per-stage CI gate
|
||||
## CI gate
|
||||
|
||||
Every completed stage is exercised on `gitea.iliadenisov.ru` before it is marked
|
||||
done in [`../PLAN.md`](../PLAN.md):
|
||||
Every change is exercised on `gitea.iliadenisov.ru` before it is merged:
|
||||
|
||||
1. Commit the stage on its `feature/*` branch.
|
||||
1. Commit the change on its `feature/*` branch.
|
||||
2. Push to `origin`.
|
||||
3. Watch the run to completion — never hand-roll a poll loop:
|
||||
`python3 ~/.claude/bin/gitea-ci-watch.py` (launch in the background).
|
||||
4. Only after every workflow that fired is green may the stage be marked done.
|
||||
4. Only after every workflow that fired is green may the change be merged.
|
||||
|
||||
+21
-10
@@ -8,7 +8,13 @@ emoji glyphs. Tokens are CSS custom properties (`ui/src/app.css`), light/dark vi
|
||||
`prefers-color-scheme` or an explicit Settings choice, and **Telegram-themed**:
|
||||
on a Telegram Mini App launch — the app is served under `/telegram/` and detects the
|
||||
launch by `Telegram.WebApp.initData` — the SDK's `themeParams` override the tokens at
|
||||
runtime; opened outside Telegram, the `/telegram/` path redirects to the site root.
|
||||
runtime; on that path without sign-in data (no `initData` — outside Telegram, or a Mini App
|
||||
launch that delivered none, as seen on some Android clients) the app renders a compact,
|
||||
shareable launch-diagnostic screen (`screens/TelegramLaunchError.svelte`) rather than
|
||||
redirecting to the site root. `telegram-web-app.js` is loaded **dynamically with a timeout**,
|
||||
only on a Telegram entry — not a render-blocking `<script>` in the shared `index.html` shell —
|
||||
so a network that blocks `telegram.org` cannot hang the page; `/app/` (web) and the native build
|
||||
never load it.
|
||||
|
||||
## Layout shell (`components/Screen.svelte`)
|
||||
|
||||
@@ -91,14 +97,16 @@ dismisses as soon as the lobby is ready. The pure layout and timing live in `lib
|
||||
which leaks into the Telegram Desktop webview and otherwise fights it) and the Settings
|
||||
theme switcher is hidden; the nav bar takes Telegram's background and `setHeaderColor` /
|
||||
`setBackgroundColor` / `setBottomBarColor` paint Telegram's own chrome to match; the
|
||||
native header **BackButton** drives back-navigation (the app's chevron is hidden in
|
||||
Telegram); **HapticFeedback** fires on tile placement / commit / error; on **mobile**
|
||||
clients the app enters **immersive fullscreen** on launch (`requestFullscreen`, Bot API
|
||||
8.0+) like Telegram's own Mini Apps, while desktop keeps the bot's full-size window;
|
||||
**closing confirmation** is enabled while a game is open **on mobile only** (on desktop
|
||||
closing is deliberate and the "changes may not be saved" dialog is just noise — move drafts
|
||||
auto-save); **vertical swipes** (swipe-to-minimise)
|
||||
are disabled so they don't fight tile drag or the board scroll; **external links** (the word-check
|
||||
app's **own back chevron** (Header) drives back-navigation on every platform — the native
|
||||
Telegram BackButton is not used, as it does not render reliably in the windowed Mini App;
|
||||
**HapticFeedback** fires on tile placement / commit / error; the app calls `expand()` for the
|
||||
bot's full-size (max-height) window but **never `requestFullscreen`** — immersive fullscreen hid
|
||||
the native header (and its BackButton) and the Android system swipe-back then minimised the app,
|
||||
so it stays windowed with Telegram's thin native header (close) above the app's own header; move
|
||||
drafts auto-save, so there is **no closing-confirmation guard**; a hidden **debug panel** (ten
|
||||
quick taps on the header title) shows and shares a privacy-safe client diagnostic snapshot for
|
||||
support; **vertical swipes** (swipe-to-minimise) are disabled so they don't fight tile drag or
|
||||
the board scroll; **external links** (the word-check
|
||||
dictionary lookup, the rules link, operator-reply links) open through `Telegram.WebApp.openLink`
|
||||
so Telegram shows them in its in-app browser instead of the WebView's "open this link?"
|
||||
confirmation a plain `target=_blank` triggers; and a live stream dropped
|
||||
@@ -109,7 +117,10 @@ dismisses as soon as the lobby is ready. The pure layout and timing live in `lib
|
||||
## Tiles & board
|
||||
|
||||
- **Tiles**: the letter sits in the **top-left** corner (offset a touch more than the
|
||||
value), the point value bottom-right; blanks show no value.
|
||||
value), the point value bottom-right; blanks show no value. In **Erudit** the blank is the
|
||||
"звёздочка" (star) chip: an unplaced blank shows the star (`✻`, U+273B) centred on the rack
|
||||
tile, and a placed blank carries it in the value corner; the Scrabble variants leave the
|
||||
blank unmarked (`usesStarBlank` in `lib/variants.ts`).
|
||||
- **Board zoom** (`Board.svelte`): a two-state zoom (full 15×15 ↔ ~9 cells) by **growing
|
||||
the board's width** inside a fixed-size viewport (a real layout change → native scroll
|
||||
that works consistently across browsers; no `transform`, which broke scrolling
|
||||
|
||||
@@ -184,8 +184,10 @@ type ChatResp struct {
|
||||
}
|
||||
|
||||
// TelegramAuth provisions/finds the Telegram account and mints a session, seeding a
|
||||
// brand-new account's display name and language from the validated launch fields.
|
||||
func (c *Client) TelegramAuth(ctx context.Context, externalID, languageCode, username, firstName string) (SessionResp, error) {
|
||||
// brand-new account's display name and language from the validated launch fields and
|
||||
// its time zone from browserTz (the client's detected "±HH:MM" UTC offset; first
|
||||
// contact only).
|
||||
func (c *Client) TelegramAuth(ctx context.Context, externalID, languageCode, username, firstName, browserTz string) (SessionResp, error) {
|
||||
var out SessionResp
|
||||
err := c.do(ctx, http.MethodPost, "/api/v1/internal/sessions/telegram", "", "",
|
||||
map[string]string{
|
||||
@@ -193,6 +195,7 @@ func (c *Client) TelegramAuth(ctx context.Context, externalID, languageCode, use
|
||||
"language_code": languageCode,
|
||||
"username": username,
|
||||
"first_name": firstName,
|
||||
"browser_tz": browserTz,
|
||||
}, &out)
|
||||
return out, err
|
||||
}
|
||||
@@ -243,17 +246,21 @@ func (c *Client) ChatAccessByUser(ctx context.Context, userID string) (ChatAcces
|
||||
return out, err
|
||||
}
|
||||
|
||||
// GuestAuth provisions a guest account and mints a session.
|
||||
func (c *Client) GuestAuth(ctx context.Context) (SessionResp, error) {
|
||||
// GuestAuth provisions a guest account and mints a session, seeding its time zone
|
||||
// from browserTz (the client's detected "±HH:MM" UTC offset).
|
||||
func (c *Client) GuestAuth(ctx context.Context, browserTz string) (SessionResp, error) {
|
||||
var out SessionResp
|
||||
err := c.do(ctx, http.MethodPost, "/api/v1/internal/sessions/guest", "", "", struct{}{}, &out)
|
||||
err := c.do(ctx, http.MethodPost, "/api/v1/internal/sessions/guest", "", "",
|
||||
map[string]string{"browser_tz": browserTz}, &out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
// EmailRequest asks the backend to mail a login code.
|
||||
func (c *Client) EmailRequest(ctx context.Context, email string) error {
|
||||
// EmailRequest asks the backend to mail a login code, provisioning the account on
|
||||
// first contact; browserTz (the client's detected "±HH:MM" UTC offset) seeds the new
|
||||
// account's time zone, since the email account is created here, not at login.
|
||||
func (c *Client) EmailRequest(ctx context.Context, email, browserTz string) error {
|
||||
return c.do(ctx, http.MethodPost, "/api/v1/internal/sessions/email/request", "", "",
|
||||
map[string]string{"email": email}, nil)
|
||||
map[string]string{"email": email, "browser_tz": browserTz}, nil)
|
||||
}
|
||||
|
||||
// EmailLogin verifies a login code and mints a session.
|
||||
|
||||
@@ -27,12 +27,14 @@ type FeedbackUnreadResp struct {
|
||||
|
||||
// FeedbackSubmit posts a feedback message. The attachment bytes are base64-encoded
|
||||
// into the JSON body for the internal hop; clientIP rides X-Forwarded-For.
|
||||
func (c *Client) FeedbackSubmit(ctx context.Context, userID, body string, attachment []byte, attachmentName, channel, clientIP string) error {
|
||||
func (c *Client) FeedbackSubmit(ctx context.Context, userID, body string, attachment []byte, attachmentName, channel, version, browserTz, clientIP string) error {
|
||||
payload := map[string]string{
|
||||
"body": body,
|
||||
"attachment": "",
|
||||
"attachment_name": attachmentName,
|
||||
"channel": channel,
|
||||
"version": version,
|
||||
"browser_tz": browserTz,
|
||||
}
|
||||
if len(attachment) > 0 {
|
||||
payload["attachment"] = base64.StdEncoding.EncodeToString(attachment)
|
||||
|
||||
@@ -158,7 +158,7 @@ func authTelegramHandler(backend *backendclient.Client, tg TelegramValidator) Ha
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sess, err := backend.TelegramAuth(ctx, user.ExternalID, user.LanguageCode, user.Username, user.FirstName)
|
||||
sess, err := backend.TelegramAuth(ctx, user.ExternalID, user.LanguageCode, user.Username, user.FirstName, string(in.BrowserTz()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -167,8 +167,15 @@ func authTelegramHandler(backend *backendclient.Client, tg TelegramValidator) Ha
|
||||
}
|
||||
|
||||
func authGuestHandler(backend *backendclient.Client) Handler {
|
||||
return func(ctx context.Context, _ Request) ([]byte, error) {
|
||||
sess, err := backend.GuestAuth(ctx)
|
||||
return func(ctx context.Context, req Request) ([]byte, error) {
|
||||
// The guest bootstrap historically carried no payload; the detected zone is
|
||||
// optional, so an absent or empty one simply yields no time-zone seed (rather
|
||||
// than panicking in GetRootAs* on a zero-length buffer).
|
||||
var browserTz string
|
||||
if len(req.Payload) > 0 {
|
||||
browserTz = string(fb.GetRootAsGuestLoginRequest(req.Payload, 0).BrowserTz())
|
||||
}
|
||||
sess, err := backend.GuestAuth(ctx, browserTz)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -179,7 +186,7 @@ func authGuestHandler(backend *backendclient.Client) Handler {
|
||||
func authEmailRequestHandler(backend *backendclient.Client) Handler {
|
||||
return func(ctx context.Context, req Request) ([]byte, error) {
|
||||
in := fb.GetRootAsEmailRequestRequest(req.Payload, 0)
|
||||
if err := backend.EmailRequest(ctx, string(in.Email())); err != nil {
|
||||
if err := backend.EmailRequest(ctx, string(in.Email()), string(in.BrowserTz())); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return encodeAck(true), nil
|
||||
@@ -499,7 +506,7 @@ func hideGameHandler(backend *backendclient.Client) Handler {
|
||||
func feedbackSubmitHandler(backend *backendclient.Client) Handler {
|
||||
return func(ctx context.Context, req Request) ([]byte, error) {
|
||||
in := fb.GetRootAsFeedbackSubmitRequest(req.Payload, 0)
|
||||
if err := backend.FeedbackSubmit(ctx, req.UserID, string(in.Body()), in.AttachmentBytes(), string(in.AttachmentName()), string(in.Channel()), req.ClientIP); err != nil {
|
||||
if err := backend.FeedbackSubmit(ctx, req.UserID, string(in.Body()), in.AttachmentBytes(), string(in.AttachmentName()), string(in.Channel()), string(in.Version()), string(in.BrowserTz()), req.ClientIP); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return encodeAck(true), nil
|
||||
|
||||
+2
-1
@@ -12,7 +12,8 @@
|
||||
|
||||
# --- dictionary artifact -----------------------------------------------------
|
||||
FROM alpine:3.20 AS dawg
|
||||
ARG DICT_VERSION=v1.2.1
|
||||
# Required, no default: the build caller supplies the scrabble-dictionary release tag.
|
||||
ARG DICT_VERSION
|
||||
RUN apk add --no-cache curl tar
|
||||
RUN mkdir -p /dawg \
|
||||
&& curl -fsSL -o /tmp/dawg.tar.gz \
|
||||
|
||||
+5
-5
@@ -1,6 +1,6 @@
|
||||
# loadtest — stress harness
|
||||
|
||||
Reusable load harness for the pre-release stress pass. It
|
||||
Reusable load/stress harness. It
|
||||
seeds a large account population with pre-created sessions, drives virtual players
|
||||
through the **gateway edge protocol** in realistic games, hammers the rate limiter,
|
||||
and prints a trip-report summary. It stays in the repo for repeats.
|
||||
@@ -35,8 +35,8 @@ The harness reaches Postgres and the gateway directly, so run it as a one-shot
|
||||
container on the contour's docker network (this bypasses the host→gateway hairpin):
|
||||
|
||||
```sh
|
||||
# from the repo root
|
||||
docker build -f loadtest/Dockerfile -t scrabble-loadtest .
|
||||
# from the repo root (DICT_VERSION has no default — pass the scrabble-dictionary release tag)
|
||||
docker build --build-arg DICT_VERSION=v1.3.0 -f loadtest/Dockerfile -t scrabble-loadtest .
|
||||
|
||||
docker run --rm --cpus=3 --name scrabble-loadtest --network scrabble-internal \
|
||||
-e POSTGRES_PASSWORD="$TEST_POSTGRES_PASSWORD" \
|
||||
@@ -107,6 +107,6 @@ gateway→backend connection-pool fix, and the revised sizing — are written up
|
||||
|
||||
The harness shares the host CPU with the contour, so its own `scrabble-loadtest`
|
||||
container series is read alongside the system under test; capping it with `--cpus`
|
||||
keeps the contour's quota. Per-player transports (R7) removed the shared-transport
|
||||
artifact that inflated R2's `transport_error`, so the figures reflect the system. A
|
||||
keeps the contour's quota. Per-player transports removed the shared-transport
|
||||
artifact that previously inflated `transport_error`, so the figures reflect the system. A
|
||||
fully isolated ceiling on separate hardware remains future work.
|
||||
|
||||
@@ -129,7 +129,7 @@ func cmdRun(ctx context.Context, log *slog.Logger, args []string) error {
|
||||
drv.Hammer(ctx, pool.Durables[0], scenario.HammerConfig{Workers: *hammerWorkers, Duration: *hammerDur})
|
||||
}
|
||||
|
||||
fmt.Println("\n==== R2 load-test report ====")
|
||||
fmt.Println("\n==== load-test report ====")
|
||||
fmt.Println(rec.Summary())
|
||||
|
||||
if *doCleanup {
|
||||
|
||||
+16
-5
@@ -99,24 +99,33 @@ table MoveRecord {
|
||||
// --- auth (unauthenticated) ---
|
||||
|
||||
// TelegramLoginRequest carries the platform launch data; the gateway validates
|
||||
// its HMAC before forwarding the extracted identity to the backend.
|
||||
// its HMAC before forwarding the extracted identity to the backend. browser_tz is
|
||||
// the client's detected UTC offset ("±HH:MM"), seeded into a brand-new account's
|
||||
// time zone so the robot's sleep window and the turn-timeout away window are
|
||||
// anchored to the player's real zone from first contact (first contact only).
|
||||
table TelegramLoginRequest {
|
||||
init_data:string;
|
||||
browser_tz:string;
|
||||
}
|
||||
|
||||
// GuestLoginRequest bootstraps an ephemeral guest session. locale is an optional
|
||||
// preferred-language hint.
|
||||
// preferred-language hint; browser_tz is the detected UTC offset seeded into the
|
||||
// guest account's time zone (see TelegramLoginRequest.browser_tz).
|
||||
table GuestLoginRequest {
|
||||
locale:string;
|
||||
browser_tz:string;
|
||||
}
|
||||
|
||||
// EmailRequestRequest asks the backend to send a login confirm-code to email.
|
||||
// EmailRequestRequest asks the backend to send a login confirm-code to email. It
|
||||
// also provisions the account on first contact, so browser_tz (the detected UTC
|
||||
// offset) is seeded into its time zone here, not at the later login step.
|
||||
table EmailRequestRequest {
|
||||
email:string;
|
||||
browser_tz:string;
|
||||
}
|
||||
|
||||
// EmailLoginRequest logs in (or provisions) the account owning email, verifying
|
||||
// the confirm-code.
|
||||
// EmailLoginRequest logs in to the account owning email (provisioned at the
|
||||
// request step), verifying the confirm-code.
|
||||
table EmailLoginRequest {
|
||||
email:string;
|
||||
code:string;
|
||||
@@ -383,6 +392,8 @@ table FeedbackSubmitRequest {
|
||||
attachment:[ubyte];
|
||||
attachment_name:string;
|
||||
channel:string;
|
||||
version:string;
|
||||
browser_tz:string;
|
||||
}
|
||||
|
||||
// FeedbackReply is the operator's answer shown back to the player.
|
||||
|
||||
@@ -49,12 +49,23 @@ func (rcv *EmailRequestRequest) Email() []byte {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (rcv *EmailRequestRequest) BrowserTz() []byte {
|
||||
o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
|
||||
if o != 0 {
|
||||
return rcv._tab.ByteVector(o + rcv._tab.Pos)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func EmailRequestRequestStart(builder *flatbuffers.Builder) {
|
||||
builder.StartObject(1)
|
||||
builder.StartObject(2)
|
||||
}
|
||||
func EmailRequestRequestAddEmail(builder *flatbuffers.Builder, email flatbuffers.UOffsetT) {
|
||||
builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(email), 0)
|
||||
}
|
||||
func EmailRequestRequestAddBrowserTz(builder *flatbuffers.Builder, browserTz flatbuffers.UOffsetT) {
|
||||
builder.PrependUOffsetTSlot(1, flatbuffers.UOffsetT(browserTz), 0)
|
||||
}
|
||||
func EmailRequestRequestEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
|
||||
return builder.EndObject()
|
||||
}
|
||||
|
||||
@@ -99,8 +99,24 @@ func (rcv *FeedbackSubmitRequest) Channel() []byte {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (rcv *FeedbackSubmitRequest) Version() []byte {
|
||||
o := flatbuffers.UOffsetT(rcv._tab.Offset(12))
|
||||
if o != 0 {
|
||||
return rcv._tab.ByteVector(o + rcv._tab.Pos)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (rcv *FeedbackSubmitRequest) BrowserTz() []byte {
|
||||
o := flatbuffers.UOffsetT(rcv._tab.Offset(14))
|
||||
if o != 0 {
|
||||
return rcv._tab.ByteVector(o + rcv._tab.Pos)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func FeedbackSubmitRequestStart(builder *flatbuffers.Builder) {
|
||||
builder.StartObject(4)
|
||||
builder.StartObject(6)
|
||||
}
|
||||
func FeedbackSubmitRequestAddBody(builder *flatbuffers.Builder, body flatbuffers.UOffsetT) {
|
||||
builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(body), 0)
|
||||
@@ -117,6 +133,12 @@ func FeedbackSubmitRequestAddAttachmentName(builder *flatbuffers.Builder, attach
|
||||
func FeedbackSubmitRequestAddChannel(builder *flatbuffers.Builder, channel flatbuffers.UOffsetT) {
|
||||
builder.PrependUOffsetTSlot(3, flatbuffers.UOffsetT(channel), 0)
|
||||
}
|
||||
func FeedbackSubmitRequestAddVersion(builder *flatbuffers.Builder, version flatbuffers.UOffsetT) {
|
||||
builder.PrependUOffsetTSlot(4, flatbuffers.UOffsetT(version), 0)
|
||||
}
|
||||
func FeedbackSubmitRequestAddBrowserTz(builder *flatbuffers.Builder, browserTz flatbuffers.UOffsetT) {
|
||||
builder.PrependUOffsetTSlot(5, flatbuffers.UOffsetT(browserTz), 0)
|
||||
}
|
||||
func FeedbackSubmitRequestEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
|
||||
return builder.EndObject()
|
||||
}
|
||||
|
||||
@@ -49,12 +49,23 @@ func (rcv *GuestLoginRequest) Locale() []byte {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (rcv *GuestLoginRequest) BrowserTz() []byte {
|
||||
o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
|
||||
if o != 0 {
|
||||
return rcv._tab.ByteVector(o + rcv._tab.Pos)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func GuestLoginRequestStart(builder *flatbuffers.Builder) {
|
||||
builder.StartObject(1)
|
||||
builder.StartObject(2)
|
||||
}
|
||||
func GuestLoginRequestAddLocale(builder *flatbuffers.Builder, locale flatbuffers.UOffsetT) {
|
||||
builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(locale), 0)
|
||||
}
|
||||
func GuestLoginRequestAddBrowserTz(builder *flatbuffers.Builder, browserTz flatbuffers.UOffsetT) {
|
||||
builder.PrependUOffsetTSlot(1, flatbuffers.UOffsetT(browserTz), 0)
|
||||
}
|
||||
func GuestLoginRequestEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
|
||||
return builder.EndObject()
|
||||
}
|
||||
|
||||
@@ -49,12 +49,23 @@ func (rcv *TelegramLoginRequest) InitData() []byte {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (rcv *TelegramLoginRequest) BrowserTz() []byte {
|
||||
o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
|
||||
if o != 0 {
|
||||
return rcv._tab.ByteVector(o + rcv._tab.Pos)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TelegramLoginRequestStart(builder *flatbuffers.Builder) {
|
||||
builder.StartObject(1)
|
||||
builder.StartObject(2)
|
||||
}
|
||||
func TelegramLoginRequestAddInitData(builder *flatbuffers.Builder, initData flatbuffers.UOffsetT) {
|
||||
builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(initData), 0)
|
||||
}
|
||||
func TelegramLoginRequestAddBrowserTz(builder *flatbuffers.Builder, browserTz flatbuffers.UOffsetT) {
|
||||
builder.PrependUOffsetTSlot(1, flatbuffers.UOffsetT(browserTz), 0)
|
||||
}
|
||||
func TelegramLoginRequestEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
|
||||
return builder.EndObject()
|
||||
}
|
||||
|
||||
@@ -38,10 +38,17 @@ Telegram identity to an account from a browser. Both map a rejection to gRPC
|
||||
operator-chosen for broadcasts) with a Mini App launch button and sends it. It replies
|
||||
with an `Ack` per command (`delivered` mirrors the former connector semantics —
|
||||
false when the kind is not rendered out-of-app or the user never started the bot).
|
||||
- **Bot chat.** `/start <payload>` (and the chat menu button) reply with a Mini App
|
||||
launch button; a deep-link payload routes the launch to a game / invitation / friend
|
||||
code. This is **self-contained** — the bot never calls back into the game, so `/start`
|
||||
onboarding works even when the game is down.
|
||||
- **Bot chat.** `/start <payload>` (and the chat menu button) reply with a localized
|
||||
welcome and a Mini App launch button; a deep-link payload routes the launch to a game /
|
||||
invitation / friend code. The welcome is **Russian or English** by the sender's reported
|
||||
Telegram language (`Message.from.language_code`, which the Bot API carries on the message
|
||||
itself — no separate user-update event — English fallback) and links the game channel and
|
||||
discussion chat by their public `@username`, **resolved once at startup** from
|
||||
`TELEGRAM_GAME_CHANNEL_ID` / `TELEGRAM_CHAT_ID` via `getChat` (a chat that is unset,
|
||||
private, or unreadable degrades that link to a generic noun — "the channel" / "our
|
||||
chat" — rather than a dangling "@"). This is otherwise **self-contained**
|
||||
— the bot never calls back into the game, so `/start` onboarding works even when the game
|
||||
is down.
|
||||
- **Moderated-chat gating.** When `TELEGRAM_CHAT_ID` names a channel's linked discussion
|
||||
group, the bot gates who may write there. The group **allows sending by default** (a
|
||||
human setting) and the bot only **restricts** — Telegram intersects the chat default with
|
||||
@@ -152,7 +159,7 @@ targets, `validator` and `bot`. In the test contour (`deploy/docker-compose.yml`
|
||||
for Telegram egress and dials the gateway bot-link by its internal name. The bot-link
|
||||
mTLS material is generated by `deploy/gen-certs.sh`. In prod the bot runs on a separate
|
||||
host with native Telegram access and dials the gateway's published bot-link port with
|
||||
`PROD_` certificates (the deferred final stage — see `PRERELEASE.md`).
|
||||
`PROD_` certificates in production.
|
||||
|
||||
A real end-to-end Telegram smoke needs a BotFather bot, its token, a public HTTPS Mini
|
||||
App origin, and the bot container; the unit tests cover the wire format, templates,
|
||||
|
||||
@@ -72,6 +72,7 @@ func run(ctx context.Context, cfg config.BotConfig, logger *zap.Logger) error {
|
||||
MiniAppURL: cfg.MiniAppURL,
|
||||
SendRatePerSecond: cfg.SendRatePerSecond,
|
||||
ChatID: cfg.ChatID,
|
||||
GameChannelID: cfg.GameChannelID,
|
||||
}, logger)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -33,8 +33,12 @@ type Config struct {
|
||||
SendRatePerSecond int
|
||||
// ChatID is the moderated discussion chat the bot gates write access in; 0
|
||||
// disables chat gating (and the chat_member long-poll subscription). Gating needs
|
||||
// the bot to be an administrator there with the restrict-members right.
|
||||
// the bot to be an administrator there with the restrict-members right. Its public
|
||||
// @username is also resolved at startup for the /start welcome's discussion link.
|
||||
ChatID int64
|
||||
// GameChannelID is the game channel whose public @username the /start welcome links
|
||||
// to (resolved from this id via getChat at startup); 0 omits that follow link.
|
||||
GameChannelID int64
|
||||
}
|
||||
|
||||
// EligibilityResolver answers whether the Telegram user identified by externalID
|
||||
@@ -54,6 +58,13 @@ type Bot struct {
|
||||
limiter *rate.Limiter
|
||||
// chatID is the moderated discussion chat (0 disables gating).
|
||||
chatID int64
|
||||
// channelID is the game channel (0 omits its welcome follow link).
|
||||
channelID int64
|
||||
// channelUsername and chatUsername are the public @usernames (without the leading
|
||||
// @) of the game channel and the discussion chat, resolved once at startup
|
||||
// (resolveWelcomeHandles) for the /start welcome's follow links; "" when unresolved.
|
||||
channelUsername string
|
||||
chatUsername string
|
||||
// botID is the bot's own Telegram user id (resolved at startup); it skips the
|
||||
// chat_member updates the bot's own restrict actions generate — the grant loop guard.
|
||||
botID int64
|
||||
@@ -69,7 +80,7 @@ func New(cfg Config, log *zap.Logger) (*Bot, error) {
|
||||
if log == nil {
|
||||
log = zap.NewNop()
|
||||
}
|
||||
t := &Bot{miniAppURL: cfg.MiniAppURL, log: log, chatID: cfg.ChatID}
|
||||
t := &Bot{miniAppURL: cfg.MiniAppURL, log: log, chatID: cfg.ChatID, channelID: cfg.GameChannelID}
|
||||
if cfg.SendRatePerSecond > 0 {
|
||||
t.limiter = rate.NewLimiter(rate.Limit(cfg.SendRatePerSecond), cfg.SendRatePerSecond)
|
||||
}
|
||||
@@ -123,9 +134,43 @@ func (t *Bot) Run(ctx context.Context) {
|
||||
if t.chatID != 0 {
|
||||
t.logChatAdminStatus(ctx)
|
||||
}
|
||||
t.resolveWelcomeHandles(ctx)
|
||||
t.api.Start(ctx)
|
||||
}
|
||||
|
||||
// resolveWelcomeHandles resolves, once at startup, the public @usernames of the game
|
||||
// channel and the discussion chat from their configured ids (getChat), caching them for
|
||||
// the /start welcome's follow links. It runs before the update loop, so the handles are
|
||||
// set before any /start is handled; a chat that is unset, private (no public username)
|
||||
// or unreadable simply leaves its handle empty and the welcome omits that follow link.
|
||||
func (t *Bot) resolveWelcomeHandles(ctx context.Context) {
|
||||
t.channelUsername = t.resolveUsername(ctx, t.channelID, "game channel")
|
||||
t.chatUsername = t.resolveUsername(ctx, t.chatID, "discussion chat")
|
||||
}
|
||||
|
||||
// resolveUsername returns the public @username (without the leading @) of the chat with
|
||||
// the given id, or "" when id is 0, the chat has no public username, or getChat fails —
|
||||
// logging the reason, since a missing handle silently drops a welcome follow link.
|
||||
func (t *Bot) resolveUsername(ctx context.Context, id int64, label string) string {
|
||||
if id == 0 {
|
||||
return ""
|
||||
}
|
||||
chat, err := t.api.GetChat(ctx, &tgbot.GetChatParams{ChatID: id})
|
||||
if err != nil {
|
||||
t.log.Warn("welcome: getChat failed; follow link omitted",
|
||||
zap.String("chat", label), zap.Int64("id", id), zap.Error(err))
|
||||
return ""
|
||||
}
|
||||
if chat.Username == "" {
|
||||
t.log.Warn("welcome: chat has no public @username; follow link omitted",
|
||||
zap.String("chat", label), zap.Int64("id", id))
|
||||
return ""
|
||||
}
|
||||
t.log.Info("welcome: resolved follow link",
|
||||
zap.String("chat", label), zap.String("username", chat.Username))
|
||||
return chat.Username
|
||||
}
|
||||
|
||||
// logChatAdminStatus checks, at startup, whether the bot can actually gate the
|
||||
// moderated chat — it must be an administrator there with the restrict-members
|
||||
// ("Ban users") right, or Telegram delivers no chat_member updates and restricts
|
||||
@@ -198,11 +243,19 @@ func (t *Bot) handleStart(ctx context.Context, api *tgbot.Bot, update *models.Up
|
||||
if update.Message.Chat.Type != models.ChatTypePrivate {
|
||||
return
|
||||
}
|
||||
// The sender's Telegram language rides on the message itself (Message.from.language_code
|
||||
// in the Bot API — there is no separate user-update event); fall back to English when it
|
||||
// is absent.
|
||||
lang := ""
|
||||
if update.Message.From != nil {
|
||||
lang = update.Message.From.LanguageCode
|
||||
}
|
||||
text, button := startText(lang, t.channelUsername, t.chatUsername)
|
||||
startParam := startPayload(update.Message.Text)
|
||||
if _, err := api.SendMessage(ctx, &tgbot.SendMessageParams{
|
||||
ChatID: update.Message.Chat.ID,
|
||||
Text: "Tap to open Scrabble.",
|
||||
ReplyMarkup: t.launchMarkup("Open Scrabble", startParam),
|
||||
Text: text,
|
||||
ReplyMarkup: t.launchMarkup(button, startParam),
|
||||
}); err != nil {
|
||||
t.log.Warn("reply to start failed", zap.Error(err))
|
||||
}
|
||||
|
||||
@@ -29,6 +29,10 @@ func (f *fakeBotAPI) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
f.text = r.FormValue("text")
|
||||
f.replyMarkup = r.FormValue("reply_markup")
|
||||
io.WriteString(w, `{"ok":true,"result":{"message_id":1}}`)
|
||||
case strings.HasSuffix(r.URL.Path, "/getChat"):
|
||||
// Echo the requested id into the username so a resolver test can tell the
|
||||
// channel lookup from the chat lookup.
|
||||
io.WriteString(w, `{"ok":true,"result":{"id":-100,"type":"channel","username":"u`+r.FormValue("chat_id")+`"}}`)
|
||||
default:
|
||||
io.WriteString(w, `{"ok":true,"result":true}`)
|
||||
}
|
||||
@@ -105,7 +109,7 @@ func TestTestEnvironmentRoutesGetMe(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestHandleStartRepliesPrivateOnly(t *testing.T) {
|
||||
t.Run("private replies", func(t *testing.T) {
|
||||
t.Run("private replies in english by default", func(t *testing.T) {
|
||||
api := &fakeBotAPI{}
|
||||
b := newTestBot(t, api)
|
||||
b.handleStart(context.Background(), b.api, &models.Update{Message: &models.Message{
|
||||
@@ -114,6 +118,35 @@ func TestHandleStartRepliesPrivateOnly(t *testing.T) {
|
||||
if api.chatID != "42" || !strings.Contains(api.replyMarkup, "web_app") {
|
||||
t.Errorf("private /start: chat=%q markup=%q, want a web_app reply", api.chatID, api.replyMarkup)
|
||||
}
|
||||
// No reported language -> English welcome + English button.
|
||||
if !strings.Contains(api.text, "Hi!") {
|
||||
t.Errorf("text = %q, want the English welcome", api.text)
|
||||
}
|
||||
if !strings.Contains(api.replyMarkup, "Open") {
|
||||
t.Errorf("reply_markup = %q, want the English button", api.replyMarkup)
|
||||
}
|
||||
})
|
||||
t.Run("uses the sender's reported language", func(t *testing.T) {
|
||||
api := &fakeBotAPI{}
|
||||
b := newTestBot(t, api)
|
||||
b.handleStart(context.Background(), b.api, &models.Update{Message: &models.Message{
|
||||
Chat: models.Chat{ID: 42, Type: models.ChatTypePrivate}, Text: "/start",
|
||||
From: &models.User{ID: 7, LanguageCode: "ru"},
|
||||
}})
|
||||
if !strings.Contains(api.text, "Привет!") {
|
||||
t.Errorf("text = %q, want the Russian welcome for a ru sender", api.text)
|
||||
}
|
||||
})
|
||||
t.Run("embeds resolved follow handles", func(t *testing.T) {
|
||||
api := &fakeBotAPI{}
|
||||
b := newTestBot(t, api)
|
||||
b.channelUsername, b.chatUsername = "erudit", "erudite_chat"
|
||||
b.handleStart(context.Background(), b.api, &models.Update{Message: &models.Message{
|
||||
Chat: models.Chat{ID: 42, Type: models.ChatTypePrivate}, Text: "/start",
|
||||
}})
|
||||
if !strings.Contains(api.text, "@erudit") || !strings.Contains(api.text, "@erudite_chat") {
|
||||
t.Errorf("text = %q, want the follow handles", api.text)
|
||||
}
|
||||
})
|
||||
t.Run("group ignored", func(t *testing.T) {
|
||||
api := &fakeBotAPI{}
|
||||
@@ -127,6 +160,26 @@ func TestHandleStartRepliesPrivateOnly(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestResolveWelcomeHandles(t *testing.T) {
|
||||
api := &fakeBotAPI{}
|
||||
b := newTestBot(t, api)
|
||||
b.channelID, b.chatID = 111, 222
|
||||
b.resolveWelcomeHandles(context.Background())
|
||||
// The fake echoes the requested id into the username, so each lookup is independent.
|
||||
if b.channelUsername != "u111" {
|
||||
t.Errorf("channelUsername = %q, want u111", b.channelUsername)
|
||||
}
|
||||
if b.chatUsername != "u222" {
|
||||
t.Errorf("chatUsername = %q, want u222", b.chatUsername)
|
||||
}
|
||||
// An unset id resolves to no handle (and makes no getChat call).
|
||||
b.channelID = 0
|
||||
b.resolveWelcomeHandles(context.Background())
|
||||
if b.channelUsername != "" {
|
||||
t.Errorf("channelUsername = %q, want empty for id 0", b.channelUsername)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartPayload(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"/start g123": "g123",
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package bot
|
||||
|
||||
import "strings"
|
||||
|
||||
// startText returns the localized /start welcome body and the launch-button label.
|
||||
// Russian is used when lang (the IETF language tag the Telegram client reports on the
|
||||
// message's sender) starts with "ru", English otherwise and when it is absent — so a
|
||||
// user with no reported language still gets a sensible message. channel and chat are
|
||||
// the resolved public @usernames (without the leading @) of the game channel and the
|
||||
// discussion chat; when either is empty its follow link degrades to a generic noun
|
||||
// (e.g. "the channel" / "our chat") rather than rendering a dangling "@", since the
|
||||
// bot's own info screen still lists the real links.
|
||||
func startText(lang, channel, chat string) (text, button string) {
|
||||
if strings.HasPrefix(strings.ToLower(lang), "ru") {
|
||||
return ruWelcome(channel, chat), "Открыть «Эрудит»"
|
||||
}
|
||||
return enWelcome(channel, chat), "Open “Erudite”"
|
||||
}
|
||||
|
||||
// ruWelcome builds the Russian welcome. A known handle is named as "@<username>"; an
|
||||
// unresolved one degrades to a plain noun.
|
||||
func ruWelcome(channel, chat string) string {
|
||||
ch := "канал"
|
||||
if channel != "" {
|
||||
ch = "@" + channel
|
||||
}
|
||||
ct := "чате"
|
||||
if chat != "" {
|
||||
ct = "@" + chat
|
||||
}
|
||||
return strings.Join([]string{
|
||||
"Привет! 👋",
|
||||
"Здесь можно сражаться в «Эрудит» со случайными игроками или в компании друзей.",
|
||||
"Подписывайтесь на " + ch + ", чтобы быть в курсе последних игровых событий и вовремя " +
|
||||
"получать важные уведомления. Игроки могут обсуждать игру и просто общаться в нашем " +
|
||||
ct + "! 💬",
|
||||
"Ни слова больше.\nПервая партия сама себя не сыграет 😊",
|
||||
}, "\n\n")
|
||||
}
|
||||
|
||||
// enWelcome builds the English welcome (the fallback for any non-Russian or missing
|
||||
// language). A known handle is named as "@<username>"; an unresolved one degrades to a
|
||||
// plain noun.
|
||||
func enWelcome(channel, chat string) string {
|
||||
ch := "the channel"
|
||||
if channel != "" {
|
||||
ch = "@" + channel
|
||||
}
|
||||
ct := "group chat"
|
||||
if chat != "" {
|
||||
ct = "@" + chat
|
||||
}
|
||||
return strings.Join([]string{
|
||||
"Hi! 👋",
|
||||
"Play Scrabble against random players — or with a group of friends.",
|
||||
"Follow " + ch + " to stay up to date with the latest game events and receive important " +
|
||||
"notifications in time. Players can discuss the game and simply chat in our " + ct + "! 💬",
|
||||
"Okay, no more talking.\nFirst game won't play itself 😊",
|
||||
}, "\n\n")
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package bot
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestStartTextLocalizesByLanguage(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
lang string
|
||||
wantButton string
|
||||
wantSubstr string // a phrase unique to the chosen language body
|
||||
}{
|
||||
{"russian", "ru", "Открыть «Эрудит»", "Привет!"},
|
||||
{"russian region tag", "ru-RU", "Открыть «Эрудит»", "Первая партия"},
|
||||
{"english", "en", "Open “Erudite”", "Hi!"},
|
||||
{"other language falls back to english", "de", "Open “Erudite”", "Hi!"},
|
||||
{"absent language falls back to english", "", "Open “Erudite”", "no more talking"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
text, button := startText(tc.lang, "erudit", "erudite_chat")
|
||||
if button != tc.wantButton {
|
||||
t.Errorf("button = %q, want %q", button, tc.wantButton)
|
||||
}
|
||||
if !strings.Contains(text, tc.wantSubstr) {
|
||||
t.Errorf("text %q does not contain %q", text, tc.wantSubstr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartTextEmbedsFollowHandles(t *testing.T) {
|
||||
for _, lang := range []string{"ru", "en"} {
|
||||
text, _ := startText(lang, "erudit", "erudite_chat")
|
||||
if !strings.Contains(text, "@erudit") || !strings.Contains(text, "@erudite_chat") {
|
||||
t.Errorf("lang %q: follow paragraph missing the handles: %q", lang, text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartTextFallsBackToGenericWhenHandleMissing(t *testing.T) {
|
||||
// An unresolved handle degrades to a generic noun rather than a dangling "@" — and
|
||||
// only that slot degrades; a resolved sibling still shows its "@username".
|
||||
t.Run("both missing leaves no @", func(t *testing.T) {
|
||||
for _, lang := range []string{"ru", "en"} {
|
||||
text, _ := startText(lang, "", "")
|
||||
if strings.Contains(text, "@") {
|
||||
t.Errorf("lang %q: text shows a dangling @: %q", lang, text)
|
||||
}
|
||||
}
|
||||
// The generic nouns are present in each language.
|
||||
ru, _ := startText("ru", "", "")
|
||||
if !strings.Contains(ru, "на канал") || !strings.Contains(ru, "в нашем чате") {
|
||||
t.Errorf("russian generic fallback missing: %q", ru)
|
||||
}
|
||||
en, _ := startText("en", "", "")
|
||||
if !strings.Contains(en, "Follow the channel") || !strings.Contains(en, "in our group chat") {
|
||||
t.Errorf("english generic fallback missing: %q", en)
|
||||
}
|
||||
})
|
||||
t.Run("only the missing slot degrades", func(t *testing.T) {
|
||||
// Channel resolved, chat missing: the channel keeps its @handle, the chat is generic.
|
||||
en, _ := startText("en", "erudit", "")
|
||||
if !strings.Contains(en, "@erudit") || strings.Contains(en, "@erudite") {
|
||||
t.Errorf("channel handle not shown / chat handle leaked: %q", en)
|
||||
}
|
||||
if !strings.Contains(en, "in our group chat") {
|
||||
t.Errorf("chat slot did not degrade to a generic noun: %q", en)
|
||||
}
|
||||
})
|
||||
}
|
||||
+5
-5
@@ -1,13 +1,13 @@
|
||||
import { test as base } from '@playwright/test';
|
||||
|
||||
// All e2e specs run hermetically against the mock transport. Neutralise the real
|
||||
// telegram-web-app.js (loaded from the CDN in index.html) so the suite never blocks
|
||||
// on telegram.org — it is unreachable from the CI runner, and a render-blocking
|
||||
// <script> to it would hang every page load. Specs that exercise the Telegram launch
|
||||
// inject their own window.Telegram via addInitScript before navigating.
|
||||
// telegram-web-app.js (the app loads it dynamically — see lib/telegram.ts loadTelegramSDK) so the
|
||||
// suite never reaches telegram.org, which is unreachable from the CI runner. Specs that exercise
|
||||
// the Telegram launch inject their own window.Telegram via addInitScript before navigating, so the
|
||||
// dynamic load short-circuits on the already-present SDK.
|
||||
export const test = base.extend({
|
||||
page: async ({ page }, use) => {
|
||||
await page.route('**/telegram-web-app.js', (route) =>
|
||||
await page.route('**/telegram-web-app.js*', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/javascript', body: '' }),
|
||||
);
|
||||
await use(page);
|
||||
|
||||
@@ -44,6 +44,60 @@ test('friends: issue a code, accept an incoming request, redeem a code', async (
|
||||
await expect(page.locator('.who', { hasText: 'Friend 111111' })).toBeVisible();
|
||||
});
|
||||
|
||||
test('friends: the row kebab reveals block/remove and an outside tap closes it', async ({ page }) => {
|
||||
await loginLobby(page);
|
||||
await openFriends(page);
|
||||
|
||||
// A friend row slides open on its kebab (like the lobby), exposing two icon actions.
|
||||
const kaya = page.locator('.rowwrap', { hasText: 'Kaya' });
|
||||
await kaya.locator('.kebab').click();
|
||||
await expect(kaya).toHaveClass(/revealed/);
|
||||
await expect(kaya.locator('.acts').getByRole('button', { name: 'Block' })).toBeVisible();
|
||||
await expect(kaya.locator('.acts').getByRole('button', { name: 'Remove' })).toBeVisible();
|
||||
|
||||
// A tap anywhere outside the action buttons collapses the row again.
|
||||
await page.getByRole('heading', { name: 'Your friends' }).click();
|
||||
await expect(kaya).not.toHaveClass(/revealed/);
|
||||
});
|
||||
|
||||
test('friends: blocking from the list confirms (naming the friend) and moves them to Blocked', async ({ page }) => {
|
||||
await loginLobby(page);
|
||||
await openFriends(page);
|
||||
|
||||
const kaya = page.locator('.rowwrap', { hasText: 'Kaya' });
|
||||
await kaya.locator('.kebab').click();
|
||||
await kaya.locator('.acts').getByRole('button', { name: 'Block' }).click();
|
||||
|
||||
// The confirmation keeps a generic title and names the friend in the body.
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog.getByText('Block this player?')).toBeVisible();
|
||||
await expect(dialog.locator('.confirm-name')).toHaveText('Kaya');
|
||||
await dialog.getByRole('button', { name: 'Block' }).click();
|
||||
|
||||
// The block applied: Kaya leaves the friends list and shows under Blocked players.
|
||||
await expect(page.getByText('No friends yet.')).toBeVisible();
|
||||
const blocked = page.locator('.rowwrap', { hasText: 'Kaya' });
|
||||
await expect(blocked.getByRole('button', { name: 'Unblock' })).toBeVisible();
|
||||
});
|
||||
|
||||
test('friends: removing from the list confirms (naming the friend) and drops them', async ({ page }) => {
|
||||
await loginLobby(page);
|
||||
await openFriends(page);
|
||||
|
||||
const kaya = page.locator('.rowwrap', { hasText: 'Kaya' });
|
||||
await kaya.locator('.kebab').click();
|
||||
await kaya.locator('.acts').getByRole('button', { name: 'Remove' }).click();
|
||||
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog.getByText('Remove from friends?')).toBeVisible();
|
||||
await expect(dialog.locator('.confirm-name')).toHaveText('Kaya');
|
||||
await dialog.getByRole('button', { name: 'Remove' }).click();
|
||||
|
||||
// Unfriending just drops the friendship — Kaya is gone and not blocked.
|
||||
await expect(page.getByText('No friends yet.')).toBeVisible();
|
||||
await expect(page.locator('.rowwrap', { hasText: 'Kaya' })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('invitations: the lobby shows an invitation and accepting clears it', async ({ page }) => {
|
||||
await loginLobby(page);
|
||||
await expect(page.getByText('Invitations')).toBeVisible();
|
||||
|
||||
+24
-5
@@ -107,11 +107,30 @@ test('inside Telegram, a failed launch shows the retry screen, not the web login
|
||||
await expect(page.getByRole('button', { name: /guest/i })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('outside Telegram, the /telegram/ entry redirects to the site root', async ({ page }) => {
|
||||
test('outside Telegram, the /telegram/ entry shows the launch diagnostic, not a redirect', async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.goto('/telegram/');
|
||||
|
||||
// The guard sends a non-Telegram visitor back to the root, where the normal
|
||||
// (guest / email) login is shown.
|
||||
await expect(page.getByRole('button', { name: /guest/i })).toBeVisible();
|
||||
await expect(page).not.toHaveURL(/\/telegram\//);
|
||||
// The entry no longer bounces a visitor without Telegram sign-in data to the marketing landing;
|
||||
// it shows a compact diagnostic screen (Share + Retry) that helps pinpoint why initData was
|
||||
// absent — notably the Android empty-initData failure.
|
||||
await expect(page.getByRole('button', { name: 'Share' })).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: 'Retry' })).toBeVisible();
|
||||
// It stays on /telegram/ (no redirect) and never shows the web (guest) login.
|
||||
await expect(page).toHaveURL(/\/telegram\//);
|
||||
await expect(page.getByRole('button', { name: /guest/i })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('a blocked telegram-web-app.js does not hang the diagnostic screen', async ({ page }) => {
|
||||
// Simulate a network where telegram.org is unreachable: the SDK fetch fails. Because the SPA
|
||||
// loads the SDK dynamically with a timeout (not a render-blocking <script>), a failed/blocked
|
||||
// fetch must not strand the page — the diagnostic screen still renders, reporting no SDK. (This
|
||||
// route overrides the fixture's empty-body fulfill; the later registration wins.)
|
||||
await page.route('**/telegram-web-app.js*', (route) => route.abort());
|
||||
await page.goto('/telegram/');
|
||||
|
||||
await expect(page.getByRole('button', { name: 'Share' })).toBeVisible();
|
||||
// The diagnostic names the load outcome: a failed fetch reads as sdk-load: error.
|
||||
await expect(page.getByText('sdk-load: error')).toBeVisible();
|
||||
});
|
||||
|
||||
+5
-3
@@ -2,9 +2,11 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<!-- Telegram Mini App SDK: defines window.Telegram.WebApp. Harmless outside
|
||||
Telegram (initData is empty), so it loads on every entry. -->
|
||||
<script src="https://telegram.org/js/telegram-web-app.js"></script>
|
||||
<!-- The Telegram Mini App SDK (window.Telegram.WebApp) is deliberately NOT loaded here: a
|
||||
render-blocking <script> to telegram.org hangs the whole page on a network that blocks
|
||||
telegram.org (common where Telegram itself reaches users only over a proxy), stranding even
|
||||
the launch-diagnostic screen. The app loads it dynamically, with a timeout, only on a
|
||||
Telegram entry — see lib/telegram.ts loadTelegramSDK and lib/app.svelte.ts bootstrap. -->
|
||||
<!-- user-scalable=no: the board owns zoom; we do not want the browser's pinch
|
||||
to fight our two-state zoom. viewport-fit=cover for native (Capacitor). -->
|
||||
<meta
|
||||
|
||||
+13
-16
@@ -2,13 +2,13 @@
|
||||
import { onMount } from 'svelte';
|
||||
import { cubicOut } from 'svelte/easing';
|
||||
import { app, bootstrap } from './lib/app.svelte';
|
||||
import { navigate, router, type RouteName } from './lib/router.svelte';
|
||||
import { router, type RouteName } from './lib/router.svelte';
|
||||
import { t } from './lib/i18n/index.svelte';
|
||||
import { insideTelegram, telegramBackButton } from './lib/telegram';
|
||||
import Toast from './components/Toast.svelte';
|
||||
import Splash from './components/Splash.svelte';
|
||||
import StaleInviteModal from './components/StaleInviteModal.svelte';
|
||||
import WelcomeRedeemModal from './components/WelcomeRedeemModal.svelte';
|
||||
import DebugPanel from './components/DebugPanel.svelte';
|
||||
import Login from './screens/Login.svelte';
|
||||
import Lobby from './screens/Lobby.svelte';
|
||||
import NewGame from './screens/NewGame.svelte';
|
||||
@@ -19,6 +19,7 @@
|
||||
import Feedback from './screens/Feedback.svelte';
|
||||
import Blocked from './screens/Blocked.svelte';
|
||||
import BootError from './screens/BootError.svelte';
|
||||
import TelegramLaunchError from './screens/TelegramLaunchError.svelte';
|
||||
|
||||
onMount(() => {
|
||||
void bootstrap();
|
||||
@@ -29,19 +30,6 @@
|
||||
// another screen is not covered.
|
||||
const routeIsLobby = $derived(router.route.name === 'lobby');
|
||||
|
||||
// Inside Telegram, drive its native header back button: show it on any sub-screen
|
||||
// (everything returns to the lobby root), hide it on the lobby/login. The app's own
|
||||
// back chevron is hidden in Telegram (Header.svelte) so only the native one shows.
|
||||
$effect(() => {
|
||||
if (!insideTelegram()) return;
|
||||
const r = router.route;
|
||||
// The chat / check sub-screens step back to their game; every other sub-screen to the lobby.
|
||||
let target = '/';
|
||||
if (r.name === 'gameChat' || r.name === 'gameCheck') target = `/game/${r.params.id}`;
|
||||
else if (r.name === 'feedback') target = '/about'; // back to the Settings → Info tab
|
||||
telegramBackButton(r.name !== 'lobby' && r.name !== 'login', () => navigate(target));
|
||||
});
|
||||
|
||||
// Screen transitions: the lobby is the navigation root. Entering a screen from the
|
||||
// lobby slides it in from the right (forward); returning to the lobby slides the
|
||||
// screen out to the right and reveals the lobby (back). Transitions are local, so
|
||||
@@ -84,6 +72,11 @@
|
||||
{#if !routeIsLobby}
|
||||
<div class="splash">{t('common.loading')}</div>
|
||||
{/if}
|
||||
{:else if app.launchError}
|
||||
<!-- The /telegram/ entry without sign-in data: a compact, shareable diagnostic screen instead
|
||||
of bouncing to the marketing landing (also the probe for the empty-initData failure on
|
||||
some Android clients). -->
|
||||
<TelegramLaunchError />
|
||||
{:else if app.bootError}
|
||||
<!-- A Mini App launch that failed to authenticate (e.g. the backend was down mid-deploy):
|
||||
show the retry screen instead of falling back to the web login. -->
|
||||
@@ -128,10 +121,14 @@
|
||||
<StaleInviteModal />
|
||||
<WelcomeRedeemModal />
|
||||
|
||||
{#if routeIsLobby && !app.splashDone && !app.blocked && !app.bootError}
|
||||
{#if routeIsLobby && !app.splashDone && !app.blocked && !app.bootError && !app.launchError}
|
||||
<Splash />
|
||||
{/if}
|
||||
|
||||
{#if app.debugOpen}
|
||||
<DebugPanel />
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.splash {
|
||||
height: 100%;
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
<script lang="ts">
|
||||
// Hidden on-device debug panel, opened by tapping the header title ten times (Header.svelte) and
|
||||
// closed by tapping anywhere except the Share control. It shows a privacy-safe client diagnostic
|
||||
// snapshot (no secrets, no initData values, no IP) and shares it through the OS share sheet (or a
|
||||
// clipboard copy on desktop) — a support aid for reproducing client-specific issues, e.g. the
|
||||
// Telegram Android presentation quirks. Drawn from the top, just under the app header.
|
||||
import { app, closeDebug } from '../lib/app.svelte';
|
||||
import { connection } from '../lib/connection.svelte';
|
||||
import { shareText } from '../lib/share';
|
||||
import { telegramChromeDiag } from '../lib/telegram';
|
||||
|
||||
const report = [
|
||||
`app: ${__APP_VERSION__}`,
|
||||
`locale: ${app.locale} theme: ${app.theme} reduceMotion: ${app.reduceMotion}`,
|
||||
`online: ${connection.online} streamAlive: ${app.streamAlive}`,
|
||||
`userId: ${app.session?.userId ?? '—'} guest: ${app.profile?.isGuest ?? '—'}`,
|
||||
telegramChromeDiag(),
|
||||
].join('\n');
|
||||
|
||||
let label = $state('Share');
|
||||
async function share(e: MouseEvent): Promise<void> {
|
||||
e.stopPropagation(); // a tap on Share shares; it must not also close the panel
|
||||
const r = await shareText(report, `Scrabble debug ${__APP_VERSION__}`);
|
||||
if (r === 'copied') {
|
||||
label = 'Copied';
|
||||
setTimeout(() => (label = 'Share'), 1500);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div class="overlay" onclick={closeDebug}>
|
||||
<button class="share" onclick={share}>{label}</button>
|
||||
<pre class="body">{report}</pre>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 10000;
|
||||
/* Drawn from the top; the content clears the app header (~56px + the device safe-area). */
|
||||
padding: calc(var(--tg-safe-top, 0px) + 56px) 12px 16px;
|
||||
background: rgba(0, 0, 0, 0.82);
|
||||
overflow: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
align-items: flex-start;
|
||||
}
|
||||
.share {
|
||||
flex: 0 0 auto;
|
||||
padding: 7px 16px;
|
||||
border: 1px solid var(--accent);
|
||||
background: var(--accent);
|
||||
color: var(--accent-text);
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
.body {
|
||||
margin: 0;
|
||||
width: 100%;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size: 11px;
|
||||
line-height: 1.45;
|
||||
color: #d6e6ff;
|
||||
}
|
||||
</style>
|
||||
@@ -1,17 +1,30 @@
|
||||
<script lang="ts">
|
||||
import { navigate } from '../lib/router.svelte';
|
||||
import { insideTelegram } from '../lib/telegram';
|
||||
import { connection } from '../lib/connection.svelte';
|
||||
import { t } from '../lib/i18n/index.svelte';
|
||||
import { app } from '../lib/app.svelte';
|
||||
import { app, openDebug } from '../lib/app.svelte';
|
||||
import Spinner from './Spinner.svelte';
|
||||
import AdBanner from './AdBanner.svelte';
|
||||
|
||||
let { title, back, grow = false }: { title: string; back?: string; grow?: boolean } = $props();
|
||||
|
||||
// Inside Telegram the native header back button (App.svelte) is the back control, so
|
||||
// the app's own chevron is hidden to avoid two back affordances.
|
||||
const showBack = $derived(!!back && !insideTelegram());
|
||||
// The app always shows its own back chevron when there is a back target — on every platform, in
|
||||
// and out of Telegram. The native Telegram BackButton is not used: it does not render reliably in
|
||||
// the windowed Mini App (relying on it would lose back navigation there).
|
||||
const showBack = $derived(!!back);
|
||||
|
||||
// Ten quick taps on the title open the hidden debug panel (components/DebugPanel) — a support aid.
|
||||
let titleTaps = 0;
|
||||
let lastTitleTap = 0;
|
||||
function onTitleTap(): void {
|
||||
const now = Date.now();
|
||||
titleTaps = now - lastTitleTap < 400 ? titleTaps + 1 : 1;
|
||||
lastTitleTap = now;
|
||||
if (titleTaps >= 10) {
|
||||
titleTaps = 0;
|
||||
openDebug();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<header class="nav" class:grow>
|
||||
@@ -24,7 +37,9 @@
|
||||
<span class="spacer"></span>
|
||||
{/if}
|
||||
{#if connection.online}
|
||||
<h1>{title}</h1>
|
||||
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
||||
<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
|
||||
<h1 onclick={onTitleTap}>{title}</h1>
|
||||
{:else}
|
||||
<h1 class="connecting"><Spinner /> <span>{t('connection.connecting')}</span></h1>
|
||||
{/if}
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
<script lang="ts">
|
||||
// A best-move word drawn as a row of game tiles, mirroring the board's placed-tile
|
||||
// look (letter top-left, point value bottom-right) at a small fixed size. A blank tile
|
||||
// shows its letter but no value, exactly as on the board. Letters are upper-cased for
|
||||
// display. The tile values ride on each tile, so this renders without the variant's
|
||||
// alphabet table (which the statistics screen has not cached).
|
||||
import type { BestMoveTile } from '../lib/model';
|
||||
// shows its letter but no value, exactly as on the board; in Erudit it also carries the
|
||||
// blank's star (✻) in the value corner. Letters are upper-cased for display. The tile
|
||||
// values ride on each tile, so this needs only the variant id (for the star) — not the
|
||||
// variant's alphabet table, which the statistics screen has not cached.
|
||||
import type { BestMoveTile, Variant } from '../lib/model';
|
||||
import { usesStarBlank, BLANK_STAR } from '../lib/variants';
|
||||
|
||||
let { word }: { word: BestMoveTile[] } = $props();
|
||||
let { word, variant }: { word: BestMoveTile[]; variant: Variant } = $props();
|
||||
|
||||
const label = $derived(word.map((t) => t.letter).join('').toUpperCase());
|
||||
</script>
|
||||
@@ -15,7 +17,11 @@
|
||||
{#each word as tile, i (i)}
|
||||
<span class="tile" class:blank={tile.blank} aria-hidden="true">
|
||||
<span class="letter">{tile.letter.toUpperCase()}</span>
|
||||
{#if !tile.blank}<span class="val">{tile.value}</span>{/if}
|
||||
{#if !tile.blank}
|
||||
<span class="val">{tile.value}</span>
|
||||
{:else if usesStarBlank(variant)}
|
||||
<span class="val blankmark">{BLANK_STAR}</span>
|
||||
{/if}
|
||||
</span>
|
||||
{/each}
|
||||
</span>
|
||||
@@ -50,4 +56,10 @@
|
||||
font-size: 7px;
|
||||
font-weight: 600;
|
||||
}
|
||||
/* A placed Erudit blank ("звёздочка") shows its star where the (absent) point value sits,
|
||||
its ink kept on the value digits' line (mirrors the board tile). */
|
||||
.blankmark {
|
||||
font-size: 8px;
|
||||
bottom: 0;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
import type { Premium } from '../lib/premiums';
|
||||
import { valueForLetter } from '../lib/alphabet';
|
||||
import type { Variant } from '../lib/model';
|
||||
import { usesStarBlank, BLANK_STAR } from '../lib/variants';
|
||||
import { bonusLabel, type BoardLabelMode } from '../lib/boardlabels';
|
||||
import type { Locale } from '../lib/i18n/catalog';
|
||||
|
||||
@@ -254,7 +255,11 @@
|
||||
>
|
||||
{#if letter}
|
||||
<span class="letter">{letter}</span>
|
||||
{#if !blank}<span class="val">{valueForLetter(variant, letter)}</span>{/if}
|
||||
{#if !blank}
|
||||
<span class="val">{valueForLetter(variant, letter)}</span>
|
||||
{:else if usesStarBlank(variant)}
|
||||
<span class="val blankmark">{BLANK_STAR}</span>
|
||||
{/if}
|
||||
{:else if r === centre.row && c === centre.col}
|
||||
<span class="star">★</span>
|
||||
{:else if bl?.kind === 'single'}
|
||||
@@ -410,6 +415,12 @@
|
||||
font-size: 2.4cqw;
|
||||
font-weight: 600;
|
||||
}
|
||||
/* A placed Erudit blank ("звёздочка") shows its star where the (absent) point value sits,
|
||||
its ink centred on the same line as a neighbouring tile's value digit. */
|
||||
.blankmark {
|
||||
font-size: 2.8cqw;
|
||||
bottom: 0;
|
||||
}
|
||||
.star {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
|
||||
@@ -17,14 +17,14 @@
|
||||
import { badgeKind } from '../lib/unread';
|
||||
import { historyGrid } from '../lib/history';
|
||||
import { centre, premiumGrid } from '../lib/premiums';
|
||||
import { variantNameKey } from '../lib/variants';
|
||||
import { variantNameKey, usesStarBlank, BLANK_STAR } from '../lib/variants';
|
||||
import { alphabetLetters, hasAlphabet } from '../lib/alphabet';
|
||||
import { hintsLeft } from '../lib/hints';
|
||||
import { shareOrDownloadGcg } from '../lib/share';
|
||||
import { getCachedGame, setCachedGame, setCachedDraft, type CachedGame } from '../lib/gamecache';
|
||||
import { patchLobbyGame } from '../lib/lobbycache';
|
||||
import { applyGameOver, applyMoveDelta, applyOpponentJoined, type DeltaResult } from '../lib/gamedelta';
|
||||
import { telegramClosingConfirmation, telegramHaptic } from '../lib/telegram';
|
||||
import { telegramHaptic } from '../lib/telegram';
|
||||
import {
|
||||
BLANK,
|
||||
newPlacement,
|
||||
@@ -228,8 +228,6 @@
|
||||
placement = tiles.length ? placementFromHint(tiles, rack) : newPlacement(rack);
|
||||
}
|
||||
onMount(() => {
|
||||
// Guard against an accidental swipe-close losing the open game (Telegram).
|
||||
telegramClosingConfirmation(true);
|
||||
// Render instantly from the cache (a game opened before), then refresh in the
|
||||
// background. A cold open shows the loading state until load() resolves.
|
||||
const cached = getCachedGame(id);
|
||||
@@ -579,7 +577,6 @@
|
||||
clearTimeout(draftSaveTimer);
|
||||
void gateway.draftSave(id, serializeDraft(rackIds, placement.pending)).catch(() => {});
|
||||
}
|
||||
telegramClosingConfirmation(false);
|
||||
});
|
||||
|
||||
function onCell(row: number, col: number) {
|
||||
@@ -1293,7 +1290,7 @@
|
||||
|
||||
{#if drag}
|
||||
<div class="ghost" class:touch={drag.touch} style="left:{drag.x}px; top:{drag.y}px">
|
||||
<span>{drag.blank ? '' : drag.letter}</span>
|
||||
<span>{drag.blank ? (usesStarBlank(variant) ? BLANK_STAR : '') : drag.letter}</span>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
|
||||
+18
-2
@@ -3,6 +3,7 @@
|
||||
import { BLANK } from '../lib/placement';
|
||||
import { valueForLetter } from '../lib/alphabet';
|
||||
import type { Variant } from '../lib/model';
|
||||
import { usesStarBlank, BLANK_STAR } from '../lib/variants';
|
||||
|
||||
let {
|
||||
slots,
|
||||
@@ -66,8 +67,12 @@
|
||||
animate:hop={shuffling}
|
||||
onpointerdown={(e) => ondown(e, slot.index)}
|
||||
>
|
||||
<span class="letter">{slot.letter === BLANK ? '' : slot.letter}</span>
|
||||
{#if slot.letter !== BLANK}<span class="val">{valueForLetter(variant, slot.letter)}</span>{/if}
|
||||
{#if slot.letter === BLANK}
|
||||
{#if usesStarBlank(variant)}<span class="star">{BLANK_STAR}</span>{/if}
|
||||
{:else}
|
||||
<span class="letter">{slot.letter}</span>
|
||||
<span class="val">{valueForLetter(variant, slot.letter)}</span>
|
||||
{/if}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
@@ -133,4 +138,15 @@
|
||||
font-size: 0.7rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
/* Erudit's blank ("звёздочка") shows its star horizontally centred on the otherwise empty
|
||||
tile face; the top offset centres its ink against the neighbouring letters' block, nudged
|
||||
up a pixel to sit right by eye (it is slightly larger than them so it reads). */
|
||||
.star {
|
||||
position: absolute;
|
||||
top: calc(0.5% - 1px);
|
||||
left: 0;
|
||||
right: 0;
|
||||
text-align: center;
|
||||
font-size: 1.7rem;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -27,22 +27,34 @@ email(optionalEncoding?:any):string|Uint8Array|null {
|
||||
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
|
||||
}
|
||||
|
||||
browserTz():string|null
|
||||
browserTz(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
|
||||
browserTz(optionalEncoding?:any):string|Uint8Array|null {
|
||||
const offset = this.bb!.__offset(this.bb_pos, 6);
|
||||
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
|
||||
}
|
||||
|
||||
static startEmailRequestRequest(builder:flatbuffers.Builder) {
|
||||
builder.startObject(1);
|
||||
builder.startObject(2);
|
||||
}
|
||||
|
||||
static addEmail(builder:flatbuffers.Builder, emailOffset:flatbuffers.Offset) {
|
||||
builder.addFieldOffset(0, emailOffset, 0);
|
||||
}
|
||||
|
||||
static addBrowserTz(builder:flatbuffers.Builder, browserTzOffset:flatbuffers.Offset) {
|
||||
builder.addFieldOffset(1, browserTzOffset, 0);
|
||||
}
|
||||
|
||||
static endEmailRequestRequest(builder:flatbuffers.Builder):flatbuffers.Offset {
|
||||
const offset = builder.endObject();
|
||||
return offset;
|
||||
}
|
||||
|
||||
static createEmailRequestRequest(builder:flatbuffers.Builder, emailOffset:flatbuffers.Offset):flatbuffers.Offset {
|
||||
static createEmailRequestRequest(builder:flatbuffers.Builder, emailOffset:flatbuffers.Offset, browserTzOffset:flatbuffers.Offset):flatbuffers.Offset {
|
||||
EmailRequestRequest.startEmailRequestRequest(builder);
|
||||
EmailRequestRequest.addEmail(builder, emailOffset);
|
||||
EmailRequestRequest.addBrowserTz(builder, browserTzOffset);
|
||||
return EmailRequestRequest.endEmailRequestRequest(builder);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,8 +56,22 @@ channel(optionalEncoding?:any):string|Uint8Array|null {
|
||||
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
|
||||
}
|
||||
|
||||
version():string|null
|
||||
version(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
|
||||
version(optionalEncoding?:any):string|Uint8Array|null {
|
||||
const offset = this.bb!.__offset(this.bb_pos, 12);
|
||||
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
|
||||
}
|
||||
|
||||
browserTz():string|null
|
||||
browserTz(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
|
||||
browserTz(optionalEncoding?:any):string|Uint8Array|null {
|
||||
const offset = this.bb!.__offset(this.bb_pos, 14);
|
||||
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
|
||||
}
|
||||
|
||||
static startFeedbackSubmitRequest(builder:flatbuffers.Builder) {
|
||||
builder.startObject(4);
|
||||
builder.startObject(6);
|
||||
}
|
||||
|
||||
static addBody(builder:flatbuffers.Builder, bodyOffset:flatbuffers.Offset) {
|
||||
@@ -88,17 +102,27 @@ static addChannel(builder:flatbuffers.Builder, channelOffset:flatbuffers.Offset)
|
||||
builder.addFieldOffset(3, channelOffset, 0);
|
||||
}
|
||||
|
||||
static addVersion(builder:flatbuffers.Builder, versionOffset:flatbuffers.Offset) {
|
||||
builder.addFieldOffset(4, versionOffset, 0);
|
||||
}
|
||||
|
||||
static addBrowserTz(builder:flatbuffers.Builder, browserTzOffset:flatbuffers.Offset) {
|
||||
builder.addFieldOffset(5, browserTzOffset, 0);
|
||||
}
|
||||
|
||||
static endFeedbackSubmitRequest(builder:flatbuffers.Builder):flatbuffers.Offset {
|
||||
const offset = builder.endObject();
|
||||
return offset;
|
||||
}
|
||||
|
||||
static createFeedbackSubmitRequest(builder:flatbuffers.Builder, bodyOffset:flatbuffers.Offset, attachmentOffset:flatbuffers.Offset, attachmentNameOffset:flatbuffers.Offset, channelOffset:flatbuffers.Offset):flatbuffers.Offset {
|
||||
static createFeedbackSubmitRequest(builder:flatbuffers.Builder, bodyOffset:flatbuffers.Offset, attachmentOffset:flatbuffers.Offset, attachmentNameOffset:flatbuffers.Offset, channelOffset:flatbuffers.Offset, versionOffset:flatbuffers.Offset, browserTzOffset:flatbuffers.Offset):flatbuffers.Offset {
|
||||
FeedbackSubmitRequest.startFeedbackSubmitRequest(builder);
|
||||
FeedbackSubmitRequest.addBody(builder, bodyOffset);
|
||||
FeedbackSubmitRequest.addAttachment(builder, attachmentOffset);
|
||||
FeedbackSubmitRequest.addAttachmentName(builder, attachmentNameOffset);
|
||||
FeedbackSubmitRequest.addChannel(builder, channelOffset);
|
||||
FeedbackSubmitRequest.addVersion(builder, versionOffset);
|
||||
FeedbackSubmitRequest.addBrowserTz(builder, browserTzOffset);
|
||||
return FeedbackSubmitRequest.endFeedbackSubmitRequest(builder);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,22 +27,34 @@ locale(optionalEncoding?:any):string|Uint8Array|null {
|
||||
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
|
||||
}
|
||||
|
||||
browserTz():string|null
|
||||
browserTz(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
|
||||
browserTz(optionalEncoding?:any):string|Uint8Array|null {
|
||||
const offset = this.bb!.__offset(this.bb_pos, 6);
|
||||
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
|
||||
}
|
||||
|
||||
static startGuestLoginRequest(builder:flatbuffers.Builder) {
|
||||
builder.startObject(1);
|
||||
builder.startObject(2);
|
||||
}
|
||||
|
||||
static addLocale(builder:flatbuffers.Builder, localeOffset:flatbuffers.Offset) {
|
||||
builder.addFieldOffset(0, localeOffset, 0);
|
||||
}
|
||||
|
||||
static addBrowserTz(builder:flatbuffers.Builder, browserTzOffset:flatbuffers.Offset) {
|
||||
builder.addFieldOffset(1, browserTzOffset, 0);
|
||||
}
|
||||
|
||||
static endGuestLoginRequest(builder:flatbuffers.Builder):flatbuffers.Offset {
|
||||
const offset = builder.endObject();
|
||||
return offset;
|
||||
}
|
||||
|
||||
static createGuestLoginRequest(builder:flatbuffers.Builder, localeOffset:flatbuffers.Offset):flatbuffers.Offset {
|
||||
static createGuestLoginRequest(builder:flatbuffers.Builder, localeOffset:flatbuffers.Offset, browserTzOffset:flatbuffers.Offset):flatbuffers.Offset {
|
||||
GuestLoginRequest.startGuestLoginRequest(builder);
|
||||
GuestLoginRequest.addLocale(builder, localeOffset);
|
||||
GuestLoginRequest.addBrowserTz(builder, browserTzOffset);
|
||||
return GuestLoginRequest.endGuestLoginRequest(builder);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,22 +27,34 @@ initData(optionalEncoding?:any):string|Uint8Array|null {
|
||||
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
|
||||
}
|
||||
|
||||
browserTz():string|null
|
||||
browserTz(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null
|
||||
browserTz(optionalEncoding?:any):string|Uint8Array|null {
|
||||
const offset = this.bb!.__offset(this.bb_pos, 6);
|
||||
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
|
||||
}
|
||||
|
||||
static startTelegramLoginRequest(builder:flatbuffers.Builder) {
|
||||
builder.startObject(1);
|
||||
builder.startObject(2);
|
||||
}
|
||||
|
||||
static addInitData(builder:flatbuffers.Builder, initDataOffset:flatbuffers.Offset) {
|
||||
builder.addFieldOffset(0, initDataOffset, 0);
|
||||
}
|
||||
|
||||
static addBrowserTz(builder:flatbuffers.Builder, browserTzOffset:flatbuffers.Offset) {
|
||||
builder.addFieldOffset(1, browserTzOffset, 0);
|
||||
}
|
||||
|
||||
static endTelegramLoginRequest(builder:flatbuffers.Builder):flatbuffers.Offset {
|
||||
const offset = builder.endObject();
|
||||
return offset;
|
||||
}
|
||||
|
||||
static createTelegramLoginRequest(builder:flatbuffers.Builder, initDataOffset:flatbuffers.Offset):flatbuffers.Offset {
|
||||
static createTelegramLoginRequest(builder:flatbuffers.Builder, initDataOffset:flatbuffers.Offset, browserTzOffset:flatbuffers.Offset):flatbuffers.Offset {
|
||||
TelegramLoginRequest.startTelegramLoginRequest(builder);
|
||||
TelegramLoginRequest.addInitData(builder, initDataOffset);
|
||||
TelegramLoginRequest.addBrowserTz(builder, browserTzOffset);
|
||||
return TelegramLoginRequest.endTelegramLoginRequest(builder);
|
||||
}
|
||||
}
|
||||
|
||||
+107
-30
@@ -8,10 +8,15 @@ import { gateway } from './gateway';
|
||||
import { GatewayError } from './client';
|
||||
import { navigate, router } from './router.svelte';
|
||||
import { errorKey, localeFrom, setLocale, t, type Locale } from './i18n/index.svelte';
|
||||
import { languageNeedsServerSync } from './language';
|
||||
import { applyReduceMotion, applyTelegramTheme, applyTheme, type ThemePref } from './theme';
|
||||
import {
|
||||
insideTelegram,
|
||||
collectTelegramDiag,
|
||||
type TelegramDiag,
|
||||
onTelegramPath,
|
||||
hasLaunchFragment,
|
||||
loadTelegramSDK,
|
||||
telegramColorScheme,
|
||||
telegramContentSafeAreaTop,
|
||||
telegramSafeAreaTop,
|
||||
@@ -20,7 +25,6 @@ import {
|
||||
telegramLaunch,
|
||||
type TelegramLaunch,
|
||||
telegramOnEvent,
|
||||
telegramRequestFullscreen,
|
||||
telegramSetChrome,
|
||||
} from './telegram';
|
||||
import { parseStartParam } from './deeplink';
|
||||
@@ -46,6 +50,14 @@ export const app = $state<{
|
||||
* backend was down during a deploy). App.svelte then renders the boot-error retry screen
|
||||
* instead of the web login — a Mini App has no manual sign-in to fall back to. */
|
||||
bootError: boolean;
|
||||
/** On the dedicated /telegram/ entry, set to a privacy-safe diagnostic snapshot when a Mini App
|
||||
* launch carried no sign-in data (empty initData). App.svelte then renders the compact
|
||||
* launch-error screen (screens/TelegramLaunchError) — a shareable probe for why Telegram
|
||||
* delivered no initData (seen on some Android clients) — instead of bouncing to the landing. */
|
||||
launchError: TelegramDiag | null;
|
||||
/** Whether the hidden on-device debug panel (components/DebugPanel) is open — toggled by tapping
|
||||
* the header title ten times in quick succession. A support aid; carries no secrets. */
|
||||
debugOpen: boolean;
|
||||
/** Whether the lobby's first cold load has settled (success or error). The loading splash
|
||||
* (components/Splash.svelte) watches it to know when to dismiss; set by screens/Lobby. */
|
||||
lobbyReady: boolean;
|
||||
@@ -67,7 +79,6 @@ export const app = $state<{
|
||||
locale: Locale;
|
||||
reduceMotion: boolean;
|
||||
boardLabels: BoardLabelMode;
|
||||
localeLocked: boolean;
|
||||
/** Pending incoming friend requests, for the lobby ⚙️ badge and the Settings Friends tab. */
|
||||
notifications: number;
|
||||
/** Per-game flag: the player has at least one unread chat entry (message or nudge) in that
|
||||
@@ -96,6 +107,8 @@ export const app = $state<{
|
||||
}>({
|
||||
ready: false,
|
||||
bootError: false,
|
||||
launchError: null,
|
||||
debugOpen: false,
|
||||
lobbyReady: false,
|
||||
splashDone: false,
|
||||
streamAlive: false,
|
||||
@@ -108,7 +121,6 @@ export const app = $state<{
|
||||
locale: 'en',
|
||||
reduceMotion: false,
|
||||
boardLabels: 'beginner',
|
||||
localeLocked: false,
|
||||
notifications: 0,
|
||||
chatUnread: {},
|
||||
messageUnread: {},
|
||||
@@ -188,6 +200,16 @@ export function dismissWelcomeRedeem(): void {
|
||||
app.welcomeRedeem = false;
|
||||
}
|
||||
|
||||
/** openDebug / closeDebug toggle the hidden on-device debug panel (components/DebugPanel), opened
|
||||
* by tapping the header title ten times — a support aid that shows and shares client diagnostics. */
|
||||
export function openDebug(): void {
|
||||
app.debugOpen = true;
|
||||
}
|
||||
|
||||
export function closeDebug(): void {
|
||||
app.debugOpen = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* seedChatUnread sets a game's unread flags from an authoritative per-viewer REST view (the lobby
|
||||
* list, a game's state, or a move result): unread is any unread entry, message whether one of them
|
||||
@@ -450,11 +472,20 @@ async function adoptSession(s: Session): Promise<void> {
|
||||
await saveSession(s);
|
||||
try {
|
||||
app.profile = await gateway.profileGet();
|
||||
// The live interface language follows the device — the explicit local choice (locked, saved
|
||||
// in prefs) or the system guess made at bootstrap — and is no longer overridden from the
|
||||
// account here. preferred_language stays the user's saved choice (written from Settings,
|
||||
// and used for out-of-app push routing), but the Telegram bot a user signs in through must
|
||||
// not dictate the UI: a ru-bot launch on an English system stays English.
|
||||
// The live interface language follows the device — the explicit local choice (saved in
|
||||
// prefs) or the system guess made at bootstrap — and is no longer overridden from the
|
||||
// account here: the Telegram bot a user signs in through must not dictate the UI, so a
|
||||
// ru-bot launch on an English system stays English.
|
||||
//
|
||||
// The banner and out-of-app push are resolved server-side from preferred_language, so it
|
||||
// must track whatever language the UI actually shows — the explicit choice AND the system
|
||||
// guess. Reconcile it to the active locale on every adopt, not only after an explicit
|
||||
// Settings choice: a user who never opened Settings would otherwise be stuck on the
|
||||
// creation-time seed — e.g. an English banner under a Russian UI. This keeps every
|
||||
// server-rendered, language-dependent surface (banner, out-of-app push) aligned with the
|
||||
// interface, not just one. persistLanguageToServer self-gates (a no-op for guests and when
|
||||
// already equal), so there is no write in the steady state.
|
||||
void persistLanguageToServer(app.locale);
|
||||
} catch (err) {
|
||||
handleError(err);
|
||||
}
|
||||
@@ -475,6 +506,10 @@ export async function applyLinkResult(r: LinkResult): Promise<void> {
|
||||
return;
|
||||
}
|
||||
app.profile = await gateway.profileGet();
|
||||
// A guest who linked in place now has a durable account: push the active interface language
|
||||
// so the banner + push routing follow it (see adoptSession — reconciled regardless of an
|
||||
// explicit Settings choice).
|
||||
void persistLanguageToServer(app.locale);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -518,6 +553,31 @@ function syncViewportHeight(): void {
|
||||
if (h > 0) document.documentElement.style.setProperty('--vvh', `${h}px`);
|
||||
}
|
||||
|
||||
/**
|
||||
* applyTelegramChrome applies a Mini App launch's visual integration: Telegram's authoritative
|
||||
* colour scheme and theme, the matching header / background / bottom chrome, the safe-area insets,
|
||||
* the swipe-down guard, and immersive fullscreen on mobile. It is idempotent, so both the initial
|
||||
* bootstrap and a manual launch retry call it.
|
||||
*/
|
||||
function applyTelegramChrome(launch: TelegramLaunch): void {
|
||||
if (launch.theme) applyTelegramTheme(launch.theme);
|
||||
// Inside Telegram the colour scheme is Telegram's to decide; force it explicitly so the OS
|
||||
// prefers-color-scheme (which leaks into the Telegram Desktop webview) cannot fight it. Falls
|
||||
// back to the stored preference when the SDK omits it.
|
||||
applyTheme(telegramColorScheme() ?? app.theme);
|
||||
// Match Telegram's chrome to the app and stop its swipe-down-to-minimise from fighting tile
|
||||
// drag / board scroll.
|
||||
syncTelegramChrome();
|
||||
syncTelegramSafeArea();
|
||||
telegramDisableVerticalSwipes();
|
||||
}
|
||||
|
||||
/** How long to wait for the dynamically loaded Telegram Mini App SDK before giving up and showing
|
||||
* the launch-error screen. A network that blocks telegram.org makes the script hang rather than
|
||||
* fail fast (a connection refusal resolves immediately via the script's error event), so this only
|
||||
* bounds a true hang; it is generous enough not to misfire on a slow but working network. */
|
||||
const TELEGRAM_SDK_TIMEOUT_MS = 10000;
|
||||
|
||||
export async function bootstrap(): Promise<void> {
|
||||
const prefs = await loadPrefs();
|
||||
app.theme = prefs.theme ?? 'auto';
|
||||
@@ -527,7 +587,6 @@ export async function bootstrap(): Promise<void> {
|
||||
applyReduceMotion(app.reduceMotion);
|
||||
if (prefs.locale) {
|
||||
app.locale = prefs.locale;
|
||||
app.localeLocked = true;
|
||||
setLocale(prefs.locale);
|
||||
} else {
|
||||
const guess = localeFrom(typeof navigator !== 'undefined' ? navigator.language : 'en');
|
||||
@@ -542,33 +601,30 @@ export async function bootstrap(): Promise<void> {
|
||||
window.visualViewport.addEventListener('scroll', syncViewportHeight);
|
||||
}
|
||||
|
||||
// Telegram Mini App launch: apply the platform theme, authenticate via initData,
|
||||
// and route any deep-link start parameter. On the dedicated /telegram/ entry path
|
||||
// outside Telegram (no initData), refuse to render and send the visitor to the
|
||||
// site root.
|
||||
// Load the Telegram Mini App SDK dynamically, with a timeout, on a Telegram entry — it is no
|
||||
// longer a render-blocking <script> in index.html, so a network that blocks telegram.org (common
|
||||
// where Telegram itself reaches users only over a proxy) cannot hang the page and strand the app
|
||||
// or the diagnostic screen below. Skipped on a plain web / native entry, which never needs it.
|
||||
if (onTelegramPath() || hasLaunchFragment()) {
|
||||
await loadTelegramSDK(TELEGRAM_SDK_TIMEOUT_MS);
|
||||
}
|
||||
// Telegram Mini App launch: apply the platform theme, authenticate via initData, and route any
|
||||
// deep-link start parameter. On the dedicated /telegram/ entry without sign-in data (no/empty
|
||||
// initData — outside Telegram, or a Mini App launch that delivered none, as seen on some Android
|
||||
// clients), render the compact launch-error screen with a diagnostic snapshot the user can share
|
||||
// with the developer, instead of bouncing the visitor to the marketing landing.
|
||||
if (onTelegramPath() && !insideTelegram()) {
|
||||
if (typeof location !== 'undefined') location.replace('/');
|
||||
app.launchError = collectTelegramDiag();
|
||||
app.ready = true;
|
||||
return;
|
||||
}
|
||||
if (insideTelegram()) {
|
||||
const launch = telegramLaunch();
|
||||
if (launch.theme) applyTelegramTheme(launch.theme);
|
||||
// Inside Telegram the colour scheme is Telegram's to decide; force it explicitly
|
||||
// so the OS prefers-color-scheme (which leaks into the Telegram Desktop webview)
|
||||
// cannot fight it. Falls back to the stored preference when the SDK omits it.
|
||||
applyTheme(telegramColorScheme() ?? app.theme);
|
||||
// Match Telegram's chrome to the app and stop its swipe-down-to-minimise from
|
||||
// fighting tile drag / board scroll.
|
||||
syncTelegramChrome();
|
||||
syncTelegramSafeArea();
|
||||
applyTelegramChrome(launch);
|
||||
// Re-sync the safe-area insets whenever Telegram's chrome changes (registered once per load).
|
||||
telegramOnEvent('contentSafeAreaChanged', syncTelegramSafeArea);
|
||||
telegramOnEvent('safeAreaChanged', syncTelegramSafeArea);
|
||||
telegramOnEvent('fullscreenChanged', syncTelegramSafeArea);
|
||||
telegramDisableVerticalSwipes();
|
||||
// On mobile, go immersive fullscreen like Telegram's own Mini Apps; the fullscreenChanged
|
||||
// listener above then re-syncs the safe-area insets. Desktop keeps the bot's full-size
|
||||
// window. No-op on clients predating Bot API 8.0.
|
||||
telegramRequestFullscreen();
|
||||
await bootTelegram(launch);
|
||||
app.ready = true;
|
||||
return;
|
||||
@@ -635,6 +691,28 @@ export async function retryTelegramBoot(): Promise<void> {
|
||||
app.ready = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* retryTelegramLaunch re-attempts a Mini App launch from the launch-error screen's Retry button. If
|
||||
* sign-in data is present now (e.g. it arrived late on a slow client) it clears the error and runs
|
||||
* the normal launch; otherwise it refreshes the diagnostic snapshot so the screen reflects the
|
||||
* current state. It never reloads — telegram-web-app.js consumes the launch fragment on first load,
|
||||
* so a reload could discard the very data we are waiting for.
|
||||
*/
|
||||
export async function retryTelegramLaunch(): Promise<void> {
|
||||
// Re-attempt the SDK load — the network may have recovered since the launch-error screen showed.
|
||||
await loadTelegramSDK(TELEGRAM_SDK_TIMEOUT_MS);
|
||||
if (!insideTelegram()) {
|
||||
app.launchError = collectTelegramDiag();
|
||||
return;
|
||||
}
|
||||
app.launchError = null;
|
||||
app.ready = false;
|
||||
const launch = telegramLaunch();
|
||||
applyTelegramChrome(launch);
|
||||
await bootTelegram(launch);
|
||||
app.ready = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* routeStartParam navigates a Telegram deep-link start parameter to its target: a
|
||||
* specific game, the friends screen with a friend-code redemption, or the lobby
|
||||
@@ -743,7 +821,6 @@ export function setTheme(theme: ThemePref): void {
|
||||
|
||||
export function setLocalePref(locale: Locale): void {
|
||||
app.locale = locale;
|
||||
app.localeLocked = true;
|
||||
setLocale(locale);
|
||||
persistPrefs();
|
||||
void persistLanguageToServer(locale);
|
||||
@@ -756,7 +833,7 @@ export function setLocalePref(locale: Locale): void {
|
||||
*/
|
||||
async function persistLanguageToServer(locale: Locale): Promise<void> {
|
||||
const p = app.profile;
|
||||
if (!p || p.isGuest || p.preferredLanguage === locale) return;
|
||||
if (!p || !languageNeedsServerSync(p, locale)) return;
|
||||
try {
|
||||
app.profile = await gateway.profileUpdate({
|
||||
displayName: p.displayName,
|
||||
|
||||
@@ -19,13 +19,16 @@ import {
|
||||
decodeStateView,
|
||||
decodeStats,
|
||||
encodeCheckWord,
|
||||
encodeEmailRequest,
|
||||
encodeFeedbackSubmit,
|
||||
encodeDraftSave,
|
||||
encodeEnqueue,
|
||||
encodeExchange,
|
||||
encodeGuestLogin,
|
||||
encodeStateRequest,
|
||||
encodeSubmitPlay,
|
||||
encodeTarget,
|
||||
encodeTelegramLogin,
|
||||
encodeUpdateProfile,
|
||||
} from './codec';
|
||||
|
||||
@@ -73,21 +76,45 @@ describe('codec', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('carries the detected browser zone on every account-creating auth request', () => {
|
||||
const tg = fb.TelegramLoginRequest.getRootAsTelegramLoginRequest(
|
||||
new ByteBuffer(encodeTelegramLogin('init-data-blob', '+03:00')),
|
||||
);
|
||||
expect(tg.initData()).toBe('init-data-blob');
|
||||
expect(tg.browserTz()).toBe('+03:00');
|
||||
|
||||
const guest = fb.GuestLoginRequest.getRootAsGuestLoginRequest(
|
||||
new ByteBuffer(encodeGuestLogin('ru', '-05:30')),
|
||||
);
|
||||
expect(guest.locale()).toBe('ru');
|
||||
expect(guest.browserTz()).toBe('-05:30');
|
||||
|
||||
const email = fb.EmailRequestRequest.getRootAsEmailRequestRequest(
|
||||
new ByteBuffer(encodeEmailRequest('a@example.com', '+00:00')),
|
||||
);
|
||||
expect(email.email()).toBe('a@example.com');
|
||||
expect(email.browserTz()).toBe('+00:00');
|
||||
});
|
||||
|
||||
it('round-trips a feedback submit and decodes state + unread', () => {
|
||||
const att = new Uint8Array([1, 2, 3, 4]);
|
||||
const req = fb.FeedbackSubmitRequest.getRootAsFeedbackSubmitRequest(
|
||||
new ByteBuffer(encodeFeedbackSubmit('please fix', att, 'shot.png', 'ios')),
|
||||
new ByteBuffer(encodeFeedbackSubmit('please fix', att, 'shot.png', 'ios', 'v1.2.3', '+03:00')),
|
||||
);
|
||||
expect(req.body()).toBe('please fix');
|
||||
expect(req.attachmentName()).toBe('shot.png');
|
||||
expect(req.channel()).toBe('ios');
|
||||
expect(req.version()).toBe('v1.2.3');
|
||||
expect(req.browserTz()).toBe('+03:00');
|
||||
expect(Array.from(req.attachmentArray() ?? [])).toEqual([1, 2, 3, 4]);
|
||||
|
||||
// No attachment: the vector is empty.
|
||||
const req2 = fb.FeedbackSubmitRequest.getRootAsFeedbackSubmitRequest(
|
||||
new ByteBuffer(encodeFeedbackSubmit('hi', null, '', 'web')),
|
||||
new ByteBuffer(encodeFeedbackSubmit('hi', null, '', 'web', 'dev', '+00:00')),
|
||||
);
|
||||
expect(req2.body()).toBe('hi');
|
||||
expect(req2.version()).toBe('dev');
|
||||
expect(req2.browserTz()).toBe('+00:00');
|
||||
expect(req2.attachmentLength()).toBe(0);
|
||||
|
||||
// State carrying a reply.
|
||||
|
||||
+15
-3
@@ -179,27 +179,33 @@ export function encodeChatPost(gameId: string, body: string): Uint8Array {
|
||||
return finish(b, fb.ChatPostRequest.endChatPostRequest(b));
|
||||
}
|
||||
|
||||
export function encodeTelegramLogin(initData: string): Uint8Array {
|
||||
export function encodeTelegramLogin(initData: string, browserTz: string): Uint8Array {
|
||||
const b = new Builder(512);
|
||||
const d = b.createString(initData);
|
||||
const tz = b.createString(browserTz);
|
||||
fb.TelegramLoginRequest.startTelegramLoginRequest(b);
|
||||
fb.TelegramLoginRequest.addInitData(b, d);
|
||||
fb.TelegramLoginRequest.addBrowserTz(b, tz);
|
||||
return finish(b, fb.TelegramLoginRequest.endTelegramLoginRequest(b));
|
||||
}
|
||||
|
||||
export function encodeGuestLogin(locale: string): Uint8Array {
|
||||
export function encodeGuestLogin(locale: string, browserTz: string): Uint8Array {
|
||||
const b = new Builder(64);
|
||||
const l = b.createString(locale);
|
||||
const tz = b.createString(browserTz);
|
||||
fb.GuestLoginRequest.startGuestLoginRequest(b);
|
||||
fb.GuestLoginRequest.addLocale(b, l);
|
||||
fb.GuestLoginRequest.addBrowserTz(b, tz);
|
||||
return finish(b, fb.GuestLoginRequest.endGuestLoginRequest(b));
|
||||
}
|
||||
|
||||
export function encodeEmailRequest(email: string): Uint8Array {
|
||||
export function encodeEmailRequest(email: string, browserTz: string): Uint8Array {
|
||||
const b = new Builder(128);
|
||||
const e = b.createString(email);
|
||||
const tz = b.createString(browserTz);
|
||||
fb.EmailRequestRequest.startEmailRequestRequest(b);
|
||||
fb.EmailRequestRequest.addEmail(b, e);
|
||||
fb.EmailRequestRequest.addBrowserTz(b, tz);
|
||||
return finish(b, fb.EmailRequestRequest.endEmailRequestRequest(b));
|
||||
}
|
||||
|
||||
@@ -489,17 +495,23 @@ export function encodeFeedbackSubmit(
|
||||
attachment: Uint8Array | null,
|
||||
attachmentName: string,
|
||||
channel: string,
|
||||
version: string,
|
||||
browserTz: string,
|
||||
): Uint8Array {
|
||||
const b = new Builder(256);
|
||||
const bodyOff = b.createString(body);
|
||||
const attOff = attachment && attachment.length > 0 ? fb.FeedbackSubmitRequest.createAttachmentVector(b, attachment) : 0;
|
||||
const nameOff = b.createString(attachmentName);
|
||||
const chOff = b.createString(channel);
|
||||
const verOff = b.createString(version);
|
||||
const tzOff = b.createString(browserTz);
|
||||
fb.FeedbackSubmitRequest.startFeedbackSubmitRequest(b);
|
||||
fb.FeedbackSubmitRequest.addBody(b, bodyOff);
|
||||
if (attOff) fb.FeedbackSubmitRequest.addAttachment(b, attOff);
|
||||
fb.FeedbackSubmitRequest.addAttachmentName(b, nameOff);
|
||||
fb.FeedbackSubmitRequest.addChannel(b, chOff);
|
||||
fb.FeedbackSubmitRequest.addVersion(b, verOff);
|
||||
fb.FeedbackSubmitRequest.addBrowserTz(b, tzOff);
|
||||
return finish(b, fb.FeedbackSubmitRequest.endFeedbackSubmitRequest(b));
|
||||
}
|
||||
|
||||
|
||||
+11
-2
@@ -14,6 +14,11 @@ export const en = {
|
||||
'boot.errorTitle': "Couldn't load the game",
|
||||
'boot.errorBody': 'Please try again in a moment.',
|
||||
|
||||
'launch.errorTitle': "Can't open in Telegram",
|
||||
'launch.errorBody': 'Screenshot or share this with the developer.',
|
||||
'launch.share': 'Share',
|
||||
'launch.copied': 'Copied',
|
||||
|
||||
'common.back': 'Back',
|
||||
'common.cancel': 'Cancel',
|
||||
'common.ok': 'OK',
|
||||
@@ -227,6 +232,9 @@ export const en = {
|
||||
'friends.decline': 'Decline',
|
||||
'friends.unfriend': 'Remove',
|
||||
'friends.block': 'Block',
|
||||
'friends.actions': 'Actions',
|
||||
'friends.blockConfirm': 'Block this player?',
|
||||
'friends.unfriendConfirm': 'Remove from friends?',
|
||||
'friends.add': 'Add a friend',
|
||||
'friends.addFromGame': 'Add to friends',
|
||||
'friends.blockFromGame': 'Block player',
|
||||
@@ -257,6 +265,7 @@ export const en = {
|
||||
'invitations.with': 'With {names}',
|
||||
'invitations.accept': 'Accept',
|
||||
'invitations.decline': 'Decline',
|
||||
'invitations.declineConfirm': 'Decline invitation?',
|
||||
'invitations.cancel': 'Cancel',
|
||||
'invitations.waiting': 'Waiting for replies',
|
||||
|
||||
@@ -264,10 +273,10 @@ export const en = {
|
||||
'new.withFriends': 'Play with friends',
|
||||
'new.pickFriends': 'Choose who to invite',
|
||||
'new.searchFriends': 'Search friends',
|
||||
'new.gameType': 'Game type',
|
||||
'new.gameType': 'Variant',
|
||||
'new.invite': 'Send invitation',
|
||||
'new.moveTime': 'Move time',
|
||||
'new.hintsPerPlayer': 'Hints per player',
|
||||
'new.hintsPerPlayer': 'Hints',
|
||||
'new.multipleWordsPerTurn': 'Multiple words per turn',
|
||||
'new.start': 'Start game',
|
||||
'new.invited': 'Invitation sent.',
|
||||
|
||||
+11
-2
@@ -15,6 +15,11 @@ export const ru: Record<MessageKey, string> = {
|
||||
'boot.errorTitle': 'Не удалось загрузить игру',
|
||||
'boot.errorBody': 'Попробуйте ещё раз или зайдите позже.',
|
||||
|
||||
'launch.errorTitle': 'Не открывается в Telegram',
|
||||
'launch.errorBody': 'Сделайте скриншот или поделитесь с разработчиком.',
|
||||
'launch.share': 'Поделиться',
|
||||
'launch.copied': 'Скопировано',
|
||||
|
||||
'common.back': 'Назад',
|
||||
'common.cancel': 'Отмена',
|
||||
'common.ok': 'ОК',
|
||||
@@ -228,6 +233,9 @@ export const ru: Record<MessageKey, string> = {
|
||||
'friends.decline': 'Отклонить',
|
||||
'friends.unfriend': 'Удалить',
|
||||
'friends.block': 'Заблокировать',
|
||||
'friends.actions': 'Действия',
|
||||
'friends.blockConfirm': 'Заблокировать?',
|
||||
'friends.unfriendConfirm': 'Удалить из друзей?',
|
||||
'friends.add': 'Добавить друга',
|
||||
'friends.addFromGame': 'В друзья',
|
||||
'friends.blockFromGame': 'Заблокировать',
|
||||
@@ -258,6 +266,7 @@ export const ru: Record<MessageKey, string> = {
|
||||
'invitations.with': 'С {names}',
|
||||
'invitations.accept': 'Принять',
|
||||
'invitations.decline': 'Отклонить',
|
||||
'invitations.declineConfirm': 'Отклонить приглашение?',
|
||||
'invitations.cancel': 'Отменить',
|
||||
'invitations.waiting': 'Ожидаем ответы',
|
||||
|
||||
@@ -265,10 +274,10 @@ export const ru: Record<MessageKey, string> = {
|
||||
'new.withFriends': 'Игра с друзьями',
|
||||
'new.pickFriends': 'Кого пригласить',
|
||||
'new.searchFriends': 'Поиск друзей',
|
||||
'new.gameType': 'Тип игры',
|
||||
'new.gameType': 'Вариант',
|
||||
'new.invite': 'Отправить приглашение',
|
||||
'new.moveTime': 'Время на ход',
|
||||
'new.hintsPerPlayer': 'Подсказок на игрока',
|
||||
'new.hintsPerPlayer': 'Подсказки',
|
||||
'new.multipleWordsPerTurn': 'Несколько слов за ход',
|
||||
'new.start': 'Начать игру',
|
||||
'new.invited': 'Приглашение отправлено.',
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
|
||||
import { languageNeedsServerSync } from './language';
|
||||
import type { Profile } from './model';
|
||||
|
||||
// The reconciler only reads isGuest + preferredLanguage; a partial cast keeps the fixture small.
|
||||
const profile = (over: Partial<Profile>): Profile => ({ isGuest: false, preferredLanguage: 'en', ...over }) as Profile;
|
||||
|
||||
describe('languageNeedsServerSync', () => {
|
||||
it('is false without a profile', () => {
|
||||
expect(languageNeedsServerSync(null, 'ru')).toBe(false);
|
||||
expect(languageNeedsServerSync(undefined, 'ru')).toBe(false);
|
||||
});
|
||||
|
||||
it('is false for a guest — guests keep only the client preference', () => {
|
||||
expect(languageNeedsServerSync(profile({ isGuest: true, preferredLanguage: 'en' }), 'ru')).toBe(false);
|
||||
});
|
||||
|
||||
it('is false when the account already matches the locale', () => {
|
||||
expect(languageNeedsServerSync(profile({ preferredLanguage: 'ru' }), 'ru')).toBe(false);
|
||||
});
|
||||
|
||||
it('is true for a real account whose stored language differs (banner + push follow it)', () => {
|
||||
expect(languageNeedsServerSync(profile({ preferredLanguage: 'en' }), 'ru')).toBe(true);
|
||||
expect(languageNeedsServerSync(profile({ preferredLanguage: 'ru' }), 'en')).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
// Interface-language reconciliation. Kept out of app.svelte.ts (a runes module that the
|
||||
// node-env Vitest layer cannot import) so the decision is unit-testable.
|
||||
|
||||
import type { Locale } from './i18n/catalog';
|
||||
import type { Profile } from './model';
|
||||
|
||||
/**
|
||||
* languageNeedsServerSync reports whether the durable account's `preferred_language` should be
|
||||
* rewritten to the chosen interface `locale`. It is true only for a real (non-guest) account
|
||||
* whose stored language differs from the locale; guests keep only the client-side preference,
|
||||
* and an already-matching account is a no-op.
|
||||
*
|
||||
* The UI language follows the device (the local choice / system guess), but the advertising
|
||||
* banner and out-of-app push routing are resolved server-side from `preferred_language`. A saved
|
||||
* device choice the account has not yet recorded — picked while a guest, or differing from the
|
||||
* Telegram system-language seed — would otherwise leave the banner and pushes in the wrong
|
||||
* language until the next Settings change. Both the Settings control and the on-load reconciler
|
||||
* gate their write on this.
|
||||
*/
|
||||
export function languageNeedsServerSync(profile: Profile | null | undefined, locale: Locale): boolean {
|
||||
return !!profile && !profile.isGuest && profile.preferredLanguage !== locale;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { pickGcgDelivery, shareOrDownloadGcg } from './share';
|
||||
import { pickGcgDelivery, pickTextShare, shareOrDownloadGcg, shareText } from './share';
|
||||
import type { GcgExport } from './model';
|
||||
|
||||
const file = {} as File;
|
||||
@@ -60,3 +60,42 @@ describe('shareOrDownloadGcg', () => {
|
||||
expect(anchor.click).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
describe('pickTextShare', () => {
|
||||
it('shares when Web Share is available', () => {
|
||||
expect(pickTextShare({ share: async () => {}, canShare: () => true })).toBe('share');
|
||||
});
|
||||
|
||||
it('shares when share exists without canShare (text needs no file capability check)', () => {
|
||||
expect(pickTextShare({ share: async () => {} })).toBe('share');
|
||||
});
|
||||
|
||||
it('copies when there is no Web Share (desktop)', () => {
|
||||
expect(pickTextShare(undefined)).toBe('copy');
|
||||
expect(pickTextShare({} as never)).toBe('copy');
|
||||
});
|
||||
});
|
||||
|
||||
describe('shareText', () => {
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
it('uses the OS share sheet when available', async () => {
|
||||
const share = vi.fn().mockResolvedValue(undefined);
|
||||
vi.stubGlobal('navigator', { share, canShare: () => true });
|
||||
expect(await shareText('diag', 'title')).toBe('shared');
|
||||
expect(share).toHaveBeenCalledWith({ title: 'title', text: 'diag' });
|
||||
});
|
||||
|
||||
it('copies to the clipboard when Web Share is absent (desktop)', async () => {
|
||||
const writeText = vi.fn().mockResolvedValue(undefined);
|
||||
vi.stubGlobal('navigator', { clipboard: { writeText } });
|
||||
expect(await shareText('diag', 'title')).toBe('copied');
|
||||
expect(writeText).toHaveBeenCalledWith('diag');
|
||||
});
|
||||
|
||||
it('reports failure without a fallback when the share is cancelled', async () => {
|
||||
const share = vi.fn().mockRejectedValue(new DOMException('cancelled', 'AbortError'));
|
||||
vi.stubGlobal('navigator', { share, canShare: () => true });
|
||||
expect(await shareText('diag', 'title')).toBe('failed');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -51,3 +51,42 @@ function downloadFile(content: string, filename: string): void {
|
||||
a.remove();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
type TextShareNav = Pick<Navigator, 'share'> & { canShare?: Navigator['canShare'] };
|
||||
|
||||
/**
|
||||
* pickTextShare decides how to deliver a plain-text payload: through the OS share sheet (Web Share,
|
||||
* available on mobile including the Telegram Mini App) or, on a desktop browser without it, a
|
||||
* clipboard copy. Pure, so it is unit-tested with a mock navigator.
|
||||
*/
|
||||
export function pickTextShare(nav: TextShareNav | undefined): 'share' | 'copy' {
|
||||
if (nav && typeof nav.share === 'function' && (typeof nav.canShare !== 'function' || nav.canShare({ text: 'x' }))) {
|
||||
return 'share';
|
||||
}
|
||||
return 'copy';
|
||||
}
|
||||
|
||||
/**
|
||||
* shareText delivers text through the OS share sheet where supported, else copies it to the
|
||||
* clipboard. It reports the path taken — 'shared', 'copied', or 'failed' (a cancelled share or an
|
||||
* unavailable clipboard) — so the caller can confirm a silent copy to the user. Like
|
||||
* shareOrDownloadGcg it never strands the webview: a cancelled share simply does nothing.
|
||||
*/
|
||||
export async function shareText(text: string, title: string): Promise<'shared' | 'copied' | 'failed'> {
|
||||
const nav = typeof navigator !== 'undefined' ? navigator : undefined;
|
||||
if (!nav) return 'failed';
|
||||
if (pickTextShare(nav) === 'share') {
|
||||
try {
|
||||
await nav.share({ title, text });
|
||||
return 'shared';
|
||||
} catch {
|
||||
return 'failed';
|
||||
}
|
||||
}
|
||||
try {
|
||||
await nav.clipboard.writeText(text);
|
||||
return 'copied';
|
||||
} catch {
|
||||
return 'failed';
|
||||
}
|
||||
}
|
||||
|
||||
+106
-65
@@ -1,11 +1,12 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
collectTelegramDiag,
|
||||
insideTelegram,
|
||||
loadTelegramSDK,
|
||||
telegramSdkOutcome,
|
||||
routeExternalLinkInTelegram,
|
||||
telegramClosingConfirmation,
|
||||
telegramLaunch,
|
||||
telegramOpenExternalLink,
|
||||
telegramRequestFullscreen,
|
||||
} from './telegram';
|
||||
|
||||
function stubWebApp(initData: string, startParam?: string) {
|
||||
@@ -45,69 +46,6 @@ describe('telegram launch detection', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// stubClient stands up a fake WebApp on the given platform with spies for the mobile-gated
|
||||
// chrome toggles, so the platform gate can be asserted without a real Telegram client.
|
||||
function stubClient(platform?: string) {
|
||||
const enable = vi.fn();
|
||||
const disable = vi.fn();
|
||||
const requestFullscreen = vi.fn();
|
||||
vi.stubGlobal('window', {
|
||||
Telegram: {
|
||||
WebApp: { platform, enableClosingConfirmation: enable, disableClosingConfirmation: disable, requestFullscreen },
|
||||
},
|
||||
});
|
||||
return { enable, disable, requestFullscreen };
|
||||
}
|
||||
|
||||
const mobilePlatforms = ['ios', 'android', 'android_x'];
|
||||
const desktopPlatforms = ['tdesktop', 'macos', 'web', undefined];
|
||||
|
||||
describe('telegramClosingConfirmation', () => {
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
it('arms the close guard on mobile clients', () => {
|
||||
for (const p of mobilePlatforms) {
|
||||
const { enable } = stubClient(p);
|
||||
telegramClosingConfirmation(true);
|
||||
expect(enable, `platform=${p}`).toHaveBeenCalledOnce();
|
||||
}
|
||||
});
|
||||
|
||||
it('skips the close guard on desktop clients (the dialog there is just noise)', () => {
|
||||
for (const p of desktopPlatforms) {
|
||||
const { enable } = stubClient(p);
|
||||
telegramClosingConfirmation(true);
|
||||
expect(enable, `platform=${p}`).not.toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
|
||||
it('always lifts the guard on leave, regardless of platform', () => {
|
||||
const { disable } = stubClient('tdesktop');
|
||||
telegramClosingConfirmation(false);
|
||||
expect(disable).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
describe('telegramRequestFullscreen', () => {
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
it('goes immersive fullscreen on mobile clients', () => {
|
||||
for (const p of mobilePlatforms) {
|
||||
const { requestFullscreen } = stubClient(p);
|
||||
telegramRequestFullscreen();
|
||||
expect(requestFullscreen, `platform=${p}`).toHaveBeenCalledOnce();
|
||||
}
|
||||
});
|
||||
|
||||
it('leaves desktop clients as a standard window (the bot full-size setting fills it)', () => {
|
||||
for (const p of desktopPlatforms) {
|
||||
const { requestFullscreen } = stubClient(p);
|
||||
telegramRequestFullscreen();
|
||||
expect(requestFullscreen, `platform=${p}`).not.toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('telegramOpenExternalLink', () => {
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
@@ -155,3 +93,106 @@ describe('routeExternalLinkInTelegram', () => {
|
||||
expect(routeExternalLinkInTelegram({ href: 'https://x.io', target: '_blank' })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('collectTelegramDiag', () => {
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
it('reports a missing SDK outside Telegram', () => {
|
||||
const d = collectTelegramDiag();
|
||||
expect(d.hasSDK).toBe(false);
|
||||
expect(d.hasWebApp).toBe(false);
|
||||
expect(d.initDataLen).toBe(0);
|
||||
expect(d.fieldsPresent).toEqual([]);
|
||||
expect(d.fieldsMissing).toEqual(['user', 'auth_date', 'hash', 'signature']);
|
||||
});
|
||||
|
||||
it('reads field NAMES (never values) from a non-empty initData', () => {
|
||||
stubWebApp('query_id=abc&user=%7B%7D&auth_date=1&hash=deadbeef');
|
||||
const d = collectTelegramDiag();
|
||||
expect(d.hasSDK).toBe(true);
|
||||
expect(d.hasWebApp).toBe(true);
|
||||
expect(d.initDataLen).toBeGreaterThan(0);
|
||||
expect(d.fieldsPresent).toEqual(['query_id', 'user', 'auth_date', 'hash']);
|
||||
expect(d.fieldsMissing).toEqual(['signature']);
|
||||
});
|
||||
|
||||
it('recovers field names from the URL fragment when the SDK left initData empty', () => {
|
||||
// Telegram passed launch data in the fragment, but WebApp.initData is empty (the Android
|
||||
// failure this screen diagnoses): the names come from the raw fragment instead, and
|
||||
// hashHadTgData flags that the data did arrive in the URL.
|
||||
vi.stubGlobal('window', { Telegram: { WebApp: { initData: '', platform: 'android' } } });
|
||||
vi.stubGlobal('location', {
|
||||
hash: '#tgWebAppData=user%3D%257B%257D%26auth_date%3D1%26hash%3Ddeadbeef&tgWebAppVersion=7.0',
|
||||
pathname: '/telegram/',
|
||||
});
|
||||
const d = collectTelegramDiag();
|
||||
expect(d.hasSDK).toBe(true);
|
||||
expect(d.platform).toBe('android');
|
||||
expect(d.initDataLen).toBe(0);
|
||||
expect(d.hashHadTgData).toBe(true);
|
||||
expect(d.fieldsPresent).toEqual(['user', 'auth_date', 'hash']);
|
||||
expect(d.fieldsMissing).toEqual(['signature']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadTelegramSDK', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('resolves true and records "present" when the SDK is already there', async () => {
|
||||
vi.stubGlobal('window', { Telegram: { WebApp: { initData: '' } } });
|
||||
vi.stubGlobal('document', { createElement: vi.fn(), head: { appendChild: vi.fn() } });
|
||||
await expect(loadTelegramSDK(10000)).resolves.toBe(true);
|
||||
expect(telegramSdkOutcome()).toBe('present');
|
||||
});
|
||||
|
||||
it('records "loaded" when the script defines the WebApp', async () => {
|
||||
const script: Record<string, unknown> = {};
|
||||
vi.stubGlobal('window', {});
|
||||
vi.stubGlobal('document', {
|
||||
createElement: () => script,
|
||||
head: {
|
||||
appendChild: () => {
|
||||
(window as unknown as { Telegram: unknown }).Telegram = { WebApp: { initData: '' } };
|
||||
(script.onload as () => void)();
|
||||
},
|
||||
},
|
||||
});
|
||||
await expect(loadTelegramSDK(10000)).resolves.toBe(true);
|
||||
expect(telegramSdkOutcome()).toBe('loaded');
|
||||
});
|
||||
|
||||
it('records "no-webapp" when the script loads but defines nothing', async () => {
|
||||
const script: Record<string, unknown> = {};
|
||||
vi.stubGlobal('window', {});
|
||||
vi.stubGlobal('document', {
|
||||
createElement: () => script,
|
||||
head: { appendChild: () => (script.onload as () => void)() },
|
||||
});
|
||||
await expect(loadTelegramSDK(10000)).resolves.toBe(false);
|
||||
expect(telegramSdkOutcome()).toBe('no-webapp');
|
||||
});
|
||||
|
||||
it('records "error" when the script fails to load (telegram.org unreachable)', async () => {
|
||||
const script: Record<string, unknown> = {};
|
||||
vi.stubGlobal('window', {});
|
||||
vi.stubGlobal('document', {
|
||||
createElement: () => script,
|
||||
head: { appendChild: () => (script.onerror as () => void)() },
|
||||
});
|
||||
await expect(loadTelegramSDK(10000)).resolves.toBe(false);
|
||||
expect(telegramSdkOutcome()).toBe('error');
|
||||
});
|
||||
|
||||
it('records "timeout" when the script neither loads nor fails in time', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubGlobal('window', {});
|
||||
vi.stubGlobal('document', { createElement: () => ({}), head: { appendChild: vi.fn() } });
|
||||
const p = loadTelegramSDK(10000);
|
||||
await vi.advanceTimersByTimeAsync(10000);
|
||||
await expect(p).resolves.toBe(false);
|
||||
expect(telegramSdkOutcome()).toBe('timeout');
|
||||
});
|
||||
});
|
||||
|
||||
+230
-66
@@ -1,6 +1,7 @@
|
||||
// Telegram Mini App SDK access. The official telegram-web-app.js (loaded in
|
||||
// index.html) exposes window.Telegram.WebApp; this wraps the subset the app uses:
|
||||
// launch detection, initData (for auth.telegram), the deep-link start parameter,
|
||||
// Telegram Mini App SDK access. The official telegram-web-app.js (loaded dynamically with a
|
||||
// timeout by loadTelegramSDK — not a render-blocking <script> in index.html, so a network that
|
||||
// blocks telegram.org cannot hang the page) exposes window.Telegram.WebApp; this wraps the subset
|
||||
// the app uses: launch detection, initData (for auth.telegram), the deep-link start parameter,
|
||||
// theme params, and ready()/expand(). Every helper is safe to call outside Telegram.
|
||||
|
||||
import type { TelegramThemeParams } from './theme';
|
||||
@@ -9,14 +10,18 @@ interface TelegramWebApp {
|
||||
initData: string;
|
||||
initDataUnsafe?: { start_param?: string };
|
||||
platform?: string;
|
||||
version?: string;
|
||||
themeParams?: TelegramThemeParams;
|
||||
colorScheme?: 'light' | 'dark';
|
||||
isFullscreen?: boolean;
|
||||
isExpanded?: boolean;
|
||||
viewportHeight?: number;
|
||||
viewportStableHeight?: number;
|
||||
exitFullscreen?: () => void;
|
||||
safeAreaInset?: { top: number; bottom: number; left: number; right: number };
|
||||
contentSafeAreaInset?: { top: number; bottom: number; left: number; right: number };
|
||||
ready?: () => void;
|
||||
expand?: () => void;
|
||||
requestFullscreen?: () => void;
|
||||
openTelegramLink?: (url: string) => void;
|
||||
openLink?: (url: string) => void;
|
||||
onEvent?: (event: string, handler: () => void) => void;
|
||||
@@ -24,14 +29,13 @@ interface TelegramWebApp {
|
||||
setBackgroundColor?: (color: string) => void;
|
||||
setBottomBarColor?: (color: string) => void;
|
||||
disableVerticalSwipes?: () => void;
|
||||
enableClosingConfirmation?: () => void;
|
||||
disableClosingConfirmation?: () => void;
|
||||
HapticFeedback?: {
|
||||
impactOccurred?: (style: string) => void;
|
||||
notificationOccurred?: (type: string) => void;
|
||||
selectionChanged?: () => void;
|
||||
};
|
||||
BackButton?: {
|
||||
isVisible?: boolean;
|
||||
show?: () => void;
|
||||
hide?: () => void;
|
||||
onClick?: (cb: () => void) => void;
|
||||
@@ -53,6 +57,72 @@ export function insideTelegram(): boolean {
|
||||
return !!w && typeof w.initData === 'string' && w.initData.length > 0;
|
||||
}
|
||||
|
||||
// The ?NN suffix pins the Bot API SDK version Telegram serves (and busts the cache); keep it at the
|
||||
// version the official Mini Apps page currently recommends so newer client features (fullscreen,
|
||||
// safe-area insets, vertical-swipe guard, …) are available. Bump it when Telegram bumps theirs.
|
||||
const sdkScriptSrc = 'https://telegram.org/js/telegram-web-app.js?62';
|
||||
|
||||
/**
|
||||
* TelegramSdkOutcome records how the dynamic telegram-web-app.js load resolved, surfaced on the
|
||||
* launch-error screen to tell the failure modes apart — notably 'error' / 'timeout', which mean the
|
||||
* network could not reach telegram.org (the script blocked or hung):
|
||||
*
|
||||
* not-attempted — loadTelegramSDK was never called (a plain web / native entry)
|
||||
* present — window.Telegram.WebApp was already there (a cached load or native injection)
|
||||
* loaded — the script loaded and defined window.Telegram.WebApp
|
||||
* no-webapp — the script loaded (HTTP 200) but did not define window.Telegram.WebApp
|
||||
* error — the script failed to load (telegram.org unreachable / blocked, a fast failure)
|
||||
* timeout — the script neither loaded nor failed within the timeout (a blocked, hanging fetch)
|
||||
*/
|
||||
export type TelegramSdkOutcome = 'not-attempted' | 'present' | 'loaded' | 'no-webapp' | 'error' | 'timeout';
|
||||
|
||||
let sdkLoadOutcome: TelegramSdkOutcome = 'not-attempted';
|
||||
|
||||
/** telegramSdkOutcome returns how the last loadTelegramSDK attempt resolved (see TelegramSdkOutcome). */
|
||||
export function telegramSdkOutcome(): TelegramSdkOutcome {
|
||||
return sdkLoadOutcome;
|
||||
}
|
||||
|
||||
/**
|
||||
* loadTelegramSDK injects the official telegram-web-app.js and resolves true once
|
||||
* window.Telegram.WebApp is available, or false if the script errors or does not load within
|
||||
* timeoutMs. It is loaded dynamically — not a render-blocking <script> in index.html — so a network
|
||||
* that blocks telegram.org (common where Telegram itself reaches users only over a proxy) cannot
|
||||
* hang the page and strand the app or the launch-error screen. Resolves true immediately when the
|
||||
* SDK is already present (a cached load, or a future native injection); a fast connection failure
|
||||
* resolves via the error event without waiting out the timeout, so the timeout only bounds a true
|
||||
* hang.
|
||||
*/
|
||||
export function loadTelegramSDK(timeoutMs: number): Promise<boolean> {
|
||||
if (typeof document === 'undefined') return Promise.resolve(false);
|
||||
if (webApp()) {
|
||||
sdkLoadOutcome = 'present';
|
||||
return Promise.resolve(true);
|
||||
}
|
||||
return new Promise<boolean>((resolve) => {
|
||||
let done = false;
|
||||
const finish = (outcome: TelegramSdkOutcome): void => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
sdkLoadOutcome = outcome;
|
||||
resolve(outcome === 'loaded');
|
||||
};
|
||||
const timer = setTimeout(() => finish(webApp() ? 'loaded' : 'timeout'), timeoutMs);
|
||||
const s = document.createElement('script');
|
||||
s.src = sdkScriptSrc;
|
||||
s.async = true;
|
||||
s.onload = () => {
|
||||
clearTimeout(timer);
|
||||
finish(webApp() ? 'loaded' : 'no-webapp');
|
||||
};
|
||||
s.onerror = () => {
|
||||
clearTimeout(timer);
|
||||
finish('error');
|
||||
};
|
||||
document.head.appendChild(s);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* telegramOpenLink opens a t.me link through the Mini App SDK, so Telegram navigates to
|
||||
* it natively (e.g. a bot chat) rather than spawning an in-app browser tab. Returns false
|
||||
@@ -224,66 +294,6 @@ export function telegramHaptic(kind: Haptic): void {
|
||||
else h.impactOccurred?.(kind);
|
||||
}
|
||||
|
||||
/**
|
||||
* isMobilePlatform reports whether the Mini App runs on a Telegram mobile client — iOS or
|
||||
* Android (the latter reported as 'android' by Telegram for Android and 'android_x' by
|
||||
* Telegram X). Desktop clients (tdesktop, macOS, web) report other values. Used to limit
|
||||
* mobile-only chrome such as the close guard and immersive fullscreen.
|
||||
*/
|
||||
function isMobilePlatform(): boolean {
|
||||
const p = webApp()?.platform;
|
||||
return p === 'ios' || p === 'android' || p === 'android_x';
|
||||
}
|
||||
|
||||
/**
|
||||
* telegramRequestFullscreen asks Telegram to open the Mini App in fullscreen (Bot API 8.0+),
|
||||
* but only on mobile clients — mirroring how Telegram's own Mini Apps go immersive on phones
|
||||
* while staying a standard window on desktop (where the bot's full-size setting already fills
|
||||
* the window). A no-op outside Telegram, on desktop, or on clients predating the method.
|
||||
*/
|
||||
export function telegramRequestFullscreen(): void {
|
||||
if (isMobilePlatform()) webApp()?.requestFullscreen?.();
|
||||
}
|
||||
|
||||
/**
|
||||
* telegramClosingConfirmation toggles the confirmation Telegram shows when the user swipes
|
||||
* the Mini App closed — enabled during an active game so it is not lost by accident. The
|
||||
* guard is only armed on mobile clients: on desktop, closing a window is deliberate and
|
||||
* Telegram surfaces a "changes may not be saved" dialog that is just noise here (drafts
|
||||
* auto-save), so the confirmation is skipped there.
|
||||
*/
|
||||
export function telegramClosingConfirmation(on: boolean): void {
|
||||
const w = webApp();
|
||||
if (on) {
|
||||
if (isMobilePlatform()) w?.enableClosingConfirmation?.();
|
||||
} else {
|
||||
w?.disableClosingConfirmation?.();
|
||||
}
|
||||
}
|
||||
|
||||
let backHandler: (() => void) | null = null;
|
||||
|
||||
/**
|
||||
* telegramBackButton shows or hides Telegram's native header back button, wiring its
|
||||
* click to onClick (replacing any previous handler). The app hides its own back chevron
|
||||
* inside Telegram so only the native control shows.
|
||||
*/
|
||||
export function telegramBackButton(show: boolean, onClick?: () => void): void {
|
||||
const b = webApp()?.BackButton;
|
||||
if (!b) return;
|
||||
if (backHandler) b.offClick?.(backHandler);
|
||||
backHandler = null;
|
||||
if (show) {
|
||||
if (onClick) {
|
||||
backHandler = onClick;
|
||||
b.onClick?.(onClick);
|
||||
}
|
||||
b.show?.();
|
||||
} else {
|
||||
b.hide?.();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* startParamFromURL reads a startapp parameter from the page URL — a bot web_app
|
||||
* launch button carries the deep-link there rather than in initDataUnsafe.
|
||||
@@ -302,6 +312,160 @@ export function onTelegramPath(): boolean {
|
||||
return location.pathname.startsWith('/telegram/');
|
||||
}
|
||||
|
||||
/** hasLaunchFragment reports whether the URL fragment carries Telegram launch params (tgWebApp…),
|
||||
* the form Telegram appends when opening a Mini App — so the SDK is loaded for a Mini App opened
|
||||
* at the site root too, not only the /telegram/ path. */
|
||||
export function hasLaunchFragment(): boolean {
|
||||
if (typeof location === 'undefined') return false;
|
||||
return location.hash.includes('tgWebApp');
|
||||
}
|
||||
|
||||
// --- Launch diagnostics (the /telegram/ entry without sign-in data) ---
|
||||
|
||||
/** The initData fields a valid Telegram launch is expected to carry; their absence is the signal
|
||||
* the launch-error screen reports. Only field names are ever inspected, never their values. */
|
||||
const expectedInitDataFields = ['user', 'auth_date', 'hash', 'signature'];
|
||||
|
||||
interface uaBrand {
|
||||
brand: string;
|
||||
version: string;
|
||||
}
|
||||
|
||||
interface uaDataValue {
|
||||
platform?: string;
|
||||
mobile?: boolean;
|
||||
brands?: uaBrand[];
|
||||
}
|
||||
|
||||
/** uaData returns the User-Agent Client Hints object (Chromium only — notably the Android Telegram
|
||||
* webview), or undefined where it is unavailable (iOS / Safari / Firefox). */
|
||||
function uaData(): uaDataValue | undefined {
|
||||
if (typeof navigator === 'undefined') return undefined;
|
||||
return (navigator as unknown as { userAgentData?: uaDataValue }).userAgentData;
|
||||
}
|
||||
|
||||
/** launchFragmentData returns the raw tgWebAppData carried in the URL fragment (the form Telegram
|
||||
* appends on launch), or '' when absent. With no SDK present a non-empty value means Telegram
|
||||
* delivered the data but telegram-web-app.js never ran to parse it. */
|
||||
function launchFragmentData(): string {
|
||||
if (typeof location === 'undefined') return '';
|
||||
const frag = location.hash.replace(/^#/, '');
|
||||
if (!frag) return '';
|
||||
try {
|
||||
return new URLSearchParams(frag).get('tgWebAppData') ?? '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/** initDataFieldNames parses a Telegram initData (or raw fragment data) query string and returns
|
||||
* only its field NAMES — never the values, since the hash / signature are auth material. */
|
||||
function initDataFieldNames(raw: string): string[] {
|
||||
if (!raw) return [];
|
||||
try {
|
||||
return [...new URLSearchParams(raw).keys()];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* TelegramDiag is a privacy-safe snapshot of why a Mini App launch lacked sign-in data, taken at
|
||||
* the moment of failure and rendered on the launch-error screen so a stuck user can share it with
|
||||
* the developer. It carries no secret values — only presence flags, client / OS identification and
|
||||
* the field NAMES of the launch data, never the signed initData itself, and never an IP.
|
||||
*/
|
||||
export interface TelegramDiag {
|
||||
/** Whether window.Telegram (the telegram-web-app.js script) is present at all. */
|
||||
hasSDK: boolean;
|
||||
/** Whether window.Telegram.WebApp is present. */
|
||||
hasWebApp: boolean;
|
||||
/** How the dynamic telegram-web-app.js load resolved (see TelegramSdkOutcome) — 'error' /
|
||||
* 'timeout' mean telegram.org was unreachable, the prime suspect for an empty launch. */
|
||||
sdkLoad: TelegramSdkOutcome;
|
||||
/** Telegram's own platform string (ios | android | android_x | tdesktop | web | …), or ''. */
|
||||
platform: string;
|
||||
/** The Bot API version the client reports, or ''. */
|
||||
version: string;
|
||||
/** The length of WebApp.initData — 0 is the failure this screen reports. */
|
||||
initDataLen: number;
|
||||
/** Whether the URL fragment still carried tgWebAppData at launch; true with hasSDK false means
|
||||
* Telegram delivered the data but the SDK script did not load to parse it. */
|
||||
hashHadTgData: boolean;
|
||||
/** The field names present in the launch data (from initData, or the raw fragment when the SDK
|
||||
* left initData empty); values are never included. */
|
||||
fieldsPresent: string[];
|
||||
/** The expected field names absent from the launch data (a subset of expectedInitDataFields). */
|
||||
fieldsMissing: string[];
|
||||
/** The OS / platform per User-Agent Client Hints (else navigator.platform), e.g. 'Android', ''. */
|
||||
osPlatform: string;
|
||||
/** Whether the client reports itself mobile per Client Hints: 'yes' | 'no' | '' (unknown). */
|
||||
mobile: string;
|
||||
/** The browser brands + major versions per Client Hints (Chromium only), or ''. */
|
||||
browser: string;
|
||||
/** The full User-Agent string — the catch-all that also carries the OS version and webview build. */
|
||||
userAgent: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* collectTelegramDiag captures a TelegramDiag snapshot of the current launch state. Call it at the
|
||||
* point a /telegram/ launch is found to lack sign-in data, so the snapshot reflects that moment —
|
||||
* sign-in data arriving late would otherwise mask the failure.
|
||||
*/
|
||||
export function collectTelegramDiag(): TelegramDiag {
|
||||
const w = webApp();
|
||||
const sdk = typeof window !== 'undefined' && !!(window as unknown as { Telegram?: unknown }).Telegram;
|
||||
const initData = w?.initData ?? '';
|
||||
const fragData = initData ? '' : launchFragmentData();
|
||||
const present = initDataFieldNames(initData || fragData);
|
||||
const ua = uaData();
|
||||
const navPlatform =
|
||||
typeof navigator === 'undefined' ? '' : (navigator as unknown as { platform?: string }).platform ?? '';
|
||||
return {
|
||||
hasSDK: sdk,
|
||||
hasWebApp: !!w,
|
||||
sdkLoad: sdkLoadOutcome,
|
||||
platform: w?.platform ?? '',
|
||||
version: w?.version ?? '',
|
||||
initDataLen: initData.length,
|
||||
hashHadTgData: fragData.length > 0,
|
||||
fieldsPresent: present,
|
||||
fieldsMissing: expectedInitDataFields.filter((f) => !present.includes(f)),
|
||||
osPlatform: ua?.platform ?? navPlatform,
|
||||
mobile: ua?.mobile === undefined ? '' : ua.mobile ? 'yes' : 'no',
|
||||
browser: (ua?.brands ?? []).map((b) => `${b.brand} ${b.version}`).join(', '),
|
||||
userAgent: typeof navigator === 'undefined' ? '' : navigator.userAgent,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* telegramChromeDiag returns a compact, privacy-safe readout of Telegram's viewport / chrome state
|
||||
* (platform, version, fullscreen/expanded, viewport geometry, safe-area insets, SDK-load outcome,
|
||||
* back-button state, UA). It feeds the hidden debug panel (components/DebugPanel), opened by tapping
|
||||
* the header title ten times. No secrets: no initData values, no IP.
|
||||
*/
|
||||
export function telegramChromeDiag(): string {
|
||||
const w = webApp();
|
||||
if (!w) return 'no telegram';
|
||||
const win = typeof window === 'undefined' ? undefined : window;
|
||||
const scr = typeof screen === 'undefined' ? undefined : screen;
|
||||
const vv = win?.visualViewport ?? undefined;
|
||||
const bar = typeof document === 'undefined' ? null : (document.querySelector('.bar')?.getBoundingClientRect() ?? null);
|
||||
const sa = w.safeAreaInset;
|
||||
const csa = w.contentSafeAreaInset;
|
||||
const n = (v: number | undefined): string => (v === undefined ? '—' : String(Math.round(v)));
|
||||
return [
|
||||
`platform: ${w.platform ?? '—'} version: ${w.version ?? '—'} scheme: ${w.colorScheme ?? '—'}`,
|
||||
`isFullscreen: ${w.isFullscreen} isExpanded: ${w.isExpanded}`,
|
||||
`inTG: ${insideTelegram()} sdkLoad: ${sdkLoadOutcome} backPresent: ${!!w.BackButton} backVisible: ${w.BackButton?.isVisible}`,
|
||||
`innerH: ${n(win?.innerHeight)} outerH: ${n(win?.outerHeight)} screenH: ${n(scr?.height)} availH: ${n(scr?.availHeight)}`,
|
||||
`screenY: ${n(win?.screenY)} vv.offTop: ${n(vv?.offsetTop)} vv.h: ${n(vv?.height)}`,
|
||||
`tgViewportH: ${n(w.viewportHeight)} stableH: ${n(w.viewportStableHeight)}`,
|
||||
`safeArea T/B: ${n(sa?.top)}/${n(sa?.bottom)} contentSafe T/B: ${n(csa?.top)}/${n(csa?.bottom)}`,
|
||||
`appHeader top/h: ${bar ? Math.round(bar.top) : '—'}/${bar ? Math.round(bar.height) : '—'}`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
// --- Login Widget (web sign-in for account linking) ---
|
||||
|
||||
// The Login Widget is the web (non-Mini-App) Telegram sign-in. It is used only to
|
||||
|
||||
@@ -10,6 +10,7 @@ import { createConnectTransport } from '@connectrpc/connect-web';
|
||||
import { Gateway } from '../gen/edge/v1/edge_pb';
|
||||
import { GatewayError, type GatewayClient } from './client';
|
||||
import * as codec from './codec';
|
||||
import { browserOffset } from './profileValidation';
|
||||
import { registerProbe, reportOffline, reportOnline } from './connection.svelte';
|
||||
import { backoffMs, isConnectionCode, retryable, toGatewayError } from './retry';
|
||||
|
||||
@@ -62,13 +63,13 @@ export function createTransport(baseUrl: string): GatewayClient {
|
||||
},
|
||||
|
||||
async authTelegram(initData) {
|
||||
return codec.decodeSession(await exec('auth.telegram', codec.encodeTelegramLogin(initData)));
|
||||
return codec.decodeSession(await exec('auth.telegram', codec.encodeTelegramLogin(initData, browserOffset())));
|
||||
},
|
||||
async authGuest(locale) {
|
||||
return codec.decodeSession(await exec('auth.guest', codec.encodeGuestLogin(locale ?? '')));
|
||||
return codec.decodeSession(await exec('auth.guest', codec.encodeGuestLogin(locale ?? '', browserOffset())));
|
||||
},
|
||||
async authEmailRequest(email) {
|
||||
await exec('auth.email.request', codec.encodeEmailRequest(email));
|
||||
await exec('auth.email.request', codec.encodeEmailRequest(email, browserOffset()));
|
||||
},
|
||||
async authEmailLogin(email, code) {
|
||||
return codec.decodeSession(await exec('auth.email.login', codec.encodeEmailLogin(email, code)));
|
||||
@@ -147,7 +148,10 @@ export function createTransport(baseUrl: string): GatewayClient {
|
||||
await exec('chat.read', codec.encodeGameAction(id));
|
||||
},
|
||||
async feedbackSubmit(body, attachment, attachmentName, channel) {
|
||||
await exec('feedback.submit', codec.encodeFeedbackSubmit(body, attachment, attachmentName, channel));
|
||||
// The app build (Vite define) and the device's detected UTC offset ride with the report
|
||||
// so the operator sees which version it came from and the local time it was filed; the
|
||||
// caller need not pass them.
|
||||
await exec('feedback.submit', codec.encodeFeedbackSubmit(body, attachment, attachmentName, channel, __APP_VERSION__, browserOffset()));
|
||||
},
|
||||
async feedbackGet() {
|
||||
return codec.decodeFeedbackState(await exec('feedback.get', codec.empty()));
|
||||
|
||||
@@ -5,6 +5,8 @@ import {
|
||||
availableVariants,
|
||||
supportsMultipleWordsToggle,
|
||||
multipleWordsForRequest,
|
||||
usesStarBlank,
|
||||
BLANK_STAR,
|
||||
} from './variants';
|
||||
|
||||
describe('ALL_VARIANTS', () => {
|
||||
@@ -53,3 +55,16 @@ describe('multipleWordsForRequest', () => {
|
||||
expect(multipleWordsForRequest('scrabble_en', true)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('usesStarBlank', () => {
|
||||
it('marks the blank with a star for Erudit only', () => {
|
||||
expect(usesStarBlank('erudit_ru')).toBe(true);
|
||||
expect(usesStarBlank('scrabble_ru')).toBe(false);
|
||||
expect(usesStarBlank('scrabble_en')).toBe(false);
|
||||
});
|
||||
|
||||
it('BLANK_STAR is the heavy teardrop-spoked asterisk (U+273B)', () => {
|
||||
expect(BLANK_STAR).toBe('✻');
|
||||
expect(BLANK_STAR.codePointAt(0)).toBe(0x273b);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -48,6 +48,20 @@ export const VARIANT_FLAG: Record<Variant, string> = {
|
||||
// ru -> Russian + Эрудит.
|
||||
export const VARIANT_LANGUAGE: Record<Variant, 'en' | 'ru'> = { scrabble_en: 'en', scrabble_ru: 'ru', erudit_ru: 'ru' };
|
||||
|
||||
// BLANK_STAR is the glyph drawn on an Эрудит blank tile: the variant's blank is the
|
||||
// "звёздочка" (star) chip, so it carries a star rather than a bare face. U+273B HEAVY
|
||||
// TEARDROP-SPOKED ASTERISK.
|
||||
export const BLANK_STAR = '✻';
|
||||
|
||||
// usesStarBlank reports whether a variant marks its blank tiles with BLANK_STAR. Only
|
||||
// Эрудит does: an empty rack blank shows the star centred, and a placed blank carries it
|
||||
// in the value corner (the corner is free — a blank has no point value). The Scrabble
|
||||
// variants leave the blank unmarked (an empty rack face; a placed blank shown by its
|
||||
// designated letter alone).
|
||||
export function usesStarBlank(v: Variant): boolean {
|
||||
return v === 'erudit_ru';
|
||||
}
|
||||
|
||||
// availableVariants gates ALL_VARIANTS by the player's variant preferences (the set
|
||||
// they enabled in Settings). An empty or absent set is ungated (returns every variant)
|
||||
// — a safety fallback; a real profile always carries at least one preference.
|
||||
|
||||
+189
-42
@@ -1,5 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import Modal from '../components/Modal.svelte';
|
||||
import { app, handleError, refreshNotifications, showToast } from '../lib/app.svelte';
|
||||
import { connection } from '../lib/connection.svelte';
|
||||
import { gateway } from '../lib/gateway';
|
||||
@@ -16,6 +17,11 @@
|
||||
let robotBlocks = $state<RobotBlockEntry[]>([]);
|
||||
let code = $state<FriendCode | null>(null);
|
||||
let redeemInput = $state('');
|
||||
// The friend row whose kebab actions are slid open, like the lobby list.
|
||||
let revealedId = $state<string | null>(null);
|
||||
// Pending confirmation targets: the friend account awaiting a block / unfriend confirm.
|
||||
let blockTarget = $state<AccountRef | null>(null);
|
||||
let unfriendTarget = $state<AccountRef | null>(null);
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
@@ -52,6 +58,41 @@
|
||||
const blockUser = (id: string) => act(() => gateway.block(id));
|
||||
const unblock = (id: string) => act(() => gateway.unblock(id));
|
||||
|
||||
// toggleReveal slides one friend row open (closing any other), exposing its
|
||||
// block / unfriend icon actions; tapping the same kebab again closes it.
|
||||
function toggleReveal(id: string): void {
|
||||
revealedId = revealedId === id ? null : id;
|
||||
}
|
||||
|
||||
// confirmBlock / confirmUnfriend run the pending action once its modal is
|
||||
// accepted, then clear the target and the revealed row.
|
||||
function confirmBlock(): void {
|
||||
const target = blockTarget;
|
||||
blockTarget = null;
|
||||
revealedId = null;
|
||||
if (target) void blockUser(target.accountId);
|
||||
}
|
||||
|
||||
function confirmUnfriend(): void {
|
||||
const target = unfriendTarget;
|
||||
unfriendTarget = null;
|
||||
revealedId = null;
|
||||
if (target) void remove(target.accountId);
|
||||
}
|
||||
|
||||
// While a friend row is slid open, a tap anywhere outside its action buttons
|
||||
// closes it again. Taps on a kebab are skipped so its own toggle stays in charge.
|
||||
$effect(() => {
|
||||
if (revealedId === null) return;
|
||||
function onDown(e: PointerEvent) {
|
||||
const el = e.target as Element | null;
|
||||
if (el?.closest('.acts') || el?.closest('.kebab')) return;
|
||||
revealedId = null;
|
||||
}
|
||||
window.addEventListener('pointerdown', onDown, true);
|
||||
return () => window.removeEventListener('pointerdown', onDown, true);
|
||||
});
|
||||
|
||||
async function getCode() {
|
||||
try {
|
||||
code = await gateway.friendCodeIssue();
|
||||
@@ -152,30 +193,39 @@
|
||||
{#if incoming.length}
|
||||
<section>
|
||||
<h3>{t('friends.incoming')}</h3>
|
||||
{#each incoming as r (r.accountId)}
|
||||
<div class="item">
|
||||
<span class="who">{r.displayName}</span>
|
||||
<span class="acts">
|
||||
<button class="btn" onclick={() => respond(r.accountId, true)} disabled={!connection.online}>{t('friends.accept')}</button>
|
||||
<button class="ghost" onclick={() => respond(r.accountId, false)} disabled={!connection.online}>{t('friends.decline')}</button>
|
||||
</span>
|
||||
</div>
|
||||
{/each}
|
||||
<div class="list">
|
||||
{#each incoming as r (r.accountId)}
|
||||
<div class="rowwrap">
|
||||
<div class="row">
|
||||
<span class="who">{r.displayName}</span>
|
||||
<span class="btns">
|
||||
<button class="btn" onclick={() => respond(r.accountId, true)} disabled={!connection.online}>{t('friends.accept')}</button>
|
||||
<button class="ghost" onclick={() => respond(r.accountId, false)} disabled={!connection.online}>{t('friends.decline')}</button>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
{/if}
|
||||
|
||||
<section>
|
||||
<h3>{t('friends.yours')}</h3>
|
||||
{#if friends.length}
|
||||
{#each friends as f (f.accountId)}
|
||||
<div class="item">
|
||||
<span class="who">{f.displayName}</span>
|
||||
<span class="acts">
|
||||
<button class="ghost" onclick={() => remove(f.accountId)} disabled={!connection.online}>{t('friends.unfriend')}</button>
|
||||
<button class="ghost danger" onclick={() => blockUser(f.accountId)} disabled={!connection.online}>{t('friends.block')}</button>
|
||||
</span>
|
||||
</div>
|
||||
{/each}
|
||||
<div class="list">
|
||||
{#each friends as f (f.accountId)}
|
||||
<div class="rowwrap" class:revealed={revealedId === f.accountId}>
|
||||
<div class="acts">
|
||||
<button class="iconbtn" onclick={() => (blockTarget = f)} disabled={!connection.online} aria-label={t('friends.block')}>🚫</button>
|
||||
<button class="iconbtn" onclick={() => (unfriendTarget = f)} disabled={!connection.online} aria-label={t('friends.unfriend')}>✖️</button>
|
||||
</div>
|
||||
<div class="row">
|
||||
<span class="who">{f.displayName}</span>
|
||||
<button class="kebab" onclick={() => toggleReveal(f.accountId)} aria-label={t('friends.actions')}>⋮</button>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{:else}
|
||||
<p class="muted">{t('friends.none')}</p>
|
||||
{/if}
|
||||
@@ -184,20 +234,49 @@
|
||||
{#if blocked.length || robotBlocks.length}
|
||||
<section>
|
||||
<h3>{t('friends.blockedList')}</h3>
|
||||
{#each blocked as b (b.accountId)}
|
||||
<div class="item">
|
||||
<span class="who">{b.displayName}</span>
|
||||
<button class="ghost" onclick={() => unblock(b.accountId)} disabled={!connection.online}>{t('friends.unblock')}</button>
|
||||
</div>
|
||||
{/each}
|
||||
{#each robotBlocks as r (r.id)}
|
||||
<div class="item">
|
||||
<span class="who">{r.displayName}</span>
|
||||
<button class="ghost" onclick={() => unblock(r.id)} disabled={!connection.online}>{t('friends.unblock')}</button>
|
||||
</div>
|
||||
{/each}
|
||||
<div class="list">
|
||||
{#each blocked as b (b.accountId)}
|
||||
<div class="rowwrap">
|
||||
<div class="row">
|
||||
<span class="who">{b.displayName}</span>
|
||||
<span class="btns">
|
||||
<button class="ghost" onclick={() => unblock(b.accountId)} disabled={!connection.online}>{t('friends.unblock')}</button>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
{#each robotBlocks as r (r.id)}
|
||||
<div class="rowwrap">
|
||||
<div class="row">
|
||||
<span class="who">{r.displayName}</span>
|
||||
<span class="btns">
|
||||
<button class="ghost" onclick={() => unblock(r.id)} disabled={!connection.online}>{t('friends.unblock')}</button>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
{/if}
|
||||
|
||||
{#if blockTarget}
|
||||
<Modal title={t('friends.blockConfirm')} onclose={() => (blockTarget = null)}>
|
||||
<p class="confirm-name">{blockTarget.displayName}</p>
|
||||
<div class="confirm-row">
|
||||
<button class="cancel" onclick={() => (blockTarget = null)}>{t('common.cancel')}</button>
|
||||
<button class="danger" onclick={confirmBlock} disabled={!connection.online}>{t('friends.block')}</button>
|
||||
</div>
|
||||
</Modal>
|
||||
{/if}
|
||||
{#if unfriendTarget}
|
||||
<Modal title={t('friends.unfriendConfirm')} onclose={() => (unfriendTarget = null)}>
|
||||
<p class="confirm-name">{unfriendTarget.displayName}</p>
|
||||
<div class="confirm-row">
|
||||
<button class="cancel" onclick={() => (unfriendTarget = null)}>{t('common.cancel')}</button>
|
||||
<button class="danger" onclick={confirmUnfriend} disabled={!connection.online}>{t('friends.unfriend')}</button>
|
||||
</div>
|
||||
</Modal>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -279,28 +358,76 @@
|
||||
padding: 4px 0;
|
||||
text-align: left;
|
||||
}
|
||||
.item {
|
||||
.list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
/* One-line rows split by hairlines, mirroring the lobby list. */
|
||||
.rowwrap {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
.rowwrap + .rowwrap {
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
/* Block / unfriend icon actions sit behind the friend row, exposed when it slides left. */
|
||||
.acts {
|
||||
position: absolute;
|
||||
inset: 0 0 0 auto;
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
}
|
||||
.iconbtn {
|
||||
flex: 0 0 auto;
|
||||
width: 48px;
|
||||
border: none;
|
||||
background: var(--bg-elev);
|
||||
color: var(--text);
|
||||
font-size: 1.1rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.iconbtn + .iconbtn {
|
||||
border-left: 1px solid var(--border); /* the vertical divider between 🚫 and ✖️ */
|
||||
}
|
||||
.row {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--border);
|
||||
background: var(--surface);
|
||||
border-radius: var(--radius-sm);
|
||||
margin-bottom: 8px;
|
||||
background: var(--bg);
|
||||
transform: translateX(0);
|
||||
transition: transform 0.18s ease;
|
||||
}
|
||||
.rowwrap.revealed .row {
|
||||
transform: translateX(-96px); /* 2 × 48px icon buttons */
|
||||
}
|
||||
.kebab {
|
||||
flex: 0 0 auto;
|
||||
width: 30px;
|
||||
padding: 6px 0;
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--text-muted);
|
||||
font-size: 1.4rem;
|
||||
line-height: 1;
|
||||
}
|
||||
.btns {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
.who {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-weight: 600;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.acts {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
.btn {
|
||||
padding: 8px 12px;
|
||||
border: 1px solid var(--accent);
|
||||
@@ -315,7 +442,27 @@
|
||||
color: var(--text);
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
.ghost.danger {
|
||||
color: var(--danger, #c0392b);
|
||||
.confirm-name {
|
||||
margin: 0 0 12px;
|
||||
font-weight: 600;
|
||||
overflow-wrap: anywhere; /* a long display name wraps instead of stretching the sheet */
|
||||
}
|
||||
.confirm-row {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
.confirm-row button {
|
||||
flex: 1;
|
||||
padding: 11px;
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--border);
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
font-weight: 600;
|
||||
}
|
||||
.confirm-row .danger {
|
||||
background: var(--danger);
|
||||
color: #fff;
|
||||
border-color: var(--danger);
|
||||
}
|
||||
</style>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user