Skip to content

Commit 70886ed

Browse files
committed
chore(drift): fold gemini-live-servercontent into this change
2 parents 7a95e71 + 4e77a82 commit 70886ed

6 files changed

Lines changed: 543 additions & 18 deletions

File tree

‎src/__tests__/drift/helpers.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,38 @@ export const AUDIO_FIXTURE: Fixture = {
177177
/** The prompt that selects {@link AUDIO_FIXTURE} on both sides of a drift leg. */
178178
export const AUDIO_PROMPT = "Greet me aloud";
179179

180+
/**
181+
* Tool-call fixture for the Gemini Live drift leg.
182+
*
183+
* A Live session carries exactly ONE response modality and it is `AUDIO`, so a
184+
* turn in which the model calls a function is an AUDIO turn that ALSO calls it:
185+
* the model speaks (`serverContent`) and then asks for the call (`toolCall`).
186+
* The shared {@link TOOL_FIXTURE} describes a text-protocol tool turn — tool
187+
* call and nothing else — so driving the Live leg's mock side with it produces
188+
* a bare `toolCall` with no model turn at all.
189+
*
190+
* That mis-drive is what run 31896605497's head report recorded as
191+
* `SSE:serverContent … mock:"<absent>"`, and the ORDER in it is not a guess: the
192+
* probe collects up to and including the FIRST `toolCall`, the real leg's
193+
* `toolCallCount > 0` assertion passed, and a `serverContent` was nonetheless
194+
* present in what it collected — so the provider sent `serverContent` strictly
195+
* BEFORE the `toolCall`. It is the same class of error as the TEXT-modality
196+
* request that mis-drove the REAL side: one side driven into a shape the
197+
* session's modality cannot produce.
198+
*
199+
* NOT PROVEN: the fields of the provider's pre-`toolCall` `serverContent`. The
200+
* artifact records the event TYPE only. `AUDIO` being the session's sole
201+
* modality, audio parts are the shape reproduced here; confirming the
202+
* provider's exact fields needs a live run.
203+
*/
204+
export const LIVE_TOOL_FIXTURE: Fixture = {
205+
match: { userMessage: "Weather in Paris" },
206+
response: {
207+
audio: { b64Json: "AAAAAA==", contentType: "audio/pcm;rate=24000" },
208+
toolCalls: [{ name: "get_weather", arguments: '{"city":"Paris"}' }],
209+
},
210+
};
211+
180212
// ---------------------------------------------------------------------------
181213
// Server lifecycle
182214
// ---------------------------------------------------------------------------
@@ -188,6 +220,22 @@ export async function startDriftServer(): Promise<ServerInstance> {
188220
});
189221
}
190222

223+
/**
224+
* Drift server for the Gemini Live legs.
225+
*
226+
* Separate from {@link startDriftServer} because the Live leg's fixtures are
227+
* modality-specific: {@link LIVE_TOOL_FIXTURE} answers the same
228+
* `"Weather in Paris"` prompt as the shared {@link TOOL_FIXTURE} but with the
229+
* AUDIO turn a Live session actually produces. Putting it on the shared server
230+
* would mean either shadowing `TOOL_FIXTURE` for every other provider's tool
231+
* leg or gating it on a model-name pattern — and a Live model is not
232+
* identifiable by its name (see the header of ws-gemini-live.drift.ts). A
233+
* dedicated instance needs neither.
234+
*/
235+
export async function startGeminiLiveDriftServer(): Promise<ServerInstance> {
236+
return createServer([AUDIO_FIXTURE, LIVE_TOOL_FIXTURE], { port: 0, chunkSize: 100 });
237+
}
238+
191239
export async function stopDriftServer(instance: ServerInstance): Promise<void> {
192240
await new Promise<void>((r) => instance.server.close(() => r()));
193241
}

