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(agents): question card review flow, progress and chat-answer summary; count chat runs (#920)

Ruben Lütke79ca1777427a
diff --git a/dodaios/agent_chat/store.py b/dodaios/agent_chat/store.py
index 592b9793ea..f5f4f448cc 100644
--- a/dodaios/agent_chat/store.py
+++ b/dodaios/agent_chat/store.py
@@ -640,6 +640,23 @@ class AgentChatStore:
"payload": json.loads(row["payload"]),
}
+ def finished_turns(self, prefix: str) -> list[tuple[str, str, int, str]]:
+ """``(session_id, turn_id, ts_ms, status)`` of every finished turn in the
+ sessions whose id starts with ``prefix``, oldest first."""
+ with self._lock:
+ rows = self._conn.execute(
+ "SELECT session_id, ts_ms, json_extract(payload, '$.turn_id') AS turn_id, "
+ "json_extract(payload, '$.status') AS status FROM agent_chat_events "
+ "WHERE substr(session_id, 1, ?) = ? AND kind = 'turn_finished' "
+ "ORDER BY ts_ms, seq",
+ (len(prefix), prefix),
+ ).fetchall()
+ return [
+ (str(r["session_id"]), str(r["turn_id"]), int(r["ts_ms"]), str(r["status"] or ""))
+ for r in rows
+ if r["turn_id"]
+ ]
+
def turn_has_text_before(self, session_id: str, turn_id: str, before_seq: int) -> bool:
"""Whether this exact turn wrote a nonblank answer before its terminal."""
with self._lock:
diff --git a/dodaios/plugins/tool/delegate_to_agent.py b/dodaios/plugins/tool/delegate_to_agent.py
index 8e47e9638c..653819b8ee 100644
--- a/dodaios/plugins/tool/delegate_to_agent.py
+++ b/dodaios/plugins/tool/delegate_to_agent.py
@@ -469,8 +469,9 @@ class SocietyStatusTool:
output={
"agents": rows,
"measurement_note": (
- "Runs count recorded RESULT events, including failures; costs are "
- "recorded costs only. No independent quality rating is available."
+ "Runs count recorded RESULT events and finished chat turns, once "
+ "each and including failures; costs are recorded costs only. No "
+ "independent quality rating is available."
),
},
)
diff --git a/dodaios/society/chat_runs.py b/dodaios/society/chat_runs.py
new file mode 100644
index 0000000000..fff95fdf37
--- /dev/null
+++ b/dodaios/society/chat_runs.py
@@ -0,0 +1,132 @@
+"""Chat turns as agent runs: what the Record's Runs and Last active count.
+
+Every turn of a society chat (``society:<agent>``, its conversations and its
+routine runs) ends with one ``turn_finished`` in the agent chat service,
+whatever runtime ran it: Jarvis' own brain, a CLI seat, Hermes or OpenClaw.
+This ledger listens for that event and remembers the turn in the society
+store (``society_agent_turns``), so ``SocietyStore.agent_stats`` counts it.
+
+A board dispatch is a chat turn too, and it already sends a RESULT; the
+stats count that run once (run_id ``turn:<turn_id>``). A routine run is one
+turn in its own chat and sends no RESULT, so it counts once as well.
+
+Turns that finished before this ledger existed are read back from the chat
+store once (``_BACKFILL_KEY``).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import random
+import time
+from typing import Any, Final
+
+log = logging.getLogger(__name__)
+
+__all__ = ["ChatRunLedger"]
+
+_PREFIX: Final[str] = "society:"
+#: Set once the chat store's older turns were copied in.
+_BACKFILL_KEY: Final[str] = "chat_turns_backfilled"
+
+
+class ChatRunLedger:
+ """Copies finished society chat turns into the society store."""
+
+ def __init__(self, runtime: Any) -> None:
+ self.runtime = runtime
+ self._service: Any = None
+ self._attach_task: asyncio.Task[None] | None = None
+ self._writes: set[asyncio.Task[Any]] = set()
+
+ async def start(self) -> None:
+ if await self._attach() is None:
+ # The society can start before the chat service exists.
+ self._attach_task = asyncio.create_task(self._attach_later(), name="chat-runs-attach")
+
+ async def _attach_later(self) -> None:
+ for _ in range(150):
+ # Jitter only spreads the retries; nothing here is security relevant.
+ await asyncio.sleep(2.0 + random.uniform(0, 1.0)) # noqa: S311
+ if await self._attach() is not None:
+ return
+ log.info("chat runs: no chat service appeared; chat turns are not counted")
+
+ async def _attach(self) -> Any:
+ if self._service is not None:
+ return self._service
+ service = self.runtime.chat_service()
+ if service is None or not hasattr(service, "add_event_listener"):
+ return None
+ service.add_event_listener(self.on_event)
+ self._service = service
+ await self._backfill(service)
+ return service
+
+ async def close(self) -> None:
+ if self._service is not None:
+ self._service.remove_event_listener(self.on_event)
+ self._service = None
+ if self._attach_task is not None:
+ self._attach_task.cancel()
+ await asyncio.gather(self._attach_task, return_exceptions=True)
+ self._attach_task = None
+ if self._writes:
+ await asyncio.gather(*list(self._writes), return_exceptions=True)
+
+ def on_event(self, session_id: str, event: dict[str, Any]) -> None:
+ """The chat service's synchronous observer: a finished turn is a run."""
+ if event.get("kind") != "turn_finished" or not session_id.startswith(_PREFIX):
+ return
+ row = _row(session_id, event)
+ if row is None:
+ return
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ log.debug("chat runs: turn %s finished off the event loop; not counted", row[0])
+ return
+ task = loop.create_task(self._record([row]))
+ self._writes.add(task)
+ task.add_done_callback(self._writes.discard)
+
+ async def _record(self, rows: list[tuple[str, str, str, int, str]]) -> None:
+ try:
+ await self.runtime.store.record_chat_turns(rows)
+ except Exception: # noqa: BLE001 — a lost row only undercounts the Record
+ log.warning("chat runs: a finished turn was not recorded", exc_info=True)
+
+ async def _backfill(self, service: Any) -> None:
+ store = self.runtime.store
+ reader = getattr(service.store, "finished_turns", None)
+ if reader is None:
+ return
+ try:
+ if await store.get_meta(_BACKFILL_KEY) == "1":
+ return
+ found = await asyncio.to_thread(reader, _PREFIX)
+ rows = [
+ row for row in (
+ _row(sid, {"ts_ms": ts, "payload": {"turn_id": tid, "status": status}})
+ for sid, tid, ts, status in found
+ ) if row is not None
+ ]
+ added = await store.record_chat_turns(rows)
+ await store.set_meta(_BACKFILL_KEY, "1")
+ if added:
+ log.info("chat runs: counted %d earlier chat turns", added)
+ except Exception: # noqa: BLE001 — the next start tries again
+ log.warning("chat runs: earlier chat turns were not counted", exc_info=True)
+
+
+def _row(session_id: str, event: dict[str, Any]) -> tuple[str, str, str, int, str] | None:
+ from .surface import agent_id_of
+
+ payload = event.get("payload") or {}
+ turn_id = str(payload.get("turn_id") or "")
+ agent_id = agent_id_of(session_id)
+ if not turn_id or not agent_id:
+ return None
+ ts_ms = int(event.get("ts_ms") or 0) or int(time.time() * 1000)
+ return (turn_id, agent_id, session_id, ts_ms, str(payload.get("status") or ""))
diff --git a/dodaios/society/runtime.py b/dodaios/society/runtime.py
index 5120b18e5d..343d1c1bc8 100644
--- a/dodaios/society/runtime.py
+++ b/dodaios/society/runtime.py
@@ -191,6 +191,9 @@ class SocietyRuntime:
from .coding_threads import CodingThreads
self.coding_threads = CodingThreads(self)
+ from .chat_runs import ChatRunLedger
+
+ self.chat_runs = ChatRunLedger(self)
self._get_manager = mission_manager or (lambda: None)
self._get_mission_bus = mission_bus or (lambda: None)
self._get_budget = budget_tracker or (lambda: None)
@@ -354,6 +357,7 @@ class SocietyRuntime:
self._delivery_task = asyncio.create_task(self._deliver_pending())
set_current_runtime(self)
await self.coding_threads.start()
+ await self.chat_runs.start()
self._require_open_owner()
self.background(self.recover_reviews())
self._runtime_updates_task = asyncio.create_task(self._keep_agent_runtimes_current())
@@ -568,6 +572,7 @@ class SocietyRuntime:
cleanup.callback(unsubscribe)
setattr(self, attribute, None)
cleanup.push_async_callback(self.coding_threads.close)
+ cleanup.push_async_callback(self.chat_runs.close)
# Hermes / OpenClaw agents: their Gateways must not outlive the app.
from dodaios.agent_runtimes import stop_all as stop_agent_runtimes
diff --git a/dodaios/society/society_schema.sql b/dodaios/society/society_schema.sql
index cb82dd89c8..bb942b5651 100644
--- a/dodaios/society/society_schema.sql
+++ b/dodaios/society/society_schema.sql
@@ -236,3 +236,17 @@ WHEN NEW.msg_type IN ('SAY', 'QUERY', 'ANSWER', 'PROPOSE', 'HOLD', 'RELEASE')
BEGIN
INSERT OR IGNORE INTO society_deliveries (event_id) VALUES (NEW.event_id);
END;
+
+-- Every finished chat turn of an agent (its own chat, its conversations, its
+-- routine runs), whatever runtime ran it (dodaios/society/chat_runs.py). A
+-- turn the board dispatched also has a RESULT whose run_id is 'turn:<turn_id>';
+-- agent_stats counts that run once.
+CREATE TABLE IF NOT EXISTS society_agent_turns (
+ turn_id TEXT PRIMARY KEY,
+ agent_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ ts_ms INTEGER NOT NULL,
+ status TEXT NOT NULL DEFAULT ''
+);
+
+CREATE INDEX IF NOT EXISTS idx_society_agent_turns_agent ON society_agent_turns(agent_id, ts_ms);
diff --git a/dodaios/society/store.py b/dodaios/society/store.py
index 56fcdcff50..123678fe70 100644
--- a/dodaios/society/store.py
+++ b/dodaios/society/store.py
@@ -618,8 +618,30 @@ class SocietyStore:
await cur.close()
return float(row[0]) if row else 0.0
+ async def record_chat_turns(self, turns: list[tuple[str, str, str, int, str]]) -> int:
+ """Remember finished chat turns ``(turn_id, agent_id, session_id, ts_ms, status)``.
+
+ Idempotent by turn id: a replayed or backfilled turn is kept once.
+ Returns how many were new.
+ """
+ if not turns:
+ return 0
+ before = self.conn.total_changes
+ await self.conn.executemany(
+ "INSERT OR IGNORE INTO society_agent_turns "
+ "(turn_id, agent_id, session_id, ts_ms, status) VALUES (?, ?, ?, ?, ?)",
+ [(str(t), str(a), str(s), int(ms), str(st)) for t, a, s, ms, st in turns],
+ )
+ return self.conn.total_changes - before
+
async def agent_stats(self, agent_id: str) -> dict[str, Any]:
- """Derived numbers: runs (RESULTs sent), lifetime cost, last activity.
+ """Derived numbers: runs, lifetime cost, last activity.
+
+ A run is a RESULT the agent sent (board work, missions, team goals)
+ or a finished chat turn of its own (society_agent_turns: its chat,
+ conversations and routine runs, on any runtime). A board dispatch is
+ both a chat turn and a RESULT with run_id ``turn:<turn_id>``; it
+ counts once.
``spent_today_usd`` rides along because the daily budget is a real
gate — the scheduler refuses a dispatch once an agent has spent its
@@ -638,9 +660,24 @@ class SocietyStore:
row = await cur.fetchone()
await cur.close()
runs, cost, last = row or (0, 0.0, None)
+ cur = await self.conn.execute(
+ # The agent's RESULT run ids are read once (not per turn); a turn
+ # that has one is already counted among the RESULTs above.
+ "SELECT SUM(CASE WHEN 'turn:' || t.turn_id IN ("
+ " SELECT json_extract(e.payload_json, '$.run_id') FROM society_events e "
+ " WHERE e.from_agent = ? AND e.msg_type = 'RESULT'"
+ ") THEN 0 ELSE 1 END), MAX(t.ts_ms) "
+ "FROM society_agent_turns t WHERE t.agent_id = ?",
+ (agent_id, agent_id),
+ )
+ turn_row = await cur.fetchone()
+ await cur.close()
+ chat_runs, chat_last = turn_row or (0, None)
+ if chat_last is not None and (last is None or int(chat_last) > int(last)):
+ last = chat_last
today = await self.cost_since(agent_id, day_start_ms(now_ms()))
return {
- "runs": int(runs or 0),
+ "runs": int(runs or 0) + int(chat_runs or 0),
"total_cost_usd": float(cost or 0.0),
"spent_today_usd": today,
"last_active_ms": int(last) if last is not None else None,
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/QuestionCard.test.tsx b/dodaios/ui/web/frontend/src/components/agentchat/QuestionCard.test.tsx
index 26ee595317..20c740f732 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/QuestionCard.test.tsx
+++ b/dodaios/ui/web/frontend/src/components/agentchat/QuestionCard.test.tsx
@@ -5,7 +5,8 @@ import { createAgentChatStore } from "@/store/agentChat";
import { AgentChatStoreProvider } from "./AgentChatStoreContext";
import { QuestionCard } from "./QuestionCard";
import { EMPTY_TIMELINE, reduceEvents, type QuestionState, type ToolBlock, type TurnItem } from "./reduce";
-import { useQuestionDrafts } from "./questions/questionDraftStore";
+import { EMPTY_DRAFT, useQuestionDrafts } from "./questions/questionDraftStore";
+import { answeredByMessage, ownWords, pickedIndices } from "./questions/questionModel";
import { resetQuestionKeyboard } from "./questions/useQuestionKeyboard";
let seq = 0;
@@ -94,6 +95,24 @@ describe("question events", () => {
expect(block.question?.closed).toBe(true);
});
+ it("settle a card answered from the composer with the typed answer and its option", () => {
+ const q = questionOf(asking([
+ ev("question_resolved", {
+ turn_id: "t1",
+ question_id: "q1",
+ answers: [
+ { answer: "Postgres", option_index: 1, source: "message" },
+ { answer: "Laptop", option_index: 0, source: "moved_on" },
+ ],
+ }),
+ ]));
+ expect(q.closed).toBe(true);
+ expect(q.answers[0]).toMatchObject({ text: "Postgres", optionIndex: 1, source: "message" });
+ expect(answeredByMessage(q)).toBe(true);
+ expect(pickedIndices(q.answers[0])).toEqual([1]);
+ expect(ownWords(q.answers[0], q.questions[0])).toBe("");
+ });
+
it("read an older single-question event as a single-select question", () => {
const tl = reduceEvents(EMPTY_TIMELINE, [
ev("turn_started", { turn_id: "t1" }),
@@ -228,17 +247,94 @@ describe("QuestionCard", () => {
expect(review.textContent).toContain("SQLite");
expect(review.textContent).toContain("Both");
expect(submit).not.toHaveBeenCalled();
- // Change the first answer, then come back to the review.
+ // Change the first answer: the new pick returns straight to the review.
fireEvent.click(within(review).getAllByRole("button")[0]);
expect(screen.getByTestId("question-step").textContent).toBe("1 of 2");
expect(rowsOf(card)[0].querySelector("[data-on]")).not.toBeNull();
fireEvent.click(rowsOf(card)[1]);
- await waitFor(() => expect(screen.getByTestId("question-step").textContent).toBe("2 of 2"));
- fireEvent.click(within(card).getByRole("button", { name: /^review$/i }));
+ await waitFor(() => expect(review.closest(".qc-step")?.hasAttribute("data-active")).toBe(true));
+ expect(review.textContent).toContain("Postgres");
fireEvent.click(screen.getByTestId("question-send"));
await waitFor(() => expect(submit).toHaveBeenCalledWith("q1", [{ option_index: 1 }, { option_index: 2 }]));
});
+ it("returns to the review from a step opened there, by Next or by a pick", async () => {
+ vi.useFakeTimers();
+ const { submit } = draw(questionOf(asking([], [DB, HOST, FEATURES])));
+ const card = screen.getByTestId("question-card");
+ const active = () => card.querySelector(".qc-step[data-active] .qc-title")?.textContent;
+ const advance = () => act(() => { vi.advanceTimersByTime(200); });
+ const reviewRow = (i: number) => within(screen.getByTestId("question-review")).getAllByRole("button")[i];
+ fireEvent.click(rowsOf(card)[0]);
+ advance();
+ fireEvent.click(rowsOf(card)[0]);
+ advance();
+ fireEvent.click(rowsOf(card)[1]);
+ fireEvent.click(within(card).getByRole("button", { name: /^review$/i }));
+ expect(active()).toBe("Your answers");
+ // Opened from the review, Next reads Review and goes back there.
+ fireEvent.click(reviewRow(0));
+ expect(active()).toBe(DB.question);
+ fireEvent.click(within(card).getByRole("button", { name: /^review$/i }));
+ expect(active()).toBe("Your answers");
+ // A new single pick returns there too, never to the step after it.
+ fireEvent.click(reviewRow(0));
+ fireEvent.click(rowsOf(card)[1]);
+ advance();
+ expect(active()).toBe("Your answers");
+ expect(screen.getByTestId("question-review").textContent).toContain("Postgres");
+ // A multi step opened there returns with its Review button as well.
+ fireEvent.click(reviewRow(2));
+ expect(active()).toBe(FEATURES.question);
+ fireEvent.click(rowsOf(card)[2]);
+ fireEvent.click(within(card).getByRole("button", { name: /^review$/i }));
+ expect(active()).toBe("Your answers");
+ // Walking with Back and Next moves step by step again.
+ fireEvent.click(within(card).getByRole("button", { name: /^back$/i }));
+ fireEvent.click(within(card).getByRole("button", { name: /^back$/i }));
+ expect(active()).toBe(HOST.question);
+ fireEvent.click(within(card).getByRole("button", { name: /^next$/i }));
+ expect(active()).toBe(FEATURES.question);
+ fireEvent.click(within(card).getByRole("button", { name: /^review$/i }));
+ fireEvent.click(screen.getByTestId("question-send"));
+ vi.useRealTimers();
+ await waitFor(() => expect(submit).toHaveBeenCalledWith("q1", [
+ { option_index: 1 }, { option_index: 0 }, { option_indices: [1, 2] },
+ ]));
+ });
+
+ it("keeps the way back to the review in the draft store", async () => {
+ expect(EMPTY_DRAFT.returnToReview).toBe(false);
+ draw(questionOf(asking()));
+ const card = screen.getByTestId("question-card");
+ fireEvent.click(within(card).getByRole("button", { name: /^skip$/i }));
+ fireEvent.click(within(card).getByRole("button", { name: /^skip$/i }));
+ fireEvent.click(within(screen.getByTestId("question-review")).getAllByRole("button")[1]);
+ expect(useQuestionDrafts.getState().drafts.q1).toMatchObject({ step: 1, returnToReview: true });
+ fireEvent.click(within(card).getByRole("button", { name: /^back$/i }));
+ expect(useQuestionDrafts.getState().drafts.q1).toMatchObject({ step: 0, returnToReview: false });
+ });
+
+ it("marks answered, current and open steps in the progress dots", async () => {
+ draw(questionOf(asking([], [DB, HOST, FEATURES])));
+ const card = screen.getByTestId("question-card");
+ const states = () => Array.from(screen.getByTestId("question-dots").querySelectorAll(".qc-dot"))
+ .map((d) => d.getAttribute("data-state"));
+ expect(states()).toEqual(["current", "open", "open"]);
+ fireEvent.click(rowsOf(card)[0]);
+ await waitFor(() => expect(states()).toEqual(["done", "current", "open"]));
+ fireEvent.click(within(card).getByRole("button", { name: /^skip$/i }));
+ expect(states()).toEqual(["done", "done", "current"]);
+ fireEvent.click(rowsOf(card)[0]);
+ fireEvent.click(within(card).getByRole("button", { name: /^review$/i }));
+ // The review: every step answered, none on screen.
+ expect(states()).toEqual(["done", "done", "done"]);
+ expect(screen.getByTestId("question-dots").getAttribute("aria-label")).toBe("3 of 3 answered");
+ // Only the review takes part in the layout, so the card sizes to it.
+ expect(card.querySelector(".qc-steps")?.hasAttribute("data-reviewing")).toBe(true);
+ expect(card.querySelector(".qc-steps-frame")).not.toBeNull();
+ });
+
it("goes back and skips steps in a series", async () => {
const { submit } = draw(questionOf(asking()));
const card = screen.getByTestId("question-card");
@@ -383,7 +479,7 @@ describe("QuestionCard", () => {
expect(card.textContent).toContain("Skipped");
});
- it("turns a card answered in the chat into the question and the reply", () => {
+ it("settles a card answered in the chat with answer chips and keeps the reply", () => {
draw(questionOf(asking([
ev("question_resolved", {
turn_id: "t1",
@@ -395,9 +491,44 @@ describe("QuestionCard", () => {
}),
])));
const card = screen.getByTestId("question-card");
- expect(card.getAttribute("data-state")).toBe("message");
- expect(card.textContent).toContain(DB.question);
- expect(card.querySelector(".qc-reply-bubble")?.textContent).toBe("Neither, use files");
+ expect(card.hasAttribute("data-settled")).toBe(true);
+ expect(card.hasAttribute("data-in-chat")).toBe(true);
+ const chips = Array.from(card.querySelectorAll(".qc-chip")).map((c) => c.textContent);
+ expect(chips).toEqual(["Neither, use files", "ALaptop"]);
+ const reply = screen.getByTestId("question-answered-in-chat").querySelector(".qc-reply-bubble");
+ expect(reply?.textContent).toBe("Neither, use files");
+ });
+
+ it("maps a chat answer that named an option to its letter", () => {
+ draw(questionOf(asking([
+ ev("question_resolved", {
+ turn_id: "t1",
+ question_id: "q1",
+ answers: [{ answer: "Postgres", option_index: 1, source: "message" }],
+ }),
+ ], [DB])));
+ const card = screen.getByTestId("question-card");
+ expect(card.hasAttribute("data-settled")).toBe(true);
+ const chip = card.querySelector(".qc-chip");
+ expect(chip?.querySelector(".qc-keycap")?.textContent).toBe("B");
+ expect(chip?.textContent).toBe("BPostgres");
+ expect(card.querySelector(".qc-chip[data-plain]")).toBeNull();
+ const reply = screen.getByTestId("question-answered-in-chat").querySelector(".qc-reply-bubble");
+ expect(reply?.textContent).toBe("Postgres");
+ });
+
+ it("leaves an end-of-turn card's chat reply to the chat's own message", () => {
+ draw(questionOf(asking([
+ ev("question_resolved", {
+ turn_id: "t1",
+ question_id: "q1",
+ answers: [{ answer: "Use files", option_index: null, source: "message" }],
+ }),
+ ], [DB], { deferred: true })));
+ const card = screen.getByTestId("question-card");
+ expect(card.hasAttribute("data-settled")).toBe(true);
+ expect(card.textContent).toContain("Use files");
+ expect(screen.queryByTestId("question-answered-in-chat")).toBeNull();
});
});
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/questions/QuestionCard.tsx b/dodaios/ui/web/frontend/src/components/agentchat/questions/QuestionCard.tsx
index 333346bcfc..ac0cd5ab5b 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/questions/QuestionCard.tsx
+++ b/dodaios/ui/web/frontend/src/components/agentchat/questions/QuestionCard.tsx
@@ -1,4 +1,4 @@
-import { memo, useEffect, useId, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from "react";
+import { memo, useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type RefObject } from "react";
import { CircleAlert, CornerDownLeft, MoreHorizontal, SkipForward, Sparkles, X } from "lucide-react";
import { useT } from "@/i18n";
import type { QuestionState } from "../reduce";
@@ -73,6 +73,25 @@ function useRemaining(question: QuestionState): number | null {
return left;
}
+/**
+ * The pixel height of `inner`, kept current, so a frame around it can ease
+ * between steps of different heights (CSS cannot transition `auto`).
+ * Null until measured, or where there is no ResizeObserver.
+ */
+function useMeasuredHeight(inner: RefObject<HTMLElement | null>): number | null {
+ const [height, setHeight] = useState<number | null>(null);
+ useLayoutEffect(() => {
+ const el = inner.current;
+ if (!el || typeof ResizeObserver === "undefined") return;
+ const measure = () => setHeight(el.offsetHeight);
+ measure();
+ const observer = new ResizeObserver(measure);
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, [inner]);
+ return height;
+}
+
function clock(ms: number): string {
const seconds = Math.ceil(ms / 1000);
return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
@@ -112,6 +131,8 @@ function OpenCard({
const titleId = useId();
const cardRef = useRef<HTMLElement>(null);
const ownRefs = useRef<(HTMLTextAreaElement | null)[]>([]);
+ const stepsRef = useRef<HTMLDivElement>(null);
+ const stepsHeight = useMeasuredHeight(stepsRef);
const advance = useRef<number | null>(null);
const [menuOpen, setMenuOpen] = useState(false);
const [entered] = useState(() => (question.closed ? undefined : "new"));
@@ -128,6 +149,8 @@ function OpenCard({
const item = reviewing ? null : questions[step];
const local = reviewing ? EMPTY_ANSWER : locals[step];
const locked = (i: number) => question.answers[i] !== null;
+ // A step opened from the review returns there once it is answered.
+ const backToReview = series && !reviewing && draft.returnToReview;
useEffect(() => () => {
if (advance.current !== null) window.clearTimeout(advance.current);
@@ -142,11 +165,13 @@ function OpenCard({
};
const setLocal = (index: number, next: LocalAnswer) =>
write((d, current) => ({ ...d, answers: current.map((a, i) => (i === index ? next : a)) }));
- const goTo = (next: number) => {
+ const goTo = (next: number, fromReview = false) => {
if (advance.current !== null) window.clearTimeout(advance.current);
advance.current = null;
- write((d) => ({ ...d, step: Math.max(0, Math.min(next, total)) }));
+ write((d) => ({ ...d, step: Math.max(0, Math.min(next, total)), returnToReview: fromReview }));
};
+ /** Past the step on screen: the next one, or the review it was opened from. */
+ const forward = () => goTo(backToReview ? total : step + 1);
/** Send the whole card with `override` folded in (the read is the store's newest). */
const submitWith = (index: number, override: LocalAnswer) => {
const current = questions.map((q, i) => {
@@ -174,7 +199,9 @@ function OpenCard({
const from = step;
advance.current = window.setTimeout(() => {
advance.current = null;
- patchQuestionDraft(questionId, (d) => ((d.step < 0 ? firstOpen : d.step) === from ? { ...d, step: from + 1 } : d));
+ patchQuestionDraft(questionId, (d) => ((d.step < 0 ? firstOpen : d.step) === from
+ ? { ...d, step: d.returnToReview ? total : from + 1, returnToReview: false }
+ : d));
}, 180);
};
const typed = (text: string) => item && setLocal(step, withText(local, item, text));
@@ -185,7 +212,7 @@ function OpenCard({
submitWith(step, hasAnswer(local) ? local : { ...EMPTY_ANSWER, skipped: true });
return;
}
- goTo(step + 1);
+ forward();
};
const skipStep = () => {
setMenuOpen(false);
@@ -195,7 +222,7 @@ function OpenCard({
return;
}
setLocal(step, skipped);
- goTo(step + 1);
+ forward();
};
const decideAll = () => {
setMenuOpen(false);
@@ -289,7 +316,8 @@ function OpenCard({
/>
) : null}
- <div className="qc-steps">
+ <div className="qc-steps-frame" style={stepsHeight === null ? undefined : { height: stepsHeight }}>
+ <div ref={stepsRef} className="qc-steps" data-reviewing={reviewing ? "" : undefined}>
{questions.map((q, i) => (
<QuestionStep
key={i}
@@ -317,7 +345,7 @@ function OpenCard({
? ""
: [...a.picks.map((p) => q.options[p]?.label), ...(a.text.trim() ? [a.text.trim()] : [])].join("\n");
return (
- <button key={i} type="button" className="qc-review-row" onClick={() => goTo(i)} disabled={locked(i)}
+ <button key={i} type="button" className="qc-review-row" onClick={() => goTo(i, true)} disabled={locked(i)}
aria-label={`${q.question}: ${text || t("question_card.skipped_chip")}. ${t("question_card.change")}`}>
<span className="qc-keycap" data-on={text ? "" : undefined} aria-hidden>{i + 1}</span>
<span className="min-w-0 flex-1">
@@ -332,6 +360,7 @@ function OpenCard({
</div>
) : null}
</div>
+ </div>
{footer ? (
<footer className="qc-foot">
@@ -341,7 +370,7 @@ function OpenCard({
<span>{t("question_card.failed")}</span>
</p>
) : series ? (
- <Dots total={total} current={step} done={answered} label={t("question_card.step")} />
+ <Dots total={total} current={step} done={answered} label={t("question_card.step")} progressLabel={t("question_card.progress")} />
) : null}
<span className="qc-foot-end">
{failed ? (
@@ -358,8 +387,8 @@ function OpenCard({
</button>
) : null}
{series && !reviewing ? (
- <button type="button" className="qc-btn qc-btn-primary" onClick={() => goTo(step + 1)} disabled={!hasAnswer(local) && !locked(step)}>
- {step === total - 1 ? t("question_card.review") : t("question_card.next")}
+ <button type="button" className="qc-btn qc-btn-primary" onClick={forward} disabled={!hasAnswer(local) && !locked(step)}>
+ {step === total - 1 || backToReview ? t("question_card.review") : t("question_card.next")}
</button>
) : null}
{reviewing ? (
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/questions/QuestionStep.tsx b/dodaios/ui/web/frontend/src/components/agentchat/questions/QuestionStep.tsx
index e85b51829b..883b55f4c6 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/questions/QuestionStep.tsx
+++ b/dodaios/ui/web/frontend/src/components/agentchat/questions/QuestionStep.tsx
@@ -9,7 +9,8 @@ import { LETTERS, type LocalAnswer } from "./questionModel";
* One question of the card: its prompt as the title, the lettered answers,
* and the person's own-words row behind the next letter. Every step of a
* series is drawn at once and stacked in one grid cell (QuestionCard), so
- * only `active` is visible and the card keeps the height of its tallest step.
+ * only `active` is visible and the card keeps the height of its tallest step
+ * (the review step alone sizes to itself, and the frame eases between them).
*/
export const QuestionStep = forwardRef<HTMLTextAreaElement, {
item: QuestionItem;
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/questions/SettledQuestion.tsx b/dodaios/ui/web/frontend/src/components/agentchat/questions/SettledQuestion.tsx
index ded651cdf4..31c3bb6594 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/questions/SettledQuestion.tsx
+++ b/dodaios/ui/web/frontend/src/components/agentchat/questions/SettledQuestion.tsx
@@ -41,8 +41,9 @@ function useNoteText() {
/**
* A question card after it settled: one quiet line, "prompt → chosen answers",
* that opens into a read-only review of every step. A card nobody answered
- * reads muted with a dotted chip; a card answered from the chat reads as the
- * plain question followed by the person's reply.
+ * reads muted with a dotted chip. A card answered from the chat settles the
+ * same way (the typed reply as its answer chip, under the option's letter when
+ * it named one) and keeps the person's reply as their bubble below it.
*/
export function SettledQuestion({
question,
@@ -68,8 +69,6 @@ export function SettledQuestion({
return () => window.clearTimeout(id);
}, [copied]);
- if (answeredByMessage(question)) return <AnsweredInChat question={question} agent={agent} style={style} />;
-
const total = question.questions.length;
const dismissed = isDismissed(question);
const expanded = draft.expanded;
@@ -86,13 +85,14 @@ export function SettledQuestion({
? t("question_card.title_many").replace("{agent}", agentName).replace("{count}", String(total))
: question.questions[0].question;
- return (
+ const card = (
<div
className="qc"
data-settled=""
data-dismissed={dismissed ? "" : undefined}
data-testid="question-card"
data-state={sources}
+ data-in-chat={answeredByMessage(question) ? "" : undefined}
style={style}
>
<div className="flex items-center">
@@ -185,6 +185,14 @@ export function SettledQuestion({
</div>
</div>
);
+ const reply = chatReply(question);
+ if (!reply) return card;
+ return (
+ <div className="flex w-full flex-col gap-1.5" data-testid="question-answered-in-chat">
+ {card}
+ <div className="qc-reply"><div className="qc-reply-bubble">{reply}</div></div>
+ </div>
+ );
}
function answerChips(item: QuestionItem, answer: QuestionState["answers"][number], index: number, skippedLabel: string) {
@@ -201,35 +209,55 @@ function answerChips(item: QuestionItem, answer: QuestionState["answers"][number
return chips;
}
-/** Progress dots of a series: a pill for the step on screen, darker for done ones. */
-export function Dots({ total, current, done, label }: { total: number; current: number; done: number | readonly boolean[]; label: string }) {
+/**
+ * Progress dots of a series, one per question: a wide pill for the step on
+ * screen, a filled dot for an answered one, a hollow ring for one still open.
+ * On the review step (`current === total`) every dot reads by its own state.
+ */
+export function Dots({
+ total,
+ current,
+ done,
+ label,
+ progressLabel,
+}: {
+ total: number;
+ current: number;
+ done: number | readonly boolean[];
+ label: string;
+ /** "{answered} of {total} answered", read out beside the step. */
+ progressLabel?: string;
+}) {
const isDone = (i: number) => (typeof done === "number" ? i < done : Boolean(done[i]));
- const text = label.replace("{current}", String(Math.min(current + 1, total))).replace("{total}", String(total));
+ const answered = Array.from({ length: total }, (_, i) => isDone(i)).filter(Boolean).length;
+ const onStep = current < total;
+ const stepText = label.replace("{current}", String(Math.min(current + 1, total))).replace("{total}", String(total));
+ const progressText = progressLabel?.replace("{answered}", String(answered)).replace("{total}", String(total)) ?? "";
+ const text = [onStep ? stepText : "", progressText].filter(Boolean).join(", ") || stepText;
return (
- <span className="qc-dots" role="img" aria-label={text}>
- {Array.from({ length: total }, (_, i) => (
- <span key={i} className="qc-dot" data-on={i === current ? "" : undefined} data-done={isDone(i) && i !== current ? "" : undefined} />
- ))}
+ <span className="qc-dots" role="img" aria-label={text} data-testid="question-dots">
+ {Array.from({ length: total }, (_, i) => {
+ const state = i === current ? "current" : isDone(i) ? "done" : "open";
+ return (
+ <span
+ key={i}
+ className="qc-dot"
+ data-state={state}
+ data-on={state === "current" ? "" : undefined}
+ data-done={isDone(i) ? "" : undefined}
+ />
+ );
+ })}
</span>
);
}
-/** The person answered in the chat: the question reads as the agent's message, the reply as theirs. */
-function AnsweredInChat({ question, agent, style }: { question: QuestionState; agent: SocietyAgent | null; style: CSSProperties | undefined }) {
- const t = useT();
- const index = question.answers.findIndex((a) => a?.source === "message");
- const reply = question.answers[index]?.text ?? "";
- return (
- <div className="flex w-full flex-col gap-1.5" data-testid="question-card" data-state="message" style={style}>
- <div className="qc-asked">
- <AskerMark agent={agent} size={20} />
- <div className="qc-asked-bubble jarvis-chat-in">
- <span className="qc-sr">{t("question_card.asked")}</span>
- {question.questions.map((item, i) => <p key={i}>{item.question}</p>)}
- </div>
- </div>
- {/* An end-of-turn card's reply went out as an ordinary message, which the chat shows itself. */}
- {question.deferred || !reply ? null : <div className="qc-reply"><div className="qc-reply-bubble">{reply}</div></div>}
- </div>
- );
+/**
+ * The reply the person typed into the chat to answer a live card. The chat
+ * sent no message of its own for it, so the card keeps it as their bubble;
+ * an end-of-turn card's reply went out as an ordinary message instead.
+ */
+function chatReply(question: QuestionState): string {
+ if (question.deferred) return "";
+ return question.answers.find((a) => a?.source === "message")?.text ?? "";
}
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/questions/questionCard.css b/dodaios/ui/web/frontend/src/components/agentchat/questions/questionCard.css
index f5b763d2ec..d51519bcc6 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/questions/questionCard.css
+++ b/dodaios/ui/web/frontend/src/components/agentchat/questions/questionCard.css
@@ -130,11 +130,23 @@
/* --- The steps: stacked in one cell, so the card never jumps ------------- */
+/* The frame eases to the measured height of the steps (QuestionCard). */
+.qc-steps-frame {
+ overflow: clip;
+ overflow-clip-margin: 6px;
+ transition: height 220ms var(--qc-ease-std);
+}
+
.qc-steps {
display: grid;
grid-template-columns: minmax(0, 1fr);
}
+/* The review takes its own height, not the tallest question's. */
+.qc-steps[data-reviewing] > .qc-step:not([data-active]) {
+ display: none;
+}
+
.qc-step {
grid-area: 1 / 1;
min-width: 0;
@@ -442,21 +454,32 @@
gap: 5px;
}
+/* Open: a hollow ring. Answered: a filled dot. On screen: a wide pill. */
.qc-dot {
- width: 6px;
- height: 6px;
+ width: 7px;
+ height: 7px;
border-radius: 999px;
- background: hsl(var(--border-strong));
- transition: width 200ms var(--qc-ease-std), background-color 200ms;
+ background: transparent;
+ box-shadow: inset 0 0 0 1.5px hsl(var(--border-strong));
+ transition: width 200ms var(--qc-ease-std), background-color 200ms, box-shadow 200ms;
}
-.qc-dot[data-done] {
- background: hsl(var(--muted-foreground));
+.qc-dot[data-state="done"] {
+ background: var(--qc-tint);
+ box-shadow: none;
+ opacity: 0.6;
}
-.qc-dot[data-on] {
- width: 16px;
+.qc-dot[data-state="current"] {
+ width: 18px;
background: var(--qc-tint);
+ box-shadow: none;
+}
+
+/* The step on screen still open: the pill stays hollow until it is answered. */
+.qc-dot[data-state="current"]:not([data-done]) {
+ background: color-mix(in srgb, var(--qc-tint) 22%, transparent);
+ box-shadow: inset 0 0 0 1.5px var(--qc-tint);
}
.qc-btn {
@@ -700,23 +723,7 @@
}
}
-/* --- Answered from the chat: a plain question and the person's reply ---- */
-
-.qc-asked {
- display: flex;
- align-items: flex-start;
- gap: 8px;
-}
-
-.qc-asked-bubble {
- min-width: 0;
- max-width: min(85%, 42rem);
- padding: 8px 14px;
- border-radius: 18px;
- font-size: 14px;
- line-height: 21px;
- overflow-wrap: anywhere;
-}
+/* --- Answered from the chat: the person's reply below the settled card -- */
.qc-reply {
display: flex;
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/questions/questionDraftStore.ts b/dodaios/ui/web/frontend/src/components/agentchat/questions/questionDraftStore.ts
index 510e6de6e1..42b00ac795 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/questions/questionDraftStore.ts
+++ b/dodaios/ui/web/frontend/src/components/agentchat/questions/questionDraftStore.ts
@@ -31,6 +31,8 @@ export interface QuestionSubmission {
export interface QuestionDraft {
/** The step on screen; `questions.length` is the review step, -1 the first open one. */
step: number;
+ /** The step on screen was opened from the review: finishing it goes back there. */
+ returnToReview: boolean;
answers: LocalAnswer[];
submission: QuestionSubmission | null;
/** A settled card the person opened to read again, and the page they are on. */
@@ -38,7 +40,7 @@ export interface QuestionDraft {
page: number;
}
-export const EMPTY_DRAFT: QuestionDraft = { step: -1, answers: [], submission: null, expanded: false, page: 0 };
+export const EMPTY_DRAFT: QuestionDraft = { step: -1, returnToReview: false, answers: [], submission: null, expanded: false, page: 0 };
interface DraftStore {
drafts: Record<string, QuestionDraft>;
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/de.json b/dodaios/ui/web/frontend/src/i18n/locales/de.json
index 005870914a..3f6c1188e9 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/de.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/de.json
@@ -7550,8 +7550,8 @@
"title_many": "{count} Fragen von {agent}",
"fallback_agent": "Dein Agent",
"asks": "fragt",
- "asked": "Frage des Agenten:",
"step": "{current} von {total}",
+ "progress": "{answered} von {total} beantwortet",
"recommended": "Empfohlen",
"why_toggle": "Warum diese Empfehlung?",
"pick_many": "Wähle alles Passende.",
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/en.json b/dodaios/ui/web/frontend/src/i18n/locales/en.json
index 9d7eaf4d36..27f584e89e 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/en.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/en.json
@@ -7550,8 +7550,8 @@
"title_many": "{agent}'s {count} questions",
"fallback_agent": "Your agent",
"asks": "asks",
- "asked": "Question from the agent:",
"step": "{current} of {total}",
+ "progress": "{answered} of {total} answered",
"recommended": "Recommended",
"why_toggle": "Why this recommendation?",
"pick_many": "Pick all that apply.",
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/es.json b/dodaios/ui/web/frontend/src/i18n/locales/es.json
index 67bbb59b0e..84641f32aa 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/es.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/es.json
@@ -7550,8 +7550,8 @@
"title_many": "{count} preguntas de {agent}",
"fallback_agent": "Tu agente",
"asks": "pregunta",
- "asked": "Pregunta del agente:",
"step": "{current} de {total}",
+ "progress": "{answered} de {total} respondidas",
"recommended": "Recomendada",
"why_toggle": "¿Por qué esta recomendación?",
"pick_many": "Elige todas las que apliquen.",
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/pt.json
index 3f39ac2cf4..dc7583e370 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/pt.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/pt.json
@@ -7550,8 +7550,8 @@
"title_many": "{count} perguntas de {agent}",
"fallback_agent": "Seu agente",
"asks": "pergunta",
- "asked": "Pergunta do agente:",
"step": "{current} de {total}",
+ "progress": "{answered} de {total} respondidas",
"recommended": "Recomendada",
"why_toggle": "Por que esta recomendação?",
"pick_many": "Escolha todas as que se aplicam.",
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/zh.json
index 51adbaf1d5..eb0acc1d93 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/zh.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/zh.json
@@ -7550,8 +7550,8 @@
"title_many": "{agent} 的 {count} 个问题",
"fallback_agent": "你的智能体",
"asks": "提问",
- "asked": "智能体的提问:",
"step": "{current} / {total}",
+ "progress": "已回答 {answered} / {total}",
"recommended": "推荐",
"why_toggle": "为什么推荐这个?",
"pick_many": "选择所有适用的选项。",
diff --git a/tests/unit/society/test_chat_runs.py b/tests/unit/society/test_chat_runs.py
new file mode 100644
index 0000000000..ae24e0a3b3
--- /dev/null
+++ b/tests/unit/society/test_chat_runs.py
@@ -0,0 +1,163 @@
+"""Chat turns count as agent runs on the Record (dodaios/society/chat_runs.py)."""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from dodaios.agent_chat.events import make_event
+from dodaios.agent_chat.service import AgentChatService
+from dodaios.agent_chat.store import AgentChatStore
+from dodaios.society.chat_runs import ChatRunLedger
+from dodaios.society.events import MsgType, SocietyEnvelope
+from dodaios.society.store import SocietyStore
+
+
+async def store(tmp_path: Path):
+ s = SocietyStore(tmp_path / "society.db")
+ await s.open()
+ try:
+ yield s
+ finally:
+ await s.close()
+
+
+def _result(agent: str, run_id: str) -> SocietyEnvelope:
+ return SocietyEnvelope(
+ msg_type=MsgType.RESULT,
+ from_agent=agent,
+ trace_id="t",
+ payload={"run_id": run_id, "status": "done", "done": "x", "output": []},
+ )
+
+
+def _session(chat: AgentChatStore, session_id: str, runtime: str = "") -> None:
+ chat.create_session(
+ session_id=session_id,
+ surface="society",
+ provider="claude-cli",
+ model="",
+ effort="",
+ cwd=".",
+ runtime=runtime,
+ )
+
+
+def _finish(turn_id: str, status: str = "done") -> dict[str, Any]:
+ return make_event("turn_finished", {"turn_id": turn_id, "status": status})
+
+
+async def _settle(ledger: ChatRunLedger) -> None:
+ for _ in range(5):
+ await asyncio.sleep(0)
+ if ledger._writes:
+ await asyncio.gather(*list(ledger._writes))
+
+
+async def test_chat_turns_count_as_runs_and_activity(store: SocietyStore):
+ assert (await store.agent_stats("ada"))["runs"] == 0
+ added = await store.record_chat_turns([
+ ("t1", "ada", "society:ada", 1_000, "done"),
+ ("t2", "ada", "society:ada", 2_000, "error"),
+ ])
+ assert added == 2
+ stats = await store.agent_stats("ada")
+ assert stats["runs"] == 2
+ assert stats["last_active_ms"] == 2_000
+ # Idempotent by turn id.
+ assert await store.record_chat_turns([("t1", "ada", "society:ada", 1_000, "done")]) == 0
+ assert (await store.agent_stats("ada"))["runs"] == 2
+ assert (await store.agent_stats("bob"))["runs"] == 0
+
+
+async def test_a_board_dispatch_counts_once(store: SocietyStore):
+ # The dispatched turn finished in the chat and sent its RESULT.
+ await store.record_chat_turns([("t1", "ada", "society:ada", 1_000, "done")])
+ await store.append_and_publish(_result("ada", "turn:t1"))
+ # A mission RESULT is a run with no chat turn behind it.
+ await store.append_and_publish(_result("ada", "mission-7"))
+ assert (await store.agent_stats("ada"))["runs"] == 2
+
+
+async def test_listener_counts_every_society_chat_once(store: SocietyStore):
+ chat = AgentChatStore()
+ service = AgentChatService(chat)
+ for sid, runtime in (
+ ("society:ada", "claude-cli"),
+ ("society:ada:routine:r1:abc", ""),
+ ("society:ada:with:bob", "hermes"),
+ ("society:cat", "openclaw"),
+ ):
+ _session(chat, sid, runtime)
+ plain = chat.create_session(provider="claude-cli", model="", effort="", cwd=".")
+ runtime = SimpleNamespace(store=store, chat_service=lambda: service)
+ ledger = ChatRunLedger(runtime)
+ await ledger.start()
+ try:
+ await service._emit("society:ada", _finish("a1"))
+ await service._emit("society:ada", _finish("a1")) # a duplicate completion
+ text = make_event("assistant_text", {"turn_id": "a2", "text": "hi"})
+ await service._emit("society:ada", text)
+ await service._emit("society:ada:routine:r1:abc", _finish("r1"))
+ await service._emit("society:ada:with:bob", _finish("p1", "cancelled"))
+ await service._emit("society:cat", _finish("c1"))
+ await service._emit(plain.session_id, _finish("x1"))
+ await _settle(ledger)
+ ada = await store.agent_stats("ada")
+ assert ada["runs"] == 3
+ assert ada["last_active_ms"] is not None
+ assert (await store.agent_stats("cat"))["runs"] == 1
+ finally:
+ await ledger.close()
+ assert service._event_listeners == []
+
+
+async def test_earlier_turns_are_read_back_once(store: SocietyStore):
+ chat = AgentChatStore()
+ _session(chat, "society:ada")
+ _session(chat, "society:ada:routine:r1:abc")
+ chat.append_event("society:ada", _finish("old1"))
+ chat.append_event("society:ada:routine:r1:abc", _finish("old2"))
+ chat.append_event("society:ada", make_event("turn_started", {"turn_id": "old3"}))
+ assert [row[1] for row in chat.finished_turns("society:")] == ["old1", "old2"]
+ service = SimpleNamespace(
+ store=chat,
+ add_event_listener=lambda _fn: None,
+ remove_event_listener=lambda _fn: None,
+ )
+ runtime = SimpleNamespace(store=store, chat_service=lambda: service)
+ first = ChatRunLedger(runtime)
+ await first.start()
+ await first.close()
+ assert (await store.agent_stats("ada"))["runs"] == 2
+ # Backfilled once: a turn the chat store gains later is the listener's job.
+ chat.append_event("society:ada", _finish("old4"))
+ second = ChatRunLedger(runtime)
+ await second.start()
+ await second.close()
+ assert (await store.agent_stats("ada"))["runs"] == 2
+
+
+async def test_results_without_a_run_id_leave_chat_turns_counted(store: SocietyStore):
+ # A RESULT with no run_id must not hide the chat turns (SQL NULL in IN).
+ await store.append_and_publish(
+ SocietyEnvelope(
+ msg_type=MsgType.RESULT,
+ from_agent="ada",
+ trace_id="t",
+ payload={"status": "done", "done": "x", "output": []},
+ )
+ )
+ await store.record_chat_turns([
+ ("t1", "ada", "society:ada", 1_000, "done"),
+ ("t2", "ada", "society:ada", 2_000, "done"),
+ ])
+ await store.append_and_publish(_result("ada", "turn:t2"))
+ # Another agent's RESULT for the same turn id does not dedupe ada's turn.
+ await store.append_and_publish(_result("bob", "turn:t1"))
+ assert (await store.agent_stats("ada"))["runs"] == 3