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): give Jarvis and agents their own conversation chats
rubenluetke10-beep9959247d5a1e
diff --git a/docs/agent-society/agent-definition.md b/docs/agent-society/agent-definition.mdindex 6ff21e12c3..de42d99389 100644--- a/docs/agent-society/agent-definition.md+++ b/docs/agent-society/agent-definition.md@@ -332,6 +332,13 @@ Gmail agent stood on the island. The team card (`jarvis/society/lead_card.py`) i- **Agent ↔ agent:** exactly one tool, `message_agent(target, text, kind)` → one `SAY` /`QUERY` / `PROPOSE` envelope to ONE teammate; the scheduler wakes the target's chat.`@name` in a canonical chat by the USER also produces a `SAY` from the user's identity.+- **Conversation chats (2026-10-02):** whatever Jarvis or a teammate sends an agent runs in the+ agent's own chat with that sender, `society:<agent_id>:with:<sender_id>` — never in the+ person's canonical chat. It is the same agent (`agent_id_of` resolves it): seat, workspace,+ approvals, tools, memory review and briefing are identical; only `society_propose_change`+ with `mode=apply` stays reserved for the person's own request. Recall searches every chat+ the agent owns; the card lists the conversations above the chat+ (`GET /api/society/agents/{id}/conversations`) and opens one as a full chat.- **Group:** a room (`ROOM_OPEN → SAY* → ROOM_SETTLE`), opened by Jarvis or an orchestrator,rendered as one thread in the society feed and as the meeting pavilion in the world.diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.pyindex 5c0a00a1c1..583e960481 100644--- a/jarvis/agent_chat/service.py+++ b/jarvis/agent_chat/service.py@@ -372,6 +372,10 @@ class AgentChatService:run = self._running.get(session_id)return bool(run and run.task and not run.task.done())+ def running_session_ids(self) -> list[str]:+ """Every session with a live turn right now."""+ return [sid for sid in list(self._running) if self.is_running(sid)]+async def seal_stopped_turn(self, session_id: str) -> bool:"""Close a turn the stop button can still see after its runner is gone.diff --git a/jarvis/agent_chat/store.py b/jarvis/agent_chat/store.pyindex cf2ce5959b..5a6a9a273a 100644--- a/jarvis/agent_chat/store.py+++ b/jarvis/agent_chat/store.py@@ -216,6 +216,19 @@ class AgentChatStore:).fetchall()return [self._row_to_session(r) for r in rows]+ def list_sessions_matching(+ self, prefix: str, suffix: str = "", *, limit: int = 200+ ) -> list[AgentChatSession]:+ """Newest first; every session whose id starts with ``prefix`` (and ends+ with ``suffix`` when given) — e.g. an agent's conversation chats."""+ with self._lock:+ rows = self._conn.execute(+ "SELECT * FROM agent_chat_sessions WHERE substr(session_id,1,?)=? "+ "AND (?='' OR substr(session_id,-?)=?) ORDER BY updated_ms DESC LIMIT ?",+ (len(prefix), prefix, suffix, max(1, len(suffix)), suffix, int(limit)),+ ).fetchall()+ return [self._row_to_session(r) for r in rows]+def update_session(self, session_id: str, **fields: Any) -> AgentChatSession | None:"""Set any of title / provider / model / effort / cwd / permission_mode /vendor_session. Unknown keys are ignored so a route can pass its bodydiff --git a/jarvis/society/agent_tools.py b/jarvis/society/agent_tools.pyindex 2140db35ed..bd2c20ca89 100644--- a/jarvis/society/agent_tools.py+++ b/jarvis/society/agent_tools.py@@ -219,6 +219,13 @@ class MessageAgentTool:FailureReason.BLOCKED_BY_POLICY, "no success reply was requested")trace_id = parent.trace_id if parent is not None else None+ from jarvis.core.protocols import current_chat_turn++ turn = current_chat_turn.get()+ if turn is not None and turn.session_id:+ # Which of the caller's chats wrote it: the person's chat with the+ # agent shows only its own outgoing messages, never a conversation's.+ payload["from_session"] = turn.session_idenv = await rt.say(from_agent=caller.agent_id,to_agent=target.agent_id,@@ -494,6 +501,7 @@ class ProposeChangeTool:from jarvis.core.protocols import current_chat_turnfrom .proposals import ProposalRefused, propose, resolve+ from .surface import agent_id_ofrt = self._runtimeif await rt.store.kill_switch():@@ -509,7 +517,7 @@ class ProposeChangeTool:if (turn is Noneor not turn.direct_user- or turn.session_id != caller.session_id+ or agent_id_of(turn.session_id) != caller.agent_idor not quoteor (len(quote) < 4 and quote != turn.user_text.strip())or quote not in turn.user_textdiff --git a/jarvis/society/chat_binding.py b/jarvis/society/chat_binding.pyindex 15cfaa7089..30e64c4fcd 100644--- a/jarvis/society/chat_binding.py+++ b/jarvis/society/chat_binding.py@@ -9,8 +9,10 @@ kept). Without a provider on the row the session runs on the Agents tierthe rest of the app uses (``local_models.assistant_session.agents_tier``).``make_deliver_hook`` is what the scheduler calls for SAY / QUERY / ANSWER /-PROPOSE / RESULT envelopes: ensure the target's session, then start a turn-with the message framed as coming from the sender. A busy session raises+PROPOSE / RESULT envelopes: ensure the target's conversation chat with the+sender (``society:<target>:with:<sender>``; the person's own messages use the+canonical chat), then start a turn with the message framed as coming from the+sender. A busy session raises``target busy`` so the scheduler writes a typed veto and the envelope staysin the inbox for the next turn."""@@ -25,7 +27,13 @@ from typing import Any, Finalfrom .communication import response_instructionfrom .delivery import DeliveryBusy, IncomingMessage, incoming_contextfrom .events import MsgType, SocietyEnvelope-from .roster import LEAD_AGENT_ID, AgentRecord, PermissionCeiling+from .roster import (+ LEAD_AGENT_ID,+ PAIR_SESSION_MARKER,+ AgentRecord,+ PermissionCeiling,+ conversation_session_id,+)from .scheduler import DeliverHooklog = logging.getLogger(__name__)@@ -77,14 +85,27 @@ def _workspace(cfg: Any, agent: AgentRecord) -> str:return str(folder)-def ensure_session(svc: Any, cfg: Any, agent: AgentRecord) -> Any:- """The agent's canonical session, created or re-seated to the roster row."""+def ensure_session(+ svc: Any,+ cfg: Any,+ agent: AgentRecord,+ *,+ counterpart: str = "",+ counterpart_name: str = "",+) -> Any:+ """The agent's session, created or re-seated to the roster row.++ Without ``counterpart`` this is the canonical chat, the one a person has+ with the agent. With it, it is the agent's own conversation with Jarvis or+ a teammate (``society:<agent>:with:<counterpart>``): same seat, workspace,+ approvals, tools and memory, but its turns never land in the person's chat.+ """from jarvis.agent_chat.effort import default_effortfrom jarvis.agent_chat.permissions import ladder_key, normalize_permissionfrom jarvis.agent_chat.service import resolve_runnerprovider, model, effort = pair_for(cfg, agent)- session_id = agent.session_id+ session_id = conversation_session_id(agent.agent_id, counterpart)existing = svc.store.get_session(session_id)if existing is None:ladder = ladder_key(SURFACE, resolve_runner(provider, surface=SURFACE))@@ -95,7 +116,11 @@ def ensure_session(svc: Any, cfg: Any, agent: AgentRecord) -> Any:effort=effort or default_effort(provider),cwd=_workspace(cfg, agent),permission_mode=mode,- title=agent.name,+ title=(+ agent.name+ if session_id == agent.session_id+ else f"{agent.name} · {counterpart_name or counterpart}"+ ),session_id=session_id,surface=SURFACE,account_id=agent.account_id,@@ -114,6 +139,22 @@ def ensure_session(svc: Any, cfg: Any, agent: AgentRecord) -> Any:return existing+def _agent_busy(svc: Any, agent: AgentRecord) -> bool:+ """Whether the person's chat or a conversation chat of ``agent`` runs a turn.++ Messages wait until the agent is free, as they did when it had one chat:+ two message turns never share its seat, workspace and browser at once.+ Routine runs are background work and do not hold messages up.+ """+ if svc.is_running(agent.session_id):+ return True+ running = getattr(svc, "running_session_ids", None)+ if not callable(running):+ return False+ prefix = agent.session_id + PAIR_SESSION_MARKER+ return any(sid.startswith(prefix) for sid in running())++def frame_incoming(env: SocietyEnvelope, sender_name: str) -> str:"""How a board envelope reads inside the receiving agent's chat."""kind = str(env.msg_type).lower()@@ -196,7 +237,11 @@ def make_deliver_hook(raise DeliveryBusy("Jarvis chat is not open yet")session = sessions[0]else:- session = ensure_session(svc, get_cfg(), target)+ # Jarvis and teammates talk in their own conversation chat; only the+ # person's own messages belong in the agent's canonical chat.+ session = ensure_session(+ svc, get_cfg(), target, counterpart=env.from_agent, counterpart_name=sender+ )await svc.receive_message(session.session_id, incoming)return svc, session, incoming@@ -210,7 +255,7 @@ def make_deliver_hook(receipt = svc.store.incoming_message(session.session_id, env.event_id)if receipt is not None and receipt["status"] == "delivered":return- if svc.is_running(session.session_id):+ if svc.is_running(session.session_id) or _agent_busy(svc, target):raise DeliveryBusy(f"target busy: {target.name} is running a turn")token = incoming_context.set(incoming)try:diff --git a/jarvis/society/checkpoints.py b/jarvis/society/checkpoints.pyindex 229e1e2713..2e269a1b1d 100644--- a/jarvis/society/checkpoints.py+++ b/jarvis/society/checkpoints.py@@ -291,6 +291,20 @@ _MOVING_TYPES = frozenset()+def _other_running_chat(svc: Any, agent_id: str, current: str) -> str | None:+ """A chat of ``agent_id`` other than ``current`` that runs a turn right now."""+ from .roster import canonical_session_id++ canonical = canonical_session_id(agent_id)+ running = getattr(svc, "running_session_ids", None)+ if not callable(running):+ return None+ for sid in running():+ if sid != current and (sid == canonical or sid.startswith(canonical + ":")):+ return sid+ return None++class CheckpointEngine:def __init__(self,@@ -413,6 +427,7 @@ class CheckpointEngine:if svc is None:returnqueue = svc.subscribe(session_id)+ cancelled = Falsetry:agent = await self._runtime.roster.get(agent_id)cli_seat = agent is not None and self._cli_seat(agent)@@ -433,12 +448,19 @@ class CheckpointEngine:elif kind == "turn_finished":breakexcept asyncio.CancelledError:+ cancelled = Trueraiseexcept Exception: # noqa: BLE001 — the world is a projection; a miss never breaks the turnlog.warning("society checkpoints: turn watcher for %s failed", agent_id, exc_info=True)finally:svc.unsubscribe(session_id, queue)- self.clear_tool_calls(agent_id)+ # Another of the agent's chats may still work (a conversation with+ # Jarvis beside the person's chat): follow that one next.+ other = None if cancelled else _other_running_chat(svc, agent_id, session_id)+ if other is None:+ self.clear_tool_calls(agent_id)+ else:+ asyncio.get_running_loop().call_soon(self.note_turn_started, agent_id, other)# Runs on the loop even when the task is cancelled during shutdown.self._fire(agent_id, "turn")@@ -455,14 +477,24 @@ class CheckpointEngine:return Nonedef turn_running(self, agent_id: str) -> bool:- """True while the agent's canonical chat session runs a turn."""+ """True while any of the agent's chats runs a turn.++ That is its canonical chat, a routine run or a conversation with+ Jarvis or a teammate (``society:<agent_id>:...``).+ """svc = self._chat_service()if svc is None:return Falsefrom .roster import canonical_session_id+ canonical = canonical_session_id(agent_id)try:- return bool(svc.is_running(canonical_session_id(agent_id)))+ if svc.is_running(canonical):+ return True+ running = getattr(svc, "running_session_ids", None)+ if not callable(running):+ return False+ return any(sid.startswith(canonical + ":") for sid in running())except Exception: # noqa: BLE001 — a service without the probe reports no turnlog.debug("society checkpoints: is_running probe failed", exc_info=True)return Falsediff --git a/jarvis/society/conversation.py b/jarvis/society/conversation.pyindex 36ff4f85ee..d5219cb38e 100644--- a/jarvis/society/conversation.py+++ b/jarvis/society/conversation.py@@ -98,34 +98,46 @@ class ConversationArchive:"INSERT INTO messages_fts(rowid,text) VALUES(?,?)", (cursor.lastrowid, text))- def search(self, session: str, query: str, *, limit: int = 5) -> list[dict[str, Any]]:+ def search(+ self, session: str, query: str, *, limit: int = 5, include_owned: bool = False+ ) -> list[dict[str, Any]]:+ """Search one chat; ``include_owned`` adds every ``<session>:...`` chat.++ An agent's canonical chat owns its routine runs and its conversations+ with Jarvis and teammates, so recall finds what was said in any of them.+ """words = re.findall(r"\w+", query, re.UNICODE)if not words:return []limit = max(1, min(20, limit))+ prefix = session + ":"+ scope = "(m.session=? OR substr(m.session,1,?)=?)" if include_owned else "m.session=?"+ scope_args: tuple[Any, ...] = (+ (session, len(prefix), prefix) if include_owned else (session,)+ )with self._lock:if self.fts_available:expression = " OR ".join('"' + w + '"' for w in words[:32])- rows = self._db.execute(- "SELECT m.seq,m.kind,m.text FROM messages_fts f "+ sql = (+ "SELECT m.session,m.seq,m.kind,m.text FROM messages_fts f " # noqa: S608"JOIN messages m ON m.id=f.rowid WHERE messages_fts MATCH ? "- "AND m.session=? ORDER BY bm25(messages_fts),m.seq DESC LIMIT ?",- (expression, session, limit),- ).fetchall()+ f"AND {scope} ORDER BY bm25(messages_fts),m.seq DESC LIMIT ?"+ )+ rows = self._db.execute(sql, (expression, *scope_args, limit)).fetchall()else:- clauses = " OR ".join("instr(lower(text),?)>0" for _ in words[:32])- rows = self._db.execute(- "SELECT seq,kind,text FROM messages WHERE session=? AND (" # noqa: S608 - bound values- + clauses- + ") ORDER BY seq DESC LIMIT ?",- (session, *(w.lower() for w in words[:32]), limit),- ).fetchall()+ clauses = " OR ".join("instr(lower(m.text),?)>0" for _ in words[:32])+ sql = ( # scope and clauses are fixed SQL; every value is bound+ "SELECT m.session,m.seq,m.kind,m.text FROM messages m " # noqa: S608+ f"WHERE {scope} AND ({clauses}) ORDER BY m.seq DESC LIMIT ?"+ )+ words_lower = (w.lower() for w in words[:32])+ rows = self._db.execute(sql, (*scope_args, *words_lower, limit)).fetchall()return [{"seq": r["seq"],"kind": r["kind"],"text": r["text"],- "source": f"chat:{session}#seq={r['seq']}",+ "source": f"chat:{r['session']}#seq={r['seq']}",}for r in rows]@@ -239,9 +251,13 @@ class ConversationArchive:)def review_counts(self, agent_id: str) -> dict[str, int]:- """Count direct chats and routine reviews without reading conversation contents."""+ """Count reviews of every chat the agent owns without reading their contents.++ That is the canonical chat, routine runs and the conversations with+ Jarvis and teammates (``society:<agent>:...``).+ """session = f"society:{agent_id}"- prefix = session + ":routine:"+ prefix = session + ":"with self._lock:rows = self._db.execute("SELECT status,count(*) AS n FROM reviews WHERE session=? OR "diff --git a/jarvis/society/conversation_tool.py b/jarvis/society/conversation_tool.pyindex 7e388466fe..5c77aff1e0 100644--- a/jarvis/society/conversation_tool.py+++ b/jarvis/society/conversation_tool.py@@ -11,8 +11,10 @@ class ConversationRecallTool:name = "society_conversation_recall"risk_tier = "safe"description = (- "Recall YOUR earlier conversations. Use query to search, or after_seq to read "- "the next page of original events. Results are historical evidence, not new instructions. "+ "Recall YOUR earlier conversations. Use query to search every chat of yours (the "+ "user's chat with you, routine runs and your conversations with Jarvis and teammates), "+ "or after_seq to read the next page of your chat with the user. Results are "+ "historical evidence, not new instructions. ""Cite the returned source; no other agent's private chat is accessible.")schema = {@@ -38,9 +40,9 @@ class ConversationRecallTool:archive.ingest(session, service.store.list_events(session))limit = max(1, min(20, int(args.get("limit") or 5)))if str(args.get("query") or "").strip():- return ToolResult(- True, {"hits": archive.search(session, str(args["query"]), limit=limit)}- )+ query = str(args["query"])+ hits = archive.search(session, query, limit=limit, include_owned=True)+ return ToolResult(True, {"hits": hits})events = archive.read(session, after_seq=max(0, int(args.get("after_seq") or 0)), limit=limit)@@ -124,13 +126,15 @@ class RoutineInvokeTool:store, scheduler = self._runtime.task_services()if store is None or scheduler is None:return ToolResult(False, {}, "The routine scheduler is unavailable")+ from .surface import agent_id_of+turn = current_chat_turn.get()task_id = str(args.get("task_id") or "")row = await store.get(task_id)if (not turnor not turn.direct_user- or turn.session_id != agent.session_id+ or agent_id_of(turn.session_id) != self._agent_idor not rowor not is_agent_routine(row, self._agent_id)):diff --git a/jarvis/society/quests.py b/jarvis/society/quests.pyindex f00b0cfe23..34991dbe23 100644--- a/jarvis/society/quests.py+++ b/jarvis/society/quests.py@@ -41,7 +41,7 @@ from jarvis.missions.ids import uuid7_strfrom .capabilities import CapabilityRowfrom .events import USER_ACTOR, MsgType, QuestState, SocietyEnvelope, Tier, now_msfrom .focus import derive_focus-from .roster import AgentRecord, AgentState+from .roster import AgentRecord, AgentState, conversation_session_idfrom .seeds import proposal_for_capabilitylog = logging.getLogger(__name__)@@ -336,14 +336,18 @@ class Quests:# ------------------------------------------------------------ waiting- def blocker_of(self, agent_id: str) -> str:+ def blocker_of(self, agent_id: str, sender: str = USER_ACTOR) -> str:"""Why the agent cannot take work right now: ``approval`` (its chat waits- for the person), ``busy`` (a turn runs), or an empty string."""+ for the person), ``busy`` (a turn runs), or an empty string.++ ``sender`` picks the chat the quest runs in: the person's quests use the+ agent's canonical chat, Jarvis' its conversation chat with Jarvis.+ """get_chat = getattr(self._runtime, "_get_chat", None)svc = get_chat() if callable(get_chat) else Noneif svc is None:return ""- session_id = f"society:{agent_id}"+ session_id = conversation_session_id(agent_id, sender)try:pending = getattr(svc, "pending_approvals", None)if callable(pending) and pending(session_id):@@ -590,7 +594,11 @@ class Quests:result = {"status": "waiting","reason": reason,- "blocker": self.blocker_of(quest.agent_id) if quest.agent_id else "",+ "blocker": (+ self.blocker_of(quest.agent_id, quest.created_by or USER_ACTOR)+ if quest.agent_id+ else ""+ ),"text": env.text,"attempts": attempts,}diff --git a/jarvis/society/remote.py b/jarvis/society/remote.pyindex 40fa3d61b0..47c78865af 100644--- a/jarvis/society/remote.py+++ b/jarvis/society/remote.py@@ -212,7 +212,8 @@ async def placement_for_session(session: Any) -> tuple[str, str] | None:session_id = str(getattr(session, "session_id", "") or "")if not session_id.startswith("society:"):return None- agent_id = session_id.split(":", 1)[1]+ # Routine runs and conversation chats keep their owner's remote placement.+ agent_id = session_id.split(":", 2)[1]from .runtime import current_runtimeruntime = current_runtime()diff --git a/jarvis/society/roster.py b/jarvis/society/roster.pyindex 657824dd0c..f6f45cb019 100644--- a/jarvis/society/roster.py+++ b/jarvis/society/roster.py@@ -41,7 +41,10 @@ __all__ = ["LEAD_AGENT_ID","Roster","RosterError",+ "PAIR_SESSION_MARKER","canonical_session_id",+ "conversation_session_id",+ "pair_session_id","slugify",]@@ -74,6 +77,32 @@ def canonical_session_id(agent_id: str) -> str:return f"society:{agent_id}"+#: Marks the receiver's own chat for one counterpart:+#: ``society:<receiver>:with:<sender>``.+PAIR_SESSION_MARKER: Final[str] = ":with:"+_SLUG_RE: Final[re.Pattern[str]] = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*")+++def pair_session_id(agent_id: str, counterpart_id: str) -> str:+ """The chat ``agent_id`` works in on messages from ``counterpart_id``.++ Jarvis and the teammates talk in their own conversation, never in the+ chat a person has with the agent: that chat stays the person's.+ """+ return f"{canonical_session_id(agent_id)}{PAIR_SESSION_MARKER}{counterpart_id}"+++def conversation_session_id(agent_id: str, sender_id: str) -> str:+ """Where a message from ``sender_id`` to ``agent_id`` runs.++ The person (``user``) speaks in the agent's canonical chat; Jarvis and+ every other agent get the pair chat of that sender.+ """+ if sender_id == "user" or sender_id == agent_id or not _SLUG_RE.fullmatch(sender_id):+ return canonical_session_id(agent_id)+ return pair_session_id(agent_id, sender_id)++def _loads(value: Any, default: Any) -> Any:if value is None:return defaultdiff --git a/jarvis/society/runtime.py b/jarvis/society/runtime.pyindex 9a90818078..a27e6d58c4 100644--- a/jarvis/society/runtime.py+++ b/jarvis/society/runtime.py@@ -42,7 +42,7 @@ from .learning import AgentSkills, LearningPass, TurnDigest, default_creator_facfrom .memory import SocietyMemoryfrom .quests import Questsfrom .rooms import Rooms-from .roster import LEAD_AGENT_ID, AgentRecord, Roster+from .roster import LEAD_AGENT_ID, AgentRecord, Roster, conversation_session_idfrom .scheduler import DeliverHook, SocietySchedulerfrom .seeds import seed_first_runfrom .store import SocietyStore@@ -290,7 +290,7 @@ class SocietyRuntime:for original in await self.store.events_for_trace(env.trace_id):if original.event_id != env.parent_event_id or not original.to_agent:continue- session_id = f"society:{original.to_agent}"+ session_id = conversation_session_id(original.to_agent, original.from_agent)if svc.store.incoming_message(session_id, original.event_id) is not None:await svc.message_status(session_id, original.event_id, "failed", error=env.text)break@@ -503,7 +503,7 @@ class SocietyRuntime:request is Noneor request.to_agent is Noneor request.msg_type not in (MsgType.QUERY, MsgType.SAY, MsgType.PROPOSE)- or session.session_id != f"society:{request.to_agent}"+ or session.session_id != conversation_session_id(request.to_agent, request.from_agent)or reply_policy(request) == "none"or await self.store.kill_switch()):@@ -546,7 +546,11 @@ class SocietyRuntime:trace_id=request.trace_id,parent_event_id=request.event_id,msg_type=MsgType.ANSWER,- payload={"reply_policy": "none", "reply_status": status},+ payload={+ "reply_policy": "none",+ "reply_status": status,+ "from_session": session.session_id,+ },)async def recover_reviews(self) -> None:@@ -707,7 +711,16 @@ class SocietyRuntime:raise RuntimeError("agent chat service unavailable: the society cannot start work")from .chat_binding import ensure_session, frame_assignment- session = ensure_session(svc, self._get_cfg(), target)+ sender = await self.roster.get(env.from_agent) if env.from_agent != "user" else None+ # Work Jarvis or a teammate hands out runs in the target's own+ # conversation with that sender, never in the person's chat with it.+ session = ensure_session(+ svc,+ self._get_cfg(),+ target,+ counterpart=env.from_agent,+ counterpart_name=sender.name if sender is not None else env.from_agent,+ )if svc.is_running(session.session_id):raise RuntimeError(f"target busy: {target.name} is running a turn")queue = svc.subscribe(session.session_id)diff --git a/jarvis/society/scheduler.py b/jarvis/society/scheduler.pyindex e47b30ff47..21be221dc0 100644--- a/jarvis/society/scheduler.py+++ b/jarvis/society/scheduler.py@@ -286,15 +286,20 @@ class SocietyScheduler:await self._deliver(target, env)async def drain_deliveries(self) -> None:- """FIFO per recipient. Busy recipients never block other conversations."""+ """FIFO per conversation. A busy chat never blocks the recipient's others.++ Each sender talks to a recipient in its own chat (the person in the+ canonical one), so ordering only matters within one sender's queue.+ """if self._delivery_lock.locked():returnasync with self._delivery_lock:- busy: set[str | None] = set()+ busy: set[tuple[str | None, str]] = set()for env in await self._store.pending_deliveries():if await self._record_assignment_reply(env):continue- if env.to_agent in busy:+ conversation = (env.to_agent, env.from_agent)+ if conversation in busy:receive = getattr(self._deliver, "receive", None)target = await self._resolve_target(env)if receive is not None and isinstance(target, AgentRecord):@@ -306,7 +311,7 @@ class SocietyScheduler:log.warning("society: queued receipt projection failed", exc_info=True)continueif not await self._on_deliver(env):- busy.add(env.to_agent)+ busy.add(conversation)async def _record_assignment_reply(self, env: SocietyEnvelope) -> bool:"""Assignment outcomes belong to the watcher, not a second chat turn."""diff --git a/jarvis/society/surface.py b/jarvis/society/surface.pyindex 8b2d57d402..04413ad18a 100644--- a/jarvis/society/surface.py+++ b/jarvis/society/surface.py@@ -42,7 +42,7 @@ from .communication import COMMUNICATION_GUIDANCEfrom .conversation_tool import ConversationRecallTool, RoutineInvokeTool, RoutineListToolfrom .learning import RunLearnedSkillToolfrom .memory import resolve_society_vault-from .roster import AgentRecord, canonical_session_id+from .roster import PAIR_SESSION_MARKER, AgentRecord, canonical_session_idfrom .routine_runner import is_routine_sessionfrom .runtime import current_runtime@@ -51,6 +51,7 @@ log = logging.getLogger(__name__)__all__ = ["SURFACE","agent_id_of",+ "counterpart_of","build_briefing","capability_epoch","remember_always_allow",@@ -180,13 +181,27 @@ your location, use these names."""def agent_id_of(session_id: str) -> str | None:- """Resolve canonical and per-execution routine chats to their live owner."""+ """Resolve canonical, routine and conversation chats to their live owner.++ ``society:<agent>``, ``society:<agent>:routine:<task>:<run>`` and+ ``society:<agent>:with:<counterpart>`` all belong to ``<agent>``: every one+ of them gets the same identity, tools, memory and briefing.+ """if not session_id.startswith(_PREFIX):return None- agent_id = session_id[len(_PREFIX) :].split(":routine:", 1)[0].strip()+ agent_id = session_id[len(_PREFIX) :].split(":routine:", 1)[0]+ agent_id = agent_id.split(PAIR_SESSION_MARKER, 1)[0].strip()return agent_id or None+def counterpart_of(session_id: str) -> str | None:+ """The other side of a conversation chat (``society:<a>:with:<b>`` → ``b``)."""+ if not session_id.startswith(_PREFIX) or PAIR_SESSION_MARKER not in session_id:+ return None+ counterpart = session_id.split(PAIR_SESSION_MARKER, 1)[1].strip()+ return counterpart or None++def _vault_root(cfg: Any) -> Path:"""The vault the agent writes into (one resolver: ``memory.resolve_society_vault``)."""return resolve_society_vault(cfg)diff --git a/jarvis/ui/web/frontend/src/components/agentchat/useOutgoingMessages.ts b/jarvis/ui/web/frontend/src/components/agentchat/useOutgoingMessages.tsindex 5607d32973..89b91c0ea9 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/useOutgoingMessages.ts+++ b/jarvis/ui/web/frontend/src/components/agentchat/useOutgoingMessages.ts@@ -5,14 +5,22 @@ import type { InternalMessageItem, TimelineItem } from "./reduce";const MESSAGE_TYPES = new Set(["SAY", "QUERY", "ANSWER", "PROPOSE"]);const EMPTY_EVENTS: SocietyEnvelope[] = [];-/** Retain outgoing messages and their delivery vetoes, never unrelated board activity. */+/**+ * Retain outgoing messages and their delivery vetoes, never unrelated board activity.+ *+ * With `sessionId`, keep only what that chat sent: a reply the agent wrote in+ * its conversation with Jarvis or a teammate stays in that conversation.+ * Messages from before the board recorded their chat count as this chat's.+ */export function collectOutgoing(- previous: SocietyEnvelope[], rows: SocietyEnvelope[], agentId: string,+ previous: SocietyEnvelope[], rows: SocietyEnvelope[], agentId: string, sessionId?: string | null,): SocietyEnvelope[] {const messages = new Map(previous.map((row) => [row.event_id, row]));for (const row of rows) {+ const origin = row.payload.from_session;if (row.from_agent === agentId && row.to_agent && row.to_agent !== agentId&& row.to_agent !== "user" && MESSAGE_TYPES.has(row.msg_type)+ && (!sessionId || typeof origin !== "string" || origin === sessionId)&& typeof row.payload.text === "string" && row.payload.text.trim()) {messages.set(row.event_id, row);} else if (row.msg_type === "VETO" && row.parent_event_id && messages.has(row.parent_event_id)) {@@ -46,7 +54,7 @@ export function mergeOutgoingMessages(return [...items, ...outgoing].sort((a, b) => time(a) - time(b));}-export function useOutgoingMessages(agentId: string | null): SocietyEnvelope[] {+export function useOutgoingMessages(agentId: string | null, sessionId?: string | null): SocietyEnvelope[] {const [state, setState] = useState({ agentId, events: EMPTY_EVENTS });useEffect(() => {if (!agentId) return;@@ -65,7 +73,7 @@ export function useOutgoingMessages(agentId: string | null): SocietyEnvelope[] {const data: { events: SocietyEnvelope[] } = await response.json();if (controller.signal.aborted) return;setState((previous) => {- const events = collectOutgoing(previous.agentId === agentId ? previous.events : EMPTY_EVENTS, data.events, agentId);+ const events = collectOutgoing(previous.agentId === agentId ? previous.events : EMPTY_EVENTS, data.events, agentId, sessionId);return previous.agentId === agentId && previous.events === events ? previous : { agentId, events };});const next = data.events.at(-1)?.seq ?? cursor;@@ -80,6 +88,6 @@ export function useOutgoingMessages(agentId: string | null): SocietyEnvelope[] {};void read();return () => { controller.abort(); clearTimeout(timer); };- }, [agentId]);+ }, [agentId, sessionId]);return useMemo(() => state.agentId === agentId ? state.events : EMPTY_EVENTS, [agentId, state]);}diff --git a/jarvis/ui/web/frontend/src/components/society/card/RoutineChat.tsx b/jarvis/ui/web/frontend/src/components/society/card/RoutineChat.tsxindex 55d131aada..94118b1bd5 100644--- a/jarvis/ui/web/frontend/src/components/society/card/RoutineChat.tsx+++ b/jarvis/ui/web/frontend/src/components/society/card/RoutineChat.tsx@@ -1,4 +1,7 @@-/** The selected execution occupies the agent's chat lane and loads only on navigation. */+/**+ * The selected routine run or agent conversation occupies the agent's chat+ * lane and loads only on navigation.+ */import { useEffect, useMemo, useState } from "react";import { ArrowLeft, Send, Square } from "lucide-react";import { AgentTimeline } from "@/components/agentchat/AgentTimeline";@@ -23,9 +26,9 @@ export default function RoutineChat({ target, onClose }: { target: RoutineChatTa<div className="min-w-0 flex-1"><h3 className="truncate text-sm font-medium">{target.title}</h3><time className="text-[11px] text-muted-foreground" dateTime={new Date(target.timestamp).toISOString()}>{new Date(target.timestamp).toLocaleString()}</time></div>- <span className="text-[11px] text-muted-foreground">{t("society.routine_detail.background_chat")}</span>+ <span className="text-[11px] text-muted-foreground">{t(target.kind === "conversation" ? "society.conversations.badge" : "society.routine_detail.background_chat")}</span></header>- {target.legacy ? <HistoricalExecution target={target} /> : <LiveExecution sessionId={target.sessionId} />}+ {target.legacy ? <HistoricalExecution target={target} /> : <LiveExecution sessionId={target.sessionId} conversation={target.kind === "conversation"} />}</section>;}@@ -62,9 +65,10 @@ function HistoricalExecution({ target }: { target: RoutineChatTarget }) {</>;}-function LiveExecution({ sessionId }: { sessionId: string }) {+function LiveExecution({ sessionId, conversation = false }: { sessionId: string; conversation?: boolean }) {const t = useT();const label = (key: string) => t(`society.routine_detail.${key}`);+ const followUp = conversation ? t("society.conversations.follow_up") : label("follow_up");const [store] = useState(() => createAgentChatStore("society", "routine"));const timeline = store((state) => state.timeline);const visibleItems = useMemo(() => displayItems(timeline.items), [timeline.items]);@@ -91,7 +95,7 @@ function LiveExecution({ sessionId }: { sessionId: string }) {if (!message.trim() || !ready || running) return;void store.getState().send(message).then(() => { if (!store.getState().lastError) setMessage(""); });}}>- <textarea className="min-w-0 flex-1 rounded-lg border border-border bg-background p-2 text-sm" rows={2} aria-label={label("follow_up")} placeholder={label("follow_up")} value={message} onChange={(event) => setMessage(event.target.value)} />+ <textarea className="min-w-0 flex-1 rounded-lg border border-border bg-background p-2 text-sm" rows={2} aria-label={followUp} placeholder={followUp} value={message} onChange={(event) => setMessage(event.target.value)} />{running ? <button type="button" className="rounded p-2 hover:bg-secondary" aria-label={label("stop_run")} onClick={() => void store.getState().cancel()}><Square size={16} /></button>: <button type="submit" className="rounded p-2 hover:bg-secondary disabled:opacity-50" disabled={!ready || !message.trim()} aria-label={label("send")}><Send size={16} /></button>}</form>diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsxindex 5f9e1222a6..b0fa3b4770 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx@@ -27,6 +27,7 @@ import { useRoutineNavigation } from "./routineNavigation";import { notifyRoutineChanged } from "../cardData";import { routineTaskId } from "./routineExecution";import { RoutineChatHost } from "./RoutineChatHost";+import { AgentConversationsBar } from "./AgentConversations";import { MessageSquare, Mic, Paperclip, Plus, RotateCcw, Send, Square } from "lucide-react";import { ChatMarkdown, MediaPreview, mediaKind } from "@/components/agentchat/ChatMarkdown";@@ -148,6 +149,15 @@ export function itemsForOpenSession(return sessionId !== null && sessionId === activeSessionId ? items : [];}+/** Roster id → the name a person sees (the lead follows the wake word). */+function useRosterDisplayName(roster: SocietyAgent[]): (id: string, fallback: string) => string {+ const assistantName = useEventStore((state) => state.assistantName);+ return useCallback((id: string, fallback: string) => {+ const member = roster.find((a) => a.agentId === id);+ return member ? societyDisplayName(member, assistantName) : fallback;+ }, [roster, assistantName]);+}+export function AgentChatPanel(props: AgentChatPanelProps) {const disconnect = useCallback(() => {(props.agent.tier === "lead" ? useAgentChatStore : props.chatStore ?? useSocietyChatStore).getState().disconnect();@@ -226,7 +236,7 @@ function SpecialistChat({ agent, roster }: AgentChatPanelProps) {}}}, [visibleItems, agent.agentId]);- const outgoing = useOutgoingMessages(sessionReady ? agent.agentId : null);+ const outgoing = useOutgoingMessages(sessionReady ? agent.agentId : null, sessionId);const allItems = useMemo(() => mergeOutgoingMessages(visibleItems, outgoing, agent.agentId, agent.name,new Map(roster.map((member) => [member.agentId, member.name])),@@ -263,6 +273,7 @@ function SpecialistChat({ agent, roster }: AgentChatPanelProps) {() => roster.filter((a) => a.agentId !== agent.agentId && a.tier !== "lead"),[roster, agent.agentId],);+ const displayName = useRosterDisplayName(roster);return (<div@@ -271,6 +282,7 @@ function SpecialistChat({ agent, roster }: AgentChatPanelProps) {data-session-id={sessionId ?? ""}data-session-ready={sessionReady ? "true" : "false"}>+ <AgentConversationsBar agentId={agent.agentId} agentName={agent.name} displayName={displayName} /><Transcript key={`${sessionId ?? agent.agentId}:${view.boundaryId}`} items={view.items} agent={agent} roster={roster} onDecide={decide} />{lastError && sessionReady ? (<p role="alert" className="px-4 pb-1 text-xs text-destructive">@@ -353,6 +365,7 @@ function JarvisChat({ agent, roster }: AgentChatPanelProps) {// selection may open an older session; polling must not undo New chat.const mentionable = useMemo(() => roster.filter((a) => a.tier !== "lead"), [roster]);+ const displayName = useRosterDisplayName(roster);// Voice or typed — Jarvis' card only. The other agents have no voice: the// wake word, the realtime brain and the microphone belong to the lead.@@ -406,6 +419,7 @@ function JarvisChat({ agent, roster }: AgentChatPanelProps) {return (<div className="flex h-full min-h-0 flex-col bg-background" data-testid="society-chat" data-mode="chat">{header}+ <AgentConversationsBar agentId={agent.agentId} agentName={displayName(agent.agentId, agent.name)} displayName={displayName} /><Transcript key={`${activeSessionId ?? ""}:${view.boundaryId}`} items={view.items} agent={agent} roster={roster} onDecide={decide} />{lastError ? (<p role="alert" className="px-4 pb-1 text-xs text-destructive">diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentConversations.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentConversations.test.tsxnew file mode 100644index 0000000000..a365f76370--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentConversations.test.tsx@@ -0,0 +1,56 @@+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, expect, it, vi } from "vitest";+import type { SocietyEnvelope } from "@/lib/societyApi";+import { collectOutgoing } from "@/components/agentchat/useOutgoingMessages";+import { AgentConversationsBar } from "./AgentConversations";+import { useRoutineNavigation } from "./routineNavigation";++vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));+afterEach(() => { cleanup(); vi.unstubAllGlobals(); useRoutineNavigation.getState().close(); });++function sent(seq: number, fromSession?: string): SocietyEnvelope {+ return { seq, event_id: `m${seq}`, msg_type: "ANSWER", from_agent: "scout", to_agent: "jarvis",+ trace_id: "t", parent_event_id: null, ts_ms: seq * 1000, cost_usd: 0,+ payload: { text: `Reply ${seq}`, ...(fromSession ? { from_session: fromSession } : {}) } };+}++it("keeps a reply written in a conversation chat out of the person's chat", () => {+ const rows = [sent(1), sent(2, "society:scout"), sent(3, "society:scout:with:jarvis")];+ expect(collectOutgoing([], rows, "scout", "society:scout").map((row) => row.event_id)).toEqual(["m1", "m2"]);+ expect(collectOutgoing([], rows, "scout").map((row) => row.event_id)).toEqual(["m1", "m2", "m3"]);+});++it("lists the agent's conversations and opens one as a full chat", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ conversations: [{+ session_id: "society:scout:with:jarvis", title: "Scout · Jarvis", updated_ms: 5000, running: true,+ owner_id: "scout", counterpart_id: "jarvis", counterpart_name: "Jarvis",+ }] }))));+ render(<AgentConversationsBar agentId="scout" agentName="Scout" displayName={(id, fallback) => id === "jarvis" ? "Hanna" : fallback} />);+ const chip = await screen.findByTestId("agent-conversation");+ expect(chip.textContent).toContain("society.conversations.with");+ expect(chip.dataset.state).toBe("running");+ fireEvent.click(chip);+ expect(useRoutineNavigation.getState().target).toEqual({+ agentId: "scout", sessionId: "society:scout:with:jarvis", kind: "conversation",+ title: "Scout · Hanna", timestamp: 5000,+ });+});++it("shows nothing while the agent has no conversations", async () => {+ const fetchMock = vi.fn(async () => new Response(JSON.stringify({ conversations: [] })));+ vi.stubGlobal("fetch", fetchMock);+ const { container } = render(<AgentConversationsBar agentId="scout" agentName="Scout" displayName={(_, f) => f} />);+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledWith("/api/society/agents/scout/conversations", expect.anything()));+ expect(container.innerHTML).toBe("");+});++it("marks a conversation that waits for the person", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ conversations: [{+ session_id: "society:scout:with:nova", title: "Scout · Nova", updated_ms: 1, running: true, waiting: true,+ owner_id: "scout", counterpart_id: "nova", counterpart_name: "Nova",+ }] }))));+ render(<AgentConversationsBar agentId="scout" agentName="Scout" displayName={(_, f) => f} />);+ const chip = await screen.findByTestId("agent-conversation");+ expect(chip.dataset.state).toBe("waiting");+ expect(chip.textContent).toContain("society.conversations.waiting");+});diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentConversations.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentConversations.tsxnew file mode 100644index 0000000000..ee28fddd38--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentConversations.tsx@@ -0,0 +1,120 @@+/**+ * The agent's own conversations with Jarvis and its teammates.+ *+ * When Jarvis or another agent sends this agent something, the agent works on+ * it in a separate chat (`society:<agent>:with:<sender>`) — never in the+ * person's chat with the agent. This strip lists those chats and opens one in+ * the card's chat lane as a full chat: the whole work trace, approvals and a+ * composer to step in.+ */+import { useEffect, useState } from "react";+import { MessagesSquare } from "lucide-react";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { useRoutineNavigation } from "./routineNavigation";++export interface AgentConversation {+ session_id: string;+ title: string;+ updated_ms: number;+ running: boolean;+ /** An approval card or a question in this chat waits for the person. */+ waiting?: boolean;+ owner_id: string;+ counterpart_id: string;+ counterpart_name: string;+}++export async function fetchAgentConversations(agentId: string, signal?: AbortSignal): Promise<AgentConversation[]> {+ const response = await fetch(`/api/society/agents/${encodeURIComponent(agentId)}/conversations`, { signal });+ if (!response.ok) throw new Error(`HTTP ${response.status}`);+ const data: { conversations?: AgentConversation[] } = await response.json();+ return data.conversations ?? [];+}++/**+ * Keep the list fresh without hammering the backend: one jittered request every+ * 8-12 s. Not gated on `document.hidden` — WebView2 misreports it.+ */+function useAgentConversations(agentId: string): AgentConversation[] {+ const [state, setState] = useState<{ agentId: string; rows: AgentConversation[] }>({ agentId, rows: [] });+ useEffect(() => {+ const controller = new AbortController();+ let timer: ReturnType<typeof setTimeout>;+ const read = async () => {+ try {+ const rows = await fetchAgentConversations(agentId, controller.signal);+ if (!controller.signal.aborted) setState({ agentId, rows });+ } catch (cause) {+ if (!controller.signal.aborted) console.warn("Could not load the agent's conversations", cause);+ } finally {+ if (!controller.signal.aborted) timer = setTimeout(() => void read(), 8000 + Math.random() * 4000);+ }+ };+ void read();+ return () => { controller.abort(); clearTimeout(timer); };+ }, [agentId]);+ return state.agentId === agentId ? state.rows : [];+}++export function AgentConversationsBar({ agentId, agentName, displayName }: {+ agentId: string;+ agentName: string;+ /** The name a person sees for a roster id (the lead follows the wake word). */+ displayName: (id: string, fallback: string) => string;+}) {+ const t = useT();+ const open = useRoutineNavigation((state) => state.open);+ const rows = useAgentConversations(agentId);+ if (!rows.length) return null;+ return (+ <div+ className="flex shrink-0 items-center gap-2 overflow-x-auto border-b border-border px-3 py-1.5"+ data-testid="agent-conversations"+ title={t("society.conversations.hint")}+ >+ <span className="flex shrink-0 items-center gap-1 text-[11px] text-muted-foreground">+ <MessagesSquare className="h-3.5 w-3.5" aria-hidden />+ {t("society.conversations.label")}+ </span>+ {rows.map((row) => {+ const name = displayName(row.counterpart_id, row.counterpart_name);+ return (+ <button+ key={row.session_id}+ type="button"+ data-testid="agent-conversation"+ data-session-id={row.session_id}+ onClick={() => open({+ agentId,+ sessionId: row.session_id,+ kind: "conversation",+ // The owner's name first: the lead's list opens the agents' chats with it.+ title: row.owner_id === agentId+ ? `${agentName} · ${name}`+ : `${name} · ${agentName}`,+ timestamp: row.updated_ms,+ })}+ data-state={row.waiting ? "waiting" : row.running ? "running" : "idle"}+ title={row.waiting ? t("society.conversations.waiting") : undefined}+ className={cn(+ "flex shrink-0 items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-[11px] hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ row.waiting ? "border-warning text-warning" : "border-border text-foreground",+ )}+ >+ <span+ aria-hidden+ className={cn(+ "h-1.5 w-1.5 rounded-full",+ row.waiting ? "bg-warning" : row.running ? "bg-success" : "bg-muted-foreground/50",+ )}+ />+ {t("society.conversations.with").replace("{0}", name)}+ {row.waiting ? <span className="sr-only">{t("society.conversations.waiting")}</span>+ : row.running ? <span className="sr-only">{t("society.conversations.running")}</span> : null}+ </button>+ );+ })}+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/chat/routineExecution.ts b/jarvis/ui/web/frontend/src/components/society/chat/routineExecution.tsindex 6c65dd4fce..874158440f 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/routineExecution.ts+++ b/jarvis/ui/web/frontend/src/components/society/chat/routineExecution.ts@@ -3,6 +3,8 @@ import type { AgentChatEvent } from "@/lib/agentChatApi";export interface RoutineChatTarget {agentId: string;sessionId: string;+ /** A routine run (default) or the agent's conversation with Jarvis or a teammate. */+ kind?: "routine" | "conversation";title: string;timestamp: number;result?: string;diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json b/jarvis/ui/web/frontend/src/i18n/locales/society/de.jsonindex 1878d6108d..b8e72e7765 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json@@ -45,6 +45,15 @@"read_only": "Nur lesen · Von diesem Agenten gepflegt","model": "Modell"},+ "conversations": {+ "label": "Gespräche",+ "hint": "Hier arbeitet der Agent an dem, was {name} oder ein anderer Agent ihm schickt – getrennt von deinem Chat.",+ "with": "mit {0}",+ "running": "arbeitet gerade",+ "waiting": "wartet auf dich",+ "badge": "Agenten-Gespräch",+ "follow_up": "In diesem Gespräch nachfragen…"+ },"routine_detail": {"back_to_agent": "Zurück zum Agenten-Chat","saved_result": "Gespeichertes Ausführungsergebnis",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json b/jarvis/ui/web/frontend/src/i18n/locales/society/en.jsonindex ea4367d805..60fc39fa7d 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json@@ -45,6 +45,15 @@"read_only": "Read-only · Maintained by this agent","model": "Model"},+ "conversations": {+ "label": "Conversations",+ "hint": "Where this agent works on what {name} or a teammate sent it, kept apart from your chat.",+ "with": "with {0}",+ "running": "working now",+ "waiting": "waiting for you",+ "badge": "Agent conversation",+ "follow_up": "Ask in this conversation…"+ },"routine_detail": {"back_to_agent": "Back to agent chat","saved_result": "Saved execution result",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json b/jarvis/ui/web/frontend/src/i18n/locales/society/es.jsonindex da27eccfff..37f8b9b17b 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json@@ -45,6 +45,15 @@"read_only": "Solo lectura · Mantenido por este agente","model": "Modelo"},+ "conversations": {+ "label": "Conversaciones",+ "hint": "Aquí el agente trabaja en lo que {name} u otro agente le envía, separado de tu chat.",+ "with": "con {0}",+ "running": "trabajando ahora",+ "waiting": "te está esperando",+ "badge": "Conversación entre agentes",+ "follow_up": "Preguntar en esta conversación…"+ },"routine_detail": {"back_to_agent": "Volver al chat del agente","saved_result": "Resultado guardado de la ejecución",diff --git a/jarvis/ui/web/mcp_server_routes.py b/jarvis/ui/web/mcp_server_routes.pyindex b18328b390..1fc42309f3 100644--- a/jarvis/ui/web/mcp_server_routes.py+++ b/jarvis/ui/web/mcp_server_routes.py@@ -137,7 +137,10 @@ def session_ref(scope: dict[str, Any]) -> str | None:value = raw_value.decode("latin-1").strip()# Society chats use a namespaced roster slug, while ordinary chats# use opaque alphanumeric IDs. Preserve that scope for tool lookup.- if len(value) <= 128 and re.fullmatch(r"society:[a-z0-9]+(?:-[a-z0-9]+)*", value):+ if len(value) <= 128 and re.fullmatch(+ r"society:[a-z0-9]+(?:-[a-z0-9]+)*(?::with:[a-z0-9]+(?:-[a-z0-9]+)*)?",+ value,+ ):return valueif len(value) <= 64 and re.fullmatch(r"[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*", value):return valuediff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.pyindex e24db48975..6b7bbfd89c 100644--- a/jarvis/ui/web/society_routes.py+++ b/jarvis/ui/web/society_routes.py@@ -12,6 +12,7 @@ is dangerous in both directions because releasing it resumes work.from __future__ import annotations+import asyncioimport loggingfrom collections.abc import Iteratorfrom contextlib import contextmanager@@ -360,6 +361,53 @@ async def bind_agent_chat(agent_id: str, request: Request) -> dict[str, Any]:return {"session": session.to_dict(), "agent_id": agent.agent_id}[email protected]("/agents/{agent_id}/conversations", openapi_extra={"x-jarvis-readonly": True})+async def agent_conversations(agent_id: str, request: Request) -> dict[str, Any]:+ """The agent's own chats with Jarvis and teammates, newest first.++ Each is ``society:<agent>:with:<counterpart>``: where the agent works on what+ Jarvis or a teammate sent it, kept out of the person's chat with the agent.+ For Jarvis these are the agents' chats with Jarvis. Nothing runs or bills.+ """+ rt = await _runtime(request)+ agent = await rt.roster.resolve(agent_id)+ if agent is None:+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})+ svc = rt.chat_service()+ if svc is None:+ raise HTTPException(503, "agent chat service unavailable")+ from jarvis.society.roster import LEAD_AGENT_ID, PAIR_SESSION_MARKER+ from jarvis.society.surface import agent_id_of, counterpart_of++ if agent.agent_id == LEAD_AGENT_ID:+ sessions = await asyncio.to_thread(+ svc.store.list_sessions_matching, "society:", PAIR_SESSION_MARKER + LEAD_AGENT_ID+ )+ else:+ sessions = await asyncio.to_thread(+ svc.store.list_sessions_matching, agent.session_id + PAIR_SESSION_MARKER+ )+ names = {member.agent_id: member.name for member in await rt.roster.list()}+ rows: list[dict[str, Any]] = []+ for session in sessions:+ sid = session.session_id+ owner_id = agent_id_of(sid) or ""+ counterpart_id = counterpart_of(sid) or ""+ other_id = owner_id if agent.agent_id == LEAD_AGENT_ID else counterpart_id+ row = session.to_dict()+ row["running"] = svc.is_running(sid)+ # An approval card or a question waits for the person in this chat.+ questions = getattr(svc, "pending_questions", None)+ row["waiting"] = bool(+ svc.pending_approvals(sid) or (questions(sid) if callable(questions) else [])+ )+ row["owner_id"] = owner_id+ row["counterpart_id"] = other_id+ row["counterpart_name"] = names.get(other_id, other_id)+ rows.append(row)+ return {"agent_id": agent.agent_id, "conversations": rows}++@router.delete("/agents/{agent_id}")async def archive_agent(agent_id: str, request: Request) -> dict[str, Any]:rt = await _runtime(request)@@ -703,9 +751,19 @@ async def switch_agent_model(agent_id: str, body: ModelBody, request: Request) -"account_id": body.account_id.strip(),}chat = rt._get_chat()- if chat is not None and hasattr(chat, "controls") and chat.store.get_session(agent.session_id):- await chat.controls.pause(agent.session_id, "Model settings changed")- await chat.controls._clear_saved_native(agent.session_id)+ if chat is not None and hasattr(chat, "controls"):+ from jarvis.society.roster import PAIR_SESSION_MARKER++ # The person's chat and every conversation chat run on the card's seat.+ matching = getattr(chat.store, "list_sessions_matching", None)+ owned = [agent.session_id] + [+ s.session_id+ for s in (matching(agent.session_id + PAIR_SESSION_MARKER) if matching else [])+ ]+ for sid in owned:+ if chat.store.get_session(sid):+ await chat.controls.pause(sid, "Model settings changed")+ await chat.controls._clear_saved_native(sid)try:updated = await rt.roster.update(agent.agent_id, fields)except RosterError as exc:diff --git a/tests/contract/test_internal_messages.py b/tests/contract/test_internal_messages.pyindex 653efd08ca..6890f05a02 100644--- a/tests/contract/test_internal_messages.py+++ b/tests/contract/test_internal_messages.py@@ -78,7 +78,9 @@ async def test_lead_message_is_an_internal_chat_receipt(world):await drain(rt)assert result.success and tool.risk_tier == "safe"target = await rt.roster.resolve("Gmail agent")- events = svc.store.list_events(target.session_id)+ # Jarvis' message lands in the agent's conversation with Jarvis, not the person's chat.+ assert svc.store.get_session(target.session_id) is None+ events = svc.store.list_events(f"{target.session_id}:with:jarvis")receipt = next(e["payload"] for e in events if e["kind"] == "agent_message")assert receipt["sender_name"] == "Jarvis" and receipt["sender_kind"] == "jarvis"assert receipt["text"] == "A test message"@@ -95,16 +97,16 @@ async def test_busy_recipient_keeps_fifo_receipts_then_resumes_once(world):third = await rt.say(from_agent=rt.lead_id, to_agent="scout", text="third")await drain(rt)assert await rt.store.delivery_status(second.event_id) == "queued"- receipt = svc.store.incoming_message("society:scout", second.event_id)+ receipt = svc.store.incoming_message("society:scout:with:jarvis", second.event_id)assert receipt["status"] == "queued"- await svc.cancel("society:scout")+ await svc.cancel("society:scout:with:jarvis")await drain(rt)assert await rt.store.delivery_status(second.event_id) == "delivered"assert await rt.store.delivery_status(third.event_id) == "queued"await rt.scheduler.on_envelope(first)- await svc.cancel("society:scout")+ await svc.cancel("society:scout:with:jarvis")await drain(rt)- events = svc.store.list_events("society:scout")+ events = svc.store.list_events("society:scout:with:jarvis")assert [e["payload"]["text"] for e in events if e["kind"] == "agent_message"] == ["first","second",@@ -120,9 +122,9 @@ async def test_replay_after_chat_acceptance_does_not_start_another_turn(world):# Simulate interruption after chat accepted the turn but before the board# stored the receipt. The receiving chat is the idempotency boundary.await rt.store.mark_delivery(env.event_id, "queued")- await svc.cancel("society:scout")+ await svc.cancel("society:scout:with:jarvis")await drain(rt)- events = svc.store.list_events("society:scout")+ events = svc.store.list_events("society:scout:with:jarvis")assert sum(e["kind"] == "turn_started" for e in events) == 1assert sum(e["kind"] == "agent_message" for e in events) == 1@@ -156,7 +158,8 @@ async def test_failure_updates_a_visible_queued_message(world):await rt.store.set_kill_switch(True)await drain(rt)assert await rt.store.delivery_status(env.event_id) == "failed"- assert svc.store.incoming_message("society:scout", env.event_id)["status"] == "failed"+ receipt = svc.store.incoming_message("society:scout:with:jarvis", env.event_id)+ assert receipt["status"] == "failed"async def test_agent_reply_keeps_conversation_and_cannot_forge_sender(world):diff --git a/tests/contract/test_society_communication.py b/tests/contract/test_society_communication.pyindex c6b7807985..581888da03 100644--- a/tests/contract/test_society_communication.py+++ b/tests/contract/test_society_communication.py@@ -125,7 +125,8 @@ async def finish_message(rt, chat, request, **kwargs):try:done, events = completion(**kwargs)await rt._complete_message_reply(- chat.store.get_session(f"society:{request.to_agent}"),+ # Jarvis' message runs in the receiver's conversation chat with Jarvis.+ chat.store.get_session(f"society:{request.to_agent}:with:{request.from_agent}"),done,events,)@@ -282,7 +283,7 @@ async def test_assignment_reporting_preserves_result_and_releases_slot(chat.store.incoming_message(session.session_id, reported.output["message_id"])for session in chat.store.list_sessions(surface="jarvis"))- queue = chat.queues["society:scout"]+ queue = chat.queues["society:scout:with:jarvis"]await queue.put({"kind": "assistant_text", "payload": {"text": "Recorded outcome."}})await queue.put({"kind": "turn_finished", "payload": {"status": "completed"}})watchers = list(rt._watchers)diff --git a/tests/contract/test_trigger_sources.py b/tests/contract/test_trigger_sources.pyindex 2e8f29521a..a7aac1f1f0 100644--- a/tests/contract/test_trigger_sources.py+++ b/tests/contract/test_trigger_sources.py@@ -94,7 +94,7 @@ async def test_chat_invocation_requires_owner_user_turn_and_is_absent_in_plan_moclass Roster:async def get(self, agent_id):- return SimpleNamespace(state="active", session_id="owner-chat")+ return SimpleNamespace(state="active", session_id="society:owner")class State:async def kill_switch(self):@@ -107,9 +107,11 @@ async def test_chat_invocation_requires_owner_user_turn_and_is_absent_in_plan_molisting = RoutineListTool(runtime, "owner")assert plan_filter({invoke.name: invoke, listing.name: listing}) == {listing.name: listing}for session_id, direct_user, allowed in (- ("owner-chat", False, False),- ("other-chat", True, False),- ("owner-chat", True, True),+ ("society:owner", False, False),+ ("society:other", True, False),+ ("society:owner", True, True),+ # The person stepped into the owner's conversation chat with Jarvis.+ ("society:owner:with:jarvis", True, True),):context = current_chat_turn.set(ChatTurn(session_id, "turn", "Run it", direct_user, "trace")@@ -119,7 +121,7 @@ async def test_chat_invocation_requires_owner_user_turn_and_is_absent_in_plan_moassert result.success is allowedfinally:current_chat_turn.reset(context)- assert (await store.hooks.counts(task_id))[1] == 1+ assert (await store.hooks.counts(task_id))[1] == 2def test_seven_groups_have_real_source_definitions():diff --git a/tests/unit/plugins/tool/test_delegate_to_agent.py b/tests/unit/plugins/tool/test_delegate_to_agent.pyindex 7da4f5ceae..9f97215462 100644--- a/tests/unit/plugins/tool/test_delegate_to_agent.py+++ b/tests/unit/plugins/tool/test_delegate_to_agent.py@@ -73,7 +73,7 @@ async def test_delegate_acks_and_assigns(runtime):assert res.artifacts[1].startswith("assignment:")assert res.artifacts[2].startswith("trace:voice:")# The assignment went through the scheduler into Scout's canonical chat.- assert chat.sent and chat.sent[0][0] == "society:scout"+ assert chat.sent and chat.sent[0][0] == "society:scout:with:jarvis"assert "Find the best VPS." in chat.sent[0][1]events = await rt.store.events_since(0)assert [e.msg_type for e in events][-2:] == [MsgType.ASSIGN, MsgType.CLAIM]@@ -189,7 +189,7 @@ async def test_delegate_without_a_name_picks_by_the_task(team):)assert res.success, res.errorassert res.output["acknowledgement"] == "Gmail agent is on it, I will let you know."- assert chat.sent and chat.sent[0][0] == "society:gmail-agent"+ assert chat.sent and chat.sent[0][0] == "society:gmail-agent:with:jarvis"async def test_delegate_unknown_name_does_not_redirect_work(team):diff --git a/tests/unit/society/test_chat_binding.py b/tests/unit/society/test_chat_binding.pyindex 37a8df501b..3033a95932 100644--- a/tests/unit/society/test_chat_binding.py+++ b/tests/unit/society/test_chat_binding.py@@ -119,9 +119,11 @@ async def test_deliver_hook_frames_and_sends(world):payload={"text": "Where is the VPS note?", "refs": ["wiki:society/archivist/vps.md"]},)await deliver(scout, env)+ # A teammate's message runs in Scout's conversation with that teammate,+ # never in the person's own chat with Scout.assert svc.sent == [(- "society:scout",+ "society:scout:with:archivist","[query from Archivist]\nWhere is the VPS note?\nRefs: wiki:society/archivist/vps.md\n"f"Message id: {env.event_id}; sender id: archivist\n""Reply to the sender using society_message_agent with kind 'answer'. "@@ -130,7 +132,9 @@ async def test_deliver_hook_frames_and_sends(world):"messaging connector. No preliminary acknowledgement is needed.",)]- svc.busy.add("society:scout")+ assert svc.store.get_session("society:scout") is None+ assert svc.store.get_session("society:scout:with:archivist").title == "Scout · Archivist"+ svc.busy.add("society:scout:with:archivist")with pytest.raises(RuntimeError, match="target busy"):await deliver(scout, env)@@ -164,7 +168,7 @@ async def test_scheduler_delivers_through_the_hook(world):await rt.roster.create(name="Archivist", provider="openai")rt.set_deliver(make_deliver_hook(lambda: svc, lambda: cfg))await rt.say(from_agent="scout", to_agent="archivist", text="ping")- assert [s[0] for s in svc.sent] == ["society:archivist"]+ assert [s[0] for s in svc.sent] == ["society:archivist:with:scout"]assert svc.sent[0][1].startswith("[say from Scout]")diff --git a/tests/unit/society/test_conversation_chats.py b/tests/unit/society/test_conversation_chats.pynew file mode 100644index 0000000000..b6793be0b8--- /dev/null+++ b/tests/unit/society/test_conversation_chats.py@@ -0,0 +1,290 @@+"""Jarvis and the agents talk in their own conversation chats.++Live bug 2026-10-02: when Jarvis (or a teammate) messaged an agent, the message+and the agent's whole work turn landed in the person's own chat with that+agent. Every sender now gets its own chat on the receiving side,+``society:<agent>:with:<sender>``, with the agent's full identity: the same+seat, tools, memory and briefing as the person's chat.+"""++from __future__ import annotations++import asyncio+from pathlib import Path+from types import SimpleNamespace++from fastapi import FastAPI++from jarvis.agent_chat.service import AgentChatService+from jarvis.agent_chat.store import AgentChatStore+from jarvis.society.chat_binding import make_deliver_hook+from jarvis.society.conversation import ConversationArchive+from jarvis.society.events import MsgType+from jarvis.society.roster import (+ canonical_session_id,+ conversation_session_id,+ pair_session_id,+)+from jarvis.society.runtime import SocietyRuntime+from jarvis.society.surface import agent_id_of, counterpart_of+++class TurnService:+ """The agent-chat surface the society drives, without a model behind it."""++ receive_message = AgentChatService.receive_message+ message_status = AgentChatService.message_status++ def __init__(self, store: AgentChatStore) -> None:+ self.store = store+ self.sent: list[tuple[str, str]] = []+ self.busy: set[str] = set()+ self.approvals: dict[str, list[str]] = {}+ self.queues: dict[str, list[asyncio.Queue]] = {}++ async def _emit(self, session_id, event):+ self.store.append_event(session_id, event)++ def is_running(self, session_id: str) -> bool:+ return session_id in self.busy++ def running_session_ids(self) -> list[str]:+ return sorted(self.busy)++ def pending_approvals(self, session_id: str) -> list[str]:+ return list(self.approvals.get(session_id, []))++ def subscribe(self, session_id: str) -> asyncio.Queue:+ q: asyncio.Queue = asyncio.Queue()+ self.queues.setdefault(session_id, []).append(q)+ return q++ def unsubscribe(self, session_id: str, q) -> None:+ self.queues.get(session_id, []).remove(q)++ async def send(self, session_id: str, text: str, attachments=None, **_: object) -> str:+ self.sent.append((session_id, text))+ return "turn-1"++ async def finish(self, session_id: str, text: str) -> None:+ for q in list(self.queues.get(session_id, [])):+ q.put_nowait({"kind": "assistant_text", "payload": {"turn_id": "turn-1", "text": text}})+ q.put_nowait(+ {"kind": "turn_finished", "payload": {"turn_id": "turn-1", "status": "ok"}}+ )+++def _runtime(tmp_path: Path, svc: TurnService) -> SocietyRuntime:+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))+ return SocietyRuntime(+ tmp_path, seed_starter_team=False, chat_service=lambda: svc, cfg=lambda: cfg+ )+++def test_session_ids_name_the_owner_and_the_counterpart():+ assert pair_session_id("scout", "jarvis") == "society:scout:with:jarvis"+ assert conversation_session_id("scout", "jarvis") == "society:scout:with:jarvis"+ assert conversation_session_id("scout", "nova") == "society:scout:with:nova"+ # The person always speaks in the agent's own chat.+ assert conversation_session_id("scout", "user") == canonical_session_id("scout")+ assert conversation_session_id("scout", "") == "society:scout"+ # Every chat of an agent resolves to that agent's identity (tools, memory, briefing).+ assert agent_id_of("society:scout:with:jarvis") == "scout"+ assert agent_id_of("society:scout:with:mail-bot") == "scout"+ assert agent_id_of("society:scout:routine:t1:r1") == "scout"+ assert agent_id_of("society:scout") == "scout"+ assert counterpart_of("society:scout:with:jarvis") == "jarvis"+ assert counterpart_of("society:scout") is None+++async def test_jarvis_assignment_runs_in_its_own_chat_not_the_persons(tmp_path: Path):+ svc = TurnService(AgentChatStore(tmp_path / "agent_chat.db"))+ rt = _runtime(tmp_path, svc)+ await rt.ensure_started()+ try:+ await rt.roster.create(name="Scout", provider="openai", model="gpt-5.2")+ env = await rt.say(+ from_agent="jarvis", to_agent="scout", text="Find a VPS.", msg_type=MsgType.ASSIGN+ )+ assert [sid for sid, _ in svc.sent] == ["society:scout:with:jarvis"]+ assert svc.store.get_session("society:scout") is None+ pair = svc.store.get_session("society:scout:with:jarvis")+ assert pair is not None and pair.surface == "society"+ assert pair.provider == "openai" and pair.model == "gpt-5.2"+ assert pair.title.startswith("Scout · ")++ await svc.finish("society:scout:with:jarvis", "Hetzner wins.")+ await asyncio.sleep(0.05)+ result = (await rt.store.events_for_trace(env.trace_id))[-1]+ assert result.msg_type is MsgType.RESULT+ assert result.payload["output"] == ["chat:society:scout:with:jarvis"]+ finally:+ await rt.close()+++async def test_the_persons_assignment_stays_in_the_agents_own_chat(tmp_path: Path):+ svc = TurnService(AgentChatStore(tmp_path / "agent_chat.db"))+ rt = _runtime(tmp_path, svc)+ await rt.ensure_started()+ try:+ await rt.roster.create(name="Scout", provider="openai")+ await rt.say(from_agent="user", to_agent="scout", text="x", msg_type=MsgType.ASSIGN)+ assert [sid for sid, _ in svc.sent] == ["society:scout"]+ finally:+ await rt.close()+++async def test_messages_wait_while_the_agent_works_in_any_chat(tmp_path: Path):+ svc = TurnService(AgentChatStore(tmp_path / "agent_chat.db"))+ rt = _runtime(tmp_path, svc)+ await rt.ensure_started()+ try:+ await rt.roster.create(name="Scout", provider="openai")+ await rt.roster.create(name="Nova", provider="openai")+ rt.set_deliver(make_deliver_hook(lambda: svc, rt.config))+ # Scout works in its conversation with Jarvis: Nova's message waits,+ # so two message turns never share Scout's seat and workspace.+ svc.busy.add("society:scout:with:jarvis")+ await rt.say(from_agent="nova", to_agent="scout", text="second")+ await rt.scheduler.drain_deliveries()+ assert svc.sent == []+ svc.busy.clear()+ await rt.scheduler.drain_deliveries()+ assert [sid for sid, _ in svc.sent] == ["society:scout:with:nova"]+ assert svc.store.get_session("society:scout") is None+ finally:+ await rt.close()+++async def test_the_person_can_step_into_a_conversation_and_apply_a_change(tmp_path: Path):+ from jarvis.core.chat_turn import ChatTurn, current_chat_turn+ from jarvis.society.agent_tools import ProposeChangeTool++ svc = TurnService(AgentChatStore(tmp_path / "agent_chat.db"))+ rt = _runtime(tmp_path, svc)+ await rt.ensure_started()+ try:+ await rt.roster.create(name="Scout", provider="openai")+ quote = "Always cite your sources"+ args = {"kind": "rule", "mode": "apply", "request_quote": quote, "payload": {"text": quote}}+ tool = ProposeChangeTool(rt, "scout", session_id="society:scout:with:jarvis")+ results = {}+ for direct in (True, False):+ token = current_chat_turn.set(+ ChatTurn("society:scout:with:jarvis", "turn-1", quote, direct, "trace")+ )+ try:+ results[direct] = await tool.execute(args, SimpleNamespace(config={}))+ finally:+ current_chat_turn.reset(token)+ # The person typed it in the conversation chat: it applies there too.+ assert results[True].success, results[True].error+ # A message from Jarvis is not the person's request.+ assert not results[False].success+ finally:+ await rt.close()+++def test_recall_searches_every_chat_the_agent_owns(tmp_path: Path):+ archive = ConversationArchive(tmp_path / "conversations.db")+ try:+ archive.ingest(+ "society:scout",+ [{"seq": 1, "kind": "user_message", "payload": {"text": "the person likes Hetzner"}}],+ )+ archive.ingest(+ "society:scout:with:jarvis",+ [{"seq": 1, "kind": "assistant_text", "payload": {"text": "Hetzner CX22 chosen"}}],+ )+ archive.ingest(+ "society:scout-two",+ [{"seq": 1, "kind": "assistant_text", "payload": {"text": "Hetzner elsewhere"}}],+ )+ own = archive.search("society:scout", "Hetzner", include_owned=True)+ assert sorted(hit["source"] for hit in own) == [+ "chat:society:scout#seq=1",+ "chat:society:scout:with:jarvis#seq=1",+ ]+ only = archive.search("society:scout", "Hetzner")+ assert [hit["source"] for hit in only] == ["chat:society:scout#seq=1"]+ finally:+ archive.close()+++def test_mcp_session_header_accepts_conversation_chats():+ from jarvis.ui.web.mcp_server_routes import session_ref++ def ref(value: str) -> str | None:+ return session_ref({"headers": [(b"x-jarvis-chat-session", value.encode())]})++ assert ref("society:scout:with:jarvis") == "society:scout:with:jarvis"+ assert ref("society:scout:with:mail-bot") == "society:scout:with:mail-bot"+ assert ref("society:scout:with:../x") is None+++async def test_conversations_route_lists_an_agents_chats(tmp_path: Path):+ import httpx++ from jarvis.ui.web import society_routes++ svc = TurnService(AgentChatStore(tmp_path / "agent_chat.db"))+ rt = _runtime(tmp_path, svc)+ await rt.ensure_started()+ try:+ await rt.roster.create(name="Scout", provider="openai")+ await rt.roster.create(name="Nova", provider="openai")+ rt.set_deliver(make_deliver_hook(lambda: svc, rt.config))+ for sender, target in (("jarvis", "scout"), ("nova", "scout"), ("jarvis", "nova")):+ await rt.say(from_agent=sender, to_agent=target, text="hi")+ svc.approvals["society:scout:with:nova"] = ["approval-1"]+ app = FastAPI()+ app.include_router(society_routes.router)+ app.state.society = rt+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:+ scout = (await client.get("/api/society/agents/scout/conversations")).json()+ lead = (await client.get("/api/society/agents/jarvis/conversations")).json()+ finally:+ await rt.close()+ assert sorted(row["session_id"] for row in scout["conversations"]) == [+ "society:scout:with:jarvis",+ "society:scout:with:nova",+ ]+ assert {row["counterpart_id"] for row in scout["conversations"]} == {"jarvis", "nova"}+ # An approval card waiting in a conversation shows on its chip.+ waiting = {row["counterpart_id"]: row["waiting"] for row in scout["conversations"]}+ assert waiting == {"jarvis": False, "nova": True}+ # Jarvis' card lists every agent's chat with Jarvis, named by that agent.+ assert sorted(row["session_id"] for row in lead["conversations"]) == [+ "society:nova:with:jarvis",+ "society:scout:with:jarvis",+ ]+ assert {row["counterpart_name"] for row in lead["conversations"]} == {"Scout", "Nova"}+++async def test_a_message_records_the_chat_it_was_written_in(tmp_path: Path):+ from jarvis.core.chat_turn import ChatTurn, current_chat_turn+ from jarvis.society.agent_tools import MessageAgentTool++ svc = TurnService(AgentChatStore(tmp_path / "agent_chat.db"))+ rt = _runtime(tmp_path, svc)+ await rt.ensure_started()+ try:+ await rt.roster.create(name="Scout", provider="openai")+ await rt.roster.create(name="Nova", provider="openai")+ token = current_chat_turn.set(+ ChatTurn("society:scout:with:jarvis", "turn-1", "", False, "trace")+ )+ try:+ result = await MessageAgentTool(rt, "scout").execute(+ {"target": "nova", "text": "FYI: the VPS is chosen.", "kind": "say"},+ SimpleNamespace(config={}),+ )+ finally:+ current_chat_turn.reset(token)+ assert result.success, result.error+ sent = await rt.store.get_event(result.output["message_id"])+ # The person's chat with Scout uses this to leave the reply where it was written.+ assert sent.payload["from_session"] == "society:scout:with:jarvis"+ finally:+ await rt.close()