‎src/__tests__/drift/sdk-shapes.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1252,6 +1252,32 @@ export function geminiLiveAudioEventShapes(): SSEEventShape[] {
12521252

12531253
export function geminiLiveToolCallEventShapes(): SSEEventShape[] {
12541254
return [
1255+
// The model turn that precedes the call. A Live session carries exactly one
1256+
// response modality and it is AUDIO, so the turn in which the model decides
1257+
// to call a function is itself an audio turn — `serverContent` and
1258+
// `toolCall` are alternatives of `LiveServerMessage`'s message union, so
1259+
// they arrive as two messages, `serverContent` first.
1260+
//
1261+
// Listing it here is what lets the leg grade the event's FIELDS and not
1262+
// merely its presence: `triangulateAt` raises critical drift only for a
1263+
// field the SDK shape and the real API both have and the mock lacks, so
1264+
// without a `serverContent` entry a field-level regression on it could
1265+
// never be critical.
1266+
//
1267+
// NOT PROVEN: that the provider's pre-`toolCall` `serverContent` carries
1268+
// inlineData audio specifically. The drift artifact records the event type
1269+
// only. A field the real API turns out not to send grades as `SDK EXTRA`
1270+
// (info), never as a false critical.
1271+
{
1272+
type: "serverContent",
1273+
dataShape: extractShape({
1274+
serverContent: {
1275+
modelTurn: {
1276+
parts: [{ inlineData: { mimeType: "audio/pcm;rate=24000", data: "AAAAAA==" } }],
1277+
},
1278+
},
1279+
}),
1280+
},
12551281
{
12561282
type: "toolCall",
12571283
dataShape: extractShape({

‎src/__tests__/drift/ws-gemini-live-modality.test.ts‎

Lines changed: 240 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,14 @@
3232
* NOT PROVEN HERE: that the live endpoint accepts `["AUDIO"]` and emits this
3333
* exact sequence. That is established from Google's published capabilities guide
3434
* and can only be confirmed by a live run with a real GOOGLE_API_KEY.
35+
*
36+
* THE SAME MIS-DRIVE, ON THE OTHER SIDE. Once the real side was asking for a
37+
* modality the model serves, the tool-call leg reported that the provider emits
38+
* `serverContent` and the mock does not — because the MOCK side was still being
39+
* driven by a text-shaped tool fixture into a bare `toolCall` with no model turn.
40+
* The final section of this file holds that down end to end, with the fake
41+
* provider emitting the tool turn in the order the live artifact proves it used
42+
* (`serverContent` strictly before `toolCall`).
3543
*/
3644
import { describe, it, expect, beforeAll, afterAll } from "vitest";
3745
import * as tls from "node:tls";
@@ -50,9 +58,14 @@ import {
5058
WSClosedError,
5159
} from "./ws-providers.js";
5260
import { extractShape, compareSSESequences } from "./schema.js";
53-
import { geminiLiveSetupCompleteShape, geminiLiveAudioEventShapes } from "./sdk-shapes.js";
61+
import {
62+
geminiLiveSetupCompleteShape,
63+
geminiLiveAudioEventShapes,
64+
geminiLiveToolCallEventShapes,
65+
} from "./sdk-shapes.js";
5466
import {
5567
startDriftServer,
68+
startGeminiLiveDriftServer,
5669
stopDriftServer,
5770
collectMockWSMessages,
5871
GEMINI_WS_PATH,
@@ -240,6 +253,29 @@ function startFakeProvider(options: FakeProviderOptions = {}): Promise<FakeProvi
240253
// OTHER cause a zero-message live failure can have.
241254
if (options.muteAfterSetup) return;
242255
if (hasTools) {
256+
// A Live tool turn is an AUDIO turn that ALSO calls the function:
257+
// the model speaks, THEN asks for the call, as two messages
258+
// (`serverContent` and `toolCall` are alternatives of one union
259+
// on `LiveServerMessage`, never combined).
260+
//
261+
// The ORDER is recovered from the live drift artifact, not
262+
// invented: the probe collects up to and including the FIRST
263+
// `toolCall`, the leg's `toolCallCount > 0` assertion passed, and
264+
// a `serverContent` was present in what it collected — so the
265+
// provider sent `serverContent` strictly BEFORE the `toolCall`.
266+
// The old fake sent a bare `toolCall`, which modelled the MOCK's
267+
// bug rather than the provider, and so could not reproduce it.
268+
conn.send(
269+
JSON.stringify({
270+
serverContent: {
271+
modelTurn: {
272+
parts: [
273+
{ inlineData: { mimeType: "audio/pcm;rate=24000", data: "AAAAAA==" } },
274+
],
275+
},
276+
},
277+
}),
278+
);
243279
conn.send(
244280
JSON.stringify({
245281
toolCall: {
@@ -306,15 +342,35 @@ async function withProvider<T>(
306342
}
307343

308344
/** Drive the REAL probe against the fake provider. */
309-
function probe(provider: FakeProvider, tools?: object[], waitMs?: number) {
310-
return geminiLiveWS({ apiKey: "fake-key" }, "Greet me aloud", tools, OBSERVED_MODEL, {
345+
function probe(provider: FakeProvider, tools?: object[], waitMs?: number, prompt = AUDIO_PROMPT) {
346+
return geminiLiveWS({ apiKey: "fake-key" }, prompt, tools, OBSERVED_MODEL, {
311347
host: "localhost",
312348
port: provider.port,
313349
ca: cert,
314350
waitMs,
315351
});
316352
}
317353

354+
/** The `functionDeclarations` the live tool-call leg declares, verbatim. */
355+
const WEATHER_TOOLS = [
356+
{
357+
functionDeclarations: [
358+
{
359+
name: "get_weather",
360+
description: "Get weather",
361+
parameters: {
362+
type: "object",
363+
properties: { city: { type: "string" } },
364+
required: ["city"],
365+
},
366+
},
367+
],
368+
},
369+
];
370+
371+
/** The prompt the live tool-call leg sends, verbatim. */
372+
const TOOL_PROMPT = "Weather in Paris";
373+
318374
// ---------------------------------------------------------------------------
319375
// The reproduction: what the live endpoint did to a TEXT request
320376
// ---------------------------------------------------------------------------
@@ -673,3 +729,184 @@ describe("three-way AUDIO comparison: sdk shapes × provider turn × aimock", ()
673729
expect(critical.map((d) => d.path).join(" ")).toContain("inlineData");
674730
});
675731
});
732+
733+
// ---------------------------------------------------------------------------
734+
// The TOOL turn, run locally end to end
735+
// ---------------------------------------------------------------------------
736+
//
737+
// Run 31896605497's head drift report carried exactly one Gemini Live diff, on
738+
// the TOOL-CALL leg (the audio leg graded clean):
739+
//
740+
// severity: critical
741+
// path: SSE:serverContent
742+
// issue: real API emits event type "serverContent" but mock does not
743+
// real: serverContent
744+
// mock: <absent>
745+
//
746+
// The provider was NOT emitting an event aimock has never heard of — aimock
747+
// emits `serverContent` in every other branch of the Live handler. What it
748+
// could not do was emit one in a TOOL turn, for two compounding reasons:
749+
//
750+
// 1. the leg drove the mock with the shared, text-shaped TOOL_FIXTURE, whose
751+
// Live rendering is a bare `toolCall` with no model turn at all; and
752+
// 2. the ONE fixture shape that expresses "the model speaks AND calls a
753+
// function" — an AudioResponse carrying the `toolCalls` companion — was
754+
// silently dropping that companion in the Live handler's audio branch.
755+
//
756+
// So (2) made the correct drive (1) inexpressible. Both are fixed, and the
757+
// three tests below hold each end of that down: the mis-drive still reproduces
758+
// the reported critical, the corrected drive grades clean, and a mock that
759+
// loses the model turn still goes critical.
760+
describe("three-way TOOL comparison: sdk shapes × provider turn × aimock", () => {
761+
let liveInstance: ServerInstance;
762+
let sharedInstance: ServerInstance;
763+
764+
beforeAll(async () => {
765+
liveInstance = await startGeminiLiveDriftServer();
766+
sharedInstance = await startDriftServer();
767+
});
768+
769+
afterAll(async () => {
770+
await stopDriftServer(liveInstance);
771+
await stopDriftServer(sharedInstance);
772+
});
773+
774+
/**
775+
* Drive aimock exactly as the tool-call drift leg's mock side does, against
776+
* whichever fixture set is under test.
777+
*/
778+
async function driveMockTool(instance: ServerInstance): Promise<unknown[]> {
779+
const mockWs = await connectWebSocket(instance.url, GEMINI_WS_PATH);
780+
mockWs.send(
781+
JSON.stringify({
782+
setup: {
783+
model: OBSERVED_MODEL,
784+
tools: WEATHER_TOOLS,
785+
generationConfig: { responseModalities: GEMINI_LIVE_RESPONSE_MODALITIES },
786+
},
787+
}),
788+
);
789+
const setupMsgs = await mockWs.waitForMessages(1);
790+
const raw: unknown[] = [JSON.parse(setupMsgs[0])];
791+
mockWs.send(
792+
JSON.stringify({
793+
clientContent: {
794+
turns: [{ role: "user", parts: [{ text: TOOL_PROMPT }] }],
795+
turnComplete: true,
796+
},
797+
}),
798+
);
799+
// A short budget on purpose: a mock that never emits the `toolCall` must
800+
// fail as the collector's own "timed out … Collected N messages" — which
801+
// names the defect — rather than as vitest's bare per-test timeout, which
802+
// names nothing. Everything here is local and answers in milliseconds.
803+
const content = await collectMockWSMessages(
804+
mockWs,
805+
(msg) => !!msg && typeof msg === "object" && "toolCall" in msg,
806+
3000,
807+
1,
808+
);
809+
raw.push(...content.rawMessages);
810+
mockWs.close();
811+
return raw;
812+
}
813+
814+
function toEvents(raw: unknown[]) {
815+
return raw.map((msg) => ({
816+
type: classifyGeminiMessage(msg as Record<string, unknown>),
817+
dataShape: extractShape(msg),
818+
}));
819+
}
820+
821+
const toolSdkShapes = () => [geminiLiveSetupCompleteShape(), ...geminiLiveToolCallEventShapes()];
822+
823+
it("REPRODUCTION: the text-shaped tool fixture still reports SSE:serverContent as <absent>", async () => {
824+
// The mis-drive, kept alive on purpose. This is the reported failure, not a
825+
// paraphrase of it: the shared TOOL_FIXTURE renders as a bare `toolCall`,
826+
// and grading that against a provider turn that speaks first produces the
827+
// artifact's diff verbatim. If a future change made this pass, the leg
828+
// would have stopped being able to see the bug it was built for.
829+
const realResult = await withProvider({}, (provider) =>
830+
probe(provider, WEATHER_TOOLS, undefined, TOOL_PROMPT),
831+
);
832+
const mockRaw = await driveMockTool(sharedInstance);
833+
834+
// The mock's own turn: a tool call and nothing before it.
835+
expect(summarizeGeminiLiveTurn(mockRaw)).toMatchObject({
836+
toolCallCount: 1,
837+
audioPartCount: 0,
838+
textPartCount: 0,
839+
});
840+
841+
const diffs = compareSSESequences(toolSdkShapes(), realResult.events, toEvents(mockRaw));
842+
expect(diffs).toContainEqual(
843+
expect.objectContaining({
844+
path: "SSE:serverContent",
845+
severity: "critical",
846+
expected: "serverContent",
847+
real: "serverContent",
848+
mock: "<absent>",
849+
}),
850+
);
851+
});
852+
853+
it("aimock streams the model turn BEFORE the tool call for the Live tool fixture", async () => {
854+
const raw = await driveMockTool(liveInstance);
855+
856+
// Ordering is the whole point, so it is asserted on the SEQUENCE, not on
857+
// counts: counts alone would pass a mock that spoke after calling, which is
858+
// what the handler used to do (its `turnComplete` trailed the `toolCall`
859+
// and the probe therefore never saw it).
860+
expect(toEvents(raw).map((e) => e.type)).toEqual([
861+
"setupComplete",
862+
"serverContent",
863+
"toolCall",
864+
]);
865+
866+
const turn = summarizeGeminiLiveTurn(raw);
867+
expect(turn.setupCompleteCount).toBe(1);
868+
expect(turn.audioPartCount).toBeGreaterThan(0);
869+
expect(turn.toolCallCount).toBe(1);
870+
// AUDIO modality: the turn speaks, it does not write.
871+
expect(turn.textPartCount).toBe(0);
872+
});
873+
874+
it("reports NO critical drift between the sdk tool shapes, the provider turn, and aimock", async () => {
875+
const realResult = await withProvider({}, (provider) =>
876+
probe(provider, WEATHER_TOOLS, undefined, TOOL_PROMPT),
877+
);
878+
const mockRaw = await driveMockTool(liveInstance);
879+
880+
const diffs = compareSSESequences(toolSdkShapes(), realResult.events, toEvents(mockRaw));
881+
882+
expect(diffs.filter((d) => d.severity === "critical")).toEqual([]);
883+
});
884+
885+
it("GUARD: a mock whose model turn lost its audio IS reported as critical drift", async () => {
886+
// Non-vacuity of the test above. The mock side here keeps the correct EVENT
887+
// SEQUENCE — serverContent then toolCall — and only empties the model turn,
888+
// so a comparison that graded event types alone would call this clean.
889+
const realResult = await withProvider({}, (provider) =>
890+
probe(provider, WEATHER_TOOLS, undefined, TOOL_PROMPT),
891+
);
892+
const hollowMock = [
893+
{ type: "setupComplete", dataShape: extractShape({ setupComplete: {} }) },
894+
{
895+
type: "serverContent",
896+
dataShape: extractShape({ serverContent: { modelTurn: { parts: [{ text: "" }] } } }),
897+
},
898+
{
899+
type: "toolCall",
900+
dataShape: extractShape({
901+
toolCall: { functionCalls: [{ name: "get_weather", args: {}, id: "x" }] },
902+
}),
903+
},
904+
];
905+
906+
const diffs = compareSSESequences(toolSdkShapes(), realResult.events, hollowMock);
907+
908+
const critical = diffs.filter((d) => d.severity === "critical");
909+
expect(critical.length).toBeGreaterThan(0);
910+
expect(critical.map((d) => d.path).join(" ")).toContain("inlineData");
911+
});
912+
});

0 commit comments

Comments
 (0)