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 a reopened voice chat in its own history row

rubenluetke10-beepb1106bdde98c
diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.py
index 583e960481..3e6fba7109 100644
--- a/jarvis/agent_chat/service.py
+++ b/jarvis/agent_chat/service.py
@@ -258,6 +258,8 @@ class AgentChatService:
self._voice_chat_id: str | None = None
self._voice_chat_fresh = False
self._voice_call_chats: dict[str, str] = {}
+ # The archived voice chat's history while one is continued (bind_voice_chat).
+ self._voice_archive_history: Callable[[], list[Any]] | None = None
self._retire_cli_seats()
def _retire_cli_seats(self) -> None:
@@ -914,9 +916,28 @@ class AgentChatService:
"""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:
+ @property
+ def voice_session_continued(self) -> str | None:
+ """The archived voice chat calls are recorded into, if one is on stage."""
+ from jarvis.sessions.continuation import continued_voice_session
+
+ return continued_voice_session()
+
+ def bind_voice_chat(
+ self,
+ session_id: str | None,
+ *,
+ voice_session: str | None = None,
+ voice_history: Callable[[], list[Any]] | None = None,
+ ) -> str | None:
"""Make ``session_id`` the chat voice calls continue; ``None`` = a new one.
+ ``voice_session`` puts an ARCHIVED voice chat on stage instead (a
+ history row of ``sessions.db``): the recorder files the next calls
+ into that row rather than a new one (jarvis/sessions/continuation.py),
+ no typed chat receives the turns, and ``voice_history`` answers each
+ call's starting context. Any other binding ends that continuation.
+
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
@@ -926,8 +947,12 @@ class AgentChatService:
another conversation's memory.
"""
from jarvis.agent_chat import runner_brain
+ from jarvis.sessions.continuation import continue_voice_session
brain = runner_brain.brain_manager()
+ archived = (voice_session or "").strip() or None
+ continue_voice_session(archived if session_id is None else None)
+ self._voice_archive_history = voice_history if archived and session_id is None else None
if session_id is None:
self._voice_chat_id = None
self._voice_chat_fresh = True
@@ -947,6 +972,9 @@ class AgentChatService:
def voice_chat_history(self) -> list[Any]:
"""The bound chat's turns as call context — empty when none is bound."""
+ archive = self._voice_archive_history
+ if archive is not None and self.voice_session_continued:
+ return archive()
session_id = self._voice_chat_id
if not session_id or self.store.get_session(session_id) is None:
return []
diff --git a/jarvis/agent_chat/voice_mirror.py b/jarvis/agent_chat/voice_mirror.py
index 3398e7ec77..324674b0e9 100644
--- a/jarvis/agent_chat/voice_mirror.py
+++ b/jarvis/agent_chat/voice_mirror.py
@@ -64,6 +64,10 @@ class VoiceChatMirror:
svc = self._get_service()
if svc is None:
return
+ if getattr(svc, "voice_session_continued", None):
+ # An archived voice chat is on stage: the recorder files this
+ # turn into that row, and a typed copy would be a second chat.
+ return
call_id = str(getattr(event, "session_id", "") or "")
session = self._target_session(svc, call_id)
if session is None:
diff --git a/jarvis/sessions/continuation.py b/jarvis/sessions/continuation.py
new file mode 100644
index 0000000000..f09417c8f7
--- /dev/null
+++ b/jarvis/sessions/continuation.py
@@ -0,0 +1,41 @@
+"""Which archived voice session the next call continues.
+
+Every call used to open its own ``voice_sessions`` row. Reopening an old voice
+chat from the history and talking on therefore spawned a second row ("Voice
+chat · 16:59") beside the one the person had opened. When the front page
+continues an archived voice chat (``PUT /api/agent-chat/voice-chat`` with a
+``voice_session_id``), the recorder files the next calls into that row
+instead (``SessionRecorder._on_session_started``) until another chat is put
+on stage.
+
+Process-local and in memory: a restart forgets it, and the next call simply
+records a new session again.
+"""
+
+from __future__ import annotations
+
+import threading
+
+#: Prefix of a caption segment id recorded inside a continued row:
+#: ``call:<call id>:<segment id>``. Each call's audio clock restarts at zero,
+#: so the transcript replay orders calls by this before the clock.
+CALL_SEGMENT_PREFIX = "call:"
+
+_lock = threading.Lock()
+_target: str | None = None
+
+
+def continue_voice_session(session_id: str | None) -> None:
+ """Record the next calls into ``session_id``; ``None`` = a new row per call."""
+ global _target
+ with _lock:
+ _target = (session_id or "").strip() or None
+
+
+def continued_voice_session() -> str | None:
+ """The archived voice session the next call continues, if any."""
+ with _lock:
+ return _target
+
+
+__all__ = ["CALL_SEGMENT_PREFIX", "continue_voice_session", "continued_voice_session"]
diff --git a/jarvis/sessions/recorder.py b/jarvis/sessions/recorder.py
index f5144bfabc..b908f1f368 100644
--- a/jarvis/sessions/recorder.py
+++ b/jarvis/sessions/recorder.py
@@ -74,6 +74,7 @@ from .constants import (
VOICE_MODE_PIPELINE,
VOICE_MODE_REALTIME,
)
+from .continuation import CALL_SEGMENT_PREFIX, continued_voice_session
from .store import SessionStore
log = logging.getLogger(__name__)
@@ -220,6 +221,11 @@ class _SessionState:
session_id: str
started_ms: int
language: str
+ # The ``voice_sessions`` row this call is filed under. Empty = its own row
+ # (``session_id``); set when the call continues an archived voice chat
+ # (jarvis/sessions/continuation.py). ``session_id`` stays the CALL's id,
+ # which is what every live event carries and is matched against.
+ store_id: str = ""
turn_count: int = 0
total_cost_usd: float = 0.0
total_tokens_in: int = 0
@@ -246,6 +252,11 @@ class _SessionState:
# being dropped or stamped onto the wrong turn (BUG-090).
last_final_turn: _TurnState | None = None
+ @property
+ def record_id(self) -> str:
+ """The stored session every row of this call is written to."""
+ return self.store_id or self.session_id
+
class SessionRecorder:
"""EventBus wildcard subscriber, persists voice sessions."""
@@ -344,7 +355,7 @@ class SessionRecorder:
# path has actually begun listening. It therefore also captures a
# fallback that follows a successful realtime handshake.
self._store.update_session_voice_mode(
- session_id=self._state.session_id,
+ session_id=self._state.record_id,
voice_mode=VOICE_MODE_PIPELINE,
)
self._ensure_turn_open(event.timestamp_ns // 1_000_000)
@@ -479,6 +490,8 @@ class SessionRecorder:
# A fresh session supersedes the previous one as the attach target for
# any late completion readback.
self._afterglow = None
+ if self._continue_archived(event.session_id):
+ return
self._store.upsert_session(
session_id=event.session_id,
started_ms=ts_ms,
@@ -487,12 +500,39 @@ class SessionRecorder:
)
log.info("SessionRecorder: session started id=%s", event.session_id)
+ def _continue_archived(self, call_id: str) -> bool:
+ """File this call into the archived voice chat the person reopened.
+
+ The row keeps its start time; its turn numbering and totals carry on
+ from what is stored, so the reopened chat reads as one conversation
+ and ``finalize_session`` writes the grown totals, not this call's
+ alone.
+ """
+ assert self._state is not None
+ target = continued_voice_session()
+ if not target or target == call_id:
+ return False
+ stored = self._store.get_session(target)
+ if stored is None:
+ log.info("SessionRecorder: continued session %s is gone; recording anew", target)
+ return False
+ turns = self._store.get_turns(target)
+ self._state.store_id = target
+ self._state.turn_count = stored.turn_count
+ self._state.total_cost_usd = stored.total_cost_usd
+ self._state.total_tokens_in = stored.total_tokens_in
+ self._state.total_tokens_out = stored.total_tokens_out
+ self._state.providers_used = set(stored.providers_used)
+ self._state.next_idx = max((turn.idx for turn in turns), default=-1) + 1
+ log.info("SessionRecorder: call %s continues session %s", call_id, target)
+ return True
+
def _on_realtime_ready(self, event: RealtimeSessionReady) -> None:
"""Record only an accepted provider handshake as Realtime evidence."""
if self._state is None:
return
self._store.update_session_voice_mode(
- session_id=self._state.session_id,
+ session_id=self._state.record_id,
voice_mode=VOICE_MODE_REALTIME,
)
@@ -503,7 +543,7 @@ class SessionRecorder:
if self._state.current_turn is not None and not self._state.current_turn.finalized:
self._finalize_current_turn(end_ms=event.timestamp_ns // 1_000_000)
self._store.finalize_session(
- session_id=self._state.session_id,
+ session_id=self._state.record_id,
ended_ms=event.timestamp_ns // 1_000_000,
hangup_reason=event.hangup_reason or "",
turn_count=self._state.turn_count,
@@ -523,7 +563,7 @@ class SessionRecorder:
if self._state.current_turn is not None
else None
)
- self._afterglow = (self._state.session_id, last_turn_id)
+ self._afterglow = (self._state.record_id, last_turn_id)
self._state = None
def _force_finalize_session(self, *, reason: str) -> None:
@@ -535,7 +575,7 @@ class SessionRecorder:
if self._state.current_turn is not None and not self._state.current_turn.finalized:
self._finalize_current_turn(end_ms=ts_ms)
self._store.finalize_session(
- session_id=self._state.session_id,
+ session_id=self._state.record_id,
ended_ms=ts_ms,
hangup_reason=reason,
turn_count=self._state.turn_count,
@@ -572,7 +612,7 @@ class SessionRecorder:
)
self._store.upsert_turn(
turn_id=event.turn_id,
- session_id=self._state.session_id,
+ session_id=self._state.record_id,
idx=idx,
started_ms=ts_ms,
)
@@ -647,7 +687,7 @@ class SessionRecorder:
)
self._store.upsert_turn(
turn_id=auto_id,
- session_id=self._state.session_id,
+ session_id=self._state.record_id,
idx=idx,
started_ms=ts_ms,
)
@@ -1068,8 +1108,13 @@ class SessionRecorder:
)
ts_ms = event.timestamp_ns // 1_000_000
payload = _payload_for(event)
+ if self._state.store_id and payload.get("segment_id"):
+ # A caption segment is unique within ONE call; two calls in one
+ # stored row could otherwise overwrite each other's lines.
+ call = self._state.session_id
+ payload["segment_id"] = f"{CALL_SEGMENT_PREFIX}{call}:{payload['segment_id']}"
self._store.append_event(
- session_id=self._state.session_id,
+ session_id=self._state.record_id,
turn_id=turn_id,
ts_ms=ts_ms,
kind=kind,
diff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.py
index 749fda2e74..1e74e04d0d 100644
--- a/jarvis/ui/web/agent_chat_routes.py
+++ b/jarvis/ui/web/agent_chat_routes.py
@@ -95,15 +95,39 @@ 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
+ #: An archived voice chat on stage instead (``sessions.db``): calls are
+ #: recorded into it and start with its history. Only with ``session_id`` unset.
+ voice_session_id: str | None = None
class VoiceChatResponse(BaseModel):
session_id: str | None
fresh: bool
+ voice_session_id: str | None = None
def _voice_chat_answer(svc: AgentChatService) -> VoiceChatResponse:
- return VoiceChatResponse(session_id=svc.voice_chat_id, fresh=svc.voice_chat_fresh)
+ return VoiceChatResponse(
+ session_id=svc.voice_chat_id,
+ fresh=svc.voice_chat_fresh,
+ voice_session_id=svc.voice_session_continued,
+ )
+
+
+def _archived_voice_history(request: Request, voice_session_id: str) -> Any:
+ """Reader for an archived voice chat's turns, or ``None`` when it does not exist."""
+ from .chats_routes import _normalized_messages, _seed_pairs
+
+ session_store = getattr(request.app.state, "session_store", None)
+ chat_store = getattr(request.app.state, "chat_store", None)
+ if session_store is None or session_store.get_session(voice_session_id) is None:
+ return None
+
+ def history() -> list[Any]:
+ messages = _normalized_messages("voice", voice_session_id, chat_store, session_store)
+ return _seed_pairs(messages or [])
+
+ return history
@router.get("/voice-chat", summary="The Jarvis chat voice calls continue")
@@ -115,8 +139,16 @@ async def get_voice_chat(request: Request) -> VoiceChatResponse:
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)
+ voice_session = None if body.session_id else (body.voice_session_id or "").strip() or None
+ history = None
+ if voice_session is not None:
+ history = _archived_voice_history(request, voice_session)
+ if history is None:
+ raise HTTPException(status_code=404, detail="no-such-voice-chat")
try:
- svc.bind_voice_chat(body.session_id or None)
+ svc.bind_voice_chat(
+ body.session_id or None, voice_session=voice_session, voice_history=history
+ )
except NoSuchSession as exc:
raise HTTPException(status_code=404, detail="no-such-jarvis-chat") from exc
return _voice_chat_answer(svc)
diff --git a/jarvis/ui/web/chats_routes.py b/jarvis/ui/web/chats_routes.py
index 5fd273807a..0dfef3cc82 100644
--- a/jarvis/ui/web/chats_routes.py
+++ b/jarvis/ui/web/chats_routes.py
@@ -33,6 +33,7 @@ from pydantic import BaseModel, Field
from jarvis.sessions import chat_titles
from jarvis.sessions.chat_titles import TitleRequest
+from jarvis.sessions.continuation import CALL_SEGMENT_PREFIX
from jarvis.sessions.formatter import _jarvis_outputs_for_turn
from jarvis.state.chat_store import ChatStore
from jarvis.state.conversation_constants import (
@@ -209,7 +210,21 @@ def _normalized_messages(
events = _voice_events(session_store, cid)
live_messages = _live_voice_messages(events)
if live_messages:
- return live_messages
+ # A reopened voice chat can hold an older turn-based call ahead of
+ # its live calls (jarvis/sessions/continuation.py). Those earlier
+ # turns carry no caption rows, so they would vanish behind the
+ # captions; keep them, in time order, in front.
+ first_live = min(m.ts_ms for m in live_messages)
+ captioned = {
+ getattr(e, "turn_id", None)
+ for e in events
+ if e.kind == "VoiceTranscriptUpdated"
+ }
+ earlier = [
+ turn for turn in turns
+ if int(turn.started_ms) < first_live and str(turn.id) not in captioned
+ ]
+ return _turn_messages(earlier, events) + live_messages
# Older GPT-Live sessions retained every fragment even while the chat
# rendered only the current caption. Recover them without a migration.
from jarvis.core.paths import user_data_dir
@@ -222,36 +237,41 @@ def _normalized_messages(
role=caption.role, text=caption.text,
ts_ms=int(session.started_ms) + caption.start_ms - origin,
) for caption in legacy]
- out: list[ChatTurn] = []
- for turn in turns:
- if getattr(turn, "user_text", ""):
- out.append(
- ChatTurn(role="user", text=turn.user_text, ts_ms=int(turn.started_ms))
- )
- turn_id = str(getattr(turn, "id", "") or "")
- turn_events = [
- event for event in events
- if turn_id and getattr(event, "turn_id", None) == turn_id
- ]
- # Use the export's audible-track projection: preambles and progress
- # can be all the user heard before hanging up. They remain spoken
- # history even when no final brain reply or tool call exists.
- for output in _jarvis_outputs_for_turn(turn, turn_events):
- out.append(
- ChatTurn(
- role="assistant",
- text=output.text,
- ts_ms=output.ts_ms,
- trace=(
- _voice_turn_trace(turn, events)
- if output.is_reply else None
- ),
- )
- )
- return out
+ return _turn_messages(turns, events)
return None
+def _turn_messages(turns: list[Any], events: list[Any]) -> list[ChatTurn]:
+ """A turn-based call's messages: the heard words and the audible answers."""
+ out: list[ChatTurn] = []
+ for turn in turns:
+ if getattr(turn, "user_text", ""):
+ out.append(
+ ChatTurn(role="user", text=turn.user_text, ts_ms=int(turn.started_ms))
+ )
+ turn_id = str(getattr(turn, "id", "") or "")
+ turn_events = [
+ event for event in events
+ if turn_id and getattr(event, "turn_id", None) == turn_id
+ ]
+ # Use the export's audible-track projection: preambles and progress
+ # can be all the user heard before hanging up. They remain spoken
+ # history even when no final brain reply or tool call exists.
+ for output in _jarvis_outputs_for_turn(turn, turn_events):
+ out.append(
+ ChatTurn(
+ role="assistant",
+ text=output.text,
+ ts_ms=output.ts_ms,
+ trace=(
+ _voice_turn_trace(turn, events)
+ if output.is_reply else None
+ ),
+ )
+ )
+ return out
+
+
def _voice_events(session_store: Any, session_id: str) -> list[Any]:
"""Every recorded event of a voice session; [] when the store cannot say."""
getter = getattr(session_store, "get_events", None)
@@ -284,7 +304,20 @@ def _live_voice_messages(events: list[Any]) -> list[ChatTurn]:
"start": previous["start"] if previous else event.ts_ms,
"end": event.ts_ms, "audio_start": int(payload.get("start_ms", 0)),
}
- ordered = sorted(segments.values(), key=lambda item: (item["audio_start"], item["start"]))
+ # Each call's audio clock starts at zero. A reopened voice chat holds
+ # several calls (their segment ids carry the call, see
+ # SessionRecorder._maybe_append_raw), so order calls by when they began
+ # and only then by the audio clock inside each call.
+ for segment_id, item in segments.items():
+ continued = segment_id.startswith(CALL_SEGMENT_PREFIX)
+ item["call"] = segment_id.split(":", 2)[1] if continued else ""
+ call_start: dict[str, int] = {}
+ for item in segments.values():
+ call_start[item["call"]] = min(call_start.get(item["call"], item["start"]), item["start"])
+ ordered = sorted(
+ segments.values(),
+ key=lambda item: (call_start[item["call"]], item["audio_start"], item["start"]),
+ )
messages = []
trace_start = min((item["start"] for item in ordered), default=0)
for item in ordered:
diff --git a/jarvis/ui/web/frontend/src/components/home/AssistantChat.tsx b/jarvis/ui/web/frontend/src/components/home/AssistantChat.tsx
index ef88aa06f2..5904935ab8 100644
--- a/jarvis/ui/web/frontend/src/components/home/AssistantChat.tsx
+++ b/jarvis/ui/web/frontend/src/components/home/AssistantChat.tsx
@@ -4,6 +4,7 @@ import { VoiceStage } from "@/components/home/VoiceStage";
import { transcriptFromTimeline, useVoiceModeSwitch } from "@/components/home/assistantStatus";
import { useT } from "@/i18n";
import { useAgentChatStore } from "@/store/agentChat";
+import { useEventStore } from "@/store/events";
import { useHomeStore } from "@/store/home";
const ChatStage = lazy(() =>
@@ -31,13 +32,15 @@ export function AssistantChat() {
const chatItems = useAgentChatStore((s) => s.timeline.items);
const seedTranscript = useHomeStore((s) => s.seedTranscript);
const inVoice = surface === "voice" && !agentChatId;
+ // An archived voice chat on stage owns the lane (store/home.ts reloads it).
+ const voiceThreadOpen = useEventStore((s) => s.activeKind === "voice" && Boolean(s.activeThreadId));
// 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;
+ if (!inVoice || voice.live || voiceThreadOpen) return;
seedTranscript(transcriptFromTimeline(chatItems));
- }, [chatItems, inVoice, seedTranscript, voice.live]);
+ }, [chatItems, inVoice, seedTranscript, voice.live, voiceThreadOpen]);
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 f37b7e5ccb..be1590e11f 100644
--- a/jarvis/ui/web/frontend/src/components/home/assistantStatus.ts
+++ b/jarvis/ui/web/frontend/src/components/home/assistantStatus.ts
@@ -42,6 +42,7 @@ export function transcriptFromTimeline(items: readonly TimelineItem[]): Transcri
* 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.
+ * An archived voice chat opened from the history is continued as itself.
*/
export function useVoiceModeSwitch() {
const surface = useHomeStore((s) => s.surface);
@@ -53,15 +54,21 @@ export function useVoiceModeSwitch() {
const enter = useCallback(() => {
const chat = useAgentChatStore.getState();
+ const events = useEventStore.getState();
+ // An archived voice chat on stage is continued as itself.
+ const voiceThread = !chat.activeSessionId && events.activeKind === "voice" ? events.activeThreadId : null;
+ if (voiceThread) useHomeStore.getState().setContinuedVoiceId(voiceThread);
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));
+ useHomeStore.getState().seedTranscript(
+ voiceThread ? transcriptFromMessages(events.messages) : transcriptFromTimeline(chat.timeline.items),
+ );
}
setSurface("voice");
setActiveSection("chats");
if (!startsCall) return;
- void bindVoiceChat(chat.activeSessionId)
+ void bindVoiceChat(chat.activeSessionId, voiceThread)
.catch((err: unknown) => {
// The call still starts; it just falls back to the newest chat.
console.info("Voice chat binding failed.", err);
diff --git a/jarvis/ui/web/frontend/src/components/home/chatRows.ts b/jarvis/ui/web/frontend/src/components/home/chatRows.ts
index c296b703e5..c6cac4b09d 100644
--- a/jarvis/ui/web/frontend/src/components/home/chatRows.ts
+++ b/jarvis/ui/web/frontend/src/components/home/chatRows.ts
@@ -104,7 +104,10 @@ export function useChatRows({ poll = false }: { poll?: boolean } = {}): ChatRows
// End the agent session on stage first: the chat stage renders the
// voice archive only while no agent chat is open, and its socket has
// no business staying connected to a conversation nobody is looking at.
- useAgentChatStore.getState().newChat();
+ // The voice chat goes on stage as itself: calls from here continue it
+ // (one row in the history), not a new chat beside it.
+ useAgentChatStore.getState().newChat({ voiceSessionId: row.id });
+ useHomeStore.getState().setContinuedVoiceId(row.id);
const stayOnVoice = useHomeStore.getState().surface === "voice";
const opened = openConversation("voice", row.id);
if (stayOnVoice) {
diff --git a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
index 225851c83c..882bfd56a8 100644
--- a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
@@ -74,18 +74,24 @@ export interface VoiceChatBinding {
session_id: string | null;
/** A blank page is open: the next call opens a new chat. */
fresh: boolean;
+ /** An archived voice chat calls are recorded into; absent on an older backend. */
+ voice_session_id?: string | null;
}
/**
* 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.
+ * call opens a new chat. `voiceSessionId` (with `sessionId` null) puts an
+ * archived voice chat on stage instead: calls are recorded into it.
*/
-export async function bindVoiceChat(sessionId: string | null): Promise<VoiceChatBinding> {
+export async function bindVoiceChat(
+ sessionId: string | null,
+ voiceSessionId: string | null = 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 }),
+ body: JSON.stringify({ session_id: sessionId, voice_session_id: voiceSessionId }),
}), "voice-chat-bind-failed");
}
diff --git a/jarvis/ui/web/frontend/src/store/agentChat.ts b/jarvis/ui/web/frontend/src/store/agentChat.ts
index 0108803c28..ded42336cf 100644
--- a/jarvis/ui/web/frontend/src/store/agentChat.ts
+++ b/jarvis/ui/web/frontend/src/store/agentChat.ts
@@ -153,7 +153,11 @@ export interface AgentChatStore {
providerById: (id: string) => ProviderOption | null;
setDraft: (patch: Partial<ComposerDraft>) => Promise<void>;
setPlan: (on: boolean) => Promise<void>;
- newChat: () => void;
+ /**
+ * A blank page. `voiceSessionId` = an archived voice chat goes on stage
+ * instead, and calls continue it rather than opening a new chat.
+ */
+ newChat: (opts?: { voiceSessionId?: string }) => void;
openSession: (sessionId: string) => void;
removeSession: (sessionId: string) => Promise<void>;
/** Send the sentence, with whatever files the composer is holding for it. */
@@ -285,9 +289,9 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =
* `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) => {
+ const bindVoice = (sessionId: string | null, voiceSessionId: string | null = null) => {
if (surface !== "jarvis") return;
- void bindVoiceChat(sessionId).catch((err: unknown) => {
+ void bindVoiceChat(sessionId, voiceSessionId).catch((err: unknown) => {
// Not fatal: the composer's voice button binds again before a call.
console.info("Voice chat binding failed.", err);
});
@@ -614,7 +618,7 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =
}
},
- newChat: () => {
+ newChat: (opts) => {
closeSocket();
++catalogRequest;
set({
@@ -625,7 +629,7 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =
lastError: null,
catalog: null,
});
- bindVoice(null);
+ bindVoice(null, opts?.voiceSessionId ?? null);
void get().loadCatalog();
},
diff --git a/jarvis/ui/web/frontend/src/store/home.ts b/jarvis/ui/web/frontend/src/store/home.ts
index c7f982d9d2..0b4761f978 100644
--- a/jarvis/ui/web/frontend/src/store/home.ts
+++ b/jarvis/ui/web/frontend/src/store/home.ts
@@ -1,7 +1,8 @@
import { create } from "zustand";
import { readHomeSurface, writeHomeSurface, type HomeSurface } from "@/lib/homeSurface";
-import { reduceTranscript, type TranscriptLine } from "@/lib/homeTranscript";
+import { detailToMessages, detailToTraces, resumeConversation } from "@/lib/chatsApi";
+import { reduceTranscript, transcriptFromMessages, type TranscriptLine } from "@/lib/homeTranscript";
import { useEventStore } from "@/store/events";
/**
@@ -28,6 +29,13 @@ interface HomeStore {
freshVoicePending: boolean;
voiceSelectionPending: boolean;
voiceSwitchStopping: boolean;
+ /**
+ * The archived voice chat the front page reopened from the history. Its
+ * calls are recorded into it (jarvis/sessions/continuation.py), so a hangup
+ * keeps it on stage and reloads it instead of opening an empty lane.
+ */
+ continuedVoiceId: string | null;
+ setContinuedVoiceId: (id: string | null) => void;
surface: HomeSurface;
setSurface: (surface: HomeSurface) => void;
/** What was said and answered, oldest first (lib/homeTranscript.ts). */
@@ -85,6 +93,22 @@ export function reduceLiveReply(current: string, name: string, payload: unknown)
}
}
+/** Re-read a continued voice chat after a call and put its lines back on stage. */
+async function reloadContinuedVoiceChat(id: string): Promise<void> {
+ try {
+ const detail = await resumeConversation("voice", id);
+ const events = useEventStore.getState();
+ if (events.activeKind !== "voice" || events.activeThreadId !== id) return;
+ const messages = detailToMessages(detail);
+ events.seedThinkingTraces(detailToTraces(detail));
+ events.setMessages(messages);
+ useHomeStore.getState().seedTranscript(transcriptFromMessages(messages));
+ } catch (error) {
+ // The lane keeps what the call showed; the history row has the rest.
+ console.info("Continued voice chat could not be reloaded.", error);
+ }
+}
+
export const useHomeStore = create<HomeStore>((set, get) => ({
jarvisCardMode: "voice",
setJarvisCardMode: (jarvisCardMode) => set({ jarvisCardMode }),
@@ -93,6 +117,8 @@ export const useHomeStore = create<HomeStore>((set, get) => ({
freshVoicePending: false,
voiceSelectionPending: false,
voiceSwitchStopping: false,
+ continuedVoiceId: null,
+ setContinuedVoiceId: (continuedVoiceId) => set({ continuedVoiceId }),
surface: readHomeSurface(),
setSurface: (surface) => {
writeHomeSurface(surface);
@@ -118,6 +144,18 @@ export const useHomeStore = create<HomeStore>((set, get) => ({
// empty lane; the completed conversation remains in the history rail.
if (reason !== "realtime_fallback" && reason !== "desktop_fallback") {
const events = useEventStore.getState();
+ const continued = get().continuedVoiceId;
+ if (
+ continued && events.activeKind === "voice" && events.activeThreadId === continued
+ && !get().voiceSwitchStopping
+ ) {
+ // The call was recorded into the reopened voice chat: it stays on
+ // stage, and its stored lines (now with this call) replace the lane.
+ events.setTranscription("", true);
+ set({ liveReply: "", freshVoicePending: false });
+ void reloadContinuedVoiceChat(continued);
+ return;
+ }
if (events.activeKind === "voice" && !get().voiceSwitchStopping) {
events.setActiveConversation("voice", null);
events.setMessages([]);
diff --git a/tests/unit/agent_chat/test_voice_mirror.py b/tests/unit/agent_chat/test_voice_mirror.py
index 8f33f59583..f83564a2eb 100644
--- a/tests/unit/agent_chat/test_voice_mirror.py
+++ b/tests/unit/agent_chat/test_voice_mirror.py
@@ -254,3 +254,29 @@ def test_a_chat_opened_by_a_call_keeps_the_persons_chat_model(tmp_path: Path) ->
assert (created.provider, created.model) == (typed.provider, typed.model)
asyncio.run(scenario())
+
+
+def test_a_continued_voice_chat_is_not_copied_into_a_typed_chat(tmp_path: Path) -> None:
+ from jarvis.sessions.continuation import continue_voice_session, continued_voice_session
+
+ async def scenario() -> None:
+ svc = _service(tmp_path)
+ typed = _open_session(svc)
+ svc.bind_voice_chat(
+ None, voice_session="archived", voice_history=lambda: [("user", "old words")]
+ )
+ assert continued_voice_session() == "archived"
+ assert svc.voice_chat_history() == [("user", "old words")]
+ bus = EventBus()
+ VoiceChatMirror(lambda: svc).attach(bus)
+ await bus.publish(_turn("call-1", "t1", "go on", "going on"))
+ assert svc.store.list_events(typed.session_id) == []
+ assert len(svc.store.list_sessions(limit=10, surface="jarvis")) == 1
+ # Putting a typed chat on stage ends the continuation.
+ svc.bind_voice_chat(typed.session_id)
+ assert continued_voice_session() is None
+
+ try:
+ asyncio.run(scenario())
+ finally:
+ continue_voice_session(None)
diff --git a/tests/unit/sessions/test_recorder_continuation.py b/tests/unit/sessions/test_recorder_continuation.py
new file mode 100644
index 0000000000..71bd1287e0
--- /dev/null
+++ b/tests/unit/sessions/test_recorder_continuation.py
@@ -0,0 +1,118 @@
+"""Continuing an archived voice chat records into its row, not a new one.
+
+Reopening an old voice chat from the history and talking on used to spawn a
+second history row ("Voice chat · 16:59") beside the one that was open.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterator
+
+import pytest
+
+from jarvis.core.bus import EventBus
+from jarvis.core.events import (
+ VoiceSessionEnded,
+ VoiceSessionStarted,
+ VoiceTranscriptUpdated,
+ VoiceTurnCompleted,
+ VoiceTurnStarted,
+)
+from jarvis.sessions.continuation import continue_voice_session
+from jarvis.sessions.recorder import SessionRecorder
+from jarvis.sessions.store import SessionStore
+from jarvis.ui.web.chats_routes import _normalized_messages
+
+
[email protected](autouse=True)
+def _no_continuation() -> Iterator[None]:
+ continue_voice_session(None)
+ yield
+ continue_voice_session(None)
+
+
+async def _call(bus: EventBus, call: str, turn: str, user: str, reply: str) -> None:
+ await bus.publish(VoiceSessionStarted(source_layer="test", session_id=call, language="de"))
+ await bus.publish(VoiceTurnStarted(source_layer="test", session_id=call, turn_id=turn))
+ await bus.publish(
+ VoiceTurnCompleted(
+ source_layer="test", session_id=call, turn_id=turn, user_text=user, jarvis_text=reply
+ )
+ )
+ await bus.publish(VoiceSessionEnded(source_layer="test", session_id=call))
+
+
+async def _live_call(bus: EventBus, call: str, user: str, reply: str) -> None:
+ await bus.publish(VoiceSessionStarted(source_layer="test", session_id=call, language="de"))
+ await bus.publish(VoiceTurnStarted(source_layer="test", session_id=call, turn_id=f"{call}-t"))
+ for segment, role, text, start in (("u1", "user", user, 100), ("a1", "assistant", reply, 900)):
+ await bus.publish(
+ VoiceTranscriptUpdated(
+ source_layer="test", session_id=call, segment_id=segment, role=role, # type: ignore[arg-type]
+ text=text, start_ms=start, end_ms=start + 400, revision=1,
+ )
+ )
+ await bus.publish(VoiceSessionEnded(source_layer="test", session_id=call))
+
+
+async def test_a_continued_call_lands_in_the_reopened_row(tmp_path) -> None:
+ store = SessionStore(tmp_path / "sessions.db")
+ store.open()
+ try:
+ bus = EventBus()
+ SessionRecorder(store).attach(bus)
+ await _call(bus, "old-call", "old-turn", "translate CLAUDE.md", "Done.")
+ continue_voice_session("old-call")
+ await _live_call(bus, "new-call", "and the README too", "On it.")
+
+ assert store.get_session("new-call") is None
+ assert [s.id for s in store.list_sessions(limit=10)] == ["old-call"]
+ row = store.get_session("old-call")
+ assert row is not None and row.turn_count == 2
+ assert [t.idx for t in store.get_turns("old-call")] == [0, 1]
+ messages = _normalized_messages("voice", "old-call", None, store) # type: ignore[arg-type]
+ assert [(m.role, m.text.strip()) for m in messages or []] == [
+ ("user", "translate CLAUDE.md"),
+ ("assistant", "Done."),
+ ("user", "and the README too"),
+ ("assistant", "On it."),
+ ]
+ finally:
+ store.close()
+
+
+async def test_two_live_calls_in_one_row_keep_both_and_their_order(tmp_path) -> None:
+ store = SessionStore(tmp_path / "sessions.db")
+ store.open()
+ try:
+ bus = EventBus()
+ SessionRecorder(store).attach(bus)
+ await _live_call(bus, "first", "first question", "first answer")
+ continue_voice_session("first")
+ # Same segment ids and the same audio clock as the first call.
+ await _live_call(bus, "second", "second question", "second answer")
+ messages = _normalized_messages("voice", "first", None, store) # type: ignore[arg-type]
+ assert [m.text.strip() for m in messages or []] == [
+ "first question",
+ "first answer",
+ "second question",
+ "second answer",
+ ]
+ finally:
+ store.close()
+
+
+async def test_without_a_continuation_each_call_keeps_its_own_row(tmp_path) -> None:
+ store = SessionStore(tmp_path / "sessions.db")
+ store.open()
+ try:
+ bus = EventBus()
+ SessionRecorder(store).attach(bus)
+ await _call(bus, "a", "a-t", "one", "uno")
+ await _call(bus, "b", "b-t", "two", "dos")
+ assert {s.id for s in store.list_sessions(limit=10)} == {"a", "b"}
+ finally:
+ store.close()