ui/phase-24: push events, turn-ready toast, single SubscribeEvents consumer

Wires the gateway's signed SubscribeEvents stream end-to-end:

- backend: emit game.turn.ready from lobby.OnRuntimeSnapshot on every
  current_turn advance, addressed to every active membership, push-only
  channel, idempotency key turn-ready:<game_id>:<turn>;
- ui: single EventStream singleton replaces revocation-watcher.ts and
  carries both per-event dispatch and revocation detection; toast
  primitive (store + host) lives in lib/; GameStateStore gains
  pendingTurn/markPendingTurn/advanceToPending and a persisted
  lastViewedTurn so a return after multiple turns surfaces the same
  "view now" affordance as a live push event;
- mandatory event-signature verification through ui/core
  (verifyPayloadHash + verifyEvent), full-jitter exponential backoff
  1s -> 30s on transient failure, signOut("revoked") on
  Unauthenticated or clean end-of-stream;
- catalog and migration accept the new kind; tests cover producer
  (testcontainers + capturing publisher), consumer (Vitest event
  stream, toast, game-state extensions), and a Playwright e2e
  delivering a signed frame to the live UI.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Ilia Denisov
2026-05-11 16:16:31 +02:00
parent 5a2a977dc6
commit 5b07bb4e14
26 changed files with 2181 additions and 209 deletions
+104
View File
@@ -24,6 +24,8 @@ import type { WrapMode } from "../map/world";
const PREF_NAMESPACE = "game-prefs";
const PREF_KEY_WRAP_MODE = (gameId: string) => `${gameId}/wrap-mode`;
const PREF_KEY_LAST_VIEWED_TURN = (gameId: string) =>
`${gameId}/last-viewed-turn`;
/**
* GAME_STATE_CONTEXT_KEY is the Svelte context key the in-game shell
@@ -66,6 +68,17 @@ export class GameStateStore {
* this flag is enough to keep the network silent.
*/
synthetic = $state(false);
/**
* pendingTurn carries the latest server-side turn the user has not
* yet opened: it is `> currentTurn` whenever the server reports a
* new turn (either through a `game.turn.ready` push event after
* boot, or through the boot-time discovery that the persisted
* `lastViewedTurn` is behind the lobby's `current_turn`). The
* layout's `$effect` renders a toast/banner when it is non-null;
* `advanceToPending()` refreshes the store onto the new turn and
* clears the rune.
*/
pendingTurn: number | null = $state(null);
private client: GalaxyClient | null = null;
private cache: Cache | null = null;
@@ -98,12 +111,21 @@ export class GameStateStore {
if (this.client === null || this.cache === null) {
throw new Error("game-state: setGame called before init");
}
// Only forget the pending indicator when the consumer is
// actually switching games. On the initial `setGame` after
// `init` the previous `gameId` is the empty string, and a
// concurrent `markPendingTurn` from a push event arriving
// while we were still bootstrapping must not be erased.
if (this.gameId !== "" && this.gameId !== gameId) {
this.pendingTurn = null;
}
this.gameId = gameId;
this.status = "loading";
this.error = null;
this.report = null;
this.wrapMode = await readWrapMode(this.cache, gameId);
const lastViewed = await readLastViewedTurn(this.cache, gameId);
try {
const summary = await this.findGame(gameId);
@@ -114,7 +136,68 @@ export class GameStateStore {
}
this.gameName = summary.gameName;
this.currentTurn = summary.currentTurn;
// If the persisted last-viewed turn is older than the
// server-side current turn, open the user on their last-seen
// snapshot and surface the gap through `pendingTurn` so the
// shell can render a "new turn available" affordance instead
// of silently auto-advancing.
if (
lastViewed !== null &&
lastViewed >= 0 &&
lastViewed < summary.currentTurn
) {
this.pendingTurn = summary.currentTurn;
await this.loadTurn(lastViewed);
} else {
await this.loadTurn(summary.currentTurn);
}
} catch (err) {
if (this.destroyed) return;
this.status = "error";
this.error = describe(err);
}
}
/**
* markPendingTurn records a server-reported new turn (typically
* delivered through `game.turn.ready`). Values that are not
* strictly ahead of the latest known turn (current or already
* pending) are ignored so a replayed event cannot regress the
* indicator.
*/
markPendingTurn(turn: number): void {
const latest = this.pendingTurn ?? this.currentTurn;
if (turn > latest) {
this.pendingTurn = turn;
}
}
/**
* advanceToPending re-queries the lobby record and loads the
* report at the server's latest `current_turn`, then clears the
* pending indicator. Unlike `setGame`, this skips the
* `lastViewedTurn` lookup — the user has explicitly asked to
* jump to the new turn, so any persisted bookmark from the
* previous session is irrelevant. Failures keep the indicator
* set so the user can retry from the same affordance.
*/
async advanceToPending(): Promise<void> {
if (this.pendingTurn === null || this.client === null) {
return;
}
this.status = "loading";
this.error = null;
try {
const summary = await this.findGame(this.gameId);
if (summary === null) {
this.status = "error";
this.error = `game ${this.gameId} is not in your list`;
return;
}
this.gameName = summary.gameName;
this.currentTurn = summary.currentTurn;
await this.loadTurn(summary.currentTurn);
this.pendingTurn = null;
} catch (err) {
if (this.destroyed) return;
this.status = "error";
@@ -219,6 +302,13 @@ export class GameStateStore {
this.report = report;
this.currentTurn = turn;
this.status = "ready";
if (this.cache !== null) {
await this.cache.put(
PREF_NAMESPACE,
PREF_KEY_LAST_VIEWED_TURN(this.gameId),
turn,
);
}
}
private installVisibilityListener(): void {
@@ -239,6 +329,20 @@ async function readWrapMode(cache: Cache, gameId: string): Promise<WrapMode> {
return "torus";
}
async function readLastViewedTurn(
cache: Cache,
gameId: string,
): Promise<number | null> {
const stored = await cache.get<number>(
PREF_NAMESPACE,
PREF_KEY_LAST_VIEWED_TURN(gameId),
);
if (typeof stored !== "number" || !Number.isFinite(stored)) {
return null;
}
return stored;
}
function describe(err: unknown): string {
if (err instanceof GameStateError) {
return err.message;
+5
View File
@@ -7,10 +7,15 @@
const en = {
"common.language": "language",
"common.loading": "loading…",
"common.dismiss": "dismiss",
"common.browser_not_supported_title": "browser not supported",
"common.browser_not_supported_body":
"Galaxy requires Ed25519 in WebCrypto. See supported browsers.",
"game.events.turn_ready.message": "turn {turn} is ready",
"game.events.turn_ready.action": "view now",
"game.events.signature_failed": "verification failed, reconnecting…",
"login.title": "sign in to Galaxy",
"login.email_label": "email",
"login.email_required": "email must not be empty",
+5
View File
@@ -8,10 +8,15 @@ import type en from "./en";
const ru: Record<keyof typeof en, string> = {
"common.language": "язык",
"common.loading": "загрузка…",
"common.dismiss": "закрыть",
"common.browser_not_supported_title": "браузер не поддерживается",
"common.browser_not_supported_body":
"Galaxy требует поддержки Ed25519 в WebCrypto. См. список поддерживаемых браузеров.",
"game.events.turn_ready.message": "ход {turn} готов",
"game.events.turn_ready.action": "открыть",
"game.events.signature_failed": "подпись повреждена, переподключение…",
"login.title": "вход в Galaxy",
"login.email_label": "электронная почта",
"login.email_required": "адрес не должен быть пустым",
-157
View File
@@ -1,157 +0,0 @@
// `startRevocationWatcher` opens an authenticated SubscribeEvents
// stream against the gateway and treats any non-aborted termination
// as a session-revocation signal: the watcher calls
// `session.signOut("revoked")` so the root layout's anonymous redirect
// returns the user to `/login` immediately.
//
// Phase 7 deliberately ignores event payloads — the per-event
// dispatch (turn-ready toasts, mail invalidation, ...) lands in
// Phase 24. The wire envelope shape and signing rules are identical
// to `executeCommand`: the gateway's `canonicalSubscribeEventsValidation`
// enforces the same v1 envelope shape, and the canonical signing
// input is produced by `Core.signRequest`. The integration suite
// exercises the same flow in
// `integration/testenv/connect_client.go::SubscribeEvents` with the
// `gateway.subscribe` literal.
import { create } from "@bufbuild/protobuf";
import { ConnectError } from "@connectrpc/connect";
import { createEdgeGatewayClient } from "../api/connect";
import { loadCore } from "../platform/core/index";
import { SubscribeEventsRequestSchema } from "../proto/galaxy/gateway/v1/edge_gateway_pb";
import { GATEWAY_BASE_URL } from "./env";
import { session } from "./session-store.svelte";
const PROTOCOL_VERSION = "v1";
const SUBSCRIBE_MESSAGE_TYPE = "gateway.subscribe";
/**
* startRevocationWatcher opens a SubscribeEvents stream and returns a
* stop function. Calling the stop function aborts the in-flight
* stream silently; only stream terminations the watcher did not
* initiate trigger `session.signOut("revoked")`.
*/
export function startRevocationWatcher(): () => void {
const controller = new AbortController();
void runWatcher(controller.signal);
return () => controller.abort();
}
async function runWatcher(signal: AbortSignal): Promise<void> {
if (
session.status !== "authenticated" ||
session.keypair === null ||
session.deviceSessionId === null
) {
return;
}
const keypair = session.keypair;
const deviceSessionId = session.deviceSessionId;
let stream: AsyncIterable<unknown>;
try {
const core = await loadCore();
const requestId =
typeof crypto.randomUUID === "function"
? crypto.randomUUID()
: fallbackRequestId();
const timestampMs = BigInt(Date.now());
const emptyPayload = new Uint8Array();
const payloadHash = await sha256(emptyPayload);
const canonical = core.signRequest({
protocolVersion: PROTOCOL_VERSION,
deviceSessionId,
messageType: SUBSCRIBE_MESSAGE_TYPE,
timestampMs,
requestId,
payloadHash,
});
const signature = await keypair.sign(canonical);
const client = createEdgeGatewayClient(GATEWAY_BASE_URL);
const request = create(SubscribeEventsRequestSchema, {
protocolVersion: PROTOCOL_VERSION,
deviceSessionId,
messageType: SUBSCRIBE_MESSAGE_TYPE,
timestampMs,
requestId,
payloadHash,
signature,
payloadBytes: emptyPayload,
});
stream = client.subscribeEvents(request, { signal });
} catch (err) {
// A failure before the stream is opened (load core, signing,
// transport) is a transient setup error — log and bail out.
// Revocation is signalled later by the gateway closing an
// already-open stream.
if (!signal.aborted) {
console.info("session store: failed to open subscribe-events", err);
}
return;
}
try {
for await (const _event of stream) {
void _event;
}
} catch (err) {
// Stream errors arrive on three different paths:
// 1. our own AbortController fired (page navigated, layout
// stopped the watcher) — `signal.aborted` is true;
// 2. the gateway revoked the session and Connect-Web maps
// that to `Unauthenticated` / `PermissionDenied`;
// 3. transient network failure (Wi-Fi drop, server
// restart) — anything else.
//
// Only branch 2 is a true revocation. Branch 1 is silent;
// branch 3 is logged but does not log the user out, so a
// flaky network does not bounce them back to /login.
if (signal.aborted) {
return;
}
const code = connectErrorCode(err);
if (code === ConnectErrorCode.Unauthenticated) {
await session.signOut("revoked");
return;
}
console.info("session store: subscribe-events stream errored", err);
return;
}
// Clean end-of-stream from the gateway is the documented
// `session_invalidation` signal: backend closes the push stream
// once the device session flips to revoked.
if (!signal.aborted && session.status === "authenticated") {
await session.signOut("revoked");
}
}
const ConnectErrorCode = {
Canceled: 1,
Unauthenticated: 16,
} as const;
function connectErrorCode(err: unknown): number | null {
if (err instanceof ConnectError) {
return err.code;
}
return null;
}
async function sha256(payload: Uint8Array): Promise<Uint8Array> {
const digest = await crypto.subtle.digest(
"SHA-256",
payload as BufferSource,
);
return new Uint8Array(digest);
}
function fallbackRequestId(): string {
const buf = new Uint8Array(16);
crypto.getRandomValues(buf);
let hex = "";
for (let i = 0; i < buf.length; i++) {
hex += buf[i]!.toString(16).padStart(2, "0");
}
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
}
+109
View File
@@ -0,0 +1,109 @@
<!--
Single mounting point for the global toast slot, rendered once from
the root layout. The host reads `toast.current` reactively and stays
fully empty (zero DOM nodes inside the wrapper) when no toast is
active so the surrounding shell layout is not perturbed.
-->
<script lang="ts">
import { i18n } from "$lib/i18n/index.svelte";
import { toast } from "$lib/toast.svelte";
function handleAction(): void {
const current = toast.current;
if (current === null) {
return;
}
const action = current.onAction;
toast.dismiss(current.id);
action?.();
}
function handleClose(): void {
if (toast.current === null) {
return;
}
toast.dismiss(toast.current.id);
}
</script>
{#if toast.current !== null}
<div class="toast-host" role="status" aria-live="polite">
<div class="toast" data-testid="toast">
<span class="toast-message" data-testid="toast-message">
{i18n.t(toast.current.messageKey, toast.current.messageParams)}
</span>
{#if toast.current.actionLabelKey !== undefined}
<button
type="button"
class="toast-action"
data-testid="toast-action"
onclick={handleAction}
>
{i18n.t(toast.current.actionLabelKey)}
</button>
{/if}
<button
type="button"
class="toast-close"
data-testid="toast-close"
aria-label={i18n.t("common.dismiss")}
onclick={handleClose}
>
×
</button>
</div>
</div>
{/if}
<style>
.toast-host {
position: fixed;
top: 1rem;
left: 50%;
transform: translateX(-50%);
z-index: 1000;
max-width: min(28rem, calc(100vw - 2rem));
}
.toast {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.6rem 0.85rem;
background: #1a2034;
color: #e8eaf6;
border: 1px solid #2c3354;
border-radius: 0.5rem;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.5);
font-size: 0.9rem;
}
.toast-message {
flex: 1;
min-width: 0;
}
.toast-action {
background: transparent;
color: #8ab4f8;
border: none;
font-weight: 600;
cursor: pointer;
font-size: 0.8rem;
padding: 0.2rem 0.5rem;
text-transform: uppercase;
letter-spacing: 0.04em;
}
.toast-action:hover {
text-decoration: underline;
}
.toast-close {
background: transparent;
color: #94a3b8;
border: none;
font-size: 1.1rem;
line-height: 1;
cursor: pointer;
padding: 0 0.25rem;
}
.toast-close:hover {
color: #e8eaf6;
}
</style>
+97
View File
@@ -0,0 +1,97 @@
// `ToastStore` is the single transient-notification primitive for the
// SvelteKit shell. Phase 24 ships it together with the push-event
// dispatch: the per-game layout shows one `Turn N is ready. View now.`
// toast on a verified `game.turn.ready` event. Later phases reuse the
// same store for mail / battle / lobby toasts (PLAN.md §"cross-cutting
// shell").
//
// The store keeps **one** active toast at a time: a fresh `show()`
// replaces the previous descriptor. This matches the UX intent of
// "one loud notification at a time" — the rare cases where several
// events arrive in quick succession are still observable, because
// each replacement re-arms the timer and the user sees every payload
// in turn.
import type { TranslationKey } from "./i18n/index.svelte";
/**
* ToastDescriptor describes one toast in flight. `messageKey` and
* `actionLabelKey` are typed against the i18n catalog so a missing
* translation key fails at compile time. `durationMs === null` (or
* `undefined`) makes the toast sticky — the user must dismiss it
* through the action button or another `show()` call.
*/
export interface ToastDescriptor {
id: string;
messageKey: TranslationKey;
messageParams?: Record<string, string>;
actionLabelKey?: TranslationKey;
onAction?: () => void;
durationMs?: number | null;
}
class ToastStore {
current: ToastDescriptor | null = $state(null);
private timer: ReturnType<typeof setTimeout> | null = null;
private counter = 0;
/**
* show replaces the active toast with descriptor and returns its
* fresh id. Pass that id to `dismiss(id)` from a delayed callback
* to avoid dismissing a newer toast that already took its slot.
*/
show(descriptor: Omit<ToastDescriptor, "id">): string {
this.clearTimer();
this.counter += 1;
const id = String(this.counter);
const full: ToastDescriptor = { ...descriptor, id };
this.current = full;
if (
full.durationMs !== null &&
full.durationMs !== undefined &&
full.durationMs > 0
) {
const duration = full.durationMs;
this.timer = setTimeout(() => {
this.dismiss(id);
}, duration);
}
return id;
}
/**
* dismiss clears the active toast. With an id, the call is a
* no-op when the active toast has a different id — this guards
* the auto-dismiss timer from clobbering a newer descriptor.
*/
dismiss(id?: string): void {
if (
id !== undefined &&
(this.current === null || this.current.id !== id)
) {
return;
}
this.clearTimer();
this.current = null;
}
/**
* resetForTests forgets every in-flight descriptor and the id
* counter. Production code never calls this.
*/
resetForTests(): void {
this.clearTimer();
this.current = null;
this.counter = 0;
}
private clearTimer(): void {
if (this.timer !== null) {
clearTimeout(this.timer);
this.timer = null;
}
}
}
export const toast = new ToastStore();