1
0
Fork 0

feat(minigames): superuser developer console dock across all ten games

Adds a shared fixed-position debugging dock (Controls/State/Log tabs) gated
to dynamic superusers, mounted per minigame. Multiplayer games gain synced
server-authoritative admin commands with [dev-admin] audit logging: poker
(force fold, force street, per-viewer reveal-all, clock control, stack
adjust, force expire), blackjack (bankroll adjust, next-card injection,
dealer override, force expire), bomperator (pure applyAdminCommand: crates,
pickups, eliminate, freeze, sudden death, timer, end round; mirrored over
the arena REST path), and CFF Versus (reveal fleets, force shot outcome,
skip turn). Solo games get client-side tuning via persisted dev settings:
flappy physics sliders plus pause and invincibility, EOD layout reveal and
seeded boards, radio transcript view and timer freeze, aim trainer seed and
difficulty overrides plus hitbox overlay, OPORD answer reveal and study
window, call-for-fire target reveal, seeded grids, and free corrections.

Includes 26 new integration specs (command purity, gating, audit lines) and
a poker e2e smoke for the dock. Plan: Minigame Developer Console.
This commit is contained in:
Jason Fraley 2026-10-20 12:48:27 -04:00
parent 99d4982979
commit 3c774279aa
67 changed files with 5304 additions and 426 deletions

View file

