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.

5.2 KB
Raw Blame
"""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 copy import deepcopy
from pathlib import Path

import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient

_REPO = Path(__file__).resolve().parents[4]
_FIGURES = _REPO / "dodaios" / "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


@pytest.fixture
def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:
    from dodaios.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


@pytest.mark.skipif(_shipped() is None, reason="no figure asset built yet")
def test_a_contract_figure_is_accepted_stored_and_served(client: TestClient, tmp_path: Path):
    # Uploads are standalone. Shipped figures share a separate clip library,
    # so embed those existing clips in this test-only file before importing it.
    gt = _tools()
    shipped = _shipped()
    figure_glb = gt.read_glb(shipped)
    extras = gt.figure_extras(figure_glb.doc)
    library = gt.read_glb(shipped.with_name(extras.pop("clips_from")))
    nodes = gt.node_index_by_name(figure_glb.doc)
    figure_glb.doc["animations"] = deepcopy(library.doc["animations"])
    for animation in figure_glb.doc["animations"]:
        for sampler in animation["samplers"]:
            for field in ("input", "output"):
                index = sampler[field]
                sampler[field] = gt.append_accessor(
                    figure_glb, gt.accessor_values(library, index),
                    library.doc["accessors"][index]["type"],
                )
        for channel in animation["channels"]:
            node = library.doc["nodes"][channel["target"]["node"]]["name"]
            channel["target"]["node"] = nodes[node]
    standalone = tmp_path / "standalone.glb"
    gt.write_glb(standalone, figure_glb.doc, figure_glb.blob)
    body = standalone.read_bytes()
    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


@pytest.mark.skipif(_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


def test_hostile_names_never_reach_a_file_outside(client: TestClient, tmp_path: Path):
    outside = tmp_path / "outside.glb"
    outside.write_bytes(b"glTF-outside")
    for name in ("..%5Coutside.glb", "C%3Aoutside.glb", ".hidden.glb", "..glb"):
        assert client.get(f"/api/society/figures/{name}").status_code == 404
        assert client.delete(f"/api/society/figures/{name}").status_code == 404
    assert outside.exists()