Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(society): import your own figure through the same gate, and size the card's canvas
rubenluetke10-beep459399f2651c
diff --git a/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx b/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsxindex dcdaeea276..a0b87fc2d5 100644--- a/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx+++ b/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx@@ -10,11 +10,11 @@* Until the society backend is bound, "Create" appends a sample row to this* window's roster (data.ts, the single swap point) and opens its card.*/-import { useEffect, useMemo, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import * as Collapsible from "@radix-ui/react-collapsible";import * as Dialog from "@radix-ui/react-dialog";import { useQuery } from "@tanstack/react-query";-import { ChevronDown, Shuffle, X } from "lucide-react";+import { ChevronDown, Shuffle, Upload, X } from "lucide-react";import { Button } from "@/components/ui/button";import { Combobox } from "@/components/ui/combobox";@@ -70,6 +70,10 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialoconst [focus, setFocus] = useState<string[]>([]);const [grants, setGrants] = useState<string[]>([]);const [toolQuery, setToolQuery] = useState("");+ const fileInput = useRef<HTMLInputElement>(null);+ const [importing, setImporting] = useState(false);+ const [importProblems, setImportProblems] = useState<string[] | null>(null);+ const [importedName, setImportedName] = useState<string | null>(null);const capabilities = useSocietyCapabilities(open);const [advanced, setAdvanced] = useState(false);const [submitting, setSubmitting] = useState(false);@@ -102,6 +106,8 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialosetFocus([]);setGrants([]);setToolQuery("");+ setImportProblems(null);+ setImportedName(null);setError(null);setSubmitting(false);}, [open]);@@ -115,6 +121,42 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialoif (preset) setRecipe((r) => ({ ...r, palette: { ...preset.palette } }));};+ /**+ * Import the person's own GLB: the backend runs the figure gate and keeps+ * the file only when it passes; its reasons come back verbatim otherwise.+ */+ const importFigure = async (file: File) => {+ setImporting(true);+ setImportProblems(null);+ try {+ const res = await fetch(`/api/society/figures?name=${encodeURIComponent(file.name.replace(/\.glb$/i, ""))}`, {+ method: "POST",+ headers: { "Content-Type": "model/gltf-binary" },+ body: file,+ });+ if (!res.ok) {+ const detail = (await res.json().catch(() => null)) as { detail?: unknown } | null;+ setImportProblems([typeof detail?.detail === "string" ? detail.detail : t("society.create.import_failed")]);+ return;+ }+ const payload = (await res.json()) as+ | { accepted: true; figure: { url: string; file: string; height_m: number | null } }+ | { accepted: false; problems: string[] };+ if (!payload.accepted) {+ setImportProblems(payload.problems);+ return;+ }+ setImportedName(payload.figure.file);+ setStyle("custom");+ setRecipe((r) => ({ ...r, model: payload.figure.url, parts: {}, style: "custom" }));+ } catch {+ setImportProblems([t("society.create.import_failed")]);+ } finally {+ setImporting(false);+ if (fileInput.current) fileInput.current.value = "";+ }+ };+const submit = async () => {if (!name.trim()) {setError(t("society.create.name_required"));@@ -390,6 +432,27 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialo<div className="shrink-0 border-t border-border p-4"><div className="mb-3 flex items-center justify-between"><span className={labelClass}>{t("society.create.look")}</span>+ <div className="flex items-center gap-1">+ <input+ ref={fileInput}+ type="file"+ accept=".glb,model/gltf-binary"+ className="hidden"+ onChange={(e) => {+ const file = e.target.files?.[0];+ if (file) void importFigure(file);+ }}+ />+ <button+ type="button"+ disabled={importing}+ onClick={() => fileInput.current?.click()}+ title={t("society.create.import_hint")}+ className="flex items-center gap-1 rounded-md px-2 py-1 text-xs text-muted-foreground hover:bg-secondary hover:text-foreground disabled:opacity-50"+ >+ <Upload className="h-3.5 w-3.5" aria-hidden />+ {importing ? t("society.create.importing") : t("society.create.import")}+ </button><buttontype="button"onClick={() => setRecipe((r) => ({ ...r, palette: shufflePalette() }))}@@ -398,7 +461,38 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialo<Shuffle className="h-3.5 w-3.5" aria-hidden />{t("society.create.shuffle")}</button>+ </div></div>+ {importProblems ? (+ <div role="alert" className="mb-3 rounded-md border border-destructive/40 bg-destructive/10 p-2 text-[11px] text-foreground">+ <p className="mb-1 font-medium">{t("society.create.import_rejected")}</p>+ <ul className="list-disc pl-4">+ {importProblems.map((p) => (+ <li key={p}>{p}</li>+ ))}+ </ul>+ </div>+ ) : null}+ {importedName && recipe.model ? (+ <p className="mb-3 text-[11px] text-muted-foreground">+ {t("society.create.import_ok").replace("{0}", importedName)}{" "}+ <button+ type="button"+ className="underline hover:text-foreground"+ onClick={() => {+ setImportedName(null);+ setStyle("modern");+ setRecipe((r) => {+ const next = { ...r, style: "modern" };+ delete next.model;+ return next;+ });+ }}+ >+ {t("society.create.import_reset")}+ </button>+ </p>+ ) : null}<div className="flex flex-col gap-3"><div className="flex items-center gap-3"><span className="w-16 text-[11px] text-muted-foreground">{t("society.create.style")}</span>diff --git a/jarvis/ui/web/frontend/src/components/society/figures/AgentFigureViewer.tsx b/jarvis/ui/web/frontend/src/components/society/figures/AgentFigureViewer.tsxindex 2c5fd31621..c15919bd10 100644--- a/jarvis/ui/web/frontend/src/components/society/figures/AgentFigureViewer.tsx+++ b/jarvis/ui/web/frontend/src/components/society/figures/AgentFigureViewer.tsx@@ -148,6 +148,7 @@ export function AgentFigureViewer({ recipe, clip = "idle", quiet = false, classNorbitTick={orbitTick}/></Suspense>+ <HostSizeSync /><PixelPass /></Canvas></FigureErrorBoundary>@@ -252,6 +253,32 @@ function FigureScene({ recipe, look, palette, heightM, clip, quiet, paused, orbi);}+/**+ * Keeps the renderer sized to its container. R3F measures its wrapper once+ * on mount and then through its own ResizeObserver; inside a dialog that+ * mounts mid-animation the first measure has come back 300×150 and the+ * observer never corrected it, so the figure was drawn into a thumbnail.+ * Observing the wrapper ourselves and pushing the size into the store is+ * cheap insurance.+ */+function HostSizeSync() {+ const gl = useThree((s) => s.gl);+ const setSize = useThree((s) => s.setSize);+ useEffect(() => {+ const wrapper = gl.domElement.parentElement;+ if (!wrapper || typeof ResizeObserver === "undefined") return;+ const sync = () => {+ const rect = wrapper.getBoundingClientRect();+ if (rect.width > 0 && rect.height > 0) setSize(rect.width, rect.height);+ };+ sync();+ const observer = new ResizeObserver(sync);+ observer.observe(wrapper);+ return () => observer.disconnect();+ }, [gl, setSize]);+ return null;+}+/** The island's look, in the card: the scene through a low-resolution, nearest-filtered target. */function PixelPass() {const { gl, scene, camera, size } = useThree();diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 36fa9b2256..b54693db73 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -3673,7 +3673,9 @@"empty_hint_prefix": "Ist das Backend frisch? Schau in","step_speak": "Sprich","now": "jetzt",- "ago_suffix": "her"+ "ago_suffix": "her",+ "run_missed": "verpasst",+ "run_missed_hint": "Die App lief zum geplanten Zeitpunkt nicht — übersprungen bis zum nächsten Termin."},"conductor_view": {"new_job": "Neuer Job",@@ -5221,6 +5223,13 @@"shoes": "Schuhe"},"create": {+ "import": ".glb importieren",+ "importing": "Wird geprüft…",+ "import_hint": "Bring deine eigene Figur mit — ein binäres glTF, das den Figurenvertrag einhält (docs/agent-society/character-pipeline.md).",+ "import_rejected": "Die Figur hält den Vertrag noch nicht ein:",+ "import_failed": "Die Figur konnte nicht importiert werden.",+ "import_ok": "{0} importiert — Teile und Palette kommen aus dem Katalog, das Modell ist deins.",+ "import_reset": "Zurück zum Katalog","tools_title": "Werkzeuge","focus_hint": "Wähle, wozu dieser Agent zuerst greifen soll; alle anderen erlaubten Werkzeuge behält er.","allowlist_hint": "Wähle die einzigen Werkzeuge, die dieser Agent nutzen darf.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 72c5544b13..6d158f4be0 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -3673,7 +3673,9 @@"empty_hint_prefix": "Is the backend fresh? Check","step_speak": "Speak","now": "now",- "ago_suffix": "ago"+ "ago_suffix": "ago",+ "run_missed": "missed",+ "run_missed_hint": "The app was not running at the scheduled time — skipped to the next occurrence."},"conductor_view": {"new_job": "New job",@@ -5221,6 +5223,13 @@"shoes": "Shoes"},"create": {+ "import": "Import .glb",+ "importing": "Checking…",+ "import_hint": "Bring your own figure — a binary glTF that honours the character contract (docs/agent-society/character-pipeline.md).",+ "import_rejected": "The figure does not honour the contract yet:",+ "import_failed": "The figure could not be imported.",+ "import_ok": "Imported {0} — parts and palette come from the catalog; the model is yours.",+ "import_reset": "Back to the catalog","tools_title": "Tools","focus_hint": "Pick what this agent should reach for first; it keeps every other tool the tiers allow.","allowlist_hint": "Pick the only tools this agent may use.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 86de3fff29..985ed54fe7 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -3673,7 +3673,9 @@"empty_hint_prefix": "¿El backend está recién creado? Mira en","step_speak": "Hablar","now": "ahora",- "ago_suffix": "atrás"+ "ago_suffix": "atrás",+ "run_missed": "omitida",+ "run_missed_hint": "La app no estaba en marcha a la hora programada — se saltó hasta la próxima."},"conductor_view": {"new_job": "Nuevo trabajo",@@ -5221,6 +5223,13 @@"shoes": "Zapatos"},"create": {+ "import": "Importar .glb",+ "importing": "Comprobando…",+ "import_hint": "Trae tu propia figura: un glTF binario que cumpla el contrato de personajes (docs/agent-society/character-pipeline.md).",+ "import_rejected": "La figura aún no cumple el contrato:",+ "import_failed": "No se pudo importar la figura.",+ "import_ok": "{0} importada: las piezas y la paleta vienen del catálogo; el modelo es tuyo.",+ "import_reset": "Volver al catálogo","tools_title": "Herramientas","focus_hint": "Elige qué debe usar primero este agente; conserva todas las demás herramientas permitidas.","allowlist_hint": "Elige las únicas herramientas que este agente puede usar.",diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex 2904c06bb3..a650ac8ffe 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -394,6 +394,7 @@ class WebServer:from .skills_routes import router as skills_routerfrom .socials_routes import router as socials_routerfrom .society_routes import router as society_router+ from .society_figure_routes import router as society_figure_routerfrom .starter_plan_routes import router as starter_plan_routerfrom .sub_agents_routes import router as sub_agents_routerfrom .tasks_routes import router as tasks_router@@ -573,6 +574,7 @@ class WebServer:set_society_factory(self._build_society_runtime)app.include_router(society_router)+ app.include_router(society_figure_router)app.include_router(drop_router)# Default: no recorder wired up — _init_session_stack() in start()# sets this once it succeeds.diff --git a/jarvis/ui/web/society_figure_routes.py b/jarvis/ui/web/society_figure_routes.pynew file mode 100644index 0000000000..b52caf7006--- /dev/null+++ b/jarvis/ui/web/society_figure_routes.py@@ -0,0 +1,164 @@+"""Imported society figures — a person's own characters, kept in the data dir.++The character pipeline (docs/agent-society/character-pipeline.md §8, the import+lane) lets anyone bring a figure of their own: a GLB that honours the same+contract every shipped figure honours. It is checked by the SAME gate the CI+runs (``scripts/ci/check_society_figures.py``), so a figure that faces the wrong+way or drifts its root is refused with the gate's own reasons instead of walking+backwards on the island. Accepted files live under ``DATA_DIR/society/figures``+and are served from here; a recipe references one by its URL (``model``).++Not a marketplace lane: nothing here is shared, uploaded elsewhere, or+attributed. It is the person's own file on the person's own machine.+"""++from __future__ import annotations++import hashlib+import importlib.util+import logging+import re+import sys+from pathlib import Path+from typing import Any++from fastapi import APIRouter, HTTPException, Query, Request+from fastapi.concurrency import run_in_threadpool+from fastapi.responses import FileResponse++from jarvis.core.config import DATA_DIR++log = logging.getLogger(__name__)++router = APIRouter(prefix="/api/society/figures", tags=["society"])++#: A base figure with nine 30-fps clips weighs ~400 KB; 12 MB leaves room for a+#: hand-built figure with a bigger sheet without inviting a stray video.+MAX_BYTES = 12 * 1024 * 1024+_GLB_MAGIC = b"glTF"+_REPO = Path(__file__).resolve().parents[3]+_GATE = _REPO / "scripts" / "ci" / "check_society_figures.py"+_SAFE_NAME = re.compile(r"[^a-z0-9]+")+++def figures_dir() -> Path:+ return DATA_DIR / "society" / "figures"+++def _load_gate():+ if "check_society_figures" in sys.modules:+ return sys.modules["check_society_figures"]+ if not _GATE.exists():+ return None+ spec = importlib.util.spec_from_file_location("check_society_figures", _GATE)+ module = importlib.util.module_from_spec(spec)+ assert spec and spec.loader+ sys.modules["check_society_figures"] = module+ spec.loader.exec_module(module)+ return module+++def _slug(name: str) -> str:+ return _SAFE_NAME.sub("-", name.lower()).strip("-")[:40] or "figure"+++def _extras(path: Path) -> dict[str, Any]:+ gate = _load_gate()+ if gate is None:+ return {}+ tools = gate._load_tools()+ try:+ doc = tools.read_glb(path).doc+ except (ValueError, OSError):+ return {}+ return (doc.get("asset", {}).get("extras") or {}).get("jarvis_figure") or {}+++def _describe(path: Path) -> dict[str, Any]:+ extras = _extras(path)+ return {+ "id": path.stem,+ "file": path.name,+ "url": f"/api/society/figures/{path.name}",+ "bytes": path.stat().st_size,+ "archetype": extras.get("archetype"),+ "height_m": extras.get("height_m"),+ "clips": sorted((extras.get("clips") or {}).keys()),+ "source": extras.get("source", ""),+ }+++async def list_figures() -> dict[str, Any]:+ folder = figures_dir()+ if not folder.exists():+ return {"figures": [], "total": 0}+ rows = await run_in_threadpool(lambda: [_describe(p) for p in sorted(folder.glob("*.glb"))])+ return {"figures": rows, "total": len(rows)}+++async def import_figure(request: Request, name: str = Query("figure")) -> dict[str, Any]:+ """Accept one GLB (raw body), run the figure gate, keep it only when it passes."""+ body = await request.body()+ if len(body) > MAX_BYTES:+ raise HTTPException(413, f"figure larger than {MAX_BYTES // (1024 * 1024)} MB")+ if len(body) < 12 or body[:4] != _GLB_MAGIC:+ raise HTTPException(400, "not a binary glTF (.glb) file")+ digest = hashlib.sha256(body).hexdigest()[:10]+ folder = figures_dir()+ folder.mkdir(parents=True, exist_ok=True)+ path = folder / f"{_slug(name)}-{digest}.glb"++ def _check_and_store() -> list[str]:+ gate = _load_gate()+ if gate is None:+ return ["the figure gate is not available on this install"]+ probe = path.with_suffix(".pending.glb")+ probe.write_bytes(body)+ try:+ problems = gate.check_file(probe, require_ledger=False)+ if problems:+ return problems+ probe.replace(path)+ return []+ finally:+ if probe.exists():+ probe.unlink()++ problems = await run_in_threadpool(_check_and_store)+ if problems:+ # The gate's own sentences: what to fix, in the order it found them.+ return {"accepted": False, "problems": problems}+ log.info("society figure imported: %s (%d bytes)", path.name, len(body))+ return {"accepted": True, "figure": _describe(path)}++[email protected]("/{file_name}")+def get_figure(file_name: str) -> FileResponse:+ path = figures_dir() / file_name+ if (+ not file_name.endswith(".glb")+ or "/" in file_name+ or "\\" in file_name+ or not path.is_file()+ ):+ raise HTTPException(404, "no such figure")+ return FileResponse(+ path, media_type="model/gltf-binary", headers={"Cache-Control": "public, max-age=31536000"}+ )++[email protected]("/{file_name}", openapi_extra={"x-jarvis-dangerous": True})+async def delete_figure(file_name: str) -> dict[str, Any]:+ path = figures_dir() / file_name+ if (+ not file_name.endswith(".glb")+ or "/" in file_name+ or "\\" in file_name+ or not path.is_file()+ ):+ raise HTTPException(404, "no such figure")+ await run_in_threadpool(path.unlink)+ return {"deleted": file_name}+diff --git a/scripts/ci/check_society_figures.py b/scripts/ci/check_society_figures.pyindex 5996650d26..ebaac8d7a4 100644--- a/scripts/ci/check_society_figures.py+++ b/scripts/ci/check_society_figures.py@@ -71,8 +71,13 @@ def check_file(path: Path,contract: dict | None = None,sources_md: Path | None = None,+ require_ledger: bool = True,) -> list[str]:- """Every contract violation of one GLB, as human-readable lines (empty = pass)."""+ """Every contract violation of one GLB, as human-readable lines (empty = pass).++ ``require_ledger=False`` is for a person's own imported figure: it must honour+ the contract like a shipped one, but it has no row in the provenance ledger.+ """gt = _load_tools()contract = contract or load_contract()limits = contract["limits"]@@ -322,9 +327,10 @@ def check_file(problems.append(f"needs a decoder we do not ship: {sorted(used & FORBIDDEN_EXTENSIONS)}")# 15 — provenance- ledger = sources_md if sources_md is not None else path.parent / "SOURCES.md"- if not ledger.exists() or f"`{path.name}`" not in ledger.read_text(encoding="utf-8"):- problems.append(f"no row for `{path.name}` in {ledger.name}")+ if require_ledger:+ ledger = sources_md if sources_md is not None else path.parent / "SOURCES.md"+ if not ledger.exists() or f"`{path.name}`" not in ledger.read_text(encoding="utf-8"):+ problems.append(f"no row for `{path.name}` in {ledger.name}")return problemsdiff --git a/tests/unit/ui/web/test_society_figure_routes.py b/tests/unit/ui/web/test_society_figure_routes.pynew file mode 100644index 0000000000..8e4eb80695--- /dev/null+++ b/tests/unit/ui/web/test_society_figure_routes.py@@ -0,0 +1,100 @@+"""The figure import lane keeps only figures that pass the same gate CI runs.++A person's own GLB is welcome on the island exactly when it honours the+character contract (docs/agent-society/character-pipeline.md §8): the route+refuses garbage, refuses a figure that faces the wrong way with the gate's own+reasons, and stores + serves a good one under the data dir.+"""++from __future__ import annotations++import importlib.util+import sys+from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++_REPO = Path(__file__).resolve().parents[4]+_FIGURES = _REPO / "jarvis" / "ui" / "web" / "frontend" / "src" / "assets" / "society" / "figures"+_TOOLS = _REPO / "scripts" / "figures" / "glb_tools.py"+++def _shipped() -> Path | None:+ files = sorted(_FIGURES.glob("biped-*.glb")) if _FIGURES.exists() else []+ return files[0] if files else None+++def _tools():+ if "glb_tools" in sys.modules:+ return sys.modules["glb_tools"]+ spec = importlib.util.spec_from_file_location("glb_tools", _TOOLS)+ mod = importlib.util.module_from_spec(spec)+ assert spec and spec.loader+ sys.modules["glb_tools"] = mod+ spec.loader.exec_module(mod)+ return mod+++def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:+ from jarvis.ui.web import society_figure_routes as routes++ monkeypatch.setattr(routes, "figures_dir", lambda: tmp_path / "figures")+ app = FastAPI()+ app.include_router(routes.router)+ return TestClient(app)+++def test_garbage_is_refused_as_not_a_glb(client: TestClient):+ res = client.post("/api/society/figures?name=x", content=b"hello world, not a model")+ assert res.status_code == 400++[email protected](_shipped() is None, reason="no figure asset built yet")+def test_a_contract_figure_is_accepted_stored_and_served(client: TestClient):+ body = _shipped().read_bytes() # type: ignore[union-attr]+ res = client.post("/api/society/figures?name=My Hero", content=body)+ assert res.status_code == 200, res.text+ payload = res.json()+ assert payload["accepted"] is True, payload+ figure = payload["figure"]+ assert figure["file"].startswith("my-hero-") and figure["file"].endswith(".glb")+ assert figure["archetype"] == "biped"+ assert "walk" in figure["clips"]++ listed = client.get("/api/society/figures").json()+ assert [f["file"] for f in listed["figures"]] == [figure["file"]]++ served = client.get(figure["url"])+ assert served.status_code == 200+ assert served.headers["content-type"].startswith("model/gltf-binary")+ assert served.content == body++ assert client.delete(figure["url"]).status_code == 200+ assert client.get("/api/society/figures").json()["total"] == 0++[email protected](_shipped() is None, reason="no figure asset built yet")+def test_a_figure_facing_the_wrong_way_is_refused_with_the_reason(+ client: TestClient, tmp_path: Path+):+ gt = _tools()+ glb = gt.read_glb(_shipped())+ names = gt.node_index_by_name(glb.doc)+ glb.doc["nodes"][names["FWD"]]["translation"] = [0.0, 0.5, -1.0]+ broken = tmp_path / "turned.glb"+ gt.write_glb(broken, glb.doc, glb.blob)++ res = client.post("/api/society/figures?name=turned", content=broken.read_bytes())+ assert res.status_code == 200+ payload = res.json()+ assert payload["accepted"] is False+ assert any("faces the wrong way" in p for p in payload["problems"])+ assert client.get("/api/society/figures").json()["total"] == 0+++def test_serving_never_leaves_the_figures_folder(client: TestClient):+ assert client.get("/api/society/figures/..%2F..%2Fjarvis.toml").status_code == 404+ assert client.get("/api/society/figures/nope.glb").status_code == 404