Files
interactive-story/frontend/src/components.jsx
T
JesseMarkowitz 8c65ae99de M2: cut the hosted product away from the local one
94 files, +1,395 -6,578. Three files are new; twenty-four are gone. The
milestone is subtraction, and what is left is the single-user local
storyteller the specification describes.

Removed in full: campaign scripting and its QuickJS sandbox; multi-user
accounts, guest sessions, login, registration and the shared demo key;
the visitor-analytics tables, dashboard and page beacon; the access log
of sign-ins, addresses and devices; per-IP and per-user rate limiting
and quotas; Render deployment config; Postgres and psycopg; cloud
inference providers, the API-key field and the key encryption that
existed to store it; session-cookie signing. None of it was hidden
behind a flag — the routes are gone and answer 404.

Two things were kept that the brief allowed keeping. The `users` table
and its foreign keys stay as an internal ownership detail, because
rewriting them out means a migration across most of the schema to
delete a column that costs nothing; nothing creates a second user and
no request carries an identity. Five inert tables and four inert
columns stay for the same reason, so an M1 campaign database opens
unchanged.

The one addition is app/endpoints.py, which decides where a story may
be sent. Loopback, RFC1918, link-local, unique-local and CGNAT — an
explicit allowlist of networks, not a guess at what `ipaddress` means
by "private", which calls the documentation ranges private and IPv6
loopback reserved. Every address a hostname resolves to must be in it,
so a split answer does not squeak through, and the rule runs both when
the endpoint is saved and before every outbound request, because a name
that resolved to the LAN this morning can resolve elsewhere this
afternoon. Known cloud hosts are named in the refusal so the error says
why rather than looking like broken DNS. TLS is never traded against
it: M1's shared trust context is intact on all four clients and there
is no way to skip verification.

The hardcoded 120-second model timeout is now a setting. That was not
theoretical — on this GPU-less four-core host a cold load of
qwen2.5:3b-instruct took 648.9 seconds to produce the first turn, while
turns 2 to 5 of the same campaign took 3.6 to 13.1. Connect stays short
at 10s so a wrong address still fails fast; the read timeout defaults
to 300s and is bounded at 3600, because "wait longer" must stay a
number.

Two defects found while testing and fixed here. An unknown /api path
fell through the SPA catch-all and came back as HTML with status 200,
so a client asking for JSON parsed a web page instead of learning the
route was gone. And AIDND_CORS_ORIGINS accepted "*", which on an
unauthenticated loopback API would hand every page on the Internet a
write handle on the campaign database; it now refuses to start.

Verified rather than assumed. Offline, on a network with no route out
and no DNS: five turns, retry with both takes retained, restart with an
identical transcript digest, a failed model call leaving the accepted
AI-turn count untouched, and a capture with zero non-loopback unicast
packets. Against a real second machine on the LAN over HTTPS with a
private CA: four turns, restart, and a capture showing 289 packets to
the approved host, 344 loopback, zero anywhere else, zero DNS queries.
Cloud and public endpoints refused with their reasons; no API key
settable; every removed route 404.

604 backend tests pass, down from 648 by the fifteen retired with the
subsystems they tested and up by the twenty-nine added for the endpoint
policy and the removed surface. The scripting tests were not deleted:
eight files used a JavaScript counter as instrumentation for the state
snapshot and rollback machinery, which M2 does not touch, so the
counter moved to the world-state engine and those tests still assert
what they always did. Frontend lint and build are clean; the image
builds, and its wheel-building stage is gone with quickjs.

No M3 work. Undo is still destructive and there is still no Redo.
2026-09-02 11:27:14 -04:00

346 lines
12 KiB
React

import { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react'
import { api } from './api'
export function downloadJSON(obj, filename) {
const blob = new Blob([JSON.stringify(obj, null, 2)], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = filename
a.click()
URL.revokeObjectURL(url)
}
export function pickJSONFile() {
return new Promise((resolve, reject) => {
const input = document.createElement('input')
input.type = 'file'
input.accept = '.json,application/json'
input.onchange = () => {
const file = input.files[0]
if (!file) return reject(new Error('No file selected'))
const reader = new FileReader()
reader.onload = () => {
try { resolve(JSON.parse(reader.result)) }
catch { reject(new Error('Not valid JSON')) }
}
reader.onerror = () => reject(new Error('Could not read file'))
reader.readAsText(file)
}
input.click()
})
}
// ---------- Scenario art ----------
// FNV-1a. Any stable hash works; the point is that a given title always maps to
// the same plate, so the library looks the same on every visit and every device.
function hashString(str) {
let hash = 2166136261
for (let i = 0; i < str.length; i++) {
hash ^= str.charCodeAt(i)
hash = Math.imul(hash, 16777619)
}
return hash >>> 0
}
// Deep jewel ramps that sit under gold without competing with it — the accent
// stays the brightest thing on the card. Ordered so adjacent library entries
// rarely land on neighbouring hues.
const ART_RAMPS = [
['#14424a', '#0b2328'], // drowned teal
['#4d2130', '#250f19'], // wine
['#2b2a5c', '#13122c'], // indigo
['#4a2a17', '#231309'], // rust
['#24401f', '#0f1c0c'], // moss
['#3a2b52', '#1b1328'], // violet ash
['#1f3346', '#0f1a25'], // cold slate
['#4a3a16', '#231b09'], // ochre
]
// Up to two letters from the title's most significant words.
function monogram(title) {
const words = (title || '')
.replace(/^\[[^\]]*\]\s*/, '') // drop a leading "[Demo]" style label
.split(/\s+/)
.filter((word) => word.length > 2 && !/^(the|and|of|a|an|from|for)$/i.test(word))
const letters = (words.length ? words : ['?']).slice(0, 2).map((w) => w[0])
return letters.join('').toUpperCase()
}
/** Initials for an NPC's avatar disc — "Bandit Leader" → BL, "gwen" → GW.
*
* Deliberately not `monogram`: that one drops short words, which is right for
* scenario titles and wrong for names, and it has no id to fall back on.
*/
export function npcInitials(name, id) {
const src = String(name || id || '?').trim() || '?'
const words = src.split(/[\s_-]+/).filter(Boolean)
const letters = words.length > 1 ? words[0][0] + words[1][0] : src.slice(0, 2)
return letters.toUpperCase()
}
/** A scenario's plate: uploaded picture, else emoji, else generated art.
*
* `large` is for the Continue cards, where the plate carries more weight. The
* generated tier means no card is ever an empty box, so a fresh library still
* reads as a shelf of distinct things.
*/
export function ScenarioArt({ image, icon, title, large = false }) {
const [failed, setFailed] = useState(false)
const ramp = ART_RAMPS[hashString(title || '') % ART_RAMPS.length]
const className = `art${large ? ' art-lg' : ''}`
// A stored image can 404 (scenario deleted its art in another tab, or an
// external URL rotted) — fall through to the generated tier rather than
// showing a broken-image glyph.
if (image && !failed) {
return (
<span className={`${className} art-photo`}>
<img src={image} alt="" loading="lazy" onError={() => setFailed(true)} />
</span>
)
}
const style = { background: `linear-gradient(150deg, ${ramp[0]}, ${ramp[1]})` }
if (icon) {
return <span className={`${className} art-icon`} style={style} aria-hidden="true">{icon}</span>
}
return (
<span className={`${className} art-mono`} style={style} aria-hidden="true">
{monogram(title)}
</span>
)
}
// ---------- Loading skeletons ----------
/** Placeholder cards shown while a list loads, so the grid doesn't pop in. */
export function CardSkeleton({ count = 3, lines = 2 }) {
return (
<div className="card-grid" aria-hidden="true">
{Array.from({ length: count }, (_, i) => (
<div key={i} className="card skeleton-card" style={{ animationDelay: `${i * 70}ms` }}>
<div className="sk sk-plate" />
<div className="sk sk-title" />
{Array.from({ length: lines }, (_, line) => (
<div key={line} className="sk sk-line" style={{ width: line === lines - 1 ? '62%' : '100%' }} />
))}
</div>
))}
</div>
)
}
// ---------- Toasts ----------
const ToastContext = createContext(() => {})
/** `const toast = useToast()` then `toast('Imported')` or `toast(msg, 'error')`. */
export function useToast() {
return useContext(ToastContext)
}
const TOAST_MS = 4200
export function ToastHost({ children }) {
const [toasts, setToasts] = useState([])
const nextId = useRef(1)
const timers = useRef(new Map())
const dismiss = useCallback((id) => {
setToasts((current) => current.filter((t) => t.id !== id))
const timer = timers.current.get(id)
if (timer) {
clearTimeout(timer)
timers.current.delete(id)
}
}, [])
const push = useCallback((message, kind = 'info') => {
const id = nextId.current++
setToasts((current) => [...current, { id, message: String(message), kind }])
timers.current.set(id, setTimeout(() => dismiss(id), TOAST_MS))
}, [dismiss])
// Clear pending timers if the host ever unmounts mid-flight.
useEffect(() => () => timers.current.forEach(clearTimeout), [])
return (
<ToastContext.Provider value={push}>
{children}
<div className="toast-host" role="status" aria-live="polite">
{toasts.map((toast) => (
<button
key={toast.id}
type="button"
className={`toast toast-${toast.kind}`}
onClick={() => dismiss(toast.id)}
title="Dismiss"
>
<span className="toast-mark" aria-hidden="true">{toast.kind === 'error' ? '✕' : '❖'}</span>
<span>{toast.message}</span>
</button>
))}
</div>
</ToastContext.Provider>
)
}
// Unique ${Placeholder} names, in order of first appearance, across the given texts.
export function extractPlaceholders(...texts) {
const names = []
for (const text of texts) {
for (const match of (text || '').matchAll(/\$\{([^}]+)\}/g)) {
const name = match[1].trim()
if (name && !names.includes(name)) names.push(name)
}
}
return names
}
// The modal shown before an adventure begins. It always asks who the player is
// playing as, and it also collects any `${Placeholder}` answers the scenario's
// text asks for.
//
// The two sets of fields are independent on purpose. A scenario that writes
// `${Name}` is asking its own question, and the persona does not answer it. No
// scenario in the repo uses placeholders at all, so the overlap is hypothetical;
// pre-filling one from the other is a small change here if it ever bites.
//
// `onSubmit` receives `{ persona, placeholders }`. Every persona field is
// optional — submitting them all blank gives an adventure with no persona,
// which behaves exactly as adventures did before personas existed.
export function BeginAdventureModal({ title, names = [], onSubmit, onCancel }) {
const [persona, setPersona] = useState({ name: '', pronouns: '', desc: '' })
const [values, setValues] = useState(Object.fromEntries(names.map((n) => [n, ''])))
const setField = (field, value) => setPersona((p) => ({ ...p, [field]: value }))
const submit = (e) => {
e.preventDefault()
onSubmit({ persona, placeholders: values })
}
return (
<div className="modal-overlay" onClick={onCancel}>
<form className="modal" onClick={(e) => e.stopPropagation()} onSubmit={submit}>
<h2>{title}</h2>
<p className="modal-hint">
Who are you playing as? Leave these blank to play as an unnamed character.
</p>
<div className="modal-row">
<label className="field">
<span className="label">Name</span>
<input
type="text"
autoFocus
maxLength={80}
placeholder="Kaelen"
value={persona.name}
onChange={(e) => setField('name', e.target.value)}
/>
</label>
<label className="field field-narrow">
<span className="label">Pronouns</span>
<input
type="text"
maxLength={40}
placeholder="they/them"
value={persona.pronouns}
onChange={(e) => setField('pronouns', e.target.value)}
/>
</label>
</div>
<label className="field">
<span className="label">Description</span>
<textarea
rows={3}
placeholder="A half-elf ranger, exiled from the northern holds. Wary of nobles, soft on strays."
value={persona.desc}
onChange={(e) => setField('desc', e.target.value)}
/>
</label>
{names.length > 0 && (
<>
<p className="modal-hint">This scenario asks a few questions before you begin.</p>
{names.map((name) => (
<label key={name} className="field">
<span className="label">{name}</span>
<input
type="text"
value={values[name]}
onChange={(e) => setValues({ ...values, [name]: e.target.value })}
/>
</label>
))}
</>
)}
<div className="modal-buttons">
<button type="button" onClick={onCancel}>Cancel</button>
<button type="submit" className="primary">Begin Adventure</button>
</div>
</form>
</div>
)
}
// Phase 8: register/login for the hosted multi-user mode. `onAuthed(me)` gets
// the fresh /auth/me payload after success.
export function AutoTextarea({ value, ...props }) {
const ref = useRef(null)
useEffect(() => {
const el = ref.current
if (!el) return
// Reset first: scrollHeight only ever grows while an explicit height is set,
// so without this the box could never shrink back down.
el.style.height = 'auto'
el.style.height = `${el.scrollHeight}px`
}, [value])
return <textarea ref={ref} value={value} {...props} />
}
// `maxLength` mirrors the column width the server enforces. Without it an
// over-long value is only rejected at save time, as a 422 the player sees as a
// toast after the text is already typed.
export function Field({ label, value, onChange, textarea, rows, placeholder, maxLength }) {
return (
<label className="field">
<span className="label">{label}</span>
{textarea ? (
<textarea rows={rows || 3} value={value} placeholder={placeholder} maxLength={maxLength}
onChange={(e) => onChange(e.target.value)} />
) : (
<input type="text" value={value} placeholder={placeholder} maxLength={maxLength}
onChange={(e) => onChange(e.target.value)} />
)}
</label>
)
}
export function StoryCardRow({ card, onChange, onDelete }) {
return (
<div className="storycard">
<div className="row">
<input type="text" placeholder="Name (not sent to AI)" value={card.name}
onChange={(e) => onChange({ ...card, name: e.target.value })} />
<input type="text" placeholder="Type (e.g. Character)" value={card.type}
onChange={(e) => onChange({ ...card, type: e.target.value })} />
</div>
<div className="row">
<input type="text" placeholder="Triggers, comma-separated" value={card.keys}
onChange={(e) => onChange({ ...card, keys: e.target.value })} />
</div>
<textarea rows={2} placeholder="Entry — sent to the AI when a trigger matches" value={card.entry}
onChange={(e) => onChange({ ...card, entry: e.target.value })} />
<div style={{ textAlign: 'right', marginTop: 6 }}>
<button className="danger" style={{ padding: '3px 10px', fontSize: '0.78rem' }} onClick={onDelete}>
Remove
</button>
</div>
</div>
)
}