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(verse): add the verse host, bridge and on-demand verse download (#1152)

Ruben Lütke778a7bf783f2
diff --git a/dodaios/agentic_ide/launch_sequence.py b/dodaios/agentic_ide/launch_sequence.py
new file mode 100644
index 0000000000..c04d8e3991
--- /dev/null
+++ b/dodaios/agentic_ide/launch_sequence.py
@@ -0,0 +1,139 @@
+"""The coding-agent launch sequence, shared by every launcher (contract 11, 14).
+
+The web Verse's launcher panel ran this in the browser: open a terminal,
+start it, wait for it to come up, hand it the brief. The Unreal Verse's
+``launcher.start`` needs the same sequence, so it lives here. Both callers
+use the one instance the verse host owns (``VerseHost.launcher``), so one
+batch runs at a time across them (single flight: a second start answers
+busy); ``cancel`` stops starting further
+panes, panes already open stay.
+
+The steps are injected (``LaunchSteps``) so the sequence is testable without
+a PTY; ``dodaios.verse_host.ports.AppBackend`` supplies the live ones.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import random
+import time
+from collections.abc import Awaitable, Callable
+from dataclasses import dataclass, field
+from typing import Any, Protocol
+
+log = logging.getLogger(__name__)
+
+START_TIMEOUT_S = 30.0
+START_POLL_S = 0.6
+MAX_PER_BATCH = 8
+
+
+class LaunchBusy(RuntimeError):
+ """Another batch is running."""
+
+
+class LaunchSteps(Protocol):
+ async def open_terminal(self, workspace_id: str | None, agent: str) -> tuple[str, str]: ...
+ async def start_terminal(self, name: str, workspace_id: str) -> None: ...
+ async def list_panes(self) -> list[dict[str, Any]]: ...
+ async def prompt_terminal(self, name: str, text: str, workspace_id: str) -> bool | None: ...
+
+
+@dataclass
+class LaunchedPane:
+ workspace_id: str
+ name: str
+ submitted: bool | None = None
+
+ @property
+ def pane_id(self) -> str:
+ return f"{self.workspace_id}:{self.name}"
+
+
+@dataclass
+class Batch:
+ cancelled: bool = False
+ remaining: int = 0
+ opened: list[LaunchedPane] = field(default_factory=list)
+ started_at: float = field(default_factory=time.monotonic)
+
+
+class LaunchSequence:
+ """Single-flight batch launcher."""
+
+ def __init__(
+ self,
+ steps: LaunchSteps,
+ *,
+ start_timeout_s: float = START_TIMEOUT_S,
+ poll_s: float = START_POLL_S,
+ sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
+ ) -> None:
+ self.steps = steps
+ self.start_timeout_s = start_timeout_s
+ self.poll_s = poll_s
+ self._sleep = sleep
+ self.running: Batch | None = None
+
+ @property
+ def busy(self) -> bool:
+ return self.running is not None
+
+ def cancel(self) -> int:
+ """Stop the running batch; returns how many panes it will not start."""
+ batch = self.running
+ if batch is None:
+ return 0
+ batch.cancelled = True
+ return batch.remaining
+
+ async def _wait_live(self, workspace_id: str, name: str, batch: Batch) -> bool:
+ deadline = time.monotonic() + self.start_timeout_s
+ while time.monotonic() < deadline and not batch.cancelled:
+ try:
+ for row in await self.steps.list_panes():
+ if row.get("workspace_id") == workspace_id and name in (
+ row.get("name"),
+ row.get("key"),
+ ):
+ status = row.get("status")
+ if status == "live":
+ return True
+ if status != "pending":
+ return False
+ except Exception: # noqa: BLE001 - a failed poll is retried
+ log.warning("launch sequence: pane poll failed", exc_info=True)
+ await self._sleep(self.poll_s + random.random() * 0.3) # noqa: S311
+ return False
+
+ async def run(
+ self, workspace_id: str | None, agents: list[tuple[str, int]], brief: str
+ ) -> list[LaunchedPane]:
+ """Open ``count`` panes per agent; brief each once it is live. Raises LaunchBusy."""
+ if self.running is not None:
+ raise LaunchBusy("A launch batch is already running.")
+ batch = Batch()
+ plan = [agent for agent, count in agents for _ in range(max(0, count))][:MAX_PER_BATCH]
+ batch.remaining = len(plan)
+ self.running = batch
+ brief = brief.strip()
+ try:
+ for agent in plan:
+ if batch.cancelled:
+ break
+ ws, name = await self.steps.open_terminal(workspace_id, agent)
+ batch.remaining -= 1
+ pane = LaunchedPane(ws, name)
+ batch.opened.append(pane)
+ if not brief or batch.cancelled:
+ continue
+ try:
+ await self.steps.start_terminal(name, ws)
+ except Exception: # noqa: BLE001 - the pane may start on its own
+ log.warning("launch sequence: start of %s failed", name, exc_info=True)
+ if await self._wait_live(ws, name, batch) and not batch.cancelled:
+ pane.submitted = await self.steps.prompt_terminal(name, brief, ws)
+ finally:
+ self.running = None
+ return batch.opened
diff --git a/dodaios/core/events.py b/dodaios/core/events.py
index d1ca6268b7..faee94d0b9 100644
--- a/dodaios/core/events.py
+++ b/dodaios/core/events.py
@@ -2729,3 +2729,69 @@ class SelfBuildChanged(Event):
kind: str = ""
state: str = ""
title: str = ""
+
+
+# ----------------------------------------------------------------------
+# Unreal Verse host (docs/verse/unreal/contracts/bridge-protocol.md)
+# ----------------------------------------------------------------------
+
+
+@dataclass(frozen=True, slots=True)
+class VerseOpenRequested(Event):
+ """``Verse.exe`` asked the app to open one of its views (contract 11, 14).
+
+ Published by the verse host's command relay for ``pane.open``,
+ ``ide.focus_terminal``, ``agent.open``, ``agents.open_list``,
+ ``group.open``, ``simulator.open`` and ``ide.open``. The web UI's
+ ``useWebSocket`` handler runs the same code the web Verse runs for each
+ target; the desktop process raises the app window (``ShowWindowRequested``
+ follows). Verse hides itself.
+
+ ``target`` is ``pane``, ``agent``, ``agents``, ``group``, ``simulator`` or
+ ``ide``. ``focus`` asks for keyboard focus on the pane at once (desk
+ takeover); ``open`` is ``changes`` for the pane's changes view.
+ """
+
+ target: str = ""
+ workspace_id: str = ""
+ name: str = ""
+ focus: bool = False
+ open: str = ""
+ agent_id: str = ""
+ group_id: str = ""
+ programme: str = ""
+
+
+@dataclass(frozen=True, slots=True)
+class VerseStatusChanged(Event):
+ """The Unreal Verse's host status or lifecycle state changed.
+
+ ``status`` is ``not_installed``, ``unsupported``, ``stopped``,
+ ``running`` or ``crashed``; ``state`` the lifecycle state while running
+ (``booting``, ``visible``, ``panel``, ``dormant``, ``exiting``), else
+ empty. The launcher card re-reads ``GET /api/verse/status`` on it.
+ """
+
+ status: str = ""
+ state: str = ""
+ pid: int = 0
+
+
+@dataclass(frozen=True, slots=True)
+class VerseSettingsChanged(Event):
+ """``verse.*`` settings were written (by Verse's ``settings.set`` or the import).
+
+ ``settings`` holds only the keys that changed, with their new values.
+ """
+
+ settings: dict[str, Any] = field(default_factory=dict)
+
+
+@dataclass(frozen=True, slots=True)
+class VerseDuelRecorded(Event):
+ """One duel set was stored by ``ProgressionService.record_duel`` (contract 10)."""
+
+ match_id: str = ""
+ outcome: str = ""
+ kills: int = 0
+ deaths: int = 0
diff --git a/dodaios/ui/web/frontend/src/components/agentic/sidePanel/OfficeTab.tsx b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/OfficeTab.tsx
index 34be72a4d4..b255c06350 100644
--- a/dodaios/ui/web/frontend/src/components/agentic/sidePanel/OfficeTab.tsx
+++ b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/OfficeTab.tsx
@@ -3,6 +3,7 @@ import { AlertTriangle, RotateCcw } from "lucide-react";
import { translate, useLocaleChunk } from "@/i18n";
import { useIdeSidePanelStore } from "@/store/ideSidePanel";
import { VerseLoadingScreen } from "@/components/society/verse/VerseLoadingScreen";
+import { VerseHostMount } from "@/components/verseHost/VerseHostMount";
// The ship is a WebGL scene with its own chunk: nothing of it loads until
// someone opens this tab.
@@ -50,7 +51,7 @@ export function OfficeTab() {
const ready = useLocaleChunk("society");
const openTab = useIdeSidePanelStore((state) => state.openTab);
return (
- <div data-testid="ide-office-tab" className="h-full min-h-0 w-full">
+ <div data-testid="ide-office-tab" className="relative h-full min-h-0 w-full">
<OfficeTabBoundary>
{ready && (
<Suspense fallback={<div className="relative h-full w-full"><VerseLoadingScreen /></div>}>
@@ -58,6 +59,8 @@ export function OfficeTab() {
</Suspense>
)}
</OfficeTabBoundary>
+ {/* The Unreal Verse launcher (WP17), behind verse.unreal_preview until the deletion PR. */}
+ <VerseHostMount />
</div>
);
}
diff --git a/dodaios/ui/web/frontend/src/components/verseHost/VerseHostMount.tsx b/dodaios/ui/web/frontend/src/components/verseHost/VerseHostMount.tsx
new file mode 100644
index 0000000000..f4ca31f8a3
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/verseHost/VerseHostMount.tsx
@@ -0,0 +1,26 @@
+/**
+ * Where the Unreal Verse launcher card sits on the Verse view: the bottom-right
+ * corner, only while the `verse.unreal_preview` flag is on (`GET /api/verse/flags`).
+ * Renders nothing otherwise, so the three.js Verse is untouched until parity.
+ */
+import { useEffect, useState } from "react";
+import { VerseLauncherCard } from "./VerseLauncherCard";
+import { fetchVerseFlags } from "./verseHostApi";
+
+export function VerseHostMount() {
+ const [on, setOn] = useState(false);
+ useEffect(() => {
+ let alive = true;
+ fetchVerseFlags().then(
+ (flags) => { if (alive) setOn(flags.unreal_preview); },
+ () => { if (alive) setOn(false); },
+ );
+ return () => { alive = false; };
+ }, []);
+ if (!on) return null;
+ return (
+ <div className="pointer-events-none absolute bottom-6 right-4 z-30 flex justify-end">
+ <div className="pointer-events-auto"><VerseLauncherCard /></div>
+ </div>
+ );
+}
diff --git a/dodaios/ui/web/frontend/src/components/verseHost/VerseInstallPanel.tsx b/dodaios/ui/web/frontend/src/components/verseHost/VerseInstallPanel.tsx
new file mode 100644
index 0000000000..cd58e30e31
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/verseHost/VerseInstallPanel.tsx
@@ -0,0 +1,126 @@
+/**
+ * "Download the Verse" on the launcher card (WP17.13, README Delivery). The
+ * app install never carries the Verse; this panel shows the package size, then
+ * the download progress with cancel, and hands back to the card once the
+ * Verse is installed. Polls `GET /api/verse/install/progress` while a
+ * download runs.
+ */
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useUiLanguage } from "@/i18n";
+import { launcherText, type LauncherKey } from "./strings";
+import {
+ cancelOrRemoveInstall,
+ fetchInstallProgress,
+ formatBytes,
+ isInstalling,
+ startInstall,
+ type InstallProgress,
+} from "./verseHostApi";
+
+const RUNNING_POLL_MS = 500;
+const IDLE_POLL_MS = 15000;
+
+export function VerseInstallPanel({ onInstalled }: { onInstalled?: () => void }) {
+ const lang = useUiLanguage();
+ const t = useCallback((key: LauncherKey, vars?: Record<string, string>) => launcherText(lang, key, vars), [lang]);
+ const [progress, setProgress] = useState<InstallProgress | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const alive = useRef(true);
+ const installedSeen = useRef(false);
+
+ const apply = useCallback((next: InstallProgress) => {
+ if (!alive.current) return;
+ setProgress(next);
+ if (next.state === "installed" && !installedSeen.current) {
+ installedSeen.current = true;
+ onInstalled?.();
+ }
+ }, [onInstalled]);
+
+ const refresh = useCallback(async () => {
+ try {
+ apply(await fetchInstallProgress());
+ } catch (e) {
+ if (alive.current) setError(e instanceof Error ? e.message : String(e));
+ }
+ }, [apply]);
+
+ const running = isInstalling(progress);
+ useEffect(() => {
+ alive.current = true;
+ void refresh();
+ const timer = window.setInterval(() => void refresh(), running ? RUNNING_POLL_MS : IDLE_POLL_MS);
+ return () => {
+ alive.current = false;
+ window.clearInterval(timer);
+ };
+ }, [refresh, running]);
+
+ const act = async (run: () => Promise<InstallProgress>) => {
+ setBusy(true);
+ setError(null);
+ try {
+ apply(await run());
+ } catch (e) {
+ if (alive.current) setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ if (alive.current) setBusy(false);
+ }
+ };
+
+ if (!progress) return null;
+ const size = progress.download_bytes;
+ const total = progress.total_bytes || size || 0;
+ const pct = total > 0 ? Math.min(100, Math.round((progress.done_bytes / total) * 100)) : 0;
+
+ if (progress.state === "unavailable") {
+ return <p data-testid="verse-install-unavailable" className="mt-2 text-xs text-muted-foreground">{t("install.unavailable")}</p>;
+ }
+
+ return (
+ <div data-testid="verse-install" className="mt-3 space-y-2">
+ {running ? (
+ <>
+ <div
+ role="progressbar"
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={pct}
+ aria-label={t("install.download")}
+ className="h-1.5 w-full overflow-hidden rounded-full bg-muted"
+ >
+ <div className="h-full rounded-full bg-primary transition-[width] duration-300" style={{ width: `${pct}%` }} />
+ </div>
+ <p data-testid="verse-install-progress" className="text-xs tabular-nums text-muted-foreground">
+ {progress.state === "downloading"
+ ? t("install.downloading", { done: formatBytes(progress.done_bytes), total: formatBytes(total) })
+ : t(progress.state === "verifying" ? "install.verifying" : "install.installing")}
+ </p>
+ <button type="button" disabled={busy} onClick={() => void act(cancelOrRemoveInstall)}
+ className="rounded-md border border-border px-3 py-1.5 text-sm disabled:opacity-50">
+ {t("install.cancel")}
+ </button>
+ </>
+ ) : (
+ <>
+ {size !== null && (
+ <p data-testid="verse-install-size" className="text-xs tabular-nums text-muted-foreground">
+ {t("install.size", { size: formatBytes(size) })}
+ </p>
+ )}
+ {progress.state === "cancelled" && <p className="text-xs text-muted-foreground">{t("install.cancelled")}</p>}
+ {progress.state === "failed" && progress.error && (
+ <p role="alert" className="text-xs text-destructive">{t("install.failed", { reason: progress.error })}</p>
+ )}
+ <button type="button" disabled={busy} onClick={() => void act(startInstall)}
+ className="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground disabled:opacity-50">
+ {progress.state === "cancelled" ? t("install.resume") : progress.state === "failed" ? t("install.retry") : t("install.download")}
+ </button>
+ <p className="text-xs text-muted-foreground">{t("install.hint")}</p>
+ </>
+ )}
+ {error && <p role="alert" className="text-xs text-destructive">{t("failed", { reason: error })}</p>}
+ </div>
+ );
+}
diff --git a/dodaios/ui/web/frontend/src/components/verseHost/VerseLauncherCard.tsx b/dodaios/ui/web/frontend/src/components/verseHost/VerseLauncherCard.tsx
new file mode 100644
index 0000000000..0d9aabdebb
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/verseHost/VerseLauncherCard.tsx
@@ -0,0 +1,149 @@
+/**
+ * The Unreal Verse launcher card (WP17.13): host status, open the Verse,
+ * quick-start a duel, close it. Reads `GET /api/verse/status` and re-reads on
+ * every `VerseStatusChanged` the socket forwards (`VERSE_STATUS_EVENT`), with a
+ * slow poll as a safety net. Shown behind the `verse.unreal_preview` flag.
+ *
+ * The Verse is an optional download (README Delivery): while the status is
+ * `not_installed` the card shows the download size and "Download the Verse",
+ * then the progress with a cancel button (`VerseInstallPanel`).
+ *
+ * Opening hands the foreground to `Verse.exe`: the backend (the desktop
+ * process) allows it to take focus and sends `lifecycle.show`; the app window
+ * comes back when Verse returns focus (`focus.return_to_app`).
+ */
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useUiLanguage } from "@/i18n";
+import { VERSE_STATUS_EVENT } from "./openRequest";
+import { VerseInstallPanel } from "./VerseInstallPanel";
+import { launcherText, type LauncherKey } from "./strings";
+import {
+ fetchVerseStatus,
+ importBrowserSettings,
+ launchVerse,
+ showVerse,
+ stopVerse,
+ type ShowReason,
+ type VerseStatus,
+} from "./verseHostApi";
+
+const POLL_MS = 5000;
+
+let importDone = false;
+
+export function VerseLauncherCard({ className = "" }: { className?: string }) {
+ const lang = useUiLanguage();
+ const t = useCallback((key: LauncherKey, vars?: Record<string, string>) => launcherText(lang, key, vars), [lang]);
+ const [status, setStatus] = useState<VerseStatus | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const alive = useRef(true);
+
+ const refresh = useCallback(async () => {
+ try {
+ const next = await fetchVerseStatus();
+ if (alive.current) setStatus(next);
+ } catch (e) {
+ if (alive.current) setError(e instanceof Error ? e.message : String(e));
+ }
+ }, []);
+
+ useEffect(() => {
+ alive.current = true;
+ void refresh();
+ const timer = window.setInterval(() => void refresh(), POLL_MS);
+ const onStatus = () => void refresh();
+ window.addEventListener(VERSE_STATUS_EVENT, onStatus);
+ if (!importDone) {
+ importDone = true;
+ void importBrowserSettings().catch(() => { importDone = false; });
+ }
+ return () => {
+ alive.current = false;
+ window.clearInterval(timer);
+ window.removeEventListener(VERSE_STATUS_EVENT, onStatus);
+ };
+ }, [refresh]);
+
+ const act = useCallback(async (run: () => Promise<VerseStatus>) => {
+ setBusy(true);
+ setError(null);
+ try {
+ const next = await run();
+ if (alive.current) setStatus(next);
+ } catch (e) {
+ if (alive.current) setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ if (alive.current) setBusy(false);
+ }
+ }, []);
+
+ const open = (reason: ShowReason) => act(() => showVerse(reason));
+ const s = status?.status;
+ const canRun = s === "stopped" || s === "running";
+ const line = !status
+ ? t("starting")
+ : s === "running"
+ ? `${t("status.running")}${status.state ? ` · ${t(`state.${status.state}` as LauncherKey)}` : ""}`
+ : t(`status.${status.status}` as LauncherKey);
+
+ return (
+ <section
+ data-testid="verse-launcher-card"
+ aria-label={t("title")}
+ className={`w-[min(22rem,calc(100vw-2rem))] rounded-xl border border-border bg-card/95 p-4 text-card-foreground shadow-lg backdrop-blur ${className}`}
+ >
+ <header className="flex items-center justify-between gap-2">
+ <h2 className="text-sm font-semibold tracking-wide">{t("title")}</h2>
+ <span
+ aria-hidden
+ className={`h-2 w-2 rounded-full ${s === "running" ? "bg-emerald-500" : s === "crashed" ? "bg-red-500" : s === "stopped" ? "bg-amber-500" : "bg-muted-foreground/40"}`}
+ />
+ </header>
+ <p data-testid="verse-launcher-status" className="mt-2 text-sm text-muted-foreground">{line}</p>
+ {status?.status === "running" && status.vram_mb !== null && (
+ <p className="mt-1 text-xs tabular-nums text-muted-foreground">
+ {status.vram_mb} MB{status.fps !== null ? ` · ${Math.round(status.fps)} fps` : ""}
+ </p>
+ )}
+ {status?.status === "crashed" && status.crash_report && (
+ <p className="mt-1 truncate text-xs text-muted-foreground" title={status.crash_report}>
+ {t("crash_report")}: {status.crash_report}
+ </p>
+ )}
+ {s === "not_installed" && <VerseInstallPanel onInstalled={() => void refresh()} />}
+ {error && <p role="alert" className="mt-2 text-xs text-destructive">{t("failed", { reason: error })}</p>}
+ <div className="mt-3 flex flex-wrap gap-2">
+ {canRun && (
+ <>
+ <button type="button" disabled={busy} onClick={() => void open("verse_view")}
+ className="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground disabled:opacity-50">
+ {t("open")}
+ </button>
+ <button type="button" disabled={busy} onClick={() => void open("quick_start_duel")}
+ className="rounded-md border border-border px-3 py-1.5 text-sm disabled:opacity-50">
+ {t("quick_duel")}
+ </button>
+ </>
+ )}
+ {s === "running" && (
+ <button type="button" disabled={busy} onClick={() => void act(stopVerse)}
+ className="rounded-md px-3 py-1.5 text-sm text-muted-foreground hover:text-foreground disabled:opacity-50">
+ {t("stop")}
+ </button>
+ )}
+ {s === "crashed" && (
+ <button type="button" disabled={busy} onClick={() => void act(launchVerse)}
+ className="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground disabled:opacity-50">
+ {t("retry")}
+ </button>
+ )}
+ </div>
+ </section>
+ );
+}
+
+/** For tests: forget that the one-time settings import ran. */
+export function resetLauncherImportForTests(): void {
+ importDone = false;
+}
diff --git a/dodaios/ui/web/frontend/src/components/verseHost/VerseSettingsGroup.tsx b/dodaios/ui/web/frontend/src/components/verseHost/VerseSettingsGroup.tsx
new file mode 100644
index 0000000000..53226cf826
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/verseHost/VerseSettingsGroup.tsx
@@ -0,0 +1,117 @@
+/**
+ * Settings → General → Unreal Verse: "Remove the Verse" (README Delivery).
+ *
+ * The Verse is an optional download; this group shows the installed version
+ * and size and removes it again (`DELETE /api/verse/install`, which stops a
+ * running Verse first). It renders only while the Unreal Verse preview flag is
+ * on or a Verse is installed, so the classic Verse's settings stay as they are.
+ */
+import { useCallback, useEffect, useState } from "react";
+import { Button } from "@/components/ui/button";
+import { useUiLanguage } from "@/i18n";
+import { SettingsCard, SettingsNote, SettingsRow, SettingsSection } from "@/views/settings/SettingsLayout";
+import { VERSE_STATUS_EVENT } from "./openRequest";
+import { launcherText, type LauncherKey } from "./strings";
+import {
+ cancelOrRemoveInstall,
+ fetchInstallProgress,
+ fetchVerseFlags,
+ formatBytes,
+ type InstallProgress,
+} from "./verseHostApi";
+
+export function VerseSettingsGroup() {
+ const lang = useUiLanguage();
+ const t = useCallback((key: LauncherKey, vars?: Record<string, string>) => launcherText(lang, key, vars), [lang]);
+ const [preview, setPreview] = useState(false);
+ const [progress, setProgress] = useState<InstallProgress | null>(null);
+ const [failed, setFailed] = useState(false);
+ const [confirming, setConfirming] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ // Once shown, the group stays for this visit, so a removal reads "Not installed".
+ const [shown, setShown] = useState(false);
+
+ const refresh = useCallback(async () => {
+ try {
+ setProgress(await fetchInstallProgress());
+ setFailed(false);
+ } catch {
+ setFailed(true);
+ }
+ }, []);
+
+ useEffect(() => {
+ let alive = true;
+ fetchVerseFlags().then((f) => { if (alive) setPreview(f.unreal_preview); }, () => undefined);
+ void refresh();
+ const onStatus = () => void refresh();
+ window.addEventListener(VERSE_STATUS_EVENT, onStatus);
+ return () => {
+ alive = false;
+ window.removeEventListener(VERSE_STATUS_EVENT, onStatus);
+ };
+ }, [refresh]);
+
+ const installed = progress?.installed_version ?? null;
+ const visible = preview || !!installed || shown;
+ useEffect(() => {
+ if (visible && !shown) setShown(true);
+ }, [visible, shown]);
+ if (!visible) return null;
+
+ const remove = async () => {
+ setBusy(true);
+ setError(null);
+ try {
+ setProgress(await cancelOrRemoveInstall());
+ setConfirming(false);
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const detail = installed
+ ? `${t("settings.installed", { version: installed })}${progress?.install_bytes ? ` · ${formatBytes(progress.install_bytes)}` : ""}`
+ : t("settings.not_installed");
+
+ return (
+ <SettingsSection title={t("settings.title")} description={t("settings.description")}>
+ <SettingsCard>
+ <SettingsRow
+ id="settings-verse-remove"
+ testId="verse-settings-row"
+ title={t("settings.remove")}
+ description={detail}
+ control={
+ installed && !confirming ? (
+ <Button variant="outline" size="sm" disabled={busy} onClick={() => setConfirming(true)}>
+ {t("settings.remove")}
+ </Button>
+ ) : undefined
+ }
+ >
+ {failed && <SettingsNote tone="error">{t("settings.unavailable")}</SettingsNote>}
+ {confirming && installed && (
+ <SettingsNote tone="warning" testId="verse-settings-confirm">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <span>{t("settings.confirm")}</span>
+ <span className="flex gap-2">
+ <Button variant="ghost" size="sm" disabled={busy} onClick={() => setConfirming(false)}>
+ {t("install.cancel")}
+ </Button>
+ <Button variant="destructive" size="sm" disabled={busy} onClick={() => void remove()}>
+ {busy ? t("settings.removing") : t("settings.remove")}
+ </Button>
+ </span>
+ </div>
+ </SettingsNote>
+ )}
+ {error && <SettingsNote tone="error">{t("failed", { reason: error })}</SettingsNote>}
+ </SettingsRow>
+ </SettingsCard>
+ </SettingsSection>
+ );
+}
diff --git a/dodaios/ui/web/frontend/src/components/verseHost/__tests__/dutyParity.test.ts b/dodaios/ui/web/frontend/src/components/verseHost/__tests__/dutyParity.test.ts
new file mode 100644
index 0000000000..a442d56680
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/verseHost/__tests__/dutyParity.test.ts
@@ -0,0 +1,47 @@
+/**
+ * Parity of the backend's duty and chat-line ports (`dodaios/verse_host/duty.py`,
+ * `chat_lines.py`) with the web Verse's TS code (bridge contract 4.1, BW11).
+ * The table `tests/unit/verse_host/parity/duty_cases.json` is asserted by
+ * pytest against Python and here against TypeScript.
+ */
+import { readFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { describe, expect, it } from "vitest";
+import { dotKindFor, stateKeyFor } from "@/components/agentic/sidePanel/agentStatus";
+import { chatLines } from "@/components/society/crewFeeds/deskChat";
+import { dutyOf, dutyOfPane } from "@/components/society/verse/ranks/dutyStatus";
+import type { WorkspacePaneRow } from "@/lib/agenticIdeApi";
+import type { AgentChatEvent } from "@/lib/agentChatApi";
+import type { AgentRunState } from "@/components/society/data";
+
+interface Cases {
+ agents: { state: AgentRunState; lifecycle: "active" | "paused" | null; asking: boolean; error: boolean; duty: string }[];
+ panes: { pane: Record<string, unknown>; dot: string; state_key: string; duty: string }[];
+ chat: { events: AgentChatEvent[]; lines: { kind: string; text: string }[] }[];
+}
+
+const cases = JSON.parse(
+ readFileSync(resolve(__dirname, "../../../../../../../../tests/unit/verse_host/parity/duty_cases.json"), "utf-8"),
+) as Cases;
+
+describe("duty status parity with the backend port", () => {
+ it.each(cases.agents)("agent %#", (c) => {
+ expect(dutyOf({ state: c.state, lifecycle: c.lifecycle ?? undefined }, { asking: c.asking, error: c.error })).toBe(c.duty);
+ });
+
+ it.each(cases.panes)("pane %#", (c) => {
+ const pane = c.pane as unknown as WorkspacePaneRow;
+ const dot = dotKindFor(pane);
+ const key = stateKeyFor(pane, dot);
+ expect(dot).toBe(c.dot);
+ expect(key).toBe(c.state_key);
+ expect(dutyOfPane(dot, key)).toBe(c.duty);
+ });
+});
+
+describe("chat lines parity with the backend port", () => {
+ it.each(cases.chat)("chat %#", (c) => {
+ // Short texts only: the backend cuts long lines on a word boundary (contract 6).
+ expect(chatLines(c.events).map(({ kind, text }) => ({ kind, text }))).toEqual(c.lines);
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/verseHost/__tests__/verseHost.test.tsx b/dodaios/ui/web/frontend/src/components/verseHost/__tests__/verseHost.test.tsx
new file mode 100644
index 0000000000..c7a70f5ac0
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/verseHost/__tests__/verseHost.test.tsx
@@ -0,0 +1,104 @@
+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { useEventStore } from "@/store/events";
+import { useIdeChatStore } from "@/store/ideChat";
+import { handleVerseOpen, VERSE_OPEN_GROUP_EVENT, VERSE_STATUS_EVENT } from "../openRequest";
+import { LAUNCHER_STRINGS } from "../strings";
+import { resetLauncherImportForTests, VerseLauncherCard } from "../VerseLauncherCard";
+import { parseStatus } from "../verseHostApi";
+
+function respond(map: Record<string, unknown>) {
+ return vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ const key = `${init?.method ?? "GET"} ${url}`;
+ const body = map[key] ?? map[url];
+ if (body === undefined) return new Response("{}", { status: 404 });
+ return new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" } });
+ });
+}
+
+const running = { status: "running", state: "visible", pid: 41, vram_mb: 4200, fps: 120, crash_report: null };
+const stopped = { status: "stopped", state: null, pid: null, vram_mb: null, fps: null, crash_report: null };
+
+describe("parseStatus", () => {
+ it("falls back to stopped for an unknown status", () => {
+ expect(parseStatus({ status: "weird" }).status).toBe("stopped");
+ expect(parseStatus(running)).toEqual(running);
+ });
+});
+
+describe("launcher strings", () => {
+ it("every language has every key", () => {
+ const keys = Object.keys(LAUNCHER_STRINGS.en).sort();
+ for (const table of Object.values(LAUNCHER_STRINGS)) expect(Object.keys(table).sort()).toEqual(keys);
+ });
+});
+
+describe("VerseLauncherCard", () => {
+ beforeEach(() => resetLauncherImportForTests());
+ afterEach(() => vi.unstubAllGlobals());
+
+ it("shows the status, opens the Verse and a quick duel", async () => {
+ const fetchMock = respond({
+ "GET /api/verse/status": stopped,
+ "POST /api/verse/show": running,
+ "POST /api/verse/settings/import": { imported: [] },
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ render(<VerseLauncherCard />);
+ await screen.findByText("Ready to start.");
+ fireEvent.click(screen.getByText("Quick duel"));
+ await screen.findByText(/Running · on screen/);
+ const show = fetchMock.mock.calls.find(([u, i]) => String(u) === "/api/verse/show" && i?.method === "POST");
+ expect(JSON.parse(String(show?.[1]?.body)).reason).toBe("quick_start_duel");
+ expect(screen.getByText("Close")).toBeTruthy();
+ });
+
+ it("re-reads on a VerseStatusChanged and offers a restart after a crash loop", async () => {
+ let body: unknown = stopped;
+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
+ if (String(input) === "/api/verse/status") return new Response(JSON.stringify(body));
+ return new Response(JSON.stringify({ imported: [] }));
+ }));
+ render(<VerseLauncherCard />);
+ await screen.findByText("Ready to start.");
+ body = { ...stopped, status: "crashed", crash_report: "C:/data/verse/crashes/1" };
+ act(() => { window.dispatchEvent(new CustomEvent(VERSE_STATUS_EVENT)); });
+ await screen.findByText("The Verse stopped after repeated crashes.");
+ expect(screen.getByText("Start again")).toBeTruthy();
+ });
+
+ it("says so on a machine that cannot run it", async () => {
+ vi.stubGlobal("fetch", respond({ "GET /api/verse/status": { ...stopped, status: "unsupported" }, "POST /api/verse/settings/import": { imported: [] } }));
+ render(<VerseLauncherCard />);
+ await waitFor(() => expect(screen.getByTestId("verse-launcher-status").textContent).toMatch(/graphics card/));
+ expect(screen.queryByText("Open the Verse")).toBeNull();
+ });
+});
+
+describe("handleVerseOpen", () => {
+ it("opens a pane maximised in the IDE, with its changes view on request", () => {
+ const requestPane = vi.fn();
+ useIdeChatStore.setState({ requestPane } as never);
+ useEventStore.setState({ solo: false } as never);
+ expect(handleVerseOpen({ target: "pane", workspace_id: "ws_91", name: "T1", open: "changes" })).toBe(true);
+ expect(useEventStore.getState().activeSection).toBe("agentic-ide");
+ expect(requestPane).toHaveBeenCalledWith("ws_91", "T1", { maximize: true, open: "changes" });
+ });
+
+ it("opens the agents section and names the group", () => {
+ useEventStore.setState({ solo: false } as never);
+ const seen: unknown[] = [];
+ const on = (e: Event) => seen.push((e as CustomEvent).detail);
+ window.addEventListener(VERSE_OPEN_GROUP_EVENT, on);
+ expect(handleVerseOpen({ target: "group", group_id: "grp_a" })).toBe(true);
+ window.removeEventListener(VERSE_OPEN_GROUP_EVENT, on);
+ expect(useEventStore.getState().activeSection).toBe("agents");
+ expect(seen).toEqual([{ groupId: "grp_a" }]);
+ });
+
+ it("ignores unknown targets and detached windows", () => {
+ expect(handleVerseOpen({ target: "bogus" }, false)).toBe(false);
+ expect(handleVerseOpen({ target: "ide" }, true)).toBe(false);
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/verseHost/__tests__/verseInstall.test.tsx b/dodaios/ui/web/frontend/src/components/verseHost/__tests__/verseInstall.test.tsx
new file mode 100644
index 0000000000..7c4baf0d30
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/verseHost/__tests__/verseInstall.test.tsx
@@ -0,0 +1,119 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { resetLauncherImportForTests, VerseLauncherCard } from "../VerseLauncherCard";
+import { VerseSettingsGroup } from "../VerseSettingsGroup";
+import { formatBytes, parseInstall } from "../verseHostApi";
+
+const notInstalled = { status: "not_installed", state: null, pid: null, vram_mb: null, fps: null, crash_report: null };
+const stopped = { ...notInstalled, status: "stopped" };
+const idle = {
+ state: "idle", done_bytes: 0, total_bytes: 0, version: "5.0.0", installed_version: null,
+ download_bytes: 7_400_000_000, install_bytes: 10_300_000_000, error: null, bytes_per_s: null,
+};
+
+type Handler = (init?: RequestInit) => unknown;
+
+function server(routes: Record<string, Handler>) {
+ return vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const key = `${init?.method ?? "GET"} ${String(input)}`;
+ const handler = routes[key];
+ if (!handler) return new Response("{}", { status: 404 });
+ return new Response(JSON.stringify(handler(init)), { status: 200, headers: { "Content-Type": "application/json" } });
+ });
+}
+
+describe("install helpers", () => {
+ it("formats sizes and reads an unknown state as unavailable", () => {
+ expect(formatBytes(7_400_000_000)).toBe("7.4 GB");
+ expect(formatBytes(820_000_000)).toBe("820 MB");
+ expect(parseInstall({ state: "weird" }).state).toBe("unavailable");
+ expect(parseInstall(idle)).toEqual(idle);
+ });
+});
+
+describe("launcher card download", () => {
+ beforeEach(() => resetLauncherImportForTests());
+ afterEach(() => vi.unstubAllGlobals());
+
+ it("shows the size, downloads with progress and cancel, then hands back to the card", async () => {
+ let status: unknown = notInstalled;
+ let progress: Record<string, unknown> = idle;
+ let finish = false;
+ const fetchMock = server({
+ "GET /api/verse/status": () => status,
+ "POST /api/verse/settings/import": () => ({ imported: [] }),
+ "GET /api/verse/install/progress": () => progress,
+ "POST /api/verse/install": () => {
+ progress = finish
+ ? { ...idle, state: "installed", installed_version: "5.0.0" }
+ : { ...idle, state: "downloading", done_bytes: 1_850_000_000, total_bytes: 7_400_000_000 };
+ return progress;
+ },
+ "DELETE /api/verse/install": () => {
+ progress = { ...idle, state: "cancelled", done_bytes: 1_850_000_000, total_bytes: 7_400_000_000 };
+ return { cancelled: true, removed: false, ...progress };
+ },
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ render(<VerseLauncherCard />);
+ expect((await screen.findByTestId("verse-install-size")).textContent).toContain("7.4 GB");
+ fireEvent.click(screen.getByText("Download the Verse"));
+ expect((await screen.findByTestId("verse-install-progress")).textContent).toBe("Downloading… 1.9 GB of 7.4 GB");
+ expect(screen.getByRole("progressbar").getAttribute("aria-valuenow")).toBe("25");
+ fireEvent.click(screen.getByText("Cancel"));
+ await screen.findByText("Continue the download");
+ expect(fetchMock.mock.calls.some(([u, i]) => String(u) === "/api/verse/install" && i?.method === "DELETE")).toBe(true);
+
+ finish = true;
+ status = stopped;
+ fireEvent.click(screen.getByText("Continue the download"));
+ await screen.findByText("Ready to start.");
+ expect(screen.queryByTestId("verse-install")).toBeNull();
+ });
+
+ it("says when no download is published yet", async () => {
+ vi.stubGlobal("fetch", server({
+ "GET /api/verse/status": () => notInstalled,
+ "POST /api/verse/settings/import": () => ({ imported: [] }),
+ "GET /api/verse/install/progress": () => ({ ...idle, state: "unavailable", version: null, download_bytes: null }),
+ }));
+ render(<VerseLauncherCard />);
+ await screen.findByTestId("verse-install-unavailable");
+ expect(screen.queryByText("Download the Verse")).toBeNull();
+ });
+});
+
+describe("Settings: Remove the Verse", () => {
+ afterEach(() => vi.unstubAllGlobals());
+
+ it("removes an installed Verse after a confirm", async () => {
+ let progress: Record<string, unknown> = { ...idle, installed_version: "5.0.0" };
+ const fetchMock = server({
+ "GET /api/verse/flags": () => ({ unreal_preview: false, dev_bridge: false }),
+ "GET /api/verse/install/progress": () => progress,
+ "DELETE /api/verse/install": () => {
+ progress = { ...idle };
+ return { cancelled: false, removed: true, ...progress };
+ },
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ render(<VerseSettingsGroup />);
+ await screen.findByText(/Installed, version 5.0.0 · 10.3 GB/);
+ fireEvent.click(screen.getByRole("button", { name: "Remove the Verse" }));
+ const confirm = await screen.findByTestId("verse-settings-confirm");
+ fireEvent.click(confirm.querySelector("button:last-child") as HTMLButtonElement);
+ await screen.findByText("Not installed. Download it from the Verse view.");
+ expect(fetchMock.mock.calls.filter(([, i]) => i?.method === "DELETE")).toHaveLength(1);
+ });
+
+ it("stays hidden with no Verse installed and the preview off", async () => {
+ const fetchMock = server({
+ "GET /api/verse/flags": () => ({ unreal_preview: false }),
+ "GET /api/verse/install/progress": () => idle,
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ const { container } = render(<VerseSettingsGroup />);
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+ expect(container.textContent).toBe("");
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/verseHost/openRequest.ts b/dodaios/ui/web/frontend/src/components/verseHost/openRequest.ts
new file mode 100644
index 0000000000..4ff5ca3bdc
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/verseHost/openRequest.ts
@@ -0,0 +1,80 @@
+/**
+ * `VerseOpenRequested` (bridge contract 11 and 14): the Unreal Verse asked the
+ * app to open one of its views. Each target runs the code the web Verse runs
+ * for the same click, so both Verses open the same thing.
+ *
+ * | target | opens |
+ * |-------------|-----------------------------------------------------------|
+ * | `pane` | the IDE on that pane, maximised (`open: "changes"`: its changes view) |
+ * | `agent` | the agent's card in the Agents section |
+ * | `agents` | the Agents section |
+ * | `group` | the Agents section; `dodaios:verse-open-group` names the group |
+ * | `simulator` | the Agents section; `dodaios:verse-open-simulator` names the programme |
+ * | `ide` | the IDE section without a pane |
+ */
+import { useEventStore } from "@/store/events";
+import { useIdeChatStore } from "@/store/ideChat";
+import { useIdeSidePanelStore } from "@/store/ideSidePanel";
+import { openAgent } from "@/views/society/agentNavigation";
+
+export interface VerseOpenPayload {
+ target?: string;
+ workspace_id?: string;
+ name?: string;
+ focus?: boolean;
+ open?: string;
+ agent_id?: string;
+ group_id?: string;
+ programme?: string;
+}
+
+/** The socket forwarded a `VerseStatusChanged`; the launcher card re-reads its status. */
+export const VERSE_STATUS_EVENT = "dodaios:verse-status";
+export const VERSE_OPEN_GROUP_EVENT = "dodaios:verse-open-group";
+export const VERSE_OPEN_SIMULATOR_EVENT = "dodaios:verse-open-simulator";
+
+function section(id: "agentic-ide" | "agents"): void {
+ const events = useEventStore.getState();
+ if (events.activeSection !== id) events.setActiveSection(id);
+}
+
+/** Returns false for a payload this app does not know how to open. */
+export function handleVerseOpen(payload: VerseOpenPayload, solo = useEventStore.getState().solo): boolean {
+ // A detached window is pinned to its own section; the main window opens it.
+ if (solo) return false;
+ switch (payload.target) {
+ case "pane": {
+ if (!payload.workspace_id || !payload.name) return false;
+ section("agentic-ide");
+ useIdeChatStore.getState().requestPane(payload.workspace_id, payload.name, {
+ maximize: true,
+ ...(payload.open === "changes" ? { open: "changes" as const } : {}),
+ });
+ // A full-view side panel would hide the very pane it just focused.
+ useIdeSidePanelStore.getState().setMaximized(false);
+ return true;
+ }
+ case "ide":
+ section("agentic-ide");
+ return true;
+ case "agent":
+ if (!payload.agent_id) return false;
+ openAgent(payload.agent_id);
+ return true;
+ case "agents":
+ section("agents");
+ return true;
+ case "group":
+ if (!payload.group_id) return false;
+ section("agents");
+ window.dispatchEvent(new CustomEvent(VERSE_OPEN_GROUP_EVENT, { detail: { groupId: payload.group_id } }));
+ return true;
+ case "simulator":
+ if (!payload.programme) return false;
+ section("agents");
+ window.dispatchEvent(new CustomEvent(VERSE_OPEN_SIMULATOR_EVENT, { detail: { programme: payload.programme } }));
+ return true;
+ default:
+ return false;
+ }
+}
diff --git a/dodaios/ui/web/frontend/src/components/verseHost/strings.ts b/dodaios/ui/web/frontend/src/components/verseHost/strings.ts
new file mode 100644
index 0000000000..f968a83688
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/verseHost/strings.ts
@@ -0,0 +1,262 @@
+/**
+ * Words of the Unreal Verse launcher card, in the app's five UI languages.
+ * Kept beside the card while it sits behind the `verse.unreal_preview` flag;
+ * they move into the `ship` locale chunk with the three.js deletion PR.
+ */
+import type { UiLanguage } from "@/i18n";
+
+export type LauncherKey =
+ | "title"
+ | "open"
+ | "quick_duel"
+ | "stop"
+ | "retry"
+ | "starting"
+ | "status.not_installed"
+ | "status.unsupported"
+ | "status.stopped"
+ | "status.running"
+ | "status.crashed"
+ | "state.booting"
+ | "state.visible"
+ | "state.panel"
+ | "state.dormant"
+ | "state.exiting"
+ | "crash_report"
+ | "failed"
+ | "install.download"
+ | "install.size"
+ | "install.hint"
+ | "install.downloading"
+ | "install.verifying"
+ | "install.installing"
+ | "install.cancel"
+ | "install.cancelled"
+ | "install.resume"
+ | "install.failed"
+ | "install.unavailable"
+ | "install.retry"
+ | "settings.title"
+ | "settings.description"
+ | "settings.installed"
+ | "settings.not_installed"
+ | "settings.remove"
+ | "settings.removing"
+ | "settings.confirm"
+ | "settings.unavailable";
+
+type Table = Record<LauncherKey, string>;
+
+const en: Table = {
+ title: "Unreal Verse",
+ open: "Open the Verse",
+ quick_duel: "Quick duel",
+ stop: "Close",
+ retry: "Start again",
+ starting: "Starting…",
+ "status.not_installed": "The Unreal Verse is optional and not installed yet.",
+ "status.unsupported": "This computer's graphics card cannot run the Unreal Verse. Everything else keeps working.",
+ "status.stopped": "Ready to start.",
+ "status.running": "Running",
+ "status.crashed": "The Verse stopped after repeated crashes.",
+ "state.booting": "starting",
+ "state.visible": "on screen",
+ "state.panel": "in the side panel",
+ "state.dormant": "resting in the background",
+ "state.exiting": "closing",
+ crash_report: "Crash report folder",
+ failed: "That did not work: {reason}",
+ "install.download": "Download the Verse",
+ "install.size": "Download size: {size}",
+ "install.hint": "It is not part of the app install; you can remove it again in Settings.",
+ "install.downloading": "Downloading… {done} of {total}",
+ "install.verifying": "Checking the package…",
+ "install.installing": "Installing…",
+ "install.cancel": "Cancel",
+ "install.cancelled": "Download paused. It continues where it stopped.",
+ "install.resume": "Continue the download",
+ "install.failed": "The download did not work: {reason}",
+ "install.unavailable": "The Verse download is not available yet.",
+ "install.retry": "Try again",
+ "settings.title": "Unreal Verse",
+ "settings.description": "The optional 3D Verse is downloaded separately and can be removed at any time. The classic Verse stays.",
+ "settings.installed": "Installed, version {version}",
+ "settings.not_installed": "Not installed. Download it from the Verse view.",
+ "settings.remove": "Remove the Verse",
+ "settings.removing": "Removing…",
+ "settings.confirm": "Remove the Verse from this computer? You can download it again later.",
+ "settings.unavailable": "The Verse status could not be read.",
+};
+
+const de: Table = {
+ title: "Unreal Verse", // i18n-allow
+ open: "Verse öffnen", // i18n-allow
+ quick_duel: "Schnelles Duell", // i18n-allow
+ stop: "Schließen", // i18n-allow
+ retry: "Neu starten", // i18n-allow
+ starting: "Startet…", // i18n-allow
+ "status.not_installed": "Das Unreal Verse ist optional und noch nicht installiert.", // i18n-allow
+ "status.unsupported": "Die Grafikkarte dieses Computers kann das Unreal Verse nicht ausführen. Alles andere funktioniert weiter.", // i18n-allow
+ "status.stopped": "Bereit zum Start.", // i18n-allow
+ "status.running": "Läuft", // i18n-allow
+ "status.crashed": "Das Verse wurde nach wiederholten Abstürzen angehalten.", // i18n-allow
+ "state.booting": "startet", // i18n-allow
+ "state.visible": "im Bild", // i18n-allow
+ "state.panel": "im Seitenpanel", // i18n-allow
+ "state.dormant": "ruht im Hintergrund", // i18n-allow
+ "state.exiting": "wird geschlossen", // i18n-allow
+ crash_report: "Ordner mit dem Absturzbericht", // i18n-allow
+ failed: "Das hat nicht geklappt: {reason}", // i18n-allow
+ "install.download": "Verse herunterladen", // i18n-allow
+ "install.size": "Downloadgröße: {size}", // i18n-allow
+ "install.hint": "Es gehört nicht zur App-Installation; in den Einstellungen kannst du es wieder entfernen.", // i18n-allow
+ "install.downloading": "Lädt herunter… {done} von {total}", // i18n-allow
+ "install.verifying": "Paket wird geprüft…", // i18n-allow
+ "install.installing": "Wird installiert…", // i18n-allow
+ "install.cancel": "Abbrechen", // i18n-allow
+ "install.cancelled": "Download pausiert. Er geht dort weiter, wo er aufgehört hat.", // i18n-allow
+ "install.resume": "Download fortsetzen", // i18n-allow
+ "install.failed": "Der Download hat nicht geklappt: {reason}", // i18n-allow
+ "install.unavailable": "Der Verse-Download ist noch nicht verfügbar.", // i18n-allow
+ "install.retry": "Noch einmal versuchen", // i18n-allow
+ "settings.title": "Unreal Verse", // i18n-allow
+ "settings.description": "Das optionale 3D-Verse wird separat heruntergeladen und lässt sich jederzeit entfernen. Das klassische Verse bleibt.", // i18n-allow
+ "settings.installed": "Installiert, Version {version}", // i18n-allow
+ "settings.not_installed": "Nicht installiert. Du kannst es in der Verse-Ansicht herunterladen.", // i18n-allow
+ "settings.remove": "Verse entfernen", // i18n-allow
+ "settings.removing": "Wird entfernt…", // i18n-allow
+ "settings.confirm": "Das Verse von diesem Computer entfernen? Du kannst es später wieder herunterladen.", // i18n-allow
+ "settings.unavailable": "Der Verse-Status konnte nicht gelesen werden.", // i18n-allow
+};
+
+const es: Table = {
+ title: "Unreal Verse",
+ open: "Abrir el Verse",
+ quick_duel: "Duelo rápido",
+ stop: "Cerrar",
+ retry: "Iniciar de nuevo",
+ starting: "Iniciando…",
+ "status.not_installed": "El Unreal Verse es opcional y aún no está instalado.",
+ "status.unsupported": "La tarjeta gráfica de este ordenador no puede ejecutar el Unreal Verse. Todo lo demás sigue funcionando.",
+ "status.stopped": "Listo para iniciar.",
+ "status.running": "En marcha",
+ "status.crashed": "El Verse se detuvo tras varios fallos seguidos.",
+ "state.booting": "iniciando",
+ "state.visible": "en pantalla",
+ "state.panel": "en el panel lateral",
+ "state.dormant": "en reposo en segundo plano",
+ "state.exiting": "cerrando",
+ crash_report: "Carpeta del informe de fallos",
+ failed: "No ha funcionado: {reason}",
+ "install.download": "Descargar el Verse",
+ "install.size": "Tamaño de la descarga: {size}",
+ "install.hint": "No forma parte de la instalación de la app; puedes quitarlo en Ajustes.",
+ "install.downloading": "Descargando… {done} de {total}",
+ "install.verifying": "Comprobando el paquete…",
+ "install.installing": "Instalando…",
+ "install.cancel": "Cancelar",
+ "install.cancelled": "Descarga en pausa. Continuará donde se quedó.",
+ "install.resume": "Continuar la descarga",
+ "install.failed": "La descarga no ha funcionado: {reason}",
+ "install.unavailable": "La descarga del Verse aún no está disponible.",
+ "install.retry": "Intentar de nuevo",
+ "settings.title": "Unreal Verse",
+ "settings.description": "El Verse 3D opcional se descarga por separado y se puede quitar en cualquier momento. El Verse clásico se queda.",
+ "settings.installed": "Instalado, versión {version}",
+ "settings.not_installed": "No instalado. Descárgalo desde la vista del Verse.",
+ "settings.remove": "Quitar el Verse",
+ "settings.removing": "Quitando…",
+ "settings.confirm": "¿Quitar el Verse de este ordenador? Puedes volver a descargarlo más tarde.",
+ "settings.unavailable": "No se pudo leer el estado del Verse.",
+};
+
+const pt: Table = {
+ title: "Unreal Verse",
+ open: "Abrir o Verse",
+ quick_duel: "Duelo rápido",
+ stop: "Fechar",
+ retry: "Iniciar de novo",
+ starting: "Iniciando…",
+ "status.not_installed": "O Unreal Verse é opcional e ainda não está instalado.",
+ "status.unsupported": "A placa de vídeo deste computador não consegue executar o Unreal Verse. Todo o resto continua funcionando.",
+ "status.stopped": "Pronto para iniciar.",
+ "status.running": "Em execução",
+ "status.crashed": "O Verse parou após falhas repetidas.",
+ "state.booting": "iniciando",
+ "state.visible": "na tela",
+ "state.panel": "no painel lateral",
+ "state.dormant": "em repouso em segundo plano",
+ "state.exiting": "fechando",
+ crash_report: "Pasta do relatório de falha",
+ failed: "Não funcionou: {reason}",
+ "install.download": "Baixar o Verse",
+ "install.size": "Tamanho do download: {size}",
+ "install.hint": "Ele não faz parte da instalação do app; você pode removê-lo nas Configurações.",
+ "install.downloading": "Baixando… {done} de {total}",
+ "install.verifying": "Verificando o pacote…",
+ "install.installing": "Instalando…",
+ "install.cancel": "Cancelar",
+ "install.cancelled": "Download pausado. Ele continua de onde parou.",
+ "install.resume": "Continuar o download",
+ "install.failed": "O download não funcionou: {reason}",
+ "install.unavailable": "O download do Verse ainda não está disponível.",
+ "install.retry": "Tentar de novo",
+ "settings.title": "Unreal Verse",
+ "settings.description": "O Verse 3D opcional é baixado separadamente e pode ser removido a qualquer momento. O Verse clássico continua.",
+ "settings.installed": "Instalado, versão {version}",
+ "settings.not_installed": "Não instalado. Baixe-o na tela do Verse.",
+ "settings.remove": "Remover o Verse",
+ "settings.removing": "Removendo…",
+ "settings.confirm": "Remover o Verse deste computador? Você pode baixá-lo de novo depois.",
+ "settings.unavailable": "Não foi possível ler o status do Verse.",
+};
+
+const zh: Table = {
+ title: "Unreal Verse",
+ open: "打开 Verse",
+ quick_duel: "快速对决",
+ stop: "关闭",
+ retry: "重新启动",
+ starting: "正在启动…",
+ "status.not_installed": "Unreal Verse 是可选组件,尚未安装。",
+ "status.unsupported": "此电脑的显卡无法运行 Unreal Verse。其他功能照常可用。",
+ "status.stopped": "可以启动。",
+ "status.running": "运行中",
+ "status.crashed": "Verse 多次崩溃后已停止。",
+ "state.booting": "正在启动",
+ "state.visible": "显示中",
+ "state.panel": "在侧边面板中",
+ "state.dormant": "在后台休眠",
+ "state.exiting": "正在关闭",
+ crash_report: "崩溃报告文件夹",
+ failed: "操作失败:{reason}",
+ "install.download": "下载 Verse",
+ "install.size": "下载大小:{size}",
+ "install.hint": "它不包含在应用安装中;可在设置中再次移除。",
+ "install.downloading": "正在下载… {done} / {total}",
+ "install.verifying": "正在校验安装包…",
+ "install.installing": "正在安装…",
+ "install.cancel": "取消",
+ "install.cancelled": "下载已暂停,会从中断处继续。",
+ "install.resume": "继续下载",
+ "install.failed": "下载失败:{reason}",
+ "install.unavailable": "Verse 下载暂不可用。",
+ "install.retry": "重试",
+ "settings.title": "Unreal Verse",
+ "settings.description": "可选的 3D Verse 需单独下载,可随时移除。经典 Verse 保持不变。",
+ "settings.installed": "已安装,版本 {version}",
+ "settings.not_installed": "未安装。可在 Verse 视图中下载。",
+ "settings.remove": "移除 Verse",
+ "settings.removing": "正在移除…",
+ "settings.confirm": "要从此电脑移除 Verse 吗?之后可以重新下载。",
+ "settings.unavailable": "无法读取 Verse 状态。",
+};
+
+export const LAUNCHER_STRINGS: Readonly<Record<UiLanguage, Table>> = { en, de, es, pt, zh };
+
+export function launcherText(lang: UiLanguage, key: LauncherKey, vars: Record<string, string> = {}): string {
+ const table = LAUNCHER_STRINGS[lang] ?? en;
+ let text = table[key] ?? en[key];
+ for (const [name, value] of Object.entries(vars)) text = text.split(`{${name}}`).join(value);
+ return text;
+}
diff --git a/dodaios/ui/web/frontend/src/components/verseHost/verseHostApi.ts b/dodaios/ui/web/frontend/src/components/verseHost/verseHostApi.ts
new file mode 100644
index 0000000000..dd3d294639
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/verseHost/verseHostApi.ts
@@ -0,0 +1,179 @@
+/**
+ * The Unreal Verse host's REST surface (`dodaios/ui/web/verse_routes.py`).
+ * `GET /api/verse/status` answers `{status, state, pid, vram_mb, fps, crash_report}`
+ * (architecture 1.1); the launcher card reads nothing else.
+ */
+
+export type VerseHostStatus = "not_installed" | "unsupported" | "stopped" | "running" | "crashed";
+export type VerseLifecycle = "booting" | "visible" | "panel" | "dormant" | "exiting";
+
+export interface VerseStatus {
+ status: VerseHostStatus;
+ state: VerseLifecycle | null;
+ pid: number | null;
+ vram_mb: number | null;
+ fps: number | null;
+ crash_report: string | null;
+}
+
+export type ShowReason = "verse_view" | "quick_start_duel" | "station";
+
+const STATUSES: readonly VerseHostStatus[] = ["not_installed", "unsupported", "stopped", "running", "crashed"];
+
+/** A status body as the backend sends it; an unknown value reads as `stopped`. */
+export function parseStatus(body: unknown): VerseStatus {
+ const raw = (body ?? {}) as Record<string, unknown>;
+ const status = STATUSES.includes(raw.status as VerseHostStatus) ? (raw.status as VerseHostStatus) : "stopped";
+ const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : null);
+ return {
+ status,
+ state: typeof raw.state === "string" ? (raw.state as VerseLifecycle) : null,
+ pid: num(raw.pid),
+ vram_mb: num(raw.vram_mb),
+ fps: num(raw.fps),
+ crash_report: typeof raw.crash_report === "string" ? raw.crash_report : null,
+ };
+}
+
+async function call(path: string, init?: RequestInit): Promise<unknown> {
+ const res = await fetch(path, init);
+ if (!res.ok) throw new Error(`${path} answered ${res.status}`);
+ return res.json();
+}
+
+function post(path: string, body?: unknown): Promise<unknown> {
+ return call(path, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body ?? {}),
+ });
+}
+
+export async function fetchVerseStatus(): Promise<VerseStatus> {
+ return parseStatus(await call("/api/verse/status"));
+}
+
+/** The monitor the app window is on, as `lifecycle.show` wants it. */
+export function currentMonitor(): { x: number; y: number; w: number; h: number; dpi: number } {
+ const s = window.screen as Screen & { availLeft?: number; availTop?: number };
+ return {
+ x: Math.round(s.availLeft ?? 0),
+ y: Math.round(s.availTop ?? 0),
+ w: Math.max(1, Math.round(s.width || 1920)),
+ h: Math.max(1, Math.round(s.height || 1080)),
+ dpi: Math.round(96 * (window.devicePixelRatio || 1)),
+ };
+}
+
+export async function showVerse(reason: ShowReason = "verse_view"): Promise<VerseStatus> {
+ return parseStatus(await post("/api/verse/show", { reason, monitor: currentMonitor() }));
+}
+
+export async function stopVerse(): Promise<VerseStatus> {
+ return parseStatus(await post("/api/verse/stop"));
+}
+
+export async function launchVerse(): Promise<VerseStatus> {
+ return parseStatus(await post("/api/verse/launch"));
+}
+
+export async function fetchVerseFlags(): Promise<{ unreal_preview: boolean }> {
+ const body = (await call("/api/verse/flags")) as { unreal_preview?: unknown };
+ return { unreal_preview: body.unreal_preview === true };
+}
+
+/** Browser-stored values of the web Verse, posted once (bridge contract 14). */
+export const IMPORT_KEYS = [
+ "dodaios.verse.view.v1",
+ "dodaios.verse.uniform.v1",
+ "jarvis.verse.level.sound.v1",
+ "jarvis.verse.levels.seen.v1",
+ "jarvis.office.arcade.asteroids.best",
+] as const;
+
+export async function importBrowserSettings(storage: Pick<Storage, "getItem"> = window.localStorage): Promise<string[]> {
+ const values: Record<string, string> = {};
+ for (const key of IMPORT_KEYS) {
+ try {
+ const value = storage.getItem(key);
+ if (value !== null) values[key] = value;
+ } catch {
+ // Storage blocked: nothing to import.
+ }
+ }
+ const body = (await post("/api/verse/settings/import", { values })) as { imported?: unknown };
+ return Array.isArray(body.imported) ? body.imported.filter((k): k is string => typeof k === "string") : [];
+}
+
+/**
+ * The optional Verse download (README Delivery): the app install never carries
+ * the Verse. `GET /api/verse/install/progress`, `POST /api/verse/install`,
+ * `DELETE /api/verse/install` (cancels a running download, else removes it).
+ */
+export type InstallState =
+ | "idle"
+ | "downloading"
+ | "verifying"
+ | "installing"
+ | "installed"
+ | "cancelled"
+ | "failed"
+ | "removing"
+ | "unavailable";
+
+export interface InstallProgress {
+ state: InstallState;
+ done_bytes: number;
+ total_bytes: number;
+ version: string | null;
+ installed_version: string | null;
+ download_bytes: number | null;
+ install_bytes: number | null;
+ error: string | null;
+ bytes_per_s: number | null;
+}
+
+const INSTALL_STATES: readonly InstallState[] = [
+ "idle", "downloading", "verifying", "installing", "installed", "cancelled", "failed", "removing", "unavailable",
+];
+
+export function parseInstall(body: unknown): InstallProgress {
+ const raw = (body ?? {}) as Record<string, unknown>;
+ const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : null);
+ const str = (v: unknown) => (typeof v === "string" && v ? v : null);
+ return {
+ state: INSTALL_STATES.includes(raw.state as InstallState) ? (raw.state as InstallState) : "unavailable",
+ done_bytes: num(raw.done_bytes) ?? 0,
+ total_bytes: num(raw.total_bytes) ?? 0,
+ version: str(raw.version),
+ installed_version: str(raw.installed_version),
+ download_bytes: num(raw.download_bytes),
+ install_bytes: num(raw.install_bytes),
+ error: str(raw.error),
+ bytes_per_s: num(raw.bytes_per_s),
+ };
+}
+
+export function isInstalling(p: InstallProgress | null): boolean {
+ return !!p && (p.state === "downloading" || p.state === "verifying" || p.state === "installing");
+}
+
+export async function fetchInstallProgress(): Promise<InstallProgress> {
+ return parseInstall(await call("/api/verse/install/progress"));
+}
+
+export async function startInstall(): Promise<InstallProgress> {
+ return parseInstall(await post("/api/verse/install"));
+}
+
+/** Cancel the running download, or remove the installed Verse when none runs. */
+export async function cancelOrRemoveInstall(): Promise<InstallProgress> {
+ return parseInstall(await call("/api/verse/install", { method: "DELETE" }));
+}
+
+/** `7.4 GB`, `820 MB`: decimal units, one decimal from GB up. */
+export function formatBytes(bytes: number): string {
+ if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB`;
+ if (bytes >= 1e6) return `${Math.round(bytes / 1e6)} MB`;
+ return `${Math.max(0, Math.round(bytes / 1e3))} KB`;
+}
diff --git a/dodaios/ui/web/frontend/src/hooks/useWebSocket.ts b/dodaios/ui/web/frontend/src/hooks/useWebSocket.ts
index 0bee50ebfb..36af20b05f 100644
--- a/dodaios/ui/web/frontend/src/hooks/useWebSocket.ts
+++ b/dodaios/ui/web/frontend/src/hooks/useWebSocket.ts
@@ -40,6 +40,7 @@ import { petKeys } from "@/hooks/usePets";
import { focusChatComposer, startNewTextChat } from "@/lib/newChat";
import { SPEAKER_MUTE_EVENT } from "@/lib/speakerMute";
import { onAgentAttention, seedAgentAttention } from "@/components/society/attention/attentionBus";
+import { handleVerseOpen, VERSE_STATUS_EVENT, type VerseOpenPayload } from "@/components/verseHost/openRequest";
let singleton: WSClient | null = null;
@@ -622,6 +623,17 @@ export function useWebSocket(): void {
}
}
+ if (env.event_name === "VerseOpenRequested" || env.event_name === "VerseStatusChanged") {
+ // The Unreal Verse (verse.bridge/1): a station asked the app to open
+ // a view, or the Verse host changed state. Opening runs the same
+ // code the web Verse runs; the launcher card re-reads its status.
+ if (env.event_name === "VerseOpenRequested") {
+ handleVerseOpen(env.payload as VerseOpenPayload);
+ } else {
+ window.dispatchEvent(new CustomEvent(VERSE_STATUS_EVENT, { detail: env.payload }));
+ }
+ }
+
if (env.event_name === "AgenticIdePaneActivity") {
// One pane's agent changed state — started, stopped, asked, died.
// The payload is the activity half of a `/panes` row, so the session
diff --git a/dodaios/ui/web/frontend/src/views/DodaiosAgentsView.tsx b/dodaios/ui/web/frontend/src/views/DodaiosAgentsView.tsx
index 82824c5fa4..044f8d8167 100644
--- a/dodaios/ui/web/frontend/src/views/DodaiosAgentsView.tsx
+++ b/dodaios/ui/web/frontend/src/views/DodaiosAgentsView.tsx
@@ -7,6 +7,7 @@ import { useLocaleChunk } from "@/i18n";
import type { PlaceId } from "@/components/society/world/islandLayout";
import { VerseStage } from "@/components/society/verse/VerseStage";
import { VerseLoadingScreen } from "@/components/society/verse/VerseLoadingScreen";
+import { VerseHostMount } from "@/components/verseHost/VerseHostMount";
export interface DodaiosAgentsViewProps {
onSelectAgent?: (agentId: string | null) => void;
@@ -21,8 +22,10 @@ export function DodaiosAgentsView({ onSelectAgent, onOpenAgents, onCreateAgent,
const ready = useLocaleChunk("society");
if (!ready) return <div className="relative h-full"><VerseLoadingScreen /></div>;
return (
- <div className="h-full min-h-0">
+ <div className="relative h-full min-h-0">
<VerseStage active={active} onOpenLedger={onOpenAgents} onSelectAgent={onSelectAgent} onCreateAgent={onCreateAgent} onOpenGroup={onOpenGroup} />
+ {/* The Unreal Verse launcher, behind verse.unreal_preview until the deletion PR. */}
+ <VerseHostMount />
</div>
);
}
diff --git a/dodaios/ui/web/frontend/src/views/SettingsView.tsx b/dodaios/ui/web/frontend/src/views/SettingsView.tsx
index b50ff9560b..83f753bf0e 100644
--- a/dodaios/ui/web/frontend/src/views/SettingsView.tsx
+++ b/dodaios/ui/web/frontend/src/views/SettingsView.tsx
@@ -11,6 +11,7 @@ import { VolumeGroup } from "@/views/settings/VolumeGroup";
import { AudioDevicesGroup } from "@/views/settings/AudioDevicesGroup";
import { SystemPromptGroup } from "@/views/settings/SystemPromptGroup";
import { SelfBuildGroup } from "@/views/settings/SelfBuildGroup";
+import { VerseSettingsGroup } from "@/components/verseHost/VerseSettingsGroup";
import { SettingsGroupBoundary } from "@/views/settings/SettingsGroupBoundary";
import { settingsInputCls } from "@/views/settings/SettingsBlock";
import {
@@ -140,6 +141,7 @@ const SECTIONS: readonly { id: string; render: () => React.ReactNode }[] = [
{ id: "self-build", render: () => <SelfBuildGroup /> },
{ id: "music", render: () => <MusicGroup /> },
{ id: "overlay-taskbar", render: () => <OverlayTaskbarGroup /> },
+ { id: "verse", render: () => <VerseSettingsGroup /> },
];
/** "Autopilot toasts" — the one row of the former "More" group. */
diff --git a/dodaios/ui/web/server.py b/dodaios/ui/web/server.py
index c76c026db8..9a6b1d5cab 100644
--- a/dodaios/ui/web/server.py
+++ b/dodaios/ui/web/server.py
@@ -849,6 +849,11 @@ class WebServer:
)
app.state.progression = self._progression
app.include_router(progression_router)
+ # The Unreal Verse host (dodaios/verse_host): status, launch and the
+ # verse.bridge/1 socket. Nothing starts until the first show.
+ from .verse_routes import router as verse_router
+
+ app.include_router(verse_router)
# Default: no recorder wired up — _init_session_stack() in start()
# sets this once it succeeds.
app.state.session_store = None
@@ -2945,6 +2950,15 @@ class WebServer:
_boot_mark("uvicorn_serve")
+ # The Unreal Verse host launches nothing at start; with the dev_bridge
+ # flag on it renews the editor's discovery file (contract 1).
+ try:
+ from .verse_routes import start_verse_host
+
+ await start_verse_host(self.app, resolved_port)
+ except Exception: # noqa: BLE001 -- the Verse never blocks the app start
+ logger.opt(exception=True).warning("Verse host start step failed")
+
# Voice-ready UI backstop (permanent "starting up" bug): the frontend's
# startup banner + top-left "STARTING…" status clear ONLY on a
# VoiceBootStatus(ready=True). If the speech pipeline crashes during
@@ -4236,6 +4250,15 @@ class WebServer:
except Exception:
logger.opt(exception=True).warning("Appshot helpers failed to stop")
+ # Ask a running Verse to save and quit (lifecycle.quit app_quit) and
+ # delete the dev discovery file that holds a token.
+ try:
+ from .verse_routes import stop_verse_host
+
+ await stop_verse_host(self.app)
+ except Exception: # noqa: BLE001 -- independent resources must still shut down
+ logger.opt(exception=True).warning("Verse host stop failed")
+
if runtime_refs.get_web_app() is self.app:
runtime_refs.set_web_app(None)
# A cancelled setup waiter cannot stop its worker thread. Join it
diff --git a/dodaios/ui/web/surface_security.py b/dodaios/ui/web/surface_security.py
index 850eee2a1f..deda035db3 100644
--- a/dodaios/ui/web/surface_security.py
+++ b/dodaios/ui/web/surface_security.py
@@ -1177,6 +1177,11 @@ class SurfaceSecurity:
if kind == "websocket" and path == "/api/telephony/media":
await self.app(scope, receive, send)
return
+ if kind == "websocket" and path == "/api/verse/bridge":
+ # Verse.exe has no session cookie: the route checks the loopback
+ # peer and the per-launch token of its hello frame instead.
+ await self.app(scope, receive, send)
+ return
if kind == "http":
# Browser preflights do not carry cookies or Authorization. Once
diff --git a/dodaios/ui/web/verse_routes.py b/dodaios/ui/web/verse_routes.py
new file mode 100644
index 0000000000..a1b9fd3dbe
--- /dev/null
+++ b/dodaios/ui/web/verse_routes.py
@@ -0,0 +1,383 @@
+"""Routes of the Unreal Verse host (architecture 1.1, contract bridge-protocol 1 and 14).
+
+REST (the app's own session auth):
+
+* ``GET /api/verse/status`` ``{status, state, pid, vram_mb, fps, crash_report}``
+* ``POST /api/verse/launch`` manual launch (also leaves a crash loop)
+* ``POST /api/verse/show`` ``{reason, monitor?}``: open the Verse view
+* ``POST /api/verse/hide`` ``{reason}``
+* ``POST /api/verse/stop`` quit Verse (``lifecycle.quit``, then by PID)
+* ``POST /api/verse/panel`` IDE side panel visibility / size
+* ``POST /api/verse/gpu`` GPU pressure (``gpu.yield`` / ``gpu.free``)
+* ``POST /api/verse/settings/import`` one-time import of browser-stored settings
+* ``GET/POST /api/verse/flags`` ``unreal_preview`` (the launcher card), ``dev_bridge``
+* ``POST /api/verse/launcher/start`` the shared coding-agent launch sequence
+* ``POST /api/verse/launcher/cancel``
+* ``POST /api/verse/qa`` a ``Verse.QA.*`` command run inside Verse (QA env only)
+* ``POST /api/verse/install`` start the on-demand download (README Delivery)
+* ``DELETE /api/verse/install`` cancel a running download, else remove the Verse
+* ``GET /api/verse/install/progress`` ``{state, done_bytes, total_bytes, version,
+ installed_version, download_bytes, install_bytes, error, bytes_per_s}``
+
+WebSockets (their own auth; exempt from the session cookie check):
+
+* ``WS /api/verse/bridge`` ``verse.bridge/1``: loopback only, ``hello`` + token
+* ``WS /api/verse/signal`` Pixel Streaming signalling (WP20); closes ``1013``
+ until ``dodaios.verse_host.signal`` is installed
+"""
+
+from __future__ import annotations
+
+import asyncio
+import importlib
+import logging
+from pathlib import Path
+from typing import Any, Literal
+
+from fastapi import APIRouter, HTTPException, Request, WebSocket
+from pydantic import BaseModel, Field
+from starlette.websockets import WebSocketDisconnect
+
+from dodaios.verse_host import protocol as P
+from dodaios.verse_host.bridge import TransportClosed
+from dodaios.verse_host.host import VerseHost, get_host
+
+log = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/api/verse", tags=["verse"])
+APP_QUIT_TIMEOUT_S = 6.0
+
+
+def _bound_port(conn: Request | WebSocket) -> int | None:
+ """The port this server's socket is bound to (ASGI ``scope["server"]``).
+
+ Never the Host header: a dev proxy or a forged header must not change the
+ bridge URL the next Verse launch is given.
+ """
+ server = conn.scope.get("server")
+ if isinstance(server, list | tuple) and len(server) == 2 and isinstance(server[1], int):
+ return server[1]
+ return None
+
+
+def _host(request: Request | WebSocket) -> VerseHost:
+ host = get_host(request.app)
+ host.set_port(_bound_port(request))
+ return host
+
+
+async def start_verse_host(app: Any, port: int | None) -> None:
+ """App start: nothing launches; only the dev discovery file is renewed.
+
+ With the ``dev_bridge`` flag already on, an editor run needs a fresh token
+ after every app restart (contract 1, Dev discovery).
+ """
+ from dodaios.core.config import DATA_DIR
+ from dodaios.verse_host.settings_store import SettingsStore
+
+ store = SettingsStore(Path(DATA_DIR) / "verse" / "settings.json")
+ if not store.flag("dev_bridge", "DODAIOS_VERSE_DEV_BRIDGE"):
+ return
+ host = get_host(app)
+ host.set_port(port)
+ host.write_dev_discovery()
+
+
+async def stop_verse_host(app: Any) -> None:
+ """App quit: ``lifecycle.quit {reason: app_quit}`` (contract 12), then drop the dev file."""
+ host: VerseHost | None = getattr(app.state, "verse_host", None)
+ if host is None:
+ return
+ try:
+ if host.install.running:
+ await host.install.cancel()
+ await asyncio.wait_for(host.stop("app_quit"), APP_QUIT_TIMEOUT_S)
+ except Exception: # noqa: BLE001 - shutdown goes on; the job object ends Verse
+ log.warning("verse host: clean quit failed", exc_info=True)
+ finally:
+ host.remove_dev_discovery()
+
+
+class Monitor(BaseModel):
+ x: int = 0
+ y: int = 0
+ w: int = Field(1920, ge=1)
+ h: int = Field(1080, ge=1)
+ dpi: float = Field(96.0, gt=0)
+
+
+class ShowBody(BaseModel):
+ reason: Literal["verse_view", "quick_start_duel", "station"] = "verse_view"
+ monitor: Monitor | None = None
+
+
+class HideBody(BaseModel):
+ reason: Literal["app_focus", "user", "minimised"] = "user"
+
+
+class PanelBody(BaseModel):
+ visible: bool
+ w: int = Field(0, ge=0)
+ h: int = Field(0, ge=0)
+ dpr: float = Field(1.0, gt=0)
+
+
+class GpuBody(BaseModel):
+ busy: bool
+ by: Literal["blender_cook", "local_stt", "local_model", "other"] = "other"
+
+
+class ImportBody(BaseModel):
+ values: dict[str, Any] = Field(default_factory=dict)
+
+
+class FlagsBody(BaseModel):
+ unreal_preview: bool | None = None
+ dev_bridge: bool | None = None
+
+
+class LaunchAgent(BaseModel):
+ agent: str = Field(min_length=1)
+ count: int = Field(1, ge=1, le=8)
+
+
+class LauncherBody(BaseModel):
+ workspace_id: str | None = None
+ agents: list[LaunchAgent] = Field(min_length=1)
+ brief: str = ""
+
+
[email protected]("/status", summary="Whether the Unreal Verse can run and what it is doing")
+def verse_status(request: Request, refresh: bool = False) -> dict[str, Any]:
+ host = _host(request)
+ if refresh:
+ host.check(refresh=True)
+ return host.status()
+
+
[email protected]("/launch", summary="Start the Unreal Verse now (also leaves a crash loop)")
+async def verse_launch(request: Request) -> dict[str, Any]:
+ host = _host(request)
+ if (await host.acheck()).status != "ok":
+ return await host.astatus()
+ await host.supervisor.ensure_running(manual=True)
+ return await host.astatus()
+
+
[email protected]("/show", summary="Open the Unreal Verse view")
+async def verse_show(body: ShowBody, request: Request) -> dict[str, Any]:
+ host = _host(request)
+ monitor = body.monitor.model_dump() if body.monitor is not None else None
+ return await host.show(body.reason, monitor)
+
+
[email protected]("/hide", summary="Hide the Unreal Verse")
+async def verse_hide(body: HideBody, request: Request) -> dict[str, Any]:
+ host = _host(request)
+ await host.hide(body.reason)
+ return await host.astatus()
+
+
[email protected]("/stop", summary="Quit the Unreal Verse")
+async def verse_stop(request: Request) -> dict[str, Any]:
+ return await _host(request).stop("app_quit")
+
+
[email protected]("/panel", summary="The IDE side panel showing the Verse became visible or hidden")
+async def verse_panel(body: PanelBody, request: Request) -> dict[str, Any]:
+ host = _host(request)
+ sent = await host.panel_visibility(body.visible, body.w, body.h, body.dpr)
+ return {"sent": sent, **(await host.astatus())}
+
+
[email protected]("/gpu", summary="Tell the Verse another part of the app needs the GPU")
+async def verse_gpu(body: GpuBody, request: Request) -> dict[str, Any]:
+ return {"sent": await _host(request).gpu_pressure(body.busy, body.by)}
+
+
[email protected]("/settings/import", summary="Import the web Verse's browser-stored settings once")
+async def verse_settings_import(body: ImportBody, request: Request) -> dict[str, Any]:
+ host = _host(request)
+ imported = host.import_browser_settings(body.values)
+ if imported:
+ await host.settings_changed(host.store.settings())
+ return {"imported": imported}
+
+
[email protected]("/settings", summary="The verse.* settings")
+def verse_settings(request: Request) -> dict[str, Any]:
+ return {"settings": _host(request).store.settings()}
+
+
[email protected]("/flags", summary="Feature flags of the Unreal Verse")
+def verse_flags(request: Request) -> dict[str, Any]:
+ store = _host(request).store
+ return {
+ "unreal_preview": store.flag("unreal_preview", "DODAIOS_VERSE_UNREAL_PREVIEW"),
+ "dev_bridge": store.flag("dev_bridge", "DODAIOS_VERSE_DEV_BRIDGE"),
+ }
+
+
[email protected]("/flags", summary="Switch feature flags of the Unreal Verse")
+def verse_set_flags(body: FlagsBody, request: Request) -> dict[str, Any]:
+ host = _host(request)
+ if body.unreal_preview is not None:
+ host.store.set_flag("unreal_preview", body.unreal_preview)
+ if body.dev_bridge is not None:
+ host.store.set_flag("dev_bridge", body.dev_bridge)
+ if body.dev_bridge:
+ host.write_dev_discovery()
+ else:
+ host.remove_dev_discovery()
+ return verse_flags(request)
+
+
+class QaBody(BaseModel):
+ command: str = Field(pattern=r"^Verse\.QA\.[A-Za-z0-9_.]+$")
+ args: list[str] = Field(default_factory=list)
+
+
[email protected]("/qa", summary="Run a Verse.QA.* command inside Verse (DODAIOS_VERSE_QA=1 only)")
+async def verse_qa(body: QaBody, request: Request) -> dict[str, Any]:
+ try:
+ return await _host(request).qa_exec(body.command, body.args)
+ except P.BridgeError as exc:
+ status = 503 if exc.code == "unavailable" else 400
+ raise HTTPException(status_code=status, detail=exc.message) from exc
+ except TimeoutError as exc:
+ raise HTTPException(status_code=504, detail="Verse did not answer.") from exc
+
+
[email protected]("/install/progress", summary="Download size and progress of the optional Verse")
+async def verse_install_progress(request: Request, refresh: bool = False) -> dict[str, Any]:
+ return await _host(request).install.progress(refresh=refresh)
+
+
[email protected]("/install", summary="Download and install the Verse (never part of the app install)")
+async def verse_install(request: Request) -> dict[str, Any]:
+ host = _host(request)
+ cap = await host.acheck()
+ if cap.status == "unsupported" and not cap.gpu.failed:
+ raise HTTPException(status_code=409, detail="This computer cannot run the Verse.")
+ return await host.install.start()
+
+
+ "/install",
+ summary="Cancel the running download, or remove the installed Verse",
+ openapi_extra={"x-jarvis-dangerous": True},
+)
+async def verse_uninstall(request: Request) -> dict[str, Any]:
+ from dodaios.verse_host.install_port import InstallError
+
+ job = _host(request).install
+ if job.running:
+ await job.cancel()
+ return {"cancelled": True, "removed": False, **(await job.progress())}
+ try:
+ progress = await job.remove()
+ except InstallError as exc:
+ raise HTTPException(status_code=500, detail=exc.message) from exc
+ return {"cancelled": False, "removed": True, **progress}
+
+
[email protected]("/launcher/start", summary="Open coding panes and brief them (shared sequence)")
+async def verse_launcher_start(body: LauncherBody, request: Request) -> dict[str, Any]:
+ from dodaios.agentic_ide.launch_sequence import LaunchBusy
+
+ host = _host(request)
+ try:
+ panes = await host.launcher.run(
+ body.workspace_id, [(a.agent, a.count) for a in body.agents], body.brief
+ )
+ except LaunchBusy as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ return {"panes": [{"pane_id": p.pane_id, "submitted": p.submitted} for p in panes]}
+
+
+ "/launcher/cancel",
+ summary="Stop the running launch batch",
+ openapi_extra={"x-jarvis-dangerous": True},
+)
+def verse_launcher_cancel(request: Request) -> dict[str, Any]:
+ return {"stopped": _host(request).launcher.cancel()}
+
+
+# ---------------------------------------------------------------------- WebSockets
+
+
+class StarletteTransport:
+ """:class:`dodaios.verse_host.bridge.Transport` over a Starlette WebSocket."""
+
+ def __init__(self, ws: WebSocket) -> None:
+ self.ws = ws
+ self.closed = False
+
+ async def receive(self) -> str | bytes:
+ if self.closed:
+ raise TransportClosed()
+ try:
+ message = await self.ws.receive()
+ except (WebSocketDisconnect, RuntimeError) as exc:
+ self.closed = True
+ raise TransportClosed() from exc
+ if message.get("type") == "websocket.disconnect":
+ self.closed = True
+ raise TransportClosed()
+ if message.get("bytes") is not None:
+ return message["bytes"]
+ return message.get("text") or ""
+
+ async def send_text(self, text: str) -> None:
+ try:
+ await self.ws.send_text(text)
+ except (WebSocketDisconnect, RuntimeError) as exc:
+ raise TransportClosed() from exc
+
+ async def send_bytes(self, data: bytes) -> None:
+ try:
+ await self.ws.send_bytes(data)
+ except (WebSocketDisconnect, RuntimeError) as exc:
+ raise TransportClosed() from exc
+
+ async def close(self, code: int, reason: str = "") -> None:
+ if self.closed:
+ return
+ self.closed = True
+ try:
+ await self.ws.close(code=code, reason=reason[:120])
+ except (WebSocketDisconnect, RuntimeError): # socket already gone; nothing left to close
+ pass
+
+
+async def verse_bridge(ws: WebSocket) -> None:
+ """``verse.bridge/1``: the peer check runs before the handshake (contract 1)."""
+ host = _host(ws)
+ await ws.accept()
+ peer = ws.client.host if ws.client is not None else None
+ code = await host.hub.serve(StarletteTransport(ws), peer)
+ log.info("verse bridge: connection closed with %s", code)
+
+
+async def verse_signal(ws: WebSocket) -> None:
+ """Pixel Streaming signalling; served by WP20's ``signal`` module once it lands."""
+ await ws.accept()
+ peer = ws.client.host if ws.client is not None else None
+ from dodaios.verse_host.bridge import is_loopback
+
+ if not is_loopback(peer):
+ await ws.close(code=P.CLOSE_PEER, reason="loopback only")
+ return
+ try:
+ signal = importlib.import_module("dodaios.verse_host.signal")
+ except ImportError: # WP20 signalling not installed yet; closes 1013
+ await ws.close(code=P.CLOSE_TRY_LATER, reason="signalling not available")
+ return
+ serve = getattr(signal, "serve", None)
+ if serve is None:
+ await ws.close(code=P.CLOSE_TRY_LATER, reason="signalling not available")
+ return
+ await serve(ws, get_host(ws.app))
diff --git a/dodaios/verse_host/__init__.py b/dodaios/verse_host/__init__.py
new file mode 100644
index 0000000000..871fbecdcf
--- /dev/null
+++ b/dodaios/verse_host/__init__.py
@@ -0,0 +1,10 @@
+"""The verse host: the backend side of the Unreal Verse (``verse.bridge/1``).
+
+``Verse.exe`` is a supervised child of the desktop process. This package
+launches and watches it (:mod:`.supervisor`), checks the machine can run it
+(:mod:`.probe`), serves the one WebSocket it talks to (:mod:`.bridge`) and
+turns backend state and bus events into bridge topics (:mod:`.relays`).
+
+The frozen contract is ``docs/verse/unreal/contracts/bridge-protocol.md``;
+the process model is ``docs/verse/unreal/architecture.md`` section 1.
+"""
diff --git a/dodaios/verse_host/bridge.py b/dodaios/verse_host/bridge.py
new file mode 100644
index 0000000000..7e003fcb4e
--- /dev/null
+++ b/dodaios/verse_host/bridge.py
@@ -0,0 +1,767 @@
+"""The bridge server: the one WebSocket ``Verse.exe`` talks to (BW1, contract 1-3).
+
+Transport-independent: :class:`BridgeHub` serves any :class:`Transport`
+(the Starlette adapter lives in ``dodaios/ui/web/verse_routes.py``; tests
+use an in-memory pair). One hub per app, at most one live session.
+
+Rules implemented here, each from ``contracts/bridge-protocol.md``:
+
+* loopback peers only (``4403``), ``hello`` within 5 s (``4400``), token in
+ constant time (``4401``), protocol list (``4426``), a second authenticated
+ client replaces the first (``4409``), frames over 1 MiB (``1009``);
+* ``ping`` / ``pong``; 5 s without any Verse frame is reported as hung;
+* one ``seq`` counter per connection, strictly increasing; deltas carry
+ ``base`` = the ``seq`` of the last frame of their topic; no replay on
+ reconnect, a fresh snapshot per resubscribed topic;
+* one bounded queue per topic: ``screens`` keeps the newest frame per pane,
+ ``roster``, ``groups``, ``chat_tails``, ``meetings`` coalesce into a fresh
+ snapshot on overflow, events and replies are never dropped;
+* exactly one ``reply`` per command; unknown types are ignored and logged
+ once per type; command rate limits.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import hmac
+import ipaddress
+import itertools
+import logging
+import os
+import secrets
+import time
+from collections import deque
+from collections.abc import Awaitable, Callable, Iterable
+from dataclasses import dataclass, field
+from typing import Any, Protocol
+
+from . import protocol as P
+from .cells_codec import encode as encode_cells
+
+log = logging.getLogger(__name__)
+
+#: Pending feed frames per coalescing topic before they fold into a snapshot.
+COALESCE_LIMIT = 32
+SEND_TIMEOUT_S = 5.0
+
+
+class TransportClosed(Exception):
+ """The peer went away."""
+
+
+class Transport(Protocol):
+ async def receive(self) -> str | bytes: ...
+ async def send_text(self, text: str) -> None: ...
+ async def send_bytes(self, data: bytes) -> None: ...
+ async def close(self, code: int, reason: str = "") -> None: ...
+
+
+Handler = Callable[["BridgeSession", P.Inbound], Awaitable[dict[str, Any] | None]]
+NoticeHandler = Callable[["BridgeSession", P.Inbound], Awaitable[None]]
+
+
+def is_loopback(host: str | None) -> bool:
+ if not host:
+ return False
+ if host == "localhost":
+ return True
+ try:
+ addr = ipaddress.ip_address(host.split("%", 1)[0])
+ except ValueError: # not an IP literal (a host name), so not loopback
+ return False
+ if addr.is_loopback:
+ return True
+ mapped = getattr(addr, "ipv4_mapped", None)
+ return bool(mapped is not None and mapped.is_loopback)
+
+
+def mint_token() -> str:
+ """256 bits, URL-safe base64 without padding (43 characters)."""
+ return secrets.token_urlsafe(32)
+
+
+@dataclass
+class RateLimit:
+ """At most ``count`` calls per ``window_s`` seconds."""
+
+ count: int
+ window_s: float
+ _calls: deque[float] = field(default_factory=deque)
+
+ def allow(self, now: float) -> bool:
+ while self._calls and now - self._calls[0] >= self.window_s:
+ self._calls.popleft()
+ if len(self._calls) >= self.count:
+ return False
+ self._calls.append(now)
+ return True
+
+
+OPEN_COMMANDS = (
+ "pane.open",
+ "agent.open",
+ "ide.focus_terminal",
+ "agents.open_list",
+ "group.open",
+ "simulator.open",
+ "ide.open",
+)
+
+
+def default_rate_limits() -> dict[str, RateLimit]:
+ shared_open = RateLimit(4, 1.0)
+ limits = {name: shared_open for name in OPEN_COMMANDS}
+ limits["agent.create"] = RateLimit(1, 5.0)
+ limits["launcher.start"] = RateLimit(1, 10.0)
+ return limits
+
+
+# ---------------------------------------------------------------------- outbound
+
+
+@dataclass
+class _Out:
+ """One queued server frame. ``data`` may be a callable evaluated at write time."""
+
+ type: str
+ data: Any
+ topic: str | None = None
+ delta: bool = False
+ re: str | None = None
+ key: str | None = None # screens: one slot per pane
+ ref: int | None = None # screens: binary when set
+ feed: bool = False
+ rid: str | None = None # server -> Verse command id
+
+
+class Outbox:
+ """Ordered frames with per-topic back pressure (contract 1, Back pressure)."""
+
+ COALESCING = ("roster", "groups", "chat_tails", "meetings", "companion")
+
+ def __init__(self, limit: int = COALESCE_LIMIT) -> None:
+ self._items: deque[_Out] = deque()
+ self._slots: dict[str, _Out] = {}
+ self._pending: dict[str, int] = {}
+ self._limit = limit
+ self._ready = asyncio.Event()
+ self.snapshot_of: dict[str, Callable[[], Any]] = {}
+ self.dropped = 0
+ self.coalesced = 0
+
+ def __len__(self) -> int:
+ return len(self._items)
+
+ def put(self, item: _Out) -> None:
+ if item.key is not None:
+ existing = self._slots.get(item.key)
+ if existing is not None:
+ # One slot per pane. A newer snapshot replaces whatever is queued; a
+ # newer delta folds its rows into the queued frame (a snapshot is
+ # never downgraded, and an older delta's rows are never lost).
+ if not item.delta:
+ existing.data, existing.delta, existing.type = item.data, item.delta, item.type
+ elif existing.delta:
+ self._merge_deltas(existing, item)
+ else:
+ self._merge_rows(existing, item)
+ self.dropped += 1
+ return
+ self._slots[item.key] = item
+ if item.feed and item.topic in self.COALESCING:
+ count = self._pending.get(item.topic, 0) + 1
+ self._pending[item.topic] = count
+ if count > self._limit and item.topic in self.snapshot_of:
+ self._fold(item.topic)
+ return
+ self._items.append(item)
+ self._ready.set()
+
+ @staticmethod
+ def _merge_rows(snapshot: _Out, delta: _Out) -> None:
+ """A delta queued behind an unsent snapshot of the same pane: fold its rows in."""
+ if not isinstance(snapshot.data, dict) or not isinstance(delta.data, dict):
+ return
+ rows = {r["row"]: r for r in snapshot.data.get("rows_changed", [])}
+ for record in delta.data.get("rows_changed", []):
+ rows[record["row"]] = record
+ merged = dict(snapshot.data)
+ merged["rows_changed"] = [rows[k] for k in sorted(rows) if rows[k]["runs"]]
+ merged["cursor"] = delta.data.get("cursor", snapshot.data.get("cursor"))
+ snapshot.data = merged
+
+ @staticmethod
+ def _merge_deltas(older: _Out, newer: _Out) -> None:
+ """Two unsent deltas of one pane: the union of their rows, newest row wins.
+
+ Empty rows stay (in a delta they mean "this row is now blank"); the
+ newest frame's cursor and size are kept.
+ """
+ if not isinstance(older.data, dict) or not isinstance(newer.data, dict):
+ older.data = newer.data
+ return
+ rows = {r["row"]: r for r in older.data.get("rows_changed", [])}
+ for record in newer.data.get("rows_changed", []):
+ rows[record["row"]] = record
+ merged = dict(newer.data)
+ merged["rows_changed"] = [rows[k] for k in sorted(rows)]
+ older.data = merged
+
+ def _fold(self, topic: str) -> None:
+ """Too many pending deltas: drop them and send one fresh snapshot instead."""
+ kept = deque(i for i in self._items if not (i.feed and i.topic == topic))
+ self.coalesced += len(self._items) - len(kept)
+ self._items = kept
+ self._pending[topic] = 1
+ snap_type = f"{topic}.snapshot" if topic != "chat_tails" else "chat_tails.update"
+ self._items.append(_Out(snap_type, self.snapshot_of[topic], topic=topic, feed=True))
+ self._ready.set()
+
+ async def get(self) -> _Out:
+ while not self._items:
+ self._ready.clear()
+ await self._ready.wait()
+ item = self._items.popleft()
+ if item.key is not None:
+ self._slots.pop(item.key, None)
+ if item.feed and item.topic in self._pending:
+ self._pending[item.topic] = max(0, self._pending[item.topic] - 1)
+ return item
+
+ def clear_topic(self, topic: str) -> None:
+ self._items = deque(i for i in self._items if i.topic != topic)
+ self._slots = {k: v for k, v in self._slots.items() if v.topic != topic}
+ self._pending.pop(topic, None)
+
+
+# ---------------------------------------------------------------------- session
+
+
+class Relay(Protocol):
+ """A topic producer bound to one session (``relays/*.py``)."""
+
+ topics: tuple[str, ...]
+
+ async def start(self) -> None: ...
+ async def stop(self) -> None: ...
+ async def subscribe(self, topic: str) -> None: ...
+ async def unsubscribe(self, topic: str) -> None: ...
+ async def resync(self, topic: str, data: dict[str, Any]) -> None: ...
+
+
+class BridgeSession:
+ """One authenticated connection."""
+
+ def __init__(
+ self,
+ hub: BridgeHub,
+ transport: Transport,
+ hello: P.Inbound,
+ *,
+ session_id: str,
+ ) -> None:
+ self.hub = hub
+ self.transport = transport
+ self.hello = hello
+ self.id = session_id
+ self.pid = hello.data.get("pid") if isinstance(hello.data.get("pid"), int) else None
+ encodings = hello.data.get("encodings") or {}
+ screens = encodings.get("screens") if isinstance(encodings, dict) else None
+ self.screens_encoding = (
+ "cells.bin/1"
+ if not isinstance(screens, list) or "cells.bin/1" in screens or not screens
+ else ("cells.json/1" if "cells.json/1" in screens else "cells.bin/1")
+ )
+ self.seq = 0
+ self.last_seq_of: dict[str, int] = {}
+ self.outbox = Outbox()
+ self.subscribed: set[str] = set()
+ self.relays: list[Relay] = []
+ self.closed = asyncio.Event()
+ self.close_code: int | None = None
+ self.last_frame_at = hub.clock()
+ self.hung_reported = False
+ self.bytes_sent = 0
+ self.screen_bytes = 0
+ self.frames_sent = 0
+ self._warned_types: set[str] = set()
+ self._ids_seen: set[str] = set()
+ self._log_budget = RateLimit(10, 1.0)
+ self.rates = default_rate_limits()
+ self._command_tasks: set[asyncio.Task[None]] = set()
+ self._requests: dict[str, asyncio.Future[dict[str, Any]]] = {}
+ self._request_ids = itertools.count(1)
+ self.lifecycle: dict[str, Any] = {"state": "booting"}
+ self.ready_ms: int | None = None
+ self.panel_stream: dict[str, Any] = {"state": "stopped"}
+
+ # ------------------------------------------------------------------ sending
+ def send(
+ self,
+ type_: str,
+ data: Any,
+ *,
+ topic: str | None = None,
+ delta: bool = False,
+ key: str | None = None,
+ ref: int | None = None,
+ feed: bool = False,
+ ) -> None:
+ """Queue one server frame; ``seq`` and ``base`` are assigned at write time."""
+ if self.closed.is_set():
+ return
+ self.outbox.put(_Out(type_, data, topic=topic, delta=delta, key=key, ref=ref, feed=feed))
+
+ def reply(self, rid: str, body: dict[str, Any]) -> None:
+ if self.closed.is_set():
+ return
+ self.outbox.put(_Out("reply", body, re=rid))
+
+ async def _write(self, item: _Out) -> None:
+ data = item.data() if callable(item.data) else item.data
+ if data is None:
+ return
+ if asyncio.iscoroutine(data):
+ data = await data
+ if data is None:
+ return
+ self.seq += 1
+ seq = self.seq
+ base: int | None = None
+ slot = item.key or item.topic
+ if item.delta and slot is not None:
+ base = self.last_seq_of.get(slot)
+ if base is None:
+ # Never send a delta without the frame it applies to.
+ self.seq -= 1
+ return
+ if item.ref is not None and self.screens_encoding == "cells.bin/1":
+ if data.get("kind") == "snapshot":
+ # The companion text frame goes right before each binary snapshot.
+ meta = {
+ k: data[k] for k in ("pane_id", "ref", "cols", "rows", "style", "cut", "at")
+ }
+ meta_seq, seq = seq, seq + 1
+ self.seq = seq
+ text = P.encode(P.frame("screens.meta", meta_seq, meta))
+ await asyncio.wait_for(self.transport.send_text(text), SEND_TIMEOUT_S)
+ self.bytes_sent += len(text.encode("utf-8"))
+ self.frames_sent += 1
+ blob = encode_cells(data, ref=item.ref, seq=seq, base=base)
+ await asyncio.wait_for(self.transport.send_bytes(blob), SEND_TIMEOUT_S)
+ self.bytes_sent += len(blob)
+ self.screen_bytes += len(blob)
+ else:
+ text = P.encode(P.frame(item.type, seq, data, base=base, re=item.re, id=item.rid))
+ await asyncio.wait_for(self.transport.send_text(text), SEND_TIMEOUT_S)
+ size = len(text.encode("utf-8"))
+ self.bytes_sent += size
+ if item.ref is not None:
+ self.screen_bytes += size
+ self.frames_sent += 1
+ if slot is not None and item.re is None:
+ self.last_seq_of[slot] = seq
+ if self.hub.on_frame_sent is not None:
+ self.hub.on_frame_sent(self, item.type, data)
+
+ async def writer(self) -> None:
+ try:
+ while not self.closed.is_set():
+ item = await self.outbox.get()
+ await self._write(item)
+ except (
+ TransportClosed,
+ TimeoutError,
+ ConnectionError,
+ ): # link gone; close() reports
+ await self.close(1011, "send failed")
+ except asyncio.CancelledError:
+ raise
+ except Exception: # noqa: BLE001
+ log.exception("verse bridge: writer failed")
+ await self.close(1011, "internal error")
+
+ async def close(self, code: int, reason: str = "") -> None:
+ if self.closed.is_set():
+ return
+ self.close_code = code
+ self.closed.set()
+ for task in list(self._command_tasks):
+ task.cancel()
+ with contextlib.suppress(Exception):
+ await self.transport.close(code, reason)
+
+ # ------------------------------------------------------------------ receiving
+ def warn_once(self, type_: str, message: str) -> None:
+ if type_ not in self._warned_types:
+ self._warned_types.add(type_)
+ log.info("verse bridge: %s (%s)", message, type_)
+
+ async def handle(self, inbound: P.Inbound) -> None:
+ hub = self.hub
+ entry_cmd = hub.commands.get(inbound.type)
+ if entry_cmd is not None:
+ if inbound.id is None:
+ self.warn_once(inbound.type, "command without id ignored")
+ return
+ if inbound.id in self._ids_seen:
+ self.reply(inbound.id, P.error("bad_request", "Request id reused."))
+ return
+ self._ids_seen.add(inbound.id)
+ busy = hub.busy_checks.get(inbound.type)
+ if busy is not None and busy():
+ self.reply(inbound.id, P.error("busy", f"{inbound.type} is already running."))
+ return
+ limit = self.rates.get(inbound.type)
+ if limit is not None and not limit.allow(hub.clock()):
+ self.reply(inbound.id, P.error("rate_limited", f"{inbound.type} rate limit."))
+ return
+ # Commands run beside the reader, so a long one (a launch batch)
+ # never stalls ping handling; replies are matched by ``re``.
+ task = asyncio.ensure_future(self._run_command(entry_cmd, inbound))
+ self._command_tasks.add(task)
+ task.add_done_callback(self._command_tasks.discard)
+ return
+ notice = hub.notices.get(inbound.type)
+ if notice is not None:
+ try:
+ await notice(self, inbound)
+ except Exception: # noqa: BLE001
+ log.exception("verse bridge: notice %s failed", inbound.type)
+ return
+ self.warn_once(inbound.type, "unknown message type ignored")
+
+ async def request(self, type_: str, data: dict[str, Any], *, timeout_s: float = 10.0) -> dict:
+ """A server -> Verse command (``qa.exec``); returns the ``data`` of Verse's reply."""
+ rid = f"s-{next(self._request_ids)}"
+ future: asyncio.Future[dict[str, Any]] = asyncio.get_running_loop().create_future()
+ self._requests[rid] = future
+ self.outbox.put(_Out(type_, data, rid=rid))
+ try:
+ return await asyncio.wait_for(future, timeout_s)
+ finally:
+ self._requests.pop(rid, None)
+
+ def resolve(self, msg: P.Inbound) -> None:
+ re_ = msg.raw.get("re")
+ future = self._requests.get(re_) if isinstance(re_, str) else None
+ if future is not None and not future.done():
+ future.set_result(msg.data)
+
+ async def _run_command(self, handler: Handler, inbound: P.Inbound) -> None:
+ assert inbound.id is not None
+ try:
+ result = await handler(self, inbound)
+ except P.BridgeError as exc:
+ self.reply(inbound.id, P.error(exc.code, exc.message))
+ return
+ except asyncio.CancelledError:
+ raise
+ except Exception: # noqa: BLE001
+ log.exception("verse bridge: %s failed", inbound.type)
+ self.reply(inbound.id, P.error("internal", f"{inbound.type} failed."))
+ return
+ self.reply(inbound.id, P.ok(result))
+
+ async def drain_commands(self) -> None:
+ """Wait for every running command (tests and orderly shutdown)."""
+ while self._command_tasks:
+ await asyncio.gather(*list(self._command_tasks), return_exceptions=True)
+
+ async def reader(self) -> None:
+ while not self.closed.is_set():
+ try:
+ raw = await self.transport.receive()
+ except TransportClosed: # peer closed; the loop below reports the close
+ break
+ self.last_frame_at = self.hub.clock()
+ self.hung_reported = False
+ size = len(raw) if isinstance(raw, bytes) else len(raw.encode("utf-8"))
+ if size > P.MAX_FRAME_BYTES:
+ await self.close(P.CLOSE_TOO_BIG, "frame too large")
+ break
+ if isinstance(raw, bytes):
+ self.warn_once("binary", "binary frame from Verse ignored")
+ continue
+ try:
+ inbound = P.parse(raw)
+ except P.MalformedFrame as exc:
+ self.warn_once("malformed", f"malformed frame ignored: {exc}")
+ continue
+ await self.handle(inbound)
+ await self.close(1000, "")
+
+ async def watchdog(self) -> None:
+ """5 s without any Verse frame: report the link as hung (once per silence)."""
+ while not self.closed.is_set():
+ await asyncio.sleep(self.hub.watchdog_tick_s)
+ idle = self.hub.clock() - self.last_frame_at
+ if idle >= P.DEAD_LINK_S and not self.hung_reported:
+ self.hung_reported = True
+ log.warning("verse bridge: no frame for %.1f s, reporting hung", idle)
+ if self.hub.on_hung is not None:
+ with contextlib.suppress(Exception):
+ await self.hub.on_hung(self)
+
+ def allow_log(self) -> bool:
+ return self._log_budget.allow(self.hub.clock())
+
+
+# ---------------------------------------------------------------------- hub
+
+TokenCheck = Callable[[str], bool]
+RelayFactory = Callable[[BridgeSession], Relay]
+WelcomeBuilder = Callable[[BridgeSession], dict[str, Any]]
+
+
+class BridgeHub:
+ """Serves ``/api/verse/bridge``: handshake, the one live session, dispatch."""
+
+ def __init__(
+ self,
+ *,
+ check_token: TokenCheck,
+ welcome: WelcomeBuilder,
+ features: Iterable[str] = P.BASE_FEATURES,
+ clock: Callable[[], float] = time.monotonic,
+ ) -> None:
+ self.check_token = check_token
+ self.build_welcome = welcome
+ self.features = list(features)
+ self.clock = clock
+ self.current: BridgeSession | None = None
+ self.commands: dict[str, Handler] = {}
+ # Single-flight commands: answered ``busy`` before the rate limit is spent.
+ self.busy_checks: dict[str, Callable[[], bool]] = {}
+ self.notices: dict[str, NoticeHandler] = {}
+ self.relay_factories: list[RelayFactory] = []
+ self.on_hung: Callable[[BridgeSession], Awaitable[None]] | None = None
+ self.on_session: Callable[[BridgeSession | None], Awaitable[None]] | None = None
+ self.on_frame_sent: Callable[[BridgeSession, str, Any], None] | None = None
+ self.watchdog_tick_s = 0.1
+ self._ids = itertools.count(1)
+ self._register_core()
+
+ # ------------------------------------------------------------------ registry
+ def command(self, type_: str, handler: Handler) -> None:
+ self.commands[type_] = handler
+
+ def notice(self, type_: str, handler: NoticeHandler) -> None:
+ self.notices[type_] = handler
+
+ def relay(self, factory: RelayFactory) -> None:
+ self.relay_factories.append(factory)
+
+ def _register_core(self) -> None:
+ async def ping(session: BridgeSession, _msg: P.Inbound) -> None:
+ session.send("pong", {})
+
+ async def log_notice(session: BridgeSession, msg: P.Inbound) -> None:
+ if not session.allow_log():
+ return
+ level = msg.data.get("level")
+ text = str(msg.data.get("message", ""))[:2000]
+ category = str(msg.data.get("category", "verse"))[:64]
+ py_level = {"error": logging.ERROR, "warning": logging.WARNING}.get(
+ level if isinstance(level, str) else "", logging.INFO
+ )
+ log.log(py_level, "Verse [%s] %s", category, text)
+
+ async def reply(session: BridgeSession, msg: P.Inbound) -> None:
+ session.resolve(msg)
+
+ self.notice("ping", ping)
+ self.notice("reply", reply)
+ self.notice("log", log_notice)
+ self.command("subscribe", self._subscribe)
+ self.command("unsubscribe", self._unsubscribe)
+ self.command("resync", self._resync)
+
+ def _relay_for(self, session: BridgeSession, topic: str) -> Relay | None:
+ for relay in session.relays:
+ if topic in relay.topics:
+ return relay
+ return None
+
+ async def _subscribe(self, session: BridgeSession, msg: P.Inbound) -> dict[str, Any]:
+ topics = msg.data.get("topics")
+ if not isinstance(topics, list) or not all(isinstance(t, str) for t in topics):
+ raise P.BridgeError("bad_request", "topics must be a list of names.")
+ subscribed, unavailable = [], []
+ for topic in dict.fromkeys(topics):
+ if topic not in self.features:
+ unavailable.append(topic)
+ continue
+ subscribed.append(topic)
+ if not subscribed and unavailable:
+ raise P.BridgeError("unavailable", f"Not served: {', '.join(unavailable)}.")
+ for topic in subscribed:
+ session.subscribed.add(topic)
+ relay = self._relay_for(session, topic)
+ if relay is not None and topic in P.SNAPSHOT_TOPICS:
+ # The reply goes first; the snapshot follows before any delta.
+ asyncio.get_running_loop().call_soon(
+ lambda r=relay, t=topic: asyncio.ensure_future(r.subscribe(t))
+ )
+ elif relay is not None:
+ await relay.subscribe(topic)
+ return {"subscribed": subscribed, "unavailable": unavailable}
+
+ async def _unsubscribe(self, session: BridgeSession, msg: P.Inbound) -> dict[str, Any]:
+ topics = msg.data.get("topics")
+ if not isinstance(topics, list) or not all(isinstance(t, str) for t in topics):
+ raise P.BridgeError("bad_request", "topics must be a list of names.")
+ done = []
+ for topic in dict.fromkeys(topics):
+ if topic in session.subscribed:
+ session.subscribed.discard(topic)
+ session.outbox.clear_topic(topic)
+ session.last_seq_of.pop(topic, None)
+ relay = self._relay_for(session, topic)
+ if relay is not None:
+ await relay.unsubscribe(topic)
+ done.append(topic)
+ return {"unsubscribed": done}
+
+ async def _resync(self, session: BridgeSession, msg: P.Inbound) -> dict[str, Any]:
+ topic = msg.data.get("topic")
+ if not isinstance(topic, str) or topic not in P.BASE_FEATURES + ("duel_stats",):
+ raise P.BridgeError("bad_request", "Unknown topic.")
+ if topic not in self.features:
+ raise P.BridgeError("unavailable", f"{topic} is not served.")
+ relay = self._relay_for(session, topic)
+ pane_id = msg.data.get("pane_id")
+ if topic == "screens" and pane_id is not None:
+ if pane_id not in getattr(relay, "watched", {}):
+ raise P.BridgeError("not_found", "Pane is not watched.")
+ if relay is not None:
+ asyncio.get_running_loop().call_soon(
+ lambda: asyncio.ensure_future(relay.resync(topic, msg.data))
+ )
+ return {}
+
+ # ------------------------------------------------------------------ serving
+ async def serve(self, transport: Transport, peer_host: str | None) -> int:
+ """Run one connection to its end; returns the close code it ended with."""
+ if not is_loopback(peer_host):
+ await transport.close(P.CLOSE_PEER, "loopback only")
+ return P.CLOSE_PEER
+ hello = await self._handshake(transport)
+ if isinstance(hello, int):
+ return hello
+ previous = self.current
+ session = BridgeSession(self, transport, hello, session_id=f"vb-{next(self._ids):04x}")
+ if previous is not None:
+ await previous.close(P.CLOSE_REPLACED, "replaced")
+ await self._end(previous)
+ self.current = session
+ tasks: list[asyncio.Task[Any]] = []
+ try:
+ for factory in self.relay_factories:
+ session.relays.append(factory(session))
+ welcome = self.build_welcome(session)
+ session.send("welcome", welcome)
+ tasks = [
+ asyncio.create_task(session.writer(), name="verse-bridge-writer"),
+ asyncio.create_task(session.watchdog(), name="verse-bridge-watchdog"),
+ ]
+ for relay in session.relays:
+ await relay.start()
+ if self.on_session is not None:
+ await self.on_session(session)
+ await session.reader()
+ finally:
+ for task in tasks:
+ task.cancel()
+ for task in tasks:
+ with contextlib.suppress(BaseException):
+ await task
+ await self._end(session)
+ return session.close_code or 1000
+
+ async def _end(self, session: BridgeSession) -> None:
+ relays, session.relays = session.relays, []
+ for relay in relays:
+ with contextlib.suppress(Exception):
+ await relay.stop()
+ if self.current is session:
+ self.current = None
+ if self.on_session is not None:
+ with contextlib.suppress(Exception):
+ await self.on_session(None)
+
+ async def _handshake(self, transport: Transport) -> P.Inbound | int:
+ try:
+ raw = await asyncio.wait_for(transport.receive(), P.HELLO_TIMEOUT_S)
+ except TimeoutError: # answered with close code 4400
+ await transport.close(P.CLOSE_BAD_HELLO, "hello timeout")
+ return P.CLOSE_BAD_HELLO
+ except TransportClosed: # peer left before hello; nothing to report
+ return 1000
+ try:
+ hello = P.parse(raw)
+ except P.MalformedFrame: # answered with close code 4400
+ await transport.close(P.CLOSE_BAD_HELLO, "malformed hello")
+ return P.CLOSE_BAD_HELLO
+ if hello.type != "hello":
+ await transport.close(P.CLOSE_BAD_HELLO, "expected hello frame first")
+ return P.CLOSE_BAD_HELLO
+ token = hello.data.get("token")
+ protocols = hello.data.get("protocols")
+ if not isinstance(token, str) or not isinstance(protocols, list):
+ await transport.close(P.CLOSE_BAD_HELLO, "hello needs token and protocols")
+ return P.CLOSE_BAD_HELLO
+ if not self.check_token(token):
+ await transport.close(P.CLOSE_TOKEN, "unauthorized")
+ return P.CLOSE_TOKEN
+ if not any(p in P.SUPPORTED_PROTOCOLS for p in protocols):
+ await transport.close(P.CLOSE_PROTOCOL, P.welcome_reason_unsupported())
+ return P.CLOSE_PROTOCOL
+ build = hello.data.get("build") if isinstance(hello.data.get("build"), dict) else {}
+ log.info(
+ "verse bridge: hello from pid %s build %s %s",
+ hello.data.get("pid"),
+ build.get("version"),
+ build.get("changelist"),
+ )
+ return hello
+
+ async def push_all(self, type_: str, data: dict[str, Any], *, topic: str = "lifecycle") -> bool:
+ """Send one server event to the live session; False when none is connected."""
+ session = self.current
+ if session is None or session.closed.is_set():
+ return False
+ session.send(type_, data, topic=None)
+ return True
+
+ async def disconnect(self, code: int = 4401, reason: str = "launch over") -> None:
+ if self.current is not None:
+ await self.current.close(code, reason)
+
+
+class TokenBox:
+ """The tokens valid right now: the running launch's and the dev discovery one."""
+
+ def __init__(self) -> None:
+ self._tokens: dict[str, str] = {}
+
+ def set(self, slot: str, token: str | None) -> None:
+ if token:
+ self._tokens[slot] = token
+ else:
+ self._tokens.pop(slot, None)
+
+ def check(self, token: str) -> bool:
+ ok = False
+ for valid in self._tokens.values():
+ # Compare against every slot so timing does not tell which one matched.
+ ok |= hmac.compare_digest(valid.encode(), token.encode())
+ return ok
+
+ def __bool__(self) -> bool:
+ return bool(self._tokens)
+
+
+def app_pid() -> int:
+ return os.getpid()
diff --git a/dodaios/verse_host/cells_codec.py b/dodaios/verse_host/cells_codec.py
new file mode 100644
index 0000000000..6790078a66
--- /dev/null
+++ b/dodaios/verse_host/cells_codec.py
@@ -0,0 +1,355 @@
+"""Terminal screen cells: ``cells.bin/1`` and ``cells.json/1`` (contract 5.4).
+
+The backend codec. It produces byte for byte what the golden vectors in
+``tests/unit/verse_host/fixtures/bridge/cells/vectors.json`` hold, and the
+Unreal decoder (``VerseBridge``) reads the same bytes.
+
+A row is sent as runs of cells sharing ``fg``, ``bg`` and ``attrs``. Colour
+u32: high byte mode (0 default, 1 palette, 2 RGB). Attribute bits: bold, dim,
+italic, underline, inverse, strikethrough, invisible, blink, wide.
+"""
+
+from __future__ import annotations
+
+import re
+import struct
+import unicodedata
+from collections.abc import Iterable, Sequence
+from typing import Any
+
+MAGIC = b"VC"
+VERSION = 1
+KIND_SNAPSHOT = 1
+KIND_DELTA = 2
+KINDS = {"snapshot": KIND_SNAPSHOT, "delta": KIND_DELTA}
+KIND_NAMES = {v: k for k, v in KINDS.items()}
+
+ATTRS = (
+ "bold",
+ "dim",
+ "italic",
+ "underline",
+ "inverse",
+ "strikethrough",
+ "invisible",
+ "blink",
+ "wide",
+)
+ATTR_BITS = {name: 1 << i for i, name in enumerate(ATTRS)}
+WIDE = ATTR_BITS["wide"]
+#: Attributes that paint a blank cell, so a trailing blank carrying one is kept.
+_VISIBLE_ON_BLANK = ATTR_BITS["inverse"] | ATTR_BITS["underline"] | ATTR_BITS["strikethrough"]
+
+MODE_DEFAULT = 0
+MODE_PALETTE = 1
+MODE_RGB = 2
+DEFAULT_COLOUR = 0
+
+MAX_COLS = 240
+MAX_ROWS = 60
+
+_HEADER = struct.Struct("<2sBBHIIHHhhH")
+_ROW = struct.Struct("<HH")
+_RUN = struct.Struct("<HHIIHH")
+_HEX = re.compile(r"^#[0-9a-f]{6}$")
+HEADER_SIZE = _HEADER.size
+
+
+class CellsError(ValueError):
+ """A frame that is not valid ``cells.bin/1`` or ``cells.json/1``."""
+
+
+# ------------------------------------------------------------------ colours, attrs
+
+
+def palette(index: int) -> int:
+ return (MODE_PALETTE << 24) | (index & 0xFF)
+
+
+def rgb(r: int, g: int, b: int) -> int:
+ return (MODE_RGB << 24) | ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | (b & 0xFF)
+
+
+def colour_to_u32(colour: Any) -> int:
+ if colour is None:
+ return DEFAULT_COLOUR
+ if isinstance(colour, dict):
+ index = colour.get("i")
+ if (
+ set(colour) != {"i"}
+ or not isinstance(index, int)
+ or isinstance(index, bool)
+ or not 0 <= index <= 255
+ ):
+ raise CellsError(f"bad palette colour {colour!r}")
+ return palette(index)
+ if isinstance(colour, str) and _HEX.match(colour):
+ return (MODE_RGB << 24) | int(colour[1:], 16)
+ raise CellsError(f"bad colour {colour!r}")
+
+
+def colour_from_u32(value: int) -> Any:
+ mode, low = value >> 24, value & 0xFFFFFF
+ if mode == MODE_DEFAULT:
+ if low:
+ raise CellsError(f"default colour with payload {value:#010x}")
+ return None
+ if mode == MODE_PALETTE:
+ if low > 0xFF:
+ raise CellsError(f"palette colour out of range {value:#010x}")
+ return {"i": low}
+ if mode == MODE_RGB:
+ return f"#{low:06x}"
+ raise CellsError(f"unknown colour mode {mode}")
+
+
+def attrs_to_u16(names: Iterable[str]) -> int:
+ bits = 0
+ for name in names:
+ if name not in ATTR_BITS:
+ raise CellsError(f"unknown attribute {name!r}")
+ bits |= ATTR_BITS[name]
+ return bits
+
+
+def attrs_from_u16(bits: int) -> list[str]:
+ if bits >> len(ATTRS):
+ raise CellsError(f"unknown attribute bits {bits:#06x}")
+ return [name for name in ATTRS if bits & ATTR_BITS[name]]
+
+
+# ------------------------------------------------------------------ graphemes
+
+
+def _extends(ch: str) -> bool:
+ cp = ord(ch)
+ return (
+ unicodedata.category(ch) in {"Mn", "Me", "Mc"}
+ or cp == 0x200D
+ or 0xFE00 <= cp <= 0xFE0F
+ or 0x1F3FB <= cp <= 0x1F3FF
+ or 0xE0020 <= cp <= 0xE007F
+ )
+
+
+def graphemes(text: str) -> list[str]:
+ """Grapheme clusters: combining marks, ZWJ sequences, variation selectors,
+ skin-tone modifiers and tag characters extend the previous cluster."""
+ clusters: list[str] = []
+ join_next = False
+ for ch in text:
+ if clusters and (join_next or _extends(ch)):
+ clusters[-1] += ch
+ else:
+ clusters.append(ch)
+ join_next = ord(ch) == 0x200D
+ return clusters
+
+
+def is_wide(cluster: str) -> bool:
+ """East Asian wide or fullwidth glyphs and emoji presentation take two columns."""
+ if not cluster:
+ return False
+ first = cluster[0]
+ if unicodedata.east_asian_width(first) in ("W", "F"):
+ return True
+ return "️" in cluster and ord(first) > 0x2000
+
+
+def run_span(run: dict) -> int:
+ width = 2 if "wide" in run.get("attrs", []) else 1
+ return len(graphemes(run["text"])) * width
+
+
+def check_rows(cols: int, rows: int, rows_changed: Sequence[dict]) -> None:
+ """Rows inside the grid, each row once, runs sorted, inside the row, not overlapping."""
+ if not 1 <= cols <= MAX_COLS or not 1 <= rows <= MAX_ROWS:
+ raise CellsError(f"grid {cols}x{rows} outside 1..{MAX_COLS} x 1..{MAX_ROWS}")
+ seen: set[int] = set()
+ for record in rows_changed:
+ row = record["row"]
+ if not 0 <= row < rows:
+ raise CellsError(f"row {row} outside 0..{rows - 1}")
+ if row in seen:
+ raise CellsError(f"row {row} sent twice")
+ seen.add(row)
+ end = 0
+ for run in record["runs"]:
+ if not run["text"]:
+ raise CellsError(f"row {row}: empty run at col {run['col']}")
+ if run["col"] < end:
+ raise CellsError(f"row {row}: run at col {run['col']} overlaps or is out of order")
+ end = run["col"] + run_span(run)
+ if end > cols:
+ raise CellsError(
+ f"row {row}: run at col {run['col']} ends at {end}, past {cols} cols"
+ )
+
+
+# ------------------------------------------------------------------ cells -> runs
+
+#: One cell of a styled grid: ``(char, fg, bg, attrs)`` with u32 colours and
+#: u16 attrs. The second column of a wide glyph holds ``""``.
+Cell = tuple[str, int, int, int]
+
+
+def row_runs(cells: Sequence[Cell], cols: int | None = None) -> list[dict]:
+ """One row of cells as JSON runs: equal style merged, trailing blanks dropped.
+
+ A trailing blank (a space on the default background with no attribute
+ that paints a blank) is not sent; Verse clears to the default background.
+ A wide glyph covers two columns and its second column is skipped.
+ """
+ limit = len(cells) if cols is None else min(cols, len(cells))
+ end = limit
+ while end > 0:
+ ch, _fg, bg, attrs = cells[end - 1]
+ if ch in (" ", "") and bg == DEFAULT_COLOUR and not attrs & _VISIBLE_ON_BLANK:
+ end -= 1
+ continue
+ break
+ runs: list[dict] = []
+ cur: dict | None = None
+ cur_key: tuple[int, int, int] | None = None
+ cur_end = -1
+ col = 0
+ while col < end:
+ ch, fg, bg, attrs = cells[col]
+ if ch == "":
+ col += 1
+ continue
+ width = 2 if attrs & WIDE else 1
+ if col + width > limit:
+ # A wide glyph cut by the right edge becomes a blank.
+ ch, attrs, width = " ", attrs & ~WIDE, 1
+ key = (fg, bg, attrs)
+ if cur is not None and key == cur_key and cur_end == col:
+ cur["text"] += ch
+ else:
+ cur = {
+ "col": col,
+ "text": ch,
+ "fg": colour_from_u32(fg),
+ "bg": colour_from_u32(bg),
+ "attrs": attrs_from_u16(attrs),
+ }
+ cur_key = key
+ runs.append(cur)
+ cur_end = col + width
+ col += width
+ return runs
+
+
+# ------------------------------------------------------------------ encode / decode
+
+
+def encode(data: dict, *, ref: int, seq: int, base: int | None) -> bytes:
+ """Encode the ``data`` of a ``screens.frame`` (``cells.json/1``) as ``cells.bin/1``."""
+ kind = KINDS.get(data["kind"])
+ if kind is None:
+ raise CellsError(f"bad kind {data['kind']!r}")
+ if kind == KIND_SNAPSHOT:
+ base = 0
+ elif base is None:
+ raise CellsError("a delta needs a base seq")
+ cols, rows = data["cols"], data["rows"]
+ check_rows(cols, rows, data["rows_changed"])
+ cur_row, cur_col = data["cursor"]
+ parts = [
+ _HEADER.pack(
+ MAGIC,
+ VERSION,
+ kind,
+ ref,
+ seq,
+ base,
+ cols,
+ rows,
+ cur_row,
+ cur_col,
+ len(data["rows_changed"]),
+ )
+ ]
+ for record in data["rows_changed"]:
+ parts.append(_ROW.pack(record["row"], len(record["runs"])))
+ for run in record["runs"]:
+ text = run["text"].encode("utf-8")
+ parts.append(
+ _RUN.pack(
+ run["col"],
+ len(graphemes(run["text"])),
+ colour_to_u32(run.get("fg")),
+ colour_to_u32(run.get("bg")),
+ attrs_to_u16(run.get("attrs", [])),
+ len(text),
+ )
+ )
+ parts.append(text)
+ return b"".join(parts)
+
+
+def decode(blob: bytes) -> dict:
+ """Decode a ``cells.bin/1`` frame; :class:`CellsError` on anything malformed."""
+ if len(blob) < HEADER_SIZE:
+ raise CellsError(
+ f"frame of {len(blob)} bytes is shorter than the {HEADER_SIZE}-byte header"
+ )
+ magic, version, kind, ref, seq, base, cols, rows, cur_row, cur_col, count = _HEADER.unpack_from(
+ blob, 0
+ )
+ if magic != MAGIC:
+ raise CellsError(f"bad magic {magic!r}")
+ if version != VERSION:
+ raise CellsError(f"unsupported version {version}")
+ if kind not in KIND_NAMES:
+ raise CellsError(f"bad kind {kind}")
+ if kind == KIND_SNAPSHOT and base != 0:
+ raise CellsError("a snapshot carries base 0")
+ if (cur_row, cur_col) != (-1, -1) and not (0 <= cur_row < rows and 0 <= cur_col < cols):
+ raise CellsError(f"cursor {cur_row},{cur_col} outside the grid")
+ offset = HEADER_SIZE
+ records: list[dict] = []
+ for _ in range(count):
+ if offset + _ROW.size > len(blob):
+ raise CellsError("truncated row record")
+ row, run_count = _ROW.unpack_from(blob, offset)
+ offset += _ROW.size
+ runs: list[dict] = []
+ for _ in range(run_count):
+ if offset + _RUN.size > len(blob):
+ raise CellsError("truncated run")
+ col, cells, fg, bg, attrs, text_bytes = _RUN.unpack_from(blob, offset)
+ offset += _RUN.size
+ if offset + text_bytes > len(blob):
+ raise CellsError("run text runs past the end of the frame")
+ try:
+ text = blob[offset : offset + text_bytes].decode("utf-8")
+ except UnicodeDecodeError as exc:
+ raise CellsError(f"run text is not UTF-8: {exc}") from exc
+ offset += text_bytes
+ held = len(graphemes(text))
+ if held != cells:
+ raise CellsError(f"run at row {row} col {col} says {cells} cells but holds {held}")
+ runs.append(
+ {
+ "col": col,
+ "text": text,
+ "fg": colour_from_u32(fg),
+ "bg": colour_from_u32(bg),
+ "attrs": attrs_from_u16(attrs),
+ }
+ )
+ records.append({"row": row, "runs": runs})
+ if offset != len(blob):
+ raise CellsError(f"{len(blob) - offset} trailing bytes")
+ check_rows(cols, rows, records)
+ return {
+ "kind": KIND_NAMES[kind],
+ "ref": ref,
+ "seq": seq,
+ "base": base if kind == KIND_DELTA else None,
+ "cols": cols,
+ "rows": rows,
+ "cursor": [cur_row, cur_col],
+ "rows_changed": records,
+ }
diff --git a/dodaios/verse_host/chat_lines.py b/dodaios/verse_host/chat_lines.py
new file mode 100644
index 0000000000..8236509030
--- /dev/null
+++ b/dodaios/verse_host/chat_lines.py
@@ -0,0 +1,80 @@
+"""Desk-monitor chat lines: a Python port of ``crewFeeds/deskChat.ts`` (contract 6).
+
+The tail of an agent's chat reduced to a few short lines: who said what and
+which tool runs. Limits of the contract: at most 12 lines; each cut on a word
+boundary at 160 characters (tool 80, notice and error 100).
+"""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Iterable, Mapping
+from typing import Any, Final
+
+MAX_LINES: Final = 12
+TEXT_MAX: Final = 160
+TOOL_MAX: Final = 80
+NOTICE_MAX: Final = 100
+_SPACE = re.compile(r"\s+")
+
+
+def clean(text: Any, limit: int = TEXT_MAX) -> str:
+ """Whitespace flattened; longer than ``limit``: cut on a word boundary plus an ellipsis."""
+ if not isinstance(text, str):
+ return ""
+ flat = _SPACE.sub(" ", text).strip()
+ if len(flat) <= limit:
+ return flat
+ cut = flat[: limit - 1]
+ space = cut.rfind(" ")
+ # Only back off to a word boundary when it keeps most of the line.
+ if space >= limit // 2:
+ cut = cut[:space]
+ return f"{cut.rstrip()}…"
+
+
+def tool_label(name: Any) -> str:
+ """Short tool names: ``mcp__dodaios__society_shell`` -> ``society_shell``."""
+ if not isinstance(name, str) or not name:
+ return "tool"
+ return name.split("__")[-1] or name
+
+
+def _line(event: Mapping[str, Any]) -> dict[str, str] | None:
+ p = event.get("payload") or {}
+ if not isinstance(p, Mapping):
+ p = {}
+ kind = event.get("kind")
+ if kind == "user_message":
+ return {"kind": "user", "text": clean(p.get("text"))}
+ if kind == "agent_message":
+ who = "user" if p.get("sender_kind") == "user" else "agent"
+ return {"kind": who, "text": clean(p.get("text"))}
+ if kind == "assistant_text":
+ return {"kind": "agent", "text": clean(p.get("text"))}
+ if kind == "tool_call":
+ summary = p.get("summary")
+ label = summary if isinstance(summary, str) and summary else tool_label(p.get("name"))
+ return {"kind": "tool", "text": clean(label, TOOL_MAX)}
+ if kind == "notice":
+ text = p.get("text") if p.get("text") is not None else p.get("summary")
+ return {"kind": "notice", "text": clean(text, NOTICE_MAX)}
+ if kind == "error":
+ return {"kind": "error", "text": clean(p.get("message"), NOTICE_MAX)}
+ return None
+
+
+def chat_lines(
+ events: Iterable[Mapping[str, Any]], max_lines: int = MAX_LINES
+) -> list[dict[str, str]]:
+ lines = [line for e in events if (line := _line(e)) is not None and line["text"]]
+ return lines[-max_lines:]
+
+
+def chat_version(events: list[Mapping[str, Any]]) -> str:
+ """A cheap identity for "did anything change": last event id or seq, and count."""
+ if not events:
+ return ""
+ last = events[-1]
+ ident = last.get("event_id") or last.get("id") or last.get("seq") or ""
+ return f"{ident}:{len(events)}"
diff --git a/dodaios/verse_host/duty.py b/dodaios/verse_host/duty.py
new file mode 100644
index 0000000000..4fbd8f4493
--- /dev/null
+++ b/dodaios/verse_host/duty.py
@@ -0,0 +1,95 @@
+"""Duty status of crew members, computed by the backend (contract 4.1).
+
+A Python port of ``frontend/src/components/society/verse/ranks/dutyStatus.ts``
+(``dutyOf``, ``dutyOfPane``) and of the pane dot reading in
+``frontend/src/components/agentic/sidePanel/agentStatus.ts`` (``dotKindFor``,
+``stateKeyFor``), so Unreal never re-implements the precedence rules.
+
+Precedence: paused > waiting > working > error > idle. The parity table
+``tests/unit/verse_host/parity/duty_cases.json`` is checked against both the
+TS code (vitest) and this module (pytest).
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, Final
+
+DUTY_STATUSES: Final = ("working", "waiting", "idle", "paused", "error")
+RUN_STATES: Final = ("paused", "waiting", "working", "idle")
+PANE_STATUSES: Final = ("pending", "live", "exited", "error")
+PANE_ACTIVITIES: Final = (
+ "starting",
+ "working",
+ "waiting",
+ "asking",
+ "failed",
+ "exited",
+ "stopped",
+ "unknown",
+ "",
+)
+
+
+def duty_of(
+ state: str, lifecycle: str | None = None, *, asking: bool = False, error: bool = False
+) -> str:
+ """A society agent's duty status (``dutyOf``)."""
+ if state == "paused" or lifecycle == "paused":
+ return "paused"
+ if asking or state == "waiting":
+ return "waiting"
+ if state == "working":
+ return "working"
+ if error:
+ return "error"
+ return "idle"
+
+
+def dot_kind_for(pane: Mapping[str, Any]) -> str:
+ """The IDE's dot colour of a pane (``dotKindFor``)."""
+ status, activity = pane.get("status"), pane.get("activity")
+ if status == "error" or activity == "failed":
+ return "error"
+ if activity == "asking":
+ return "waiting"
+ if activity in ("working", "starting") or status == "pending":
+ return "working"
+ return "idle"
+
+
+def state_key_for(pane: Mapping[str, Any], kind: str | None = None) -> str:
+ """The finer reading behind a pane's dot (``stateKeyFor``)."""
+ kind = kind or dot_kind_for(pane)
+ activity, status = pane.get("activity"), pane.get("status")
+ if activity in ("stopped", "unknown"):
+ return str(activity)
+ if kind == "working":
+ return "starting" if activity == "starting" or status == "pending" else "working"
+ if kind == "waiting":
+ return "needs_input"
+ if kind == "error":
+ return "failed" if activity == "failed" else "error"
+ if status == "exited":
+ return "exited"
+ return "done" if pane.get("worked") else "idle"
+
+
+def duty_of_pane(dot: str, state_key: str | None = None) -> str:
+ """A coding pane's duty status from its dot and state key (``dutyOfPane``)."""
+ if state_key == "stopped":
+ return "paused"
+ if dot in ("working", "waiting", "error"):
+ return dot
+ return "idle"
+
+
+def pane_duty(pane: Mapping[str, Any]) -> str:
+ """Shortcut: the duty of a ``WorkspacePaneRow``-shaped pane row."""
+ kind = dot_kind_for(pane)
+ return duty_of_pane(kind, state_key_for(pane, kind))
+
+
+def or_fallback(value: Any, allowed: tuple[str, ...], fallback: str) -> str:
+ """An enum value as sent, or the documented fallback for anything else."""
+ return value if isinstance(value, str) and value in allowed else fallback
diff --git a/dodaios/verse_host/env.py b/dodaios/verse_host/env.py
new file mode 100644
index 0000000000..be99ca2f0b
--- /dev/null
+++ b/dodaios/verse_host/env.py
@@ -0,0 +1,26 @@
+"""Read a ``DODAIOS_VERSE_*`` switch the way the app's environment holds it.
+
+Importing ``dodaios`` moves every ``DODAIOS_<NAME>`` variable to
+``JARVIS_<NAME>`` (``dodaios/core/env_prefix.py``), so a plain
+``os.environ.get("DODAIOS_VERSE_QA")`` never sees what the user set. The verse
+host documents and reads the ``DODAIOS_`` names; this helper looks at both
+spellings, the ``DODAIOS_`` one first (a test or a late ``os.environ`` write).
+"""
+
+from __future__ import annotations
+
+import os
+
+_NEW = "DODAIOS_"
+_OLD = "JARVIS_"
+
+
+def getenv(name: str, default: str = "") -> str:
+ value = os.environ.get(name)
+ if value not in (None, ""):
+ return value
+ if name.startswith(_NEW):
+ value = os.environ.get(_OLD + name[len(_NEW) :])
+ if value not in (None, ""):
+ return value
+ return default
diff --git a/dodaios/verse_host/host.py b/dodaios/verse_host/host.py
new file mode 100644
index 0000000000..f7e2145315
--- /dev/null
+++ b/dodaios/verse_host/host.py
@@ -0,0 +1,575 @@
+"""The verse host: one object per app that ties supervisor, probe, bridge and relays.
+
+``dodaios/ui/web/verse_routes.py`` creates it lazily on ``app.state`` and
+calls into it; nothing runs until the first ``show`` (architecture 1.1:
+never at app start). Lifecycle (contract 12): the host sends ``lifecycle.*``,
+``panel.*``, ``gpu.*`` and ``settings.changed``, and tracks what Verse
+reports (``lifecycle.state``, ``lifecycle.ready``, ``window.state``,
+``panel.stream_state``, ``focus.return_to_app``, ``lifecycle.bye``).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import json
+import logging
+import os
+import sys
+import time
+from pathlib import Path
+from typing import Any
+
+from . import probe as probe_mod
+from . import protocol as P
+from .bridge import BridgeHub, BridgeSession, TokenBox, mint_token
+from .install_port import InstallJob, VerseInstaller, load_installer
+from .ports import AppBackend, BackendPort
+from .relays.chat_tails import ChatTailsRelay
+from .relays.commands import CommandsRelay
+from .relays.meetings import MeetingsRelay
+from .relays.progression import ProgressionRelay
+from .relays.roster import RosterRelay
+from .relays.screens import ScreensRelay
+from .relays.settings import CompanionRelay, SettingsRelay, locale_block
+from .settings_store import SettingsStore
+from .supervisor import Supervisor
+
+log = logging.getLogger(__name__)
+
+IDLE_QUIT_S = 600.0
+GPU_YIELD_QUIT_S = 10.0
+DECKS = ("bridge", "ops", "engineering", "hangar")
+
+
+def allow_foreground(pid: int | None) -> None:
+ """Let ``pid`` take the foreground (Windows foreground lock); a no-op elsewhere."""
+ if not pid or sys.platform != "win32":
+ return
+ try: # pragma: no cover - Windows only
+ import ctypes
+
+ ctypes.windll.user32.AllowSetForegroundWindow(int(pid))
+ except Exception: # noqa: BLE001
+ log.debug("verse host: AllowSetForegroundWindow failed", exc_info=True)
+
+
+def panel_available() -> bool:
+ import importlib.util
+
+ try:
+ return importlib.util.find_spec("dodaios.verse_host.signal") is not None
+ except (ImportError, ValueError): # WP20 signalling not installed yet
+ return False
+
+
+def restrict_to_user(path: Path) -> None:
+ """User-only access to ``path`` (the dev discovery file holds a token)."""
+ if sys.platform == "win32": # pragma: no cover - Windows only
+ import subprocess
+
+ user = os.environ.get("USERNAME", "")
+ if user:
+ subprocess.run(
+ ["icacls", str(path), "/inheritance:r", "/grant:r", f"{user}:F"], # noqa: S607
+ capture_output=True,
+ check=False,
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
+ )
+ else:
+ os.chmod(path, 0o600)
+
+
+class VerseHost:
+ def __init__(
+ self,
+ app: Any,
+ *,
+ backend: BackendPort | None = None,
+ store: SettingsStore | None = None,
+ data_dir: Path | None = None,
+ supervisor: Supervisor | None = None,
+ app_version: str | None = None,
+ installer: VerseInstaller | None = None,
+ ) -> None:
+ if data_dir is None:
+ from dodaios.core.config import DATA_DIR
+
+ data_dir = Path(DATA_DIR)
+ self.app = app
+ self.data_dir = Path(data_dir) / "verse"
+ self.backend: BackendPort = backend or AppBackend(app)
+ self.store = store or SettingsStore(self.data_dir / "settings.json")
+ self.tokens = TokenBox()
+ self.port = 8765
+ if app_version is None:
+ try:
+ from dodaios import __version__ as app_version
+ except Exception: # source checkout without a version; the welcome says 0.0.0
+ app_version = "0.0.0"
+ self.app_version = str(app_version)
+ from dodaios.agentic_ide.launch_sequence import LaunchSequence
+
+ self.launcher = LaunchSequence(_LaunchSteps(self.backend))
+ self.hub = BridgeHub(check_token=self.tokens.check, welcome=self._welcome)
+ self.hub.on_hung = self._on_hung
+ self.hub.on_session = self._on_session
+ self.supervisor = supervisor or Supervisor(
+ exe=probe_mod.find_executable,
+ bridge_url=self.bridge_url,
+ set_token=lambda t: self.tokens.set("launch", t),
+ mint=mint_token,
+ crash_dir=self.data_dir / "crashes",
+ on_change=self._status_changed,
+ request_quit=self._request_quit,
+ )
+ self.capability: probe_mod.Capability | None = None
+ self.visibility = "hidden"
+ self.panel = "hidden"
+ self.gpu = "free"
+ self.state: str | None = None
+ self.vram_mb: int | None = None
+ self.fps: float | None = None
+ self.dormant_since: float | None = None
+ self.pending_show: dict[str, Any] | None = None
+ self.timings: dict[str, Any] = {}
+ self._show_sent_at: float | None = None
+ self._launch_at: float | None = None
+ self._idle_task: asyncio.Task[None] | None = None
+ self.dev_file: Path | None = None
+ self.qa: dict[str, Any] = {}
+ self._roster: RosterRelay | None = None
+ self.install = InstallJob(
+ installer or load_installer(Path(data_dir)),
+ on_change=self._install_changed,
+ before_remove=self._before_remove,
+ )
+ self._wire()
+
+ # ------------------------------------------------------------------ wiring
+ def _wire(self) -> None:
+ hub = self.hub
+ hub.relay(self._make_roster)
+ hub.relay(lambda s: ScreensRelay(s, self.backend))
+ hub.relay(lambda s: ChatTailsRelay(s, self.backend))
+ hub.relay(lambda s: MeetingsRelay(s, self.backend))
+ hub.relay(lambda s: ProgressionRelay(s, self.backend, self.store))
+ hub.relay(lambda s: SettingsRelay(s, self.backend, self.store, self._publish_settings))
+ hub.relay(lambda s: CompanionRelay(s, self.backend))
+ hub.relay(
+ lambda s: CommandsRelay(
+ s, self.backend, launcher=self.launcher, qa=self.qa, on_open=self._after_open
+ )
+ )
+ for name, handler in (
+ ("lifecycle.state", self._n_state),
+ ("lifecycle.ready", self._n_ready),
+ ("lifecycle.bye", self._n_bye),
+ ("window.state", self._n_window),
+ ("panel.stream_state", self._n_panel_stream),
+ ("focus.return_to_app", self._n_return),
+ ):
+ hub.notice(name, handler)
+ self.qa["Verse.QA.SetDuty"] = self._qa_set_duty
+
+ def _make_roster(self, session: BridgeSession) -> RosterRelay:
+ relay = RosterRelay(session, self.backend)
+ relay.uniform = str(self.store.settings().get("uniform", "standard"))
+ self._roster = relay
+ return relay
+
+ async def _qa_set_duty(self, args: list[str]) -> Any:
+ if len(args) != 2:
+ raise P.BridgeError("bad_request", "Verse.QA.SetDuty <agent_id> <duty>")
+ if self._roster is None:
+ raise P.BridgeError("unavailable", "The roster relay is not running.")
+ return await self._roster.qa_set_duty(args[0], args[1])
+
+ # ------------------------------------------------------------------ urls, tokens
+ def bridge_url(self) -> str:
+ return f"ws://127.0.0.1:{self.port}{P.PATH}"
+
+ def set_port(self, port: int | None) -> None:
+ if port:
+ self.port = int(port)
+
+ def features(self) -> list[str]:
+ feats = list(P.BASE_FEATURES)
+ if not panel_available():
+ # The panel is Pixel Streaming (WP20); announced once its signalling lands.
+ feats.remove("panel")
+ if self.backend.duel_service() is not None:
+ feats.insert(feats.index("companion"), "duel_stats")
+ return feats
+
+ def _welcome(self, session: BridgeSession) -> dict[str, Any]:
+ self.hub.features = self.features()
+ config = getattr(getattr(self.app, "state", None), "config", None)
+ return {
+ "protocol": P.PROTOCOL,
+ "app_version": self.app_version,
+ "app_pid": os.getpid(),
+ "session": session.id,
+ "features": self.hub.features,
+ "encoding": {"screens": session.screens_encoding},
+ "limits": dict(P.LIMITS),
+ "locale": locale_block(config),
+ "settings": self.store.settings(),
+ "decks": list(DECKS),
+ "state": {"visibility": self.visibility, "panel": self.panel, "gpu": self.gpu},
+ }
+
+ def write_dev_discovery(self) -> Path | None:
+ """``<DATA_DIR>/verse/bridge.json`` for editor runs (contract 1, Dev discovery)."""
+ if not self.store.flag("dev_bridge", "DODAIOS_VERSE_DEV_BRIDGE"):
+ return None
+ token = mint_token()
+ self.tokens.set("dev", token)
+ path = self.data_dir / "bridge.json"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ body = {"url": self.bridge_url(), "token": token, "pid": os.getpid()}
+ path.write_text(json.dumps(body), encoding="utf-8")
+ restrict_to_user(path)
+ self.dev_file = path
+ return path
+
+ def remove_dev_discovery(self) -> None:
+ if self.dev_file is not None:
+ with contextlib.suppress(OSError):
+ self.dev_file.unlink()
+ self.dev_file = None
+ self.tokens.set("dev", None)
+
+ # ------------------------------------------------------------------ status
+ def _stale(self) -> bool:
+ cap = self.capability
+ return cap is None or (
+ cap.gpu.failed and time.time() - cap.checked_at >= probe_mod.RETRY_FAILED_S
+ )
+
+ def check(self, *, refresh: bool = False) -> probe_mod.Capability:
+ """The cached capability; blocking when it has to probe (sync callers only)."""
+ if refresh or self._stale():
+ self.capability = probe_mod.check(refresh=refresh)
+ assert self.capability is not None
+ return self.capability
+
+ async def acheck(self, *, refresh: bool = False) -> probe_mod.Capability:
+ """:meth:`check` for async paths: the GPU probe runs off the event loop."""
+ if refresh or self._stale():
+ self.capability = await asyncio.to_thread(probe_mod.check, refresh=refresh)
+ assert self.capability is not None
+ return self.capability
+
+ def status(self) -> dict[str, Any]:
+ sup = self.supervisor.state
+ if sup.status in ("running", "crashed"):
+ status = sup.status
+ else:
+ cap = self.check()
+ status = {"unsupported": "unsupported", "not_installed": "not_installed"}.get(
+ cap.status, "stopped"
+ )
+ running = status == "running"
+ return {
+ "status": status,
+ "state": (self.state or "booting") if running else None,
+ "pid": sup.pid if running else None,
+ "vram_mb": self.vram_mb if running else None,
+ "fps": self.fps if running else None,
+ "crash_report": sup.crash_report,
+ }
+
+ async def astatus(self) -> dict[str, Any]:
+ """:meth:`status` for async paths (any probe runs off the event loop)."""
+ await self.acheck()
+ return self.status()
+
+ async def _install_changed(self) -> None:
+ """A download finished or the Verse was removed: find the executable again."""
+ self.capability = None
+ await self.acheck()
+ await self._status_changed()
+
+ async def _before_remove(self) -> None:
+ if self.supervisor.running:
+ await self.supervisor.stop("update")
+
+ async def _status_changed(self) -> None:
+ if not self.supervisor.running:
+ self.state = None
+ self.vram_mb = self.fps = None
+ bus = self.backend.bus
+ if bus is None:
+ return
+ from dodaios.core.events import VerseStatusChanged
+
+ await self.acheck() # status() then reads the cache, never probes on the loop
+ st = self.status()
+ with contextlib.suppress(Exception):
+ await bus.publish(
+ VerseStatusChanged(
+ source_layer="verse_host",
+ status=st["status"],
+ state=st["state"] or "",
+ pid=st["pid"] or 0,
+ )
+ )
+
+ # ------------------------------------------------------------------ commands from the app
+ async def show(self, reason: str = "verse_view", monitor: dict[str, Any] | None = None) -> dict:
+ """Open the Verse view: launch lazily, then ``lifecycle.show`` once linked."""
+ if reason not in ("verse_view", "quick_start_duel", "station"):
+ raise ValueError(f"bad show reason {reason!r}")
+ cap = await self.acheck()
+ if cap.status != "ok" and self.supervisor.state.status != "running":
+ return self.status()
+ self.pending_show = {
+ "monitor": monitor or {"x": 0, "y": 0, "w": 1920, "h": 1080, "dpi": 96},
+ "reason": reason,
+ }
+ self._show_sent_at = time.monotonic()
+ if not self.supervisor.running:
+ self._launch_at = time.monotonic()
+ await self.supervisor.ensure_running(manual=True)
+ else:
+ await self._flush_show()
+ return self.status()
+
+ async def _flush_show(self) -> None:
+ session = self.hub.current
+ if session is None or self.pending_show is None:
+ return
+ allow_foreground(session.pid or self.supervisor.state.pid)
+ session.send("lifecycle.show", self.pending_show)
+ self.visibility = "visible"
+ self.pending_show = None
+
+ async def hide(self, reason: str = "user") -> bool:
+ if reason not in ("app_focus", "user", "minimised"):
+ raise ValueError(f"bad hide reason {reason!r}")
+ self.visibility = "hidden"
+ return await self.hub.push_all("lifecycle.hide", {"reason": reason})
+
+ async def app_took_focus(self) -> bool:
+ self.visibility = "hidden"
+ return await self.hub.push_all("focus.app_took", {})
+
+ async def pause(self, reason: str, *, resume: bool = False) -> bool:
+ return await self.hub.push_all(
+ "lifecycle.resume" if resume else "lifecycle.pause", {"reason": reason}
+ )
+
+ async def stop(self, reason: str = "app_quit") -> dict[str, Any]:
+ await self.supervisor.stop(reason)
+ return await self.astatus()
+
+ async def _request_quit(self, reason: str, deadline_ms: int) -> bool:
+ return await self.hub.push_all(
+ "lifecycle.quit", {"reason": reason, "deadline_ms": deadline_ms}
+ )
+
+ async def panel_visibility(self, visible: bool, w: int, h: int, dpr: float) -> bool:
+ self.panel = "visible" if visible else "hidden"
+ if visible and not self.supervisor.running and (await self.acheck()).status == "ok":
+ await self.supervisor.ensure_running(manual=True)
+ return await self.hub.push_all(
+ "panel.visibility", {"visible": visible, "w": w, "h": h, "dpr": dpr}
+ )
+
+ async def panel_resize(self, w: int, h: int, dpr: float) -> bool:
+ return await self.hub.push_all("panel.resize", {"w": w, "h": h, "dpr": dpr})
+
+ async def gpu_pressure(self, busy: bool, by: str = "other") -> bool:
+ """``gpu.yield`` / ``gpu.free``; a Dormant Verse quits itself on ``gpu.yield``."""
+ self.gpu = "yield" if busy else "free"
+ if by not in ("blender_cook", "local_stt", "local_model", "other"):
+ by = "other"
+ sent = await self.hub.push_all("gpu.yield" if busy else "gpu.free", {"by": by})
+ if sent and busy and self.state == "dormant":
+ # Contract 12: a Dormant Verse quits at once on gpu.yield. That exit
+ # gives the GPU back; it is not a crash and must not relaunch.
+ self.supervisor.expect_exit(GPU_YIELD_QUIT_S)
+ return sent
+
+ async def settings_changed(self, changed: dict[str, Any]) -> bool:
+ if not changed:
+ return False
+ return await self.hub.push_all("settings.changed", changed)
+
+ async def qa_exec(self, command: str, args: list[str]) -> dict[str, Any]:
+ """Run a ``Verse.QA.*`` command inside Verse (Shipping too); needs DODAIOS_VERSE_QA=1."""
+ from .relays.commands import qa_enabled
+
+ if not qa_enabled():
+ raise P.BridgeError("unavailable", "QA commands need DODAIOS_VERSE_QA=1.")
+ if not command.startswith("Verse.QA."):
+ raise P.BridgeError("bad_request", "command must be a Verse.QA.* command.")
+ session = self.hub.current
+ if session is None:
+ raise P.BridgeError("unavailable", "Verse is not connected.")
+ return await session.request("qa.exec", {"command": command, "args": list(args)})
+
+ async def _publish_settings(self, changed: dict[str, Any]) -> None:
+ bus = self.backend.bus
+ if bus is None:
+ return
+ from dodaios.core.events import VerseSettingsChanged
+
+ await bus.publish(VerseSettingsChanged(source_layer="verse_host", settings=changed))
+
+ async def _after_open(self) -> None:
+ self.visibility = "hidden"
+
+ # ------------------------------------------------------------------ bridge callbacks
+ async def _on_hung(self, session: BridgeSession) -> None:
+ await self.supervisor.on_hung()
+
+ async def _on_session(self, session: BridgeSession | None) -> None:
+ if session is None:
+ return
+ await self._flush_show()
+ if self._idle_task is None or self._idle_task.done():
+ self._idle_task = asyncio.ensure_future(self._idle_loop())
+
+ async def _n_state(self, session: BridgeSession, msg: P.Inbound) -> None:
+ state = msg.data.get("state")
+ if state not in P.LIFECYCLE_STATES:
+ return
+ previous, self.state = self.state, state
+ vram = msg.data.get("vram_mb")
+ fps = msg.data.get("fps")
+ self.vram_mb = vram if isinstance(vram, int) else self.vram_mb
+ self.fps = float(fps) if isinstance(fps, int | float) else self.fps
+ now = time.monotonic()
+ if state == "dormant":
+ self.dormant_since = now
+ self.visibility = "hidden"
+ else:
+ self.dormant_since = None
+ if state == "visible":
+ self.visibility = "visible"
+ if previous == "dormant" and self._show_sent_at is not None:
+ self.timings["dormant_to_visible_ms"] = round((now - self._show_sent_at) * 1000)
+ if previous != state:
+ await self._status_changed()
+
+ async def _n_ready(self, session: BridgeSession, msg: P.Inbound) -> None:
+ self.supervisor.mark_healthy()
+ first = msg.data.get("first_frame_ms")
+ if isinstance(first, int | float):
+ self.timings["first_frame_ms"] = first
+ if self._launch_at is not None:
+ self.timings["cold_start_ms"] = round((time.monotonic() - self._launch_at) * 1000)
+ self._launch_at = None
+
+ async def _n_bye(self, session: BridgeSession, msg: P.Inbound) -> None:
+ log.info("verse host: Verse said bye (saved=%s)", msg.data.get("saved"))
+ # Verse quits after a bye (an answer to lifecycle.quit, or its own exit,
+ # e.g. after a launch): the exit that follows is a stop.
+ self.supervisor.expect_exit()
+
+ async def _n_window(self, session: BridgeSession, msg: P.Inbound) -> None:
+ visible = msg.data.get("visible")
+ if isinstance(visible, bool):
+ self.visibility = "visible" if visible else "hidden"
+
+ async def _n_panel_stream(self, session: BridgeSession, msg: P.Inbound) -> None:
+ state = msg.data.get("state")
+ if state in ("starting", "streaming", "stopped", "failed"):
+ session.panel_stream = dict(msg.data)
+
+ async def _n_return(self, session: BridgeSession, msg: P.Inbound) -> None:
+ """Verse hid itself and allowed our foreground: raise the app window."""
+ self.visibility = "hidden"
+ bus = self.backend.bus
+ if bus is None:
+ return
+ from dodaios.core.events import ShowWindowRequested
+
+ await bus.publish(ShowWindowRequested(source_layer="verse_host", source="verse_return"))
+
+ async def _idle_loop(self) -> None:
+ """Dormant for 10 minutes: ask Verse to quit (``idle_10min``)."""
+ while self.hub.current is not None:
+ await asyncio.sleep(5.0)
+ since = self.dormant_since
+ if since is not None and time.monotonic() - since >= IDLE_QUIT_S:
+ self.dormant_since = None
+ await self.supervisor.stop("idle_10min")
+ return
+
+ # ------------------------------------------------------------------ import
+ def import_browser_settings(self, values: dict[str, Any]) -> list[str]:
+ """``POST /api/verse/settings/import``: write each key only where it is still unset."""
+ if self.store.get("imported"):
+ return []
+ patch: dict[str, Any] = {}
+ imported: list[str] = []
+ view = values.get("dodaios.verse.view.v1")
+ if isinstance(view, str):
+ with contextlib.suppress(ValueError):
+ view = json.loads(view)
+ if isinstance(view, dict):
+ clean: dict[str, Any] = {}
+ for key, value in view.items():
+ if self.store.is_set(f"view.{key}"):
+ continue
+ try:
+ from .settings_store import validate
+
+ clean.update(validate({"view": {key: value}})["view"])
+ except ValueError: # invalid browser value is skipped on import
+ continue
+ if clean:
+ patch["view"] = clean
+ imported.append("dodaios.verse.view.v1")
+ uniform = values.get("dodaios.verse.uniform.v1")
+ if isinstance(uniform, str) and uniform and not self.store.is_set("uniform"):
+ patch["uniform"] = uniform.strip('"')[:40]
+ imported.append("dodaios.verse.uniform.v1")
+ sound = values.get("jarvis.verse.level.sound.v1")
+ if sound is not None and not self.store.is_set("level_sound"):
+ patch["level_sound"] = str(sound).strip('"').lower() not in ("0", "false", "off")
+ imported.append("jarvis.verse.level.sound.v1")
+ if patch:
+ self.store.update(patch)
+ seen = values.get("jarvis.verse.levels.seen.v1")
+ if seen is not None and self.store.get("told_seq") is None:
+ with contextlib.suppress(TypeError, ValueError):
+ self.store.raise_told_seq(int(str(seen).strip('"')))
+ imported.append("jarvis.verse.levels.seen.v1")
+ best = values.get("jarvis.office.arcade.asteroids.best")
+ if best is not None and self.store.get("arcade_best") is None:
+ with contextlib.suppress(TypeError, ValueError):
+ self.store.put("arcade_best", int(str(best).strip('"')))
+ imported.append("jarvis.office.arcade.asteroids.best")
+ self.store.put("imported", True)
+ return imported
+
+
+class _LaunchSteps:
+ """The backend port as the launch sequence's steps."""
+
+ def __init__(self, backend: BackendPort) -> None:
+ self.backend = backend
+
+ async def open_terminal(self, workspace_id: str | None, agent: str) -> tuple[str, str]:
+ return await self.backend.open_terminal(workspace_id, agent)
+
+ async def start_terminal(self, name: str, workspace_id: str) -> None:
+ await self.backend.start_terminal(name, workspace_id)
+
+ async def list_panes(self) -> list[dict[str, Any]]:
+ return await self.backend.list_panes()
+
+ async def prompt_terminal(self, name: str, text: str, workspace_id: str) -> bool | None:
+ return await self.backend.prompt_terminal(name, text, workspace_id)
+
+
+def get_host(app: Any) -> VerseHost:
+ host = getattr(app.state, "verse_host", None)
+ if host is None:
+ host = VerseHost(app)
+ app.state.verse_host = host
+ return host
diff --git a/dodaios/verse_host/install_port.py b/dodaios/verse_host/install_port.py
new file mode 100644
index 0000000000..4205f9e432
--- /dev/null
+++ b/dodaios/verse_host/install_port.py
@@ -0,0 +1,327 @@
+"""The on-demand Verse download, as the host and its routes see it (README Delivery).
+
+The Unreal Verse is never part of the installer, a ``git clone`` or an app
+update. When the host status is ``not_installed`` the launcher card offers
+"Download the Verse"; Settings offers "Remove the Verse". The work itself
+(manifest, resumable download, signature and hash check, unpack, uninstall)
+belongs to WP22's package ``dodaios.verse_host.install``. This module is the
+seam between the two:
+
+* :class:`VerseInstaller` is the interface the package implements. Its
+ module exposes ``get_installer(data_dir: Path) -> VerseInstaller``; the
+ build it installs lands in ``<data_dir>/verse/build`` so
+ :func:`dodaios.verse_host.probe.candidate_executables` finds it.
+* :class:`InstallJob` runs one download at a time (single flight), keeps the
+ progress the card polls, cancels on request and refreshes the host status
+ when the install finishes or the Verse is removed.
+* Until the package lands, :func:`load_installer` returns
+ :class:`UnavailableInstaller` (the card says the download is not published
+ yet). ``DODAIOS_VERSE_FAKE_INSTALL=1`` selects :class:`SimulatedInstaller`
+ for UI checks: it walks through the progress states and installs nothing.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import importlib
+import logging
+import time
+from collections.abc import Awaitable, Callable
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from typing import Any, Literal, Protocol, runtime_checkable
+
+from .env import getenv
+
+log = logging.getLogger(__name__)
+
+INSTALL_MODULE = "dodaios.verse_host.install"
+FAKE_ENV = "DODAIOS_VERSE_FAKE_INSTALL"
+
+Phase = Literal["downloading", "verifying", "installing"]
+JobState = Literal[
+ "idle", # nothing running; see ``installed_version`` for what is on disk
+ "downloading",
+ "verifying",
+ "installing",
+ "installed", # the last run finished
+ "cancelled",
+ "failed",
+ "removing",
+ "unavailable", # no package published for this platform (or WP22 not landed)
+]
+ProgressFn = Callable[[Phase, int, int], None]
+
+
+@dataclass(frozen=True)
+class Manifest:
+ """What the published Verse package for this platform is."""
+
+ version: str
+ download_bytes: int
+ install_bytes: int
+
+
+class InstallError(Exception):
+ """The installer refused or failed; ``message`` is shown on the card."""
+
+ def __init__(self, message: str) -> None:
+ super().__init__(message)
+ self.message = message
+
+
+@runtime_checkable
+class VerseInstaller(Protocol):
+ """Implemented by ``dodaios.verse_host.install`` (WP22.5)."""
+
+ async def manifest(self) -> Manifest | None:
+ """The package on offer, or ``None`` when none is published for this platform."""
+ ...
+
+ def installed_version(self) -> str | None:
+ """The version on disk, or ``None`` when the Verse is not installed."""
+ ...
+
+ async def install(self, progress: ProgressFn) -> None:
+ """Download (resuming a partial file), verify and unpack.
+
+ Calls ``progress(phase, done_bytes, total_bytes)`` as it goes. A task
+ cancel (``asyncio.CancelledError``) stops it and keeps the partial
+ download for the next resume. Raises :class:`InstallError` when the
+ package is rejected (signature, hash, disk space).
+ """
+ ...
+
+ async def uninstall(self) -> None:
+ """Delete the installed Verse folder; a no-op when nothing is installed."""
+ ...
+
+
+class UnavailableInstaller:
+ """Stand-in until WP22's package lands: nothing to download, nothing installed."""
+
+ async def manifest(self) -> Manifest | None:
+ return None
+
+ def installed_version(self) -> str | None:
+ return None
+
+ async def install(self, progress: ProgressFn) -> None:
+ raise InstallError("The Verse download is not published yet.")
+
+ async def uninstall(self) -> None:
+ return None
+
+
+class SimulatedInstaller:
+ """UI check double (``DODAIOS_VERSE_FAKE_INSTALL=1``): progress only, no files."""
+
+ def __init__(self, *, download_bytes: int = 7_400_000_000, seconds: float = 40.0) -> None:
+ self.download_bytes = download_bytes
+ self.seconds = seconds
+ self.version: str | None = None
+ self.done = 0
+
+ async def manifest(self) -> Manifest | None:
+ return Manifest("0.0.0-simulated", self.download_bytes, int(self.download_bytes * 1.4))
+
+ def installed_version(self) -> str | None:
+ return self.version
+
+ async def install(self, progress: ProgressFn) -> None:
+ steps = 200
+ chunk = self.download_bytes // steps
+ while self.done < self.download_bytes:
+ await asyncio.sleep(self.seconds / steps)
+ self.done = min(self.download_bytes, self.done + chunk)
+ progress("downloading", self.done, self.download_bytes)
+ progress("verifying", self.download_bytes, self.download_bytes)
+ await asyncio.sleep(0.5)
+ progress("installing", self.download_bytes, self.download_bytes)
+ await asyncio.sleep(0.5)
+ self.version = "0.0.0-simulated"
+
+ async def uninstall(self) -> None:
+ self.version = None
+ self.done = 0
+
+
+def load_installer(data_dir: Path) -> VerseInstaller:
+ """WP22's installer when present, else the simulated or the unavailable one."""
+ if getenv(FAKE_ENV).strip() == "1":
+ return SimulatedInstaller()
+ try:
+ module = importlib.import_module(INSTALL_MODULE)
+ except ImportError: # WP22 install package not landed; the card says not published
+ return UnavailableInstaller()
+ factory = getattr(module, "get_installer", None)
+ if factory is None:
+ log.warning("verse install: %s has no get_installer(); download disabled", INSTALL_MODULE)
+ return UnavailableInstaller()
+ installer = factory(Path(data_dir))
+ if not isinstance(installer, VerseInstaller):
+ log.warning("verse install: %s.get_installer() returned %r", INSTALL_MODULE, installer)
+ return UnavailableInstaller()
+ return installer
+
+
+@dataclass
+class Progress:
+ state: JobState = "idle"
+ done_bytes: int = 0
+ total_bytes: int = 0
+ version: str | None = None
+ installed_version: str | None = None
+ download_bytes: int | None = None
+ install_bytes: int | None = None
+ error: str | None = None
+ started_at: float | None = None
+ bytes_per_s: float | None = None
+
+ def to_json(self) -> dict[str, Any]:
+ out = asdict(self)
+ out.pop("started_at")
+ return out
+
+
+class InstallBusy(Exception):
+ """A remove was asked for while a download runs (cancel it first)."""
+
+
+class InstallJob:
+ """One download or removal at a time; the routes read :meth:`progress`."""
+
+ def __init__(
+ self,
+ installer: VerseInstaller,
+ *,
+ on_change: Callable[[], Awaitable[None]] | None = None,
+ before_remove: Callable[[], Awaitable[None]] | None = None,
+ ) -> None:
+ self.installer = installer
+ self.on_change = on_change
+ self.before_remove = before_remove
+ self._progress = Progress()
+ self._task: asyncio.Task[None] | None = None
+ self._manifest: Manifest | None = None
+ self._manifest_at = 0.0
+
+ @property
+ def running(self) -> bool:
+ return self._task is not None and not self._task.done()
+
+ async def _read_manifest(self, *, refresh: bool = False) -> Manifest | None:
+ if refresh or self._manifest is None or time.monotonic() - self._manifest_at > 600:
+ try:
+ self._manifest = await self.installer.manifest()
+ except Exception as exc: # noqa: BLE001 - offline, server error: show and retry later
+ log.info("verse install: manifest unavailable: %s", exc)
+ self._manifest = None
+ self._manifest_at = time.monotonic()
+ return self._manifest
+
+ async def progress(self, *, refresh: bool = False) -> dict[str, Any]:
+ p = self._progress
+ if not self.running:
+ manifest = await self._read_manifest(refresh=refresh)
+ p.installed_version = self.installer.installed_version()
+ if manifest is None:
+ p.download_bytes = p.install_bytes = p.version = None
+ if p.state in ("idle", "unavailable"):
+ p.state = "unavailable"
+ else:
+ p.version = manifest.version
+ p.download_bytes = manifest.download_bytes
+ p.install_bytes = manifest.install_bytes
+ if p.state == "unavailable":
+ p.state = "idle"
+ return p.to_json()
+
+ async def start(self) -> dict[str, Any]:
+ """Start the download; a second call while one runs joins it."""
+ if self.running:
+ return self._progress.to_json()
+ manifest = await self._read_manifest(refresh=True)
+ if manifest is None:
+ self._progress = Progress(
+ state="unavailable",
+ installed_version=self.installer.installed_version(),
+ error="The Verse download is not published yet.",
+ )
+ return self._progress.to_json()
+ self._progress = Progress(
+ state="downloading",
+ total_bytes=manifest.download_bytes,
+ version=manifest.version,
+ download_bytes=manifest.download_bytes,
+ install_bytes=manifest.install_bytes,
+ installed_version=self.installer.installed_version(),
+ started_at=time.monotonic(),
+ )
+ self._task = asyncio.ensure_future(self._run())
+ return self._progress.to_json()
+
+ def _report(self, phase: Phase, done: int, total: int) -> None:
+ p = self._progress
+ p.state = phase
+ p.done_bytes = max(0, int(done))
+ p.total_bytes = max(p.done_bytes, int(total))
+ if phase == "downloading" and p.started_at is not None:
+ spent = time.monotonic() - p.started_at
+ if spent > 0.5:
+ p.bytes_per_s = p.done_bytes / spent
+
+ async def _run(self) -> None:
+ p = self._progress
+ try:
+ await self.installer.install(self._report)
+ except asyncio.CancelledError:
+ p.state = "cancelled"
+ p.bytes_per_s = None
+ raise
+ except InstallError as exc: # shown on the card as the failure reason
+ p.state, p.error = "failed", exc.message
+ except Exception as exc: # noqa: BLE001 - a network or disk error ends this run only
+ log.warning("verse install failed: %s", exc)
+ p.state, p.error = "failed", str(exc) or exc.__class__.__name__
+ else:
+ p.state = "installed"
+ p.done_bytes = p.total_bytes
+ p.installed_version = self.installer.installed_version()
+ finally:
+ p.bytes_per_s = None if p.state != "installed" else p.bytes_per_s
+ await self._changed()
+
+ async def cancel(self) -> bool:
+ task = self._task
+ if task is None or task.done():
+ return False
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError, Exception):
+ await task
+ return True
+
+ async def remove(self) -> dict[str, Any]:
+ """Stop the Verse and delete the installed build."""
+ if self.running:
+ raise InstallBusy("A download is running; cancel it first.")
+ if self.before_remove is not None:
+ await self.before_remove()
+ self._progress.state = "removing"
+ try:
+ await self.installer.uninstall()
+ except Exception as exc: # noqa: BLE001 - files in use, permissions
+ self._progress.state, self._progress.error = "failed", str(exc)
+ raise InstallError(f"The Verse could not be removed: {exc}") from exc
+ self._progress = Progress()
+ await self._changed()
+ return await self.progress()
+
+ async def _changed(self) -> None:
+ if self.on_change is None:
+ return
+ try:
+ await self.on_change()
+ except Exception: # noqa: BLE001
+ log.exception("verse install: status refresh failed")
diff --git a/dodaios/verse_host/ports.py b/dodaios/verse_host/ports.py
new file mode 100644
index 0000000000..3c73e900d9
--- /dev/null
+++ b/dodaios/verse_host/ports.py
@@ -0,0 +1,307 @@
+"""What the verse host needs from the rest of the backend, as one port.
+
+The relays never speak HTTP: every command is "executed by the relay
+in-process" (architecture 5.2). :class:`AppBackend` calls the same route
+functions the web UI reaches over REST, with a synthetic request bound to
+the running app, so both callers share one code path. Tests use a fake port.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from collections.abc import Awaitable, Callable
+from typing import Any, Protocol
+
+log = logging.getLogger(__name__)
+
+
+class UnknownWorldAction(ValueError):
+ """``progression.action`` named an action the rulebook does not list."""
+
+
+class NotFound(LookupError):
+ """The pane, agent, group or session a command names is gone."""
+
+
+OutputHandler = Callable[[str], Awaitable[None]]
+ExitHandler = Callable[[int], Awaitable[None]]
+
+
+class BackendPort(Protocol):
+ """Reads and actions of the backend the relays use."""
+
+ @property
+ def bus(self) -> Any: ...
+
+ async def list_agents(self) -> list[dict[str, Any]]: ...
+ async def list_panes(self) -> list[dict[str, Any]]: ...
+ async def progression(self) -> dict[str, Any]: ...
+ async def report_action(self, action: str, ref: str) -> dict[str, Any] | None: ...
+ def duel_service(self) -> Any | None: ...
+ async def chat_tail(self, session_id: str, tail: int) -> list[dict[str, Any]] | None: ...
+ async def chat_groups(self) -> list[dict[str, Any]]: ...
+ async def group_meeting(self, group_id: str) -> dict[str, Any] | None: ...
+ async def meeting_start(self, group_id: str, text: str) -> dict[str, Any]: ...
+ async def meeting_stop(self, group_id: str) -> dict[str, Any]: ...
+ async def confirm_dangerous(self, action: str, detail: str) -> bool: ...
+ async def create_agent(self, fields: dict[str, Any]) -> str: ...
+ async def ide_state(self) -> dict[str, Any]: ...
+ async def ide_agents(self) -> list[dict[str, Any]]: ...
+ async def open_terminal(self, workspace_id: str | None, agent: str) -> tuple[str, str]: ...
+ async def start_terminal(self, name: str, workspace_id: str) -> None: ...
+ async def prompt_terminal(self, name: str, text: str, workspace_id: str) -> bool | None: ...
+ async def active_pet(self) -> dict[str, Any]: ...
+ async def attach_screen(
+ self, pane_id: str, on_output: OutputHandler, on_exit: ExitHandler
+ ) -> tuple[int, int] | None: ...
+ def detach_screen(self, pane_id: str, on_output: OutputHandler) -> None: ...
+ def plain_screen(self, pane_id: str) -> dict[str, Any] | None: ...
+
+
+def split_pane_id(pane_id: str) -> tuple[str, str]:
+ """``<workspace_id>:<key>`` -> ``(workspace_id, key)``; NotFound when malformed."""
+ workspace_id, sep, key = pane_id.partition(":")
+ if not sep or not workspace_id or not key:
+ raise NotFound(f"bad pane id {pane_id!r}")
+ return workspace_id, key
+
+
+def _status(exc: BaseException) -> int | None:
+ return getattr(exc, "status_code", None)
+
+
+class AppBackend:
+ """The live backend: route functions called in-process against ``app``."""
+
+ def __init__(self, app: Any) -> None:
+ self.app = app
+
+ @property
+ def bus(self) -> Any:
+ return getattr(self.app.state, "bus", None)
+
+ def _request(self, method: str = "GET") -> Any:
+ from starlette.requests import Request
+
+ scope = {
+ "type": "http",
+ "app": self.app,
+ "method": method,
+ "path": "/api/verse/bridge",
+ "headers": [],
+ "query_string": b"",
+ "client": ("127.0.0.1", 0),
+ }
+ return Request(scope)
+
+ # ------------------------------------------------------------------ reads
+ async def list_agents(self) -> list[dict[str, Any]]:
+ from dodaios.ui.web import society_routes
+
+ body = await society_routes.list_agents(self._request(), include_archived=False)
+ return list(body.get("agents", []))
+
+ async def list_panes(self) -> list[dict[str, Any]]:
+ from dodaios.ui.web import agentic_ide_routes
+
+ body = await asyncio.to_thread(agentic_ide_routes.get_panes)
+ return list(body.get("panes", []))
+
+ async def progression(self) -> dict[str, Any]:
+ from dodaios.ui.web import progression_routes
+
+ return await progression_routes.get_progression(self._request(), after_seq=0)
+
+ async def report_action(self, action: str, ref: str) -> dict[str, Any] | None:
+ from dodaios.progression.service import UnknownAction
+
+ service = getattr(self.app.state, "progression", None)
+ if service is None:
+ raise RuntimeError("progression service is not running")
+ try:
+ award = await service.report_action(action, ref=ref)
+ except UnknownAction as exc:
+ raise UnknownWorldAction(str(exc)) from exc
+ return award.to_dict() if award is not None else None
+
+ def duel_service(self) -> Any | None:
+ """The progression service when it records duels (WP21), else ``None``."""
+ service = getattr(self.app.state, "progression", None)
+ return service if callable(getattr(service, "record_duel", None)) else None
+
+ async def chat_tail(self, session_id: str, tail: int) -> list[dict[str, Any]] | None:
+ from dodaios.ui.web import agent_chat_routes
+
+ try:
+ body = await agent_chat_routes.get_session(session_id, self._request(), tail=tail)
+ except Exception as exc: # noqa: BLE001 - a 404 means "no chat yet"
+ if _status(exc) == 404:
+ return None
+ raise
+ return list(body.get("events", []))
+
+ async def chat_groups(self) -> list[dict[str, Any]]:
+ from dodaios.ui.web import society_routes
+
+ body = await society_routes.list_chat_groups(self._request())
+ return list(body.get("groups", body.get("chat_groups", [])))
+
+ async def group_meeting(self, group_id: str) -> dict[str, Any] | None:
+ from dodaios.ui.web import society_routes
+
+ try:
+ return await society_routes.get_group_meeting(group_id, self._request())
+ except Exception as exc: # noqa: BLE001
+ if _status(exc) == 404:
+ return None
+ raise
+
+ async def meeting_start(self, group_id: str, text: str) -> dict[str, Any]:
+ from dodaios.ui.web import society_routes
+
+ body = society_routes.MeetingMessageBody(text=text)
+ try:
+ return await society_routes.send_group_meeting(group_id, body, self._request("POST"))
+ except Exception as exc: # noqa: BLE001
+ if _status(exc) == 404:
+ raise NotFound(group_id) from exc
+ raise
+
+ async def meeting_stop(self, group_id: str) -> dict[str, Any]:
+ from dodaios.ui.web import society_routes
+
+ try:
+ return await society_routes.stop_group_meeting(group_id, self._request("POST"))
+ except Exception as exc: # noqa: BLE001
+ if _status(exc) == 404:
+ raise NotFound(group_id) from exc
+ raise
+
+ async def confirm_dangerous(self, action: str, detail: str) -> bool:
+ """The app's confirmation path for a dangerous station command.
+
+ A host that installs ``app.state.verse_confirm`` (an async
+ ``(action, detail) -> bool``) decides. Without one, the person's own
+ press at the Verse station (which asks before it sends) confirms.
+ """
+ confirm = getattr(self.app.state, "verse_confirm", None)
+ if confirm is None:
+ return True
+ return bool(await confirm(action, detail))
+
+ async def create_agent(self, fields: dict[str, Any]) -> str:
+ from dodaios.ui.web import society_routes
+
+ body = society_routes.CreateAgentBody(**fields)
+ result = await society_routes.create_agent(body, self._request("POST"))
+ agent = result.get("agent", result)
+ return str(agent.get("agent_id", ""))
+
+ async def ide_state(self) -> dict[str, Any]:
+ from dodaios.ui.web import agentic_ide_routes
+
+ return await asyncio.to_thread(agentic_ide_routes.get_state)
+
+ async def ide_agents(self) -> list[dict[str, Any]]:
+ from dodaios.ui.web import agentic_ide_routes
+
+ body = await agentic_ide_routes.get_agents(quick=True)
+ data = body.model_dump() if hasattr(body, "model_dump") else dict(body)
+ return list(data.get("agents", []))
+
+ # ------------------------------------------------------------------ launcher
+ async def open_terminal(self, workspace_id: str | None, agent: str) -> tuple[str, str]:
+ from dodaios.ui.web import agentic_ide_routes
+
+ req = agentic_ide_routes.AddTerminalRequest(workspace_id=workspace_id, agent=agent)
+ body = await agentic_ide_routes.add_terminal(req)
+ term = body.get("terminal", {})
+ state = body.get("state", {}) or {}
+ ws = str(term.get("workspace_id") or workspace_id or state.get("active_id") or "")
+ return ws, str(term.get("name") or term.get("key") or "")
+
+ async def start_terminal(self, name: str, workspace_id: str) -> None:
+ from dodaios.ui.web import agentic_ide_routes
+
+ await agentic_ide_routes.terminal_start(name, workspace_id)
+
+ async def prompt_terminal(self, name: str, text: str, workspace_id: str) -> bool | None:
+ from dodaios.ui.web import agentic_ide_routes
+
+ req = agentic_ide_routes.PromptRequest(prompt=text)
+ body = await agentic_ide_routes.terminal_prompt(
+ self._request("POST"), name, req, workspace_id
+ )
+ submitted = body.get("submitted") if isinstance(body, dict) else None
+ return submitted if isinstance(submitted, bool) else None
+
+ # ------------------------------------------------------------------ companion
+ async def active_pet(self) -> dict[str, Any]:
+ cfg = getattr(self.app.state, "config", None)
+ pet = getattr(cfg, "pet", None)
+ ui = getattr(cfg, "ui", None)
+ pet_id = str(
+ getattr(ui, "pet_id", "") or getattr(pet, "pet_id", "") or getattr(pet, "id", "") or ""
+ )
+ service = getattr(self.app.state, "progression", None)
+ if not pet_id and service is not None:
+ try:
+ pet_id = str(service.current_pet() or "")
+ except Exception: # noqa: BLE001
+ log.debug("verse: current pet unavailable", exc_info=True)
+ pet_id = ""
+ style = str(getattr(ui, "overlay_style", "") or "default")
+ look = str(getattr(pet, "look", "") or pet_id or "")
+ return {"pet_id": pet_id or "drone", "look": look or "drone", "style": style}
+
+ # ------------------------------------------------------------------ screens
+ def _registry(self) -> Any:
+ from dodaios.agentic_ide.session import get_registry
+
+ return get_registry()
+
+ async def attach_screen(
+ self, pane_id: str, on_output: OutputHandler, on_exit: ExitHandler
+ ) -> tuple[int, int] | None:
+ """Attach as a non-claiming viewer; the replay seeds the mirror. Returns the PTY size."""
+ workspace_id, key = split_pane_id(pane_id)
+ registry = self._registry()
+
+ async def on_replay(text: str, repaint: bool = False) -> None:
+ await on_output(text)
+
+ try:
+ await registry.attach(
+ key,
+ 80,
+ 24,
+ on_output,
+ on_exit,
+ workspace_id=workspace_id,
+ on_replay=on_replay,
+ claim_owner=False,
+ )
+ except Exception as exc: # noqa: BLE001
+ raise NotFound(pane_id) from exc
+ geometry = registry.pty_geometry(key, workspace_id)
+ return (int(geometry[0]), int(geometry[1])) if geometry else None
+
+ def detach_screen(self, pane_id: str, on_output: OutputHandler) -> None:
+ try:
+ workspace_id, key = split_pane_id(pane_id)
+ self._registry().detach(key, workspace_id, viewer=on_output)
+ except Exception: # noqa: BLE001 - detaching a gone pane is a no-op
+ log.debug("verse: detach of %s failed", pane_id, exc_info=True)
+
+ def plain_screen(self, pane_id: str) -> dict[str, Any] | None:
+ """The plain ``ScreenBuffer`` rows of one pane (the fallback of 5.1)."""
+ from dodaios.agentic_ide import screen_feed
+
+ try:
+ refs = screen_feed.parse_pane_refs([pane_id])
+ shots = screen_feed.collect_screens(self._registry(), refs)
+ except Exception: # noqa: BLE001
+ log.debug("verse: screen capture failed", exc_info=True)
+ return None
+ return shots[0] if shots else None
diff --git a/dodaios/verse_host/probe.py b/dodaios/verse_host/probe.py
new file mode 100644
index 0000000000..912123e73a
--- /dev/null
+++ b/dodaios/verse_host/probe.py
@@ -0,0 +1,325 @@
+"""Capability probe (17.4, architecture 1.1): can this machine run the Verse?
+
+Windows: a hardware D3D12 adapter with shader model 6 and at least 6 GB of
+dedicated VRAM. Linux: a Vulkan 1.3 device that is not a CPU device. No
+such device means ``unsupported``; the rest of the app is untouched.
+
+The GPU check runs in a short-lived child process (``python -m
+dodaios.verse_host.probe``) so a driver fault cannot take the app down and
+no D3D12 device lives in the app process. Results are cached per run.
+
+Install check: the first existing ``Verse`` executable of
+:func:`candidate_executables` (``DODAIOS_VERSE_EXE``, the installed build
+under ``<DATA_DIR>/verse/build`` that the on-demand download writes
+(``install_port``), a dev staged build under ``unreal/Verse/Saved/StagedBuilds``).
+The installer and app updates never carry the Verse, so a fresh install is
+``not_installed`` until the user downloads it.
+
+``DODAIOS_VERSE_PROBE=pass`` or ``=fail`` overrides the GPU check (tests,
+CI runners without a GPU).
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+import time
+from dataclasses import asdict, dataclass, field
+from pathlib import Path
+from typing import Any
+
+from .env import getenv
+
+MIN_VRAM_MB = 6 * 1024
+PROBE_TIMEOUT_S = 20.0
+
+
+@dataclass
+class GpuReport:
+ ok: bool
+ api: str = ""
+ adapter: str = ""
+ vram_mb: int = 0
+ shader_model: str = ""
+ reason: str = ""
+ adapters: list[dict[str, Any]] = field(default_factory=list)
+ # The probe itself failed (timeout, crash, garbled output): no verdict yet,
+ # so it is asked again later instead of reading as a final "unsupported".
+ failed: bool = False
+
+
+# ---------------------------------------------------------------------- Windows
+
+
+def _probe_d3d12() -> GpuReport: # pragma: no cover - needs a Windows GPU
+ import ctypes
+ from ctypes import wintypes
+
+ class GUID(ctypes.Structure):
+ _fields_ = [
+ ("Data1", ctypes.c_uint32),
+ ("Data2", ctypes.c_uint16),
+ ("Data3", ctypes.c_uint16),
+ ("Data4", ctypes.c_ubyte * 8),
+ ]
+
+ def guid(text: str) -> GUID:
+ import uuid
+
+ u = uuid.UUID(text)
+ g = GUID()
+ g.Data1, g.Data2, g.Data3 = u.fields[0], u.fields[1], u.fields[2]
+ g.Data4[:] = list(u.bytes[8:])
+ return g
+
+ class DXGI_ADAPTER_DESC1(ctypes.Structure): # noqa: N801
+ _fields_ = [
+ ("Description", wintypes.WCHAR * 128),
+ ("VendorId", wintypes.UINT),
+ ("DeviceId", wintypes.UINT),
+ ("SubSysId", wintypes.UINT),
+ ("Revision", wintypes.UINT),
+ ("DedicatedVideoMemory", ctypes.c_size_t),
+ ("DedicatedSystemMemory", ctypes.c_size_t),
+ ("SharedSystemMemory", ctypes.c_size_t),
+ ("AdapterLuidLow", wintypes.DWORD),
+ ("AdapterLuidHigh", wintypes.LONG),
+ ("Flags", wintypes.UINT),
+ ]
+
+ def vcall(obj: ctypes.c_void_p, index: int, restype: Any, *argtypes: Any) -> Any:
+ vtable = ctypes.cast(obj, ctypes.POINTER(ctypes.POINTER(ctypes.c_void_p))).contents
+ proto = ctypes.WINFUNCTYPE(restype, ctypes.c_void_p, *argtypes)
+ return proto(vtable[index])
+
+ def release(obj: ctypes.c_void_p) -> None:
+ if obj:
+ vcall(obj, 2, ctypes.c_ulong)(obj)
+
+ try:
+ dxgi = ctypes.WinDLL("dxgi")
+ d3d12 = ctypes.WinDLL("d3d12")
+ except OSError as exc:
+ return GpuReport(False, "d3d12", reason=f"no D3D12 runtime: {exc}")
+
+ factory = ctypes.c_void_p()
+ iid_factory = guid("770aae78-f26f-4dba-a829-253c83d1b387")
+ hr = dxgi.CreateDXGIFactory1(ctypes.byref(iid_factory), ctypes.byref(factory))
+ if hr != 0:
+ return GpuReport(False, "d3d12", reason=f"CreateDXGIFactory1 failed {hr & 0xFFFFFFFF:#x}")
+ iid_device = guid("189819f1-1db6-4b57-be54-1821339b85f7")
+ best: GpuReport | None = None
+ adapters: list[dict[str, Any]] = []
+ try:
+ enum = vcall(factory, 12, ctypes.c_long, wintypes.UINT, ctypes.POINTER(ctypes.c_void_p))
+ index = 0
+ while True:
+ adapter = ctypes.c_void_p()
+ if enum(factory, index, ctypes.byref(adapter)) != 0:
+ break
+ index += 1
+ try:
+ desc = DXGI_ADAPTER_DESC1()
+ vcall(adapter, 10, ctypes.c_long, ctypes.POINTER(DXGI_ADAPTER_DESC1))(
+ adapter, ctypes.byref(desc)
+ )
+ software = bool(desc.Flags & 2)
+ vram_mb = int(desc.DedicatedVideoMemory // (1024 * 1024))
+ row = {"name": desc.Description, "vram_mb": vram_mb, "software": software}
+ adapters.append(row)
+ if software:
+ continue
+ device = ctypes.c_void_p()
+ hr = d3d12.D3D12CreateDevice(
+ adapter, 0xC000, ctypes.byref(iid_device), ctypes.byref(device)
+ )
+ if hr != 0:
+ row["d3d12"] = False
+ continue
+ try:
+ sm = ctypes.c_uint32(0x60)
+ check = vcall(
+ device, 13, ctypes.c_long, ctypes.c_int, ctypes.c_void_p, wintypes.UINT
+ )
+ hr = check(device, 7, ctypes.byref(sm), ctypes.sizeof(sm))
+ model = sm.value if hr == 0 else 0
+ finally:
+ release(device)
+ row["shader_model"] = f"{model >> 4}.{model & 0xF}"
+ ok = model >= 0x60 and vram_mb >= MIN_VRAM_MB
+ report = GpuReport(
+ ok,
+ "d3d12",
+ desc.Description,
+ vram_mb,
+ row["shader_model"],
+ "" if ok else ("needs 6 GB VRAM" if model >= 0x60 else "needs shader model 6"),
+ )
+ if best is None or (report.ok, report.vram_mb) > (best.ok, best.vram_mb):
+ best = report
+ finally:
+ release(adapter)
+ finally:
+ release(factory)
+ if best is None:
+ best = GpuReport(False, "d3d12", reason="no hardware D3D12 adapter")
+ best.adapters = adapters
+ return best
+
+
+# ---------------------------------------------------------------------- Linux
+
+
+def parse_vulkaninfo(text: str) -> GpuReport:
+ """``vulkaninfo --summary`` output -> the best Vulkan 1.3 non-CPU device."""
+ best: GpuReport | None = None
+ device: dict[str, str] = {}
+ devices: list[dict[str, str]] = []
+ for line in text.splitlines():
+ stripped = line.strip()
+ if stripped.startswith("GPU") and stripped.rstrip(":").split()[0].startswith("GPU"):
+ if device:
+ devices.append(device)
+ device = {}
+ continue
+ if "=" in stripped:
+ key, _, value = stripped.partition("=")
+ device[key.strip()] = value.strip()
+ if device:
+ devices.append(device)
+ for d in devices:
+ api = d.get("apiVersion", "0.0")
+ parts = [int(p) for p in api.split(" ")[0].split(".")[:2] if p.isdigit()]
+ major, minor = (parts + [0, 0])[:2]
+ kind = d.get("deviceType", "")
+ ok = (major, minor) >= (1, 3) and "CPU" not in kind
+ report = GpuReport(
+ ok,
+ "vulkan",
+ d.get("deviceName", ""),
+ 0,
+ "",
+ "" if ok else ("CPU device" if "CPU" in kind else "needs Vulkan 1.3"),
+ )
+ if best is None or report.ok > best.ok:
+ best = report
+ return best or GpuReport(False, "vulkan", reason="no Vulkan device")
+
+
+def _probe_vulkan() -> GpuReport: # pragma: no cover - needs a Linux GPU
+ try:
+ out = subprocess.run(
+ ["vulkaninfo", "--summary"],
+ capture_output=True,
+ text=True,
+ timeout=PROBE_TIMEOUT_S,
+ check=False,
+ )
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ return GpuReport(False, "vulkan", reason=f"vulkaninfo unavailable: {exc}")
+ return parse_vulkaninfo(out.stdout)
+
+
+def probe_gpu_here() -> GpuReport:
+ if sys.platform == "win32":
+ return _probe_d3d12()
+ if sys.platform.startswith("linux"):
+ return _probe_vulkan()
+ return GpuReport(False, "", reason="platform not supported yet")
+
+
+# ---------------------------------------------------------------------- cached API
+
+_cache: GpuReport | None = None
+_cache_at = 0.0
+RETRY_FAILED_S = 60.0
+
+
+def probe_gpu(*, refresh: bool = False) -> GpuReport:
+ """The GPU verdict, from a child process, cached for this app run.
+
+ Blocking (up to ``PROBE_TIMEOUT_S``): async callers use
+ ``asyncio.to_thread``. A failed probe is cached only for
+ ``RETRY_FAILED_S``, then asked again.
+ """
+ global _cache, _cache_at
+ override = getenv("DODAIOS_VERSE_PROBE").strip().lower()
+ if override in ("pass", "fail"):
+ return GpuReport(override == "pass", "override", reason=f"DODAIOS_VERSE_PROBE={override}")
+ if _cache is not None and not refresh:
+ if not _cache.failed or time.monotonic() - _cache_at < RETRY_FAILED_S:
+ return _cache
+ _cache_at = time.monotonic()
+ try:
+ out = subprocess.run(
+ [sys.executable, "-m", "dodaios.verse_host.probe", "--json"],
+ capture_output=True,
+ text=True,
+ timeout=PROBE_TIMEOUT_S,
+ check=False,
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
+ )
+ data = json.loads(out.stdout.strip().splitlines()[-1])
+ _cache = GpuReport(**data)
+ except (OSError, subprocess.TimeoutExpired, ValueError, IndexError, TypeError) as exc:
+ _cache = GpuReport(False, reason=f"probe failed: {exc}", failed=True)
+ return _cache
+
+
+def exe_name() -> str:
+ return "Verse.exe" if sys.platform == "win32" else "Verse.sh"
+
+
+def candidate_executables() -> list[Path]:
+ out: list[Path] = []
+ env = getenv("DODAIOS_VERSE_EXE")
+ if env:
+ out.append(Path(env))
+ try:
+ from dodaios.core.config import DATA_DIR
+
+ out.append(Path(DATA_DIR) / "verse" / "build" / exe_name())
+ except Exception: # noqa: BLE001,S110 - no data dir in some test contexts
+ pass
+ app_root = Path(__file__).resolve().parents[2]
+ platform_dir = "Windows" if sys.platform == "win32" else "Linux"
+ out.append(app_root / "unreal" / "Verse" / "Saved" / "StagedBuilds" / platform_dir / exe_name())
+ return out
+
+
+def find_executable() -> Path | None:
+ for path in candidate_executables():
+ if path.is_file():
+ return path
+ return None
+
+
+@dataclass
+class Capability:
+ status: str # "ok", "not_installed", "unsupported"
+ exe: str | None
+ gpu: GpuReport
+ checked_at: float
+
+
+def check(*, refresh: bool = False) -> Capability:
+ exe = find_executable()
+ gpu = probe_gpu(refresh=refresh)
+ if not gpu.ok:
+ status = "unsupported"
+ elif exe is None:
+ status = "not_installed"
+ else:
+ status = "ok"
+ return Capability(status, str(exe) if exe else None, gpu, time.time())
+
+
+def main() -> int: # pragma: no cover - run as a child process
+ report = probe_gpu_here()
+ print(json.dumps(asdict(report)))
+ return 0
+
+
+if __name__ == "__main__": # pragma: no cover
+ raise SystemExit(main())
diff --git a/dodaios/verse_host/protocol.py b/dodaios/verse_host/protocol.py
new file mode 100644
index 0000000000..32fed958a3
--- /dev/null
+++ b/dodaios/verse_host/protocol.py
@@ -0,0 +1,193 @@
+"""Envelope, close codes, error codes and limits of ``verse.bridge/1``.
+
+Everything here is frozen by ``contracts/bridge-protocol.md`` sections 1, 2
+and 8. The codec is deliberately strict on the envelope (a frame that is not
+an object with a string ``type`` is malformed) and lenient on payloads
+(unknown fields and unknown types are ignored, contract section 2).
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from dataclasses import dataclass
+from typing import Any, Final
+
+PROTOCOL: Final = "verse.bridge/1"
+SUPPORTED_PROTOCOLS: Final = (PROTOCOL,)
+PATH: Final = "/api/verse/bridge"
+
+# Close codes (contract section 1).
+CLOSE_BAD_HELLO: Final = 4400
+CLOSE_TOKEN: Final = 4401
+CLOSE_PEER: Final = 4403
+CLOSE_REPLACED: Final = 4409
+CLOSE_PROTOCOL: Final = 4426
+CLOSE_TOO_BIG: Final = 1009
+CLOSE_TRY_LATER: Final = 1013
+
+HELLO_TIMEOUT_S: Final = 5.0
+DEAD_LINK_S: Final = 5.0
+MAX_FRAME_BYTES: Final = 1 << 20
+
+# Reply error codes (contract section 2).
+ERROR_CODES: Final = (
+ "bad_request",
+ "not_found",
+ "conflict",
+ "busy",
+ "unavailable",
+ "rate_limited",
+ "internal",
+)
+
+#: Feature names announced in ``welcome.features``; a topic outside this set
+#: answers ``unavailable``.
+BASE_FEATURES: Final = (
+ "roster",
+ "panes",
+ "screens",
+ "chat_tails",
+ "meetings",
+ "groups",
+ "progression",
+ "companion",
+ "lifecycle",
+ "panel",
+)
+
+#: Topics that answer ``subscribe`` with a snapshot (schema ``x-subscribed-topics``).
+SNAPSHOT_TOPICS: Final = ("roster", "groups", "meetings", "progression", "companion")
+#: Topics a subscription accepts without sending anything (fixture README).
+SILENT_TOPICS: Final = ("panes", "duel_stats", "lifecycle", "panel")
+
+LIMITS: Final = {
+ "screens_max_panes": 8,
+ "screens_max_rows": 60,
+ "screens_max_cols": 240,
+ "screens_max_hz": 10,
+ "chat_tails_max_agents": 6,
+ "chat_tail_lines": 12,
+}
+
+SCREENS_MAX_BYTES_PER_S: Final = 200 * 1024
+
+#: Verse frames that carry no ``id`` and get no reply (fixture README).
+NOTICES: Final = frozenset(
+ {
+ "hello",
+ "ping",
+ "log",
+ "lifecycle.state",
+ "lifecycle.ready",
+ "lifecycle.bye",
+ "window.state",
+ "panel.stream_state",
+ "focus.return_to_app",
+ }
+)
+
+DUTY_STATUSES: Final = ("working", "waiting", "idle", "paused", "error")
+LIFECYCLE_STATES: Final = ("booting", "visible", "panel", "dormant", "exiting")
+
+
+class BridgeError(Exception):
+ """A command failed; becomes ``reply {ok: false, error: {code, message}}``."""
+
+ def __init__(self, code: str, message: str) -> None:
+ if code not in ERROR_CODES:
+ code = "internal"
+ super().__init__(message)
+ self.code = code
+ self.message = message
+
+
+class MalformedFrame(ValueError):
+ """Text that is not a ``verse.bridge/1`` JSON frame."""
+
+
+@dataclass(frozen=True, slots=True)
+class Inbound:
+ """One parsed Verse -> server frame."""
+
+ type: str
+ data: dict[str, Any]
+ id: str | None
+ ts: float | None
+ raw: dict[str, Any]
+
+
+def now() -> float:
+ return time.time()
+
+
+def parse(text: str | bytes) -> Inbound:
+ """Parse one Verse frame. Raises :class:`MalformedFrame` on a bad envelope."""
+ if isinstance(text, bytes):
+ try:
+ text = text.decode("utf-8")
+ except UnicodeDecodeError as exc:
+ raise MalformedFrame("frame is not UTF-8") from exc
+ try:
+ obj = json.loads(text)
+ except ValueError as exc:
+ raise MalformedFrame(f"frame is not JSON: {exc}") from exc
+ if not isinstance(obj, dict):
+ raise MalformedFrame("frame is not a JSON object")
+ type_ = obj.get("type")
+ if not isinstance(type_, str) or not type_:
+ raise MalformedFrame("frame has no type")
+ data = obj.get("data", {})
+ if data is None:
+ data = {}
+ if not isinstance(data, dict):
+ raise MalformedFrame("data is not an object")
+ rid = obj.get("id")
+ if rid is not None and not isinstance(rid, str):
+ raise MalformedFrame("id is not a string")
+ ts = obj.get("ts")
+ if ts is not None and (isinstance(ts, bool) or not isinstance(ts, int | float)):
+ raise MalformedFrame("ts is not a number")
+ return Inbound(type=type_, data=data, id=rid, ts=float(ts) if ts is not None else None, raw=obj)
+
+
+def frame(
+ type_: str,
+ seq: int,
+ data: dict[str, Any],
+ *,
+ base: int | None = None,
+ re: str | None = None,
+ ts: float | None = None,
+ id: str | None = None, # noqa: A002 - the envelope field is called id
+) -> dict[str, Any]:
+ """A server -> Verse frame in envelope order ``type, seq, base, re, ts, data``."""
+ out: dict[str, Any] = {"type": type_, "seq": seq}
+ if base is not None:
+ out["base"] = base
+ if re is not None:
+ out["re"] = re
+ if id is not None:
+ out["id"] = id
+ out["ts"] = round(now() if ts is None else ts, 3)
+ out["data"] = data
+ return out
+
+
+def encode(obj: dict[str, Any]) -> str:
+ return json.dumps(obj, ensure_ascii=False, separators=(",", ":"))
+
+
+def ok(result: dict[str, Any] | None = None) -> dict[str, Any]:
+ return {"ok": True, "result": result if result is not None else {}}
+
+
+def error(code: str, message: str) -> dict[str, Any]:
+ if code not in ERROR_CODES:
+ code = "internal"
+ return {"ok": False, "error": {"code": code, "message": message}}
+
+
+def welcome_reason_unsupported() -> str:
+ """Close reason for ``4426``: ``welcome``-shaped text naming the supported versions."""
+ return encode({"type": "welcome", "data": {"protocols": list(SUPPORTED_PROTOCOLS)}})
diff --git a/dodaios/verse_host/relays/base.py b/dodaios/verse_host/relays/base.py
new file mode 100644
index 0000000000..455ea80e02
--- /dev/null
+++ b/dodaios/verse_host/relays/base.py
@@ -0,0 +1,143 @@
+"""Shared plumbing of the relays: bus subscriptions, coalesced re-reads, row diffs."""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import logging
+from collections.abc import Awaitable, Callable, Iterable
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from ..bridge import BridgeSession
+ from ..ports import BackendPort
+
+log = logging.getLogger(__name__)
+
+
+class RelayBase:
+ """A topic producer bound to one session; subclasses set ``topics``."""
+
+ topics: tuple[str, ...] = ()
+
+ def __init__(self, session: BridgeSession, backend: BackendPort) -> None:
+ self.session = session
+ self.backend = backend
+ self._subs: list[tuple[Any, Any]] = []
+ self._tasks: set[asyncio.Task[Any]] = set()
+ self.stopped = False
+
+ # ------------------------------------------------------------------ lifecycle
+ async def start(self) -> None:
+ return None
+
+ async def stop(self) -> None:
+ self.stopped = True
+ bus = self.backend.bus
+ for event_type, handler in self._subs:
+ with contextlib.suppress(Exception):
+ bus.unsubscribe(event_type, handler)
+ self._subs.clear()
+ for task in list(self._tasks):
+ task.cancel()
+ for task in list(self._tasks):
+ with contextlib.suppress(BaseException):
+ await task
+ self._tasks.clear()
+
+ async def subscribe(self, topic: str) -> None:
+ return None
+
+ async def unsubscribe(self, topic: str) -> None:
+ return None
+
+ async def resync(self, topic: str, data: dict[str, Any]) -> None:
+ await self.subscribe(topic)
+
+ # ------------------------------------------------------------------ helpers
+ def listen(
+ self, event_types: Iterable[type], handler: Callable[[Any], Awaitable[None]]
+ ) -> None:
+ bus = self.backend.bus
+ if bus is None:
+ return
+ for event_type in event_types:
+ bus.subscribe(event_type, handler)
+ self._subs.append((event_type, handler))
+
+ def spawn(self, coro: Awaitable[Any], name: str = "verse-relay") -> asyncio.Task[Any]:
+ task = asyncio.ensure_future(coro)
+ self._tasks.add(task)
+ task.add_done_callback(self._done)
+ return task
+
+ def _done(self, task: asyncio.Task[Any]) -> None:
+ self._tasks.discard(task)
+ if not task.cancelled() and task.exception() is not None:
+ log.warning("verse relay task failed", exc_info=task.exception())
+
+ def every(self, seconds: float, fn: Callable[[], Awaitable[None]]) -> None:
+ async def loop() -> None:
+ while not self.stopped:
+ await asyncio.sleep(seconds)
+ try:
+ await fn()
+ except asyncio.CancelledError:
+ raise
+ except Exception: # noqa: BLE001
+ log.warning("verse relay: periodic read failed", exc_info=True)
+
+ self.spawn(loop())
+
+ @property
+ def subscribed(self) -> set[str]:
+ return self.session.subscribed
+
+
+class Coalescer:
+ """Run ``fn`` at most once per ``interval`` s however often it is asked for."""
+
+ def __init__(
+ self, relay: RelayBase, fn: Callable[[], Awaitable[None]], interval: float
+ ) -> None:
+ self._relay = relay
+ self._fn = fn
+ self._interval = interval
+ self._scheduled = False
+ self._last = 0.0
+
+ def poke(self) -> None:
+ if self._scheduled or self._relay.stopped:
+ return
+ self._scheduled = True
+ loop = asyncio.get_running_loop()
+ delay = max(0.0, self._last + self._interval - loop.time())
+
+ async def run() -> None:
+ try:
+ if delay:
+ await asyncio.sleep(delay)
+ self._last = asyncio.get_running_loop().time()
+ self._scheduled = False
+ await self._fn()
+ finally:
+ self._scheduled = False
+
+ self._relay.spawn(run())
+
+
+def diff_rows(
+ old: dict[str, dict[str, Any]], new: dict[str, dict[str, Any]], id_field: str
+) -> tuple[list[dict[str, Any]], list[str]]:
+ """Partial upserts (id plus changed fields; new ids complete) and removed ids."""
+ upserts: list[dict[str, Any]] = []
+ for key, row in new.items():
+ before = old.get(key)
+ if before is None:
+ upserts.append(dict(row))
+ continue
+ changed = {k: v for k, v in row.items() if before.get(k) != v}
+ if changed:
+ upserts.append({id_field: key, **changed})
+ removed = [key for key in old if key not in new]
+ return upserts, removed
diff --git a/dodaios/verse_host/relays/chat_tails.py b/dodaios/verse_host/relays/chat_tails.py
new file mode 100644
index 0000000000..41cf50692a
--- /dev/null
+++ b/dodaios/verse_host/relays/chat_tails.py
@@ -0,0 +1,103 @@
+"""Chat tails relay (BW5, contract 6): the last lines of watched agents' chats.
+
+No agent-chat bus event exists, so the relay polls each watched agent every
+2.5 s (plus jitter), at most 6 agents and 6 reads in flight, as the web
+Verse does today. A ``chat_tails.update`` goes out only when ``version``
+changes; an agent without a chat session yields one empty update.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import random
+from typing import Any
+
+from .. import protocol as P
+from ..chat_lines import chat_lines, chat_version
+from .base import RelayBase
+
+log = logging.getLogger(__name__)
+
+POLL_S = 2.5
+JITTER_S = 1.2
+TAIL_EVENTS = 60
+
+
+class ChatTailsRelay(RelayBase):
+ topics = ("chat_tails",)
+
+ def __init__(self, session: Any, backend: Any) -> None:
+ super().__init__(session, backend)
+ self.watching: list[str] = []
+ self.versions: dict[str, str] = {}
+ self.sessions: dict[str, str | None] = {}
+ self._wake = asyncio.Event()
+
+ async def start(self) -> None:
+ self.session.hub.command("chat_tails.watch", self._watch)
+ self.spawn(self._loop())
+
+ async def resync(self, topic: str, data: dict[str, Any]) -> None:
+ self.versions.clear()
+ self._wake.set()
+
+ async def _watch(self, session: Any, msg: P.Inbound) -> dict[str, Any]:
+ agents = msg.data.get("agents")
+ if not isinstance(agents, list) or not all(isinstance(a, str) and a for a in agents):
+ raise P.BridgeError("bad_request", "agents must be a list of agent ids.")
+ unique = list(dict.fromkeys(agents))
+ limit = P.LIMITS["chat_tails_max_agents"]
+ self.watching, dropped = unique[:limit], unique[limit:]
+ for gone in [a for a in self.versions if a not in self.watching]:
+ self.versions.pop(gone, None)
+ self._wake.set()
+ return {"watching": list(self.watching), "dropped": dropped}
+
+ async def _session_for(self, agent_id: str) -> str | None:
+ if agent_id not in self.sessions:
+ session_id = None
+ try:
+ for row in await self.backend.list_agents():
+ if row.get("agent_id") == agent_id:
+ session_id = row.get("session_id") or row.get("chat_session_id")
+ break
+ except Exception: # noqa: BLE001
+ log.debug("verse chat tails: roster read failed", exc_info=True)
+ self.sessions[agent_id] = session_id or f"society:{agent_id}"
+ return self.sessions[agent_id]
+
+ async def read_one(self, agent_id: str) -> None:
+ session_id = await self._session_for(agent_id)
+ events = None
+ if session_id:
+ try:
+ events = await self.backend.chat_tail(session_id, TAIL_EVENTS)
+ except Exception: # noqa: BLE001 - the monitor keeps its last good frame
+ log.debug("verse chat tails: read failed for %s", agent_id, exc_info=True)
+ return
+ if events is None:
+ data = {"agent_id": agent_id, "lines": [], "version": ""}
+ else:
+ data = {
+ "agent_id": agent_id,
+ "version": chat_version(events),
+ "lines": chat_lines(events, P.LIMITS["chat_tail_lines"]),
+ }
+ if agent_id not in self.watching:
+ return
+ if self.versions.get(agent_id) == data["version"]:
+ return
+ self.versions[agent_id] = data["version"]
+ self.session.send("chat_tails.update", data, topic="chat_tails", feed=True)
+
+ async def _loop(self) -> None:
+ while not self.stopped:
+ batch = list(self.watching)
+ if batch:
+ await asyncio.gather(*(self.read_one(a) for a in batch), return_exceptions=True)
+ self._wake.clear()
+ try:
+ await asyncio.wait_for(self._wake.wait(), POLL_S + random.random() * JITTER_S) # noqa: S311
+ except TimeoutError: # poll interval elapsed; next round
+ pass
diff --git a/dodaios/verse_host/relays/commands.py b/dodaios/verse_host/relays/commands.py
new file mode 100644
index 0000000000..900dc73909
--- /dev/null
+++ b/dodaios/verse_host/relays/commands.py
@@ -0,0 +1,235 @@
+"""Station commands (BW9, BW12; contract 11 and 14).
+
+Open commands publish ``VerseOpenRequested`` (the web UI opens the view) and
+``ShowWindowRequested`` (the desktop process raises the app window).
+``agent.create`` runs the same code as ``POST /api/society/agents``.
+``launcher.*`` share :mod:`dodaios.agentic_ide.launch_sequence` with the web
+launcher (single flight, ``busy``, ``launcher.cancel``). ``qa.exec`` answers
+``unavailable`` unless the backend runs with ``DODAIOS_VERSE_QA=1``.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Awaitable, Callable
+from typing import Any
+
+from dodaios.agentic_ide.launch_sequence import LaunchBusy, LaunchSequence
+
+from .. import protocol as P
+from ..env import getenv
+from ..ports import NotFound, split_pane_id
+from .base import RelayBase
+
+log = logging.getLogger(__name__)
+
+QaHandler = Callable[[list[str]], Awaitable[Any]]
+
+
+def qa_enabled() -> bool:
+ return getenv("DODAIOS_VERSE_QA").strip() == "1"
+
+
+class CommandsRelay(RelayBase):
+ topics = ()
+
+ def __init__(
+ self,
+ session: Any,
+ backend: Any,
+ *,
+ launcher: LaunchSequence,
+ qa: dict[str, QaHandler],
+ on_open: Callable[[], Awaitable[None]] | None = None,
+ ) -> None:
+ super().__init__(session, backend)
+ self.launcher = launcher
+ self.qa = qa
+ self.on_open = on_open
+
+ async def start(self) -> None:
+ hub = self.session.hub
+ for name, handler in (
+ ("pane.open", self._pane_open),
+ ("ide.focus_terminal", self._focus_terminal),
+ ("agent.open", self._agent_open),
+ ("agents.open_list", self._agents_list),
+ ("group.open", self._group_open),
+ ("simulator.open", self._simulator_open),
+ ("ide.open", self._ide_open),
+ ("agent.create", self._agent_create),
+ ("launcher.options", self._launcher_options),
+ ("launcher.start", self._launcher_start),
+ ("launcher.cancel", self._launcher_cancel),
+ ("qa.exec", self._qa_exec),
+ ):
+ hub.command(name, handler)
+ hub.busy_checks["launcher.start"] = lambda: self.launcher.busy
+
+ # ------------------------------------------------------------------ open
+ async def _publish_open(self, **fields: Any) -> None:
+ from dodaios.core.events import ShowWindowRequested, VerseOpenRequested
+
+ bus = self.backend.bus
+ if bus is None:
+ raise P.BridgeError("unavailable", "The app is not listening.")
+ await bus.publish(VerseOpenRequested(source_layer="verse_host", **fields))
+ await bus.publish(ShowWindowRequested(source_layer="verse_host", source="verse"))
+ if self.on_open is not None:
+ await self.on_open()
+
+ async def _known_pane(self, pane_id: Any) -> tuple[str, str]:
+ if not isinstance(pane_id, str):
+ raise P.BridgeError("bad_request", "pane_id is required.")
+ try:
+ workspace_id, key = split_pane_id(pane_id)
+ except NotFound as exc:
+ raise P.BridgeError("bad_request", "pane_id is <workspace_id>:<key>.") from exc
+ for row in await self.backend.list_panes():
+ if row.get("workspace_id") == workspace_id and key in (row.get("key"), row.get("name")):
+ return workspace_id, str(row.get("name") or key)
+ raise P.BridgeError("not_found", "Pane is gone.")
+
+ async def _pane_open(self, session: Any, msg: P.Inbound) -> dict[str, Any]:
+ opened = msg.data.get("open")
+ if opened not in (None, "changes"):
+ raise P.BridgeError("bad_request", "open must be changes.")
+ ws, name = await self._known_pane(msg.data.get("pane_id"))
+ await self._publish_open(target="pane", workspace_id=ws, name=name, open=opened or "")
+ return {}
+
+ async def _focus_terminal(self, session: Any, msg: P.Inbound) -> dict[str, Any]:
+ ws, name = await self._known_pane(msg.data.get("pane_id"))
+ await self._publish_open(target="pane", workspace_id=ws, name=name, focus=True)
+ return {}
+
+ async def _agent_open(self, session: Any, msg: P.Inbound) -> dict[str, Any]:
+ agent_id = msg.data.get("agent_id")
+ if not isinstance(agent_id, str) or not agent_id:
+ raise P.BridgeError("bad_request", "agent_id is required.")
+ if not any(a.get("agent_id") == agent_id for a in await self.backend.list_agents()):
+ raise P.BridgeError("not_found", "Agent is gone.")
+ await self._publish_open(target="agent", agent_id=agent_id)
+ return {}
+
+ async def _agents_list(self, session: Any, msg: P.Inbound) -> dict[str, Any]:
+ await self._publish_open(target="agents")
+ return {}
+
+ async def _group_open(self, session: Any, msg: P.Inbound) -> dict[str, Any]:
+ group_id = msg.data.get("group_id")
+ if not isinstance(group_id, str) or not group_id:
+ raise P.BridgeError("bad_request", "group_id is required.")
+ groups = await self.backend.chat_groups()
+ if not any((g.get("group_id") or g.get("id")) == group_id for g in groups):
+ raise P.BridgeError("not_found", "Group is gone.")
+ await self._publish_open(target="group", group_id=group_id)
+ return {}
+
+ async def _simulator_open(self, session: Any, msg: P.Inbound) -> dict[str, Any]:
+ programme = msg.data.get("programme")
+ if not isinstance(programme, str) or not programme:
+ raise P.BridgeError("bad_request", "programme is required.")
+ await self._publish_open(target="simulator", programme=programme)
+ return {}
+
+ async def _ide_open(self, session: Any, msg: P.Inbound) -> dict[str, Any]:
+ await self._publish_open(target="ide")
+ return {}
+
+ # ------------------------------------------------------------------ create
+ async def _agent_create(self, session: Any, msg: P.Inbound) -> dict[str, Any]:
+ fields: dict[str, Any] = {}
+ name, title = msg.data.get("name"), msg.data.get("title")
+ if name is not None:
+ if not isinstance(name, str) or not 1 <= len(name) <= 40:
+ raise P.BridgeError("bad_request", "name must be 1 to 40 characters.")
+ fields["name"] = name
+ if title is not None:
+ if not isinstance(title, str) or len(title) > 120:
+ raise P.BridgeError("bad_request", "title must be a short string.")
+ fields["title"] = title
+ try:
+ agent_id = await self.backend.create_agent(fields)
+ except Exception as exc:
+ status = getattr(exc, "status_code", None)
+ if status in (409, 422):
+ raise P.BridgeError("conflict", str(getattr(exc, "detail", exc))) from exc
+ if status == 503:
+ raise P.BridgeError("unavailable", str(getattr(exc, "detail", exc))) from exc
+ raise
+ if not agent_id:
+ raise P.BridgeError("internal", "The agent was not created.")
+ return {"agent_id": agent_id}
+
+ # ------------------------------------------------------------------ launcher
+ async def _launcher_options(self, session: Any, msg: P.Inbound) -> dict[str, Any]:
+ state = await self.backend.ide_state()
+ active = state.get("active_id")
+ workspaces = []
+ for w in state.get("workspaces", []):
+ wid = w.get("id") or w.get("workspace_id")
+ if isinstance(wid, str) and wid:
+ workspaces.append(
+ {
+ "workspace_id": wid,
+ "name": str(w.get("name") or w.get("folder") or wid),
+ "active": wid == active,
+ }
+ )
+ agents = []
+ for a in await self.backend.ide_agents():
+ name = a.get("name")
+ if not isinstance(name, str) or not name or (a.get("kind") or "cli") == "shell":
+ continue
+ agents.append(
+ {
+ "agent": name,
+ "display_name": str(a.get("display_name") or a.get("label") or name),
+ "available": bool(a.get("installed", True)),
+ }
+ )
+ return {"workspaces": workspaces, "agents": agents}
+
+ async def _launcher_start(self, session: Any, msg: P.Inbound) -> dict[str, Any]:
+ data = msg.data
+ workspace_id = data.get("workspace_id")
+ agents = data.get("agents")
+ brief = data.get("brief", "")
+ if workspace_id is not None and (not isinstance(workspace_id, str) or not workspace_id):
+ raise P.BridgeError("bad_request", "workspace_id must be a non-empty string.")
+ if not isinstance(brief, str) or not isinstance(agents, list) or not agents:
+ raise P.BridgeError("bad_request", "launcher.start needs agents and brief.")
+ plan: list[tuple[str, int]] = []
+ for item in agents:
+ agent = item.get("agent") if isinstance(item, dict) else None
+ count = item.get("count") if isinstance(item, dict) else None
+ if not isinstance(agent, str) or not agent:
+ raise P.BridgeError("bad_request", "every entry needs an agent.")
+ if isinstance(count, bool) or not isinstance(count, int) or not 1 <= count <= 8:
+ raise P.BridgeError("bad_request", "count must be 1 to 8.")
+ plan.append((agent, count))
+ if self.launcher.busy:
+ raise P.BridgeError("busy", "A launch batch is already running.")
+ try:
+ panes = await self.launcher.run(workspace_id, plan, brief)
+ except LaunchBusy as exc:
+ raise P.BridgeError("busy", str(exc)) from exc
+ return {"panes": [{"pane_id": p.pane_id, "submitted": p.submitted} for p in panes]}
+
+ async def _launcher_cancel(self, session: Any, msg: P.Inbound) -> dict[str, Any]:
+ return {"stopped": self.launcher.cancel()}
+
+ # ------------------------------------------------------------------ QA
+ async def _qa_exec(self, session: Any, msg: P.Inbound) -> dict[str, Any]:
+ if not qa_enabled():
+ raise P.BridgeError("unavailable", "QA commands need DODAIOS_VERSE_QA=1.")
+ command, args = msg.data.get("command"), msg.data.get("args", [])
+ if not isinstance(command, str) or not command.startswith("Verse.QA."):
+ raise P.BridgeError("bad_request", "command must be a Verse.QA.* command.")
+ if not isinstance(args, list) or not all(isinstance(a, str) for a in args):
+ raise P.BridgeError("bad_request", "args must be strings.")
+ handler = self.qa.get(command)
+ if handler is None:
+ raise P.BridgeError("not_found", f"No backend QA command {command}.")
+ return {"result": await handler(args)}
diff --git a/dodaios/verse_host/relays/meetings.py b/dodaios/verse_host/relays/meetings.py
new file mode 100644
index 0000000000..a6573bddde
--- /dev/null
+++ b/dodaios/verse_host/relays/meetings.py
@@ -0,0 +1,210 @@
+"""Groups and meetings relay (BW6, contract 7).
+
+``groups.snapshot`` on subscribe, ``groups.delta`` when a group changed (same
+rules as the roster delta). ``meetings.update`` is pushed on every trigger
+for a group with a running room, and once with ``running: false`` when it
+settles. ``meeting.start`` / ``meeting.stop`` run the app's own meeting calls
+after its confirmation path; a declined confirmation replies ``conflict``.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from .. import protocol as P
+from ..ports import NotFound
+from .base import Coalescer, RelayBase, diff_rows
+
+log = logging.getLogger(__name__)
+
+MAX_MESSAGES = 8
+TEXT_MAX = 200
+SAFETY_S = 60.0
+
+
+def _cut(text: Any, limit: int = TEXT_MAX) -> str:
+ s = " ".join(str(text or "").split())
+ return s if len(s) <= limit else s[: limit - 1].rstrip() + "…"
+
+
+def group_row(raw: dict[str, Any]) -> dict[str, Any] | None:
+ gid = raw.get("group_id") or raw.get("id")
+ if not isinstance(gid, str) or not gid:
+ return None
+ members = []
+ for m in raw.get("members") or []:
+ mid = m.get("agent_id") if isinstance(m, dict) else m
+ if isinstance(mid, str) and mid:
+ members.append(mid)
+ lead = raw.get("lead") or raw.get("lead_id")
+ goal = raw.get("goal")
+ goal_out = None
+ if isinstance(goal, dict) and isinstance(goal.get("goal_id") or goal.get("id"), str):
+ goal_out = {
+ "goal_id": str(goal.get("goal_id") or goal.get("id")),
+ "state": str(goal.get("state") or "running"),
+ }
+ return {
+ "group_id": gid,
+ "name": str(raw.get("name") or ""),
+ "members": members,
+ "lead": lead if isinstance(lead, str) and lead else None,
+ "goal": goal_out,
+ }
+
+
+def meeting_update(group_id: str, snap: dict[str, Any]) -> dict[str, Any]:
+ room = snap.get("room") if isinstance(snap.get("room"), dict) else None
+ messages = [
+ {
+ "id": str(m.get("id")),
+ "speaker": str(m.get("speaker") or "user"),
+ "text": _cut(m.get("text")),
+ }
+ for m in (snap.get("messages") or [])
+ if isinstance(m, dict) and m.get("id")
+ ][-MAX_MESSAGES:]
+ room_out = None
+ if room is not None:
+ phase = room.get("phase")
+ room_out = {
+ "room_id": str(room.get("room_id") or "room"),
+ "phase": phase if phase in ("open", "settle") else "open",
+ "topic": str(room.get("topic") or ""),
+ "rounds": max(0, int(room.get("rounds") or 0)),
+ "max_rounds": max(1, int(room.get("max_rounds") or 1)),
+ }
+ speakers = [m["speaker"] for m in messages if m["speaker"] != "user"]
+ running = bool(snap.get("running"))
+ return {
+ "group_id": group_id,
+ "running": running,
+ "round": room_out["rounds"] if room_out else None,
+ "speaker": speakers[-1] if speakers and running else None,
+ "room": room_out,
+ "messages": messages,
+ }
+
+
+class MeetingsRelay(RelayBase):
+ topics = ("groups", "meetings")
+
+ def __init__(self, session: Any, backend: Any) -> None:
+ super().__init__(session, backend)
+ self.groups: dict[str, dict[str, Any]] = {}
+ self.sent_groups: dict[str, dict[str, Any]] | None = None
+ self.running: set[str] = set()
+ self._later = Coalescer(self, self._refresh, 0.5)
+
+ async def start(self) -> None:
+ from dodaios.core import events as E
+
+ hub = self.session.hub
+ hub.command("meeting.start", self._start)
+ hub.command("meeting.stop", self._stop)
+ self.listen([E.SocietyRoomChanged, E.SocietyMessageSent, E.SocietyTeamChanged], self._poke)
+ self.every(SAFETY_S, self._refresh)
+
+ async def subscribe(self, topic: str) -> None:
+ await self._read_groups()
+ if topic == "groups":
+ self.sent_groups = None
+ self._emit_groups()
+ else:
+ for gid in list(self.groups):
+ await self._push_meeting(gid, initial=True)
+
+ async def _read_groups(self) -> None:
+ try:
+ raw = await self.backend.chat_groups()
+ except Exception: # noqa: BLE001
+ log.warning("verse meetings: group read failed", exc_info=True)
+ return
+ rows = {}
+ for g in raw:
+ row = group_row(g)
+ if row is not None:
+ rows[row["group_id"]] = row
+ self.groups = rows
+
+ def _snapshot(self) -> dict[str, Any]:
+ self.sent_groups = {k: dict(v) for k, v in self.groups.items()}
+ return {"groups": list(self.sent_groups.values())}
+
+ def _emit_groups(self) -> None:
+ if "groups" not in self.subscribed:
+ return
+ self.session.outbox.snapshot_of["groups"] = self._snapshot
+ if self.sent_groups is None:
+ self.session.send("groups.snapshot", self._snapshot, topic="groups", feed=True)
+ return
+ upserts, removed = diff_rows(self.sent_groups, self.groups, "group_id")
+ if not upserts and not removed:
+ return
+ self.sent_groups = {k: dict(v) for k, v in self.groups.items()}
+ data = {"upsert": {"groups": upserts}, "remove": {"groups": removed}}
+ self.session.send("groups.delta", data, topic="groups", delta=True, feed=True)
+
+ async def _push_meeting(self, group_id: str, initial: bool = False) -> None:
+ if "meetings" not in self.subscribed:
+ return
+ try:
+ snap = await self.backend.group_meeting(group_id)
+ except Exception: # noqa: BLE001
+ log.debug("verse meetings: meeting read failed", exc_info=True)
+ return
+ if snap is None:
+ return
+ update = meeting_update(group_id, snap)
+ was_running = group_id in self.running
+ if update["running"]:
+ self.running.add(group_id)
+ else:
+ self.running.discard(group_id)
+ if update["running"] or was_running or (initial and update["room"] is not None):
+ self.session.send("meetings.update", update, topic="meetings", feed=True)
+
+ async def _refresh(self) -> None:
+ await self._read_groups()
+ self._emit_groups()
+ for gid in list(self.groups):
+ await self._push_meeting(gid)
+
+ async def _poke(self, _event: Any) -> None:
+ self._later.poke()
+
+ # ------------------------------------------------------------------ commands
+ async def _start(self, session: Any, msg: P.Inbound) -> dict[str, Any]:
+ gid, text = msg.data.get("group_id"), msg.data.get("text")
+ if not isinstance(gid, str) or not gid or not isinstance(text, str) or not text.strip():
+ raise P.BridgeError("bad_request", "meeting.start needs group_id and text.")
+ if not await self.backend.confirm_dangerous("meeting.start", gid):
+ raise P.BridgeError("conflict", "The person declined.")
+ await self._call(self.backend.meeting_start(gid, text))
+ self._later.poke()
+ return {}
+
+ async def _stop(self, session: Any, msg: P.Inbound) -> dict[str, Any]:
+ gid = msg.data.get("group_id")
+ if not isinstance(gid, str) or not gid:
+ raise P.BridgeError("bad_request", "meeting.stop needs group_id.")
+ if not await self.backend.confirm_dangerous("meeting.stop", gid):
+ raise P.BridgeError("conflict", "The person declined.")
+ await self._call(self.backend.meeting_stop(gid))
+ self._later.poke()
+ return {}
+
+ @staticmethod
+ async def _call(coro: Any) -> Any:
+ try:
+ return await coro
+ except NotFound as exc:
+ raise P.BridgeError("not_found", "Group is gone.") from exc
+ except Exception as exc:
+ status = getattr(exc, "status_code", None)
+ if status == 404:
+ raise P.BridgeError("not_found", "Group is gone.") from exc
+ if status == 409:
+ raise P.BridgeError("conflict", str(getattr(exc, "detail", exc))) from exc
+ raise
diff --git a/dodaios/verse_host/relays/progression.py b/dodaios/verse_host/relays/progression.py
new file mode 100644
index 0000000000..a8951293c8
--- /dev/null
+++ b/dodaios/verse_host/relays/progression.py
@@ -0,0 +1,190 @@
+"""Progression relay (BW7, contract 9, 10 and 14): levels, awards, world actions.
+
+``progression.snapshot`` on subscribe (with ``told_seq`` and the duel
+totals), every ``ProgressionAwarded`` forwarded field for field as
+``progression.awarded`` (an event: never dropped), ``progression.action``
+onto the rulebook's world actions, ``progression.told`` stored, and
+``duel.result`` handed to the duel service of WP21 (``unavailable`` until it
+is installed).
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from .. import protocol as P
+from ..ports import UnknownWorldAction
+from .base import RelayBase
+
+log = logging.getLogger(__name__)
+
+WORLD_ACTIONS = (
+ "daily_visit",
+ "deck_discovered",
+ "inspection",
+ "walk_together",
+ "team_briefing",
+ "simulator_round",
+ "simulator_record",
+)
+EMPTY_DUEL_STATS: dict[str, Any] = {
+ "matches": 0,
+ "wins": 0,
+ "losses": 0,
+ "unfinished": 0,
+ "kills": 0,
+ "deaths": 0,
+ "headshots": 0,
+ "finishers": 0,
+ "best_streak": 0,
+ "by_tier": {},
+}
+
+
+def subject_row(s: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "subject_id": str(s.get("subject_id")),
+ "kind": str(s.get("kind") or "person"),
+ "level": max(1, int(s.get("level") or 1)),
+ "total_xp": max(0, int(s.get("total_xp", s.get("xp", 0)) or 0)),
+ "into_level": max(0, int(s.get("into_level", s.get("xp_into_level", 0)) or 0)),
+ "for_next": max(0, int(s.get("for_next", s.get("xp_for_next", 0)) or 0)),
+ "title": str(s.get("title") or ""),
+ }
+
+
+def rulebook(prog: dict[str, Any]) -> dict[str, Any]:
+ titles: dict[str, str] = {}
+ raw_titles = prog.get("titles") or {}
+ if isinstance(raw_titles, dict):
+ for kind, bands in raw_titles.items():
+ if isinstance(bands, list):
+ for band in bands:
+ if isinstance(band, dict):
+ titles[f"{kind}.{band.get('level')}"] = str(band.get("title", ""))
+ elif isinstance(bands, str):
+ titles[str(kind)] = bands
+ return {
+ "ranks": [
+ {"id": r["id"], "level": int(r["level"]), "tier": r["tier"]}
+ for r in prog.get("ranks", [])
+ if isinstance(r, dict)
+ ],
+ "rewards": [r for r in prog.get("rewards", []) if isinstance(r, dict)],
+ "looks": [r for r in prog.get("looks", []) if isinstance(r, dict)],
+ "titles": titles,
+ }
+
+
+def award_data(event: Any) -> dict[str, Any]:
+ """``ProgressionAwarded`` as it is (contract 9), without the bus envelope fields."""
+ return {
+ "seq": int(event.seq),
+ "subject_id": str(event.subject_id),
+ "subject_kind": str(event.subject_kind),
+ "xp_source": str(event.xp_source),
+ "xp": int(event.xp),
+ "total_xp": int(event.total_xp),
+ "level": int(event.level),
+ "previous_level": int(event.previous_level),
+ "title": str(event.title),
+ "unlocked": list(event.unlocked),
+ "unlocked_looks": list(event.unlocked_looks),
+ }
+
+
+class ProgressionRelay(RelayBase):
+ topics = ("progression", "duel_stats")
+
+ def __init__(self, session: Any, backend: Any, store: Any) -> None:
+ super().__init__(session, backend)
+ self.store = store
+
+ async def start(self) -> None:
+ from dodaios.core import events as E
+
+ hub = self.session.hub
+ hub.command("progression.action", self._action)
+ hub.command("progression.told", self._told)
+ hub.command("duel.result", self._duel)
+ self.listen([E.ProgressionAwarded], self._on_award)
+
+ async def subscribe(self, topic: str) -> None:
+ if topic == "progression":
+ self.session.send("progression.snapshot", await self.snapshot(), topic="progression")
+
+ async def duel_stats(self) -> dict[str, Any]:
+ service = self.backend.duel_service()
+ if service is None:
+ return dict(EMPTY_DUEL_STATS)
+ try:
+ stats = service.duel_stats()
+ if hasattr(stats, "__await__"):
+ stats = await stats
+ return dict(stats) if isinstance(stats, dict) else dict(EMPTY_DUEL_STATS)
+ except Exception: # noqa: BLE001
+ log.warning("verse progression: duel stats read failed", exc_info=True)
+ return dict(EMPTY_DUEL_STATS)
+
+ async def snapshot(self) -> dict[str, Any]:
+ prog = await self.backend.progression()
+ subjects = [subject_row(s) for s in prog.get("subjects", []) if s.get("subject_id")]
+ pet = prog.get("pet_id")
+ return {
+ "subjects": subjects,
+ "pet_id": pet if isinstance(pet, str) and pet else None,
+ "latest_seq": max(0, int(prog.get("latest_seq") or 0)),
+ "told_seq": self.store.told_seq(),
+ "rulebook": rulebook(prog),
+ "duel_stats": prog.get("duel_stats") or await self.duel_stats(),
+ }
+
+ async def _on_award(self, event: Any) -> None:
+ if "progression" in self.subscribed:
+ self.session.send("progression.awarded", award_data(event), topic=None)
+
+ # ------------------------------------------------------------------ commands
+ async def _action(self, session: Any, msg: P.Inbound) -> dict[str, Any]:
+ action, ref = msg.data.get("action"), msg.data.get("ref", "")
+ if not isinstance(action, str) or not isinstance(ref, str) or len(ref) > 40:
+ raise P.BridgeError("bad_request", "progression.action needs action and ref.")
+ if action in ("duel_won", "duel_lost", "duel_finisher") or action not in WORLD_ACTIONS:
+ raise P.BridgeError("bad_request", f"{action} is not a world action.")
+ try:
+ award = await self.backend.report_action(action, ref)
+ except UnknownWorldAction as exc:
+ raise P.BridgeError("bad_request", str(exc)) from exc
+ return {"awarded": award}
+
+ async def _told(self, session: Any, msg: P.Inbound) -> dict[str, Any]:
+ seq = msg.data.get("seq")
+ if isinstance(seq, bool) or not isinstance(seq, int) or seq < 0:
+ raise P.BridgeError("bad_request", "seq must be a non-negative integer.")
+ return {"told_seq": self.store.raise_told_seq(seq)}
+
+ async def _duel(self, session: Any, msg: P.Inbound) -> dict[str, Any]:
+ service = self.backend.duel_service()
+ if service is None:
+ raise P.BridgeError("unavailable", "Duel results are not recorded yet.")
+ data = msg.data
+ if not isinstance(data.get("match_id"), str) or data.get("outcome") not in (
+ "won",
+ "lost",
+ "unfinished",
+ ):
+ raise P.BridgeError("bad_request", "duel.result needs match_id and outcome.")
+ result = service.record_duel(data)
+ if hasattr(result, "__await__"):
+ result = await result
+ if not isinstance(result, dict):
+ raise P.BridgeError("internal", "The duel service gave no answer.")
+ return {
+ "recorded": bool(result.get("recorded", True)),
+ "awards": [
+ {"xp_source": str(a.get("xp_source")), "xp": int(a.get("xp", 0))}
+ for a in result.get("awards", [])
+ if isinstance(a, dict)
+ ],
+ "duel_stats": result.get("duel_stats") or await self.duel_stats(),
+ }
diff --git a/dodaios/verse_host/relays/roster.py b/dodaios/verse_host/relays/roster.py
new file mode 100644
index 0000000000..e9c1ec4b12
--- /dev/null
+++ b/dodaios/verse_host/relays/roster.py
@@ -0,0 +1,344 @@
+"""Roster relay (BW3, contract 4): officers, technicians, ranks and duty status.
+
+Snapshot on subscribe; agents re-read on any society trigger (coalesced to at
+most 2 Hz); panes patched in place from ``AgenticIdePaneActivity`` and re-read
+on ``TerminalsAdded/Closed/WorkspaceChanged``; ranks re-joined on
+``ProgressionAwarded``; a safety re-read every 30 s. A delta goes out only
+when a field Verse sees changed.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from .. import protocol as P
+from ..duty import (
+ PANE_ACTIVITIES,
+ PANE_STATUSES,
+ RUN_STATES,
+ duty_of,
+ or_fallback,
+ pane_duty,
+)
+from .base import Coalescer, RelayBase, diff_rows
+
+log = logging.getLogger(__name__)
+
+SAFETY_REREAD_S = 30.0
+AGENT_REREAD_S = 0.5
+
+
+def rank_of(level: int) -> str:
+ from dodaios.progression.rules import rank_for
+
+ return rank_for(max(1, int(level)))[1]
+
+
+def _str(v: Any, default: str = "") -> str:
+ return v if isinstance(v, str) else default
+
+
+def agent_row(
+ row: dict[str, Any],
+ *,
+ levels: dict[str, int],
+ errors: set[str],
+ overrides: dict[str, str],
+ panes_by_agent: dict[str, str],
+ teams: dict[str, list[str]],
+) -> dict[str, Any]:
+ """One society roster row as contract 4.2 sends it (and nothing else)."""
+ agent_id = _str(row.get("agent_id"))
+ state = _str(row.get("state"), "active")
+ lifecycle = "paused" if state == "paused" else "active"
+ run_state = or_fallback(row.get("run_state"), RUN_STATES, "idle")
+ reason = row.get("waiting_reason")
+ duty = duty_of(run_state, lifecycle, asking=reason is not None, error=agent_id in errors)
+ duty = overrides.get(agent_id, duty)
+ level = levels.get(f"agent:{agent_id}", 1)
+ avatar_raw = row.get("avatar")
+ avatar = avatar_raw if isinstance(avatar_raw, dict) else {}
+ look = (
+ _str(row.get("look"))
+ or _str(avatar.get("look"))
+ or (avatar_raw if isinstance(avatar_raw, str) else "")
+ )
+ figure = row.get("figure") if isinstance(row.get("figure"), dict) else avatar
+ return {
+ "agent_id": agent_id,
+ "name": _str(row.get("name")),
+ "title": _str(row.get("title")),
+ "tier": _str(row.get("tier"), "specialist"),
+ "lifecycle": lifecycle,
+ "run_state": run_state,
+ "waiting_reason": reason if isinstance(reason, str) else None,
+ "duty": duty,
+ "level": level,
+ "rank": rank_of(level),
+ "look": look,
+ "figure": {
+ "archetype": _str(figure.get("archetype"), "crew"),
+ "palette": _str(figure.get("palette"), "graphite"),
+ },
+ "team_ids": sorted(teams.get(agent_id, [])),
+ "pane": panes_by_agent.get(agent_id),
+ }
+
+
+def pane_row(row: dict[str, Any], active_id: str | None = None) -> dict[str, Any] | None:
+ """One ``WorkspacePaneRow`` as contract 4.2 sends it, or None when it has no id."""
+ workspace_id = _str(row.get("workspace_id"))
+ key = _str(row.get("key")) or _str(row.get("name"))
+ if not workspace_id or not key or ":" in workspace_id or ":" in key:
+ return None
+ since = row.get("activity_since")
+ pane = {
+ "pane_id": f"{workspace_id}:{key}",
+ "workspace_id": workspace_id,
+ "key": key,
+ "history_id": row.get("history_id") if isinstance(row.get("history_id"), str) else None,
+ "name": _str(row.get("name"), key),
+ "display_name": _str(row.get("display_name")) or _str(row.get("agent")),
+ "agent": _str(row.get("agent")),
+ "title": _str(row.get("title")),
+ "status": or_fallback(row.get("status"), PANE_STATUSES, "pending"),
+ "activity": or_fallback(row.get("activity"), PANE_ACTIVITIES, "unknown"),
+ "activity_since": float(since) if isinstance(since, int | float) and since else None,
+ "worked": bool(row.get("worked")),
+ "duty": "idle",
+ "workspace_active": bool(
+ row.get("workspace_active", active_id is not None and workspace_id == active_id)
+ ),
+ "cols": max(1, int(row.get("cols") or 80)),
+ "rows": max(1, int(row.get("rows") or 24)),
+ }
+ pane["duty"] = pane_duty(pane)
+ return pane
+
+
+class RosterRelay(RelayBase):
+ topics = ("roster", "panes")
+
+ def __init__(self, session: Any, backend: Any) -> None:
+ super().__init__(session, backend)
+ self.agents_raw: list[dict[str, Any]] = []
+ self.panes: dict[str, dict[str, Any]] = {}
+ self.levels: dict[str, int] = {}
+ self.titles: dict[str, str] = {}
+ self.errors: set[str] = set()
+ self.overrides: dict[str, str] = {}
+ self.teams: dict[str, list[str]] = {}
+ self.sent_agents: dict[str, dict[str, Any]] | None = None
+ self.sent_panes: dict[str, dict[str, Any]] = {}
+ self.sent_commander: dict[str, Any] | None = None
+ self.uniform = "standard"
+ self._agents_later = Coalescer(self, self._reread_agents, AGENT_REREAD_S)
+
+ # ------------------------------------------------------------------ wiring
+ async def start(self) -> None:
+ from dodaios.core import events as E
+
+ society = [
+ E.SocietyRoomChanged,
+ E.SocietyMessageSent,
+ E.SocietyTeamChanged,
+ E.SocietyCheckpointChanged,
+ ]
+ self.listen(society, self._on_society)
+ self.listen([E.SocietyResultPosted], self._on_result)
+ self.listen([E.AgenticIdePaneActivity], self._on_pane_activity)
+ self.listen(
+ [E.AgenticIdeTerminalsAdded, E.AgenticIdeTerminalsClosed, E.AgenticIdeWorkspaceChanged],
+ self._on_panes_changed,
+ )
+ self.listen([E.ProgressionAwarded], self._on_award)
+ self.every(SAFETY_REREAD_S, self._safety)
+
+ async def subscribe(self, topic: str) -> None:
+ if topic == "roster":
+ await self._read_all()
+ self.sent_agents = None
+ self._emit(snapshot=True)
+
+ async def unsubscribe(self, topic: str) -> None:
+ if topic == "roster":
+ self.sent_agents = None
+
+ # ------------------------------------------------------------------ reads
+ async def _read_agents(self) -> None:
+ try:
+ self.agents_raw = await self.backend.list_agents()
+ except Exception: # noqa: BLE001
+ log.warning("verse roster: agent read failed", exc_info=True)
+
+ async def _read_panes(self) -> None:
+ try:
+ rows = await self.backend.list_panes()
+ except Exception: # noqa: BLE001
+ log.warning("verse roster: pane read failed", exc_info=True)
+ return
+ panes = {}
+ for raw in rows:
+ if raw.get("archived"):
+ continue
+ pane = pane_row(raw)
+ if pane is not None:
+ panes[pane["pane_id"]] = pane
+ self.panes = panes
+
+ async def _read_levels(self) -> None:
+ try:
+ prog = await self.backend.progression()
+ except Exception: # noqa: BLE001
+ log.warning("verse roster: progression read failed", exc_info=True)
+ return
+ levels, titles = {}, {}
+ for s in prog.get("subjects", []):
+ sid = s.get("subject_id")
+ if isinstance(sid, str):
+ levels[sid] = int(s.get("level") or 1)
+ titles[sid] = _str(s.get("title"))
+ self.levels, self.titles = levels, titles
+
+ async def _read_teams(self) -> None:
+ try:
+ groups = await self.backend.chat_groups()
+ except Exception: # noqa: BLE001
+ log.debug("verse: chat groups unavailable", exc_info=True)
+ return
+ teams: dict[str, list[str]] = {}
+ for g in groups:
+ gid = g.get("group_id") or g.get("id")
+ for member in g.get("members") or g.get("member_ids") or []:
+ mid = member.get("agent_id") if isinstance(member, dict) else member
+ if isinstance(mid, str) and isinstance(gid, str):
+ teams.setdefault(mid, []).append(gid)
+ self.teams = teams
+
+ async def _read_all(self) -> None:
+ await self._read_agents()
+ await self._read_panes()
+ await self._read_levels()
+ await self._read_teams()
+
+ # ------------------------------------------------------------------ view
+ def commander(self) -> dict[str, Any]:
+ level = self.levels.get("person", 1)
+ return {
+ "subject_id": "person",
+ "level": level,
+ "rank": rank_of(level),
+ "title": self.titles.get("person", ""),
+ "uniform": self.uniform,
+ }
+
+ def view_agents(self) -> dict[str, dict[str, Any]]:
+ panes_by_agent: dict[str, str] = {}
+ out: dict[str, dict[str, Any]] = {}
+ for raw in self.agents_raw:
+ if str(raw.get("state", "active")) == "archived":
+ continue
+ row = agent_row(
+ raw,
+ levels=self.levels,
+ errors=self.errors,
+ overrides=self.overrides,
+ panes_by_agent=panes_by_agent,
+ teams=self.teams,
+ )
+ if row["agent_id"]:
+ out[row["agent_id"]] = row
+ return out
+
+ def snapshot(self) -> dict[str, Any]:
+ agents = self.view_agents()
+ self.sent_agents = agents
+ self.sent_panes = {k: dict(v) for k, v in self.panes.items()}
+ self.sent_commander = self.commander()
+ return {
+ "commander": self.sent_commander,
+ "agents": list(agents.values()),
+ "panes": list(self.sent_panes.values()),
+ }
+
+ def _emit(self, snapshot: bool = False) -> None:
+ if "roster" not in self.subscribed:
+ return
+ self.session.outbox.snapshot_of["roster"] = self.snapshot
+ if snapshot or self.sent_agents is None:
+ self.session.send("roster.snapshot", self.snapshot, topic="roster", feed=True)
+ return
+ agents = self.view_agents()
+ up_a, rm_a = diff_rows(self.sent_agents, agents, "agent_id")
+ up_p, rm_p = diff_rows(self.sent_panes, self.panes, "pane_id")
+ commander = self.commander()
+ cmd_changed = commander != self.sent_commander
+ if not (up_a or rm_a or up_p or rm_p or cmd_changed):
+ return
+ self.sent_agents = agents
+ self.sent_panes = {k: dict(v) for k, v in self.panes.items()}
+ self.sent_commander = commander
+ data = {
+ "upsert": {"agents": up_a, "panes": up_p},
+ "remove": {"agents": rm_a, "panes": rm_p},
+ "commander": commander if cmd_changed else None,
+ }
+ self.session.send("roster.delta", data, topic="roster", delta=True, feed=True)
+
+ # ------------------------------------------------------------------ triggers
+ async def _reread_agents(self) -> None:
+ await self._read_agents()
+ await self._read_teams()
+ self._emit()
+
+ async def _on_society(self, _event: Any) -> None:
+ self._agents_later.poke()
+
+ async def _on_result(self, event: Any) -> None:
+ agent_id = getattr(event, "agent_id", "")
+ if getattr(event, "status", "") == "blocked":
+ self.errors.add(agent_id)
+ else:
+ self.errors.discard(agent_id)
+ self._agents_later.poke()
+
+ async def _on_pane_activity(self, event: Any) -> None:
+ pane_id = f"{getattr(event, 'session_id', '')}:{getattr(event, 'key', '')}"
+ pane = self.panes.get(pane_id)
+ if pane is None:
+ await self._read_panes()
+ else:
+ pane["status"] = or_fallback(
+ getattr(event, "status", ""), PANE_STATUSES, pane["status"]
+ )
+ pane["activity"] = or_fallback(
+ getattr(event, "activity", ""), PANE_ACTIVITIES, "unknown"
+ )
+ since = getattr(event, "activity_since", 0.0)
+ pane["activity_since"] = float(since) if since else None
+ pane["worked"] = bool(getattr(event, "worked", pane["worked"]))
+ pane["duty"] = pane_duty(pane)
+ self._emit()
+
+ async def _on_panes_changed(self, _event: Any) -> None:
+ await self._read_panes()
+ self._emit()
+
+ async def _on_award(self, _event: Any) -> None:
+ await self._read_levels()
+ self._emit()
+
+ async def _safety(self) -> None:
+ if "roster" not in self.subscribed:
+ return
+ await self._read_all()
+ self._emit()
+
+ # ------------------------------------------------------------------ QA
+ async def qa_set_duty(self, agent_id: str, duty: str) -> dict[str, Any]:
+ if duty not in P.DUTY_STATUSES:
+ raise P.BridgeError("bad_request", f"Unknown duty {duty!r}.")
+ self.overrides[agent_id] = duty
+ self._emit()
+ return {"agent_id": agent_id, "duty": duty}
diff --git a/dodaios/verse_host/relays/screens.py b/dodaios/verse_host/relays/screens.py
new file mode 100644
index 0000000000..57c3ce980d
--- /dev/null
+++ b/dodaios/verse_host/relays/screens.py
@@ -0,0 +1,360 @@
+"""Screens relay (BW4, contract 5): styled desk-monitor cells of watched panes.
+
+Verse names the desks it wants with ``screens.watch`` (nearest first, at most
+8). Each bound pane gets a :class:`StyledScreen` mirror fed from its PTY as a
+non-claiming viewer (seeded from the replay bytes). Dirty rows go out at
+most ``min(hz, 10)`` times a second, coalesced; the whole screens feed,
+snapshots included, stays under 200 KB/s by delaying the farthest panes
+first (their dirty rows wait). A pane without output sends nothing. When
+the mirror is not available (attach refused, parser error) the plain
+``ScreenBuffer`` rows go out with ``style: "plain"``.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import time
+from dataclasses import dataclass, field
+from typing import Any
+
+from .. import protocol as P
+from ..cells_codec import DEFAULT_COLOUR, MAX_COLS, MAX_ROWS, Cell, row_runs
+from ..ports import NotFound
+from ..styled_screen import StyledScreen
+from .base import RelayBase
+
+log = logging.getLogger(__name__)
+
+SAFETY_SNAPSHOT_S = 30.0
+TICK_S = 0.05
+PLAIN_POLL_S = 0.5
+
+
+@dataclass
+class Watched:
+ pane_id: str
+ ref: int
+ hz: int
+ mirror: StyledScreen | None = None
+ style: str = "styled"
+ at: float | None = None
+ last_frame: float = 0.0
+ last_snapshot: float = 0.0
+ need_snapshot: bool = True
+ plain_rows: list[list[Cell]] = field(default_factory=list)
+ plain_cols: int = 0
+ plain_rows_n: int = 0
+ plain_cursor: list[int] = field(default_factory=lambda: [-1, -1])
+ plain_dirty: set[int] = field(default_factory=set)
+ last_plain_poll: float = 0.0
+ output_handler: Any = None
+ gone: bool = False
+
+
+class ScreensRelay(RelayBase):
+ topics = ("screens",)
+
+ def __init__(self, session: Any, backend: Any) -> None:
+ super().__init__(session, backend)
+ self.watched: dict[str, Watched] = {}
+ self.budget_bytes_per_s = P.SCREENS_MAX_BYTES_PER_S
+ self._window: list[tuple[float, int]] = []
+ self.clock = time.monotonic
+ self.feed_seconds: list[float] = []
+ self.frame_seconds: list[float] = []
+
+ async def start(self) -> None:
+ from dodaios.core import events as E
+
+ self.session.hub.command("screens.watch", self._watch)
+ self.listen([E.AgenticIdeTerminalsClosed], self._on_closed)
+ self.spawn(self._pump())
+
+ async def stop(self) -> None:
+ for w in list(self.watched.values()):
+ self._unbind(w)
+ self.watched.clear()
+ await super().stop()
+
+ async def resync(self, topic: str, data: dict[str, Any]) -> None:
+ pane_id = data.get("pane_id")
+ for w in self.watched.values():
+ if pane_id is None or w.pane_id == pane_id:
+ w.need_snapshot = True
+
+ # ------------------------------------------------------------------ watch
+ async def _watch(self, session: Any, msg: P.Inbound) -> dict[str, Any]:
+ panes = msg.data.get("panes")
+ if not isinstance(panes, list):
+ raise P.BridgeError("bad_request", "panes must be a list.")
+ wanted: list[tuple[str, int]] = []
+ for item in panes:
+ if not isinstance(item, dict) or not isinstance(item.get("pane_id"), str):
+ raise P.BridgeError("bad_request", "every pane needs a pane_id.")
+ hz = item.get("hz", 10)
+ if isinstance(hz, bool) or not isinstance(hz, int) or not 1 <= hz <= 10:
+ raise P.BridgeError("bad_request", "hz must be 1 to 10.")
+ if item["pane_id"] not in (p for p, _ in wanted):
+ wanted.append((item["pane_id"], hz))
+ limit = P.LIMITS["screens_max_panes"]
+ served, dropped = wanted[:limit], [p for p, _ in wanted[limit:]]
+ keep = {p for p, _ in served}
+ for pane_id in list(self.watched):
+ if pane_id not in keep:
+ self._unbind(self.watched.pop(pane_id))
+ bound, missing = [], []
+ ref = 0
+ new: dict[str, Watched] = {}
+ for pane_id, hz in served:
+ w = self.watched.get(pane_id)
+ if w is None:
+ w = await self._bind(pane_id, hz)
+ if w is None:
+ missing.append(pane_id)
+ continue
+ ref += 1
+ w.ref, w.hz, w.need_snapshot = ref, hz, True
+ new[pane_id] = w
+ bound.append({"pane_id": pane_id, "ref": ref})
+ self.watched = new
+ return {"bound": bound, "dropped": dropped, "missing": missing}
+
+ async def _bind(self, pane_id: str, hz: int) -> Watched | None:
+ w = Watched(pane_id=pane_id, ref=0, hz=hz)
+
+ async def on_output(text: str) -> None:
+ if w.mirror is None or w.gone:
+ return
+ started = time.perf_counter()
+ w.mirror.feed(text)
+ self.feed_seconds.append(time.perf_counter() - started)
+ if len(self.feed_seconds) > 4096:
+ del self.feed_seconds[:2048]
+ w.at = time.time()
+ if w.mirror.errors:
+ self._to_plain(w)
+
+ async def on_exit(_code: int) -> None:
+ self._gone(w, "exited")
+
+ w.output_handler = on_output
+ w.mirror = StyledScreen(80, 24)
+ try:
+ size = await self.backend.attach_screen(pane_id, on_output, on_exit)
+ except NotFound: # pane has no live screen; the plain mirror is used
+ size = None
+ w.mirror = None
+ if self.backend.plain_screen(pane_id) is None:
+ return None
+ w.style = "plain"
+ return w
+ except Exception: # noqa: BLE001 - a mirror that cannot start falls back to plain
+ log.warning("verse screens: attach failed for %s", pane_id, exc_info=True)
+ w.mirror = None
+ w.style = "plain"
+ if self.backend.plain_screen(pane_id) is None:
+ return None
+ return w
+ if size and w.mirror is not None:
+ w.mirror.resize(*size)
+ return w
+
+ def _unbind(self, w: Watched) -> None:
+ w.gone = True
+ if w.output_handler is not None and w.style == "styled":
+ self.backend.detach_screen(w.pane_id, w.output_handler)
+ self.session.outbox.clear_topic(f"screens:{w.pane_id}")
+
+ def _to_plain(self, w: Watched) -> None:
+ if w.style == "plain":
+ return
+ log.info("verse screens: %s falls back to plain rows", w.pane_id)
+ if w.output_handler is not None:
+ self.backend.detach_screen(w.pane_id, w.output_handler)
+ w.mirror = None
+ w.style = "plain"
+ w.need_snapshot = True
+
+ def _gone(self, w: Watched, reason: str) -> None:
+ if w.gone:
+ return
+ current = self.watched.get(w.pane_id)
+ self._unbind(w)
+ if current is w:
+ del self.watched[w.pane_id]
+ self.session.send("screens.gone", {"pane_id": w.pane_id, "reason": reason})
+
+ async def _on_closed(self, event: Any) -> None:
+ workspace = getattr(event, "session_id", "") or getattr(event, "workspace_id", "")
+ names = set(getattr(event, "keys", ()) or ()) | set(getattr(event, "names", ()) or ())
+ for w in list(self.watched.values()):
+ ws, _, key = w.pane_id.partition(":")
+ if ws == workspace and (not names or key in names):
+ self._gone(w, "closed")
+
+ # ------------------------------------------------------------------ pump
+ def _spent(self, now: float) -> int:
+ self._window = [(t, n) for t, n in self._window if now - t < 1.0]
+ return sum(n for _, n in self._window)
+
+ async def _pump(self) -> None:
+ while not self.stopped:
+ await asyncio.sleep(TICK_S)
+ try:
+ await self.flush(self.clock())
+ except Exception: # noqa: BLE001
+ log.warning("verse screens: flush failed", exc_info=True)
+
+ async def flush(self, now: float) -> None:
+ """One tick: nearest panes first, each at most at its rate, under the byte budget.
+
+ The loop yields after every pane it framed, so building eight busy
+ screens never holds the event loop in one piece.
+ """
+ for w in list(self.watched.values()):
+ if w.gone:
+ continue
+ if w.style == "plain" and now - w.last_plain_poll >= max(PLAIN_POLL_S, 1.0 / w.hz):
+ w.last_plain_poll = now
+ self._poll_plain(w)
+ if now - w.last_snapshot >= SAFETY_SNAPSHOT_S:
+ w.need_snapshot = True
+ if w.mirror is not None and w.mirror.resized:
+ w.mirror.resized = False
+ w.need_snapshot = True
+ due = now - w.last_frame >= 1.0 / min(w.hz, P.LIMITS["screens_max_hz"])
+ if not due:
+ continue
+ if not w.need_snapshot and not self._has_dirty(w):
+ continue
+ started = time.perf_counter()
+ pending = self._dirty_rows(w)
+ data = self._frame(w)
+ size = self._estimate(data)
+ self.frame_seconds.append(time.perf_counter() - started)
+ if len(self.frame_seconds) > 4096:
+ del self.frame_seconds[:2048]
+ spent = self._spent(now)
+ if spent and spent + size > self.budget_bytes_per_s:
+ # Over budget (snapshots count too): this pane waits for a later
+ # tick. Framing took its dirty rows, so put them back; nothing
+ # changed is lost. A frame always goes out on an empty window,
+ # so one large snapshot cannot stall forever.
+ self._restore_dirty(w, pending)
+ continue
+ self._window.append((now, size))
+ w.last_frame = now
+ snapshot = data["kind"] == "snapshot"
+ if snapshot:
+ w.last_snapshot = now
+ w.need_snapshot = False
+ self.session.send(
+ "screens.frame",
+ data,
+ topic=f"screens:{w.pane_id}",
+ key=f"screens:{w.pane_id}",
+ delta=not snapshot,
+ ref=w.ref,
+ feed=True,
+ )
+ await asyncio.sleep(0)
+
+ @staticmethod
+ def _estimate(data: dict[str, Any]) -> int:
+ size = 32
+ for record in data["rows_changed"]:
+ size += 4
+ for run in record["runs"]:
+ size += 16 + len(run["text"].encode("utf-8"))
+ return size
+
+ @staticmethod
+ def _dirty_rows(w: Watched) -> set[int]:
+ return set(w.mirror.dirty) if w.mirror is not None else set(w.plain_dirty)
+
+ @staticmethod
+ def _restore_dirty(w: Watched, rows: set[int]) -> None:
+ if w.mirror is not None:
+ w.mirror.dirty |= rows
+ else:
+ w.plain_dirty |= rows
+
+ def _has_dirty(self, w: Watched) -> bool:
+ if w.mirror is not None:
+ return bool(w.mirror.dirty)
+ return bool(w.plain_dirty)
+
+ def _frame(self, w: Watched) -> dict[str, Any]:
+ snapshot = w.need_snapshot
+ if w.mirror is not None:
+ m = w.mirror
+ rows = m.snapshot_rows() if snapshot else m.take_dirty()
+ if snapshot:
+ m.dirty = set()
+ cols, nrows, cursor, cut = m.sent_cols, m.sent_rows, m.cursor(), m.cut
+ else:
+ cols, nrows = max(1, w.plain_cols), max(1, w.plain_rows_n)
+ indices = range(nrows) if snapshot else sorted(w.plain_dirty)
+ w.plain_dirty = set()
+ rows = []
+ for r in indices:
+ runs = row_runs(w.plain_rows[r], cols) if r < len(w.plain_rows) else []
+ if runs or not snapshot:
+ rows.append({"row": r, "runs": runs})
+ cursor, cut = w.plain_cursor, False
+ data: dict[str, Any] = {
+ "pane_id": w.pane_id,
+ "kind": "snapshot" if snapshot else "delta",
+ "cols": cols,
+ "rows": nrows,
+ "cursor": cursor,
+ "style": w.style,
+ "rows_changed": rows,
+ }
+ if snapshot:
+ data.update({"ref": w.ref, "cut": cut, "at": w.at})
+ return data
+
+ def _poll_plain(self, w: Watched) -> None:
+ shot = self.backend.plain_screen(w.pane_id)
+ if shot is None:
+ self._gone(w, "not_found")
+ return
+ cols = max(1, min(int(shot.get("cols") or 80), MAX_COLS))
+ nrows = max(1, min(int(shot.get("rows") or 24), MAX_ROWS))
+ lines = [str(line)[:cols] for line in shot.get("lines", [])][:nrows]
+ grid: list[list[Cell]] = [
+ [(ch, DEFAULT_COLOUR, DEFAULT_COLOUR, 0) for ch in line] for line in lines
+ ]
+ while len(grid) < nrows:
+ grid.append([])
+ if (cols, nrows) != (w.plain_cols, w.plain_rows_n):
+ w.need_snapshot = True
+ for r in range(nrows):
+ old = w.plain_rows[r] if r < len(w.plain_rows) else []
+ if old != grid[r]:
+ w.plain_dirty.add(r)
+ cursor = shot.get("cursor")
+ w.plain_cursor = (
+ [int(cursor[0]), int(cursor[1])]
+ if isinstance(cursor, list | tuple) and len(cursor) == 2
+ else [-1, -1]
+ )
+ w.plain_rows, w.plain_cols, w.plain_rows_n = grid, cols, nrows
+ at = shot.get("at")
+ w.at = float(at) if isinstance(at, int | float) else w.at
+
+ # ------------------------------------------------------------------ metrics
+ def feed_p99_ms(self) -> float:
+ return self._p99(self.feed_seconds)
+
+ def frame_p99_ms(self) -> float:
+ return self._p99(self.frame_seconds)
+
+ @staticmethod
+ def _p99(samples: list[float]) -> float:
+ if not samples:
+ return 0.0
+ ordered = sorted(samples)
+ return ordered[min(len(ordered) - 1, int(len(ordered) * 0.99))] * 1000.0
diff --git a/dodaios/verse_host/relays/settings.py b/dodaios/verse_host/relays/settings.py
new file mode 100644
index 0000000000..a7be37f741
--- /dev/null
+++ b/dodaios/verse_host/relays/settings.py
@@ -0,0 +1,134 @@
+"""Locale, ``verse.*`` settings and the companion topic (BW10, BW12; contract 3.2, 12, 14).
+
+``welcome.locale`` carries the frontend i18n chunk ``ship`` for the
+person's language, read from the same JSON files the web app bundles, so a
+string change needs no Unreal rebuild. ``settings.set`` validates and writes
+the ``verse.*`` keys and answers with every setting; ``settings.changed``
+then reaches Verse and, through ``VerseSettingsChanged`` on the bus, the web
+UI. The ``companion`` topic sends the active pet and the overlay style, and
+an update within 2 s of a ``PetChanged``.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from functools import lru_cache
+from pathlib import Path
+from typing import Any
+
+from .. import protocol as P
+from ..settings_store import SettingsError, SettingsStore
+from .base import RelayBase
+
+log = logging.getLogger(__name__)
+
+LOCALES = ("en", "de", "es", "pt", "zh")
+SHIP_DIR = (
+ Path(__file__).resolve().parents[2]
+ / "ui"
+ / "web"
+ / "frontend"
+ / "src"
+ / "i18n"
+ / "locales"
+ / "ship"
+)
+
+
+def _flatten(prefix: str, node: Any, out: dict[str, str]) -> None:
+ if isinstance(node, dict):
+ for key, value in node.items():
+ _flatten(f"{prefix}.{key}" if prefix else str(key), value, out)
+ elif isinstance(node, str):
+ out[prefix] = node
+
+
+@lru_cache(maxsize=8)
+def _chunk(lang: str, root: str) -> dict[str, str]:
+ out: dict[str, str] = {}
+ folder = Path(root)
+ if not folder.is_dir():
+ return out
+ for path in sorted(folder.glob(f"*.{lang}.json")):
+ try:
+ _flatten("", json.loads(path.read_text(encoding="utf-8")), out)
+ except (OSError, ValueError):
+ log.warning("verse locale: %s unreadable", path.name)
+ return out
+
+
+def locale_strings(lang: str, root: Path = SHIP_DIR) -> dict[str, str]:
+ """The ``ship`` chunk for ``lang`` over the English one (missing keys fall back)."""
+ strings = dict(_chunk("en", str(root)))
+ if lang != "en":
+ strings.update(_chunk(lang, str(root)))
+ return strings
+
+
+def ui_language(config: Any) -> str:
+ lang = str(getattr(getattr(config, "ui", None), "language", "") or "en").lower()
+ lang = lang.split("-", 1)[0].split("_", 1)[0]
+ return lang if lang in LOCALES else "en"
+
+
+def locale_block(config: Any, root: Path = SHIP_DIR) -> dict[str, Any]:
+ lang = ui_language(config)
+ return {"lang": lang, "fallback": "en", "strings": locale_strings(lang, root)}
+
+
+class SettingsRelay(RelayBase):
+ """``settings.set`` and the live ``settings.changed`` push."""
+
+ topics = ()
+
+ def __init__(self, session: Any, backend: Any, store: SettingsStore, publish: Any) -> None:
+ super().__init__(session, backend)
+ self.store = store
+ self.publish = publish
+
+ async def start(self) -> None:
+ self.session.hub.command("settings.set", self._set)
+
+ async def _set(self, session: Any, msg: P.Inbound) -> dict[str, Any]:
+ try:
+ settings = self.store.update(dict(msg.data))
+ except SettingsError as exc:
+ raise P.BridgeError("bad_request", str(exc)) from exc
+ changed = {k: settings[k] for k in msg.data if k in settings}
+ self.session.send("settings.changed", changed)
+ if self.publish is not None:
+ await self.publish(changed)
+ return {"settings": settings}
+
+
+class CompanionRelay(RelayBase):
+ topics = ("companion",)
+
+ async def start(self) -> None:
+ from dodaios.core import events as E
+
+ self.listen([E.PetChanged], self._on_pet)
+ self.last: dict[str, Any] | None = None
+
+ async def read(self) -> dict[str, Any]:
+ pet = await self.backend.active_pet()
+ pet_id = pet.get("pet_id")
+ return {
+ "pet_id": pet_id if isinstance(pet_id, str) and pet_id else None,
+ "look": str(pet.get("look") or ""),
+ "style": str(pet.get("style") or "default"),
+ }
+
+ async def subscribe(self, topic: str) -> None:
+ self.last = await self.read()
+ self.session.outbox.snapshot_of["companion"] = lambda: self.last
+ self.session.send("companion.snapshot", self.last, topic="companion", feed=True)
+
+ async def _on_pet(self, _event: Any) -> None:
+ if "companion" not in self.subscribed:
+ return
+ current = await self.read()
+ if current != self.last:
+ self.last = current
+ self.session.send("companion.update", current, topic="companion", feed=True)
diff --git a/dodaios/verse_host/settings_store.py b/dodaios/verse_host/settings_store.py
new file mode 100644
index 0000000000..7b7f05bb08
--- /dev/null
+++ b/dodaios/verse_host/settings_store.py
@@ -0,0 +1,210 @@
+"""The ``verse.*`` settings: one small JSON store under ``<DATA_DIR>/verse/``.
+
+Contract 3.2 and 14: ``welcome.settings`` carries them, ``settings.set``
+writes them, ``settings.changed`` announces them, and the one-time
+``POST /api/verse/settings/import`` moves the values the web Verse kept in
+browser storage. The file layout is internal (not frozen by the contract).
+
+Keys also kept here that never cross the bridge: ``told_seq`` (the highest
+award Verse has shown), ``unreal_preview`` (the launcher card flag),
+``dev_bridge`` (dev discovery file), ``imported`` (import done) and
+``arcade_best`` (the simulator record imported from the web arcade).
+"""
+
+from __future__ import annotations
+
+import copy
+import json
+import logging
+import os
+import re
+import threading
+from pathlib import Path
+from typing import Any, Final
+
+from .env import getenv
+
+log = logging.getLogger(__name__)
+
+DEFAULT_SETTINGS: Final[dict[str, Any]] = {
+ "gore": "full",
+ "reduced_motion": False,
+ "return_key": "F10",
+ "ui_sound": True,
+ "level_sound": True,
+ "uniform": "standard",
+ "view": {
+ "mode": "third",
+ "sensitivity": 1.0,
+ "invert_y": False,
+ "fov_third": 70,
+ "fov_first": 85,
+ "quality": "auto",
+ "volume": 0.7,
+ },
+}
+_KEY_NAME = re.compile(r"^[A-Za-z0-9_+\-]{1,24}$")
+
+
+class SettingsError(ValueError):
+ """A ``settings.set`` value or key the contract does not allow."""
+
+
+def _is_number(v: Any) -> bool:
+ return isinstance(v, int | float) and not isinstance(v, bool)
+
+
+def _check_view(view: Any) -> dict[str, Any]:
+ if not isinstance(view, dict) or not view:
+ raise SettingsError("view must be a non-empty object")
+ out: dict[str, Any] = {}
+ for key, value in view.items():
+ if key == "mode":
+ if value not in ("overview", "third", "first"):
+ raise SettingsError(f"view.mode {value!r}")
+ elif key == "quality":
+ if value not in ("auto", "high", "low"):
+ raise SettingsError(f"view.quality {value!r}")
+ elif key == "invert_y":
+ if not isinstance(value, bool):
+ raise SettingsError("view.invert_y must be a boolean")
+ elif key == "sensitivity":
+ if not _is_number(value) or value <= 0 or value > 20:
+ raise SettingsError("view.sensitivity must be a number above 0")
+ elif key in ("fov_third", "fov_first"):
+ if not _is_number(value) or not 30 <= value <= 130:
+ raise SettingsError(f"view.{key} must be 30..130")
+ elif key == "volume":
+ if not _is_number(value) or not 0 <= value <= 1:
+ raise SettingsError("view.volume must be 0..1")
+ else:
+ raise SettingsError(f"unknown setting view.{key}")
+ out[key] = value
+ return out
+
+
+def validate(patch: Any) -> dict[str, Any]:
+ """A ``settings.set`` body checked key by key; unknown keys raise."""
+ if not isinstance(patch, dict) or not patch:
+ raise SettingsError("settings.set needs at least one setting")
+ out: dict[str, Any] = {}
+ for key, value in patch.items():
+ if key == "gore":
+ if value not in ("full", "reduced"):
+ raise SettingsError(f"gore {value!r}")
+ elif key in ("reduced_motion", "ui_sound", "level_sound"):
+ if not isinstance(value, bool):
+ raise SettingsError(f"{key} must be a boolean")
+ elif key == "return_key":
+ if not isinstance(value, str) or not _KEY_NAME.match(value) or value == "Escape":
+ raise SettingsError("return_key must be a key name other than Escape")
+ elif key == "uniform":
+ if not isinstance(value, str) or not 1 <= len(value) <= 40:
+ raise SettingsError("uniform must be a short id")
+ elif key == "view":
+ value = _check_view(value)
+ else:
+ raise SettingsError(f"unknown setting {key}")
+ out[key] = value
+ return out
+
+
+class SettingsStore:
+ """Thread-safe JSON file of the Verse settings and its small state."""
+
+ def __init__(self, path: Path | None = None) -> None:
+ if path is None:
+ from dodaios.core.config import DATA_DIR
+
+ path = Path(DATA_DIR) / "verse" / "settings.json"
+ self.path = Path(path)
+ self._lock = threading.Lock()
+ self._data: dict[str, Any] | None = None
+
+ def _load(self) -> dict[str, Any]:
+ if self._data is None:
+ try:
+ raw = json.loads(self.path.read_text(encoding="utf-8"))
+ self._data = raw if isinstance(raw, dict) else {}
+ except FileNotFoundError: # first run: no settings file yet
+ self._data = {}
+ except (OSError, ValueError):
+ log.warning("verse: settings file unreadable, starting from defaults")
+ self._data = {}
+ return self._data
+
+ def _save(self) -> None:
+ assert self._data is not None
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = self.path.with_suffix(".tmp")
+ tmp.write_text(json.dumps(self._data, indent=2, sort_keys=True), encoding="utf-8")
+ os.replace(tmp, self.path)
+
+ # ------------------------------------------------------------------ settings
+ def settings(self) -> dict[str, Any]:
+ """Every bridge setting: stored values over the defaults."""
+ with self._lock:
+ stored = self._load().get("settings", {})
+ out = copy.deepcopy(DEFAULT_SETTINGS)
+ for key, value in stored.items():
+ if key == "view" and isinstance(value, dict):
+ out["view"].update(value)
+ elif key in out:
+ out[key] = value
+ return out
+
+ def is_set(self, key: str) -> bool:
+ with self._lock:
+ stored = self._load().get("settings", {})
+ head, _, sub = key.partition(".")
+ if sub:
+ return isinstance(stored.get(head), dict) and sub in stored[head]
+ return head in stored
+
+ def update(self, patch: dict[str, Any]) -> dict[str, Any]:
+ """Write a validated patch; returns every setting after the write."""
+ patch = validate(patch)
+ with self._lock:
+ data = self._load()
+ stored = data.setdefault("settings", {})
+ for key, value in patch.items():
+ if key == "view":
+ stored.setdefault("view", {}).update(value)
+ else:
+ stored[key] = value
+ self._save()
+ return self.settings()
+
+ # ------------------------------------------------------------------ state
+ def get(self, key: str, default: Any = None) -> Any:
+ with self._lock:
+ return self._load().get(key, default)
+
+ def put(self, key: str, value: Any) -> None:
+ with self._lock:
+ self._load()[key] = value
+ self._save()
+
+ def told_seq(self) -> int:
+ value = self.get("told_seq", 0)
+ return value if isinstance(value, int) and value >= 0 else 0
+
+ def raise_told_seq(self, seq: int) -> int:
+ """Store ``seq`` when it is higher; returns the stored value."""
+ with self._lock:
+ data = self._load()
+ current = data.get("told_seq", 0)
+ if not isinstance(current, int) or seq > current:
+ data["told_seq"] = seq
+ self._save()
+ return int(data["told_seq"]) if "told_seq" in data else 0
+
+ def flag(self, name: str, env: str | None = None) -> bool:
+ """A boolean flag of this store, overridden by ``env`` when set."""
+ value = getenv(env) if env else ""
+ if value:
+ return value.strip().lower() in ("1", "true", "yes", "on")
+ return bool(self.get(name, False))
+
+ def set_flag(self, name: str, value: bool) -> None:
+ self.put(name, bool(value))
diff --git a/dodaios/verse_host/styled_screen.py b/dodaios/verse_host/styled_screen.py
new file mode 100644
index 0000000000..21d6651a7b
--- /dev/null
+++ b/dodaios/verse_host/styled_screen.py
@@ -0,0 +1,565 @@
+"""The styled screen mirror of one watched pane (contract 5.1, architecture 5.3).
+
+``dodaios.agentic_ide.screen.ScreenBuffer`` replays a PTY stream for reading
+and drops colours. The Verse desk monitors need what the IDE shows, so this
+is a second, attribute-keeping grid created only for the panes Verse
+watches. It keeps per cell ``(char, fg, bg, attrs)`` in the ``cells.bin/1``
+encodings (:mod:`.cells_codec`) and records which rows changed since the
+last frame, so the screens relay sends dirty rows only.
+
+Supported beyond the base buffer: SGR (bold, dim, italic, underline, blink,
+inverse, invisible, strikethrough, 16/256 palette colours, 24-bit RGB, their
+resets), wide glyphs (two columns), the alternate screen (1049/1047/47),
+save and restore cursor (DECSC/DECRC, CSI s/u). The base buffer stays
+untouched and dependency-free.
+"""
+
+from __future__ import annotations
+
+import re
+import unicodedata
+
+from .cells_codec import (
+ ATTR_BITS,
+ DEFAULT_COLOUR,
+ MAX_COLS,
+ MAX_ROWS,
+ WIDE,
+ Cell,
+ is_wide,
+ palette,
+ rgb,
+ row_runs,
+)
+
+_SGR_SET = {
+ 1: ATTR_BITS["bold"],
+ 2: ATTR_BITS["dim"],
+ 3: ATTR_BITS["italic"],
+ 4: ATTR_BITS["underline"],
+ 5: ATTR_BITS["blink"],
+ 6: ATTR_BITS["blink"],
+ 7: ATTR_BITS["inverse"],
+ 8: ATTR_BITS["invisible"],
+ 9: ATTR_BITS["strikethrough"],
+}
+_SGR_CLEAR = {
+ 21: ATTR_BITS["bold"],
+ 22: ATTR_BITS["bold"] | ATTR_BITS["dim"],
+ 23: ATTR_BITS["italic"],
+ 24: ATTR_BITS["underline"],
+ 25: ATTR_BITS["blink"],
+ 27: ATTR_BITS["inverse"],
+ 28: ATTR_BITS["invisible"],
+ 29: ATTR_BITS["strikethrough"],
+}
+
+
+_ASCII_RUN = re.compile(r"[ -~]+")
+
+
+def _clamp(value: int, low: int, high: int) -> int:
+ return low if value < low else high if value > high else value
+
+
+class StyledScreen:
+ """A styled cell grid with a cursor and dirty-row tracking."""
+
+ def __init__(self, cols: int = 100, rows: int = 30) -> None:
+ self.cols = _clamp(cols, 1, 500)
+ self.rows = _clamp(rows, 1, 200)
+ self._fg = DEFAULT_COLOUR
+ self._bg = DEFAULT_COLOUR
+ self._attrs = 0
+ self._grid = [self._blank_row() for _ in range(self.rows)]
+ self._alt: list[list[Cell]] | None = None
+ self._main_saved: list[list[Cell]] | None = None
+ self.cursor_row = 0
+ self.cursor_col = 0
+ self.cursor_visible = True
+ self._saved_cursor = (0, 0, DEFAULT_COLOUR, DEFAULT_COLOUR, 0)
+ self._scroll_top = 0
+ self._scroll_bottom = self.rows - 1
+ self._wrap_pending = False
+ self._pending = ""
+ self.dirty: set[int] = set(range(self.rows))
+ self.resized = False
+ self.errors = 0
+
+ # ------------------------------------------------------------------ grid
+ def _blank(self) -> Cell:
+ # Erase fills with the current background (VT "bce" behaviour).
+ return (" ", DEFAULT_COLOUR, self._bg, 0)
+
+ def _blank_row(self) -> list[Cell]:
+ blank = self._blank()
+ return [blank] * self.cols
+
+ def _touch(self, row: int) -> None:
+ self.dirty.add(row)
+
+ def _touch_range(self, top: int, bottom: int) -> None:
+ self.dirty.update(range(top, bottom + 1))
+
+ def resize(self, cols: int, rows: int) -> None:
+ cols, rows = _clamp(cols, 1, 500), _clamp(rows, 1, 200)
+ if (cols, rows) == (self.cols, self.rows):
+ return
+ old = self._grid
+ self.cols, self.rows = cols, rows
+ self._grid = [self._blank_row() for _ in range(rows)]
+ for r in range(min(rows, len(old))):
+ for c in range(min(cols, len(old[r]))):
+ self._grid[r][c] = old[r][c]
+ self.cursor_row = min(self.cursor_row, rows - 1)
+ self.cursor_col = min(self.cursor_col, cols - 1)
+ self._scroll_top, self._scroll_bottom = 0, rows - 1
+ self.dirty = set(range(rows))
+ self.resized = True
+
+ def _scroll_up(self, count: int = 1) -> None:
+ for _ in range(max(1, count)):
+ self._grid.pop(self._scroll_top)
+ self._grid.insert(self._scroll_bottom, self._blank_row())
+ self._touch_range(self._scroll_top, self._scroll_bottom)
+
+ def _scroll_down(self, count: int = 1) -> None:
+ for _ in range(max(1, count)):
+ self._grid.pop(self._scroll_bottom)
+ self._grid.insert(self._scroll_top, self._blank_row())
+ self._touch_range(self._scroll_top, self._scroll_bottom)
+
+ def _newline(self) -> None:
+ if self.cursor_row == self._scroll_bottom:
+ self._scroll_up()
+ elif self.cursor_row < self.rows - 1:
+ self.cursor_row += 1
+
+ def _put(self, ch: str) -> None:
+ width = 2 if is_wide(ch) else 1
+ if self._wrap_pending or self.cursor_col + width > self.cols:
+ if self._wrap_pending or self.cursor_col > 0:
+ self.cursor_col = 0
+ self._newline()
+ self._wrap_pending = False
+ row = self._grid[self.cursor_row]
+ col = self.cursor_col
+ # Writing over half of a wide glyph blanks its other half.
+ if row[col][0] == "" and col > 0:
+ row[col - 1] = self._blank()
+ attrs = self._attrs | (WIDE if width == 2 else 0)
+ row[col] = (ch, self._fg, self._bg, attrs)
+ if width == 2 and col + 1 < self.cols:
+ row[col + 1] = ("", self._fg, self._bg, 0)
+ elif col + 1 < self.cols and row[col + 1][0] == "" and width == 1:
+ row[col + 1] = self._blank()
+ self._touch(self.cursor_row)
+ if col + width >= self.cols:
+ self._wrap_pending = True
+ self.cursor_col = self.cols - 1
+ else:
+ self.cursor_col = col + width
+
+ def _append_combining(self, ch: str) -> None:
+ col = self.cursor_col - 1 if not self._wrap_pending else self.cursor_col
+ row = self._grid[self.cursor_row]
+ while col > 0 and row[col][0] == "":
+ col -= 1
+ if 0 <= col < self.cols and row[col][0] not in ("", " "):
+ c, fg, bg, attrs = row[col]
+ row[col] = (c + ch, fg, bg, attrs)
+ self._touch(self.cursor_row)
+
+ # ------------------------------------------------------------------ feed
+ def feed(self, chunk: str) -> None:
+ """Replay a raw PTY chunk; a parser error marks the mirror unreliable."""
+ if not chunk:
+ return
+ try:
+ self._feed(chunk)
+ except Exception: # noqa: BLE001 — a hostile stream must not take the relay down
+ self.errors += 1
+ self._pending = ""
+
+ def _put_ascii(self, text: str) -> None:
+ """Fast path for a run of printable ASCII (one column per char, no clusters)."""
+ fg, bg, attrs = self._fg, self._bg, self._attrs
+ cols = self.cols
+ pos = 0
+ n = len(text)
+ while pos < n:
+ if self._wrap_pending:
+ self.cursor_col = 0
+ self._newline()
+ self._wrap_pending = False
+ row = self._grid[self.cursor_row]
+ col = self.cursor_col
+ if col > 0 and row[col][0] == "":
+ row[col - 1] = self._blank()
+ take = min(n - pos, cols - col)
+ for k in range(take):
+ row[col + k] = (text[pos + k], fg, bg, attrs)
+ end = col + take
+ if end < cols and row[end][0] == "":
+ row[end] = self._blank()
+ self.dirty.add(self.cursor_row)
+ pos += take
+ if end >= cols:
+ self._wrap_pending = True
+ self.cursor_col = cols - 1
+ else:
+ self.cursor_col = end
+
+ def _feed(self, chunk: str) -> None:
+ data = self._pending + chunk
+ self._pending = ""
+ i, n = 0, len(data)
+ while i < n:
+ ch = data[i]
+ if " " <= ch <= "~":
+ m = _ASCII_RUN.match(data, i)
+ assert m is not None
+ self._put_ascii(m.group())
+ i = m.end()
+ continue
+ if ch == "\x1b":
+ consumed = self._escape(data, i)
+ if consumed == 0:
+ self._pending = data[i:][:256]
+ return
+ i += consumed
+ continue
+ i += 1
+ if ch == "\n" or ch == "\x0b" or ch == "\x0c":
+ self._wrap_pending = False
+ self._newline()
+ elif ch == "\r":
+ self._wrap_pending = False
+ self.cursor_col = 0
+ elif ch == "\b":
+ self._wrap_pending = False
+ self.cursor_col = max(0, self.cursor_col - 1)
+ elif ch == "\t":
+ self._wrap_pending = False
+ self.cursor_col = min(self.cols - 1, (self.cursor_col // 8 + 1) * 8)
+ elif ch < " " or ch == "\x7f":
+ continue
+ elif (
+ unicodedata.category(ch) in ("Mn", "Me", "Mc")
+ or ch == "‍"
+ or "︀" <= ch <= "️"
+ or 0x1F3FB <= ord(ch) <= 0x1F3FF
+ ):
+ self._append_combining(ch)
+ else:
+ self._put(ch)
+
+ def _escape(self, data: str, start: int) -> int:
+ n = len(data)
+ if start + 1 >= n:
+ return 0
+ kind = data[start + 1]
+ if kind == "[":
+ return self._csi(data, start)
+ if kind in "]PX^_":
+ # OSC / DCS / SOS / PM / APC: string ends at BEL or ST.
+ j = start + 2
+ while j < n:
+ if data[j] == "\x07":
+ return j - start + 1
+ if data[j] == "\x1b":
+ if j + 1 >= n:
+ return 0
+ return j - start + (2 if data[j + 1] == "\\" else 1)
+ j += 1
+ return 0
+ if kind in "()#%*+":
+ return 3 if start + 2 < n else 0
+ if kind == "D":
+ self._newline()
+ elif kind == "M":
+ if self.cursor_row == self._scroll_top:
+ self._scroll_down()
+ else:
+ self.cursor_row = max(0, self.cursor_row - 1)
+ elif kind == "E":
+ self.cursor_col = 0
+ self._newline()
+ elif kind == "7":
+ self._save_cursor()
+ elif kind == "8":
+ self._restore_cursor()
+ elif kind == "c":
+ self.reset()
+ return 2
+
+ def _save_cursor(self) -> None:
+ self._saved_cursor = (self.cursor_row, self.cursor_col, self._fg, self._bg, self._attrs)
+
+ def _restore_cursor(self) -> None:
+ r, c, self._fg, self._bg, self._attrs = self._saved_cursor
+ self.cursor_row = min(r, self.rows - 1)
+ self.cursor_col = min(c, self.cols - 1)
+ self._wrap_pending = False
+
+ def _set_alt(self, on: bool) -> None:
+ if on and self._main_saved is None:
+ self._main_saved = self._grid
+ self._grid = [self._blank_row() for _ in range(self.rows)]
+ elif not on and self._main_saved is not None:
+ saved = self._main_saved
+ self._main_saved = None
+ self._grid = [
+ (row + [self._blank()] * self.cols)[: self.cols] for row in saved[: self.rows]
+ ]
+ while len(self._grid) < self.rows:
+ self._grid.append(self._blank_row())
+ self.dirty = set(range(self.rows))
+
+ def _csi(self, data: str, start: int) -> int:
+ n = len(data)
+ j = start + 2
+ params_start = j
+ while j < n and "\x30" <= data[j] <= "\x3f":
+ j += 1
+ while j < n and "\x20" <= data[j] <= "\x2f":
+ j += 1
+ if j >= n:
+ return 0 if n - start < 256 else n - start
+ final = data[j]
+ raw = data[params_start:j]
+ length = j - start + 1
+ if raw.startswith("?"):
+ modes = raw[1:].split(";")
+ if final in "hl":
+ on = final == "h"
+ if "25" in modes:
+ self.cursor_visible = on
+ if any(m in ("1049", "1047", "47") for m in modes):
+ if on and "1049" in modes:
+ self._save_cursor()
+ self._set_alt(on)
+ if not on and "1049" in modes:
+ self._restore_cursor()
+ return length
+ if raw[:1] in (">", "=", "<"):
+ return length
+ if final == "m":
+ self._sgr(raw)
+ return length
+ params = (
+ [int(p) if p.isdigit() else 0 for p in raw.replace(":", ";").split(";")] if raw else []
+ )
+
+ def p(index: int, default: int = 1) -> int:
+ if index < len(params) and params[index] > 0:
+ return params[index]
+ return default
+
+ self._wrap_pending = False
+ row_i = self.cursor_row
+ if final in "Hf":
+ self.cursor_row = _clamp(p(0) - 1, 0, self.rows - 1)
+ self.cursor_col = _clamp(p(1) - 1, 0, self.cols - 1)
+ elif final == "A":
+ self.cursor_row = max(0, self.cursor_row - p(0))
+ elif final in "Be":
+ self.cursor_row = min(self.rows - 1, self.cursor_row + p(0))
+ elif final in "Ca":
+ self.cursor_col = min(self.cols - 1, self.cursor_col + p(0))
+ elif final == "D":
+ self.cursor_col = max(0, self.cursor_col - p(0))
+ elif final in "G`":
+ self.cursor_col = _clamp(p(0) - 1, 0, self.cols - 1)
+ elif final == "d":
+ self.cursor_row = _clamp(p(0) - 1, 0, self.rows - 1)
+ elif final == "E":
+ self.cursor_col = 0
+ self.cursor_row = min(self.rows - 1, self.cursor_row + p(0))
+ elif final == "F":
+ self.cursor_col = 0
+ self.cursor_row = max(0, self.cursor_row - p(0))
+ elif final == "K":
+ mode = params[0] if params else 0
+ row = self._grid[row_i]
+ lo, hi = (
+ (self.cursor_col, self.cols)
+ if mode == 0
+ else (0, min(self.cursor_col + 1, self.cols))
+ if mode == 1
+ else (0, self.cols)
+ )
+ blank = self._blank()
+ for c in range(lo, hi):
+ row[c] = blank
+ self._touch(row_i)
+ elif final == "J":
+ mode = params[0] if params else 0
+ blank = self._blank()
+ if mode == 0:
+ for c in range(self.cursor_col, self.cols):
+ self._grid[row_i][c] = blank
+ for r in range(row_i + 1, self.rows):
+ self._grid[r] = self._blank_row()
+ self._touch_range(row_i, self.rows - 1)
+ elif mode == 1:
+ for c in range(0, min(self.cursor_col + 1, self.cols)):
+ self._grid[row_i][c] = blank
+ for r in range(0, row_i):
+ self._grid[r] = self._blank_row()
+ self._touch_range(0, row_i)
+ else:
+ self._grid = [self._blank_row() for _ in range(self.rows)]
+ self.dirty = set(range(self.rows))
+ elif final == "L":
+ if self._scroll_top <= row_i <= self._scroll_bottom:
+ for _ in range(p(0)):
+ self._grid.pop(self._scroll_bottom)
+ self._grid.insert(row_i, self._blank_row())
+ self._touch_range(row_i, self._scroll_bottom)
+ elif final == "M":
+ if self._scroll_top <= row_i <= self._scroll_bottom:
+ for _ in range(p(0)):
+ self._grid.pop(row_i)
+ self._grid.insert(self._scroll_bottom, self._blank_row())
+ self._touch_range(row_i, self._scroll_bottom)
+ elif final == "P":
+ row = self._grid[row_i]
+ for _ in range(min(p(0), self.cols - self.cursor_col)):
+ del row[self.cursor_col]
+ row.append(self._blank())
+ self._touch(row_i)
+ elif final == "@":
+ row = self._grid[row_i]
+ for _ in range(min(p(0), self.cols - self.cursor_col)):
+ row.insert(self.cursor_col, self._blank())
+ row.pop()
+ self._touch(row_i)
+ elif final == "X":
+ row = self._grid[row_i]
+ blank = self._blank()
+ for c in range(self.cursor_col, min(self.cursor_col + p(0), self.cols)):
+ row[c] = blank
+ self._touch(row_i)
+ elif final == "S":
+ self._scroll_up(p(0))
+ elif final == "T":
+ self._scroll_down(p(0))
+ elif final == "r":
+ top = _clamp(p(0) - 1, 0, self.rows - 1)
+ bottom = _clamp(p(1, self.rows) - 1, 0, self.rows - 1)
+ if top < bottom:
+ self._scroll_top, self._scroll_bottom = top, bottom
+ else:
+ self._scroll_top, self._scroll_bottom = 0, self.rows - 1
+ self.cursor_row, self.cursor_col = 0, 0
+ elif final == "s":
+ self._save_cursor()
+ elif final == "u":
+ self._restore_cursor()
+ return length
+
+ def _sgr(self, raw: str) -> None:
+ parts = raw.replace(":", ";").split(";") if raw else ["0"]
+ values = [int(v) if v.isdigit() else 0 for v in parts]
+ i = 0
+ while i < len(values):
+ v = values[i]
+ i += 1
+ if v == 0:
+ self._fg, self._bg, self._attrs = DEFAULT_COLOUR, DEFAULT_COLOUR, 0
+ elif v in _SGR_SET:
+ self._attrs |= _SGR_SET[v]
+ elif v in _SGR_CLEAR:
+ self._attrs &= ~_SGR_CLEAR[v]
+ elif 30 <= v <= 37:
+ self._fg = palette(v - 30)
+ elif 90 <= v <= 97:
+ self._fg = palette(v - 90 + 8)
+ elif v == 39:
+ self._fg = DEFAULT_COLOUR
+ elif 40 <= v <= 47:
+ self._bg = palette(v - 40)
+ elif 100 <= v <= 107:
+ self._bg = palette(v - 100 + 8)
+ elif v == 49:
+ self._bg = DEFAULT_COLOUR
+ elif v in (38, 48, 58):
+ colour = None
+ if i < len(values) and values[i] == 5 and i + 1 < len(values):
+ colour = palette(values[i + 1])
+ i += 2
+ elif i < len(values) and values[i] == 2 and i + 3 < len(values):
+ colour = rgb(values[i + 1], values[i + 2], values[i + 3])
+ i += 4
+ else:
+ break
+ if v == 38:
+ self._fg = colour
+ elif v == 48:
+ self._bg = colour
+
+ def reset(self) -> None:
+ self._fg = self._bg = DEFAULT_COLOUR
+ self._attrs = 0
+ self._grid = [self._blank_row() for _ in range(self.rows)]
+ self._main_saved = None
+ self.cursor_row = self.cursor_col = 0
+ self.cursor_visible = True
+ self._scroll_top, self._scroll_bottom = 0, self.rows - 1
+ self._wrap_pending = False
+ self._pending = ""
+ self.dirty = set(range(self.rows))
+
+ # ---------------------------------------------------------------- output
+ @property
+ def cut(self) -> bool:
+ return self.cols > MAX_COLS or self.rows > MAX_ROWS
+
+ @property
+ def sent_cols(self) -> int:
+ return min(self.cols, MAX_COLS)
+
+ @property
+ def sent_rows(self) -> int:
+ return min(self.rows, MAX_ROWS)
+
+ def cursor(self) -> list[int]:
+ """``[row, col]`` inside the sent grid, or ``[-1, -1]`` when hidden or cut away."""
+ if not self.cursor_visible:
+ return [-1, -1]
+ if self.cursor_row >= self.sent_rows or self.cursor_col >= self.sent_cols:
+ return [-1, -1]
+ return [self.cursor_row, self.cursor_col]
+
+ def row_record(self, row: int) -> dict:
+ return {"row": row, "runs": row_runs(self._grid[row], self.sent_cols)}
+
+ def snapshot_rows(self) -> list[dict]:
+ """Every non-empty row of the sent grid (snapshot rule of 5.4)."""
+ out = []
+ for r in range(self.sent_rows):
+ record = self.row_record(r)
+ if record["runs"]:
+ out.append(record)
+ return out
+
+ def take_dirty(self) -> list[dict]:
+ """Row records of the rows changed since the last call, then clear the set."""
+ rows = sorted(r for r in self.dirty if r < self.sent_rows)
+ self.dirty = set()
+ return [self.row_record(r) for r in rows]
+
+ def text_rows(self) -> list[str]:
+ return ["".join(c[0] for c in row).rstrip() for row in self._grid]
+
+
+def plain_cells(lines: list[str], cols: int) -> list[list[Cell]]:
+ """Plain ``ScreenBuffer`` rows as default-coloured cells (the ``style: plain`` fallback)."""
+ grid: list[list[Cell]] = []
+ for line in lines:
+ row: list[Cell] = []
+ for ch in line[:cols]:
+ row.append((ch, DEFAULT_COLOUR, DEFAULT_COLOUR, 0))
+ grid.append(row)
+ return grid
diff --git a/dodaios/verse_host/supervisor.py b/dodaios/verse_host/supervisor.py
new file mode 100644
index 0000000000..a0870a3b28
--- /dev/null
+++ b/dodaios/verse_host/supervisor.py
@@ -0,0 +1,428 @@
+"""Supervisor (17.3, BW2, architecture 1.1): spawn, watch, restart, stop ``Verse.exe``.
+
+* Lazy: launched on the first ``show``, never at app start.
+* Containment: a Windows job object with ``KILL_ON_JOB_CLOSE`` (the app's
+ handle closes when the app dies, and the job kills Verse); on Linux
+ ``prctl(PR_SET_PDEATHSIG, SIGKILL)`` plus its own process group. Verse is
+ only ever stopped by the PID this supervisor started.
+* Token: 256 bits, minted per launch, passed in ``DODAIOS_VERSE_TOKEN`` with
+ the bridge URL in ``DODAIOS_VERSE_BRIDGE``; never on the command line and
+ never logged.
+* Liveness: an unplanned exit or a hung bridge (5 s silent) is a crash. An
+ exit Verse announced (``lifecycle.bye``, or ``gpu.yield`` while Dormant,
+ contract 12) is a stop: status ``stopped``, no restart, no crash entry. Restarts after
+ 1 s, 4 s, 15 s; three crashes within 5 minutes stop it: status ``crashed``
+ until a manual launch.
+* Crash data: ``<DATA_DIR>/verse/crashes/<stamp>/`` gets the exit record, the
+ last Verse log and any minidump. Never uploaded.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import json
+import logging
+import os
+import shutil
+import signal
+import subprocess
+import sys
+import time
+from collections.abc import Awaitable, Callable
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Protocol
+
+log = logging.getLogger(__name__)
+
+BACKOFF_S = (1.0, 4.0, 15.0)
+CRASH_WINDOW_S = 300.0
+CRASH_LIMIT = 3
+HEALTHY_AFTER_S = 300.0
+QUIT_DEADLINE_MS = 3000
+
+
+class Process(Protocol):
+ pid: int
+
+ async def wait(self) -> int: ...
+ def kill(self) -> None: ...
+ def alive(self) -> bool: ...
+
+
+Spawner = Callable[[list[str], dict[str, str], Path], Awaitable[Process]]
+
+
+# ---------------------------------------------------------------------- containment
+
+
+class _WindowsJob: # pragma: no cover - exercised by the Windows containment test
+ """A job object that kills every process in it when its last handle closes."""
+
+ def __init__(self) -> None:
+ import ctypes
+ from ctypes import wintypes
+
+ self._ctypes = ctypes
+ k32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ self._k32 = k32
+ k32.CreateJobObjectW.restype = wintypes.HANDLE
+ k32.CreateJobObjectW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR]
+ k32.SetInformationJobObject.argtypes = [
+ wintypes.HANDLE,
+ ctypes.c_int,
+ ctypes.c_void_p,
+ wintypes.DWORD,
+ ]
+ k32.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
+ k32.OpenProcess.restype = wintypes.HANDLE
+ k32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
+ k32.CloseHandle.argtypes = [wintypes.HANDLE]
+
+ class IO_COUNTERS(ctypes.Structure): # noqa: N801
+ _fields_ = [(n, ctypes.c_ulonglong) for n in ("r", "w", "o", "rb", "wb", "ob")]
+
+ class BASIC(ctypes.Structure):
+ _fields_ = [
+ ("PerProcessUserTimeLimit", ctypes.c_longlong),
+ ("PerJobUserTimeLimit", ctypes.c_longlong),
+ ("LimitFlags", wintypes.DWORD),
+ ("MinimumWorkingSetSize", ctypes.c_size_t),
+ ("MaximumWorkingSetSize", ctypes.c_size_t),
+ ("ActiveProcessLimit", wintypes.DWORD),
+ ("Affinity", ctypes.c_size_t),
+ ("PriorityClass", wintypes.DWORD),
+ ("SchedulingClass", wintypes.DWORD),
+ ]
+
+ class EXTENDED(ctypes.Structure):
+ _fields_ = [
+ ("BasicLimitInformation", BASIC),
+ ("IoInfo", IO_COUNTERS),
+ ("ProcessMemoryLimit", ctypes.c_size_t),
+ ("JobMemoryLimit", ctypes.c_size_t),
+ ("PeakProcessMemoryUsed", ctypes.c_size_t),
+ ("PeakJobMemoryUsed", ctypes.c_size_t),
+ ]
+
+ self.handle = k32.CreateJobObjectW(None, None)
+ if not self.handle:
+ raise OSError(ctypes.get_last_error(), "CreateJobObject failed")
+ info = EXTENDED()
+ info.BasicLimitInformation.LimitFlags = 0x2000 # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
+ if not k32.SetInformationJobObject(
+ self.handle, 9, ctypes.byref(info), ctypes.sizeof(info)
+ ): # JobObjectExtendedLimitInformation
+ raise OSError(ctypes.get_last_error(), "SetInformationJobObject failed")
+
+ def assign(self, pid: int) -> None:
+ k32 = self._k32
+ process = k32.OpenProcess(0x0001 | 0x0100, False, pid) # TERMINATE | SET_QUOTA
+ if not process:
+ raise OSError(self._ctypes.get_last_error(), "OpenProcess failed")
+ try:
+ if not k32.AssignProcessToJobObject(self.handle, process):
+ raise OSError(self._ctypes.get_last_error(), "AssignProcessToJobObject failed")
+ finally:
+ k32.CloseHandle(process)
+
+
+_job: Any = None
+
+
+def _shared_job() -> Any: # pragma: no cover - Windows only
+ """One job per app process; its handle lives as long as the app does."""
+ global _job
+ if _job is None:
+ _job = _WindowsJob()
+ return _job
+
+
+def _linux_preexec() -> None: # pragma: no cover - runs in the child on Linux
+ import ctypes
+
+ libc = ctypes.CDLL("libc.so.6", use_errno=True)
+ libc.prctl(1, signal.SIGKILL) # PR_SET_PDEATHSIG
+ os.setpgid(0, 0)
+
+
+@dataclass
+class PopenProcess:
+ popen: subprocess.Popen[bytes]
+
+ @property
+ def pid(self) -> int:
+ return self.popen.pid
+
+ async def wait(self) -> int:
+ return await asyncio.to_thread(self.popen.wait)
+
+ def kill(self) -> None:
+ with contextlib.suppress(OSError):
+ self.popen.kill()
+
+ def alive(self) -> bool:
+ return self.popen.poll() is None
+
+
+async def spawn_contained(argv: list[str], env: dict[str, str], cwd: Path) -> Process:
+ """Start ``argv`` so it dies with this process (job object / PDEATHSIG)."""
+ return await asyncio.to_thread(_spawn_contained_sync, argv, env, cwd)
+
+
+def _spawn_contained_sync(argv: list[str], env: dict[str, str], cwd: Path) -> Process:
+ kwargs: dict[str, Any] = {
+ "cwd": str(cwd),
+ "env": env,
+ "stdin": subprocess.DEVNULL,
+ "stdout": subprocess.DEVNULL,
+ "stderr": subprocess.DEVNULL,
+ "close_fds": True,
+ }
+ if sys.platform == "win32":
+ kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
+ popen = subprocess.Popen(argv, **kwargs) # noqa: S603 - argv is our own exe, no shell
+ try:
+ _shared_job().assign(popen.pid)
+ except OSError:
+ log.warning("verse supervisor: job object unavailable; Verse may outlive the app")
+ else:
+ kwargs["preexec_fn"] = _linux_preexec # noqa: PLW1509 - prctl must run in the child
+ popen = subprocess.Popen(argv, **kwargs) # noqa: S603
+ return PopenProcess(popen)
+
+
+# ---------------------------------------------------------------------- supervisor
+
+
+@dataclass
+class SupervisorState:
+ status: str = "stopped"
+ pid: int | None = None
+ crash_report: str | None = None
+ crashes: list[float] = field(default_factory=list)
+ consecutive: int = 0
+ launched_at: float | None = None
+ last_exit: int | None = None
+
+
+class Supervisor:
+ def __init__(
+ self,
+ *,
+ exe: Callable[[], Path | None],
+ bridge_url: Callable[[], str],
+ set_token: Callable[[str | None], None],
+ mint: Callable[[], str],
+ crash_dir: Path,
+ spawn: Spawner = spawn_contained,
+ on_change: Callable[[], Awaitable[None]] | None = None,
+ request_quit: Callable[[str, int], Awaitable[bool]] | None = None,
+ clock: Callable[[], float] = time.monotonic,
+ sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
+ extra_args: list[str] | None = None,
+ ) -> None:
+ self._exe = exe
+ self._bridge_url = bridge_url
+ self._set_token = set_token
+ self._mint = mint
+ self.crash_dir = crash_dir
+ self._spawn = spawn
+ self._on_change = on_change
+ self._request_quit = request_quit
+ self._clock = clock
+ self._sleep = sleep
+ self.extra_args = list(extra_args or [])
+ self.state = SupervisorState()
+ self.process: Process | None = None
+ self._watch: asyncio.Task[None] | None = None
+ self._restart: asyncio.Task[None] | None = None
+ self._stopping = False
+ self._planned_until: float | None = None
+ self._lock = asyncio.Lock()
+ self.token_in_env: str | None = None
+ self.last_argv: list[str] = []
+ self.healthy_since: float | None = None
+
+ # ------------------------------------------------------------------ status
+ @property
+ def running(self) -> bool:
+ return self.process is not None and self.process.alive()
+
+ async def _changed(self) -> None:
+ if self._on_change is not None:
+ with contextlib.suppress(Exception):
+ await self._on_change()
+
+ # ------------------------------------------------------------------ launch
+ async def ensure_running(self, *, manual: bool = False) -> bool:
+ """Launch unless running. A crash loop stays stopped unless ``manual``."""
+ async with self._lock:
+ if self.running:
+ return True
+ if self.state.status == "crashed" and not manual:
+ return False
+ if manual:
+ self.state.crashes.clear()
+ self.state.consecutive = 0
+ return await self._launch()
+
+ async def _launch(self) -> bool:
+ exe = self._exe()
+ if exe is None:
+ self.state.status = "stopped"
+ return False
+ token = self._mint()
+ env = {
+ k: v
+ for k, v in os.environ.items()
+ if not k.startswith(("DODAIOS_VERSE_TOKEN", "JARVIS_VERSE_TOKEN"))
+ }
+ env["DODAIOS_VERSE_BRIDGE"] = self._bridge_url()
+ env["DODAIOS_VERSE_TOKEN"] = token
+ env["DODAIOS_VERSE_APP_PID"] = str(os.getpid())
+ argv = [str(exe), *self.extra_args]
+ self.last_argv = argv
+ self._set_token(token)
+ self.token_in_env = token
+ self._stopping = False
+ self._planned_until = None
+ try:
+ process = await self._spawn(argv, env, exe.parent)
+ except OSError as exc:
+ log.warning("verse supervisor: launch failed: %s", exc)
+ self._set_token(None)
+ self.state.status = "stopped"
+ await self._changed()
+ return False
+ self.process = process
+ self.state.status = "running"
+ self.state.pid = process.pid
+ self.state.launched_at = self._clock()
+ self.healthy_since = None
+ log.info("verse supervisor: started Verse pid %s", process.pid)
+ self._watch = asyncio.ensure_future(self._watch_exit(process))
+ await self._changed()
+ return True
+
+ def mark_healthy(self) -> None:
+ """``lifecycle.ready`` arrived: the launch counts as healthy."""
+ self.healthy_since = self._clock()
+
+ def expect_exit(self, within_s: float | None = None) -> None:
+ """Verse is about to quit on its own (``lifecycle.bye``, or ``gpu.yield`` while
+ Dormant): that exit is a stop, not a crash, and nothing restarts it.
+
+ ``within_s`` bounds the expectation; ``None`` holds until the next launch.
+ """
+ if self.process is None:
+ return
+ self._planned_until = float("inf") if within_s is None else self._clock() + float(within_s)
+ if self._restart is not None:
+ self._restart.cancel()
+
+ def _planned(self) -> bool:
+ return self._planned_until is not None and self._clock() <= self._planned_until
+
+ # ------------------------------------------------------------------ watch
+ async def _watch_exit(self, process: Process) -> None:
+ code = await process.wait()
+ if self.process is not process:
+ return
+ self.process = None
+ self.state.pid = None
+ self.state.last_exit = code
+ self._set_token(None)
+ self.token_in_env = None
+ if self._stopping or self._planned():
+ self._planned_until = None
+ self.state.status = "stopped"
+ log.info("verse supervisor: Verse exited (%s) after a stop", code)
+ await self._changed()
+ return
+ await self._crashed(code, "exited")
+
+ async def _crashed(self, code: int | None, why: str) -> None:
+ now = self._clock()
+ if self.healthy_since is not None and now - self.healthy_since >= HEALTHY_AFTER_S:
+ self.state.consecutive = 0
+ self.state.crashes = [t for t in self.state.crashes if now - t < CRASH_WINDOW_S]
+ self.state.crashes.append(now)
+ self.state.consecutive += 1
+ self.state.crash_report = self._save_crash(code, why)
+ log.warning(
+ "verse supervisor: Verse %s (code %s); crash %s", why, code, self.state.consecutive
+ )
+ if len(self.state.crashes) >= CRASH_LIMIT:
+ self.state.status = "crashed"
+ await self._changed()
+ return
+ delay = BACKOFF_S[min(self.state.consecutive, len(BACKOFF_S)) - 1]
+ self.state.status = "stopped"
+ await self._changed()
+ self._restart = asyncio.ensure_future(self._restart_after(delay))
+
+ async def _restart_after(self, delay: float) -> None:
+ await self._sleep(delay)
+ async with self._lock:
+ if self.running or self._stopping or self.state.status == "crashed":
+ return
+ await self._launch()
+
+ async def on_hung(self) -> None:
+ """The bridge saw 5 s of silence: stop this Verse by its own PID; it restarts."""
+ process = self.process
+ if process is None:
+ return
+ log.warning("verse supervisor: bridge hung, stopping pid %s", process.pid)
+ process.kill()
+
+ # ------------------------------------------------------------------ stop
+ async def stop(self, reason: str = "app_quit") -> None:
+ """Ask Verse to quit (``lifecycle.quit``), then end it by PID after the deadline."""
+ self._stopping = True
+ if self._restart is not None:
+ self._restart.cancel()
+ process = self.process
+ if process is None:
+ self.state.status = "stopped" if self.state.status != "crashed" else "crashed"
+ return
+ asked = False
+ if self._request_quit is not None:
+ with contextlib.suppress(Exception):
+ asked = await self._request_quit(reason, QUIT_DEADLINE_MS)
+ if asked:
+ deadline = self._clock() + QUIT_DEADLINE_MS / 1000.0 + 0.5
+ while process.alive() and self._clock() < deadline:
+ await self._sleep(0.05)
+ if process.alive():
+ process.kill()
+ if self._watch is not None:
+ with contextlib.suppress(Exception):
+ await asyncio.wait_for(asyncio.shield(self._watch), 5.0)
+
+ # ------------------------------------------------------------------ crash data
+ def _save_crash(self, code: int | None, why: str) -> str | None:
+ stamp = time.strftime("%Y%m%d-%H%M%S")
+ folder = self.crash_dir / stamp
+ try:
+ folder.mkdir(parents=True, exist_ok=True)
+ record = {"exit_code": code, "reason": why, "at": time.time()}
+ (folder / "exit.json").write_text(json.dumps(record, indent=2), encoding="utf-8")
+ exe = self._exe()
+ if exe is not None:
+ saved = exe.parent / "Verse" / "Saved"
+ log_file = saved / "Logs" / "Verse.log"
+ if log_file.is_file():
+ shutil.copy2(log_file, folder / "Verse.log")
+ crashes = saved / "Crashes"
+ if crashes.is_dir():
+ newest = sorted(crashes.iterdir(), key=lambda p: p.stat().st_mtime)[-1:]
+ for entry in newest:
+ for dump in entry.glob("*.dmp"):
+ shutil.copy2(dump, folder / dump.name)
+ except (OSError, IndexError):
+ log.warning("verse supervisor: crash data not saved", exc_info=True)
+ return None
+ return str(folder)
diff --git a/tests/unit/verse_host/_support.py b/tests/unit/verse_host/_support.py
new file mode 100644
index 0000000000..65ad992ee3
--- /dev/null
+++ b/tests/unit/verse_host/_support.py
@@ -0,0 +1,382 @@
+"""Test doubles for the verse host: a fake backend port, bus and in-memory socket."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from collections import defaultdict
+from pathlib import Path
+from typing import Any
+
+from dodaios.verse_host.bridge import TransportClosed
+from dodaios.verse_host.ports import NotFound, UnknownWorldAction
+
+FIXTURES = Path(__file__).parent / "fixtures" / "bridge"
+TOKEN = "t" * 43
+
+
+def golden(type_: str) -> list[dict]:
+ return json.loads((FIXTURES / "messages" / f"{type_}.json").read_text(encoding="utf-8"))
+
+
+def golden_replies(command: str) -> list[dict]:
+ return json.loads((FIXTURES / "replies" / f"{command}.json").read_text(encoding="utf-8"))
+
+
+def schema():
+ from scripts.unreal import bridge_schema
+
+ return bridge_schema.load()
+
+
+class FakeBus:
+ def __init__(self) -> None:
+ self.handlers: dict[type, list[Any]] = defaultdict(list)
+ self.published: list[Any] = []
+
+ def subscribe(self, event_type: type, handler: Any) -> None:
+ self.handlers[event_type].append(handler)
+
+ def unsubscribe(self, event_type: type, handler: Any) -> None:
+ if handler in self.handlers[event_type]:
+ self.handlers[event_type].remove(handler)
+
+ async def publish(self, event: Any) -> None:
+ self.published.append(event)
+ for handler in list(self.handlers[type(event)]):
+ await handler(event)
+
+
+class FakeDuelService:
+ def __init__(self) -> None:
+ self.results: dict[str, dict] = {}
+
+ def duel_stats(self) -> dict[str, Any]:
+ wins = sum(1 for r in self.results.values() if r["outcome"] == "won")
+ return {"matches": len(self.results), "wins": wins}
+
+ def record_duel(self, result: dict[str, Any]) -> dict[str, Any]:
+ first = result["match_id"] not in self.results
+ self.results.setdefault(result["match_id"], result)
+ awards = (
+ [{"xp_source": "duel_won", "xp": 60}] if first and result["outcome"] == "won" else []
+ )
+ return {"recorded": True, "awards": awards, "duel_stats": self.duel_stats()}
+
+
+class FakeBackend:
+ """Every read the relays make, from plain lists the test edits."""
+
+ def __init__(self) -> None:
+ self.bus = FakeBus()
+ self.agents: list[dict[str, Any]] = [
+ {
+ "agent_id": "ag_7f1",
+ "name": "Mara",
+ "title": "Research scout",
+ "tier": "specialist",
+ "state": "active",
+ "run_state": "waiting",
+ "waiting_reason": "question",
+ "avatar": {"look": "look_02", "archetype": "engineer", "palette": "graphite"},
+ "session_id": "society:ag_7f1",
+ "api_key": "sk-ant-secret-should-never-cross",
+ "description": "standing instructions stay in the app",
+ }
+ ]
+ self.panes: list[dict[str, Any]] = [
+ {
+ "workspace_id": "ws_91",
+ "key": "T1",
+ "name": "T1",
+ "history_id": "h_55",
+ "display_name": "Claude Code",
+ "agent": "claude",
+ "title": "Fix the login retry",
+ "status": "live",
+ "activity": "working",
+ "activity_since": 1793612301.0,
+ "worked": True,
+ "cols": 132,
+ "rows": 40,
+ "prompt": "secret prompt text",
+ }
+ ]
+ self.subjects = [
+ {
+ "subject_id": "person",
+ "kind": "person",
+ "level": 14,
+ "xp": 5230,
+ "xp_into_level": 130,
+ "xp_for_next": 600,
+ "title": "Lieutenant",
+ },
+ {
+ "subject_id": "agent:ag_7f1",
+ "kind": "agent",
+ "level": 6,
+ "xp": 400,
+ "xp_into_level": 10,
+ "xp_for_next": 90,
+ "title": "Ensign",
+ },
+ ]
+ self.groups = [
+ {"group_id": "grp_a", "name": "Release crew", "members": ["ag_7f1", "ag_02c"]}
+ ]
+ self.meetings: dict[str, dict] = {"grp_a": {"messages": [], "running": False, "room": None}}
+ self.chats: dict[str, list[dict]] = {
+ "society:ag_7f1": [
+ {"seq": 1, "kind": "user_message", "payload": {"text": "Check the retry window."}},
+ {"seq": 2, "kind": "tool_call", "payload": {"name": "mcp__x__read_file"}},
+ ]
+ }
+ self.actions: list[tuple[str, str]] = []
+ self.created: list[dict] = []
+ self.opened: list[tuple[str | None, str]] = []
+ self.prompts: list[tuple[str, str, str]] = []
+ self.duel: FakeDuelService | None = None
+ self.confirm = True
+ self.screens: dict[str, dict] = {}
+ self.attached: dict[str, Any] = {}
+ self.attach_fails: set[str] = set()
+ self.launch_gate: asyncio.Event | None = None
+ self.pet = {"pet_id": "drone", "look": "drone", "style": "default"}
+
+ async def list_agents(self) -> list[dict[str, Any]]:
+ return [dict(a) for a in self.agents]
+
+ async def list_panes(self) -> list[dict[str, Any]]:
+ return [dict(p) for p in self.panes]
+
+ async def progression(self) -> dict[str, Any]:
+ return {
+ "subjects": [dict(s) for s in self.subjects],
+ "pet_id": "drone",
+ "latest_seq": 902,
+ "ranks": [{"id": "recruit", "level": 1, "tier": "deck"}],
+ "rewards": [],
+ "looks": [],
+ "titles": {"person": [{"level": 1, "title": "Cadet"}]},
+ }
+
+ async def report_action(self, action: str, ref: str) -> dict[str, Any] | None:
+ if action == "bogus":
+ raise UnknownWorldAction(action)
+ self.actions.append((action, ref))
+ return None
+
+ def duel_service(self) -> Any:
+ return self.duel
+
+ async def chat_tail(self, session_id: str, tail: int) -> list[dict[str, Any]] | None:
+ events = self.chats.get(session_id)
+ return None if events is None else events[-tail:]
+
+ async def chat_groups(self) -> list[dict[str, Any]]:
+ return [dict(g) for g in self.groups]
+
+ async def group_meeting(self, group_id: str) -> dict[str, Any] | None:
+ return self.meetings.get(group_id)
+
+ async def meeting_start(self, group_id: str, text: str) -> dict[str, Any]:
+ if group_id not in self.meetings:
+ raise NotFound(group_id)
+ self.meetings[group_id] = {
+ "running": True,
+ "messages": [{"id": "r1", "speaker": "user", "text": text}],
+ "room": {
+ "room_id": "room_44",
+ "phase": "open",
+ "topic": text,
+ "rounds": 0,
+ "max_rounds": 4,
+ },
+ }
+ return self.meetings[group_id]
+
+ async def meeting_stop(self, group_id: str) -> dict[str, Any]:
+ if group_id not in self.meetings:
+ raise NotFound(group_id)
+ self.meetings[group_id]["running"] = False
+ return self.meetings[group_id]
+
+ async def confirm_dangerous(self, action: str, detail: str) -> bool:
+ return self.confirm
+
+ async def create_agent(self, fields: dict[str, Any]) -> str:
+ self.created.append(fields)
+ return f"ag_new{len(self.created)}"
+
+ async def ide_state(self) -> dict[str, Any]:
+ return {"active_id": "ws_91", "workspaces": [{"id": "ws_91", "name": "dodaios"}]}
+
+ async def ide_agents(self) -> list[dict[str, Any]]:
+ return [
+ {"name": "claude", "display_name": "Claude Code", "installed": True},
+ {"name": "shell", "kind": "shell", "installed": True},
+ ]
+
+ async def open_terminal(self, workspace_id: str | None, agent: str) -> tuple[str, str]:
+ if self.launch_gate is not None:
+ await self.launch_gate.wait()
+ ws = workspace_id or "ws_91"
+ name = f"T{len(self.panes) + 1}"
+ self.opened.append((ws, name))
+ self.panes.append(
+ {
+ "workspace_id": ws,
+ "key": name,
+ "name": name,
+ "status": "live",
+ "activity": "starting",
+ "agent": agent,
+ }
+ )
+ return ws, name
+
+ async def start_terminal(self, name: str, workspace_id: str) -> None:
+ return None
+
+ async def prompt_terminal(self, name: str, text: str, workspace_id: str) -> bool | None:
+ self.prompts.append((workspace_id, name, text))
+ return True
+
+ async def active_pet(self) -> dict[str, Any]:
+ return dict(self.pet)
+
+ async def attach_screen(self, pane_id: str, on_output: Any, on_exit: Any) -> tuple[int, int]:
+ if pane_id in self.attach_fails or not any(
+ f"{p['workspace_id']}:{p['key']}" == pane_id for p in self.panes
+ ):
+ raise NotFound(pane_id)
+ self.attached[pane_id] = (on_output, on_exit)
+ return (80, 24)
+
+ def detach_screen(self, pane_id: str, on_output: Any) -> None:
+ self.attached.pop(pane_id, None)
+
+ def plain_screen(self, pane_id: str) -> dict[str, Any] | None:
+ return self.screens.get(pane_id)
+
+
+class MemoryTransport:
+ """One side of an in-memory WebSocket: the test plays Verse."""
+
+ def __init__(self) -> None:
+ self.inbox: asyncio.Queue[str | bytes | None] = asyncio.Queue()
+ self.sent: list[str | bytes] = []
+ self.closed_with: tuple[int, str] | None = None
+ self._new = asyncio.Event()
+
+ # --- server side (Transport protocol)
+ async def receive(self) -> str | bytes:
+ item = await self.inbox.get()
+ if item is None:
+ raise TransportClosed()
+ return item
+
+ async def send_text(self, text: str) -> None:
+ if self.closed_with is not None:
+ raise TransportClosed()
+ self.sent.append(text)
+ self._new.set()
+
+ async def send_bytes(self, data: bytes) -> None:
+ if self.closed_with is not None:
+ raise TransportClosed()
+ self.sent.append(data)
+ self._new.set()
+
+ async def close(self, code: int, reason: str = "") -> None:
+ if self.closed_with is None:
+ self.closed_with = (code, reason)
+ await self.inbox.put(None)
+ self._new.set()
+
+ # --- Verse side
+ def push(self, frame: dict | str | bytes) -> None:
+ self.inbox.put_nowait(json.dumps(frame) if isinstance(frame, dict) else frame)
+
+ def frames(self) -> list[dict]:
+ return [json.loads(f) for f in self.sent if isinstance(f, str)]
+
+ def binary(self) -> list[bytes]:
+ return [f for f in self.sent if isinstance(f, bytes)]
+
+ def of_type(self, type_: str) -> list[dict]:
+ return [f for f in self.frames() if f["type"] == type_]
+
+ async def wait_for(self, pred: Any, within: float = 3.0) -> Any:
+ loop = asyncio.get_running_loop()
+ end = loop.time() + within
+ while True:
+ for f in self.frames():
+ if pred(f):
+ return f
+ left = end - loop.time()
+ if left <= 0:
+ raise AssertionError(f"no matching frame; got {[f['type'] for f in self.frames()]}")
+ self._new.clear()
+ try:
+ await asyncio.wait_for(self._new.wait(), left)
+ except TimeoutError:
+ pass
+
+ async def reply_to(self, rid: str, within: float = 3.0) -> dict:
+ return await self.wait_for(lambda f: f["type"] == "reply" and f.get("re") == rid, within)
+
+
+def hello(token: str = TOKEN, **extra: Any) -> dict:
+ data = {
+ "token": token,
+ "protocols": ["verse.bridge/1"],
+ "build": {
+ "version": "0.1.0",
+ "changelist": "a1b2c3d",
+ "config": "Shipping",
+ "platform": "Win64",
+ },
+ "pid": 23144,
+ "last_seq": 0,
+ "encodings": {"screens": ["cells.bin/1", "cells.json/1"]},
+ "capabilities": {"panel_stream": True, "duel": True},
+ }
+ data.update(extra)
+ return {"type": "hello", "ts": 1.0, "data": data}
+
+
+def make_host(tmp_path: Path, backend: FakeBackend | None = None, **kwargs: Any):
+ from dodaios.verse_host.host import VerseHost
+ from dodaios.verse_host.settings_store import SettingsStore
+
+ class _App:
+ class state: # noqa: N801
+ config = None
+
+ backend = backend or FakeBackend()
+ host = VerseHost(
+ _App(),
+ backend=backend,
+ store=SettingsStore(tmp_path / "settings.json"),
+ data_dir=tmp_path,
+ app_version="4.1.1",
+ **kwargs,
+ )
+ host.tokens.set("launch", TOKEN)
+ return host, backend
+
+
+async def connect(host: Any, *, peer: str = "127.0.0.1", **hello_extra: Any):
+ """Start a session; returns ``(transport, serve_task)`` after ``welcome``."""
+ t = MemoryTransport()
+ t.push(hello(**hello_extra))
+ task = asyncio.ensure_future(host.hub.serve(t, peer))
+ await t.wait_for(lambda f: f["type"] == "welcome")
+ return t, task
+
+
+async def close(t: MemoryTransport, task: asyncio.Task) -> None:
+ t.inbox.put_nowait(None)
+ await asyncio.wait_for(task, 5)
diff --git a/tests/unit/verse_host/parity/duty_cases.json b/tests/unit/verse_host/parity/duty_cases.json
new file mode 100644
index 0000000000..6bda9793db
--- /dev/null
+++ b/tests/unit/verse_host/parity/duty_cases.json
@@ -0,0 +1,1183 @@
+{
+ "agents": [
+ {
+ "state": "paused",
+ "lifecycle": "active",
+ "asking": false,
+ "error": false,
+ "duty": "paused"
+ },
+ {
+ "state": "paused",
+ "lifecycle": "active",
+ "asking": false,
+ "error": true,
+ "duty": "paused"
+ },
+ {
+ "state": "paused",
+ "lifecycle": "active",
+ "asking": true,
+ "error": false,
+ "duty": "paused"
+ },
+ {
+ "state": "paused",
+ "lifecycle": "active",
+ "asking": true,
+ "error": true,
+ "duty": "paused"
+ },
+ {
+ "state": "paused",
+ "lifecycle": "paused",
+ "asking": false,
+ "error": false,
+ "duty": "paused"
+ },
+ {
+ "state": "paused",
+ "lifecycle": "paused",
+ "asking": false,
+ "error": true,
+ "duty": "paused"
+ },
+ {
+ "state": "paused",
+ "lifecycle": "paused",
+ "asking": true,
+ "error": false,
+ "duty": "paused"
+ },
+ {
+ "state": "paused",
+ "lifecycle": "paused",
+ "asking": true,
+ "error": true,
+ "duty": "paused"
+ },
+ {
+ "state": "paused",
+ "lifecycle": null,
+ "asking": false,
+ "error": false,
+ "duty": "paused"
+ },
+ {
+ "state": "paused",
+ "lifecycle": null,
+ "asking": false,
+ "error": true,
+ "duty": "paused"
+ },
+ {
+ "state": "paused",
+ "lifecycle": null,
+ "asking": true,
+ "error": false,
+ "duty": "paused"
+ },
+ {
+ "state": "paused",
+ "lifecycle": null,
+ "asking": true,
+ "error": true,
+ "duty": "paused"
+ },
+ {
+ "state": "waiting",
+ "lifecycle": "active",
+ "asking": false,
+ "error": false,
+ "duty": "waiting"
+ },
+ {
+ "state": "waiting",
+ "lifecycle": "active",
+ "asking": false,
+ "error": true,
+ "duty": "waiting"
+ },
+ {
+ "state": "waiting",
+ "lifecycle": "active",
+ "asking": true,
+ "error": false,
+ "duty": "waiting"
+ },
+ {
+ "state": "waiting",
+ "lifecycle": "active",
+ "asking": true,
+ "error": true,
+ "duty": "waiting"
+ },
+ {
+ "state": "waiting",
+ "lifecycle": "paused",
+ "asking": false,
+ "error": false,
+ "duty": "paused"
+ },
+ {
+ "state": "waiting",
+ "lifecycle": "paused",
+ "asking": false,
+ "error": true,
+ "duty": "paused"
+ },
+ {
+ "state": "waiting",
+ "lifecycle": "paused",
+ "asking": true,
+ "error": false,
+ "duty": "paused"
+ },
+ {
+ "state": "waiting",
+ "lifecycle": "paused",
+ "asking": true,
+ "error": true,
+ "duty": "paused"
+ },
+ {
+ "state": "waiting",
+ "lifecycle": null,
+ "asking": false,
+ "error": false,
+ "duty": "waiting"
+ },
+ {
+ "state": "waiting",
+ "lifecycle": null,
+ "asking": false,
+ "error": true,
+ "duty": "waiting"
+ },
+ {
+ "state": "waiting",
+ "lifecycle": null,
+ "asking": true,
+ "error": false,
+ "duty": "waiting"
+ },
+ {
+ "state": "waiting",
+ "lifecycle": null,
+ "asking": true,
+ "error": true,
+ "duty": "waiting"
+ },
+ {
+ "state": "working",
+ "lifecycle": "active",
+ "asking": false,
+ "error": false,
+ "duty": "working"
+ },
+ {
+ "state": "working",
+ "lifecycle": "active",
+ "asking": false,
+ "error": true,
+ "duty": "working"
+ },
+ {
+ "state": "working",
+ "lifecycle": "active",
+ "asking": true,
+ "error": false,
+ "duty": "waiting"
+ },
+ {
+ "state": "working",
+ "lifecycle": "active",
+ "asking": true,
+ "error": true,
+ "duty": "waiting"
+ },
+ {
+ "state": "working",
+ "lifecycle": "paused",
+ "asking": false,
+ "error": false,
+ "duty": "paused"
+ },
+ {
+ "state": "working",
+ "lifecycle": "paused",
+ "asking": false,
+ "error": true,
+ "duty": "paused"
+ },
+ {
+ "state": "working",
+ "lifecycle": "paused",
+ "asking": true,
+ "error": false,
+ "duty": "paused"
+ },
+ {
+ "state": "working",
+ "lifecycle": "paused",
+ "asking": true,
+ "error": true,
+ "duty": "paused"
+ },
+ {
+ "state": "working",
+ "lifecycle": null,
+ "asking": false,
+ "error": false,
+ "duty": "working"
+ },
+ {
+ "state": "working",
+ "lifecycle": null,
+ "asking": false,
+ "error": true,
+ "duty": "working"
+ },
+ {
+ "state": "working",
+ "lifecycle": null,
+ "asking": true,
+ "error": false,
+ "duty": "waiting"
+ },
+ {
+ "state": "working",
+ "lifecycle": null,
+ "asking": true,
+ "error": true,
+ "duty": "waiting"
+ },
+ {
+ "state": "idle",
+ "lifecycle": "active",
+ "asking": false,
+ "error": false,
+ "duty": "idle"
+ },
+ {
+ "state": "idle",
+ "lifecycle": "active",
+ "asking": false,
+ "error": true,
+ "duty": "error"
+ },
+ {
+ "state": "idle",
+ "lifecycle": "active",
+ "asking": true,
+ "error": false,
+ "duty": "waiting"
+ },
+ {
+ "state": "idle",
+ "lifecycle": "active",
+ "asking": true,
+ "error": true,
+ "duty": "waiting"
+ },
+ {
+ "state": "idle",
+ "lifecycle": "paused",
+ "asking": false,
+ "error": false,
+ "duty": "paused"
+ },
+ {
+ "state": "idle",
+ "lifecycle": "paused",
+ "asking": false,
+ "error": true,
+ "duty": "paused"
+ },
+ {
+ "state": "idle",
+ "lifecycle": "paused",
+ "asking": true,
+ "error": false,
+ "duty": "paused"
+ },
+ {
+ "state": "idle",
+ "lifecycle": "paused",
+ "asking": true,
+ "error": true,
+ "duty": "paused"
+ },
+ {
+ "state": "idle",
+ "lifecycle": null,
+ "asking": false,
+ "error": false,
+ "duty": "idle"
+ },
+ {
+ "state": "idle",
+ "lifecycle": null,
+ "asking": false,
+ "error": true,
+ "duty": "error"
+ },
+ {
+ "state": "idle",
+ "lifecycle": null,
+ "asking": true,
+ "error": false,
+ "duty": "waiting"
+ },
+ {
+ "state": "idle",
+ "lifecycle": null,
+ "asking": true,
+ "error": true,
+ "duty": "waiting"
+ }
+ ],
+ "panes": [
+ {
+ "pane": {
+ "status": "pending",
+ "activity": "starting",
+ "worked": false
+ },
+ "dot": "working",
+ "state_key": "starting",
+ "duty": "working"
+ },
+ {
+ "pane": {
+ "status": "pending",
+ "activity": "starting",
+ "worked": true
+ },
+ "dot": "working",
+ "state_key": "starting",
+ "duty": "working"
+ },
+ {
+ "pane": {
+ "status": "pending",
+ "activity": "working",
+ "worked": false
+ },
+ "dot": "working",
+ "state_key": "starting",
+ "duty": "working"
+ },
+ {
+ "pane": {
+ "status": "pending",
+ "activity": "working",
+ "worked": true
+ },
+ "dot": "working",
+ "state_key": "starting",
+ "duty": "working"
+ },
+ {
+ "pane": {
+ "status": "pending",
+ "activity": "waiting",
+ "worked": false
+ },
+ "dot": "working",
+ "state_key": "starting",
+ "duty": "working"
+ },
+ {
+ "pane": {
+ "status": "pending",
+ "activity": "waiting",
+ "worked": true
+ },
+ "dot": "working",
+ "state_key": "starting",
+ "duty": "working"
+ },
+ {
+ "pane": {
+ "status": "pending",
+ "activity": "asking",
+ "worked": false
+ },
+ "dot": "waiting",
+ "state_key": "needs_input",
+ "duty": "waiting"
+ },
+ {
+ "pane": {
+ "status": "pending",
+ "activity": "asking",
+ "worked": true
+ },
+ "dot": "waiting",
+ "state_key": "needs_input",
+ "duty": "waiting"
+ },
+ {
+ "pane": {
+ "status": "pending",
+ "activity": "failed",
+ "worked": false
+ },
+ "dot": "error",
+ "state_key": "failed",
+ "duty": "error"
+ },
+ {
+ "pane": {
+ "status": "pending",
+ "activity": "failed",
+ "worked": true
+ },
+ "dot": "error",
+ "state_key": "failed",
+ "duty": "error"
+ },
+ {
+ "pane": {
+ "status": "pending",
+ "activity": "exited",
+ "worked": false
+ },
+ "dot": "working",
+ "state_key": "starting",
+ "duty": "working"
+ },
+ {
+ "pane": {
+ "status": "pending",
+ "activity": "exited",
+ "worked": true
+ },
+ "dot": "working",
+ "state_key": "starting",
+ "duty": "working"
+ },
+ {
+ "pane": {
+ "status": "pending",
+ "activity": "stopped",
+ "worked": false
+ },
+ "dot": "working",
+ "state_key": "stopped",
+ "duty": "paused"
+ },
+ {
+ "pane": {
+ "status": "pending",
+ "activity": "stopped",
+ "worked": true
+ },
+ "dot": "working",
+ "state_key": "stopped",
+ "duty": "paused"
+ },
+ {
+ "pane": {
+ "status": "pending",
+ "activity": "unknown",
+ "worked": false
+ },
+ "dot": "working",
+ "state_key": "unknown",
+ "duty": "working"
+ },
+ {
+ "pane": {
+ "status": "pending",
+ "activity": "unknown",
+ "worked": true
+ },
+ "dot": "working",
+ "state_key": "unknown",
+ "duty": "working"
+ },
+ {
+ "pane": {
+ "status": "pending",
+ "activity": "",
+ "worked": false
+ },
+ "dot": "working",
+ "state_key": "starting",
+ "duty": "working"
+ },
+ {
+ "pane": {
+ "status": "pending",
+ "activity": "",
+ "worked": true
+ },
+ "dot": "working",
+ "state_key": "starting",
+ "duty": "working"
+ },
+ {
+ "pane": {
+ "status": "live",
+ "activity": "starting",
+ "worked": false
+ },
+ "dot": "working",
+ "state_key": "starting",
+ "duty": "working"
+ },
+ {
+ "pane": {
+ "status": "live",
+ "activity": "starting",
+ "worked": true
+ },
+ "dot": "working",
+ "state_key": "starting",
+ "duty": "working"
+ },
+ {
+ "pane": {
+ "status": "live",
+ "activity": "working",
+ "worked": false
+ },
+ "dot": "working",
+ "state_key": "working",
+ "duty": "working"
+ },
+ {
+ "pane": {
+ "status": "live",
+ "activity": "working",
+ "worked": true
+ },
+ "dot": "working",
+ "state_key": "working",
+ "duty": "working"
+ },
+ {
+ "pane": {
+ "status": "live",
+ "activity": "waiting",
+ "worked": false
+ },
+ "dot": "idle",
+ "state_key": "idle",
+ "duty": "idle"
+ },
+ {
+ "pane": {
+ "status": "live",
+ "activity": "waiting",
+ "worked": true
+ },
+ "dot": "idle",
+ "state_key": "done",
+ "duty": "idle"
+ },
+ {
+ "pane": {
+ "status": "live",
+ "activity": "asking",
+ "worked": false
+ },
+ "dot": "waiting",
+ "state_key": "needs_input",
+ "duty": "waiting"
+ },
+ {
+ "pane": {
+ "status": "live",
+ "activity": "asking",
+ "worked": true
+ },
+ "dot": "waiting",
+ "state_key": "needs_input",
+ "duty": "waiting"
+ },
+ {
+ "pane": {
+ "status": "live",
+ "activity": "failed",
+ "worked": false
+ },
+ "dot": "error",
+ "state_key": "failed",
+ "duty": "error"
+ },
+ {
+ "pane": {
+ "status": "live",
+ "activity": "failed",
+ "worked": true
+ },
+ "dot": "error",
+ "state_key": "failed",
+ "duty": "error"
+ },
+ {
+ "pane": {
+ "status": "live",
+ "activity": "exited",
+ "worked": false
+ },
+ "dot": "idle",
+ "state_key": "idle",
+ "duty": "idle"
+ },
+ {
+ "pane": {
+ "status": "live",
+ "activity": "exited",
+ "worked": true
+ },
+ "dot": "idle",
+ "state_key": "done",
+ "duty": "idle"
+ },
+ {
+ "pane": {
+ "status": "live",
+ "activity": "stopped",
+ "worked": false
+ },
+ "dot": "idle",
+ "state_key": "stopped",
+ "duty": "paused"
+ },
+ {
+ "pane": {
+ "status": "live",
+ "activity": "stopped",
+ "worked": true
+ },
+ "dot": "idle",
+ "state_key": "stopped",
+ "duty": "paused"
+ },
+ {
+ "pane": {
+ "status": "live",
+ "activity": "unknown",
+ "worked": false
+ },
+ "dot": "idle",
+ "state_key": "unknown",
+ "duty": "idle"
+ },
+ {
+ "pane": {
+ "status": "live",
+ "activity": "unknown",
+ "worked": true
+ },
+ "dot": "idle",
+ "state_key": "unknown",
+ "duty": "idle"
+ },
+ {
+ "pane": {
+ "status": "live",
+ "activity": "",
+ "worked": false
+ },
+ "dot": "idle",
+ "state_key": "idle",
+ "duty": "idle"
+ },
+ {
+ "pane": {
+ "status": "live",
+ "activity": "",
+ "worked": true
+ },
+ "dot": "idle",
+ "state_key": "done",
+ "duty": "idle"
+ },
+ {
+ "pane": {
+ "status": "exited",
+ "activity": "starting",
+ "worked": false
+ },
+ "dot": "working",
+ "state_key": "starting",
+ "duty": "working"
+ },
+ {
+ "pane": {
+ "status": "exited",
+ "activity": "starting",
+ "worked": true
+ },
+ "dot": "working",
+ "state_key": "starting",
+ "duty": "working"
+ },
+ {
+ "pane": {
+ "status": "exited",
+ "activity": "working",
+ "worked": false
+ },
+ "dot": "working",
+ "state_key": "working",
+ "duty": "working"
+ },
+ {
+ "pane": {
+ "status": "exited",
+ "activity": "working",
+ "worked": true
+ },
+ "dot": "working",
+ "state_key": "working",
+ "duty": "working"
+ },
+ {
+ "pane": {
+ "status": "exited",
+ "activity": "waiting",
+ "worked": false
+ },
+ "dot": "idle",
+ "state_key": "exited",
+ "duty": "idle"
+ },
+ {
+ "pane": {
+ "status": "exited",
+ "activity": "waiting",
+ "worked": true
+ },
+ "dot": "idle",
+ "state_key": "exited",
+ "duty": "idle"
+ },
+ {
+ "pane": {
+ "status": "exited",
+ "activity": "asking",
+ "worked": false
+ },
+ "dot": "waiting",
+ "state_key": "needs_input",
+ "duty": "waiting"
+ },
+ {
+ "pane": {
+ "status": "exited",
+ "activity": "asking",
+ "worked": true
+ },
+ "dot": "waiting",
+ "state_key": "needs_input",
+ "duty": "waiting"
+ },
+ {
+ "pane": {
+ "status": "exited",
+ "activity": "failed",
+ "worked": false
+ },
+ "dot": "error",
+ "state_key": "failed",
+ "duty": "error"
+ },
+ {
+ "pane": {
+ "status": "exited",
+ "activity": "failed",
+ "worked": true
+ },
+ "dot": "error",
+ "state_key": "failed",
+ "duty": "error"
+ },
+ {
+ "pane": {
+ "status": "exited",
+ "activity": "exited",
+ "worked": false
+ },
+ "dot": "idle",
+ "state_key": "exited",
+ "duty": "idle"
+ },
+ {
+ "pane": {
+ "status": "exited",
+ "activity": "exited",
+ "worked": true
+ },
+ "dot": "idle",
+ "state_key": "exited",
+ "duty": "idle"
+ },
+ {
+ "pane": {
+ "status": "exited",
+ "activity": "stopped",
+ "worked": false
+ },
+ "dot": "idle",
+ "state_key": "stopped",
+ "duty": "paused"
+ },
+ {
+ "pane": {
+ "status": "exited",
+ "activity": "stopped",
+ "worked": true
+ },
+ "dot": "idle",
+ "state_key": "stopped",
+ "duty": "paused"
+ },
+ {
+ "pane": {
+ "status": "exited",
+ "activity": "unknown",
+ "worked": false
+ },
+ "dot": "idle",
+ "state_key": "unknown",
+ "duty": "idle"
+ },
+ {
+ "pane": {
+ "status": "exited",
+ "activity": "unknown",
+ "worked": true
+ },
+ "dot": "idle",
+ "state_key": "unknown",
+ "duty": "idle"
+ },
+ {
+ "pane": {
+ "status": "exited",
+ "activity": "",
+ "worked": false
+ },
+ "dot": "idle",
+ "state_key": "exited",
+ "duty": "idle"
+ },
+ {
+ "pane": {
+ "status": "exited",
+ "activity": "",
+ "worked": true
+ },
+ "dot": "idle",
+ "state_key": "exited",
+ "duty": "idle"
+ },
+ {
+ "pane": {
+ "status": "error",
+ "activity": "starting",
+ "worked": false
+ },
+ "dot": "error",
+ "state_key": "error",
+ "duty": "error"
+ },
+ {
+ "pane": {
+ "status": "error",
+ "activity": "starting",
+ "worked": true
+ },
+ "dot": "error",
+ "state_key": "error",
+ "duty": "error"
+ },
+ {
+ "pane": {
+ "status": "error",
+ "activity": "working",
+ "worked": false
+ },
+ "dot": "error",
+ "state_key": "error",
+ "duty": "error"
+ },
+ {
+ "pane": {
+ "status": "error",
+ "activity": "working",
+ "worked": true
+ },
+ "dot": "error",
+ "state_key": "error",
+ "duty": "error"
+ },
+ {
+ "pane": {
+ "status": "error",
+ "activity": "waiting",
+ "worked": false
+ },
+ "dot": "error",
+ "state_key": "error",
+ "duty": "error"
+ },
+ {
+ "pane": {
+ "status": "error",
+ "activity": "waiting",
+ "worked": true
+ },
+ "dot": "error",
+ "state_key": "error",
+ "duty": "error"
+ },
+ {
+ "pane": {
+ "status": "error",
+ "activity": "asking",
+ "worked": false
+ },
+ "dot": "error",
+ "state_key": "error",
+ "duty": "error"
+ },
+ {
+ "pane": {
+ "status": "error",
+ "activity": "asking",
+ "worked": true
+ },
+ "dot": "error",
+ "state_key": "error",
+ "duty": "error"
+ },
+ {
+ "pane": {
+ "status": "error",
+ "activity": "failed",
+ "worked": false
+ },
+ "dot": "error",
+ "state_key": "failed",
+ "duty": "error"
+ },
+ {
+ "pane": {
+ "status": "error",
+ "activity": "failed",
+ "worked": true
+ },
+ "dot": "error",
+ "state_key": "failed",
+ "duty": "error"
+ },
+ {
+ "pane": {
+ "status": "error",
+ "activity": "exited",
+ "worked": false
+ },
+ "dot": "error",
+ "state_key": "error",
+ "duty": "error"
+ },
+ {
+ "pane": {
+ "status": "error",
+ "activity": "exited",
+ "worked": true
+ },
+ "dot": "error",
+ "state_key": "error",
+ "duty": "error"
+ },
+ {
+ "pane": {
+ "status": "error",
+ "activity": "stopped",
+ "worked": false
+ },
+ "dot": "error",
+ "state_key": "stopped",
+ "duty": "paused"
+ },
+ {
+ "pane": {
+ "status": "error",
+ "activity": "stopped",
+ "worked": true
+ },
+ "dot": "error",
+ "state_key": "stopped",
+ "duty": "paused"
+ },
+ {
+ "pane": {
+ "status": "error",
+ "activity": "unknown",
+ "worked": false
+ },
+ "dot": "error",
+ "state_key": "unknown",
+ "duty": "error"
+ },
+ {
+ "pane": {
+ "status": "error",
+ "activity": "unknown",
+ "worked": true
+ },
+ "dot": "error",
+ "state_key": "unknown",
+ "duty": "error"
+ },
+ {
+ "pane": {
+ "status": "error",
+ "activity": "",
+ "worked": false
+ },
+ "dot": "error",
+ "state_key": "error",
+ "duty": "error"
+ },
+ {
+ "pane": {
+ "status": "error",
+ "activity": "",
+ "worked": true
+ },
+ "dot": "error",
+ "state_key": "error",
+ "duty": "error"
+ }
+ ],
+ "chat": [
+ {
+ "events": [
+ {
+ "seq": 1,
+ "kind": "user_message",
+ "payload": {
+ "text": "Check the\nretry window."
+ }
+ },
+ {
+ "seq": 2,
+ "kind": "agent_message",
+ "payload": {
+ "text": "From the person",
+ "sender_kind": "user"
+ }
+ },
+ {
+ "seq": 3,
+ "kind": "agent_message",
+ "payload": {
+ "text": "Agent reply"
+ }
+ },
+ {
+ "seq": 4,
+ "kind": "assistant_text",
+ "payload": {
+ "text": "Thinking out loud"
+ }
+ },
+ {
+ "seq": 5,
+ "kind": "tool_call",
+ "payload": {
+ "name": "mcp__dodaios__society_shell"
+ }
+ },
+ {
+ "seq": 6,
+ "kind": "tool_call",
+ "payload": {
+ "name": "x",
+ "summary": "Read login.py"
+ }
+ },
+ {
+ "seq": 7,
+ "kind": "tool_call",
+ "payload": {}
+ },
+ {
+ "seq": 8,
+ "kind": "notice",
+ "payload": {
+ "summary": "Compacted"
+ }
+ },
+ {
+ "seq": 9,
+ "kind": "error",
+ "payload": {
+ "message": "Rate limit"
+ }
+ },
+ {
+ "seq": 10,
+ "kind": "thinking",
+ "payload": {
+ "text": "ignored"
+ }
+ },
+ {
+ "seq": 11,
+ "kind": "assistant_text",
+ "payload": {
+ "text": " "
+ }
+ }
+ ],
+ "lines": [
+ {
+ "kind": "user",
+ "text": "Check the retry window."
+ },
+ {
+ "kind": "user",
+ "text": "From the person"
+ },
+ {
+ "kind": "agent",
+ "text": "Agent reply"
+ },
+ {
+ "kind": "agent",
+ "text": "Thinking out loud"
+ },
+ {
+ "kind": "tool",
+ "text": "society_shell"
+ },
+ {
+ "kind": "tool",
+ "text": "Read login.py"
+ },
+ {
+ "kind": "tool",
+ "text": "tool"
+ },
+ {
+ "kind": "notice",
+ "text": "Compacted"
+ },
+ {
+ "kind": "error",
+ "text": "Rate limit"
+ }
+ ]
+ }
+ ]
+}
diff --git a/tests/unit/verse_host/test_app_lifecycle.py b/tests/unit/verse_host/test_app_lifecycle.py
new file mode 100644
index 0000000000..feeff8d8c4
--- /dev/null
+++ b/tests/unit/verse_host/test_app_lifecycle.py
@@ -0,0 +1,120 @@
+"""App start/stop of the verse host, the bridge port, and the probe off the event loop.
+
+Contract 1 (Dev discovery: written at start with the flag on, deleted on
+shutdown), contract 12 (``lifecycle.quit {reason: app_quit}`` on app quit).
+"""
+
+from __future__ import annotations
+
+import subprocess
+import time
+from pathlib import Path
+
+import httpx
+from fastapi import FastAPI
+
+from dodaios.ui.web import verse_routes
+from dodaios.verse_host import probe
+from tests.unit.verse_host._support import close, connect, make_host
+from tests.unit.verse_host.test_supervisor import Clock, _settle, _supervisor
+
+
+def _app(host) -> FastAPI:
+ app = FastAPI()
+ app.include_router(verse_routes.router)
+ app.state.verse_host = host
+ return app
+
+
+async def test_bridge_port_comes_from_the_bound_socket(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setenv("DODAIOS_VERSE_PROBE", "pass")
+ host, _ = make_host(tmp_path)
+ transport = httpx.ASGITransport(app=_app(host))
+ async with httpx.AsyncClient(transport=transport, base_url="http://127.0.0.1:9123") as c:
+ res = await c.get("/api/verse/status", headers={"Host": "evil.example:5555"})
+ assert res.status_code == 200
+ assert host.bridge_url() == "ws://127.0.0.1:9123/api/verse/bridge"
+
+
+async def test_start_renews_dev_discovery_and_stop_removes_it(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setenv("DODAIOS_VERSE_DEV_BRIDGE", "1")
+ host, _ = make_host(tmp_path)
+ app = _app(host)
+ await verse_routes.start_verse_host(app, 8811)
+ path = tmp_path / "verse" / "bridge.json"
+ assert path.is_file()
+ assert '"url": "ws://127.0.0.1:8811/api/verse/bridge"' in path.read_text(encoding="utf-8")
+ token = host.tokens._tokens["dev"]
+ assert host.tokens.check(token)
+ await verse_routes.stop_verse_host(app)
+ assert not path.exists()
+ assert not host.tokens.check(token)
+
+
+async def test_start_without_the_flag_creates_no_host(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setenv("DODAIOS_VERSE_DEV_BRIDGE", "0")
+ app = FastAPI()
+ await verse_routes.start_verse_host(app, 8811)
+ assert getattr(app.state, "verse_host", None) is None
+ await verse_routes.stop_verse_host(app) # nothing to stop
+
+
+async def test_app_quit_asks_verse_to_quit(tmp_path: Path) -> None:
+ clock, spawned = Clock(), []
+ sup = _supervisor(tmp_path, clock, spawned)
+ host, _ = make_host(tmp_path, supervisor=sup)
+ sup._request_quit = host._request_quit
+ await sup.ensure_running()
+ t, task = await connect(host)
+ await verse_routes.stop_verse_host(_app(host))
+ await _settle()
+ quits = t.of_type("lifecycle.quit")
+ assert [q["data"]["reason"] for q in quits] == ["app_quit"]
+ assert spawned[0].killed # it did not exit before the deadline, so it was ended by PID
+ assert sup.state.status == "stopped" and sup.state.crashes == []
+ await close(t, task)
+
+
+def test_a_failed_probe_is_retried_not_final(monkeypatch) -> None:
+ monkeypatch.delenv("DODAIOS_VERSE_PROBE", raising=False)
+ calls = {"n": 0}
+
+ def timeout(*args, **kwargs):
+ calls["n"] += 1
+ raise subprocess.TimeoutExpired("probe", probe.PROBE_TIMEOUT_S)
+
+ monkeypatch.setattr(probe, "_cache", None)
+ monkeypatch.setattr(probe.subprocess, "run", timeout)
+ first = probe.probe_gpu()
+ assert not first.ok and first.failed
+ assert probe.probe_gpu() is first and calls["n"] == 1 # cached briefly
+ monkeypatch.setattr(probe, "_cache_at", time.monotonic() - probe.RETRY_FAILED_S - 1)
+ probe.probe_gpu()
+ assert calls["n"] == 2
+
+
+async def test_install_is_allowed_while_the_probe_has_no_verdict(tmp_path: Path) -> None:
+ host, _ = make_host(tmp_path)
+ host.capability = probe.Capability(
+ "unsupported", None, probe.GpuReport(False, reason="probe failed", failed=True), time.time()
+ )
+ transport = httpx.ASGITransport(app=_app(host))
+ async with httpx.AsyncClient(transport=transport, base_url="http://127.0.0.1") as c:
+ res = await c.post("/api/verse/install")
+ assert res.status_code != 409
+
+
+async def test_async_paths_probe_in_a_thread(tmp_path: Path, monkeypatch) -> None:
+ import threading
+
+ host, _ = make_host(tmp_path)
+ seen: list[bool] = []
+
+ def check(*, refresh: bool = False) -> probe.Capability:
+ seen.append(threading.current_thread() is threading.main_thread())
+ return probe.Capability("not_installed", None, probe.GpuReport(True), time.time())
+
+ monkeypatch.setattr(probe, "check", check)
+ host.capability = None
+ await host.acheck()
+ assert seen == [False]
diff --git a/tests/unit/verse_host/test_bridge_transport.py b/tests/unit/verse_host/test_bridge_transport.py
new file mode 100644
index 0000000000..0d5597cde4
--- /dev/null
+++ b/tests/unit/verse_host/test_bridge_transport.py
@@ -0,0 +1,195 @@
+"""17.2 / A17.2 and A17.3 (link half): the route over a real loopback socket.
+
+Wrong token closes 4401 within 100 ms; no ``hello`` in 5 s closes 4400; a
+non-loopback peer gets 4403; a second client replaces the first (4409); an
+oversized frame closes 1009; the dead link is declared at 5 s within 0.5 s.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import socket
+import time
+from pathlib import Path
+
+import pytest
+import uvicorn
+from fastapi import FastAPI
+from websockets.asyncio.client import connect as ws_connect
+from websockets.exceptions import ConnectionClosed
+
+from dodaios.ui.web import verse_routes
+from dodaios.verse_host import protocol as P
+from tests.unit.verse_host._support import TOKEN, hello, make_host
+
+
+def _free_port() -> int:
+ with socket.socket() as s:
+ s.bind(("127.0.0.1", 0))
+ return s.getsockname()[1]
+
+
+async def server(tmp_path: Path):
+ host, backend = make_host(tmp_path)
+ app = FastAPI()
+ app.include_router(verse_routes.router)
+ app.state.verse_host = host
+ port = _free_port()
+ config = uvicorn.Config(app, host="127.0.0.1", port=port, log_level="warning", lifespan="off")
+ srv = uvicorn.Server(config)
+ task = asyncio.ensure_future(srv.serve())
+ for _ in range(100):
+ if srv.started:
+ break
+ await asyncio.sleep(0.02)
+ yield host, f"ws://127.0.0.1:{port}{P.PATH}"
+ srv.should_exit = True
+ await asyncio.wait_for(task, 10)
+
+
+async def _close_code(ws) -> int:
+ try:
+ while True:
+ await asyncio.wait_for(ws.recv(), 10)
+ except ConnectionClosed as exc:
+ return exc.rcvd.code if exc.rcvd else 1006
+
+
+async def test_wrong_token_closes_4401_within_100ms(server) -> None:
+ _host, url = server
+ async with ws_connect(url) as ws:
+ started = time.perf_counter()
+ await ws.send(json.dumps(hello(token="x" * 43)))
+ code = await _close_code(ws)
+ elapsed = time.perf_counter() - started
+ assert code == 4401
+ assert elapsed < 0.1, elapsed
+
+
+async def test_hello_timeout_is_5s_and_closes_4400(server, monkeypatch) -> None:
+ assert P.HELLO_TIMEOUT_S == 5.0
+ _host, url = server
+ async with ws_connect(url) as ws:
+ started = time.perf_counter()
+ code = await _close_code(ws)
+ elapsed = time.perf_counter() - started
+ assert code == 4400
+ assert 4.9 <= elapsed <= 5.6, elapsed
+
+
+async def test_malformed_and_unsupported_hello(server) -> None:
+ _host, url = server
+ async with ws_connect(url) as ws:
+ await ws.send("not json")
+ assert await _close_code(ws) == 4400
+ async with ws_connect(url) as ws:
+ await ws.send(json.dumps(hello(protocols=["verse.bridge/9"])))
+ try:
+ await asyncio.wait_for(ws.recv(), 5)
+ except ConnectionClosed as exc:
+ assert exc.rcvd.code == 4426
+ assert "verse.bridge/1" in exc.rcvd.reason
+
+
+async def test_second_client_replaces_first(server) -> None:
+ host, url = server
+ async with ws_connect(url) as first:
+ await first.send(json.dumps(hello()))
+ welcome = json.loads(await first.recv())
+ assert welcome["type"] == "welcome" and welcome["seq"] == 1
+ async with ws_connect(url) as second:
+ await second.send(json.dumps(hello()))
+ assert json.loads(await second.recv())["type"] == "welcome"
+ assert await _close_code(first) == 4409
+ await second.send(json.dumps({"type": "ping", "ts": 1.0, "data": {}}))
+ pong = json.loads(await second.recv())
+ assert pong["type"] == "pong" and pong["seq"] == 2
+
+
+async def test_oversized_frame_closes_1009(server) -> None:
+ _host, url = server
+ async with ws_connect(url, max_size=None) as ws:
+ await ws.send(json.dumps(hello()))
+ await ws.recv()
+ await ws.send("x" * (P.MAX_FRAME_BYTES + 10))
+ assert await _close_code(ws) == 1009
+
+
+async def test_dead_link_declared_at_5s(server) -> None:
+ host, url = server
+ declared: list[float] = []
+
+ async def on_hung(_session) -> None:
+ declared.append(time.perf_counter())
+
+ host.hub.on_hung = on_hung
+ async with ws_connect(url) as ws:
+ await ws.send(json.dumps(hello()))
+ await ws.recv()
+ last = time.perf_counter()
+ for _ in range(3):
+ await ws.send(json.dumps({"type": "ping", "ts": 1.0, "data": {}}))
+ await ws.recv()
+ last = time.perf_counter()
+ await asyncio.sleep(1.0)
+ assert declared == []
+ await asyncio.sleep(5.8 - (time.perf_counter() - last))
+ assert declared, "no dead link declared"
+ assert 5.0 <= declared[0] - last <= 5.5, declared[0] - last
+
+
+async def test_non_loopback_peer_gets_4403(tmp_path: Path) -> None:
+ from tests.unit.verse_host._support import MemoryTransport
+
+ host, _ = make_host(tmp_path)
+ for peer in ("192.168.1.20", "10.0.0.5", "testclient", None):
+ t = MemoryTransport()
+ t.push(hello(token=TOKEN))
+ code = await host.hub.serve(t, peer)
+ assert code == 4403 and t.closed_with[0] == 4403
+ assert t.sent == []
+ for peer in ("127.0.0.1", "::1", "::ffff:127.0.0.1"):
+ assert verse_routes_is_loopback(peer)
+
+
+def verse_routes_is_loopback(peer: str) -> bool:
+ from dodaios.verse_host.bridge import is_loopback
+
+ return is_loopback(peer)
+
+
+async def test_signal_route_closes_1013_until_wp20(server) -> None:
+ _host, url = server
+ async with ws_connect(url.replace("/bridge", "/signal")) as ws:
+ assert await _close_code(ws) == 1013
+
+
+def test_outbox_merges_two_queued_deltas_of_one_pane() -> None:
+ from dodaios.verse_host.bridge import Outbox, _Out
+
+ box = Outbox()
+
+ def delta(rows: list[tuple[int, str]], cursor: list[int]) -> _Out:
+ data = {
+ "pane_id": "ws_91:T1",
+ "kind": "delta",
+ "cols": 80,
+ "rows": 24,
+ "cursor": cursor,
+ "style": "styled",
+ "rows_changed": [
+ {"row": r, "runs": [{"col": 0, "text": t}] if t else []} for r, t in rows
+ ],
+ }
+ return _Out("screens.frame", data, key="screens:ws_91:T1", delta=True, ref=1, feed=True)
+
+ box.put(delta([(1, "a"), (2, "old")], [1, 1]))
+ box.put(delta([(2, "new"), (5, "")], [5, 0]))
+ assert len(box) == 1
+ data = box._items[0].data
+ assert [r["row"] for r in data["rows_changed"]] == [1, 2, 5]
+ assert data["rows_changed"][1]["runs"][0]["text"] == "new"
+ assert data["rows_changed"][2]["runs"] == [] # a cleared row survives the merge
+ assert data["cursor"] == [5, 0]
diff --git a/tests/unit/verse_host/test_commands_and_host.py b/tests/unit/verse_host/test_commands_and_host.py
new file mode 100644
index 0000000000..3cae05f541
--- /dev/null
+++ b/tests/unit/verse_host/test_commands_and_host.py
@@ -0,0 +1,337 @@
+"""17.5, 17.7-17.10, A17.6 (host half), A17.8, A17.9: relays, commands and the host."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import re
+import time
+from pathlib import Path
+
+from dodaios.core.events import (
+ PetChanged,
+ ProgressionAwarded,
+ ShowWindowRequested,
+ SocietyResultPosted,
+ VerseOpenRequested,
+ VerseSettingsChanged,
+)
+from dodaios.verse_host import probe
+from tests.unit.verse_host._support import (
+ FakeDuelService,
+ close,
+ connect,
+ make_host,
+ schema,
+)
+
+PROOF = Path(__file__).resolve().parents[3] / "unreal" / "Verse" / "Saved" / "Harness" / "proof"
+
+
+def _cmd(t, type_: str, rid: str, data: dict) -> None:
+ t.push({"type": type_, "id": rid, "ts": 1.0, "data": data})
+
+
+async def test_launcher_single_flight_busy_and_cancel(tmp_path: Path) -> None:
+ host, backend = make_host(tmp_path)
+ backend.launch_gate = asyncio.Event()
+ t, task = await connect(host)
+ _cmd(t, "launcher.start", "c-1", {"agents": [{"agent": "claude", "count": 3}], "brief": "Go."})
+ await asyncio.sleep(0.05)
+ for _ in range(20):
+ if host.launcher.busy:
+ break
+ await asyncio.sleep(0.01)
+ _cmd(t, "launcher.start", "c-2", {"agents": [{"agent": "claude", "count": 1}], "brief": "x"})
+ busy = await t.reply_to("c-2")
+ assert busy["data"]["error"]["code"] == "busy"
+ _cmd(t, "launcher.cancel", "c-3", {})
+ cancel = await t.reply_to("c-3")
+ assert cancel["data"]["result"]["stopped"] == 3
+ backend.launch_gate.set()
+ done = await t.reply_to("c-1")
+ assert done["data"]["ok"] is True
+ assert len(done["data"]["result"]["panes"]) == 1 # cancelled after the first open
+ await close(t, task)
+
+
+async def test_launcher_briefs_each_pane(tmp_path: Path) -> None:
+ host, backend = make_host(tmp_path)
+ t, task = await connect(host)
+ _cmd(
+ t,
+ "launcher.start",
+ "c-1",
+ {
+ "workspace_id": "ws_91",
+ "agents": [{"agent": "claude", "count": 2}],
+ "brief": "Write the tests.",
+ },
+ )
+ reply = await t.reply_to("c-1")
+ panes = reply["data"]["result"]["panes"]
+ assert [p["submitted"] for p in panes] == [True, True]
+ assert [p[2] for p in backend.prompts] == ["Write the tests.", "Write the tests."]
+ _cmd(t, "launcher.start", "c-2", {"agents": [{"agent": "claude", "count": 1}], "brief": ""})
+ limited = await t.reply_to("c-2")
+ assert limited["data"]["error"]["code"] == "rate_limited"
+ await close(t, task)
+
+
+async def test_qa_exec_gate(tmp_path: Path, monkeypatch) -> None:
+ host, _ = make_host(tmp_path)
+ monkeypatch.delenv("DODAIOS_VERSE_QA", raising=False)
+ t, task = await connect(host)
+ _cmd(t, "qa.exec", "c-1", {"command": "Verse.QA.SetDuty", "args": ["ag_7f1", "error"]})
+ assert (await t.reply_to("c-1"))["data"]["error"]["code"] == "unavailable"
+ monkeypatch.setenv("DODAIOS_VERSE_QA", "1")
+ _cmd(t, "subscribe", "c-2", {"topics": ["roster"]})
+ await t.wait_for(lambda f: f["type"] == "roster.snapshot")
+ _cmd(t, "qa.exec", "c-3", {"command": "Verse.QA.SetDuty", "args": ["ag_7f1", "error"]})
+ ok = await t.reply_to("c-3")
+ assert ok["data"]["result"] == {"result": {"agent_id": "ag_7f1", "duty": "error"}}
+ delta = await t.wait_for(lambda f: f["type"] == "roster.delta")
+ assert delta["data"]["upsert"]["agents"][0]["duty"] == "error"
+ await close(t, task)
+
+
+async def test_open_commands_publish_and_raise(tmp_path: Path) -> None:
+ host, backend = make_host(tmp_path)
+ t, task = await connect(host)
+ _cmd(t, "pane.open", "c-1", {"pane_id": "ws_91:T1", "open": "changes"})
+ _cmd(t, "ide.focus_terminal", "c-2", {"pane_id": "ws_91:T1"})
+ _cmd(t, "group.open", "c-3", {"group_id": "gone"})
+ _cmd(t, "pane.open", "c-4", {"pane_id": "ws_91:T9"})
+ for rid in ("c-1", "c-2", "c-3", "c-4"):
+ await t.reply_to(rid)
+ await close(t, task)
+ opens = [e for e in backend.bus.published if isinstance(e, VerseOpenRequested)]
+ assert [(e.target, e.workspace_id, e.name, e.open, e.focus) for e in opens] == [
+ ("pane", "ws_91", "T1", "changes", False),
+ ("pane", "ws_91", "T1", "", True),
+ ]
+ assert sum(isinstance(e, ShowWindowRequested) for e in backend.bus.published) == 2
+ codes = {f["re"]: f["data"].get("error", {}).get("code") for f in t.of_type("reply")}
+ assert codes["c-3"] == "not_found" and codes["c-4"] == "not_found"
+
+
+async def test_settings_set_and_import_once(tmp_path: Path) -> None:
+ host, backend = make_host(tmp_path)
+ t, task = await connect(host)
+ welcome = t.of_type("welcome")[0]["data"]
+ assert welcome["settings"]["return_key"] == "F10"
+ assert welcome["locale"]["strings"].get("verse.ranks.duty.working")
+ _cmd(t, "settings.set", "c-1", {"gore": "reduced", "view": {"fov_first": 90}})
+ reply = await t.reply_to("c-1")
+ assert reply["data"]["result"]["settings"]["gore"] == "reduced"
+ assert reply["data"]["result"]["settings"]["view"]["fov_first"] == 90
+ changed = await t.wait_for(lambda f: f["type"] == "settings.changed")
+ assert changed["data"] == {
+ "gore": "reduced",
+ "view": reply["data"]["result"]["settings"]["view"],
+ }
+ _cmd(t, "settings.set", "c-2", {"colour": "cyan"})
+ assert (await t.reply_to("c-2"))["data"]["error"]["code"] == "bad_request"
+ await close(t, task)
+ assert any(isinstance(e, VerseSettingsChanged) for e in backend.bus.published)
+ values = {
+ "dodaios.verse.view.v1": json.dumps({"fov_first": 70, "sensitivity": 1.5, "bogus": 1}),
+ "dodaios.verse.uniform.v1": "dress",
+ "jarvis.verse.level.sound.v1": "false",
+ "jarvis.verse.levels.seen.v1": "880",
+ "jarvis.office.arcade.asteroids.best": "4200",
+ }
+ first = host.import_browser_settings(values)
+ assert set(first) == set(values)
+ settings = host.store.settings()
+ assert settings["view"]["fov_first"] == 90 # already set by Verse: kept
+ assert settings["view"]["sensitivity"] == 1.5
+ assert settings["uniform"] == "dress" and settings["level_sound"] is False
+ assert host.store.told_seq() == 880
+ assert host.import_browser_settings(values) == []
+
+
+async def test_progression_relay_snapshot_awards_and_duel(tmp_path: Path) -> None:
+ host, backend = make_host(tmp_path)
+ t, task = await connect(host)
+ _cmd(t, "subscribe", "c-1", {"topics": ["progression"]})
+ snap = await t.wait_for(lambda f: f["type"] == "progression.snapshot")
+ assert snap["data"]["told_seq"] == 0 and snap["data"]["latest_seq"] == 902
+ await backend.bus.publish(
+ ProgressionAwarded(
+ seq=903,
+ subject_id="person",
+ subject_kind="person",
+ xp_source="daily_visit",
+ xp=25,
+ total_xp=5255,
+ level=14,
+ previous_level=14,
+ title="Lieutenant",
+ )
+ )
+ award = await t.wait_for(lambda f: f["type"] == "progression.awarded")
+ assert award["data"]["seq"] == 903 and award["data"]["xp_source"] == "daily_visit"
+ _cmd(t, "progression.told", "c-2", {"seq": 903})
+ assert (await t.reply_to("c-2"))["data"]["result"] == {"told_seq": 903}
+ _cmd(t, "progression.action", "c-3", {"action": "duel_won", "ref": ""})
+ assert (await t.reply_to("c-3"))["data"]["error"]["code"] == "bad_request"
+ _cmd(t, "progression.action", "c-4", {"action": "inspection", "ref": "hangar"})
+ assert (await t.reply_to("c-4"))["data"]["result"] == {"awarded": None}
+ assert backend.actions == [("inspection", "hangar")]
+ _cmd(t, "duel.result", "c-5", {"match_id": "m1", "outcome": "won"})
+ assert (await t.reply_to("c-5"))["data"]["error"]["code"] == "unavailable"
+ backend.duel = FakeDuelService()
+ _cmd(t, "duel.result", "c-6", {"match_id": "m1", "outcome": "won"})
+ _cmd(t, "duel.result", "c-7", {"match_id": "m1", "outcome": "won"})
+ first, again = await t.reply_to("c-6"), await t.reply_to("c-7")
+ assert first["data"]["result"]["awards"] == [{"xp_source": "duel_won", "xp": 60}]
+ assert again["data"]["result"]["awards"] == [] and again["data"]["result"]["recorded"]
+ await close(t, task)
+
+
+async def test_roster_error_signal_and_companion_update(tmp_path: Path) -> None:
+ host, backend = make_host(tmp_path)
+ backend.agents[0]["run_state"] = "idle"
+ backend.agents[0]["waiting_reason"] = None
+ t, task = await connect(host)
+ _cmd(t, "subscribe", "c-1", {"topics": ["roster", "companion"]})
+ snap = await t.wait_for(lambda f: f["type"] == "roster.snapshot")
+ agent = snap["data"]["agents"][0]
+ assert agent["duty"] == "idle" and agent["rank"] == "technician" and agent["level"] == 6
+ assert snap["data"]["commander"]["rank"] == "lieutenant"
+ assert snap["data"]["panes"][0]["pane_id"] == "ws_91:T1"
+ assert "api_key" not in json.dumps(snap) and "secret prompt" not in json.dumps(snap)
+ await backend.bus.publish(SocietyResultPosted(agent_id="ag_7f1", status="blocked"))
+ delta = await t.wait_for(lambda f: f["type"] == "roster.delta")
+ assert delta["data"]["upsert"]["agents"] == [{"agent_id": "ag_7f1", "duty": "error"}]
+ await t.wait_for(lambda f: f["type"] == "companion.snapshot")
+ started = time.perf_counter()
+ backend.pet = {"pet_id": "owl", "look": "owl", "style": "default"}
+ await backend.bus.publish(PetChanged(pet_id="owl"))
+ update = await t.wait_for(lambda f: f["type"] == "companion.update")
+ assert update["data"]["pet_id"] == "owl" and time.perf_counter() - started < 2.0
+ await close(t, task)
+
+
+async def test_lifecycle_messages_and_timings(tmp_path: Path) -> None:
+ host, backend = make_host(tmp_path)
+ # A cached "ok" verdict: check() and acheck() then never start the real GPU probe.
+ host.capability = probe.Capability("ok", "Verse.exe", probe.GpuReport(True), time.time())
+ host.supervisor.state.status = "running"
+ host.supervisor.process = type("P", (), {"alive": lambda self: True, "pid": 1})()
+ t, task = await connect(host)
+ t.push({"type": "lifecycle.ready", "ts": 1.0, "data": {"first_frame_ms": 4100}})
+ t.push(
+ {
+ "type": "lifecycle.state",
+ "ts": 1.0,
+ "data": {"state": "visible", "vram_mb": 4300, "fps": 120},
+ }
+ )
+ t.push({"type": "focus.return_to_app", "ts": 1.0, "data": {"reason": "return_key"}})
+ t.push(
+ {
+ "type": "lifecycle.state",
+ "ts": 1.0,
+ "data": {"state": "dormant", "vram_mb": 1800, "fps": 2},
+ }
+ )
+ await asyncio.sleep(0.1)
+ assert host.state == "dormant" and host.visibility == "hidden"
+ assert any(isinstance(e, ShowWindowRequested) for e in backend.bus.published)
+ await host.show("station")
+ show = await t.wait_for(lambda f: f["type"] == "lifecycle.show")
+ assert show["data"]["reason"] == "station"
+ t.push({"type": "lifecycle.state", "ts": 1.0, "data": {"state": "visible"}})
+ await asyncio.sleep(0.05)
+ assert "dormant_to_visible_ms" in host.timings
+ await host.hide("user")
+ await host.gpu_pressure(True, "local_model")
+ await host.panel_visibility(True, 480, 320, 1.5)
+ await t.wait_for(lambda f: f["type"] == "panel.visibility")
+ await host.settings_changed({"lang": "de", "gore": "full"})
+ await t.wait_for(lambda f: f["type"] == "settings.changed")
+ host.supervisor.process = None
+ await close(t, task)
+ sch = schema()
+ for frame in t.frames():
+ assert sch.validate_frame(frame) == [], frame
+ assert [
+ f["type"] for f in t.frames() if f["type"].startswith(("lifecycle.", "gpu.", "panel."))
+ ] == ["lifecycle.show", "lifecycle.hide", "gpu.yield", "panel.visibility"]
+ out = PROOF / "WP17" / "17.12"
+ out.mkdir(parents=True, exist_ok=True)
+ (out / "host_lifecycle_timing.json").write_text(
+ json.dumps({"source": "backend host (simulated Verse frames)", **host.timings}, indent=2)
+ )
+
+
+SECRET = re.compile(
+ r"(sk-[A-Za-z0-9_-]{8,}|sk-ant-|AKIA[0-9A-Z]{16}|ghp_[A-Za-z0-9]{20,}|xox[bp]-|"
+ r"-----BEGIN [A-Z ]*PRIVATE KEY|api[_-]?key|password|secret|bearer\s)",
+ re.IGNORECASE,
+)
+
+
+async def test_no_secrets_cross_the_bridge(tmp_path: Path) -> None:
+ """A17.8: a long busy session's every frame is scanned for key or credential patterns."""
+ host, backend = make_host(tmp_path)
+ backend.agents[0]["provider_key"] = "sk-proj-ABCDEFGHIJKLMNOP"
+ backend.agents[0]["account_id"] = "ghp_ABCDEFGHIJKLMNOPQRSTUV"
+ t, task = await connect(host)
+ _cmd(
+ t,
+ "subscribe",
+ "c-1",
+ {"topics": ["roster", "progression", "groups", "meetings", "companion"]},
+ )
+ _cmd(t, "chat_tails.watch", "c-2", {"agents": ["ag_7f1"]})
+ _cmd(t, "screens.watch", "c-3", {"panes": [{"pane_id": "ws_91:T1", "hz": 10}]})
+ await t.reply_to("c-3")
+ from dodaios.core.events import SocietyMessageSent
+
+ for i in range(200):
+ backend.agents[0]["run_state"] = "working" if i % 2 else "idle"
+ await backend.bus.publish(SocietyMessageSent())
+ await backend.attached["ws_91:T1"][0](f"\x1b[{i % 20 + 1};1Hbuild step {i} ok")
+ await asyncio.sleep(0.005)
+ await asyncio.sleep(0.3)
+ await close(t, task)
+ hits = []
+ for raw in t.sent:
+ text = raw if isinstance(raw, str) else raw.decode("utf-8", "replace")
+ if text.startswith('{"type":"welcome"'):
+ # Locale strings are UI copy (they may say "password" as a word).
+ text = text.split('"locale"')[0]
+ hits += SECRET.findall(text)
+ assert hits == [], hits
+ assert len(t.sent) > 20
+
+
+async def test_qa_exec_server_to_verse(tmp_path: Path, monkeypatch) -> None:
+ """qa.exec S->V: the backend forwards a Verse.QA.* command and returns Verse's reply."""
+ import pytest
+
+ from dodaios.verse_host import protocol as P
+
+ host, _ = make_host(tmp_path)
+ monkeypatch.delenv("DODAIOS_VERSE_QA", raising=False)
+ with pytest.raises(P.BridgeError):
+ await host.qa_exec("Verse.QA.Stats", [])
+ monkeypatch.setenv("DODAIOS_VERSE_QA", "1")
+ t, task = await connect(host)
+ pending = asyncio.ensure_future(host.qa_exec("Verse.QA.Stats", []))
+ sent = await t.wait_for(lambda f: f["type"] == "qa.exec")
+ assert sent["id"].startswith("s-") and sent["data"] == {"command": "Verse.QA.Stats", "args": []}
+ t.push(
+ {
+ "type": "reply",
+ "re": sent["id"],
+ "ts": 1.0,
+ "data": {"ok": True, "result": {"result": {"fps": 120}}},
+ }
+ )
+ answer = await asyncio.wait_for(pending, 3)
+ assert answer["result"]["result"] == {"fps": 120}
+ await close(t, task)
diff --git a/tests/unit/verse_host/test_conformance.py b/tests/unit/verse_host/test_conformance.py
new file mode 100644
index 0000000000..1fabcda5fc
--- /dev/null
+++ b/tests/unit/verse_host/test_conformance.py
@@ -0,0 +1,220 @@
+"""17.1 / A17.1: the backend codec passes every G0.11 golden fixture and scenario.
+
+* every golden message frame parses and re-encodes identically;
+* every ``cells.bin/1`` vector encodes to the exact bytes and decodes back,
+ and every malformed vector is rejected;
+* every golden command request, driven through a live :class:`BridgeHub`
+ session, gets exactly one reply that validates against the schema, with the
+ golden reply's ``ok`` and error code;
+* every frame the backend sends in those sessions validates as golden data;
+* every ``fake_bridge.py`` scenario frame parses with the backend codec.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+
+import pytest
+
+from dodaios.verse_host import cells_codec, protocol
+from tests.unit.verse_host._support import (
+ FIXTURES,
+ FakeBackend,
+ FakeDuelService,
+ close,
+ connect,
+ make_host,
+ schema,
+)
+
+MESSAGES = sorted((FIXTURES / "messages").glob("*.json"))
+REPLIES = sorted((FIXTURES / "replies").glob("*.json"))
+SCENARIOS = sorted((FIXTURES / "scenarios").glob("*.json"))
+VECTORS = json.loads((FIXTURES / "cells" / "vectors.json").read_text(encoding="utf-8"))
+
+
+def _load(path: Path):
+ return json.loads(path.read_text(encoding="utf-8"))
+
+
[email protected]("path", MESSAGES, ids=lambda p: p.stem)
+def test_golden_message_round_trip(path: Path) -> None:
+ for frame in _load(path):
+ text = protocol.encode(frame)
+ parsed = protocol.parse(text)
+ assert parsed.type == frame["type"]
+ assert parsed.data == frame["data"]
+ assert json.loads(protocol.encode(parsed.raw)) == frame
+
+
[email protected]("vector", VECTORS["valid"], ids=lambda v: v["name"])
+def test_cells_vector_encodes_exactly(vector: dict) -> None:
+ frame = vector["frame"]
+ data = frame["data"]
+ blob = cells_codec.encode(data, ref=vector["ref"], seq=frame["seq"], base=frame.get("base"))
+ assert blob.hex() == vector["bin_hex"]
+ decoded = cells_codec.decode(bytes.fromhex(vector["bin_hex"]))
+ assert decoded["kind"] == data["kind"]
+ assert decoded["cols"] == data["cols"] and decoded["rows"] == data["rows"]
+ assert decoded["cursor"] == data["cursor"]
+ assert decoded["seq"] == frame["seq"]
+ expected = [
+ {
+ "row": r["row"],
+ "runs": [
+ {
+ "col": u["col"],
+ "text": u["text"],
+ "fg": u.get("fg"),
+ "bg": u.get("bg"),
+ "attrs": list(u.get("attrs", [])),
+ }
+ for u in r["runs"]
+ ],
+ }
+ for r in data["rows_changed"]
+ ]
+ assert decoded["rows_changed"] == expected
+
+
[email protected]("vector", VECTORS["invalid"], ids=lambda v: v["name"])
+def test_cells_vector_rejected(vector: dict) -> None:
+ with pytest.raises(cells_codec.CellsError):
+ cells_codec.decode(bytes.fromhex(vector["bin_hex"]))
+
+
[email protected]("path", SCENARIOS, ids=lambda p: p.stem)
+def test_scenario_frames_parse(path: Path) -> None:
+ scenario = _load(path)
+ for step in scenario["steps"]:
+ if "frame" in step:
+ frame = dict(step["frame"], seq=2, ts=0.0)
+ parsed = protocol.parse(protocol.encode(frame))
+ assert parsed.type == step["frame"]["type"]
+ if parsed.type == "screens.frame":
+ data = parsed.data
+ blob = cells_codec.encode(
+ data, ref=1, seq=5, base=4 if data["kind"] == "delta" else None
+ )
+ assert cells_codec.decode(blob)["rows_changed"] is not None
+
+
+def _requests() -> list[tuple[str, dict, dict]]:
+ out = []
+ for path in REPLIES:
+ for pair in _load(path):
+ out.append((path.stem, pair["request"], pair["reply"]))
+ return out
+
+
+ "command,request_frame,golden_reply",
+ _requests(),
+ ids=[f"{c}-{r['id']}" for c, r, _ in _requests()],
+)
+async def test_golden_command_gets_one_valid_reply(
+ command: str, request_frame: dict, golden_reply: dict, tmp_path: Path, monkeypatch
+) -> None:
+ backend = FakeBackend()
+ backend.duel = FakeDuelService()
+ backend.panes.append(dict(backend.panes[0], key="T2", name="T2"))
+ backend.agents.append(
+ {"agent_id": "ag_02c", "name": "Ode", "state": "active", "run_state": "idle"}
+ )
+ golden_ok = golden_reply["data"]["ok"]
+ golden_code = None if golden_ok else golden_reply["data"]["error"]["code"]
+ if command == "qa.exec" and golden_ok:
+ monkeypatch.setenv("DODAIOS_VERSE_QA", "1")
+ else:
+ monkeypatch.delenv("DODAIOS_VERSE_QA", raising=False)
+ if command in ("meeting.start", "meeting.stop") and golden_code == "conflict":
+ backend.confirm = False
+ host, _ = make_host(tmp_path, backend)
+ t, task = await connect(host)
+ if golden_code == "busy":
+ backend.launch_gate = asyncio.Event()
+ host.launcher.running = object() # type: ignore[assignment]
+ if golden_code == "rate_limited":
+ limit = t # noqa: F841
+ for i in range(8):
+ t.push(dict(request_frame, id=f"warm-{i}"))
+ await asyncio.sleep(0.05)
+ t.push(request_frame)
+ reply = await t.reply_to(request_frame["id"])
+ if golden_code == "busy":
+ host.launcher.running = None
+ await close(t, task)
+ sch = schema()
+ assert sch.validate_reply(reply, command) == [], reply
+ replies = [f for f in t.frames() if f["type"] == "reply" and f.get("re") == request_frame["id"]]
+ assert len(replies) == 1
+ if golden_code in (
+ "not_found",
+ "bad_request",
+ "unavailable",
+ "busy",
+ "conflict",
+ "rate_limited",
+ ):
+ if command not in ("progression.action",) or golden_code != "not_found":
+ assert reply["data"]["ok"] is False, reply
+ assert reply["data"]["error"]["code"] == golden_code, reply
+ elif golden_ok:
+ assert reply["data"]["ok"] is True, reply
+
+
+async def test_every_sent_frame_is_golden_valid(tmp_path: Path) -> None:
+ backend = FakeBackend()
+ host, _ = make_host(tmp_path, backend)
+ t, task = await connect(host)
+ t.push(
+ {
+ "type": "subscribe",
+ "id": "c-1",
+ "ts": 1.0,
+ "data": {
+ "topics": [
+ "roster",
+ "panes",
+ "progression",
+ "meetings",
+ "groups",
+ "companion",
+ "lifecycle",
+ "panel",
+ ]
+ },
+ }
+ )
+ t.push({"type": "chat_tails.watch", "id": "c-2", "ts": 1.0, "data": {"agents": ["ag_7f1"]}})
+ t.push({"type": "ping", "ts": 1.0, "data": {}})
+ await t.wait_for(lambda f: f["type"] == "roster.snapshot")
+ await t.wait_for(lambda f: f["type"] == "progression.snapshot")
+ await t.wait_for(lambda f: f["type"] == "groups.snapshot")
+ await t.wait_for(lambda f: f["type"] == "companion.snapshot")
+ await t.wait_for(lambda f: f["type"] == "chat_tails.update")
+ await t.wait_for(lambda f: f["type"] == "pong")
+ backend.agents[0]["run_state"] = "working"
+ backend.agents[0]["waiting_reason"] = None
+ from dodaios.core.events import SocietyMessageSent
+
+ await backend.bus.publish(SocietyMessageSent())
+ await t.wait_for(lambda f: f["type"] == "roster.delta", 3.0)
+ await close(t, task)
+ sch = schema()
+ seqs = []
+ for frame in t.frames():
+ errors = sch.validate_frame(frame)
+ assert errors == [], (frame["type"], errors)
+ seqs.append(frame["seq"])
+ assert seqs == sorted(seqs) and len(set(seqs)) == len(seqs)
+ welcome = t.frames()[0]
+ assert welcome["type"] == "welcome" and welcome["seq"] == 1
+ delta = t.of_type("roster.delta")[0]
+ snap = t.of_type("roster.snapshot")[0]
+ assert delta["base"] == snap["seq"]
+ assert delta["data"]["upsert"]["agents"] == [
+ {"agent_id": "ag_7f1", "run_state": "working", "waiting_reason": None, "duty": "working"}
+ ]
diff --git a/tests/unit/verse_host/test_install.py b/tests/unit/verse_host/test_install.py
new file mode 100644
index 0000000000..54f1f18cdc
--- /dev/null
+++ b/tests/unit/verse_host/test_install.py
@@ -0,0 +1,309 @@
+"""17.13 (on-demand download): the install routes and job against a fake installer.
+
+The Verse is never part of the app install (README Delivery). With no Verse
+on disk the host says ``not_installed``; ``POST /api/verse/install`` downloads
+it through WP22's ``dodaios.verse_host.install`` (faked here),
+``GET /api/verse/install/progress`` reports size and progress, ``DELETE``
+cancels a running download or removes the installed Verse.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+
+import httpx
+import pytest
+from fastapi import FastAPI
+
+from dodaios.ui.web import verse_routes
+from dodaios.verse_host import install_port
+from dodaios.verse_host.install_port import (
+ InstallBusy,
+ InstallError,
+ InstallJob,
+ Manifest,
+ SimulatedInstaller,
+ UnavailableInstaller,
+ VerseInstaller,
+ load_installer,
+)
+from tests.unit.verse_host._support import make_host
+
+
+class FakeInstaller:
+ """Implements :class:`VerseInstaller` exactly; the test steps the download."""
+
+ def __init__(self, build_dir: Path, *, size: int = 1000) -> None:
+ self.build_dir = build_dir
+ self.size = size
+ self.published = True
+ self.partial = 0
+ self.gate = asyncio.Event()
+ self.reject: str | None = None
+ self.uninstalls = 0
+
+ @property
+ def exe(self) -> Path:
+ return self.build_dir / "Verse.exe"
+
+ async def manifest(self) -> Manifest | None:
+ return Manifest("5.0.0", self.size, self.size * 2) if self.published else None
+
+ def installed_version(self) -> str | None:
+ return "5.0.0" if self.exe.is_file() else None
+
+ async def install(self, progress) -> None:
+ # Resume from the partial file of an earlier, cancelled run.
+ while self.partial < self.size:
+ progress("downloading", self.partial, self.size)
+ await self.gate.wait()
+ self.gate.clear()
+ self.partial = min(self.size, self.partial + self.size // 4)
+ progress("verifying", self.size, self.size)
+ if self.reject:
+ self.partial = 0
+ raise InstallError(self.reject)
+ progress("installing", self.size, self.size)
+ self.build_dir.mkdir(parents=True, exist_ok=True)
+ self.exe.write_bytes(b"MZ")
+
+ async def uninstall(self) -> None:
+ self.uninstalls += 1
+ if self.exe.is_file():
+ self.exe.unlink()
+ self.partial = 0
+
+
+def gpu_ok(monkeypatch):
+ monkeypatch.setenv("DODAIOS_VERSE_PROBE", "pass")
+ monkeypatch.delenv("DODAIOS_VERSE_FAKE_INSTALL", raising=False)
+
+
+def setup(tmp_path: Path, monkeypatch, gpu_ok):
+ fake = FakeInstaller(tmp_path / "verse" / "build")
+ from dodaios.verse_host import probe
+
+ monkeypatch.setattr(probe, "candidate_executables", lambda: [fake.exe])
+ host, backend = make_host(tmp_path, installer=fake)
+ app = FastAPI()
+ app.include_router(verse_routes.router)
+ app.state.verse_host = host
+ client = httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://127.0.0.1")
+ return host, backend, fake, client
+
+
+async def _until(predicate, limit: float = 3.0) -> None:
+ deadline = asyncio.get_running_loop().time() + limit
+ while not predicate():
+ if asyncio.get_running_loop().time() > deadline:
+ raise AssertionError("condition not reached")
+ await asyncio.sleep(0.01)
+
+
+def test_fake_and_shipped_doubles_implement_the_interface(tmp_path: Path) -> None:
+ for obj in (FakeInstaller(tmp_path), UnavailableInstaller(), SimulatedInstaller()):
+ assert isinstance(obj, VerseInstaller)
+
+
+def test_loader_falls_back_until_wp22_lands(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.delenv("DODAIOS_VERSE_FAKE_INSTALL", raising=False)
+
+ def missing(name: str):
+ raise ImportError(name)
+
+ monkeypatch.setattr(install_port.importlib, "import_module", missing)
+ assert isinstance(load_installer(tmp_path), UnavailableInstaller)
+ monkeypatch.setenv("DODAIOS_VERSE_FAKE_INSTALL", "1")
+ assert isinstance(load_installer(tmp_path), SimulatedInstaller)
+
+
+def test_loader_uses_the_install_package(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.delenv("DODAIOS_VERSE_FAKE_INSTALL", raising=False)
+ fake = FakeInstaller(tmp_path)
+ seen: list[Path] = []
+
+ class Module:
+ @staticmethod
+ def get_installer(data_dir: Path):
+ seen.append(data_dir)
+ return fake
+
+ monkeypatch.setattr(install_port.importlib, "import_module", lambda name: Module)
+ assert load_installer(tmp_path) is fake
+ assert seen == [tmp_path]
+
+
+async def test_fresh_install_is_not_installed_and_shows_the_size(setup) -> None:
+ host, _, fake, client = setup
+ async with client:
+ status = (await client.get("/api/verse/status")).json()
+ assert status["status"] == "not_installed"
+ progress = (await client.get("/api/verse/install/progress")).json()
+ assert progress["state"] == "idle"
+ assert progress["download_bytes"] == fake.size
+ assert progress["install_bytes"] == fake.size * 2
+ assert progress["version"] == "5.0.0"
+ assert progress["installed_version"] is None
+
+
+async def test_download_installs_and_status_becomes_ready(setup) -> None:
+ from dodaios.core.events import VerseStatusChanged
+
+ host, backend, fake, client = setup
+ async with client:
+ started = (await client.post("/api/verse/install")).json()
+ assert started["state"] == "downloading"
+ # A second press joins the running download (single flight).
+ again = (await client.post("/api/verse/install")).json()
+ assert again["state"] == "downloading"
+ for _ in range(4):
+ fake.gate.set()
+ await asyncio.sleep(0.02)
+ await _until(lambda: not host.install.running)
+ progress = (await client.get("/api/verse/install/progress")).json()
+ status = (await client.get("/api/verse/status")).json()
+ assert progress["state"] == "installed"
+ assert progress["done_bytes"] == progress["total_bytes"] == fake.size
+ assert progress["installed_version"] == "5.0.0"
+ assert status["status"] == "stopped"
+ changes = [e for e in backend.bus.published if isinstance(e, VerseStatusChanged)]
+ assert changes and changes[-1].status == "stopped"
+
+
+async def test_cancel_then_resume_keeps_the_partial_download(setup) -> None:
+ host, _, fake, client = setup
+ async with client:
+ await client.post("/api/verse/install")
+ fake.gate.set()
+ await _until(lambda: fake.partial == fake.size // 4)
+ await _until(lambda: host.install._progress.done_bytes == fake.size // 4)
+ mid = (await client.get("/api/verse/install/progress")).json()
+ assert mid["state"] == "downloading" and mid["done_bytes"] == fake.size // 4
+ cancelled = (await client.delete("/api/verse/install")).json()
+ assert cancelled["cancelled"] is True and cancelled["removed"] is False
+ assert cancelled["state"] == "cancelled"
+ assert fake.uninstalls == 0
+ await client.post("/api/verse/install")
+ await _until(lambda: host.install._progress.done_bytes == fake.size // 4)
+ for _ in range(3):
+ fake.gate.set()
+ await asyncio.sleep(0.02)
+ await _until(lambda: not host.install.running)
+ status = (await client.get("/api/verse/status")).json()
+ assert host.install._progress.state == "installed"
+ assert status["status"] == "stopped"
+
+
+async def test_tampered_package_is_rejected(setup) -> None:
+ host, _, fake, client = setup
+ fake.reject = "The Verse package failed its signature check."
+ async with client:
+ await client.post("/api/verse/install")
+ for _ in range(4):
+ fake.gate.set()
+ await asyncio.sleep(0.02)
+ await _until(lambda: not host.install.running)
+ progress = (await client.get("/api/verse/install/progress")).json()
+ status = (await client.get("/api/verse/status")).json()
+ assert progress["state"] == "failed"
+ assert progress["error"] == fake.reject
+ assert status["status"] == "not_installed"
+
+
+async def test_remove_stops_the_verse_and_returns_to_not_installed(setup) -> None:
+ host, _, fake, client = setup
+ fake.build_dir.mkdir(parents=True)
+ fake.exe.write_bytes(b"MZ")
+ host.capability = None
+ stops: list[str] = []
+
+ async def stop(reason: str = "app_quit") -> None:
+ stops.append(reason)
+
+ class Alive:
+ def alive(self) -> bool:
+ return not stops
+
+ host.supervisor.stop = stop # type: ignore[method-assign]
+ host.supervisor.process = Alive() # type: ignore[assignment]
+ async with client:
+ before = (await client.get("/api/verse/install/progress")).json()
+ assert before["installed_version"] == "5.0.0"
+ removed = (await client.delete("/api/verse/install")).json()
+ status = (await client.get("/api/verse/status")).json()
+ assert stops == ["update"]
+ assert removed["removed"] is True and removed["installed_version"] is None
+ assert fake.uninstalls == 1 and not fake.exe.exists()
+ assert status["status"] == "not_installed"
+
+
+async def test_unpublished_package_says_unavailable(setup) -> None:
+ host, _, fake, client = setup
+ fake.published = False
+ async with client:
+ progress = (await client.get("/api/verse/install/progress?refresh=true")).json()
+ started = (await client.post("/api/verse/install")).json()
+ assert progress["state"] == "unavailable" and progress["download_bytes"] is None
+ assert started["state"] == "unavailable" and started["error"]
+ assert not host.install.running
+
+
+async def test_unsupported_gpu_cannot_download(setup, monkeypatch) -> None:
+ host, _, _, client = setup
+ monkeypatch.setenv("DODAIOS_VERSE_PROBE", "fail")
+ host.check(refresh=True)
+ async with client:
+ res = await client.post("/api/verse/install")
+ assert res.status_code == 409
+ assert not host.install.running
+
+
+async def test_job_without_host_reports_each_phase(tmp_path: Path) -> None:
+ fake = FakeInstaller(tmp_path / "build", size=8)
+ changed: list[str] = []
+
+ async def on_change() -> None:
+ changed.append(fake.installed_version() or "none")
+
+ job = InstallJob(fake, on_change=on_change)
+ phases: list[str] = []
+ original = job._report
+
+ def spy(phase, done, total):
+ phases.append(phase)
+ original(phase, done, total)
+
+ job._report = spy # type: ignore[method-assign]
+ await job.start()
+ while job.running:
+ fake.gate.set()
+ await asyncio.sleep(0.01)
+ assert phases[0] == "downloading" and phases[-2:] == ["verifying", "installing"]
+ assert changed == ["5.0.0"]
+ fake.partial = 0
+ await job.start()
+ with pytest.raises(InstallBusy):
+ await job.remove()
+ assert await job.cancel() is True
+ assert await job.cancel() is False
+ assert (await job.remove())["installed_version"] is None
+ assert changed[-1] == "none"
+
+
+def test_switches_are_read_under_the_adopted_spelling(tmp_path: Path, monkeypatch) -> None:
+ """Importing ``dodaios`` renames DODAIOS_* to JARVIS_*; the host must still see them."""
+ from dodaios.verse_host.env import getenv
+ from dodaios.verse_host.relays.commands import qa_enabled
+
+ for name in ("DODAIOS_VERSE_FAKE_INSTALL", "DODAIOS_VERSE_QA"):
+ monkeypatch.delenv(name, raising=False)
+ monkeypatch.setenv("JARVIS_VERSE_FAKE_INSTALL", "1")
+ monkeypatch.setenv("JARVIS_VERSE_QA", "1")
+ assert getenv("DODAIOS_VERSE_FAKE_INSTALL") == "1"
+ assert isinstance(load_installer(tmp_path), SimulatedInstaller)
+ assert qa_enabled()
+ monkeypatch.setenv("DODAIOS_VERSE_QA", "0")
+ assert not qa_enabled()
diff --git a/tests/unit/verse_host/test_ports_and_parity.py b/tests/unit/verse_host/test_ports_and_parity.py
new file mode 100644
index 0000000000..b1db73ff83
--- /dev/null
+++ b/tests/unit/verse_host/test_ports_and_parity.py
@@ -0,0 +1,54 @@
+"""BW3 / BW5 parity: the duty and chat-line ports match the shared parity table.
+
+The same table is asserted against the TypeScript originals by
+``frontend/src/components/verseHost/__tests__/dutyParity.test.ts``.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from dodaios.verse_host.chat_lines import chat_lines, clean
+from dodaios.verse_host.duty import dot_kind_for, duty_of, duty_of_pane, state_key_for
+
+CASES = json.loads((Path(__file__).parent / "parity" / "duty_cases.json").read_text("utf-8"))
+
+
[email protected]("case", CASES["agents"])
+def test_agent_duty(case: dict) -> None:
+ got = duty_of(case["state"], case["lifecycle"], asking=case["asking"], error=case["error"])
+ assert got == case["duty"]
+
+
[email protected]("case", CASES["panes"])
+def test_pane_duty(case: dict) -> None:
+ dot = dot_kind_for(case["pane"])
+ key = state_key_for(case["pane"], dot)
+ assert (dot, key, duty_of_pane(dot, key)) == (case["dot"], case["state_key"], case["duty"])
+
+
+def test_precedence_rules() -> None:
+ assert duty_of("working", "paused") == "paused"
+ assert duty_of("working", asking=True) == "waiting"
+ assert duty_of("working", error=True) == "working"
+ assert duty_of("idle", error=True) == "error"
+
+
[email protected]("case", CASES["chat"])
+def test_chat_lines(case: dict) -> None:
+ assert chat_lines(case["events"]) == case["lines"]
+
+
+def test_chat_line_limits() -> None:
+ long = "word " * 80
+ cut = clean(long, 160)
+ assert len(cut) <= 160 and cut.endswith("…") and not cut[:-1].endswith(" ")
+ assert clean("x" * 300, 80) == "x" * 79 + "…"
+ events = [{"kind": "user_message", "payload": {"text": f"line {i}"}} for i in range(30)]
+ lines = chat_lines(events)
+ assert len(lines) == 12 and lines[-1]["text"] == "line 29"
+ tool = chat_lines([{"kind": "tool_call", "payload": {"summary": "y " * 100}}])[0]
+ assert len(tool["text"]) <= 80
diff --git a/tests/unit/verse_host/test_screens.py b/tests/unit/verse_host/test_screens.py
new file mode 100644
index 0000000000..f8374a7d7d
--- /dev/null
+++ b/tests/unit/verse_host/test_screens.py
@@ -0,0 +1,309 @@
+"""17.6 / A17.7: styled mirror, screens relay, cells codec on the wire.
+
+8 busy panes stay under 200 KB/s and the parser adds at most 5 ms (p99) to
+the event loop per output chunk; plain fallback; screens.gone; resync.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import random
+import time
+from pathlib import Path
+
+from dodaios.verse_host import cells_codec
+from dodaios.verse_host.styled_screen import StyledScreen
+from tests.unit.verse_host._support import close, connect, make_host, schema
+
+PROOF = Path(__file__).resolve().parents[3] / "unreal" / "Verse" / "Saved" / "Harness" / "proof"
+
+
+def test_styled_screen_keeps_colours_and_attrs() -> None:
+ s = StyledScreen(40, 5)
+ s.feed("\x1b[1;38;2;79;184;106m✔ ok\x1b[0m \x1b[38;5;8m(42)\x1b[0m\r\n\x1b[7minv\x1b[27m")
+ runs = s.row_record(0)["runs"]
+ assert runs[0] == {"col": 0, "text": "✔ ok", "fg": "#4fb86a", "bg": None, "attrs": ["bold"]}
+ assert runs[1]["text"] == " " and runs[2] == {
+ "col": 5,
+ "text": "(42)",
+ "fg": {"i": 8},
+ "bg": None,
+ "attrs": [],
+ }
+ assert s.row_record(1)["runs"][0]["attrs"] == ["inverse"]
+ assert s.cursor() == [1, 3]
+
+
+def test_wide_glyphs_and_alt_screen() -> None:
+ s = StyledScreen(10, 3)
+ s.feed("漢字ab")
+ runs = s.row_record(0)["runs"]
+ assert runs[0] == {"col": 0, "text": "漢字", "fg": None, "bg": None, "attrs": ["wide"]}
+ assert runs[1]["col"] == 4 and runs[1]["text"] == "ab"
+ s.take_dirty()
+ s.feed("\x1b[?1049h\x1b[HALT")
+ assert s.text_rows()[0] == "ALT"
+ s.feed("\x1b[?1049l")
+ assert s.text_rows()[0] == "漢字ab"
+ blob = cells_codec.encode(
+ {
+ "kind": "snapshot",
+ "cols": 10,
+ "rows": 3,
+ "cursor": s.cursor(),
+ "rows_changed": s.snapshot_rows(),
+ },
+ ref=1,
+ seq=2,
+ base=None,
+ )
+ assert cells_codec.decode(blob)["rows_changed"][0]["runs"][0]["text"] == "漢字"
+
+
+def test_dirty_rows_only_and_scroll() -> None:
+ s = StyledScreen(20, 4)
+ s.take_dirty()
+ s.feed("\x1b[3;1Hhello")
+ assert [r["row"] for r in s.take_dirty()] == [2]
+ s.feed("\x1b[4;1H\n")
+ assert {r["row"] for r in s.take_dirty()} == {0, 1, 2, 3}
+
+
+def test_hostile_stream_never_raises() -> None:
+ s = StyledScreen(30, 5)
+ rng = random.Random(7) # noqa: S311 - test data
+ alphabet = "\x1b[;?0123456789mHJKABCDsuhl\x07]\\P\n\r\t abc漢́"
+ for _ in range(200):
+ s.feed("".join(rng.choice(alphabet) for _ in range(rng.randint(1, 80))))
+ for r in s.snapshot_rows():
+ cells_codec.check_rows(s.sent_cols, s.sent_rows, [r])
+
+
+def _busy_chunk(rng: random.Random, i: int) -> str:
+ row = rng.randint(1, 40)
+ colour = rng.choice([31, 32, 33, 34, 35, 36, 90])
+ text = "".join(
+ rng.choice("abcdefghijklmnopqrstuvwxyz ./:") for _ in range(rng.randint(20, 120))
+ )
+ return f"\x1b[{row};1H\x1b[2K\x1b[{colour}m{i:06d} {text}\x1b[0m"
+
+
+async def test_eight_busy_panes_stay_under_budget(tmp_path: Path) -> None:
+ host, backend = make_host(tmp_path)
+ for n in range(2, 10):
+ backend.panes.append(dict(backend.panes[0], key=f"T{n}", name=f"T{n}"))
+ t, task = await connect(host)
+ panes = [{"pane_id": f"ws_91:T{n}", "hz": 10} for n in range(1, 10)]
+ t.push({"type": "screens.watch", "id": "c-30", "ts": 1.0, "data": {"panes": panes}})
+ reply = await t.reply_to("c-30")
+ assert [b["ref"] for b in reply["data"]["result"]["bound"]] == list(range(1, 9))
+ assert reply["data"]["result"]["dropped"] == ["ws_91:T9"]
+ relay = next(r for r in host.hub.current.relays if r.topics == ("screens",))
+ rng = random.Random(1) # noqa: S311 - test data
+ loop = asyncio.get_running_loop()
+
+ async def lag_probe(seconds: float) -> list[float]:
+ """How long work queued on the loop waits before it runs (no timer granularity)."""
+ lags, end = [], time.perf_counter() + seconds
+ while time.perf_counter() < end:
+ fut = loop.create_future()
+ t0 = time.perf_counter()
+ loop.call_soon(fut.set_result, None)
+ await fut
+ lags.append(time.perf_counter() - t0)
+ await asyncio.sleep(0.002)
+ return sorted(lags)
+
+ baseline = await lag_probe(1.0)
+ duration = 3.0
+ counter = {"chunks": 0}
+ first_bytes = host.hub.current.screen_bytes
+
+ chunks = [_busy_chunk(rng, k) * 4 for k in range(512)]
+
+ async def feeder(pane_id: str) -> None:
+ end = loop.time() + duration
+ while loop.time() < end:
+ on_output, _ = backend.attached[pane_id]
+ await on_output(chunks[counter["chunks"] % len(chunks)])
+ counter["chunks"] += 1
+ await asyncio.sleep(0.02)
+
+ feeders = [asyncio.ensure_future(feeder(p)) for p in list(backend.attached)]
+ lags = await lag_probe(duration)
+ await asyncio.gather(*feeders)
+ i = counter["chunks"]
+ spent = host.hub.current.screen_bytes - first_bytes
+ rate = spent / duration
+ p99_feed = relay.feed_p99_ms()
+ p99_frame = relay.frame_p99_ms()
+ await close(t, task)
+ p99_lag_ms = lags[int(len(lags) * 0.99)] * 1000
+ p99_base_ms = baseline[int(len(baseline) * 0.99)] * 1000
+ assert rate <= 200 * 1024, rate
+ assert p99_feed <= 5.0, p99_feed
+ # The relay's own work per loop step: one output chunk parsed, one pane framed.
+ p99_frame = relay.frame_p99_ms()
+ assert p99_frame <= 5.0, p99_frame
+ metas = t.of_type("screens.meta")
+ assert {m["data"]["pane_id"] for m in metas} == {f"ws_91:T{n}" for n in range(1, 9)}
+ blobs = t.binary()
+ assert blobs, "no binary cell frames"
+ decoded = [cells_codec.decode(b) for b in blobs]
+ by_ref: dict[int, list[dict]] = {}
+ for d in decoded:
+ by_ref.setdefault(d["ref"], []).append(d)
+ for frames in by_ref.values():
+ assert frames[0]["kind"] == "snapshot"
+ for prev, cur in zip(frames, frames[1:], strict=False):
+ if cur["kind"] == "delta":
+ assert cur["base"] == prev["seq"]
+ out = PROOF / "WP17" / "17.6"
+ out.mkdir(parents=True, exist_ok=True)
+ (out / "screens_budget.json").write_text(
+ json.dumps(
+ {
+ "panes": 8,
+ "seconds": duration,
+ "screens_bytes_per_s": round(rate),
+ "budget_bytes_per_s": 200 * 1024,
+ "parser_p99_ms": round(p99_feed, 3),
+ "frame_build_p99_ms": round(p99_frame, 3),
+ "loop_lag_p99_ms": round(p99_lag_ms, 3),
+ "loop_lag_p99_baseline_ms": round(p99_base_ms, 3),
+ "loop_lag_p99_added_ms": round(p99_lag_ms - p99_base_ms, 3),
+ "binary_frames": len(blobs),
+ "chunks_fed": i,
+ "measured_at": time.time(),
+ },
+ indent=2,
+ )
+ )
+
+
+async def test_plain_fallback_gone_and_resync(tmp_path: Path, monkeypatch) -> None:
+ host, backend = make_host(tmp_path)
+ backend.panes.append(dict(backend.panes[0], key="T2", name="T2"))
+ backend.attach_fails.add("ws_91:T2")
+ backend.screens["ws_91:T2"] = {
+ "cols": 40,
+ "rows": 5,
+ "lines": ["$ make", "ok"],
+ "cursor": [1, 2],
+ "at": 5.0,
+ }
+ t, task = await connect(host, encodings={"screens": ["cells.json/1"]})
+ t.push(
+ {
+ "type": "screens.watch",
+ "id": "c-1",
+ "ts": 1.0,
+ "data": {
+ "panes": [
+ {"pane_id": "ws_91:T1", "hz": 10},
+ {"pane_id": "ws_91:T2", "hz": 2},
+ {"pane_id": "ws_91:T7", "hz": 2},
+ ]
+ },
+ }
+ )
+ reply = await t.reply_to("c-1")
+ assert reply["data"]["result"]["missing"] == ["ws_91:T7"]
+ plain = await t.wait_for(
+ lambda f: f["type"] == "screens.frame" and f["data"]["pane_id"] == "ws_91:T2"
+ )
+ assert plain["data"]["style"] == "plain" and plain["data"]["kind"] == "snapshot"
+ assert plain["data"]["rows_changed"][0]["runs"][0]["text"] == "$ make"
+ await backend.attached["ws_91:T1"][0]("\x1b[32mgreen\x1b[0m")
+ styled = await t.wait_for(
+ lambda f: (
+ f["type"] == "screens.frame"
+ and f["data"]["pane_id"] == "ws_91:T1"
+ and f["data"]["kind"] == "delta"
+ )
+ )
+ assert styled["data"]["rows_changed"][0]["runs"][0]["fg"] == {"i": 2}
+ t.push(
+ {
+ "type": "resync",
+ "id": "c-2",
+ "ts": 1.0,
+ "data": {"topic": "screens", "pane_id": "ws_91:T1"},
+ }
+ )
+ await t.reply_to("c-2")
+
+ def snaps() -> list[dict]:
+ return [
+ f
+ for f in t.of_type("screens.frame")
+ if f["data"]["pane_id"] == "ws_91:T1" and f["data"]["kind"] == "snapshot"
+ ]
+
+ await t.wait_for(lambda f: len(snaps()) >= 2)
+ await backend.attached["ws_91:T1"][1](0)
+ gone = await t.wait_for(lambda f: f["type"] == "screens.gone")
+ assert gone["data"] == {"pane_id": "ws_91:T1", "reason": "exited"}
+ await close(t, task)
+ sch = schema()
+ for frame in t.frames():
+ assert sch.validate_frame(frame) == [], frame
+
+
+async def test_over_budget_frame_keeps_its_rows_for_the_next_tick() -> None:
+ from dodaios.verse_host.relays.screens import ScreensRelay, Watched
+
+ sent: list[dict] = []
+
+ class _Outbox:
+ def clear_topic(self, topic: str) -> None:
+ return None
+
+ class _Session:
+ outbox = _Outbox()
+
+ def send(self, type_: str, data: dict, **kw: object) -> None:
+ sent.append(data)
+
+ relay = ScreensRelay(_Session(), backend=None)
+ mirror = StyledScreen(40, 6)
+ w = Watched(pane_id="ws_91:T1", ref=1, hz=10, mirror=mirror, need_snapshot=False)
+ relay.watched[w.pane_id] = w
+ mirror.dirty = set()
+ mirror.feed("one\r\ntwo\r\nthree")
+ changed = set(mirror.dirty)
+ assert changed
+ relay._window = [(10.0, relay.budget_bytes_per_s)] # this second's budget is spent
+ await relay.flush(10.5)
+ assert sent == []
+ assert changed <= mirror.dirty, "skipped rows must stay dirty"
+ await relay.flush(11.6) # a new second: the delayed frame goes out whole
+ assert len(sent) == 1 and sent[0]["kind"] == "delta"
+ assert {r["row"] for r in sent[0]["rows_changed"]} >= changed
+
+
+async def test_snapshots_wait_for_budget_too() -> None:
+ from dodaios.verse_host.relays.screens import ScreensRelay, Watched
+
+ sent: list[dict] = []
+
+ class _Session:
+ class outbox: # noqa: N801
+ @staticmethod
+ def clear_topic(topic: str) -> None:
+ return None
+
+ def send(self, type_: str, data: dict, **kw: object) -> None:
+ sent.append(data)
+
+ relay = ScreensRelay(_Session(), backend=None)
+ mirror = StyledScreen(40, 6)
+ mirror.feed("hello")
+ w = Watched(pane_id="ws_91:T1", ref=1, hz=10, mirror=mirror, last_snapshot=10.0)
+ relay.watched[w.pane_id] = w
+ relay._window = [(10.0, relay.budget_bytes_per_s)]
+ await relay.flush(10.5)
+ assert sent == [] and w.need_snapshot
+ await relay.flush(11.6)
+ assert [d["kind"] for d in sent] == ["snapshot"]
diff --git a/tests/unit/verse_host/test_supervisor.py b/tests/unit/verse_host/test_supervisor.py
new file mode 100644
index 0000000000..6c7870e2ac
--- /dev/null
+++ b/tests/unit/verse_host/test_supervisor.py
@@ -0,0 +1,298 @@
+"""17.3 / A17.3, A17.4, A17.5: supervisor liveness, containment and the token rule."""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import subprocess
+import sys
+import textwrap
+import time
+from pathlib import Path
+from typing import Any
+
+import psutil
+import pytest
+
+from dodaios.verse_host.bridge import TokenBox, mint_token
+from dodaios.verse_host.supervisor import BACKOFF_S, Supervisor, spawn_contained
+
+
+class FakeProcess:
+ def __init__(self, pid: int) -> None:
+ self.pid = pid
+ self._exit: asyncio.Future[int] = asyncio.get_running_loop().create_future()
+ self.killed = False
+
+ async def wait(self) -> int:
+ return await self._exit
+
+ def kill(self) -> None:
+ self.killed = True
+ self.exit(-9)
+
+ def exit(self, code: int) -> None:
+ if not self._exit.done():
+ self._exit.set_result(code)
+
+ def alive(self) -> bool:
+ return not self._exit.done()
+
+
+class Clock:
+ def __init__(self) -> None:
+ self.now = 1000.0
+ self.sleeps: list[float] = []
+
+ def __call__(self) -> float:
+ return self.now
+
+ async def sleep(self, seconds: float) -> None:
+ self.sleeps.append(seconds)
+ self.now += seconds
+ await asyncio.sleep(0)
+
+
+def _supervisor(tmp_path: Path, clock: Clock, spawned: list[FakeProcess], **kw: Any) -> Supervisor:
+ exe = tmp_path / "Verse.exe"
+ exe.write_text("dummy")
+ tokens = TokenBox()
+
+ async def spawn(argv: list[str], env: dict[str, str], cwd: Path) -> FakeProcess:
+ p = FakeProcess(4000 + len(spawned))
+ p.argv, p.env = argv, env # type: ignore[attr-defined]
+ spawned.append(p)
+ return p
+
+ sup = Supervisor(
+ exe=lambda: exe,
+ bridge_url=lambda: "ws://127.0.0.1:8765/api/verse/bridge",
+ set_token=lambda t: tokens.set("launch", t),
+ mint=mint_token,
+ crash_dir=tmp_path / "crashes",
+ spawn=spawn,
+ clock=clock,
+ sleep=clock.sleep,
+ **kw,
+ )
+ sup.tokens = tokens # type: ignore[attr-defined]
+ return sup
+
+
+async def _settle() -> None:
+ for _ in range(20):
+ await asyncio.sleep(0)
+
+
+async def test_restart_backoff_and_crash_loop(tmp_path: Path) -> None:
+ clock, spawned = Clock(), []
+ sup = _supervisor(tmp_path, clock, spawned)
+ assert sup.state.status == "stopped"
+ assert await sup.ensure_running()
+ assert sup.state.status == "running" and len(spawned) == 1
+ # Crash 1 -> restart after 1 s.
+ spawned[0].exit(3)
+ await _settle()
+ assert clock.sleeps[-1] == BACKOFF_S[0] == 1.0
+ assert len(spawned) == 2 and sup.state.status == "running"
+ # Crash 2 -> restart after 4 s.
+ clock.now += 30
+ spawned[1].exit(3)
+ await _settle()
+ assert clock.sleeps[-1] == BACKOFF_S[1] == 4.0
+ assert len(spawned) == 3
+ # Crash 3 within 5 minutes -> crashed, no restart.
+ clock.now += 30
+ spawned[2].exit(3)
+ await _settle()
+ assert sup.state.status == "crashed"
+ assert len(spawned) == 3
+ assert not await sup.ensure_running() # a crash loop needs a manual launch
+ assert (Path(sup.state.crash_report) / "exit.json").is_file()
+ assert await sup.ensure_running(manual=True)
+ assert sup.state.status == "running" and len(spawned) == 4
+
+
+async def test_third_backoff_is_15s_when_crashes_are_spread(tmp_path: Path) -> None:
+ clock, spawned = Clock(), []
+ sup = _supervisor(tmp_path, clock, spawned)
+ await sup.ensure_running()
+ for i in range(2):
+ clock.now += 200
+ spawned[i].exit(1)
+ await _settle()
+ clock.now += 200 # the first crash has left the 5-minute window
+ spawned[2].exit(1)
+ await _settle()
+ assert clock.sleeps[-1] == BACKOFF_S[2] == 15.0
+ assert sup.state.status == "running"
+
+
+async def test_hung_bridge_kills_by_own_pid_and_restarts(tmp_path: Path) -> None:
+ clock, spawned = Clock(), []
+ sup = _supervisor(tmp_path, clock, spawned)
+ await sup.ensure_running()
+ await sup.on_hung()
+ await _settle()
+ assert spawned[0].killed
+ assert len(spawned) == 2
+
+
+async def test_stop_is_not_a_crash(tmp_path: Path) -> None:
+ clock, spawned = Clock(), []
+ asked: list[tuple[str, int]] = []
+
+ async def request_quit(reason: str, deadline: int) -> bool:
+ asked.append((reason, deadline))
+ spawned[-1].exit(0)
+ return True
+
+ sup = _supervisor(tmp_path, clock, spawned, request_quit=request_quit)
+ await sup.ensure_running()
+ await sup.stop("app_quit")
+ await _settle()
+ assert asked == [("app_quit", 3000)]
+ assert sup.state.status == "stopped" and len(spawned) == 1
+ assert not sup.tokens.check(spawned[0].env["DODAIOS_VERSE_TOKEN"]) # type: ignore[attr-defined]
+
+
+async def test_token_only_in_env_and_valid_only_while_alive(tmp_path: Path, caplog) -> None:
+ caplog.set_level(logging.DEBUG)
+ clock, spawned = Clock(), []
+ sup = _supervisor(tmp_path, clock, spawned)
+ await sup.ensure_running()
+ proc = spawned[0]
+ token = proc.env["DODAIOS_VERSE_TOKEN"] # type: ignore[attr-defined]
+ assert len(token) == 43
+ assert proc.env["DODAIOS_VERSE_BRIDGE"].startswith("ws://127.0.0.1:") # type: ignore[attr-defined]
+ assert all(token not in arg for arg in proc.argv) # type: ignore[attr-defined]
+ assert sup.tokens.check(token)
+ proc.exit(1)
+ await _settle()
+ assert not sup.tokens.check(token)
+ assert token not in caplog.text
+
+
+CHILD = textwrap.dedent(
+ """
+ import os, sys, time
+ sys.stdout.write("ARGV=" + repr(sys.argv) + "\\n")
+ sys.stdout.write("HAS_TOKEN=" + str(bool(os.environ.get("DODAIOS_VERSE_TOKEN"))) + "\\n")
+ sys.stdout.flush()
+ time.sleep(60)
+ """
+)
+
+APP = textwrap.dedent(
+ """
+ import asyncio, sys
+ from pathlib import Path
+ sys.path.insert(0, {root!r})
+ from dodaios.verse_host.supervisor import spawn_contained
+
+ async def main():
+ env = dict(__import__("os").environ, DODAIOS_VERSE_TOKEN="T" * 43)
+ p = await spawn_contained([sys.executable, {child!r}], env, Path({cwd!r}))
+ print(p.pid, flush=True)
+ await asyncio.sleep(60)
+
+ asyncio.run(main())
+ """
+)
+
+
[email protected](sys.platform not in ("win32", "linux"), reason="containment is Windows/Linux")
+def test_killing_the_app_ends_verse_within_2s(tmp_path: Path) -> None:
+ root = str(Path(__file__).resolve().parents[3])
+ child = tmp_path / "dummy_verse.py"
+ child.write_text(CHILD)
+ app = tmp_path / "app.py"
+ app.write_text(APP.format(root=root, child=str(child), cwd=str(tmp_path)))
+ proc = subprocess.Popen( # noqa: S603
+ [sys.executable, str(app)], stdout=subprocess.PIPE, text=True
+ )
+ try:
+ line = proc.stdout.readline().strip() # type: ignore[union-attr]
+ verse_pid = int(line)
+ assert psutil.pid_exists(verse_pid)
+ verse = psutil.Process(verse_pid)
+ cmdline = " ".join(verse.cmdline())
+ assert "T" * 43 not in cmdline # A17.5: never on the command line
+ started = time.perf_counter()
+ proc.kill() # the app process dies hard, by its own PID
+ proc.wait(5)
+ try:
+ verse.wait(2.0)
+ except psutil.TimeoutExpired:
+ verse.kill()
+ pytest.fail("dummy Verse outlived the app by more than 2 s")
+ assert time.perf_counter() - started <= 2.0
+ finally:
+ if proc.poll() is None:
+ proc.kill()
+
+
+async def test_real_spawn_keeps_token_off_the_command_line(tmp_path: Path) -> None:
+ child = tmp_path / "dummy_verse.py"
+ child.write_text(CHILD.replace("time.sleep(60)", "time.sleep(0.2)"))
+ token = mint_token()
+ env = dict(__import__("os").environ, DODAIOS_VERSE_TOKEN=token)
+ p = await spawn_contained([sys.executable, str(child)], env, tmp_path)
+ try:
+ cmd = " ".join(psutil.Process(p.pid).cmdline())
+ assert token not in cmd
+ finally:
+ p.kill()
+ await p.wait()
+
+
+async def test_exit_after_bye_is_a_stop(tmp_path: Path) -> None:
+ clock, spawned = Clock(), []
+ sup = _supervisor(tmp_path, clock, spawned)
+ await sup.ensure_running()
+ sup.expect_exit() # lifecycle.bye arrived
+ clock.now += 60
+ spawned[0].exit(0)
+ await _settle()
+ assert sup.state.status == "stopped"
+ assert len(spawned) == 1 and sup.state.crashes == []
+ # The next launch clears the expectation: a later exit is a crash again.
+ assert await sup.ensure_running(manual=True)
+ spawned[1].exit(3)
+ await _settle()
+ assert len(sup.state.crashes) == 1 and len(spawned) == 3
+
+
+async def test_expected_exit_window_expires(tmp_path: Path) -> None:
+ clock, spawned = Clock(), []
+ sup = _supervisor(tmp_path, clock, spawned)
+ await sup.ensure_running()
+ sup.expect_exit(10.0)
+ clock.now += 11 # Verse did not quit in time; a later exit is a crash
+ spawned[0].exit(3)
+ await _settle()
+ assert len(sup.state.crashes) == 1 and len(spawned) == 2
+
+
+async def test_dormant_gpu_yield_exit_is_not_a_crash(tmp_path: Path) -> None:
+ from tests.unit.verse_host._support import close, connect, make_host
+
+ clock, spawned = Clock(), []
+ sup = _supervisor(tmp_path, clock, spawned)
+ host, _ = make_host(tmp_path, supervisor=sup)
+ await sup.ensure_running()
+ t, task = await connect(host)
+ t.push({"type": "lifecycle.state", "ts": 1.0, "data": {"state": "dormant", "vram_mb": 900}})
+ for _ in range(100):
+ if host.state == "dormant":
+ break
+ await asyncio.sleep(0.01)
+ assert host.state == "dormant"
+ assert await host.gpu_pressure(True, "local_model")
+ await t.wait_for(lambda f: f["type"] == "gpu.yield")
+ spawned[0].exit(0) # a Dormant Verse quits at once on gpu.yield (contract 12)
+ await _settle()
+ assert sup.state.status == "stopped"
+ assert len(spawned) == 1, "a GPU yield must not relaunch Verse"
+ assert sup.state.crashes == [] and sup.state.crash_report is None
+ await close(t, task)
diff --git a/unreal/Verse/Source/VerseBridge/Private/Bridge/VerseBridgeClient.cpp b/unreal/Verse/Source/VerseBridge/Private/Bridge/VerseBridgeClient.cpp
new file mode 100644
index 0000000000..15d3c563dd
--- /dev/null
+++ b/unreal/Verse/Source/VerseBridge/Private/Bridge/VerseBridgeClient.cpp
@@ -0,0 +1,520 @@
+#include "Bridge/VerseBridgeClient.h"
+
+#include "Bridge/VerseCellsCodec.h"
+#include "HAL/PlatformMisc.h"
+#include "HAL/PlatformProcess.h"
+#include "Misc/FileHelper.h"
+#include "Misc/Paths.h"
+#include "VerseLog.h"
+
+using namespace VerseBridgeJson;
+
+namespace
+{
+ TSharedPtr<FJsonObject> StringArrayField(const TCHAR* Field, const TArray<FString>& Values)
+ {
+ TArray<TSharedPtr<FJsonValue>> A;
+ for (const FString& V : Values)
+ {
+ A.Add(MakeShared<FJsonValueString>(V));
+ }
+ TSharedPtr<FJsonObject> O = MakeShared<FJsonObject>();
+ O->SetArrayField(Field, A);
+ return O;
+ }
+
+ /** The backend's DATA_DIR sits next to the checkout (dodaios/core/instance.py); the
+ * Unreal project is <checkout>/unreal/Verse, so the dev file is two levels up. */
+ FString DevDiscoveryPath()
+ {
+ const FString DataDir = FPlatformMisc::GetEnvironmentVariable(TEXT("JARVIS_DATA_DIR"));
+ if (!DataDir.IsEmpty())
+ {
+ return FPaths::Combine(DataDir, TEXT("verse"), TEXT("bridge.json"));
+ }
+ return FPaths::ConvertRelativePathToFull(FPaths::Combine(FPaths::ProjectDir(), TEXT(".."), TEXT(".."), TEXT("data"), TEXT("verse"), TEXT("bridge.json")));
+ }
+}
+
+double FVerseBridgeClient::BackoffFor(int32 Attempt)
+{
+ static const double Steps[] = {0.25, 1.0, 2.0, 4.0};
+ return Attempt < 1 ? 0.0 : Attempt <= 4 ? Steps[Attempt - 1] : 5.0;
+}
+
+bool FVerseBridgeClient::Discover(FDiscovery& Out, const FString& DevFileOverride)
+{
+ Out.Url = FPlatformMisc::GetEnvironmentVariable(TEXT("DODAIOS_VERSE_BRIDGE"));
+ Out.Token = FPlatformMisc::GetEnvironmentVariable(TEXT("DODAIOS_VERSE_TOKEN"));
+ if (!Out.Url.IsEmpty() && !Out.Token.IsEmpty())
+ {
+ return true;
+ }
+#if !UE_BUILD_SHIPPING
+ // Editor or standalone run without a supervisor (contract 1, Dev discovery).
+ FString Explicit = FPlatformMisc::GetEnvironmentVariable(TEXT("DODAIOS_VERSE_DISCOVERY"));
+ const FString Path = !DevFileOverride.IsEmpty() ? DevFileOverride : !Explicit.IsEmpty() ? Explicit : DevDiscoveryPath();
+ FString Text;
+ if (FFileHelper::LoadFileToString(Text, *Path))
+ {
+ const TSharedPtr<FJsonObject> O = Read(Text);
+ Out.Url = Str(O, TEXT("url"));
+ Out.Token = Str(O, TEXT("token"));
+ return !Out.Url.IsEmpty() && !Out.Token.IsEmpty();
+ }
+#endif
+ return false;
+}
+
+FVerseBridgeClient::FVerseBridgeClient() = default;
+
+FVerseBridgeClient::~FVerseBridgeClient()
+{
+ Stop();
+}
+
+void FVerseBridgeClient::Start(const FDiscovery& Discovery)
+{
+ Target = Discovery;
+ Attempts = 0;
+ State = EState::Waiting;
+ NextAttemptAt = 0.0;
+}
+
+void FVerseBridgeClient::Stop()
+{
+ Socket.Close(1000);
+ FailPending(TEXT("internal"));
+ State = EState::Idle;
+}
+
+void FVerseBridgeClient::Connect(double Now)
+{
+ State = EState::Connecting;
+ LastFrameAt = Now;
+ if (!Socket.Connect(Target.Url))
+ {
+ State = EState::Idle;
+ UE_LOG(LogVerseBridge, Error, TEXT("bridge: no usable bridge URL"));
+ }
+}
+
+void FVerseBridgeClient::Tick(double Now)
+{
+ if (State == EState::Waiting && Now >= NextAttemptAt)
+ {
+ Connect(Now);
+ }
+ FVerseWsClient::FEvent E;
+ while (Socket.Poll(E))
+ {
+ switch (E.Kind)
+ {
+ case FVerseWsClient::FEvent::EKind::Connected:
+ {
+ State = EState::Handshaking;
+ LastFrameAt = Now;
+ TSharedPtr<FJsonObject> Hello = MakeShared<FJsonObject>();
+ Hello->SetStringField(TEXT("token"), Target.Token);
+ Hello->SetArrayField(TEXT("protocols"), {MakeShared<FJsonValueString>(VerseBridge::Protocol)});
+ TSharedPtr<FJsonObject> Build = MakeShared<FJsonObject>();
+ Build->SetStringField(TEXT("version"), BuildVersion);
+ Build->SetStringField(TEXT("changelist"), BuildChangelist.IsEmpty() ? TEXT("dev") : BuildChangelist);
+#if UE_BUILD_SHIPPING
+ Build->SetStringField(TEXT("config"), TEXT("Shipping"));
+#elif UE_BUILD_DEVELOPMENT
+ Build->SetStringField(TEXT("config"), TEXT("Development"));
+#else
+ Build->SetStringField(TEXT("config"), TEXT("Debug"));
+#endif
+ Build->SetStringField(TEXT("platform"), PLATFORM_WINDOWS ? TEXT("Win64") : TEXT("Linux"));
+ Hello->SetObjectField(TEXT("build"), Build);
+ Hello->SetNumberField(TEXT("pid"), double(FPlatformProcess::GetCurrentProcessId()));
+ Hello->SetNumberField(TEXT("last_seq"), double(LastSeq));
+ TSharedPtr<FJsonObject> Enc = MakeShared<FJsonObject>();
+ TArray<TSharedPtr<FJsonValue>> ScreenEncodings;
+ if (!bPreferJsonScreens)
+ {
+ ScreenEncodings.Add(MakeShared<FJsonValueString>(TEXT("cells.bin/1")));
+ }
+ ScreenEncodings.Add(MakeShared<FJsonValueString>(TEXT("cells.json/1")));
+ Enc->SetArrayField(TEXT("screens"), ScreenEncodings);
+ Hello->SetObjectField(TEXT("encodings"), Enc);
+ TSharedPtr<FJsonObject> Caps = MakeShared<FJsonObject>();
+ Caps->SetBoolField(TEXT("panel_stream"), true);
+ Caps->SetBoolField(TEXT("duel"), true);
+ Hello->SetObjectField(TEXT("capabilities"), Caps);
+ SendNotice(TEXT("hello"), Hello);
+ break;
+ }
+ case FVerseWsClient::FEvent::EKind::Text:
+ HandleText(E.Text, Now);
+ break;
+ case FVerseWsClient::FEvent::EKind::Binary:
+ HandleBinary(E.Bytes, Now);
+ break;
+ case FVerseWsClient::FEvent::EKind::Closed:
+ HandleClosed(E.CloseCode, Now);
+ break;
+ }
+ }
+ if (State == EState::Linked)
+ {
+ if (Now - LastPingAt >= PingInterval)
+ {
+ LastPingAt = Now;
+ SendNotice(TEXT("ping"), MakeShared<FJsonObject>());
+ }
+ if (Now - LastFrameAt >= DeadLink)
+ {
+ UE_LOG(LogVerseBridge, Warning, TEXT("bridge: no frame for %.1f s, reconnecting"), Now - LastFrameAt);
+ Socket.Close(1001);
+ Unlink(1006, Now);
+ }
+ }
+ else if ((State == EState::Connecting || State == EState::Handshaking) && Now - LastFrameAt >= DeadLink)
+ {
+ Socket.Close(1001);
+ Unlink(1006, Now);
+ }
+}
+
+void FVerseBridgeClient::Unlink(int32 Code, double Now)
+{
+ const bool bWasLinked = State == EState::Linked;
+ FailPending(TEXT("internal"));
+ LastSeqOf.Reset();
+ ResyncInFlight.Reset();
+ Screens.Reset();
+ if (Code == int32(VerseBridge::ECloseCode::Token) && bEverLinked)
+ {
+ State = EState::LaunchOver;
+ UE_LOG(LogVerseBridge, Log, TEXT("bridge: token refused on reconnect, the launch is over"));
+ OnLaunchOver.Broadcast();
+ return;
+ }
+ if (Code == int32(VerseBridge::ECloseCode::Replaced))
+ {
+ // Another Verse took the link; this one must not fight for it.
+ State = EState::Idle;
+ OnUnlinked.Broadcast(Code);
+ return;
+ }
+ ++Attempts;
+ State = EState::Waiting;
+ NextAttemptAt = Now + BackoffFor(Attempts);
+ if (bWasLinked)
+ {
+ OnUnlinked.Broadcast(Code);
+ }
+}
+
+void FVerseBridgeClient::HandleClosed(int32 Code, double Now)
+{
+ UE_LOG(LogVerseBridge, Log, TEXT("bridge: closed with %d"), Code);
+ Socket.Close(Code);
+ Unlink(Code, Now);
+}
+
+void FVerseBridgeClient::SendFrame(const FVerseBridgeFrame& Frame)
+{
+ Socket.SendText(Frame.Encode());
+}
+
+FString FVerseBridgeClient::SendCommand(const FString& Type, TSharedPtr<FJsonObject> Data, FReply OnReply)
+{
+ const FString Id = FString::Printf(TEXT("c-%d"), NextId++);
+ if (State != EState::Linked)
+ {
+ if (OnReply)
+ {
+ OnReply(false, nullptr, TEXT("unavailable"));
+ }
+ return Id;
+ }
+ Pending.Add(Id, MoveTemp(OnReply));
+ SendFrame(FVerseBridgeFrame::Make(Type, Data, Id));
+ return Id;
+}
+
+void FVerseBridgeClient::SendNotice(const FString& Type, TSharedPtr<FJsonObject> Data)
+{
+ SendFrame(FVerseBridgeFrame::Make(Type, Data));
+}
+
+void FVerseBridgeClient::Reply(const FString& Re, bool bOk, TSharedPtr<FJsonObject> Result, const FString& ErrorCode, const FString& Message)
+{
+ TSharedPtr<FJsonObject> Data = MakeShared<FJsonObject>();
+ Data->SetBoolField(TEXT("ok"), bOk);
+ if (bOk)
+ {
+ Data->SetObjectField(TEXT("result"), Result.IsValid() ? Result : MakeShared<FJsonObject>());
+ }
+ else
+ {
+ TSharedPtr<FJsonObject> Err = MakeShared<FJsonObject>();
+ Err->SetStringField(TEXT("code"), ErrorCode.IsEmpty() ? TEXT("internal") : ErrorCode);
+ Err->SetStringField(TEXT("message"), Message);
+ Data->SetObjectField(TEXT("error"), Err);
+ }
+ FVerseBridgeFrame F = FVerseBridgeFrame::Make(TEXT("reply"), Data);
+ F.Re = Re;
+ SendFrame(F);
+}
+
+void FVerseBridgeClient::FailPending(const FString& Code)
+{
+ TMap<FString, FReply> Failed = MoveTemp(Pending);
+ Pending.Reset();
+ for (TPair<FString, FReply>& P : Failed)
+ {
+ if (P.Value)
+ {
+ P.Value(false, nullptr, Code);
+ }
+ }
+}
+
+void FVerseBridgeClient::Subscribe(const TArray<FString>& InTopics)
+{
+ for (const FString& T : InTopics)
+ {
+ Topics.AddUnique(T);
+ }
+ if (IsLinked())
+ {
+ SendCommand(TEXT("subscribe"), StringArrayField(TEXT("topics"), InTopics));
+ }
+}
+
+void FVerseBridgeClient::WatchScreens(const TArray<TPair<FString, int32>>& PanesNearestFirst)
+{
+ ScreenWatch = PanesNearestFirst;
+ if (!IsLinked())
+ {
+ return;
+ }
+ TArray<TSharedPtr<FJsonValue>> List;
+ for (const TPair<FString, int32>& P : ScreenWatch)
+ {
+ TSharedPtr<FJsonObject> O = MakeShared<FJsonObject>();
+ O->SetStringField(TEXT("pane_id"), P.Key);
+ O->SetNumberField(TEXT("hz"), FMath::Clamp(P.Value, 1, 10));
+ List.Add(MakeShared<FJsonValueObject>(O));
+ }
+ TSharedPtr<FJsonObject> Data = MakeShared<FJsonObject>();
+ Data->SetArrayField(TEXT("panes"), List);
+ SendCommand(TEXT("screens.watch"), Data, [this](bool bOk, const TSharedPtr<FJsonObject>& Result, const FString&)
+ {
+ if (bOk)
+ {
+ Screens.Bind(Result);
+ }
+ });
+}
+
+void FVerseBridgeClient::WatchChatTails(const TArray<FString>& AgentIds)
+{
+ ChatWatch = AgentIds;
+ if (IsLinked())
+ {
+ SendCommand(TEXT("chat_tails.watch"), StringArrayField(TEXT("agents"), AgentIds));
+ }
+}
+
+void FVerseBridgeClient::Resync(const FString& Topic, const FString& PaneId)
+{
+ const FString Slot = PaneId.IsEmpty() ? Topic : PaneId;
+ if (ResyncInFlight.Contains(Slot))
+ {
+ return;
+ }
+ TSharedPtr<FJsonObject> Data = MakeShared<FJsonObject>();
+ Data->SetStringField(TEXT("topic"), Topic);
+ if (!PaneId.IsEmpty())
+ {
+ Data->SetStringField(TEXT("pane_id"), PaneId);
+ }
+ ResyncInFlight.Add(Slot, Topic);
+ UE_LOG(LogVerseBridge, Log, TEXT("bridge: gap on %s, resync"), *Slot);
+ SendCommand(TEXT("resync"), Data, [this, Slot](bool, const TSharedPtr<FJsonObject>&, const FString&) {});
+}
+
+bool FVerseBridgeClient::CheckBase(const FString& Slot, const FVerseBridgeFrame& Frame)
+{
+ const int64* Last = LastSeqOf.Find(Slot);
+ if (!Frame.HasBase() || !Last || *Last != Frame.Base)
+ {
+ return false;
+ }
+ return true;
+}
+
+void FVerseBridgeClient::HandleText(const FString& Text, double Now)
+{
+ LastFrameAt = Now;
+ FVerseBridgeFrame F;
+ FString Error;
+ if (!FVerseBridgeFrame::Parse(Text, F, &Error))
+ {
+ UE_LOG(LogVerseBridge, Warning, TEXT("bridge: malformed frame ignored (%s)"), *Error);
+ return;
+ }
+ if (F.Seq >= 0)
+ {
+ LastSeq = FMath::Max(LastSeq, F.Seq);
+ }
+ if (State == EState::Handshaking)
+ {
+ if (F.Type != TEXT("welcome"))
+ {
+ return;
+ }
+ Welcome = F.Data;
+ Settings.ApplyWelcome(F.Data);
+ State = EState::Linked;
+ bEverLinked = true;
+ Attempts = 0;
+ LastPingAt = Now;
+ UE_LOG(LogVerseBridge, Log, TEXT("bridge: linked (session %s, app %s)"), *Str(F.Data, TEXT("session")), *Str(F.Data, TEXT("app_version")));
+ // No replay: a fresh snapshot per resubscribed topic (contract 1, Reconnect).
+ if (Topics.Num())
+ {
+ SendCommand(TEXT("subscribe"), StringArrayField(TEXT("topics"), Topics));
+ }
+ if (ScreenWatch.Num())
+ {
+ WatchScreens(ScreenWatch);
+ }
+ if (ChatWatch.Num())
+ {
+ WatchChatTails(ChatWatch);
+ }
+ OnLinked.Broadcast();
+ OnFrame.Broadcast(F);
+ return;
+ }
+ Dispatch(F);
+}
+
+void FVerseBridgeClient::Dispatch(const FVerseBridgeFrame& F)
+{
+ const FString& T = F.Type;
+ if (T == TEXT("reply"))
+ {
+ FReply Callback;
+ if (Pending.RemoveAndCopyValue(F.Re, Callback) && Callback)
+ {
+ const bool bOk = Bool(F.Data, TEXT("ok"));
+ Callback(bOk, Obj(F.Data, TEXT("result")), Str(Obj(F.Data, TEXT("error")), TEXT("code")));
+ }
+ OnFrame.Broadcast(F);
+ return;
+ }
+ if (!F.Id.IsEmpty() && T == TEXT("qa.exec"))
+ {
+ OnServerCommand.Broadcast(F);
+ return;
+ }
+ auto Track = [this, &F](const FString& Topic, bool bDelta, TFunction<void()> Apply)
+ {
+ if (bDelta && !CheckBase(Topic, F))
+ {
+ Resync(Topic);
+ return;
+ }
+ ResyncInFlight.Remove(Topic);
+ LastSeqOf.Add(Topic, F.Seq);
+ Apply();
+ };
+ if (T == TEXT("roster.snapshot"))
+ {
+ Track(TEXT("roster"), false, [&] { Roster.ApplySnapshot(F.Data); });
+ }
+ else if (T == TEXT("roster.delta"))
+ {
+ Track(TEXT("roster"), true, [&] { Roster.ApplyDelta(F.Data); });
+ }
+ else if (T == TEXT("groups.snapshot"))
+ {
+ Track(TEXT("groups"), false, [&] { Groups.ApplySnapshot(F.Data); });
+ }
+ else if (T == TEXT("groups.delta"))
+ {
+ Track(TEXT("groups"), true, [&] { Groups.ApplyDelta(F.Data); });
+ }
+ else if (T == TEXT("meetings.update"))
+ {
+ Groups.ApplyMeeting(F.Data);
+ }
+ else if (T == TEXT("progression.snapshot"))
+ {
+ Progression.ApplySnapshot(F.Data);
+ }
+ else if (T == TEXT("progression.awarded"))
+ {
+ Progression.ApplyAward(F.Data);
+ }
+ else if (T == TEXT("chat_tails.update"))
+ {
+ ChatTails.Apply(F.Data);
+ }
+ else if (T == TEXT("companion.snapshot") || T == TEXT("companion.update"))
+ {
+ Companion.Apply(F.Data);
+ }
+ else if (T == TEXT("settings.changed"))
+ {
+ Settings.ApplyChanged(F.Data);
+ }
+ else if (T == TEXT("screens.meta"))
+ {
+ Screens.ApplyMeta(F.Data);
+ }
+ else if (T == TEXT("screens.gone"))
+ {
+ Screens.ApplyGone(F.Data);
+ }
+ else if (T == TEXT("screens.frame"))
+ {
+ FVerseCellsFrame Cells;
+ FString Error;
+ if (FVerseCellsFrame::FromJson(F.Data, Cells, &Error))
+ {
+ Cells.Seq = uint32(F.Seq);
+ Cells.Base = F.HasBase() ? uint32(F.Base) : 0;
+ const FString PaneId = Str(F.Data, TEXT("pane_id"));
+ if (Cells.bSnapshot)
+ {
+ Screens.ApplyMeta(F.Data);
+ }
+ if (!Screens.ApplyFrame(Cells, PaneId))
+ {
+ Resync(TEXT("screens"), PaneId);
+ }
+ }
+ else
+ {
+ UE_LOG(LogVerseBridge, Warning, TEXT("bridge: bad screens.frame (%s)"), *Error);
+ }
+ }
+ OnFrame.Broadcast(F);
+}
+
+void FVerseBridgeClient::HandleBinary(const TArray<uint8>& Bytes, double Now)
+{
+ LastFrameAt = Now;
+ FVerseCellsFrame Cells;
+ FString Error;
+ if (!FVerseCellsFrame::Decode(Bytes, Cells, &Error))
+ {
+ UE_LOG(LogVerseBridge, Warning, TEXT("bridge: bad cells.bin/1 frame (%s)"), *Error);
+ return;
+ }
+ LastSeq = FMath::Max<int64>(LastSeq, Cells.Seq);
+ const FString PaneId = Screens.PaneForRef(Cells.Ref);
+ if (!Screens.ApplyFrame(Cells) && !PaneId.IsEmpty())
+ {
+ Resync(TEXT("screens"), PaneId);
+ }
+}
diff --git a/unreal/Verse/Source/VerseBridge/Private/Bridge/VerseBridgeCodec.cpp b/unreal/Verse/Source/VerseBridge/Private/Bridge/VerseBridgeCodec.cpp
new file mode 100644
index 0000000000..d6774e94bb
--- /dev/null
+++ b/unreal/Verse/Source/VerseBridge/Private/Bridge/VerseBridgeCodec.cpp
@@ -0,0 +1,239 @@
+#include "Bridge/VerseBridgeCodec.h"
+
+#include "Policies/CondensedJsonPrintPolicy.h"
+#include "Serialization/JsonReader.h"
+#include "Serialization/JsonSerializer.h"
+#include "Serialization/JsonWriter.h"
+
+namespace
+{
+ bool ReadInt(const TSharedPtr<FJsonObject>& O, const TCHAR* Field, int64& Out)
+ {
+ const TSharedPtr<FJsonValue> V = O->TryGetField(Field);
+ if (!V.IsValid() || V->Type != EJson::Number)
+ {
+ return false;
+ }
+ Out = static_cast<int64>(V->AsNumber());
+ return true;
+ }
+}
+
+bool FVerseBridgeFrame::Parse(const FString& Text, FVerseBridgeFrame& Out, FString* OutError)
+{
+ auto Fail = [OutError](const TCHAR* Why)
+ {
+ if (OutError)
+ {
+ *OutError = Why;
+ }
+ return false;
+ };
+ TSharedPtr<FJsonObject> Root = VerseBridgeJson::Read(Text);
+ if (!Root.IsValid())
+ {
+ return Fail(TEXT("frame is not a JSON object"));
+ }
+ FString Type;
+ if (!Root->TryGetStringField(TEXT("type"), Type) || Type.IsEmpty())
+ {
+ return Fail(TEXT("frame has no type"));
+ }
+ Out = FVerseBridgeFrame();
+ Out.Type = Type;
+ const TSharedPtr<FJsonValue> DataValue = Root->TryGetField(TEXT("data"));
+ if (!DataValue.IsValid() || DataValue->Type == EJson::Null)
+ {
+ Out.Data = MakeShared<FJsonObject>();
+ }
+ else if (DataValue->Type == EJson::Object)
+ {
+ Out.Data = DataValue->AsObject();
+ }
+ else
+ {
+ return Fail(TEXT("data is not an object"));
+ }
+ ReadInt(Root, TEXT("seq"), Out.Seq);
+ ReadInt(Root, TEXT("base"), Out.Base);
+ Root->TryGetStringField(TEXT("id"), Out.Id);
+ Root->TryGetStringField(TEXT("re"), Out.Re);
+ Root->TryGetNumberField(TEXT("ts"), Out.Ts);
+ return true;
+}
+
+FString FVerseBridgeFrame::Encode() const
+{
+ FString Out;
+ TSharedRef<TJsonWriter<TCHAR, TCondensedJsonPrintPolicy<TCHAR>>> W = TJsonWriterFactory<TCHAR, TCondensedJsonPrintPolicy<TCHAR>>::Create(&Out);
+ W->WriteObjectStart();
+ W->WriteValue(TEXT("type"), Type);
+ if (Seq >= 0)
+ {
+ W->WriteValue(TEXT("seq"), Seq);
+ }
+ if (Base >= 0)
+ {
+ W->WriteValue(TEXT("base"), Base);
+ }
+ if (!Re.IsEmpty())
+ {
+ W->WriteValue(TEXT("re"), Re);
+ }
+ if (!Id.IsEmpty())
+ {
+ W->WriteValue(TEXT("id"), Id);
+ }
+ W->WriteValue(TEXT("ts"), Ts);
+ W->WriteIdentifierPrefix(TEXT("data"));
+ FJsonSerializer::Serialize(Data.IsValid() ? Data.ToSharedRef() : MakeShared<FJsonObject>(), W, false);
+ W->WriteObjectEnd();
+ W->Close();
+ return Out;
+}
+
+FVerseBridgeFrame FVerseBridgeFrame::Make(const FString& InType, TSharedPtr<FJsonObject> InData, const FString& InId)
+{
+ FVerseBridgeFrame F;
+ F.Type = InType;
+ F.Id = InId;
+ F.Ts = FDateTime::UtcNow().ToUnixTimestampDecimal();
+ F.Data = InData.IsValid() ? InData : MakeShared<FJsonObject>();
+ return F;
+}
+
+namespace VerseBridgeJson
+{
+ bool Equal(const TSharedPtr<FJsonObject>& A, const TSharedPtr<FJsonObject>& B)
+ {
+ if (!A.IsValid() || !B.IsValid())
+ {
+ return A.IsValid() == B.IsValid();
+ }
+ if (A->Values.Num() != B->Values.Num())
+ {
+ return false;
+ }
+ for (const TPair<FString, TSharedPtr<FJsonValue>>& Pair : A->Values)
+ {
+ const TSharedPtr<FJsonValue>* Other = B->Values.Find(Pair.Key);
+ if (!Other || !Equal(Pair.Value, *Other))
+ {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ bool Equal(const TSharedPtr<FJsonValue>& A, const TSharedPtr<FJsonValue>& B)
+ {
+ if (!A.IsValid() || !B.IsValid())
+ {
+ return A.IsValid() == B.IsValid();
+ }
+ if (A->Type != B->Type)
+ {
+ return false;
+ }
+ switch (A->Type)
+ {
+ case EJson::Null:
+ return true;
+ case EJson::String:
+ return A->AsString() == B->AsString();
+ case EJson::Number:
+ return A->AsNumber() == B->AsNumber();
+ case EJson::Boolean:
+ return A->AsBool() == B->AsBool();
+ case EJson::Array:
+ {
+ const TArray<TSharedPtr<FJsonValue>>& X = A->AsArray();
+ const TArray<TSharedPtr<FJsonValue>>& Y = B->AsArray();
+ if (X.Num() != Y.Num())
+ {
+ return false;
+ }
+ for (int32 I = 0; I < X.Num(); ++I)
+ {
+ if (!Equal(X[I], Y[I]))
+ {
+ return false;
+ }
+ }
+ return true;
+ }
+ case EJson::Object:
+ return Equal(A->AsObject(), B->AsObject());
+ default:
+ return false;
+ }
+ }
+
+ FString Write(const TSharedPtr<FJsonObject>& Object)
+ {
+ FString Out;
+ TSharedRef<TJsonWriter<TCHAR, TCondensedJsonPrintPolicy<TCHAR>>> W = TJsonWriterFactory<TCHAR, TCondensedJsonPrintPolicy<TCHAR>>::Create(&Out);
+ FJsonSerializer::Serialize(Object.IsValid() ? Object.ToSharedRef() : MakeShared<FJsonObject>(), W);
+ return Out;
+ }
+
+ TSharedPtr<FJsonObject> Read(const FString& Text)
+ {
+ TSharedPtr<FJsonObject> Root;
+ TSharedRef<TJsonReader<TCHAR>> Reader = TJsonReaderFactory<TCHAR>::Create(Text);
+ if (!FJsonSerializer::Deserialize(Reader, Root) || !Root.IsValid())
+ {
+ return nullptr;
+ }
+ return Root;
+ }
+
+ FString Str(const TSharedPtr<FJsonObject>& O, const TCHAR* Field, const FString& Default)
+ {
+ FString V;
+ return O.IsValid() && O->TryGetStringField(Field, V) ? V : Default;
+ }
+
+ int64 Int(const TSharedPtr<FJsonObject>& O, const TCHAR* Field, int64 Default)
+ {
+ double V = 0.0;
+ return O.IsValid() && O->TryGetNumberField(Field, V) ? static_cast<int64>(V) : Default;
+ }
+
+ double Num(const TSharedPtr<FJsonObject>& O, const TCHAR* Field, double Default)
+ {
+ double V = 0.0;
+ return O.IsValid() && O->TryGetNumberField(Field, V) ? V : Default;
+ }
+
+ bool Bool(const TSharedPtr<FJsonObject>& O, const TCHAR* Field, bool Default)
+ {
+ bool V = false;
+ return O.IsValid() && O->TryGetBoolField(Field, V) ? V : Default;
+ }
+
+ TSharedPtr<FJsonObject> Obj(const TSharedPtr<FJsonObject>& O, const TCHAR* Field)
+ {
+ const TSharedPtr<FJsonObject>* V = nullptr;
+ return O.IsValid() && O->TryGetObjectField(Field, V) && V ? *V : nullptr;
+ }
+
+ const TArray<TSharedPtr<FJsonValue>>* Arr(const TSharedPtr<FJsonObject>& O, const TCHAR* Field)
+ {
+ const TArray<TSharedPtr<FJsonValue>>* V = nullptr;
+ return O.IsValid() && O->TryGetArrayField(Field, V) ? V : nullptr;
+ }
+
+ FString Enum(const TSharedPtr<FJsonObject>& O, const TCHAR* Field, std::initializer_list<const TCHAR*> Allowed, const TCHAR* Fallback)
+ {
+ const FString V = Str(O, Field);
+ for (const TCHAR* A : Allowed)
+ {
+ if (V == A)
+ {
+ return V;
+ }
+ }
+ return Fallback;
+ }
+}
diff --git a/unreal/Verse/Source/VerseBridge/Private/Bridge/VerseBridgeFeeds.cpp b/unreal/Verse/Source/VerseBridge/Private/Bridge/VerseBridgeFeeds.cpp
new file mode 100644
index 0000000000..10f84afa0a
--- /dev/null
+++ b/unreal/Verse/Source/VerseBridge/Private/Bridge/VerseBridgeFeeds.cpp
@@ -0,0 +1,460 @@
+#include "Bridge/VerseBridgeFeeds.h"
+
+#include "Bridge/VerseBridgeCodec.h"
+
+using namespace VerseBridgeJson;
+
+namespace
+{
+ TArray<FString> Strings(const TSharedPtr<FJsonObject>& O, const TCHAR* Field)
+ {
+ TArray<FString> Out;
+ if (const TArray<TSharedPtr<FJsonValue>>* A = Arr(O, Field))
+ {
+ for (const TSharedPtr<FJsonValue>& V : *A)
+ {
+ Out.Add(V->AsString());
+ }
+ }
+ return Out;
+ }
+}
+
+FVerseAgent FVerseAgent::FromJson(const TSharedPtr<FJsonObject>& O)
+{
+ FVerseAgent A;
+ A.AgentId = Str(O, TEXT("agent_id"));
+ A.Name = Str(O, TEXT("name"));
+ A.Title = Str(O, TEXT("title"));
+ A.Tier = Str(O, TEXT("tier"));
+ A.Lifecycle = Enum(O, TEXT("lifecycle"), {TEXT("active"), TEXT("paused")}, TEXT("active"));
+ A.RunState = Enum(O, TEXT("run_state"), {TEXT("paused"), TEXT("waiting"), TEXT("working"), TEXT("idle")}, TEXT("idle"));
+ A.WaitingReason = Str(O, TEXT("waiting_reason"));
+ A.Duty = Enum(O, TEXT("duty"), {TEXT("working"), TEXT("waiting"), TEXT("idle"), TEXT("paused"), TEXT("error")}, TEXT("idle"));
+ A.Level = int32(Int(O, TEXT("level"), 1));
+ A.Rank = Str(O, TEXT("rank"), TEXT("recruit"));
+ A.Look = Str(O, TEXT("look"));
+ const TSharedPtr<FJsonObject> Figure = Obj(O, TEXT("figure"));
+ A.Archetype = Str(Figure, TEXT("archetype"));
+ A.Palette = Str(Figure, TEXT("palette"));
+ A.TeamIds = Strings(O, TEXT("team_ids"));
+ A.PaneId = Str(O, TEXT("pane"));
+ return A;
+}
+
+FVersePane FVersePane::FromJson(const TSharedPtr<FJsonObject>& O)
+{
+ FVersePane P;
+ P.PaneId = Str(O, TEXT("pane_id"));
+ P.WorkspaceId = Str(O, TEXT("workspace_id"));
+ P.Key = Str(O, TEXT("key"));
+ P.Name = Str(O, TEXT("name"));
+ P.DisplayName = Str(O, TEXT("display_name"));
+ P.Agent = Str(O, TEXT("agent"));
+ P.Title = Str(O, TEXT("title"));
+ P.Status = Enum(O, TEXT("status"), {TEXT("pending"), TEXT("live"), TEXT("exited"), TEXT("error")}, TEXT("pending"));
+ P.Activity = Enum(O, TEXT("activity"),
+ {TEXT("starting"), TEXT("working"), TEXT("waiting"), TEXT("asking"), TEXT("failed"), TEXT("exited"), TEXT("stopped"), TEXT("unknown"), TEXT("")},
+ TEXT("unknown"));
+ P.ActivitySince = Num(O, TEXT("activity_since"));
+ P.bWorked = Bool(O, TEXT("worked"));
+ P.Duty = Enum(O, TEXT("duty"), {TEXT("working"), TEXT("waiting"), TEXT("idle"), TEXT("paused"), TEXT("error")}, TEXT("idle"));
+ P.bWorkspaceActive = Bool(O, TEXT("workspace_active"));
+ P.Cols = int32(Int(O, TEXT("cols"), 80));
+ P.Rows = int32(Int(O, TEXT("rows"), 24));
+ return P;
+}
+
+void FVerseKeyedRows::Replace(const TArray<TSharedPtr<FJsonValue>>* List, const TCHAR* IdField)
+{
+ Rows.Reset();
+ Upsert(List, IdField);
+}
+
+void FVerseKeyedRows::Upsert(const TArray<TSharedPtr<FJsonValue>>* List, const TCHAR* IdField)
+{
+ if (!List)
+ {
+ return;
+ }
+ for (const TSharedPtr<FJsonValue>& V : *List)
+ {
+ const TSharedPtr<FJsonObject> Row = V.IsValid() ? V->AsObject() : nullptr;
+ const FString Id = Str(Row, IdField);
+ if (Id.IsEmpty())
+ {
+ continue;
+ }
+ TSharedPtr<FJsonObject>& Held = Rows.FindOrAdd(Id);
+ if (!Held.IsValid())
+ {
+ Held = MakeShared<FJsonObject>();
+ }
+ for (const TPair<FString, TSharedPtr<FJsonValue>>& Field : Row->Values)
+ {
+ Held->Values.Add(Field.Key, Field.Value);
+ }
+ }
+}
+
+void FVerseKeyedRows::Remove(const TArray<TSharedPtr<FJsonValue>>* Ids)
+{
+ if (!Ids)
+ {
+ return;
+ }
+ for (const TSharedPtr<FJsonValue>& V : *Ids)
+ {
+ Rows.Remove(V->AsString());
+ }
+}
+
+void FVerseRosterFeed::ReadCommander(const TSharedPtr<FJsonObject>& O)
+{
+ if (!O.IsValid())
+ {
+ return;
+ }
+ Commander.Level = int32(Int(O, TEXT("level"), 1));
+ Commander.Rank = Str(O, TEXT("rank"), TEXT("recruit"));
+ Commander.Title = Str(O, TEXT("title"));
+ Commander.Uniform = Str(O, TEXT("uniform"), TEXT("standard"));
+}
+
+void FVerseRosterFeed::ApplySnapshot(const TSharedPtr<FJsonObject>& Data)
+{
+ Agents.Replace(Arr(Data, TEXT("agents")), TEXT("agent_id"));
+ Panes.Replace(Arr(Data, TEXT("panes")), TEXT("pane_id"));
+ ReadCommander(Obj(Data, TEXT("commander")));
+ bHasSnapshot = true;
+ OnChanged.Broadcast();
+}
+
+void FVerseRosterFeed::ApplyDelta(const TSharedPtr<FJsonObject>& Data)
+{
+ const TSharedPtr<FJsonObject> Up = Obj(Data, TEXT("upsert"));
+ const TSharedPtr<FJsonObject> Rm = Obj(Data, TEXT("remove"));
+ Agents.Upsert(Arr(Up, TEXT("agents")), TEXT("agent_id"));
+ Panes.Upsert(Arr(Up, TEXT("panes")), TEXT("pane_id"));
+ Agents.Remove(Arr(Rm, TEXT("agents")));
+ Panes.Remove(Arr(Rm, TEXT("panes")));
+ ReadCommander(Obj(Data, TEXT("commander")));
+ OnChanged.Broadcast();
+}
+
+TArray<FVerseAgent> FVerseRosterFeed::GetAgents() const
+{
+ TArray<FVerseAgent> Out;
+ for (const TPair<FString, TSharedPtr<FJsonObject>>& P : Agents.Get())
+ {
+ Out.Add(FVerseAgent::FromJson(P.Value));
+ }
+ Out.Sort([](const FVerseAgent& A, const FVerseAgent& B) { return A.AgentId < B.AgentId; });
+ return Out;
+}
+
+TArray<FVersePane> FVerseRosterFeed::GetPanes() const
+{
+ TArray<FVersePane> Out;
+ for (const TPair<FString, TSharedPtr<FJsonObject>>& P : Panes.Get())
+ {
+ Out.Add(FVersePane::FromJson(P.Value));
+ }
+ Out.Sort([](const FVersePane& A, const FVersePane& B) { return A.PaneId < B.PaneId; });
+ return Out;
+}
+
+bool FVerseRosterFeed::FindAgent(const FString& AgentId, FVerseAgent& Out) const
+{
+ if (const TSharedPtr<FJsonObject>* Row = Agents.Get().Find(AgentId))
+ {
+ Out = FVerseAgent::FromJson(*Row);
+ return true;
+ }
+ return false;
+}
+
+bool FVerseRosterFeed::FindPane(const FString& PaneId, FVersePane& Out) const
+{
+ if (const TSharedPtr<FJsonObject>* Row = Panes.Get().Find(PaneId))
+ {
+ Out = FVersePane::FromJson(*Row);
+ return true;
+ }
+ return false;
+}
+
+void FVerseGroupsFeed::ApplySnapshot(const TSharedPtr<FJsonObject>& Data)
+{
+ Groups.Replace(Arr(Data, TEXT("groups")), TEXT("group_id"));
+ OnChanged.Broadcast();
+}
+
+void FVerseGroupsFeed::ApplyDelta(const TSharedPtr<FJsonObject>& Data)
+{
+ Groups.Upsert(Arr(Obj(Data, TEXT("upsert")), TEXT("groups")), TEXT("group_id"));
+ Groups.Remove(Arr(Obj(Data, TEXT("remove")), TEXT("groups")));
+ OnChanged.Broadcast();
+}
+
+void FVerseGroupsFeed::ApplyMeeting(const TSharedPtr<FJsonObject>& Data)
+{
+ const FString Id = Str(Data, TEXT("group_id"));
+ if (Id.IsEmpty())
+ {
+ return;
+ }
+ Meetings.Add(Id, Data);
+ OnMeeting.Broadcast(Id);
+}
+
+void FVerseScreensFeed::Bind(const TSharedPtr<FJsonObject>& Result)
+{
+ Refs.Reset();
+ if (const TArray<TSharedPtr<FJsonValue>>* Bound = Arr(Result, TEXT("bound")))
+ {
+ for (const TSharedPtr<FJsonValue>& V : *Bound)
+ {
+ const TSharedPtr<FJsonObject> B = V->AsObject();
+ Refs.Add(uint16(Int(B, TEXT("ref"))), Str(B, TEXT("pane_id")));
+ }
+ }
+ TArray<FString> Gone;
+ for (const TPair<FString, FVerseScreen>& S : Screens)
+ {
+ bool bKept = false;
+ for (const TPair<uint16, FString>& R : Refs)
+ {
+ bKept |= R.Value == S.Key;
+ }
+ if (!bKept)
+ {
+ Gone.Add(S.Key);
+ }
+ }
+ for (const FString& G : Gone)
+ {
+ Screens.Remove(G);
+ }
+}
+
+FString FVerseScreensFeed::PaneForRef(uint16 Ref) const
+{
+ const FString* P = Refs.Find(Ref);
+ return P ? *P : FString();
+}
+
+void FVerseScreensFeed::ApplyMeta(const TSharedPtr<FJsonObject>& Data)
+{
+ const FString PaneId = Str(Data, TEXT("pane_id"));
+ if (PaneId.IsEmpty())
+ {
+ return;
+ }
+ const uint16 Ref = uint16(Int(Data, TEXT("ref")));
+ if (Ref)
+ {
+ Refs.Add(Ref, PaneId);
+ }
+ FVerseScreen& S = Screens.FindOrAdd(PaneId);
+ S.PaneId = PaneId;
+ S.bStyled = Str(Data, TEXT("style"), TEXT("styled")) != TEXT("plain");
+ S.bCut = Bool(Data, TEXT("cut"));
+ S.At = Num(Data, TEXT("at"));
+}
+
+bool FVerseScreensFeed::ApplyFrame(const FVerseCellsFrame& Frame, const FString& PaneIdOverride)
+{
+ const FString PaneId = PaneIdOverride.IsEmpty() ? PaneForRef(Frame.Ref) : PaneIdOverride;
+ if (PaneId.IsEmpty())
+ {
+ return true;
+ }
+ FVerseScreen& S = Screens.FindOrAdd(PaneId);
+ if (!Frame.bSnapshot && (S.LastSeq == 0 || Frame.Base != S.LastSeq))
+ {
+ return false;
+ }
+ S.PaneId = PaneId;
+ if (Frame.bSnapshot)
+ {
+ S.Lines.Reset();
+ }
+ S.Cols = Frame.Cols;
+ S.Rows = Frame.Rows;
+ S.CursorRow = Frame.CursorRow;
+ S.CursorCol = Frame.CursorCol;
+ for (const FVerseCellRow& Row : Frame.RowsChanged)
+ {
+ if (Row.Runs.Num() == 0)
+ {
+ S.Lines.Remove(Row.Row);
+ }
+ else
+ {
+ S.Lines.Add(Row.Row, Row);
+ }
+ }
+ TArray<uint16> Outside;
+ for (const TPair<uint16, FVerseCellRow>& L : S.Lines)
+ {
+ if (L.Key >= S.Rows)
+ {
+ Outside.Add(L.Key);
+ }
+ }
+ for (uint16 R : Outside)
+ {
+ S.Lines.Remove(R);
+ }
+ S.LastSeq = Frame.Seq;
+ OnFrame.Broadcast(PaneId);
+ return true;
+}
+
+void FVerseScreensFeed::ApplyGone(const TSharedPtr<FJsonObject>& Data)
+{
+ const FString PaneId = Str(Data, TEXT("pane_id"));
+ Screens.Remove(PaneId);
+ OnGone.Broadcast(PaneId, Str(Data, TEXT("reason"), TEXT("closed")));
+}
+
+void FVerseScreensFeed::Reset()
+{
+ Refs.Reset();
+ Screens.Reset();
+}
+
+void FVerseChatTailsFeed::Apply(const TSharedPtr<FJsonObject>& Data)
+{
+ const FString Agent = Str(Data, TEXT("agent_id"));
+ const FString Version = Str(Data, TEXT("version"));
+ if (Agent.IsEmpty() || (Versions.Contains(Agent) && Versions[Agent] == Version && !Version.IsEmpty()))
+ {
+ return;
+ }
+ Versions.Add(Agent, Version);
+ TArray<FVerseChatLine>& Out = Lines.FindOrAdd(Agent);
+ Out.Reset();
+ if (const TArray<TSharedPtr<FJsonValue>>* L = Arr(Data, TEXT("lines")))
+ {
+ for (const TSharedPtr<FJsonValue>& V : *L)
+ {
+ const TSharedPtr<FJsonObject> Line = V->AsObject();
+ Out.Add({Enum(Line, TEXT("kind"), {TEXT("user"), TEXT("agent"), TEXT("tool"), TEXT("notice"), TEXT("error")}, TEXT("notice")),
+ Str(Line, TEXT("text"))});
+ }
+ }
+ OnUpdate.Broadcast(Agent);
+}
+
+void FVerseProgressionFeed::ApplySnapshot(const TSharedPtr<FJsonObject>& Data)
+{
+ Snapshot = Data;
+ ToldSeq = FMath::Max(ToldSeq, Int(Data, TEXT("told_seq")));
+ OnChanged.Broadcast();
+}
+
+void FVerseProgressionFeed::ApplyAward(const TSharedPtr<FJsonObject>& Data)
+{
+ if (Snapshot.IsValid())
+ {
+ const FString Subject = Str(Data, TEXT("subject_id"));
+ if (const TArray<TSharedPtr<FJsonValue>>* Subjects = Arr(Snapshot, TEXT("subjects")))
+ {
+ for (const TSharedPtr<FJsonValue>& V : *Subjects)
+ {
+ const TSharedPtr<FJsonObject> S = V->AsObject();
+ if (Str(S, TEXT("subject_id")) == Subject)
+ {
+ S->SetNumberField(TEXT("level"), double(Int(Data, TEXT("level"), 1)));
+ S->SetNumberField(TEXT("total_xp"), double(Int(Data, TEXT("total_xp"))));
+ S->SetStringField(TEXT("title"), Str(Data, TEXT("title")));
+ }
+ }
+ }
+ Snapshot->SetNumberField(TEXT("latest_seq"), double(FMath::Max(Int(Snapshot, TEXT("latest_seq")), Int(Data, TEXT("seq")))));
+ }
+ OnAward.Broadcast(Data);
+ OnChanged.Broadcast();
+}
+
+int32 FVerseProgressionFeed::LevelOf(const FString& SubjectId) const
+{
+ if (const TArray<TSharedPtr<FJsonValue>>* Subjects = Arr(Snapshot, TEXT("subjects")))
+ {
+ for (const TSharedPtr<FJsonValue>& V : *Subjects)
+ {
+ if (Str(V->AsObject(), TEXT("subject_id")) == SubjectId)
+ {
+ return int32(Int(V->AsObject(), TEXT("level"), 1));
+ }
+ }
+ }
+ return 1;
+}
+
+void FVerseCompanionFeed::Apply(const TSharedPtr<FJsonObject>& Data)
+{
+ PetId = Str(Data, TEXT("pet_id"));
+ Look = Str(Data, TEXT("look"));
+ Style = Str(Data, TEXT("style"), TEXT("default"));
+ OnChanged.Broadcast();
+}
+
+void FVerseSettingsFeed::ApplyWelcome(const TSharedPtr<FJsonObject>& Welcome)
+{
+ const TSharedPtr<FJsonObject> Locale = Obj(Welcome, TEXT("locale"));
+ Lang = Str(Locale, TEXT("lang"), TEXT("en"));
+ Strings.Reset();
+ if (const TSharedPtr<FJsonObject> S = Obj(Locale, TEXT("strings")))
+ {
+ for (const TPair<FString, TSharedPtr<FJsonValue>>& P : S->Values)
+ {
+ Strings.Add(P.Key, P.Value->AsString());
+ }
+ }
+ if (const TSharedPtr<FJsonObject> Set = Obj(Welcome, TEXT("settings")))
+ {
+ Settings = Set;
+ }
+ OnChanged.Broadcast();
+}
+
+void FVerseSettingsFeed::ApplyChanged(const TSharedPtr<FJsonObject>& Data)
+{
+ if (!Data.IsValid())
+ {
+ return;
+ }
+ for (const TPair<FString, TSharedPtr<FJsonValue>>& P : Data->Values)
+ {
+ if (P.Key == TEXT("lang"))
+ {
+ Lang = P.Value->AsString();
+ }
+ else if (P.Key == TEXT("strings") && P.Value->Type == EJson::Object)
+ {
+ for (const TPair<FString, TSharedPtr<FJsonValue>>& S : P.Value->AsObject()->Values)
+ {
+ Strings.Add(S.Key, S.Value->AsString());
+ }
+ }
+ else
+ {
+ Settings->Values.Add(P.Key, P.Value);
+ }
+ }
+ OnChanged.Broadcast();
+}
+
+FString FVerseSettingsFeed::Text(const FString& Key) const
+{
+ const FString* S = Strings.Find(Key);
+ return S ? *S : Key;
+}
+
+FString FVerseSettingsFeed::ReturnKey() const
+{
+ return Str(Settings, TEXT("return_key"), TEXT("F10"));
+}
diff --git a/unreal/Verse/Source/VerseBridge/Private/Bridge/VerseCellsCodec.cpp b/unreal/Verse/Source/VerseBridge/Private/Bridge/VerseCellsCodec.cpp
new file mode 100644
index 0000000000..567b4b3867
--- /dev/null
+++ b/unreal/Verse/Source/VerseBridge/Private/Bridge/VerseCellsCodec.cpp
@@ -0,0 +1,467 @@
+#include "Bridge/VerseCellsCodec.h"
+
+#include "Bridge/VerseBridgeCodec.h"
+
+namespace
+{
+ /** Decodes one UTF-8 code point; returns its byte length, or 0 when malformed. */
+ int32 DecodeOne(const uint8* P, int32 Left, uint32& Cp)
+ {
+ const uint8 B0 = P[0];
+ if (B0 < 0x80)
+ {
+ Cp = B0;
+ return 1;
+ }
+ int32 Len = 0;
+ if ((B0 & 0xE0) == 0xC0)
+ {
+ Len = 2;
+ Cp = B0 & 0x1F;
+ }
+ else if ((B0 & 0xF0) == 0xE0)
+ {
+ Len = 3;
+ Cp = B0 & 0x0F;
+ }
+ else if ((B0 & 0xF8) == 0xF0)
+ {
+ Len = 4;
+ Cp = B0 & 0x07;
+ }
+ else
+ {
+ return 0;
+ }
+ if (Left < Len)
+ {
+ return 0;
+ }
+ for (int32 I = 1; I < Len; ++I)
+ {
+ if ((P[I] & 0xC0) != 0x80)
+ {
+ return 0;
+ }
+ Cp = (Cp << 6) | (P[I] & 0x3F);
+ }
+ static const uint32 Min[5] = {0, 0, 0x80, 0x800, 0x10000};
+ if (Cp < Min[Len] || Cp > 0x10FFFF || (Cp >= 0xD800 && Cp <= 0xDFFF))
+ {
+ return 0;
+ }
+ return Len;
+ }
+
+ /** Unicode categories Mn, Me, Mc in the blocks terminal text uses, plus the joiners. */
+ bool Extends(uint32 Cp)
+ {
+ return (Cp >= 0x0300 && Cp <= 0x036F) || (Cp >= 0x0483 && Cp <= 0x0489) || (Cp >= 0x0591 && Cp <= 0x05BD)
+ || (Cp >= 0x0610 && Cp <= 0x061A) || (Cp >= 0x064B && Cp <= 0x065F) || (Cp >= 0x0900 && Cp <= 0x0903)
+ || (Cp >= 0x093A && Cp <= 0x094F) || (Cp >= 0x0E31 && Cp <= 0x0E3A && Cp != 0x0E32 && Cp != 0x0E33)
+ || (Cp >= 0x1AB0 && Cp <= 0x1AFF) || (Cp >= 0x1DC0 && Cp <= 0x1DFF) || (Cp >= 0x20D0 && Cp <= 0x20FF)
+ || (Cp >= 0x302A && Cp <= 0x302F) || (Cp >= 0x3099 && Cp <= 0x309A) || (Cp >= 0xFE20 && Cp <= 0xFE2F)
+ || Cp == 0x200D || (Cp >= 0xFE00 && Cp <= 0xFE0F) || (Cp >= 0x1F3FB && Cp <= 0x1F3FF)
+ || (Cp >= 0xE0020 && Cp <= 0xE007F) || (Cp >= 0xE0100 && Cp <= 0xE01EF);
+ }
+
+ struct FReader
+ {
+ const TArray<uint8>& B;
+ int32 Off = 0;
+ bool bOk = true;
+
+ bool Has(int32 N) const { return Off + N <= B.Num(); }
+ uint8 U8() { return bOk && Has(1) ? B[Off++] : (bOk = false, 0); }
+ uint16 U16()
+ {
+ if (!bOk || !Has(2))
+ {
+ bOk = false;
+ return 0;
+ }
+ const uint16 V = uint16(B[Off]) | (uint16(B[Off + 1]) << 8);
+ Off += 2;
+ return V;
+ }
+ uint32 U32()
+ {
+ const uint32 Lo = U16();
+ const uint32 Hi = U16();
+ return Lo | (Hi << 16);
+ }
+ };
+
+ void W16(TArray<uint8>& O, uint16 V)
+ {
+ O.Add(uint8(V & 0xFF));
+ O.Add(uint8(V >> 8));
+ }
+
+ void W32(TArray<uint8>& O, uint32 V)
+ {
+ W16(O, uint16(V & 0xFFFF));
+ W16(O, uint16(V >> 16));
+ }
+
+ bool ColourValid(uint32 C)
+ {
+ const uint32 M = C >> 24;
+ const uint32 Low = C & 0xFFFFFF;
+ return (M == 0 && Low == 0) || (M == 1 && Low <= 0xFF) || M == 2;
+ }
+
+ static const TCHAR* AttrNames[] = {TEXT("bold"), TEXT("dim"), TEXT("italic"), TEXT("underline"), TEXT("inverse"),
+ TEXT("strikethrough"), TEXT("invisible"), TEXT("blink"), TEXT("wide")};
+}
+
+int32 VerseCells::CountGraphemes(const uint8* Utf8, int32 Bytes, bool* bValidUtf8)
+{
+ int32 Count = 0;
+ bool bJoinNext = false;
+ int32 I = 0;
+ while (I < Bytes)
+ {
+ uint32 Cp = 0;
+ const int32 Len = DecodeOne(Utf8 + I, Bytes - I, Cp);
+ if (Len == 0)
+ {
+ if (bValidUtf8)
+ {
+ *bValidUtf8 = false;
+ }
+ return -1;
+ }
+ I += Len;
+ if (Count > 0 && (bJoinNext || Extends(Cp)))
+ {
+ // Extends the previous cluster.
+ }
+ else
+ {
+ ++Count;
+ }
+ bJoinNext = Cp == 0x200D;
+ }
+ if (bValidUtf8)
+ {
+ *bValidUtf8 = true;
+ }
+ return Count;
+}
+
+bool FVerseCellsFrame::CheckRows(FString* OutError) const
+{
+ auto Fail = [OutError](const FString& Why)
+ {
+ if (OutError)
+ {
+ *OutError = Why;
+ }
+ return false;
+ };
+ if (Cols < 1 || Cols > VerseCells::MaxCols || Rows < 1 || Rows > VerseCells::MaxRows)
+ {
+ return Fail(FString::Printf(TEXT("grid %dx%d outside the limits"), Cols, Rows));
+ }
+ TSet<uint16> Seen;
+ for (const FVerseCellRow& R : RowsChanged)
+ {
+ if (R.Row >= Rows)
+ {
+ return Fail(FString::Printf(TEXT("row %d outside the grid"), R.Row));
+ }
+ if (Seen.Contains(R.Row))
+ {
+ return Fail(FString::Printf(TEXT("row %d sent twice"), R.Row));
+ }
+ Seen.Add(R.Row);
+ int32 End = 0;
+ for (const FVerseCellRun& Run : R.Runs)
+ {
+ if (Run.Utf8.Num() == 0 || Run.Cells == 0)
+ {
+ return Fail(FString::Printf(TEXT("row %d: empty run"), R.Row));
+ }
+ if (Run.Col < End)
+ {
+ return Fail(FString::Printf(TEXT("row %d: run at col %d overlaps"), R.Row, Run.Col));
+ }
+ End = Run.Col + Run.Span();
+ if (End > Cols)
+ {
+ return Fail(FString::Printf(TEXT("row %d: run past the last column"), R.Row));
+ }
+ }
+ }
+ return true;
+}
+
+bool FVerseCellsFrame::Decode(const TArray<uint8>& Blob, FVerseCellsFrame& Out, FString* OutError)
+{
+ auto Fail = [OutError](const FString& Why)
+ {
+ if (OutError)
+ {
+ *OutError = Why;
+ }
+ return false;
+ };
+ if (Blob.Num() < VerseCells::HeaderSize)
+ {
+ return Fail(TEXT("shorter than the header"));
+ }
+ FReader R{Blob};
+ const uint8 M0 = R.U8();
+ const uint8 M1 = R.U8();
+ if (M0 != 'V' || M1 != 'C')
+ {
+ return Fail(TEXT("bad magic"));
+ }
+ if (R.U8() != 1)
+ {
+ return Fail(TEXT("unsupported version"));
+ }
+ const uint8 Kind = R.U8();
+ if (Kind != 1 && Kind != 2)
+ {
+ return Fail(TEXT("bad kind"));
+ }
+ Out = FVerseCellsFrame();
+ Out.bSnapshot = Kind == 1;
+ Out.Ref = R.U16();
+ Out.Seq = R.U32();
+ Out.Base = R.U32();
+ Out.Cols = R.U16();
+ Out.Rows = R.U16();
+ Out.CursorRow = int16(R.U16());
+ Out.CursorCol = int16(R.U16());
+ const uint16 Count = R.U16();
+ if (Out.bSnapshot && Out.Base != 0)
+ {
+ return Fail(TEXT("a snapshot carries base 0"));
+ }
+ const bool bHidden = Out.CursorRow == -1 && Out.CursorCol == -1;
+ if (!bHidden && (Out.CursorRow < 0 || Out.CursorRow >= Out.Rows || Out.CursorCol < 0 || Out.CursorCol >= Out.Cols))
+ {
+ return Fail(TEXT("cursor outside the grid"));
+ }
+ for (int32 I = 0; I < Count; ++I)
+ {
+ if (!R.Has(4))
+ {
+ return Fail(TEXT("truncated row record"));
+ }
+ FVerseCellRow& Row = Out.RowsChanged.AddDefaulted_GetRef();
+ Row.Row = R.U16();
+ const uint16 RunCount = R.U16();
+ for (int32 J = 0; J < RunCount; ++J)
+ {
+ if (!R.Has(16))
+ {
+ return Fail(TEXT("truncated run"));
+ }
+ FVerseCellRun& Run = Row.Runs.AddDefaulted_GetRef();
+ Run.Col = R.U16();
+ Run.Cells = R.U16();
+ Run.Fg = R.U32();
+ Run.Bg = R.U32();
+ Run.Attrs = R.U16();
+ const uint16 Bytes = R.U16();
+ if (!R.Has(Bytes))
+ {
+ return Fail(TEXT("run text runs past the end of the frame"));
+ }
+ if (!ColourValid(Run.Fg) || !ColourValid(Run.Bg))
+ {
+ return Fail(TEXT("bad colour"));
+ }
+ if (Run.Attrs & ~VerseCells::AllAttrs)
+ {
+ return Fail(TEXT("unknown attribute bits"));
+ }
+ Run.Utf8.Append(Blob.GetData() + R.Off, Bytes);
+ R.Off += Bytes;
+ bool bValid = true;
+ const int32 Held = VerseCells::CountGraphemes(Run.Utf8.GetData(), Run.Utf8.Num(), &bValid);
+ if (!bValid)
+ {
+ return Fail(TEXT("run text is not UTF-8"));
+ }
+ if (Held != Run.Cells)
+ {
+ return Fail(FString::Printf(TEXT("run says %d cells but holds %d"), Run.Cells, Held));
+ }
+ const FUTF8ToTCHAR Conv(reinterpret_cast<const ANSICHAR*>(Run.Utf8.GetData()), Run.Utf8.Num());
+ Run.Text = FString(Conv.Length(), Conv.Get());
+ }
+ }
+ if (!R.bOk)
+ {
+ return Fail(TEXT("truncated frame"));
+ }
+ if (R.Off != Blob.Num())
+ {
+ return Fail(TEXT("trailing bytes"));
+ }
+ return Out.CheckRows(OutError);
+}
+
+TArray<uint8> FVerseCellsFrame::Encode() const
+{
+ TArray<uint8> O;
+ O.Add('V');
+ O.Add('C');
+ O.Add(1);
+ O.Add(bSnapshot ? 1 : 2);
+ W16(O, Ref);
+ W32(O, Seq);
+ W32(O, bSnapshot ? 0 : Base);
+ W16(O, Cols);
+ W16(O, Rows);
+ W16(O, uint16(CursorRow));
+ W16(O, uint16(CursorCol));
+ W16(O, uint16(RowsChanged.Num()));
+ for (const FVerseCellRow& Row : RowsChanged)
+ {
+ W16(O, Row.Row);
+ W16(O, uint16(Row.Runs.Num()));
+ for (const FVerseCellRun& Run : Row.Runs)
+ {
+ W16(O, Run.Col);
+ W16(O, uint16(VerseCells::CountGraphemes(Run.Utf8.GetData(), Run.Utf8.Num())));
+ W32(O, Run.Fg);
+ W32(O, Run.Bg);
+ W16(O, Run.Attrs);
+ W16(O, uint16(Run.Utf8.Num()));
+ O.Append(Run.Utf8);
+ }
+ }
+ return O;
+}
+
+uint32 FVerseCellsFrame::ColourFromJson(const TSharedPtr<FJsonValue>& Value, bool& bOk)
+{
+ if (!Value.IsValid() || Value->Type == EJson::Null)
+ {
+ return VerseCells::DefaultColour;
+ }
+ if (Value->Type == EJson::Object)
+ {
+ const TSharedPtr<FJsonObject> O = Value->AsObject();
+ double I = -1;
+ if (O->Values.Num() != 1 || !O->TryGetNumberField(TEXT("i"), I) || I < 0 || I > 255)
+ {
+ bOk = false;
+ return 0;
+ }
+ return (1u << 24) | uint32(I);
+ }
+ if (Value->Type == EJson::String)
+ {
+ const FString S = Value->AsString();
+ if (S.Len() == 7 && S[0] == '#')
+ {
+ uint32 V = 0;
+ for (int32 K = 1; K < 7; ++K)
+ {
+ const TCHAR C = S[K];
+ const int32 D = (C >= '0' && C <= '9') ? C - '0' : (C >= 'a' && C <= 'f') ? C - 'a' + 10 : -1;
+ if (D < 0)
+ {
+ bOk = false;
+ return 0;
+ }
+ V = (V << 4) | uint32(D);
+ }
+ return (2u << 24) | V;
+ }
+ }
+ bOk = false;
+ return 0;
+}
+
+uint16 FVerseCellsFrame::AttrsFromJson(const TArray<TSharedPtr<FJsonValue>>* Names, bool& bOk)
+{
+ uint16 Bits = 0;
+ if (!Names)
+ {
+ return 0;
+ }
+ for (const TSharedPtr<FJsonValue>& V : *Names)
+ {
+ const FString Name = V.IsValid() ? V->AsString() : FString();
+ bool bFound = false;
+ for (int32 I = 0; I < UE_ARRAY_COUNT(AttrNames); ++I)
+ {
+ if (Name == AttrNames[I])
+ {
+ Bits |= uint16(1u << I);
+ bFound = true;
+ }
+ }
+ bOk &= bFound;
+ }
+ return Bits;
+}
+
+bool FVerseCellsFrame::FromJson(const TSharedPtr<FJsonObject>& Data, FVerseCellsFrame& Out, FString* OutError)
+{
+ if (!Data.IsValid())
+ {
+ return false;
+ }
+ Out = FVerseCellsFrame();
+ FString Kind;
+ Data->TryGetStringField(TEXT("kind"), Kind);
+ Out.bSnapshot = Kind != TEXT("delta");
+ Out.Cols = uint16(VerseBridgeJson::Num(Data, TEXT("cols")));
+ Out.Rows = uint16(VerseBridgeJson::Num(Data, TEXT("rows")));
+ Out.Ref = uint16(VerseBridgeJson::Num(Data, TEXT("ref")));
+ const TArray<TSharedPtr<FJsonValue>>* Cursor = nullptr;
+ if (Data->TryGetArrayField(TEXT("cursor"), Cursor) && Cursor->Num() == 2)
+ {
+ Out.CursorRow = int16((*Cursor)[0]->AsNumber());
+ Out.CursorCol = int16((*Cursor)[1]->AsNumber());
+ }
+ bool bOk = true;
+ const TArray<TSharedPtr<FJsonValue>>* RowList = nullptr;
+ if (Data->TryGetArrayField(TEXT("rows_changed"), RowList))
+ {
+ for (const TSharedPtr<FJsonValue>& RowValue : *RowList)
+ {
+ const TSharedPtr<FJsonObject> RowObj = RowValue->AsObject();
+ FVerseCellRow& Row = Out.RowsChanged.AddDefaulted_GetRef();
+ Row.Row = uint16(RowObj->GetNumberField(TEXT("row")));
+ const TArray<TSharedPtr<FJsonValue>>* Runs = nullptr;
+ if (!RowObj->TryGetArrayField(TEXT("runs"), Runs))
+ {
+ continue;
+ }
+ for (const TSharedPtr<FJsonValue>& RunValue : *Runs)
+ {
+ const TSharedPtr<FJsonObject> RunObj = RunValue->AsObject();
+ FVerseCellRun& Run = Row.Runs.AddDefaulted_GetRef();
+ Run.Col = uint16(RunObj->GetNumberField(TEXT("col")));
+ Run.Text = RunObj->GetStringField(TEXT("text"));
+ const FTCHARToUTF8 Utf8(*Run.Text);
+ Run.Utf8.Append(reinterpret_cast<const uint8*>(Utf8.Get()), Utf8.Length());
+ Run.Cells = uint16(VerseCells::CountGraphemes(Run.Utf8.GetData(), Run.Utf8.Num()));
+ Run.Fg = ColourFromJson(RunObj->TryGetField(TEXT("fg")), bOk);
+ Run.Bg = ColourFromJson(RunObj->TryGetField(TEXT("bg")), bOk);
+ const TArray<TSharedPtr<FJsonValue>>* Attrs = nullptr;
+ RunObj->TryGetArrayField(TEXT("attrs"), Attrs);
+ Run.Attrs = AttrsFromJson(Attrs, bOk);
+ }
+ }
+ }
+ if (!bOk)
+ {
+ if (OutError)
+ {
+ *OutError = TEXT("bad colour or attribute");
+ }
+ return false;
+ }
+ return Out.CheckRows(OutError);
+}
diff --git a/unreal/Verse/Source/VerseBridge/Private/Bridge/VerseWsClient.cpp b/unreal/Verse/Source/VerseBridge/Private/Bridge/VerseWsClient.cpp
new file mode 100644
index 0000000000..f2ad9e2392
--- /dev/null
+++ b/unreal/Verse/Source/VerseBridge/Private/Bridge/VerseWsClient.cpp
@@ -0,0 +1,435 @@
+#include "Bridge/VerseWsClient.h"
+
+#include "HAL/PlatformProcess.h"
+#include "HAL/RunnableThread.h"
+#include "IPAddress.h"
+#include "Math/UnrealMathUtility.h"
+#include "Misc/Base64.h"
+#include "Misc/SecureHash.h"
+#include "SocketSubsystem.h"
+#include "Sockets.h"
+#include "VerseLog.h"
+
+namespace
+{
+ constexpr int32 MaxMessageBytes = 1 << 20;
+ constexpr double ConnectTimeoutS = 2.0;
+}
+
+FVerseWsClient::FVerseWsClient() = default;
+
+FVerseWsClient::~FVerseWsClient()
+{
+ Close(1001);
+}
+
+bool FVerseWsClient::ParseUrl(const FString& Url, FString& OutHost, int32& OutPort, FString& OutPath)
+{
+ FString Rest;
+ if (!Url.StartsWith(TEXT("ws://")))
+ {
+ return false;
+ }
+ Rest = Url.Mid(5);
+ int32 Slash = INDEX_NONE;
+ FString HostPort = Rest;
+ OutPath = TEXT("/");
+ if (Rest.FindChar('/', Slash))
+ {
+ HostPort = Rest.Left(Slash);
+ OutPath = Rest.Mid(Slash);
+ }
+ int32 Colon = INDEX_NONE;
+ if (!HostPort.FindLastChar(':', Colon))
+ {
+ return false;
+ }
+ OutHost = HostPort.Left(Colon).Replace(TEXT("["), TEXT("")).Replace(TEXT("]"), TEXT(""));
+ OutPort = FCString::Atoi(*HostPort.Mid(Colon + 1));
+ const bool bLoopback = OutHost == TEXT("127.0.0.1") || OutHost == TEXT("localhost") || OutHost == TEXT("::1");
+ if (OutHost == TEXT("localhost"))
+ {
+ OutHost = TEXT("127.0.0.1");
+ }
+ return bLoopback && OutPort > 0 && OutPort < 65536;
+}
+
+FString FVerseWsClient::AcceptFor(const FString& Key)
+{
+ const FString Joined = Key + TEXT("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
+ const FTCHARToUTF8 Utf8(*Joined);
+ uint8 Digest[20];
+ FSHA1::HashBuffer(Utf8.Get(), Utf8.Length(), Digest);
+ return FBase64::Encode(Digest, 20);
+}
+
+void FVerseWsClient::EncodeFrame(uint8 Opcode, const uint8* Payload, int64 Len, const uint8 Mask[4], TArray<uint8>& Out)
+{
+ Out.Reset();
+ Out.Add(0x80 | (Opcode & 0x0F));
+ if (Len < 126)
+ {
+ Out.Add(0x80 | uint8(Len));
+ }
+ else if (Len <= 0xFFFF)
+ {
+ Out.Add(0x80 | 126);
+ Out.Add(uint8(Len >> 8));
+ Out.Add(uint8(Len & 0xFF));
+ }
+ else
+ {
+ Out.Add(0x80 | 127);
+ for (int32 I = 7; I >= 0; --I)
+ {
+ Out.Add(uint8((uint64(Len) >> (8 * I)) & 0xFF));
+ }
+ }
+ Out.Append(Mask, 4);
+ const int32 Start = Out.Num();
+ Out.AddUninitialized(int32(Len));
+ for (int64 I = 0; I < Len; ++I)
+ {
+ Out[Start + int32(I)] = Payload[I] ^ Mask[I & 3];
+ }
+}
+
+bool FVerseWsClient::Connect(const FString& Url)
+{
+ Close(1000);
+ if (!ParseUrl(Url, Host, Port, Path))
+ {
+ UE_LOG(LogVerseBridge, Warning, TEXT("bridge URL is not a loopback ws:// URL"));
+ return false;
+ }
+ bStopping = false;
+ bOpen = false;
+ bFinished = false;
+ CloseRequested = 0;
+ Buffer.Reset();
+ Thread = FRunnableThread::Create(this, TEXT("VerseBridgeSocket"), 0, TPri_Normal);
+ return Thread != nullptr;
+}
+
+void FVerseWsClient::Close(int32 Code)
+{
+ if (!Thread)
+ {
+ return;
+ }
+ CloseRequested = Code;
+ bStopping = true;
+ Thread->WaitForCompletion();
+ delete Thread;
+ Thread = nullptr;
+}
+
+void FVerseWsClient::SendText(const FString& Text)
+{
+ const FTCHARToUTF8 Utf8(*Text);
+ FOutgoing O;
+ O.Opcode = 1;
+ O.Payload.Append(reinterpret_cast<const uint8*>(Utf8.Get()), Utf8.Length());
+ Outgoing.Enqueue(MoveTemp(O));
+}
+
+void FVerseWsClient::SendBinary(const TArray<uint8>& Bytes)
+{
+ FOutgoing O;
+ O.Opcode = 2;
+ O.Payload = Bytes;
+ Outgoing.Enqueue(MoveTemp(O));
+}
+
+bool FVerseWsClient::SendRaw(const uint8* Data, int32 Len)
+{
+ int32 Sent = 0;
+ while (Sent < Len)
+ {
+ int32 N = 0;
+ if (!Socket->Send(Data + Sent, Len - Sent, N) || N <= 0)
+ {
+ if (N == 0 && Socket->GetConnectionState() == SCS_Connected)
+ {
+ FPlatformProcess::Sleep(0.001f);
+ continue;
+ }
+ return false;
+ }
+ Sent += N;
+ }
+ return true;
+}
+
+bool FVerseWsClient::SendFrame(uint8 Opcode, const TArray<uint8>& Payload)
+{
+ uint8 Mask[4];
+ const uint32 R = uint32(FMath::Rand()) ^ (uint32(FMath::Rand()) << 15) ^ uint32(FPlatformTime::Cycles());
+ FMemory::Memcpy(Mask, &R, 4);
+ TArray<uint8> Wire;
+ EncodeFrame(Opcode, Payload.GetData(), Payload.Num(), Mask, Wire);
+ return SendRaw(Wire.GetData(), Wire.Num());
+}
+
+bool FVerseWsClient::Handshake()
+{
+ uint8 Nonce[16];
+ for (uint8& B : Nonce)
+ {
+ B = uint8(FMath::RandRange(0, 255));
+ }
+ const FString Key = FBase64::Encode(Nonce, 16);
+ const FString Request = FString::Printf(
+ TEXT("GET %s HTTP/1.1\r\nHost: %s:%d\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n")
+ TEXT("Sec-WebSocket-Key: %s\r\nSec-WebSocket-Version: 13\r\n\r\n"),
+ *Path, *Host, Port, *Key);
+ const FTCHARToUTF8 Utf8(*Request);
+ if (!SendRaw(reinterpret_cast<const uint8*>(Utf8.Get()), Utf8.Length()))
+ {
+ return false;
+ }
+ const double Deadline = FPlatformTime::Seconds() + ConnectTimeoutS;
+ while (FPlatformTime::Seconds() < Deadline && !bStopping)
+ {
+ if (!ReadAvailable())
+ {
+ return false;
+ }
+ for (int32 I = 3; I < Buffer.Num(); ++I)
+ {
+ if (Buffer[I - 3] == '\r' && Buffer[I - 2] == '\n' && Buffer[I - 1] == '\r' && Buffer[I] == '\n')
+ {
+ const FString Head = FString(FUTF8ToTCHAR(reinterpret_cast<const ANSICHAR*>(Buffer.GetData()), I + 1).Length(),
+ FUTF8ToTCHAR(reinterpret_cast<const ANSICHAR*>(Buffer.GetData()), I + 1).Get());
+ Buffer.RemoveAt(0, I + 1);
+ if (!Head.StartsWith(TEXT("HTTP/1.1 101")))
+ {
+ return false;
+ }
+ return Head.Contains(AcceptFor(Key), ESearchCase::CaseSensitive);
+ }
+ }
+ FPlatformProcess::Sleep(0.002f);
+ }
+ return false;
+}
+
+bool FVerseWsClient::ReadAvailable()
+{
+ uint32 Pending = 0;
+ while (Socket->HasPendingData(Pending) && Pending > 0)
+ {
+ const int32 Start = Buffer.Num();
+ Buffer.AddUninitialized(int32(Pending));
+ int32 Read = 0;
+ if (!Socket->Recv(Buffer.GetData() + Start, int32(Pending), Read))
+ {
+ Buffer.SetNum(Start);
+ return false;
+ }
+ Buffer.SetNum(Start + Read);
+ if (Read == 0)
+ {
+ break;
+ }
+ }
+ return Socket->GetConnectionState() != SCS_ConnectionError;
+}
+
+bool FVerseWsClient::ProcessBuffer()
+{
+ while (Buffer.Num() >= 2)
+ {
+ const uint8 B0 = Buffer[0];
+ const uint8 B1 = Buffer[1];
+ const bool bFin = (B0 & 0x80) != 0;
+ const uint8 Opcode = B0 & 0x0F;
+ uint64 Len = B1 & 0x7F;
+ int32 Off = 2;
+ if (Len == 126)
+ {
+ if (Buffer.Num() < 4)
+ {
+ return true;
+ }
+ Len = (uint64(Buffer[2]) << 8) | Buffer[3];
+ Off = 4;
+ }
+ else if (Len == 127)
+ {
+ if (Buffer.Num() < 10)
+ {
+ return true;
+ }
+ Len = 0;
+ for (int32 I = 0; I < 8; ++I)
+ {
+ Len = (Len << 8) | Buffer[2 + I];
+ }
+ Off = 10;
+ }
+ if ((B1 & 0x80) != 0 || Len > uint64(MaxMessageBytes))
+ {
+ Finish(1002);
+ return false;
+ }
+ if (uint64(Buffer.Num()) < Off + Len)
+ {
+ return true;
+ }
+ TArray<uint8> Payload(Buffer.GetData() + Off, int32(Len));
+ Buffer.RemoveAt(0, Off + int32(Len));
+ if (Opcode == 8)
+ {
+ const int32 Code = Payload.Num() >= 2 ? (int32(Payload[0]) << 8) | Payload[1] : 1005;
+ TArray<uint8> Echo;
+ if (Payload.Num() >= 2)
+ {
+ Echo.Append(Payload.GetData(), 2);
+ }
+ SendFrame(8, Echo);
+ Finish(Code);
+ return false;
+ }
+ if (Opcode == 9)
+ {
+ SendFrame(10, Payload);
+ continue;
+ }
+ if (Opcode == 10)
+ {
+ continue;
+ }
+ if (Opcode == 1 || Opcode == 2)
+ {
+ FragmentOpcode = Opcode;
+ Fragment = MoveTemp(Payload);
+ }
+ else if (Opcode == 0)
+ {
+ Fragment.Append(Payload);
+ }
+ if (!bFin)
+ {
+ continue;
+ }
+ FEvent E;
+ if (FragmentOpcode == 1)
+ {
+ E.Kind = FEvent::EKind::Text;
+ const FUTF8ToTCHAR Conv(reinterpret_cast<const ANSICHAR*>(Fragment.GetData()), Fragment.Num());
+ E.Text = FString(Conv.Length(), Conv.Get());
+ }
+ else
+ {
+ E.Kind = FEvent::EKind::Binary;
+ E.Bytes = MoveTemp(Fragment);
+ }
+ Fragment.Reset();
+ Events.Enqueue(MoveTemp(E));
+ }
+ return true;
+}
+
+void FVerseWsClient::Finish(int32 Code)
+{
+ if (bFinished)
+ {
+ return;
+ }
+ bFinished = true;
+ bOpen = false;
+ FEvent E;
+ E.Kind = FEvent::EKind::Closed;
+ E.CloseCode = Code;
+ Events.Enqueue(MoveTemp(E));
+}
+
+uint32 FVerseWsClient::Run()
+{
+ ISocketSubsystem* Subsystem = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM);
+ if (!Subsystem)
+ {
+ Finish(1006);
+ return 1;
+ }
+ TSharedRef<FInternetAddr> Addr = Subsystem->CreateInternetAddr();
+ bool bValid = false;
+ Addr->SetIp(*Host, bValid);
+ Addr->SetPort(Port);
+ Socket = bValid ? Subsystem->CreateSocket(NAME_Stream, TEXT("VerseBridge"), Addr->GetProtocolType()) : nullptr;
+ if (!Socket)
+ {
+ Finish(1006);
+ return 1;
+ }
+ Socket->SetNoDelay(true);
+ if (!Socket->Connect(*Addr) || !Handshake())
+ {
+ Finish(1006);
+ }
+ else
+ {
+ bOpen = true;
+ FEvent E;
+ E.Kind = FEvent::EKind::Connected;
+ Events.Enqueue(MoveTemp(E));
+ Socket->SetNonBlocking(true);
+ ProcessBuffer();
+ while (!bStopping && !bFinished)
+ {
+ FOutgoing O;
+ bool bSendOk = true;
+ while (bSendOk && Outgoing.Dequeue(O))
+ {
+ bSendOk = SendFrame(O.Opcode, O.Payload);
+ }
+ if (!bSendOk)
+ {
+ Finish(1006);
+ break;
+ }
+ if (Socket->Wait(ESocketWaitConditions::WaitForRead, FTimespan::FromMilliseconds(5)))
+ {
+ if (!ReadAvailable())
+ {
+ Finish(1006);
+ break;
+ }
+ uint32 Pending = 0;
+ if (Buffer.Num() == 0 && !Socket->HasPendingData(Pending))
+ {
+ // Readable with nothing to read: the peer closed the connection.
+ uint8 Probe = 0;
+ int32 Read = 0;
+ if (!Socket->Recv(&Probe, 1, Read, ESocketReceiveFlags::Peek) || Read == 0)
+ {
+ if (Socket->GetConnectionState() != SCS_Connected)
+ {
+ Finish(1006);
+ break;
+ }
+ }
+ }
+ ProcessBuffer();
+ }
+ }
+ if (!bFinished && CloseRequested != 0)
+ {
+ // Flush what the game queued before closing (lifecycle.bye, a last duel.result).
+ FOutgoing Last;
+ while (Outgoing.Dequeue(Last) && SendFrame(Last.Opcode, Last.Payload))
+ {
+ }
+ const int32 Code = CloseRequested;
+ TArray<uint8> Payload{uint8(Code >> 8), uint8(Code & 0xFF)};
+ SendFrame(8, Payload);
+ Finish(Code);
+ }
+ }
+ Socket->Close();
+ Subsystem->DestroySocket(Socket);
+ Socket = nullptr;
+ bOpen = false;
+ return 0;
+}
diff --git a/unreal/Verse/Source/VerseBridge/Private/Lifecycle/VerseLifecycle.cpp b/unreal/Verse/Source/VerseBridge/Private/Lifecycle/VerseLifecycle.cpp
new file mode 100644
index 0000000000..7452f92ceb
--- /dev/null
+++ b/unreal/Verse/Source/VerseBridge/Private/Lifecycle/VerseLifecycle.cpp
@@ -0,0 +1,232 @@
+#include "Lifecycle/VerseLifecycle.h"
+
+#include "Bridge/VerseBridgeClient.h"
+#include "Bridge/VerseBridgeCodec.h"
+#include "HAL/PlatformTime.h"
+#include "VerseLog.h"
+
+using namespace VerseBridgeJson;
+
+const TCHAR* LexToString(EVerseLifecycleState State)
+{
+ switch (State)
+ {
+ case EVerseLifecycleState::Booting: return TEXT("booting");
+ case EVerseLifecycleState::Visible: return TEXT("visible");
+ case EVerseLifecycleState::Panel: return TEXT("panel");
+ case EVerseLifecycleState::Dormant: return TEXT("dormant");
+ case EVerseLifecycleState::Exiting: return TEXT("exiting");
+ }
+ return TEXT("booting");
+}
+
+double IVerseLifecycleHost::Now() const
+{
+ return FPlatformTime::Seconds();
+}
+
+FVerseLifecycleController::FVerseLifecycleController(IVerseLifecycleHost& InHost, FVerseBridgeClient& InClient)
+ : Host(InHost)
+ , Client(InClient)
+{
+}
+
+void FVerseLifecycleController::ReportState()
+{
+ TSharedPtr<FJsonObject> Data = MakeShared<FJsonObject>();
+ Data->SetStringField(TEXT("state"), LexToString(State));
+ Data->SetNumberField(TEXT("vram_mb"), FMath::Max(0, Host.VramMb()));
+ Data->SetNumberField(TEXT("fps"), FMath::Max(0.f, Host.Fps()));
+ Client.SendNotice(TEXT("lifecycle.state"), Data);
+}
+
+void FVerseLifecycleController::NotifyLinked()
+{
+ if (const TSharedPtr<FJsonObject> Welcome = Client.GetWelcome())
+ {
+ AppPid = int32(Int(Welcome, TEXT("app_pid")));
+ ReturnKey = Str(Obj(Welcome, TEXT("settings")), TEXT("return_key"), ReturnKey);
+ const TSharedPtr<FJsonObject> St = Obj(Welcome, TEXT("state"));
+ bPanelVisible = Str(St, TEXT("panel")) == TEXT("visible");
+ bGpuYield = Str(St, TEXT("gpu")) == TEXT("yield");
+ }
+ ReportState();
+}
+
+void FVerseLifecycleController::Enter(EVerseLifecycleState Next)
+{
+ if (State == EVerseLifecycleState::Exiting || Next == State)
+ {
+ return;
+ }
+ const EVerseLifecycleState Previous = State;
+ State = Next;
+ switch (Next)
+ {
+ case EVerseLifecycleState::Visible:
+ Host.SetRendering(true);
+ Host.SetMaxFps(0.f);
+ Host.SetMuted(false);
+ Host.SetPaused(bPaused);
+ Host.SetLowScalability(bGpuYield);
+ break;
+ case EVerseLifecycleState::Panel:
+ // Offscreen at panel size, decks only, no match (architecture 1.3).
+ Host.HideWindow();
+ Host.SetRendering(true);
+ Host.SetMaxFps(30.f);
+ Host.SetMuted(true);
+ Host.SetPaused(true);
+ break;
+ case EVerseLifecycleState::Dormant:
+ Host.HideWindow();
+ Host.SetRendering(false);
+ Host.SetMaxFps(2.f);
+ Host.SetMuted(true);
+ Host.SetPaused(true);
+ break;
+ case EVerseLifecycleState::Exiting:
+ case EVerseLifecycleState::Booting:
+ Host.SetRendering(false);
+ Host.SetMuted(true);
+ break;
+ }
+ UE_LOG(LogVerseBridge, Log, TEXT("lifecycle: %s -> %s"), LexToString(Previous), LexToString(Next));
+ ReportState();
+ OnStateChanged.Broadcast(Next);
+}
+
+void FVerseLifecycleController::HandleFrame(const FVerseBridgeFrame& F)
+{
+ const FString& T = F.Type;
+ if (T == TEXT("welcome"))
+ {
+ NotifyLinked();
+ return;
+ }
+ if (T == TEXT("lifecycle.show"))
+ {
+ const TSharedPtr<FJsonObject> M = Obj(F.Data, TEXT("monitor"));
+ FVerseMonitor Monitor;
+ if (M.IsValid())
+ {
+ Monitor.X = int32(Int(M, TEXT("x")));
+ Monitor.Y = int32(Int(M, TEXT("y")));
+ Monitor.W = int32(Int(M, TEXT("w"), 1920));
+ Monitor.H = int32(Int(M, TEXT("h"), 1080));
+ Monitor.Dpi = float(Num(M, TEXT("dpi"), 96.0));
+ }
+ ShowAt = Host.Now();
+ Host.ShowWindow(Monitor, Str(F.Data, TEXT("activation_token")));
+ Enter(EVerseLifecycleState::Visible);
+ LastShowSeconds = Host.Now() - ShowAt;
+ if (Str(F.Data, TEXT("reason")) == TEXT("quick_start_duel"))
+ {
+ OnQuickStartDuel.Broadcast();
+ }
+ }
+ else if (T == TEXT("lifecycle.hide") || T == TEXT("focus.app_took"))
+ {
+ Enter(bPanelVisible ? EVerseLifecycleState::Panel : EVerseLifecycleState::Dormant);
+ }
+ else if (T == TEXT("lifecycle.pause") || T == TEXT("lifecycle.resume"))
+ {
+ bPaused = T == TEXT("lifecycle.pause");
+ if (State == EVerseLifecycleState::Visible)
+ {
+ Host.SetPaused(bPaused);
+ Host.SetMuted(bPaused);
+ }
+ }
+ else if (T == TEXT("lifecycle.quit"))
+ {
+ Quit(Str(F.Data, TEXT("reason"), TEXT("app_quit")));
+ }
+ else if (T == TEXT("panel.visibility"))
+ {
+ bPanelVisible = Bool(F.Data, TEXT("visible"));
+ if (bPanelVisible)
+ {
+ Host.ResizePanel(int32(Int(F.Data, TEXT("w"))), int32(Int(F.Data, TEXT("h"))), float(Num(F.Data, TEXT("dpr"), 1.0)));
+ if (State != EVerseLifecycleState::Visible)
+ {
+ Enter(EVerseLifecycleState::Panel);
+ }
+ }
+ else if (State == EVerseLifecycleState::Panel)
+ {
+ Enter(EVerseLifecycleState::Dormant);
+ }
+ }
+ else if (T == TEXT("panel.resize"))
+ {
+ Host.ResizePanel(int32(Int(F.Data, TEXT("w"))), int32(Int(F.Data, TEXT("h"))), float(Num(F.Data, TEXT("dpr"), 1.0)));
+ }
+ else if (T == TEXT("gpu.yield"))
+ {
+ bGpuYield = true;
+ if (State == EVerseLifecycleState::Dormant || State == EVerseLifecycleState::Booting)
+ {
+ Quit(TEXT("gpu_pressure"));
+ }
+ else
+ {
+ Host.SetLowScalability(true);
+ }
+ }
+ else if (T == TEXT("gpu.free"))
+ {
+ bGpuYield = false;
+ Host.SetLowScalability(false);
+ }
+ else if (T == TEXT("settings.changed"))
+ {
+ ReturnKey = Str(F.Data, TEXT("return_key"), ReturnKey);
+ }
+}
+
+void FVerseLifecycleController::ReturnToApp(const FString& Reason)
+{
+ if (State != EVerseLifecycleState::Visible)
+ {
+ return;
+ }
+ // Order matters on Windows: allow the app to take the foreground, tell it, then hide.
+ Host.AllowForeground(AppPid);
+ TSharedPtr<FJsonObject> Data = MakeShared<FJsonObject>();
+ Data->SetStringField(TEXT("reason"), Reason);
+ Client.SendNotice(TEXT("focus.return_to_app"), Data);
+ Enter(bPanelVisible ? EVerseLifecycleState::Panel : EVerseLifecycleState::Dormant);
+}
+
+void FVerseLifecycleController::NotifyFirstFrame(double MsSinceStart)
+{
+ if (bReady)
+ {
+ return;
+ }
+ bReady = true;
+ TSharedPtr<FJsonObject> Data = MakeShared<FJsonObject>();
+ Data->SetNumberField(TEXT("first_frame_ms"), FMath::RoundToDouble(MsSinceStart));
+ Client.SendNotice(TEXT("lifecycle.ready"), Data);
+}
+
+void FVerseLifecycleController::Quit(const FString& Reason)
+{
+ if (State == EVerseLifecycleState::Exiting)
+ {
+ return;
+ }
+ OnQuitting.Broadcast(Reason);
+ Enter(EVerseLifecycleState::Exiting);
+ const bool bSaved = Host.SaveState();
+ TSharedPtr<FJsonObject> Data = MakeShared<FJsonObject>();
+ Data->SetBoolField(TEXT("saved"), bSaved);
+ Client.SendNotice(TEXT("lifecycle.bye"), Data);
+ Host.RequestExit();
+}
+
+void FVerseLifecycleController::LaunchOver()
+{
+ Quit(TEXT("launch_over"));
+}
diff --git a/unreal/Verse/Source/VerseBridge/Private/Tests/Bridge/VerseBridgeClientTest.cpp b/unreal/Verse/Source/VerseBridge/Private/Tests/Bridge/VerseBridgeClientTest.cpp
new file mode 100644
index 0000000000..7f2aa1e58b
--- /dev/null
+++ b/unreal/Verse/Source/VerseBridge/Private/Tests/Bridge/VerseBridgeClientTest.cpp
@@ -0,0 +1,225 @@
+#include "Bridge/VerseBridgeClient.h"
+#include "HAL/FileManager.h"
+#include "HAL/PlatformMisc.h"
+#include "HAL/PlatformProcess.h"
+#include "Lifecycle/VerseLifecycle.h"
+#include "Misc/AutomationTest.h"
+#include "Misc/FileHelper.h"
+#include "Misc/Guid.h"
+#include "Misc/Paths.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+namespace
+{
+ /** Runs scripts/unreal/fake_bridge.py (G0.11) with a dev discovery file; the test plays Verse. */
+ struct FFakeBridge
+ {
+ FProcHandle Proc;
+ FString Discovery;
+ FString Report;
+ FString Token;
+
+ bool Start(const FString& Scenario, const FString& Extra = FString())
+ {
+ const FString Repo = FPaths::ConvertRelativePathToFull(FPaths::Combine(FPaths::ProjectDir(), TEXT(".."), TEXT("..")));
+ const FString Dir = FPaths::ConvertRelativePathToFull(FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("Automation"), TEXT("Bridge")));
+ IFileManager::Get().MakeDirectory(*Dir, true);
+ const FString Id = FGuid::NewGuid().ToString(EGuidFormats::Digits);
+ Discovery = FPaths::Combine(Dir, Id + TEXT(".json"));
+ Report = FPaths::Combine(Dir, Id + TEXT(".report.json"));
+ Token = Id + Id.Left(11);
+ const FString Python = FPlatformMisc::GetEnvironmentVariable(TEXT("DODAIOS_PYTHON")).IsEmpty()
+ ? FString(PLATFORM_WINDOWS ? TEXT("python") : TEXT("python3"))
+ : FPlatformMisc::GetEnvironmentVariable(TEXT("DODAIOS_PYTHON"));
+ const FString Args = FString::Printf(TEXT("\"%s\" --scenario %s --speed 0 --once --token %s --discovery \"%s\" --report \"%s\" %s"),
+ *FPaths::Combine(Repo, TEXT("scripts"), TEXT("unreal"), TEXT("fake_bridge.py")), *Scenario, *Token, *Discovery, *Report, *Extra);
+ Proc = FPlatformProcess::CreateProc(*Python, *Args, false, true, true, nullptr, 0, *Repo, nullptr);
+ const double Deadline = FPlatformTime::Seconds() + 20.0;
+ while (FPlatformTime::Seconds() < Deadline && Proc.IsValid() && FPlatformProcess::IsProcRunning(Proc))
+ {
+ if (IFileManager::Get().FileExists(*Discovery))
+ {
+ return true;
+ }
+ FPlatformProcess::Sleep(0.05f);
+ }
+ return false;
+ }
+
+ void Stop()
+ {
+ if (Proc.IsValid())
+ {
+ const double Deadline = FPlatformTime::Seconds() + 5.0;
+ while (FPlatformProcess::IsProcRunning(Proc) && FPlatformTime::Seconds() < Deadline)
+ {
+ FPlatformProcess::Sleep(0.05f);
+ }
+ if (FPlatformProcess::IsProcRunning(Proc))
+ {
+ FPlatformProcess::TerminateProc(Proc, false);
+ }
+ FPlatformProcess::CloseProc(Proc);
+ }
+ }
+ };
+
+ template <typename F>
+ bool PumpUntil(FVerseBridgeClient& Client, double Seconds, F&& Done)
+ {
+ const double Deadline = FPlatformTime::Seconds() + Seconds;
+ while (FPlatformTime::Seconds() < Deadline)
+ {
+ Client.Tick(FPlatformTime::Seconds());
+ if (Done())
+ {
+ return true;
+ }
+ FPlatformProcess::Sleep(0.01f);
+ }
+ return false;
+ }
+}
+
+// 17.11 against the G0.11 fake bridge: hello, welcome, subscribe, snapshots and deltas with
+// base checks, a command with exactly one reply, ping and pong.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBridgeClientFakeBridgeTest, "Verse.Bridge.Client.FakeBridge",
+ EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)
+
+bool FVerseBridgeClientFakeBridgeTest::RunTest(const FString& Parameters)
+{
+ FFakeBridge Fake;
+ if (!Fake.Start(TEXT("roster_churn")))
+ {
+ AddWarning(TEXT("fake_bridge.py did not start (python missing?); skipped"));
+ Fake.Stop();
+ return true;
+ }
+ FVerseBridgeClient::FDiscovery Discovery;
+ FVerseBridgeClient::Discover(Discovery, Fake.Discovery);
+ TestEqual(TEXT("token from the discovery file"), Discovery.Token, Fake.Token);
+ FVerseBridgeClient Client;
+ Client.Subscribe({TEXT("roster")});
+ int32 RosterChanges = 0;
+ Client.Roster.OnChanged.AddLambda([&RosterChanges]() { ++RosterChanges; });
+ Client.Start(Discovery);
+ TestTrue(TEXT("linked"), PumpUntil(Client, 10.0, [&] { return Client.IsLinked(); }));
+ TestTrue(TEXT("welcome carries the protocol"), Client.GetWelcome().IsValid() && VerseBridgeJson::Str(Client.GetWelcome(), TEXT("protocol")) == VerseBridge::Protocol);
+ TestTrue(TEXT("roster snapshot and deltas"), PumpUntil(Client, 10.0, [&] { return Client.Roster.HasSnapshot() && RosterChanges >= 3; }));
+ int32 Replies = 0;
+ bool bOk = false;
+ TSharedPtr<FJsonObject> Action = MakeShared<FJsonObject>();
+ Action->SetStringField(TEXT("action"), TEXT("inspection"));
+ Action->SetStringField(TEXT("ref"), TEXT("hangar"));
+ Client.SendCommand(TEXT("progression.action"), Action, [&](bool bReplyOk, const TSharedPtr<FJsonObject>&, const FString&) { ++Replies; bOk = bReplyOk; });
+ TestTrue(TEXT("one reply"), PumpUntil(Client, 5.0, [&] { return Replies > 0; }));
+ PumpUntil(Client, 1.5, [] { return false; });
+ TestEqual(TEXT("exactly one reply"), Replies, 1);
+ TestTrue(TEXT("still linked after pings"), Client.IsLinked());
+ AddInfo(FString::Printf(TEXT("agents %d, panes %d, last seq %lld"), Client.Roster.GetAgents().Num(), Client.Roster.GetPanes().Num(), Client.GetLastSeq()));
+ Client.Stop();
+ Fake.Stop();
+ FString Report;
+ if (FFileHelper::LoadFileToString(Report, *Fake.Report))
+ {
+ AddInfo(Report.Left(400));
+ }
+ return true;
+}
+
+// Reconnect backoff of contract section 1: 250 ms, 1 s, 2 s, 4 s, then every 5 s.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBridgeBackoffTest, "Verse.Bridge.Client.Backoff",
+ EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)
+
+bool FVerseBridgeBackoffTest::RunTest(const FString& Parameters)
+{
+ TestEqual(TEXT("1"), FVerseBridgeClient::BackoffFor(1), 0.25);
+ TestEqual(TEXT("2"), FVerseBridgeClient::BackoffFor(2), 1.0);
+ TestEqual(TEXT("3"), FVerseBridgeClient::BackoffFor(3), 2.0);
+ TestEqual(TEXT("4"), FVerseBridgeClient::BackoffFor(4), 4.0);
+ TestEqual(TEXT("5"), FVerseBridgeClient::BackoffFor(5), 5.0);
+ TestEqual(TEXT("9"), FVerseBridgeClient::BackoffFor(9), 5.0);
+ TestEqual(TEXT("dead link"), FVerseBridgeClient::DeadLink, 5.0);
+ TestEqual(TEXT("ping"), FVerseBridgeClient::PingInterval, 1.0);
+ return true;
+}
+
+namespace
+{
+ struct FFakeHost : IVerseLifecycleHost
+ {
+ TArray<FString> Calls;
+ double Clock = 100.0;
+ bool bVisible = false;
+ bool bRendering = true;
+ float MaxFps = 0.f;
+ bool bExit = false;
+ virtual void ShowWindow(const FVerseMonitor& M, const FString& Token) override { Calls.Add(TEXT("show")); bVisible = true; }
+ virtual void HideWindow() override { Calls.Add(TEXT("hide")); bVisible = false; }
+ virtual void SetRendering(bool bOn) override { bRendering = bOn; }
+ virtual void SetMaxFps(float Fps) override { MaxFps = Fps; }
+ virtual void SetMuted(bool) override {}
+ virtual void SetPaused(bool) override {}
+ virtual void SetLowScalability(bool bLow) override { Calls.Add(bLow ? TEXT("low") : TEXT("normal")); }
+ virtual void AllowForeground(int32 Pid) override { Calls.Add(FString::Printf(TEXT("allow:%d"), Pid)); }
+ virtual bool SaveState() override { Calls.Add(TEXT("save")); return true; }
+ virtual void RequestExit() override { bExit = true; }
+ virtual double Now() const override { return Clock; }
+ };
+
+ FVerseBridgeFrame Server(const TCHAR* Type, const TCHAR* Json = TEXT("{}"))
+ {
+ FVerseBridgeFrame F;
+ F.Type = Type;
+ F.Seq = 2;
+ F.Data = VerseBridgeJson::Read(Json);
+ return F;
+ }
+}
+
+// 17.12: the lifecycle state machine against a fake engine host.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseLifecycleStatesTest, "Verse.Bridge.Lifecycle.States",
+ EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)
+
+bool FVerseLifecycleStatesTest::RunTest(const FString& Parameters)
+{
+ FFakeHost Host;
+ FVerseBridgeClient Client;
+ FVerseLifecycleController L(Host, Client);
+ TestTrue(TEXT("boots"), L.GetState() == EVerseLifecycleState::Booting);
+ int32 Duels = 0;
+ L.OnQuickStartDuel.AddLambda([&Duels]() { ++Duels; });
+ L.HandleFrame(Server(TEXT("lifecycle.show"), TEXT("{\"monitor\":{\"x\":0,\"y\":0,\"w\":2560,\"h\":1440,\"dpi\":144},\"reason\":\"quick_start_duel\"}")));
+ TestTrue(TEXT("visible"), L.GetState() == EVerseLifecycleState::Visible);
+ TestEqual(TEXT("quick start"), Duels, 1);
+ L.HandleFrame(Server(TEXT("gpu.yield"), TEXT("{\"by\":\"local_model\"}")));
+ TestTrue(TEXT("visible drops to low"), Host.Calls.Contains(TEXT("low")));
+ L.HandleFrame(Server(TEXT("gpu.free"), TEXT("{\"by\":\"local_model\"}")));
+ TestTrue(TEXT("back to normal"), Host.Calls.Contains(TEXT("normal")));
+ L.HandleFrame(Server(TEXT("settings.changed"), TEXT("{\"return_key\":\"F9\"}")));
+ TestEqual(TEXT("return key rebinds live"), L.GetReturnKey(), FString(TEXT("F9")));
+ L.ReturnToApp();
+ TestTrue(TEXT("return key -> dormant"), L.GetState() == EVerseLifecycleState::Dormant);
+ TestTrue(TEXT("foreground allowed before hiding"), Host.Calls.IndexOfByKey(TEXT("allow:0")) < Host.Calls.FindLast(TEXT("hide")));
+ TestFalse(TEXT("dormant renders nothing"), Host.bRendering);
+ TestEqual(TEXT("dormant ticks at 2 Hz"), Host.MaxFps, 2.f);
+ L.HandleFrame(Server(TEXT("panel.visibility"), TEXT("{\"visible\":true,\"w\":480,\"h\":320,\"dpr\":1.5}")));
+ TestTrue(TEXT("panel"), L.GetState() == EVerseLifecycleState::Panel);
+ L.HandleFrame(Server(TEXT("lifecycle.show"), TEXT("{\"monitor\":{\"x\":0,\"y\":0,\"w\":1920,\"h\":1080,\"dpi\":96},\"reason\":\"verse_view\"}")));
+ TestTrue(TEXT("panel -> visible"), L.GetState() == EVerseLifecycleState::Visible);
+ L.HandleFrame(Server(TEXT("focus.app_took")));
+ TestTrue(TEXT("app took focus while the panel streams"), L.GetState() == EVerseLifecycleState::Panel);
+ L.HandleFrame(Server(TEXT("panel.visibility"), TEXT("{\"visible\":false,\"w\":0,\"h\":0,\"dpr\":1}")));
+ TestTrue(TEXT("panel hidden -> dormant"), L.GetState() == EVerseLifecycleState::Dormant);
+ TestTrue(TEXT("show measured"), L.GetLastShowSeconds() >= 0.0);
+ L.HandleFrame(Server(TEXT("gpu.yield"), TEXT("{\"by\":\"blender_cook\"}")));
+ TestTrue(TEXT("dormant quits at once on gpu.yield"), L.GetState() == EVerseLifecycleState::Exiting);
+ TestTrue(TEXT("state saved"), Host.Calls.Contains(TEXT("save")));
+ TestTrue(TEXT("exit requested"), Host.bExit);
+ L.HandleFrame(Server(TEXT("lifecycle.show"), TEXT("{\"monitor\":{\"x\":0,\"y\":0,\"w\":1,\"h\":1,\"dpi\":96},\"reason\":\"verse_view\"}")));
+ TestTrue(TEXT("exiting is final"), L.GetState() == EVerseLifecycleState::Exiting);
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseBridge/Private/Tests/Bridge/VerseBridgeCodecTest.cpp b/unreal/Verse/Source/VerseBridge/Private/Tests/Bridge/VerseBridgeCodecTest.cpp
new file mode 100644
index 0000000000..bb9c7ac510
--- /dev/null
+++ b/unreal/Verse/Source/VerseBridge/Private/Tests/Bridge/VerseBridgeCodecTest.cpp
@@ -0,0 +1,207 @@
+#include "Bridge/VerseBridgeCodec.h"
+#include "Bridge/VerseBridgeFeeds.h"
+#include "Bridge/VerseCellsCodec.h"
+#include "Bridge/VerseWsClient.h"
+#include "HAL/FileManager.h"
+#include "Misc/AutomationTest.h"
+#include "Misc/FileHelper.h"
+#include "Misc/Parse.h"
+#include "Misc/Paths.h"
+#include "Serialization/JsonReader.h"
+#include "Serialization/JsonSerializer.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+namespace
+{
+ FString BridgeDataDir()
+ {
+ return FPaths::Combine(FPaths::ProjectDir(), TEXT("Tests"), TEXT("Data"), TEXT("bridge"));
+ }
+
+ TArray<TSharedPtr<FJsonValue>> ReadArray(const FString& Path)
+ {
+ FString Text;
+ TArray<TSharedPtr<FJsonValue>> Out;
+ if (FFileHelper::LoadFileToString(Text, *Path))
+ {
+ TSharedRef<TJsonReader<TCHAR>> Reader = TJsonReaderFactory<TCHAR>::Create(Text);
+ FJsonSerializer::Deserialize(Reader, Out);
+ }
+ return Out;
+ }
+
+ TArray<uint8> FromHex(const FString& Hex)
+ {
+ TArray<uint8> Out;
+ for (int32 I = 0; I + 1 < Hex.Len(); I += 2)
+ {
+ Out.Add(uint8(FParse::HexDigit(Hex[I]) * 16 + FParse::HexDigit(Hex[I + 1])));
+ }
+ return Out;
+ }
+
+ FString ToHex(const TArray<uint8>& Bytes)
+ {
+ FString Out;
+ for (uint8 B : Bytes)
+ {
+ Out += FString::Printf(TEXT("%02x"), B);
+ }
+ return Out;
+ }
+}
+
+// A17.1 (C++ half): every golden message parses, re-encodes and parses back to the same frame.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBridgeGoldenMessagesTest, "Verse.Bridge.Codec.GoldenMessages",
+ EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)
+
+bool FVerseBridgeGoldenMessagesTest::RunTest(const FString& Parameters)
+{
+ TArray<FString> Files;
+ IFileManager::Get().FindFiles(Files, *FPaths::Combine(BridgeDataDir(), TEXT("messages"), TEXT("*.json")), true, false);
+ TestTrue(TEXT("golden message files found"), Files.Num() >= 40);
+ int32 Frames = 0;
+ for (const FString& File : Files)
+ {
+ for (const TSharedPtr<FJsonValue>& V : ReadArray(FPaths::Combine(BridgeDataDir(), TEXT("messages"), File)))
+ {
+ const FString Text = VerseBridgeJson::Write(V->AsObject());
+ FVerseBridgeFrame A;
+ FString Error;
+ if (!TestTrue(FString::Printf(TEXT("%s parses (%s)"), *File, *Error), FVerseBridgeFrame::Parse(Text, A, &Error)))
+ {
+ continue;
+ }
+ FVerseBridgeFrame B;
+ TestTrue(TEXT("re-encoded frame parses"), FVerseBridgeFrame::Parse(A.Encode(), B));
+ TestEqual(TEXT("type"), B.Type, A.Type);
+ TestEqual(TEXT("seq"), B.Seq, A.Seq);
+ TestEqual(TEXT("base"), B.Base, A.Base);
+ TestEqual(TEXT("id"), B.Id, A.Id);
+ TestEqual(TEXT("re"), B.Re, A.Re);
+ TestTrue(FString::Printf(TEXT("%s data round trip"), *File), VerseBridgeJson::Equal(A.Data, B.Data));
+ TestTrue(FString::Printf(TEXT("%s equals the golden object"), *File), VerseBridgeJson::Equal(VerseBridgeJson::Read(A.Encode()), V->AsObject()));
+ ++Frames;
+ }
+ }
+ AddInfo(FString::Printf(TEXT("%d golden frames round-tripped"), Frames));
+ FVerseBridgeFrame Bad;
+ TestFalse(TEXT("no type is malformed"), FVerseBridgeFrame::Parse(TEXT("{\"data\":{}}"), Bad));
+ TestFalse(TEXT("array data is malformed"), FVerseBridgeFrame::Parse(TEXT("{\"type\":\"x\",\"data\":[]}"), Bad));
+ TestFalse(TEXT("not JSON"), FVerseBridgeFrame::Parse(TEXT("nope"), Bad));
+ return true;
+}
+
+// A17.1 (C++ half): cells.bin/1 vectors encode to the exact bytes and decode back; bad ones fail.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBridgeCellsVectorsTest, "Verse.Bridge.Codec.CellsVectors",
+ EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)
+
+bool FVerseBridgeCellsVectorsTest::RunTest(const FString& Parameters)
+{
+ FString Text;
+ if (!TestTrue(TEXT("vectors file"), FFileHelper::LoadFileToString(Text, *FPaths::Combine(BridgeDataDir(), TEXT("cells"), TEXT("vectors.json")))))
+ {
+ return false;
+ }
+ const TSharedPtr<FJsonObject> Root = VerseBridgeJson::Read(Text);
+ int32 Valid = 0;
+ for (const TSharedPtr<FJsonValue>& V : *VerseBridgeJson::Arr(Root, TEXT("valid")))
+ {
+ const TSharedPtr<FJsonObject> Vec = V->AsObject();
+ const FString Name = VerseBridgeJson::Str(Vec, TEXT("name"));
+ const TSharedPtr<FJsonObject> Frame = VerseBridgeJson::Obj(Vec, TEXT("frame"));
+ FVerseCellsFrame FromJson;
+ FString Error;
+ if (!TestTrue(FString::Printf(TEXT("%s json form reads (%s)"), *Name, *Error), FVerseCellsFrame::FromJson(VerseBridgeJson::Obj(Frame, TEXT("data")), FromJson, &Error)))
+ {
+ continue;
+ }
+ FromJson.Ref = uint16(VerseBridgeJson::Int(Vec, TEXT("ref")));
+ FromJson.Seq = uint32(VerseBridgeJson::Int(Frame, TEXT("seq")));
+ FromJson.Base = uint32(VerseBridgeJson::Int(Frame, TEXT("base")));
+ const FString Hex = VerseBridgeJson::Str(Vec, TEXT("bin_hex"));
+ TestEqual(FString::Printf(TEXT("%s encodes to the golden bytes"), *Name), ToHex(FromJson.Encode()), Hex);
+ FVerseCellsFrame Decoded;
+ if (TestTrue(FString::Printf(TEXT("%s decodes"), *Name), FVerseCellsFrame::Decode(FromHex(Hex), Decoded, &Error)))
+ {
+ TestEqual(TEXT("decoded re-encodes identically"), ToHex(Decoded.Encode()), Hex);
+ TestEqual(TEXT("rows"), Decoded.RowsChanged.Num(), FromJson.RowsChanged.Num());
+ for (int32 R = 0; R < FMath::Min(Decoded.RowsChanged.Num(), FromJson.RowsChanged.Num()); ++R)
+ {
+ for (int32 U = 0; U < FMath::Min(Decoded.RowsChanged[R].Runs.Num(), FromJson.RowsChanged[R].Runs.Num()); ++U)
+ {
+ TestEqual(TEXT("run text"), Decoded.RowsChanged[R].Runs[U].Text, FromJson.RowsChanged[R].Runs[U].Text);
+ }
+ }
+ }
+ ++Valid;
+ }
+ TestTrue(TEXT("valid vectors"), Valid >= 5);
+ for (const TSharedPtr<FJsonValue>& V : *VerseBridgeJson::Arr(Root, TEXT("invalid")))
+ {
+ const TSharedPtr<FJsonObject> Vec = V->AsObject();
+ FVerseCellsFrame Decoded;
+ TestFalse(FString::Printf(TEXT("%s is rejected"), *VerseBridgeJson::Str(Vec, TEXT("name"))),
+ FVerseCellsFrame::Decode(FromHex(VerseBridgeJson::Str(Vec, TEXT("bin_hex"))), Decoded));
+ }
+ return true;
+}
+
+// Feeds: snapshot + partial deltas + removals, unknown enum fallback, screens gap detection.
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBridgeFeedsTest, "Verse.Bridge.Feeds",
+ EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)
+
+bool FVerseBridgeFeedsTest::RunTest(const FString& Parameters)
+{
+ FVerseRosterFeed Roster;
+ int32 Changes = 0;
+ Roster.OnChanged.AddLambda([&Changes]() { ++Changes; });
+ for (const TSharedPtr<FJsonValue>& V : ReadArray(FPaths::Combine(BridgeDataDir(), TEXT("messages"), TEXT("roster.snapshot.json"))))
+ {
+ Roster.ApplySnapshot(VerseBridgeJson::Obj(V->AsObject(), TEXT("data")));
+ break;
+ }
+ TestTrue(TEXT("snapshot applied"), Roster.HasSnapshot() && Roster.GetAgents().Num() > 0);
+ FVerseAgent Mara;
+ TestTrue(TEXT("agent found"), Roster.FindAgent(TEXT("ag_7f1"), Mara));
+ TestEqual(TEXT("duty"), Mara.Duty, FString(TEXT("waiting")));
+ const TSharedPtr<FJsonObject> Delta = VerseBridgeJson::Read(TEXT(
+ "{\"upsert\":{\"agents\":[{\"agent_id\":\"ag_7f1\",\"duty\":\"dancing\",\"run_state\":\"working\"}],\"panes\":[]},"
+ "\"remove\":{\"agents\":[],\"panes\":[\"ws_91:T1\"]},\"commander\":null}"));
+ Roster.ApplyDelta(Delta);
+ TestTrue(TEXT("agent still found"), Roster.FindAgent(TEXT("ag_7f1"), Mara));
+ TestEqual(TEXT("unknown duty falls back to idle"), Mara.Duty, FString(TEXT("idle")));
+ TestEqual(TEXT("partial upsert keeps the name"), Mara.Name, FString(TEXT("Mara")));
+ FVersePane Pane;
+ TestFalse(TEXT("pane removed"), Roster.FindPane(TEXT("ws_91:T1"), Pane));
+ TestEqual(TEXT("two change notices"), Changes, 2);
+
+ FVerseScreensFeed Screens;
+ Screens.Bind(VerseBridgeJson::Read(TEXT("{\"bound\":[{\"pane_id\":\"ws_91:T1\",\"ref\":1}],\"dropped\":[],\"missing\":[]}")));
+ FVerseCellsFrame Snap;
+ Snap.bSnapshot = true;
+ Snap.Ref = 1;
+ Snap.Seq = 10;
+ Snap.Cols = 20;
+ Snap.Rows = 4;
+ TestTrue(TEXT("snapshot applies"), Screens.ApplyFrame(Snap));
+ FVerseCellsFrame Gap = Snap;
+ Gap.bSnapshot = false;
+ Gap.Seq = 14;
+ Gap.Base = 12;
+ TestFalse(TEXT("a delta on the wrong base is a gap"), Screens.ApplyFrame(Gap));
+ Gap.Base = 10;
+ TestTrue(TEXT("a delta on the last frame applies"), Screens.ApplyFrame(Gap));
+
+ TestEqual(TEXT("accept key (RFC 6455 example)"), FVerseWsClient::AcceptFor(TEXT("dGhlIHNhbXBsZSBub25jZQ==")), FString(TEXT("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=")));
+ FString Host, Path;
+ int32 Port = 0;
+ TestTrue(TEXT("loopback url"), FVerseWsClient::ParseUrl(TEXT("ws://127.0.0.1:8765/api/verse/bridge"), Host, Port, Path));
+ TestEqual(TEXT("port"), Port, 8765);
+ TestEqual(TEXT("path"), Path, FString(TEXT("/api/verse/bridge")));
+ TestFalse(TEXT("remote hosts are refused"), FVerseWsClient::ParseUrl(TEXT("ws://10.0.0.2:8765/x"), Host, Port, Path));
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseBridge/Private/VerseBridgeSubsystem.cpp b/unreal/Verse/Source/VerseBridge/Private/VerseBridgeSubsystem.cpp
new file mode 100644
index 0000000000..d720851f17
--- /dev/null
+++ b/unreal/Verse/Source/VerseBridge/Private/VerseBridgeSubsystem.cpp
@@ -0,0 +1,335 @@
+#include "VerseBridgeSubsystem.h"
+
+#include "Engine/Engine.h"
+#include "Engine/GameInstance.h"
+#include "Engine/GameViewportClient.h"
+#include "Framework/Application/IInputProcessor.h"
+#include "Framework/Application/SlateApplication.h"
+#include "HAL/IConsoleManager.h"
+#include "HAL/PlatformMisc.h"
+#include "HAL/PlatformProcess.h"
+#include "InputCoreTypes.h"
+#include "Kismet/GameplayStatics.h"
+#include "Misc/App.h"
+#include "Misc/CommandLine.h"
+#include "Misc/CoreDelegates.h"
+#include "Misc/FileHelper.h"
+#include "Misc/Paths.h"
+#include "Qa/VerseQaRegistry.h"
+#include "Scalability.h"
+#include "VerseLog.h"
+#include "Widgets/SWindow.h"
+
+#if PLATFORM_WINDOWS
+#include "Windows/WindowsHWrapper.h"
+#endif
+
+using namespace VerseBridgeJson;
+
+/** The engine side of IVerseLifecycleHost. */
+class FVerseEngineLifecycleHost : public IVerseLifecycleHost
+{
+public:
+ explicit FVerseEngineLifecycleHost(UGameInstance* InGameInstance, FVerseBridgeClient* InClient)
+ : GameInstance(InGameInstance)
+ , Client(InClient)
+ {
+ }
+
+ TSharedPtr<SWindow> Window() const
+ {
+ return GEngine && GEngine->GameViewport ? GEngine->GameViewport->GetWindow() : nullptr;
+ }
+
+ virtual void ShowWindow(const FVerseMonitor& Monitor, const FString& ActivationToken) override
+ {
+#if PLATFORM_LINUX
+ if (!ActivationToken.IsEmpty())
+ {
+ // xdg-activation: the app handed its token over the bridge (architecture 1.2).
+ FPlatformMisc::SetEnvironmentVar(TEXT("XDG_ACTIVATION_TOKEN"), *ActivationToken);
+ }
+#endif
+ if (TSharedPtr<SWindow> W = Window())
+ {
+ W->MoveWindowTo(FVector2D(Monitor.X, Monitor.Y));
+ W->Resize(FVector2D(Monitor.W, Monitor.H));
+ W->ShowWindow();
+ W->BringToFront(true);
+ FSlateApplication::Get().SetAllUserFocusToGameViewport();
+ }
+ }
+
+ virtual void HideWindow() override
+ {
+ if (TSharedPtr<SWindow> W = Window())
+ {
+ W->HideWindow();
+ }
+ }
+
+ virtual void SetRendering(bool bOn) override
+ {
+ if (GEngine && GEngine->GameViewport)
+ {
+ GEngine->GameViewport->bDisableWorldRendering = !bOn;
+ }
+ }
+
+ virtual void SetMaxFps(float Fps) override
+ {
+ if (IConsoleVariable* Var = IConsoleManager::Get().FindConsoleVariable(TEXT("t.MaxFPS")))
+ {
+ Var->Set(Fps, ECVF_SetByCode);
+ }
+ }
+
+ virtual void SetMuted(bool bMuted) override
+ {
+ FApp::SetVolumeMultiplier(bMuted ? 0.f : 1.f);
+ }
+
+ virtual void SetPaused(bool bPaused) override
+ {
+ if (GameInstance && GameInstance->GetWorld())
+ {
+ UGameplayStatics::SetGamePaused(GameInstance->GetWorld(), bPaused);
+ }
+ }
+
+ virtual void SetLowScalability(bool bLow) override
+ {
+ if (bLow && !bLowered)
+ {
+ Saved = Scalability::GetQualityLevels();
+ Scalability::FQualityLevels Low = Saved;
+ Low.SetFromSingleQualityLevel(0);
+ Scalability::SetQualityLevels(Low);
+ bLowered = true;
+ }
+ else if (!bLow && bLowered)
+ {
+ Scalability::SetQualityLevels(Saved);
+ bLowered = false;
+ }
+ }
+
+ virtual void AllowForeground(int32 Pid) override
+ {
+#if PLATFORM_WINDOWS
+ if (Pid > 0)
+ {
+ ::AllowSetForegroundWindow(static_cast<DWORD>(Pid));
+ }
+#endif
+ }
+
+ virtual bool SaveState() override
+ {
+ const FString Path = FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("VerseState.json"));
+ const TSharedPtr<FJsonObject> State = MakeShared<FJsonObject>();
+ State->SetObjectField(TEXT("settings"), Client ? Client->Settings.GetSettings() : MakeShared<FJsonObject>());
+ State->SetNumberField(TEXT("saved_at"), FDateTime::UtcNow().ToUnixTimestampDecimal());
+ return FFileHelper::SaveStringToFile(Write(State), *Path);
+ }
+
+ virtual void RequestExit() override
+ {
+ FPlatformMisc::RequestExit(false, TEXT("VerseLifecycle"));
+ }
+
+ virtual float Fps() const override
+ {
+ const double Dt = FApp::GetDeltaTime();
+ return Dt > 0.0 ? float(1.0 / Dt) : 0.f;
+ }
+
+private:
+ UGameInstance* GameInstance = nullptr;
+ FVerseBridgeClient* Client = nullptr;
+ Scalability::FQualityLevels Saved;
+ bool bLowered = false;
+};
+
+/** The one key back to the app (default F10, rebindable; Esc stays the in-game menu). */
+class FVerseReturnKeyProcessor : public IInputProcessor
+{
+public:
+ explicit FVerseReturnKeyProcessor(FVerseLifecycleController* InLifecycle)
+ : Lifecycle(InLifecycle)
+ {
+ }
+
+ virtual void Tick(const float DeltaTime, FSlateApplication& SlateApp, TSharedRef<ICursor> Cursor) override {}
+
+ virtual bool HandleKeyDownEvent(FSlateApplication& SlateApp, const FKeyEvent& InKeyEvent) override
+ {
+ if (!Lifecycle || Lifecycle->GetState() != EVerseLifecycleState::Visible)
+ {
+ return false;
+ }
+ const FKey Wanted(*Lifecycle->GetReturnKey());
+ if (InKeyEvent.GetKey() == Wanted && !InKeyEvent.IsRepeat())
+ {
+ Lifecycle->ReturnToApp(TEXT("return_key"));
+ return true;
+ }
+ return false;
+ }
+
+ virtual const TCHAR* GetDebugName() const override { return TEXT("VerseReturnKey"); }
+
+private:
+ FVerseLifecycleController* Lifecycle;
+};
+
+TArray<FString> UVerseBridgeSubsystem::DefaultTopics()
+{
+ return {TEXT("roster"), TEXT("panes"), TEXT("progression"), TEXT("groups"), TEXT("meetings"), TEXT("companion"), TEXT("lifecycle"), TEXT("panel")};
+}
+
+bool UVerseBridgeSubsystem::AcquireInstance()
+{
+ FPlatformProcess::FSemaphore* Lock = FPlatformProcess::NewInterprocessSynchObject(TEXT("DodaiosVerseInstance"), true, 1);
+ if (!Lock)
+ {
+ return true;
+ }
+ if (!Lock->TryLock(0))
+ {
+ FPlatformProcess::DeleteInterprocessSynchObject(Lock);
+ return false;
+ }
+ InstanceMutex = Lock;
+ return true;
+}
+
+void UVerseBridgeSubsystem::ReleaseInstance()
+{
+ if (InstanceMutex)
+ {
+ FPlatformProcess::FSemaphore* Lock = static_cast<FPlatformProcess::FSemaphore*>(InstanceMutex);
+ Lock->Unlock();
+ FPlatformProcess::DeleteInterprocessSynchObject(Lock);
+ InstanceMutex = nullptr;
+ }
+}
+
+void UVerseBridgeSubsystem::Initialize(FSubsystemCollectionBase& Collection)
+{
+ Super::Initialize(Collection);
+ BridgeClient = MakeShared<FVerseBridgeClient>();
+ EngineHost = MakeShared<FVerseEngineLifecycleHost>(GetGameInstance(), BridgeClient.Get());
+ LifecycleController = MakeShared<FVerseLifecycleController>(*EngineHost, *BridgeClient);
+
+ FVerseBridgeClient::FDiscovery Discovery;
+ const bool bSupervised = !FPlatformMisc::GetEnvironmentVariable(TEXT("DODAIOS_VERSE_TOKEN")).IsEmpty();
+ if (bSupervised)
+ {
+ bOwnsInstance = AcquireInstance();
+ if (!bOwnsInstance)
+ {
+ // A second launch hands its command line to the first and exits.
+ FFileHelper::SaveStringToFile(FCommandLine::Get(), *FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("Verse.handoff")));
+ UE_LOG(LogVerseBridge, Warning, TEXT("bridge: another Verse is running; handing over and exiting"));
+ FPlatformMisc::RequestExit(false, TEXT("VerseSingleInstance"));
+ return;
+ }
+ }
+ if (!FVerseBridgeClient::Discover(Discovery))
+ {
+ UE_LOG(LogVerseBridge, Log, TEXT("bridge: no backend to talk to (no DODAIOS_VERSE_BRIDGE, no dev discovery file)"));
+ return;
+ }
+ BridgeClient->Subscribe(DefaultTopics());
+ BridgeClient->OnFrame.AddLambda([this](const FVerseBridgeFrame& F) { LifecycleController->HandleFrame(F); });
+ BridgeClient->OnLaunchOver.AddLambda([this]() { LifecycleController->LaunchOver(); });
+ BridgeClient->OnServerCommand.AddUObject(this, &UVerseBridgeSubsystem::HandleServerCommand);
+ BridgeClient->Start(Discovery);
+ bConnected = true;
+ TickHandle = FTSTicker::GetCoreTicker().AddTicker(FTickerDelegate::CreateUObject(this, &UVerseBridgeSubsystem::Tick));
+ if (FSlateApplication::IsInitialized())
+ {
+ ReturnKey = MakeShared<FVerseReturnKeyProcessor>(LifecycleController.Get());
+ FSlateApplication::Get().RegisterInputPreProcessor(ReturnKey);
+ }
+ EndFrameHandle = FCoreDelegates::OnEndFrame.AddLambda([this]()
+ {
+ if (GEngine && GEngine->GameViewport && GFrameCounter > 2)
+ {
+ LifecycleController->NotifyFirstFrame((FPlatformTime::Seconds() - GStartTime) * 1000.0);
+ FCoreDelegates::OnEndFrame.Remove(EndFrameHandle);
+ }
+ });
+}
+
+void UVerseBridgeSubsystem::Deinitialize()
+{
+ if (TickHandle.IsValid())
+ {
+ FTSTicker::GetCoreTicker().RemoveTicker(TickHandle);
+ }
+ if (EndFrameHandle.IsValid())
+ {
+ FCoreDelegates::OnEndFrame.Remove(EndFrameHandle);
+ }
+ if (ReturnKey.IsValid() && FSlateApplication::IsInitialized())
+ {
+ FSlateApplication::Get().UnregisterInputPreProcessor(ReturnKey);
+ }
+ if (BridgeClient)
+ {
+ BridgeClient->Stop();
+ }
+ ReleaseInstance();
+ LifecycleController.Reset();
+ EngineHost.Reset();
+ BridgeClient.Reset();
+ Super::Deinitialize();
+}
+
+bool UVerseBridgeSubsystem::Tick(float DeltaSeconds)
+{
+ if (BridgeClient)
+ {
+ BridgeClient->Tick(FPlatformTime::Seconds());
+ }
+ return true;
+}
+
+void UVerseBridgeSubsystem::HandleServerCommand(const FVerseBridgeFrame& Frame)
+{
+ // qa.exec (bridge-protocol.md 14): the backend forwards it only with DODAIOS_VERSE_QA=1.
+ UVerseQaRegistry* Registry = UVerseQaRegistry::Get();
+ if (!Registry)
+ {
+ BridgeClient->Reply(Frame.Id, false, nullptr, TEXT("unavailable"), TEXT("QA registry is not running."));
+ return;
+ }
+ TArray<FString> Args;
+ if (const TArray<TSharedPtr<FJsonValue>>* A = Arr(Frame.Data, TEXT("args")))
+ {
+ for (const TSharedPtr<FJsonValue>& V : *A)
+ {
+ Args.Add(V->AsString());
+ }
+ }
+ FString Out;
+ const FString Command = Str(Frame.Data, TEXT("command"));
+ if (!Registry->Execute(Command, Args, Out))
+ {
+ BridgeClient->Reply(Frame.Id, false, nullptr, TEXT("not_found"), Out);
+ return;
+ }
+ TSharedPtr<FJsonObject> Result = MakeShared<FJsonObject>();
+ const TSharedPtr<FJsonObject> Parsed = Read(Out);
+ if (Parsed.IsValid())
+ {
+ Result->SetObjectField(TEXT("result"), Parsed);
+ }
+ else
+ {
+ Result->SetStringField(TEXT("result"), Out);
+ }
+ BridgeClient->Reply(Frame.Id, true, Result);
+}
diff --git a/unreal/Verse/Source/VerseBridge/Public/Bridge/VerseBridgeClient.h b/unreal/Verse/Source/VerseBridge/Public/Bridge/VerseBridgeClient.h
new file mode 100644
index 0000000000..dda65d04ad
--- /dev/null
+++ b/unreal/Verse/Source/VerseBridge/Public/Bridge/VerseBridgeClient.h
@@ -0,0 +1,121 @@
+#pragma once
+
+#include "CoreMinimal.h"
+#include "Bridge/VerseBridgeCodec.h"
+#include "Bridge/VerseBridgeFeeds.h"
+#include "Bridge/VerseWsClient.h"
+
+/**
+ * The Verse side of verse.bridge/1 (WP17.11, bridge-protocol.md 1-3, 8): discovery, hello,
+ * ping every second, 5 s dead-link rule, reconnect with backoff (250 ms, 1 s, 2 s, 4 s, then
+ * every 5 s) and the same token, fresh snapshots on resubscribe (no replay), seq gap
+ * detection with resync, typed feeds, and commands with exactly one reply each.
+ *
+ * Plain C++ so it is testable outside a world: UVerseBridgeSubsystem owns one and ticks it.
+ */
+class VERSEBRIDGE_API FVerseBridgeClient
+{
+public:
+ using FReply = TFunction<void(bool bOk, const TSharedPtr<FJsonObject>& Result, const FString& ErrorCode)>;
+
+ enum class EState : uint8
+ {
+ Idle,
+ Connecting,
+ Handshaking,
+ Linked,
+ Waiting, // backing off before the next attempt
+ LaunchOver // 4401 on reconnect: the launch is over
+ };
+
+ struct FDiscovery
+ {
+ FString Url;
+ FString Token;
+ };
+
+ /** DODAIOS_VERSE_BRIDGE + DODAIOS_VERSE_TOKEN, else (non-Shipping) <DATA_DIR>/verse/bridge.json. */
+ static bool Discover(FDiscovery& Out, const FString& DevFileOverride = FString());
+
+ FVerseBridgeClient();
+ ~FVerseBridgeClient();
+
+ void Start(const FDiscovery& Discovery);
+ void Stop();
+
+ /** Drains socket events and runs timers; Now is seconds (FPlatformTime::Seconds). */
+ void Tick(double Now);
+
+ /** A command: exactly one reply comes back (a lost link answers internal). */
+ FString SendCommand(const FString& Type, TSharedPtr<FJsonObject> Data, FReply OnReply = FReply());
+ /** A notice: no id, no reply (lifecycle.state, log, ...). */
+ void SendNotice(const FString& Type, TSharedPtr<FJsonObject> Data);
+
+ /** Topics to (re)subscribe after every welcome. */
+ void Subscribe(const TArray<FString>& Topics);
+ void WatchScreens(const TArray<TPair<FString, int32>>& PanesNearestFirst);
+ void WatchChatTails(const TArray<FString>& AgentIds);
+
+ EState GetState() const { return State; }
+ bool IsLinked() const { return State == EState::Linked; }
+ TSharedPtr<FJsonObject> GetWelcome() const { return Welcome; }
+ int64 GetLastSeq() const { return LastSeq; }
+ int32 GetAttempts() const { return Attempts; }
+
+ /** Every server frame after the client handled it (lifecycle, panel, gpu and tests). */
+ TMulticastDelegate<void(const FVerseBridgeFrame&)> OnFrame;
+ TMulticastDelegate<void()> OnLinked;
+ TMulticastDelegate<void(int32 /*CloseCode*/)> OnUnlinked;
+ TMulticastDelegate<void()> OnLaunchOver;
+ /** A server -> Verse command (qa.exec): answer with Reply(Frame.Id, ...). */
+ TMulticastDelegate<void(const FVerseBridgeFrame&)> OnServerCommand;
+
+ void Reply(const FString& Re, bool bOk, TSharedPtr<FJsonObject> Result, const FString& ErrorCode = FString(), const FString& Message = FString());
+
+ FVerseRosterFeed Roster;
+ FVerseGroupsFeed Groups;
+ FVerseScreensFeed Screens;
+ FVerseChatTailsFeed ChatTails;
+ FVerseProgressionFeed Progression;
+ FVerseCompanionFeed Companion;
+ FVerseSettingsFeed Settings;
+
+ /** Build info sent in hello. */
+ FString BuildVersion = TEXT("0.1.0");
+ FString BuildChangelist;
+ bool bPreferJsonScreens = false;
+
+ static constexpr double PingInterval = 1.0;
+ static constexpr double DeadLink = 5.0;
+ static double BackoffFor(int32 Attempt);
+
+private:
+ void Connect(double Now);
+ void HandleText(const FString& Text, double Now);
+ void HandleBinary(const TArray<uint8>& Bytes, double Now);
+ void HandleClosed(int32 Code, double Now);
+ void Dispatch(const FVerseBridgeFrame& Frame);
+ bool CheckBase(const FString& Slot, const FVerseBridgeFrame& Frame);
+ void Resync(const FString& Topic, const FString& PaneId = FString());
+ void SendFrame(const FVerseBridgeFrame& Frame);
+ void FailPending(const FString& Code);
+ void Unlink(int32 Code, double Now);
+
+ FVerseWsClient Socket;
+ FDiscovery Target;
+ EState State = EState::Idle;
+ double NextAttemptAt = 0.0;
+ double LastFrameAt = 0.0;
+ double LastPingAt = 0.0;
+ int32 Attempts = 0;
+ bool bEverLinked = false;
+ int64 LastSeq = 0;
+ int32 NextId = 1;
+ TSharedPtr<FJsonObject> Welcome;
+ TMap<FString, FReply> Pending;
+ TMap<FString, int64> LastSeqOf;
+ TArray<FString> Topics;
+ TArray<TPair<FString, int32>> ScreenWatch;
+ TArray<FString> ChatWatch;
+ TMap<FString, FString> ResyncInFlight;
+};
diff --git a/unreal/Verse/Source/VerseBridge/Public/Bridge/VerseBridgeCodec.h b/unreal/Verse/Source/VerseBridge/Public/Bridge/VerseBridgeCodec.h
new file mode 100644
index 0000000000..be6e410b86
--- /dev/null
+++ b/unreal/Verse/Source/VerseBridge/Public/Bridge/VerseBridgeCodec.h
@@ -0,0 +1,71 @@
+#pragma once
+
+#include "CoreMinimal.h"
+#include "Dom/JsonObject.h"
+
+/**
+ * verse.bridge/1 envelope (docs/verse/unreal/contracts/bridge-protocol.md section 2).
+ *
+ * Every JSON frame is one object { type, seq?, base?, id?, re?, ts, data }. Unknown fields are
+ * ignored; a frame without a string "type" or with a non-object "data" is malformed.
+ */
+namespace VerseBridge
+{
+ static constexpr const TCHAR* Protocol = TEXT("verse.bridge/1");
+
+ /** Close codes of contract section 1. */
+ enum class ECloseCode : int32
+ {
+ Normal = 1000,
+ TooBig = 1009,
+ TryLater = 1013,
+ BadHello = 4400,
+ Token = 4401,
+ Peer = 4403,
+ Replaced = 4409,
+ Protocol = 4426,
+ };
+}
+
+struct VERSEBRIDGE_API FVerseBridgeFrame
+{
+ FString Type;
+ /** -1 when absent (Verse -> server frames carry none). */
+ int64 Seq = -1;
+ int64 Base = -1;
+ FString Id;
+ FString Re;
+ double Ts = 0.0;
+ TSharedPtr<FJsonObject> Data;
+
+ bool HasBase() const { return Base >= 0; }
+ bool IsReply() const { return Type == TEXT("reply"); }
+
+ /** Parses one text frame; false on a malformed envelope. */
+ static bool Parse(const FString& Text, FVerseBridgeFrame& Out, FString* OutError = nullptr);
+
+ /** Compact JSON in the envelope order type, seq, base, re, id, ts, data. */
+ FString Encode() const;
+
+ /** A Verse -> server frame: { type, id?, ts, data }. */
+ static FVerseBridgeFrame Make(const FString& Type, TSharedPtr<FJsonObject> Data, const FString& Id = FString());
+};
+
+namespace VerseBridgeJson
+{
+ /** Deep equality of two JSON values (object key order ignored, numbers by value). */
+ VERSEBRIDGE_API bool Equal(const TSharedPtr<FJsonValue>& A, const TSharedPtr<FJsonValue>& B);
+ VERSEBRIDGE_API bool Equal(const TSharedPtr<FJsonObject>& A, const TSharedPtr<FJsonObject>& B);
+ VERSEBRIDGE_API FString Write(const TSharedPtr<FJsonObject>& Object);
+ VERSEBRIDGE_API TSharedPtr<FJsonObject> Read(const FString& Text);
+
+ VERSEBRIDGE_API FString Str(const TSharedPtr<FJsonObject>& O, const TCHAR* Field, const FString& Default = FString());
+ VERSEBRIDGE_API int64 Int(const TSharedPtr<FJsonObject>& O, const TCHAR* Field, int64 Default = 0);
+ VERSEBRIDGE_API double Num(const TSharedPtr<FJsonObject>& O, const TCHAR* Field, double Default = 0.0);
+ VERSEBRIDGE_API bool Bool(const TSharedPtr<FJsonObject>& O, const TCHAR* Field, bool Default = false);
+ VERSEBRIDGE_API TSharedPtr<FJsonObject> Obj(const TSharedPtr<FJsonObject>& O, const TCHAR* Field);
+ VERSEBRIDGE_API const TArray<TSharedPtr<FJsonValue>>* Arr(const TSharedPtr<FJsonObject>& O, const TCHAR* Field);
+
+ /** An enum value as sent, or the documented fallback for anything else (contract 2). */
+ VERSEBRIDGE_API FString Enum(const TSharedPtr<FJsonObject>& O, const TCHAR* Field, std::initializer_list<const TCHAR*> Allowed, const TCHAR* Fallback);
+}
diff --git a/unreal/Verse/Source/VerseBridge/Public/Bridge/VerseBridgeFeeds.h b/unreal/Verse/Source/VerseBridge/Public/Bridge/VerseBridgeFeeds.h
new file mode 100644
index 0000000000..25f0173c5f
--- /dev/null
+++ b/unreal/Verse/Source/VerseBridge/Public/Bridge/VerseBridgeFeeds.h
@@ -0,0 +1,228 @@
+#pragma once
+
+#include "CoreMinimal.h"
+#include "Bridge/VerseCellsCodec.h"
+#include "Dom/JsonObject.h"
+
+/**
+ * Typed feeds of verse.bridge/1 (bridge-protocol.md 4-7, 9, 14). Each feed keeps the
+ * server's view of one topic, applies snapshots and partial deltas, and tells listeners
+ * what changed. Unknown enum values read as the documented fallback.
+ */
+
+struct VERSEBRIDGE_API FVerseAgent
+{
+ FString AgentId;
+ FString Name;
+ FString Title;
+ FString Tier;
+ FString Lifecycle; // active | paused
+ FString RunState; // paused | waiting | working | idle
+ FString WaitingReason;
+ FString Duty; // working | waiting | idle | paused | error
+ int32 Level = 1;
+ FString Rank;
+ FString Look;
+ FString Archetype;
+ FString Palette;
+ TArray<FString> TeamIds;
+ FString PaneId;
+
+ static FVerseAgent FromJson(const TSharedPtr<FJsonObject>& O);
+};
+
+struct VERSEBRIDGE_API FVersePane
+{
+ FString PaneId;
+ FString WorkspaceId;
+ FString Key;
+ FString Name;
+ FString DisplayName;
+ FString Agent;
+ FString Title;
+ FString Status; // pending | live | exited | error
+ FString Activity; // starting | working | waiting | asking | failed | exited | stopped | unknown | ""
+ double ActivitySince = 0.0;
+ bool bWorked = false;
+ FString Duty;
+ bool bWorkspaceActive = false;
+ int32 Cols = 80;
+ int32 Rows = 24;
+
+ static FVersePane FromJson(const TSharedPtr<FJsonObject>& O);
+};
+
+struct VERSEBRIDGE_API FVerseCommander
+{
+ int32 Level = 1;
+ FString Rank;
+ FString Title;
+ FString Uniform;
+};
+
+DECLARE_MULTICAST_DELEGATE(FVerseFeedChanged);
+
+/** Rows keyed by id, merged from snapshots and partial upserts. */
+class VERSEBRIDGE_API FVerseKeyedRows
+{
+public:
+ void Reset() { Rows.Reset(); }
+ void Replace(const TArray<TSharedPtr<FJsonValue>>* List, const TCHAR* IdField);
+ /** Merges partial rows (id plus changed fields; unknown ids arrive complete). */
+ void Upsert(const TArray<TSharedPtr<FJsonValue>>* List, const TCHAR* IdField);
+ void Remove(const TArray<TSharedPtr<FJsonValue>>* Ids);
+ const TMap<FString, TSharedPtr<FJsonObject>>& Get() const { return Rows; }
+
+private:
+ TMap<FString, TSharedPtr<FJsonObject>> Rows;
+};
+
+class VERSEBRIDGE_API FVerseRosterFeed
+{
+public:
+ void ApplySnapshot(const TSharedPtr<FJsonObject>& Data);
+ void ApplyDelta(const TSharedPtr<FJsonObject>& Data);
+
+ TArray<FVerseAgent> GetAgents() const;
+ TArray<FVersePane> GetPanes() const;
+ bool FindAgent(const FString& AgentId, FVerseAgent& Out) const;
+ bool FindPane(const FString& PaneId, FVersePane& Out) const;
+ const FVerseCommander& GetCommander() const { return Commander; }
+ bool HasSnapshot() const { return bHasSnapshot; }
+
+ FVerseFeedChanged OnChanged;
+
+private:
+ void ReadCommander(const TSharedPtr<FJsonObject>& O);
+
+ FVerseKeyedRows Agents;
+ FVerseKeyedRows Panes;
+ FVerseCommander Commander;
+ bool bHasSnapshot = false;
+};
+
+class VERSEBRIDGE_API FVerseGroupsFeed
+{
+public:
+ void ApplySnapshot(const TSharedPtr<FJsonObject>& Data);
+ void ApplyDelta(const TSharedPtr<FJsonObject>& Data);
+ void ApplyMeeting(const TSharedPtr<FJsonObject>& Data);
+
+ const TMap<FString, TSharedPtr<FJsonObject>>& GetGroups() const { return Groups.Get(); }
+ /** The last meetings.update per group. */
+ const TMap<FString, TSharedPtr<FJsonObject>>& GetMeetings() const { return Meetings; }
+
+ FVerseFeedChanged OnChanged;
+ TMulticastDelegate<void(const FString& /*GroupId*/)> OnMeeting;
+
+private:
+ FVerseKeyedRows Groups;
+ TMap<FString, TSharedPtr<FJsonObject>> Meetings;
+};
+
+/** One desk monitor's grid, rebuilt from cells frames. */
+struct VERSEBRIDGE_API FVerseScreen
+{
+ FString PaneId;
+ uint16 Cols = 0;
+ uint16 Rows = 0;
+ int16 CursorRow = -1;
+ int16 CursorCol = -1;
+ bool bStyled = true;
+ bool bCut = false;
+ double At = 0.0;
+ /** Row index -> the row's runs (absent rows are blank). */
+ TMap<uint16, FVerseCellRow> Lines;
+ uint32 LastSeq = 0;
+};
+
+class VERSEBRIDGE_API FVerseScreensFeed
+{
+public:
+ /** Applies a screens.watch reply: binds refs to pane ids. */
+ void Bind(const TSharedPtr<FJsonObject>& Result);
+ void ApplyMeta(const TSharedPtr<FJsonObject>& Data);
+ /** Returns false when a delta does not apply on top of the last frame (gap: resync). */
+ bool ApplyFrame(const FVerseCellsFrame& Frame, const FString& PaneIdOverride = FString());
+ void ApplyGone(const TSharedPtr<FJsonObject>& Data);
+ void Reset();
+
+ const FVerseScreen* Find(const FString& PaneId) const { return Screens.Find(PaneId); }
+ FString PaneForRef(uint16 Ref) const;
+
+ TMulticastDelegate<void(const FString& /*PaneId*/)> OnFrame;
+ TMulticastDelegate<void(const FString& /*PaneId*/, const FString& /*Reason*/)> OnGone;
+
+private:
+ TMap<uint16, FString> Refs;
+ TMap<FString, FVerseScreen> Screens;
+};
+
+struct FVerseChatLine
+{
+ FString Kind; // user | agent | tool | notice | error
+ FString Text;
+};
+
+class VERSEBRIDGE_API FVerseChatTailsFeed
+{
+public:
+ void Apply(const TSharedPtr<FJsonObject>& Data);
+ const TArray<FVerseChatLine>* Find(const FString& AgentId) const { return Lines.Find(AgentId); }
+
+ TMulticastDelegate<void(const FString& /*AgentId*/)> OnUpdate;
+
+private:
+ TMap<FString, TArray<FVerseChatLine>> Lines;
+ TMap<FString, FString> Versions;
+};
+
+class VERSEBRIDGE_API FVerseProgressionFeed
+{
+public:
+ void ApplySnapshot(const TSharedPtr<FJsonObject>& Data);
+ void ApplyAward(const TSharedPtr<FJsonObject>& Data);
+
+ TSharedPtr<FJsonObject> GetSnapshot() const { return Snapshot; }
+ int64 GetToldSeq() const { return ToldSeq; }
+ void SetToldSeq(int64 Seq) { ToldSeq = FMath::Max(ToldSeq, Seq); }
+ int32 LevelOf(const FString& SubjectId) const;
+
+ FVerseFeedChanged OnChanged;
+ TMulticastDelegate<void(const TSharedPtr<FJsonObject>& /*Award*/)> OnAward;
+
+private:
+ TSharedPtr<FJsonObject> Snapshot;
+ int64 ToldSeq = 0;
+};
+
+class VERSEBRIDGE_API FVerseCompanionFeed
+{
+public:
+ void Apply(const TSharedPtr<FJsonObject>& Data);
+ FString PetId;
+ FString Look;
+ FString Style;
+ FVerseFeedChanged OnChanged;
+};
+
+/** Locale and verse.* settings from welcome and settings.changed (contract 3.2, 12). */
+class VERSEBRIDGE_API FVerseSettingsFeed
+{
+public:
+ void ApplyWelcome(const TSharedPtr<FJsonObject>& Welcome);
+ void ApplyChanged(const TSharedPtr<FJsonObject>& Data);
+
+ /** A localised string by key ("verse.ranks.duty.working"), or the key itself. */
+ FString Text(const FString& Key) const;
+ FString GetLang() const { return Lang; }
+ TSharedPtr<FJsonObject> GetSettings() const { return Settings; }
+ FString ReturnKey() const;
+
+ FVerseFeedChanged OnChanged;
+
+private:
+ FString Lang = TEXT("en");
+ TMap<FString, FString> Strings;
+ TSharedPtr<FJsonObject> Settings = MakeShared<FJsonObject>();
+};
diff --git a/unreal/Verse/Source/VerseBridge/Public/Bridge/VerseCellsCodec.h b/unreal/Verse/Source/VerseBridge/Public/Bridge/VerseCellsCodec.h
new file mode 100644
index 0000000000..532648922f
--- /dev/null
+++ b/unreal/Verse/Source/VerseBridge/Public/Bridge/VerseCellsCodec.h
@@ -0,0 +1,90 @@
+#pragma once
+
+#include "CoreMinimal.h"
+#include "Dom/JsonObject.h"
+
+/**
+ * Terminal screen cells: cells.bin/1 and cells.json/1 (bridge-protocol.md 5.4).
+ *
+ * Little endian: "VC", version 1, kind (1 snapshot, 2 delta), u16 ref, u32 seq, u32 base,
+ * u16 cols, u16 rows, i16 cursor row, i16 cursor col, u16 row count, then row records
+ * (u16 row, u16 run count, runs: u16 col, u16 cells, u32 fg, u32 bg, u16 attrs, u16 bytes, UTF-8).
+ * Colour u32: high byte mode (0 default, 1 palette index, 2 RGB). Attribute bits: bold, dim,
+ * italic, underline, inverse, strikethrough, invisible, blink, wide.
+ */
+namespace VerseCells
+{
+ enum EAttr : uint16
+ {
+ Bold = 1 << 0,
+ Dim = 1 << 1,
+ Italic = 1 << 2,
+ Underline = 1 << 3,
+ Inverse = 1 << 4,
+ Strikethrough = 1 << 5,
+ Invisible = 1 << 6,
+ Blink = 1 << 7,
+ Wide = 1 << 8,
+ AllAttrs = (1 << 9) - 1,
+ };
+
+ static constexpr uint32 DefaultColour = 0;
+ static constexpr int32 MaxCols = 240;
+ static constexpr int32 MaxRows = 60;
+ static constexpr int32 HeaderSize = 24;
+
+ inline uint32 Mode(uint32 Colour) { return Colour >> 24; }
+
+ /** Grapheme clusters in UTF-8 bytes with the contract's simplified rules (combining marks,
+ * ZWJ sequences, variation selectors, skin-tone modifiers and tag characters extend). */
+ VERSEBRIDGE_API int32 CountGraphemes(const uint8* Utf8, int32 Bytes, bool* bValidUtf8 = nullptr);
+}
+
+struct FVerseCellRun
+{
+ uint16 Col = 0;
+ uint16 Cells = 0;
+ uint32 Fg = VerseCells::DefaultColour;
+ uint32 Bg = VerseCells::DefaultColour;
+ uint16 Attrs = 0;
+ /** The run's UTF-8 bytes as sent, and as text. */
+ TArray<uint8> Utf8;
+ FString Text;
+
+ /** Columns the run covers (a wide glyph covers two). */
+ int32 Span() const { return Cells * ((Attrs & VerseCells::Wide) ? 2 : 1); }
+};
+
+struct FVerseCellRow
+{
+ uint16 Row = 0;
+ TArray<FVerseCellRun> Runs;
+};
+
+struct VERSEBRIDGE_API FVerseCellsFrame
+{
+ bool bSnapshot = true;
+ uint16 Ref = 0;
+ uint32 Seq = 0;
+ uint32 Base = 0;
+ uint16 Cols = 0;
+ uint16 Rows = 0;
+ int16 CursorRow = -1;
+ int16 CursorCol = -1;
+ TArray<FVerseCellRow> RowsChanged;
+
+ /** Decodes a binary frame; false (with a reason) on anything malformed. */
+ static bool Decode(const TArray<uint8>& Blob, FVerseCellsFrame& Out, FString* OutError = nullptr);
+
+ /** Encodes this frame as cells.bin/1. */
+ TArray<uint8> Encode() const;
+
+ /** Reads the data object of a cells.json/1 screens.frame (ref and seq come from outside). */
+ static bool FromJson(const TSharedPtr<FJsonObject>& Data, FVerseCellsFrame& Out, FString* OutError = nullptr);
+
+ /** Rows inside the grid, each once, runs sorted, inside the row, not overlapping. */
+ bool CheckRows(FString* OutError = nullptr) const;
+
+ static uint32 ColourFromJson(const TSharedPtr<FJsonValue>& Value, bool& bOk);
+ static uint16 AttrsFromJson(const TArray<TSharedPtr<FJsonValue>>* Names, bool& bOk);
+};
diff --git a/unreal/Verse/Source/VerseBridge/Public/Bridge/VerseWsClient.h b/unreal/Verse/Source/VerseBridge/Public/Bridge/VerseWsClient.h
new file mode 100644
index 0000000000..134b161849
--- /dev/null
+++ b/unreal/Verse/Source/VerseBridge/Public/Bridge/VerseWsClient.h
@@ -0,0 +1,94 @@
+#pragma once
+
+#include "CoreMinimal.h"
+#include "Containers/Queue.h"
+#include "HAL/Runnable.h"
+
+class FSocket;
+class FRunnableThread;
+
+/**
+ * A minimal RFC 6455 WebSocket client for the loopback bridge (ws:// only, no extensions).
+ *
+ * The bridge is always 127.0.0.1 (bridge-protocol.md 1), so this needs no TLS and keeps the
+ * module inside the frozen dependency list (Core, CoreUObject, Engine; Sockets comes through
+ * Engine). Socket work runs on its own thread; events are queued and drained on the caller's
+ * thread with Poll(), so every callback runs on the game thread.
+ */
+class VERSEBRIDGE_API FVerseWsClient : public FRunnable
+{
+public:
+ struct FEvent
+ {
+ enum class EKind : uint8
+ {
+ Connected,
+ Text,
+ Binary,
+ Closed,
+ };
+ EKind Kind = EKind::Text;
+ FString Text;
+ TArray<uint8> Bytes;
+ int32 CloseCode = 0;
+ };
+
+ FVerseWsClient();
+ virtual ~FVerseWsClient() override;
+
+ /** Starts connecting to ws://host:port/path. False when the URL is not a loopback ws:// URL. */
+ bool Connect(const FString& Url);
+
+ /** Closes the socket (sends a close frame with Code when connected) and joins the thread. */
+ void Close(int32 Code = 1000);
+
+ void SendText(const FString& Text);
+ void SendBinary(const TArray<uint8>& Bytes);
+
+ /** Drains queued events (game thread). */
+ bool Poll(FEvent& Out) { return Events.Dequeue(Out); }
+
+ bool IsOpen() const { return bOpen; }
+
+ /** Parses ws://host:port/path; only loopback hosts are accepted. */
+ static bool ParseUrl(const FString& Url, FString& OutHost, int32& OutPort, FString& OutPath);
+
+ /** The Sec-WebSocket-Accept value for a key (RFC 6455 4.2.2). */
+ static FString AcceptFor(const FString& Key);
+
+ /** Encodes one masked client frame (exposed for tests). */
+ static void EncodeFrame(uint8 Opcode, const uint8* Payload, int64 Len, const uint8 Mask[4], TArray<uint8>& Out);
+
+ // FRunnable
+ virtual uint32 Run() override;
+ virtual void Stop() override { bStopping = true; }
+
+private:
+ struct FOutgoing
+ {
+ uint8 Opcode = 1;
+ TArray<uint8> Payload;
+ };
+
+ bool Handshake();
+ bool SendRaw(const uint8* Data, int32 Len);
+ bool SendFrame(uint8 Opcode, const TArray<uint8>& Payload);
+ bool ReadAvailable();
+ bool ProcessBuffer();
+ void Finish(int32 Code);
+
+ FString Host;
+ int32 Port = 0;
+ FString Path;
+ FSocket* Socket = nullptr;
+ FRunnableThread* Thread = nullptr;
+ TQueue<FOutgoing, EQueueMode::Mpsc> Outgoing;
+ TQueue<FEvent, EQueueMode::Spsc> Events;
+ TArray<uint8> Buffer;
+ TArray<uint8> Fragment;
+ uint8 FragmentOpcode = 0;
+ TAtomic<bool> bStopping{false};
+ TAtomic<bool> bOpen{false};
+ TAtomic<int32> CloseRequested{0};
+ bool bFinished = false;
+};
diff --git a/unreal/Verse/Source/VerseBridge/Public/Lifecycle/VerseLifecycle.h b/unreal/Verse/Source/VerseBridge/Public/Lifecycle/VerseLifecycle.h
new file mode 100644
index 0000000000..e3159ec921
--- /dev/null
+++ b/unreal/Verse/Source/VerseBridge/Public/Lifecycle/VerseLifecycle.h
@@ -0,0 +1,109 @@
+#pragma once
+
+#include "CoreMinimal.h"
+#include "Dom/JsonObject.h"
+
+class FVerseBridgeClient;
+struct FVerseBridgeFrame;
+
+/** Lifecycle states of Verse.exe (architecture.md 1.3; wire spelling lower case). */
+enum class EVerseLifecycleState : uint8
+{
+ Booting,
+ Visible,
+ Panel,
+ Dormant,
+ Exiting,
+};
+
+VERSEBRIDGE_API const TCHAR* LexToString(EVerseLifecycleState State);
+
+struct FVerseMonitor
+{
+ int32 X = 0;
+ int32 Y = 0;
+ int32 W = 1920;
+ int32 H = 1080;
+ float Dpi = 96.f;
+};
+
+/** What the lifecycle controller asks of the engine and the OS (faked in tests). */
+class IVerseLifecycleHost
+{
+public:
+ virtual ~IVerseLifecycleHost() = default;
+ virtual void ShowWindow(const FVerseMonitor& Monitor, const FString& ActivationToken) = 0;
+ virtual void HideWindow() = 0;
+ virtual void SetRendering(bool bOn) = 0;
+ virtual void SetMaxFps(float Fps) = 0;
+ virtual void SetMuted(bool bMuted) = 0;
+ virtual void SetPaused(bool bPaused) = 0;
+ virtual void SetLowScalability(bool bLow) = 0;
+ /** Windows AllowSetForegroundWindow; X11/Wayland hand-off on Linux. */
+ virtual void AllowForeground(int32 Pid) = 0;
+ /** Save match-free state (deck, position, settings); true when saved. */
+ virtual bool SaveState() = 0;
+ virtual void RequestExit() = 0;
+ virtual void ResizePanel(int32 W, int32 H, float Dpr) {}
+ virtual int32 VramMb() const { return 0; }
+ virtual float Fps() const { return 0.f; }
+ virtual double Now() const;
+};
+
+/**
+ * The lifecycle state machine (WP17.12, bridge-protocol.md 12): Booting, Visible, Panel,
+ * Dormant, Exiting. Applies lifecycle.*, panel.*, gpu.*, focus.app_took and settings.changed
+ * from the backend; reports lifecycle.state on every change, lifecycle.ready after the first
+ * frame, focus.return_to_app for the return key, lifecycle.bye on quit.
+ */
+class VERSEBRIDGE_API FVerseLifecycleController
+{
+public:
+ FVerseLifecycleController(IVerseLifecycleHost& InHost, FVerseBridgeClient& InClient);
+
+ /** Feed every server frame here (bound to FVerseBridgeClient::OnFrame). */
+ void HandleFrame(const FVerseBridgeFrame& Frame);
+
+ /** The return key (or a station, or the Esc menu): give the foreground back to the app. */
+ void ReturnToApp(const FString& Reason = TEXT("return_key"));
+
+ /** The first frame was presented; MsSinceStart is the process-relative time. */
+ void NotifyFirstFrame(double MsSinceStart);
+
+ /** The bridge said the launch is over (4401 on reconnect): save and quit. */
+ void LaunchOver();
+
+ /** The link came up: report the current state. */
+ void NotifyLinked();
+
+ EVerseLifecycleState GetState() const { return State; }
+ bool IsPanelVisible() const { return bPanelVisible; }
+ bool IsGpuYielded() const { return bGpuYield; }
+ FString GetReturnKey() const { return ReturnKey; }
+ int32 GetAppPid() const { return AppPid; }
+ /** Seconds the last lifecycle.show took to reach Visible (-1 before one). */
+ double GetLastShowSeconds() const { return LastShowSeconds; }
+
+ /** lifecycle.show with reason quick_start_duel: the arena opens straight away. */
+ TMulticastDelegate<void()> OnQuickStartDuel;
+ /** Before the bye: send any pending duel.result (WP21 hooks here). */
+ TMulticastDelegate<void(const FString& /*Reason*/)> OnQuitting;
+ TMulticastDelegate<void(EVerseLifecycleState)> OnStateChanged;
+
+private:
+ void Enter(EVerseLifecycleState Next);
+ void ReportState();
+ void Quit(const FString& Reason);
+
+ IVerseLifecycleHost& Host;
+ FVerseBridgeClient& Client;
+ EVerseLifecycleState State = EVerseLifecycleState::Booting;
+ bool bPanelVisible = false;
+ bool bGpuYield = false;
+ bool bPaused = false;
+ bool bReady = false;
+ FString ReturnKey = TEXT("F10");
+ int32 AppPid = 0;
+ double ShowAt = -1.0;
+ double LastShowSeconds = -1.0;
+};
diff --git a/unreal/Verse/Source/VerseBridge/Public/VerseBridgeSubsystem.h b/unreal/Verse/Source/VerseBridge/Public/VerseBridgeSubsystem.h
new file mode 100644
index 0000000000..41917f2ad0
--- /dev/null
+++ b/unreal/Verse/Source/VerseBridge/Public/VerseBridgeSubsystem.h
@@ -0,0 +1,59 @@
+#pragma once
+
+#include "CoreMinimal.h"
+#include "Bridge/VerseBridgeClient.h"
+#include "Containers/Ticker.h"
+#include "Lifecycle/VerseLifecycle.h"
+#include "Subsystems/GameInstanceSubsystem.h"
+
+#include "VerseBridgeSubsystem.generated.h"
+
+class FVerseEngineLifecycleHost;
+class FVerseReturnKeyProcessor;
+
+/**
+ * The bridge for game code: one per game instance. Finds the backend (environment, or the dev
+ * discovery file outside Shipping), keeps the link up, exposes the typed feeds and the command
+ * sender, runs the lifecycle state machine against the engine, answers qa.exec through
+ * UVerseQaRegistry, and holds the single-instance mutex (architecture 1.1).
+ *
+ * UVerseBridgeSubsystem* Bridge = GetGameInstance()->GetSubsystem<UVerseBridgeSubsystem>();
+ * Bridge->Client().Roster.OnChanged.AddLambda(...);
+ * Bridge->Client().SendCommand(TEXT("pane.open"), Data, OnReply);
+ */
+UCLASS()
+class VERSEBRIDGE_API UVerseBridgeSubsystem : public UGameInstanceSubsystem
+{
+ GENERATED_BODY()
+
+public:
+ virtual void Initialize(FSubsystemCollectionBase& Collection) override;
+ virtual void Deinitialize() override;
+
+ FVerseBridgeClient& Client() { return *BridgeClient; }
+ FVerseLifecycleController& Lifecycle() { return *LifecycleController; }
+
+ /** Whether this process owns the single-instance mutex (false: another Verse runs). */
+ bool OwnsInstance() const { return bOwnsInstance; }
+
+ /** Topics every Verse subscribes to; feeds of other topics subscribe on demand. */
+ static TArray<FString> DefaultTopics();
+
+private:
+ bool Tick(float DeltaSeconds);
+ void HandleServerCommand(const FVerseBridgeFrame& Frame);
+ bool AcquireInstance();
+ void ReleaseInstance();
+
+ // Shared pointers: their deleters are bound where the objects are made, so the
+ // engine host can stay a private type of the .cpp.
+ TSharedPtr<FVerseBridgeClient> BridgeClient;
+ TSharedPtr<FVerseEngineLifecycleHost> EngineHost;
+ TSharedPtr<FVerseLifecycleController> LifecycleController;
+ TSharedPtr<FVerseReturnKeyProcessor> ReturnKey;
+ FTSTicker::FDelegateHandle TickHandle;
+ FDelegateHandle EndFrameHandle;
+ bool bOwnsInstance = false;
+ bool bConnected = false;
+ void* InstanceMutex = nullptr;
+};
diff --git a/unreal/Verse/Source/VerseBridge/VerseBridge.Build.cs b/unreal/Verse/Source/VerseBridge/VerseBridge.Build.cs
index 51651f54e5..c4ec3d761e 100644
--- a/unreal/Verse/Source/VerseBridge/VerseBridge.Build.cs
+++ b/unreal/Verse/Source/VerseBridge/VerseBridge.Build.cs
@@ -9,7 +9,11 @@ public class VerseBridge : ModuleRules
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine" });
PublicDependencyModuleNames.AddRange(new string[] { "VerseCore" });
- // Json: the duel.result codec and its pending store (WP21.6, bridge-protocol.md 10).
- PrivateDependencyModuleNames.AddRange(new string[] { "Json" });
+ // Engine modules of the bridge client (WP17.11, 17.12): Json is in the public
+ // feed and codec headers and also serves the duel.result codec (WP21.6);
+ // Sockets carries the WebSocket client; Slate, SlateCore and InputCore move,
+ // show and focus the window and catch the return key.
+ PublicDependencyModuleNames.AddRange(new string[] { "Json" });
+ PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore", "InputCore", "Sockets" });
}
}