Files
patriothacks/src/admin/AdminSeedPanel.tsx
T
OmO Orchestrator adb3bde4ee refactor(admin): migrate AdminSeedPanel inline styles to a CSS module
AdminSeedPanel.tsx was 100% inline-styled with hardcoded hex colors that
didn't match the app's real design tokens (e.g. error #b00020 vs the real
--color-negative #d4380d). Extract every static style={{...}} into
AdminSeedPanel.module.css, mapping each value to the matching token:
- #555 text -> var(--color-ink-soft)
- #b00020 error -> var(--color-negative)
- #1a7a1a success -> var(--color-positive)
- #8a6d00 disclaimer -> var(--color-warning-strong)
- #ddd section border -> var(--color-border)
- 24px/16px spacing -> var(--space-6)/var(--space-4)
- system-ui font stack -> var(--sans)

Follows the exact class-naming/value convention already used by the
sibling AdminAggregatePanel.module.css (container, section, heading,
description, error). No layout/structure change; visual proportions are
preserved except for the off-brand colors being corrected.

Verified: vitest run src/admin/AdminSeedPanel.test.tsx (11/11 passing),
npm run build (clean), npx oxlint on both changed files (clean), and a
Playwright before/after screenshot comparison of the live /admin route.
2026-11-20 19:57:12 -05:00

361 lines
13 KiB
TypeScript

import { useState } from "react";
import { append } from "../lib/eventlog";
import styles from "./AdminSeedPanel.module.css";
import { init as initIdentity } from "../lib/identity";
import { recordHousingAssignmentCycle } from "../lib/housing";
import {
FAIRSHARE_RESOURCES,
postFairshareFloor,
type FairshareResource,
} from "../lib/fairshare";
import { toAccountId } from "../shell/accountId";
import { AdminAggregatePanel } from "./AdminAggregatePanel";
import { loadHollowDemoFixture } from "./loadHollowDemo";
import {
RESOURCE_TYPES,
buildDemoHousingCycleInput,
validateSeedInput,
type ResourceType,
type SeedCategory,
type SeedFormInput,
} from "./seedEvents";
const emptyInput: SeedFormInput = { category: "population" };
export interface AdminSeedPanelProps {
/** Test seam: seeds Assembly's starting roster + proposal onto a
* specific `y-indexeddb` database name instead of the production
* default, so tests never share on-disk Assembly CRDT state across runs
* (mirrors `AssemblyScreen`'s own `dbName` test seam). Production always
* omits this. */
assemblyDbName?: string;
/** Test seam: passed straight through to `AdminAggregatePanel`'s own
* `endpoint` prop. Production always omits this. */
aggregateEndpoint?: string;
}
export function AdminSeedPanel({ assemblyDbName, aggregateEndpoint }: AdminSeedPanelProps = {}) {
const [input, setInput] = useState<SeedFormInput>(emptyInput);
const [error, setError] = useState<string | null>(null);
const [lastSubmitted, setLastSubmitted] = useState<string | null>(null);
const [submitting, setSubmitting] = useState(false);
const [demoStatus, setDemoStatus] = useState<string | null>(null);
const [demoLoading, setDemoLoading] = useState(false);
const [housingCycleStatus, setHousingCycleStatus] = useState<string | null>(null);
const [housingCycleRunning, setHousingCycleRunning] = useState(false);
const [floorResource, setFloorResource] = useState<FairshareResource>(FAIRSHARE_RESOURCES[0]);
const [floorValue, setFloorValue] = useState("");
const [floorError, setFloorError] = useState<string | null>(null);
const [floorStatus, setFloorStatus] = useState<string | null>(null);
const [floorSubmitting, setFloorSubmitting] = useState(false);
/**
* Thin UI wrapper around `loadHollowDemoFixture()` (plan todo 5): owns
* this panel's own `demoStatus`/`demoLoading` state, the extracted
* function itself touches none. Shares its idempotency guarantee with
* `ShellLayout`'s boot-time auto-seed, which calls the same function.
*/
async function handleLoadDemo() {
setDemoLoading(true);
setDemoStatus(null);
try {
const { alreadyLoaded } = await loadHollowDemoFixture(assemblyDbName);
setDemoStatus(
alreadyLoaded
? "Demo data already loaded - no new events appended."
: "Demo data loaded into the Event Log.",
);
} finally {
setDemoLoading(false);
}
}
/**
* Admin-panel-only housing assignment-cycle trigger (plan todo 15):
* `recordHousingAssignmentCycle()` (src/lib/housing.ts) is fully
* implemented and real but had zero non-test callers before this - no
* resident-facing button exists anywhere, since running an assignment
* cycle is a cycle-level civic action (consistent with D11's
* admin-panel-for-setup/cycle-actions pattern), never something an
* individual resident triggers for themselves. Reuses the same small,
* provably-feasible demo instance `handleLoadDemo` runs once
* automatically, so a judge can also re-run a cycle manually (e.g. to
* see the fairness-debt ledger carry forward across cycles) without
* reloading the whole demo fixture.
*/
async function handleRunHousingCycle() {
setHousingCycleRunning(true);
setHousingCycleStatus(null);
try {
const { publicKey } = await initIdentity();
const accountId = toAccountId(publicKey);
const { result } = await recordHousingAssignmentCycle(
buildDemoHousingCycleInput(accountId),
);
if (result.status === "optimal") {
setHousingCycleStatus(
`Housing assignment cycle recorded (${result.assignments.length} resident(s) assigned).`,
);
} else {
setHousingCycleStatus(`Housing assignment cycle could not run: ${result.reason}`);
}
} finally {
setHousingCycleRunning(false);
}
}
/**
* Admin-panel control for setting a per-resource Fair Share survival
* floor (plan todo 2, GAP-2): reuses the exact manual-seed-entry pattern
* above (a small form, `validateSeedInput`-style rejection before any
* append, a `data-testid` success marker) but writes through
* `postFairshareFloor()` (src/lib/fairshare.ts) instead of a `seed.*`
* payload, since a survival floor is a policy input to the CEEI solve,
* not starting configuration. `postFairshareFloor` itself rejects a
* malformed value (NaN/negative/Infinity) before signing/appending - the
* try/catch here only turns that rejection into the same inline error
* message pattern the rest of this panel already uses.
*/
async function handleSetFairshareFloor(e: React.FormEvent) {
e.preventDefault();
setFloorError(null);
setFloorStatus(null);
const parsed = Number(floorValue);
if (floorValue.trim() === "" || !Number.isFinite(parsed) || parsed < 0) {
setFloorError("Per-agent floor is required and must be a finite, non-negative number.");
return;
}
setFloorSubmitting(true);
try {
await initIdentity();
await postFairshareFloor(floorResource, parsed);
setFloorStatus(`Set a ${parsed} per-agent floor for ${floorResource}.`);
setFloorValue("");
} catch (err) {
setFloorError(err instanceof Error ? err.message : String(err));
} finally {
setFloorSubmitting(false);
}
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError(null);
setLastSubmitted(null);
const result = validateSeedInput(input);
if (!result.valid) {
setError(result.error);
return;
}
setSubmitting(true);
try {
// Same reasoning as handleLoadDemo: never assume the shell already ran
// identity.init() before this panel renders.
await initIdentity();
const stored = await append(result.payload);
setLastSubmitted(result.payload.type);
setInput({ category: input.category });
void stored;
} finally {
setSubmitting(false);
}
}
return (
<div className={styles.container}>
<h1 className={styles.title}>Admin: manual seed entry</h1>
<p className={styles.description}>
Writes starting configuration (population, resource pools, baseline
readings) as signed events into the Event Log. Not for outcome data.
</p>
<form onSubmit={handleSubmit}>
<label htmlFor="seed-category">Category</label>
<select
id="seed-category"
value={input.category}
onChange={(e) =>
setInput({ category: e.target.value as SeedCategory })
}
>
<option value="population">Population</option>
<option value="resource">Resource pool</option>
<option value="baseline">Baseline reading</option>
</select>
{input.category === "population" && (
<div>
<label htmlFor="population-count">Population count</label>
<input
id="population-count"
type="number"
value={input.populationCount ?? ""}
onChange={(e) =>
setInput({ ...input, populationCount: e.target.value })
}
/>
</div>
)}
{input.category === "resource" && (
<div>
<label htmlFor="resource-type">Resource</label>
<select
id="resource-type"
value={input.resource ?? ""}
onChange={(e) =>
setInput({ ...input, resource: e.target.value as ResourceType })
}
>
<option value="">Select a resource</option>
{RESOURCE_TYPES.map((r) => (
<option key={r} value={r}>
{r}
</option>
))}
</select>
<label htmlFor="resource-amount">Pool amount</label>
<input
id="resource-amount"
type="number"
value={input.resourceAmount ?? ""}
onChange={(e) =>
setInput({ ...input, resourceAmount: e.target.value })
}
/>
</div>
)}
{input.category === "baseline" && (
<div>
<label htmlFor="baseline-channel">Channel</label>
<input
id="baseline-channel"
type="text"
value={input.baselineChannel ?? ""}
onChange={(e) =>
setInput({ ...input, baselineChannel: e.target.value })
}
/>
<label htmlFor="baseline-value">Reading value</label>
<input
id="baseline-value"
type="number"
value={input.baselineValue ?? ""}
onChange={(e) =>
setInput({ ...input, baselineValue: e.target.value })
}
/>
</div>
)}
<button type="submit" disabled={submitting}>
Submit
</button>
</form>
{error && (
<p role="alert" className={styles.error}>
{error}
</p>
)}
{lastSubmitted && (
<p data-testid="seed-success" className={styles.success}>
Appended {lastSubmitted} to the Event Log.
</p>
)}
<section className={styles.section}>
<h2 className={styles.heading}>
Load Hollow demo{" "}
<span data-testid="demo-data-label" className={styles.demoBadge}>
Demo data
</span>
</h2>
<p className={styles.description}>
One-click bundled starting configuration (population, resource
pools, baseline readings) for a cold visitor, appended as signed
seed.* events through the exact same Event Log path as manual entry
above. Demo configuration only - never presented as live activity.
</p>
<p
data-testid="assembly-demo-fixture-disclaimer"
className={styles.disclaimer}
>
Note: any seeded Assembly roster, QV credits, and ballots are
demo-fixture data signed by this one device's single identity. They
are exempt from the live ballot-signature verification (which binds a
real ballot's voterId to the key that signed it) and are NOT a
security guarantee - only ballots cast live through the Assembly
screen by your own identity are verified and would reject a forgery.
</p>
<button type="button" onClick={handleLoadDemo} disabled={demoLoading}>
Load Hollow demo
</button>
{demoStatus && <p data-testid="demo-load-status">{demoStatus}</p>}
</section>
<section className={styles.section}>
<h2 className={styles.heading}>Fair Share: set a survival floor</h2>
<p className={styles.description}>
Guarantees every agent at least this much of a resource before the
CEEI market solves the remaining pool - clamped down automatically
if it would otherwise exceed what the pool can guarantee everyone.
</p>
<form onSubmit={handleSetFairshareFloor}>
<label htmlFor="fairshare-floor-resource">Floor resource</label>
<select
id="fairshare-floor-resource"
value={floorResource}
onChange={(e) => setFloorResource(e.target.value as FairshareResource)}
>
{FAIRSHARE_RESOURCES.map((r) => (
<option key={r} value={r}>
{r}
</option>
))}
</select>
<label htmlFor="fairshare-floor-value">Per-agent floor</label>
<input
id="fairshare-floor-value"
type="number"
value={floorValue}
onChange={(e) => setFloorValue(e.target.value)}
/>
<button type="submit" disabled={floorSubmitting}>
Set floor
</button>
</form>
{floorError && (
<p role="alert" className={styles.error}>
{floorError}
</p>
)}
{floorStatus && <p data-testid="fairshare-floor-status">{floorStatus}</p>}
</section>
<section className={styles.section}>
<h2 className={styles.heading}>Run housing assignment cycle</h2>
<p className={styles.description}>
Cycle-level civic action, not resident-facing: solves one Housing
room-slot assignment cycle against the current fairness-debt
ledger and signs/appends the result through the real Event Log
path, same as everything else on this page.
</p>
<button type="button" onClick={handleRunHousingCycle} disabled={housingCycleRunning}>
Run housing assignment cycle
</button>
{housingCycleStatus && (
<p data-testid="housing-cycle-status">{housingCycleStatus}</p>
)}
</section>
<AdminAggregatePanel endpoint={aggregateEndpoint} />
</div>
);
}