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.

feat(agents): add compact centered map switch and fullscreen workspace

rubenluetke10-beep0fe60050a3a0
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index b61cb3c784..432b51f15f 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -4454,6 +4454,12 @@ class DesktopApp:
"""
return f"{WINDOW_TITLE} — {DETACHABLE_VIEWS[view]}"
+ def set_fullscreen(self, enabled: bool) -> dict[str, Any]:
+ """Set the main window's fullscreen state without blocking the API loop."""
+ from jarvis.ui.window_fullscreen import set_window_fullscreen
+
+ return set_window_fullscreen(self._window, enabled)
+
def _window_background(self) -> str:
"""The theme-correct frame color, same derivation as the main window."""
from jarvis.ui.theme import window_background
diff --git a/jarvis/ui/web/desktop_routes.py b/jarvis/ui/web/desktop_routes.py
index 6cc000e7b1..8578809203 100644
--- a/jarvis/ui/web/desktop_routes.py
+++ b/jarvis/ui/web/desktop_routes.py
@@ -118,3 +118,21 @@ async def window_reattach(body: DetachBody, request: Request) -> dict[str, Any]:
except Exception as exc: # noqa: BLE001
log.warning("window reattach failed: %s: %s", type(exc).__name__, exc)
return {"ok": False, "reason": f"{type(exc).__name__}: {exc}"}
+
+
+class FullscreenBody(BaseModel):
+ enabled: bool
+
+
[email protected]("/fullscreen", operation_id="fullscreen")
+async def window_fullscreen(body: FullscreenBody, request: Request) -> dict[str, Any]:
+ """Enter or leave native desktop fullscreen."""
+ desktop = getattr(request.app.state, "desktop_app", None)
+ setter = getattr(desktop, "set_fullscreen", None)
+ if not callable(setter):
+ return {"ok": False, "reason": "no_desktop_shell"}
+ try:
+ return await asyncio.to_thread(setter, body.enabled)
+ except Exception:
+ log.exception("Could not change desktop fullscreen")
+ return {"ok": False, "reason": "fullscreen_failed"}
diff --git a/jarvis/ui/web/frontend/src/App.tsx b/jarvis/ui/web/frontend/src/App.tsx
index e04dffe00e..2747f802a9 100644
--- a/jarvis/ui/web/frontend/src/App.tsx
+++ b/jarvis/ui/web/frontend/src/App.tsx
@@ -1,3 +1,4 @@
+import { useSocietyShell } from "@/store/societyShell";
import { Suspense, lazy, useCallback, useEffect, useState } from "react";
import { isSectionId, useEventStore } from "@/store/events";
@@ -272,6 +273,9 @@ export default function App() {
);
const activeSection = useEventStore((s) => s.activeSection);
+ const agentsNavOpen = useSocietyShell((s) => s.navigationOpen);
+ const toggleAgentsNav = useSocietyShell((s) => s.toggleNavigation);
+ const hideNavigation = activeSection === "agents" && !agentsNavOpen;
const solo = useEventStore((s) => s.solo);
const detachedViews = useEventStore((s) => s.detachedViews);
@@ -328,10 +332,11 @@ export default function App() {
{brokerMounted && <SubscriptionRealtimeTransportBroker />}
<DesktopWallpaper />
+ {!hideNavigation && <>
<Sidebar
width={sidebar.size}
- collapsed={navCollapsed}
- onToggleCollapsed={toggleNav}
+ collapsed={activeSection === "agents" ? false : navCollapsed}
+ onToggleCollapsed={activeSection === "agents" ? toggleAgentsNav : toggleNav}
/>
<PaneResizer
@@ -342,6 +347,7 @@ export default function App() {
active={sidebar.isResizing}
title="Drag to resize the sidebar — double-click to reset"
/>
+ </>}
{/*
The stage column carries NO z-index, and must not get one back.
diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentCardOverlay.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentCardOverlay.tsx
index f9a198e7a0..64f67b8642 100644
--- a/jarvis/ui/web/frontend/src/components/society/card/AgentCardOverlay.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentCardOverlay.tsx
@@ -1,6 +1,6 @@
/**
* The agent card is a chat workspace: agent selection, conversation and actions.
- * The identity header is informational; there is no separate profile view.
+ * The workspace can be embedded in the section or opened as a modal.
* Radix Dialog provides focus containment and Escape-to-close.
*/
import * as Dialog from "@radix-ui/react-dialog";
@@ -25,9 +25,11 @@ export interface AgentCardOverlayProps {
sample?: boolean;
/** A row in the rail was clicked: the card swaps to that agent. */
onSelectAgent?: (agentId: string) => void;
- /** "+" in the rail. The creator wants the island, so the card closes first. */
+ /** "+" in the rail opens the existing creator. */
onCreate?: () => void;
onClose: () => void;
+ /** Render as the section workspace instead of a modal. */
+ embedded?: boolean;
}
export function AgentCardOverlay({
@@ -38,61 +40,69 @@ export function AgentCardOverlay({
onSelectAgent,
onCreate,
onClose,
+ embedded = false,
}: AgentCardOverlayProps) {
const t = useT();
useLocaleChunk("society");
+ const Title = embedded ? "h2" : Dialog.Title;
+ const Description = embedded ? "p" : Dialog.Description;
+ const content = (
+ <>
+ {agent ? (
+ <>
+ <header className="flex shrink-0 items-center gap-3 border-b border-border px-5 py-3">
+ <div data-testid="agent-card-identity" className="flex min-w-0 flex-1 items-center gap-3">
+ <AgentSwatch agent={agent} size={40} />
+ <div className="min-w-0 flex-1">
+ <Title className="truncate font-display text-base font-semibold tracking-tight text-foreground">
+ {agent.name}
+ </Title>
+ <Description className="truncate text-xs text-muted-foreground">
+ {agent.title}
+ </Description>
+ </div>
+ </div>
+ <Badge variant="outline">{t(`society.state.${agent.state}`)}</Badge>
+ {!embedded && (
+ <button type="button" onClick={onClose} aria-label={t("society.card.close")}
+ className="rounded-md p-1.5 text-muted-foreground hover:bg-secondary hover:text-foreground">
+ <X className="h-4 w-4" aria-hidden />
+ </button>
+ )}
+ </header>
+ <div className="grid min-h-0 flex-1 grid-cols-[minmax(220px,1fr)_minmax(0,5fr)_minmax(300px,320px)]">
+ <RosterRail
+ agents={roster}
+ loading={rosterLoading}
+ sample={sample}
+ activeAgentId={agent.agentId}
+ onOpen={(id) => { if (id !== agent.agentId) onSelectAgent?.(id); }}
+ onCreate={() => onCreate?.()}
+ side="left"
+ className="w-full"
+ />
+ <section
+ className="flex min-h-0 flex-col"
+ aria-label={t("society.card.chat")}
+ data-testid="agent-card-chat"
+ >
+ <AgentChatPanel key={agent.agentId} agent={agent} roster={roster} />
+ </section>
+ <OptionsRail agent={agent} onRetired={onClose} sample={sample} />
+ </div>
+ </>
+ ) : null}
+ </>
+ );
+ if (embedded) {
+ return <div data-testid="agent-card" className="flex min-h-0 flex-1 flex-col overflow-hidden bg-card">{content}</div>;
+ }
return (
<Dialog.Root open={agent !== null} onOpenChange={(next) => (next ? undefined : onClose())}>
<Dialog.Portal>
- <Dialog.Overlay className="fixed inset-0 z-40 bg-scrim/60 backdrop-blur-sm data-[state=open]:animate-in data-[state=open]:fade-in-0 motion-reduce:animate-none" />
- <Dialog.Content
- data-testid="agent-card"
- className="fixed inset-0 z-50 flex flex-col overflow-hidden bg-card focus:outline-none data-[state=open]:animate-in data-[state=open]:fade-in-0 motion-reduce:animate-none"
- >
- {agent ? (
- <>
- <header className="flex shrink-0 items-center gap-3 border-b border-border px-5 py-3">
- <div data-testid="agent-card-identity" className="flex min-w-0 flex-1 items-center gap-3">
- <AgentSwatch agent={agent} size={40} />
- <div className="min-w-0 flex-1">
- <Dialog.Title className="truncate font-display text-base font-semibold tracking-tight text-foreground">
- {agent.name}
- </Dialog.Title>
- <Dialog.Description className="truncate text-xs text-muted-foreground">
- {agent.title}
- </Dialog.Description>
- </div>
- </div>
- <Badge variant="outline">{t(`society.state.${agent.state}`)}</Badge>
- <Dialog.Close
- aria-label={t("society.card.close")}
- className="rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-strong"
- >
- <X className="h-4 w-4" aria-hidden />
- </Dialog.Close>
- </header>
- <div className="grid min-h-0 flex-1 grid-cols-[minmax(220px,1fr)_minmax(0,5fr)_minmax(300px,320px)]">
- <RosterRail
- agents={roster}
- loading={rosterLoading}
- sample={sample}
- activeAgentId={agent.agentId}
- onOpen={(id) => { if (id !== agent.agentId) onSelectAgent?.(id); }}
- onCreate={() => onCreate?.()}
- side="left"
- className="w-full"
- />
- <section
- className="flex min-h-0 flex-col"
- aria-label={t("society.card.chat")}
- data-testid="agent-card-chat"
- >
- <AgentChatPanel key={agent.agentId} agent={agent} roster={roster} />
- </section>
- <OptionsRail agent={agent} onRetired={onClose} sample={sample} />
- </div>
- </>
- ) : null}
+ <Dialog.Overlay className="fixed inset-0 z-40 bg-scrim/60 backdrop-blur-sm" />
+ <Dialog.Content data-testid="agent-card" className="fixed inset-0 z-50 flex flex-col overflow-hidden bg-card focus:outline-none">
+ {content}
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
diff --git a/jarvis/ui/web/frontend/src/components/society/world/WorldStage.tsx b/jarvis/ui/web/frontend/src/components/society/world/WorldStage.tsx
index c75a2d3c17..1a7302272e 100644
--- a/jarvis/ui/web/frontend/src/components/society/world/WorldStage.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/world/WorldStage.tsx
@@ -9,7 +9,7 @@
* IntersectionObserver (`useCanvasAwake`) — never `document.hidden`;
* - `prefers-reduced-motion` freezes the island (demand-driven frames, no
* wander, no water drift, no clouds) instead of animating it;
- * - no WebGL at all → an honest fallback that points to the ledger.
+ * - no WebGL at all → an honest fallback that points to the Agents workspace.
*
* Everything inside the canvas wears the world's own branding (§4.3); the
* switch the section hands in for the top-right corner is app chrome.
@@ -65,10 +65,10 @@ import { SKY } from "./worldPalette";
import { useWorldSettings } from "./worldSettings";
export interface WorldStageProps {
- /** App-chrome content for the HUD's top-right corner (the World / Ledger switch). */
+ /** App-chrome content for the HUD's top-right corner (the Map / Agents switch). */
topRight?: ReactNode;
/** Where the fallback sends someone whose window cannot draw 3D. */
- onOpenLedger: () => void;
+ onOpenAgents: () => void;
/** A figure was clicked (or the selection cleared). The model card hooks in here. */
onSelectAgent?: (agentId: string | null) => void;
/**
@@ -84,7 +84,7 @@ const CAMERA_START = cameraOffset();
/** Zoom step the island snaps to when it shows a newborn leaving the foundry. */
const SPAWN_ZOOM = 1;
-export function WorldStage({ topRight, onOpenLedger, onSelectAgent, onSelectPlace }: WorldStageProps) {
+export function WorldStage({ topRight, onOpenAgents, onSelectAgent, onSelectPlace }: WorldStageProps) {
const t = useT();
const ready = useLocaleChunk("society");
const hostRef = useRef<HTMLDivElement>(null);
@@ -140,13 +140,13 @@ export function WorldStage({ topRight, onOpenLedger, onSelectAgent, onSelectPlac
<h3 className="font-display text-base font-semibold text-foreground">
{t("society.world.webgl_missing_title")}
</h3>
- <p className="text-sm text-muted-foreground">{t("society.world.webgl_missing_body")}</p>
+ <p className="text-sm text-muted-foreground">{t("society.world.webgl_agents_body")}</p>
<button
type="button"
- onClick={onOpenLedger}
+ onClick={onOpenAgents}
className="inline-flex h-8 items-center rounded-md bg-secondary px-3 text-sm font-medium text-foreground hover:bg-muted"
>
- {t("society.world.open_ledger")}
+ {t("society.world.open_agents")}
</button>
</div>
</div>
@@ -163,7 +163,7 @@ export function WorldStage({ topRight, onOpenLedger, onSelectAgent, onSelectPlac
data-grain={grain > 0 ? grain : undefined}
tabIndex={0}
role="application"
- aria-label={ready ? t("society.world.mode_world") : undefined}
+ aria-label={ready ? t("society.world.mode_map") : undefined}
>
<Canvas
key={generation}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
index e491f02983..e278deb505 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
@@ -63,7 +63,9 @@
"room_reason_user": "von dir beendet",
"room_reason_kill_switch": "die Society wurde gestoppt",
"mode_label": "Agenten-Ansicht",
- "mode_world": "Welt",
+ "toggle_sections": "Sektionen ein- oder ausblenden",
+ "fullscreen_failed": "Vollbild konnte nicht geändert werden. Die Buttons Map / Agents bleiben verfügbar.",
+ "mode_map": "Map",
"mode_ledger": "Ledger",
"hud_agents": "{count} Agenten",
"hud_active": "{count} aktiv",
@@ -84,8 +86,8 @@
"view_reset": "Zurück zur Standardansicht (R)",
"minimap_label": "Inselkarte – klicken, um dorthin zu springen",
"webgl_missing_title": "Die Insel braucht WebGL",
- "webgl_missing_body": "Dieses Fenster kann gerade kein 3D zeichnen. Das Ledger zeigt dieselben Agenten.",
- "open_ledger": "Ledger öffnen",
+ "webgl_agents_body": "Dieses Fenster kann gerade kein 3D zeichnen. Die Agents-Ansicht bleibt verfügbar.",
+ "open_agents": "Agents öffnen",
"loading": "Die Insel wird gebaut…",
"place_plugins": "Plugin-Docks",
"place_foundry": "Agent-Foundry",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
index 516d9ab0e5..87ab773c07 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
@@ -63,7 +63,9 @@
"room_reason_user": "closed by you",
"room_reason_kill_switch": "the society was halted",
"mode_label": "Agents view",
- "mode_world": "World",
+ "toggle_sections": "Show or hide sections",
+ "fullscreen_failed": "Fullscreen could not be changed. The Map / Agents buttons remain available.",
+ "mode_map": "Map",
"mode_ledger": "Ledger",
"hud_agents": "{count} agents",
"hud_active": "{count} active",
@@ -84,8 +86,8 @@
"view_reset": "Back to the designed view (R)",
"minimap_label": "Island map — click to jump there",
"webgl_missing_title": "The island needs WebGL",
- "webgl_missing_body": "This window cannot draw 3D right now. The ledger lists the same agents.",
- "open_ledger": "Open the ledger",
+ "webgl_agents_body": "This window cannot draw 3D right now. You can still use the Agents view.",
+ "open_agents": "Open Agents",
"loading": "Building the island…",
"place_plugins": "Plugin Docks",
"place_foundry": "Agent Foundry",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
index a6e90b2978..5d6383328b 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
@@ -63,7 +63,9 @@
"room_reason_user": "la cerraste tú",
"room_reason_kill_switch": "la sociedad se detuvo",
"mode_label": "Vista de agentes",
- "mode_world": "Mundo",
+ "toggle_sections": "Mostrar u ocultar secciones",
+ "fullscreen_failed": "No se pudo cambiar la pantalla completa. Los botones Mapa / Agentes siguen disponibles.",
+ "mode_map": "Mapa",
"mode_ledger": "Registro",
"hud_agents": "{count} agentes",
"hud_active": "{count} activos",
@@ -84,8 +86,8 @@
"view_reset": "Volver a la vista original (R)",
"minimap_label": "Mapa de la isla: haz clic para saltar allí",
"webgl_missing_title": "La isla necesita WebGL",
- "webgl_missing_body": "Esta ventana no puede dibujar 3D ahora mismo. El registro muestra los mismos agentes.",
- "open_ledger": "Abrir el registro",
+ "webgl_agents_body": "Esta ventana no puede mostrar 3D. Puedes seguir usando la vista Agentes.",
+ "open_agents": "Abrir Agentes",
"loading": "Construyendo la isla…",
"place_plugins": "Muelles de Plugins",
"place_foundry": "Fundición de Agentes",
diff --git a/jarvis/ui/web/frontend/src/lib/mapFullscreen.test.ts b/jarvis/ui/web/frontend/src/lib/mapFullscreen.test.ts
new file mode 100644
index 0000000000..822e70b090
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/mapFullscreen.test.ts
@@ -0,0 +1,35 @@
+import { afterEach, expect, it, vi } from "vitest";
+import { setMapFullscreen } from "./mapFullscreen";
+import { inDesktopShell } from "./nativeDrop";
+vi.mock("./nativeDrop", () => ({ inDesktopShell: vi.fn(() => false) }));
+afterEach(() => { vi.unstubAllGlobals(); vi.mocked(inDesktopShell).mockReturnValue(false); });
+
+it("restores the browser when exit was clicked before fullscreen entry completed", async () => {
+ let finish!: () => void;
+ const host = { fullscreenElement: null as object | null, documentElement: {
+ requestFullscreen: () => new Promise<void>((resolve) => { finish = resolve; }),
+ }, exitFullscreen: vi.fn(async () => { host.fullscreenElement = null; }) };
+ vi.stubGlobal("document", host);
+ const entry = setMapFullscreen(true);
+ await setMapFullscreen(false);
+ host.fullscreenElement = {};
+ finish();
+ await entry;
+ expect(host.exitFullscreen).toHaveBeenCalledOnce();
+});
+
+it("serializes native entry and exit", async () => {
+ vi.mocked(inDesktopShell).mockReturnValue(true);
+ const requests: boolean[] = [];
+ vi.stubGlobal("fetch", vi.fn(async (_url, init) => {
+ requests.push(JSON.parse(init.body).enabled);
+ return { ok: true, json: async () => ({ ok: true }) };
+ }));
+ await Promise.all([setMapFullscreen(true), setMapFullscreen(false)]);
+ expect(requests).toEqual([true, false]);
+});
+
+it("reports browser fullscreen rejection", async () => {
+ vi.stubGlobal("document", { fullscreenElement: null, documentElement: {} });
+ await expect(setMapFullscreen(true)).rejects.toThrow("Fullscreen unavailable");
+});
diff --git a/jarvis/ui/web/frontend/src/lib/mapFullscreen.ts b/jarvis/ui/web/frontend/src/lib/mapFullscreen.ts
new file mode 100644
index 0000000000..cfc92b7ae1
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/mapFullscreen.ts
@@ -0,0 +1,32 @@
+import { inDesktopShell } from "./nativeDrop";
+
+let pending = Promise.resolve();
+let requested = false;
+
+/** Serialize desktop transitions so a quick return cannot leave the window fullscreen. */
+export function setMapFullscreen(enabled: boolean): Promise<void> {
+ requested = enabled;
+ if (inDesktopShell()) {
+ // A previous caller already reports its failure; allow the next transition.
+ const next = pending.catch(() => undefined).then(async () => {
+ const response = await fetch("/api/window/fullscreen", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ enabled }),
+ });
+ if (!response.ok || !(await response.json()).ok) throw new Error("Desktop fullscreen unavailable");
+ });
+ pending = next;
+ return next;
+ }
+ // Browser entry must stay synchronous with the user's click for activation.
+ if (enabled && !document.fullscreenElement) {
+ const enter = document.documentElement.requestFullscreen?.();
+ if (!enter) return Promise.reject(new Error("Fullscreen unavailable"));
+ return enter.then(async () => {
+ if (!requested && document.fullscreenElement) await document.exitFullscreen();
+ });
+ }
+ if (!enabled && document.fullscreenElement) return document.exitFullscreen();
+ return Promise.resolve();
+}
diff --git a/jarvis/ui/web/frontend/src/store/societyShell.ts b/jarvis/ui/web/frontend/src/store/societyShell.ts
new file mode 100644
index 0000000000..1e6e187f63
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/store/societyShell.ts
@@ -0,0 +1,12 @@
+import { create } from "zustand";
+
+/** Section-local navigation starts hidden on every visit. */
+export const useSocietyShell = create<{
+ navigationOpen: boolean;
+ toggleNavigation: () => void;
+ reset: () => void;
+}>((set) => ({
+ navigationOpen: false,
+ toggleNavigation: () => set((s) => ({ navigationOpen: !s.navigationOpen })),
+ reset: () => set({ navigationOpen: false }),
+}));
diff --git a/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx b/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx
index f6a210c161..560f3554d4 100644
--- a/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx
@@ -1,286 +1,23 @@
-/**
- * JarvisAgentsView — board of every Jarvis-Agent, live and past.
- *
- * This file is the data half. It reads THREE sources and merges them:
- *
- * - `/api/sub-agents/tree` — the live registry. Carries tool calls and a
- * running clock, but it is an in-memory bus subscriber that drops a finished
- * node after 60s and starts empty on every app start.
- * - `/api/missions` — the durable record of the same runs. No tool calls, but
- * it survives, so the board is not blank whenever nothing happens to be
- * running in this exact minute.
- * - `/api/outputs` — the archive of output directories. It knows a run's
- * terminal reason, one-line summary and the slug its deliverables live
- * under, which is what turns "Failed" into "provider quota exhausted" on the
- * board and what the insight page opens the Artifacts section with.
- *
- * Before the merge the board was live-only, which meant every number read 0
- * and the table read "no agents are running right now" even with hundreds of
- * finished runs on disk. See `missionRows.ts` for the mapping and why a run
- * present in both wins as its live node.
- *
- * Presentation lives in two siblings: `DepartureBoard` (header, headline
- * numbers, table) and `AgentInsight` (one run in full — outcome, story,
- * transcript, review, output). Clicking a row swaps the board for the insight
- * page inside this section; "← Back" swaps it back. Both render with the
- * shared `components/extensions/primitives` so this section looks like Spend,
- * Skills, Plugins, MCPs and CLIs rather than like a screen of its own.
- */
-import { Suspense, lazy, useCallback, useEffect, useMemo, useState } from "react";
-import { useQuery } from "@tanstack/react-query";
-
-import { useSubAgentStore, type SubAgentNode, type SubAgentTreeSnapshot } from "@/store/jarvisAgents";
-import { useEventStore } from "@/store/events";
+/** Lazy map surface for the Agents section. */
+import { Suspense, lazy } from "react";
import type { PlaceId } from "@/components/society/world/islandLayout";
-import { DepartureBoard } from "./sub-agents/DepartureBoard";
-import { AgentInsight } from "./sub-agents/AgentInsight";
-import { selectTaskRows } from "./sub-agents/rows";
-import { mergeBoardRows, HISTORY_LIMIT, normalizeTraceId } from "./sub-agents/missionRows";
-import { resolveAgentsMode, type AgentsMode } from "./sub-agents/agentsMode";
-import { fetchMissions } from "@/components/missions/api";
-import { useMissionWebSocket } from "@/components/missions/useMissionWebSocket";
-import { useMissionsStore } from "@/components/missions/store";
-import { useOutputsList } from "@/hooks/useOutputs";
-import { useSectionHealth } from "@/hooks/useProviders";
-import { SegmentedFilter } from "@/components/extensions/primitives";
-import { useLocaleChunk, useT } from "@/i18n";
-import { detectWebgl } from "@/lib/graphDimension";
-
-/** The query parameter the Artifacts section reads to pre-select a run. */
-const RUN_PARAM = "run";
-
-/**
- * The section's two faces (MASTERPLAN §4.1): the 3D island is the face, the
- * board stays as the data-dense "Ledger" and the declared fallback wherever
- * WebGL is absent. The world is a lazy chunk — three.js and the island never
- * load for someone who only ever reads the ledger.
- */
-const MODE_KEY = "jarvis.agents.mode.v2";
const WorldStage = lazy(() =>
import("@/components/society/world/WorldStage").then((m) => ({ default: m.WorldStage })),
);
-function readMode(): AgentsMode {
- if (!detectWebgl()) return "ledger";
- try {
- const raw = localStorage.getItem(MODE_KEY);
- if (raw === "city") writeMode("world");
- const legacy = raw === "city" || raw === "world" || raw === "ledger"
- ? null
- : localStorage.getItem("jarvis.agents.mode");
- return resolveAgentsMode(raw, legacy, true);
- } catch {
- /* private mode: fall through to the default */
- }
- return "world";
-}
-
-function writeMode(mode: AgentsMode): void {
- try {
- localStorage.setItem(MODE_KEY, mode);
- } catch {
- /* not persisted, still switched */
- }
-}
-
-function ModeSwitch({ mode, onChange }: { mode: AgentsMode; onChange: (m: AgentsMode) => void }) {
- const t = useT();
- const ready = useLocaleChunk("society");
- if (!ready) return null;
- return (
- <div className="rounded-md border border-border bg-popover p-0.5 shadow-float">
- <SegmentedFilter<AgentsMode>
- value={mode}
- onChange={onChange}
- label={t("society.world.mode_label")}
- options={[
- { id: "world", label: t("society.world.mode_world") },
- { id: "ledger", label: t("society.world.mode_ledger") },
- ]}
- />
- </div>
- );
-}
-
-/** Shown while the world chunk loads: a quiet sky-coloured block, no invented numbers. */
-function WorldLoading() {
- return <div className="h-full w-full animate-pulse bg-secondary" aria-hidden />;
-}
export interface JarvisAgentsViewProps {
- /**
- * A figure on the island was clicked (or the selection cleared). The
- * society view hooks its model card in here; standalone, nothing listens.
- */
onSelectAgent?: (agentId: string | null) => void;
- /** A building with a card was clicked on the island; the society view opens its card. */
onSelectPlace?: (place: PlaceId) => void;
+ onOpenAgents: () => void;
}
-export function JarvisAgentsView({ onSelectAgent, onSelectPlace }: JarvisAgentsViewProps = {}) {
- const { health } = useSectionHealth();
- const subAgents = useSubAgentStore((s) => s.subAgents);
- const sweepExpired = useSubAgentStore((s) => s.sweepExpired);
- const hydrateSnapshot = useSubAgentStore((s) => s.hydrateSnapshot);
- const setActiveSection = useEventStore((s) => s.setActiveSection);
- const [snapshotError, setSnapshotError] = useState<string | null>(null);
- // The run whose insight page is open, by dash-stripped id. Kept as an id
- // rather than a node so the page follows the row through live updates.
- const [openTraceId, setOpenTraceId] = useState<string | null>(null);
- const [mode, setMode] = useState<AgentsMode>(readMode);
- const switchMode = useCallback((next: AgentsMode) => {
- writeMode(next);
- setMode(next);
- }, []);
-
- // One row per task: collapse each worker into its mission row so a single
- // dispatched task shows once (the mission "Sub-Agent" carrying the task
- // text), not twice (mission + its "Worker" child). The store keeps both
- // nodes for the DetailPanel; this only filters the displayed list. Header
- // counts and the DepartureBoard metric panel both derive from this array,
- // so they stay consistent with the rows actually shown.
- const liveRows = useMemo(() => selectTaskRows(subAgents), [subAgents]);
-
- // The durable half. Shares its query key with the Missions view, so opening
- // both costs one request. A failure here is not surfaced as an error: the
- // live board still works without history, and the section already has a
- // banner for the snapshot it cannot do without.
- const historyQuery = useQuery({
- queryKey: ["missions"],
- queryFn: fetchMissions,
- refetchInterval: 30_000,
- });
-
- // The archive half — optional enrichment, never a blocker: a row whose
- // directory is gone keeps what the mission record says about it.
- const outputsQuery = useOutputsList();
-
- const nodesList = useMemo(
- () =>
- mergeBoardRows(
- liveRows,
- historyQuery.data?.missions ?? [],
- HISTORY_LIMIT,
- outputsQuery.data ?? [],
- ),
- [liveRows, historyQuery.data, outputsQuery.data],
- );
-
- const openAgent = useMemo(
- () =>
- openTraceId
- ? nodesList.find((n) => normalizeTraceId(n.trace_id) === openTraceId) ?? null
- : null,
- [nodesList, openTraceId],
- );
-
- const loadSnapshot = useCallback(async (signal?: AbortSignal) => {
- try {
- const res = await fetch("/api/sub-agents/tree", { signal });
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- const snapshot = (await res.json()) as SubAgentTreeSnapshot;
- hydrateSnapshot(snapshot);
- setSnapshotError(null);
- } catch (error) {
- if ((error as { name?: string }).name === "AbortError") return;
- setSnapshotError(error instanceof Error ? error.message : "Snapshot failed");
- }
- }, [hydrateSnapshot]);
-
- useEffect(() => {
- const id = setInterval(sweepExpired, 5_000);
- return () => clearInterval(id);
- }, [sweepExpired]);
-
- useEffect(() => {
- const controller = new AbortController();
- void loadSnapshot(controller.signal);
- const id = window.setInterval(() => void loadSnapshot(), 15_000);
- return () => {
- controller.abort();
- window.clearInterval(id);
- };
- }, [loadSnapshot]);
-
- // Live trigger. The board's REST snapshot (`/api/sub-agents/tree`) is the
- // source of truth — the backend SubAgentRegistry translates Phase-6 mission
- // events into the tree. After the Welle-4 migration the live events ride
- // `/api/missions/ws` as MissionDispatched/WorkerSpawned/... — names and JSON
- // shape that the legacy `SUB_AGENT_EVENT_NAMES` WS filter never matches, so
- // without this the board only refreshed on the 15s poll and felt dead during
- // an active spawn. We reuse the already-working mission stream purely as a
- // "something changed" signal and debounce a snapshot refetch, rather than
- // re-implementing the registry's reducer in TS (which would re-introduce the
- // multi-layer enum drift of BUG-008). The 15s poll above stays as a fallback.
- // Open (or share) the mission-bus WS so the board receives live mission
- // events even when the Missions view is not mounted (`share: true` in the
- // underlying hook reuses the single socket). `lastSeq` increments on every
- // mission event applied to the store, so it is our "something changed" tick.
- useMissionWebSocket();
- const missionLastSeq = useMissionsStore((s) => s.lastSeq);
- useEffect(() => {
- if (missionLastSeq === 0) return;
- const id = window.setTimeout(() => void loadSnapshot(), 350);
- return () => window.clearTimeout(id);
- }, [missionLastSeq, loadSnapshot]);
-
- // Hand a run to the Artifacts section. That view reads `?run=<slug>` once at
- // mount (VisualizationView), so the address is written first and the section
- // switched second; `useSectionUrlMemory` carries the parameter along.
- const openOutput = useCallback(
- (slug: string) => {
- try {
- const url = new URL(window.location.href);
- url.searchParams.set(RUN_PARAM, slug);
- window.history.replaceState(window.history.state, "", `${url.pathname}${url.search}${url.hash}`);
- } catch {
- /* a WebView that refuses the write still switches sections; the
- Artifacts view then opens on its newest run instead of this one */
- }
- setActiveSection("visualization");
- },
- [setActiveSection],
- );
-
- const onOpen = useCallback((agent: SubAgentNode) => {
- setOpenTraceId(normalizeTraceId(agent.trace_id));
- }, []);
-
- if (openAgent) {
- return (
- <AgentInsight
- agent={openAgent}
- onBack={() => setOpenTraceId(null)}
- onOpenOutput={openOutput}
- />
- );
- }
-
- const modeSwitch = <ModeSwitch mode={mode} onChange={switchMode} />;
-
- if (mode === "world") {
- return (
- <div className="h-full min-h-0">
- <Suspense fallback={<WorldLoading />}>
- <WorldStage
- topRight={modeSwitch}
- onOpenLedger={() => switchMode("ledger")}
- onSelectAgent={onSelectAgent}
- onSelectPlace={onSelectPlace}
- />
- </Suspense>
- </div>
- );
- }
-
+export function JarvisAgentsView({ onSelectAgent, onSelectPlace, onOpenAgents }: JarvisAgentsViewProps) {
return (
- <DepartureBoard
- agents={nodesList}
- snapshotError={snapshotError}
- health={health["subagents"] ?? null}
- historyError={historyQuery.isError}
- onOpen={onOpen}
- headerActions={modeSwitch}
- />
+ <div className="h-full min-h-0">
+ <Suspense fallback={<div className="h-full w-full animate-pulse bg-secondary" aria-hidden />}>
+ <WorldStage onOpenAgents={onOpenAgents} onSelectAgent={onSelectAgent} onSelectPlace={onSelectPlace} />
+ </Suspense>
+ </div>
);
}
diff --git a/jarvis/ui/web/frontend/src/views/society/SocietyView.test.tsx b/jarvis/ui/web/frontend/src/views/society/SocietyView.test.tsx
new file mode 100644
index 0000000000..8626881442
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/society/SocietyView.test.tsx
@@ -0,0 +1,82 @@
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+import { useSocietyShell } from "@/store/societyShell";
+import { setMapFullscreen } from "@/lib/mapFullscreen";
+import { SocietyView } from "./SocietyView";
+
+vi.mock("@/lib/mapFullscreen", () => ({ setMapFullscreen: vi.fn(async () => undefined) }));
+vi.mock("@/i18n", () => ({ useT: () => (key: string) => key, useLocaleChunk: () => true }));
+vi.mock("@/components/society/chat/useModelMenuData", () => ({ useModelMenuData: () => undefined }));
+vi.mock("@/components/society/data", () => ({ useSocietyRoster: () => ({ data: { sample: false, agents: [
+ { 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 }: any) => (
+ <div data-testid="map"><button onClick={() => onSelectAgent("specialist")}>Map specialist</button><button onClick={onOpenAgents}>Map fallback</button></div>
+) }));
+vi.mock("@/components/society/card/AgentCardOverlay", () => ({ AgentCardOverlay: ({ agent, embedded, onSelectAgent, onCreate }: any) => (
+ <div data-testid="workspace" data-embedded={String(embedded)}>
+ <span>{agent.name}</span><input aria-label="Draft" />
+ <button onClick={() => onSelectAgent("specialist")}>Select specialist</button>
+ <button onClick={onCreate}>Create agent</button>
+ </div>
+) }));
+vi.mock("@/components/society/roster/RosterRail", () => ({ RosterRail: () => <div data-testid="roster" /> }));
+vi.mock("@/components/society/card/BuildingCardOverlay", () => ({ BuildingCardOverlay: () => null }));
+vi.mock("@/components/society/create/CreateAgentDialog", () => ({ CreateAgentDialog: ({ open, onClose }: any) => open ? <button onClick={onClose}>Close creator</button> : null }));
+
+afterEach(cleanup);
+
+it("defaults to the embedded Agents workspace even with a saved legacy ledger preference", () => {
+ localStorage.setItem("jarvis.agents.mode.v2", "ledger");
+ render(<SocietyView />);
+ expect(screen.getByTestId("workspace").getAttribute("data-embedded")).toBe("true");
+ expect(screen.getByText("Lead")).toBeTruthy();
+ expect(screen.queryByTestId("map")).toBeNull();
+ localStorage.removeItem("jarvis.agents.mode.v2");
+});
+
+it("switches to Map and back without losing the selected agent or draft", async () => {
+ render(<SocietyView />);
+ fireEvent.click(screen.getByText("Select specialist"));
+ 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();
+ fireEvent.click(screen.getByRole("tab", { name: "society.roster.title" }));
+ expect(screen.queryByTestId("map")).toBeNull();
+ expect(screen.getByText("Specialist")).toBeTruthy();
+ expect(screen.getByLabelText("Draft")).toBe(draft);
+ expect(draft.value).toBe("Unsent message");
+});
+
+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.getByText("Specialist")).toBeTruthy();
+ fireEvent.click(screen.getByText("Create agent"));
+ fireEvent.click(screen.getByText("Close creator"));
+ expect(screen.queryByText("Close creator")).toBeNull();
+});
+
+
+it("starts with sections hidden and toggles them independently of the agent roster", () => {
+ render(<SocietyView />);
+ expect(useSocietyShell.getState().navigationOpen).toBe(false);
+ fireEvent.click(screen.getByRole("button", { name: "society.world.toggle_sections" }));
+ expect(useSocietyShell.getState().navigationOpen).toBe(true);
+ fireEvent.click(screen.getByRole("button", { name: "society.world.toggle_sections" }));
+ expect(useSocietyShell.getState().navigationOpen).toBe(false);
+});
+
+it("requests fullscreen for Map and leaves it on Escape", async () => {
+ render(<SocietyView />);
+ fireEvent.click(screen.getByRole("tab", { name: "society.world.mode_map" }));
+ await screen.findByTestId("map");
+ expect(setMapFullscreen).toHaveBeenLastCalledWith(true);
+ fireEvent.keyDown(document, { key: "Escape" });
+ expect(setMapFullscreen).toHaveBeenLastCalledWith(false);
+ expect(screen.queryByTestId("map")).toBeNull();
+});
diff --git a/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx b/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx
index 59a2a4b336..174e83db95 100644
--- a/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx
+++ b/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx
@@ -1,18 +1,10 @@
-/**
- * The Agents section as the society (MASTERPLAN §4.1): left, the app's own
- * sidebar (unchanged, outside this view); centre, the stage; right, the fixed
- * agents rail. A thin strip above the stage carries the counts. Clicking a
- * row in the rail — or a figure on the island — opens the model card above
- * the stage; "+" opens the creator.
- *
- * The stage is the existing Jarvis-Agents board until the island (M3, built in
- * a parallel session under components/society/world/) mounts here — the
- * board then moves to the Ledger tab. The section keeps its id "agents", so
- * deep links, the navigate tool and the section parity tests are untouched.
- */
-import { lazy, Suspense, useCallback, useMemo, useState } from "react";
+import { lazy, Suspense, useCallback, useMemo, useState, useEffect } from "react";
-import { useT } from "@/i18n";
+import { PanelLeft } from "lucide-react";
+import { useSocietyShell } from "@/store/societyShell";
+import { setMapFullscreen } from "@/lib/mapFullscreen";
+import { inDesktopShell } from "@/lib/nativeDrop";
+import { useLocaleChunk, useT } from "@/i18n";
import { AgentCardOverlay } from "@/components/society/card/AgentCardOverlay";
import { BuildingCardOverlay } from "@/components/society/card/BuildingCardOverlay";
import { isBuildingPlace, type BuildingPlace } from "@/components/society/card/buildingCards";
@@ -30,79 +22,123 @@ const JarvisAgentsBoard = lazy(() =>
export function SocietyView() {
useModelMenuData();
const t = useT();
+ useLocaleChunk("society");
+ const [mode, setMode] = useState<"agents" | "world">("agents");
const roster = useSocietyRoster();
const agents = useMemo(() => roster.data?.agents ?? [], [roster.data]);
const sample = roster.data?.sample ?? true;
const [openAgentId, setOpenAgentId] = useState<string | null>(null);
const [creating, setCreating] = useState(false);
+ const [openPlace, setOpenPlace] = useState<BuildingPlace | null>(null);
const openAgent = useMemo(
- () => agents.find((a) => a.agentId === openAgentId) ?? null,
+ () => agents.find((a) => a.agentId === openAgentId) ?? agents.find((a) => a.tier === "lead") ?? agents[0] ?? null,
[agents, openAgentId],
);
const activeCount = agents.filter((a) => a.state === "working" || a.state === "waiting").length;
const onCreated = useCallback(() => {
setCreating(false);
- // The card does NOT open on top of the island: a brand-new agent is
- // walking out of the foundry right now, and its card would cover exactly
- // that. It holds nothing new anyway — the maker just typed all of it. The
- // rail lists the newcomer; a click on it, or on the figure, opens it.
}, []);
- // A figure clicked on the island opens its card, like a row in the rail
- // (maintainer, 2026-09-02). Clearing the island's selection (a click on
- // the ground) leaves the card alone — it has its own close.
- const onIslandSelect = useCallback((agentId: string | null) => {
- if (agentId) setOpenAgentId(agentId);
+ const navigationOpen = useSocietyShell((s) => s.navigationOpen);
+ const toggleNavigation = useSocietyShell((s) => s.toggleNavigation);
+ const [fullscreenError, setFullscreenError] = useState(false);
+ const switchMode = useCallback((next: "agents" | "world") => {
+ setMode(next);
+ setFullscreenError(false);
+ void setMapFullscreen(next === "world").catch(() => setFullscreenError(true));
}, []);
+ useEffect(() => {
+ const reset = useSocietyShell.getState().reset;
+ reset();
+ // A reload starts in Agents; restore a native window left fullscreen by it.
+ if (inDesktopShell()) void setMapFullscreen(false).catch(() => setFullscreenError(true));
+ return () => {
+ reset();
+ void setMapFullscreen(false).catch((error) => console.warn("Fullscreen exit failed", error));
+ };
+ }, []);
+
+ useEffect(() => {
+ const onKey = (event: KeyboardEvent) => {
+ if (event.key === "Escape" && mode === "world" && !openPlace && !creating) switchMode("agents");
+ };
+ const onFullscreen = () => {
+ if (!document.fullscreenElement && !inDesktopShell()) setMode("agents");
+ };
+ document.addEventListener("keydown", onKey);
+ document.addEventListener("fullscreenchange", onFullscreen);
+ return () => {
+ document.removeEventListener("keydown", onKey);
+ document.removeEventListener("fullscreenchange", onFullscreen);
+ };
+ }, [mode, creating, switchMode, openPlace]);
+
+ const onIslandSelect = useCallback((agentId: string | null) => {
+ if (agentId) {
+ setOpenAgentId(agentId);
+ switchMode("agents");
+ }
+ }, [switchMode]);
+
// A building clicked on the island opens its own card: the building
// rendered as it stands on the map, and beside it what it does.
- const [openPlace, setOpenPlace] = useState<BuildingPlace | null>(null);
const onIslandPlace = useCallback((place: PlaceId) => {
if (isBuildingPlace(place)) setOpenPlace(place);
}, []);
+ const modeSwitch = (
+ <div role="tablist" aria-label={t("society.world.mode_label")} className="flex items-center gap-0.5 rounded-md border border-border/60 p-0.5">
+ {(["world", "agents"] as const).map((value) => {
+ return <button key={value} type="button" role="tab" aria-selected={mode === value}
+ onClick={() => switchMode(value)}
+ className={`inline-flex h-6 items-center justify-center rounded px-3 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${mode === value ? "bg-secondary text-foreground" : "text-muted-foreground hover:text-foreground"}`}>
+ {t(value === "world" ? "society.world.mode_map" : "society.roster.title")}
+ </button>;
+ })}
+ </div>
+ );
+
return (
- <div className="flex h-full min-h-0 w-full" data-testid="society-view">
+ <div className={mode === "world" ? "fixed inset-0 z-30 flex flex-col bg-background" : "flex h-full min-h-0 w-full flex-col"} data-testid="society-view">
<div className="flex min-h-0 min-w-0 flex-1 flex-col">
- <div className="flex h-9 shrink-0 items-center gap-3 border-b border-border px-4 text-xs text-muted-foreground">
- <span className="font-medium text-foreground">{t("society.strip.title")}</span>
- <span aria-live="polite">
- {t("society.strip.active").replace("{0}", String(activeCount))}
- </span>
+ <div className="grid h-9 shrink-0 grid-cols-[1fr_auto_1fr] items-center gap-3 border-b border-border px-3">
+ <div className="flex items-center">
+ {mode === "agents" && <button type="button" onClick={toggleNavigation} aria-expanded={navigationOpen}
+ aria-label={t("society.world.toggle_sections")} title={t("society.world.toggle_sections")}
+ className="rounded p-1 text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring">
+ <PanelLeft className="h-4 w-4" aria-hidden />
+ </button>}
+ </div>
+ {modeSwitch}
+ <span className="justify-self-end text-xs text-muted-foreground" aria-live="polite">{t("society.strip.active").replace("{0}", String(activeCount))}</span>
+ </div>
+ {fullscreenError && <p role="alert" className="bg-card px-4 py-2 text-sm text-destructive">{t("society.world.fullscreen_failed")}</p>}
+ {mode === "world" ? (
+ <div className="relative flex min-h-0 flex-1">
+ <div className="min-w-0 flex-1">
+ <CanvasActivity.Provider value={!openPlace && !creating}>
+ <Suspense fallback={null}>
+ <JarvisAgentsBoard onSelectAgent={onIslandSelect} onSelectPlace={onIslandPlace} onOpenAgents={() => switchMode("agents")} />
+ </Suspense>
+ </CanvasActivity.Provider>
+ </div>
+
</div>
- <div className="relative min-h-0 flex-1">
- <CanvasActivity.Provider value={!openAgent && !openPlace && !creating}>
- <Suspense fallback={null}>
- <JarvisAgentsBoard onSelectAgent={onIslandSelect} onSelectPlace={onIslandPlace} />
- </Suspense>
- </CanvasActivity.Provider>
+ ) : null}
+ <div className={mode === "agents" ? "flex min-h-0 flex-1 flex-col" : "hidden"}>
+ {openAgent ? (
+ <AgentCardOverlay embedded agent={openAgent} roster={agents} rosterLoading={roster.isLoading}
+ sample={sample} onSelectAgent={setOpenAgentId} onCreate={() => setCreating(true)}
+ onClose={() => setOpenAgentId(null)} />
+ ) : (
+ <RosterRail agents={agents} loading={roster.isLoading} sample={sample}
+ activeAgentId={null} onOpen={setOpenAgentId} onCreate={() => setCreating(true)} side="left" />
+ )}
</div>
</div>
- <RosterRail
- agents={agents}
- loading={roster.isLoading}
- sample={sample}
- activeAgentId={openAgentId}
- onOpen={setOpenAgentId}
- onCreate={() => setCreating(true)}
- />
- <AgentCardOverlay
- agent={openAgent}
- roster={agents}
- rosterLoading={roster.isLoading}
- sample={sample}
- onSelectAgent={setOpenAgentId}
- onCreate={() => {
- // The creator ends with the newcomer walking out of the foundry on
- // the island; the card sits on top of exactly that, so it closes.
- setOpenAgentId(null);
- setCreating(true);
- }}
- onClose={() => setOpenAgentId(null)}
- />
<BuildingCardOverlay
place={openPlace}
onClose={() => setOpenPlace(null)}
diff --git a/jarvis/ui/window_fullscreen.py b/jarvis/ui/window_fullscreen.py
new file mode 100644
index 0000000000..fd0d4dddcc
--- /dev/null
+++ b/jarvis/ui/window_fullscreen.py
@@ -0,0 +1,23 @@
+"""Idempotent fullscreen control through the cross-platform pywebview API."""
+
+from __future__ import annotations
+
+import threading
+import weakref
+from typing import Any
+
+_lock = threading.Lock()
+_states: weakref.WeakKeyDictionary[Any, bool] = weakref.WeakKeyDictionary()
+
+
+def set_window_fullscreen(window: Any, enabled: bool) -> dict[str, Any]:
+ """Set fullscreen on a supported live window, restoring its previous frame on exit."""
+ toggle = getattr(window, "toggle_fullscreen", None)
+ if not callable(toggle):
+ return {"ok": False, "reason": "fullscreen_unavailable"}
+ with _lock:
+ current = _states.get(window, bool(getattr(window, "fullscreen", False)))
+ if current != enabled:
+ toggle()
+ _states[window] = enabled
+ return {"ok": True, "fullscreen": enabled}
diff --git a/tests/unit/ui/test_window_fullscreen.py b/tests/unit/ui/test_window_fullscreen.py
new file mode 100644
index 0000000000..cfc4c0d588
--- /dev/null
+++ b/tests/unit/ui/test_window_fullscreen.py
@@ -0,0 +1,63 @@
+"""Fullscreen transitions preserve the native window's restore semantics."""
+
+from types import SimpleNamespace
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.ui.web.desktop_routes import router
+from jarvis.ui.window_fullscreen import set_window_fullscreen
+
+
+class Window:
+ def __init__(self):
+ self.calls = 0
+ self.fail = False
+
+ def toggle_fullscreen(self):
+ if self.fail:
+ raise RuntimeError("window unavailable")
+ self.calls += 1
+
+
+def test_idempotent_entry_and_restoration():
+ window = Window()
+ for enabled in [False, True, True, False, False]:
+ assert set_window_fullscreen(window, enabled) == {"ok": True, "fullscreen": enabled}
+ assert window.calls == 2
+
+
+def test_failed_transition_is_retryable():
+ window = Window()
+ window.fail = True
+ with pytest.raises(RuntimeError):
+ set_window_fullscreen(window, True)
+ window.fail = False
+ assert set_window_fullscreen(window, True)["ok"]
+ assert window.calls == 1
+
+
+def test_headless_degrades():
+ assert not set_window_fullscreen(None, True)["ok"]
+
+
+def test_route_and_cli_metadata():
+ app = FastAPI()
+ app.include_router(router)
+ client = TestClient(app)
+ assert (
+ client.post("/api/window/fullscreen", json={"enabled": True}).json()["reason"]
+ == "no_desktop_shell"
+ )
+ window = Window()
+ app.state.desktop_app = SimpleNamespace(
+ set_fullscreen=lambda enabled: set_window_fullscreen(window, enabled)
+ )
+ assert client.post("/api/window/fullscreen", json={"enabled": True}).json()["fullscreen"]
+ assert (
+ client.post("/api/window/fullscreen", json={"enabled": False}).json()["fullscreen"] is False
+ )
+ operation = app.openapi()["paths"]["/api/window/fullscreen"]["post"]
+ assert operation["operationId"] == "fullscreen"
+ assert operation["tags"] == ["window"]