fix: make asset revisions robust and route business pages

This commit is contained in:
eust-w 2026-07-13 14:27:16 +08:00
parent a922757052
commit a5d43db570
4 changed files with 148 additions and 4 deletions

View File

@ -464,9 +464,24 @@ def revise_scene_asset(
if delete:
emit(f"Removing asset {target.get('name') or asset_id} from the scene revision")
parent = next((node for node in worldbody.iter() if body in list(node)), None)
# ElementTree compares elements by identity in current CPython builds,
# but the explicit identity check also works with alternate XML
# implementations and avoids deleting the wrong nested body.
parent = next(
(
node
for node in worldbody.iter()
if any(child is body for child in list(node))
),
None,
)
if parent is None:
raise ValueError(f"scene asset body is not removable: {asset_id}")
removed_joint_names = {
str(node.get("name") or "")
for node in body.iter()
if node.tag in {"joint", "freejoint"} and node.get("name")
}
parent.remove(body)
mesh_names = {
str(geom.get("mesh") or "")
@ -478,6 +493,31 @@ def revise_scene_asset(
for mesh in list(asset_node.findall("mesh")):
if str(mesh.get("name") or "") in mesh_names or str(mesh.get("name") or "").startswith(f"{asset_id}_"):
asset_node.remove(mesh)
# A deleted body can be referenced by cameras, equality constraints or
# keyframes. Leaving those references behind makes an otherwise valid
# revision fail at the runtime loader. A fixed camera is still useful,
# so only remove the target-body mode when its target disappears.
for camera in root.iter("camera"):
if str(camera.get("target") or "") == str(asset_id):
camera.attrib.pop("target", None)
if camera.get("mode") == "targetbody":
camera.attrib.pop("mode", None)
equality = root.find("equality")
if equality is not None and removed_joint_names:
for constraint in list(equality):
if any(str(value or "") in removed_joint_names for value in constraint.attrib.values()):
equality.remove(constraint)
# Keyframe qpos/qvel arrays are indexed by the model's joints. Since
# the deleted asset may own a freejoint (7 qpos values), preserving an
# old keyframe can make nqpos inconsistent. The runtime can safely
# start from its model defaults when no keyframe block remains.
if removed_joint_names:
keyframe = root.find("keyframe")
if keyframe is not None:
root.remove(keyframe)
manifest["assets"] = [item for index, item in enumerate(assets) if index != target_index]
changed_asset = {"id": asset_id, "name": target.get("name"), "deleted": True}
operation = "deleted"

View File

@ -1,4 +1,4 @@
const STATIC_VERSION = "20260713-scene-library-assets-v7";
const STATIC_VERSION = "20260713-asset-delete-routes-v8";
const state = {
datasets: [],
@ -54,6 +54,43 @@ const taskScopes = {
inferTaskList: ["inference"],
};
// Keep each business area addressable and refresh-safe while retaining the
// existing static-shell deployment. Nginx falls back to index.html for these
// paths, so users can bookmark or share a page without a second frontend app.
const TAB_ROUTES = Object.freeze({
overview: "/",
data: "/data",
reconstruct: "/reconstruct",
scenes: "/scenes",
compose: "/compose",
collect: "/collect",
train: "/train",
infer: "/infer",
});
const TAB_TITLES = Object.freeze({
overview: "总览",
data: "数据管理",
reconstruct: "场景重建",
scenes: "场景管理",
compose: "场景组合",
collect: "数据采集",
train: "模型训练",
infer: "在线推理",
});
function tabFromLocation() {
const pathname = window.location.pathname.replace(/\/+$/, "") || "/";
return Object.entries(TAB_ROUTES).find(([, route]) => route === pathname)?.[0] || "overview";
}
function syncTabUrl(tabId, { replace = false } = {}) {
const route = TAB_ROUTES[tabId] || TAB_ROUTES.overview;
if (window.location.pathname === route && !window.location.search) return;
const method = replace ? "replaceState" : "pushState";
window.history[method]({ tab: tabId }, "", route);
}
async function api(path, options = {}) {
const response = await fetch(path, { credentials: "same-origin", ...options });
const type = response.headers.get("content-type") || "";
@ -98,6 +135,7 @@ async function bootstrap() {
state.recipes = await api("/api/recipes");
applyRuntimeOptions();
showApp();
switchTab(tabFromLocation(), { syncUrl: false });
await refresh();
startTaskEvents();
clearInterval(state.refreshTimer);
@ -231,9 +269,12 @@ function setActionAvailability(id, enabled, reason) {
button.title = enabled ? "" : reason;
}
function switchTab(tabId) {
function switchTab(tabId, { syncUrl = true, replace = false } = {}) {
if (!TAB_ROUTES[tabId]) tabId = "overview";
if (syncUrl) syncTabUrl(tabId, { replace });
document.querySelectorAll(".tab").forEach((button) => button.classList.toggle("active", button.dataset.tab === tabId));
document.querySelectorAll(".page").forEach((page) => page.classList.toggle("active", page.id === tabId));
document.title = `Real2Sim · ${TAB_TITLES[tabId]}`;
document.querySelectorAll("iframe").forEach((frame) => {
frame.contentWindow?.postMessage({ type: "real2sim-viewer-visibility", visible: frame.closest(".page")?.id === tabId }, location.origin);
});
@ -2244,6 +2285,7 @@ function bindEvents() {
$("openUsers")?.addEventListener("click", openUserManager);
$("createUserForm")?.addEventListener("submit", createUser);
document.querySelectorAll(".tab").forEach((button) => button.addEventListener("click", () => switchTab(button.dataset.tab)));
window.addEventListener("popstate", () => switchTab(tabFromLocation(), { syncUrl: false }));
$("closeDrawer")?.addEventListener("click", closeDrawer);
$("importForm")?.addEventListener("submit", submitImport);
$("editForm")?.addEventListener("submit", saveEdit);

View File

@ -797,6 +797,6 @@
</dialog>
<div id="toast" class="toast" role="status"></div>
<script src="/static/app.js?v=20260713-scene-library-assets-v7"></script>
<script src="/static/app.js?v=20260713-asset-delete-routes-v8"></script>
</body>
</html>

View File

@ -13,6 +13,7 @@ from PIL import Image
from real2sim_platform.adapters import _export_3dgs_rgb_fallback, collect_task_reports
from real2sim_platform.config import PlatformConfig
from real2sim_platform import motrix_scene
from real2sim_platform.server import create_app
from real2sim_platform.store import PlatformStore
@ -277,6 +278,67 @@ def test_scene_library_clone_and_asset_revision_requests_are_real_tasks(tmp_path
assert delete.json()["task"]["type"] == "scene_asset_delete"
def test_scene_asset_delete_cleans_runtime_references(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
package = tmp_path / "editable_package"
runtime_dir = package / "simulator_assets"
runtime_dir.mkdir(parents=True)
runtime = runtime_dir / "scene.xml"
runtime.write_text(
"""<mujoco model="fixture">
<worldbody>
<body name="base_link"><geom type="box" size="0.1 0.1 0.1" /></body>
<body name="pick_cube"><freejoint name="pick_cube_free" /><geom type="box" size="0.03 0.03 0.03" /></body>
<camera name="overview" mode="targetbody" target="pick_cube" pos="1 -1 1" />
</worldbody>
<equality><joint joint1="pick_cube_free" joint2="base_joint" /></equality>
<keyframe><key name="home" qpos="0 0 0 0 0 0 0" qvel="0 0 0 0 0 0 0" /></keyframe>
</mujoco>""",
encoding="utf-8",
)
(package / "scene_manifest.json").write_text(
json.dumps(
{
"schema": "real2sim.scene_manifest.v3",
"assets": [
{"name": "抓取方块", "role": "added_asset", "runtime": {"body": "pick_cube"}},
{"name": "机器人", "role": "robot", "runtime": {"body": "base_link"}},
],
"simulator_artifacts": {"motrixsim": {"runtime_scene": str(runtime)}},
}
),
encoding="utf-8",
)
monkeypatch.setattr(
motrix_scene,
"validate_runtime_scene",
lambda _runtime, steps: {
"steps": steps,
"mujoco": {"ok": True},
"motrixsim": {"ok": True},
"ok": True,
},
)
result = motrix_scene.revise_scene_asset(
package,
asset_id="pick_cube",
delete=True,
validation_steps=1,
)
assert result["operation"] == "deleted"
root = __import__("xml.etree.ElementTree", fromlist=["parse"]).parse(runtime).getroot()
assert root.find(".//body[@name='pick_cube']") is None
camera = root.find(".//camera[@name='overview']")
assert camera is not None
assert camera.get("target") is None
assert camera.get("mode") is None
assert root.find("keyframe") is None
assert root.find("equality") is not None and list(root.find("equality")) == []
manifest = json.loads((package / "scene_manifest.json").read_text(encoding="utf-8"))
assert all(item.get("runtime", {}).get("body") != "pick_cube" for item in manifest["assets"])
def test_scene_runtime_metadata_update(tmp_path: Path) -> None:
store = PlatformStore(tmp_path / "state.db")
scene_file = tmp_path / "scene.xml"