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
fix(society): recover a lost team task from the member's chat and show a goal's text once (#559)
Ruben Lütkefa0837ab1851
diff --git a/docs/agent-society/team-leads.md b/docs/agent-society/team-leads.mdindex a216c10814..b9ed23bd07 100644--- a/docs/agent-society/team-leads.md+++ b/docs/agent-society/team-leads.md@@ -98,9 +98,12 @@ Both vocabularies are pinned across Python, SQL and TypeScript by- The society kill switch pauses every running goal.- Goals that were running when the app closed come back `paused`, with theiropen tasks marked as interrupted. Opening the app never resumes one.-- A task with no sign of life is checked against the scheduler; a run that- ended without a result reaches the lead as `blocked` instead of being- waited on forever.+- A task with no sign of life is checked against the scheduler and then+ against the member's own chat. A member that is still working is left+ alone, a turn that finished without its result reaching the board becomes+ the task's result, and only work the chat never saw reaches the lead as+ `blocked`. The lead is never left waiting forever, and never hands the same+ work out twice because a start was slow.## Check-insdiff --git a/jarvis/society/team_lead.py b/jarvis/society/team_lead.pyindex ff764e3643..e8a00b022b 100644--- a/jarvis/society/team_lead.py+++ b/jarvis/society/team_lead.py@@ -37,7 +37,7 @@ import refrom collections.abc import Callable, Mappingfrom dataclasses import dataclassfrom functools import partial-from typing import Any, Final+from typing import Any, Final, Literalfrom jarvis.missions.ids import uuid7_str@@ -1658,6 +1658,12 @@ class TeamLeads:continueif task.state is TeamTaskState.RUNNING and task.run_id in running:continue+ outcome = await self._chat_outcome(task)+ if outcome == "running":+ continue # The member is still on it; a later pass reads its end.+ if outcome is not None:+ await self._close_task(task, outcome[0], outcome[1])+ continueawait self._close_task(task,TeamTaskState.BLOCKED,@@ -1676,6 +1682,59 @@ class TeamLeads:else:await self._park(goal, "stalled")+ async def _chat_outcome(+ self, task: TeamTask+ ) -> tuple[TeamTaskState, str] | Literal["running"] | None:+ """What the member's own chat says about an assignment the board lost.++ The scheduler abandons a start that takes too long. The member may be+ working all the same, with nobody left to write its RESULT, and calling+ the task "never picked up" would make the lead hand the same work out+ twice. The chat is durable and the framed assignment carries its message+ id, so the turn that answered it is read back from there. ``None`` means+ the chat never saw the assignment, or its turn left no ending.+ """+ svc = self._rt.chat_service()+ if svc is None or not task.assign_event_id:+ return None+ from .roster import canonical_session_id++ session_id = canonical_session_id(task.agent_id)+ try:+ events = await asyncio.to_thread(svc.store.list_events, session_id, tail=600)+ except Exception: # noqa: BLE001 — an unreadable chat reads as "never seen"+ log.warning("society team lead: chat of %s unreadable", task.agent_id, exc_info=True)+ return None+ marker = f"Message id: {task.assign_event_id};"+ start = next(+ (+ index+ for index, event in enumerate(events)+ if event.get("kind") == "user_message"+ and marker in str((event.get("payload") or {}).get("text") or "")+ ),+ None,+ )+ if start is None:+ return None+ final, status, error = "", "", ""+ for event in events[start + 1 :]:+ kind = event.get("kind")+ payload = event.get("payload") or {}+ if kind == "user_message":+ break # The next turn began; this one left no ending.+ if kind == "assistant_text" and not payload.get("media_only"):+ final = str(payload.get("text") or final)+ elif kind == "turn_finished":+ status = str(payload.get("status") or "done")+ error = str(payload.get("error") or "")+ break+ if not status:+ return "running" if svc.is_running(session_id) else None+ if status in ("ok", "done", "completed") and final.strip():+ return TeamTaskState.DONE, final.strip()+ return TeamTaskState.BLOCKED, (final or error or "The turn ended without a result.").strip()+# ------------------------------------------------------------ pushesasync def _announce(diff --git a/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadBoard.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadBoard.test.tsxindex c469265f91..3069b9b6c3 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadBoard.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadBoard.test.tsx@@ -143,6 +143,28 @@ it("shows each task with its member, state and result", () => {expect(within(draft).queryByRole("button")).toBeNull();});+it("shows a goal's text once: the full first line as heading, the rest below", () => {+ const long = "Research the three largest cities of the country and then do a good deal more with them";+ api.team = team({+ goals: [+ goal({ title: `${long.slice(0, 40)}…`, text: `${long}+Second line with details.` }),+ goal({ goal_id: "g2", title: "Short goal", text: "Short goal" }),+ goal({ goal_id: "g3", title: "Given title", text: "A different description." }),+ ],+ });+ mount();+ const cut = screen.getByTestId("team-goal-g1");+ expect(within(cut).getByRole("heading", { level: 4 }).textContent).toBe(long);+ expect(within(cut).getByText("Second line with details.")).toBeTruthy();+ expect(cut.textContent?.split(long).length).toBe(2);+ const short = screen.getByTestId("team-goal-g2");+ expect(short.textContent?.split("Short goal").length).toBe(2);+ const given = screen.getByTestId("team-goal-g3");+ expect(within(given).getByRole("heading", { level: 4 }).textContent).toBe("Given title");+ expect(within(given).getByText("A different description.")).toBeTruthy();+});+it("answers the lead's question and stops a goal", async () => {api.team = team({ goals: [goal({ state: "needs_input", report: "Which market?", note: "question" })] });mount();diff --git a/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadBoard.tsx b/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadBoard.tsxindex 4c0c0d6a92..a18c49d439 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadBoard.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadBoard.tsx@@ -350,9 +350,14 @@ function GoalCard({ goal, leadName, assistantName, agentOf, nameOf, busy, onMessconst source = goal.source === "jarvis" ? t("society.lead.source_jarvis").replace("{0}", assistantName): goal.source === "lead" ? t("society.lead.source_lead").replace("{0}", leadName): goal.source === "assignment" ? t("society.lead.source_assignment") : "";- // The title is the goal's first line; show only what the text adds to it.+ // The title is the goal's first line, cut short when it is long. Show the+ // line in full as the heading and only what the text adds to it below.const text = goal.text.trim();- const detailText = text.startsWith(goal.title) ? text.slice(goal.title.length).trim() : text;+ const firstLine = text.split("\n", 1)[0].trim();+ const stem = goal.title.endsWith("\u2026") ? goal.title.slice(0, -1).trimEnd() : goal.title;+ const ownsTitle = stem.length > 0 && firstLine.replace(/\s+/g, " ").startsWith(stem);+ const heading = ownsTitle ? firstLine : goal.title;+ const detailText = ownsTitle ? text.slice(text.indexOf(firstLine) + firstLine.length).trim() : text;const detail = goal.note.startsWith("error:") ? goal.note.slice(6) : "";const note = goal.state !== "paused" && goal.state !== "failed" ? "": detail ? t("society.lead.note_error").replace("{0}", detail)@@ -369,7 +374,7 @@ function GoalCard({ goal, leadName, assistantName, agentOf, nameOf, busy, onMessdata-testid={`team-goal-${goal.goal_id}`} data-state={goal.state}><header className="flex items-start gap-3"><div className="min-w-0 flex-1">- <h4 className="text-sm font-semibold text-foreground">{goal.title}</h4>+ <h4 className="text-sm font-semibold text-foreground">{heading}</h4>{detailText && <p className="mt-1 whitespace-pre-wrap text-sm text-muted-foreground">{detailText}</p>}{source && <p className="mt-1 text-xs text-muted-foreground">{source}</p>}</div>diff --git a/tests/unit/society/test_team_lead.py b/tests/unit/society/test_team_lead.pyindex f1c7b91305..bb5ccf0d35 100644--- a/tests/unit/society/test_team_lead.py+++ b/tests/unit/society/test_team_lead.py@@ -606,6 +606,77 @@ async def test_a_resume_during_a_turn_that_is_winding_down_is_not_lost(team):assert any(text.startswith("[team goal resumed") for text in svc.prompts(LEAD))+async def _lost_assignment(rt, svc):+ """A task whose start the scheduler abandoned: on the board, never claimed."""+ from jarvis.agent_chat.events import make_event+ from jarvis.society.chat_binding import ensure_session++ leads = rt.team_leads+ rt.scheduler.detach() # the ASSIGN gets neither a CLAIM nor a VETO+ receipt = await leads.assign("boss", member="scout", title="Research", brief="Go.")+ rt.scheduler.attach()+ task = (await leads.tasks(receipt["goal_id"]))[0]+ assert task.state is TeamTaskState.ASSIGNED+ await rt.store.update_team_task(task.task_id, {"updated_ms": 1})+ scout = await rt.roster.get("scout")+ ensure_session(svc, rt.config(), scout)++ def say(kind: str, payload: dict[str, Any]) -> None:+ svc.store.append_event(SCOUT, make_event(kind, payload))++ return leads, receipt["goal_id"], task, say+++async def test_a_lost_assignment_is_read_back_from_the_members_chat(team):+ rt, svc = team+ leads, goal_id, task, say = await _lost_assignment(rt, svc)+ seen: list[str] = []++ async def boss(text: str, kwargs: dict[str, Any]) -> str:+ seen.append(text)+ await leads.report("boss", status="done", summary="Scout found it.")+ return "Closed."++ svc.scripts[LEAD] = boss+ # The member works on it all the same: its chat holds the framed assignment.+ framed = f"[assignment from boss] Go. Message id: {task.assign_event_id}; sender id: boss"+ say("user_message", {"text": framed})+ svc.busy.add(SCOUT)+ await leads.sweep()+ # Still running: the task is left alone and the lead is not woken.+ assert (await leads.tasks(goal_id))[0].state is TeamTaskState.ASSIGNED+ assert seen == []++ say("assistant_text", {"turn_id": "t1", "text": "Found: three sources."})+ say("turn_finished", {"turn_id": "t1", "status": "done"})+ svc.busy.discard(SCOUT)+ await leads.sweep()+ await until(_state_is(rt, goal_id, TeamGoalState.DONE))+ done = (await leads.tasks(goal_id))[0]+ assert done.state is TeamTaskState.DONE and done.result == "Found: three sources."+ # The lead heard the real result once; nothing was handed out twice.+ assert len(seen) == 1 and "Found: three sources." in seen[0]+ assert len(await leads.tasks(goal_id)) == 1 and svc.prompts(SCOUT) == []+++async def test_a_lost_assignment_that_failed_or_never_arrived_is_reported_blocked(team):+ rt, svc = team+ leads, goal_id, task, say = await _lost_assignment(rt, svc)+ svc.replies[LEAD] = "Noted."+ await leads.sweep() # the member's chat never saw it+ first = (await leads.tasks(goal_id))[0]+ assert first.state is TeamTaskState.BLOCKED and "never picked up" in first.result++ await rt.store.update_team_task(+ task.task_id, {"state": "assigned", "updated_ms": 1, "result": "", "done_ms": None}+ )+ say("user_message", {"text": f"Message id: {task.assign_event_id}; sender id: boss"})+ say("turn_finished", {"turn_id": "t1", "status": "error", "error": "provider unavailable"})+ await leads.sweep()+ failed = (await leads.tasks(goal_id))[0]+ assert failed.state is TeamTaskState.BLOCKED and failed.result == "provider unavailable"++# ------------------------------------------------- assignments from the board