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.

fix(missions): make /rerun idempotent (one parent -> one live child)

Ruben Lütke76a21060255e
diff --git a/jarvis/missions/event_store.py b/jarvis/missions/event_store.py
index cd579dc633..a05676b51a 100644
--- a/jarvis/missions/event_store.py
+++ b/jarvis/missions/event_store.py
@@ -297,6 +297,44 @@ class MissionEventStore:
await cur.close()
return [(str(r[0]), str(r[1]), str(r[2])) for r in rows]
+ async def find_child_missions(
+ self, parent_mission_id: str
+ ) -> list[tuple[str, str]]:
+ """Return ``(child_mission_id, current_state)`` for every mission whose
+ ``MissionDispatched`` event names ``parent_mission_id`` as its parent.
+
+ Newest first. The parent link lives only in the event payload (the
+ ``missions`` header has no parent column), so we read the dispatch
+ events and parse the payload in Python — the same idiom the sub-agent
+ registry (``jarvis/agents/registry.py``) uses, avoiding a hard
+ dependency on SQLite's JSON1 ``json_extract`` (cloud-first portability).
+
+ Used by the rerun endpoint to stay idempotent: a parent must not spawn
+ a second LIVE re-run child while a prior one is still active (forensic
+ 2026-06-22, mission 019eefcb-cee2 — a ``/rerun`` click-storm created
+ nine children for one mission).
+ """
+ cur = await self.conn.execute(
+ """
+ SELECT m.id, m.state, e.payload_json
+ FROM mission_events e
+ JOIN missions m ON m.id = e.mission_id
+ WHERE e.event_type = 'MissionDispatched'
+ ORDER BY m.created_ms DESC
+ """
+ )
+ rows = await cur.fetchall()
+ await cur.close()
+ out: list[tuple[str, str]] = []
+ for mid, state, payload_json in rows:
+ try:
+ parent = json.loads(payload_json or "{}").get("parent_mission_id")
+ except (ValueError, TypeError):
+ parent = None
+ if parent == parent_mission_id:
+ out.append((str(mid), str(state)))
+ return out
+
async def get_mission_state(self, mission_id: str) -> str | None:
cur = await self.conn.execute(
"SELECT state FROM missions WHERE id = ?",
diff --git a/jarvis/ui/web/missions_routes.py b/jarvis/ui/web/missions_routes.py
index eb2ac5754e..24dad75d86 100644
--- a/jarvis/ui/web/missions_routes.py
+++ b/jarvis/ui/web/missions_routes.py
@@ -27,6 +27,7 @@ from jarvis.missions.manager import MissionManager
from jarvis.missions.state_machine import (
IllegalStateTransition,
MissionState,
+ is_terminal,
)
from jarvis.ui.web.missions_worker import extract_worker_missions
@@ -349,6 +350,14 @@ _RERUNNABLE_STATES: frozenset[MissionState] = frozenset(
}
)
+# Terminal mission-state *values* (string form, as stored in the header). A
+# re-run child counts as "live" while its state is NOT in this set. Unknown
+# strings are treated as live (conservative: block a duplicate rather than
+# spawn one). Derived from the single source of truth in the state machine.
+_TERMINAL_STATE_VALUES: frozenset[str] = frozenset(
+ s.value for s in MissionState if is_terminal(s)
+)
+
@router.post("/{mission_id}/rerun")
async def rerun_mission(
@@ -403,6 +412,46 @@ async def rerun_mission(
),
)
+ # Idempotency / liveness guard (forensic 2026-06-22, mission 019eefcb-cee2):
+ # the source mission stays terminal forever as an audit record, so it is
+ # re-runnable indefinitely — and a burst of /rerun POSTs (a click-storm or a
+ # frontend re-render loop) used to dispatch one NEW child per request: nine
+ # children, "one mission with nine sub-agents". A parent may have at most ONE
+ # live (non-terminal) re-run child; while one exists, return it idempotently
+ # instead of spawning a duplicate. This mirrors the spawn_worker tool's
+ # cooldown gate, which guards the source_actor="hauptjarvis" voice path the
+ # same way — the source_actor="ui" rerun path simply never had its
+ # equivalent. Once the child reaches a terminal state, a fresh re-run is
+ # allowed again (the guard is a liveness gate, not a permanent lock). Placed
+ # before the destructive gate so a still-running, already-confirmed child is
+ # never re-prompted for confirmation.
+ live_children = [
+ child_id
+ for (child_id, child_state) in await mgr.store.find_child_missions(
+ mission_id
+ )
+ if child_state not in _TERMINAL_STATE_VALUES
+ ]
+ if live_children:
+ existing_child = live_children[0]
+ action = (
+ "continue" if source_state is MissionState.CANCELLED else "restart"
+ )
+ logger.info(
+ "rerun_mission: parent %s already has a live re-run child %s — "
+ "returning it idempotently instead of dispatching a duplicate",
+ mission_id,
+ existing_child,
+ )
+ return {
+ "ok": True,
+ "parent_mission_id": mission_id,
+ "mission_id": existing_child,
+ "action": action,
+ "started": True,
+ "deduplicated": True,
+ }
+
# Destructive re-gate: a re-run must not bypass the safety check the
# original dispatch enforced. Same helper + same 409 shape as /dispatch.
if not body.confirmed:
diff --git a/tests/missions/api/test_missions_routes.py b/tests/missions/api/test_missions_routes.py
index 716a7a5f38..cfe35f5fc8 100644
--- a/tests/missions/api/test_missions_routes.py
+++ b/tests/missions/api/test_missions_routes.py
@@ -622,3 +622,69 @@ def test_rerun_returns_503_without_manager(app_no_manager: FastAPI) -> None:
with TestClient(app_no_manager) as client:
r = client.post("/api/missions/some-id/rerun", json={})
assert r.status_code == 503
+
+
+async def test_rerun_is_idempotent_while_child_alive(
+ manager: MissionManager,
+) -> None:
+ """A burst of /rerun POSTs must NOT spawn one child mission per request.
+
+ Forensic 2026-06-22 (mission 019eefcb-cee2): a click-storm / re-render loop
+ POSTed /rerun nine times in three seconds and the endpoint created NINE
+ child missions — "one mission, nine sub-agents". The source mission stays
+ terminal forever (a permanent audit record) and is thus re-runnable
+ indefinitely, so without a choke-point every repeated POST dispatched
+ another child. The spawn_worker voice path already has a liveness gate; the
+ source_actor="ui" rerun path is the missing equivalent: a parent may have
+ at most ONE live (non-terminal) re-run child, and extra POSTs resolve to
+ that same child idempotently.
+ """
+ src = await manager.dispatch(prompt="build the thing", language="en")
+ await _drive_to(manager, src, MissionState.CANCELLED)
+
+ ids: list[str] = []
+ with TestClient(_app_for(manager)) as client:
+ for _ in range(9):
+ r = client.post(f"/api/missions/{src}/rerun", json={})
+ assert r.status_code == 200
+ ids.append(r.json()["mission_id"])
+
+ # All nine POSTs resolve to the SAME single child mission.
+ assert len(set(ids)) == 1, f"expected one child, got {sorted(set(ids))}"
+ child = ids[0]
+ assert child != src
+
+ # The store holds exactly ONE child of the parent.
+ children = await manager.store.find_child_missions(src)
+ assert len(children) == 1
+ assert children[0][0] == child
+
+
+async def test_rerun_allowed_again_after_child_terminal(
+ manager: MissionManager,
+) -> None:
+ """The guard blocks only while a child is LIVE — never permanently.
+
+ Once the first re-run child reaches a terminal state, a fresh re-run is
+ allowed again and creates a second child. This keeps the legitimate
+ "Continue / Restart again" flow working.
+ """
+ src = await manager.dispatch(prompt="again please", language="en")
+ await _drive_to(manager, src, MissionState.CANCELLED)
+
+ with TestClient(_app_for(manager)) as client:
+ first = client.post(f"/api/missions/{src}/rerun", json={}).json()[
+ "mission_id"
+ ]
+
+ # Drive the live child to a terminal state, then re-run once more.
+ await _drive_to(manager, first, MissionState.FAILED)
+
+ with TestClient(_app_for(manager)) as client:
+ second = client.post(f"/api/missions/{src}/rerun", json={}).json()[
+ "mission_id"
+ ]
+
+ assert second != first
+ children = await manager.store.find_child_missions(src)
+ assert {c[0] for c in children} == {first, second}