Skip to content

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.

perf(verse): avoid rebuilding the world after chat visits (#483)

Ruben Lütke32aebcb7df36
diff --git a/jarvis/ui/web/frontend/src/components/society/data.ts b/jarvis/ui/web/frontend/src/components/society/data.ts
index e5f7fbd120..dc190a90ec 100644
--- a/jarvis/ui/web/frontend/src/components/society/data.ts
+++ b/jarvis/ui/web/frontend/src/components/society/data.ts
@@ -91,7 +91,7 @@ export interface AgentStats {
lastActiveMs: number | null;
}
-/** Plain-language rules under the ceiling (agent-definition §3.4); require wins. */
+/** Permission rules under the ceiling (agent-definition §3.4); require wins. */
export interface ApprovalRules {
requireApproval: string[];
alwaysAllow: string[];
@@ -312,12 +312,13 @@ export function withLeadName(data: RosterData, assistantName: string): RosterDat
return { ...data, agents: data.agents.map((a) => (a.tier === "lead" ? { ...a, name } : a)) };
}
-export function useSocietyRoster() {
+export function useSocietyRoster(enabled = true) {
const assistantName = useEventStore((s) => s.assistantName) ?? "";
const select = useCallback((data: RosterData) => withLeadName(data, assistantName), [assistantName]);
return useQuery({
queryKey: ROSTER_QUERY_KEY,
queryFn: fetchSocietyRoster,
+ enabled,
select,
staleTime: 15_000,
// A refetch mid-ceremony would delete the figure being carried to the
diff --git a/jarvis/ui/web/frontend/src/components/society/office/CommandOffice.tsx b/jarvis/ui/web/frontend/src/components/society/office/CommandOffice.tsx
index 03fad7b7f4..0e59f73d1f 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/CommandOffice.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/CommandOffice.tsx
@@ -13,7 +13,8 @@
* Pieces are built in local space centred on the origin, front facing +z, and
* stay inside their FURNITURE_SIZE box.
*/
-import { useEffect, useMemo, useRef, useState, type RefObject } from "react";
+import { useContext, useEffect, useMemo, useRef, useState, type RefObject } from "react";
+import { CanvasActivity } from "@/hooks/useCanvasAwake";
import { Html } from "@react-three/drei";
import { useFrame, type ThreeEvent } from "@react-three/fiber";
import { CanvasTexture, CylinderGeometry, MeshBasicMaterial, MeshStandardMaterial, Quaternion, SRGBColorSpace, Vector3, type Group } from "three";
@@ -245,11 +246,13 @@ function useLiveScreen(width: number, height: number, key: string, draw: (ctx: C
/** Minutes change the clock; a timer ticks it without any network. */
function useClock(): string {
+ const active = useContext(CanvasActivity);
const [now, setNow] = useState(() => new Date());
useEffect(() => {
+ if (!active) return;
const timer = setInterval(() => setNow(new Date()), 20_000);
return () => clearInterval(timer);
- }, []);
+ }, [active]);
return now.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/MissionScreens.tsx b/jarvis/ui/web/frontend/src/components/society/office/MissionScreens.tsx
index 12731ef128..1a23a3aeeb 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/MissionScreens.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/MissionScreens.tsx
@@ -15,7 +15,8 @@
* the desk monitors use. Mounting the real IDE would attach a second xterm
* to every PTY and resize the user's live terminals to monitor size.
*/
-import { Suspense, lazy, useEffect, useMemo, useState, type CSSProperties, type ReactNode } from "react";
+import { Suspense, lazy, useContext, useEffect, useMemo, useState, type CSSProperties, type ReactNode } from "react";
+import { CanvasActivity } from "@/hooks/useCanvasAwake";
import { Html } from "@react-three/drei";
import { QueryClientProvider, useQueryClient } from "@tanstack/react-query";
import { useT } from "@/i18n";
@@ -242,9 +243,16 @@ const SECTIONS: Record<MonitorSection, () => ReactNode> = {
};
/** `section`, live, on a monitor `widthM` metres wide whose glass sits at `position`. */
-export function MissionLiveScreen({ section, widthM, position }: {
+type MissionLiveScreenProps = {
section: MonitorSection; widthM: number; position: [number, number, number];
-}) {
+};
+
+export function MissionLiveScreen(props: MissionLiveScreenProps) {
+ const active = useContext(CanvasActivity);
+ return active ? <ActiveMissionLiveScreen {...props} /> : null;
+}
+
+function ActiveMissionLiveScreen({ section, widthM, position }: MissionLiveScreenProps) {
// drei renders <Html> content in a separate React root: the app's data client
// must be handed over, or the sections' queries throw and the screen stays blank.
const client = useQueryClient();
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeBubbles.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeBubbles.tsx
index 1d931abbb7..78b18497c0 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeBubbles.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeBubbles.tsx
@@ -7,12 +7,13 @@
* camera distance. Ambient bubbles (agents nobody is talking to) hide when
* the camera is far away, so the overview never turns into a wall of text.
*/
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useMemo, useRef, useState } from "react";
import { Html } from "@react-three/drei";
import { useFrame } from "@react-three/fiber";
import { AlertTriangle, Check, LoaderCircle } from "lucide-react";
import { Vector3, type Group } from "three";
import { useT } from "@/i18n";
+import { useCanvasInterval } from "@/hooks/useCanvasInterval";
import { useEventStore } from "@/store/events";
import { memoryNoteFor, useMemoryWrites, type MemoryWrite } from "@/store/memoryWrites";
import type { SocietyAgent } from "../data";
@@ -92,11 +93,7 @@ function useErrandBubble(agent: SocietyAgent): Bubble | null {
/** Re-renders once a second while `active`, so a settled bubble can expire. */
function useClock(active: boolean): number {
const [now, setNow] = useState(() => Date.now());
- useEffect(() => {
- if (!active) return;
- const id = window.setInterval(() => setNow(Date.now()), 1000);
- return () => window.clearInterval(id);
- }, [active]);
+ useCanvasInterval(() => setNow(Date.now()), 1000, active);
return now;
}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeCameraRig.lifecycle.test.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeCameraRig.lifecycle.test.tsx
new file mode 100644
index 0000000000..7b54a240eb
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeCameraRig.lifecycle.test.tsx
@@ -0,0 +1,75 @@
+import { useEffect, useImperativeHandle } from "react";
+import { act, cleanup, render } from "@testing-library/react";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { PerspectiveCamera, Vector3 } from "three";
+import { CanvasActivity } from "@/hooks/useCanvasAwake";
+import { OfficeCameraRig } from "./OfficeCameraRig";
+import { buildOfficeLayout } from "./officeLayout";
+import { officeSession, useOfficeStore } from "./officeStore";
+
+const state = vi.hoisted(() => ({
+ frames: new Set<(_state: unknown, dt: number) => void>(),
+ renderer: null as unknown as { camera: PerspectiveCamera; size: { width: number; height: number }; gl: { domElement: HTMLCanvasElement }; scene: object; events: { connected: undefined } },
+ controls: null as unknown as { target: Vector3; enabled: boolean; update: () => void; mouseButtons: { LEFT: number } },
+}));
+
+vi.mock("@react-three/fiber", () => ({
+ useThree: (select: (value: typeof state.renderer) => unknown) => select(state.renderer),
+ useFrame: (frame: (_state: unknown, dt: number) => void) => {
+ useEffect(() => { state.frames.add(frame); return () => { state.frames.delete(frame); }; }, [frame]);
+ },
+}));
+vi.mock("@react-three/drei", async () => {
+ const { forwardRef } = await import("react");
+ return {
+ OrbitControls: forwardRef(({ enabled }: { enabled: boolean }, ref) => {
+ state.controls.enabled = enabled;
+ useImperativeHandle(ref, () => state.controls);
+ return null;
+ }),
+ };
+});
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ state.renderer = {
+ camera: new PerspectiveCamera(35, 1.6, 0.2, 800), size: { width: 1280, height: 800 },
+ gl: { domElement: document.createElement("canvas") }, scene: {}, events: { connected: undefined },
+ };
+ state.controls = { target: new Vector3(), enabled: true, update: () => undefined, mouseButtons: { LEFT: 0 } };
+ officeSession.camera = null;
+ useOfficeStore.setState({ zoom: null, focus: null, follow: true });
+});
+
+afterEach(() => {
+ cleanup();
+ state.frames.clear();
+ vi.useRealTimers();
+});
+
+it.each([2, 14])("returns from a hidden monitor dive after %i frames without replaying it", (frames) => {
+ const layout = buildOfficeLayout([]);
+ const tree = (active: boolean) => <CanvasActivity.Provider value={active}><OfficeCameraRig layout={layout} overview={0} /></CanvasActivity.Provider>;
+ const view = render(tree(true));
+ const initialPosition = state.renderer.camera.position.toArray();
+ const initialTarget = state.controls.target.toArray();
+ act(() => {
+ useOfficeStore.getState().zoomInto([4, 1, 7], 0);
+ for (let i = 0; i < frames; i += 1) for (const step of state.frames) step(null, 0.1);
+ });
+ expect(state.renderer.camera.position.toArray()).not.toEqual(initialPosition);
+ expect(state.controls.enabled).toBe(false);
+
+ view.rerender(tree(false));
+ expect(state.renderer.camera.position.toArray()).toEqual(initialPosition);
+ expect(state.controls.target.toArray()).toEqual(initialTarget);
+ expect(vi.getTimerCount()).toBe(0);
+ act(() => vi.advanceTimersByTime(3_000));
+ expect(state.controls.enabled).toBe(false);
+
+ view.rerender(tree(true));
+ act(() => { for (const step of state.frames) step(null, 0.1); });
+ expect(state.renderer.camera.position.toArray()).toEqual(initialPosition);
+ expect(state.controls.target.toArray()).toEqual(initialTarget);
+ expect(state.controls.enabled).toBe(true);
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeCameraRig.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeCameraRig.tsx
index 9f38863026..3240c87fed 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeCameraRig.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeCameraRig.tsx
@@ -10,7 +10,8 @@
* A press that turned the camera never ends in a click, and the wheel zooms
* by how far it turned (see officeCamera.ts).
*/
-import { useEffect, useRef } from "react";
+import { useContext, useEffect, useRef } from "react";
+import { CanvasActivity } from "@/hooks/useCanvasAwake";
import { OrbitControls } from "@react-three/drei";
import { useFrame, useThree } from "@react-three/fiber";
import { MOUSE, Vector3, type PerspectiveCamera } from "three";
@@ -42,6 +43,9 @@ export function screenFillDistance(fovDeg: number, aspect: number, width = SCREE
}
export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; overview: number }) {
+ const active = useContext(CanvasActivity);
+ const activeRef = useRef(active);
+ activeRef.current = active;
const controls = useRef<OrbitControlsImpl>(null);
const camera = useThree((s) => s.camera);
const size = useThree((s) => s.size);
@@ -74,7 +78,7 @@ export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; ov
else viewport?.removeAttribute("data-first-person");
};
useEffect(() => () => {
- cameraView.firstPerson = false;
+ if (activeRef.current) cameraView.firstPerson = false;
gl.domElement.closest(".office-viewport")?.removeAttribute("data-first-person");
}, [gl]);
@@ -99,7 +103,41 @@ export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; ov
// Remember the view when leaving: the pose before a dive, never the inside of a monitor,
// and the view before sitting down, never the character's eyes.
const preDive = useRef<{ position: [number, number, number]; target: [number, number, number] } | null>(null);
+ useEffect(() => {
+ const store = useOfficeStore.getState();
+ lastZoom.current = store.zoom?.seq ?? 0;
+ lastFocus.current = store.focus?.seq ?? 0;
+ if (active) return;
+ clearTimeout(backOff.current);
+ dive.current = null;
+ flight.current = null;
+ const c = controls.current;
+ const beforeSeat = seated.current.before;
+ const saved = beforeSeat
+ ? { position: beforeSeat.position.toArray() as [number, number, number], target: beforeSeat.target.toArray() as [number, number, number] }
+ : preDive.current;
+ if (saved) {
+ camera.position.set(...saved.position);
+ c?.target.set(...saved.target);
+ }
+ if (beforeSeat) {
+ (camera as PerspectiveCamera).fov = beforeSeat.fov;
+ (camera as PerspectiveCamera).updateProjectionMatrix();
+ }
+ seated.current = { blend: 0, before: null };
+ preDive.current = null;
+ if (c) {
+ c.enabled = false;
+ c.update();
+ officeSession.camera = { position: camera.position.toArray() as [number, number, number], target: c.target.toArray() as [number, number, number] };
+ }
+ officeSession.follow = store.follow;
+ shownFirstPerson.current = false;
+ gl.domElement.closest(".office-viewport")?.removeAttribute("data-first-person");
+ }, [active, camera, gl]);
useEffect(() => () => {
+ // An inactive retained rig already saved its pose; another visible office may own the session now.
+ if (!activeRef.current) return;
const c = controls.current;
const beforeSeat = seated.current.before;
officeSession.camera = beforeSeat
@@ -114,6 +152,7 @@ export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; ov
// Start where the last visit left off, or close to the character.
useEffect(() => {
+ if (!active) return;
if (import.meta.env.DEV) (window as unknown as Record<string, unknown>).__office = { camera, controls: controls.current, gl, scene };
const saved = officeSession.camera;
if (saved) {
@@ -130,11 +169,11 @@ export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; ov
controls.current?.target.copy(target);
controls.current?.update();
useOfficeStore.getState().setFollow(true);
- }, [camera, gl, scene, layout.spawn]);
+ }, [camera, gl, scene, layout.spawn, active]);
// "Overview": frame the whole floor and stop following.
useEffect(() => {
- if (overview === 0) return;
+ if (!active || overview === 0) return;
// Seated in first person the glide would keep the camera in the chair: stand up first.
if (seated.current.blend > 0 || (layout.command && useLeadSeat.getState().seated === layout.command.id)) leaveFirstPerson();
const home = cameraHome(layout.bounds, size.width / Math.max(1, size.height));
@@ -156,6 +195,7 @@ export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; ov
// floating label skipped it and kept the last Shift press's "pan", so a
// plain drag slid the view while the follow dragged it back.
useEffect(() => {
+ if (!active) return;
const el = connected ?? gl.domElement;
const down = (event: PointerEvent) => {
const c = controls.current;
@@ -165,7 +205,7 @@ export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; ov
};
el.addEventListener("pointerdown", down, true);
return () => el.removeEventListener("pointerdown", down, true);
- }, [connected, gl]);
+ }, [connected, gl, active]);
// A drag turns the camera and nothing else. R3F still delivers a click when
// the press ends on the object it started on, so a small turn over the
@@ -174,6 +214,7 @@ export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; ov
// swallowed here, in the capture phase, before R3F or a label sees it.
// The wheel zooms by how far it turned, not a fixed step per event.
useEffect(() => {
+ if (!active) return;
const el = connected ?? gl.domElement;
let origin: { x: number; y: number } | null = null;
let dragged = false;
@@ -208,10 +249,11 @@ export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; ov
el.removeEventListener("click", click, true);
el.removeEventListener("wheel", wheel, true);
};
- }, [connected, gl]);
+ }, [connected, gl, active]);
// The near plane follows the zoom, or coplanar layers (oak over slab) fight in bands when zoomed out.
useFrame(() => {
+ if (!active) return;
const c = controls.current;
const lens = camera as PerspectiveCamera;
if (!c || !lens.isPerspectiveCamera) return;
@@ -222,6 +264,7 @@ export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; ov
});
useFrame((_, rawDt) => {
+ if (!active) return;
const c = controls.current;
if (!c) return;
// Publish the view for the minimap: where the camera stands and which way it looks.
@@ -334,7 +377,7 @@ export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; ov
});
return (
- <OrbitControls ref={controls} makeDefault enableDamping dampingFactor={0.12} screenSpacePanning={false}
+ <OrbitControls ref={controls} makeDefault enabled={active} enableDamping dampingFactor={0.12} screenSpacePanning={false}
minPolarAngle={CAMERA_LIMITS.minPolar} maxPolarAngle={CAMERA_LIMITS.maxPolar}
minDistance={CAMERA_LIMITS.minDistance} maxDistance={CAMERA_LIMITS.maxDistance} />
);
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsx
index fd9fd0a18b..f85e2944ba 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficePlayer.tsx
@@ -170,6 +170,7 @@ export function OfficePlayer({ layout, grid, look, name, awake, reduced }: {
// 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.
useEffect(() => {
+ if (!awake) return;
player.path = []; player.moving = false;
if (officeSession.playerPlaced && isWalkable(grid, player)) return;
const start = (officeSession.playerPlaced ? nearestWalkable(grid, player) : null)
@@ -177,7 +178,7 @@ export function OfficePlayer({ layout, grid, look, name, awake, reduced }: {
player.x = start.x; player.z = start.z;
if (!officeSession.playerPlaced) player.heading = Math.PI;
officeSession.playerPlaced = true;
- }, [grid, layout.spawn]);
+ }, [grid, layout.spawn, awake]);
useFrame((_, rawDt) => {
const dt = Math.min(rawDt, 0.1);
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx
index 27dabb08d0..e2f465df16 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeScene.tsx
@@ -59,8 +59,9 @@ const PLAYER_OWNER = { current: playerBody };
* before the player controller checks its spot; it repeats for every rebuilt
* plan until the floor's roster has loaded, then the arrival is done.
*/
-function FloorArrival({ floor, layout, grid, ready }: { floor: OfficeFloor; layout: OfficeLayout; grid: NavGrid; ready: boolean }) {
+function FloorArrival({ floor, layout, grid, ready, awake }: { floor: OfficeFloor; layout: OfficeLayout; grid: NavGrid; ready: boolean; awake: boolean }) {
useLayoutEffect(() => {
+ if (!awake) return;
const arrival = officeSession.arrival;
if (!arrival || arrival.floor !== floor) return;
const pose = arrivalPose(layout, arrival.at, officeSession.floors[floor]);
@@ -69,7 +70,7 @@ function FloorArrival({ floor, layout, grid, ready }: { floor: OfficeFloor; layo
playerBody.path = []; playerBody.moving = false;
officeSession.playerPlaced = true;
if (ready) officeSession.arrival = null;
- }, [floor, layout, grid, ready]);
+ }, [floor, layout, grid, ready, awake]);
return null;
}
@@ -122,7 +123,7 @@ function SharedFloorParts({ floor, layout, grid, ready, awake, reduced, player,
<ElevatorCallButton shaft={shaft} floor={floor} lit={elevatorCall.lit} animate={awake && !reduced}
near={atLift} hint={atLift && !elevatorCall.picking} onPress={elevatorCall.onPress} />
)}
- <FloorArrival floor={floor} layout={layout} grid={grid} ready={ready} />
+ <FloorArrival floor={floor} layout={layout} grid={grid} ready={ready} awake={awake} />
<OfficePlayer layout={layout} grid={grid} look={player.look} name={player.name} awake={awake} reduced={reduced} />
<PlayerBubble height={OFFICE_FIGURE_HEIGHT_M + 0.49} />
</>
@@ -225,7 +226,7 @@ function OfficeFloorDressing({ floor, occupants, layout, agents, newcomers, awak
: <LiveMonitors desks={desks} agents={agents} chats={chats} onOpen={onOpenScreen} />}
{layout.furniture.map((item) => <FurniturePiece key={item.id} item={item} />)}
{table && <MeetingChairs table={table} />}
- {board && <TeamBoardFace board={board} enabled={floor === "agents"} />}
+ {board && <TeamBoardFace board={board} enabled={awake && floor === "agents"} />}
{teamRoom && table && <TeamRoomFittings room={teamRoom} table={table} />}
{breakRoom && <BreakLoungeFittings room={breakRoom} furniture={layout.furniture} />}
{wardrobeRug && <WardrobeFittings rug={wardrobeRug} />}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.lifecycle.test.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.lifecycle.test.tsx
new file mode 100644
index 0000000000..51597ad61f
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.lifecycle.test.tsx
@@ -0,0 +1,132 @@
+import { useContext, useEffect, type ReactNode } from "react";
+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+import { CanvasActivity } from "@/hooks/useCanvasAwake";
+import { useOfficeStore } from "./officeStore";
+import { useProgression } from "../progression/progressionStore";
+import { OfficeStage } from "./OfficeStage";
+
+const state = vi.hoisted(() => ({
+ canvasMounts: 0, canvasUnmounts: 0, visits: 0, maps: 0,
+ roster: { data: { agents: [], sample: false } },
+ coding: { occupants: [], byAgentId: new Map(), loaded: true },
+ rosterEnabled: vi.fn(), codingEnabled: vi.fn(), chatsEnabled: vi.fn(),
+ client: { invalidateQueries: vi.fn(async () => undefined) },
+}));
+
+vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));
+vi.mock("@tanstack/react-query", () => ({ useQueryClient: () => state.client }));
+vi.mock("framer-motion", () => ({ useReducedMotion: () => false }));
+vi.mock("@/hooks/useWebglSurface", () => ({ useWebglSurface: () => ({ generation: 0 }) }));
+vi.mock("@/lib/graphDimension", () => ({ useWebglSupported: () => true }));
+vi.mock("@/hooks/usePets", () => ({ useActivePet: () => null }));
+vi.mock("../companion/companionPetStore", () => ({ useSyncCompanionPet: () => undefined }));
+vi.mock("../data", () => ({
+ useSocietyRoster: (enabled: boolean) => { state.rosterEnabled(enabled); return state.roster; },
+ useQuickCreateAgent: () => async () => undefined,
+}));
+vi.mock("./codingFloor", () => ({
+ useCodingFloorOccupants: (enabled: boolean) => { state.codingEnabled(enabled); return state.coding; },
+}));
+vi.mock("./useDeskChats", () => ({
+ useDeskChats: (_sessions: unknown, enabled: boolean) => { state.chatsEnabled(enabled); return new Map(); },
+}));
+vi.mock("./useDprBudget", () => ({ useDprBudget: () => 1 }));
+vi.mock("@react-three/fiber", () => ({
+ advance: () => undefined,
+ Canvas: ({ children, frameloop }: { children: ReactNode; frameloop: string }) => {
+ const active = useContext(CanvasActivity);
+ useEffect(() => {
+ state.canvasMounts += 1;
+ return () => { state.canvasUnmounts += 1; };
+ }, []);
+ return <div data-testid="canvas" data-loop={frameloop} data-active={active}>{children}</div>;
+ },
+}));
+vi.mock("./OfficeScene", () => ({ OfficeScene: ({ awake }: { awake: boolean }) => <div data-testid="scene" data-awake={awake} /> }));
+vi.mock("./OfficeCameraRig", () => ({ ZOOM_SECONDS: 1 }));
+vi.mock("./OfficeFrameDriver", () => ({ OfficeFrameDriver: () => null }));
+vi.mock("./OfficePlayer", () => ({ ownsKeyboard: () => false }));
+vi.mock("./OfficePanels", () => ({ AgentPanel: () => null, CheckpointPanel: () => null }));
+vi.mock("./PaneCommandPanel", () => ({ PaneCommandPanel: () => null }));
+vi.mock("./ArcadeCabinet", () => ({ ArcadeCabinet: () => null }));
+vi.mock("./ElevatorPanel", () => ({ ElevatorPanel: () => null }));
+vi.mock("./ElevatorDoors", () => ({ ElevatorDoors: () => null }));
+vi.mock("./OfficeCompass", () => ({ OfficeCompass: () => null }));
+vi.mock("./OfficeMinimap", () => ({ OfficeMinimap: () => {
+ useEffect(() => { state.maps += 1; return () => { state.maps -= 1; }; }, []);
+ return null;
+} }));
+vi.mock("../progression/useProgressionSync", () => ({ useProgressionSync: () => {
+ useEffect(() => { state.visits += 1; return () => { state.visits -= 1; }; }, []);
+} }));
+vi.mock("../progression/LevelHud", () => ({ LevelHud: () => null, LevelToasts: () => null }));
+vi.mock("../progression/LevelUpBanner", () => ({ LevelUpBanner: () => null }));
+vi.mock("../progression/hall/LevelHallScreen", () => ({ LevelHallScreen: () => null }));
+
+afterEach(() => {
+ cleanup();
+ useOfficeStore.getState().select(null);
+ useProgression.getState().openPanel(null);
+ vi.useRealTimers();
+ vi.clearAllMocks();
+ state.canvasMounts = 0;
+ state.canvasUnmounts = 0;
+});
+
+it("retains one canvas across chat visits while stopping input, visits, HUD and polling", () => {
+ vi.useFakeTimers();
+ const view = render(<OfficeStage />);
+ const canvas = screen.getByTestId("canvas");
+ expect(canvas.dataset.loop).toBe("always");
+ expect(state.canvasMounts).toBe(1);
+ expect(state.visits).toBe(1);
+ expect(state.maps).toBe(1);
+ fireEvent.keyDown(window, { code: "KeyH" });
+ expect(useOfficeStore.getState().selection).toEqual({ kind: "checkpoint", id: "create" });
+
+ view.rerender(<OfficeStage active={false} />);
+ expect(screen.getByTestId("canvas")).toBe(canvas);
+ expect(canvas.dataset.loop).toBe("never");
+ expect(canvas.dataset.active).toBe("false");
+ expect(screen.getByTestId("scene").dataset.awake).toBe("false");
+ expect(state.visits).toBe(0);
+ expect(state.maps).toBe(0);
+ expect(state.rosterEnabled).toHaveBeenLastCalledWith(false);
+ expect(state.codingEnabled).toHaveBeenLastCalledWith(false);
+ expect(state.chatsEnabled).toHaveBeenLastCalledWith(false);
+ expect(useOfficeStore.getState().selection).toBeNull();
+ for (const code of ["KeyH", "KeyL", "KeyM"]) {
+ const event = new KeyboardEvent("keydown", { code, bubbles: true, cancelable: true });
+ window.dispatchEvent(event);
+ expect(event.defaultPrevented).toBe(false);
+ }
+ expect(useOfficeStore.getState().selection).toBeNull();
+ expect(useProgression.getState().panel).toBeNull();
+ act(() => vi.advanceTimersByTime(30_000));
+ expect(state.client.invalidateQueries).not.toHaveBeenCalled();
+
+ view.rerender(<OfficeStage />);
+ expect(screen.getByTestId("canvas")).toBe(canvas);
+ expect(canvas.dataset.loop).toBe("always");
+ expect(state.canvasMounts).toBe(1);
+ expect(state.canvasUnmounts).toBe(0);
+ expect(state.visits).toBe(1);
+ expect(state.maps).toBe(1);
+ expect(state.rosterEnabled).toHaveBeenLastCalledWith(true);
+ act(() => vi.advanceTimersByTime(7_000));
+ expect(state.client.invalidateQueries).toHaveBeenCalledOnce();
+ view.unmount();
+ expect(state.canvasUnmounts).toBe(1);
+ expect(state.visits).toBe(0);
+ expect(state.maps).toBe(0);
+});
+
+it("releases the coding poll while a visited coding floor is hidden", () => {
+ const view = render(<OfficeStage initialFloor="coding" />);
+ expect(state.codingEnabled).toHaveBeenLastCalledWith(true);
+ view.rerender(<OfficeStage initialFloor="coding" active={false} />);
+ expect(state.codingEnabled).toHaveBeenLastCalledWith(false);
+ view.rerender(<OfficeStage initialFloor="coding" />);
+ expect(state.codingEnabled).toHaveBeenLastCalledWith(true);
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx
index 4102c97c80..94a666707c 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/OfficeStage.tsx
@@ -13,7 +13,7 @@ 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";
+import { CanvasActivity, useCanvasAwake } from "@/hooks/useCanvasAwake";
import { useWebglSurface } from "@/hooks/useWebglSurface";
import { useWebglSupported } from "@/lib/graphDimension";
import { useT } from "@/i18n";
@@ -100,6 +100,14 @@ export interface OfficeStageProps {
initialFloor?: OfficeFloor;
/** A narrow host (the IDE side panel): smaller HUD, no minimap or compass. */
compact?: boolean;
+ /** A visited map keeps its renderer while its host shows chat. */
+ active?: boolean;
+}
+
+/** Visit-only subscriptions and sounds end when the retained world is hidden. */
+function OfficeVisit({ floor }: { floor: OfficeFloor }) {
+ useProgressionSync(true, floor);
+ return null;
}
function useRosterRefresh(awake: boolean) {
@@ -135,10 +143,13 @@ function useNewcomers(active: SocietyAgent[], floor: OfficeFloor): ReadonlySet<s
}
const EMPTY_IDS: ReadonlySet<string> = new Set();
-export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenGroup, initialFloor, compact = false }: OfficeStageProps) {
+export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenGroup, initialFloor, compact = false, active: onScreen = true }: OfficeStageProps) {
const t = useT();
const hostRef = useRef<HTMLDivElement>(null);
- const awake = useCanvasAwake(hostRef);
+ const visible = useCanvasAwake(hostRef);
+ const awake = onScreen && visible;
+ const onScreenRef = useRef(onScreen);
+ onScreenRef.current = onScreen;
const reduced = useReducedMotion() ?? false;
const { generation } = useWebglSurface(hostRef);
const webgl = useWebglSupported();
@@ -148,13 +159,12 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
const coding = floor === "coding";
// The arcade floor has no agents: no roster, desks or chats, just the cabinets.
const arcade = floor === "arcade";
- const roster = useSocietyRoster();
+ const roster = useSocietyRoster(awake);
useRosterRefresh(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);
@@ -165,7 +175,7 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
// The call button tells how many are upstairs, so standing at the elevator wakes the coding roster too.
const atLift = nearby?.kind === "checkpoint" && nearby.id === "elevator";
- const codingFloor = useCodingFloorOccupants(coding || atLift);
+ const codingFloor = useCodingFloorOccupants(awake && (coding || atLift));
const jarvisAgents = useMemo(() => (roster.data?.agents ?? []).filter((a) => a.lifecycle !== "archived"), [roster.data]);
const codingAgents = useMemo(() => codingFloor.occupants.map((o) => o.agent), [codingFloor.occupants]);
const active = useMemo(() => (arcade ? [] : coding ? codingAgents : jarvisAgents), [arcade, coding, codingAgents, jarvisAgents]);
@@ -232,6 +242,7 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
useEffect(() => {
if (!sectionDive || sectionDive.seq === lastSectionDive.current) return;
lastSectionDive.current = sectionDive.seq;
+ if (!awake) return;
const { section } = sectionDive;
const go = () => {
if (section === "agents" && !compact && onOpenLedger) onOpenLedger();
@@ -241,7 +252,7 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
if (reduced) { go(); return; }
setDiving(true);
openTimer.current = setTimeout(() => { go(); setDiving(false); }, ZOOM_SECONDS * 1000 + 260);
- }, [sectionDive, compact, onOpenLedger, reduced]);
+ }, [sectionDive, compact, onOpenLedger, reduced, awake]);
// The elevator: pressing its call button, standing at the doors, opens the
// button panel; pressing a floor there closes the elevator doors over the
@@ -279,10 +290,10 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
}, [ride, reduced]);
// E at the elevator, or a click on its floor token, presses the call button instead of opening a panel.
useEffect(() => {
- if (selection?.kind !== "checkpoint" || selection.id !== "elevator") return;
+ if (!awake || selection?.kind !== "checkpoint" || selection.id !== "elevator") return;
select(null);
pressCall();
- }, [selection, select, pressCall]);
+ }, [selection, select, pressCall, awake]);
useEffect(() => {
if (ride?.phase === "closed" && floor === ride.to && ready) {
// The doors stay shut a short beat at least, so the change reads as a ride and not a cut.
@@ -328,6 +339,7 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
// Escape closes an open panel before it can leave the map.
useEffect(() => {
+ if (!awake) return;
const onKey = (event: KeyboardEvent) => {
// A field or a dialog (e.g. the create dialog opened from reception) owns its own Escape.
if (event.key !== "Escape" || !useOfficeStore.getState().selection || ownsKeyboard(event.target)) return;
@@ -337,7 +349,7 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
};
document.addEventListener("keydown", onKey, true);
return () => document.removeEventListener("keydown", onKey, true);
- }, [select]);
+ }, [select, awake]);
// H (or the HUD button) opens reception on the controls guide from anywhere, and closes it again.
const toggleGuide = useCallback(() => {
@@ -347,6 +359,7 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
select({ kind: "checkpoint", id: "create" });
}, [select]);
useEffect(() => {
+ if (!awake) return;
const onKey = (event: KeyboardEvent) => {
if (event.code !== "KeyH" || event.repeat || event.ctrlKey || event.metaKey || event.altKey || ownsKeyboard(event.target)) return;
if (useOfficeStore.getState().selection?.kind === "arcade") return;
@@ -355,17 +368,18 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
- }, [toggleGuide]);
+ }, [toggleGuide, awake]);
// The Level Hall's two checkpoints open its screen: the stage on the studio, the guide on the overview.
useEffect(() => {
- if (selection?.kind !== "checkpoint" || (selection.id !== "studio" && selection.id !== "levels")) return;
+ if (!awake || selection?.kind !== "checkpoint" || (selection.id !== "studio" && selection.id !== "levels")) return;
useProgression.getState().openPanel(selection.id === "studio" ? "studio" : "overview");
select(null);
- }, [selection, select]);
+ }, [selection, select, awake]);
// L (or the level card) opens the Level Hall screen, and closes it again.
useEffect(() => {
+ if (!awake) return;
const onKey = (event: KeyboardEvent) => {
if (event.code !== "KeyL" || event.repeat || event.ctrlKey || event.metaKey || event.altKey) return;
const levels = useProgression.getState();
@@ -376,22 +390,39 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
- }, []);
+ }, [awake]);
// The Level Hall screen closes with the map.
- useEffect(() => () => useProgression.getState().openPanel(null), []);
+ useEffect(() => () => { if (onScreenRef.current) useProgression.getState().openPanel(null); }, []);
// Leaving the map forgets panels and calls; the office opens fresh next time.
useEffect(() => () => {
+ if (!onScreenRef.current) return;
const store = useOfficeStore.getState();
store.select(null);
store.setNearby(null);
store.clearSummons();
}, []);
+ useEffect(() => {
+ if (onScreen) return;
+ // A mode change ends input and pending navigation without discarding GPU resources.
+ clearTimeout(openTimer.current);
+ clearTimeout(rideTimer.current);
+ setDiving(false);
+ setPicking(false);
+ setRide(null);
+ setMapOpen(false);
+ useProgression.getState().openPanel(null);
+ const store = useOfficeStore.getState();
+ store.select(null);
+ store.setNearby(null);
+ store.clearSummons();
+ }, [onScreen]);
+
// A panel for an agent that left the roster closes itself.
useEffect(() => {
- if (selection?.kind === "agent" && ready && !agents.has(selection.id)) select(null);
- }, [selection, agents, ready, select]);
+ if (awake && selection?.kind === "agent" && ready && !agents.has(selection.id)) select(null);
+ }, [selection, agents, ready, select, awake]);
const selectedAgent = selection?.kind === "agent" ? agents.get(selection.id) ?? null : null;
const selectedPane = selectedAgent ? occupants.get(selectedAgent.agentId) ?? null : null;
@@ -422,8 +453,9 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
const dpr = useDprBudget(hostRef);
return (
+ <CanvasActivity.Provider value={awake}>
<section className={compact ? "office-stage office-stage-compact" : "office-stage"} aria-label={t(titleKey)}
- data-office-agents={active.length} data-office-floor={floor}>
+ data-office-agents={active.length} data-office-floor={floor} data-office-awake={awake}>
<div ref={hostRef} className="office-viewport" tabIndex={0} role="application" aria-label={t("society.office.viewport")}>
{webgl ? (
<RenderBoundary key={generation} fallbackText={t("society.office.no_graphics")}>
@@ -443,6 +475,8 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
) : <div className="office-fallback" role="status">{t("society.office.no_graphics")}</div>}
</div>
+ {awake && <>
+ <OfficeVisit floor={floor} />
<div className="office-hud office-hud-left" data-office-ui>
<div className="office-card office-title">
<strong>{t(titleKey)}</strong>
@@ -520,7 +554,9 @@ export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpen
<LevelToasts names={agentNames} agents={jarvisAgents} />
<LevelHallScreen agents={jarvisAgents} playerName={playerName} petName={petName} playerLook={playerToyLook} />
<LevelUpBanner playerName={playerName} petName={petName} />
+ </>}
</section>
+ </CanvasActivity.Provider>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/society/office/RealChatScreen.tsx b/jarvis/ui/web/frontend/src/components/society/office/RealChatScreen.tsx
index 8b35697624..01d87ecbcd 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/RealChatScreen.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/RealChatScreen.tsx
@@ -5,7 +5,8 @@
* touches the chat the rest of the app has open. Display only: clicks go to
* the monitor underneath, which dives into the chat view.
*/
-import { Suspense, lazy, useEffect, useMemo } from "react";
+import { Suspense, lazy, useContext, useEffect, useMemo } from "react";
+import { CanvasActivity } from "@/hooks/useCanvasAwake";
import { Html } from "@react-three/drei";
import { QueryClientProvider, useQueryClient } from "@tanstack/react-query";
import { createAgentChatStore } from "@/store/agentChat";
@@ -21,9 +22,16 @@ const SCREEN_W_M = 0.66;
const SCREEN_Z_RANGE: [number, number] = [10, 0];
const DISTANCE_FACTOR = (SCREEN_W_M * 400) / REAL_CHAT_PX.w;
-export function RealChatScreen({ agent, roster, position }: {
+type RealChatScreenProps = {
agent: SocietyAgent; roster: SocietyAgent[]; position: [number, number, number];
-}) {
+};
+
+export function RealChatScreen(props: RealChatScreenProps) {
+ const active = useContext(CanvasActivity);
+ return active ? <ActiveRealChatScreen {...props} /> : null;
+}
+
+function ActiveRealChatScreen({ agent, roster, position }: RealChatScreenProps) {
// drei renders <Html> content in a separate React root: the app's data client
// must be handed over, or the chat panel's queries throw and the screen stays blank.
const client = useQueryClient();
diff --git a/jarvis/ui/web/frontend/src/components/society/office/ServerRoom.tsx b/jarvis/ui/web/frontend/src/components/society/office/ServerRoom.tsx
index 48018d642f..6e76d76257 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/ServerRoom.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/ServerRoom.tsx
@@ -16,7 +16,9 @@
* Pieces are built in local space centred on the origin, front facing +z, and
* stay inside their FURNITURE_SIZE box.
*/
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useContext, useEffect, useMemo, useRef, useState } from "react";
+import { CanvasActivity } from "@/hooks/useCanvasAwake";
+import { useCanvasInterval } from "@/hooks/useCanvasInterval";
import { useFrame } from "@react-three/fiber";
import {
CanvasTexture, Color, CylinderGeometry, InstancedMesh, MeshBasicMaterial, MeshStandardMaterial, Object3D,
@@ -614,10 +616,7 @@ function useClusterData(): ClusterData {
/** A counter that ticks on a slow timer; the screens redraw on it, never per frame. */
function useTicker(ms: number): number {
const [tick, setTick] = useState(0);
- useEffect(() => {
- const timer = setInterval(() => setTick((t) => t + 1), ms);
- return () => clearInterval(timer);
- }, [ms]);
+ useCanvasInterval(() => setTick((t) => t + 1), ms);
return tick;
}
@@ -908,7 +907,8 @@ const IDE_SPEND_FILTERS: CostFilters = { ...EMPTY_FILTERS, surfaces: ["agentic-i
/** A floor-standing status display: the Agentic IDE's spend for the whole room. A click dives into it and opens Spend. */
export function StatusWall() {
- const summary = useCostSummary(IDE_SPEND_FILTERS);
+ const active = useContext(CanvasActivity);
+ const summary = useCostSummary(IDE_SPEND_FILTERS, active);
const spend = ideSpendFrom(summary.data, IDE_SPEND_FILTERS.days);
// The clock in the corner moves once a minute; the numbers when the summary answers.
const tick = useTicker(30_000);
diff --git a/jarvis/ui/web/frontend/src/components/society/office/TerminalMonitors.tsx b/jarvis/ui/web/frontend/src/components/society/office/TerminalMonitors.tsx
index a2bccd884b..b31ffd71dd 100644
--- a/jarvis/ui/web/frontend/src/components/society/office/TerminalMonitors.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/office/TerminalMonitors.tsx
@@ -10,6 +10,7 @@ import { useFrame, type ThreeEvent } from "@react-three/fiber";
import { CanvasTexture, SRGBColorSpace } from "three";
import { useT } from "@/i18n";
import { useThemeValue } from "@/hooks/useTheme";
+import { useCanvasInterval } from "@/hooks/useCanvasInterval";
import type { PaneScreen } from "@/lib/paneScreensApi";
import { usePaneTitle } from "@/store/paneRecaps";
import { storedTerminalAppearance } from "@/components/agentic/terminalThemes";
@@ -132,10 +133,7 @@ export function TerminalMonitors({ desks, occupants, awake, onOpen }: {
const appearance = storedTerminalAppearance() ?? appTheme;
const palette = useMemo(() => monitorPalette(appearance), [appearance]);
const [nowMs, setNowMs] = useState(() => Date.now());
- useEffect(() => {
- const timer = setInterval(() => setNowMs(Date.now()), META_TICK_MS);
- return () => clearInterval(timer);
- }, []);
+ useCanvasInterval(() => setNowMs(Date.now()), META_TICK_MS, awake);
return (
<group>
{desks.map((desk) => {
diff --git a/jarvis/ui/web/frontend/src/hooks/useCanvasInterval.test.tsx b/jarvis/ui/web/frontend/src/hooks/useCanvasInterval.test.tsx
new file mode 100644
index 0000000000..09e81d6545
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useCanvasInterval.test.tsx
@@ -0,0 +1,65 @@
+import { StrictMode } from "react";
+import { act, cleanup, render } from "@testing-library/react";
+import { afterEach, beforeEach, expect, test, vi } from "vitest";
+import { CanvasActivity } from "./useCanvasAwake";
+import { useCanvasInterval } from "./useCanvasInterval";
+
+function Clock({ onTick, enabled = true }: { onTick: () => void; enabled?: boolean }) {
+ useCanvasInterval(onTick, 1000, enabled);
+ return null;
+}
+
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => { cleanup(); vi.useRealTimers(); });
+
+test("retained clocks stop while hidden and resume without replaying missed ticks", () => {
+ const ticks: number[] = [];
+ const onTick = () => ticks.push(Date.now());
+ const tree = (active: boolean) => <CanvasActivity.Provider value={active}><Clock onTick={onTick} /></CanvasActivity.Provider>;
+ const view = render(tree(true));
+ act(() => vi.advanceTimersByTime(1000));
+ expect(ticks).toHaveLength(1);
+
+ view.rerender(tree(false));
+ expect(vi.getTimerCount()).toBe(0);
+ act(() => vi.advanceTimersByTime(60_000));
+ expect(ticks).toHaveLength(1);
+
+ view.rerender(tree(true));
+ expect(ticks).toHaveLength(1);
+ act(() => vi.advanceTimersByTime(999));
+ expect(ticks).toHaveLength(1);
+ act(() => vi.advanceTimersByTime(1));
+ expect(ticks).toHaveLength(2);
+ view.unmount();
+ expect(vi.getTimerCount()).toBe(0);
+});
+
+test("a hidden initial mount and a locally disabled clock never schedule work", () => {
+ const ticks: number[] = [];
+ const tree = (active: boolean, enabled: boolean) => <CanvasActivity.Provider value={active}>
+ <Clock enabled={enabled} onTick={() => ticks.push(1)} />
+ </CanvasActivity.Provider>;
+ const view = render(tree(false, true));
+ expect(vi.getTimerCount()).toBe(0);
+ view.rerender(tree(true, false));
+ expect(vi.getTimerCount()).toBe(0);
+ act(() => vi.advanceTimersByTime(5000));
+ expect(ticks).toEqual([]);
+ view.rerender(tree(true, true));
+ act(() => vi.advanceTimersByTime(1000));
+ expect(ticks).toEqual([1]);
+});
+
+test("rerenders use the latest callback without restarting the cadence or duplicating StrictMode timers", () => {
+ const ticks: string[] = [];
+ const tree = (label: string) => <StrictMode><Clock onTick={() => ticks.push(label)} /></StrictMode>;
+ const view = render(tree("old"));
+ expect(vi.getTimerCount()).toBe(1);
+ act(() => vi.advanceTimersByTime(600));
+ view.rerender(tree("new"));
+ act(() => vi.advanceTimersByTime(400));
+ expect(ticks).toEqual(["new"]);
+ view.unmount();
+ expect(vi.getTimerCount()).toBe(0);
+});
diff --git a/jarvis/ui/web/frontend/src/hooks/useCanvasInterval.ts b/jarvis/ui/web/frontend/src/hooks/useCanvasInterval.ts
new file mode 100644
index 0000000000..921e11fd06
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useCanvasInterval.ts
@@ -0,0 +1,14 @@
+import { useContext, useEffect, useRef } from "react";
+import { CanvasActivity } from "./useCanvasAwake";
+
+/** Wall-clock updates sleep with a retained canvas and resume at their normal cadence. */
+export function useCanvasInterval(callback: () => void, milliseconds: number, enabled = true): void {
+ const active = useContext(CanvasActivity);
+ const latest = useRef(callback);
+ latest.current = callback;
+ useEffect(() => {
+ if (!active || !enabled) return;
+ const timer = window.setInterval(() => latest.current(), milliseconds);
+ return () => window.clearInterval(timer);
+ }, [active, enabled, milliseconds]);
+}
diff --git a/jarvis/ui/web/frontend/src/hooks/useCosts.activity.test.tsx b/jarvis/ui/web/frontend/src/hooks/useCosts.activity.test.tsx
new file mode 100644
index 0000000000..0ed2686d5f
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useCosts.activity.test.tsx
@@ -0,0 +1,40 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, cleanup, render, waitFor } from "@testing-library/react";
+import { afterEach, expect, test, vi } from "vitest";
+import { EMPTY_FILTERS, useCostSummary } from "./useCosts";
+
+afterEach(() => { cleanup(); vi.unstubAllGlobals(); vi.useRealTimers(); });
+
+test("a retained spend monitor sleeps without removing cached results or polling", async () => {
+ const requests: string[] = [];
+ vi.stubGlobal("fetch", async (url: string) => {
+ requests.push(url);
+ return new Response(JSON.stringify({ total_cost: 12 }), { headers: { "Content-Type": "application/json" } });
+ });
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: Infinity } } });
+ function Monitor({ active }: { active: boolean }) {
+ const summary = useCostSummary(EMPTY_FILTERS, active);
+ return <span>{summary.data ? "cached" : "empty"}</span>;
+ }
+ const tree = (active: boolean) => <QueryClientProvider client={client}><Monitor active={active} /></QueryClientProvider>;
+ vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] });
+ const view = render(tree(false));
+ expect(requests).toEqual([]);
+ view.rerender(tree(true));
+ await waitFor(() => expect(view.getByText("cached")).toBeTruthy());
+ expect(requests).toHaveLength(1);
+
+ view.rerender(tree(false));
+ await act(async () => {
+ await client.invalidateQueries({ queryKey: ["costs", "summary"] });
+ vi.advanceTimersByTime(240_000);
+ });
+ expect(requests).toHaveLength(1);
+ expect(view.getByText("cached")).toBeTruthy();
+
+ vi.useRealTimers();
+ view.rerender(tree(true));
+ await waitFor(() => expect(requests).toHaveLength(2));
+ view.unmount();
+ client.clear();
+});
diff --git a/jarvis/ui/web/frontend/src/hooks/useCosts.ts b/jarvis/ui/web/frontend/src/hooks/useCosts.ts
index c8f35c6616..dfafd947c2 100644
--- a/jarvis/ui/web/frontend/src/hooks/useCosts.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useCosts.ts
@@ -326,9 +326,10 @@ export function costDailyQueryOptions(filters: CostFilters) {
};
}
-export function useCostSummary(filters: CostFilters) {
+export function useCostSummary(filters: CostFilters, enabled = true) {
return useQuery({
...costSummaryQueryOptions(filters),
+ enabled,
// Spend only moves when a turn finishes, and this is the most expensive
// read in the app. At thirty seconds a slow answer was still in flight
// when the next poll fired, so the section spent its whole life queueing
diff --git a/jarvis/ui/web/frontend/src/views/JarvisAgentsView.test.tsx b/jarvis/ui/web/frontend/src/views/JarvisAgentsView.test.tsx
index 79b76cf8f2..1b47fd9ccd 100644
--- a/jarvis/ui/web/frontend/src/views/JarvisAgentsView.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/JarvisAgentsView.test.tsx
@@ -5,7 +5,7 @@ import { JarvisAgentsView } from "./JarvisAgentsView";
vi.mock("@/i18n", () => ({ useLocaleChunk: () => true }));
vi.mock("@/components/society/world/WorldStage", () => ({ WorldStage: () => { throw new Error("Legacy world must not mount"); } }));
vi.mock("@/components/society/mars/MarsWorldStage", () => ({ MarsWorldStage: () => { throw new Error("Mars must not mount as the map"); } }));
-vi.mock("@/components/society/office/OfficeStage", () => ({ OfficeStage: ({ onOpenLedger, onSelectAgent }: any) => <div data-testid="office-map"><button onClick={onOpenLedger}>Open agents</button><button onClick={() => onSelectAgent("a1")}>Agent a1</button></div> }));
+vi.mock("@/components/society/office/OfficeStage", () => ({ OfficeStage: ({ active, onOpenLedger, onSelectAgent }: any) => <div data-testid="office-map" data-active={active}><button onClick={onOpenLedger}>Open agents</button><button onClick={() => onSelectAgent("a1")}>Agent a1</button></div> }));
const initialUrl = window.location.href;
afterEach(() => { cleanup(); window.history.replaceState(null, "", initialUrl); });
@@ -25,3 +25,12 @@ it("forwards an agent picked in the office", async () => {
fireEvent.click(await screen.findByText("Agent a1"));
expect(onSelect).toHaveBeenCalledWith("a1");
});
+
+it("forwards visibility without replacing the office", () => {
+ const view = render(<JarvisAgentsView onOpenAgents={() => undefined} />);
+ const office = screen.getByTestId("office-map");
+ expect(office.dataset.active).toBe("true");
+ view.rerender(<JarvisAgentsView active={false} onOpenAgents={() => undefined} />);
+ expect(screen.getByTestId("office-map")).toBe(office);
+ expect(office.dataset.active).toBe("false");
+});
diff --git a/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx b/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx
index c4ef6ec669..494970e1cf 100644
--- a/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx
@@ -1,9 +1,7 @@
/** Lazy map surface; the parent keeps the existing Agents workspace mounted. */
-import { Suspense, lazy } from "react";
import { useLocaleChunk } from "@/i18n";
import type { PlaceId } from "@/components/society/world/islandLayout";
-
-const OfficeStage = lazy(() => import("@/components/society/office/OfficeStage").then((m) => ({ default: m.OfficeStage })));
+import { OfficeStage } from "@/components/society/office/OfficeStage";
export interface JarvisAgentsViewProps {
onSelectAgent?: (agentId: string | null) => void;
@@ -11,16 +9,15 @@ export interface JarvisAgentsViewProps {
onOpenAgents: () => void;
onCreateAgent?: () => void;
onOpenGroup?: (groupId: string) => void;
+ active?: boolean;
}
-export function JarvisAgentsView({ onSelectAgent, onOpenAgents, onCreateAgent, onOpenGroup }: JarvisAgentsViewProps) {
+export function JarvisAgentsView({ onSelectAgent, onOpenAgents, onCreateAgent, onOpenGroup, active = true }: JarvisAgentsViewProps) {
const ready = useLocaleChunk("society");
if (!ready) return null;
return (
<div className="h-full min-h-0">
- <Suspense fallback={<div className="h-full w-full animate-pulse bg-secondary" aria-hidden />}>
- <OfficeStage onOpenLedger={onOpenAgents} onSelectAgent={onSelectAgent} onCreateAgent={onCreateAgent} onOpenGroup={onOpenGroup} />
- </Suspense>
+ <OfficeStage active={active} onOpenLedger={onOpenAgents} onSelectAgent={onSelectAgent} onCreateAgent={onCreateAgent} onOpenGroup={onOpenGroup} />
</div>
);
}
diff --git a/jarvis/ui/web/frontend/src/views/society/SocietyView.deferred.test.tsx b/jarvis/ui/web/frontend/src/views/society/SocietyView.deferred.test.tsx
index 8d20ca77ab..5e64037848 100644
--- a/jarvis/ui/web/frontend/src/views/society/SocietyView.deferred.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/society/SocietyView.deferred.test.tsx
@@ -47,7 +47,12 @@ it("never evaluates closed dialog modules; creates agents without a dialog", asy
expect(screen.getByLabelText("Existing chat draft")).toBe(draft);
expect((draft as HTMLInputElement).value).toBe("Keep this draft");
- fireEvent.click(screen.getByRole("tab", { name: "society.world.mode_map" }));
+ const worldTab = screen.getByRole("tab", { name: "society.world.mode_map" });
+ fireEvent.pointerEnter(worldTab);
+ await waitFor(() => expect(loaded.world).toBe(1));
+ expect(screen.queryByTestId("society-world-surface")).toBeNull();
+ expect(screen.queryByRole("button", { name: "Open foundry" })).toBeNull();
+ fireEvent.click(worldTab);
fireEvent.click(await screen.findByRole("button", { name: "Open foundry" }));
expect(await screen.findByRole("dialog", { name: "Building" })).toBeTruthy();
expect(screen.getByText("foundry")).toBeTruthy();
diff --git a/jarvis/ui/web/frontend/src/views/society/SocietyView.test.tsx b/jarvis/ui/web/frontend/src/views/society/SocietyView.test.tsx
index ed2dbc3eb2..7e2363d505 100644
--- a/jarvis/ui/web/frontend/src/views/society/SocietyView.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/society/SocietyView.test.tsx
@@ -26,8 +26,8 @@ vi.mock("@/components/society/data", () => ({ useQuickCreateAgent: () => quick.c
{ agentId: "lead", name: "Lead", tier: "lead", state: "idle" },
{ agentId: "specialist", name: "Specialist", tier: "specialist", state: "idle" },
] }, isLoading: false }) }));
-vi.mock("@/views/JarvisAgentsView", () => ({ JarvisAgentsView: ({ onSelectAgent, onOpenAgents, onMarsSelectionChange }: any) => (
- <div data-testid="map"><button onClick={() => onSelectAgent("specialist")}>Map specialist</button><button onClick={onOpenAgents}>Map fallback</button><div data-mars-ui><input aria-label="Mars draft" /></div><div data-mars-mode="player"><button>Player viewport</button></div><div data-mars-mode="follow"><button>Follow viewport</button></div><button onClick={() => onMarsSelectionChange(false)}>Previous world</button><button onClick={() => onMarsSelectionChange(true)}>Mars world</button></div>
+vi.mock("@/views/JarvisAgentsView", () => ({ JarvisAgentsView: ({ active, onSelectAgent, onOpenAgents, onMarsSelectionChange }: any) => (
+ <div data-testid="map" data-active={active}><button onClick={() => onSelectAgent("specialist")}>Map specialist</button><button onClick={onOpenAgents}>Map fallback</button><div data-mars-ui><input aria-label="Mars draft" /></div><div data-mars-mode="player"><button>Player viewport</button></div><div data-mars-mode="follow"><button>Follow viewport</button></div><button onClick={() => onMarsSelectionChange(false)}>Previous world</button><button onClick={() => onMarsSelectionChange(true)}>Mars world</button></div>
) }));
vi.mock("@/components/society/mars/MarsStationPanel", () => ({ MarsStationPanel: ({ onClose }: any) => <aside aria-label="Mars station"><button onClick={onClose}>Close station</button></aside> }));
vi.mock("@/components/society/card/AgentCardOverlay", () => ({ AgentCardOverlay: ({ agent, embedded, onSelectAgent, onSelectGroup, onCreate, railHeader }: any) => (
@@ -69,12 +69,19 @@ it("switches to Map and back without losing the selected agent or draft", async
const draft = screen.getByLabelText("Draft") as HTMLInputElement;
fireEvent.change(draft, { target: { value: "Unsent message" } });
fireEvent.click(screen.getByRole("tab", { name: "society.world.mode_map" }));
- expect(await screen.findByTestId("map")).toBeTruthy();
+ const map = await screen.findByTestId("map");
+ expect(map.dataset.active).toBe("true");
fireEvent.click(screen.getByRole("tab", { name: "society.roster.title" }));
- expect(screen.queryByTestId("map")).toBeNull();
+ expect(screen.getByTestId("society-world-surface").getAttribute("aria-hidden")).toBe("true");
expect(screen.getByText("Specialist")).toBeTruthy();
expect(screen.getByLabelText("Draft")).toBe(draft);
expect(draft.value).toBe("Unsent message");
+ expect(screen.getByTestId("map")).toBe(map);
+ expect(map.dataset.active).toBe("false");
+ fireEvent.click(screen.getByRole("tab", { name: "society.world.mode_map" }));
+ expect(screen.getByTestId("map")).toBe(map);
+ expect(map.dataset.active).toBe("true");
+ expect(screen.getByTestId("society-world-surface").getAttribute("aria-hidden")).toBe("false");
});
it("restores the most recently selected agent after the view is remounted", () => {
@@ -92,7 +99,7 @@ it("opens map selections in Agents and keeps creation available", async () => {
render(<SocietyView />);
fireEvent.click(screen.getByRole("tab", { name: "society.world.mode_map" }));
fireEvent.click(await screen.findByText("Map specialist"));
- expect(screen.queryByTestId("map")).toBeNull();
+ expect(screen.getByTestId("society-world-surface").getAttribute("aria-hidden")).toBe("true");
expect(screen.getByText("Specialist")).toBeTruthy();
fireEvent.click(screen.getByText("Create agent"));
await waitFor(() => expect(quick.create).toHaveBeenCalledTimes(1));
@@ -129,7 +136,7 @@ it("keeps the Map/Agents switch in the caption in both modes", async () => {
expect(screen.getByTestId("mode-switch")).toBeTruthy();
expect(screen.queryByRole("button", { name: "settings_hub.back_to_app" })).toBeNull();
fireEvent.click(screen.getByRole("tab", { name: "society.roster.title" }));
- expect(screen.queryByTestId("map")).toBeNull();
+ expect(screen.getByTestId("society-world-surface").getAttribute("aria-hidden")).toBe("true");
expect(screen.getByTestId("mode-switch")).toBeTruthy();
expect(screen.queryByRole("button", { name: "settings_hub.back_to_app" })).toBeNull();
});
@@ -148,7 +155,7 @@ it("leaves Map on Escape without requesting native fullscreen in a browser", asy
await screen.findByTestId("map");
expect(setMapFullscreen).not.toHaveBeenCalledWith(true);
fireEvent.keyDown(document, { key: "Escape" });
- expect(screen.queryByTestId("map")).toBeNull();
+ expect(screen.getByTestId("society-world-surface").getAttribute("aria-hidden")).toBe("true");
});
it("shows no station shortcut in Agents mode", () => {
@@ -166,7 +173,7 @@ it("does not discard a Mars form when Escape belongs to its input", async () =>
expect(screen.getByTestId("map")).toBeTruthy();
expect((field as HTMLInputElement).value).toBe("Unsent station draft");
fireEvent.keyDown(document, { key: "Escape" });
- expect(screen.queryByTestId("map")).toBeNull();
+ expect(screen.getByTestId("society-world-surface").getAttribute("aria-hidden")).toBe("true");
});
it.each(["Mars draft", "Player viewport", "Follow viewport"])("preserves focused %s when the browser exits fullscreen without a keydown", async (target) => {
@@ -182,7 +189,7 @@ it.each(["Mars draft", "Player viewport", "Follow viewport"])("preserves focused
expect(screen.getByLabelText("Mars draft")).toBe(field);
expect((field as HTMLInputElement).value).toBe("Unsent station draft");
fireEvent.click(screen.getByRole("tab", { name: "society.roster.title" }));
- expect(screen.queryByTestId("map")).toBeNull();
+ expect(screen.getByTestId("society-world-surface").getAttribute("aria-hidden")).toBe("true");
});
it("still leaves the ordinary map when browser fullscreen exits", async () => {
@@ -190,7 +197,7 @@ it("still leaves the ordinary map when browser fullscreen exits", async () => {
fireEvent.click(screen.getByRole("tab", { name: "society.world.mode_map" }));
await screen.findByTestId("map");
fireEvent(document, new Event("fullscreenchange"));
- expect(screen.queryByTestId("map")).toBeNull();
+ expect(screen.getByTestId("society-world-surface").getAttribute("aria-hidden")).toBe("true");
});
diff --git a/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx b/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx
index 15c87e45bb..997705c06d 100644
--- a/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx
+++ b/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx
@@ -32,9 +32,9 @@ const MODES = [
{ value: "agents", labelKey: "society.roster.title", Icon: Users },
] as const;
-const JarvisAgentsBoard = lazy(() =>
- import("@/views/JarvisAgentsView").then((m) => ({ default: m.JarvisAgentsView })),
-);
+const loadWorld = () => import("@/views/JarvisAgentsView").then((m) => ({ default: m.JarvisAgentsView }));
+const JarvisAgentsBoard = lazy(loadWorld);
+const preloadWorld = () => { void loadWorld().catch((error) => console.debug("World preload unavailable", error)); };
// Do not evaluate either dialog's 3D dependencies until someone opens it.
const loadBuildingDialog = () => import("@/components/society/card/BuildingCardOverlay")
@@ -51,6 +51,7 @@ export function SocietyView() {
const t = useT();
useLocaleChunk("society");
const [mode, setMode] = useState<"agents" | "world">("agents");
+ const [worldVisited, setWorldVisited] = useState(false);
const roster = useSocietyRoster();
const agents = useMemo(() => roster.data?.agents ?? [], [roster.data]);
const sample = roster.data?.sample ?? true;
@@ -120,6 +121,7 @@ export function SocietyView() {
const [fullscreenError, setFullscreenError] = useState(false);
const switchMode = useCallback((next: "agents" | "world") => {
+ if (next === "world") setWorldVisited(true);
setMode(next);
setFullscreenError(false);
if (inDesktopShell()) void setMapFullscreen(next === "world").catch(() => setFullscreenError(true));
@@ -190,6 +192,8 @@ export function SocietyView() {
return <button key={value} type="button" role="tab" aria-selected={mode === value}
aria-label={label} title={label} data-testid={`society-mode-${value}`}
onClick={() => switchMode(value)}
+ onPointerEnter={value === "world" ? preloadWorld : undefined}
+ onFocus={value === "world" ? preloadWorld : undefined}
style={{ width: CAPTION_SEGMENT_PX }}
className={cn(CAPTION_SEGMENT, mode === value ? CAPTION_SEGMENT_ON : CAPTION_SEGMENT_OFF)}>
<Icon aria-hidden className={CAPTION_ICON_CLASS} strokeWidth={CAPTION_ICON_STROKE} />
@@ -214,12 +218,13 @@ export function SocietyView() {
{fullscreenError && <p role="alert" className="bg-card px-4 py-2 text-sm text-destructive">{t("society.world.fullscreen_failed")}</p>}
{groupError && <p role="alert" className="bg-card px-4 py-2 text-sm text-destructive">{groupError}</p>}
{createError && <p role="alert" className="bg-card px-4 py-2 text-sm text-destructive">{createError}</p>}
- {mode === "world" ? (
- <div className="relative flex min-h-0 flex-1">
+ {worldVisited ? (
+ <div className={mode === "world" ? "relative flex min-h-0 flex-1" : "hidden"} data-testid="society-world-surface" aria-hidden={mode !== "world"}>
<div className="min-w-0 flex-1">
- <CanvasActivity.Provider value={!openPlace}>
- <Suspense fallback={null}>
+ <CanvasActivity.Provider value={mode === "world" && !openPlace}>
+ <Suspense fallback={<div className="flex h-full items-center justify-center text-sm text-muted-foreground" role="status">{t("society.office.loading")}</div>}>
<JarvisAgentsBoard onSelectAgent={onIslandSelect} onSelectPlace={onIslandPlace} onOpenAgents={() => switchMode("agents")}
+ active={mode === "world"}
onCreateAgent={createAgent} onOpenGroup={(groupId) => { selectGroup(groupId); switchMode("agents"); }} />
</Suspense>
</CanvasActivity.Provider>