@ -7,17 +7,21 @@
import config from "@payload-config";
import { getPayload } from "payload";
import type { BlackjackActionKind } from "@/lib/minigames/blackjack/types";
import type { Payload } from "payload";
import type { BlackjackActionKind, Card } from "@/lib/minigames/blackjack/types";
import { isSuperuser } from "@/utils/access-control/hasPermission";
import {
adjustBankroll,
applyBlackjackAction,
createTable,
forceExpireTable,
getSnapshotFor,
injectNextCard,
joinTableWithBuyIn,
leaveTableWithBuyIn,
listSummaries,
renameTable,
setDealerHand,
spectateTable,
startGameWithBuyIn,
type BlackjackSnapshot,
@ -69,6 +73,13 @@ function userName(user: UserLike): string {
return `Player ${user.id}`;
}
/** Audit line for every multiplayer admin action taken from the dev console. */
function auditDevAction(payload: Payload, userId: number, action: string, target: string): void {
payload.logger.info(
`[dev-admin] user=${userId} game=blackjack action=${action} target=${target}`,
);
}
export async function createBlackjackTable(): Promise<ActionResult<{ tableId: string }>> {
try {
const { user } = await authenticate();
@ -95,6 +106,7 @@ export async function forceExpireBlackjackTable(tableId: string): Promise<Action
if (!allowed) {
return { success: false, error: "Only administrators can force-end tables." };
}
auditDevAction(payload, Number(user.id), "force-expire-table", tableId);
forceExpireTable(tableId, payload);
return { success: true };
} catch (error) {
@ -180,3 +192,62 @@ export async function blackjackAction(
return toError(error);
}
}
/* ------------------------------------------------------------- dev console */
export type BlackjackCardInput = Card;
export async function adjustBlackjackBankroll(
tableId: string,
seatId: number,
delta: number,
): Promise<ActionResult<BlackjackSnapshot>> {
try {
const { payload, user } = await authenticate();
const allowed = await isSuperuser(payload, user);
if (!allowed) {
return { success: false, error: "Only administrators can use dev controls." };
}
const snapshot = adjustBankroll(tableId, Number(user.id), seatId, delta);
auditDevAction(payload, Number(user.id), "adjust-bankroll", `${tableId}/seat-${seatId}`);
return { success: true, data: snapshot };
} catch (error) {
return toError(error);
}
}
export async function forceBlackjackNextCard(
tableId: string,
card: Card,
): Promise<ActionResult<BlackjackSnapshot>> {
try {
const { payload, user } = await authenticate();
const allowed = await isSuperuser(payload, user);
if (!allowed) {
return { success: false, error: "Only administrators can use dev controls." };
}
const snapshot = injectNextCard(tableId, Number(user.id), card);
auditDevAction(payload, Number(user.id), "force-next-card", tableId);
return { success: true, data: snapshot };
} catch (error) {
return toError(error);
}
}
export async function setBlackjackDealerHand(
tableId: string,
cards: Card[],
): Promise<ActionResult<BlackjackSnapshot>> {
try {
const { payload, user } = await authenticate();
const allowed = await isSuperuser(payload, user);
if (!allowed) {
return { success: false, error: "Only administrators can use dev controls." };
}
const snapshot = setDealerHand(tableId, Number(user.id), cards);
auditDevAction(payload, Number(user.id), "set-dealer-hand", tableId);
return { success: true, data: snapshot };
} catch (error) {
return toError(error);
}
}

View file

@ -17,14 +17,17 @@
import config from "@payload-config";
import { getPayload } from "payload";
import type { Payload } from "payload";
import { SignJWT } from "jose";
import { isSuperuser } from "@/utils/access-control/hasPermission";
import type {
BomperatorAdminCommand,
BomperatorMatchSummary,
BomperatorView,
} from "@/lib/minigames/bomperator/types";
import type { BomperatorInput } from "@/lib/minigames/bomperator/engine";
import {
applyAdminCommandFor,
createMatch,
endMatch,
forceExpireMatch,
@ -36,7 +39,7 @@ import {
submitInput,
} from "@/lib/minigames/bomperator/registry";
export type { BomperatorMatchSummary, BomperatorView, BomperatorInput };
export type { BomperatorAdminCommand, BomperatorMatchSummary, BomperatorView, BomperatorInput };
interface ActionResult<T = undefined> {
success: boolean;
@ -81,6 +84,48 @@ function userName(user: UserLike): string {
return `Operator ${user.id}`;
}
/** Audit line for every multiplayer admin action taken from the dev console. */
function auditDevAction(payload: Payload, userId: number, action: string, target: string): void {
payload.logger.info(
`[dev-admin] user=${userId} game=bomperator action=${action} target=${target}`,
);
}
const ADMIN_COMMAND_KINDS = new Set([
"destroyCrates",
"grantPickup",
"eliminate",
"freeze",
"suddenDeathNow",
"setRoundTimer",
"endRound",
]);
/** Reject anything that is not a known command shape before it reaches the engine. */
function isValidAdminCommand(cmd: unknown): cmd is BomperatorAdminCommand {
if (typeof cmd !== "object" || cmd === null) return false;
const kind = (cmd as { kind?: unknown }).kind;
if (typeof kind !== "string" || !ADMIN_COMMAND_KINDS.has(kind)) return false;
const record = cmd as Record<string, unknown>;
switch (kind) {
case "grantPickup":
return (
typeof record.seat === "number" &&
["bomb", "range", "speed", "kick"].includes(String(record.pickup))
);
case "eliminate":
return typeof record.seat === "number";
case "freeze":
return typeof record.frozen === "boolean";
case "setRoundTimer":
return typeof record.ticks === "number" && Number.isFinite(record.ticks);
case "endRound":
return record.winnerSeat === null || typeof record.winnerSeat === "number";
default:
return true;
}
}
/* ------------------------------------------------------------------ arena */
/** Internal (server-reachable) base URL of the arena process. */
@ -288,6 +333,7 @@ export async function forceExpireBomperatorMatch(
if (!allowed) {
return { success: false, error: "Only administrators can force-end matches." };
}
auditDevAction(payload, Number(user.id), "force-expire-match", matchId);
if (ARENA_ENABLED) {
await arenaCall("POST", "/matches/force-expire", { matchId });
return { success: true };
@ -298,3 +344,33 @@ export async function forceExpireBomperatorMatch(
return toError(error);
}
}
/**
* Dev-console admin command for a live Ordnance Disposal match. Superuser-only;
* the command is validated against the known set before it reaches either
* transport (arena REST proxy or in-process registry). Cheats ride the normal
* snapshot fan-out, so every client sees them by next tick.
*/
export async function bomperatorAdminCommand(
matchId: string,
cmd: BomperatorAdminCommand,
): Promise<ActionResult<undefined>> {
try {
const { payload, user } = await authenticate();
const allowed = await isSuperuser(payload, user);
if (!allowed) {
return { success: false, error: "Only administrators can use dev controls." };
}
if (!isValidAdminCommand(cmd)) {
return { success: false, error: "Invalid admin command." };
}
auditDevAction(payload, Number(user.id), `cmd:${cmd.kind}`, matchId);
if (ARENA_ENABLED) {
return await arenaCall("POST", "/matches/admin", { matchId, cmd });
}
applyAdminCommandFor(matchId, cmd);
return { success: true };
} catch (error) {
return toError(error);
}
}

View file

@ -7,6 +7,7 @@ import { Bomb } from "lucide-react";
import { MinigameComingSoon } from "@/components/frontend/minigames/MinigameComingSoon";
import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBanner";
import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry";
import { isSuperuser } from "@/utils/access-control/hasPermission";
import { BomperatorArena } from "@/components/frontend/minigames/bomperator/BomperatorArena";
export const metadata: Metadata = {
@ -35,6 +36,8 @@ export default async function BomperatorPage({ searchParams }: BomperatorPagePro
return <MinigameComingSoon game={release.game} />;
}
const superuser = await isSuperuser(payload, user);
const profileRes = await payload.find({
collection: "profiles",
where: { user: { equals: Number(user.id) } },
@ -81,6 +84,7 @@ export default async function BomperatorPage({ searchParams }: BomperatorPagePro
initialStats={stats}
currentUserId={Number(user.id)}
initialMatchId={initialMatchId}
isSuperuser={superuser}
/>
</div>
);

View file

@ -8,14 +8,17 @@
import config from "@payload-config";
import { getPayload } from "payload";
import type { Payload } from "payload";
import { isSuperuser } from "@/utils/access-control/hasPermission";
import type {
VersusAdminCommand,
VersusMatchSummary,
VersusMatchView,
} from "@/lib/minigames/call-for-fire-versus/types";
import type { FobPlacement } from "@/lib/minigames/call-for-fire-versus/constants";
import type { VersusShotInput } from "@/lib/minigames/call-for-fire-versus/engine";
import {
applyAdminCommandFor,
createMatch,
fireShotFor,
forceExpireMatch,
@ -26,7 +29,7 @@ import {
placeFleetFor,
} from "@/lib/minigames/call-for-fire-versus/registry";
export type { VersusMatchSummary, VersusMatchView, VersusShotInput, FobPlacement };
export type { VersusAdminCommand, VersusMatchSummary, VersusMatchView, VersusShotInput, FobPlacement };
interface ActionResult<T = undefined> {
success: boolean;
@ -71,6 +74,31 @@ function userName(user: UserLike): string {
return `Operator ${user.id}`;
}
/** Audit line for every multiplayer admin action taken from the dev console. */
function auditDevAction(payload: Payload, userId: number, action: string, target: string): void {
payload.logger.info(
`[dev-admin] user=${userId} game=cff-versus action=${action} target=${target}`,
);
}
/** Reject anything that is not a known command shape before it reaches the engine. */
function isValidAdminCommand(cmd: unknown): cmd is VersusAdminCommand {
if (typeof cmd !== "object" || cmd === null) return false;
const record = cmd as Record<string, unknown>;
switch (record.kind) {
case "revealFleets":
return typeof record.on === "boolean";
case "forceShotResult":
return (
record.outcome === null || record.outcome === "hit" || record.outcome === "miss"
);
case "skipTurn":
return true;
default:
return false;
}
}
export async function createVersusMatch(): Promise<ActionResult<{ matchId: string }>> {
try {
const { user } = await authenticate();
@ -149,9 +177,36 @@ export async function forceExpireVersusMatch(matchId: string): Promise<ActionRes
if (!allowed) {
return { success: false, error: "Only administrators can force-end matches." };
}
auditDevAction(payload, Number(user.id), "force-expire-match", matchId);
forceExpireMatch(matchId);
return { success: true };
} catch (error) {
return toError(error);
}
}
/**
* Dev-console admin command for a live versus match (reveal fleets, force the
* next shot result, skip a turn). Superuser-only; commands are validated
* against the known set before they reach the registry.
*/
export async function versusAdminCommand(
matchId: string,
cmd: VersusAdminCommand,
): Promise<ActionResult<undefined>> {
try {
const { payload, user } = await authenticate();
const allowed = await isSuperuser(payload, user);
if (!allowed) {
return { success: false, error: "Only administrators can use dev controls." };
}
if (!isValidAdminCommand(cmd)) {
return { success: false, error: "Invalid admin command." };
}
auditDevAction(payload, Number(user.id), `cmd:${cmd.kind}`, matchId);
applyAdminCommandFor(matchId, cmd);
return { success: true };
} catch (error) {
return toError(error);
}
}

View file

@ -7,6 +7,7 @@ import { Swords } from "lucide-react";
import { MinigameComingSoon } from "@/components/frontend/minigames/MinigameComingSoon";
import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBanner";
import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry";
import { isSuperuser } from "@/utils/access-control/hasPermission";
import { CallForFireVersusArena } from "@/components/frontend/minigames/call-for-fire-versus/CallForFireVersusArena";
export const metadata: Metadata = {
@ -35,6 +36,8 @@ export default async function CallForFireVersusPage({ searchParams }: VersusPage
return <MinigameComingSoon game={release.game} />;
}
const superuser = await isSuperuser(payload, user);
const profileRes = await payload.find({
collection: "profiles",
where: { user: { equals: Number(user.id) } },
@ -81,6 +84,7 @@ export default async function CallForFireVersusPage({ searchParams }: VersusPage
initialStats={stats}
currentUserId={Number(user.id)}
initialMatchId={initialMatchId}
isSuperuser={superuser}
/>
</div>
);

View file

@ -7,6 +7,7 @@ import { Target } from "lucide-react";
import { CallForFireArena } from "@/components/frontend/minigames/call-for-fire/CallForFireArena";
import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBanner";
import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry";
import { isSuperuser } from "@/utils/access-control/hasPermission";
export const metadata: Metadata = {
title: "Call for Fire (Polaris Task Force)",
@ -23,6 +24,8 @@ export default async function CallForFirePage() {
redirect(`/login?returnTo=${encodeURIComponent("/minigames/call-for-fire")}`);
}
const superuser = await isSuperuser(payload, user);
const release = await getMinigameReleaseState(payload, "callForFire");
const profileRes = await payload.find({
@ -66,7 +69,11 @@ export default async function CallForFirePage() {
</p>
</div>
<CallForFireArena initialStats={stats} currentUserId={user.id as number} />
<CallForFireArena
initialStats={stats}
currentUserId={user.id as number}
isSuperuser={superuser}
/>
</div>
);
}

View file

@ -6,6 +6,7 @@ import { redirect } from "next/navigation";
import { MinigameComingSoon } from "@/components/frontend/minigames/MinigameComingSoon";
import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBanner";
import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry";
import { isSuperuser } from "@/utils/access-control/hasPermission";
import { Bomb } from "lucide-react";
import { EodArena } from "@/components/frontend/minigames/eod/EodArena";
@ -29,6 +30,8 @@ export default async function EodPage() {
return <MinigameComingSoon game={release.game} />;
}
const superuser = await isSuperuser(payload, user);
const profileRes = await payload.find({
collection: "profiles",
where: { user: { equals: user.id as number } },
@ -70,7 +73,7 @@ export default async function EodPage() {
</p>
</div>
<EodArena initialStats={stats} currentUserId={user.id as number} />
<EodArena initialStats={stats} currentUserId={user.id as number} isSuperuser={superuser} />
</div>
);
}

View file

@ -8,6 +8,7 @@ import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBann
import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry";
import { Bird } from "lucide-react";
import { FlappyArena } from "@/components/frontend/minigames/flappy/FlappyArena";
import { isSuperuser } from "@/utils/access-control/hasPermission";
export const metadata: Metadata = {
title: "Flight Simulator: Polaris Task Force",
@ -29,6 +30,8 @@ export default async function FlappyPage() {
return <MinigameComingSoon game={release.game} />;
}
const superuser = await isSuperuser(payload, user);
const profileRes = await payload.find({
collection: "profiles",
where: { user: { equals: user.id as number } },
@ -63,12 +66,11 @@ export default async function FlappyPage() {
<h1 className="text-lg font-semibold">Flight Simulator</h1>
</div>
<p className="text-sm text-muted-foreground">
An unofficial side activity. Earn 1 XP per 15 obstacles
passed in a single run.
An unofficial side activity. Earn 1 XP per 15 obstacles passed in a single run.
</p>
</div>
<FlappyArena initialStats={stats} currentUserId={user.id as number} />
<FlappyArena initialStats={stats} currentUserId={user.id as number} isSuperuser={superuser} />
</div>
);
}

View file

@ -6,6 +6,7 @@ import { redirect } from "next/navigation";
import { MinigameComingSoon } from "@/components/frontend/minigames/MinigameComingSoon";
import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBanner";
import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry";
import { isSuperuser } from "@/utils/access-control/hasPermission";
import { ScrollText } from "lucide-react";
import { OpordArena } from "@/components/frontend/minigames/opord/OpordArena";
@ -24,6 +25,8 @@ export default async function OpordPage() {
redirect(`/login?returnTo=${encodeURIComponent("/minigames/opord")}`);
}
const superuser = await isSuperuser(payload, user);
const release = await getMinigameReleaseState(payload, "opord");
if (release.upcoming && release.game) {
return <MinigameComingSoon game={release.game} />;
@ -71,7 +74,11 @@ export default async function OpordPage() {
</p>
</div>
<OpordArena initialStats={stats} currentUserId={user.id as number} />
<OpordArena
initialStats={stats}
currentUserId={user.id as number}
isSuperuser={superuser}
/>
</div>
);
}

View file

@ -8,16 +8,21 @@
import config from "@payload-config";
import { getPayload } from "payload";
import type { Payload } from "payload";
import type { Card, PokerActionKind, PrivatePlayerView } from "@/lib/minigames/poker/types";
import { isSuperuser } from "@/utils/access-control/hasPermission";
import {
adjustStack,
applyPlayerAction,
clockControl,
createTable,
forceExpireTable,
forceFold,
forceStreet,
getSnapshotFor,
joinTableWithBuyIn,
leaveTableWithBuyIn,
setRevealAll,
spectateTable,
listSummaries,
renameTable,
@ -74,6 +79,15 @@ function userName(user: UserLike): string {
return `Player ${user.id}`;
}
/**
* Audit line for every multiplayer admin action taken from the dev console.
* Deliberately a logger line, not a game event: these are operator tooling
* traces, not player-facing history (dev console plan decision).
*/
function auditDevAction(payload: Payload, userId: number, action: string, target: string): void {
payload.logger.info(`[dev-admin] user=${userId} game=poker action=${action} target=${target}`);
}
export async function createPokerTable(): Promise<ActionResult<{ tableId: string }>> {
try {
const { user } = await authenticate();
@ -100,6 +114,7 @@ export async function forceExpirePokerTable(tableId: string): Promise<ActionResu
if (!allowed) {
return { success: false, error: "Only administrators can force-end tables." };
}
auditDevAction(payload, Number(user.id), "force-expire-table", tableId);
forceExpireTable(tableId, payload);
return { success: true };
} catch (error) {
@ -138,6 +153,7 @@ export async function setPokerBoardQueue(
return { success: false, error: "Only administrators can use dev controls." };
}
const snapshot = setBoardQueue(tableId, Number(user.id), cards);
auditDevAction(payload, Number(user.id), "set-board-queue", tableId);
return { success: true, data: snapshot };
} catch (error) {
return toError(error);
@ -156,6 +172,7 @@ export async function setPokerHoleQueue(
return { success: false, error: "Only administrators can use dev controls." };
}
const snapshot = setHoleQueue(tableId, Number(user.id), seatId, cards);
auditDevAction(payload, Number(user.id), "set-hole-queue", `${tableId}/seat-${seatId}`);
return { success: true, data: snapshot };
} catch (error) {
return toError(error);
@ -174,6 +191,76 @@ export async function adjustPokerStack(
return { success: false, error: "Only administrators can use dev controls." };
}
const snapshot = adjustStack(tableId, Number(user.id), seatId, delta);
auditDevAction(payload, Number(user.id), "adjust-stack", `${tableId}/seat-${seatId}`);
return { success: true, data: snapshot };
} catch (error) {
return toError(error);
}
}
export async function forceFoldPokerPlayer(
tableId: string,
seatId: number,
): Promise<ActionResult<PokerSnapshot>> {
try {
const { payload, user } = await authenticate();
const allowed = await isSuperuser(payload, user);
if (!allowed) {
return { success: false, error: "Only administrators can use dev controls." };
}
const snapshot = forceFold(tableId, Number(user.id), seatId);
auditDevAction(payload, Number(user.id), "force-fold", `${tableId}/seat-${seatId}`);
return { success: true, data: snapshot };
} catch (error) {
return toError(error);
}
}
export async function forcePokerStreet(tableId: string): Promise<ActionResult<PokerSnapshot>> {
try {
const { payload, user } = await authenticate();
const allowed = await isSuperuser(payload, user);
if (!allowed) {
return { success: false, error: "Only administrators can use dev controls." };
}
const snapshot = forceStreet(tableId, Number(user.id));
auditDevAction(payload, Number(user.id), "force-street", tableId);
return { success: true, data: snapshot };
} catch (error) {
return toError(error);
}
}
export async function setPokerRevealAll(
tableId: string,
enabled: boolean,
): Promise<ActionResult<PokerSnapshot>> {
try {
const { payload, user } = await authenticate();
const allowed = await isSuperuser(payload, user);
if (!allowed) {
return { success: false, error: "Only administrators can use dev controls." };
}
const snapshot = setRevealAll(tableId, Number(user.id), enabled);
auditDevAction(payload, Number(user.id), enabled ? "reveal-on" : "reveal-off", tableId);
return { success: true, data: snapshot };
} catch (error) {
return toError(error);
}
}
export async function pokerClockControl(
tableId: string,
mode: "reset" | "now",
): Promise<ActionResult<PokerSnapshot>> {
try {
const { payload, user } = await authenticate();
const allowed = await isSuperuser(payload, user);
if (!allowed) {
return { success: false, error: "Only administrators can use dev controls." };
}
const snapshot = clockControl(tableId, Number(user.id), mode);
auditDevAction(payload, Number(user.id), `clock-${mode}`, tableId);
return { success: true, data: snapshot };
} catch (error) {
return toError(error);

View file

@ -6,6 +6,7 @@ import { redirect } from "next/navigation";
import { MinigameComingSoon } from "@/components/frontend/minigames/MinigameComingSoon";
import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBanner";
import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry";
import { isSuperuser } from "@/utils/access-control/hasPermission";
import { Crosshair } from "lucide-react";
import type { AimTrainerStats } from "@/app/(frontend)/minigames/qualification/actions";
@ -26,6 +27,8 @@ export default async function QualificationPage() {
redirect(`/login?returnTo=${encodeURIComponent("/minigames/qualification")}`);
}
const superuser = await isSuperuser(payload, user);
const release = await getMinigameReleaseState(payload, "qualification");
if (release.upcoming && release.game) {
return <MinigameComingSoon game={release.game} />;
@ -75,7 +78,7 @@ export default async function QualificationPage() {
</p>
</div>
<AimTrainerArena initialStats={stats} currentUserId={user.id} />
<AimTrainerArena initialStats={stats} currentUserId={user.id} isSuperuser={superuser} />
</div>
);
}

View file

@ -6,6 +6,7 @@ import { redirect } from "next/navigation";
import { MinigameComingSoon } from "@/components/frontend/minigames/MinigameComingSoon";
import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBanner";
import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry";
import { isSuperuser } from "@/utils/access-control/hasPermission";
import { Radio } from "lucide-react";
import { RadioArena } from "@/components/frontend/minigames/radio/RadioArena";
@ -24,6 +25,8 @@ export default async function RadioPage() {
redirect(`/login?returnTo=${encodeURIComponent("/minigames/radio")}`);
}
const superuser = await isSuperuser(payload, user);
const release = await getMinigameReleaseState(payload, "radio");
if (release.upcoming && release.game) {
return <MinigameComingSoon game={release.game} />;
@ -79,7 +82,11 @@ export default async function RadioPage() {
</p>
</div>
<RadioArena initialStats={stats} currentUserId={user.id as number} />
<RadioArena
initialStats={stats}
currentUserId={user.id as number}
isSuperuser={superuser}
/>
</div>
);
}

View file

@ -33,6 +33,7 @@ import {
TICK_MS,
} from "@/lib/minigames/bomperator/constants";
import {
applyAdminCommand,
applyInput,
createMatchState,
dissolveMatch,
@ -41,7 +42,12 @@ import {
tick as engineTick,
type BomperatorInput,
} from "@/lib/minigames/bomperator/engine";
import type { BomperatorMatchSummary, BomperatorState, BomperatorView } from "@/lib/minigames/bomperator/types";
import type {
BomperatorAdminCommand,
BomperatorMatchSummary,
BomperatorState,
BomperatorView,
} from "@/lib/minigames/bomperator/types";
import { buildBomperatorView } from "@/lib/minigames/bomperator/views";
import type { ServerMessage } from "../protocol";
import type { RealtimeGameModule } from "./types";
@ -568,6 +574,24 @@ export class BomperatorGameModule implements RealtimeGameModule {
this.disposeMatch(record);
}
/**
* Dev-console command entry point (WS transport). Mirrors the registry's
* applyAdminCommandFor exactly: pure command application, version bump,
* snapshot fan-out over sockets, immediate completion handling.
*/
adminCommand(matchId: string, cmd: BomperatorAdminCommand): void {
const record = this.matches.get(matchId);
if (!record) throw new Error("Match not found.");
record.state = applyAdminCommand(record.state, cmd);
record.version += 1;
record.lastActivityAt = Date.now();
this.pushSnapshots(record);
if (record.state.phase === "complete") {
this.stopTickLoop(record);
this.awardCompleted(record);
}
}
listSummaries(viewerId?: number): BomperatorMatchSummary[] {
return [...this.matches.values()].map((record) => ({
matchId: record.id,

View file

@ -248,6 +248,17 @@ export async function startArena(options: ArenaOptions = {}): Promise<ArenaHandl
await run(() => game.forceExpire(str("matchId")));
return;
}
if (url.pathname === "/matches/admin" && req.method === "POST") {
// Dev-console commands (superuser-gated in the Next action that proxies
// here; this endpoint shares the same x-arena-secret trust as the rest).
const cmd = body.cmd as { kind?: unknown } | undefined;
if (!cmd || typeof cmd.kind !== "string") {
sendJson(res, 200, { success: false, error: "Invalid admin command." });
return;
}
await run(() => game.adminCommand(str("matchId"), cmd as never));
return;
}
sendJson(res, 404, { success: false, error: "Not found." });
}

View file

@ -14,6 +14,8 @@ import type { BlackjackPhase } from "@/lib/minigames/blackjack";
import { useRealtimePresence } from "@/hooks/useRealtimePresence";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { ChipBankCard } from "@/components/frontend/minigames/ChipBankCard";
import { BlackjackDevControls } from "@/components/frontend/minigames/dev/BlackjackDevControls";
import { MinigameDevDock } from "@/components/frontend/minigames/dev/MinigameDevDock";
import { BlackjackGuide } from "./BlackjackGuide";
import {
BLACKJACK_STATE_EVENT,
@ -332,6 +334,19 @@ export function BlackjackArena({
</div>
<ChipBankCard initialChipBank={initialChipBank} initialChipTopUpAt={initialChipTopUpAt} />
{view === "table" && snapshot && (
<MinigameDevDock
isSuperuser={isSuperuser}
gameKey="blackjack"
gameLabel="Blackjack"
snapshot={snapshot}
>
{snapshot.you && (
<BlackjackDevControls tableId={snapshot.tableId} view={snapshot.you} />
)}
</MinigameDevDock>
)}
</div>
);
}

View file

@ -11,6 +11,8 @@ import {
import { toast } from "sonner";
import { useRealtimePresence } from "@/hooks/useRealtimePresence";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { BomperatorDevControls } from "@/components/frontend/minigames/dev/BomperatorDevControls";
import { MinigameDevDock } from "@/components/frontend/minigames/dev/MinigameDevDock";
import { BomperatorLobby } from "./BomperatorLobby";
import { BomperatorGame } from "./BomperatorGame";
import {
@ -41,10 +43,12 @@ export function BomperatorArena({
initialStats,
currentUserId,
initialMatchId,
isSuperuser = false,
}: {
initialStats: BomperatorStats;
currentUserId: number | string;
initialMatchId?: string;
isSuperuser?: boolean;
}) {
const [view, setView] = useState<ArenaView>(initialMatchId ? "match" : "lobby");
const [match, setMatch] = useState<BomperatorView | null>(null);
@ -246,6 +250,17 @@ export function BomperatorArena({
) : (
<p className="text-sm text-muted-foreground">Loading match…</p>
)}
{view === "match" && match && (
<MinigameDevDock
isSuperuser={isSuperuser}
gameKey="bomperator"
gameLabel="Ordnance Disposal"
snapshot={match}
>
<BomperatorDevControls matchId={match.matchId} match={match} />
</MinigameDevDock>
)}
</div>
);
}

View file

@ -8,6 +8,8 @@ import {
} from "@/app/(frontend)/minigames/call-for-fire-versus/actions";
import { useRealtimePresence } from "@/hooks/useRealtimePresence";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { MinigameDevDock } from "@/components/frontend/minigames/dev/MinigameDevDock";
import { VersusDevControls } from "@/components/frontend/minigames/dev/VersusDevControls";
import { VersusLobby } from "./VersusLobby";
import { VersusMatch } from "./VersusMatch";
@ -33,10 +35,12 @@ export function CallForFireVersusArena({
initialStats,
currentUserId,
initialMatchId,
isSuperuser = false,
}: {
initialStats: VersusStats;
currentUserId: number | string;
initialMatchId?: string;
isSuperuser?: boolean;
}) {
const [view, setView] = useState<ArenaView>(initialMatchId ? "match" : "lobby");
const [match, setMatch] = useState<VersusMatchView | null>(null);
@ -164,6 +168,17 @@ export function CallForFireVersusArena({
) : (
<p className="text-sm text-muted-foreground">Loading match…</p>
)}
{view === "match" && match && (
<MinigameDevDock
isSuperuser={isSuperuser}
gameKey="cff-versus"
gameLabel="CFF Versus"
snapshot={match}
>
<VersusDevControls matchId={match.matchId} match={match} />
</MinigameDevDock>
)}
</div>
);
}

View file

@ -9,19 +9,24 @@ import { useRealtimePresence } from "@/hooks/useRealtimePresence";
import { useSidebar } from "@/components/ui/sidebar";
import { AllTimeLeaderboard } from "@/components/frontend/minigames/AllTimeLeaderboard";
import { PeriodStandingsCard } from "@/components/frontend/minigames/PeriodStandingsCard";
import { CallForFireDevControls } from "@/components/frontend/minigames/dev/CallForFireDevControls";
import { MinigameDevDock } from "@/components/frontend/minigames/dev/MinigameDevDock";
import { CallForFireLeaderboard } from "./CallForFireLeaderboard";
import { FireMissionBoard } from "./FireMissionBoard";
import { FireMissionBoard, type CallForFireDevSnapshot } from "./FireMissionBoard";
export function CallForFireArena({
initialStats,
currentUserId,
isSuperuser = false,
}: {
initialStats: CallForFireStats;
currentUserId: number | string;
isSuperuser?: boolean;
}) {
const [refreshKey, setRefreshKey] = useState(0);
const [playing, setPlaying] = useState(false);
const [selectedDifficulty, setSelectedDifficulty] = useState<CallForFireDifficulty>("patrol");
const [missionSnapshot, setMissionSnapshot] = useState<CallForFireDevSnapshot | null>(null);
const { isMobile, setOpenMobile } = useSidebar();
const activeTeams = useRealtimePresence("callForFire", playing, true);
const onPhaseChange = useCallback((phase: "ready" | "playing" | "over") => {
@ -39,6 +44,8 @@ export function CallForFireArena({
onGameRecorded={() => setRefreshKey((key) => key + 1)}
onPhaseChange={onPhaseChange}
onDifficultyChange={setSelectedDifficulty}
isSuperuser={isSuperuser}
onDevSnapshotChange={setMissionSnapshot}
/>
<PeriodStandingsCard
gameKey="callForFire"
@ -57,6 +64,19 @@ export function CallForFireArena({
onDifficultyChange={setSelectedDifficulty}
/>
</AllTimeLeaderboard>
<MinigameDevDock
isSuperuser={isSuperuser}
gameKey="call-for-fire"
gameLabel="Call for Fire"
snapshot={
missionSnapshot ?? {
phase: "ready",
difficulty: selectedDifficulty,
}
}
>
<CallForFireDevControls />
</MinigameDevDock>
</div>
);
}

View file

@ -1,6 +1,6 @@
"use client";
import { useCallback, useEffect, useRef, useState, type CSSProperties } from "react";
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties } from "react";
import { Crosshair, Radio, RotateCcw, Target, Timer } from "lucide-react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
@ -26,6 +26,11 @@ import {
import { PROFILE_UPDATE_EVENT } from "@/hooks/useGameTick";
import { useSessionExpired } from "@/hooks/useSessionExpired";
import { LoginLink } from "@/components/frontend/auth/LoginLink";
import {
CALL_FOR_FIRE_DEV_GAME_KEY,
CALL_FOR_FIRE_DEV_SETTINGS_EVENT,
} from "@/components/frontend/minigames/dev/CallForFireDevControls";
import { readDevSetting } from "@/components/frontend/minigames/dev/devSettings";
import { cn } from "@/lib/utils";
type Phase = "ready" | "playing" | "over";
@ -51,6 +56,49 @@ type Impact = {
const DIFFICULTY_KEYS: readonly CallForFireDifficulty[] = ["patrol", "checkpoint", "compound"];
const CORRECTION_STEP = 50;
/** Observer net keeps the last six transmissions unless dev free corrections is on. */
const RADIO_LOG_LIMIT = 6;
/** Plain, cheap summary of the live run served to the developer dock's State tab. */
export interface CallForFireDevSnapshot {
readonly phase: Phase;
readonly difficulty: CallForFireDifficulty;
readonly gridSize: number;
readonly lethalRadiusM: number;
readonly roundsUsed: number;
readonly roundsLeft: number;
readonly correctionsFired: number;
readonly secondsLeft: number;
readonly lastImpact: (GridPoint & { readonly grid: string }) | null;
readonly target: (GridPoint & { readonly grid: string }) | null;
readonly dev: {
readonly showTarget: boolean;
readonly freeCorrections: boolean;
readonly seed: number | null;
};
}
/**
* Deterministic PRNG (mulberry32) used only when a developer seed is set.
* Without a seed, mission generation keeps calling Math.random(), so normal
* play is byte-for-byte the same behavior as before.
*/
function mulberry32(seed: number): () => number {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;
let value = state;
value = Math.imul(value ^ (value >>> 15), value | 1);
value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
return ((value ^ (value >>> 14)) >>> 0) / 4_294_967_296;
};
}
function readDevSeed(): number | null {
const stored = readDevSetting<number | null>(CALL_FOR_FIRE_DEV_GAME_KEY, "seed", null);
return typeof stored === "number" && Number.isFinite(stored) ? Math.trunc(stored) : null;
}
function formatClock(totalSeconds: number): string {
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
@ -62,11 +110,15 @@ export function FireMissionBoard({
onGameRecorded,
onPhaseChange,
onDifficultyChange,
isSuperuser = false,
onDevSnapshotChange,
}: {
initialStats: CallForFireStats;
onGameRecorded: () => void;
onPhaseChange: (phase: Phase) => void;
onDifficultyChange: (difficulty: CallForFireDifficulty) => void;
isSuperuser?: boolean;
onDevSnapshotChange: (snapshot: CallForFireDevSnapshot) => void;
}) {
const router = useRouter();
const { expired, expiredRef } = useSessionExpired();
@ -86,6 +138,10 @@ export function FireMissionBoard({
const submittingRef = useRef(false);
const statsRef = useRef<CallForFireStats>(serverStats);
const secondsLeftRef = useRef(0);
const [devShowTarget, setDevShowTarget] = useState(false);
const [devFreeCorrections, setDevFreeCorrections] = useState(false);
const [devSeed, setDevSeed] = useState<number | null>(null);
const devSeedRef = useRef<number | null>(null);
const config = CALL_FOR_FIRE_DIFFICULTIES[difficulty];
const roundsLeft = config.maxRounds - roundsUsed;
@ -103,6 +159,31 @@ export function FireMissionBoard({
onPhaseChange("ready");
}, [onPhaseChange]);
// Dev dock settings live in localStorage and are broadcast on a window event,
// so toggling them in the dock updates this board without prop plumbing. They
// only affect local rendering (target overlay, observer net history, client
// round cap) and the RNG at mission generation, never the submitted payload.
useEffect(() => {
if (!isSuperuser) {
setDevShowTarget(false);
setDevFreeCorrections(false);
setDevSeed(null);
devSeedRef.current = null;
return;
}
const sync = () => {
setDevShowTarget(readDevSetting(CALL_FOR_FIRE_DEV_GAME_KEY, "showTarget", false));
setDevFreeCorrections(readDevSetting(CALL_FOR_FIRE_DEV_GAME_KEY, "freeCorrections", false));
const nextSeed = readDevSeed();
if (devSeedRef.current === nextSeed) return;
devSeedRef.current = nextSeed;
setDevSeed(nextSeed);
};
sync();
window.addEventListener(CALL_FOR_FIRE_DEV_SETTINGS_EVENT, sync);
return () => window.removeEventListener(CALL_FOR_FIRE_DEV_SETTINGS_EVENT, sync);
}, [isSuperuser]);
const reset = useCallback(
(nextDifficulty: CallForFireDifficulty = difficulty) => {
if (submittingRef.current) return;
@ -218,12 +299,11 @@ export function FireMissionBoard({
const begin = useCallback(() => {
if (expiredRef.current || submittingRef.current) return;
const nextScenario = createScenario(difficulty);
const rng = devSeed === null ? Math.random : mulberry32(devSeed);
const nextScenario = createScenario(difficulty, rng);
const report = observerReport(nextScenario.target, nextScenario.spotting);
setScenario(nextScenario);
setImpacts([
{ point: nextScenario.spotting, effective: false, spotting: true },
]);
setImpacts([{ point: nextScenario.spotting, effective: false, spotting: true }]);
setLastImpact(nextScenario.spotting);
setRadioLog([
`Splash, over. Spotting round ${gridDesignation(nextScenario.spotting)}: ${report.message}`,
@ -235,7 +315,7 @@ export function FireMissionBoard({
setDeflectionM(0);
setLastRun(null);
setPhaseSafe("playing");
}, [config.maxSeconds, difficulty, expiredRef, setPhaseSafe]);
}, [config.maxSeconds, devSeed, difficulty, expiredRef, setPhaseSafe]);
const fireMission = useCallback(() => {
if (phase !== "playing" || submittingRef.current || expiredRef.current) return;
@ -244,11 +324,9 @@ export function FireMissionBoard({
const impactPoint = applyCorrection(lastImpact, { rangeM, deflectionM }, config.size);
const distance = distanceMeters(scenario.target, impactPoint);
const effective = isEffectiveHit(scenario.target, impactPoint, config.lethalRadiusM);
const nextImpacts = [
...impacts,
{ point: impactPoint, effective, spotting: false },
];
const nextImpacts = [...impacts, { point: impactPoint, effective, spotting: false }];
const nextUsed = roundsUsed + 1;
const radioLimit = devFreeCorrections ? Number.MAX_SAFE_INTEGER : RADIO_LOG_LIMIT;
setImpacts(nextImpacts);
setLastImpact(impactPoint);
setRoundsUsed(nextUsed);
@ -260,7 +338,7 @@ export function FireMissionBoard({
[
...log,
`Splash, over. Effective on grid ${gridDesignation(impactPoint)}. Target destroyed.`,
].slice(-6),
].slice(-radioLimit),
);
setPhaseSafe("over");
void recordResult(true, nextUsed, elapsedSeconds, distance);
@ -269,13 +347,10 @@ export function FireMissionBoard({
const report = observerReport(scenario.target, impactPoint);
setRadioLog((log) =>
[
...log,
`Impact grid ${gridDesignation(impactPoint)}: ${report.message}`,
].slice(-6),
[...log, `Impact grid ${gridDesignation(impactPoint)}: ${report.message}`].slice(-radioLimit),
);
if (nextUsed >= config.maxRounds) {
if (!devFreeCorrections && nextUsed >= config.maxRounds) {
setPhaseSafe("over");
void recordResult(false, nextUsed, elapsedSeconds, distance);
}
@ -283,6 +358,7 @@ export function FireMissionBoard({
config.lethalRadiusM,
config.maxRounds,
config.size,
devFreeCorrections,
elapsedSeconds,
expiredRef,
impacts,
@ -302,6 +378,48 @@ export function FireMissionBoard({
: "border-destructive/40 bg-destructive/10"
: "border-border bg-card";
// Dev dock payload: cheap plain object describing the live run. Client-only,
// and the dock renders nothing unless the page computed a superuser.
const correctionsFired = Math.max(0, roundsUsed - 1);
const devSnapshot = useMemo<CallForFireDevSnapshot>(
() => ({
phase,
difficulty,
gridSize: config.size,
lethalRadiusM: config.lethalRadiusM,
roundsUsed,
roundsLeft: Math.max(0, roundsLeft),
correctionsFired,
secondsLeft,
lastImpact: lastImpact ? { ...lastImpact, grid: gridDesignation(lastImpact) } : null,
target: scenario ? { ...scenario.target, grid: gridDesignation(scenario.target) } : null,
dev: {
showTarget: devShowTarget,
freeCorrections: devFreeCorrections,
seed: devSeed,
},
}),
[
config.lethalRadiusM,
config.size,
correctionsFired,
devFreeCorrections,
devSeed,
devShowTarget,
difficulty,
lastImpact,
phase,
roundsLeft,
roundsUsed,
scenario,
secondsLeft,
],
);
useEffect(() => {
onDevSnapshotChange(devSnapshot);
}, [devSnapshot, onDevSnapshotChange]);
return (
<div className="flex w-full max-w-5xl flex-col gap-4">
{expired && (
@ -418,7 +536,7 @@ export function FireMissionBoard({
{phase === "over" && !lastRun && <span>Recording fire mission…</span>}
{lastRun?.won && (
<span className="text-xs text-emerald-500">
Score {lastRun.score} · accuracy {Math.round(lastRun.finalDistanceM)}m · +
Score {lastRun.score} · accuracy {Math.round(lastRun.finalDistanceM)}m · +
{lastRun.xpEarned} XP earned.
</span>
)}
@ -474,7 +592,11 @@ export function FireMissionBoard({
row={row}
size={config.size}
impacts={impacts}
target={phase === "over" ? scenario?.target : undefined}
target={
phase === "over" || (isSuperuser && devShowTarget)
? scenario?.target
: undefined
}
disabled={phase !== "playing" || expired}
/>
))}
@ -521,7 +643,9 @@ export function FireMissionBoard({
Observer net
</div>
{radioLog.length === 0 ? (
<p className="text-xs text-muted-foreground">Net quiet. Awaiting your first call.</p>
<p className="text-xs text-muted-foreground">
Net quiet. Awaiting your first call.
</p>
) : (
<ul className="space-y-1 font-mono text-xs tabular-nums">
{radioLog.map((line, index) => (
@ -541,8 +665,8 @@ export function FireMissionBoard({
</div>
<p className="text-center text-xs text-muted-foreground">
Read the spotting report, correct range and deflection, and walk the rounds onto the target
before time runs out
Read the spotting report, correct range and deflection, and walk the rounds onto the
target before time runs out
</p>
</div>
@ -600,16 +724,28 @@ function ImpactRow({
key={`${row}-${column}`}
role="gridcell"
aria-label={`grid ${gridDesignation({ x: column, y: row })}${
impact ? (impact.effective ? " effective impact" : impact.spotting ? " spotting round" : " impact") : ""
isTarget ? " target location" : ""
}${
impact
? impact.effective
? " effective impact"
: impact.spotting
? " spotting round"
: " impact"
: ""
}`}
className={cn(
"flex size-[var(--cell-size)] items-center justify-center rounded-sm border text-xs font-bold transition-colors",
"border-border bg-card",
impact?.effective &&
"border-emerald-400 bg-emerald-600/80 text-emerald-50 shadow-[0_0_8px_rgb(16_185_129_/_0.6)]",
impact && !impact.effective && impact.spotting &&
impact &&
!impact.effective &&
impact.spotting &&
"border-sky-400/80 bg-sky-500/20 text-sky-200",
impact && !impact.effective && !impact.spotting &&
impact &&
!impact.effective &&
!impact.spotting &&
"border-amber-500/70 bg-amber-500/20 text-amber-200",
isTarget && "border-destructive bg-destructive/25 text-red-300",
disabled && "opacity-90",
@ -620,6 +756,8 @@ function ImpactRow({
className={cn("size-3.5", impact.spotting && "text-sky-300")}
strokeWidth={impact.spotting ? 2.5 : 2}
/>
) : isTarget ? (
<Target className="size-3.5 opacity-80" aria-hidden="true" />
) : null}
</div>
);

View file

@ -0,0 +1,183 @@
"use client";
import { useState } from "react";
import type { BlackjackSnapshot } from "@/app/(frontend)/minigames/blackjack/actions";
import {
adjustBlackjackBankroll,
forceBlackjackNextCard,
forceExpireBlackjackTable,
setBlackjackDealerHand,
} from "@/app/(frontend)/minigames/blackjack/actions";
import type { Card } from "@/lib/minigames/blackjack/types";
import { Button } from "@/components/ui/button";
import { Combobox } from "@/components/ui/combobox";
import { Input } from "@/components/ui/input";
import { cardLabel, CardPicker } from "../poker/PokerDevPanel";
import { pushDevLog } from "./devLog";
import { DevButton, DevSection } from "./primitives";
/**
* Blackjack controls for the shared minigame dev dock: bankroll adjustment
* (mirrors poker's stack adjust), forcing the next card drawn via top-of-shoe
* injection, replacing the dealer hand mid-round, and force-ending the table.
*/
interface BlackjackDevControlsProps {
readonly tableId: string;
readonly view: NonNullable<BlackjackSnapshot["you"]>;
}
export function BlackjackDevControls({ tableId, view }: BlackjackDevControlsProps) {
const [adjustSeat, setAdjustSeat] = useState<string>("");
const [adjustAmount, setAdjustAmount] = useState<string>("");
const [nextCard, setNextCard] = useState<Card | null>(null);
const [dealerA, setDealerA] = useState<Card | null>(null);
const [dealerB, setDealerB] = useState<Card | null>(null);
const [error, setError] = useState<string | null>(null);
const run = async (name: string, action: () => Promise<{ success: boolean; error?: string }>) => {
pushDevLog("action", `blackjack: ${name} sent`);
try {
const result = await action();
if (!result.success) {
const message = result.error ?? "The dev action failed.";
setError(message);
pushDevLog("error", `blackjack: ${name} failed (${message})`);
} else {
setError(null);
pushDevLog("action", `blackjack: ${name} applied`);
}
return result.success;
} catch (caught) {
const message = caught instanceof Error ? caught.message : "The dev action failed.";
setError(message);
pushDevLog("error", `blackjack: ${name} threw (${message})`);
return false;
}
};
const adjust = (sign: 1 | -1) => {
if (adjustSeat === "") return;
const amount = Number(adjustAmount);
if (!Number.isInteger(amount) || amount <= 0) {
setError("Enter a positive whole number of chips.");
return;
}
void run("adjust-bankroll", async () => {
const result = await adjustBlackjackBankroll(tableId, Number(adjustSeat), sign * amount);
if (result.success) setAdjustAmount("");
return result;
});
};
const dealerRoundLive =
(view.phase === "insurance" || view.phase === "player") && view.dealer.cards.length > 0;
return (
<>
{error && <p className="text-sm text-destructive">{error}</p>}
<DevSection title="Bankroll adjustment">
<Combobox
className="h-8 text-xs"
value={adjustSeat}
onValueChange={setAdjustSeat}
placeholder="Player"
searchPlaceholder="Search players..."
options={view.players
.filter((player) => !player.left)
.map((player) => ({
value: String(player.seatId),
label: `${player.name} (${player.bankroll.toLocaleString()})`,
}))}
/>
<div className="flex items-center gap-2">
<Input
type="number"
min={1}
step={1}
placeholder="Chips"
value={adjustAmount}
onChange={(event) => setAdjustAmount(event.target.value)}
className="h-8 w-28 text-xs"
/>
<Button type="button" variant="outline" size="sm" onClick={() => adjust(1)}>
Add
</Button>
<Button type="button" variant="outline" size="sm" onClick={() => adjust(-1)}>
Subtract
</Button>
</div>
</DevSection>
<DevSection title="Force next card">
<p className="text-xs text-muted-foreground">
Injects the card at the top of the shoe: the next card drawn, to the
acting player or the dealer, will be this one.
</p>
<CardPicker label="Card" value={nextCard} onChange={setNextCard} />
<DevButton
type="button"
size="sm"
className="w-fit"
disabled={!nextCard}
confirm
onClick={() => {
if (!nextCard) return;
void run("force-next-card", async () => {
const result = await forceBlackjackNextCard(tableId, nextCard);
if (result.success) setNextCard(null);
return result;
});
}}
>
{nextCard ? `Inject ${cardLabel(nextCard)}` : "Inject card"}
</DevButton>
</DevSection>
<DevSection title="Dealer hand override">
<p className="text-xs text-muted-foreground">
Replaces the dealer&apos;s cards while the round is live (insurance or
player phase). The reveal and settle then run against these cards.
</p>
<CardPicker label="Card 1" value={dealerA} onChange={setDealerA} />
<CardPicker label="Card 2" value={dealerB} onChange={setDealerB} />
<DevButton
type="button"
size="sm"
className="w-fit"
confirm
disabled={!dealerA || !dealerRoundLive}
onClick={() => {
if (!dealerA) return;
const cards = dealerB ? [dealerA, dealerB] : [dealerA];
void run("set-dealer-hand", async () => {
const result = await setBlackjackDealerHand(tableId, cards);
if (result.success) {
setDealerA(null);
setDealerB(null);
}
return result;
});
}}
>
Set dealer hand
</DevButton>
</DevSection>
<DevSection title="Table">
<DevButton
type="button"
variant="destructive"
size="sm"
className="w-fit"
confirm
confirmLabel="Click again to end table"
onClick={() => void run("force-expire-table", () => forceExpireBlackjackTable(tableId))}
>
Force end table
</DevButton>
</DevSection>
</>
);
}

View file

@ -0,0 +1,250 @@
"use client";
import { useState } from "react";
import type {
BomperatorAdminCommand,
BomperatorView,
} from "@/app/(frontend)/minigames/bomperator/actions";
import {
bomperatorAdminCommand,
forceExpireBomperatorMatch,
} from "@/app/(frontend)/minigames/bomperator/actions";
import type { PowerUpKind } from "@/lib/minigames/bomperator/types";
import { TICKS_PER_SECOND } from "@/lib/minigames/bomperator/constants";
import { Combobox } from "@/components/ui/combobox";
import { Input } from "@/components/ui/input";
import { pushDevLog } from "./devLog";
import { DevButton, DevSection } from "./primitives";
/**
* Ordnance Disposal controls for the shared minigame dev dock. Every command
* rides `bomperatorAdminCommand`, which works over both transports (arena REST
* proxy or in-process registry); cheats land on the board through the normal
* snapshot fan-out, so every client sees them by next tick.
*/
const PICKUP_OPTIONS: readonly { value: PowerUpKind; label: string }[] = [
{ value: "bomb", label: "Bomb (+1 charge)" },
{ value: "range", label: "Range (+1 reach)" },
{ value: "speed", label: "Speed (+1 cell/s)" },
{ value: "kick", label: "Kick (shove charges)" },
];
interface BomperatorDevControlsProps {
readonly matchId: string;
readonly match: BomperatorView;
}
export function BomperatorDevControls({ matchId, match }: BomperatorDevControlsProps) {
const [seat, setSeat] = useState<string>("");
const [pickup, setPickup] = useState<PowerUpKind>("bomb");
const [timerSeconds, setTimerSeconds] = useState<string>("30");
const [winnerSeat, setWinnerSeat] = useState<string>("");
const [error, setError] = useState<string | null>(null);
const send = async (cmd: BomperatorAdminCommand) => {
pushDevLog("action", `bomperator: ${cmd.kind} sent`);
try {
const result = await bomperatorAdminCommand(matchId, cmd);
if (!result.success) {
const message = result.error ?? "The admin command failed.";
setError(message);
pushDevLog("error", `bomperator: ${cmd.kind} failed (${message})`);
} else {
setError(null);
pushDevLog("action", `bomperator: ${cmd.kind} applied`);
}
} catch (caught) {
const message = caught instanceof Error ? caught.message : "The admin command failed.";
setError(message);
pushDevLog("error", `bomperator: ${cmd.kind} threw (${message})`);
}
};
const seatOptions = match.players.map((player) => ({
value: String(player.seat),
label: `${player.name}${player.alive ? "" : " (down)"} · seat ${player.seat}`,
}));
const aliveSeatOptions = match.players
.filter((player) => player.alive)
.map((player) => ({ value: String(player.seat), label: player.name }));
return (
<>
{error && <p className="text-sm text-destructive">{error}</p>}
<DevSection title="Board">
<DevButton
type="button"
variant="outline"
size="sm"
className="w-fit"
confirm
onClick={() => void send({ kind: "destroyCrates" })}
>
Destroy all crates
</DevButton>
<DevButton
type="button"
variant="outline"
size="sm"
className="w-fit"
confirm
disabled={match.suddenDeath}
onClick={() => void send({ kind: "suddenDeathNow" })}
>
Sudden death now
</DevButton>
</DevSection>
<DevSection title="Grant pickup to seat">
<div className="flex items-center gap-2">
<Combobox
className="h-8 flex-1 text-xs"
value={seat}
onValueChange={setSeat}
placeholder="Seat"
searchPlaceholder="Search technicians..."
options={seatOptions}
/>
<Combobox
className="h-8 w-32 text-xs"
value={pickup}
onValueChange={(next) => setPickup(next as PowerUpKind)}
options={PICKUP_OPTIONS.map((option) => ({
value: option.value,
label: option.label,
}))}
/>
</div>
<DevButton
type="button"
variant="outline"
size="sm"
className="w-fit"
disabled={seat === ""}
onClick={() => {
if (seat === "") return;
void send({ kind: "grantPickup", seat: Number(seat), pickup });
}}
>
Grant pickup
</DevButton>
</DevSection>
<DevSection title="Eliminate technician">
<div className="flex items-center gap-2">
<Combobox
className="h-8 flex-1 text-xs"
value={seat}
onValueChange={setSeat}
placeholder="Seat"
searchPlaceholder="Search technicians..."
options={aliveSeatOptions}
/>
<DevButton
type="button"
variant="destructive"
size="sm"
confirm
disabled={seat === ""}
onClick={() => {
if (seat === "") return;
void send({ kind: "eliminate", seat: Number(seat) });
}}
>
Eliminate
</DevButton>
</div>
</DevSection>
<DevSection title="Match control">
<div className="flex items-center gap-2">
<DevButton
type="button"
variant={match.frozen ? "default" : "outline"}
size="sm"
onClick={() => void send({ kind: "freeze", frozen: !match.frozen })}
>
{match.frozen ? "Unfreeze ticks" : "Freeze ticks"}
</DevButton>
{match.frozen && (
<span className="text-xs font-medium text-amber-400">Simulation frozen</span>
)}
</div>
<div className="flex items-center gap-2">
<Input
type="number"
min={0}
step={1}
placeholder="Seconds"
value={timerSeconds}
onChange={(event) => setTimerSeconds(event.target.value)}
className="h-8 w-24 text-xs"
/>
<DevButton
type="button"
variant="outline"
size="sm"
disabled={!Number.isFinite(Number(timerSeconds)) || Number(timerSeconds) < 0}
onClick={() =>
void send({
kind: "setRoundTimer",
ticks: Math.round(Number(timerSeconds) * TICKS_PER_SECOND),
})
}
>
Set round timer
</DevButton>
</div>
<div className="flex items-center gap-2">
<Combobox
className="h-8 flex-1 text-xs"
value={winnerSeat}
onValueChange={setWinnerSeat}
placeholder="Round winner (empty = draw)"
searchPlaceholder="Search technicians..."
options={[{ value: "-1", label: "Draw (no winner)" }, ...aliveSeatOptions]}
/>
<DevButton
type="button"
variant="outline"
size="sm"
confirm
onClick={() =>
void send({
kind: "endRound",
winnerSeat: winnerSeat === "" || winnerSeat === "-1" ? null : Number(winnerSeat),
})
}
>
Force end round
</DevButton>
</div>
</DevSection>
<DevSection title="Match">
<DevButton
type="button"
variant="destructive"
size="sm"
className="w-fit"
confirm
confirmLabel="Click again to expire match"
onClick={async () => {
pushDevLog("action", "bomperator: force-expire-match sent");
const result = await forceExpireBomperatorMatch(matchId);
pushDevLog(
result.success ? "action" : "error",
result.success
? "bomperator: force-expire-match applied"
: `bomperator: force-expire-match failed (${result.error ?? "unknown"})`,
);
}}
>
Force expire match
</DevButton>
</DevSection>
</>
);
}

View file

@ -0,0 +1,207 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { RotateCcw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { clearDevSetting, readDevSetting, writeDevSetting } from "./devSettings";
import { pushDevLog } from "./devLog";
import { CopyButton, DevSection } from "./primitives";
/**
* Call for Fire controls for the shared minigame dev dock.
*
* Both toggles are client-side observation aids and the seed replaces the RNG
* only at mission generation. The submitted result payload and its server-side
* validation are untouched: the hidden target is generated on the client, so
* revealing it (or reproducing it from a seed) changes what the operator sees,
* not what the action accepts.
*/
export const CALL_FOR_FIRE_DEV_GAME_KEY = "call-for-fire";
export const CALL_FOR_FIRE_DEV_SETTINGS_EVENT = "ptf:dev-settings-changed";
const SHOW_TARGET_KEY = "showTarget";
const FREE_CORRECTIONS_KEY = "freeCorrections";
const SEED_KEY = "seed";
function announceSettingsChanged(): void {
if (typeof window === "undefined") return;
window.dispatchEvent(new Event(CALL_FOR_FIRE_DEV_SETTINGS_EVENT));
}
function readStoredSeed(): number | null {
const stored = readDevSetting<number | null>(CALL_FOR_FIRE_DEV_GAME_KEY, SEED_KEY, null);
return typeof stored === "number" && Number.isFinite(stored) ? Math.trunc(stored) : null;
}
export function CallForFireDevControls() {
const [showTarget, setShowTarget] = useState(() =>
readDevSetting(CALL_FOR_FIRE_DEV_GAME_KEY, SHOW_TARGET_KEY, false),
);
const [freeCorrections, setFreeCorrections] = useState(() =>
readDevSetting(CALL_FOR_FIRE_DEV_GAME_KEY, FREE_CORRECTIONS_KEY, false),
);
const [seed, setSeed] = useState<number | null>(readStoredSeed);
const [seedDraft, setSeedDraft] = useState(() => {
const stored = readStoredSeed();
return stored === null ? "" : String(stored);
});
const [error, setError] = useState<string | null>(null);
const seedRef = useRef<number | null>(seed);
useEffect(() => {
const sync = () => {
setShowTarget(readDevSetting(CALL_FOR_FIRE_DEV_GAME_KEY, SHOW_TARGET_KEY, false));
setFreeCorrections(readDevSetting(CALL_FOR_FIRE_DEV_GAME_KEY, FREE_CORRECTIONS_KEY, false));
const nextSeed = readStoredSeed();
if (seedRef.current === nextSeed) return;
seedRef.current = nextSeed;
setSeed(nextSeed);
setSeedDraft(nextSeed === null ? "" : String(nextSeed));
};
sync();
window.addEventListener(CALL_FOR_FIRE_DEV_SETTINGS_EVENT, sync);
return () => window.removeEventListener(CALL_FOR_FIRE_DEV_SETTINGS_EVENT, sync);
}, []);
const toggle = (key: string, value: boolean, setValue: (next: boolean) => void) => {
setValue(value);
writeDevSetting(CALL_FOR_FIRE_DEV_GAME_KEY, key, value);
pushDevLog("action", `call-for-fire: ${key} = ${String(value)}`);
announceSettingsChanged();
};
const applySeed = (next: number) => {
seedRef.current = next;
setSeed(next);
setSeedDraft(String(next));
setError(null);
writeDevSetting(CALL_FOR_FIRE_DEV_GAME_KEY, SEED_KEY, next);
pushDevLog("action", `call-for-fire: seed = ${next}`);
announceSettingsChanged();
};
const clearSeed = () => {
seedRef.current = null;
setSeed(null);
setSeedDraft("");
setError(null);
clearDevSetting(CALL_FOR_FIRE_DEV_GAME_KEY, SEED_KEY);
pushDevLog("action", "call-for-fire: seed = default");
announceSettingsChanged();
};
const applyDraft = () => {
const trimmed = seedDraft.trim();
if (trimmed === "") {
clearSeed();
return;
}
const parsed = Number(trimmed);
if (!Number.isSafeInteger(parsed)) {
setError("Enter a whole number, or leave the field empty for the default RNG.");
return;
}
applySeed(parsed);
};
return (
<>
{error && <p className="text-sm text-destructive">{error}</p>}
<DevSection title="Target">
<div className="flex items-center justify-between gap-3">
<div className="flex flex-col gap-0.5">
<Label htmlFor="cff-dev-show-target" className="text-xs font-medium">
Show target location
</Label>
<span className="text-xs text-muted-foreground">
Marks the hidden target cell on the board during play. Display only.
</span>
</div>
<Switch
id="cff-dev-show-target"
checked={showTarget}
onCheckedChange={(checked) => toggle(SHOW_TARGET_KEY, checked, setShowTarget)}
/>
</div>
</DevSection>
<DevSection title="Corrections">
<div className="flex items-center justify-between gap-3">
<div className="flex flex-col gap-0.5">
<Label htmlFor="cff-dev-free-corrections" className="text-xs font-medium">
Free corrections
</Label>
<span className="text-xs text-muted-foreground">
Lifts the client-side round cap so you can keep correcting past max rounds, and keeps
the full observer net history instead of the last six transmissions. Rounds fired are
still reported as-is, so the unchanged server validation rejects a result that exceeds
the cap; accepted scores are unaffected.
</span>
</div>
<Switch
id="cff-dev-free-corrections"
checked={freeCorrections}
onCheckedChange={(checked) => toggle(FREE_CORRECTIONS_KEY, checked, setFreeCorrections)}
/>
</div>
</DevSection>
<DevSection title="Mission seed">
<p className="text-xs text-muted-foreground">
Target and spotting round are generated when a mission begins, so a seed reproduces the
same scenario on the next Begin. Leave the field empty and apply to use Math.random.
</p>
<div className="flex items-center gap-2">
<Label htmlFor="cff-dev-seed" className="sr-only">
Mission seed
</Label>
<Input
id="cff-dev-seed"
type="number"
step={1}
inputMode="numeric"
placeholder="Seed"
value={seedDraft}
onChange={(event) => setSeedDraft(event.target.value)}
onKeyDown={(event) => {
if (event.key !== "Enter") return;
event.preventDefault();
applyDraft();
}}
className="h-8 w-28 text-xs"
/>
<Button
type="button"
size="sm"
onClick={applyDraft}
disabled={seedDraft.trim() === "" && seed === null}
>
Apply
</Button>
{seed !== null && <CopyButton getText={() => String(seed)} label="Copy seed" />}
</div>
<div className="flex flex-wrap items-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={clearSeed}
disabled={seed === null && seedDraft === ""}
>
<RotateCcw /> Default RNG
</Button>
{seed !== null ? (
<p className="font-mono text-[10px] text-muted-foreground">active seed: {seed}</p>
) : (
<p className="text-[10px] text-muted-foreground">active seed: Math.random</p>
)}
</div>
</DevSection>
</>
);
}

View file

@ -0,0 +1,190 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { Dices, RotateCcw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { clearDevSetting, readDevSetting, writeDevSetting } from "./devSettings";
import { pushDevLog } from "./devLog";
import { DevSection } from "./primitives";
/**
* Developer controls for Minefield Clearance, rendered inside the shared
* minigame dev dock.
*
* Everything here is client-side and gameplay/presentation only: the submitted
* result payload and the server-side validation are untouched. Settings persist
* in localStorage under the "eod" key and are announced with a window event so
* the mounted board re-reads them without prop plumbing.
*/
export const EOD_DEV_GAME_KEY = "eod";
export const DEV_SETTINGS_CHANGED_EVENT = "ptf:dev-settings-changed";
const REVEAL_KEY = "revealLayout";
const DIG_ANYWHERE_KEY = "digAnywhere";
const SEED_KEY = "seed";
function announceSettingsChanged(): void {
if (typeof window === "undefined") return;
window.dispatchEvent(new Event(DEV_SETTINGS_CHANGED_EVENT));
}
function readStoredSeed(): number | null {
const stored = readDevSetting<number | null>(EOD_DEV_GAME_KEY, SEED_KEY, null);
return typeof stored === "number" && Number.isFinite(stored) ? Math.trunc(stored) : null;
}
export function EodDevControls() {
const [revealLayout, setRevealLayout] = useState(false);
const [digAnywhere, setDigAnywhere] = useState(false);
const [seed, setSeed] = useState<number | null>(null);
const [seedDraft, setSeedDraft] = useState("");
const [error, setError] = useState<string | null>(null);
const seedRef = useRef<number | null>(null);
useEffect(() => {
const sync = () => {
setRevealLayout(readDevSetting(EOD_DEV_GAME_KEY, REVEAL_KEY, false));
setDigAnywhere(readDevSetting(EOD_DEV_GAME_KEY, DIG_ANYWHERE_KEY, false));
const nextSeed = readStoredSeed();
if (seedRef.current === nextSeed) return;
seedRef.current = nextSeed;
setSeed(nextSeed);
setSeedDraft(nextSeed === null ? "" : String(nextSeed));
};
sync();
window.addEventListener(DEV_SETTINGS_CHANGED_EVENT, sync);
return () => window.removeEventListener(DEV_SETTINGS_CHANGED_EVENT, sync);
}, []);
const toggle = (key: string, value: boolean, setValue: (next: boolean) => void) => {
setValue(value);
writeDevSetting(EOD_DEV_GAME_KEY, key, value);
pushDevLog("action", `eod: ${key} = ${value}`);
announceSettingsChanged();
};
const applySeed = (next: number) => {
seedRef.current = next;
setSeed(next);
setSeedDraft(String(next));
setError(null);
writeDevSetting(EOD_DEV_GAME_KEY, SEED_KEY, next);
pushDevLog("action", `eod: seed = ${next}`);
announceSettingsChanged();
};
const applyDraft = () => {
const trimmed = seedDraft.trim();
const parsed = Number(trimmed);
if (trimmed === "" || !Number.isSafeInteger(parsed)) {
setError("Enter a whole number.");
return;
}
applySeed(parsed);
};
const clearSeed = () => {
seedRef.current = null;
setSeed(null);
setSeedDraft("");
setError(null);
clearDevSetting(EOD_DEV_GAME_KEY, SEED_KEY);
pushDevLog("action", "eod: seed = default (Math.random)");
announceSettingsChanged();
};
return (
<>
{error && <p className="text-sm text-destructive">{error}</p>}
<DevSection title="Board overlays">
<div className="flex items-center justify-between gap-3">
<div className="flex flex-col gap-0.5">
<Label htmlFor="eod-dev-reveal" className="text-xs font-medium">
Reveal layout
</Label>
<span className="text-xs text-muted-foreground">
Outline every charge on the board. Display only.
</span>
</div>
<Switch
id="eod-dev-reveal"
checked={revealLayout}
onCheckedChange={(checked) => toggle(REVEAL_KEY, checked, setRevealLayout)}
/>
</div>
<div className="flex items-center justify-between gap-3">
<div className="flex flex-col gap-0.5">
<Label htmlFor="eod-dev-dig-anywhere" className="text-xs font-medium">
Dig anywhere
</Label>
<span className="text-xs text-muted-foreground">
A click on a charge clears it instead of ending the run.
</span>
</div>
<Switch
id="eod-dev-dig-anywhere"
checked={digAnywhere}
onCheckedChange={(checked) => toggle(DIG_ANYWHERE_KEY, checked, setDigAnywhere)}
/>
</div>
</DevSection>
<DevSection title="Minefield seed">
<p className="text-xs text-muted-foreground">
Layouts are generated on the first dig, with a safe pocket around that click, so a seed
reproduces the same field for the same first click. Changing the seed restarts the sector.
</p>
<div className="flex items-center gap-2">
<Label htmlFor="eod-dev-seed" className="sr-only">
Minefield seed
</Label>
<Input
id="eod-dev-seed"
type="number"
step={1}
inputMode="numeric"
placeholder="Seed"
value={seedDraft}
onChange={(event) => setSeedDraft(event.target.value)}
onKeyDown={(event) => {
if (event.key !== "Enter") return;
event.preventDefault();
applyDraft();
}}
className="h-8 w-28 text-xs"
/>
<Button type="button" size="sm" onClick={applyDraft} disabled={seedDraft.trim() === ""}>
Apply
</Button>
</div>
<div className="flex flex-wrap items-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => applySeed(Math.floor(Math.random() * 2_147_483_647))}
>
<Dices /> Random seed
</Button>
<Button
type="button"
variant="outline"
size="sm"
onClick={clearSeed}
disabled={seed === null}
>
<RotateCcw /> Default RNG
</Button>
</div>
{seed !== null && (
<p className="font-mono text-[10px] text-muted-foreground">active seed: {seed}</p>
)}
</DevSection>
</>
);
}

View file

@ -0,0 +1,196 @@
"use client";
import { useState } from "react";
import { RotateCcw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Slider } from "@/components/ui/slider";
import { Switch } from "@/components/ui/switch";
import {
FLAPPY_DEV_EVENT,
FLAPPY_DEV_GAME_KEY,
FLAPPY_DEV_RANGES,
readFlappyDevConfig,
type FlappyDevConfig,
} from "../flappy/devConfig";
import { pushDevLog } from "./devLog";
import { clearDevSetting, writeDevSetting } from "./devSettings";
import { DevSection } from "./primitives";
/**
* Flight Simulator controls for the shared minigame dev dock.
*
* Physics sliders (gravity, pipe speed, pipe gap) commit on release rather
* than on every Radix change tick: intermediate drag values still preview in
* the local label, but only the released value is persisted, broadcast, and
* logged. Toggles apply immediately. Everything is client-side: the running
* game re-reads on `ptf:dev-settings-changed`, and submissions are untouched.
*/
type NumericKey = "gravity" | "pipeSpeed" | "pipeGap";
type ToggleKey = "paused" | "invincible" | "fpsOverlay";
interface SliderRowProps {
readonly label: string;
readonly value: number;
readonly range: { readonly min: number; readonly max: number; readonly step: number };
readonly format: (value: number) => string;
readonly onChange: (value: number) => void;
readonly onCommit: (value: number) => void;
}
function SliderRow({ label, value, range, format, onChange, onCommit }: SliderRowProps) {
return (
<div className="flex flex-col gap-1.5">
<div className="flex items-center justify-between gap-2">
<span className="text-xs font-normal text-muted-foreground">{label}</span>
<span className="font-mono text-xs tabular-nums">{format(value)}</span>
</div>
<Slider
aria-label={label}
min={range.min}
max={range.max}
step={range.step}
value={[value]}
onValueChange={(next) => {
const first = next[0];
if (typeof first === "number") onChange(first);
}}
onValueCommit={(next) => {
const first = next[0];
if (typeof first === "number") onCommit(first);
}}
/>
</div>
);
}
interface ToggleRowProps {
readonly id: string;
readonly label: string;
readonly checked: boolean;
readonly onChange: (checked: boolean) => void;
}
function ToggleRow({ id, label, checked, onChange }: ToggleRowProps) {
return (
<div className="flex items-center justify-between gap-2">
<Label htmlFor={id} className="text-xs font-normal text-muted-foreground">
{label}
</Label>
<Switch id={id} checked={checked} onCheckedChange={onChange} />
</div>
);
}
const NUMBER_FORMAT: Record<NumericKey, (value: number) => string> = {
gravity: (value) => value.toFixed(2),
pipeSpeed: (value) => value.toFixed(2),
pipeGap: (value) => `${Math.round(value)} px`,
};
interface FlappyDevControlsProps {
/** The game's module constants, used for the initial read and reset. */
readonly defaults: FlappyDevConfig;
}
export function FlappyDevControls({ defaults }: FlappyDevControlsProps) {
const [config, setConfig] = useState<FlappyDevConfig>(() => readFlappyDevConfig(defaults));
const persist = (key: keyof FlappyDevConfig, value: number | boolean) => {
writeDevSetting(FLAPPY_DEV_GAME_KEY, key, value);
window.dispatchEvent(new Event(FLAPPY_DEV_EVENT));
pushDevLog("action", `flappy: ${key} = ${String(value)}`);
};
const applyNumber = (key: NumericKey, value: number) => {
setConfig((current) => ({ ...current, [key]: value }));
persist(key, value);
};
const applyToggle = (key: ToggleKey, value: boolean) => {
setConfig((current) => ({ ...current, [key]: value }));
persist(key, value);
};
const reset = () => {
const keys: (keyof FlappyDevConfig)[] = [
"gravity",
"pipeSpeed",
"pipeGap",
"paused",
"invincible",
"fpsOverlay",
];
for (const key of keys) clearDevSetting(FLAPPY_DEV_GAME_KEY, key);
setConfig(defaults);
window.dispatchEvent(new Event(FLAPPY_DEV_EVENT));
pushDevLog("action", "flappy: reset to defaults");
};
return (
<>
<DevSection title="Physics">
<SliderRow
label="Gravity"
value={config.gravity}
range={FLAPPY_DEV_RANGES.gravity}
format={NUMBER_FORMAT.gravity}
onChange={(value) => setConfig((current) => ({ ...current, gravity: value }))}
onCommit={(value) => applyNumber("gravity", value)}
/>
<SliderRow
label="Pipe speed"
value={config.pipeSpeed}
range={FLAPPY_DEV_RANGES.pipeSpeed}
format={NUMBER_FORMAT.pipeSpeed}
onChange={(value) => setConfig((current) => ({ ...current, pipeSpeed: value }))}
onCommit={(value) => applyNumber("pipeSpeed", value)}
/>
<SliderRow
label="Pipe gap"
value={config.pipeGap}
range={FLAPPY_DEV_RANGES.pipeGap}
format={NUMBER_FORMAT.pipeGap}
onChange={(value) => setConfig((current) => ({ ...current, pipeGap: value }))}
onCommit={(value) => applyNumber("pipeGap", value)}
/>
<p className="text-xs text-muted-foreground">
Sliders apply on release. Values persist in this browser and re-read live.
</p>
</DevSection>
<DevSection title="Simulation">
<ToggleRow
id="flappy-dev-pause"
label="Pause simulation"
checked={config.paused}
onChange={(checked) => applyToggle("paused", checked)}
/>
<ToggleRow
id="flappy-dev-invincible"
label="Invincibility"
checked={config.invincible}
onChange={(checked) => applyToggle("invincible", checked)}
/>
<ToggleRow
id="flappy-dev-fps"
label="FPS overlay"
checked={config.fpsOverlay}
onChange={(checked) => applyToggle("fpsOverlay", checked)}
/>
</DevSection>
<Button
type="button"
variant="outline"
size="sm"
className="h-7 w-fit gap-1 text-xs"
onClick={reset}
>
<RotateCcw className="size-3.5" />
Reset to defaults
</Button>
</>
);
}

View file

@ -0,0 +1,229 @@
"use client";
import { useEffect, useMemo, useState, type ReactNode } from "react";
import { Shield, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { cn } from "@/lib/utils";
import { readDevSetting, writeDevSetting } from "./devSettings";
import { formatDevLog, isDevLogMirrored, pushDevLog, setDevLogMirror, useDevLog } from "./useDevLog";
import { CopyButton } from "./primitives";
/**
* Floating developer dock shared by every minigame (superuser-only).
*
* Collapsed it is just the Shield button in the bottom-right corner (the same
* affordance poker's old inline dev panel used); expanded it is a dense panel
* with three tabs: Controls (per-game content passed as children), State (raw
* snapshot JSON inspector with copy-to-clipboard), and Log (the client dev
* console ring buffer). The dock stays mounted during play.
*
* Availability is gated twice: the page computes `isSuperuser` server-side and
* passes it here, and every action the panels fire re-checks it. Rendering is
* purely cosmetic gating; the actions are the security boundary.
*/
const STATE_JSON_LIMIT = 200_000;
type DockTab = "controls" | "state" | "log";
export interface MinigameDevDockProps {
readonly isSuperuser: boolean;
/** Registry key for settings namespacing and log prefixes, e.g. "poker". */
readonly gameKey: string;
/** Human label shown in the dock header, e.g. "Poker". */
readonly gameLabel: string;
/** Current snapshot served to this client; shown raw in the State tab. */
readonly snapshot: unknown;
/** Per-game controls rendered in the Controls tab. */
readonly children?: ReactNode;
}
function snapshotVersion(snapshot: unknown): number | null {
if (typeof snapshot === "object" && snapshot !== null && "version" in snapshot) {
const value = (snapshot as { version?: unknown }).version;
if (typeof value === "number") return value;
}
return null;
}
export function MinigameDevDock({
isSuperuser,
gameKey,
gameLabel,
snapshot,
children,
}: MinigameDevDockProps) {
const [open, setOpen] = useState(() => readDevSetting(gameKey, "dockOpen", false));
const [tab, setTab] = useState<DockTab>(() => readDevSetting<DockTab>(gameKey, "dockTab", "controls"));
const [, setMirrorTick] = useState(0);
const { entries, clear } = useDevLog();
// Log every fresh snapshot the game applies (SSE push or poll merge): the
// version is stamped by the server, so this doubles as a sync watchdog.
const version = snapshotVersion(snapshot);
useEffect(() => {
if (!isSuperuser || version === null) return;
pushDevLog("state", `${gameKey}: snapshot v${version} received`);
}, [gameKey, isSuperuser, version]);
const stateJson = useMemo(() => {
if (snapshot === undefined || snapshot === null) return "(no snapshot yet)";
try {
const json = JSON.stringify(snapshot, null, 2) ?? String(snapshot);
return json.length > STATE_JSON_LIMIT
? `${json.slice(0, STATE_JSON_LIMIT)}\n… truncated (${json.length} chars total)`
: json;
} catch {
return String(snapshot);
}
}, [snapshot]);
if (!isSuperuser) return null;
const toggleOpen = () =>
setOpen((current) => {
const next = !current;
writeDevSetting(gameKey, "dockOpen", next);
return next;
});
return (
<div className="pointer-events-none fixed bottom-4 right-4 z-[70] flex flex-col items-end gap-2">
{open && (
<div className="pointer-events-auto flex max-h-[75dvh] w-[min(24rem,calc(100vw-2rem))] flex-col rounded-lg border border-border bg-background/95 shadow-xl backdrop-blur-sm">
<div className="flex items-center gap-2 border-b border-border px-3 py-2">
<Shield className="size-4 shrink-0 text-muted-foreground" aria-hidden="true" />
<span className="text-xs font-semibold uppercase tracking-wider">
{gameLabel} dev console
</span>
{version !== null && (
<span className="font-mono text-[10px] tabular-nums text-muted-foreground">
v{version}
</span>
)}
<Button
type="button"
variant="ghost"
size="icon"
className="ml-auto size-6"
aria-label="Collapse developer dock"
title="Collapse developer dock"
onClick={toggleOpen}
>
<X className="size-3.5" />
</Button>
</div>
<Tabs
value={tab}
onValueChange={(next) => {
const parsed = next as DockTab;
setTab(parsed);
writeDevSetting(gameKey, "dockTab", parsed);
}}
className="flex min-h-0 flex-1 flex-col gap-0"
>
<TabsList className="mx-3 mt-2 w-fit">
<TabsTrigger value="controls" className="text-xs">
Controls
</TabsTrigger>
<TabsTrigger value="state" className="text-xs">
State
</TabsTrigger>
<TabsTrigger value="log" className="text-xs">
Log ({entries.length})
</TabsTrigger>
</TabsList>
<TabsContent
value="controls"
className="min-h-0 flex-1 overflow-y-auto p-3 data-[state=inactive]:hidden"
>
<div className="flex flex-col gap-3">{children}</div>
</TabsContent>
<TabsContent
value="state"
className="min-h-0 flex-1 overflow-hidden p-3 data-[state=inactive]:hidden"
>
<div className="flex h-full min-h-0 flex-col gap-2">
<div className="flex items-center justify-between gap-2">
<span className="text-xs text-muted-foreground">Raw snapshot JSON</span>
<CopyButton getText={() => stateJson} label="Copy state" />
</div>
<pre className="min-h-0 flex-1 overflow-auto rounded-md border border-border bg-muted/40 p-2 font-mono text-[10px] leading-relaxed">
{stateJson}
</pre>
</div>
</TabsContent>
<TabsContent
value="log"
className="min-h-0 flex-1 overflow-hidden p-3 data-[state=inactive]:hidden"
>
<div className="flex h-full min-h-0 flex-col gap-2">
<div className="flex flex-wrap items-center gap-2">
<Label
htmlFor={`${gameKey}-dev-console-mirror`}
className="flex items-center gap-2 text-xs font-normal text-muted-foreground"
>
<Switch
id={`${gameKey}-dev-console-mirror`}
checked={isDevLogMirrored()}
onCheckedChange={(checked) => {
setDevLogMirror(checked);
setMirrorTick((tick) => tick + 1);
}}
/>
Mirror to console
</Label>
<CopyButton getText={() => formatDevLog()} label="Copy log" className="ml-auto" />
<Button type="button" variant="outline" size="sm" className="h-7 text-xs" onClick={clear}>
Clear
</Button>
</div>
<div className="min-h-0 flex-1 overflow-auto rounded-md border border-border bg-muted/40 p-2 font-mono text-[10px] leading-relaxed">
{entries.length === 0 ? (
<span className="text-muted-foreground">No entries yet.</span>
) : (
[...entries].reverse().map((entry) => (
<div
key={entry.id}
className={cn(
"whitespace-pre-wrap break-words",
entry.kind === "error" && "text-destructive",
entry.kind === "action" && "text-sky-300",
entry.kind === "state" && "text-muted-foreground",
)}
>
<span className="tabular-nums opacity-60">{entry.at.slice(11, 19)}</span>{" "}
{entry.text}
</div>
))
)}
</div>
</div>
</TabsContent>
</Tabs>
</div>
)}
{!open && (
<Button
type="button"
variant="outline"
size="icon"
className="pointer-events-auto"
aria-label="Developer controls"
title="Developer controls"
onClick={toggleOpen}
>
<Shield aria-hidden="true" />
</Button>
)}
</div>
);
}

View file

@ -0,0 +1,176 @@
"use client";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { clearDevSetting, readDevSetting, writeDevSetting } from "./devSettings";
import { pushDevLog } from "./devLog";
import { DevSection } from "./primitives";
/**
* OPORD Recall controls for the shared minigame dev dock.
*
* Both controls are client-only debugging aids (the solo game keeps no server
* state):
* - "Reveal answers" marks the correct option of the question on screen. The
* quiz is built client-side from the seeded scenario, so the questions,
* their `correctIndex` values, and typed answers are already in the browser.
* - "Study time override" turns the self-paced briefing into a countdown that
* starts the recall quiz when it expires.
*
* Neither touches the submission: the result payload, its bounds, the timer
* check, and the scoring math stay exactly as before.
*/
export const OPORD_DEV_GAME_KEY = "opord";
export const OPORD_DEV_SETTINGS_EVENT = "ptf:dev-settings-changed";
export interface OpordDevSettings {
readonly revealAnswers: boolean;
/** Study countdown in seconds; null keeps the self-paced briefing. */
readonly studySeconds: number | null;
}
const MIN_STUDY_SECONDS = 5;
const MAX_STUDY_SECONDS = 3600;
function readStudySeconds(): number | null {
const value = readDevSetting<number | null>(OPORD_DEV_GAME_KEY, "studySeconds", null);
if (typeof value !== "number" || !Number.isFinite(value)) return null;
const rounded = Math.round(value);
if (rounded < MIN_STUDY_SECONDS || rounded > MAX_STUDY_SECONDS) return null;
return rounded;
}
/** Snapshot of both overrides; safe to call during SSR (falls back to defaults). */
export function readOpordDevSettings(): OpordDevSettings {
return {
revealAnswers: readDevSetting<boolean>(OPORD_DEV_GAME_KEY, "revealAnswers", false) === true,
studySeconds: readStudySeconds(),
};
}
export function OpordDevControls({
isSuperuser = false,
}: {
readonly isSuperuser?: boolean;
}) {
const [revealAnswers, setRevealAnswers] = useState(() => readOpordDevSettings().revealAnswers);
const [studySeconds, setStudySeconds] = useState<number | null>(
() => readOpordDevSettings().studySeconds,
);
const [studyDraft, setStudyDraft] = useState(() => {
const seconds = readOpordDevSettings().studySeconds;
return seconds === null ? "" : String(seconds);
});
const [error, setError] = useState<string | null>(null);
const updateRevealAnswers = (checked: boolean) => {
writeDevSetting(OPORD_DEV_GAME_KEY, "revealAnswers", checked);
setRevealAnswers(checked);
window.dispatchEvent(new Event(OPORD_DEV_SETTINGS_EVENT));
pushDevLog("action", `opord: revealAnswers = ${checked}`);
};
const clearStudyOverride = () => {
clearDevSetting(OPORD_DEV_GAME_KEY, "studySeconds");
setStudySeconds(null);
setStudyDraft("");
setError(null);
window.dispatchEvent(new Event(OPORD_DEV_SETTINGS_EVENT));
pushDevLog("action", "opord: studySeconds = default");
};
const applyStudySeconds = () => {
const trimmed = studyDraft.trim();
if (trimmed.length === 0) {
clearStudyOverride();
return;
}
const parsed = Number(trimmed);
if (!Number.isInteger(parsed) || parsed < MIN_STUDY_SECONDS || parsed > MAX_STUDY_SECONDS) {
setError(
`Enter a whole number of seconds between ${MIN_STUDY_SECONDS} and ${MAX_STUDY_SECONDS}.`,
);
return;
}
writeDevSetting(OPORD_DEV_GAME_KEY, "studySeconds", parsed);
setStudySeconds(parsed);
setStudyDraft(String(parsed));
setError(null);
window.dispatchEvent(new Event(OPORD_DEV_SETTINGS_EVENT));
pushDevLog("action", `opord: studySeconds = ${parsed}`);
};
if (!isSuperuser) return null;
return (
<>
<DevSection title="Answer reveal">
<Label
htmlFor="opord-dev-reveal-answers"
className="flex items-center gap-2 text-xs font-normal text-muted-foreground"
>
<Switch
id="opord-dev-reveal-answers"
checked={revealAnswers}
onCheckedChange={updateRevealAnswers}
/>
Reveal answers
</Label>
<p className="text-xs text-muted-foreground">
Highlights the correct option while the recall quiz is on screen; typed questions show
the expected answer. The quiz is generated in the browser, so no server data is involved.
</p>
</DevSection>
<DevSection title="Study time">
<Label
htmlFor="opord-dev-study-seconds"
className="text-xs font-normal text-muted-foreground"
>
Study window (seconds)
</Label>
<div className="flex items-center gap-2">
<Input
id="opord-dev-study-seconds"
type="number"
min={MIN_STUDY_SECONDS}
max={MAX_STUDY_SECONDS}
step={1}
inputMode="numeric"
placeholder="Self-paced"
value={studyDraft}
onChange={(event) => setStudyDraft(event.target.value)}
onKeyDown={(event) => {
if (event.key !== "Enter") return;
event.preventDefault();
applyStudySeconds();
}}
className="h-8 w-28 text-xs"
/>
<Button type="button" size="sm" onClick={applyStudySeconds}>
Apply
</Button>
<Button
type="button"
variant="outline"
size="sm"
disabled={studySeconds === null && studyDraft.length === 0}
onClick={clearStudyOverride}
>
Default
</Button>
</div>
{error && <p className="text-xs text-destructive">{error}</p>}
<p className="text-xs text-muted-foreground">
Counts down during the briefing and starts the recall quiz when it reaches zero. Clear
the field and Apply (or press Default) to return to self-paced study.
{studySeconds === null ? "" : ` Active override: ${studySeconds}s.`}
</p>
</DevSection>
</>
);
}

View file

@ -0,0 +1,301 @@
"use client";
import { useState } from "react";
import { Trash2 } from "lucide-react";
import type { Card } from "@/lib/minigames/poker";
import type { PokerSnapshot } from "@/app/(frontend)/minigames/poker/actions";
import {
adjustPokerStack,
forceExpirePokerTable,
forceFoldPokerPlayer,
forcePokerStreet,
pokerClockControl,
setPokerBoardQueue,
setPokerHoleQueue,
setPokerRevealAll,
} from "@/app/(frontend)/minigames/poker/actions";
import { Button } from "@/components/ui/button";
import { Combobox } from "@/components/ui/combobox";
import { Input } from "@/components/ui/input";
import { cardLabel, CardPicker } from "../poker/PokerDevPanel";
import { pushDevLog } from "./devLog";
import { DevButton, DevSection } from "./primitives";
/**
* Poker controls for the shared minigame dev dock. Migrated from the old
* inline PokerDevPanel dialog (board queue / hole queue / stack adjust) and
* extended with moderation overrides: force-fold a seat, force the next
* street, reveal all hands (per-viewer), turn-clock control, and force-end.
* Sync back to every client is free via the registry's pushTable -> SSE.
*/
interface PokerDevControlsProps {
readonly tableId: string;
readonly view: NonNullable<PokerSnapshot["you"]>;
}
export function PokerDevControls({ tableId, view }: PokerDevControlsProps) {
const [boardQueue, setBoardQueue] = useState<Card[]>([]);
const [boardDraft, setBoardDraft] = useState<Card | null>(null);
const [seatId, setSeatId] = useState<string>("");
const [holeA, setHoleA] = useState<Card | null>(null);
const [holeB, setHoleB] = useState<Card | null>(null);
const [adjustSeat, setAdjustSeat] = useState<string>("");
const [adjustAmount, setAdjustAmount] = useState<string>("");
const [foldSeat, setFoldSeat] = useState<string>("");
const [revealOn, setRevealOn] = useState(false);
const [error, setError] = useState<string | null>(null);
const run = async (name: string, action: () => Promise<{ success: boolean; error?: string }>) => {
pushDevLog("action", `poker: ${name} sent`);
try {
const result = await action();
if (!result.success) {
const message = result.error ?? "The dev action failed.";
setError(message);
pushDevLog("error", `poker: ${name} failed (${message})`);
} else {
setError(null);
pushDevLog("action", `poker: ${name} applied`);
}
return result.success;
} catch (caught) {
const message = caught instanceof Error ? caught.message : "The dev action failed.";
setError(message);
pushDevLog("error", `poker: ${name} threw (${message})`);
return false;
}
};
const queueBoard = () => {
if (boardQueue.length === 0) return;
void run("set-board-queue", async () => {
const result = await setPokerBoardQueue(tableId, boardQueue);
if (result.success) setBoardQueue([]);
return result;
});
};
const queueHole = () => {
if (seatId === "" || !holeA || !holeB) return;
void run("set-hole-queue", async () => {
const result = await setPokerHoleQueue(tableId, Number(seatId), [holeA, holeB]);
if (result.success) {
setHoleA(null);
setHoleB(null);
}
return result;
});
};
const adjust = (sign: 1 | -1) => {
if (adjustSeat === "") return;
const amount = Number(adjustAmount);
if (!Number.isInteger(amount) || amount <= 0) {
setError("Enter a positive whole number of chips.");
return;
}
void run("adjust-stack", async () => {
const result = await adjustPokerStack(tableId, Number(adjustSeat), sign * amount);
if (result.success) setAdjustAmount("");
return result;
});
};
const seatedPlayers = view.players.filter((player) => !player.eliminated);
const boardSlotsLeft = 5 - view.communityCards.length - boardQueue.length;
return (
<>
{error && <p className="text-sm text-destructive">{error}</p>}
<DevSection title="Board queue">
<CardPicker label="Card" value={boardDraft} onChange={setBoardDraft} />
<Button
type="button"
variant="outline"
size="sm"
className="w-fit"
disabled={boardQueue.length >= boardSlotsLeft}
onClick={() => {
if (!boardDraft) return;
setBoardQueue((current) => [...current, boardDraft]);
setBoardDraft(null);
}}
>
Add to queue ({boardSlotsLeft} slot{boardSlotsLeft === 1 ? "" : "s"} left)
</Button>
{boardQueue.length > 0 && (
<ul className="flex flex-col gap-1">
{boardQueue.map((card, index) => (
<li key={`${card.rank}-${card.suit}-${index}`} className="flex items-center gap-2 text-xs">
<span className="font-mono text-muted-foreground">{index + 1}.</span>
<span>{cardLabel(card)}</span>
<button
type="button"
aria-label={`Remove ${cardLabel(card)}`}
className="ml-auto text-muted-foreground hover:text-destructive"
onClick={() => setBoardQueue((current) => current.filter((_, i) => i !== index))}
>
<Trash2 className="size-3.5" />
</button>
</li>
))}
</ul>
)}
<Button
type="button"
size="sm"
className="w-fit"
onClick={queueBoard}
disabled={boardQueue.length === 0}
>
Set board queue
</Button>
</DevSection>
<DevSection title="Next hand hole cards">
<Combobox
className="h-8 text-xs"
value={seatId}
onValueChange={setSeatId}
placeholder="Player"
searchPlaceholder="Search players..."
options={seatedPlayers.map((player) => ({
value: String(player.seatId),
label: player.name,
}))}
/>
<CardPicker label="Card 1" value={holeA} onChange={setHoleA} />
<CardPicker label="Card 2" value={holeB} onChange={setHoleB} />
<Button
type="button"
size="sm"
className="w-fit"
onClick={queueHole}
disabled={seatId === "" || !holeA || !holeB}
>
Queue hand
</Button>
</DevSection>
<DevSection title="Stack adjustment">
<Combobox
className="h-8 text-xs"
value={adjustSeat}
onValueChange={setAdjustSeat}
placeholder="Player"
searchPlaceholder="Search players..."
options={seatedPlayers.map((player) => ({
value: String(player.seatId),
label: `${player.name} (${player.stack.toLocaleString()})`,
}))}
/>
<div className="flex items-center gap-2">
<Input
type="number"
min={1}
step={1}
placeholder="Chips"
value={adjustAmount}
onChange={(event) => setAdjustAmount(event.target.value)}
className="h-8 w-28 text-xs"
/>
<Button type="button" variant="outline" size="sm" onClick={() => adjust(1)}>
Add
</Button>
<Button type="button" variant="outline" size="sm" onClick={() => adjust(-1)}>
Subtract
</Button>
</div>
</DevSection>
<DevSection title="Hand overrides">
<div className="flex items-center gap-2">
<Combobox
className="h-8 flex-1 text-xs"
value={foldSeat}
onValueChange={setFoldSeat}
placeholder="Force fold player"
searchPlaceholder="Search players..."
options={view.players
.filter((player) => !player.eliminated && !player.folded)
.map((player) => ({ value: String(player.seatId), label: player.name }))}
/>
<DevButton
type="button"
variant="outline"
size="sm"
confirm
disabled={foldSeat === ""}
onClick={() => {
if (foldSeat === "") return;
void run("force-fold", () => forceFoldPokerPlayer(tableId, Number(foldSeat)));
}}
>
Force fold
</DevButton>
</div>
<DevButton
type="button"
variant="outline"
size="sm"
className="w-fit"
confirm
onClick={() => void run("force-street", () => forcePokerStreet(tableId))}
>
Force next street
</DevButton>
<div className="flex items-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => void run("clock-reset", () => pokerClockControl(tableId, "reset"))}
>
Reset clock
</Button>
<DevButton
type="button"
variant="outline"
size="sm"
confirm
onClick={() => void run("clock-now", () => pokerClockControl(tableId, "now"))}
>
Run timeout now
</DevButton>
</div>
<DevButton
type="button"
variant={revealOn ? "default" : "outline"}
size="sm"
className="w-fit"
onClick={() => {
const next = !revealOn;
void run(next ? "reveal-on" : "reveal-off", async () => {
const result = await setPokerRevealAll(tableId, next);
if (result.success) setRevealOn(next);
return result;
});
}}
>
{revealOn ? "Hide all hands" : "Reveal all hands"}
</DevButton>
</DevSection>
<DevSection title="Table">
<DevButton
type="button"
variant="destructive"
size="sm"
className="w-fit"
confirm
confirmLabel="Click again to end table"
onClick={() => void run("force-expire-table", () => forceExpirePokerTable(tableId))}
>
Force end table
</DevButton>
</DevSection>
</>
);
}

View file

@ -0,0 +1,190 @@
"use client";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { isAimTrainerDifficulty } from "@/lib/minigames/aim-trainer";
import {
QUALIFICATION_DEV_EVENT,
QUALIFICATION_DEV_GAME_KEY,
readQualificationDevConfig,
type QualificationDevConfig,
} from "../qualification/devConfig";
import { pushDevLog } from "./devLog";
import { clearDevSetting, writeDevSetting } from "./devSettings";
import { CopyButton, DevSection } from "./primitives";
/**
* Qualification Course controls for the shared minigame dev dock.
*
* Everything here is client-side and gameplay-only: a spawn seed makes target
* placement reproducible, the difficulty override pins the tier without
* touching the player's lane choice, and the hitbox overlay draws the exact
* head circle / torso rectangle used by hit resolution. The submitted result
* payload and its server-side validation stay exactly as they are.
*/
const DIFFICULTY_OPTIONS = [
{ value: "none", label: "None (player's lane)" },
{ value: "recruit", label: "Recruit" },
{ value: "veteran", label: "Veteran" },
{ value: "elite", label: "Elite" },
] as const;
export function QualificationDevControls() {
const [config, setConfig] = useState<QualificationDevConfig>(() => readQualificationDevConfig());
const [seedDraft, setSeedDraft] = useState(() => {
const seed = readQualificationDevConfig().seed;
return seed === null ? "" : String(seed);
});
const [error, setError] = useState<string | null>(null);
const broadcast = () => {
window.dispatchEvent(new Event(QUALIFICATION_DEV_EVENT));
};
const applySeed = () => {
const trimmed = seedDraft.trim();
if (trimmed === "") {
clearDevSetting(QUALIFICATION_DEV_GAME_KEY, "seed");
setConfig((current) => ({ ...current, seed: null }));
setError(null);
broadcast();
pushDevLog("action", "qualification: seed = cleared (random)");
return;
}
const parsed = Number(trimmed);
if (!Number.isFinite(parsed)) {
setError("Enter a whole number seed, or leave the field empty.");
return;
}
const seed = Math.trunc(parsed);
writeDevSetting(QUALIFICATION_DEV_GAME_KEY, "seed", seed);
setSeedDraft(String(seed));
setConfig((current) => ({ ...current, seed }));
setError(null);
broadcast();
pushDevLog("action", `qualification: seed = ${seed}`);
};
const applyDifficulty = (value: string) => {
if (value === "none") {
clearDevSetting(QUALIFICATION_DEV_GAME_KEY, "difficulty");
setConfig((current) => ({ ...current, difficultyOverride: null }));
broadcast();
pushDevLog("action", "qualification: difficulty = none (player's lane)");
return;
}
if (!isAimTrainerDifficulty(value)) return;
writeDevSetting(QUALIFICATION_DEV_GAME_KEY, "difficulty", value);
setConfig((current) => ({ ...current, difficultyOverride: value }));
broadcast();
pushDevLog("action", `qualification: difficulty = ${value}`);
};
const applyHitboxOverlay = (checked: boolean) => {
writeDevSetting(QUALIFICATION_DEV_GAME_KEY, "hitboxOverlay", checked);
setConfig((current) => ({ ...current, hitboxOverlay: checked }));
broadcast();
pushDevLog("action", `qualification: hitboxOverlay = ${checked}`);
};
return (
<>
<DevSection title="Spawn seed">
<div className="flex items-end gap-2">
<div className="flex flex-1 flex-col gap-1.5">
<Label
htmlFor="qualification-dev-seed"
className="text-xs font-normal text-muted-foreground"
>
Seed
</Label>
<Input
id="qualification-dev-seed"
type="number"
step={1}
inputMode="numeric"
placeholder="Random"
value={seedDraft}
onChange={(event) => {
setSeedDraft(event.target.value);
setError(null);
}}
onKeyDown={(event) => {
if (event.key !== "Enter") return;
event.preventDefault();
applySeed();
}}
className="h-8 text-xs"
/>
</div>
<Button type="button" size="sm" className="h-8" onClick={applySeed}>
Apply
</Button>
{config.seed !== null && (
<CopyButton getText={() => String(config.seed)} label="Copy seed" />
)}
</div>
<p className="text-xs text-muted-foreground">
{config.seed === null
? "Random placement. Apply a seed to make target spawns reproducible."
: `Spawn placement draws from a fixed sequence seeded with ${config.seed}. Takes effect on the next run.`}
</p>
{error && <p className="text-xs text-destructive">{error}</p>}
</DevSection>
<DevSection title="Difficulty override">
<Select value={config.difficultyOverride ?? "none"} onValueChange={applyDifficulty}>
<SelectTrigger className="h-8 text-xs" aria-label="Difficulty override">
<SelectValue placeholder="None (player's lane)" />
</SelectTrigger>
<SelectContent>
{DIFFICULTY_OPTIONS.map((option) => (
<SelectItem key={option.value} value={option.value} className="text-xs">
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
{config.difficultyOverride === null
? "The lane picked on the range card decides the tier."
: `All runs use ${config.difficultyOverride} until this is set back to none.`}
</p>
</DevSection>
<DevSection title="Overlays">
<div className="flex items-center justify-between gap-2">
<Label
htmlFor="qualification-dev-hitbox"
className="text-xs font-normal text-muted-foreground"
>
Hitbox overlay
</Label>
<Switch
id="qualification-dev-hitbox"
checked={config.hitboxOverlay}
onCheckedChange={applyHitboxOverlay}
/>
</div>
<p className="text-xs text-muted-foreground">
Draws every target&apos;s exact head circle and torso hit rectangle on the canvas.
</p>
</DevSection>
</>
);
}

View file

@ -0,0 +1,147 @@
"use client";
import { useEffect, useState } from "react";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { readDevSetting, writeDevSetting } from "./devSettings";
import { pushDevLog } from "./devLog";
import { CopyButton, DevSection } from "./primitives";
/**
* Radio Traffic controls for the shared minigame dev dock.
*
* Both toggles are client-only debugging conveniences for the solo game:
* - "Show transcript" reveals the generated ground truth beside the game.
* - "Freeze timer" pauses the sprint stopwatch and the watch countdown.
*
* Neither touches submissions: results still carry the same payload and are
* validated server side exactly as before. Frozen runs are never flagged or
* recorded differently, they are just easier to inspect.
*/
export const RADIO_DEV_GAME_KEY = "radio";
export const RADIO_DEV_SETTINGS_EVENT = "ptf:dev-settings-changed";
type RadioDevSettingKey = "showTranscript" | "freezeTimer";
/** Plain-text dump of the round's generated messages, one per line. */
export function formatTranscript(messages: readonly string[]): string {
return messages.map((message, index) => `${index + 1}. ${message}`).join("\n");
}
export function RadioDevControls({
transcript,
messageCount,
}: {
readonly transcript: string;
readonly messageCount: number;
}) {
const [showTranscript, setShowTranscript] = useState(() =>
readDevSetting(RADIO_DEV_GAME_KEY, "showTranscript", false),
);
const [freezeTimer, setFreezeTimer] = useState(() =>
readDevSetting(RADIO_DEV_GAME_KEY, "freezeTimer", false),
);
// Settings are shared with the arena, which also listens for this event, so
// the transcript panel and the paused clock follow the dock immediately.
useEffect(() => {
const sync = () => {
setShowTranscript(readDevSetting(RADIO_DEV_GAME_KEY, "showTranscript", false));
setFreezeTimer(readDevSetting(RADIO_DEV_GAME_KEY, "freezeTimer", false));
};
window.addEventListener(RADIO_DEV_SETTINGS_EVENT, sync);
return () => window.removeEventListener(RADIO_DEV_SETTINGS_EVENT, sync);
}, []);
const update = (key: RadioDevSettingKey, value: boolean) => {
writeDevSetting(RADIO_DEV_GAME_KEY, key, value);
if (key === "showTranscript") setShowTranscript(value);
else setFreezeTimer(value);
pushDevLog("action", `radio: ${key} = ${value}`);
window.dispatchEvent(new Event(RADIO_DEV_SETTINGS_EVENT));
};
return (
<>
<DevSection title="Transcript">
<Label
htmlFor="radio-dev-show-transcript"
className="flex items-center gap-2 text-xs font-normal text-muted-foreground"
>
<Switch
id="radio-dev-show-transcript"
checked={showTranscript}
onCheckedChange={(checked) => update("showTranscript", checked)}
/>
Show transcript
</Label>
<p className="text-xs text-muted-foreground">
{messageCount} message{messageCount === 1 ? "" : "s"} generated this round. The full text
renders beside the game while enabled.
</p>
<CopyButton getText={() => transcript} label="Copy transcript" className="w-fit" />
</DevSection>
<DevSection title="Timer">
<Label
htmlFor="radio-dev-freeze-timer"
className="flex items-center gap-2 text-xs font-normal text-muted-foreground"
>
<Switch
id="radio-dev-freeze-timer"
checked={freezeTimer}
onCheckedChange={(checked) => update("freezeTimer", checked)}
/>
Freeze timer
</Label>
<p className="text-xs text-muted-foreground">
Pauses the sprint stopwatch and the watch countdown. Debugging convenience only; the run
still submits the same payload.
</p>
</DevSection>
</>
);
}
/**
* Ground-truth transcript rendered next to the game (not inside the dock) so
* the operator can read the full generated round while typing.
*/
export function RadioTranscriptPanel({
messages,
messageIndex,
}: {
readonly messages: readonly string[];
readonly messageIndex: number;
}) {
return (
<div className="w-full rounded-xl border border-dashed border-amber-400/40 bg-amber-400/5 p-3">
<div className="flex items-center justify-between gap-2">
<span className="font-mono text-[10px] uppercase tracking-widest text-amber-300/80">
Dev // generated transcript
</span>
<CopyButton getText={() => formatTranscript(messages)} label="Copy transcript" />
</div>
<ol className="mt-2 max-h-56 overflow-y-auto font-mono text-[11px] leading-relaxed text-muted-foreground">
{messages.length === 0 ? (
<li className="text-muted-foreground/70">No messages generated yet.</li>
) : (
messages.map((message, index) => (
<li
key={`${index}-${message}`}
aria-current={index === messageIndex ? "step" : undefined}
className={index === messageIndex ? "text-foreground" : undefined}
>
<span className="tabular-nums opacity-60">{String(index + 1).padStart(2, "0")}</span>{" "}
{message}
</li>
))
)}
</ol>
<p className="mt-1.5 text-[10px] text-muted-foreground/70">
Watch mode appends transmissions as the round generates them.
</p>
</div>
);
}

View file

@ -0,0 +1,128 @@
"use client";
import { useState } from "react";
import type { VersusAdminCommand } from "@/app/(frontend)/minigames/call-for-fire-versus/actions";
import {
forceExpireVersusMatch,
versusAdminCommand,
} from "@/app/(frontend)/minigames/call-for-fire-versus/actions";
import type { VersusMatchView } from "@/lib/minigames/call-for-fire-versus/types";
import { Button } from "@/components/ui/button";
import { pushDevLog } from "./devLog";
import { DevButton, DevSection } from "./primitives";
/**
* Call for Fire: Versus controls for the shared minigame dev dock. Reveal
* fleets flips a match-level flag so views.ts serves both fleets to everyone
* (the revealed layout shows up in this dock's State tab); force shot result
* arms a one-shot override the acting player's next round consumes; skip turn
* passes the clock; force expire tears the match down. Sync rides the existing
* polling path every versus client already runs.
*/
interface VersusDevControlsProps {
readonly matchId: string;
readonly match: VersusMatchView;
}
export function VersusDevControls({ matchId, match }: VersusDevControlsProps) {
const [error, setError] = useState<string | null>(null);
const revealOn = match.opponentFleet !== undefined;
const send = async (cmd: VersusAdminCommand) => {
pushDevLog("action", `cff-versus: ${cmd.kind} sent`);
try {
const result = await versusAdminCommand(matchId, cmd);
if (!result.success) {
const message = result.error ?? "The admin command failed.";
setError(message);
pushDevLog("error", `cff-versus: ${cmd.kind} failed (${message})`);
} else {
setError(null);
pushDevLog("action", `cff-versus: ${cmd.kind} applied`);
}
} catch (caught) {
const message = caught instanceof Error ? caught.message : "The admin command failed.";
setError(message);
pushDevLog("error", `cff-versus: ${cmd.kind} threw (${message})`);
}
};
return (
<>
{error && <p className="text-sm text-destructive">{error}</p>}
<DevSection title="Hidden information">
<Button
type="button"
variant={revealOn ? "default" : "outline"}
size="sm"
className="w-fit"
onClick={() => void send({ kind: "revealFleets", on: !revealOn })}
>
{revealOn ? "Hide fleets" : "Reveal fleets"}
</Button>
<p className="text-xs text-muted-foreground">
While revealed, every snapshot carries both fleets; inspect them in
the State tab.
</p>
</DevSection>
<DevSection title="Force next shot result">
<p className="text-xs text-muted-foreground">
Arms a one-shot override for the acting player&apos;s next round:
&quot;hit&quot; snaps an errant round onto the nearest un-struck enemy
cell, &quot;miss&quot; suppresses damage even on a struck cell.
</p>
<div className="flex items-center gap-2">
<Button type="button" variant="outline" size="sm" onClick={() => void send({ kind: "forceShotResult", outcome: "hit" })}>
Force hit
</Button>
<Button type="button" variant="outline" size="sm" onClick={() => void send({ kind: "forceShotResult", outcome: "miss" })}>
Force miss
</Button>
<Button type="button" variant="ghost" size="sm" onClick={() => void send({ kind: "forceShotResult", outcome: null })}>
Clear
</Button>
</div>
</DevSection>
<DevSection title="Turn clock">
<DevButton
type="button"
variant="outline"
size="sm"
className="w-fit"
confirm
disabled={match.turnUserId === null}
onClick={() => void send({ kind: "skipTurn" })}
>
Skip current turn
</DevButton>
</DevSection>
<DevSection title="Match">
<DevButton
type="button"
variant="destructive"
size="sm"
className="w-fit"
confirm
confirmLabel="Click again to expire match"
onClick={async () => {
pushDevLog("action", "cff-versus: force-expire-match sent");
const result = await forceExpireVersusMatch(matchId);
pushDevLog(
result.success ? "action" : "error",
result.success
? "cff-versus: force-expire-match applied"
: `cff-versus: force-expire-match failed (${result.error ?? "unknown"})`,
);
}}
>
Force expire match
</DevButton>
</DevSection>
</>
);
}

View file

@ -0,0 +1,86 @@
/**
* Client-side dev console log for the minigame developer dock.
*
* A module-level ring buffer (newest last, capped at MAX_ENTRIES) shared by
* every panel in the dock: game panels push entries when they send actions,
* the dock itself pushes snapshot-received entries, and the Log tab renders
* the buffer live. Optional console mirroring writes each entry to
* `console.debug` as well so a devtools console tells the same story.
*/
export type DevLogKind = "info" | "action" | "state" | "error";
export interface DevLogEntry {
readonly id: number;
/** ISO instant the entry was recorded. */
readonly at: string;
readonly kind: DevLogKind;
readonly text: string;
}
const MAX_ENTRIES = 200;
const MIRROR_KEY = "ptf.dev.consoleMirror";
let entries: DevLogEntry[] = [];
let nextId = 1;
const listeners = new Set<() => void>();
function readMirrorFlag(): boolean {
if (typeof window === "undefined") return false;
try {
return window.localStorage.getItem(MIRROR_KEY) === "1";
} catch {
return false;
}
}
let mirror = readMirrorFlag();
function emit(): void {
for (const listener of listeners) listener();
}
/** Append an entry, dropping the oldest when the buffer is full. */
export function pushDevLog(kind: DevLogKind, text: string): void {
const entry: DevLogEntry = { id: nextId++, at: new Date().toISOString(), kind, text };
entries = [...entries, entry].slice(-MAX_ENTRIES);
if (mirror) console.debug(`[dev-console] ${kind}: ${text}`);
emit();
}
export function clearDevLog(): void {
if (entries.length === 0) return;
entries = [];
emit();
}
/** Stable snapshot reference for useSyncExternalStore (replaced on every push). */
export function getDevLogEntries(): readonly DevLogEntry[] {
return entries;
}
export function subscribeDevLog(listener: () => void): () => void {
listeners.add(listener);
return () => listeners.delete(listener);
}
export function isDevLogMirrored(): boolean {
return mirror;
}
export function setDevLogMirror(on: boolean): void {
mirror = on;
if (typeof window !== "undefined") {
try {
window.localStorage.setItem(MIRROR_KEY, on ? "1" : "0");
} catch {
// Storage unavailable (private mode): the flag just stays session-only.
}
}
emit();
}
/** Plain-text dump of the whole buffer, newest last. */
export function formatDevLog(entriesToFormat: readonly DevLogEntry[] = entries): string {
return entriesToFormat.map((entry) => `${entry.at} [${entry.kind}] ${entry.text}`).join("\n");
}

View file

@ -0,0 +1,48 @@
/**
* localStorage-backed per-game developer settings for the minigame dev dock.
*
* Two consumers:
* - The dock itself persists its UI state (open/collapsed, active tab).
* - Games read tuning overrides at parameter sites (Phase 2 sliders: flappy
* gravity/speed/pipe-gap, aim-trainer seeds, etc.). Values are namespaced
* per game key so one game's overrides never leak into another.
*
* Everything degrades to the caller's fallback when storage is unavailable
* (private mode, SSR render): dev tooling must never break a game page.
*/
const PREFIX = "ptf.dev";
function storageKey(gameKey: string, key: string): string {
return `${PREFIX}.${gameKey}.${key}`;
}
export function readDevSetting<T>(gameKey: string, key: string, fallback: T): T {
if (typeof window === "undefined") return fallback;
try {
const raw = window.localStorage.getItem(storageKey(gameKey, key));
if (raw === null) return fallback;
return JSON.parse(raw) as T;
} catch {
return fallback;
}
}
export function writeDevSetting(gameKey: string, key: string, value: unknown): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(storageKey(gameKey, key), JSON.stringify(value));
} catch {
// Storage full or blocked: the setting simply does not persist.
}
}
/** Remove one override so the next read falls back to the game default. */
export function clearDevSetting(gameKey: string, key: string): void {
if (typeof window === "undefined") return;
try {
window.localStorage.removeItem(storageKey(gameKey, key));
} catch {
// Nothing to do when storage is unavailable.
}
}

View file

@ -0,0 +1,123 @@
"use client";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { Copy, Check } from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
/**
* Shared building blocks for minigame developer panels. The section chrome
* matches the original PokerDevPanel look (bordered box, uppercase header) so
* every game's dev controls read as one surface.
*/
export function DevSection({
title,
children,
className,
}: {
readonly title: string;
readonly children?: ReactNode;
readonly className?: string;
}) {
return (
<section className={cn("flex flex-col gap-2 border border-border p-3", className)}>
<h3 className="text-xs font-semibold uppercase tracking-wider">{title}</h3>
{children}
</section>
);
}
interface DevButtonProps extends React.ComponentProps<typeof Button> {
/** Destructive actions arm on the first click and fire on the second. */
readonly confirm?: boolean;
readonly confirmLabel?: string;
}
export function DevButton({
confirm = false,
confirmLabel = "Click again to confirm",
onClick,
children,
className,
...rest
}: DevButtonProps) {
const [armed, setArmed] = useState(false);
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(
() => () => {
if (timerRef.current) clearTimeout(timerRef.current);
},
[],
);
return (
<Button
{...rest}
className={cn(className)}
onClick={(event) => {
if (!confirm) {
onClick?.(event);
return;
}
if (!armed) {
setArmed(true);
if (timerRef.current) clearTimeout(timerRef.current);
timerRef.current = setTimeout(() => setArmed(false), 3000);
return;
}
setArmed(false);
if (timerRef.current) clearTimeout(timerRef.current);
onClick?.(event);
}}
>
{armed ? confirmLabel : children}
</Button>
);
}
/** Small copy-to-clipboard icon button with a brief "copied" confirmation. */
export function CopyButton({
getText,
label,
className,
}: {
readonly getText: () => string;
readonly label?: string;
readonly className?: string;
}) {
const [copied, setCopied] = useState(false);
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(
() => () => {
if (timerRef.current) clearTimeout(timerRef.current);
},
[],
);
return (
<Button
type="button"
variant="outline"
size="sm"
className={cn("h-7 gap-1 px-2 text-xs", className)}
aria-label={label ?? "Copy to clipboard"}
title={label ?? "Copy to clipboard"}
onClick={() => {
void navigator.clipboard
?.writeText(getText())
.then(() => {
setCopied(true);
if (timerRef.current) clearTimeout(timerRef.current);
timerRef.current = setTimeout(() => setCopied(false), 1500);
})
.catch(() => undefined);
}}
>
{copied ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}
{copied ? "Copied" : label ?? "Copy"}
</Button>
);
}

View file

@ -0,0 +1,31 @@
"use client";
import { useSyncExternalStore } from "react";
import {
clearDevLog,
formatDevLog,
getDevLogEntries,
isDevLogMirrored,
pushDevLog,
setDevLogMirror,
subscribeDevLog,
type DevLogEntry,
type DevLogKind,
} from "./devLog";
export type { DevLogEntry, DevLogKind };
export { clearDevLog, formatDevLog, isDevLogMirrored, pushDevLog, setDevLogMirror };
/**
* The dock's live view over the dev console ring buffer. Panels outside the
* dock tree can import `pushDevLog` directly from ./devLog; this hook is the
* React binding used by the Log tab.
*/
export function useDevLog(): {
readonly entries: readonly DevLogEntry[];
readonly push: (kind: DevLogKind, text: string) => void;
readonly clear: () => void;
} {
const entries = useSyncExternalStore(subscribeDevLog, getDevLogEntries, getDevLogEntries);
return { entries, push: pushDevLog, clear: clearDevLog };
}

View file

@ -15,9 +15,11 @@ import { MinesweeperBoard } from "./MinesweeperBoard";
export function EodArena({
initialStats,
currentUserId,
isSuperuser = false,
}: {
initialStats: EodStats;
currentUserId: number | string;
isSuperuser?: boolean;
}) {
const [refreshKey, setRefreshKey] = useState(0);
const [playing, setPlaying] = useState(false);
@ -65,6 +67,7 @@ export function EodArena({
onGameRecorded={() => setRefreshKey((key) => key + 1)}
onPhaseChange={onPhaseChange}
onDifficultyChange={setSelectedDifficulty}
isSuperuser={isSuperuser}
/>
<PeriodStandingsCard
gameKey="eod"

View file

@ -2,7 +2,15 @@
// allow: SIZE_OK — the board is a single interactive game state machine required by the route contract.
import { useCallback, useEffect, useRef, useState, type CSSProperties, type PointerEvent } from "react";
import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
type CSSProperties,
type PointerEvent,
} from "react";
import { Bomb, Flag, RotateCcw, ShieldCheck, Timer, X } from "lucide-react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
@ -21,6 +29,14 @@ import { useSessionExpired } from "@/hooks/useSessionExpired";
import { LoginLink } from "@/components/frontend/auth/LoginLink";
import { cn } from "@/lib/utils";
import { isEodUnlocked } from "@/lib/minigames/custom/eod";
import { MinigameDevDock } from "@/components/frontend/minigames/dev/MinigameDevDock";
import { readDevSetting } from "@/components/frontend/minigames/dev/devSettings";
import { pushDevLog } from "@/components/frontend/minigames/dev/devLog";
import {
DEV_SETTINGS_CHANGED_EVENT,
EOD_DEV_GAME_KEY,
EodDevControls,
} from "@/components/frontend/minigames/dev/EodDevControls";
import { playClear, playExplosion, playFlag, playReveal, playXp } from "./sounds";
type Phase = "ready" | "playing" | "over";
@ -136,12 +152,29 @@ function neighbors(index: number, rows: number, cols: number): number[] {
return nearby;
}
function createBoard(config: GameConfig, safeIndex: number): Board {
/**
* Deterministic PRNG (mulberry32) used only when a developer seed is set.
* Without a seed, board generation keeps calling Math.random(), so normal play
* is byte-for-byte the same behavior as before.
*/
function mulberry32(seed: number): () => number {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;
let value = state;
value = Math.imul(value ^ (value >>> 15), value | 1);
value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
return ((value ^ (value >>> 14)) >>> 0) / 4_294_967_296;
};
}
function createBoard(config: GameConfig, safeIndex: number, seed: number | null = null): Board {
const size = config.rows * config.cols;
const safe = new Set([safeIndex, ...neighbors(safeIndex, config.rows, config.cols)]);
const random = seed === null ? Math.random : mulberry32(seed);
const mines = new Set<number>();
while (mines.size < config.mines) {
const candidate = Math.floor(Math.random() * size);
const candidate = Math.floor(random() * size);
if (!safe.has(candidate)) mines.add(candidate);
}
const mined = emptyBoard(size).map((cell, index) => ({ ...cell, mine: mines.has(index) }));
@ -192,11 +225,13 @@ export function MinesweeperBoard({
onGameRecorded,
onPhaseChange,
onDifficultyChange,
isSuperuser = false,
}: {
initialStats: EodStats;
onGameRecorded: () => void;
onPhaseChange: (phase: Phase) => void;
onDifficultyChange: (difficulty: EodDifficulty) => void;
isSuperuser?: boolean;
}) {
const router = useRouter();
const { expired, expiredRef } = useSessionExpired();
@ -220,6 +255,10 @@ export function MinesweeperBoard({
const [isMobile, setIsMobile] = useState(false);
const [isLandscape, setIsLandscape] = useState(false);
const [isNarrow, setIsNarrow] = useState(false);
const [devRevealLayout, setDevRevealLayout] = useState(false);
const [devDigAnywhere, setDevDigAnywhere] = useState(false);
const [devSeed, setDevSeed] = useState<number | null>(null);
const devSeedRef = useRef<number | null>(null);
const generatedRef = useRef(false);
const previousViewportRef = useRef<string | null>(null);
const submittingRef = useRef(false);
@ -304,6 +343,34 @@ export function MinesweeperBoard({
[customConfig, difficulty, expiredRef, isLandscape, isMobile, onDifficultyChange, setPhaseSafe],
);
// The dev dock persists its overrides in localStorage and announces each
// change; the board re-reads them here so a toggle lands without prop
// plumbing. These settings only affect local rendering and click handling,
// never the submitted result payload.
const resetRef = useRef(reset);
useEffect(() => {
resetRef.current = reset;
}, [reset]);
useEffect(() => {
const applyDevSettings = () => {
setDevRevealLayout(readDevSetting(EOD_DEV_GAME_KEY, "revealLayout", false));
setDevDigAnywhere(readDevSetting(EOD_DEV_GAME_KEY, "digAnywhere", false));
const stored = readDevSetting<number | null>(EOD_DEV_GAME_KEY, "seed", null);
const nextSeed =
typeof stored === "number" && Number.isFinite(stored) ? Math.trunc(stored) : null;
if (devSeedRef.current === nextSeed) return;
devSeedRef.current = nextSeed;
setDevSeed(nextSeed);
// A seed is consumed when the field is generated on the first dig, so
// restart the sector to make the change visible right away.
resetRef.current();
};
applyDevSettings();
window.addEventListener(DEV_SETTINGS_CHANGED_EVENT, applyDevSettings);
return () => window.removeEventListener(DEV_SETTINGS_CHANGED_EVENT, applyDevSettings);
}, []);
useEffect(() => {
const viewportKey = `${isMobile}-${isLandscape}`;
if (previousViewportRef.current === null) {
@ -443,18 +510,32 @@ export function MinesweeperBoard({
if (expiredRef.current) return;
const existing = board[index];
if (!existing || existing.flagged || existing.revealed) return;
const workingBoard = generatedRef.current ? board : createBoard(config, index);
const workingBoard = generatedRef.current ? board : createBoard(config, index, devSeed);
generatedRef.current = true;
const cell = workingBoard[index];
if (!cell) return;
if (phase === "ready") setPhaseSafe("playing");
if (cell.mine) {
finishGame(
false,
workingBoard.map((item, cellIndex) =>
cellIndex === index ? { ...item, exploded: true } : item,
),
if (!devDigAnywhere) {
finishGame(
false,
workingBoard.map((item, cellIndex) =>
cellIndex === index ? { ...item, exploded: true } : item,
),
);
return;
}
// Dev tool: "dig anywhere" clears the charge instead of ending the run.
// Local to this client; the submitted payload keeps its normal shape.
const row = Math.floor(index / config.cols) + 1;
const col = (index % config.cols) + 1;
pushDevLog("action", `eod: dig-anywhere cleared a charge at row ${row} col ${col}`);
playReveal();
const safeBoard = workingBoard.map((item, cellIndex) =>
cellIndex === index ? { ...item, revealed: true } : item,
);
setBoard(safeBoard);
if (safeBoard.every((item) => item.mine || item.revealed)) finishGame(true, safeBoard);
return;
}
playReveal();
@ -462,7 +543,7 @@ export function MinesweeperBoard({
setBoard(nextBoard);
if (nextBoard.every((item) => item.mine || item.revealed)) finishGame(true, nextBoard);
},
[board, config, expiredRef, finishGame, phase, setPhaseSafe],
[board, config, devDigAnywhere, devSeed, expiredRef, finishGame, phase, setPhaseSafe],
);
const toggleFlag = useCallback(
@ -492,6 +573,42 @@ export function MinesweeperBoard({
(count, cell) => count + (cell.incorrectFlagged ? 1 : 0),
0,
);
// Cheap plain-object view of the live board for the dev dock State tab.
const devSnapshot = useMemo(
() => ({
phase,
difficulty,
sector: config.label,
grid: { rows: config.rows, cols: config.cols },
cells: board.length,
revealed: board.reduce((count, cell) => count + (cell.revealed ? 1 : 0), 0),
flagged: flaggedCount,
mines: config.mines,
minesRemaining: config.mines - flaggedCount,
seconds,
dev: {
revealLayout: devRevealLayout,
digAnywhere: devDigAnywhere,
seed: devSeed,
},
}),
[
board,
config.cols,
config.label,
config.mines,
config.rows,
devDigAnywhere,
devRevealLayout,
devSeed,
difficulty,
flaggedCount,
phase,
seconds,
],
);
const statusClass =
phase === "over"
? lastRun?.won
@ -555,6 +672,10 @@ export function MinesweeperBoard({
"border-amber-300 bg-amber-500/25 text-amber-200 shadow-[inset_0_1px_0_rgb(255_255_255_/_0.14),0_1px_2px_rgb(0_0_0_/_0.35)]",
revealedMine && "border-destructive bg-destructive/30 text-red-300",
cell.exploded && "border-destructive bg-destructive text-destructive-foreground",
devRevealLayout &&
cell.mine &&
!cell.revealed &&
"ring-2 ring-inset ring-red-500/80",
cell.revealed && cell.adjacent > 0 && NUMBER_CLASSES[cell.adjacent],
)}
onClick={() => {
@ -915,6 +1036,10 @@ export function MinesweeperBoard({
revealedMine && "border-destructive bg-destructive/30 text-red-300",
cell.exploded &&
"border-destructive bg-destructive text-destructive-foreground",
devRevealLayout &&
cell.mine &&
!cell.revealed &&
"ring-2 ring-inset ring-red-500/80",
cell.revealed && cell.adjacent > 0 && NUMBER_CLASSES[cell.adjacent],
)}
onClick={() => {
@ -1001,6 +1126,15 @@ export function MinesweeperBoard({
<span className="font-semibold text-foreground">{stats.eodXp}</span>
</div>
</div>
<MinigameDevDock
isSuperuser={isSuperuser}
gameKey={EOD_DEV_GAME_KEY}
gameLabel="Minefield Clearance"
snapshot={devSnapshot}
>
<EodDevControls />
</MinigameDevDock>
</div>
);
}

View file

@ -11,9 +11,11 @@ import { FlappyLeaderboard } from "./FlappyLeaderboard";
export function FlappyArena({
initialStats,
currentUserId,
isSuperuser = false,
}: {
initialStats: FlappyStats;
currentUserId: number | string;
isSuperuser?: boolean;
}) {
const [refreshKey, setRefreshKey] = useState(0);
@ -25,7 +27,12 @@ export function FlappyArena({
return (
<div className="flex flex-col items-center gap-6">
<FlappyBird initialStats={initialStats} onGameRecorded={() => setRefreshKey((k) => k + 1)} onPhaseChange={onPhaseChange} />
<FlappyBird
initialStats={initialStats}
onGameRecorded={() => setRefreshKey((k) => k + 1)}
onPhaseChange={onPhaseChange}
isSuperuser={isSuperuser}
/>
<PeriodStandingsCard
gameKey="flappy"
icon="Bird"
@ -34,7 +41,11 @@ export function FlappyArena({
presence={{ participants: activePilots, noun: "pilot" }}
/>
<AllTimeLeaderboard className="max-w-[420px]">
<FlappyLeaderboard refreshKey={refreshKey} currentUserId={currentUserId} activePilots={activePilots} />
<FlappyLeaderboard
refreshKey={refreshKey}
currentUserId={currentUserId}
activePilots={activePilots}
/>
</AllTimeLeaderboard>
</div>
);

View file

@ -7,7 +7,10 @@ import { type FlappyStats, submitFlappyScore } from "@/app/(frontend)/minigames/
import { PROFILE_UPDATE_EVENT } from "@/hooks/useGameTick";
import { useSessionExpired } from "@/hooks/useSessionExpired";
import { LoginLink } from "@/components/frontend/auth/LoginLink";
import { FlappyDevControls } from "@/components/frontend/minigames/dev/FlappyDevControls";
import { MinigameDevDock } from "@/components/frontend/minigames/dev/MinigameDevDock";
import { Button } from "@/components/ui/button";
import { FLAPPY_DEV_EVENT, readFlappyDevConfig, type FlappyDevConfig } from "./devConfig";
import { playFlap, playHit, playXp } from "./sounds";
const CANVAS_W = 420;
@ -28,6 +31,20 @@ const PASSES_PER_XP = 15;
const RAMP_SECONDS = 60;
const MAX_SPEED_SCALE = 2;
/**
* Dev-tool defaults. The module constants above stay the source of truth;
* overrides come from localStorage through the dev dock and can never widen
* past the ranges in `devConfig.ts`.
*/
const DEFAULT_DEV_CONFIG: FlappyDevConfig = {
gravity: GRAVITY,
pipeSpeed: PIPE_SPEED,
pipeGap: PIPE_GAP,
paused: false,
invincible: false,
fpsOverlay: false,
};
const STARS = Array.from({ length: 70 }, (_, i) => ({
x: (i * 97) % CANVAS_W,
y: (i * 53) % (CANVAS_H - GROUND_H),
@ -145,8 +162,8 @@ function drawTopBuilding(ctx: CanvasRenderingContext2D, p: Pipe, light: number)
}
}
function drawBuilding(ctx: CanvasRenderingContext2D, p: Pipe, light: number) {
const bottomY = p.gapY + PIPE_GAP;
function drawBuilding(ctx: CanvasRenderingContext2D, p: Pipe, light: number, pipeGap: number) {
const bottomY = p.gapY + pipeGap;
const h = GROUND_Y - bottomY;
if (h <= 2) return;
const x = p.x;
@ -190,9 +207,9 @@ function drawBuilding(ctx: CanvasRenderingContext2D, p: Pipe, light: number) {
}
}
function drawObstacle(ctx: CanvasRenderingContext2D, p: Pipe, light: number) {
function drawObstacle(ctx: CanvasRenderingContext2D, p: Pipe, light: number, pipeGap: number) {
drawTopBuilding(ctx, p, light);
drawBuilding(ctx, p, light);
drawBuilding(ctx, p, light, pipeGap);
}
function drawCloud(ctx: CanvasRenderingContext2D, c: Cloud, light: number) {
@ -392,10 +409,10 @@ function drawHelicopter(
ctx.restore();
}
function birdHitsPipe(birdX: number, birdY: number, pipe: Pipe): boolean {
function birdHitsPipe(birdX: number, birdY: number, pipe: Pipe, pipeGap: number): boolean {
if (birdX + BIRD_R < pipe.x || birdX - BIRD_R > pipe.x + PIPE_W) return false;
const topBlocked = birdY - BIRD_R < pipe.gapY;
const bottomBlocked = birdY + BIRD_R > pipe.gapY + PIPE_GAP;
const bottomBlocked = birdY + BIRD_R > pipe.gapY + pipeGap;
return topBlocked || bottomBlocked;
}
@ -403,16 +420,21 @@ export function FlappyBird({
initialStats: serverStats,
onGameRecorded,
onPhaseChange,
isSuperuser = false,
}: {
initialStats: FlappyStats;
onGameRecorded?: () => void;
onPhaseChange?: (phase: Phase) => void;
isSuperuser?: boolean;
}) {
const router = useRouter();
const { expired, expiredRef } = useSessionExpired();
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const wrapperRef = useRef<HTMLDivElement | null>(null);
const phaseRef = useRef<Phase>("ready");
const devConfigRef = useRef<FlappyDevConfig>(DEFAULT_DEV_CONFIG);
const fpsRef = useRef(0);
const fpsTextRef = useRef<HTMLSpanElement | null>(null);
const gameRef = useRef<GameState>({
birdY: START_Y,
birdVy: 0,
@ -432,6 +454,7 @@ export function FlappyBird({
const [phase, setPhase] = useState<Phase>("ready");
const [score, setScore] = useState(0);
const [devConfig, setDevConfig] = useState<FlappyDevConfig>(DEFAULT_DEV_CONFIG);
const [stats, setStats] = useState<FlappyStats>(serverStats);
const [lastRun, setLastRun] = useState<{
score: number;
@ -441,11 +464,14 @@ export function FlappyBird({
} | null>(null);
const [submitting, setSubmitting] = useState(false);
const setPhaseSafe = useCallback((p: Phase) => {
phaseRef.current = p;
setPhase(p);
onPhaseChange?.(p);
}, [onPhaseChange]);
const setPhaseSafe = useCallback(
(p: Phase) => {
phaseRef.current = p;
setPhase(p);
onPhaseChange?.(p);
},
[onPhaseChange],
);
const reset = useCallback(() => {
if (expiredRef.current) return;
@ -465,6 +491,26 @@ export function FlappyBird({
setPhaseSafe("ready");
}, [setPhaseSafe]);
// Dev overrides resolve once on mount, then re-read on every dock broadcast.
// The rAF loop consumes the ref, so a change lands on the next frame without
// restarting the run. Non-superusers always run the defaults, even if this
// browser still holds settings from an earlier dev session.
useEffect(() => {
if (!isSuperuser) {
devConfigRef.current = DEFAULT_DEV_CONFIG;
setDevConfig(DEFAULT_DEV_CONFIG);
return;
}
const sync = () => {
const next = readFlappyDevConfig(DEFAULT_DEV_CONFIG);
devConfigRef.current = next;
setDevConfig(next);
};
sync();
window.addEventListener(FLAPPY_DEV_EVENT, sync);
return () => window.removeEventListener(FLAPPY_DEV_EVENT, sync);
}, [isSuperuser]);
const handleGameOver = useCallback(
async (finalScore: number, durationMs: number) => {
if (submittingRef.current) return;
@ -527,6 +573,10 @@ export function FlappyBird({
const flap = useCallback(() => {
if (expiredRef.current) return;
// Pause is a dev switch, not a game phase: input is ignored entirely while
// paused so a tap cannot queue a flap (or start a fresh run) that fires the
// moment the simulation resumes.
if (devConfigRef.current.paused) return;
const p = phaseRef.current;
if (p === "ready") {
const g = gameRef.current;
@ -557,14 +607,15 @@ export function FlappyBird({
let raf = 0;
let lastTime = performance.now();
let frameCount = 0;
let fpsWindowStart = lastTime;
const die = () => {
const g = gameRef.current;
setPhaseSafe("over");
playHit();
const startedAt = runStartedAtRef.current;
const durationMs =
startedAt > 0 ? Math.max(1, Math.round(performance.now() - startedAt)) : 1;
const durationMs = startedAt > 0 ? Math.max(1, Math.round(performance.now() - startedAt)) : 1;
handleGameOverRef.current(g.score, durationMs);
};
@ -574,57 +625,85 @@ export function FlappyBird({
lastTime = now;
const g = gameRef.current;
const p = phaseRef.current;
const dev = devConfigRef.current;
// FPS is sampled twice a second. The number lives in a ref and is written
// straight to the overlay's text node, so an enabled overlay never causes
// a React render per sample.
frameCount += 1;
if (now - fpsWindowStart >= 500) {
const elapsed = now - fpsWindowStart;
fpsRef.current = Math.round((frameCount * 1000) / elapsed);
frameCount = 0;
fpsWindowStart = now;
if (dev.fpsOverlay && fpsTextRef.current) {
fpsTextRef.current.textContent = String(fpsRef.current);
}
}
if (p === "ready") {
g.wingT += dt;
} else if (p === "playing") {
g.wingT += dt;
g.runTime += dt;
g.cycleT += dt / 60;
const speedScale = Math.min(1 + g.runTime / RAMP_SECONDS, MAX_SPEED_SCALE);
g.birdVy = Math.min(g.birdVy + GRAVITY * dt, MAX_VY);
g.birdY += g.birdVy * dt;
g.groundOffset = (g.groundOffset + PIPE_SPEED * dt * speedScale) % 24;
// Pause freezes gameplay physics only. Rendering continues (rotor,
// clouds, flock, FPS) so the canvas stays live and a paused frame is
// still inspectable.
if (!dev.paused) {
g.runTime += dt;
g.cycleT += dt / 60;
const speedScale = Math.min(1 + g.runTime / RAMP_SECONDS, MAX_SPEED_SCALE);
g.birdVy = Math.min(g.birdVy + dev.gravity * dt, MAX_VY);
g.birdY += g.birdVy * dt;
g.groundOffset = (g.groundOffset + dev.pipeSpeed * dt * speedScale) % 24;
if (g.pipes.length === 0 || g.pipes[g.pipes.length - 1].x < CANVAS_W - PIPE_SPACING) {
const margin = 40;
const maxGapY = GROUND_Y - PIPE_GAP - margin;
g.pipes.push({
x: CANVAS_W,
gapY: margin + Math.random() * (maxGapY - margin),
scored: false,
seed: Math.floor(Math.random() * 1000),
});
}
for (const pipe of g.pipes) pipe.x -= PIPE_SPEED * dt * speedScale;
let passed = 0;
for (const pipe of g.pipes) {
if (!pipe.scored && pipe.x + PIPE_W < BIRD_X - BIRD_R) {
pipe.scored = true;
passed += 1;
if (g.pipes.length === 0 || g.pipes[g.pipes.length - 1].x < CANVAS_W - PIPE_SPACING) {
const margin = 40;
const maxGapY = GROUND_Y - dev.pipeGap - margin;
g.pipes.push({
x: CANVAS_W,
gapY: margin + Math.random() * (maxGapY - margin),
scored: false,
seed: Math.floor(Math.random() * 1000),
});
}
}
if (passed > 0) {
g.score += passed;
setScore(g.score);
}
g.pipes = g.pipes.filter((pipe) => pipe.x + PIPE_W > -20);
for (const pipe of g.pipes) pipe.x -= dev.pipeSpeed * dt * speedScale;
if (g.birdY + BIRD_R > GROUND_Y) {
die();
return;
}
if (g.birdY - BIRD_R < 0) {
g.birdY = BIRD_R;
g.birdVy = 0;
}
for (const pipe of g.pipes) {
if (birdHitsPipe(BIRD_X, g.birdY, pipe)) {
die();
return;
let passed = 0;
for (const pipe of g.pipes) {
if (!pipe.scored && pipe.x + PIPE_W < BIRD_X - BIRD_R) {
pipe.scored = true;
passed += 1;
}
}
if (passed > 0) {
g.score += passed;
setScore(g.score);
}
g.pipes = g.pipes.filter((pipe) => pipe.x + PIPE_W > -20);
if (g.birdY + BIRD_R > GROUND_Y) {
if (!dev.invincible) {
die();
return;
}
// Invincible still respects the floor: rest on it instead of
// falling out of the world, then let input fly back up.
g.birdY = GROUND_Y - BIRD_R;
g.birdVy = 0;
}
if (g.birdY - BIRD_R < 0) {
g.birdY = BIRD_R;
g.birdVy = 0;
}
if (!dev.invincible) {
for (const pipe of g.pipes) {
if (birdHitsPipe(BIRD_X, g.birdY, pipe, dev.pipeGap)) {
die();
return;
}
}
}
}
}
@ -726,7 +805,7 @@ export function FlappyBird({
for (const c of g.clouds) drawCloud(ctx, c, light);
if (g.flock) drawFlock(ctx, g.flock, light);
for (const pipe of g.pipes) drawObstacle(ctx, pipe, light);
for (const pipe of g.pipes) drawObstacle(ctx, pipe, light, dev.pipeGap);
ctx.fillStyle = mix([11, 15, 20], [100, 116, 139], light);
ctx.fillRect(0, GROUND_Y, CANVAS_W, GROUND_H);
@ -860,6 +939,18 @@ export function FlappyBird({
</LoginLink>
</div>
)}
{devConfig.paused && (
<div className="pointer-events-none absolute left-2 top-2 rounded-sm bg-black/60 px-1.5 py-0.5 font-mono text-[10px] font-semibold uppercase tracking-wider text-amber-300">
Paused (dev)
</div>
)}
{devConfig.fpsOverlay && (
<div className="pointer-events-none absolute right-2 top-2 rounded-sm bg-black/60 px-1.5 py-0.5 font-mono text-[10px] tabular-nums text-emerald-300">
<span ref={fpsTextRef}>{fpsRef.current}</span> FPS
</div>
)}
</div>
<div className="flex flex-wrap justify-center gap-6 text-sm text-muted-foreground">
@ -880,6 +971,34 @@ export function FlappyBird({
<span className="font-semibold text-foreground">{stats.flappyXp}</span>
</div>
</div>
{isSuperuser && (
<MinigameDevDock
isSuperuser={isSuperuser}
gameKey="flappy"
gameLabel="Flight Simulator"
snapshot={{
phase,
score,
best: stats.bestScore,
lastRun: lastRun ? { score: lastRun.score, xpEarned: lastRun.xpEarned } : null,
submitting,
fps: fpsRef.current,
resolved: {
gravity: devConfig.gravity,
pipeSpeed: devConfig.pipeSpeed,
pipeGap: devConfig.pipeGap,
},
dev: {
paused: devConfig.paused,
invincible: devConfig.invincible,
fpsOverlay: devConfig.fpsOverlay,
},
}}
>
<FlappyDevControls defaults={DEFAULT_DEV_CONFIG} />
</MinigameDevDock>
)}
</div>
);
}

View file

@ -0,0 +1,59 @@
/**
* Client-side developer tuning schema for the Flight Simulator (flappy).
*
* `FlappyBird.tsx` keeps the module constants as the source of defaults; this
* module only adds the dev override shape: the slider ranges, the live-reload
* event name, and a guarded reader. Every value read from localStorage is
* clamped to its range (or rejected for toggles), so a corrupted or
* hand-edited entry can never break a run.
*/
import { readDevSetting } from "../dev/devSettings";
/** Dispatched on window after every dev control change; games re-read on it. */
export const FLAPPY_DEV_EVENT = "ptf:dev-settings-changed";
/** Settings namespace, matching the dock's `gameKey`. */
export const FLAPPY_DEV_GAME_KEY = "flappy";
export interface FlappyDevConfig {
readonly gravity: number;
readonly pipeSpeed: number;
readonly pipeGap: number;
readonly paused: boolean;
readonly invincible: boolean;
readonly fpsOverlay: boolean;
}
export const FLAPPY_DEV_RANGES = {
gravity: { min: 0.1, max: 1, step: 0.01 },
pipeSpeed: { min: 0.5, max: 4, step: 0.05 },
pipeGap: { min: 80, max: 260, step: 1 },
} as const;
function readNumber(
key: string,
fallback: number,
range: { readonly min: number; readonly max: number },
): number {
const raw = readDevSetting<unknown>(FLAPPY_DEV_GAME_KEY, key, fallback);
if (typeof raw !== "number" || !Number.isFinite(raw)) return fallback;
return Math.min(range.max, Math.max(range.min, raw));
}
function readFlag(key: string, fallback: boolean): boolean {
const raw = readDevSetting<unknown>(FLAPPY_DEV_GAME_KEY, key, fallback);
return typeof raw === "boolean" ? raw : fallback;
}
/** Resolve the current override set, falling back to the game defaults. */
export function readFlappyDevConfig(defaults: FlappyDevConfig): FlappyDevConfig {
return {
gravity: readNumber("gravity", defaults.gravity, FLAPPY_DEV_RANGES.gravity),
pipeSpeed: readNumber("pipeSpeed", defaults.pipeSpeed, FLAPPY_DEV_RANGES.pipeSpeed),
pipeGap: readNumber("pipeGap", defaults.pipeGap, FLAPPY_DEV_RANGES.pipeGap),
paused: readFlag("paused", defaults.paused),
invincible: readFlag("invincible", defaults.invincible),
fpsOverlay: readFlag("fpsOverlay", defaults.fpsOverlay),
};
}

View file

@ -8,10 +8,18 @@ import { useRealtimePresence } from "@/hooks/useRealtimePresence";
import { useSidebar } from "@/components/ui/sidebar";
import { AllTimeLeaderboard } from "@/components/frontend/minigames/AllTimeLeaderboard";
import { PeriodStandingsCard } from "@/components/frontend/minigames/PeriodStandingsCard";
import { MinigameDevDock } from "@/components/frontend/minigames/dev/MinigameDevDock";
import {
OPORD_DEV_GAME_KEY,
OPORD_DEV_SETTINGS_EVENT,
OpordDevControls,
readOpordDevSettings,
type OpordDevSettings,
} from "@/components/frontend/minigames/dev/OpordDevControls";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { cn } from "@/lib/utils";
import { OpordGame } from "./OpordGame";
import { OpordGame, type OpordRunState } from "./OpordGame";
import { OpordLeaderboard } from "./OpordLeaderboard";
const TIER_OPTIONS = [
@ -33,14 +41,27 @@ const TIER_STAT_KEYS = {
export function OpordArena({
initialStats,
currentUserId,
isSuperuser = false,
}: {
initialStats: OpordStats;
currentUserId: number | string;
isSuperuser?: boolean;
}) {
const [stats, setStats] = useState<OpordStats>(initialStats);
const [refreshKey, setRefreshKey] = useState(0);
const [difficulty, setDifficulty] = useState<OpordDifficulty>("recruit");
const [playing, setPlaying] = useState(false);
const [runState, setRunState] = useState<OpordRunState>({
phase: "ready",
questionIndex: 0,
questionCount: 0,
correctSoFar: 0,
answersSubmitted: 0,
});
const [devSettings, setDevSettings] = useState<OpordDevSettings>({
revealAnswers: false,
studySeconds: null,
});
const { isMobile, setOpenMobile } = useSidebar();
const activeOperators = useRealtimePresence("opord", playing, true);
@ -53,10 +74,34 @@ export function OpordArena({
setRefreshKey((key) => key + 1);
}, []);
const handleRunStateChange = useCallback((next: OpordRunState) => {
setRunState(next);
}, []);
// Dev overrides live in localStorage; the dock broadcasts a window event so
// the State tab reflects them without a reload.
useEffect(() => {
if (!isSuperuser) return;
const sync = () => setDevSettings(readOpordDevSettings());
sync();
window.addEventListener(OPORD_DEV_SETTINGS_EVENT, sync);
return () => window.removeEventListener(OPORD_DEV_SETTINGS_EVENT, sync);
}, [isSuperuser]);
useEffect(() => {
if (playing && isMobile) setOpenMobile(false);
}, [isMobile, playing, setOpenMobile]);
const devSnapshot = {
difficulty,
phase: runState.phase,
questionIndex: runState.questionIndex,
questionCount: runState.questionCount,
correctSoFar: runState.correctSoFar,
answersSubmitted: runState.answersSubmitted,
dev: devSettings,
};
return (
<div className="mx-auto flex w-full max-w-4xl flex-col items-center gap-6">
<Card className="w-full">
@ -120,8 +165,10 @@ export function OpordArena({
key={difficulty}
initialStats={stats}
difficulty={difficulty}
isSuperuser={isSuperuser}
onGameRecordedAction={handleGameRecorded}
onPhaseChangeAction={handlePhaseChange}
onRunStateChangeAction={handleRunStateChange}
/>
<Card className="w-full max-w-3xl">
@ -176,6 +223,15 @@ export function OpordArena({
activeOperators={activeOperators}
/>
</AllTimeLeaderboard>
<MinigameDevDock
isSuperuser={isSuperuser}
gameKey={OPORD_DEV_GAME_KEY}
gameLabel="OPORD Recall"
snapshot={devSnapshot}
>
<OpordDevControls isSuperuser={isSuperuser} />
</MinigameDevDock>
</div>
);
}

View file

@ -20,14 +20,34 @@ import type { OpordStats } from "@/app/(frontend)/minigames/opord/actions";
import { submitOpordRecallResult } from "@/app/(frontend)/minigames/opord/actions";
import { useSessionExpired } from "@/hooks/useSessionExpired";
import { PROFILE_UPDATE_EVENT } from "@/hooks/useGameTick";
import {
OPORD_DEV_SETTINGS_EVENT,
readOpordDevSettings,
} from "@/components/frontend/minigames/dev/OpordDevControls";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
type Phase = "ready" | "briefing" | "quiz" | "over";
export type Phase = "ready" | "briefing" | "quiz" | "over";
/** Cheap run-state report for the dev dock's State tab. */
export interface OpordRunState {
readonly phase: Phase;
readonly questionIndex: number;
readonly questionCount: number;
readonly correctSoFar: number;
readonly answersSubmitted: number;
}
const ANSWER_FEEDBACK_MS = 900;
function isOpordAnswerCorrect(question: OpordQuestion, value: string): boolean {
if (question.kind === "input") {
return normalizeOpordAnswer(value) === normalizeOpordAnswer(question.answer);
}
return Number(value) === question.correctIndex;
}
const CANVAS_PAD_X = 18;
const CANVAS_MAX_W = 660;
@ -348,13 +368,17 @@ function Metre({ label, value }: { label: string; value: string | number }) {
export function OpordGame({
initialStats,
difficulty,
isSuperuser = false,
onGameRecordedAction,
onPhaseChangeAction,
onRunStateChangeAction,
}: {
initialStats: OpordStats;
difficulty: OpordDifficulty;
isSuperuser?: boolean;
onGameRecordedAction: (stats: OpordStats) => void;
onPhaseChangeAction: (phase: Phase) => void;
onRunStateChangeAction?: (state: OpordRunState) => void;
}) {
const router = useRouter();
const { expired, expiredRef } = useSessionExpired();
@ -386,6 +410,42 @@ export function OpordGame({
error?: string;
} | null>(null);
// Dev dock overrides (superuser only). Stored in localStorage, mirrored to
// this component by a window event so the dock applies without a reload.
const [devRevealAnswers, setDevRevealAnswers] = useState(false);
const [devStudySeconds, setDevStudySeconds] = useState<number | null>(null);
const [studyDeadlineAt, setStudyDeadlineAt] = useState<number | null>(null);
const [studyRemainingMs, setStudyRemainingMs] = useState(0);
useEffect(() => {
if (!isSuperuser) {
setDevRevealAnswers(false);
setDevStudySeconds(null);
return;
}
const sync = () => {
const settings = readOpordDevSettings();
setDevRevealAnswers(settings.revealAnswers);
setDevStudySeconds(settings.studySeconds);
};
sync();
window.addEventListener(OPORD_DEV_SETTINGS_EVENT, sync);
return () => window.removeEventListener(OPORD_DEV_SETTINGS_EVENT, sync);
}, [isSuperuser]);
// Study-time override: seed a deadline whenever the briefing starts (or the
// override changes) and let the ticking effect below start the quiz at zero.
// With no override the briefing stays self-paced, exactly as before.
useEffect(() => {
if (phase !== "briefing" || devStudySeconds === null) {
setStudyDeadlineAt(null);
setStudyRemainingMs(0);
return;
}
setStudyDeadlineAt(Date.now() + devStudySeconds * 1000);
setStudyRemainingMs(devStudySeconds * 1000);
}, [devStudySeconds, phase]);
const setPhaseSafe = useCallback(
(next: Phase) => {
phaseRef.current = next;
@ -398,12 +458,9 @@ export function OpordGame({
const finishRun = useCallback(async () => {
if (submittingRef.current) return;
const timeMs = Math.max(1, Date.now() - quizStartedAtRef.current);
const correct = answersRef.current.filter(({ question, value }) => {
if (question.kind === "input") {
return normalizeOpordAnswer(value) === normalizeOpordAnswer(question.answer);
}
return Number(value) === question.correctIndex;
}).length;
const correct = answersRef.current.filter(({ question, value }) =>
isOpordAnswerCorrect(question, value),
).length;
const preview = gradeOpordRun(difficulty, correct, timeMs, true);
if (expiredRef.current) {
@ -576,9 +633,46 @@ export function OpordGame({
return () => window.clearInterval(interval);
}, [phase, questionIndex]);
// Dev-only study window: when an override is active the briefing counts down
// and starts the quiz at zero. beginQuiz re-checks the phase, so a reset or a
// manual "Begin recall" wins the race safely.
useEffect(() => {
if (phase !== "briefing" || studyDeadlineAt === null) return;
const interval = window.setInterval(() => {
const remaining = studyDeadlineAt - Date.now();
if (remaining <= 0) {
window.clearInterval(interval);
setStudyRemainingMs(0);
beginQuiz();
return;
}
setStudyRemainingMs(remaining);
}, 200);
return () => window.clearInterval(interval);
}, [beginQuiz, phase, studyDeadlineAt]);
// Report a small run summary for the dock's State tab. answersRef only
// advances with questionIndex, so recomputing the tally here is cheap.
useEffect(() => {
if (!onRunStateChangeAction) return;
onRunStateChangeAction({
phase,
questionIndex,
questionCount: questions.length,
correctSoFar: answersRef.current.filter(({ question: answered, value }) =>
isOpordAnswerCorrect(answered, value),
).length,
answersSubmitted: answersRef.current.length,
});
}, [onRunStateChangeAction, phase, questionIndex, questions.length]);
const question = questions[questionIndex];
const answersLocked =
lastAnswerWasCorrect !== null || quizRemainingMs <= 0 || unlockRemainingMs > 0;
const studySecondsLeft =
studyDeadlineAt === null
? (devStudySeconds ?? 0)
: Math.max(0, Math.ceil(studyRemainingMs / 1000));
return (
<div className="flex w-full max-w-3xl flex-col items-center gap-4">
@ -610,9 +704,14 @@ export function OpordGame({
<div className="flex w-full items-center justify-between gap-3 rounded-lg border border-amber-500/40 bg-amber-500/10 px-4 py-2">
<span className="flex items-center gap-2 text-sm font-medium">
<Timer aria-hidden="true" className="size-4" />
Study at your own pace
{devStudySeconds === null ? "Study at your own pace" : "Dev study window"}
</span>
<div className="flex items-center gap-3">
{devStudySeconds !== null && (
<span className="font-mono text-sm font-bold tabular-nums text-amber-300">
{studySecondsLeft}s
</span>
)}
<span className="text-xs text-muted-foreground">
Recall quiz: {tier.quizSeconds}s once started
</span>
@ -677,7 +776,12 @@ export function OpordGame({
key={`${question.id}-${index}`}
type="button"
variant="outline"
className="h-auto min-h-11 justify-center whitespace-normal break-words font-mono"
className={cn(
"h-auto min-h-11 justify-center whitespace-normal break-words font-mono",
devRevealAnswers &&
index === question.correctIndex &&
"border-emerald-500/60 bg-emerald-500/10 text-emerald-300 hover:bg-emerald-500/15 hover:text-emerald-200",
)}
disabled={answersLocked}
onClick={() => answerCurrent(String(index))}
>
@ -686,29 +790,34 @@ export function OpordGame({
))}
</div>
) : (
<form
className="flex w-full max-w-xs flex-col gap-2"
onSubmit={(event) => {
event.preventDefault();
if (typedAnswer.trim().length === 0 || answersLocked) return;
answerCurrent(typedAnswer);
}}
>
<Input
value={typedAnswer}
onChange={(event) => setTypedAnswer(event.target.value)}
className="text-center font-mono"
autoComplete="off"
autoFocus
maxLength={12}
placeholder="Type your answer"
aria-label="Answer"
disabled={answersLocked}
/>
<Button type="submit" disabled={answersLocked}>
Submit
</Button>
</form>
<div className="flex w-full max-w-xs flex-col items-center gap-2">
<form
className="flex w-full flex-col gap-2"
onSubmit={(event) => {
event.preventDefault();
if (typedAnswer.trim().length === 0 || answersLocked) return;
answerCurrent(typedAnswer);
}}
>
<Input
value={typedAnswer}
onChange={(event) => setTypedAnswer(event.target.value)}
className="text-center font-mono"
autoComplete="off"
autoFocus
maxLength={12}
placeholder="Type your answer"
aria-label="Answer"
disabled={answersLocked}
/>
<Button type="submit" disabled={answersLocked}>
Submit
</Button>
</form>
{devRevealAnswers && (
<p className="font-mono text-xs text-emerald-300">Expected: {question.answer}</p>
)}
</div>
)}
</div>
)}

View file

@ -14,6 +14,8 @@ import { useRealtimePresence } from "@/hooks/useRealtimePresence";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { ChipBankCard } from "@/components/frontend/minigames/ChipBankCard";
import { MinigameDevDock } from "@/components/frontend/minigames/dev/MinigameDevDock";
import { PokerDevControls } from "@/components/frontend/minigames/dev/PokerDevControls";
import { PokerGuide } from "./PokerGuide";
import {
POKER_STATE_EVENT,
@ -328,7 +330,6 @@ export function PokerArena({
onStart={startCurrentTable}
onLeave={leaveTable}
onBack={resetToLobby}
isSuperuser={isSuperuser}
superuserIds={superuserIds}
/>
)}
@ -341,6 +342,19 @@ export function PokerArena({
</div>
<ChipBankCard initialChipBank={initialChipBank} initialChipTopUpAt={initialChipTopUpAt} />
{view === "table" && snapshot && (
<MinigameDevDock
isSuperuser={isSuperuser}
gameKey="poker"
gameLabel="Poker"
snapshot={snapshot}
>
{snapshot.you && (
<PokerDevControls tableId={snapshot.tableId} view={snapshot.you} />
)}
</MinigameDevDock>
)}
</div>
);
}

View file

@ -1,26 +1,6 @@
"use client";
import { useState } from "react";
import { Shield, Trash2 } from "lucide-react";
import type { Card, Rank, Suit } from "@/lib/minigames/poker";
import type { PokerSnapshot } from "@/app/(frontend)/minigames/poker/actions";
import {
adjustPokerStack,
setPokerBoardQueue,
setPokerHoleQueue,
} from "@/app/(frontend)/minigames/poker/actions";
import { Button } from "@/components/ui/button";
import { Combobox } from "@/components/ui/combobox";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
@ -28,8 +8,16 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import type { Card, Rank, Suit } from "@/lib/minigames/poker";
const RANK_OPTIONS: readonly { value: Rank; label: string }[] = [
/**
* Shared card picker for developer controls. The poker dev panel itself moved
* into the minigame dev dock (src/components/frontend/minigames/dev/), but
* this picker is reused by both the poker and blackjack dock panels, so it
* keeps its original home and API.
*/
export const RANK_OPTIONS: readonly { value: Rank; label: string }[] = [
{ value: 2, label: "2" },
{ value: 3, label: "3" },
{ value: 4, label: "4" },
@ -45,14 +33,14 @@ const RANK_OPTIONS: readonly { value: Rank; label: string }[] = [
{ value: 14, label: "Ace" },
];
const SUIT_OPTIONS: readonly { value: Suit; label: string }[] = [
export const SUIT_OPTIONS: readonly { value: Suit; label: string }[] = [
{ value: "s", label: "Spades" },
{ value: "h", label: "Hearts" },
{ value: "d", label: "Diamonds" },
{ value: "c", label: "Clubs" },
];
function cardLabel(card: Card): string {
export function cardLabel(card: Card): string {
const rank =
RANK_OPTIONS.find((option) => option.value === card.rank)?.label ?? String(card.rank);
const suit = SUIT_OPTIONS.find((option) => option.value === card.suit)?.label ?? card.suit;
@ -73,7 +61,7 @@ export function applyCardPick(value: Card | null, part: "rank" | "suit", next: s
return { rank: value?.rank ?? 2, suit: next as Suit };
}
function CardPicker({
export function CardPicker({
label,
value,
onChange,
@ -114,208 +102,3 @@ function CardPicker({
</div>
);
}
export function PokerDevPanel({
tableId,
view,
}: {
readonly tableId: string;
readonly view: NonNullable<PokerSnapshot["you"]>;
}) {
const [open, setOpen] = useState(false);
const [boardQueue, setBoardQueue] = useState<Card[]>([]);
const [boardDraft, setBoardDraft] = useState<Card | null>(null);
const [seatId, setSeatId] = useState<string>("");
const [holeA, setHoleA] = useState<Card | null>(null);
const [holeB, setHoleB] = useState<Card | null>(null);
const [adjustSeat, setAdjustSeat] = useState<string>("");
const [adjustAmount, setAdjustAmount] = useState<string>("");
const [error, setError] = useState<string | null>(null);
const run = async (action: () => Promise<{ success: boolean; error?: string }>) => {
const result = await action();
if (!result.success) setError(result.error ?? "The dev action failed.");
else setError(null);
};
const queueBoard = () => {
if (boardQueue.length === 0) return;
void run(async () => {
const result = await setPokerBoardQueue(tableId, boardQueue);
if (result.success) setBoardQueue([]);
return result;
});
};
const queueHole = () => {
if (seatId === "" || !holeA || !holeB) return;
void run(async () => {
const result = await setPokerHoleQueue(tableId, Number(seatId), [holeA, holeB]);
if (result.success) {
setHoleA(null);
setHoleB(null);
}
return result;
});
};
const adjust = (sign: 1 | -1) => {
if (adjustSeat === "") return;
const amount = Number(adjustAmount);
if (!Number.isInteger(amount) || amount <= 0) {
setError("Enter a positive whole number of chips.");
return;
}
void run(async () => {
const result = await adjustPokerStack(tableId, Number(adjustSeat), sign * amount);
if (result.success) setAdjustAmount("");
return result;
});
};
const boardSlotsLeft = 5 - view.communityCards.length - boardQueue.length;
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button
type="button"
variant="outline"
size="icon"
aria-label="Developer controls"
title="Developer controls"
>
<Shield aria-hidden="true" />
</Button>
</DialogTrigger>
<DialogContent className="max-h-[85dvh] max-w-lg overflow-y-auto rounded-none">
<DialogHeader>
<DialogTitle>Developer controls</DialogTitle>
<DialogDescription>
Queue upcoming cards or adjust stacks. Queues apply at the next hand; board cards hit
the felt in order.
</DialogDescription>
</DialogHeader>
{error && <p className="text-sm text-destructive">{error}</p>}
<section className="flex flex-col gap-2 border border-border p-3">
<h3 className="text-xs font-semibold uppercase tracking-wider">Board queue</h3>
<div className="flex flex-col gap-1.5">
<CardPicker label="Card" value={boardDraft} onChange={setBoardDraft} />
<Button
type="button"
variant="outline"
size="sm"
className="w-fit"
disabled={boardQueue.length >= boardSlotsLeft}
onClick={() => {
if (!boardDraft) return;
setBoardQueue((current) => [...current, boardDraft]);
setBoardDraft(null);
}}
>
Add to queue ({boardSlotsLeft} slot{boardSlotsLeft === 1 ? "" : "s"} left)
</Button>
</div>
{boardQueue.length > 0 && (
<ul className="flex flex-col gap-1">
{boardQueue.map((card, index) => (
<li
key={`${card.rank}-${card.suit}-${index}`}
className="flex items-center gap-2 text-xs"
>
<span className="font-mono text-muted-foreground">{index + 1}.</span>
<span>{cardLabel(card)}</span>
<button
type="button"
aria-label={`Remove ${cardLabel(card)}`}
className="ml-auto text-muted-foreground hover:text-destructive"
onClick={() =>
setBoardQueue((current) => current.filter((_, i) => i !== index))
}
>
<Trash2 className="size-3.5" />
</button>
</li>
))}
</ul>
)}
<Button
type="button"
size="sm"
className="w-fit"
onClick={queueBoard}
disabled={boardQueue.length === 0}
>
Set board queue
</Button>
</section>
<section className="flex flex-col gap-2 border border-border p-3">
<h3 className="text-xs font-semibold uppercase tracking-wider">Next hand hole cards</h3>
<Combobox
className="h-8 text-xs"
value={seatId}
onValueChange={setSeatId}
placeholder="Player"
searchPlaceholder="Search players..."
options={view.players
.filter((player) => !player.eliminated)
.map((player) => ({
value: String(player.seatId),
label: player.name,
}))}
/>
<div className="flex flex-col gap-1.5">
<CardPicker label="Card 1" value={holeA} onChange={setHoleA} />
<CardPicker label="Card 2" value={holeB} onChange={setHoleB} />
</div>
<Button
type="button"
size="sm"
className="w-fit"
onClick={queueHole}
disabled={seatId === "" || !holeA || !holeB}
>
Queue hand
</Button>
</section>
<section className="flex flex-col gap-2 border border-border p-3">
<h3 className="text-xs font-semibold uppercase tracking-wider">Stack adjustment</h3>
<Combobox
className="h-8 text-xs"
value={adjustSeat}
onValueChange={setAdjustSeat}
placeholder="Player"
searchPlaceholder="Search players..."
options={view.players
.filter((player) => !player.eliminated)
.map((player) => ({
value: String(player.seatId),
label: `${player.name} (${player.stack.toLocaleString()})`,
}))}
/>
<div className="flex items-center gap-2">
<Input
type="number"
min={1}
step={1}
placeholder="Chips"
value={adjustAmount}
onChange={(event) => setAdjustAmount(event.target.value)}
className="h-8 w-28 text-xs"
/>
<Button type="button" variant="outline" size="sm" onClick={() => adjust(1)}>
Add
</Button>
<Button type="button" variant="outline" size="sm" onClick={() => adjust(-1)}>
Subtract
</Button>
</div>
</section>
</DialogContent>
</Dialog>
);
}

View file

@ -10,7 +10,6 @@ import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card as UiCard, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { PokerCardStyleToggle } from "./PokerCardStyleToggle";
import { PokerDevPanel } from "./PokerDevPanel";
import { PokerFeltCanvas, type SeatedSnapshot } from "./PokerFeltCanvas";
import { PokerSoundToggle } from "./PokerSoundToggle";
import type { PokerSoundControls } from "./usePokerSounds";
@ -27,7 +26,6 @@ interface PokerGameTableProps {
readonly sound: PokerSoundControls;
readonly popups: readonly ActivePokerPopup[];
readonly actionLog: readonly PokerActionLogEntry[];
readonly isSuperuser: boolean;
readonly superuserIds: readonly number[];
}
@ -47,7 +45,6 @@ export function PokerGameTable({
sound,
popups,
actionLog,
isSuperuser,
superuserIds,
}: PokerGameTableProps) {
const [starting, setStarting] = useState(false);
@ -129,7 +126,6 @@ export function PokerGameTable({
<Badge variant="outline">{PHASE_LABELS[view.phase]}</Badge>
</div>
<div className="flex flex-wrap items-center justify-end gap-2">
{isSuperuser && <PokerDevPanel tableId={snapshot.tableId} view={view} />}
<PokerCardStyleToggle />
<PokerSoundToggle
muted={sound.muted}
@ -188,7 +184,6 @@ export function PokerGameTable({
<span className="font-mono text-xs tabular-nums text-muted-foreground">
v{snapshot.version}
</span>
{isSuperuser && <PokerDevPanel tableId={snapshot.tableId} view={view} />}
<PokerCardStyleToggle />
<PokerSoundToggle
muted={sound.muted}

View file

@ -26,7 +26,6 @@ interface PokerTableProps {
readonly onStart: () => Promise<void>;
readonly onLeave: () => Promise<void>;
readonly onBack: () => void;
readonly isSuperuser: boolean;
readonly superuserIds: readonly number[];
}
@ -201,7 +200,6 @@ function PokerTableInner({
onStart,
onLeave,
onBack,
isSuperuser,
superuserIds,
}: PokerTableProps) {
// Sound + popup transitions must live here, ABOVE the waiting/game split:
@ -269,7 +267,6 @@ function PokerTableInner({
sound={sound}
popups={popups}
actionLog={actionLog}
isSuperuser={isSuperuser}
superuserIds={superuserIds}
/>
);

View file

@ -1,6 +1,6 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
AIM_TRAINER_DIFFICULTIES,
@ -11,12 +11,22 @@ import type { AimTrainerStats } from "@/app/(frontend)/minigames/qualification/a
import { useRealtimePresence } from "@/hooks/useRealtimePresence";
import { useSidebar } from "@/components/ui/sidebar";
import { AllTimeLeaderboard } from "@/components/frontend/minigames/AllTimeLeaderboard";
import { MinigameDevDock } from "@/components/frontend/minigames/dev/MinigameDevDock";
import { QualificationDevControls } from "@/components/frontend/minigames/dev/QualificationDevControls";
import { PeriodStandingsCard } from "@/components/frontend/minigames/PeriodStandingsCard";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { cn } from "@/lib/utils";
import { emptyAimTrainerLiveStats, type AimTrainerLiveStats } from "./AimTrainerCanvas";
import { AimTrainerGame, type AimTrainerPhase } from "./AimTrainerGame";
import { AimTrainerLeaderboard } from "./AimTrainerLeaderboard";
import {
DEFAULT_QUALIFICATION_DEV_CONFIG,
QUALIFICATION_DEV_EVENT,
QUALIFICATION_DEV_GAME_KEY,
readQualificationDevConfig,
type QualificationDevConfig,
} from "./devConfig";
const TIER_OPTIONS = [
{ value: "recruit", label: "Recruit", detail: "Steady silhouettes" },
@ -43,26 +53,93 @@ const TIER_STAT_KEYS = {
export function AimTrainerArena({
initialStats,
currentUserId,
isSuperuser = false,
}: {
readonly initialStats: AimTrainerStats;
readonly currentUserId: number | string;
readonly isSuperuser?: boolean;
}) {
const [stats, setStats] = useState<AimTrainerStats>(initialStats);
const [refreshKey, setRefreshKey] = useState(0);
const [difficulty, setDifficulty] = useState<AimTrainerDifficulty>("recruit");
const [playing, setPlaying] = useState(false);
const [phase, setPhase] = useState<AimTrainerPhase>("ready");
const [liveStats, setLiveStats] = useState<AimTrainerLiveStats>(emptyAimTrainerLiveStats);
const [devConfig, setDevConfig] = useState<QualificationDevConfig>(
DEFAULT_QUALIFICATION_DEV_CONFIG,
);
const { isMobile, setOpenMobile } = useSidebar();
const activeTrainees = useRealtimePresence("qualification", playing, true);
// Dev overrides are read only for superusers: a hand-edited localStorage
// entry must never change a regular player's run. Re-read on the shared
// settings event so the controls take effect live.
useEffect(() => {
if (!isSuperuser) {
setDevConfig(DEFAULT_QUALIFICATION_DEV_CONFIG);
return;
}
const sync = () => setDevConfig(readQualificationDevConfig());
sync();
window.addEventListener(QUALIFICATION_DEV_EVENT, sync);
return () => window.removeEventListener(QUALIFICATION_DEV_EVENT, sync);
}, [isSuperuser]);
const effectiveDifficulty = devConfig.difficultyOverride ?? difficulty;
const activeConfig = AIM_TRAINER_DIFFICULTIES[effectiveDifficulty];
// A tier change remounts the game, so clear the run flags the unmounted
// instance left behind (a dev override can swap tiers mid-run).
useEffect(() => {
setPlaying(false);
setPhase("ready");
}, [effectiveDifficulty]);
const handlePhaseChange = useCallback((nextPhase: AimTrainerPhase) => {
setPhase(nextPhase);
setPlaying(nextPhase === "playing");
}, []);
const handleLiveStats = useCallback((nextStats: AimTrainerLiveStats) => {
setLiveStats(nextStats);
}, []);
const handleGameRecorded = useCallback((nextStats: AimTrainerStats) => {
setStats(nextStats);
setRefreshKey((key) => key + 1);
}, []);
const devSnapshot = useMemo(
() => ({
phase,
laneDifficulty: difficulty,
difficulty: effectiveDifficulty,
difficultyOverride: devConfig.difficultyOverride,
seed: devConfig.seed,
hitboxOverlay: devConfig.hitboxOverlay,
score: liveStats.score,
accuracy: liveStats.accuracy,
shotsFired: liveStats.shotsFired,
hits: liveStats.headshots + liveStats.torsoHits,
headshots: liveStats.headshots,
torsoHits: liveStats.torsoHits,
civilianHits: liveStats.civilianHits,
despawnedUnhitTargets: liveStats.despawnedUnhitTargets,
gamesPlayed: stats.gamesPlayed,
bestScore: stats.bestScore,
}),
[
devConfig,
difficulty,
effectiveDifficulty,
liveStats,
phase,
stats.bestScore,
stats.gamesPlayed,
],
);
useEffect(() => {
if (playing && isMobile) setOpenMobile(false);
}, [isMobile, playing, setOpenMobile]);
@ -135,11 +212,14 @@ export function AimTrainerArena({
</Card>
<AimTrainerGame
key={difficulty}
key={effectiveDifficulty}
initialStats={stats}
difficulty={difficulty}
difficulty={effectiveDifficulty}
seed={devConfig.seed}
hitboxOverlay={devConfig.hitboxOverlay}
onGameRecordedAction={handleGameRecorded}
onPhaseChangeAction={handlePhaseChange}
onLiveStatsAction={handleLiveStats}
/>
<Card className="w-full max-w-3xl">
@ -150,9 +230,9 @@ export function AimTrainerArena({
<div className="flex flex-col gap-1">
<span className="font-medium text-foreground">Acquire</span>
<span>
Up to {AIM_TRAINER_DIFFICULTIES[difficulty].maxConcurrentTargets} hostile silhouettes
are active at once, plus an occasional blue civilian that never counts toward the
limit. Targets rebound off each other and the range walls.
Up to {activeConfig.maxConcurrentTargets} hostile silhouettes are active at once, plus
an occasional blue civilian that never counts toward the limit. Targets rebound off
each other and the range walls.
</span>
</div>
<div className="flex flex-col gap-1">
@ -166,7 +246,7 @@ export function AimTrainerArena({
<span className="font-medium text-foreground">Qualify</span>
<span>
The course adds an accuracy bonus and records the best score for each lane. Current
target window: {AIM_TRAINER_DIFFICULTIES[difficulty].targetLifetimeMs / 1000}s.
target window: {activeConfig.targetLifetimeMs / 1000}s.
</span>
</div>
</CardContent>
@ -183,11 +263,20 @@ export function AimTrainerArena({
<AllTimeLeaderboard className="max-w-3xl">
<AimTrainerLeaderboard
refreshKey={refreshKey}
difficulty={difficulty}
difficulty={effectiveDifficulty}
currentUserId={currentUserId}
activeTrainees={activeTrainees}
/>
</AllTimeLeaderboard>
<MinigameDevDock
isSuperuser={isSuperuser}
gameKey={QUALIFICATION_DEV_GAME_KEY}
gameLabel="Qualification Course"
snapshot={devSnapshot}
>
<QualificationDevControls />
</MinigameDevDock>
</div>
);
}

View file

@ -35,6 +35,8 @@ type AimTrainerSceneFrame = {
readonly now: number;
readonly targetLifetimeMs: number;
readonly crosshair: AimTrainerCrosshairPrefs;
/** Dev tool: outline the exact hit zones used by hit resolution. */
readonly hitboxOverlay: boolean;
};
export type AimTrainerGameState = {
@ -189,10 +191,7 @@ function drawTarget(
const { target, spawnedAt } = activeTarget;
const palette = target.kind === "civilian" ? CIVILIAN_TARGET_PALETTE : STANDARD_TARGET_PALETTE;
const age = Math.max(0, frame.now - spawnedAt);
const fadeDuration = Math.min(
AIM_TRAINER_TARGET_FADE_DURATION_MS,
frame.targetLifetimeMs / 5,
);
const fadeDuration = Math.min(AIM_TRAINER_TARGET_FADE_DURATION_MS, frame.targetLifetimeMs / 5);
const fadeStart = frame.targetLifetimeMs - fadeDuration;
const fadeProgress =
fadeDuration > 0 ? Math.min(1, Math.max(0, (age - fadeStart) / fadeDuration)) : 0;
@ -258,6 +257,21 @@ function drawTarget(
ctx.setLineDash([4, 5]);
ctx.strokeRect(torsoX, target.y, target.torsoW * pulse, target.torsoH);
ctx.setLineDash([]);
if (frame.hitboxOverlay) {
// Exact hit geometry (not the pulsing silhouette): the head circle and the
// torso rectangle that `resolveAimTrainerHitZone` actually tests.
ctx.strokeStyle =
target.kind === "civilian" ? "rgba(251, 191, 36, 0.9)" : "rgba(94, 234, 212, 0.9)";
ctx.lineWidth = 1;
ctx.setLineDash([3, 3]);
ctx.strokeRect(target.x - target.torsoW / 2, target.y, target.torsoW, target.torsoH);
ctx.beginPath();
ctx.arc(target.x, target.y - target.headRadius, target.headRadius, 0, Math.PI * 2);
ctx.stroke();
ctx.setLineDash([]);
}
ctx.restore();
}

View file

@ -46,6 +46,7 @@ import {
type AimTrainerLiveStats,
} from "./AimTrainerCanvas";
import { CrosshairSettings } from "./CrosshairSettings";
import { mulberry32 } from "./devConfig";
import {
DEFAULT_AIM_TRAINER_CROSSHAIR_PREFS,
loadAimTrainerCrosshairPrefs,
@ -168,13 +169,21 @@ function SummaryMetric({ label, value }: { label: string; value: string | number
export function AimTrainerGame({
initialStats: serverStats,
difficulty,
seed = null,
hitboxOverlay = false,
onGameRecordedAction,
onPhaseChangeAction,
onLiveStatsAction,
}: {
readonly initialStats: AimTrainerStats;
readonly difficulty: AimTrainerDifficulty;
/** Dev tool: deterministic spawn seed, or null for `Math.random`. */
readonly seed?: number | null;
/** Dev tool: outline each target's exact hit zones on the canvas. */
readonly hitboxOverlay?: boolean;
readonly onGameRecordedAction?: (stats: AimTrainerStats) => void;
readonly onPhaseChangeAction?: (phase: AimTrainerPhase) => void;
readonly onLiveStatsAction?: (stats: AimTrainerLiveStats) => void;
}) {
const router = useRouter();
const { expired, expiredRef } = useSessionExpired();
@ -184,15 +193,16 @@ export function AimTrainerGame({
const submittingRef = useRef(false);
const statsRef = useRef<AimTrainerStats>(serverStats);
const gameRef = useRef<AimTrainerGameState>(createAimTrainerGameState());
/** Spawn RNG: a fresh seeded generator per run, or `Math.random` normally. */
const rngRef = useRef<() => number>(Math.random);
const hitboxOverlayRef = useRef(hitboxOverlay);
const [phase, setPhase] = useState<AimTrainerPhase>("ready");
const [timerSeconds, setTimerSeconds] = useState(COURSE_DURATION_SECONDS);
const [live, setLive] = useState<AimTrainerLiveStats>(emptyAimTrainerLiveStats);
const [stats, setStats] = useState<AimTrainerStats>(serverStats);
const [lastRun, setLastRun] = useState<LastRun | null>(null);
const [submitting, setSubmitting] = useState(false);
const crosshairPrefsRef = useRef<AimTrainerCrosshairPrefs>(
DEFAULT_AIM_TRAINER_CROSSHAIR_PREFS,
);
const crosshairPrefsRef = useRef<AimTrainerCrosshairPrefs>(DEFAULT_AIM_TRAINER_CROSSHAIR_PREFS);
const [crosshairPrefs, setCrosshairPrefs] = useState<AimTrainerCrosshairPrefs>(
DEFAULT_AIM_TRAINER_CROSSHAIR_PREFS,
);
@ -205,6 +215,14 @@ export function AimTrainerGame({
setCrosshairPrefs(prefs);
}, []);
useEffect(() => {
hitboxOverlayRef.current = hitboxOverlay;
}, [hitboxOverlay]);
useEffect(() => {
onLiveStatsAction?.(live);
}, [live, onLiveStatsAction]);
const handleCrosshairPrefsChange = useCallback((prefs: AimTrainerCrosshairPrefs) => {
crosshairPrefsRef.current = prefs;
setCrosshairPrefs(prefs);
@ -319,6 +337,7 @@ export function AimTrainerGame({
const startGame = useCallback(() => {
if (expiredRef.current || submittingRef.current) return;
const now = performance.now();
rngRef.current = seed === null ? Math.random : mulberry32(seed);
const game = createAimTrainerGameState();
game.pendingSpawnAts = Array.from(
{ length: config.maxConcurrentTargets },
@ -331,7 +350,7 @@ export function AimTrainerGame({
setLastRun(null);
setPhaseSafe("playing");
wrapperRef.current?.focus({ preventScroll: true });
}, [config.maxConcurrentTargets, config.replacementDelayMs, expiredRef, setPhaseSafe]);
}, [config.maxConcurrentTargets, config.replacementDelayMs, expiredRef, seed, setPhaseSafe]);
const handlePrimaryAction = useCallback(() => {
const currentPhase = phaseRef.current;
@ -545,15 +564,18 @@ export function AimTrainerGame({
if (dueIndex === -1) break;
game.pendingSpawnAts.splice(dueIndex, 1);
game.targets.push({
target: createAimTrainerTarget(Math.random, CANVAS_W, CANVAS_H, difficulty, {
target: createAimTrainerTarget(rngRef.current, CANVAS_W, CANVAS_H, difficulty, {
existingTargets: game.targets.map((activeTarget) => activeTarget.target),
}),
spawnedAt: now,
});
standardCount += 1;
if (civilianCount < MAX_CONCURRENT_CIVILIANS && Math.random() < config.civilianChance) {
if (
civilianCount < MAX_CONCURRENT_CIVILIANS &&
rngRef.current() < config.civilianChance
) {
game.targets.push({
target: createAimTrainerTarget(Math.random, CANVAS_W, CANVAS_H, difficulty, {
target: createAimTrainerTarget(rngRef.current, CANVAS_W, CANVAS_H, difficulty, {
civilian: true,
existingTargets: game.targets.map((activeTarget) => activeTarget.target),
}),
@ -570,6 +592,7 @@ export function AimTrainerGame({
now,
targetLifetimeMs: config.targetLifetimeMs,
crosshair: crosshairPrefsRef.current,
hitboxOverlay: hitboxOverlayRef.current,
});
};

View file

@ -0,0 +1,73 @@
/**
* Client-side developer config for the Qualification Course (aim trainer).
*
* Phase 2 dev tools only: a deterministic spawn seed, a difficulty override,
* and a hitbox overlay. Every value is read from the shared per-game dev
* settings namespace and validated here, so a corrupted or hand-edited entry
* falls back to the game default instead of breaking a run. Gameplay changes
* only: submissions and their server-side validation are untouched.
*/
import { isAimTrainerDifficulty, type AimTrainerDifficulty } from "@/lib/minigames/aim-trainer";
import { readDevSetting } from "../dev/devSettings";
/** Dispatched on window after every dev control change; games re-read on it. */
export const QUALIFICATION_DEV_EVENT = "ptf:dev-settings-changed";
/** Settings namespace, matching the dock's `gameKey`. */
export const QUALIFICATION_DEV_GAME_KEY = "qualification";
export interface QualificationDevConfig {
/** Deterministic spawn seed, or null for the normal `Math.random` range. */
readonly seed: number | null;
/** Difficulty override for the current run, or null to use the chosen lane. */
readonly difficultyOverride: AimTrainerDifficulty | null;
/** Draw every target's exact hit zones (head circle + torso rectangle). */
readonly hitboxOverlay: boolean;
}
export const DEFAULT_QUALIFICATION_DEV_CONFIG: QualificationDevConfig = {
seed: null,
difficultyOverride: null,
hitboxOverlay: false,
};
/**
* Small deterministic PRNG (mulberry32). One instance is created per seeded
* run, so the same seed replays the same spawn sequence in the same order.
*/
export function mulberry32(seed: number): () => number {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;
let t = state;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function readSeed(): number | null {
const raw = readDevSetting<unknown>(QUALIFICATION_DEV_GAME_KEY, "seed", null);
if (typeof raw !== "number" || !Number.isFinite(raw)) return null;
return Math.trunc(raw);
}
function readDifficultyOverride(): AimTrainerDifficulty | null {
const raw = readDevSetting<unknown>(QUALIFICATION_DEV_GAME_KEY, "difficulty", null);
return isAimTrainerDifficulty(raw) ? raw : null;
}
function readHitboxOverlay(): boolean {
const raw = readDevSetting<unknown>(QUALIFICATION_DEV_GAME_KEY, "hitboxOverlay", false);
return typeof raw === "boolean" ? raw : false;
}
/** Resolve the current dev override set, falling back to the game defaults. */
export function readQualificationDevConfig(): QualificationDevConfig {
return {
seed: readSeed(),
difficultyOverride: readDifficultyOverride(),
hitboxOverlay: readHitboxOverlay(),
};
}

View file

@ -18,9 +18,11 @@ import { RadioTraffic } from "./RadioTraffic";
export function RadioArena({
initialStats,
currentUserId,
isSuperuser = false,
}: {
initialStats: RadioStats;
currentUserId: number | string;
isSuperuser?: boolean;
}) {
const [refreshKey, setRefreshKey] = useState(0);
const [playing, setPlaying] = useState(false);
@ -73,6 +75,7 @@ export function RadioArena({
onModeChangeAction={setMode}
onGameRecordedAction={() => setRefreshKey((key) => key + 1)}
onPhaseChangeAction={onPhaseChange}
isSuperuser={isSuperuser}
/>
<div className="w-full max-w-[520px]">
<h2 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">How scoring works</h2>

View file

@ -15,6 +15,15 @@ import { Progress } from "@/components/ui/progress";
import { Switch } from "@/components/ui/switch";
import { PROFILE_UPDATE_EVENT } from "@/hooks/useGameTick";
import { useSessionExpired } from "@/hooks/useSessionExpired";
import { MinigameDevDock } from "@/components/frontend/minigames/dev/MinigameDevDock";
import { readDevSetting } from "@/components/frontend/minigames/dev/devSettings";
import {
formatTranscript,
RADIO_DEV_GAME_KEY,
RADIO_DEV_SETTINGS_EVENT,
RadioDevControls,
RadioTranscriptPanel,
} from "@/components/frontend/minigames/dev/RadioDevControls";
import { createRadioRound, nextRadioMessage, SPRINT_MESSAGE_COUNT } from "./messageGenerator";
import { playCountdownEnd, playCountdownTick, playCorrect, playError, playKeystroke, playRoundComplete, playXp } from "./sounds";
@ -172,6 +181,7 @@ export function RadioTraffic({
onGameRecordedAction,
onPhaseChangeAction,
customTest,
isSuperuser = false,
}: {
initialStats: RadioStats;
mode: Mode;
@ -179,6 +189,7 @@ export function RadioTraffic({
onGameRecordedAction: () => void;
onPhaseChangeAction: (phase: Phase) => void;
customTest?: CustomRadioTestData;
isSuperuser?: boolean;
}) {
const router = useRouter();
const { expired, expiredRef } = useSessionExpired();
@ -199,6 +210,8 @@ export function RadioTraffic({
const tickSoundRef = useRef(true);
const submitBlockedUntilRef = useRef(0);
const incorrectMessagesRef = useRef(0);
const freezeTimerRef = useRef(false);
const frozenSinceRef = useRef<number | null>(null);
const [phase, setPhase] = useState<Phase>("ready");
const [tickSoundEnabled, setTickSoundEnabled] = useState(true);
const [messages, setMessages] = useState<readonly string[]>(() => {
@ -218,6 +231,12 @@ export function RadioTraffic({
const [incorrectSprintSubmission, setIncorrectSprintSubmission] =
useState<IncorrectSprintSubmission | null>(null);
const [submitting, setSubmitting] = useState(false);
const [showTranscript, setShowTranscript] = useState(
() => isSuperuser && readDevSetting(RADIO_DEV_GAME_KEY, "showTranscript", false),
);
const [freezeTimer, setFreezeTimer] = useState(
() => isSuperuser && readDevSetting(RADIO_DEV_GAME_KEY, "freezeTimer", false),
);
const setPhaseSafe = useCallback(
(next: Phase) => {
@ -248,6 +267,38 @@ export function RadioTraffic({
setIncorrectSprintSubmission(null);
}, [mode]);
// Dev dock settings live in localStorage and are broadcast on a window event,
// so toggling them in the dock updates this arena without a reload.
useEffect(() => {
if (!isSuperuser) return;
const sync = () => {
setShowTranscript(readDevSetting(RADIO_DEV_GAME_KEY, "showTranscript", false));
setFreezeTimer(readDevSetting(RADIO_DEV_GAME_KEY, "freezeTimer", false));
};
window.addEventListener(RADIO_DEV_SETTINGS_EVENT, sync);
return () => window.removeEventListener(RADIO_DEV_SETTINGS_EVENT, sync);
}, [isSuperuser]);
// Freeze is a debugging convenience only. It pauses the visible clock, the
// watch deadline, and the per-message timer, but submissions keep their
// existing payload shape and server-side validation. On resume every start
// instant shifts by the paused duration, so the clock continues where it
// stopped instead of jumping.
useEffect(() => {
freezeTimerRef.current = freezeTimer;
if (freezeTimer) {
if (frozenSinceRef.current === null) frozenSinceRef.current = performance.now();
return;
}
const frozenSince = frozenSinceRef.current;
frozenSinceRef.current = null;
if (frozenSince === null || phaseRef.current !== "playing") return;
const pausedMs = performance.now() - frozenSince;
roundStartedAtRef.current += pausedMs;
messageStartedAtRef.current += pausedMs;
if (roundDeadlineRef.current > 0) roundDeadlineRef.current += pausedMs;
}, [freezeTimer]);
const recordResult = useCallback(
async (
finalResults: readonly MessageResult[],
@ -400,6 +451,7 @@ export function RadioTraffic({
useEffect(() => {
if (phase !== "playing") return;
const timer = window.setInterval(() => {
if (freezeTimerRef.current) return;
const now = performance.now();
if (mode === "sprint") {
setElapsedMs(now - roundStartedAtRef.current);
@ -479,6 +531,9 @@ export function RadioTraffic({
setFeedback(null);
setIncorrectSprintSubmission(null);
messageStartedAtRef.current = now;
// A frozen start anchors the pause at the round start, so time spent
// frozen before starting is not subtracted from the run.
if (freezeTimerRef.current) frozenSinceRef.current = now;
setPhaseSafe("playing");
window.setTimeout(() => inputRef.current?.focus(), 0);
}, [customTest, expiredRef, mode, setPhaseSafe]);
@ -537,7 +592,7 @@ export function RadioTraffic({
playError();
setFeedback({ correct: false, message: "Signal mismatch. Try the transmission again." });
submitBlockedUntilRef.current = now + UNSUCCESSFUL_SUBMIT_COOLDOWN_MS;
if (mode === "watch" && now >= roundDeadlineRef.current) {
if (mode === "watch" && !freezeTimerRef.current && now >= roundDeadlineRef.current) {
finishRound(results, mode, incorrectMessagesRef.current);
}
return;
@ -552,7 +607,10 @@ export function RadioTraffic({
playCorrect();
setFeedback({ correct: true, message: "Transmission accepted." });
const watchExpired = mode === "watch" && now >= roundDeadlineRef.current;
// A frozen clock never expires: the deadline is shifted on resume, so the
// run stays interactive while paused.
const watchExpired =
mode === "watch" && !freezeTimerRef.current && now >= roundDeadlineRef.current;
const watchLimitReached = mode === "watch" && finalResults.length >= WATCH_MAX_MESSAGES;
const shouldFinish =
mode === "sprint"
@ -609,6 +667,25 @@ export function RadioTraffic({
? `Relayed ${displayRelayed}`
: `Message ${Math.min(messageIndex + 1, messages.length)} of ${messages.length}`;
const modeSelectorDisabled = phase === "playing";
// Dev dock payload: cheap plain object describing the live run. Client-only,
// and rendered only when the page computed a superuser.
const transcript = formatTranscript(messages);
const devSnapshot = {
mode,
phase,
messageIndex,
totalMessages: messages.length,
decodedMessages: results.length,
errors: displayIncorrect,
correctKeystrokes: keystrokesRef.current.correct,
incorrectKeystrokes: keystrokesRef.current.incorrect,
timer: {
kind: displayMode === "watch" ? "remaining" : "elapsed",
ms: Math.round(displayMode === "watch" ? remainingMs : elapsedMs),
frozen: freezeTimer,
},
dev: { showTranscript, freezeTimer },
};
return (
<div className="flex w-full max-w-[620px] flex-col items-center gap-4">
@ -619,6 +696,9 @@ export function RadioTraffic({
</div>
<p className="text-sm text-muted-foreground">Intercept clean transmissions under pressure.</p>
</div>
{isSuperuser && showTranscript && (
<RadioTranscriptPanel messages={messages} messageIndex={messageIndex} />
)}
<div className="relative w-full rounded-xl border border-border bg-card p-4 shadow-lg sm:p-5">
<div className="flex items-center justify-between gap-3 text-xs uppercase tracking-wider text-muted-foreground">
<span className="flex items-center gap-1.5"><Target className="size-3.5" />{headerLabel}</span>
@ -702,6 +782,14 @@ export function RadioTraffic({
{expired && <div className="absolute inset-0 flex flex-col items-center justify-center gap-3 rounded-xl bg-background/95 p-6 text-center"><span className="text-2xl font-black uppercase tracking-widest text-amber-400">Session Ending Soon</span><span className="max-w-[260px] text-xs text-muted-foreground">Your session is about to end. The app will refresh when it expires.</span><LoginLink className="mt-1"><Button type="button" size="sm">Log in</Button></LoginLink></div>}
</div>
<div className="flex flex-wrap justify-center gap-6 text-sm text-muted-foreground"><div className="flex items-center gap-1.5"><span>Games</span><span className="font-semibold text-foreground">{stats.gamesPlayed}</span></div><div className="flex items-center gap-1.5"><span>Correct messages</span><span className="font-semibold text-foreground">{stats.totalMessages}</span></div><div className="flex items-center gap-1.5"><span>Incorrect messages</span><span className="font-semibold text-foreground">{stats.incorrectMessages}</span></div><div className="flex items-center gap-1.5"><span>Best run</span><span className="font-semibold text-foreground">{stats.bestScore}</span></div><div className="flex items-center gap-1.5"><span>XP from traffic</span><span className="font-semibold text-foreground">{stats.radioTrafficXp}</span></div></div>
<MinigameDevDock
isSuperuser={isSuperuser}
gameKey={RADIO_DEV_GAME_KEY}
gameLabel="Radio Traffic"
snapshot={devSnapshot}
>
<RadioDevControls transcript={transcript} messageCount={messages.length} />
</MinigameDevDock>
</div>
);
}

View file

@ -34,6 +34,7 @@ import type {
BlackjackPlayerState,
BlackjackSeatId,
BlackjackTableState,
Card,
PrivatePlayerView,
} from "./types";
import { buildPrivateView } from "./views";
@ -893,6 +894,113 @@ export function applyBlackjackAction(
return buildSnapshot(record, userId);
}
/* ------------------------------------------------------------ dev controls */
const VALID_SUITS = new Set(["s", "h", "d", "c"]);
function isDevCard(card: unknown): card is Card {
return (
typeof card === "object" &&
card !== null &&
"rank" in card &&
"suit" in card &&
typeof (card as Card).rank === "number" &&
Number.isInteger((card as Card).rank) &&
(card as Card).rank >= 2 &&
(card as Card).rank <= 14 &&
typeof (card as Card).suit === "string" &&
VALID_SUITS.has((card as Card).suit)
);
}
/** Dev controls: add (or, with a negative delta, remove) a player's chips. */
export function adjustBankroll(
tableId: string,
userId: number,
seatId: BlackjackSeatId,
delta: number,
): BlackjackSnapshot {
const record = tables.get(tableId);
if (!record) throw new Error("Table not found.");
const state = record.state;
if (!state) throw new Error("The game has not started yet.");
const player = state.players[seatId];
if (!player) throw new Error("No such player at the table.");
if (!Number.isInteger(delta) || delta === 0) {
throw new Error("Adjustment must be a non-zero whole number.");
}
const nextBankroll = Math.max(0, player.bankroll + delta);
// Restoring a bankrupt seat to at least the table minimum un-kills it, so
// the adjustment doubles as the fix for an accidentally busted player.
const revived = player.bankrupt && nextBankroll >= state.config.minBet;
record.state = {
...state,
players: state.players.map((p) =>
p.seatId === seatId
? { ...p, bankroll: nextBankroll, ...(revived ? { bankrupt: false } : {}) }
: p,
),
};
record.lastActivityAt = Date.now();
record.version += 1;
afterMutation(record);
return buildSnapshot(record, userId);
}
/**
* Dev controls: force the next card drawn (by the acting player or, once all
* hands are done, by the dealer) to be this card, by injecting it at the top
* of the shoe. The shoe is deterministic per seed (see shoe.ts), so this is
* the only way to steer a round without breaking replayability elsewhere.
*/
export function injectNextCard(tableId: string, userId: number, card: Card): BlackjackSnapshot {
const record = tables.get(tableId);
if (!record) throw new Error("Table not found.");
const state = record.state;
if (!state) throw new Error("The game has not started yet.");
if (!isDevCard(card)) throw new Error("Invalid card.");
if (state.phase === "round-complete") {
throw new Error("The round is over; the injection would be lost to the reshuffle.");
}
record.state = { ...state, shoe: [card, ...state.shoe] };
record.lastActivityAt = Date.now();
record.version += 1;
afterMutation(record);
return buildSnapshot(record, userId);
}
/**
* Dev controls: replace the dealer's hand outright (moderation override). Only
* meaningful once the initial deal has happened and before the round settles,
* i.e. during the insurance or player phases; the reveal/settle then runs
* against the replaced cards.
*/
export function setDealerHand(
tableId: string,
userId: number,
cards: Card[],
): BlackjackSnapshot {
const record = tables.get(tableId);
if (!record) throw new Error("Table not found.");
const state = record.state;
if (!state) throw new Error("The game has not started yet.");
if (!Array.isArray(cards) || cards.length < 1 || cards.length > 5) {
throw new Error("Provide between 1 and 5 cards.");
}
if (!cards.every(isDevCard)) throw new Error("Invalid card in hand.");
if (state.dealer.cards.length === 0) {
throw new Error("The dealer has not been dealt into this round yet.");
}
if (state.phase !== "insurance" && state.phase !== "player") {
throw new Error("The dealer hand can only be changed while the round is live.");
}
record.state = { ...state, dealer: { ...state.dealer, cards } };
record.lastActivityAt = Date.now();
record.version += 1;
afterMutation(record);
return buildSnapshot(record, userId);
}
/**
* Sweeps tables whose last client interaction is older than TABLE_EXPIRY_MS:
* tabs closed without leaving, abandoned waiting rooms, gone games. Session

View file

@ -34,6 +34,7 @@ import {
TICK_MS,
} from "./constants";
import type {
BomperatorAdminCommand,
BomperatorEvent,
BomperatorState,
Bomb,
@ -209,6 +210,7 @@ export function createMatchState(
roundTimerTicks: ROUND_TIMER_TICKS,
roundEndHoldTicks: 0,
suddenDeath: false,
frozen: false,
suddenDeathTicks: 0,
suddenDeathExplosions: 0,
roundWinnerSeat: null,
@ -581,6 +583,10 @@ function withEvent(state: BomperatorState, event: BomperatorEvent): BomperatorSt
* round-end checks, the round timer, and sudden-death spawning.
*/
export function tick(state: BomperatorState): BomperatorState {
// Dev-console freeze: the sim holds exactly where it is. Snapshots keep
// flowing (the registry bumps version and pushes regardless), so every
// client sees the frozen flag and the paused board.
if (state.frozen) return state;
switch (state.phase) {
case "countdown":
return tickCountdown(state);
@ -873,3 +879,83 @@ function resolveRoundEnd(state: BomperatorState, winnerSeat: number | null): Bom
export function dissolveMatch(state: BomperatorState): BomperatorState {
return { ...state, phase: "complete", endReason: "dissolved", matchWinnerSeat: null };
}
/* ------------------------------------------------------------ admin commands */
/**
* Dev-console command application: pure like everything else here (returns a
* NEW state, never mutates, no I/O). Commands that do not fit the current
* phase are silently ignored, so a stale dock click can never corrupt a match.
* The registry / arena module wrap this and fan the result out through the
* normal snapshot path, which is why every client sees cheats by next tick.
*/
export function applyAdminCommand(
state: BomperatorState,
cmd: BomperatorAdminCommand,
): BomperatorState {
switch (cmd.kind) {
case "destroyCrates": {
if (state.phase !== "battle" && state.phase !== "countdown") return state;
const grid = [...state.grid];
const hidden = [...state.hidden];
const drops = [...state.drops];
let next = state;
for (let y = 0; y < GRID_H; y += 1) {
for (let x = 0; x < GRID_W; x += 1) {
const i = idx(x, y);
if (grid[i] !== "crate") continue;
grid[i] = "empty";
const kind = hidden[i];
hidden[i] = null;
if (kind) drops.push({ x, y, kind });
next = withEvent(next, { type: "crateBroken", x, y });
}
}
if (next === state) return state;
return { ...next, grid, hidden, drops };
}
case "grantPickup": {
const player = state.players[cmd.seat];
if (!player || !player.alive) return state;
if (state.phase === "lobby" || state.phase === "complete") return state;
const players = [...state.players];
const buffed: Mutable<Player> = { ...player };
applyPowerUp(buffed, cmd.pickup);
players[cmd.seat] = buffed;
return withEvent({ ...state, players }, { type: "pickup", seat: cmd.seat, kind: cmd.pickup });
}
case "eliminate":
return eliminateSeat(state, cmd.seat);
case "freeze":
return { ...state, frozen: cmd.frozen };
case "suddenDeathNow": {
if (state.phase !== "battle" || state.suddenDeath) return state;
return withEvent(
{ ...state, suddenDeath: true, suddenDeathTicks: 1 },
{ type: "suddenDeath" },
);
}
case "setRoundTimer": {
if (!Number.isFinite(cmd.ticks)) return state;
return { ...state, roundTimerTicks: Math.max(0, Math.floor(cmd.ticks)) };
}
case "endRound": {
if (state.phase !== "battle" && state.phase !== "countdown") return state;
const winner =
cmd.winnerSeat !== null && state.players[cmd.winnerSeat] ? cmd.winnerSeat : null;
return resolveRoundEnd(state, winner);
}
default: {
const exhaustive: never = cmd;
void exhaustive;
return state;
}
}
}

View file

@ -30,6 +30,7 @@ import {
TICK_MS,
} from "./constants";
import {
applyAdminCommand,
applyInput,
createMatchState,
dissolveMatch,
@ -39,7 +40,12 @@ import {
type BomperatorInput,
} from "./engine";
import { awardBomperatorResult, type BomperatorMatchResult } from "./stats";
import type { BomperatorMatchSummary, BomperatorState, BomperatorView } from "./types";
import type {
BomperatorAdminCommand,
BomperatorMatchSummary,
BomperatorState,
BomperatorView,
} from "./types";
import { buildBomperatorView } from "./views";
import { broadcastToUser } from "@/lib/realtime/bus";
@ -505,6 +511,25 @@ export function forceExpireMatch(matchId: string): void {
disposeMatch(record);
}
/**
* Dev-console command entry point (HTTP transport). Applies the pure admin
* command to the live state and fans the result out through the normal
* snapshot push, so every client sees it by next tick. A command that
* completes the match stops the loop and awards immediately (mirrors `step`).
*/
export function applyAdminCommandFor(matchId: string, cmd: BomperatorAdminCommand): void {
const record = matches.get(matchId);
if (!record) throw new Error("Match not found.");
record.state = applyAdminCommand(record.state, cmd);
record.version += 1;
record.lastActivityAt = Date.now();
pushSnapshots(record);
if (record.state.phase === "complete") {
stopTickLoop(record);
awardCompleted(record);
}
}
function disposeMatch(record: BomperatorMatchRecord): void {
stopTickLoop(record);
awardCompleted(record);

View file

@ -122,6 +122,13 @@ export interface BomperatorState {
readonly roundEndHoldTicks: number;
/** Whether sudden death is active this round. */
readonly suddenDeath: boolean;
/**
* Dev-console freeze: while true, `tick()` returns the state untouched so
* the whole match pauses in place (snapshots keep flowing with the flag).
* Only superusers can toggle it; it survives round transitions and clears
* when the next match starts.
*/
readonly frozen: boolean;
/** Ticks until the next sudden-death explosion. */
readonly suddenDeathTicks: number;
/** Explosions spawned in sudden death this round (draw-guard counter). */
@ -189,6 +196,8 @@ export interface BomperatorView {
readonly countdownTicks: number;
readonly roundTimerTicks: number;
readonly suddenDeath: boolean;
/** True while a dev-console freeze holds the simulation. */
readonly frozen: boolean;
readonly roundWinnerSeat: number | null;
readonly matchWinnerSeat: number | null;
readonly endReason: "rounds" | "dissolved" | null;
@ -209,3 +218,28 @@ export interface BomperatorMatchSummary {
readonly createdAt: string;
readonly joined: boolean;
}
/* ------------------------------------------------------------- admin commands */
/**
* Dev-console moderation/cheat commands applied through the pure
* `applyAdminCommand` (engine), driven identically over both transports (HTTP
* registry + arena REST). Every command is validated against the current
* phase; illegal ones return the state unchanged. Cheats ride the normal
* snapshot fan-out, so every client sees them by the next tick.
*/
export type BomperatorAdminCommand =
/** Destroy every remaining crate at once, revealing all hidden power-ups. */
| { readonly kind: "destroyCrates" }
/** Grant a specific power-up to a seat (bypasses the pickup walk-over). */
| { readonly kind: "grantPickup"; readonly seat: number; readonly pickup: PowerUpKind }
/** Eliminate a technician now (no flame needed); credits no kill. */
| { readonly kind: "eliminate"; readonly seat: number }
/** Freeze or unfreeze the whole match (tick loop holds while frozen). */
| { readonly kind: "freeze"; readonly frozen: boolean }
/** Start sudden death immediately, first random blast on the next tick. */
| { readonly kind: "suddenDeathNow" }
/** Set the round timer to N ticks (clamped to >= 0). */
| { readonly kind: "setRoundTimer"; readonly ticks: number }
/** End the current round; winnerSeat null calls it a draw. */
| { readonly kind: "endRound"; readonly winnerSeat: number | null };

View file

@ -67,6 +67,7 @@ export function buildBomperatorView(
countdownTicks: state.countdownTicks,
roundTimerTicks: Math.max(0, state.roundTimerTicks),
suddenDeath: state.suddenDeath,
frozen: state.frozen,
roundWinnerSeat: state.roundWinnerSeat,
matchWinnerSeat: state.matchWinnerSeat,
endReason: state.endReason,

View file

@ -20,6 +20,7 @@ import {
} from "./constants";
import type {
ShotOutcome,
VersusAdminCommand,
VersusEndReason,
VersusFob,
VersusPlayerState,
@ -59,6 +60,8 @@ export function createVersusState(
shotsFired: 0,
startedAt: null,
completedAt: null,
revealFleets: false,
forcedShotOutcome: null,
};
}
@ -304,6 +307,8 @@ export function fireShot(
const opponentIndex: 0 | 1 = index === 0 ? 1 : 0;
const opponent = state.players[opponentIndex];
if (!opponent.fleet) return { error: "The opponent has not placed their structures." };
// Local alias: keeps the non-null fleet narrowed for the closures below.
const enemyFleet = opponent.fleet;
let impact: GridPoint;
if (player.lastImpact === null) {
@ -322,9 +327,21 @@ export function fireShot(
);
}
const targetIndex = opponent.fleet.findIndex((fob) =>
fob.cells.some((cell) => cell.x === impact.x && cell.y === impact.y),
);
// Dev-console one-shot override (see VersusState.forcedShotOutcome):
// "hit" snaps an otherwise-errant round onto the nearest un-struck enemy
// cell (a shot that already lands is left alone), "miss" suppresses damage
// even on a struck cell. The override is consumed below either way.
const forced = state.forcedShotOutcome;
const findTarget = (point: GridPoint): number =>
enemyFleet.findIndex((fob) =>
fob.cells.some((cell) => cell.x === point.x && cell.y === point.y),
);
if (forced === "hit" && findTarget(impact) === -1) {
const snapped = nearestUnstruckCell(enemyFleet, impact);
if (snapped) impact = snapped;
}
const targetIndex = forced === "miss" ? -1 : findTarget(impact);
let outcome: ShotOutcome = "miss";
let assetId: string | null = null;
@ -359,7 +376,12 @@ export function fireShot(
const players: [VersusPlayerState, VersusPlayerState] =
index === 0 ? [updatedPlayer, updatedOpponent] : [updatedOpponent, updatedPlayer];
let next: VersusState = { ...state, players, shotsFired: state.shotsFired + 1 };
let next: VersusState = {
...state,
players,
shotsFired: state.shotsFired + 1,
forcedShotOutcome: null,
};
const opponentDead = (updatedOpponent.fleet ?? []).every(
(fob) => fob.hitCells.length >= fob.size,
@ -396,3 +418,58 @@ export function resign(
export function isFleetDestroyed(fleet: readonly VersusFob[]): boolean {
return fleet.every((fob) => fob.hitCells.length >= fob.size);
}
/**
* Nearest enemy cell that has not been struck yet, by Manhattan distance from
* `from` (scan order breaks ties, so the choice is deterministic). Used by the
* dev-console forced-"hit" override. Null when the whole fleet is already hit.
*/
function nearestUnstruckCell(
fleet: readonly VersusFob[],
from: GridPoint,
): GridPoint | null {
let best: GridPoint | null = null;
let bestDistance = Number.POSITIVE_INFINITY;
for (const fob of fleet) {
for (const cell of fob.cells) {
if (fob.hitCells.some((hit) => hit.x === cell.x && hit.y === cell.y)) continue;
const distance = Math.abs(cell.x - from.x) + Math.abs(cell.y - from.y);
if (distance < bestDistance) {
bestDistance = distance;
best = cell;
}
}
}
return best;
}
/* ---------------------------------------------------------- admin commands */
/**
* Dev-console command application for versus matches. Pure like the rest of
* the engine (returns a NEW state, never mutates); commands that do not fit
* the current phase are ignored so a stale dock click cannot corrupt a match.
* The registry wraps this and pushes fresh views; versus clients poll, so the
* effect lands on the next poll.
*/
export function applyAdminCommand(state: VersusState, cmd: VersusAdminCommand): VersusState {
switch (cmd.kind) {
case "revealFleets":
if (state.revealFleets === cmd.on) return state;
return { ...state, revealFleets: cmd.on };
case "forceShotResult":
if (cmd.outcome !== null && state.phase !== "battle") return state;
if (state.forcedShotOutcome === cmd.outcome) return state;
return { ...state, forcedShotOutcome: cmd.outcome };
case "skipTurn":
return skipTurn(state);
default: {
const exhaustive: never = cmd;
void exhaustive;
return state;
}
}
}

View file

@ -26,6 +26,7 @@ import {
type FobPlacement,
} from "./constants";
import {
applyAdminCommand,
createVersusState,
fireShot,
placeFleet,
@ -35,7 +36,12 @@ import {
type VersusShotInput,
} from "./engine";
import { awardVersusResult, type VersusMatchResult } from "./stats";
import type { VersusMatchSummary, VersusMatchView, VersusState } from "./types";
import type {
VersusAdminCommand,
VersusMatchSummary,
VersusMatchView,
VersusState,
} from "./types";
import { buildVersusView } from "./views";
const MAX_SEATS = 2;
@ -327,6 +333,20 @@ export function forceExpireMatch(matchId: string): void {
disposeMatch(record);
}
/**
* Dev-console command entry point: applies the pure admin command to the live
* state and pushes fresh views to both seats. Versus clients poll, so the
* effect lands on their next fetch (and immediately via the SSE bonus push).
*/
export function applyAdminCommandFor(matchId: string, cmd: VersusAdminCommand): void {
const record = matches.get(matchId);
if (!record) throw new Error("Match not found.");
record.state = applyAdminCommand(record.state, cmd);
record.lastActivityAt = Date.now();
record.version += 1;
afterMutation(record);
}
function sweepExpiredMatches(): void {
const now = Date.now();
let expired = false;

View file

@ -63,8 +63,31 @@ export interface VersusState {
readonly shotsFired: number;
readonly startedAt: string | null;
readonly completedAt: string | null;
/**
* Dev-console flag: when true, `buildVersusView` serves BOTH fleets to
* every viewer (the hidden-information rule is lifted for debugging).
* Superuser-gated at the action boundary.
*/
readonly revealFleets: boolean;
/**
* Dev-console one-shot override consumed by the next `fireShot`: "hit" snaps
* an otherwise-missing round onto the nearest un-struck enemy cell, "miss"
* suppresses damage even on a struck cell. Null = no override in effect.
*/
readonly forcedShotOutcome: "hit" | "miss" | null;
}
/**
* Dev-console commands applied through the pure `applyAdminCommand`. The
* plan's "set grid seed" has no counterpart here: versus matches contain no
* RNG (fleets are player-placed, shots are deterministic), so there is no
* seed to set; the remaining commands map 1:1.
*/
export type VersusAdminCommand =
| { readonly kind: "revealFleets"; readonly on: boolean }
| { readonly kind: "forceShotResult"; readonly outcome: "hit" | "miss" | null }
| { readonly kind: "skipTurn" };
/* ------------------------------------------------------------------ views */
export interface VersusFobView {
@ -108,6 +131,11 @@ export interface VersusStateView {
readonly opponentReady: boolean;
readonly turnUserId: number | null;
readonly you: VersusYouView;
/**
* Present only while the dev-console reveal flag is on: the opponent's full
* fleet, served identically to both viewers. Absent in normal matches.
*/
readonly opponentFleet?: VersusFobView[];
readonly result: { readonly winnerUserId: number | null; readonly reason: VersusEndReason } | null;
}

View file

@ -56,6 +56,8 @@ export function buildVersusView(state: VersusState, index: 0 | 1): VersusStateVi
cellsHit: viewer.cellsHit,
fobsDestroyed: viewer.fobsDestroyed,
},
// Dev-console reveal: both fleets go to every viewer while the flag is on.
...(state.revealFleets ? { opponentFleet: (opponent.fleet ?? []).map(projectFob) } : {}),
result:
state.phase === "complete"
? {

View file

@ -26,6 +26,41 @@ function failure(error: string): PokerActionResult {
return { success: false, error };
}
/**
* Dev control: fold a seat out of the hand regardless of whose turn it is.
* The normal action path validates the turn; this is the moderation override
* the registry exposes only to superusers. If the folded seat was the last
* live opponent the pot is awarded, and if the fold happens to complete the
* round the state advances like any legal action would.
*/
export function forceFoldSeat(
state: PokerTableState,
seatId: PokerSeatId,
): PokerActionResult {
if (state.phase !== "betting") {
return failure("The hand is not in a betting round right now.");
}
const player = state.players[seatId];
if (!player) return failure("No player occupies that seat.");
if (player.eliminated) return failure("That player is already eliminated.");
if (player.folded) return failure("That player has already folded.");
const players = state.players.map((p, index) =>
index === seatId ? { ...p, folded: true, hasActed: true } : p,
);
let next: PokerTableState = { ...state, players };
if (livePlayers(next).length === 1) {
return { success: true, state: awardFoldOut(next) };
}
if (next.toActSeat === seatId) {
next = { ...next, toActSeat: nextToAct(next, seatId) };
}
if (isRoundComplete(next)) {
return { success: true, state: advanceState(next) };
}
return { success: true, state: next };
}
/**
* Apply a betting action for `seatId`. Bet and raise amounts are the player's
* TOTAL commitment for the current street ("raise to X"); a bet/raise equal

View file

@ -152,21 +152,13 @@ function drawBoardCards(
const STREET_ORDER: readonly PokerStreet[] = ["preflop", "flop", "turn", "river"];
/**
* Progress the state whenever it can progress on its own:
* - mid-betting-round: no-op until the round completes;
* - round complete: collect bets, deal the next street (or run the board out
* when betting is impossible), or resolve the showdown on the river;
* - hand over: start the next hand, or finish the game when one player holds
* every chip.
* Idempotent: calling it on a resting state returns that state unchanged.
* Close the current betting round and progress one step: collect bets, deal
* the next street (or run the board out when betting is impossible), or
* resolve the showdown on the river. Shared by `advanceState` (when the round
* completed legitimately) and the dev "force next street" control (which ends
* the round early regardless of pending actions).
*/
export function advanceState(state: PokerTableState): PokerTableState {
if (state.phase === "game-complete") return state;
if (state.phase === "showdown" || state.phase === "hand-complete") {
return startHand(state);
}
if (!isRoundComplete(state)) return state;
export function closeBettingRound(state: PokerTableState): PokerTableState {
const collected = state.collectedPot + sumCommitted(state);
const next: PokerTableState = {
...state,
@ -202,6 +194,24 @@ export function advanceState(state: PokerTableState): PokerTableState {
};
}
/**
* Progress the state whenever it can progress on its own:
* - mid-betting-round: no-op until the round completes;
* - round complete: collect bets, deal the next street (or run the board out
* when betting is impossible), or resolve the showdown on the river;
* - hand over: start the next hand, or finish the game when one player holds
* every chip.
* Idempotent: calling it on a resting state returns that state unchanged.
*/
export function advanceState(state: PokerTableState): PokerTableState {
if (state.phase === "game-complete") return state;
if (state.phase === "showdown" || state.phase === "hand-complete") {
return startHand(state);
}
if (!isRoundComplete(state)) return state;
return closeBettingRound(state);
}
export function createTableState(
players: readonly PokerPlayerInit[],
options: CreateTableOptions = {},

View file

@ -23,7 +23,7 @@ import { broadcast, broadcastToUser } from "@/lib/realtime/bus";
import { notifyUser } from "@/lib/notifications";
import { creditChips, readChipBankState, spendChipBuyIn } from "@/lib/minigames/chips";
import { generateTableName } from "@/lib/minigames/tableNames";
import { applyAction } from "./actions";
import { applyAction, forceFoldSeat } from "./actions";
import { getLegalActions } from "./betting";
import {
BUY_IN,
@ -33,7 +33,7 @@ import {
STARTING_STACK,
TURN_TIMEOUT_MS,
} from "./constants";
import { advanceState, awardFoldOut, createTableState } from "./engine";
import { advanceState, awardFoldOut, closeBettingRound, createTableState } from "./engine";
import { awardPokerGameResult, type PokerPlacementResult } from "./stats";
import type {
Card,
@ -120,6 +120,8 @@ interface PokerTableRecord {
leftUsers: Set<number>;
/** Users watching the running game without a seat. */
spectators: Set<number>;
/** Dev-console "reveal all hands" toggles, tracked per acting superuser. */
devRevealUsers: Set<number>;
userNames: Map<number, string>;
createdAt: string;
/** Last client interaction (poll, action, join/leave/start); drives expiry. */
@ -375,12 +377,15 @@ function buildSnapshot(record: PokerTableRecord, userId: number): PokerSnapshot
const spectator = !seated && record.spectators.has(userId);
const state = record.state;
const inEngine = seated && state !== null && seatIndex < state.players.length;
let base = state && inEngine ? buildPrivateView(state, seatIndex) : null;
// Dev-console reveal is per-viewer: only users who toggled it see every
// seat's hole cards, so the SSE fan-out can stay a single shared push.
const revealAll = record.devRevealUsers.has(userId);
let base = state && inEngine ? buildPrivateView(state, seatIndex, { revealAll }) : null;
if (base === null && spectator && state) {
// Spectators receive the public view with no seat: hole cards stay hidden
// except for live showdown reveals, and the synthetic viewer seat (-1)
// never matches a real player, so all seats render as opponents.
base = buildPrivateView(state, -1);
base = buildPrivateView(state, -1, { revealAll });
}
const you =
base === null
@ -673,6 +678,7 @@ export function createTable(userId: number, displayName: string): string {
awayUsers: new Set(),
leftUsers: new Set(),
spectators: new Set(),
devRevealUsers: new Set(),
userNames: new Map([[userId, displayName]]),
createdAt: new Date().toISOString(),
lastActivityAt: Date.now(),
@ -918,6 +924,90 @@ export function adjustStack(
return buildSnapshot(record, userId);
}
/** Dev controls: fold a seat out of the current hand (moderation override). */
export function forceFold(tableId: string, userId: number, seatId: number): PokerSnapshot {
const record = tables.get(tableId);
if (!record) throw new Error("Table not found.");
const state = record.state;
if (!state) throw new Error("The game has not started yet.");
const result = forceFoldSeat(state, seatId);
if (!result.success) throw new Error(result.error);
record.state = result.state;
record.lastActivityAt = Date.now();
record.version += 1;
afterMutation(record);
return buildSnapshot(record, userId);
}
/** Dev controls: close the betting round now and deal the next street. */
export function forceStreet(tableId: string, userId: number): PokerSnapshot {
const record = tables.get(tableId);
if (!record) throw new Error("Table not found.");
const state = record.state;
if (!state) throw new Error("The game has not started yet.");
if (state.phase !== "betting") throw new Error("There is no live betting round to close.");
record.state = closeBettingRound(state);
record.lastActivityAt = Date.now();
record.version += 1;
afterMutation(record);
return buildSnapshot(record, userId);
}
/**
* Dev controls: toggle reveal-all hole cards for the calling user only. The
* flag lives on the record per viewer, so other clients keep the normal view.
*/
export function setRevealAll(
tableId: string,
userId: number,
enabled: boolean,
): PokerSnapshot {
const record = tables.get(tableId);
if (!record) throw new Error("Table not found.");
if (enabled) record.devRevealUsers.add(userId);
else record.devRevealUsers.delete(userId);
record.lastActivityAt = Date.now();
pushTable(record);
return buildSnapshot(record, userId);
}
/**
* Dev controls for the turn clock. "reset" restarts the current player's
* timeout window; "now" forces the auto-action (check/fold) the timeout would
* have taken, immediately.
*/
export function clockControl(
tableId: string,
userId: number,
mode: "reset" | "now",
): PokerSnapshot {
const record = tables.get(tableId);
if (!record) throw new Error("Table not found.");
const state = record.state;
if (!state) throw new Error("The game has not started yet.");
if (mode === "reset") {
if (state.phase !== "betting" || state.toActSeat === null) {
throw new Error("No player is on the clock right now.");
}
scheduleTurnTimer(record);
pushTable(record);
return buildSnapshot(record, userId);
}
if (state.phase !== "betting" || state.toActSeat === null) {
throw new Error("No player is on the clock right now.");
}
const seat = state.toActSeat;
const legal = getLegalActions(state, seat);
const result = applyAction(state, seat, legal.canCheck ? "check" : "fold");
if (!result.success) throw new Error(result.error);
clearTurnTimer(record);
record.state = result.state;
record.lastActivityAt = Date.now();
record.version += 1;
afterMutation(record);
return buildSnapshot(record, userId);
}
export function applyPlayerAction(
tableId: string,
userId: number,

View file

@ -24,9 +24,10 @@ function projectPlayer(
state: PokerTableState,
player: PokerTableState["players"][number],
viewerSeat: PokerSeatId | null,
revealAll: boolean,
): PublicPlayerView {
const isViewer = viewerSeat !== null && player.seatId === viewerSeat;
const reveal = (state.phase === "showdown" && !player.folded) || isViewer;
const reveal = revealAll || (state.phase === "showdown" && !player.folded) || isViewer;
const holeCards: readonly Card[] | null =
reveal && player.holeCards.length > 0 ? player.holeCards : null;
return {
@ -49,14 +50,20 @@ function projectPlayer(
/**
* Public view of the table. Pass `viewerSeat` to also reveal that seat's own
* hole cards; pass null for a fully spectator-safe view.
* hole cards; pass null for a fully spectator-safe view. `revealAll` is the
* dev-console override that reveals every seat's hole cards; the registry only
* sets it for viewers who toggled reveal on, and that toggle is superuser-gated.
*/
export function buildPublicView(
state: PokerTableState,
viewerSeat: PokerSeatId | null,
options?: { readonly revealAll?: boolean },
): PublicTableView {
const revealAll = options?.revealAll === true;
return {
players: state.players.map((player) => projectPlayer(state, player, viewerSeat)),
players: state.players.map((player) =>
projectPlayer(state, player, viewerSeat, revealAll),
),
buttonSeat: state.buttonSeat,
smallBlindSeat: state.smallBlindSeat,
bigBlindSeat: state.bigBlindSeat,
@ -74,9 +81,13 @@ export function buildPublicView(
}
/** Everything one seated player is allowed to know, including their options. */
export function buildPrivateView(state: PokerTableState, seatId: PokerSeatId): PrivatePlayerView {
export function buildPrivateView(
state: PokerTableState,
seatId: PokerSeatId,
options?: { readonly revealAll?: boolean },
): PrivatePlayerView {
const viewer = state.players[seatId];
const publicView = buildPublicView(state, seatId);
const publicView = buildPublicView(state, seatId, options);
return {
...publicView,
viewerSeat: seatId,

View file

@ -0,0 +1,56 @@
import { expect, test } from "@playwright/test";
/**
* Smoke test for the shared minigame developer dock after the poker panel
* migration: the old inline PokerDevPanel dialog is gone, and superusers get
* the floating dock instead (collapsed Shield button -> Controls/State/Log
* tabs). The dev login seeded by global-setup holds a superuser role doc, so
* the dock must render for it; the dock's gating itself (server-side
* isSuperuser checks on every action) is covered by
* tests/int/minigame-dev-console-gating.int.spec.ts.
*/
test.describe("Minigame dev console (poker smoke)", () => {
test("superuser sees the dock on a poker table and can open all three tabs", async ({
page,
}) => {
await page.goto("/login");
await page.getByLabel("Username").fill("dev");
await page.getByLabel("Password").fill("Test123");
await page.getByRole("button", { name: "Log in" }).click();
await page.waitForURL((url) => !url.pathname.startsWith("/login"), { timeout: 30_000 });
await page.goto("/minigames/poker");
await expect(page.getByRole("heading", { name: /poker/i }).first()).toBeVisible({
timeout: 60_000,
});
await page.getByRole("button", { name: "Create table" }).click();
// Collapsed dock = the Shield button in the bottom-right corner.
const dockButton = page.getByRole("button", { name: "Developer controls" });
await expect(dockButton).toBeVisible({ timeout: 30_000 });
await dockButton.click();
await expect(page.getByText("Poker dev console")).toBeVisible({ timeout: 10_000 });
await expect(page.getByRole("tab", { name: "Controls" })).toBeVisible();
// State tab: raw snapshot JSON inspector.
await page.getByRole("tab", { name: "State" }).click();
await expect(page.getByText("Raw snapshot JSON")).toBeVisible();
await expect(page.getByText(/"tableId"/)).toBeVisible();
// Log tab: the dock logs every received snapshot version.
await page.getByRole("tab", { name: /^Log/ }).click();
await expect(page.getByText(/poker: snapshot v\d+ received/).first()).toBeVisible({
timeout: 15_000,
});
// Back to Controls: in the waiting room there is no live hand yet, so the
// per-hand sections are absent; the tab itself must stay interactive.
await page.getByRole("tab", { name: "Controls" }).click();
await expect(page.getByRole("tab", { name: "Controls" })).toHaveAttribute(
"data-state",
"active",
);
});
});

View file

@ -0,0 +1,276 @@
/**
* Dev-console admin command specs (unit-level, pure engine).
*
* Pins the contract the Minigame Developer Console relies on: applyAdminCommand
* for Ordnance Disposal and Call for Fire Versus is pure (input state never
* mutates), phase-gated (stale commands are no-ops), and produces the state
* transitions the dock buttons advertise.
*/
import { describe, expect, it } from "vitest";
import {
MAX_BOMBS,
MAX_RANGE,
applyAdminCommand,
createMatchState,
startRound,
tick,
type BomperatorAdminCommand,
type BomperatorState,
} from "@/lib/minigames/bomperator";
import {
VERSUS_BOARD_SIZE,
type FobPlacement,
} from "@/lib/minigames/call-for-fire-versus/constants";
import {
applyAdminCommand as applyVersusAdminCommand,
createVersusState,
fireShot,
placeFleet,
} from "@/lib/minigames/call-for-fire-versus/engine";
import type { VersusState } from "@/lib/minigames/call-for-fire-versus/types";
import { buildVersusView } from "@/lib/minigames/call-for-fire-versus/views";
/* ---------------------------------------------------------------- bomperator */
function battleState(playerCount = 3): BomperatorState {
const seats = Array.from({ length: playerCount }, (_, seat) => ({
seat,
userId: 7000 + seat,
name: `P${seat}`,
}));
const state = createMatchState(seats, 3, 1234);
return startRound(state);
}
/** Advance from countdown into battle. */
function inBattle(state: BomperatorState): BomperatorState {
let next = state;
for (let i = 0; i < 80 && next.phase !== "battle"; i += 1) next = tick(next);
expect(next.phase).toBe("battle");
return next;
}
function run(cmd: BomperatorAdminCommand, state: BomperatorState): BomperatorState {
const before = JSON.stringify(state);
const after = applyAdminCommand(state, cmd);
// Purity: the input state object is never mutated.
expect(JSON.stringify(state)).toBe(before);
return after;
}
describe("bomperator applyAdminCommand", () => {
it("destroyCrates clears every crate and exposes the hidden power-ups", () => {
const state = inBattle(battleState());
const cratesBefore = state.grid.filter((cell) => cell === "crate").length;
expect(cratesBefore).toBeGreaterThan(0);
const next = run({ kind: "destroyCrates" }, state);
expect(next.grid.some((cell) => cell === "crate")).toBe(false);
expect(next.drops.length).toBe(state.drops.length + cratesBefore);
expect(next.events.some((event) => event.type === "crateBroken")).toBe(true);
});
it("destroyCrates is ignored outside an active round", () => {
const lobby = createMatchState([{ seat: 0, userId: 1, name: "A" }], 3, 7);
const next = run({ kind: "destroyCrates" }, lobby);
expect(next).toBe(lobby);
});
it("grantPickup applies the power-up to a live seat and emits a pickup event", () => {
const state = inBattle(battleState());
const before = state.players[1];
const bomb = run({ kind: "grantPickup", seat: 1, pickup: "bomb" }, state);
expect(bomb.players[1].bombsMax).toBe(before.bombsMax + 1);
expect(bomb.events.at(-1)).toMatchObject({ type: "pickup", seat: 1, kind: "bomb" });
const range = run({ kind: "grantPickup", seat: 1, pickup: "range" }, state);
expect(range.players[1].range).toBe(before.range + 1);
const kick = run({ kind: "grantPickup", seat: 1, pickup: "kick" }, state);
expect(kick.players[1].kick).toBe(true);
});
it("grantPickup respects the stat caps and ignores dead or unknown seats", () => {
const state = inBattle(battleState());
let maxed = state;
for (let i = 0; i < MAX_BOMBS + 3; i += 1) {
maxed = applyAdminCommand(maxed, { kind: "grantPickup", seat: 0, pickup: "bomb" });
}
expect(maxed.players[0].bombsMax).toBe(MAX_BOMBS);
for (let i = 0; i < MAX_RANGE + 3; i += 1) {
maxed = applyAdminCommand(maxed, { kind: "grantPickup", seat: 0, pickup: "range" });
}
expect(maxed.players[0].range).toBe(MAX_RANGE);
expect(run({ kind: "grantPickup", seat: 99, pickup: "speed" }, state)).toBe(state);
const dead = applyAdminCommand(state, { kind: "eliminate", seat: 2 });
expect(run({ kind: "grantPickup", seat: 2, pickup: "speed" }, dead)).toBe(dead);
});
it("eliminate kills a live seat, credits no kill, and emits a death event", () => {
const state = inBattle(battleState());
const next = run({ kind: "eliminate", seat: 1 }, state);
expect(next.players[1].alive).toBe(false);
expect(next.players[1].deaths).toBe(state.players[1].deaths + 1);
expect(next.players.every((p) => p.kills === state.players[p.seat].kills)).toBe(true);
expect(next.events.at(-1)).toMatchObject({ type: "death", seat: 1, killerSeat: null });
});
it("freeze holds the tick loop and unfreeze resumes it", () => {
const state = inBattle(battleState());
const frozen = run({ kind: "freeze", frozen: true }, state);
expect(frozen.frozen).toBe(true);
expect(tick(frozen)).toBe(frozen);
const thawed = run({ kind: "freeze", frozen: false }, frozen);
expect(thawed.frozen).toBe(false);
expect(tick(thawed).tickCount).toBe(thawed.tickCount + 1);
});
it("suddenDeathNow arms sudden death during battle only", () => {
const state = inBattle(battleState());
const next = run({ kind: "suddenDeathNow" }, state);
expect(next.suddenDeath).toBe(true);
expect(next.events.at(-1)?.type).toBe("suddenDeath");
const already = { ...state, suddenDeath: true };
expect(run({ kind: "suddenDeathNow" }, already)).toBe(already);
const countdown = battleState();
expect(run({ kind: "suddenDeathNow" }, countdown)).toBe(countdown);
});
it("setRoundTimer clamps to zero and rejects non-finite values", () => {
const state = inBattle(battleState());
expect(run({ kind: "setRoundTimer", ticks: 40 }, state).roundTimerTicks).toBe(40);
expect(run({ kind: "setRoundTimer", ticks: -5 }, state).roundTimerTicks).toBe(0);
expect(run({ kind: "setRoundTimer", ticks: Number.NaN }, state)).toBe(state);
});
it("endRound awards the round and completes the match at the target", () => {
let state = inBattle(battleState());
state = { ...state, players: state.players.map((p) => ({ ...p, roundsWon: 2 })) };
const next = run({ kind: "endRound", winnerSeat: 0 }, state);
expect(next.players[0].roundsWon).toBe(3);
expect(next.phase).toBe("complete");
expect(next.matchWinnerSeat).toBe(0);
expect(next.endReason).toBe("rounds");
});
it("endRound with a null winner is a draw and rolls to the next round", () => {
const state = inBattle(battleState());
const next = run({ kind: "endRound", winnerSeat: null }, state);
expect(next.roundWinnerSeat).toBeNull();
expect(next.phase).toBe("roundEnd");
});
});
/* --------------------------------------------------------------- cff versus */
/** Mirrors the engine spec layout: 3x2 CP, 4-cell L depot, three 2-cell lines. */
function fleetAt(x: number, y: number): FobPlacement[] {
return [
{ assetId: "command-post", origin: { x, y }, orientation: 0 },
{ assetId: "ammo-depot", origin: { x, y: y + 4 }, orientation: 0 },
{ assetId: "radar-site", origin: { x, y: y + 5 }, orientation: 0 },
{ assetId: "fob", origin: { x, y: y + 6 }, orientation: 0 },
{ assetId: "fob-2", origin: { x, y: y + 7 }, orientation: 0 },
];
}
function versusBattle(): VersusState {
let state = createVersusState({ userId: 8001, name: "A" }, { userId: 8002, name: "B" });
const placedA = placeFleet(state, 0, fleetAt(0, 0));
if ("error" in placedA) throw new Error(placedA.error);
state = placedA.state;
const placedB = placeFleet(state, 1, fleetAt(6, 0));
if ("error" in placedB) throw new Error(placedB.error);
state = placedB.state;
expect(state.phase).toBe("battle");
return state;
}
describe("cff-versus applyAdminCommand", () => {
it("revealFleets serves both fleets to every viewer while on", () => {
const state = versusBattle();
expect(buildVersusView(state, 0).opponentFleet).toBeUndefined();
const revealed = applyVersusAdminCommand(state, { kind: "revealFleets", on: true });
const viewA = buildVersusView(revealed, 0);
const viewB = buildVersusView(revealed, 1);
expect(viewA.opponentFleet?.length).toBeGreaterThan(0);
expect(viewB.opponentFleet?.length).toBeGreaterThan(0);
// What each viewer sees as the opponent fleet is the other's real fleet.
expect(viewA.opponentFleet?.map((fob) => fob.id)).toEqual(
revealed.players[1].fleet?.map((fob) => fob.id),
);
const hidden = applyVersusAdminCommand(revealed, { kind: "revealFleets", on: false });
expect(hidden.revealFleets).toBe(false);
expect(buildVersusView(hidden, 0).opponentFleet).toBeUndefined();
});
it("forceShotResult hit snaps an errant round onto the nearest un-struck cell", () => {
const base = versusBattle();
const armed = applyVersusAdminCommand(base, { kind: "forceShotResult", outcome: "hit" });
expect(armed.forcedShotOutcome).toBe("hit");
// Fire far away from any structure: without the override this is a miss.
const farCell = { x: VERSUS_BOARD_SIZE - 1, y: VERSUS_BOARD_SIZE - 1 };
const shot = fireShot(armed, 0, { kind: "grid", grid: farCell });
if ("error" in shot) throw new Error(shot.error);
expect(shot.shot.outcome).not.toBe("miss");
expect(shot.state.players[0].cellsHit).toBe(1);
// The one-shot override is consumed.
expect(shot.state.forcedShotOutcome).toBeNull();
});
it("forceShotResult hit leaves an already-landing shot untouched", () => {
const base = versusBattle();
const enemyCell = base.players[1].fleet?.[0].cells[0];
if (!enemyCell) throw new Error("no enemy cell");
const armed = applyVersusAdminCommand(base, { kind: "forceShotResult", outcome: "hit" });
const shot = fireShot(armed, 0, { kind: "grid", grid: enemyCell });
if ("error" in shot) throw new Error(shot.error);
expect(shot.shot.grid).toEqual(enemyCell);
expect(shot.shot.outcome).not.toBe("miss");
});
it("forceShotResult miss suppresses damage even on a struck cell", () => {
const base = versusBattle();
const enemyCell = base.players[1].fleet?.[0].cells[0];
if (!enemyCell) throw new Error("no enemy cell");
const armed = applyVersusAdminCommand(base, { kind: "forceShotResult", outcome: "miss" });
const shot = fireShot(armed, 0, { kind: "grid", grid: enemyCell });
if ("error" in shot) throw new Error(shot.error);
expect(shot.shot.outcome).toBe("miss");
expect(shot.shot.assetId).toBeNull();
expect(shot.state.players[0].cellsHit).toBe(0);
expect(shot.state.forcedShotOutcome).toBeNull();
});
it("skipTurn passes the clock and clearing the override is always allowed", () => {
const state = versusBattle();
const skipped = applyVersusAdminCommand(state, { kind: "skipTurn" });
expect(skipped.turn).toBe(1);
const cleared = applyVersusAdminCommand(
{ ...state, forcedShotOutcome: "hit" },
{ kind: "forceShotResult", outcome: null },
);
expect(cleared.forcedShotOutcome).toBeNull();
});
it("is pure: input states are never mutated", () => {
const state = versusBattle();
const before = JSON.stringify(state);
applyVersusAdminCommand(state, { kind: "revealFleets", on: true });
applyVersusAdminCommand(state, { kind: "forceShotResult", outcome: "hit" });
applyVersusAdminCommand(state, { kind: "skipTurn" });
expect(JSON.stringify(state)).toBe(before);
});
});

View file

@ -0,0 +1,400 @@
/**
* Dev-console gating integration specs.
*
* Every multiplayer admin action added for the Minigame Developer Console must
* (a) reject non-superusers at the server boundary regardless of what the
* client claims, and (b) apply for superusers, leaving an `[dev-admin]` audit
* line behind. Client-side hiding of the dock is cosmetic; this file pins the
* actual security boundary on the test database.
*/
import { getPayload, type Payload, type User } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi, type MockInstance } from "vitest";
import {
createTable as createPokerTable,
forceExpireTable as forceExpirePokerTableReg,
getSnapshotFor as getPokerSnapshot,
joinTable as joinPokerTable,
startGame as startPokerGame,
} from "@/lib/minigames/poker/tables";
import {
adjustBlackjackBankroll,
forceBlackjackNextCard,
setBlackjackDealerHand,
} from "@/app/(frontend)/minigames/blackjack/actions";
import {
clearTablesForTests as clearBlackjackTables,
createTable as createBlackjackTableReg,
getSnapshotFor as getBlackjackSnapshot,
joinTable as joinBlackjackTableReg,
startGame as startBlackjackGameReg,
} from "@/lib/minigames/blackjack/tables";
import {
bomperatorAdminCommand,
forceExpireBomperatorMatch,
} from "@/app/(frontend)/minigames/bomperator/actions";
import {
clearMatchesForTests as clearBompMatches,
createMatch as createBompMatch,
getSnapshotFor as getBompSnapshot,
joinMatch as joinBompMatch,
setAutoTickForTests,
startMatch as startBompMatch,
} from "@/lib/minigames/bomperator/registry";
import { versusAdminCommand } from "@/app/(frontend)/minigames/call-for-fire-versus/actions";
import {
clearMatchesForTests as clearVersusMatches,
createMatch as createVersusMatchReg,
getSnapshotFor as getVersusSnapshot,
joinMatch as joinVersusMatchReg,
placeFleetFor,
} from "@/lib/minigames/call-for-fire-versus/registry";
import type { FobPlacement } from "@/lib/minigames/call-for-fire-versus/constants";
import {
forceFoldPokerPlayer,
forcePokerStreet,
pokerClockControl,
setPokerRevealAll,
} from "@/app/(frontend)/minigames/poker/actions";
// Mock next/headers so the actions' authenticate() can run outside a request;
// payload.auth is spied per-test to impersonate the caller.
vi.mock("next/headers", () => ({
headers: async () => new Headers(),
}));
let payload: Payload;
let authSpy: MockInstance;
let loggerSpy: MockInstance;
const RUN = `devconsole-${Date.now().toString(36)}`;
const userIds: number[] = [];
const roleIds: number[] = [];
const pokerTableIds: string[] = [];
let superUser: User;
let plainUser: User;
// Payload types ids as string | number; the game registries take numbers.
let superId = 0;
let plainId = 0;
async function makeUser(label: string, roleDocIds?: number[]): Promise<User> {
const user = (await payload.create({
collection: "users",
data: {
username: `${RUN}-${label}`,
discordUsername: `${RUN}-${label}-discord`,
displayName: `${RUN} ${label}`,
steamId: `${RUN}-steam-${label}`,
password: "Test1234",
roles: ["user"],
...(roleDocIds && roleDocIds.length > 0 ? { roleDocs: roleDocIds } : {}),
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
userIds.push(Number(user.id));
return user;
}
function asSuperuser(): void {
authSpy.mockResolvedValue({ user: superUser } as never);
}
function asPlainUser(): void {
authSpy.mockResolvedValue({ user: plainUser } as never);
}
/** Mirrors the engine spec layout: 3x2 CP, 4-cell L depot, three 2-cell lines. */
function fleetAt(x: number, y: number): FobPlacement[] {
return [
{ assetId: "command-post", origin: { x, y }, orientation: 0 },
{ assetId: "ammo-depot", origin: { x, y: y + 4 }, orientation: 0 },
{ assetId: "radar-site", origin: { x, y: y + 5 }, orientation: 0 },
{ assetId: "fob", origin: { x, y: y + 6 }, orientation: 0 },
{ assetId: "fob-2", origin: { x, y: y + 7 }, orientation: 0 },
];
}
beforeAll(async () => {
const payloadConfig = await config;
payload = await getPayload({ config: payloadConfig });
authSpy = vi.spyOn(payload, "auth");
loggerSpy = vi.spyOn(payload.logger, "info");
const superRole = await payload.create({
collection: "roles",
data: { name: `${RUN} Dev Console`, slug: `${RUN}-devconsole`, isSuperuser: true },
overrideAccess: true,
depth: 0,
});
roleIds.push(superRole.id);
superUser = await makeUser("super", [superRole.id]);
plainUser = await makeUser("plain");
superId = Number(superUser.id);
plainId = Number(plainUser.id);
});
// Registries key live tables/matches by user id, and both users stay seated in
// whatever a previous test left behind: clear every store before each test.
beforeEach(() => {
for (const tableId of pokerTableIds.splice(0)) {
forceExpirePokerTableReg(tableId, payload);
}
clearBlackjackTables();
clearBompMatches();
clearVersusMatches();
});
afterAll(async () => {
clearBompMatches();
clearVersusMatches();
for (const id of userIds) {
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => undefined);
}
for (const id of roleIds) {
await payload.delete({ collection: "roles", id, overrideAccess: true }).catch(() => undefined);
}
authSpy.mockRestore();
loggerSpy.mockRestore();
});
/* --------------------------------------------------------------------- poker */
describe("poker dev actions: gating", () => {
function setupTable(): string {
const tableId = createPokerTable(superId, "Host");
pokerTableIds.push(tableId);
joinPokerTable(tableId, plainId, "Guest");
startPokerGame(tableId, superId);
return tableId;
}
it("rejects non-superusers on every new poker dev action", async () => {
const tableId = setupTable();
asPlainUser();
const fold = await forceFoldPokerPlayer(tableId, 1);
expect(fold.success).toBe(false);
expect(fold.error).toMatch(/administrators/i);
const street = await forcePokerStreet(tableId);
expect(street.success).toBe(false);
const reveal = await setPokerRevealAll(tableId, true);
expect(reveal.success).toBe(false);
const clock = await pokerClockControl(tableId, "reset");
expect(clock.success).toBe(false);
});
it("applies for superusers and audits each action", async () => {
const tableId = setupTable();
asSuperuser();
loggerSpy.mockClear();
const reveal = await setPokerRevealAll(tableId, true);
expect(reveal.success).toBe(true);
// Reveal-all: the host's snapshot now carries the guest's hole cards.
const revealedGuest = reveal.data?.you?.players.find((p) => p.seatId === 1);
expect(revealedGuest?.holeCards?.length ?? 0).toBe(2);
const street = await forcePokerStreet(tableId);
expect(street.success).toBe(true);
const fold = await forceFoldPokerPlayer(tableId, 1);
// The forced street may have ended the hand; either the fold lands or the
// engine rejects with a phase error, but never an auth error.
if (!fold.success) expect(fold.error).not.toMatch(/administrators/i);
const logged = loggerSpy.mock.calls.map((call) => String(call[0]));
expect(logged.some((line) => line.includes("[dev-admin]") && line.includes("game=poker"))).toBe(
true,
);
expect(logged.some((line) => line.includes("action=reveal-on"))).toBe(true);
});
it("clock control reset applies for superusers while a player is on the clock", async () => {
const tableId = setupTable();
asSuperuser();
const snapshot = getPokerSnapshot(tableId, superId);
if (snapshot.you?.phase === "betting" && snapshot.you.toActSeat !== null) {
const clock = await pokerClockControl(tableId, "reset");
expect(clock.success).toBe(true);
expect(clock.data?.turnDeadline).not.toBeNull();
}
});
});
/* ---------------------------------------------------------------- blackjack */
describe("blackjack dev actions: gating", () => {
function setupTable(): string {
const tableId = createBlackjackTableReg(superId, "Host");
joinBlackjackTableReg(tableId, plainId, "Guest");
startBlackjackGameReg(tableId, superId);
return tableId;
}
it("rejects non-superusers on every new blackjack dev action", async () => {
const tableId = setupTable();
asPlainUser();
const adjust = await adjustBlackjackBankroll(tableId, 1, 100);
expect(adjust.success).toBe(false);
expect(adjust.error).toMatch(/administrators/i);
const card = await forceBlackjackNextCard(tableId, { rank: 14, suit: "s" });
expect(card.success).toBe(false);
const dealer = await setBlackjackDealerHand(tableId, [{ rank: 10, suit: "h" }]);
expect(dealer.success).toBe(false);
});
it("applies bankroll adjustment and shoe injection for superusers", async () => {
const tableId = setupTable();
asSuperuser();
loggerSpy.mockClear();
const before = getBlackjackSnapshot(tableId, superId);
const guestBankroll = before.you?.players.find((p) => p.seatId === 1)?.bankroll ?? 0;
const adjust = await adjustBlackjackBankroll(tableId, 1, 250);
expect(adjust.success).toBe(true);
const after = adjust.data?.you?.players.find((p) => p.seatId === 1)?.bankroll ?? -1;
expect(after).toBe(guestBankroll + 250);
const card = await forceBlackjackNextCard(tableId, { rank: 14, suit: "s" });
expect(card.success).toBe(true);
// Dealer override passes the auth gate; here the round has not dealt the
// dealer in yet, so the domain rule rejects it (not the permission gate).
const dealer = await setBlackjackDealerHand(tableId, [{ rank: 10, suit: "h" }]);
if (!dealer.success) expect(dealer.error).toMatch(/dealt into this round/i);
const logged = loggerSpy.mock.calls.map((call) => String(call[0]));
expect(
logged.some((line) => line.includes("[dev-admin]") && line.includes("game=blackjack")),
).toBe(true);
});
});
/* -------------------------------------------------------------- bomperator */
describe("bomperator admin command: gating", () => {
beforeAll(() => {
setAutoTickForTests(false);
});
function setupMatch(): string {
const matchId = createBompMatch(superId, "Host");
joinBompMatch(matchId, plainId, "Guest");
startBompMatch(matchId, superId);
return matchId;
}
it("rejects non-superusers and invalid command shapes", async () => {
const matchId = setupMatch();
asPlainUser();
const denied = await bomperatorAdminCommand(matchId, { kind: "destroyCrates" });
expect(denied.success).toBe(false);
expect(denied.error).toMatch(/administrators/i);
asSuperuser();
const bogus = await bomperatorAdminCommand(matchId, {
kind: "grantPickup",
seat: 999,
pickup: "laser",
} as never);
expect(bogus.success).toBe(false);
expect(bogus.error).toMatch(/invalid admin command/i);
});
it("applies destroyCrates for a superuser and audits the line", async () => {
const matchId = setupMatch();
asSuperuser();
loggerSpy.mockClear();
const before = getBompSnapshot(matchId, superId);
expect(before.grid.some((cell) => cell === 2)).toBe(true);
const result = await bomperatorAdminCommand(matchId, { kind: "destroyCrates" });
expect(result.success).toBe(true);
const after = getBompSnapshot(matchId, superId);
expect(after.grid.some((cell) => cell === 2)).toBe(false);
expect(after.version).toBeGreaterThan(before.version);
const logged = loggerSpy.mock.calls.map((call) => String(call[0]));
expect(
logged.some(
(line) =>
line.includes("[dev-admin]") &&
line.includes("game=bomperator") &&
line.includes("action=cmd:destroyCrates") &&
line.includes(`target=${matchId}`),
),
).toBe(true);
});
it("force-expire stays superuser-only", async () => {
const matchId = createBompMatch(superId, "Host");
joinBompMatch(matchId, plainId, "Guest");
asPlainUser();
const denied = await forceExpireBomperatorMatch(matchId);
expect(denied.success).toBe(false);
asSuperuser();
const ok = await forceExpireBomperatorMatch(matchId);
expect(ok.success).toBe(true);
});
});
/* ------------------------------------------------------------- cff versus */
describe("cff-versus admin command: gating", () => {
function setupMatch(): string {
const matchId = createVersusMatchReg(superId, "Host");
joinVersusMatchReg(matchId, plainId, "Guest");
placeFleetFor(matchId, superId, fleetAt(0, 0));
placeFleetFor(matchId, plainId, fleetAt(6, 0));
return matchId;
}
it("rejects non-superusers and invalid command shapes", async () => {
const matchId = setupMatch();
asPlainUser();
const denied = await versusAdminCommand(matchId, { kind: "revealFleets", on: true });
expect(denied.success).toBe(false);
expect(denied.error).toMatch(/administrators/i);
asSuperuser();
const bogus = await versusAdminCommand(matchId, { kind: "selfDestruct" } as never);
expect(bogus.success).toBe(false);
expect(bogus.error).toMatch(/invalid admin command/i);
});
it("reveal fleets + skip turn apply for a superuser and reach both viewers", async () => {
const matchId = setupMatch();
asSuperuser();
loggerSpy.mockClear();
const revealed = await versusAdminCommand(matchId, { kind: "revealFleets", on: true });
expect(revealed.success).toBe(true);
const hostView = getVersusSnapshot(matchId, superId);
const guestView = getVersusSnapshot(matchId, plainId);
expect(hostView.opponentFleet?.length).toBeGreaterThan(0);
expect(guestView.opponentFleet?.length).toBeGreaterThan(0);
const turnBefore = hostView.turnUserId;
const skipped = await versusAdminCommand(matchId, { kind: "skipTurn" });
expect(skipped.success).toBe(true);
expect(getVersusSnapshot(matchId, superId).turnUserId).not.toBe(turnBefore);
const logged = loggerSpy.mock.calls.map((call) => String(call[0]));
expect(
logged.some(
(line) =>
line.includes("[dev-admin]") &&
line.includes("game=cff-versus") &&
line.includes("action=cmd:revealFleets"),
),
).toBe(true);
});
});