Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(verse): level up the person, their pet and every agent in the Jarvis Verse
rubenluetke10-beep29ccea5bcc96
diff --git a/jarvis/ui/web/frontend/src/components/society/arcade/RetroArcadeOverlay.tsx b/jarvis/ui/web/frontend/src/components/society/arcade/RetroArcadeOverlay.tsxindex 823ac166fd..62f6b4f541 100644--- a/jarvis/ui/web/frontend/src/components/society/arcade/RetroArcadeOverlay.tsx+++ b/jarvis/ui/web/frontend/src/components/society/arcade/RetroArcadeOverlay.tsx@@ -12,6 +12,7 @@* Phase changes are React state (rare); the loop itself runs on refs and* never sets state per frame. The HUD polls the game ten times a second.*/+import { reportWorldAction } from "../progression/progressionApi";import { useCallback, useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent } from "react";import { useReducedMotion } from "framer-motion";import { useT } from "@/i18n";@@ -147,6 +148,8 @@ export function RetroArcadeOverlay({ gameId, onClose, loadGame = loadRetroGame }const previous = readBest(gameId);const newBest = saveBest(gameId, score);const kept = Math.max(previous, score);+ // A scored round pays the person a little XP; a new record a little more (metered on the server).+ if (score > 0) void reportWorldAction(newBest ? "arcade_record" : "arcade_round");setBest(kept);setResult({ score, best: kept, newBest, won });overAt = now;diff --git a/jarvis/ui/web/frontend/src/components/society/office/GigiFlyer.tsx b/jarvis/ui/web/frontend/src/components/society/office/GigiFlyer.tsxindex 711767d30b..706cb99bef 100644--- a/jarvis/ui/web/frontend/src/components/society/office/GigiFlyer.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/GigiFlyer.tsx@@ -24,6 +24,7 @@ import { PetModel, VoxelPet, type PetDrive } from "../companion/PetModel";import type { PetMood } from "../companion/petRig";import { createGigiFlight, createGigiPose, followAnchor, stepGigiFlight, type GigiFlightMode } from "./gigiFlight";import { cameraView } from "./officeStore";+import { petBody } from "./walkerRegistry";/** Gigi's on-screen height in the office. */export const GIGI_OFFICE_SIZE_M = 0.5;@@ -179,6 +180,8 @@ export function GigiFlyer({ owner, mode, speaking, paused, reduced, clear, childreturn { geometry, shadowGeometry, positions, colours, age: new Float32Array(TRAIL_SIZE).fill(TRAIL_LIFE_S), rise: new Float32Array(TRAIL_SIZE), next: 0 };}, []);useEffect(() => () => { particles.geometry.dispose(); particles.shadowGeometry.dispose(); }, [particles]);+ // The level system's cosmetics follow the pet; nobody draws them once it is gone.+ useEffect(() => () => { petBody.active = false; }, []);useFrame((_, rawDt) => {if (paused) return;@@ -209,6 +212,10 @@ export function GigiFlyer({ owner, mode, speaking, paused, reduced, clear, child// One horizontal transform for the model, shadow and floor annotations.// The navigation target can lead this spring-smoothed position by a metre.if (groundRoot.current) groundRoot.current.position.set(pose.x, 0, pose.z);+ petBody.x = pose.x; petBody.z = pose.z; petBody.y = onFloor ? pet.heightM / 2 : pose.y;+ petBody.top = onFloor ? pet.heightM : pose.y + GIGI_OFFICE_SIZE_M * 0.55;+ petBody.sizeM = onFloor ? pet.heightM : GIGI_OFFICE_SIZE_M;+ petBody.active = !hidden;if (root.current) root.current.position.y = pose.y;if (body.current) {body.current.rotation.set(pose.pitch, pose.yaw, pose.roll, "YXZ");diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsxindex a32c4524d8..3d7edc1069 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeAgents.tsx@@ -38,6 +38,9 @@ import { officeTalkChat, useOfficeTalk } from "./officeTalk";import { deliverySpot, ERRAND_SPEED, useErrandFeed, useGigiErrands } from "./gigiErrands";import { isPaneAgentId, plateTitle } from "./codingFloor";import { agentLogoAsset } from "@/components/agentic/AgentMark";+import { LevelChip } from "../progression/LevelHud";+import { agentSubject, petSubject } from "../progression/progressionApi";+import { useProgression } from "../progression/progressionStore";/** The agent's symbol walks behind it as a little pet, about a fifth of its height. */export const PET_SIZE_M = 0.26;@@ -123,6 +126,7 @@ function Nameplate({ agent, activity, selected, onSelect, height = OFFICE_FIGURE{pane ? <PanePlateText agent={agent} state={state} /> : (<><span className="office-plate-name" title={agent.name}>{agent.name}</span>+ <PlateLevel agent={agent} />{state}</>)}@@ -132,6 +136,16 @@ function Nameplate({ agent, activity, selected, onSelect, height = OFFICE_FIGURE);}+/** An agent's level on its plate; the lead shows its pet's level, since the lead IS the pet. */+function PlateLevel({ agent }: { agent: SocietyAgent }) {+ const lead = agent.tier === "lead";+ const level = useProgression((s) => {+ if (!s.snapshot) return null;+ return s.subjects[lead ? petSubject(s.petId) : agentSubject(agent.agentId)]?.level ?? 1;+ });+ return level === null ? null : <LevelChip kind={lead ? "pet" : "agent"} level={level} />;+}+/*** The coding CLI's own mark in front of a pane's plate, instead of a lettered* hexagon: a floor of Claude panes read "C", "C", "C", which named nothing.diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsxindex 506d51e8e9..54d07c1dd8 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsx@@ -22,6 +22,9 @@ import { useOfficeDog } from "./dogLife";import { TreatBone } from "./dogProps";import { isRunning, useOfficeSettings } from "./officeSettings";import { jumpSquash, newJump, pressJump, stepJump } from "./officeJump";+import { useProgression } from "../progression/progressionStore";+import { PERSON_SUBJECT } from "../progression/progressionApi";+import { LevelChip } from "../progression/LevelHud";/** The person's pace: a brisk walk, and a sprint on Shift (m/s). */export const PLAYER_WALK_SPEED = 2.0;@@ -156,6 +159,11 @@ export function OfficePlayer({ layout, grid, look, name, awake, reduced }: {// Seated at Mission Control the camera is the character's eyes: its own figure would block the view.const firstPerson = useLeadSeat((s) => !!layout.command && s.seated === layout.command.id);const { pressed, run, jumpHeld } = useMoveKeys(awake, interact, onJump);+ // A level-up of the person's own: the character hops for joy and waves while it stands.+ useEffect(() => useProgression.subscribe((state, prev) => {+ if (state.cheerUntil > prev.cheerUntil && !reduced) pressJump(jump);+ }), [jump, reduced]);+ const level = useProgression((s) => (s.snapshot ? s.subjects[PERSON_SUBJECT]?.level ?? 1 : null));// Arrive by the elevator once per app run; coming back to the map keeps the// character where it was, unless a changed floor plan put that spot in a wall.@@ -253,7 +261,7 @@ export function OfficePlayer({ layout, grid, look, name, awake, reduced }: {applySeparation(player, separation(player, player.heading, bodiesExcept(null, null)), dt, (q) => isWalkable(grid, q));}player.moving = moved > 0;- drive.current.mode = moved > 0 ? "walk" : "idle";+ drive.current.mode = moved > 0 ? "walk" : performance.now() < useProgression.getState().cheerUntil ? "wave" : "idle";drive.current.speed = moved / Math.max(dt, 1e-3);if (group.current) {group.current.position.set(player.x, 0, player.z);@@ -288,6 +296,7 @@ export function OfficePlayer({ layout, grid, look, name, awake, reduced }: {<span className="office-plate office-plate-player" data-office-ui><span className="office-plate-badge" style={{ background: "#f5b83d" }} aria-hidden>★</span><span className="office-plate-name">{name}</span>+ {level !== null && <LevelChip kind="person" level={level} />}</span></Html>)}diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsxindex 5c5f051a52..449c1e53cd 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx@@ -47,6 +47,7 @@ import { isWalkable, nearestWalkable, type NavGrid } from "./officeNav";import { CODING_SCENE, OFFICE } from "./officePalette";import { officeSession, player as playerBody, useOfficeStore, type OfficeFloor, type Selection } from "./officeStore";import { arrivalPose } from "./officeFloors";+import { ProgressionLayer } from "../progression/ProgressionLayer";/** The person's character as a mover for Gigi to follow (the body object itself, mutated every frame). */const PLAYER_OWNER = { current: playerBody };@@ -157,6 +158,8 @@ export function OfficeScene(props: OfficeSceneProps) {)}{/* Upstairs the person's pet comes along: to the coding floor and to play in the arcade. */}{floor !== "agents" && <GigiCompanion grid={grid} awake={awake} reduced={reduced} />}+ {/* Levels: what everyone wears, level-up bursts and "+XP"; after the walkers, so it reads this frame's positions. */}+ <ProgressionLayer agents={agents} awake={awake} reduced={reduced} /><OfficeCameraRig layout={layout} overview={overview} /></>);diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsxindex 9a991037c2..02deefb806 100644--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx@@ -10,6 +10,7 @@import { Component, lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";import { useQueryClient } from "@tanstack/react-query";import { useSyncCompanionPet } from "../companion/companionPetStore";+import { useActivePet } from "@/hooks/usePets";import { advance, Canvas } from "@react-three/fiber";import { useReducedMotion } from "framer-motion";import { useCanvasAwake } from "@/hooks/useCanvasAwake";@@ -52,6 +53,12 @@ import { OfficeMinimap } from "./OfficeMinimap";import { OfficeCompass } from "./OfficeCompass";import { OfficeFullMap } from "./OfficeFullMap";import { OfficeFrameDriver } from "./OfficeFrameDriver";+import { useProgressionSync } from "../progression/useProgressionSync";+import { useProgression } from "../progression/progressionStore";+import { LevelHud, LevelToasts } from "../progression/LevelHud";+import { LevelUpBanner } from "../progression/LevelUpBanner";+import { LevelPanel } from "../progression/LevelPanel";+import "../progression/progression.css";// Only loaded when a host without its own create dialog (the IDE's side panel) spawns an agent.const CreateAgentDialog = lazy(() => import("../create/CreateAgentDialog").then((m) => ({ default: m.CreateAgentDialog })));@@ -145,6 +152,9 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenuseRosterRefresh(awake && floor === "agents");// Jarvis keeps the person company as the pet chosen in My Pets.useSyncCompanionPet();+ const petName = useActivePet()?.name || "Gigi";+ // Levels: the person, their pet and every agent earn XP for real work; the Verse shows and celebrates it.+ useProgressionSync(awake, floor);const [overview, setOverview] = useState(0);const [mapOpen, setMapOpen] = useState(false);const [profile, setProfile] = useState<PlayerProfile>(loadProfile);@@ -338,6 +348,22 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenreturn () => window.removeEventListener("keydown", onKey);}, [toggleGuide]);+ // L (or the level card) opens the progress panel, and closes it again.+ useEffect(() => {+ const onKey = (event: KeyboardEvent) => {+ if (event.code !== "KeyL" || event.repeat || event.ctrlKey || event.metaKey || event.altKey) return;+ const levels = useProgression.getState();+ if (ownsKeyboard(event.target) && !levels.panel) return;+ if (useOfficeStore.getState().selection?.kind === "arcade") return;+ event.preventDefault();+ levels.openPanel(levels.panel ? null : "you");+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, []);+ // The progress panel closes with the map.+ useEffect(() => () => useProgression.getState().openPanel(null), []);+// Leaving the map forgets panels and calls; the office opens fresh next time.useEffect(() => () => {const store = useOfficeStore.getState();@@ -369,6 +395,7 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenconst playsAsteroids = selection?.kind === "arcade" && (!playing || playing.kind === "asteroid3d");const titleKey = arcade ? "society.office.arcade_floor_title" : coding ? "society.office.coding_title" : "society.office.title";const playerName = profile.name.trim() || t("society.office.you");+ const agentNames = useMemo(() => new Map(jarvisAgents.map((a) => [a.agentId, a.name])), [jarvisAgents]);const showHintBar = useOfficeSettings((s) => s.showHintBar);const receptionOpen = selection?.kind === "checkpoint" && selection.id === "create";// Mission Control and the spawn point carry forms: they get the wide slot, like reception.@@ -406,6 +433,7 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen? t("society.office.arcade_floor_subtitle").replace("{0}", String(ARCADE_GAMES.length)): t(coding ? "society.office.coding_subtitle" : "society.office.subtitle").replace("{0}", String(active.length))}</span></div>+ <LevelHud playerName={playerName} petName={petName} compact={compact} />{arcade && <p className="office-card office-note">{t("society.office.arcade_floor_hint")}</p>}{!arcade && <div className="office-card office-counts" role="status" aria-live="polite"><span data-tone="working"><i aria-hidden />{t("society.office.count_working").replace("{0}", String(counts.working))}</span>@@ -422,6 +450,9 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen<button type="button" className="office-button" aria-pressed={follow} onClick={() => useOfficeStore.getState().setFollow(true)}>{t("society.office.me")}</button><button type="button" className="office-button" onClick={() => setOverview((v) => v + 1)}>{t("society.office.overview")}</button><button type="button" className="office-button" onClick={() => select({ kind: "checkpoint", id: "wardrobe" })}>{t("society.office.cp_wardrobe")}</button>+ <button type="button" className="office-button" aria-keyshortcuts="L" onClick={() => useProgression.getState().openPanel("you")}>+ {t("society.level.hud_button")}+ </button><button type="button" className="office-button" aria-pressed={receptionOpen} aria-keyshortcuts="H"onClick={toggleGuide}>{t("society.office.guide.hud_button")}@@ -468,6 +499,9 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen<OfficeFullMap open={mapOpen} onOpen={() => setMapOpen(true)} onClose={() => setMapOpen(false)}layout={layout} agents={agents} selectedId={selection?.kind === "agent" ? selection.id : null} />{!compact && showHintBar && <p className="office-hud office-help" data-office-ui>{t("society.office.help")}</p>}+ <LevelToasts names={agentNames} />+ <LevelPanel agents={jarvisAgents} playerName={playerName} petName={petName} />+ <LevelUpBanner playerName={playerName} petName={petName} />{creating && (<Suspense fallback={null}><CreateAgentDialog open onClose={() => setCreating(false)} onCreated={() => setCreating(false)} />diff --git a/jarvis/ui/web/frontend/src/components/society/office/walkerRegistry.ts b/jarvis/ui/web/frontend/src/components/society/office/walkerRegistry.tsindex 6461d385c6..f7334cade0 100644--- a/jarvis/ui/web/frontend/src/components/society/office/walkerRegistry.ts+++ b/jarvis/ui/web/frontend/src/components/society/office/walkerRegistry.ts@@ -32,3 +32,10 @@ export function* bodiesExcept(selfId: string | null, player: Point | null): Genefor (const [id, p] of extraBodies) if (id !== selfId) yield p;if (player) yield player;}++/**+ * The person's pet (Jarvis) as drawn right now: ground position, the height+ * of its body centre and of its top, and its size. Written by `GigiFlyer`+ * each frame; the level system's cosmetics and celebrations follow it.+ */+export const petBody = { x: 0, z: 0, y: 0, top: 0.5, sizeM: 0.5, active: false };diff --git a/jarvis/ui/web/frontend/src/components/society/progression/LevelHud.tsx b/jarvis/ui/web/frontend/src/components/society/progression/LevelHud.tsxnew file mode 100644index 0000000000..099b0f6552--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/progression/LevelHud.tsx@@ -0,0 +1,139 @@+/**+ * The level system's HUD pieces over the Verse: the person's level card (a+ * ring that fills with XP, the title, a bar with a trailing "ghost" that+ * catches up after each gain), the pet's line under it, the level chip worn+ * on name plates, and the toasts for agents that levelled up.+ */+import { useEffect, useMemo, useRef, useState } from "react";+import { useT } from "@/i18n";+import { equippedFor, levelFraction } from "./cosmetics";+import { FRAME_STYLE, type SubjectKind } from "./levelCatalog";+import { PERSON_SUBJECT, petSubject } from "./progressionApi";+import { useProgression, type Celebration } from "./progressionStore";++const TOAST_MS = 6500;++/** The frame a subject's chip wears: its chosen or best unlocked frame. */+export function useFrameStyle(kind: SubjectKind, level: number) {+ const rewards = useProgression((s) => s.snapshot?.rewards);+ const choice = useProgression((s) => (kind === "agent" ? undefined : s.choices[kind]?.frame));+ return useMemo(() => {+ const frame = rewards ? equippedFor(rewards, kind, level, choice ? { frame: choice } : {}).frame : undefined;+ return FRAME_STYLE[(frame ?? "frame_none") as keyof typeof FRAME_STYLE];+ }, [rewards, kind, level, choice]);+}++/** The small hexagon level number on a name plate. */+export function LevelChip({ kind, level }: { kind: SubjectKind; level: number }) {+ const t = useT();+ const style = useFrameStyle(kind, level);+ return (+ <span className="level-chip" title={t("society.level.level_n").replace("{0}", String(level))}+ style={{ background: style.fill, color: style.ink, boxShadow: `inset 0 0 0 1.5px ${style.ring}` }}>+ {level}+ </span>+ );+}++/** A bar whose gain lights up first and fills a beat later, so every gain reads as motion. */+export function XpBar({ fraction, kind, label }: { fraction: number; kind: SubjectKind; label: string }) {+ const [ghost, setGhost] = useState(fraction);+ const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);+ useEffect(() => {+ clearTimeout(timer.current);+ // After a level-up the bar restarts below the ghost: the ghost resets with it.+ if (fraction < ghost) { setGhost(fraction); return; }+ timer.current = setTimeout(() => setGhost(fraction), 450);+ return () => clearTimeout(timer.current);+ }, [fraction, ghost]);+ return (+ <span className="level-bar" data-kind={kind} role="progressbar" aria-label={label} aria-valuemin={0} aria-valuemax={100}+ aria-valuenow={Math.round(fraction * 100)}>+ {/* The gain shows at once in a bright segment; the solid fill slides up to it a beat later. */}+ <i className="level-bar-gain" style={{ width: `${fraction * 100}%` }} />+ <i className="level-bar-fill" style={{ width: `${Math.min(fraction, ghost) * 100}%` }} />+ </span>+ );+}++export function LevelRing({ kind, level, fraction, size = 44 }: { kind: SubjectKind; level: number; fraction: number; size?: number }) {+ const style = useFrameStyle(kind, level);+ const r = 18, c = 2 * Math.PI * r;+ return (+ <span className="level-ring" style={{ width: size, height: size }} data-kind={kind}>+ <svg viewBox="0 0 44 44" width={size} height={size} aria-hidden>+ <circle cx="22" cy="22" r={r} className="level-ring-track" />+ <circle cx="22" cy="22" r={r} className="level-ring-fill" strokeDasharray={`${c * fraction} ${c}`} transform="rotate(-90 22 22)" />+ <circle cx="22" cy="22" r="14" fill={style.fill} stroke={style.ring} strokeWidth="2" />+ </svg>+ <b style={{ color: style.ink }}>{level}</b>+ </span>+ );+}++export function LevelHud({ playerName, petName, compact }: { playerName: string; petName: string; compact: boolean }) {+ const t = useT();+ const person = useProgression((s) => s.subjects[PERSON_SUBJECT]);+ const petId = useProgression((s) => s.petId);+ const pet = useProgression((s) => s.subjects[petSubject(petId)]);+ const loaded = useProgression((s) => !!s.snapshot);+ const open = useProgression((s) => s.openPanel);+ if (!loaded) return null;+ const level = person?.level ?? 1;+ const fraction = levelFraction(person);+ const petLevel = pet?.level ?? 1;+ const xpText = person && person.xpForNext > 0+ ? t("society.level.xp_of").replace("{0}", String(person.xpIntoLevel)).replace("{1}", String(person.xpForNext))+ : person ? t("society.level.max") : t("society.level.xp_of").replace("{0}", "0").replace("{1}", "40");+ return (+ <button type="button" className="office-card level-hud" data-compact={compact || undefined} onClick={() => open("you")}+ aria-label={t("society.level.open_panel")} aria-keyshortcuts="L">+ <LevelRing kind="person" level={level} fraction={fraction} size={compact ? 34 : 44} />+ <span className="level-hud-body">+ <span className="level-hud-name">+ <strong>{playerName}</strong>+ <em>{t(`society.level.title.${person?.title || "newcomer"}`)}</em>+ </span>+ <XpBar fraction={fraction} kind="person" label={t("society.level.xp_label")} />+ {!compact && <span className="level-hud-xp">{xpText}</span>}+ {!compact && (+ <span className="level-hud-pet">+ <span>{t("society.level.pet_line").replace("{0}", petName).replace("{1}", String(petLevel))}</span>+ <XpBar fraction={levelFraction(pet)} kind="pet" label={t("society.level.pet_xp_label").replace("{0}", petName)} />+ </span>+ )}+ </span>+ </button>+ );+}++/** An agent's level-up: a quiet card in the corner, gone on its own. */+export function LevelToasts({ names }: { names: ReadonlyMap<string, string> }) {+ const t = useT();+ const toasts = useProgression((s) => s.toasts);+ const dismiss = useProgression((s) => s.dismissToast);+ useEffect(() => {+ if (toasts.length === 0) return;+ const timers = toasts.map((toast) => setTimeout(() => dismiss(toast.id), TOAST_MS));+ return () => timers.forEach(clearTimeout);+ }, [toasts, dismiss]);+ if (toasts.length === 0) return null;+ return (+ <div className="level-toasts" role="status" aria-live="polite" data-office-ui>+ {toasts.map((toast) => <LevelToast key={toast.id} toast={toast} name={names.get(toast.subjectId.slice("agent:".length)) ?? toast.subjectId.slice("agent:".length)}+ onClose={() => dismiss(toast.id)} label={t} />)}+ </div>+ );+}++function LevelToast({ toast, name, onClose, label }: { toast: Celebration; name: string; onClose: () => void; label: (key: string) => string }) {+ return (+ <button type="button" className="level-toast" onClick={onClose}>+ <LevelChip kind="agent" level={toast.level} />+ <span>+ <strong>{label("society.level.agent_up").replace("{0}", name).replace("{1}", String(toast.level))}</strong>+ <em>{toast.away ? label("society.level.while_away") : label(`society.level.title.${toast.title || "rookie"}`)}</em>+ </span>+ </button>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/progression/LevelPanel.tsx b/jarvis/ui/web/frontend/src/components/society/progression/LevelPanel.tsxnew file mode 100644index 0000000000..fec43dae6b--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/progression/LevelPanel.tsx@@ -0,0 +1,274 @@+/**+ * The progress panel (L, or a click on the level card): three tabs.+ *+ * - You / Pet: level, title and bar; what to wear in each slot (automatic,+ * none, or any unlocked piece); the reward track from level 1 to 50 with+ * the next unlock marked; and the exact rules that pay XP.+ * - Agents: every agent's level, title and bar, best first, and their rules.+ *+ * Theme tokens throughout, so it reads in light and dark mode.+ */+import { useEffect, useMemo, useRef } from "react";+import { useT } from "@/i18n";+import type { SocietyAgent } from "../data";+import { levelFraction, unlockedFor, type SlotChoice } from "./cosmetics";+import { LevelChip, LevelRing, XpBar } from "./LevelHud";+import { SLOTS, type RewardId, type SubjectKind } from "./levelCatalog";+import { agentSubject, PERSON_SUBJECT, petSubject, type RewardRow, type XpRuleRow } from "./progressionApi";+import { useProgression, type PanelTab } from "./progressionStore";+import { RewardIcon } from "./RewardIcon";+import { useLevelSound } from "./levelSounds";++const LEAD_AGENT_ID = "jarvis";++function duration(seconds: number, t: (key: string) => string): string {+ return seconds >= 60+ ? t("society.level.minutes").replace("{0}", String(Math.round(seconds / 60)))+ : t("society.level.seconds").replace("{0}", String(seconds));+}++/** The limit line under a rule: once a day, once per floor, a cooldown, a daily cap. */+export function ruleLimit(rule: XpRuleRow, t: (key: string) => string): string {+ if (rule.source === "daily_visit") return t("society.level.limit_daily");+ if (rule.source === "floor_discovered") return t("society.level.limit_floor");+ if (rule.source === "agent_hired") return t("society.level.limit_agent");+ const parts: string[] = [];+ if (rule.cooldownS > 0) parts.push(t("society.level.limit_cooldown").replace("{0}", duration(rule.cooldownS, t)));+ if (rule.dailyCap > 0) parts.push(t("society.level.limit_cap").replace("{0}", String(rule.dailyCap)));+ return parts.join(" · ");+}++function Rules({ kind }: { kind: SubjectKind }) {+ const t = useT();+ const rules = useProgression((s) => s.snapshot?.rules ?? []);+ const mine = rules.filter((r) => r.kind === kind);+ return (+ <section className="level-section">+ <h3>{t(`society.level.rules_${kind}`)}</h3>+ <ul className="level-rules">+ {mine.map((rule) => {+ const limit = ruleLimit(rule, t);+ return (+ <li key={rule.source}>+ <span className="level-rule-xp">+{rule.xp}</span>+ <span className="level-rule-text">+ <span>{t(`society.level.source.${rule.source}`)}</span>+ {limit && <em>{limit}</em>}+ </span>+ </li>+ );+ })}+ </ul>+ </section>+ );+}++function Wardrobe({ who, kind, level }: { who: "person" | "pet"; kind: SubjectKind; level: number }) {+ const t = useT();+ const rewards = useProgression((s) => s.snapshot?.rewards ?? []);+ const choices = useProgression((s) => s.choices[who] ?? {});+ const choose = useProgression((s) => s.choose);+ const open = useMemo(() => unlockedFor(rewards, kind, level), [rewards, kind, level]);+ return (+ <section className="level-section">+ <h3>{t("society.level.wear")}</h3>+ <div className="level-slots">+ {SLOTS.map((slot) => {+ const inSlot = rewards.filter((r) => r.slot === slot && r.levels[kind] !== null);+ if (inSlot.length === 0) return null;+ const current: SlotChoice = choices[slot] ?? "auto";+ const pick = (choice: SlotChoice) => choose(who, slot, choice);+ return (+ <div key={slot} className="level-slot" role="group" aria-label={t(`society.level.slot.${slot}`)}>+ <span className="level-slot-name">{t(`society.level.slot.${slot}`)}</span>+ <div className="office-chips">+ <button type="button" className="office-chip" aria-pressed={current === "auto"} onClick={() => pick("auto")}>{t("society.level.auto")}</button>+ <button type="button" className="office-chip" aria-pressed={current === "none"} onClick={() => pick("none")}>{t("society.level.none")}</button>+ {inSlot.map((reward) => {+ const unlocked = open.some((r) => r.rewardId === reward.rewardId);+ return (+ <button key={reward.rewardId} type="button" className="office-chip level-wear-chip" aria-pressed={current === reward.rewardId}+ disabled={!unlocked} onClick={() => pick(reward.rewardId)}+ title={unlocked ? undefined : t("society.level.locked_at").replace("{0}", String(reward.levels[kind]))}>+ <RewardIcon reward={reward.rewardId} locked={!unlocked} size={16} />+ {t(`society.level.reward.${reward.rewardId}`)}+ {!unlocked && <small>{t("society.level.lv").replace("{0}", String(reward.levels[kind]))}</small>}+ </button>+ );+ })}+ </div>+ </div>+ );+ })}+ </div>+ </section>+ );+}++function Track({ kind, level }: { kind: SubjectKind; level: number }) {+ const t = useT();+ const rewards = useProgression((s) => s.snapshot?.rewards ?? []);+ const titles = useProgression((s) => s.snapshot?.titles[kind] ?? []);+ const steps = useMemo(() => {+ const byLevel = new Map<number, { rewards: RewardRow[]; title?: string }>();+ for (const r of rewards) {+ const at = r.levels[kind];+ if (at === null) continue;+ const entry = byLevel.get(at) ?? { rewards: [] };+ entry.rewards.push(r);+ byLevel.set(at, entry);+ }+ for (const band of titles) {+ if (band.level <= 1) continue;+ const entry = byLevel.get(band.level) ?? { rewards: [] };+ entry.title = band.title;+ byLevel.set(band.level, entry);+ }+ return [...byLevel.entries()].sort((a, b) => a[0] - b[0]);+ }, [rewards, titles, kind]);+ const nextAt = steps.find(([at]) => at > level)?.[0];+ const track = useRef<HTMLOListElement>(null);+ // Open on the next unlock, not on level 2.+ useEffect(() => {+ track.current?.querySelector("[data-next]")?.scrollIntoView({ block: "nearest", inline: "center" });+ }, [kind]);+ return (+ <section className="level-section">+ <h3>{t("society.level.track")}</h3>+ <ol ref={track} className="level-track">+ {steps.map(([at, step]) => (+ <li key={at} data-done={level >= at || undefined} data-next={at === nextAt || undefined}>+ <span className="level-track-at">{t("society.level.lv").replace("{0}", String(at))}</span>+ <span className="level-track-items">+ {step.rewards.map((r) => (+ <span key={r.rewardId} className="level-track-item">+ <RewardIcon reward={r.rewardId as RewardId} locked={level < at} size={26} />+ <span>{t(`society.level.reward.${r.rewardId}`)}</span>+ </span>+ ))}+ {step.title && <span className="level-track-title">{t(`society.level.title.${step.title}`)}</span>}+ </span>+ </li>+ ))}+ </ol>+ </section>+ );+}++function SubjectHeader({ kind, subjectId, name }: { kind: SubjectKind; subjectId: string; name: string }) {+ const t = useT();+ const subject = useProgression((s) => s.subjects[subjectId]);+ const level = subject?.level ?? 1;+ const fraction = levelFraction(subject);+ const left = subject && subject.xpForNext > 0 ? subject.xpForNext - subject.xpIntoLevel : null;+ return (+ <div className="level-subject">+ <LevelRing kind={kind} level={level} fraction={fraction} size={58} />+ <div>+ <strong>{name}</strong>+ <em>{t(`society.level.title.${subject?.title || (kind === "pet" ? "hatchling" : "newcomer")}`)}</em>+ <XpBar fraction={fraction} kind={kind} label={t("society.level.xp_label")} />+ <span className="level-subject-xp">+ {left === null && subject ? t("society.level.max")+ : t("society.level.to_next").replace("{0}", String(left ?? 40)).replace("{1}", String(level + 1))}+ {subject ? ` · ${t("society.level.total").replace("{0}", String(subject.xp))}` : ""}+ </span>+ </div>+ </div>+ );+}++function AgentsTab({ agents }: { agents: readonly SocietyAgent[] }) {+ const t = useT();+ const subjects = useProgression((s) => s.subjects);+ const rows = useMemo(() => agents+ .filter((a) => a.agentId !== LEAD_AGENT_ID && a.tier !== "lead")+ .map((a) => ({ agent: a, subject: subjects[agentSubject(a.agentId)] }))+ .sort((a, b) => (b.subject?.xp ?? 0) - (a.subject?.xp ?? 0) || a.agent.name.localeCompare(b.agent.name)), [agents, subjects]);+ return (+ <>+ <section className="level-section">+ <h3>{t("society.level.team")}</h3>+ {rows.length === 0 ? <p className="office-hint">{t("society.level.no_agents")}</p> : (+ <ol className="level-agents">+ {rows.map(({ agent, subject }, i) => (+ <li key={agent.agentId}>+ <span className="level-agent-rank">{i + 1}</span>+ <LevelChip kind="agent" level={subject?.level ?? 1} />+ <span className="level-agent-body">+ <span><strong>{agent.name}</strong> <em>{t(`society.level.title.${subject?.title || "rookie"}`)}</em></span>+ <XpBar fraction={levelFraction(subject)} kind="agent" label={t("society.level.agent_xp_label").replace("{0}", agent.name)} />+ </span>+ </li>+ ))}+ </ol>+ )}+ </section>+ <Rules kind="agent" />+ </>+ );+}++export function LevelPanel({ agents, playerName, petName }: { agents: readonly SocietyAgent[]; playerName: string; petName: string }) {+ const t = useT();+ const tab = useProgression((s) => s.panel);+ const openPanel = useProgression((s) => s.openPanel);+ const petId = useProgression((s) => s.petId);+ const person = useProgression((s) => s.subjects[PERSON_SUBJECT]);+ const pet = useProgression((s) => s.subjects[petSubject(petId)]);+ const sound = useLevelSound();+ const panel = useRef<HTMLDivElement>(null);+ useEffect(() => {+ if (!tab) return;+ panel.current?.focus();+ const onKey = (event: KeyboardEvent) => {+ if (event.key !== "Escape") return;+ event.stopPropagation();+ openPanel(null);+ };+ window.addEventListener("keydown", onKey, true);+ return () => window.removeEventListener("keydown", onKey, true);+ }, [tab, openPanel]);+ if (!tab) return null;+ const tabs: PanelTab[] = ["you", "pet", "agents"];+ return (+ <div className="level-panel-layer" data-office-ui onPointerDown={(e) => { if (e.target === e.currentTarget) openPanel(null); }}>+ <div ref={panel} className="office-card level-panel" role="dialog" aria-modal="false" aria-labelledby="level-panel-title" tabIndex={-1}>+ <header className="level-panel-head">+ <h2 id="level-panel-title">{t("society.level.panel_title")}</h2>+ <div className="level-tabs" role="tablist">+ {tabs.map((id) => (+ <button key={id} type="button" role="tab" aria-selected={tab === id} className="level-tab" onClick={() => openPanel(id)}>+ {id === "pet" ? petName : t(`society.level.tab_${id}`)}+ </button>+ ))}+ </div>+ <button type="button" className="office-icon-button" onClick={() => openPanel(null)} aria-label={t("society.office.close")}>×</button>+ </header>+ <div className="level-panel-body">+ {tab === "you" && <>+ <SubjectHeader kind="person" subjectId={PERSON_SUBJECT} name={playerName} />+ <Wardrobe who="person" kind="person" level={person?.level ?? 1} />+ <Track kind="person" level={person?.level ?? 1} />+ <Rules kind="person" />+ </>}+ {tab === "pet" && <>+ <SubjectHeader kind="pet" subjectId={petSubject(petId)} name={petName} />+ <p className="office-hint">{t("society.level.pet_intro")}</p>+ <Wardrobe who="pet" kind="pet" level={pet?.level ?? 1} />+ <Track kind="pet" level={pet?.level ?? 1} />+ <Rules kind="pet" />+ </>}+ {tab === "agents" && <AgentsTab agents={agents} />}+ </div>+ <footer className="level-panel-foot">+ <label className="level-sound">+ <input type="checkbox" checked={sound.on} onChange={(e) => sound.set(e.target.checked)} />+ {t("society.level.sound")}+ </label>+ <span className="office-hint">{t("society.level.free_note")}</span>+ </footer>+ </div>+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/progression/LevelUpBanner.tsx b/jarvis/ui/web/frontend/src/components/society/progression/LevelUpBanner.tsxnew file mode 100644index 0000000000..5e1db4c2c5--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/progression/LevelUpBanner.tsx@@ -0,0 +1,77 @@+/**+ * The level-up banner for the person and their pet, in four beats:+ * light rays and a flash behind (0 s), "LEVEL UP" stamps in with an+ * overshoot (0.1 s), the old number rolls out and the new one in (0.35 s),+ * then the new title and each unlocked reward card slide up one after the+ * other (0.8 s on). It stays about four seconds — longer when it has+ * rewards to show — and a click or Escape closes it early. Several level-ups+ * play one after another. Reduced motion shows the same card without motion.+ */+import { useEffect } from "react";+import { useT } from "@/i18n";+import { useProgression } from "./progressionStore";+import { RewardIcon } from "./RewardIcon";++const BASE_MS = 4000;++function titleAt(bands: { level: number; title: string }[] | undefined, level: number): string {+ let title = "";+ for (const band of bands ?? []) if (level >= band.level) title = band.title;+ return title;+}++const PER_REWARD_MS = 700;++export function LevelUpBanner({ playerName, petName }: { playerName: string; petName: string }) {+ const t = useT();+ const banner = useProgression((s) => s.banners[0]);+ const dismiss = useProgression((s) => s.dismissBanner);+ const bands = useProgression((s) => (banner ? s.snapshot?.titles[banner.kind] : undefined));++ useEffect(() => {+ if (!banner) return;+ const timer = setTimeout(dismiss, BASE_MS + banner.unlocked.length * PER_REWARD_MS);+ const onKey = (event: KeyboardEvent) => { if (event.key === "Escape") { event.stopPropagation(); dismiss(); } };+ window.addEventListener("keydown", onKey, true);+ return () => { clearTimeout(timer); window.removeEventListener("keydown", onKey, true); };+ }, [banner, dismiss]);++ if (!banner) return null;+ const pet = banner.kind === "pet";+ const who = pet ? t("society.level.pet_up").replace("{0}", petName) : playerName;+ // The title line only when the climb crossed into a new title band.+ const titleChanged = !!banner.title && titleAt(bands, banner.previousLevel) !== banner.title;+ return (+ <div className="level-banner-layer" data-office-ui>+ <button type="button" key={banner.id} className="level-banner" data-kind={banner.kind} onClick={dismiss}+ aria-label={t("society.level.banner_aria").replace("{0}", who).replace("{1}", String(banner.level))}>+ <span className="level-banner-rays" aria-hidden />+ <span className="level-banner-flash" aria-hidden />+ {banner.away && <span className="level-banner-away">{t("society.level.while_away")}</span>}+ <span className="level-banner-kicker">{t("society.level.level_up")}</span>+ <span className="level-banner-number" aria-hidden>+ <span className="level-banner-old">{banner.previousLevel}</span>+ <span className="level-banner-new">{banner.level}</span>+ </span>+ <span className="level-banner-who">{who}</span>+ {titleChanged && (+ <span className="level-banner-title">+ {t("society.level.title_line").replace("{0}", t(`society.level.title.${banner.title}`))}+ </span>+ )}+ {banner.unlocked.length > 0 && (+ <span className="level-banner-rewards">+ <span className="level-banner-unlocked">{t("society.level.unlocked")}</span>+ {banner.unlocked.map((reward, i) => (+ <span key={reward} className="level-banner-reward" style={{ animationDelay: `${0.9 + i * 0.18}s` }}>+ <RewardIcon reward={reward} size={34} />+ <span>{t(`society.level.reward.${reward}`)}</span>+ </span>+ ))}+ <span className="level-banner-hint">{t(pet ? "society.level.equip_hint_pet" : "society.level.equip_hint")}</span>+ </span>+ )}+ </button>+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/progression/ProgressionLayer.tsx b/jarvis/ui/web/frontend/src/components/society/progression/ProgressionLayer.tsxnew file mode 100644index 0000000000..496a774d8f--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/progression/ProgressionLayer.tsx@@ -0,0 +1,151 @@+/**+ * Everything the level system draws inside the Verse's canvas: what the+ * person, their pet and every agent wear (trail, aura, gadget), the burst of+ * a level-up and the floating "+XP". It only reads the shared positions the+ * walkers already publish (`player`, `agentPositions`, `petBody`); it never+ * moves anyone.+ */+import { useMemo, useRef } from "react";+import { useFrame } from "@react-three/fiber";+import { useT } from "@/i18n";+import type { SocietyAgent } from "../data";+import { OFFICE_FIGURE_HEIGHT_M } from "../office/OfficeAgents";+import { player } from "../office/officeStore";+import { agentPositions, petBody } from "../office/walkerRegistry";+import { CosmeticTrail, type FlairSource, type TrailKind } from "./effects/CosmeticTrail";+import { CosmeticAura, CosmeticGadget, type AuraKind, type GadgetKind } from "./effects/CosmeticWear";+import { LevelUpBurst, XpPopup } from "./effects/LevelUpBurst";+import { equippedFor, type Loadout } from "./cosmetics";+import { agentSubject, PERSON_SUBJECT, petSubject, reportWorldAction } from "./progressionApi";+import { useProgression } from "./progressionStore";+import type { SubjectKind } from "./levelCatalog";++/** The lead is the person's pet, never an agent with its own flair. */+const LEAD_AGENT_ID = "jarvis";++const personSource: FlairSource = () => ({ x: player.x, z: player.z, heading: player.heading });+const petSource: FlairSource = () => (petBody.active ? { x: petBody.x, z: petBody.z } : null);+const petTopSource: FlairSource = () => (petBody.active ? { x: petBody.x, z: petBody.z, y: petBody.top } : null);++/** Agents carry no heading in the registry; it is read off their motion, and held while they stand. */+function agentSource(agentId: string): FlairSource {+ let last: { x: number; z: number } | null = null;+ let heading = 0;+ return () => {+ const p = agentPositions.get(agentId);+ if (!p) return null;+ if (last) {+ const dx = p.x - last.x, dz = p.z - last.z;+ if (dx * dx + dz * dz > 1e-5) heading = Math.atan2(dx, dz);+ }+ last = { x: p.x, z: p.z };+ return { x: p.x, z: p.z, heading };+ };+}++function Flair({ loadout, source, topSource, top, scale, paused, reduced }: {+ loadout: Loadout; source: FlairSource; topSource?: FlairSource; top: number; scale: number; paused: boolean; reduced: boolean;+}) {+ return (+ <>+ {loadout.aura && <CosmeticAura kind={loadout.aura as AuraKind} source={source} scale={scale} paused={paused} reduced={reduced} />}+ {loadout.trail && !reduced && <CosmeticTrail kind={loadout.trail as TrailKind} source={source} scale={scale} paused={paused} />}+ {loadout.gadget && <CosmeticGadget kind={loadout.gadget as GadgetKind} source={topSource ?? source} top={top} scale={scale}+ paused={paused} reduced={reduced} />}+ </>+ );+}++function AgentFlair({ agentId, loadout, paused, reduced }: { agentId: string; loadout: Loadout; paused: boolean; reduced: boolean }) {+ const source = useMemo(() => agentSource(agentId), [agentId]);+ return <Flair loadout={loadout} source={source} top={OFFICE_FIGURE_HEIGHT_M + 0.02} scale={1} paused={paused} reduced={reduced} />;+}++/** Where a subject stands, for a burst or a "+XP", and how tall it is there. */+function locate(subjectId: string, petId: string): { source: FlairSource; height: number; scale: number } | null {+ if (subjectId === PERSON_SUBJECT) return { source: personSource, height: OFFICE_FIGURE_HEIGHT_M, scale: 1 };+ if (subjectId === petSubject(petId)) return petBody.active ? { source: petSource, height: petBody.top, scale: 0.6 } : null;+ if (subjectId.startsWith("agent:")) {+ const id = subjectId.slice("agent:".length);+ if (!agentPositions.has(id)) return null;+ return { source: () => agentPositions.get(id) ?? null, height: OFFICE_FIGURE_HEIGHT_M, scale: 1 };+ }+ return null;+}++/** Every this many metres walked with the pet at your side, the pet earns a little XP (metered on the server). */+export const WALK_REPORT_M = 50;++/** Counts the metres the person walks while their pet is drawn beside them. */+function useWalkTogether(awake: boolean) {+ const state = useRef({ last: null as { x: number; z: number } | null, metres: 0 });+ useFrame(() => {+ const s = state.current;+ if (!awake || !petBody.active) { s.last = null; return; }+ if (s.last) {+ const step = Math.hypot(player.x - s.last.x, player.z - s.last.z);+ // An elevator ride or a floor switch is no walk.+ if (step < 1) s.metres += step;+ }+ s.last = { x: player.x, z: player.z };+ if (s.metres >= WALK_REPORT_M) {+ s.metres = 0;+ void reportWorldAction("walk_together");+ }+ });+}++const BURST_LABEL: Record<SubjectKind, string> = { person: "society.level.burst_you", pet: "society.level.burst_pet", agent: "society.level.burst_agent" };++export function ProgressionLayer({ agents, awake, reduced }: { agents: ReadonlyMap<string, SocietyAgent>; awake: boolean; reduced: boolean }) {+ const t = useT();+ const rewards = useProgression((s) => s.snapshot?.rewards);+ const subjects = useProgression((s) => s.subjects);+ const choices = useProgression((s) => s.choices);+ const petId = useProgression((s) => s.petId);+ const bursts = useProgression((s) => s.bursts);+ const popups = useProgression((s) => s.popups);+ const paused = !awake;++ // Popups and bursts expire on the scene's own clock.+ useFrame(() => useProgression.getState().expire(performance.now()));+ useWalkTogether(awake);++ const personLevel = subjects[PERSON_SUBJECT]?.level ?? 1;+ const petLevel = subjects[petSubject(petId)]?.level ?? 1;+ const personLoadout = useMemo(() => (rewards ? equippedFor(rewards, "person", personLevel, choices.person) : {}), [rewards, personLevel, choices.person]);+ const petLoadout = useMemo(() => (rewards ? equippedFor(rewards, "pet", petLevel, choices.pet) : {}), [rewards, petLevel, choices.pet]);+ const agentLoadouts = useMemo(() => {+ if (!rewards) return [];+ const out: { agentId: string; loadout: Loadout }[] = [];+ for (const id of agents.keys()) {+ if (id === LEAD_AGENT_ID) continue;+ const level = subjects[agentSubject(id)]?.level;+ if (!level || level < 2) continue;+ const loadout = equippedFor(rewards, "agent", level);+ if (loadout.aura || loadout.trail || loadout.gadget) out.push({ agentId: id, loadout });+ }+ return out;+ }, [rewards, agents, subjects]);++ return (+ <group>+ <Flair loadout={personLoadout} source={personSource} top={OFFICE_FIGURE_HEIGHT_M + 0.02} scale={1} paused={paused} reduced={reduced} />+ <Flair loadout={petLoadout} source={petSource} topSource={petTopSource} top={0.5} scale={0.55} paused={paused} reduced={reduced} />+ {agentLoadouts.map(({ agentId, loadout }) => <AgentFlair key={agentId} agentId={agentId} loadout={loadout} paused={paused} reduced={reduced} />)}+ {bursts.map((burst) => {+ const where = locate(burst.subjectId, petId);+ if (!where) return null;+ return <LevelUpBurst key={burst.id} source={where.source} kind={burst.kind} level={burst.level} label={t(BURST_LABEL[burst.kind])}+ height={where.height} scale={where.scale} reduced={reduced} />;+ })}+ {popups.map((popup) => {+ const where = locate(popup.subjectId, petId);+ const at = where?.source();+ if (!where || !at) return null;+ const kind = popup.subjectId === PERSON_SUBJECT ? "person" : popup.subjectId.startsWith("pet:") ? "pet" : "agent";+ return <XpPopup key={popup.id} x={at.x} z={at.z} y={where.height + 0.3} xp={popup.xp} kind={kind} />;+ })}+ </group>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/progression/RewardIcon.tsx b/jarvis/ui/web/frontend/src/components/society/progression/RewardIcon.tsxnew file mode 100644index 0000000000..0aee878423--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/progression/RewardIcon.tsx@@ -0,0 +1,33 @@+/**+ * A cosmetic's small picture for the HUD and the progress panel: its slot's+ * glyph on a tile in the effect's own colours. Purely decorative — the name+ * always sits next to it.+ */+import { EFFECT_COLOURS, FRAME_STYLE, slotOf, type RewardId } from "./levelCatalog";++function tileColours(reward: RewardId): [string, string] {+ if (reward.startsWith("frame_")) {+ const style = FRAME_STYLE[reward as keyof typeof FRAME_STYLE];+ return [style.ring, style.fill];+ }+ const colours = EFFECT_COLOURS[reward as keyof typeof EFFECT_COLOURS];+ return [colours[0], colours[colours.length - 1]];+}++function Glyph({ reward }: { reward: RewardId }) {+ const slot = slotOf(reward);+ if (slot === "frame") return <path d="M7 2.5h10l5 9.5-5 9.5H7l-5-9.5z" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinejoin="round" />;+ if (slot === "aura") return <><ellipse cx="12" cy="16" rx="9" ry="3.6" fill="none" stroke="currentColor" strokeWidth="2" /><circle cx="12" cy="9" r="3" fill="currentColor" /></>;+ if (slot === "trail") return <><circle cx="6" cy="17" r="2.2" fill="currentColor" /><circle cx="12" cy="12" r="2.6" fill="currentColor" /><circle cx="18.5" cy="6.5" r="3" fill="currentColor" /></>;+ return <path d="M12 2.8l2.6 5.6 6.1.7-4.5 4.2 1.2 6-5.4-3-5.4 3 1.2-6L3.3 9.1l6.1-.7z" fill="currentColor" />;+}++export function RewardIcon({ reward, locked = false, size = 30 }: { reward: RewardId; locked?: boolean; size?: number }) {+ const [a, b] = tileColours(reward);+ return (+ <span className="level-reward-icon" data-locked={locked || undefined} aria-hidden+ style={{ width: size, height: size, background: locked ? undefined : `linear-gradient(145deg, ${a}, ${b})` }}>+ <svg viewBox="0 0 24 24" width={size * 0.6} height={size * 0.6}><Glyph reward={reward} /></svg>+ </span>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/progression/cosmetics.ts b/jarvis/ui/web/frontend/src/components/society/progression/cosmetics.tsnew file mode 100644index 0000000000..1a5aaf7117--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/progression/cosmetics.ts@@ -0,0 +1,70 @@+/**+ * Which cosmetics a subject wears. Pure: the level comes from the server,+ * the unlock levels from the rulebook, and the person's own choice (for+ * themself and their pet) from browser storage. Agents always wear the best+ * they have unlocked; so does anyone who never chose.+ */+import type { RewardRow, SubjectLevel } from "./progressionApi";+import { SLOTS, type RewardId, type Slot, type SubjectKind } from "./levelCatalog";++/** A slot left on "automatic" wears the latest unlock; "none" wears nothing. */+export type SlotChoice = RewardId | "none" | "auto";+export type Loadout = Partial<Record<Slot, RewardId>>;++export function unlockedFor(rewards: readonly RewardRow[], kind: SubjectKind, level: number): RewardRow[] {+ return rewards.filter((r) => { const at = r.levels[kind]; return at !== null && level >= at; });+}++export function equippedFor(rewards: readonly RewardRow[], kind: SubjectKind, level: number,+ choices: Partial<Record<Slot, SlotChoice>> = {}): Loadout {+ const open = unlockedFor(rewards, kind, level);+ const loadout: Loadout = {};+ for (const slot of SLOTS) {+ const choice = choices[slot] ?? "auto";+ if (choice === "none") continue;+ const inSlot = open.filter((r) => r.slot === slot);+ const picked = choice !== "auto" ? inSlot.find((r) => r.rewardId === choice) : undefined;+ const best = inSlot.reduce<RewardRow | undefined>((top, r) => (!top || (r.levels[kind] ?? 0) >= (top.levels[kind] ?? 0) ? r : top), undefined);+ const wear = picked ?? best;+ if (wear) loadout[slot] = wear.rewardId;+ }+ return loadout;+}++/** XP gathered into the current level and the level's size, from the curve the server sent. */+export function progressFor(levelXp: readonly number[], totalXp: number, level: number): { into: number; size: number } {+ const start = levelXp[level - 1] ?? 0;+ const next = levelXp[level];+ return { into: Math.max(0, totalXp - start), size: next === undefined ? 0 : Math.max(1, next - start) };+}++/** A subject's place on its level bar, 0..1 (1 at the cap). */+export function levelFraction(subject: Pick<SubjectLevel, "xpIntoLevel" | "xpForNext"> | undefined): number {+ if (!subject) return 0;+ if (subject.xpForNext <= 0) return 1;+ return Math.max(0, Math.min(1, subject.xpIntoLevel / subject.xpForNext));+}++const CHOICES_KEY = "jarvis.verse.cosmetics.v1";++export type ChoiceBook = Partial<Record<"person" | "pet", Partial<Record<Slot, SlotChoice>>>>;++export function loadChoices(): ChoiceBook {+ try {+ const raw = typeof localStorage === "undefined" ? null : localStorage.getItem(CHOICES_KEY);+ const parsed = raw ? (JSON.parse(raw) as unknown) : null;+ return parsed && typeof parsed === "object" ? (parsed as ChoiceBook) : {};+ } catch (error) {+ // Blocked storage: everyone wears their best unlocks, which is the default anyway.+ console.debug("Verse cosmetics choices unavailable", error);+ return {};+ }+}++export function saveChoices(book: ChoiceBook): void {+ try {+ localStorage.setItem(CHOICES_KEY, JSON.stringify(book));+ } catch (error) {+ console.debug("Verse cosmetics choices not saved", error);+ }+}diff --git a/jarvis/ui/web/frontend/src/components/society/progression/effects/CosmeticTrail.tsx b/jarvis/ui/web/frontend/src/components/society/progression/effects/CosmeticTrail.tsxnew file mode 100644index 0000000000..1faea9d8a2--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/progression/effects/CosmeticTrail.tsx@@ -0,0 +1,229 @@+/**+ * The trail a levelled-up figure leaves while it moves: glowing footprints,+ * sparkles, a comet tail, a neon ribbon, a rainbow or star dust. Every trail+ * lives in world space (it stays where it was drawn and fades), is one draw+ * call, and recycles a fixed pool, so a long walk never allocates.+ */+import { useEffect, useLayoutEffect, useMemo, useRef } from "react";+import { useFrame } from "@react-three/fiber";+import {+ AdditiveBlending, BufferAttribute, BufferGeometry, Color, DoubleSide, Euler, InstancedMesh, Matrix4, PlaneGeometry,+ Quaternion, Vector3, type Points,+} from "three";+import { EFFECT_COLOURS, type RewardId } from "../levelCatalog";+import { footprintTexture, glowTexture, starTexture } from "./flairTextures";+import { footprintAt, pruneSamples, pushSample, rainbowHue, RIBBON_MAX_SAMPLES, STEP_LENGTH_M, writeRibbon, type TrailSample } from "./trailModel";++export type TrailKind = Extract<RewardId, `trail_${string}`>;++/** Where the wearer is now; null hides nothing but stops new trail. */+export type FlairSource = () => { x: number; z: number; heading?: number; y?: number } | null;++const RIBBON_LIFE_S = 0.9;+const RIBBON_WIDTH: Partial<Record<TrailKind, number>> = { trail_comet: 0.34, trail_neon: 0.22, trail_rainbow: 0.4 };++export function CosmeticTrail({ kind, source, scale = 1, paused }: { kind: TrailKind; source: FlairSource; scale?: number; paused: boolean }) {+ if (kind === "trail_footprints") return <Footprints source={source} scale={scale} paused={paused} />;+ if (kind === "trail_sparkle" || kind === "trail_stardust") return <Sparks kind={kind} source={source} scale={scale} paused={paused} />;+ return <Ribbon kind={kind} source={source} scale={scale} paused={paused} />;+}++// ------------------------------------------------------------------ footprints++const PRINTS = 16;+const PRINT_LIFE_S = 2.6;++function Footprints({ source, scale, paused }: { source: FlairSource; scale: number; paused: boolean }) {+ const mesh = useRef<InstancedMesh>(null);+ const state = useRef({ travelled: 0, left: true, last: null as { x: number; z: number } | null, next: 0, clock: 0 });+ const born = useMemo(() => new Float32Array(PRINTS).fill(-99), []);+ const geometry = useMemo(() => new PlaneGeometry(0.13 * scale, 0.2 * scale), [scale]);+ useEffect(() => () => geometry.dispose(), [geometry]);+ const tmp = useMemo(() => ({ m: new Matrix4(), q: new Quaternion(), e: new Euler(), p: new Vector3(), s: new Vector3(1, 1, 1), c: new Color() }), []);+ const base = useMemo(() => new Color(EFFECT_COLOURS.trail_footprints[0]), []);++ // Before the first frame every print is hidden (zero scale, black), so none flashes at the origin.+ useLayoutEffect(() => {+ const m = mesh.current;+ if (!m) return;+ tmp.c.setRGB(0, 0, 0);+ for (let i = 0; i < PRINTS; i++) { m.setColorAt(i, tmp.c); tmp.m.makeScale(0, 0, 0); m.setMatrixAt(i, tmp.m); }+ m.instanceMatrix.needsUpdate = true;+ if (m.instanceColor) m.instanceColor.needsUpdate = true;+ }, [tmp, geometry]);++ useFrame((_, rawDt) => {+ const m = mesh.current;+ if (!m || paused) return;+ const s = state.current;+ s.clock += Math.min(rawDt, 0.1);+ const at = source();+ if (at) {+ if (s.last) {+ const step = Math.hypot(at.x - s.last.x, at.z - s.last.z);+ s.travelled += step < 2.5 ? step : 0;+ }+ s.last = { x: at.x, z: at.z };+ if (s.travelled >= STEP_LENGTH_M * scale) {+ s.travelled = 0;+ const print = footprintAt(at.x, at.z, at.heading ?? 0, s.left);+ s.left = !s.left;+ const i = s.next;+ s.next = (i + 1) % PRINTS;+ born[i] = s.clock;+ tmp.e.set(-Math.PI / 2, print.rot + Math.PI, 0, "YXZ");+ tmp.q.setFromEuler(tmp.e);+ tmp.p.set(print.x, 0.022, print.z);+ tmp.m.compose(tmp.p, tmp.q, tmp.s);+ m.setMatrixAt(i, tmp.m);+ m.instanceMatrix.needsUpdate = true;+ }+ }+ for (let i = 0; i < PRINTS; i++) {+ const fade = Math.max(0, 1 - (s.clock - born[i]) / PRINT_LIFE_S);+ tmp.c.copy(base).multiplyScalar(fade * 0.85);+ m.setColorAt(i, tmp.c);+ }+ if (m.instanceColor) m.instanceColor.needsUpdate = true;+ });++ return (+ <instancedMesh ref={mesh} args={[geometry, undefined, PRINTS]} frustumCulled={false} renderOrder={2}>+ <meshBasicMaterial map={footprintTexture()} transparent blending={AdditiveBlending} depthWrite={false} side={DoubleSide} />+ </instancedMesh>+ );+}++// ------------------------------------------------------------------ sparks++const SPARKS = 48;++function nextRandom(seed: { value: number }): number {+ seed.value = (Math.imul(seed.value, 1664525) + 1013904223) >>> 0;+ return seed.value / 4294967296;+}++function Sparks({ kind, source, scale, paused }: { kind: "trail_sparkle" | "trail_stardust"; source: FlairSource; scale: number; paused: boolean }) {+ const points = useRef<Points>(null);+ const stardust = kind === "trail_stardust";+ const life = stardust ? 1.4 : 0.9;+ const pool = useMemo(() => {+ const geometry = new BufferGeometry();+ const positions = new Float32Array(SPARKS * 3);+ const colours = new Float32Array(SPARKS * 3);+ geometry.setAttribute("position", new BufferAttribute(positions, 3));+ geometry.setAttribute("color", new BufferAttribute(colours, 3));+ return { geometry, positions, colours, age: new Float32Array(SPARKS).fill(99), rise: new Float32Array(SPARKS), tint: new Float32Array(SPARKS), next: 0 };+ }, []);+ useEffect(() => () => pool.geometry.dispose(), [pool]);+ const palette = useMemo(() => EFFECT_COLOURS[kind].map((c) => new Color(c)), [kind]);+ const state = useRef({ last: null as { x: number; z: number } | null, debt: 0, clock: 0, seed: { value: 0x2545f491 } });++ useFrame((_, rawDt) => {+ if (paused) return;+ const dt = Math.min(rawDt, 0.1);+ const s = state.current;+ s.clock += dt;+ const at = source();+ const { positions, colours, age, rise, tint } = pool;+ if (at) {+ const moved = s.last ? Math.hypot(at.x - s.last.x, at.z - s.last.z) : 0;+ s.last = { x: at.x, z: at.z };+ if (moved > 0.004 && moved < 2.5) {+ s.debt += dt * (stardust ? 34 : 26);+ while (s.debt >= 1) {+ s.debt -= 1;+ const i = pool.next;+ pool.next = (i + 1) % SPARKS;+ const spread = (stardust ? 0.5 : 0.3) * scale;+ positions[i * 3] = at.x + (nextRandom(s.seed) - 0.5) * spread;+ positions[i * 3 + 1] = (0.08 + nextRandom(s.seed) * (stardust ? 1.0 : 0.6)) * scale + (at.y ?? 0);+ positions[i * 3 + 2] = at.z + (nextRandom(s.seed) - 0.5) * spread;+ rise[i] = (stardust ? 0.05 : 0.25) + nextRandom(s.seed) * 0.2;+ tint[i] = Math.floor(nextRandom(s.seed) * palette.length);+ age[i] = 0;+ }+ } else s.debt = 0;+ }+ let alive = false;+ for (let i = 0; i < SPARKS; i++) {+ if (age[i] >= life) { colours[i * 3] = colours[i * 3 + 1] = colours[i * 3 + 2] = 0; continue; }+ age[i] += dt;+ positions[i * 3 + 1] += rise[i] * dt;+ let fade = Math.max(0, 1 - age[i] / life);+ if (stardust) fade *= 0.55 + 0.45 * Math.sin(s.clock * 14 + i * 1.7);+ const c = palette[tint[i]] ?? palette[0];+ colours[i * 3] = c.r * fade; colours[i * 3 + 1] = c.g * fade; colours[i * 3 + 2] = c.b * fade;+ alive = true;+ }+ if (points.current) points.current.visible = alive;+ if (alive) {+ pool.geometry.attributes.position.needsUpdate = true;+ pool.geometry.attributes.color.needsUpdate = true;+ }+ });++ return (+ <points ref={points} geometry={pool.geometry} frustumCulled={false} visible={false} renderOrder={2}>+ <pointsMaterial map={stardust ? starTexture() : glowTexture()} size={(stardust ? 0.13 : 0.08) * Math.max(0.6, scale)} sizeAttenuation+ vertexColors transparent blending={AdditiveBlending} depthWrite={false} />+ </points>+ );+}++// ------------------------------------------------------------------ ribbons++function Ribbon({ kind, source, scale, paused }: { kind: Exclude<TrailKind, "trail_footprints" | "trail_sparkle" | "trail_stardust">; source: FlairSource; scale: number; paused: boolean }) {+ const strip = useMemo(() => {+ const geometry = new BufferGeometry();+ const positions = new Float32Array(RIBBON_MAX_SAMPLES * 6);+ const colours = new Float32Array(RIBBON_MAX_SAMPLES * 6);+ const index: number[] = [];+ for (let i = 0; i < RIBBON_MAX_SAMPLES - 1; i++) {+ const a = i * 2;+ index.push(a, a + 1, a + 2, a + 1, a + 3, a + 2);+ }+ geometry.setIndex(index);+ geometry.setAttribute("position", new BufferAttribute(positions, 3));+ geometry.setAttribute("color", new BufferAttribute(colours, 3));+ geometry.setDrawRange(0, 0);+ return { geometry, positions, colours };+ }, []);+ useEffect(() => () => strip.geometry.dispose(), [strip]);+ const samples = useRef<TrailSample[]>([]);+ const clock = useRef(0);+ const colourA = useMemo(() => new Color(EFFECT_COLOURS[kind][0]), [kind]);+ const colourB = useMemo(() => new Color(EFFECT_COLOURS[kind][1] ?? EFFECT_COLOURS[kind][0]), [kind]);+ const mix = useMemo(() => new Color(), []);+ const width = (RIBBON_WIDTH[kind] ?? 0.3) * scale;++ useFrame((_, rawDt) => {+ if (paused) return;+ clock.current += Math.min(rawDt, 0.1);+ const t = clock.current;+ const at = source();+ const list = samples.current;+ if (at) pushSample(list, at.x, at.z, t);+ pruneSamples(list, t, RIBBON_LIFE_S);+ const n = list.length;+ if (n < 2) { strip.geometry.setDrawRange(0, 0); return; }+ const bright = writeRibbon(list, t, RIBBON_LIFE_S, width, 0.025, strip.positions);+ for (let i = 0; i < n; i++) {+ const along = i / (n - 1);+ if (kind === "trail_rainbow") mix.setHSL(rainbowHue(along, t), 0.95, 0.6);+ else if (kind === "trail_neon") mix.copy(colourA).lerp(colourB, 0.5 + 0.5 * Math.sin(t * 4 + along * 6));+ else mix.copy(colourA).lerp(colourB, along * along);+ const b = bright[i] * 0.9;+ for (const v of [i * 6, i * 6 + 3]) { strip.colours[v] = mix.r * b; strip.colours[v + 1] = mix.g * b; strip.colours[v + 2] = mix.b * b; }+ }+ strip.geometry.setDrawRange(0, (n - 1) * 6);+ strip.geometry.attributes.position.needsUpdate = true;+ strip.geometry.attributes.color.needsUpdate = true;+ });++ return (+ <mesh geometry={strip.geometry} frustumCulled={false} renderOrder={2}>+ <meshBasicMaterial vertexColors transparent blending={AdditiveBlending} depthWrite={false} side={DoubleSide} />+ </mesh>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/progression/effects/CosmeticWear.tsx b/jarvis/ui/web/frontend/src/components/society/progression/effects/CosmeticWear.tsxnew file mode 100644index 0000000000..1d2a1d159f--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/progression/effects/CosmeticWear.tsx@@ -0,0 +1,302 @@+/**+ * What a levelled-up figure wears: an aura on the floor under it and a+ * gadget on or around it. Both follow the wearer's ground position every+ * frame; nothing here is solid, casts a shadow or takes a click.+ *+ * Auras: a warm glow, a turning rune circle, a crackling storm ring and the+ * prismatic legend circle with rising motes. Gadgets: a hovering drone, a+ * halo, a crown and a pair of light wings.+ */+import { useEffect, useMemo, useRef, type RefObject } from "react";+import { useFrame } from "@react-three/fiber";+import {+ AdditiveBlending, BufferAttribute, BufferGeometry, Color, DoubleSide, Shape, ShapeGeometry,+ type Group, type LineSegments, type Mesh, type MeshBasicMaterial, type Points,+} from "three";+import { EFFECT_COLOURS, type RewardId } from "../levelCatalog";+import { glowTexture, runeTexture } from "./flairTextures";+import type { FlairSource } from "./CosmeticTrail";++export type AuraKind = Extract<RewardId, `aura_${string}`>;+export type GadgetKind = Extract<RewardId, `gadget_${string}`>;++function useFollow(source: FlairSource, paused: boolean, place: (g: Group, at: NonNullable<ReturnType<FlairSource>>, t: number, dt: number) => void) {+ const group = useRef<Group>(null);+ const clock = useRef(0);+ useFrame((_, rawDt) => {+ const g = group.current;+ if (!g) return;+ const at = source();+ g.visible = !!at;+ if (!at) return;+ const dt = paused ? 0 : Math.min(rawDt, 0.1);+ clock.current += dt;+ place(g, at, clock.current, dt);+ });+ return group;+}++// ------------------------------------------------------------------ auras++export function CosmeticAura({ kind, source, scale = 1, paused, reduced }: { kind: AuraKind; source: FlairSource; scale?: number; paused: boolean; reduced: boolean }) {+ const disc = useRef<Mesh>(null);+ const ringA = useRef<Mesh>(null);+ const ringB = useRef<Mesh>(null);+ const colours = useMemo(() => EFFECT_COLOURS[kind].map((c) => new Color(c)), [kind]);+ const hue = useMemo(() => new Color(), []);+ const group = useFollow(source, paused, (g, at, t) => {+ g.position.set(at.x, 0.018, at.z);+ const pulse = reduced ? 0.5 : 0.5 + 0.5 * Math.sin(t * 2.4);+ if (disc.current) {+ const m = disc.current.material as MeshBasicMaterial;+ m.opacity = kind === "aura_glow" ? 0.35 + 0.3 * pulse : 0.22 + 0.15 * pulse;+ disc.current.scale.setScalar(1 + 0.08 * pulse);+ }+ const spin = reduced ? 0 : t;+ if (ringA.current) ringA.current.rotation.z = spin * (kind === "aura_storm" ? 1.6 : 0.5);+ if (ringB.current) ringB.current.rotation.z = -spin * 0.8;+ if (kind === "aura_legend") {+ hue.setHSL((t * 0.08) % 1, 0.9, 0.65);+ if (ringA.current) (ringA.current.material as MeshBasicMaterial).color.copy(hue);+ hue.setHSL((t * 0.08 + 0.5) % 1, 0.9, 0.65);+ if (ringB.current) (ringB.current.material as MeshBasicMaterial).color.copy(hue);+ }+ });+ const flat: [number, number, number] = [-Math.PI / 2, 0, 0];+ const r = 0.8 * scale;+ return (+ <group ref={group} renderOrder={1}>+ <mesh ref={disc} rotation={flat} renderOrder={1}>+ <circleGeometry args={[r, 40]} />+ <meshBasicMaterial map={glowTexture()} color={colours[0]} transparent opacity={0.4} blending={AdditiveBlending} depthWrite={false} />+ </mesh>+ {kind !== "aura_glow" && (+ <mesh ref={ringA} rotation={flat} position={[0, 0.004, 0]} renderOrder={1}>+ <planeGeometry args={[r * 2.1, r * 2.1]} />+ <meshBasicMaterial map={runeTexture()} color={colours[0]} transparent opacity={kind === "aura_storm" ? 0.55 : 0.8}+ blending={AdditiveBlending} depthWrite={false} side={DoubleSide} />+ </mesh>+ )}+ {kind === "aura_legend" && (+ <mesh ref={ringB} rotation={flat} position={[0, 0.006, 0]} scale={0.7} renderOrder={1}>+ <planeGeometry args={[r * 2.1, r * 2.1]} />+ <meshBasicMaterial map={runeTexture()} color={colours[1]} transparent opacity={0.75} blending={AdditiveBlending} depthWrite={false} side={DoubleSide} />+ </mesh>+ )}+ {kind === "aura_storm" && !reduced && <Lightning radius={r} colour={colours[1]} paused={paused} />}+ {kind === "aura_legend" && !reduced && <Motes radius={r * 0.7} paused={paused} />}+ </group>+ );+}++const BOLTS = 6;+const BOLT_SEGMENTS = 4;++/** Short zig-zag arcs jumping round the ring, re-struck a dozen times a second. */+function Lightning({ radius, colour, paused }: { radius: number; colour: Color; paused: boolean }) {+ const lines = useRef<LineSegments>(null);+ const geometry = useMemo(() => {+ const g = new BufferGeometry();+ g.setAttribute("position", new BufferAttribute(new Float32Array(BOLTS * BOLT_SEGMENTS * 2 * 3), 3));+ return g;+ }, []);+ useEffect(() => () => geometry.dispose(), [geometry]);+ const next = useRef(0);+ const clock = useRef(0);+ useFrame((_, dt) => {+ if (paused || !lines.current) return;+ clock.current += Math.min(dt, 0.1);+ if (clock.current < next.current) return;+ next.current = clock.current + 0.08 + Math.random() * 0.06;+ const pos = geometry.attributes.position.array as Float32Array;+ let k = 0;+ for (let b = 0; b < BOLTS; b++) {+ const a0 = Math.random() * Math.PI * 2;+ let x = Math.cos(a0) * radius * 0.55, y = 0.02, z = Math.sin(a0) * radius * 0.55;+ for (let s = 0; s < BOLT_SEGMENTS; s++) {+ const nx = x + Math.cos(a0) * radius * 0.12 + (Math.random() - 0.5) * 0.12;+ const ny = y + 0.06 + Math.random() * 0.1;+ const nz = z + Math.sin(a0) * radius * 0.12 + (Math.random() - 0.5) * 0.12;+ pos[k++] = x; pos[k++] = y; pos[k++] = z; pos[k++] = nx; pos[k++] = ny; pos[k++] = nz;+ x = nx; y = ny; z = nz;+ }+ }+ geometry.attributes.position.needsUpdate = true;+ (lines.current.material as MeshBasicMaterial).opacity = 0.5 + Math.random() * 0.5;+ });+ return (+ <lineSegments ref={lines} geometry={geometry} frustumCulled={false} renderOrder={2}>+ <lineBasicMaterial color={colour} transparent blending={AdditiveBlending} depthWrite={false} />+ </lineSegments>+ );+}++const MOTES = 24;++/** Prismatic motes spiralling up out of the legend circle. */+function Motes({ radius, paused }: { radius: number; paused: boolean }) {+ const points = useRef<Points>(null);+ const pool = useMemo(() => {+ const geometry = new BufferGeometry();+ const positions = new Float32Array(MOTES * 3);+ const colours = new Float32Array(MOTES * 3);+ geometry.setAttribute("position", new BufferAttribute(positions, 3));+ geometry.setAttribute("color", new BufferAttribute(colours, 3));+ return { geometry, positions, colours, phase: Float32Array.from({ length: MOTES }, (_, i) => i / MOTES) };+ }, []);+ useEffect(() => () => pool.geometry.dispose(), [pool]);+ const c = useMemo(() => new Color(), []);+ const clock = useRef(0);+ useFrame((_, dt) => {+ if (paused) return;+ clock.current += Math.min(dt, 0.1);+ const t = clock.current;+ for (let i = 0; i < MOTES; i++) {+ const life = (pool.phase[i] + t * 0.35) % 1;+ const angle = i * 2.39996 + t * 1.2;+ const r = radius * (1 - life * 0.5);+ pool.positions[i * 3] = Math.cos(angle) * r;+ pool.positions[i * 3 + 1] = 0.05 + life * 1.6;+ pool.positions[i * 3 + 2] = Math.sin(angle) * r;+ c.setHSL((i / MOTES + t * 0.1) % 1, 0.9, 0.65).multiplyScalar(Math.sin(life * Math.PI));+ pool.colours[i * 3] = c.r; pool.colours[i * 3 + 1] = c.g; pool.colours[i * 3 + 2] = c.b;+ }+ pool.geometry.attributes.position.needsUpdate = true;+ pool.geometry.attributes.color.needsUpdate = true;+ });+ return (+ <points ref={points} geometry={pool.geometry} frustumCulled={false} renderOrder={2}>+ <pointsMaterial map={glowTexture()} size={0.09} sizeAttenuation vertexColors transparent blending={AdditiveBlending} depthWrite={false} />+ </points>+ );+}++// ------------------------------------------------------------------ gadgets++/**+ * `top` is the height of the wearer's head top above the floor; `heading`+ * (from the source) turns the wings onto its back.+ */+export function CosmeticGadget({ kind, source, top, scale = 1, paused, reduced }: {+ kind: GadgetKind; source: FlairSource; top: number; scale?: number; paused: boolean; reduced: boolean;+}) {+ const spinner = useRef<Group>(null);+ const extra = useRef<Group>(null);+ const blink = useRef<Mesh>(null);+ const group = useFollow(source, paused, (g, at, t) => {+ const lift = at.y !== undefined && kind !== "gadget_wings" ? at.y : top;+ g.position.set(at.x, kind === "gadget_wings" ? top * 0.55 : lift, at.z);+ if (kind === "gadget_wings") g.rotation.y = at.heading ?? 0;+ const calm = reduced ? 0 : 1;+ if (kind === "gadget_halo" && spinner.current) {+ spinner.current.position.y = 0.14 * scale + 0.025 * Math.sin(t * 2.2) * calm;+ spinner.current.rotation.z = 0.15 * Math.sin(t * 0.9) * calm;+ }+ if (kind === "gadget_crown" && spinner.current) spinner.current.rotation.y = t * 0.4 * calm;+ if (kind === "gadget_drone" && spinner.current) {+ spinner.current.rotation.y = t * 1.1 * calm;+ if (extra.current) {+ extra.current.position.y = 0.04 * Math.sin(t * 3) * calm;+ extra.current.children.forEach((rotor, i) => { if (i < 4) rotor.rotation.y = t * 40 * calm; });+ }+ if (blink.current) (blink.current.material as MeshBasicMaterial).opacity = Math.sin(t * 6) > 0.2 ? 1 : 0.2;+ }+ if (kind === "gadget_wings" && extra.current) {+ // Each wing swings its tip backwards (+θ about y sends +x towards −z) and forwards again.+ const sweep = WING_REST + (reduced ? 0 : 0.22 + 0.22 * Math.sin(t * 3.2));+ const [left, right] = extra.current.children;+ if (left) left.rotation.y = sweep;+ if (right) right.rotation.y = -sweep;+ }+ });+ const [main, accent] = EFFECT_COLOURS[kind];+ return (+ <group ref={group}>+ {kind === "gadget_halo" && (+ <group ref={spinner}>+ <mesh rotation={[Math.PI / 2, 0, 0]}>+ <torusGeometry args={[0.17 * scale, 0.022 * scale, 10, 36]} />+ <meshBasicMaterial color={main} toneMapped={false} />+ </mesh>+ <mesh rotation={[-Math.PI / 2, 0, 0]}>+ <circleGeometry args={[0.32 * scale, 24]} />+ <meshBasicMaterial map={glowTexture()} color={main} transparent opacity={0.6} blending={AdditiveBlending} depthWrite={false} />+ </mesh>+ </group>+ )}+ {kind === "gadget_crown" && (+ <group ref={spinner} position={[0, -0.05 * scale, 0]} scale={scale}>+ <mesh position={[0, 0.045, 0]}>+ <cylinderGeometry args={[0.13, 0.12, 0.09, 20, 1, true]} />+ <meshStandardMaterial color={main} metalness={0.7} roughness={0.25} emissive={main} emissiveIntensity={0.25} side={DoubleSide} />+ </mesh>+ {[0, 1, 2, 3, 4].map((i) => {+ const a = (i / 5) * Math.PI * 2;+ return (+ <mesh key={i} position={[Math.sin(a) * 0.125, 0.12, Math.cos(a) * 0.125]}>+ <coneGeometry args={[0.03, 0.08, 6]} />+ <meshStandardMaterial color={main} metalness={0.7} roughness={0.25} emissive={main} emissiveIntensity={0.25} />+ </mesh>+ );+ })}+ <mesh position={[0, 0.05, 0.128]}>+ <sphereGeometry args={[0.022, 10, 8]} />+ <meshStandardMaterial color={accent} emissive={accent} emissiveIntensity={0.6} roughness={0.2} />+ </mesh>+ </group>+ )}+ {kind === "gadget_drone" && (+ <group ref={spinner} position={[0, 0.2 * scale, 0]}>+ <group ref={extra} position={[0.55 * scale, 0, 0]} scale={scale}>+ {[[-1, -1], [1, -1], [-1, 1], [1, 1]].map(([sx, sz], i) => (+ <mesh key={i} position={[sx * 0.075, 0.03, sz * 0.075]}>+ <cylinderGeometry args={[0.045, 0.045, 0.006, 12]} />+ <meshBasicMaterial color={accent} transparent opacity={0.45} />+ </mesh>+ ))}+ <mesh>+ <boxGeometry args={[0.13, 0.045, 0.13]} />+ <meshStandardMaterial color={main} roughness={0.35} metalness={0.4} />+ </mesh>+ <mesh ref={blink} position={[0, -0.03, 0.066]}>+ <sphereGeometry args={[0.014, 8, 6]} />+ <meshBasicMaterial color={accent} transparent toneMapped={false} />+ </mesh>+ </group>+ </group>+ )}+ {kind === "gadget_wings" && <Wings refGroup={extra} colour={main} scale={scale} />}+ </group>+ );+}++/** The wings' resting sweep behind the back, radians. */+const WING_REST = 0.35;++function Wings({ refGroup, colour, scale }: { refGroup: RefObject<Group>; colour: string; scale: number }) {+ const geometry = useMemo(() => {+ // One feathered wing, drawn outward along +x from the shoulder.+ const s = new Shape();+ s.moveTo(0, 0);+ s.bezierCurveTo(0.18, 0.2, 0.42, 0.26, 0.6, 0.18);+ s.lineTo(0.5, 0.08);+ s.lineTo(0.56, 0.0);+ s.lineTo(0.42, -0.04);+ s.lineTo(0.46, -0.13);+ s.lineTo(0.3, -0.12);+ s.bezierCurveTo(0.18, -0.12, 0.06, -0.06, 0, 0);+ return new ShapeGeometry(s, 12);+ }, []);+ useEffect(() => () => geometry.dispose(), [geometry]);+ return (+ <group ref={refGroup} position={[0, 0, -0.13 * scale]} scale={scale}>+ {[1, -1].map((side) => (+ <group key={side} rotation={[0, side * WING_REST, 0]}>+ <mesh geometry={geometry} scale={[side, 1, 1]}>+ <meshBasicMaterial color={colour} transparent opacity={0.55} blending={AdditiveBlending} depthWrite={false} side={DoubleSide} />+ </mesh>+ </group>+ ))}+ </group>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/progression/effects/LevelUpBurst.tsx b/jarvis/ui/web/frontend/src/components/society/progression/effects/LevelUpBurst.tsxnew file mode 100644index 0000000000..b9ebdd00cc--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/progression/effects/LevelUpBurst.tsx@@ -0,0 +1,149 @@+/**+ * The level-up moment in the world, in three beats that overlap:+ *+ * 1. a column of light shoots up from the floor around the figure (0–0.3 s),+ * 2. two shockwave rings race out across the floor (0.05–1.1 s),+ * 3. a fountain of sparks bursts up and rains back down (0.1–2.2 s),+ *+ * while a "LEVEL n" tag rises over the head. The column and sparks follow+ * the figure if it keeps walking. Reduced motion keeps only the tag.+ */+import { useEffect, useMemo, useRef } from "react";+import { Html } from "@react-three/drei";+import { useFrame } from "@react-three/fiber";+import { AdditiveBlending, BufferAttribute, BufferGeometry, Color, DoubleSide, type Group, type Mesh, type MeshBasicMaterial, type Points } from "three";+import { beamTexture, glowTexture } from "./flairTextures";+import type { FlairSource } from "./CosmeticTrail";+import type { SubjectKind } from "../levelCatalog";+import { BURST_MS } from "../progressionStore";++/** Gold for the person, the pet's teal, an agent's green: the same three as the HUD. */+export const BURST_COLOURS: Record<SubjectKind, [string, string]> = {+ person: ["#ffd25e", "#fff3c4"],+ pet: ["#5eead4", "#e0fffa"],+ agent: ["#86efac", "#f0fff4"],+};++const SPARKS = 90;+const GRAVITY = 5.5;++/** 0..1 ease-out (cubic). */+const easeOut = (x: number) => 1 - Math.pow(1 - Math.min(1, Math.max(0, x)), 3);++export function LevelUpBurst({ source, kind, level, label, height, scale = 1, reduced }: {+ source: FlairSource; kind: SubjectKind; level: number; label: string; height: number; scale?: number; reduced: boolean;+}) {+ const group = useRef<Group>(null);+ const column = useRef<Mesh>(null);+ const ring1 = useRef<Mesh>(null);+ const ring2 = useRef<Mesh>(null);+ const flash = useRef<Mesh>(null);+ const sparks = useRef<Points>(null);+ const t = useRef(0);+ const [main, light] = BURST_COLOURS[kind];+ const pool = useMemo(() => {+ const geometry = new BufferGeometry();+ const positions = new Float32Array(SPARKS * 3);+ const colours = new Float32Array(SPARKS * 3);+ const velocity = new Float32Array(SPARKS * 3);+ const a = new Color(main), b = new Color(light);+ for (let i = 0; i < SPARKS; i++) {+ const angle = (i / SPARKS) * Math.PI * 2 * 7.3;+ const out = (0.8 + ((i * 37) % 11) / 11 * 1.6) * scale;+ velocity[i * 3] = Math.cos(angle) * out;+ velocity[i * 3 + 1] = (2.6 + ((i * 53) % 13) / 13 * 2.8) * scale;+ velocity[i * 3 + 2] = Math.sin(angle) * out;+ const c = i % 3 === 0 ? b : a;+ colours[i * 3] = c.r; colours[i * 3 + 1] = c.g; colours[i * 3 + 2] = c.b;+ }+ geometry.setAttribute("position", new BufferAttribute(positions, 3));+ geometry.setAttribute("color", new BufferAttribute(colours.slice(), 3));+ return { geometry, positions, base: colours, velocity };+ }, [main, light, scale]);+ useEffect(() => () => pool.geometry.dispose(), [pool]);++ useFrame((_, rawDt) => {+ const g = group.current;+ if (!g) return;+ const at = source();+ if (at) g.position.set(at.x, 0, at.z);+ t.current += Math.min(rawDt, 0.1);+ const s = t.current;+ if (reduced) return;+ if (column.current) {+ const grow = easeOut(s / 0.3);+ const fade = s < 0.9 ? 1 : Math.max(0, 1 - (s - 0.9) / 1.2);+ column.current.scale.set(1 - 0.35 * easeOut((s - 0.9) / 1.2), grow, 1 - 0.35 * easeOut((s - 0.9) / 1.2));+ (column.current.material as MeshBasicMaterial).opacity = 0.75 * fade;+ column.current.rotation.y = s * 1.5;+ }+ for (const [ring, delay, span] of [[ring1.current, 0.05, 1.0], [ring2.current, 0.25, 1.1]] as const) {+ if (!ring) continue;+ const k = (s - delay) / span;+ ring.visible = k > 0 && k < 1;+ ring.scale.setScalar(0.3 + easeOut(k) * 3.4 * scale);+ (ring.material as MeshBasicMaterial).opacity = 0.9 * (1 - Math.min(1, Math.max(0, k)));+ }+ if (flash.current) {+ const k = s / 0.5;+ flash.current.visible = k < 1;+ flash.current.scale.setScalar((0.6 + k * 2.4) * scale);+ (flash.current.material as MeshBasicMaterial).opacity = 0.85 * (1 - k);+ }+ const st = s - 0.1;+ if (sparks.current) sparks.current.visible = st > 0 && st < 2.1;+ if (st > 0) {+ const { positions, velocity, base } = pool;+ const colours = pool.geometry.attributes.color.array as Float32Array;+ const fade = Math.max(0, 1 - st / 2.1);+ for (let i = 0; i < SPARKS; i++) {+ positions[i * 3] = velocity[i * 3] * st;+ positions[i * 3 + 1] = Math.max(0.02, 0.4 * scale + velocity[i * 3 + 1] * st - 0.5 * GRAVITY * scale * st * st);+ positions[i * 3 + 2] = velocity[i * 3 + 2] * st;+ const twinkle = 0.6 + 0.4 * Math.sin(st * 20 + i);+ colours[i * 3] = base[i * 3] * fade * twinkle; colours[i * 3 + 1] = base[i * 3 + 1] * fade * twinkle; colours[i * 3 + 2] = base[i * 3 + 2] * fade * twinkle;+ }+ pool.geometry.attributes.position.needsUpdate = true;+ pool.geometry.attributes.color.needsUpdate = true;+ }+ });++ const flat: [number, number, number] = [-Math.PI / 2, 0, 0];+ return (+ <group ref={group}>+ {!reduced && <>+ <mesh ref={column} position={[0, 3 * scale, 0]} renderOrder={3}>+ <cylinderGeometry args={[0.55 * scale, 0.7 * scale, 6 * scale, 28, 1, true]} />+ <meshBasicMaterial map={beamTexture()} color={main} transparent opacity={0.7} blending={AdditiveBlending} depthWrite={false} side={DoubleSide} />+ </mesh>+ <mesh ref={flash} rotation={flat} position={[0, 0.03, 0]} renderOrder={3}>+ <circleGeometry args={[0.6, 32]} />+ <meshBasicMaterial map={glowTexture()} color={light} transparent opacity={0.8} blending={AdditiveBlending} depthWrite={false} />+ </mesh>+ {[ring1, ring2].map((ref, i) => (+ <mesh key={i} ref={ref} rotation={flat} position={[0, 0.035, 0]} visible={false} renderOrder={3}>+ <ringGeometry args={[0.86, 1, 48]} />+ <meshBasicMaterial color={i === 0 ? main : light} transparent opacity={0.9} blending={AdditiveBlending} depthWrite={false} side={DoubleSide} />+ </mesh>+ ))}+ <points ref={sparks} geometry={pool.geometry} frustumCulled={false} visible={false} renderOrder={3}>+ <pointsMaterial map={glowTexture()} size={0.14 * scale} sizeAttenuation vertexColors transparent blending={AdditiveBlending} depthWrite={false} />+ </points>+ </>}+ <Html center position={[0, height + 0.55, 0]} zIndexRange={[45, 40]}>+ <span className="level-burst-tag" data-kind={kind} style={{ animationDuration: `${BURST_MS}ms` }} aria-hidden>+ <small>{label}</small><b>{level}</b>+ </span>+ </Html>+ </group>+ );+}++/** "+5 XP", rising and fading over the wearer's head (CSS does the motion). */+export function XpPopup({ x, z, y, xp, kind }: { x: number; z: number; y: number; xp: number; kind: SubjectKind }) {+ return (+ <Html center position={[x, y, z]} zIndexRange={[44, 40]}>+ <span className="level-xp-pop" data-kind={kind} aria-hidden>+{xp} XP</span>+ </Html>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/progression/effects/flairTextures.ts b/jarvis/ui/web/frontend/src/components/society/progression/effects/flairTextures.tsnew file mode 100644index 0000000000..711d4c5005--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/progression/effects/flairTextures.ts@@ -0,0 +1,101 @@+/**+ * The few canvas textures every level effect shares: a soft glow, a+ * four-point star, a rune circle, a footprint and a vertical light beam.+ * Drawn once per page on first use; three.js re-uploads them from their+ * canvas after a lost WebGL context, so they are never disposed.+ */+import { CanvasTexture, SRGBColorSpace, type Texture } from "three";++type Draw = (ctx: CanvasRenderingContext2D, size: number) => void;++const cache = new Map<string, Texture>();++function canvasTexture(key: string, size: number, draw: Draw, height = size): Texture {+ const hit = cache.get(key);+ if (hit) return hit;+ const canvas = document.createElement("canvas");+ canvas.width = size;+ canvas.height = height;+ const ctx = canvas.getContext("2d");+ if (ctx) draw(ctx, size);+ const texture = new CanvasTexture(canvas);+ texture.colorSpace = SRGBColorSpace;+ cache.set(key, texture);+ return texture;+}++export function glowTexture(): Texture {+ return canvasTexture("glow", 64, (ctx) => {+ const g = ctx.createRadialGradient(32, 32, 0, 32, 32, 32);+ g.addColorStop(0, "rgba(255,255,255,1)");+ g.addColorStop(0.3, "rgba(255,255,255,0.55)");+ g.addColorStop(0.65, "rgba(255,255,255,0.14)");+ g.addColorStop(1, "rgba(255,255,255,0)");+ ctx.fillStyle = g;+ ctx.fillRect(0, 0, 64, 64);+ });+}++export function starTexture(): Texture {+ return canvasTexture("star", 64, (ctx) => {+ const g = ctx.createRadialGradient(32, 32, 0, 32, 32, 12);+ g.addColorStop(0, "rgba(255,255,255,1)");+ g.addColorStop(1, "rgba(255,255,255,0)");+ ctx.fillStyle = g;+ ctx.fillRect(0, 0, 64, 64);+ ctx.fillStyle = "rgba(255,255,255,0.95)";+ for (const [w, h] of [[3, 30], [30, 3]] as const) {+ ctx.beginPath();+ ctx.ellipse(32, 32, w, h, 0, 0, Math.PI * 2);+ ctx.fill();+ }+ });+}++/** A ring of rune ticks and dots on a thin circle, for the rune aura. */+export function runeTexture(): Texture {+ return canvasTexture("runes", 256, (ctx) => {+ ctx.translate(128, 128);+ ctx.strokeStyle = "rgba(255,255,255,0.95)";+ ctx.lineWidth = 3;+ ctx.beginPath(); ctx.arc(0, 0, 118, 0, Math.PI * 2); ctx.stroke();+ ctx.lineWidth = 1.5;+ ctx.beginPath(); ctx.arc(0, 0, 92, 0, Math.PI * 2); ctx.stroke();+ ctx.lineWidth = 3;+ for (let i = 0; i < 16; i++) {+ ctx.save();+ ctx.rotate((i / 16) * Math.PI * 2);+ ctx.translate(0, -105);+ ctx.beginPath();+ // A small glyph per slot: a stroke, a hook or a triangle in turn.+ if (i % 3 === 0) { ctx.moveTo(-5, -6); ctx.lineTo(5, 6); ctx.moveTo(5, -6); ctx.lineTo(0, 0); }+ else if (i % 3 === 1) { ctx.moveTo(0, -7); ctx.lineTo(0, 7); ctx.moveTo(0, -2); ctx.lineTo(6, -6); }+ else { ctx.moveTo(-6, 6); ctx.lineTo(0, -7); ctx.lineTo(6, 6); ctx.closePath(); }+ ctx.stroke();+ ctx.restore();+ }+ });+}++/** A rounded sole with four toe dots; drawn pointing up (+v). */+export function footprintTexture(): Texture {+ return canvasTexture("foot", 64, (ctx) => {+ ctx.fillStyle = "rgba(255,255,255,1)";+ ctx.beginPath(); ctx.ellipse(32, 38, 11, 17, 0, 0, Math.PI * 2); ctx.fill();+ for (const [x, y, r] of [[22, 15, 4], [29, 11, 4.2], [36, 11, 4], [42, 15, 3.6]] as const) {+ ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill();+ }+ });+}++/** Bright at the floor, fading out towards the top: the level-up column. */+export function beamTexture(): Texture {+ return canvasTexture("beam", 16, (ctx) => {+ const g = ctx.createLinearGradient(0, 128, 0, 0);+ g.addColorStop(0, "rgba(255,255,255,1)");+ g.addColorStop(0.35, "rgba(255,255,255,0.5)");+ g.addColorStop(1, "rgba(255,255,255,0)");+ ctx.fillStyle = g;+ ctx.fillRect(0, 0, 16, 128);+ }, 128);+}diff --git a/jarvis/ui/web/frontend/src/components/society/progression/effects/trailModel.ts b/jarvis/ui/web/frontend/src/components/society/progression/effects/trailModel.tsnew file mode 100644index 0000000000..bc938d5979--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/progression/effects/trailModel.ts@@ -0,0 +1,70 @@+/**+ * Pure bookkeeping behind the trails: where a ribbon keeps its samples, when+ * the next footprint lands, how a ribbon turns into a flat strip on the floor.+ * Kept free of three.js so the rules are unit tested.+ */++export interface TrailSample { x: number; z: number; t: number }++/** Distance between two ribbon samples, metres. */+export const RIBBON_STEP_M = 0.12;+export const RIBBON_MAX_SAMPLES = 28;+/** Distance between two footprints, metres. */+export const STEP_LENGTH_M = 0.42;++/** Adds a sample once the mover is a step past the last one; drops the oldest beyond the cap. */+export function pushSample(samples: TrailSample[], x: number, z: number, t: number): boolean {+ const last = samples[samples.length - 1];+ if (last && Math.hypot(x - last.x, z - last.z) < RIBBON_STEP_M) return false;+ // A jump of several metres is a teleport (elevator, floor switch): the ribbon starts over.+ if (last && Math.hypot(x - last.x, z - last.z) > 2.5) samples.length = 0;+ samples.push({ x, z, t });+ if (samples.length > RIBBON_MAX_SAMPLES) samples.splice(0, samples.length - RIBBON_MAX_SAMPLES);+ return true;+}++export function pruneSamples(samples: TrailSample[], t: number, lifeS: number): void {+ let drop = 0;+ while (drop < samples.length && t - samples[drop].t > lifeS) drop++;+ if (drop > 0) samples.splice(0, drop);+}++/**+ * Writes a flat strip along the samples into `positions` (two vertices per+ * sample, at height `y`) and returns, per sample, how bright it is (1 at the+ * newest, 0 at the oldest or fully aged). The strip narrows towards its tail.+ */+export function writeRibbon(samples: readonly TrailSample[], t: number, lifeS: number, widthM: number, y: number,+ positions: Float32Array): number[] {+ const n = samples.length;+ const bright: number[] = [];+ for (let i = 0; i < n; i++) {+ const s = samples[i];+ const prev = samples[Math.max(0, i - 1)];+ const next = samples[Math.min(n - 1, i + 1)];+ let dx = next.x - prev.x, dz = next.z - prev.z;+ const len = Math.hypot(dx, dz) || 1;+ dx /= len; dz /= len;+ const along = n > 1 ? i / (n - 1) : 1;+ const age = Math.min(1, Math.max(0, (t - s.t) / lifeS));+ const half = (widthM / 2) * along * (1 - age * 0.5);+ // Perpendicular on the floor: (-dz, dx).+ positions[i * 6] = s.x - dz * half; positions[i * 6 + 1] = y; positions[i * 6 + 2] = s.z + dx * half;+ positions[i * 6 + 3] = s.x + dz * half; positions[i * 6 + 4] = y; positions[i * 6 + 5] = s.z - dx * half;+ bright.push(along * (1 - age));+ }+ return bright;+}++/** Footprints alternate left and right of the path, a hand's width apart. */+export function footprintAt(x: number, z: number, heading: number, left: boolean): { x: number; z: number; rot: number } {+ const side = left ? 1 : -1;+ // Right of heading h is (−cos h, sin h) for a +z-forward figure.+ return { x: x + Math.cos(heading) * 0.09 * side, z: z - Math.sin(heading) * 0.09 * side, rot: heading };+}++/** Hue (0..1) along a rainbow ribbon, cycling slowly with time. */+export function rainbowHue(along: number, t: number): number {+ const h = (along * 0.85 + t * 0.15) % 1;+ return h < 0 ? h + 1 : h;+}diff --git a/jarvis/ui/web/frontend/src/components/society/progression/levelCatalog.ts b/jarvis/ui/web/frontend/src/components/society/progression/levelCatalog.tsnew file mode 100644index 0000000000..967cd2d12c--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/progression/levelCatalog.ts@@ -0,0 +1,77 @@+/**+ * The Verse's copy of the level system's ids (jarvis/progression/rules.py):+ * subject kinds, cosmetic slots, reward ids, title ids and XP sources. The+ * server sends levels and amounts; this file only knows what each id LOOKS+ * like. tests/unit/progression/test_frontend_parity.py pins every list here+ * to the Python rulebook (AP-4): add an id in Python first, then here.+ */++export const SUBJECT_KINDS = ["person", "agent", "pet"] as const;+export type SubjectKind = (typeof SUBJECT_KINDS)[number];++export const SLOTS = ["frame", "trail", "aura", "gadget"] as const;+export type Slot = (typeof SLOTS)[number];++export const REWARD_IDS = [+ "frame_bronze", "frame_silver", "frame_gold", "frame_diamond",+ "trail_footprints", "trail_sparkle", "trail_comet", "trail_neon", "trail_rainbow", "trail_stardust",+ "aura_glow", "aura_runes", "aura_storm", "aura_legend",+ "gadget_drone", "gadget_halo", "gadget_crown", "gadget_wings",+] as const;+export type RewardId = (typeof REWARD_IDS)[number];++export const TITLE_IDS = [+ "newcomer", "apprentice", "operator", "specialist", "strategist", "architect", "commander", "visionary", "legend",+ "rookie", "trainee", "associate", "professional", "expert", "veteran", "elite", "grandmaster",+ "hatchling", "buddy", "sidekick", "partner", "guardian", "champion", "mythic",+] as const;++export const XP_SOURCES = [+ "chat_turn", "voice_turn", "quest_posted", "quest_completed", "agent_hired", "mission_completed",+ "daily_visit", "floor_discovered", "dog_petted", "dog_treat", "arcade_round", "arcade_record", "team_meeting",+ "task_done", "task_blocked", "quest_done", "answered_teammate",+ "jarvis_answered", "delegated", "walk_together",+] as const;+export type XpSource = (typeof XP_SOURCES)[number];++/** The world actions the Verse itself reports (`trigger: "world"` in the rulebook). */+export type WorldAction = "daily_visit" | "floor_discovered" | "dog_petted" | "dog_treat" | "arcade_round"+ | "arcade_record" | "team_meeting" | "walk_together";++export function slotOf(reward: RewardId): Slot {+ return reward.slice(0, reward.indexOf("_")) as Slot;+}++export function isRewardId(value: unknown): value is RewardId {+ return typeof value === "string" && (REWARD_IDS as readonly string[]).includes(value);+}++/** Frame tiers colour the level chip on name plates and the HUD ring. */+export const FRAME_STYLE: Record<"frame_none" | Extract<RewardId, `frame_${string}`>, { ring: string; fill: string; ink: string }> = {+ frame_none: { ring: "#94a3b8", fill: "#334155", ink: "#f8fafc" },+ frame_bronze: { ring: "#d08a4f", fill: "#6b3b1c", ink: "#ffe8d3" },+ frame_silver: { ring: "#d7dee8", fill: "#4b5563", ink: "#ffffff" },+ frame_gold: { ring: "#ffd25e", fill: "#8a5a00", ink: "#fff7da" },+ frame_diamond: { ring: "#9be8ff", fill: "#1d4e89", ink: "#ffffff" },+};++/**+ * The colours of each effect in the diorama. The world keeps one palette in+ * light and dark mode (office-map.md §2), so these are fixed, not tokens.+ */+export const EFFECT_COLOURS: Record<Exclude<RewardId, `frame_${string}`>, readonly string[]> = {+ trail_footprints: ["#ffe2a8"],+ trail_sparkle: ["#fff1b8", "#ffd166"],+ trail_comet: ["#7dd3fc", "#ffffff"],+ trail_neon: ["#22d3ee", "#e879f9"],+ trail_rainbow: ["#ff5e5e", "#ffb347", "#fff275", "#6ee7a0", "#5ec8ff", "#b18cff"],+ trail_stardust: ["#c4b5fd", "#ffffff", "#93c5fd"],+ aura_glow: ["#ffd98a"],+ aura_runes: ["#7dd3fc"],+ aura_storm: ["#a78bfa", "#e0f2fe"],+ aura_legend: ["#ff8ad8", "#ffe36e", "#7af0ff"],+ gadget_drone: ["#e2e8f0", "#38bdf8"],+ gadget_halo: ["#ffe28a"],+ gadget_crown: ["#ffcf40", "#e11d48"],+ gadget_wings: ["#bfe9ff", "#ffffff"],+};diff --git a/jarvis/ui/web/frontend/src/components/society/progression/levelSounds.ts b/jarvis/ui/web/frontend/src/components/society/progression/levelSounds.tsnew file mode 100644index 0000000000..5161fb5c14--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/progression/levelSounds.ts@@ -0,0 +1,81 @@+/**+ * Level-up sounds, synthesised with Web Audio: no files to ship, nothing to+ * load. A rising major arpeggio with a shimmer on top for the person and the+ * pet, a short two-note chime for an agent, a soft tick for "+XP". The+ * listener can switch them off in the progress panel. A browser without Web+ * Audio, or one that refuses to start it, plays nothing.+ */+import { create } from "zustand";++const SOUND_KEY = "jarvis.verse.level.sound.v1";++function readSoundOn(): boolean {+ try {+ return typeof localStorage === "undefined" || localStorage.getItem(SOUND_KEY) !== "off";+ } catch (error) {+ console.debug("Verse sound setting unavailable", error);+ return true;+ }+}++export const useLevelSound = create<{ on: boolean; set: (on: boolean) => void }>((set) => ({+ on: readSoundOn(),+ set: (on) => {+ set({ on });+ try { localStorage.setItem(SOUND_KEY, on ? "on" : "off"); } catch (error) { console.debug("Verse sound setting not saved", error); }+ },+}));++let context: AudioContext | null = null;++function audio(): AudioContext | null {+ if (!useLevelSound.getState().on) return null;+ try {+ const Ctor = window.AudioContext ?? (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;+ if (!Ctor) return null;+ context ??= new Ctor();+ if (context.state === "suspended") void context.resume().catch(() => undefined);+ return context;+ } catch (error) {+ console.debug("Web Audio unavailable", error);+ return null;+ }+}++function tone(ctx: AudioContext, freq: number, start: number, length: number, gain: number, type: OscillatorType = "triangle"): void {+ const osc = ctx.createOscillator();+ const amp = ctx.createGain();+ osc.type = type;+ osc.frequency.setValueAtTime(freq, start);+ amp.gain.setValueAtTime(0.0001, start);+ amp.gain.exponentialRampToValueAtTime(gain, start + 0.015);+ amp.gain.exponentialRampToValueAtTime(0.0001, start + length);+ osc.connect(amp).connect(ctx.destination);+ osc.start(start);+ osc.stop(start + length + 0.02);+}++/** C major up to the octave, then a sparkle on the fifth above. */+const FANFARE = [523.25, 659.25, 783.99, 1046.5];++export function playLevelUp(big: boolean): void {+ const ctx = audio();+ if (!ctx) return;+ const t = ctx.currentTime + 0.02;+ if (!big) {+ tone(ctx, 783.99, t, 0.22, 0.06);+ tone(ctx, 1046.5, t + 0.11, 0.35, 0.06);+ return;+ }+ FANFARE.forEach((f, i) => tone(ctx, f, t + i * 0.09, 0.32, 0.08));+ tone(ctx, 1046.5, t + 0.36, 0.9, 0.07);+ tone(ctx, 1318.5, t + 0.36, 0.9, 0.05);+ for (let i = 0; i < 6; i++) tone(ctx, 2093 + i * 220, t + 0.42 + i * 0.05, 0.18, 0.018, "sine");+}++export function playXpTick(): void {+ const ctx = audio();+ if (!ctx) return;+ const t = ctx.currentTime + 0.01;+ tone(ctx, 1567.98, t, 0.09, 0.025, "sine");+}diff --git a/jarvis/ui/web/frontend/src/components/society/progression/progression.css b/jarvis/ui/web/frontend/src/components/society/progression/progression.cssnew file mode 100644index 0000000000..5c96de2652--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/progression/progression.css@@ -0,0 +1,158 @@+/*+ * The Verse's level system. The level card, toasts and progress panel are+ * app chrome over the canvas: theme tokens only, so light and dark mode both+ * read. The level chip, the "+XP" numbers, the world tag and the level-up+ * banner belong to the game itself and keep one dark-and-gold look in both+ * modes, like the name plates in the diorama.+ */++/* ---------- level card (HUD, top left) ---------- */+.level-hud { display:flex; align-items:center; gap:10px; padding:8px 12px 8px 8px; min-width:236px; max-width:300px; text-align:left; font:inherit; color:hsl(var(--popover-foreground)); cursor:pointer; }+.level-hud:hover { background:hsl(var(--secondary) / .92); }+.level-hud:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:2px; }+.level-hud[data-compact] { min-width:0; padding:5px 10px 5px 5px; }+.level-hud-body { display:flex; flex-direction:column; gap:4px; min-width:0; flex:1; }+.level-hud-name { display:flex; align-items:baseline; gap:6px; min-width:0; }+.level-hud-name strong { font-size:13px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }+.level-hud-name em { font-style:normal; font-size:11px; font-weight:600; color:hsl(var(--warning)); white-space:nowrap; }+.level-hud-xp { font-size:10.5px; color:hsl(var(--muted-foreground)); font-variant-numeric:tabular-nums; }+.level-hud-pet { display:flex; flex-direction:column; gap:3px; margin-top:2px; padding-top:5px; border-top:1px solid hsl(var(--border)); font-size:11px; color:hsl(var(--muted-foreground)); }++/* ---------- ring and bar ---------- */+.level-ring { position:relative; display:inline-flex; flex:none; align-items:center; justify-content:center; }+.level-ring svg { position:absolute; inset:0; }+.level-ring b { position:relative; font-size:15px; font-weight:800; font-variant-numeric:tabular-nums; }+.level-ring-track { fill:none; stroke:hsl(var(--border)); stroke-width:3.5; }+.level-ring-fill { fill:none; stroke-width:3.5; stroke-linecap:round; stroke:#f5b83d; transition:stroke-dasharray .7s cubic-bezier(.2,.8,.2,1); }+.level-ring[data-kind="pet"] .level-ring-fill { stroke:#2dd4bf; }+.level-ring[data-kind="agent"] .level-ring-fill { stroke:#4ade80; }+.level-bar { position:relative; display:block; height:6px; border-radius:999px; overflow:hidden; background:hsl(var(--muted)); }+.level-bar i { position:absolute; left:0; top:0; bottom:0; border-radius:inherit; }+.level-bar-gain { background:#fff1b8; box-shadow:0 0 8px #ffd25e; transition:width .15s ease-out; }+.level-bar-fill { background:linear-gradient(90deg, #f0a92b, #ffd25e); transition:width .65s cubic-bezier(.2,.8,.2,1); }+.level-bar[data-kind="pet"] .level-bar-fill { background:linear-gradient(90deg, #14b8a6, #5eead4); }+.level-bar[data-kind="pet"] .level-bar-gain { background:#ccfbf1; box-shadow:0 0 8px #5eead4; }+.level-bar[data-kind="agent"] .level-bar-fill { background:linear-gradient(90deg, #22c55e, #86efac); }+.level-bar[data-kind="agent"] .level-bar-gain { background:#dcfce7; box-shadow:0 0 8px #86efac; }++/* ---------- level chip on name plates (in-world, one look) ---------- */+.level-chip { display:inline-flex; flex:none; align-items:center; justify-content:center; min-width:20px; height:18px; padding:0 4px; font-size:10px; font-weight:800; font-variant-numeric:tabular-nums; clip-path:polygon(18% 0, 82% 0, 100% 50%, 82% 100%, 18% 100%, 0 50%); }+.office-plate .level-chip { margin-left:1px; }++/* ---------- agent toasts (bottom left) ---------- */+.level-toasts { position:absolute; z-index:38; left:14px; bottom:14px; display:flex; flex-direction:column; gap:6px; max-width:min(320px, calc(100% - 28px)); }+.level-toast { display:flex; align-items:center; gap:9px; padding:8px 12px 8px 9px; border:1px solid hsl(var(--border)); border-radius:12px; background:hsl(var(--popover) / .95); color:hsl(var(--popover-foreground)); font:inherit; text-align:left; cursor:pointer; box-shadow:0 6px 20px rgb(0 0 0 / .25); animation:level-toast-in .45s cubic-bezier(.2,1.4,.4,1) both; }+.level-toast span { display:flex; flex-direction:column; gap:1px; min-width:0; }+.level-toast strong { font-size:12px; }+.level-toast em { font-style:normal; font-size:11px; color:hsl(var(--muted-foreground)); }+@keyframes level-toast-in { from { opacity:0; transform:translateX(-24px) scale(.96); } to { opacity:1; transform:none; } }++/* ---------- world tag and "+XP" (in-world, one look) ---------- */+.level-burst-tag { display:inline-flex; align-items:center; gap:6px; padding:4px 12px 4px 10px; border-radius:999px; background:rgb(24 18 4 / .88); color:#fff3c4; box-shadow:0 0 0 2px #ffd25e, 0 0 22px rgb(255 210 94 / .65); font-weight:800; white-space:nowrap; pointer-events:none; animation-name:level-tag; animation-timing-function:ease-out; animation-fill-mode:both; }+.level-burst-tag small { font-size:10px; letter-spacing:.12em; text-transform:uppercase; }+.level-burst-tag b { font-size:18px; }+.level-burst-tag[data-kind="pet"] { color:#ccfbf1; box-shadow:0 0 0 2px #5eead4, 0 0 22px rgb(94 234 212 / .6); background:rgb(4 30 28 / .88); }+.level-burst-tag[data-kind="agent"] { color:#dcfce7; box-shadow:0 0 0 2px #86efac, 0 0 22px rgb(134 239 172 / .6); background:rgb(6 30 14 / .88); }+@keyframes level-tag { 0% { opacity:0; transform:translateY(20px) scale(.5); } 12% { opacity:1; transform:translateY(0) scale(1.15); } 20% { transform:scale(1); } 80% { opacity:1; transform:translateY(-24px); } 100% { opacity:0; transform:translateY(-40px); } }+.level-xp-pop { display:inline-block; font-size:13px; font-weight:800; color:#ffe58a; text-shadow:0 1px 0 #6b4a00, 0 0 8px rgb(255 210 94 / .8); white-space:nowrap; pointer-events:none; animation:level-xp 1.6s ease-out both; }+.level-xp-pop[data-kind="pet"] { color:#99f6e4; text-shadow:0 1px 0 #0f4f47, 0 0 8px rgb(94 234 212 / .8); }+.level-xp-pop[data-kind="agent"] { color:#bbf7d0; text-shadow:0 1px 0 #14532d, 0 0 8px rgb(134 239 172 / .8); }+@keyframes level-xp { 0% { opacity:0; transform:translateY(8px) scale(.7); } 15% { opacity:1; transform:translateY(0) scale(1.1); } 30% { transform:scale(1); } 100% { opacity:0; transform:translateY(-34px); } }++/* ---------- level-up banner (game overlay, one look) ---------- */+.level-banner-layer { position:absolute; inset:0; z-index:55; display:flex; align-items:center; justify-content:center; pointer-events:none; }+.level-banner { position:relative; pointer-events:auto; display:flex; flex-direction:column; align-items:center; gap:4px; min-width:300px; max-width:min(460px, calc(100% - 32px)); padding:26px 34px 22px; border:0; border-radius:22px; overflow:hidden; font:inherit; color:#fff7da; cursor:pointer;+ background:radial-gradient(120% 90% at 50% 0%, rgb(84 58 6 / .96), rgb(20 14 2 / .96)); box-shadow:0 0 0 2px #ffd25e, 0 0 60px rgb(255 196 64 / .55), 0 24px 60px rgb(0 0 0 / .5); animation:level-banner-in .55s cubic-bezier(.2,1.5,.35,1) both; }+.level-banner[data-kind="pet"] { color:#e6fffb; background:radial-gradient(120% 90% at 50% 0%, rgb(8 74 66 / .96), rgb(2 20 18 / .96)); box-shadow:0 0 0 2px #5eead4, 0 0 60px rgb(45 212 191 / .5), 0 24px 60px rgb(0 0 0 / .5); }+.level-banner:focus-visible { outline:3px solid #fff; outline-offset:3px; }+.level-banner > * { position:relative; }+.level-banner-rays { position:absolute !important; inset:-60%; background:repeating-conic-gradient(from 0deg, rgb(255 226 140 / .16) 0 9deg, transparent 9deg 22deg); animation:level-rays 9s linear infinite; }+.level-banner[data-kind="pet"] .level-banner-rays { background:repeating-conic-gradient(from 0deg, rgb(153 246 228 / .16) 0 9deg, transparent 9deg 22deg); }+.level-banner-flash { position:absolute !important; inset:0; background:radial-gradient(circle at 50% 40%, rgb(255 255 255 / .9), transparent 60%); animation:level-flash .7s ease-out both; }+.level-banner-away { font-size:11px; font-weight:600; opacity:.8; }+.level-banner-kicker { font-size:15px; font-weight:900; letter-spacing:.32em; text-transform:uppercase; color:#ffd25e; text-shadow:0 0 14px rgb(255 210 94 / .8); animation:level-stamp .5s .1s cubic-bezier(.2,1.8,.4,1) both; }+.level-banner[data-kind="pet"] .level-banner-kicker { color:#5eead4; text-shadow:0 0 14px rgb(94 234 212 / .8); }+.level-banner-number { position:relative; display:grid; height:78px; overflow:hidden; font-size:72px; line-height:78px; font-weight:900; font-variant-numeric:tabular-nums; }+.level-banner-number > span { grid-area:1 / 1; text-align:center; }+.level-banner-old { animation:level-roll-out .45s .35s ease-in both; }+.level-banner-new { animation:level-roll-in .55s .45s cubic-bezier(.2,1.6,.4,1) both; text-shadow:0 0 24px rgb(255 226 140 / .9); }+.level-banner-who { font-size:15px; font-weight:700; }+.level-banner-title { margin-top:2px; padding:3px 12px; border-radius:999px; background:rgb(255 255 255 / .1); font-size:12px; font-weight:700; animation:level-rise .4s .8s ease-out both; }+.level-banner-rewards { display:flex; flex-direction:column; align-items:center; gap:6px; margin-top:12px; }+.level-banner-unlocked { font-size:10px; letter-spacing:.2em; text-transform:uppercase; opacity:.75; animation:level-rise .4s .85s ease-out both; }+.level-banner-reward { display:flex; align-items:center; gap:10px; min-width:220px; padding:6px 14px 6px 6px; border-radius:12px; background:rgb(255 255 255 / .1); box-shadow:inset 0 0 0 1px rgb(255 255 255 / .14); font-size:13px; font-weight:700; animation:level-rise .45s ease-out both; }+.level-banner-hint { margin-top:4px; font-size:11px; opacity:.7; animation:level-rise .4s 1.4s ease-out both; }+@keyframes level-banner-in { 0% { opacity:0; transform:scale(.4); } 60% { opacity:1; } 100% { transform:scale(1); } }+@keyframes level-rays { to { transform:rotate(360deg); } }+@keyframes level-flash { from { opacity:1; } to { opacity:0; } }+@keyframes level-stamp { 0% { opacity:0; transform:scale(2.4); } 100% { opacity:1; transform:scale(1); } }+@keyframes level-roll-out { to { opacity:0; transform:translateY(-80px); } }+@keyframes level-roll-in { 0% { opacity:0; transform:translateY(80px) scale(.6); } 100% { opacity:1; transform:none; } }+@keyframes level-rise { 0% { opacity:0; transform:translateY(14px); } 100% { opacity:1; transform:none; } }++/* ---------- reward icon ---------- */+.level-reward-icon { display:inline-flex; flex:none; align-items:center; justify-content:center; border-radius:8px; color:rgb(20 16 4 / .85); box-shadow:inset 0 0 0 1px rgb(255 255 255 / .35); }+.level-reward-icon[data-locked] { background:hsl(var(--muted)); color:hsl(var(--muted-foreground)); box-shadow:inset 0 0 0 1px hsl(var(--border)); }++/* ---------- progress panel ---------- */+.level-panel-layer { position:absolute; inset:0; z-index:50; display:flex; align-items:center; justify-content:center; padding:16px; background:rgb(0 0 0 / .25); }+.level-panel { display:flex; flex-direction:column; width:min(680px, 100%); max-height:min(720px, 100%); overflow:hidden; }+.level-panel:focus { outline:none; }+.level-panel-head { display:flex; align-items:center; gap:12px; padding:12px 14px 8px; border-bottom:1px solid hsl(var(--border)); }+.level-panel-head h2 { margin:0; font-size:15px; font-weight:800; }+.level-tabs { display:flex; gap:4px; flex:1; flex-wrap:wrap; }+.level-tab { border:1px solid transparent; border-radius:8px; padding:4px 10px; background:none; color:hsl(var(--muted-foreground)); font:inherit; font-size:12px; font-weight:600; cursor:pointer; }+.level-tab:hover { background:hsl(var(--secondary)); color:hsl(var(--foreground)); }+.level-tab[aria-selected="true"] { background:hsl(var(--secondary)); color:hsl(var(--foreground)); border-color:hsl(var(--border)); }+.level-tab:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:1px; }+.level-panel-body { display:flex; flex-direction:column; gap:14px; padding:12px 14px 14px; overflow:auto; font-size:12px; }+.level-panel-foot { display:flex; align-items:center; justify-content:space-between; gap:10px; flex-wrap:wrap; padding:8px 14px 10px; border-top:1px solid hsl(var(--border)); }+.level-sound { display:inline-flex; align-items:center; gap:6px; font-size:12px; cursor:pointer; }+.level-sound input { accent-color:hsl(var(--primary)); }+.level-subject { display:flex; align-items:center; gap:12px; }+.level-subject > div { display:flex; flex-direction:column; gap:4px; flex:1; min-width:0; }+.level-subject strong { font-size:15px; }+.level-subject em { font-style:normal; font-size:12px; font-weight:700; color:hsl(var(--warning)); }+.level-subject-xp { font-size:11px; color:hsl(var(--muted-foreground)); font-variant-numeric:tabular-nums; }+.level-section h3 { margin:0 0 6px; font-size:11px; font-weight:700; letter-spacing:.04em; text-transform:uppercase; color:hsl(var(--muted-foreground)); }+.level-slots { display:flex; flex-direction:column; gap:8px; }+.level-slot { display:grid; grid-template-columns:64px 1fr; gap:8px; align-items:start; }+.level-slot-name { padding-top:4px; font-weight:600; }+.level-wear-chip { display:inline-flex; align-items:center; gap:5px; padding-left:4px; }+.level-wear-chip:disabled { opacity:.55; cursor:not-allowed; }+.level-wear-chip small { font-size:10px; color:hsl(var(--muted-foreground)); }+.level-track { display:flex; gap:8px; margin:0; padding:2px 2px 8px; list-style:none; overflow-x:auto; scroll-snap-type:x proximity; }+.level-track li { flex:none; display:flex; flex-direction:column; gap:6px; min-width:118px; max-width:150px; padding:8px; border:1px solid hsl(var(--border)); border-radius:12px; background:hsl(var(--background)); scroll-snap-align:center; }+.level-track li[data-done] { border-color:hsl(var(--warning) / .55); background:hsl(var(--warning) / .08); }+.level-track li[data-next] { border-color:hsl(var(--primary)); box-shadow:0 0 0 2px hsl(var(--primary) / .25); }+.level-track-at { font-size:11px; font-weight:800; }+.level-track-items { display:flex; flex-direction:column; gap:5px; }+.level-track-item { display:flex; align-items:center; gap:6px; font-size:11px; line-height:1.25; }+.level-track-title { align-self:flex-start; padding:2px 7px; border-radius:999px; background:hsl(var(--secondary)); font-size:10.5px; font-weight:700; }+.level-rules { display:grid; grid-template-columns:repeat(auto-fill, minmax(250px, 1fr)); gap:4px 12px; margin:0; padding:0; list-style:none; }+.level-rules li { display:flex; align-items:flex-start; gap:8px; padding:5px 6px; border-radius:8px; }+.level-rules li:hover { background:hsl(var(--secondary) / .6); }+.level-rule-xp { flex:none; min-width:34px; padding:1px 5px; border-radius:6px; background:hsl(var(--warning) / .16); color:hsl(var(--foreground)); font-size:11px; font-weight:800; text-align:center; font-variant-numeric:tabular-nums; }+.level-rule-text { display:flex; flex-direction:column; gap:1px; }+.level-rule-text em { font-style:normal; font-size:10.5px; color:hsl(var(--muted-foreground)); }+.level-agents { display:flex; flex-direction:column; gap:4px; margin:0; padding:0; list-style:none; }+.level-agents li { display:flex; align-items:center; gap:8px; padding:5px 6px; border-radius:8px; }+.level-agents li:hover { background:hsl(var(--secondary) / .6); }+.level-agent-rank { width:18px; text-align:right; font-size:11px; font-weight:700; color:hsl(var(--muted-foreground)); }+.level-agent-body { display:flex; flex-direction:column; gap:4px; flex:1; min-width:0; }+.level-agent-body em { font-style:normal; font-size:11px; color:hsl(var(--muted-foreground)); }++@media (max-width:600px) {+ .level-hud { min-width:0; }+ .level-slot { grid-template-columns:1fr; }+ .level-banner { padding:20px 18px 18px; }+ .level-banner-number { font-size:56px; }+}++@media (prefers-reduced-motion: reduce) {+ .level-banner, .level-banner-kicker, .level-banner-old, .level-banner-new, .level-banner-title, .level-banner-unlocked,+ .level-banner-reward, .level-banner-hint, .level-toast, .level-burst-tag, .level-xp-pop { animation-duration:.01ms !important; animation-delay:0s !important; }+ .level-banner-old { display:none; }+ .level-banner-rays, .level-banner-flash { animation:none; opacity:.5; }+ .level-bar i, .level-ring-fill { transition:none; }+}diff --git a/jarvis/ui/web/frontend/src/components/society/progression/progression.test.ts b/jarvis/ui/web/frontend/src/components/society/progression/progression.test.tsnew file mode 100644index 0000000000..062140f818--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/progression/progression.test.ts@@ -0,0 +1,175 @@+import { beforeEach, describe, expect, it } from "vitest";+import { equippedFor, levelFraction, progressFor, unlockedFor } from "./cosmetics";+import { parseAwardEvent, parseSnapshot, type ProgressionSnapshot, type RewardRow } from "./progressionApi";+import { awayCelebrations, useProgression } from "./progressionStore";+import { footprintAt, pruneSamples, pushSample, rainbowHue, RIBBON_MAX_SAMPLES, writeRibbon, type TrailSample } from "./effects/trailModel";+import { REWARD_IDS, slotOf } from "./levelCatalog";++const REWARDS: RewardRow[] = [+ { rewardId: "frame_bronze", slot: "frame", levels: { person: 3, agent: 3, pet: 3 } },+ { rewardId: "frame_silver", slot: "frame", levels: { person: 10, agent: 10, pet: 10 } },+ { rewardId: "trail_footprints", slot: "trail", levels: { person: 2, agent: null, pet: null } },+ { rewardId: "trail_sparkle", slot: "trail", levels: { person: 5, agent: 5, pet: 2 } },+ { rewardId: "aura_glow", slot: "aura", levels: { person: 7, agent: 8, pet: 5 } },+];++/** Total XP at which each level starts, the server's `level_xp` for the first few levels. */+const CURVE = [0, 40, 105, 195, 310, 450];++function snapshot(overrides: Partial<ProgressionSnapshot> = {}): ProgressionSnapshot {+ return {+ subjects: [], petId: "ember", recent: [], latestSeq: 0, maxLevel: 50, levelXp: CURVE, rules: [], rewards: REWARDS,+ titles: { person: [{ level: 1, title: "newcomer" }, { level: 5, title: "apprentice" }], agent: [], pet: [] },+ ...overrides,+ };+}++describe("cosmetics", () => {+ it("unlocks by the subject kind's own level", () => {+ expect(unlockedFor(REWARDS, "person", 2).map((r) => r.rewardId)).toEqual(["trail_footprints"]);+ expect(unlockedFor(REWARDS, "pet", 2).map((r) => r.rewardId)).toEqual(["trail_sparkle"]);+ expect(unlockedFor(REWARDS, "agent", 4).map((r) => r.rewardId)).toEqual(["frame_bronze"]);+ });++ it("wears the latest unlock per slot unless the person chose", () => {+ expect(equippedFor(REWARDS, "person", 7)).toEqual({ frame: "frame_bronze", trail: "trail_sparkle", aura: "aura_glow" });+ expect(equippedFor(REWARDS, "person", 7, { trail: "trail_footprints", aura: "none" }))+ .toEqual({ frame: "frame_bronze", trail: "trail_footprints" });+ });++ it("ignores a chosen piece that is not unlocked (any more)", () => {+ expect(equippedFor(REWARDS, "person", 4, { frame: "frame_silver" })).toEqual({ frame: "frame_bronze", trail: "trail_footprints" });+ });++ it("measures progress inside a level from the server's curve", () => {+ expect(progressFor(CURVE, 120, 3)).toEqual({ into: 15, size: 90 });+ expect(progressFor([0, 40], 999, 2)).toEqual({ into: 959, size: 0 });+ expect(levelFraction({ xpIntoLevel: 15, xpForNext: 60 })).toBe(0.25);+ expect(levelFraction({ xpIntoLevel: 0, xpForNext: 0 })).toBe(1);+ expect(levelFraction(undefined)).toBe(0);+ });+});++describe("progressionApi", () => {+ it("parses the snapshot and drops unknown rewards", () => {+ const parsed = parseSnapshot({+ subjects: [{ subject_id: "person", kind: "person", xp: 50, level: 2, xp_into_level: 10, xp_for_next: 65, title: "newcomer" }],+ pet_id: "miso", recent: [], latest_seq: 7, max_level: 50, level_xp: [0, 40],+ rules: [{ source: "chat_turn", kind: "person", xp: 5, trigger: "server", cooldown_s: 0, daily_cap: 100 }],+ rewards: [{ reward_id: "aura_glow", slot: "aura", levels: { person: 7, agent: 8, pet: null } }, { reward_id: "hat_tall", slot: "gadget", levels: {} }],+ titles: { person: [{ level: 1, title: "newcomer" }] },+ });+ expect(parsed.subjects[0]).toMatchObject({ subjectId: "person", level: 2, xpIntoLevel: 10, xpForNext: 65 });+ expect(parsed.petId).toBe("miso");+ expect(parsed.rewards.map((r) => r.rewardId)).toEqual(["aura_glow"]);+ expect(parsed.rewards[0].levels.pet).toBeNull();+ expect(parsed.rules[0]).toMatchObject({ source: "chat_turn", dailyCap: 100 });+ });++ it("parses an award push and refuses one without a subject", () => {+ expect(parseAwardEvent({ subject_id: "agent:scout", subject_kind: "agent", xp: 40, total_xp: 108, level: 3, previous_level: 2, unlocked: ["frame_bronze", "nope"] }))+ .toMatchObject({ subjectId: "agent:scout", kind: "agent", level: 3, unlocked: ["frame_bronze"] });+ expect(parseAwardEvent({ xp: 5 })).toBeNull();+ expect(parseAwardEvent(null)).toBeNull();+ });+});++describe("progressionStore", () => {+ beforeEach(() => {+ useProgression.setState({ snapshot: null, subjects: {}, banners: [], toasts: [], popups: [], bursts: [], cheerUntil: 0 });+ useProgression.getState().hydrate(snapshot(), []);+ });++ it("applies a gain as a popup without a celebration", () => {+ useProgression.getState().apply({ seq: 1, subjectId: "person", kind: "person", source: "chat_turn", xp: 5, totalXp: 5, level: 1, previousLevel: 1, title: "newcomer", unlocked: [] }, 1000);+ const s = useProgression.getState();+ expect(s.subjects.person).toMatchObject({ xp: 5, xpIntoLevel: 5, xpForNext: 40 });+ expect(s.popups).toHaveLength(1);+ expect(s.banners).toHaveLength(0);+ expect(s.bursts).toHaveLength(0);+ });++ it("celebrates the person with a banner, a burst and a cheer; an agent with a toast", () => {+ useProgression.getState().apply({ seq: 2, subjectId: "person", kind: "person", source: "agent_hired", xp: 50, totalXp: 50, level: 2, previousLevel: 1, title: "newcomer", unlocked: ["trail_footprints"] }, 1000);+ useProgression.getState().apply({ seq: 3, subjectId: "agent:scout", kind: "agent", source: "task_done", xp: 40, totalXp: 40, level: 2, previousLevel: 1, title: "rookie", unlocked: [] }, 1000);+ const s = useProgression.getState();+ expect(s.banners.map((b) => b.subjectId)).toEqual(["person"]);+ expect(s.toasts.map((b) => b.subjectId)).toEqual(["agent:scout"]);+ expect(s.bursts).toHaveLength(2);+ expect(s.cheerUntil).toBeGreaterThan(1000);+ });++ it("ignores a late duplicate push", () => {+ const award = { seq: 4, subjectId: "person", kind: "person" as const, source: "chat_turn", xp: 5, totalXp: 5, level: 1, previousLevel: 1, title: "newcomer", unlocked: [] };+ useProgression.getState().apply(award, 1000);+ useProgression.getState().apply(award, 1000);+ expect(useProgression.getState().popups).toHaveLength(1);+ });++ it("expires popups and bursts on the scene clock", () => {+ useProgression.getState().apply({ seq: 5, subjectId: "person", kind: "person", source: "agent_hired", xp: 50, totalXp: 50, level: 2, previousLevel: 1, title: "newcomer", unlocked: [] }, 0);+ useProgression.getState().expire(100_000);+ expect(useProgression.getState().popups).toHaveLength(0);+ expect(useProgression.getState().bursts).toHaveLength(0);+ });++ it("tells each subject's missed level-ups once, and nothing on a first visit", () => {+ const missed = snapshot({+ subjects: [{ subjectId: "agent:scout", kind: "agent", xp: 200, level: 4, xpIntoLevel: 5, xpForNext: 115, title: "rookie" }],+ recent: [+ { seq: 3, subjectId: "agent:scout", kind: "agent", source: "task_done", xp: 40, levelBefore: 1, levelAfter: 2, tsMs: 0 },+ { seq: 4, subjectId: "agent:scout", kind: "agent", source: "quest_done", xp: 60, levelBefore: 2, levelAfter: 4, tsMs: 0 },+ { seq: 5, subjectId: "person", kind: "person", source: "chat_turn", xp: 5, levelBefore: 1, levelAfter: 1, tsMs: 0 },+ ],+ });+ const away = awayCelebrations(missed, 2);+ expect(away).toHaveLength(1);+ expect(away[0]).toMatchObject({ subjectId: "agent:scout", level: 4, previousLevel: 1, away: true, unlocked: ["frame_bronze"] });+ expect(awayCelebrations(missed, null)).toEqual([]);+ expect(awayCelebrations(missed, 4)).toEqual([]);+ });+});++describe("trail model", () => {+ it("samples a ribbon by distance, caps it and restarts after a teleport", () => {+ const samples: TrailSample[] = [];+ expect(pushSample(samples, 0, 0, 0)).toBe(true);+ expect(pushSample(samples, 0.05, 0, 0.1)).toBe(false);+ for (let i = 1; i <= 40; i++) pushSample(samples, i * 0.2, 0, i);+ expect(samples).toHaveLength(RIBBON_MAX_SAMPLES);+ pushSample(samples, 100, 100, 50);+ expect(samples).toHaveLength(1);+ });++ it("ages samples out", () => {+ const samples: TrailSample[] = [{ x: 0, z: 0, t: 0 }, { x: 1, z: 0, t: 1 }];+ pruneSamples(samples, 1.5, 1);+ expect(samples).toEqual([{ x: 1, z: 0, t: 1 }]);+ });++ it("writes a strip that is widest and brightest at the head", () => {+ const samples: TrailSample[] = [{ x: 0, z: 0, t: 1 }, { x: 0, z: 1, t: 1 }, { x: 0, z: 2, t: 1 }];+ const positions = new Float32Array(samples.length * 6);+ const bright = writeRibbon(samples, 1, 1, 0.4, 0.02, positions);+ expect(bright[0]).toBe(0);+ expect(bright[2]).toBe(1);+ const width = (i: number) => Math.hypot(positions[i * 6] - positions[i * 6 + 3], positions[i * 6 + 2] - positions[i * 6 + 5]);+ expect(width(2)).toBeCloseTo(0.4);+ expect(width(0)).toBeCloseTo(0);+ expect(positions[1]).toBeCloseTo(0.02);+ });++ it("places footprints left and right of the heading", () => {+ const left = footprintAt(0, 0, 0, true);+ const right = footprintAt(0, 0, 0, false);+ expect(left.x).toBeGreaterThan(0);+ expect(right.x).toBeLessThan(0);+ expect(rainbowHue(0.5, 0)).toBeGreaterThanOrEqual(0);+ });+});++describe("level catalog", () => {+ it("names every reward after its slot", () => {+ for (const id of REWARD_IDS) expect(["frame", "trail", "aura", "gadget"]).toContain(slotOf(id));+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/progression/progressionApi.ts b/jarvis/ui/web/frontend/src/components/society/progression/progressionApi.tsnew file mode 100644index 0000000000..426742d72b--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/progression/progressionApi.ts@@ -0,0 +1,140 @@+/**+ * The typed client of `/api/progression` (jarvis/ui/web/progression_routes.py)+ * and the shape of the `ProgressionAwarded` push the WebSocket forwards.+ */+import type { RewardId, Slot, SubjectKind, WorldAction, XpSource } from "./levelCatalog";+import { isRewardId } from "./levelCatalog";++export interface SubjectLevel {+ subjectId: string;+ kind: SubjectKind;+ xp: number;+ level: number;+ xpIntoLevel: number;+ xpForNext: number;+ title: string;+}++export interface XpRuleRow {+ source: XpSource;+ kind: SubjectKind;+ xp: number;+ trigger: "server" | "world";+ cooldownS: number;+ dailyCap: number;+}++export interface RewardRow {+ rewardId: RewardId;+ slot: Slot;+ levels: Record<SubjectKind, number | null>;+}++export interface AwardRow {+ seq: number;+ subjectId: string;+ kind: SubjectKind;+ source: string;+ xp: number;+ levelBefore: number;+ levelAfter: number;+ tsMs: number;+}++export interface ProgressionSnapshot {+ subjects: SubjectLevel[];+ petId: string;+ recent: AwardRow[];+ latestSeq: number;+ maxLevel: number;+ /** Total XP at which each level starts, index 0 = level 1. */+ levelXp: number[];+ rules: XpRuleRow[];+ rewards: RewardRow[];+ titles: Record<SubjectKind, { level: number; title: string }[]>;+}++/** One `ProgressionAwarded` from the bus, as the WebSocket delivers it. */+export interface AwardEvent {+ seq: number;+ subjectId: string;+ kind: SubjectKind;+ source: string;+ xp: number;+ totalXp: number;+ level: number;+ previousLevel: number;+ title: string;+ unlocked: RewardId[];+}++type Raw = Record<string, unknown>;+const num = (value: unknown, fallback = 0): number => (typeof value === "number" && Number.isFinite(value) ? value : fallback);+const str = (value: unknown): string => (typeof value === "string" ? value : "");+const kindOf = (value: unknown): SubjectKind => (value === "agent" || value === "pet" ? value : "person");++export function parseSnapshot(body: Raw): ProgressionSnapshot {+ const list = (value: unknown): Raw[] => (Array.isArray(value) ? value.filter((v): v is Raw => !!v && typeof v === "object") : []);+ const titles = (body.titles && typeof body.titles === "object" ? body.titles : {}) as Record<string, unknown>;+ const bands = (kind: SubjectKind) => list(titles[kind]).map((b) => ({ level: num(b.level, 1), title: str(b.title) }));+ return {+ subjects: list(body.subjects).map((row) => ({+ subjectId: str(row.subject_id), kind: kindOf(row.kind), xp: num(row.xp), level: num(row.level, 1),+ xpIntoLevel: num(row.xp_into_level), xpForNext: num(row.xp_for_next), title: str(row.title),+ })),+ petId: str(body.pet_id) || "gigi",+ recent: list(body.recent).map((row) => ({+ seq: num(row.seq), subjectId: str(row.subject_id), kind: kindOf(row.kind), source: str(row.source), xp: num(row.xp),+ levelBefore: num(row.level_before, 1), levelAfter: num(row.level_after, 1), tsMs: num(row.ts_ms),+ })),+ latestSeq: num(body.latest_seq),+ maxLevel: num(body.max_level, 50),+ levelXp: Array.isArray(body.level_xp) ? body.level_xp.map((v) => num(v)) : [0],+ rules: list(body.rules).map((row) => ({+ source: str(row.source) as XpSource, kind: kindOf(row.kind), xp: num(row.xp),+ trigger: row.trigger === "world" ? "world" : "server", cooldownS: num(row.cooldown_s), dailyCap: num(row.daily_cap),+ })),+ rewards: list(body.rewards).filter((row) => isRewardId(row.reward_id)).map((row) => {+ const levels = (row.levels && typeof row.levels === "object" ? row.levels : {}) as Raw;+ const at = (kind: SubjectKind) => (typeof levels[kind] === "number" ? (levels[kind] as number) : null);+ return { rewardId: row.reward_id as RewardId, slot: str(row.slot) as Slot, levels: { person: at("person"), agent: at("agent"), pet: at("pet") } };+ }),+ titles: { person: bands("person"), agent: bands("agent"), pet: bands("pet") },+ };+}++export function parseAwardEvent(payload: unknown): AwardEvent | null {+ if (!payload || typeof payload !== "object") return null;+ const p = payload as Raw;+ const subjectId = str(p.subject_id);+ if (!subjectId) return null;+ return {+ seq: num(p.seq), subjectId, kind: kindOf(p.subject_kind), source: str(p.xp_source), xp: num(p.xp),+ totalXp: num(p.total_xp), level: num(p.level, 1), previousLevel: num(p.previous_level, 1), title: str(p.title),+ unlocked: Array.isArray(p.unlocked) ? p.unlocked.filter(isRewardId) : [],+ };+}++export async function fetchProgression(afterSeq = 0): Promise<ProgressionSnapshot> {+ const res = await fetch(`/api/progression${afterSeq > 0 ? `?after_seq=${afterSeq}` : ""}`);+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ return parseSnapshot((await res.json()) as Raw);+}++/** Report a world action; the server decides whether it pays. Never throws. */+export async function reportWorldAction(action: WorldAction, ref = ""): Promise<void> {+ try {+ await fetch("/api/progression/actions", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ action, ref }),+ });+ } catch (error) {+ // XP is a garnish: an unreachable backend never disturbs the Verse.+ console.debug("Level action not reported", action, error);+ }+}++export const agentSubject = (agentId: string): string => `agent:${agentId}`;+export const petSubject = (petId: string): string => `pet:${petId}`;+export const PERSON_SUBJECT = "person";diff --git a/jarvis/ui/web/frontend/src/components/society/progression/progressionStore.ts b/jarvis/ui/web/frontend/src/components/society/progression/progressionStore.tsnew file mode 100644index 0000000000..51131f98f1--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/progression/progressionStore.ts@@ -0,0 +1,173 @@+/**+ * The Verse's level state, shared by the HUD (DOM) and the effects (canvas).+ *+ * The first read hydrates it; every `ProgressionAwarded` push applies one+ * award, queues a floating "+XP" over whoever earned it and, on a level-up,+ * a celebration: the big banner for the person and their pet, a toast for an+ * agent, and a burst of light in the world for all three.+ */+import { create } from "zustand";+import type { AwardEvent, ProgressionSnapshot, SubjectLevel } from "./progressionApi";+import { PERSON_SUBJECT } from "./progressionApi";+import type { RewardId, Slot, SubjectKind } from "./levelCatalog";+import { loadChoices, progressFor, saveChoices, type ChoiceBook, type SlotChoice } from "./cosmetics";++export interface Celebration {+ id: number;+ subjectId: string;+ kind: SubjectKind;+ level: number;+ previousLevel: number;+ title: string;+ unlocked: RewardId[];+ /** Earned while the Verse was closed: told, not staged in the world. */+ away: boolean;+}++export interface XpPopup { id: number; subjectId: string; xp: number; bornMs: number }+export interface Burst { id: number; subjectId: string; kind: SubjectKind; level: number; bornMs: number }++/** How long a floating "+XP" and a level-up burst live, in ms. */+export const POPUP_MS = 1600;+export const BURST_MS = 2600;+/** How long the person's figure cheers after their own level-up. */+export const CHEER_MS = 2200;+const MAX_POPUPS = 12;+const MAX_TOASTS = 4;++export type PanelTab = "you" | "pet" | "agents";++interface ProgressionState {+ snapshot: ProgressionSnapshot | null;+ subjects: Record<string, SubjectLevel>;+ petId: string;+ /** Person and pet level-ups waiting for the banner, oldest first. */+ banners: Celebration[];+ /** Agent level-ups, newest last. */+ toasts: Celebration[];+ popups: XpPopup[];+ bursts: Burst[];+ cheerUntil: number;+ panel: PanelTab | null;+ choices: ChoiceBook;+ hydrate: (snapshot: ProgressionSnapshot, away: Celebration[]) => void;+ apply: (award: AwardEvent, nowMs?: number) => void;+ setPetId: (petId: string) => void;+ dismissBanner: () => void;+ dismissToast: (id: number) => void;+ expire: (nowMs: number) => void;+ openPanel: (tab: PanelTab | null) => void;+ choose: (who: "person" | "pet", slot: Slot, choice: SlotChoice) => void;+}++let nextId = 1;++export function celebrationOf(award: Pick<AwardEvent, "subjectId" | "kind" | "level" | "previousLevel" | "title" | "unlocked">, away = false): Celebration {+ return {+ id: nextId++, subjectId: award.subjectId, kind: award.kind, level: award.level, previousLevel: award.previousLevel,+ title: award.title, unlocked: award.unlocked, away,+ };+}++export const useProgression = create<ProgressionState>((set, get) => ({+ snapshot: null,+ subjects: {},+ petId: "gigi",+ banners: [],+ toasts: [],+ popups: [],+ bursts: [],+ cheerUntil: 0,+ panel: null,+ choices: loadChoices(),+ hydrate: (snapshot, away) => set((s) => {+ const subjects: Record<string, SubjectLevel> = {};+ for (const row of snapshot.subjects) subjects[row.subjectId] = row;+ const banners = [...s.banners, ...away.filter((c) => c.kind !== "agent")];+ const toasts = [...s.toasts, ...away.filter((c) => c.kind === "agent")].slice(-MAX_TOASTS);+ return { snapshot, subjects, petId: snapshot.petId, banners, toasts };+ }),+ apply: (award, nowMs = performance.now()) => set((s) => {+ const known = s.subjects[award.subjectId];+ // A push older than what the subject already shows (a late duplicate) changes nothing.+ if (known && known.xp >= award.totalXp) return s;+ const curve = s.snapshot?.levelXp ?? [];+ const { into, size } = progressFor(curve, award.totalXp, award.level);+ const atCap = s.snapshot ? award.level >= s.snapshot.maxLevel : false;+ const subject: SubjectLevel = {+ subjectId: award.subjectId, kind: award.kind, xp: award.totalXp, level: award.level,+ xpIntoLevel: atCap ? 0 : into, xpForNext: atCap ? 0 : size, title: award.title,+ };+ const popups = [...s.popups, { id: nextId++, subjectId: award.subjectId, xp: award.xp, bornMs: nowMs }].slice(-MAX_POPUPS);+ if (award.level <= award.previousLevel) return { subjects: { ...s.subjects, [award.subjectId]: subject }, popups };+ const party = celebrationOf(award);+ const bursts = [...s.bursts, { id: nextId++, subjectId: award.subjectId, kind: award.kind, level: award.level, bornMs: nowMs }];+ return {+ subjects: { ...s.subjects, [award.subjectId]: subject },+ popups,+ bursts,+ banners: award.kind === "agent" ? s.banners : [...s.banners, party],+ toasts: award.kind === "agent" ? [...s.toasts, party].slice(-MAX_TOASTS) : s.toasts,+ cheerUntil: award.subjectId === PERSON_SUBJECT ? nowMs + CHEER_MS : s.cheerUntil,+ };+ }),+ setPetId: (petId) => set((s) => (s.petId === petId || !petId ? s : { petId })),+ dismissBanner: () => set((s) => ({ banners: s.banners.slice(1) })),+ dismissToast: (id) => set((s) => ({ toasts: s.toasts.filter((t) => t.id !== id) })),+ expire: (nowMs) => {+ const s = get();+ const popups = s.popups.filter((p) => nowMs - p.bornMs < POPUP_MS);+ const bursts = s.bursts.filter((b) => nowMs - b.bornMs < BURST_MS);+ if (popups.length !== s.popups.length || bursts.length !== s.bursts.length) set({ popups, bursts });+ },+ openPanel: (panel) => set({ panel }),+ choose: (who, slot, choice) => set((s) => {+ const choices: ChoiceBook = { ...s.choices, [who]: { ...(s.choices[who] ?? {}), [slot]: choice } };+ saveChoices(choices);+ return { choices };+ }),+}));++const SEEN_KEY = "jarvis.verse.levels.seen.v1";++/** The last award this browser has shown; null on a first visit. */+export function readSeenSeq(): number | null {+ try {+ const raw = typeof localStorage === "undefined" ? null : localStorage.getItem(SEEN_KEY);+ const value = raw === null ? NaN : Number(raw);+ return Number.isFinite(value) ? value : null;+ } catch (error) {+ console.debug("Verse level marker unavailable", error);+ return null;+ }+}++export function writeSeenSeq(seq: number): void {+ try {+ localStorage.setItem(SEEN_KEY, String(seq));+ } catch (error) {+ console.debug("Verse level marker not saved", error);+ }+}++/**+ * Level-ups that happened while the Verse was closed: the latest one per+ * subject, so a busy agent that climbed three levels is told once.+ */+export function awayCelebrations(snapshot: ProgressionSnapshot, seenSeq: number | null): Celebration[] {+ if (seenSeq === null) return [];+ const latest = new Map<string, Celebration>();+ for (const row of snapshot.recent) {+ if (row.seq <= seenSeq || row.levelAfter <= row.levelBefore) continue;+ const prior = latest.get(row.subjectId);+ const subject = snapshot.subjects.find((s) => s.subjectId === row.subjectId);+ const unlocked = snapshot.rewards+ .filter((r) => { const at = r.levels[row.kind]; return at !== null && at > (prior?.previousLevel ?? row.levelBefore) && at <= row.levelAfter; })+ .map((r) => r.rewardId);+ latest.set(row.subjectId, celebrationOf({+ subjectId: row.subjectId, kind: row.kind, level: row.levelAfter, previousLevel: prior?.previousLevel ?? row.levelBefore,+ title: subject?.title ?? "", unlocked,+ }, true));+ }+ return [...latest.values()];+}diff --git a/jarvis/ui/web/frontend/src/components/society/progression/useProgressionSync.ts b/jarvis/ui/web/frontend/src/components/society/progression/useProgressionSync.tsnew file mode 100644index 0000000000..18712a4f5d--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/progression/useProgressionSync.ts@@ -0,0 +1,93 @@+/**+ * Keeps the Verse's level state in step with the server while the map is+ * open, and reports the world actions the server meters.+ *+ * - First read on mount (with the level-ups missed while the map was closed),+ * then a slow jittered re-read as a safety net (AP-33); live awards arrive+ * as `ProgressionAwarded` pushes over the existing WebSocket.+ * - Daily visit and each floor discovered, a pet or a treat for the office+ * dog, a team gathered at the table: reported once each, the server+ * decides whether they pay.+ */+import { useEffect, useRef } from "react";+import { useEventStore } from "@/store/events";+import { useCompanionPet } from "../companion/companionPetStore";+import { useOfficeDog } from "../office/dogLife";+import { useOfficeStore, type OfficeFloor } from "../office/officeStore";+import { fetchProgression, parseAwardEvent, reportWorldAction } from "./progressionApi";+import { awayCelebrations, readSeenSeq, useProgression, writeSeenSeq } from "./progressionStore";+import { playLevelUp, playXpTick } from "./levelSounds";++const RESYNC_MS = 60_000;+const RESYNC_JITTER_MS = 15_000;+/** Ticks for "+XP" closer together than this are one sound. */+const TICK_GAP_MS = 400;++export function useProgressionSync(awake: boolean, floor: OfficeFloor): void {+ const seen = useRef<number>(0);++ // First read, then the slow safety net while the map is on screen.+ useEffect(() => {+ if (!awake) return;+ let cancelled = false;+ let timer: ReturnType<typeof setTimeout> | undefined;+ const load = async (first: boolean) => {+ try {+ const snapshot = await fetchProgression();+ if (cancelled) return;+ const marker = readSeenSeq();+ useProgression.getState().hydrate(snapshot, first ? awayCelebrations(snapshot, marker) : []);+ seen.current = Math.max(seen.current, snapshot.latestSeq);+ writeSeenSeq(seen.current);+ } catch (error) {+ // The Verse plays on without levels; the next read tries again.+ console.debug("Verse levels unavailable", error);+ }+ if (!cancelled) timer = setTimeout(() => void load(false), RESYNC_MS + Math.random() * RESYNC_JITTER_MS);+ };+ void load(true);+ return () => { cancelled = true; clearTimeout(timer); };+ }, [awake]);++ // Live awards from the bus.+ useEffect(() => {+ let lastId: string | null = useEventStore.getState().events[0]?.id ?? null;+ let lastTick = 0;+ return useEventStore.subscribe((state) => {+ const fresh = [];+ for (const event of state.events) {+ if (event.id === lastId) break;+ fresh.push(event);+ }+ lastId = state.events[0]?.id ?? lastId;+ for (const event of fresh.reverse()) {+ if (event.name !== "ProgressionAwarded") continue;+ const award = parseAwardEvent(event.payload);+ if (!award) continue;+ useProgression.getState().apply(award);+ if (award.seq > seen.current) { seen.current = award.seq; writeSeenSeq(award.seq); }+ if (award.level > award.previousLevel) playLevelUp(award.kind !== "agent");+ else if (award.kind !== "agent" && performance.now() - lastTick > TICK_GAP_MS) { lastTick = performance.now(); playXpTick(); }+ }+ });+ }, []);++ // The pet that earns is the one in My Pets right now.+ const petId = useCompanionPet((s) => s.pet.id);+ useEffect(() => { useProgression.getState().setPetId(petId); }, [petId]);++ // The day's first visit and every floor discovered.+ useEffect(() => { if (awake) void reportWorldAction("daily_visit"); }, [awake]);+ useEffect(() => { if (awake) void reportWorldAction("floor_discovered", floor); }, [awake, floor]);++ // The office dog: a pat, a treat.+ useEffect(() => useOfficeDog.subscribe((state, prev) => {+ if (state.petSeq !== prev.petSeq) void reportWorldAction("dog_petted");+ if (state.treatSeq !== prev.treatSeq) void reportWorldAction("dog_treat");+ }), []);++ // A team gathered at the team-room table.+ useEffect(() => useOfficeStore.subscribe((state, prev) => {+ if (state.meeting && state.meeting.groupId !== prev.meeting?.groupId) void reportWorldAction("team_meeting");+ }), []);+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json b/jarvis/ui/web/frontend/src/i18n/locales/society/de.jsonindex d10640aed7..fdca7830b2 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json@@ -1336,6 +1336,129 @@"how": "Maus zielen + Klick feuern · Pfeiltasten zielen · Leertaste feuern · Shift Batterie wählen · P Pause · Esc verlassen"}}+ },+ "level": {+ "hud_button": "Fortschritt",+ "open_panel": "Deinen Fortschritt öffnen",+ "level_n": "Level {0}",+ "lv": "Lv {0}",+ "xp_of": "{0} / {1} XP",+ "xp_label": "Erfahrung bis zum nächsten Level",+ "pet_xp_label": "Erfahrung von {0}",+ "agent_xp_label": "Erfahrung von {0}",+ "pet_line": "{0} · Level {1}",+ "max": "Höchstes Level erreicht",+ "level_up": "Level-up",+ "pet_up": "{0} ist aufgestiegen",+ "agent_up": "{0} hat Level {1} erreicht",+ "while_away": "Während du weg warst",+ "banner_aria": "{0} hat Level {1} erreicht. Zum Schließen klicken.",+ "title_line": "Neuer Titel: {0}",+ "unlocked": "Freigeschaltet",+ "equip_hint": "Unter Fortschritt (L) wählst du, was du trägst.",+ "equip_hint_pet": "Unter Fortschritt (L) wählst du, was dein Pet trägt.",+ "burst_you": "Level",+ "burst_pet": "Level",+ "burst_agent": "Level",+ "panel_title": "Fortschritt",+ "tab_you": "Du",+ "tab_agents": "Agenten",+ "wear": "Ausrüstung",+ "auto": "Automatisch",+ "none": "Nichts",+ "locked_at": "Ab Level {0}",+ "track": "Belohnungspfad",+ "to_next": "Noch {0} XP bis Level {1}",+ "total": "{0} XP insgesamt",+ "team": "Team-Rangliste",+ "no_agents": "Noch keine Agenten. Erstelle einen am Spawn-Punkt.",+ "pet_intro": "Dein Pet ist Jarvis. Es steigt mit jeder Antwort auf, mit jeder Aufgabe, die es an einen Agenten gibt, und mit jedem Spaziergang mit dir. Jedes Pet hat sein eigenes Level.",+ "rules_person": "So sammelst du XP",+ "rules_pet": "So sammelt dein Pet XP",+ "rules_agent": "So sammeln Agenten XP",+ "limit_daily": "einmal am Tag",+ "limit_floor": "einmal pro Etage",+ "limit_agent": "einmal pro neuem Agenten",+ "limit_cooldown": "höchstens alle {0}",+ "limit_cap": "bis zu {0} XP am Tag",+ "seconds": "{0} s",+ "minutes": "{0} Min.",+ "sound": "Level-up-Klänge",+ "free_note": "XP gibt es nur für echte Arbeit, und sie kosten nie Tokens.",+ "slot": {+ "frame": "Rahmen",+ "trail": "Spur",+ "aura": "Aura",+ "gadget": "Gadget"+ },+ "reward": {+ "frame_bronze": "Bronzerahmen",+ "frame_silver": "Silberrahmen",+ "frame_gold": "Goldrahmen",+ "frame_diamond": "Diamantrahmen",+ "trail_footprints": "Leuchtende Fußspuren",+ "trail_sparkle": "Funkelspur",+ "trail_comet": "Kometenschweif",+ "trail_neon": "Neonband",+ "trail_rainbow": "Regenbogenspur",+ "trail_stardust": "Sternenstaub",+ "aura_glow": "Warmes Leuchten",+ "aura_runes": "Runenkreis",+ "aura_storm": "Sturmring",+ "aura_legend": "Legendenkreis",+ "gadget_drone": "Helfer-Drohne",+ "gadget_halo": "Heiligenschein",+ "gadget_crown": "Krone",+ "gadget_wings": "Lichtflügel"+ },+ "title": {+ "newcomer": "Neuling",+ "apprentice": "Lehrling",+ "operator": "Operator",+ "specialist": "Spezialist",+ "strategist": "Stratege",+ "architect": "Architekt",+ "commander": "Kommandant",+ "visionary": "Visionär",+ "legend": "Legende",+ "rookie": "Frischling",+ "trainee": "Trainee",+ "associate": "Mitarbeiter",+ "professional": "Profi",+ "expert": "Experte",+ "veteran": "Veteran",+ "elite": "Elite",+ "grandmaster": "Großmeister",+ "hatchling": "Küken",+ "buddy": "Kumpel",+ "sidekick": "Sidekick",+ "partner": "Partner",+ "guardian": "Wächter",+ "champion": "Champion",+ "mythic": "Mythisch"+ },+ "source": {+ "chat_turn": "Einen Chat-Turn mit Jarvis abschließen",+ "voice_turn": "Einen Sprach-Turn mit Jarvis abschließen",+ "quest_posted": "Eine Quest ans Brett hängen",+ "quest_completed": "Eine deiner Quests wird erledigt",+ "agent_hired": "Einen neuen Agenten erstellen",+ "mission_completed": "Eine Mission wird freigegeben",+ "daily_visit": "Das Jarvis Verse besuchen",+ "floor_discovered": "Eine Etage entdecken",+ "dog_petted": "Den Bürohund streicheln",+ "dog_treat": "Dem Hund ein Leckerli geben",+ "arcade_round": "In einem Arcade-Spiel punkten",+ "arcade_record": "Deinen Arcade-Rekord brechen",+ "team_meeting": "Ein Team am Tisch versammeln",+ "task_done": "Eine Aufgabe erledigen",+ "task_blocked": "Eine Aufgabe als blockiert melden",+ "quest_done": "Eine Quest abschließen",+ "answered_teammate": "Einem Teamkollegen antworten",+ "jarvis_answered": "Jarvis antwortet dir (Chat oder Sprache)",+ "delegated": "Jarvis gibt eine Aufgabe an einen Agenten",+ "walk_together": "50 m zusammen laufen"+ }}}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json b/jarvis/ui/web/frontend/src/i18n/locales/society/en.jsonindex bdb586d559..8756f4334f 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json@@ -1336,6 +1336,129 @@"how": "Mouse aim + click fire · Arrows aim · Space fire · Shift pick battery · P pause · Esc leave"}}+ },+ "level": {+ "hud_button": "Progress",+ "open_panel": "Open your progress",+ "level_n": "Level {0}",+ "lv": "Lv {0}",+ "xp_of": "{0} / {1} XP",+ "xp_label": "Experience towards the next level",+ "pet_xp_label": "Experience of {0}",+ "agent_xp_label": "Experience of {0}",+ "pet_line": "{0} · level {1}",+ "max": "Highest level reached",+ "level_up": "Level up",+ "pet_up": "{0} levelled up",+ "agent_up": "{0} reached level {1}",+ "while_away": "While you were away",+ "banner_aria": "{0} reached level {1}. Click to close.",+ "title_line": "New title: {0}",+ "unlocked": "Unlocked",+ "equip_hint": "Choose what you wear under Progress (L).",+ "equip_hint_pet": "Choose what your pet wears under Progress (L).",+ "burst_you": "Level",+ "burst_pet": "Level",+ "burst_agent": "Level",+ "panel_title": "Progress",+ "tab_you": "You",+ "tab_agents": "Agents",+ "wear": "Wearing",+ "auto": "Automatic",+ "none": "None",+ "locked_at": "Unlocks at level {0}",+ "track": "Reward track",+ "to_next": "{0} XP to level {1}",+ "total": "{0} XP in total",+ "team": "Team ranking",+ "no_agents": "No agents yet. Create one at the spawn point.",+ "pet_intro": "Your pet is Jarvis. It levels up with every answer it gives, every task it hands to an agent and every walk you take together. Each pet keeps its own level.",+ "rules_person": "How you earn XP",+ "rules_pet": "How your pet earns XP",+ "rules_agent": "How agents earn XP",+ "limit_daily": "once a day",+ "limit_floor": "once per floor",+ "limit_agent": "once per new agent",+ "limit_cooldown": "at most every {0}",+ "limit_cap": "up to {0} XP a day",+ "seconds": "{0} s",+ "minutes": "{0} min",+ "sound": "Level-up sounds",+ "free_note": "XP only comes from real work and never costs tokens.",+ "slot": {+ "frame": "Frame",+ "trail": "Trail",+ "aura": "Aura",+ "gadget": "Gadget"+ },+ "reward": {+ "frame_bronze": "Bronze frame",+ "frame_silver": "Silver frame",+ "frame_gold": "Gold frame",+ "frame_diamond": "Diamond frame",+ "trail_footprints": "Glowing footprints",+ "trail_sparkle": "Sparkle trail",+ "trail_comet": "Comet tail",+ "trail_neon": "Neon ribbon",+ "trail_rainbow": "Rainbow trail",+ "trail_stardust": "Star dust",+ "aura_glow": "Warm glow",+ "aura_runes": "Rune circle",+ "aura_storm": "Storm ring",+ "aura_legend": "Legend circle",+ "gadget_drone": "Helper drone",+ "gadget_halo": "Halo",+ "gadget_crown": "Crown",+ "gadget_wings": "Light wings"+ },+ "title": {+ "newcomer": "Newcomer",+ "apprentice": "Apprentice",+ "operator": "Operator",+ "specialist": "Specialist",+ "strategist": "Strategist",+ "architect": "Architect",+ "commander": "Commander",+ "visionary": "Visionary",+ "legend": "Legend",+ "rookie": "Rookie",+ "trainee": "Trainee",+ "associate": "Associate",+ "professional": "Professional",+ "expert": "Expert",+ "veteran": "Veteran",+ "elite": "Elite",+ "grandmaster": "Grandmaster",+ "hatchling": "Hatchling",+ "buddy": "Buddy",+ "sidekick": "Sidekick",+ "partner": "Partner",+ "guardian": "Guardian",+ "champion": "Champion",+ "mythic": "Mythic"+ },+ "source": {+ "chat_turn": "Finish a chat turn with Jarvis",+ "voice_turn": "Finish a voice turn with Jarvis",+ "quest_posted": "Post a quest on the board",+ "quest_completed": "One of your quests gets done",+ "agent_hired": "Create a new agent",+ "mission_completed": "A mission is approved",+ "daily_visit": "Visit the Jarvis Verse",+ "floor_discovered": "Discover a floor",+ "dog_petted": "Pet the office dog",+ "dog_treat": "Give the dog a treat",+ "arcade_round": "Score in an arcade game",+ "arcade_record": "Beat your arcade record",+ "team_meeting": "Gather a team at the table",+ "task_done": "Finish a task",+ "task_blocked": "Report a task as blocked",+ "quest_done": "Complete a quest",+ "answered_teammate": "Answer a teammate",+ "jarvis_answered": "Jarvis answers you (chat or voice)",+ "delegated": "Jarvis hands a task to an agent",+ "walk_together": "Walk 50 m together"+ }}}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json b/jarvis/ui/web/frontend/src/i18n/locales/society/es.jsonindex 0b8691270a..0ac7945079 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json@@ -1336,6 +1336,129 @@"how": "Ratón apuntar + clic disparar · Flechas apuntar · Espacio disparar · Shift elegir batería · P pausa · Esc salir"}}+ },+ "level": {+ "hud_button": "Progreso",+ "open_panel": "Abrir tu progreso",+ "level_n": "Nivel {0}",+ "lv": "Nv {0}",+ "xp_of": "{0} / {1} XP",+ "xp_label": "Experiencia hasta el siguiente nivel",+ "pet_xp_label": "Experiencia de {0}",+ "agent_xp_label": "Experiencia de {0}",+ "pet_line": "{0} · nivel {1}",+ "max": "Nivel máximo alcanzado",+ "level_up": "Subida de nivel",+ "pet_up": "{0} ha subido de nivel",+ "agent_up": "{0} ha llegado al nivel {1}",+ "while_away": "Mientras no estabas",+ "banner_aria": "{0} ha llegado al nivel {1}. Haz clic para cerrar.",+ "title_line": "Nuevo título: {0}",+ "unlocked": "Desbloqueado",+ "equip_hint": "Elige lo que llevas en Progreso (L).",+ "equip_hint_pet": "Elige lo que lleva tu mascota en Progreso (L).",+ "burst_you": "Nivel",+ "burst_pet": "Nivel",+ "burst_agent": "Nivel",+ "panel_title": "Progreso",+ "tab_you": "Tú",+ "tab_agents": "Agentes",+ "wear": "Equipamiento",+ "auto": "Automático",+ "none": "Nada",+ "locked_at": "Se desbloquea en el nivel {0}",+ "track": "Camino de recompensas",+ "to_next": "{0} XP para el nivel {1}",+ "total": "{0} XP en total",+ "team": "Clasificación del equipo",+ "no_agents": "Aún no hay agentes. Crea uno en el punto de aparición.",+ "pet_intro": "Tu mascota es Jarvis. Sube de nivel con cada respuesta que da, cada tarea que pasa a un agente y cada paseo que dais juntos. Cada mascota tiene su propio nivel.",+ "rules_person": "Cómo ganas XP",+ "rules_pet": "Cómo gana XP tu mascota",+ "rules_agent": "Cómo ganan XP los agentes",+ "limit_daily": "una vez al día",+ "limit_floor": "una vez por planta",+ "limit_agent": "una vez por agente nuevo",+ "limit_cooldown": "como mucho cada {0}",+ "limit_cap": "hasta {0} XP al día",+ "seconds": "{0} s",+ "minutes": "{0} min",+ "sound": "Sonidos de subida de nivel",+ "free_note": "La XP solo llega por trabajo real y nunca cuesta tokens.",+ "slot": {+ "frame": "Marco",+ "trail": "Estela",+ "aura": "Aura",+ "gadget": "Accesorio"+ },+ "reward": {+ "frame_bronze": "Marco de bronce",+ "frame_silver": "Marco de plata",+ "frame_gold": "Marco de oro",+ "frame_diamond": "Marco de diamante",+ "trail_footprints": "Huellas brillantes",+ "trail_sparkle": "Estela de chispas",+ "trail_comet": "Cola de cometa",+ "trail_neon": "Cinta de neón",+ "trail_rainbow": "Estela arcoíris",+ "trail_stardust": "Polvo de estrellas",+ "aura_glow": "Brillo cálido",+ "aura_runes": "Círculo de runas",+ "aura_storm": "Anillo de tormenta",+ "aura_legend": "Círculo legendario",+ "gadget_drone": "Dron ayudante",+ "gadget_halo": "Aureola",+ "gadget_crown": "Corona",+ "gadget_wings": "Alas de luz"+ },+ "title": {+ "newcomer": "Recién llegado",+ "apprentice": "Aprendiz",+ "operator": "Operador",+ "specialist": "Especialista",+ "strategist": "Estratega",+ "architect": "Arquitecto",+ "commander": "Comandante",+ "visionary": "Visionario",+ "legend": "Leyenda",+ "rookie": "Novato",+ "trainee": "En prácticas",+ "associate": "Asociado",+ "professional": "Profesional",+ "expert": "Experto",+ "veteran": "Veterano",+ "elite": "Élite",+ "grandmaster": "Gran maestro",+ "hatchling": "Cría",+ "buddy": "Colega",+ "sidekick": "Compañero",+ "partner": "Socio",+ "guardian": "Guardián",+ "champion": "Campeón",+ "mythic": "Mítico"+ },+ "source": {+ "chat_turn": "Terminar un turno de chat con Jarvis",+ "voice_turn": "Terminar un turno de voz con Jarvis",+ "quest_posted": "Publicar una misión en el tablón",+ "quest_completed": "Una de tus misiones se completa",+ "agent_hired": "Crear un agente nuevo",+ "mission_completed": "Se aprueba una misión",+ "daily_visit": "Visitar el Jarvis Verse",+ "floor_discovered": "Descubrir una planta",+ "dog_petted": "Acariciar al perro de la oficina",+ "dog_treat": "Darle una golosina al perro",+ "arcade_round": "Puntuar en un juego arcade",+ "arcade_record": "Batir tu récord arcade",+ "team_meeting": "Reunir a un equipo en la mesa",+ "task_done": "Terminar una tarea",+ "task_blocked": "Informar de una tarea bloqueada",+ "quest_done": "Completar una misión",+ "answered_teammate": "Responder a un compañero",+ "jarvis_answered": "Jarvis te responde (chat o voz)",+ "delegated": "Jarvis pasa una tarea a un agente",+ "walk_together": "Caminar 50 m juntos"+ }}}}diff --git a/tests/unit/progression/test_frontend_parity.py b/tests/unit/progression/test_frontend_parity.pynew file mode 100644index 0000000000..86bfcd1de7--- /dev/null+++ b/tests/unit/progression/test_frontend_parity.py@@ -0,0 +1,54 @@+"""The Verse's copy of the level-system ids matches the Python rulebook (AP-4).++``levelCatalog.ts`` only knows what each id looks like; the server owns the+numbers. A reward, title, source or slot added on one side without the other+would render nothing or show a raw key, so the lists must be equal.+"""++from __future__ import annotations++import json+import re+from pathlib import Path++from jarvis.progression.rules import REWARDS, RULES, SLOTS, SUBJECT_KINDS, TITLES, WORLD_ACTIONS++_FRONTEND = Path(__file__).resolve().parents[3] / "jarvis/ui/web/frontend/src"+_CATALOG = _FRONTEND / "components/society/progression/levelCatalog.ts"+_LOCALES = _FRONTEND / "i18n/locales/society"+++def _ts_list(name: str) -> list[str]:+ text = _CATALOG.read_text(encoding="utf-8")+ match = re.search(rf"export const {name} = \[(.*?)\] as const;", text, re.S)+ assert match, f"{name} not found in levelCatalog.ts"+ return re.findall(r'"([a-z_]+)"', match.group(1))+++def _ts_union(name: str) -> set[str]:+ text = _CATALOG.read_text(encoding="utf-8")+ match = re.search(rf"export type {name} =(.*?);", text, re.S)+ assert match, f"{name} not found in levelCatalog.ts"+ return set(re.findall(r'"([a-z_]+)"', match.group(1)))+++def test_kinds_slots_rewards_titles_and_sources_match():+ assert _ts_list("SUBJECT_KINDS") == list(SUBJECT_KINDS)+ assert _ts_list("SLOTS") == list(SLOTS)+ assert _ts_list("REWARD_IDS") == [r.reward_id for r in REWARDS]+ assert set(_ts_list("TITLE_IDS")) == {t for bands in TITLES.values() for _, t in bands}+ assert _ts_list("XP_SOURCES") == [r.source for r in RULES]+ assert _ts_union("WorldAction") == set(WORLD_ACTIONS)+++def test_every_id_has_a_label_in_every_language():+ titles = {t for bands in TITLES.values() for _, t in bands}+ for lang in ("en", "de", "es"):+ chunk = json.loads((_LOCALES / f"{lang}.json").read_text(encoding="utf-8"))+ level = chunk["society"]["level"]+ assert set(level["reward"]) == {r.reward_id for r in REWARDS}, lang+ assert set(level["title"]) == titles, lang+ assert set(level["source"]) == {r.source for r in RULES}, lang+ assert set(level["slot"]) == set(SLOTS), lang+ for kind in SUBJECT_KINDS:+ assert f"rules_{kind}" in level, (lang, kind)