Realtime
Stream live call transcripts over WebSocket and track post-call processing stages over SSE.
ScaleAI provides two realtime hooks that cover the full lifecycle of a call:
| Hook | Transport | When to open |
|---|---|---|
useCallTranscript | WebSocket | Immediately after initiating a call — live audio. |
usePostCallSse | SSE | After the call ends — summary, recording, billing. |
Both hooks require the call session ID returned by useInitiateTelephonyCall or useOriginateSipCall.
Live call transcript
useCallTranscript
Opens a WebSocket connection to the transcript endpoint and accumulates TranscriptMessage frames as they arrive. You control the connection lifecycle with startTranscriptSession and stopTranscriptSession. The hook also closes the socket automatically on unmount.
import { useCallTranscript } from "@scalereal/sr-voice-engine-react-sdk/hooks";
export function LiveTranscript({ callSessionId }: { callSessionId: string }) {
const {
status,
transcripts,
isTyping,
thinkingSide,
startTranscriptSession,
stopTranscriptSession,
} = useCallTranscript({
onCallEnded: () => console.info("Call ended"),
onError: (message) => console.error("Transcript error:", message),
});
return (
<section>
<div>
<button
type="button"
onClick={() => startTranscriptSession(callSessionId)}
disabled={status === "connecting" || status === "connected"}
>
Connect
</button>
<button type="button" onClick={stopTranscriptSession}>
Disconnect
</button>
<span>Status: {status}</span>
</div>
{isTyping && (
<p className="animate-pulse">{thinkingSide} is thinking…</p>
)}
<ul>
{transcripts.map((message, index) => (
<li key={`${message.timestamp}-${index}`}>
<strong>{message.role}:</strong>{" "}
{message.type === "transcript" || message.type === "transcription"
? typeof message.content === "string"
? message.content
: message.content.message
: "[function call]"}
</li>
))}
</ul>
</section>
);
}Connection status
| Value | Meaning |
|---|---|
"idle" | No connection has been opened. |
"connecting" | Socket is being established. |
"connected" | Receiving transcript frames. |
"error" | Connection failed. Call startTranscriptSession to retry. |
Calling startTranscriptSession on a hook that already has transcripts will clear the previous transcript array before connecting. This is intentional — each call session starts fresh.
Return values
| Property | Type | Description |
|---|---|---|
status | "idle" | "connecting" | "connected" | "error" | Current WebSocket connection state. |
transcripts | TranscriptMessage[] | Accumulated frames for the current session. |
thinkingSide | ThinkingSide | null | Which side the system is waiting on ("agent", "user", etc.), or null when idle. |
isTyping | boolean | Shorthand for thinkingSide !== null. Drive a typing indicator with this. |
startTranscriptSession | (callSessionId: string) => void | Opens (or reopens) the WebSocket for the given session. |
stopTranscriptSession | () => void | Closes the socket and resets status to "idle". |
Options
| Option | Type | Description |
|---|---|---|
onCallEnded | () => void | Called when the server signals the call has ended. |
onError | (message: string) => void | Called on socket or server-side errors. |
buildUrl | (callSessionId: string, ctx: { projectId: string; secretKey: string }) => string | Override the WebSocket URL. Useful for proxying. |
createSocket | (url: string) => WebSocket | Override the WebSocket constructor. Useful for testing. |
The WebSocket URL includes the secretKey as a query parameter (?token=…). This is a browser limitation — WebSocket connections cannot carry custom Authorization headers. Use the buildUrl option to route through a server-side proxy if you need to hide credentials from the browser.
Opening the transcript right after a call
Use mutateAsync on the call initiation hook to get the session ID synchronously, then start the transcript in the same handler:
import {
useInitiateTelephonyCall,
useCallTranscript,
} from "@scalereal/sr-voice-engine-react-sdk/hooks";
export function CallWithLiveTranscript({ agentId }: { agentId: string }) {
const initiateCall = useInitiateTelephonyCall();
const transcript = useCallTranscript({
onCallEnded: () => setCallActive(false),
});
const [callActive, setCallActive] = React.useState(false);
const handleStart = async () => {
const session = await initiateCall.mutateAsync({
agent_id: agentId,
destination_number: "+14155552671",
telephony_provider: "twilio",
});
setCallActive(true);
transcript.startTranscriptSession(session.id);
};
return (
<div>
<button type="button" onClick={handleStart} disabled={initiateCall.isPending || callActive}>
Start call
</button>
{callActive && <p>Status: {transcript.status}</p>}
</div>
);
}Post-call processing
usePostCallSse
Opens a Server-Sent Events (SSE) stream after the call ends. The platform processes recordings, generates a summary, calculates billing, and fires webhooks asynchronously. usePostCallSse lets your UI track each stage as it completes.
The hook auto-retries with exponential backoff when the connection drops, up to a maximum retry count. If all retries are exhausted, onFailed is called.
import { usePostCallSse } from "@scalereal/sr-voice-engine-react-sdk/hooks";
export function PostCallDashboard({ callSessionId }: { callSessionId: string | null }) {
const {
stages,
summary,
sentiment,
audioUrl,
finalCharge,
transcript,
isConnected,
} = usePostCallSse({
callSessionId,
onCompleted: () => console.info("All post-call stages done"),
onFailed: (error) => console.error("Post-call SSE failed:", error),
});
return (
<section>
<p>{isConnected ? "Processing…" : "Awaiting connection"}</p>
<ul>
<li>Summary: {stages.summary_done ? summary ?? "—" : "Pending"}</li>
<li>Recording: {stages.recording_done ? <a href={audioUrl ?? "#"}>Listen</a> : "Pending"}</li>
<li>Billing: {stages.billing_done ? `${finalCharge} credits` : "Pending"}</li>
<li>Structured output: {stages.structured_output_done ? "Done" : "Pending"}</li>
<li>Webhooks: {stages.webhook_done ? "Fired" : "Pending"}</li>
</ul>
{sentiment && <p>Sentiment: {sentiment}</p>}
</section>
);
}Options
| Option | Type | Description |
|---|---|---|
callSessionId | string | null | Required. The call session to monitor. Pass null to keep the hook idle. |
enabled | boolean | Set to false to prevent or close the stream without unmounting. Optional. |
onCompleted | () => void | Called when the post_call.completed event arrives — all stages are done. |
onFailed | (error: string) => void | Called after max retries or when a post_call.failed event arrives. |
buildUrl | (callSessionId: string) => string | Override the SSE endpoint URL. Optional. |
Return values
| Property | Type | Description |
|---|---|---|
stages | PostCallStages | Map of pipeline stage names to completion booleans (see below). |
summary | string | null | AI-generated call summary. Available when stages.summary_done is true. |
sentiment | "positive" | "negative" | "neutral" | null | Sentiment classification of the call. |
audioUrl | string | null | Recording download URL. Available when stages.recording_done is true. |
finalCharge | string | null | Decimal-string credit amount billed for the call. Available when stages.billing_done. |
transcript | TranscriptMessage[] | null | Full transcript snapshot when the recording is done. |
transferLegBilling | { status: TransferLegBillingStatus | null; fullyBilled: boolean | null } | Billing state for transferred call legs. |
isConnected | boolean | Whether the SSE stream is currently open. |
Processing stages — PostCallStages
| Stage key | Description |
|---|---|
summary_done | AI summary has been generated. |
structured_output_done | Structured output extraction is complete. |
usage_done | Usage/token metrics have been recorded. |
recording_done | Call recording is ready. audioUrl is now set. |
webhook_done | Configured outbound webhooks have fired. |
call_session_done | The call session record has been finalized. |
billing_done | Credits have been deducted. finalCharge is now set. |
End-to-end flow
The following pattern covers the full lifecycle from initiating a call to tracking post-call processing:
import React from "react";
import {
useInitiateTelephonyCall,
useCallTranscript,
usePostCallSse,
} from "@scalereal/sr-voice-engine-react-sdk/hooks";
type CallPhase = "idle" | "live" | "post-call" | "done";
export function FullCallFlow({ agentId }: { agentId: string }) {
const [phase, setPhase] = React.useState<CallPhase>("idle");
const [sessionId, setSessionId] = React.useState<string | null>(null);
const initiateCall = useInitiateTelephonyCall();
// 1. Live transcript — open immediately after call starts
const transcript = useCallTranscript({
onCallEnded: () => {
transcript.stopTranscriptSession();
setPhase("post-call");
},
});
// 2. Post-call SSE — enabled only when the call has ended
const postCall = usePostCallSse({
callSessionId: phase === "post-call" ? sessionId : null,
onCompleted: () => setPhase("done"),
});
const handleStart = async () => {
const session = await initiateCall.mutateAsync({
agent_id: agentId,
destination_number: "+14155552671",
telephony_provider: "twilio",
});
setSessionId(session.id);
setPhase("live");
transcript.startTranscriptSession(session.id);
};
return (
<div>
{phase === "idle" && (
<button type="button" onClick={handleStart} disabled={initiateCall.isPending}>
Start call
</button>
)}
{phase === "live" && <p>Live — {transcript.status}</p>}
{phase === "post-call" && <p>Processing: {JSON.stringify(postCall.stages)}</p>}
{phase === "done" && <p>Summary: {postCall.summary}</p>}
</div>
);
}Related pages
- Calls — Initiate telephony and SIP calls to get a session ID.
- Call History — Query past sessions and their metadata.
- Components — Pre-built
TranscriptViewand related UI components. - Types —
TranscriptMessage,PostCallStages,ThinkingSide, and other type definitions.