Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
168 changes: 168 additions & 0 deletions apps/api/src/routes/playground-realtime-history.spec.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown> = {}) {
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<string, unknown>,
) {
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");
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});
104 changes: 90 additions & 14 deletions apps/api/src/routes/playground.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down Expand Up @@ -1373,15 +1381,32 @@ 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: {
params: z.object({ id: z.string() }),
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" },
),
},
},
},
Expand All @@ -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" });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -315,7 +315,7 @@ export function CallHistoryList({
onItemClick,
onItemDeleted,
}: CallHistoryListProps) {
const renameItem = useRenameRealtimeHistory();
const renameItem = useUpdateRealtimeHistory();
const deleteItem = useDeleteRealtimeHistory();
const [editingId, setEditingId] = useState<string | null>(null);
const [editTitle, setEditTitle] = useState("");
Expand Down
Loading
Loading