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(voice): continue the open chat when a voice call starts

rubenluetke10-beep15f69df6f5fd
diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.py
index 53203459f8..5c0a00a1c1 100644
--- a/jarvis/agent_chat/service.py
+++ b/jarvis/agent_chat/service.py
@@ -50,7 +50,7 @@ from jarvis.agent_chat.questions import (
recommended_answer,
)
from jarvis.agent_chat.runner_api import TurnHandle, run_api_turn, supports_api_runner
-from jarvis.agent_chat.runner_brain import run_brain_turn
+from jarvis.agent_chat.runner_brain import brain_history_from_events, run_brain_turn
from jarvis.agent_chat.runner_cli import run_cli_turn, supports_cli_runner
from jarvis.agent_chat.store import (
DEFAULT_SURFACE,
@@ -250,6 +250,14 @@ class AgentChatService:
# reconnects, and a second copy in the chat would read as if the
# person said everything twice. Bounded below in import_voice_turn.
self._mirrored_voice_turns: set[str] = set()
+ # The Jarvis chat a voice call continues (bind_voice_chat): the chat
+ # the front page shows. ``_voice_chat_fresh`` = a blank page is open,
+ # so the next call starts a new chat instead of joining the newest.
+ # ``_voice_call_chats`` pins each running call to the chat its first
+ # turn landed in, so opening another chat mid-call never splits it.
+ self._voice_chat_id: str | None = None
+ self._voice_chat_fresh = False
+ self._voice_call_chats: dict[str, str] = {}
self._retire_cli_seats()
def _retire_cli_seats(self) -> None:
@@ -890,6 +898,68 @@ class AgentChatService:
run.task = asyncio.create_task(_body(), name=f"agent-chat-{turn_id[:8]}")
return turn_id
+ # ------------------------------------------------------------ voice chat
+
+ @property
+ def voice_chat_id(self) -> str | None:
+ """The Jarvis chat the next voice call continues, if one is bound."""
+ return self._voice_chat_id
+
+ @property
+ def voice_chat_fresh(self) -> bool:
+ """True while a blank page is open: the next call opens a new chat."""
+ return self._voice_chat_fresh
+
+ def bind_voice_chat(self, session_id: str | None) -> str | None:
+ """Make ``session_id`` the chat voice calls continue; ``None`` = a new one.
+
+ The front page shows one Jarvis chat at a time. A call started there
+ — the composer's voice button or the wake word — belongs to THAT
+ chat: its turns are filed into it (voice_mirror) and it starts with
+ that chat's history as context (``BrainManager.take_voice_history_seed``
+ asks :meth:`voice_chat_history`). Binding a chat also drops an older
+ explicit seed nobody consumed, which would otherwise hand the call
+ another conversation's memory.
+ """
+ from jarvis.agent_chat import runner_brain
+
+ brain = runner_brain.brain_manager()
+ if session_id is None:
+ self._voice_chat_id = None
+ self._voice_chat_fresh = True
+ else:
+ session = self.store.get_session(session_id)
+ if session is None or session.surface != "jarvis":
+ raise NoSuchSession(session_id)
+ self._voice_chat_id = session_id
+ self._voice_chat_fresh = False
+ drop = getattr(brain, "drop_voice_history_seed", None)
+ if callable(drop):
+ drop()
+ attach = getattr(brain, "set_voice_history_source", None)
+ if callable(attach):
+ attach(self.voice_chat_history)
+ return self._voice_chat_id
+
+ def voice_chat_history(self) -> list[Any]:
+ """The bound chat's turns as call context — empty when none is bound."""
+ session_id = self._voice_chat_id
+ if not session_id or self.store.get_session(session_id) is None:
+ return []
+ return brain_history_from_events(self.store.list_events(session_id))
+
+ def voice_call_chat(self, call_id: str) -> str | None:
+ """The chat a running call already files into, if its first turn landed."""
+ return self._voice_call_chats.get(call_id) if call_id else None
+
+ def pin_voice_call(self, call_id: str, session_id: str) -> None:
+ """Keep every later turn of ``call_id`` in ``session_id``."""
+ if not call_id:
+ return
+ if len(self._voice_call_chats) > 200:
+ self._voice_call_chats.clear()
+ self._voice_call_chats[call_id] = session_id
+
async def import_voice_turn(
self,
session_id: str,
diff --git a/jarvis/agent_chat/voice_mirror.py b/jarvis/agent_chat/voice_mirror.py
index 27b8f53731..026336328e 100644
--- a/jarvis/agent_chat/voice_mirror.py
+++ b/jarvis/agent_chat/voice_mirror.py
@@ -11,9 +11,11 @@ This bridge closes that gap at the turn boundary, off the voice hot path
(AP-9): it subscribes to :class:`VoiceTurnCompleted` on the app bus and files
each turn's two texts into the newest ``jarvis``-surface chat session via
:meth:`AgentChatService.import_voice_turn` — no runner starts, nothing
-re-answers, and a session that is busy typing keeps running. The imported
-turn also becomes context for the next typed turn, because the API runner
-rebuilds its history from the same event log.
+re-answers, and a session that is busy typing keeps running. When the front
+page bound a chat (``AgentChatService.bind_voice_chat``) the turn goes there
+instead, and every turn of one call stays in the chat its first turn chose.
+The imported turn also becomes context for the next typed turn, because the
+API runner rebuilds its history from the same event log.
Only the lead's chat (surface ``jarvis``) is mirrored: the other society
agents have no microphone.
@@ -62,11 +64,19 @@ class VoiceChatMirror:
svc = self._get_service()
if svc is None:
return
- session = self._target_session(svc)
+ call_id = str(getattr(event, "session_id", "") or "")
+ session = self._target_session(svc, call_id)
if session is None:
session = self._ensure_session(svc, event)
if session is None:
return
+ if getattr(svc, "voice_chat_fresh", False):
+ # The blank page's call now has its chat; the next call
+ # from that page continues it instead of opening another.
+ svc.bind_voice_chat(session.session_id)
+ pin = getattr(svc, "pin_voice_call", None)
+ if callable(pin):
+ pin(call_id, session.session_id)
await svc.import_voice_turn(
session.session_id,
user_text,
@@ -79,9 +89,26 @@ class VoiceChatMirror:
log.debug("voice chat mirror skipped a turn: %s", exc)
@staticmethod
- def _target_session(svc: Any) -> Any | None:
- """The newest Jarvis-surface session — the chat the card shows."""
+ def _target_session(svc: Any, call_id: str = "") -> Any | None:
+ """The chat this turn belongs in.
+
+ In order: the chat this call already files into, the chat the front
+ page bound (``AgentChatService.bind_voice_chat``), and — when nothing
+ was ever bound — the newest Jarvis chat. ``None`` asks for a new chat:
+ a blank page is open, or there is no chat yet.
+ """
try:
+ for chat_id in (
+ getattr(svc, "voice_call_chat", lambda _c: None)(call_id),
+ getattr(svc, "voice_chat_id", None),
+ ):
+ if not chat_id:
+ continue
+ session = svc.store.get_session(chat_id)
+ if session is not None and session.surface == SURFACE:
+ return session
+ if getattr(svc, "voice_chat_fresh", False):
+ return None
sessions = svc.store.list_sessions(limit=1, surface=SURFACE)
except Exception as exc: # noqa: BLE001
log.debug("voice chat mirror could not list sessions: %s", exc)
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index 44f26a203c..aaa4aa5d95 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -13106,6 +13106,13 @@ class BrainManager:
to :attr:`_HISTORY_MAX`, keeping the most recent turns — an empty
input therefore behaves like :meth:`clear_history`.
"""
+ self._history = self._seedable(turns)
+ # Explicit archive selection also seeds the next duplex call. Ordinary
+ # generated turns never fill this slot: unrelated calls must stay fresh.
+ self._voice_history_seed = tuple(self._history)
+
+ def _seedable(self, turns: Iterable[Any]) -> list[BrainMessage]:
+ """``turns`` reduced to seedable messages, newest :attr:`_HISTORY_MAX` kept."""
seeded: list[BrainMessage] = []
for item in turns:
if isinstance(item, BrainMessage):
@@ -13131,19 +13138,45 @@ class BrainManager:
if isinstance(item, BrainMessage)
else BrainMessage(role=role, content=content)
)
- self._history = seeded[-self._HISTORY_MAX :]
- # Explicit archive selection also seeds the next duplex call. Ordinary
- # generated turns never fill this slot: unrelated calls must stay fresh.
- self._voice_history_seed = tuple(self._history)
+ return seeded[-self._HISTORY_MAX :]
+
+ def set_voice_history_source(self, source: Callable[[], Iterable[Any]] | None) -> None:
+ """Where a call without an explicit seed gets its starting history.
+
+ The front page's chat binds the chat a call continues
+ (``AgentChatService.bind_voice_chat``); the source answers with that
+ chat's turns at call start, so a second call in the same chat still
+ knows the first one. ``None`` returns to fresh calls.
+ """
+ if source is None:
+ self.__dict__.pop("_voice_history_source", None)
+ else:
+ self._voice_history_source = source
+
+ def drop_voice_history_seed(self) -> None:
+ """Forget an explicit seed nobody consumed, so the source answers instead."""
+ self.__dict__.pop("_voice_history_seed", None)
def take_voice_history_seed(self) -> tuple[BrainMessage, ...]:
"""Consume an explicit resume once, retaining the text brain's history.
A single dict pop transfers ownership even when desktop session setup
runs on a worker thread. Reconnects reuse the receiving call's copy.
+ Without an explicit seed the bound chat's history answers
+ (:meth:`set_voice_history_source`); an explicit empty seed — "new
+ voice chat" — still wins and starts the call fresh.
"""
- history: tuple[BrainMessage, ...] = self.__dict__.pop("_voice_history_seed", ())
- return history
+ if "_voice_history_seed" in self.__dict__:
+ history: tuple[BrainMessage, ...] = self.__dict__.pop("_voice_history_seed", ())
+ return history
+ source = self.__dict__.get("_voice_history_source")
+ if source is None:
+ return ()
+ try:
+ return tuple(self._seedable(source()))
+ except Exception: # noqa: BLE001 — a call without history beats no call
+ log.warning("voice history source failed; the call starts fresh", exc_info=True)
+ return ()
# ------------------------------------------------------------------
# Live reload for the CLI tool registry (CLI integration, task 2)
diff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.py
index f649d86e25..7d2d2835b8 100644
--- a/jarvis/ui/web/agent_chat_routes.py
+++ b/jarvis/ui/web/agent_chat_routes.py
@@ -92,6 +92,36 @@ HIDDEN_SURFACES: frozenset[str] = frozenset({"society"})
router = APIRouter(prefix="/api/agent-chat", tags=["agent-chat"])
+class VoiceChatBody(BaseModel):
+ #: The Jarvis chat on stage; ``None`` = a blank page (the next call opens a new chat).
+ session_id: str | None = None
+
+
+class VoiceChatResponse(BaseModel):
+ session_id: str | None
+ fresh: bool
+
+
+def _voice_chat_answer(svc: AgentChatService) -> VoiceChatResponse:
+ return VoiceChatResponse(session_id=svc.voice_chat_id, fresh=svc.voice_chat_fresh)
+
+
[email protected]("/voice-chat", summary="The Jarvis chat voice calls continue")
+async def get_voice_chat(request: Request) -> VoiceChatResponse:
+ return _voice_chat_answer(_service(request))
+
+
[email protected]("/voice-chat", summary="Continue voice calls in this Jarvis chat")
+async def put_voice_chat(body: VoiceChatBody, request: Request) -> VoiceChatResponse:
+ """Bind the chat the front page shows: calls file into it and start with its history."""
+ svc = _service(request)
+ try:
+ svc.bind_voice_chat(body.session_id or None)
+ except NoSuchSession as exc:
+ raise HTTPException(status_code=404, detail="no-such-jarvis-chat") from exc
+ return _voice_chat_answer(svc)
+
+
@router.get("/commands", summary="List chat slash commands and their availability")
def list_chat_commands(request: Request, session_id: str | None = None) -> dict[str, Any]:
try:
diff --git a/jarvis/ui/web/chats_routes.py b/jarvis/ui/web/chats_routes.py
index 5e92d96a66..4c3e7375a1 100644
--- a/jarvis/ui/web/chats_routes.py
+++ b/jarvis/ui/web/chats_routes.py
@@ -413,6 +413,17 @@ async def new_voice_run(request: Request) -> NewVoiceRunResponse:
brain.seed_history([])
cleared = True
+ # A fresh run is a fresh chat too: its turns must not land in the chat the
+ # previous call continued, or the new run would read as part of it.
+ try:
+ from .agent_chat_routes import _service_from_state
+
+ chat = _service_from_state(request.app.state)
+ if chat is not None:
+ chat.bind_voice_chat(None)
+ except Exception as exc: # noqa: BLE001 — the reset itself already happened
+ log.warning("new voice run could not unbind the voice chat: %s", exc)
+
ended = False
pipeline = _optional_pipeline(request)
if pipeline is not None and hasattr(pipeline, "request_voice_hangup"):
diff --git a/jarvis/ui/web/frontend/src/components/home/AssistantChat.tsx b/jarvis/ui/web/frontend/src/components/home/AssistantChat.tsx
index 0ce5e61bbb..ef88aa06f2 100644
--- a/jarvis/ui/web/frontend/src/components/home/AssistantChat.tsx
+++ b/jarvis/ui/web/frontend/src/components/home/AssistantChat.tsx
@@ -1,8 +1,9 @@
-import { lazy, Suspense } from "react";
+import { lazy, Suspense, useEffect } from "react";
import { VoiceStage } from "@/components/home/VoiceStage";
-import { useVoiceModeSwitch } from "@/components/home/assistantStatus";
+import { transcriptFromTimeline, useVoiceModeSwitch } from "@/components/home/assistantStatus";
import { useT } from "@/i18n";
+import { useAgentChatStore } from "@/store/agentChat";
import { useHomeStore } from "@/store/home";
const ChatStage = lazy(() =>
@@ -27,6 +28,16 @@ export function AssistantChat() {
const surface = useHomeStore((s) => s.surface);
const agentChatId = useHomeStore((s) => s.agentChatId);
const voice = useVoiceModeSwitch();
+ const chatItems = useAgentChatStore((s) => s.timeline.items);
+ const seedTranscript = useHomeStore((s) => s.seedTranscript);
+ const inVoice = surface === "voice" && !agentChatId;
+ // Between calls the voice lane IS the chat on stage. A hangup clears the
+ // lane (store/home.ts); the turns just spoken arrive in the chat a moment
+ // later (the backend files them there), so the lane follows the chat.
+ useEffect(() => {
+ if (!inVoice || voice.live) return;
+ seedTranscript(transcriptFromTimeline(chatItems));
+ }, [chatItems, inVoice, seedTranscript, voice.live]);
const loading = (
<div role="status" className="flex min-h-0 flex-1 items-center justify-center text-sm text-muted-foreground">
{t("common.loading")}
diff --git a/jarvis/ui/web/frontend/src/components/home/assistantStatus.ts b/jarvis/ui/web/frontend/src/components/home/assistantStatus.ts
index 0fec6fc7e7..f37b7e5ccb 100644
--- a/jarvis/ui/web/frontend/src/components/home/assistantStatus.ts
+++ b/jarvis/ui/web/frontend/src/components/home/assistantStatus.ts
@@ -1,10 +1,33 @@
import { useCallback } from "react";
import { useVoiceCall } from "@/components/agentic/useVoiceCall";
+import type { TimelineItem } from "@/components/agentchat/reduce";
import { useVoiceReadiness } from "@/hooks/useVoiceReadiness";
+import { bindVoiceChat, fetchVoiceChat } from "@/lib/agentChatApi";
+import { transcriptFromMessages, type TranscriptLine } from "@/lib/homeTranscript";
+import { useAgentChatStore } from "@/store/agentChat";
import { useEventStore } from "@/store/events";
import { useHomeStore } from "@/store/home";
+/**
+ * The chat on stage as the voice lane's lines: what was typed or said, and
+ * the answers' prose. Tool rows, notices and errors stay in the chat view.
+ */
+export function transcriptFromTimeline(items: readonly TimelineItem[]): TranscriptLine[] {
+ const messages: { role: string; content: string; ts: number }[] = [];
+ for (const item of items) {
+ if (item.type === "user") {
+ messages.push({ role: "user", content: item.text, ts: item.tsMs });
+ } else if (item.type === "turn") {
+ const text = item.blocks
+ .flatMap((block) => (block.kind === "text" ? [block.text] : []))
+ .join("\n");
+ messages.push({ role: "assistant", content: text, ts: item.startedMs });
+ }
+ }
+ return transcriptFromMessages(messages);
+}
+
/**
* Entering and leaving the front-page chat's voice mode — the ONE path the
* composer's round voice button and voice mode's "Back to typing" use.
@@ -13,6 +36,12 @@ import { useHomeStore } from "@/store/home";
* same start/stop request the Jarvis bar uses (useVoiceCall), so there is
* still exactly one way a call begins. Leaving ends a running call: "back to
* typing" with the microphone still open would be a hidden live mic.
+ *
+ * Voice mode continues the chat on stage. Before the call starts, the chat
+ * is bound on the backend (`bindVoiceChat`): the call starts with its
+ * history and its turns are filed into it. The lane opens with that chat's
+ * lines, so talking reads as the next message, not as a new conversation.
+ * A call from a blank page gets its own new chat; leaving voice mode opens it.
*/
export function useVoiceModeSwitch() {
const surface = useHomeStore((s) => s.surface);
@@ -23,14 +52,38 @@ export function useVoiceModeSwitch() {
const on = surface === "voice";
const enter = useCallback(() => {
+ const chat = useAgentChatStore.getState();
+ const startsCall = !active && !busy && !connecting && connected;
+ // A call already running elsewhere keeps its own lane.
+ if (!active && !connecting) {
+ useHomeStore.getState().seedTranscript(transcriptFromTimeline(chat.timeline.items));
+ }
setSurface("voice");
setActiveSection("chats");
- if (!active && !busy && !connecting && connected) void toggleCall();
+ if (!startsCall) return;
+ void bindVoiceChat(chat.activeSessionId)
+ .catch((err: unknown) => {
+ // The call still starts; it just falls back to the newest chat.
+ console.info("Voice chat binding failed.", err);
+ })
+ .finally(() => void toggleCall());
}, [active, busy, connected, connecting, setActiveSection, setSurface, toggleCall]);
const exit = useCallback(() => {
if (active && !busy) void toggleCall();
setSurface("chat");
+ if (useAgentChatStore.getState().activeSessionId) return;
+ // A call from a blank page opened its chat on the backend: show it.
+ void fetchVoiceChat()
+ .then(({ session_id: sessionId }) => {
+ const chat = useAgentChatStore.getState();
+ if (!sessionId || chat.activeSessionId) return;
+ chat.openSession(sessionId);
+ void chat.loadSessions();
+ })
+ .catch((err: unknown) => {
+ console.info("Voice chat lookup failed.", err);
+ });
}, [active, busy, setSurface, toggleCall]);
return { on, live: active || connecting, busy, enter, exit, toggle: on ? exit : enter };
diff --git a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
index 4703f1e3f5..225851c83c 100644
--- a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
@@ -68,6 +68,31 @@ export interface AgentChatCatalog {
shell: string;
}
+/** The Jarvis chat voice calls continue (`/api/agent-chat/voice-chat`). */
+export interface VoiceChatBinding {
+ /** Null while a blank page is open or nothing was bound yet. */
+ session_id: string | null;
+ /** A blank page is open: the next call opens a new chat. */
+ fresh: boolean;
+}
+
+/**
+ * Make `sessionId` the chat voice calls continue — its turns are filed into
+ * it and a call starts with its history. `null` = a blank page: the next
+ * call opens a new chat.
+ */
+export async function bindVoiceChat(sessionId: string | null): Promise<VoiceChatBinding> {
+ return json(await fetch("/api/agent-chat/voice-chat", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ session_id: sessionId }),
+ }), "voice-chat-bind-failed");
+}
+
+export async function fetchVoiceChat(): Promise<VoiceChatBinding> {
+ return json(await fetch("/api/agent-chat/voice-chat", { cache: "no-store" }), "voice-chat-failed");
+}
+
/**
* Where a session lives: the front page's typed chat (`jarvis` — the same
* assistant as the microphone, on a keyboard) or a coding session listed by
diff --git a/jarvis/ui/web/frontend/src/store/agentChat.ts b/jarvis/ui/web/frontend/src/store/agentChat.ts
index 64c788b786..0108803c28 100644
--- a/jarvis/ui/web/frontend/src/store/agentChat.ts
+++ b/jarvis/ui/web/frontend/src/store/agentChat.ts
@@ -14,6 +14,7 @@ import {
patchAgentChatSession,
resolveAgentChatApproval,
answerAgentChatQuestion,
+ bindVoiceChat,
skipAgentChatQuestion,
type QuestionAnswerInput,
sendAgentChatMessage,
@@ -278,6 +279,20 @@ const TIMELINE_CACHE_LIMIT = 24;
export function createAgentChatStore(surface: AgentChatSurface, draftNamespace = "") {
const DRAFT_KEY = draftKey(surface) + (draftNamespace ? `:${draftNamespace}` : "");
+ /**
+ * Tell the backend which Jarvis chat is on stage, so a voice call continues
+ * THIS chat — its turns land here and it starts with this chat's history.
+ * `null` = a blank page: the next call opens a new chat. Only the front
+ * page's chat has a voice; the other surfaces never bind.
+ */
+ const bindVoice = (sessionId: string | null) => {
+ if (surface !== "jarvis") return;
+ void bindVoiceChat(sessionId).catch((err: unknown) => {
+ // Not fatal: the composer's voice button binds again before a call.
+ console.info("Voice chat binding failed.", err);
+ });
+ };
+
let catalogRequest = 0;
let socket: WebSocket | null = null;
let socketSession: string | null = null;
@@ -610,6 +625,7 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =
lastError: null,
catalog: null,
});
+ bindVoice(null);
void get().loadCatalog();
},
@@ -626,6 +642,7 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =
busy: false,
lastError: null,
});
+ bindVoice(sessionId);
void get().loadCatalog();
connect(sessionId, 0);
},
@@ -668,6 +685,7 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =
timeline: EMPTY_TIMELINE,
sessions: [session, ...get().sessions],
});
+ bindVoice(sid);
connect(sid, 0);
}
await sendAgentChatMessage(sid, content, attachments, toolChoices);
diff --git a/tests/unit/agent_chat/test_voice_mirror.py b/tests/unit/agent_chat/test_voice_mirror.py
index c3eb1d352c..2e8b4ae4ca 100644
--- a/tests/unit/agent_chat/test_voice_mirror.py
+++ b/tests/unit/agent_chat/test_voice_mirror.py
@@ -136,3 +136,95 @@ def test_mirror_creates_first_session_when_none_open(tmp_path: Path) -> None:
assert stored[0]["payload"]["text"] == "first words ever"
asyncio.run(scenario())
+
+
+def _turn(call: str, turn: str, user: str, reply: str) -> VoiceTurnCompleted:
+ return VoiceTurnCompleted(
+ session_id=call, turn_id=turn, user_text=user, jarvis_text=reply, provider="openai"
+ )
+
+
+def test_mirror_files_into_the_bound_chat_not_the_newest(tmp_path: Path) -> None:
+ async def scenario() -> None:
+ svc = _service(tmp_path)
+ a = _open_session(svc)
+ b = _open_session(svc)
+ newest = svc.store.list_sessions(limit=1, surface="jarvis")[0]
+ older = a if newest.session_id == b.session_id else b
+ svc.bind_voice_chat(older.session_id)
+ bus = EventBus()
+ VoiceChatMirror(lambda: svc).attach(bus)
+ await bus.publish(_turn("call-1", "t1", "continue here", "continuing"))
+ assert len(svc.store.list_events(older.session_id)) == 4
+ assert svc.store.list_events(newest.session_id) == []
+
+ asyncio.run(scenario())
+
+
+def test_one_call_stays_in_one_chat_when_another_is_opened(tmp_path: Path) -> None:
+ async def scenario() -> None:
+ svc = _service(tmp_path)
+ first = _open_session(svc)
+ second = _open_session(svc)
+ svc.bind_voice_chat(first.session_id)
+ bus = EventBus()
+ VoiceChatMirror(lambda: svc).attach(bus)
+ await bus.publish(_turn("call-1", "t1", "one", "uno"))
+ svc.bind_voice_chat(second.session_id)
+ await bus.publish(_turn("call-1", "t2", "two", "dos"))
+ assert len(svc.store.list_events(first.session_id)) == 8
+ assert svc.store.list_events(second.session_id) == []
+ # The NEXT call follows the new binding.
+ await bus.publish(_turn("call-2", "t3", "three", "tres"))
+ assert len(svc.store.list_events(second.session_id)) == 4
+
+ asyncio.run(scenario())
+
+
+def test_blank_page_call_opens_a_new_chat_and_keeps_it(tmp_path: Path) -> None:
+ async def scenario() -> None:
+ svc = _service(tmp_path)
+ old = _open_session(svc)
+ svc.bind_voice_chat(None)
+ bus = EventBus()
+ VoiceChatMirror(lambda: svc).attach(bus)
+ await bus.publish(_turn("call-1", "t1", "fresh start", "fresh answer"))
+ assert svc.store.list_events(old.session_id) == []
+ created = svc.voice_chat_id
+ assert created and created != old.session_id
+ assert not svc.voice_chat_fresh
+ # A second call from the same page continues the chat the first opened.
+ await bus.publish(_turn("call-2", "t2", "again", "again answer"))
+ assert len(svc.store.list_events(created)) == 8
+ assert len(svc.store.list_sessions(limit=10, surface="jarvis")) == 2
+
+ asyncio.run(scenario())
+
+
+def test_voice_chat_history_is_the_bound_chats_prose(tmp_path: Path) -> None:
+ async def scenario() -> None:
+ svc = _service(tmp_path)
+ session = _open_session(svc)
+ assert svc.voice_chat_history() == []
+ await svc.import_voice_turn(session.session_id, "my question", "my answer")
+ svc.bind_voice_chat(session.session_id)
+ history = svc.voice_chat_history()
+ assert [(m.role, m.content) for m in history] == [
+ ("user", "my question"),
+ ("assistant", "my answer"),
+ ]
+
+ asyncio.run(scenario())
+
+
+def test_binding_rejects_unknown_and_foreign_surface_chats(tmp_path: Path) -> None:
+ import pytest
+
+ from jarvis.agent_chat.service import NoSuchSession
+
+ svc = _service(tmp_path)
+ coding = svc.create_session(provider="openai", model="m", effort="low", surface="agent")
+ with pytest.raises(NoSuchSession):
+ svc.bind_voice_chat("missing")
+ with pytest.raises(NoSuchSession):
+ svc.bind_voice_chat(coding.session_id)
diff --git a/tests/unit/realtime/test_archive_resume.py b/tests/unit/realtime/test_archive_resume.py
index 54a7ce03c8..93a3d2a643 100644
--- a/tests/unit/realtime/test_archive_resume.py
+++ b/tests/unit/realtime/test_archive_resume.py
@@ -114,3 +114,34 @@ def test_desktop_speak_seed_reaches_shared_brain() -> None:
("user", "Resume this exact conversation")
]
assert facade.take_voice_history_seed() == ()
+
+
+def test_bound_chat_answers_every_call_without_an_explicit_seed() -> None:
+ brain = BrainManager(config=JarvisConfig(), bus=EventBus(), tools={})
+ chat: list[tuple[str, str]] = [("user", "first call"), ("assistant", "first answer")]
+ brain.set_voice_history_source(lambda: list(chat))
+ assert [(m.role, m.content) for m in brain.take_voice_history_seed()] == chat
+ # The second call in the same chat sees what the first one added.
+ chat.append(("user", "second call"))
+ assert len(brain.take_voice_history_seed()) == 3
+ # An explicit seed (an archive resume, or "new voice chat") still wins once.
+ brain.seed_history([])
+ assert brain.take_voice_history_seed() == ()
+ brain.seed_history([("user", "archived")])
+ assert [m.content for m in brain.take_voice_history_seed()] == ["archived"]
+ # Binding a chat drops a seed nobody consumed.
+ brain.seed_history([("user", "stale archive")])
+ brain.drop_voice_history_seed()
+ assert len(brain.take_voice_history_seed()) == 3
+ brain.set_voice_history_source(None)
+ assert brain.take_voice_history_seed() == ()
+
+
+def test_failing_history_source_starts_the_call_fresh() -> None:
+ brain = BrainManager(config=JarvisConfig(), bus=EventBus(), tools={})
+
+ def broken() -> list[tuple[str, str]]:
+ raise RuntimeError("store gone")
+
+ brain.set_voice_history_source(broken)
+ assert brain.take_voice_history_seed() == ()