How Speak's realtime voice works: a server-minted secret, a browser-held WebRTC call, and an HTTP side channel
Speak Live works across three planes. First, the Next.js session route authenticates the user, checks budgets, resolves a thread, builds instructions and tools, and mints a short-lived OpenAI Realtime client secret through the openai SDK. Second, the browser uses that secret to open a WebRTC peer connection directly to OpenAI. Microphone audio goes up, model audio comes back, and JSON events travel over an oai-events data channel. Third, everything the app must control or record goes through separate authenticated routes: tools (/tool), metering (/heartbeat), transcript persistence (/transcript), settlement (/end), and reload discovery (/active). The useRealtimeVoice hook coordinates all three. It is mounted in a root-layout provider, so a call survives client-side navigation. A hard reload is handled by minting a new call against the same Redis session record, with thread context carried back in as a text preamble in instructions. An idle timer pauses quiet calls. Of the gaps in the 2026-09-12 audit, the transcript event-name mismatch and missing usage forwarding are fixed in code. Several others remain: delta captions are replaced rather than accumulated, thinking is never produced, tool-route budget detection is substring-based, tool network failures are never reported to the model, and daily minutes round up per interval.
1×
Sign in to listen.
Automated reviewer requested changes — ready for your evaluation · 9 open
The shape of the system, and how far to trust the older audit
Audio never passes through this app's servers. lib/speak/transport/voice-transport.ts says the browser holds the peer connection, the mic track goes straight to OpenAI, and model audio comes straight back. Its stated tradeoff is lowest latency and no media egress, at the cost of the call dying with the document. The server's role is credentialing and bookkeeping. Only the session route talks to OpenAI, and only to mint a secret with the SDK. The other routes read and write the Redis session record and Supabase.
A note on the documentation. docs/speak/current-realtime-setup.md is a 2026-09-12 audit. Its header says persistence, resume, memory, and usage forwarding changed, and that transport, limits, and accounting "still describe the current code." Checked row by row against the inspected code, its implementation-gaps table is mostly still accurate:
- Fixed. The event-name row.
lib/speak/realtime-events.tsnow accepts both the GAresponse.output_audio_transcript.*names and the beta names. - Partly addressed. The connection-health row. The transport now reports peer
connectionStatefailures, and the hook now handles Realtimeerrorevents. There is still no data-channel close handler and no startup timeout. - Still present. Incremental captions, the missing
thinkingphase, both tool-failure rows, and the early "speaking" signal. - Not checkable here. Caption override, web preview, presentation, and motion live in components I did not inspect.
One point cuts the other way despite the header. The audit's accounting bullet saying the hook never forwards token usage is now out of date, as the metering section shows.
Loading implementation view…
/**
* Voice transport seam.
*
* `useRealtimeVoice` owns session lifecycle — minting, heartbeats, transcript flushing, tool
* dispatch. It must not also own *how* bytes reach the model. That distinction is the whole
* point of this file: today the browser holds the peer connection directly
* ({@link createWebRtcVoiceTransport}), and a server-side relay can be dropped in later as a
* second implementation without the hook, the provider, or any UI changing shape.
*
* See `docs/speak/decisions/` for the continuity ADR that gated this split.
*/> **Superseded in part on 2026-09-17.** Persistence, resume, memory, and usage forwarding
> changed; see [`decisions/20260917-voice-continuity-and-memory.md`](./decisions/20260917-voice-continuity-and-memory.md)
> and the [README](./README.md). The transport, limits, and accounting sections below still
> describe the current code.| Area | Evidence and consequence |
|------|--------------------------|
| Assistant transcripts | The hook listens for `response.audio_transcript.delta/done`. The installed SDK and official Realtime guide use `response.output_audio_transcript.delta/done`. Those documented events have no matching handler, so assistant captions/transcript entries are expected to be missed. |
| Incremental captions | Even the existing delta handler replaces the caption with each delta instead of accumulating a complete utterance. |
| Caption override | After `update_display_text`, `displayText` takes precedence over later captions until Reset. Later user or system caption metadata can accompany the old override text. |
| Speaking/thinking feedback | `thinking` is declared and styled but never produced by `phaseFromEvents()`. `response.created` immediately marks the assistant speaking, before actual playback; `response.done` clears it without waiting for buffered playback to finish. |
| Connection health | “Connected” is set after applying SDP, with no peer-connection state, data-channel close/error, or Realtime `error` event handler. There is no automatic reconnect or explicit timeout/cancellation for startup. |
| Tool failures | Network failures set local error text but do not send a failed function output back to the model. Normal validation failures do return a model error. |
| Budget failures during tools | The tool route sets `shouldClose` only when error text includes uppercase `Budget`. Actual limit messages commonly contain “minute limit” or “spend cap,” so the browser may remain connected until the next heartbeat. |For a reader comfortable with HTTP APIs, think of the WebRTC call as a long-lived socket you are authorized to open but do not proxy. Wherever the app needs authority (tools, billing, persistence), it uses an ordinary authenticated POST beside that socket.
Minting: the session is configured before the browser connects
POST /api/ai/speak/realtime/session (app/api/ai/speak/realtime/session/route.ts) works through its checks in order:
- The feature flag and API key.
- Clerk authentication, then the Supabase user mapping.
- Zod validation of the request body.
- The general LLM message limit.
Then comes a subtle step. When the client is resuming after a reload, the route settles the predecessor session before the start check. The comment explains why: the orphaned record still holds the user's only concurrency slot, so checking first would reject every reload. The successor inherits expiresAt, so refreshing cannot extend the per-session minute cap.
After checkSpeakRealtimeSessionStart passes, the route resolves a thread, compiles modality-gated tools, and builds instructions. It mints the secret with the openai SDK. That call carries the whole session configuration: server-side voice activity detection, input transcription, the output voice, an 800-token response cap, and retention_ratio truncation. The browser never chooses any of these. It receives only the secret.
if (parsed.data.resumeSessionId) {
const previous = await getSpeakRealtimeSession(parsed.data.resumeSessionId);
const resumable =
previous &&
previous.userId === sbUserId &&
previous.status === "active" &&
// An already-expired predecessor has nothing left to inherit; let it settle and start over.
previous.expiresAt > Date.now() + RESUME_MIN_REMAINING_MS;
if (previous && resumable) {
continuity = {
continuityStartedAt: previous.continuityStartedAt ?? previous.startedAt,
expiresAt: previous.expiresAt,
};
inheritedThreadId = previous.threadId;
// Bills the predecessor's tail and frees its slot. The successor inherits `expiresAt`, so
// reloading cannot buy more minutes than one session is allowed.
await endSpeakRealtimeSession({ sessionId: previous.sessionId, userId: sbUserId });
} else {
logger.warn("POST", "resumeSessionId did not match a resumable session; starting fresh");
// Still settle it, or its slot blocks the fresh session we are about to start.
if (previous && previous.userId === sbUserId && previous.status === "active") {
await endSpeakRealtimeSession({ sessionId: previous.sessionId, userId: sbUserId });
}
}
} try {
secretPayload = await openai.realtime.clientSecrets.create({
expires_after: { anchor: "created_at", seconds: 600 },
session: {
type: "realtime",
model,
instructions,
tools,
tool_choice: tools.length > 0 ? "auto" : "none",
max_output_tokens: 800,
// The resumed-thread preamble lives in `instructions`. Retention-ratio truncation drops
// old conversation items when the context fills but never the instructions themselves.
truncation: { type: "retention_ratio", retention_ratio: 0.8 },
audio: {
input: {
turn_detection: { type: "server_vad" },
transcription: { model: "gpt-transcribe" },
},
output: {
voice,
},
},
},
}); const record = await registerSpeakRealtimeSession({
sessionId: ourSessionId,
userId: sbUserId,
model,
threadId,
modalities,
memoryEnabled,
continuity,
});Two lifecycles are layered here, and they are easy to confuse. The OpenAI secret expires 600 seconds after creation. The app's own deadline is expiresAt in Redis, which defaults to SPEAK_SESSION_MAX_MINUTES (8) in lib/rate-limit/speak-realtime.ts. The app's session id is OpenAI's session.id when present, with a random UUID as fallback. A thread-resolution failure is only logged, so a call can start without persistence.
The WebRTC handshake, step by step
If WebRTC is new to you, createWebRtcVoiceTransport is a compact example of the standard browser flow:
- Create an
RTCPeerConnection. - Register
ontrack, so the model's audio becomes aMediaStreamwhen it arrives. - Capture the mic with
getUserMediaandaddTrackit. - Open a data channel named
oai-eventsfor JSON events. - Generate an SDP offer and set it as the local description.
The offer is a text description of what this peer can send and receive. It is POSTed as application/sdp to https://api.openai.com/v1/realtime/calls, with the ephemeral secret as a bearer token. The response body is the SDP answer. Once setRemoteDescription applies it, ICE negotiation finishes on its own and media flows.
Three details matter for failure handling:
- Mic permission comes late. The prompt happens here, after the server session already exists. A denied permission throws into the hook's catch path, which settles the session through
/end. - SDP rejections carry a status. A non-OK SDP response throws
RealtimeConnectErrorwith the HTTP status. - Unexpected drops are reported.
onconnectionstatechangeforwardsfailedordisconnectedthroughonClosed. It stays silent whenclose()itself started the shutdown, which theclosedByUsflag tracks.
async connect({ clientSecret }, events) {
closedByUs = false;
pc = new RTCPeerConnection();
pc.ontrack = (e) => {
remote = e.streams[0] ?? null;
if (remote) events.onRemoteStream(remote);
};
pc.onconnectionstatechange = () => {
if (closedByUs || !pc) return;
if (pc.connectionState === "failed" || pc.connectionState === "disconnected") {
events.onClosed(`Connection ${pc.connectionState}`);
}
};
local = await navigator.mediaDevices.getUserMedia({ audio: true });
pc.addTrack(local.getTracks()[0]!);
dc = pc.createDataChannel("oai-events");
dc.addEventListener("message", (ev) => {
if (typeof ev.data === "string") events.onServerEvent(ev.data);
});
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
const sdpRes = await fetch(REALTIME_CALLS_URL, {
method: "POST",
body: offer.sdp,
headers: {
Authorization: `Bearer ${clientSecret}`,
"Content-Type": "application/sdp",
},
});
if (!sdpRes.ok) {
const errText = await sdpRes.text().catch(() => "");
throw new RealtimeConnectError(sdpRes.status, errText);
}
await pc.setRemoteDescription({ type: "answer", sdp: await sdpRes.text() });
}, send(event) {
if (!dc || dc.readyState !== "open") return false;
dc.send(JSON.stringify(event));
return true;
},
close() {
closedByUs = true;
try {
dc?.close();
} catch {
/* already gone */
}
dc = null;
try {
pc?.close();
} catch {
/* already gone */
}
pc = null;
local?.getTracks().forEach((t) => t.stop());
local = null;
remote = null;
},connect resolves as soon as the remote description is applied. It does not wait for the data channel's open event or for ICE to reach connected, yet the hook marks the call connected at that moment. Because send() returns false whenever dc.readyState !== "open", a client event sent in that window is dropped rather than queued. No data-channel close or error listener exists either. A channel that dies while the peer connection stays up would go unnoticed until a send fails or a heartbeat closes the session.
The hook's connect loop: one silent retry on provider 5xx
connect() in hooks/use-realtime-voice.ts wraps the mint and the transport in a loop that allows exactly one retry. isRetryableConnectError sets the rule. A 5xx from /realtime/calls can follow a successful mint, so a fresh secret may help. A 4xx means the secret or offer is itself wrong and would fail again.
On retry, the hook makes three changes:
- It passes the failed attempt's id as
resumeSessionId, so the server settles that record and frees its slot. - It sends the failure status and detail, since the SDP exchange happened in the browser and the server otherwise never sees why it failed.
- It sets
withoutThreadContext. The constant's doc comment names the tradeoff: give up recall so the call connects.
On success, the hook publishes the local and remote streams for the waveform, marks itself connected, starts a 30-second heartbeat, and resets the idle timer. Any thrown error goes to teardown({ notifyServer: true, connectFailure }), which posts /end so the server can settle the session and log the failure.
/**
* One silent retry when OpenAI 5xxs the SDP exchange. The retry mints a fresh secret that
* settles the failed session and drops the thread context from the instructions, trading
* recall for a call that connects. More than one retry would leave the user in dead air.
*/
const CONNECT_RETRY_LIMIT = 1;
const CONNECT_RETRY_DELAY_MS = 600; transport = transportFactoryRef.current();
transportRef.current = transport;
try {
await transport.connect(
{ clientSecret: mint.clientSecret },
{
onServerEvent: handleDataEvent,
onRemoteStream: (stream) => {
audioEl.srcObject = stream;
setStreams((prev) => ({ ...prev, remote: stream }));
},
onClosed: (reason) => {
setError(reason);
void teardown({ notifyServer: true });
},
}
);
break;
} catch (err) {
if (attempt >= CONNECT_RETRY_LIMIT || !isRetryableConnectError(err)) throw err;
transport.close();
transportRef.current = null;
retryFailure = connectFailureOf(err);
resumeSessionId = mint.sessionId;
await new Promise((resolve) => setTimeout(resolve, CONNECT_RETRY_DELAY_MS));
}
}/**
* Whether a fresh mint is worth trying. A 5xx from `/realtime/calls` can follow a mint that
* succeeded; a 4xx means the secret or offer itself is wrong, and a new secret for the same
* config would fail the same way.
*/
export function isRetryableConnectError(error: unknown): error is RealtimeConnectError {
return error instanceof RealtimeConnectError && error.status >= 500;
}The remote stream is attached to audioElRef. In the app-wide provider, that ref points to a single hidden <audio autoPlay> element rendered next to the children. The provider's comment says it must never live inside a page, because re-parenting a playing audio element restarts it and unmounting it silences the call.
From raw data-channel JSON to UI state
Every string arriving on oai-events goes to handleDataEvent, which parses it and hands it to the pure classifyRealtimeEvent in lib/speak/realtime-events.ts. The file comment says the classifier is kept pure so that event-name handling is unit-testable without a peer connection. It accepts both GA and beta transcript names. That resolves one specific audit finding: completed assistant transcripts were expected to be missed under GA names.
The hook keeps speaking state in refs (userSpeakingRef, assistantSpeakingRef), derives the visible phase from them with phaseFromEvents, and drives the idle timer with begin/end pairs. The classifier separates two lifecycles. The response runs from response.created to response.done. Playback runs from output_audio_buffer.started to stopped or cleared. Its comment gives the reason: on WebRTC, playback outlives response.done. cleared is the interruption path, where the user talks over the model.
switch (type) {
case "input_audio_buffer.speech_started":
return { kind: "user_speech_started" };
case "input_audio_buffer.speech_stopped":
return { kind: "user_speech_stopped" };
case "response.created":
case "response.output_audio.delta":
case "response.audio.delta":
return { kind: "assistant_started" };
case "response.done":
return { kind: "assistant_finished", usage: usageFromResponseDone(event) };
case "response.output_audio.done":
case "response.audio.done":
return { kind: "assistant_audio_stopped" };
case "output_audio_buffer.started":
return { kind: "assistant_playback_started" };
// `cleared` is the interruption path: the user talked over the model and the buffer was dropped.
case "output_audio_buffer.stopped":
case "output_audio_buffer.cleared":
return { kind: "assistant_playback_stopped" };
case "conversation.item.input_audio_transcription.completed": {
const text = String(event.transcript ?? "").trim();
return { kind: "user_transcript", text, itemId: str(event.item_id) };
}
case "response.output_audio_transcript.delta":
case "response.audio_transcript.delta":
return { kind: "assistant_transcript_delta", delta: String(event.delta ?? "") };
case "response.output_audio_transcript.done":
case "response.audio_transcript.done": {
const text = String(event.transcript ?? "").trim();
return { kind: "assistant_transcript", text, itemId: str(event.item_id) };
} case "assistant_started":
idleTimer.begin("response");
assistantSpeakingRef.current = true;
assistantStartedAtRef.current ??= Date.now();
syncPhase();
return;
case "assistant_finished":
idleTimer.end("response");
assistantSpeakingRef.current = false;
pendingUsageRef.current = sumRealtimeUsage(pendingUsageRef.current, ev.usage);
syncPhase();
return;
case "assistant_audio_stopped":
assistantSpeakingRef.current = false;
syncPhase();
return;
case "assistant_playback_started":
idleTimer.begin("playback");
return;
case "assistant_playback_stopped":
idleTimer.end("playback");
assistantSpeakingRef.current = false;
syncPhase();
return;function phaseFromEvents(args: {
connected: boolean;
userSpeaking: boolean;
assistantSpeaking: boolean;
}): LiveVoicePhase {
if (!args.connected) return "idle";
if (args.assistantSpeaking) return "speaking";
if (args.userSpeaking) return "listening";
return "idle";
}Several separate rough edges remain:
thinkingis unreachable. TheLiveVoicePhasetype on line 36 includes it, butphaseFromEventshas no branch that returns it, so the hook can never emit it.- "Speaking" starts early.
response.createdis classified asassistant_started, so the phase becomesspeakingbefore any audio plays. - The phase can end early.
assistant_finishedclearsassistantSpeakingRefwhile playback may still be running, so the phase can fall toidlemid-sentence. The idle timer, by contrast, holds itsplaybackactivity until the buffer stops. - Delta captions are replaced, not accumulated. The audit's incremental-caption gap is untouched. Each
assistant_transcript_deltasends the raw delta toonCaptionChangeas an interim caption, which replaces the previous one.
Completed user and assistant transcripts are appended to the in-memory list and pushed into turnBufferRef for persistence. Each turn is stamped with when the utterance began, because user transcription finalises asynchronously.
Tool calls: a browser-relayed round trip with two payloads
A tool call is a round trip that the browser relays.
- The model emits
response.function_call_arguments.doneon the data channel. - The browser POSTs
{sessionId, callId, name, arguments}to/api/ai/speak/realtime/tool. - The route checks auth and plan budget.
executeSpeakRealtimeToolre-verifies session ownership and active status, then runsassertSpeakBudgetOrClose, which also meters elapsed time.- It validates the tool name, gates on the session's stored modalities and memory flag, and parses the arguments.
The result has two payloads. modelResult goes back to OpenAI as a function_call_output item. clientEffects go to React state, which the provider applies through applyVoiceEffects. The hook then sends response.create so the model continues. While the tool runs, the idle timer holds a tool:<callId> activity, so a slow render does not count as silence.
try {
const res = await fetch("/api/ai/speak/realtime/tool", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
sessionId: sid,
callId: call.call_id,
name: call.name,
arguments: call.arguments ?? "{}",
}),
});
const data = (await res.json()) as ToolResponse;
if (data.clientEffects?.length) {
onClientEffects?.(data.clientEffects);
}
if (data.shouldClose) {
setError(data.error ?? "Budget exceeded");
await teardown({ notifyServer: false });
return;
}
const transport = transportRef.current;
if (transport) {
transport.send({
type: "conversation.item.create",
item: {
type: "function_call_output",
call_id: call.call_id,
output: JSON.stringify(data.modelResult ?? { ok: data.ok }),
},
});
transport.send({ type: "response.create" });
}
} catch (err) {
setError(err instanceof Error ? err.message : "Tool call failed");
} finally {
idleTimer.end(activity);
} if (!result.ok && result.error?.includes("Budget")) {
return NextResponse.json(
{
error: result.error,
shouldClose: true,
modelResult: result.modelResult,
clientEffects: result.clientEffects,
},
{ status: 402 }
);
}
logger.log("POST", `Tool ${parsed.data.name}`, {
ok: result.ok,
effects: result.clientEffects.length,
});
return NextResponse.json({
ok: result.ok,
error: result.error,
callId: parsed.data.callId ?? null,
modelResult: result.modelResult,
clientEffects: result.clientEffects,
});Follow a budget failure during a tool through the code. If assertSpeakBudgetOrClose hits a cap, it closes the Redis session and returns a message such as Session minute limit (8 min) exceeded or Daily Speak Realtime minute limit exceeded. Neither contains Budget, so the route skips its 402 branch. It returns HTTP 200 with ok: false and an error modelResult, and the response has no shouldClose field at all.
The hook never checks res.ok; it only reads data.shouldClose. So it forwards the error to the model and stays connected. The server-side session is already closed and its slot freed, but the WebRTC call keeps running. It stops at the next heartbeat (within 30 seconds), which gets Session already closed with shouldClose and tears down.
A second gap: if the fetch throws on a network error or unparsable JSON, the catch only sets local error text. No function_call_output is sent, so the model's call goes unanswered. Ordinary validation failures do reach the model as { error: ... }.
Heartbeats, metering, persistence, and teardown
Every 30 seconds, sendHeartbeat flushes buffered turns and POSTs /heartbeat with any response.done usage accumulated since the last tick. If that request fails at the network level, the usage is folded back into the pending buffer rather than dropped.
On the server, assertSpeakBudgetOrClose measures elapsed minutes on its own clock, capped at expiresAt, so the client cannot under-report time. recordSpeakUsage charges the daily and monthly limiters. When usage is present, cost comes from tokens; otherwise a per-minute estimate is used. The function then checks the deadline, daily minutes, monthly spend, and plan budget, and the route returns 402 with shouldClose if any cap is hit.
The audit's minute-rounding finding still holds. Each positive interval charges Math.max(1, Math.ceil(minutesDelta)) daily-minute units, so two 30-second heartbeats cost two units. The ledger write now passes costUsdOverride: incrementalCost, and the continuity ADR says this makes cost_usd reflect provider tokens rather than zero.
teardown is the single exit path, and its order matters:
- Stop the heartbeat and idle timer.
- Issue a final transcript flush with
keepalive, so the request can outlive a closing tab. - POST
/endon a best-effort basis, unless the server already closed the session. - Close the transport and clear the audio source.
- Reset state.
/end bills the tail interval and removes the session from the user's active set. It closes only the app's record; nothing in the inspected code hangs up the OpenAI call server-side.
const sendHeartbeat = useCallback(async () => {
const sid = sessionIdRef.current;
if (!sid) return;
void flushTurns();
const usage = pendingUsageRef.current;
pendingUsageRef.current = null;
try {
const res = await fetch("/api/ai/speak/realtime/heartbeat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sessionId: sid, usage: usage ?? undefined }),
});
const data = (await res.json()) as HeartbeatResponse;
applyBudget(data.budget);
if (!res.ok || data.shouldClose) {
setError(data.error ?? "Speak Realtime budget exceeded");
onCaptionChange?.({
role: "system",
text: data.error ?? "Session ended — budget limit reached.",
});
await teardown({ notifyServer: false });
}
} catch {
// Transient: carry the unbilled usage into the next tick rather than dropping it.
pendingUsageRef.current = sumRealtimeUsage(usage, pendingUsageRef.current);
}
}, [applyBudget, flushTurns, onCaptionChange, teardown]);async function recordSpeakUsage(args: {
session: SpeakRealtimeSessionRecord;
minutesDelta: number;
usage?: Usage;
now: number;
}): Promise<void> {
const { session, usage, now } = args;
const minutesDelta = Math.max(0, args.minutesDelta);
const modelId = normalizeRealtimeModelId(session.model);
const incrementalCost = incrementalCostUsd(session, minutesDelta, usage);
if (minutesDelta > 0) {
const minuteUnits = Math.max(1, Math.ceil(minutesDelta));
await runLimiter("recordSpeakDailyMinutes", () =>
dailyMinuteLimiter.limit(session.userId, { rate: minuteUnits })
);
} const teardown = useCallback(
async (opts?: { notifyServer?: boolean; connectFailure?: ConnectFailure }) => {
stopHeartbeat();
idleTimer.stop();
const sid = sessionIdRef.current;
// Before `/end` and before the session id is cleared; the fetch is issued synchronously.
if (sid) {
void flushTurns({ final: true });
}
if (opts?.notifyServer !== false && sid) {
void fetch("/api/ai/speak/realtime/end", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sessionId: sid, connectFailure: opts?.connectFailure }),
}).catch(() => undefined);
}
transportRef.current?.close();
transportRef.current = null;
if (audioElRef.current) {
audioElRef.current.srcObject = null;
}
A transcript flush that gets a 5xx or a network error re-queues its batch. A 4xx drops it, on the stated reasoning that the session or thread is gone. A tab that disappears without reaching /end keeps its concurrency slot until settleStaleSpeakSessions runs during the user's next start or /active check, and even then only after the deadline has passed. No scheduled worker does this cleanup.
Continuity: navigation, reloads, context preamble, and idle pause
Navigation. VoiceSessionProvider (components/voice/voice-session-provider.tsx) calls useRealtimeVoice and renders the audio sink. Per its comment and the README, it is mounted in the root layout, which the App Router preserves across client-side navigation. The peer connection and mic stream therefore never unmount on a route change. The comment calls this the whole mechanism: no relay, no worker.
Reload. A reload does destroy the peer connection. On mount, the provider calls resumeIfActive, which asks GET /active whether a Redis session is still live. If it is, the hook calls connect({ resumeSessionId }). The session route settles the old record and mints a new OpenAI call bound to the same thread and deadline.
The ADR is explicit that Realtime keeps no state across sessions, so the conversation cannot be resumed on OpenAI's side. Instead, for a resumed thread the route calls loadSpeakSessionContext and formatSpeakSessionContext to build a text preamble. Per the README, that preamble holds the thread summary, memories seeded from it, and the last four turns, under roughly a 1.8k-token cap. The preamble is passed into buildSpeakRealtimeInstructions. The ADR rejected the alternative of replaying turns as conversation.item.create items for two reasons: it keeps decrypted history from transiting the browser, and it puts the context where retention_ratio truncation cannot evict it. The cost it names is fidelity, since past turns arrive as prompt text rather than role-structured items. The connect retry drops this preamble on purpose with withoutThreadContext.
Idle. createVoiceIdleTimer (lib/speak/voice-idle.ts) fires after 20 seconds with no user speech, no response in flight, no playback, and no running tool. pauseForIdle remembers the thread and tears down with server notification. resume then reconnects to that same thread through the same preamble path.
// A resumed thread has history to carry in; a fresh one has nothing to seed a search with.
let sessionContext: string | null = null;
const withThreadContext = thread.resumed && parsed.data.withoutThreadContext !== true;
if (threadId && withThreadContext) {
const loaded = await loadSpeakSessionContext({ ownerId: sbUserId, threadId, memoryEnabled });
sessionContext = formatSpeakSessionContext(loaded) || null;
}**Rehydration goes through `instructions`, not the data channel.** Decrypted history never
transits the browser purely as a relay, and the preamble sits where truncation cannot reach it.
The cost is fidelity: turns arrive as text inside the prompt rather than as role-structured
items. Budget is `SPEAK_CONTEXT_MAX_TOKENS` (1.8k) because sessions are minutes long and the
prompt is re-read every turn. const resumeIfActive = useCallback(async (): Promise<boolean> => {
if (connectedRef.current || connecting) return false;
try {
const res = await fetch("/api/ai/speak/realtime/active");
if (!res.ok) return false;
const data = (await res.json()) as ActiveSessionResponse;
if (!data.session) return false;
await connect({ resumeSessionId: data.session.sessionId });
return true;
} catch {
// Offline or the route is unreachable: stay idle rather than surfacing an error the user
// did not ask for. They can always start a session by hand.
return false;
}
}, [connect, connecting]); const arm = () => {
disarm();
timer = setTimeout(() => {
timer = null;
if (active.size === 0) onIdle();
}, timeoutMs);
};
return {
begin(activity) {
active.add(activity);
disarm();
},
end(activity) {
if (!active.delete(activity)) return;
if (active.size === 0) arm();
},
reset() {
active.clear();
arm();
},
stop() {
active.clear();
disarm();
},
};The idle timer is conservative by design. The module comment says an end event that never arrives keeps the call open rather than risking a pause mid-answer. In that case the call stays open and metered until the heartbeat hits the session deadline. The same data channel also carries other client-to-model items: typed text via sendTextEvent, silent screen context, and subagent progress and milestones. Of these, only typed text and milestones are followed by response.create, so only they prompt the model to speak.