Files
station-master-startos/startos/serverApi.ts
T
Jesse c95620d566 Bundle Station Master v0.5.3: games in progress, and a way to end one
Pin moves to v0.5.3, package version to 0.5.3:0.

The health check no longer just probes a port. It fetches the server's own
/api/health and reports what it says — "Multiplayer server is ready — 3
games in progress", with ", 1 waiting to start" appended only when a lobby
exists and "no games in progress" on an idle server. A server that doesn't
answer is reported as STARTING, never failed: the server replays its saved
games before binding its port, so a boot legitimately looks like nothing is
listening, and calling that a failure makes an ordinary restart look like a
crash.

Two new actions, both only-running. Games in Progress is read-only and
lists every game and lobby with players, Day/Stage/phase, who it waits on,
when it started and when it last moved. Manage Game picks one from a
dropdown built live from the server and either exports it or ends it —
ending being the only way a game finishes other than being played out,
since an abandoned game otherwise stays active and is resumed on every
restart forever. Ending always returns the deleted game's save, so nothing
is destroyed without being handed back first.

They are only-running because none of it is readable from disk: a save is a
seed plus a list of moves, so whose-turn-it-is exists only after a replay
through the engine, which lives in the game repo rather than here. The
running server has already done that work and is asked for the answer.
startos/serverApi.ts is the single place that asks.

store.json gained adminSecret (32 chars) beside joinSecret, seeded on
install and backfilled on update for a volume written before the field
existed. It is deliberately NOT the join secret: every player holds that
one, so gating a delete with it would let anyone at the table destroy
anyone else's game. init/generateJoinSecret.ts is renamed generateSecrets.ts
now that it mints both.

Also brought getJoinSecret's result strings under i18n(). They shipped as
plain strings two commits ago, which actions.md is explicit about — every
user-facing string including result titles, messages and thrown errors.
The new actions follow it, so the old one shouldn't be the odd one out.

Verified on phoenix.local, installed as an UPDATE from 0.5.2:0 rather than
a fresh install, which exercised three things at once: the boot log line
("Resuming 1 saved game(s)…"), the engine-version refusal firing for real
on a game recorded under 0.5.2, and the adminSecret backfill (store.json
came out with both secrets, 24 and 32 chars). Then, from inside the
container: the package-generated admin secret authenticating against
/api/games (200) while a wrong one is refused (403), health counts tracking
0 -> lobby 1 -> active 1 through a create/bot/start, and every field the
actions render present and correct on the listing.

NOT verified: the actions' own forms and result rendering. `start-cli
package action run` fails with a client-side deserialization error on every
action on this box — including the already-shipped get-join-secret and
actual-budget's equivalent — so it is a start-cli problem, not this
package's. The data path underneath them is verified above; the SDK
form/result rendering needs the web UI.

A test game (TRESTLE-3221, Alice + a bot) is left running on the box so
there is something for Games in Progress to show.
2026-08-21 16:00:05 -04:00

99 lines
3.2 KiB
TypeScript

import { storeJson } from './fileModels/store.json'
import { uiPort } from './utils'
import { T } from '@start9labs/start-sdk'
import { i18n } from './i18n'
/**
* The one place this package talks to the game server.
*
* Everything the health check and the actions report — how many games are running, who is in them,
* whose turn it is — exists only inside the running server. This package cannot work any of it out
* for itself: the engine lives in the game repo, and answering "whose turn is it" means replaying
* a game's whole intent history through it. So the server is asked, and these functions require
* the daemon to be up. That is why the game actions declare `allowedStatuses: 'running'`.
*/
const base = `http://localhost:${uiPort}`
export type GameRow = {
gameId: string
gameCode: string | null
state: 'running' | 'lobby'
playerCount: number
playerNames: string[]
createdAt: number
// Absent on a lobby — it has no game to be part-way through.
lastMoveAt?: number
status?: 'active' | 'finished'
day?: number
stage?: number
phase?: string
waitingOn?: { seat: number; name: string } | null
}
export type HealthCounts = { active: number; lobby: number }
/** `null` when nothing answered — a server still replaying saved games has not bound its port yet. */
export async function fetchHealth(): Promise<HealthCounts | null> {
try {
const res = await fetch(`${base}/api/health`)
if (!res.ok) return null
const body = (await res.json()) as { games?: HealthCounts }
return body.games ?? { active: 0, lobby: 0 }
} catch {
return null
}
}
async function adminFetch(
effects: T.Effects,
path: string,
init?: RequestInit,
): Promise<Response> {
const adminSecret = await storeJson.read((s) => s.adminSecret).once()
if (!adminSecret) {
throw new Error(
i18n(
'No admin secret is stored for this service, so its games cannot be managed.',
),
)
}
const res = await fetch(`${base}${path}`, {
...init,
headers: { ...init?.headers, 'x-admin-secret': adminSecret },
})
if (!res.ok) {
// 404 with a correct secret means the game is gone, not that the route is missing — the
// routes themselves 404 only when the server has no admin secret at all, and it was given
// one at install.
const detail =
res.status === 404
? i18n('that game no longer exists')
: `${i18n('the server answered')} ${res.status}`
throw new Error(`${i18n('Could not reach the game server')} — ${detail}.`)
}
return res
}
export async function listGames(effects: T.Effects): Promise<GameRow[]> {
const res = await adminFetch(effects, '/api/games')
return ((await res.json()) as { games: GameRow[] }).games
}
export async function exportGame(
effects: T.Effects,
gameId: string,
): Promise<unknown> {
const res = await adminFetch(effects, `/api/games/${gameId}/save`)
return ((await res.json()) as { save: unknown }).save
}
export async function deleteGame(
effects: T.Effects,
gameId: string,
): Promise<{ gameCode: string | null; save: unknown }> {
const res = await adminFetch(effects, `/api/games/${gameId}`, {
method: 'DELETE',
})
return (await res.json()) as { gameCode: string | null; save: unknown }
}