diff --git a/apps/api/src/routes/playground-realtime-history.spec.ts b/apps/api/src/routes/playground-realtime-history.spec.ts new file mode 100644 index 0000000000..d7704c767e --- /dev/null +++ b/apps/api/src/routes/playground-realtime-history.spec.ts @@ -0,0 +1,168 @@ +import { afterEach, beforeEach, describe, expect, test } from "vitest"; + +import { app } from "@/index.js"; +import { createTestUser, deleteAll } from "@/testing.js"; + +import { db, tables } from "@llmgateway/db"; + +const usage = { + responses: 2, + inputTokens: 100, + outputTokens: 40, + totalTokens: 140, + audioInputTokens: 60, + audioOutputTokens: 30, +}; + +function turn(text: string, role: "user" | "assistant" = "user") { + return { role, text, status: "final" as const, timestamp: 1_700_000_000_000 }; +} + +async function createCall(token: string, body: Record = {}) { + const res = await app.request("/playground/realtime-history", { + method: "POST", + headers: { "Content-Type": "application/json", Cookie: token }, + body: JSON.stringify({ + title: "Test call", + model: "openai/gpt-realtime", + durationSeconds: 30, + transcript: [turn("hello"), turn("hi there", "assistant")], + usage, + ...body, + }), + }); + expect(res.status).toBe(201); + const json = await res.json(); + return json.item as { id: string; turnCount: number }; +} + +async function patchCall( + token: string, + id: string, + body: Record, +) { + return await app.request(`/playground/realtime-history/${id}`, { + method: "PATCH", + headers: { "Content-Type": "application/json", Cookie: token }, + body: JSON.stringify(body), + }); +} + +describe("playground realtime history", () => { + let token: string; + + beforeEach(async () => { + token = await createTestUser(); + }); + + afterEach(async () => { + await deleteAll(); + }); + + test("round-trips assistant audio on a transcript entry", async () => { + const audio = { base64: "UklGRgAAAABXQVZF", mediaType: "audio/wav" }; + const item = await createCall(token, { + transcript: [turn("hello"), { ...turn("hi", "assistant"), audio }], + }); + + const res = await app.request(`/playground/realtime-history/${item.id}`, { + headers: { Cookie: token }, + }); + expect(res.status).toBe(200); + const json = await res.json(); + expect(json.item.transcript[0].audio).toBeUndefined(); + expect(json.item.transcript[1].audio).toEqual(audio); + }); + + test("PATCH renames without touching the transcript", async () => { + const item = await createCall(token); + + const res = await patchCall(token, item.id, { title: "Renamed" }); + expect(res.status).toBe(200); + const json = await res.json(); + expect(json.item.title).toBe("Renamed"); + expect(json.item.turnCount).toBe(2); + expect(json.item.durationSeconds).toBe(30); + }); + + test("PATCH appends turns and sums duration and usage", async () => { + const item = await createCall(token); + + const res = await patchCall(token, item.id, { + appendTranscript: [turn("and again"), turn("sure", "assistant")], + addDurationSeconds: 12, + addUsage: usage, + }); + expect(res.status).toBe(200); + const json = await res.json(); + expect(json.item.turnCount).toBe(4); + expect(json.item.durationSeconds).toBe(42); + + const row = await db.query.playgroundRealtimeHistory.findFirst({ + where: { id: { eq: item.id } }, + }); + expect(row?.transcript.map((entry) => entry.text)).toEqual([ + "hello", + "hi there", + "and again", + "sure", + ]); + expect(row?.usage).toEqual({ + responses: 4, + inputTokens: 200, + outputTokens: 80, + totalTokens: 280, + audioInputTokens: 120, + audioOutputTokens: 60, + }); + }); + + test("PATCH sums usage onto a call that had none", async () => { + const item = await createCall(token, { usage: undefined }); + + const res = await patchCall(token, item.id, { addUsage: usage }); + expect(res.status).toBe(200); + + const row = await db.query.playgroundRealtimeHistory.findFirst({ + where: { id: { eq: item.id } }, + }); + expect(row?.usage).toEqual(usage); + }); + + // A no-op body would otherwise reach Drizzle as an empty .set(), which throws. + test("PATCH rejects an empty body", async () => { + const item = await createCall(token); + const res = await patchCall(token, item.id, {}); + expect(res.status).toBe(400); + }); + + test("PATCH 404s on a call the user does not own", async () => { + const missing = await patchCall(token, "does-not-exist", { title: "Nope" }); + expect(missing.status).toBe(404); + + // Another user's existing call must look identical to a missing one. + await db.insert(tables.user).values({ + id: "other-user-id", + name: "Other User", + email: "other@example.com", + emailVerified: true, + }); + const [theirs] = await db + .insert(tables.playgroundRealtimeHistory) + .values({ + userId: "other-user-id", + title: "Their call", + model: "openai/gpt-realtime", + transcript: [turn("their message")], + }) + .returning({ id: tables.playgroundRealtimeHistory.id }); + + const res = await patchCall(token, theirs.id, { title: "Nope" }); + expect(res.status).toBe(404); + + const row = await db.query.playgroundRealtimeHistory.findFirst({ + where: { id: { eq: theirs.id } }, + }); + expect(row?.title).toBe("Their call"); + }); +}); diff --git a/apps/api/src/routes/playground.ts b/apps/api/src/routes/playground.ts index ebc465537b..ce6f980b8b 100644 --- a/apps/api/src/routes/playground.ts +++ b/apps/api/src/routes/playground.ts @@ -1142,6 +1142,14 @@ const realtimeTranscriptEntrySchema = z.object({ text: z.string(), status: z.enum(["partial", "final", "interrupted"]), timestamp: z.number(), + // Assistant speech for the turn as a base64 WAV, so a saved call can be + // listened to and not just read. + audio: z + .object({ + base64: z.string().max(48_000_000), + mediaType: z.literal("audio/wav"), + }) + .optional(), }); const realtimeUsageSchema = z.object({ @@ -1373,7 +1381,10 @@ playground.openapi(saveRealtimeHistory, async (c) => { // ── PATCH /realtime-history/:id ────────────────────────────────────────────── -const renameRealtimeHistory = createRoute({ +// Renames a call, and/or grows it with the turns of a continued session: a +// resumed call appends to the row it continued rather than starting a new one, +// so one conversation stays one history entry. +const updateRealtimeHistory = createRoute({ method: "patch", path: "/realtime-history/{id}", request: { @@ -1381,7 +1392,21 @@ const renameRealtimeHistory = createRoute({ body: { content: { "application/json": { - schema: z.object({ title: z.string().trim().min(1).max(200) }), + schema: z + .object({ + title: z.string().trim().min(1).max(200).optional(), + appendTranscript: z + .array(realtimeTranscriptEntrySchema) + .min(1) + .optional(), + addDurationSeconds: z.number().int().min(0).optional(), + addUsage: realtimeUsageSchema.optional(), + }) + .refine( + (body) => + Object.values(body).some((value) => value !== undefined), + { message: "At least one field must be provided" }, + ), }, }, }, @@ -1398,25 +1423,76 @@ const renameRealtimeHistory = createRoute({ }, }); -playground.openapi(renameRealtimeHistory, async (c) => { +playground.openapi(updateRealtimeHistory, async (c) => { const user = c.get("user"); if (!user) { throw new HTTPException(401, { message: "Unauthorized" }); } const { id } = c.req.valid("param"); - const { title } = c.req.valid("json"); + const body = c.req.valid("json"); - const [row] = await db - .update(tables.playgroundRealtimeHistory) - .set({ title }) - .where( - and( - eq(tables.playgroundRealtimeHistory.id, id), - eq(tables.playgroundRealtimeHistory.userId, user.id), - ), - ) - .returning(); + // Appending needs the current transcript/duration/usage, so this is a + // read-modify-write. The row lock serializes two continuations of the same + // call finishing at once (e.g. from two tabs), so the later one appends to + // the earlier one's result instead of overwriting it from a stale read. + const row = await db.transaction(async (tx) => { + const [existing] = await tx + .select() + .from(tables.playgroundRealtimeHistory) + .where( + and( + eq(tables.playgroundRealtimeHistory.id, id), + eq(tables.playgroundRealtimeHistory.userId, user.id), + ), + ) + .for("update"); + + if (!existing) { + throw new HTTPException(404, { message: "Not found" }); + } + + const addUsage = body.addUsage; + const previousUsage = existing.usage; + + const [updated] = await tx + .update(tables.playgroundRealtimeHistory) + .set({ + ...(body.title !== undefined ? { title: body.title } : {}), + ...(body.appendTranscript + ? { transcript: [...existing.transcript, ...body.appendTranscript] } + : {}), + ...(body.addDurationSeconds !== undefined + ? { + durationSeconds: + existing.durationSeconds + body.addDurationSeconds, + } + : {}), + ...(addUsage + ? { + usage: { + responses: (previousUsage?.responses ?? 0) + addUsage.responses, + inputTokens: + (previousUsage?.inputTokens ?? 0) + addUsage.inputTokens, + outputTokens: + (previousUsage?.outputTokens ?? 0) + addUsage.outputTokens, + totalTokens: + (previousUsage?.totalTokens ?? 0) + addUsage.totalTokens, + audioInputTokens: + (previousUsage?.audioInputTokens ?? 0) + + addUsage.audioInputTokens, + audioOutputTokens: + (previousUsage?.audioOutputTokens ?? 0) + + addUsage.audioOutputTokens, + }, + } + : {}), + }) + .where(eq(tables.playgroundRealtimeHistory.id, existing.id)) + .returning(); + + return updated; + }); if (!row) { throw new HTTPException(404, { message: "Not found" }); diff --git a/apps/playground/src/components/playground/call-history-list.tsx b/apps/playground/src/components/playground/call-history-list.tsx index 96e3d73938..4739c1fd4a 100644 --- a/apps/playground/src/components/playground/call-history-list.tsx +++ b/apps/playground/src/components/playground/call-history-list.tsx @@ -14,7 +14,7 @@ import { Input } from "@/components/ui/input"; import { SidebarMenuAction, SidebarMenuButton } from "@/components/ui/sidebar"; import { useDeleteRealtimeHistory, - useRenameRealtimeHistory, + useUpdateRealtimeHistory, } from "@/hooks/usePlaygroundHistory"; import { formatCallDuration } from "@/lib/call-history"; @@ -315,7 +315,7 @@ export function CallHistoryList({ onItemClick, onItemDeleted, }: CallHistoryListProps) { - const renameItem = useRenameRealtimeHistory(); + const renameItem = useUpdateRealtimeHistory(); const deleteItem = useDeleteRealtimeHistory(); const [editingId, setEditingId] = useState(null); const [editTitle, setEditTitle] = useState(""); diff --git a/apps/playground/src/components/playground/realtime-page-client.tsx b/apps/playground/src/components/playground/realtime-page-client.tsx index 991b7eb566..5de698d303 100644 --- a/apps/playground/src/components/playground/realtime-page-client.tsx +++ b/apps/playground/src/components/playground/realtime-page-client.tsx @@ -1,11 +1,20 @@ "use client"; -import { Mic, MicOff, Phone, PhoneOff } from "lucide-react"; +import { + Mic, + MicOff, + Phone, + PhoneForwarded, + PhoneOff, + Play, + Square, +} from "lucide-react"; import { usePathname, useRouter, useSearchParams } from "next/navigation"; import { usePostHog } from "posthog-js/react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { toast } from "sonner"; +import { Action, Actions } from "@/components/ai-elements/actions"; import { ModelSelector } from "@/components/model-selector"; import { AuthDialog } from "@/components/playground/auth-dialog"; import { RealtimeSidebar } from "@/components/playground/realtime-sidebar"; @@ -22,12 +31,14 @@ import { import { SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar"; import { useRealtimeCall, + type RealtimeTranscriptEntry, type RealtimeCallStatus, } from "@/hooks/use-realtime-call"; import { useRealtimeHistory, useRealtimeHistoryItem, useSaveRealtimeHistory, + useUpdateRealtimeHistory, } from "@/hooks/usePlaygroundHistory"; import { useUser } from "@/hooks/useUser"; import { deriveCallTitle, formatCallDuration } from "@/lib/call-history"; @@ -36,6 +47,7 @@ import { REALTIME_MODEL_COOKIE, setModelPreferenceCookie, } from "@/lib/model-preferences"; +import { base64ToBytes } from "@/lib/realtime-audio"; import { cn } from "@/lib/utils"; import type { ApiModel, ApiProvider } from "@/lib/fetch-models"; @@ -62,6 +74,18 @@ const STATUS_LABELS: Record = { ending: "Ending…", }; +/** + * Replayed turns are re-sent to the model as conversation items, so a long + * thread costs input tokens on the first response of the continued call. + * Past either threshold the user gets a heads-up rather than a surprise bill. + */ +const REPLAY_TURN_WARNING = 20; +const REPLAY_CHAR_WARNING = 8000; +/** Marks a turn that came from the continued call rather than this session. */ +const SEED_ID_PREFIX = "seed-"; +/** How close to the bottom still counts as "following" the live transcript. */ +const FOLLOW_TRANSCRIPT_THRESHOLD_PX = 64; + /** * Restrict the catalogue to models that have at least one active realtime * mapping, and copy each surviving model with only those mappings so the @@ -182,6 +206,7 @@ export default function RealtimePageClient({ selectedOrganization?.id, ); const { mutate: saveCallHistory } = useSaveRealtimeHistory(); + const { mutate: updateCallHistory } = useUpdateRealtimeHistory(); const [viewedCallId, setViewedCallId] = useState(null); const { data: viewedCallData, isLoading: isViewedCallLoading } = useRealtimeHistoryItem(inCall ? null : viewedCallId); @@ -191,6 +216,9 @@ export default function RealtimePageClient({ // deliberately does not store conversation content. const savedCallRef = useRef(false); const previousStatusRef = useRef("idle"); + // Set while this session continues a saved call: its turns are appended to + // that row instead of starting a second history entry. + const continuedCallIdRef = useRef(null); // Latest-ref so the unmount cleanup below saves current (not first-render) // call state. const persistCallRef = useRef<() => void>(() => {}); @@ -202,27 +230,68 @@ export default function RealtimePageClient({ if (spoken.length === 0 || !selectedModel) { return; } + const continuedCallId = continuedCallIdRef.current; + // Upstream item ids are dropped: they identify a session that no longer + // exists and are not needed to replay the conversation. + const toEntry = (entry: RealtimeTranscriptEntry) => ({ + role: entry.role, + text: entry.text, + status: entry.status, + timestamp: entry.timestamp, + ...(entry.audio ? { audio: entry.audio } : {}), + }); + + if (continuedCallId) { + // Replayed turns are already stored on the row being continued. + const newTurns = spoken.filter( + (entry) => !entry.id.startsWith(SEED_ID_PREFIX), + ); + if (newTurns.length === 0) { + // Nothing new was said, so there is nothing to append — but the + // session still belongs to that call, and leaving it deselected would + // hide both its header and the button to continue it again. + setViewedCallId(continuedCallId); + return; + } + savedCallRef.current = true; + // Duration and usage are session-only counters; the server adds them + // to what the row already holds. + updateCallHistory( + { + params: { path: { id: continuedCallId } }, + body: { + appendTranscript: newTurns.map(toEntry), + addDurationSeconds: elapsedSeconds, + addUsage: usage, + }, + }, + // Reopen the call so its summary header is there as soon as the call + // ends, instead of only after picking it out of the sidebar. Settled + // rather than success: a failed append still has to return the user + // to the call they were on. The hook seeds the detail cache before + // this runs, so the reopen reads from memory without a loading flash. + { onSettled: () => setViewedCallId(continuedCallId) }, + ); + return; + } + savedCallRef.current = true; - saveCallHistory({ - body: { - title: deriveCallTitle(spoken), - model: selectedModel, - durationSeconds: elapsedSeconds, - // Upstream item ids are dropped: they identify a session that no - // longer exists and are not needed to replay the conversation. - transcript: spoken.map((entry) => ({ - role: entry.role, - text: entry.text, - status: entry.status, - timestamp: entry.timestamp, - })), - usage, - ...(voice ? { voice } : {}), - ...(selectedOrganization?.id - ? { organizationId: selectedOrganization.id } - : {}), + saveCallHistory( + { + body: { + title: deriveCallTitle(spoken), + model: selectedModel, + durationSeconds: elapsedSeconds, + transcript: spoken.map(toEntry), + usage, + ...(voice ? { voice } : {}), + ...(selectedOrganization?.id + ? { organizationId: selectedOrganization.id } + : {}), + }, }, - }); + { onSuccess: (data) => setViewedCallId(data.item.id) }, + ); }; useEffect(() => { const previous = previousStatusRef.current; @@ -261,6 +330,7 @@ export default function RealtimePageClient({ role: entry.role, text: entry.text, status: entry.status, + audio: entry.audio, })); } return transcript.map((entry) => ({ @@ -268,9 +338,96 @@ export default function RealtimePageClient({ role: entry.role, text: entry.text, status: entry.status, + audio: entry.audio, })); }, [isViewingHistory, transcript, viewedCall]); + // One clip plays at a time, decoded into a blob URL on demand so the base64 + // WAVs are not eagerly turned into objects for every turn on screen. + const [playingKey, setPlayingKey] = useState(null); + const audioElementRef = useRef(null); + const blobUrlRef = useRef(null); + + const stopPlayback = useCallback(() => { + const element = audioElementRef.current; + audioElementRef.current = null; + if (element) { + // Detached first so a late "ended" from the outgoing clip cannot clear + // the state of the one replacing it. + element.onended = null; + element.pause(); + } + if (blobUrlRef.current) { + URL.revokeObjectURL(blobUrlRef.current); + blobUrlRef.current = null; + } + setPlayingKey(null); + }, []); + + const playTurnAudio = useCallback( + (key: string, base64: string) => { + stopPlayback(); + const url = URL.createObjectURL( + new Blob([base64ToBytes(base64)], { type: "audio/wav" }), + ); + blobUrlRef.current = url; + const element = new Audio(url); + audioElementRef.current = element; + element.onended = stopPlayback; + setPlayingKey(key); + void element.play().catch(() => { + toast.error("Could not play this turn."); + stopPlayback(); + }); + }, + [stopPlayback], + ); + + // Whatever is playing belongs to the turns on screen: opening another call, + // closing one, or starting a new call invalidates it — as does unmounting. + useEffect(() => { + return () => { + stopPlayback(); + }; + }, [inCall, stopPlayback, viewedCallId]); + + // A turn's audio is attached at response.done, while the live scheduler is + // often still draining the tail of that same speech. Replaying it then would + // play the response over itself, so manual playback yields to the call. + useEffect(() => { + if (assistantSpeaking) { + stopPlayback(); + } + }, [assistantSpeaking, stopPlayback]); + + const transcriptScrollRef = useRef(null); + const followTranscriptRef = useRef(true); + + const handleTranscriptScroll = useCallback( + (event: React.UIEvent) => { + const element = event.currentTarget; + followTranscriptRef.current = + element.scrollHeight - element.scrollTop - element.clientHeight < + FOLLOW_TRANSCRIPT_THRESHOLD_PX; + }, + [], + ); + + // Each conversation opens pinned to its newest turn, regardless of where the + // previous one was left scrolled. + useEffect(() => { + followTranscriptRef.current = true; + }, [inCall, viewedCallId]); + + // Follow the live transcript only while the user is already at the bottom, so + // scrolling back to re-read or replay an earlier turn is not yanked away. + useEffect(() => { + const element = transcriptScrollRef.current; + if (element && followTranscriptRef.current) { + element.scrollTop = element.scrollHeight; + } + }, [displayedTurns]); + const displayedUsage = isViewingHistory ? viewedCall?.usage : usage.responses > 0 || inCall @@ -288,10 +445,17 @@ export default function RealtimePageClient({ [inCall], ); + // Also reachable from the sidebar mid-call, where clearing the continued-call + // link would silently strand the live session's turns in a new history row. const handleNewCall = useCallback(() => { + if (inCall) { + toast.error("End the current call before starting a new one."); + return; + } + continuedCallIdRef.current = null; setViewedCallId(null); reset(); - }, [reset]); + }, [inCall, reset]); const handleCallDeleted = useCallback((itemId: string) => { setViewedCallId((current) => (current === itemId ? null : current)); @@ -356,10 +520,58 @@ export default function RealtimePageClient({ voice, }); savedCallRef.current = false; + continuedCallIdRef.current = null; setViewedCallId(null); start(); }, [posthog, selectedModel, start, voice]); + // Reopen a saved call as a live one: its turns are replayed to the model as + // conversation items and the new turns are appended back onto the same row. + const handleContinueCall = useCallback(() => { + if (!viewedCall || !selectedModel) { + return; + } + const seed: RealtimeTranscriptEntry[] = viewedCall.transcript + .filter( + (entry) => entry.status !== "partial" && entry.text.trim().length > 0, + ) + .map((entry, index) => ({ + id: `${SEED_ID_PREFIX}${index}`, + role: entry.role, + text: entry.text, + status: entry.status, + timestamp: entry.timestamp, + ...(entry.audio ? { audio: entry.audio } : {}), + })); + if (seed.length === 0) { + toast.error("This call has no completed turns to continue from."); + return; + } + if (selectedModel !== viewedCall.model) { + toast.warning( + `Continuing with ${selectedModel} — this call was recorded on ${viewedCall.model}.`, + ); + } + const totalChars = seed.reduce( + (total, entry) => total + entry.text.length, + 0, + ); + if (seed.length > REPLAY_TURN_WARNING || totalChars > REPLAY_CHAR_WARNING) { + toast.warning( + `Replaying ${seed.length} turns — the first response will bill the whole conversation as input tokens.`, + ); + } + posthog.capture("playground_realtime_call_continued", { + model: selectedModel, + voice, + turns: seed.length, + }); + savedCallRef.current = false; + continuedCallIdRef.current = viewedCall.id; + setViewedCallId(null); + start(seed); + }, [posthog, selectedModel, start, viewedCall, voice]); + const hasBillingContext = !!selectedOrganization && !!selectedProject; const isIdleEmptyState = !inCall && !isViewingHistory && displayedTurns.length === 0; @@ -441,7 +653,7 @@ export default function RealtimePageClient({
@@ -472,77 +684,129 @@ export default function RealtimePageClient({
) : ( <> + {/* Only the transcript scrolls: the call controls below stay + on screen no matter how long the conversation gets. */}
- {isViewingHistory && viewedCall && ( -
- - {viewedCall.title} - - - {new Date(viewedCall.createdAt).toLocaleString()} - - - {formatCallDuration(viewedCall.durationSeconds)} - - - {viewedCall.model} - {viewedCall.voice ? ` · ${viewedCall.voice}` : ""} - - -
- )} - {displayedTurns.length === 0 ? ( -
- -

- {isViewedCallLoading - ? "Loading transcript…" - : inCall - ? "Say something — the transcript appears here." - : "Start a call to have a live voice conversation."} -

-
- ) : ( -
- {displayedTurns.map((turn) => ( -
+ {isViewingHistory && viewedCall && ( +
+ + {viewedCall.title} + + + {new Date(viewedCall.createdAt).toLocaleString()} + + + {formatCallDuration(viewedCall.durationSeconds)} + + + {viewedCall.model} + {viewedCall.voice ? ` · ${viewedCall.voice}` : ""} + +
- ))} -
- )} + Close + +
+ )} + {displayedTurns.length === 0 ? ( +
+ +

+ {isViewedCallLoading + ? "Loading transcript…" + : inCall + ? "Say something — the transcript appears here." + : "Start a call to have a live voice conversation."} +

+
+ ) : ( +
+ {displayedTurns.map((turn) => { + const audio = turn.audio; + const isPlaying = playingKey === turn.key; + return ( +
+
+ {turn.text || "…"} + {turn.status === "interrupted" && ( + + (interrupted) + + )} +
+ {audio && ( + + + isPlaying + ? stopPlayback() + : playTurnAudio(turn.key, audio.base64) + } + label={isPlaying ? "Stop" : "Play"} + tooltip={ + assistantSpeaking + ? "Wait for the assistant to finish" + : isPlaying + ? "Stop playback" + : "Play this response" + } + > + {isPlaying ? ( + + ) : ( + + )} + + + )} +
+ ); + })} +
+ )} +
-
+
{status === "live" && (
{!inCall ? ( - + <> + + {isViewingHistory && ( + + )} + ) : ( <>