repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by admin
extensions/voice/__serial__/speak-client.test.ts
Rawimport { mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, expect, it, vi } from "vitest";
import { SpeakClient } from "../src/speak-client.ts";
import { parseEvent, type SpeakEvent } from "../src/speak-protocol.ts";
const fake = fileURLToPath(
new URL("../__e2e__/fake-native.mjs", import.meta.url),
);
const clients: SpeakClient[] = [];
afterEach(async () => {
await Promise.all(clients.splice(0).map((client) => client.close()));
});
function client(...args: string[]) {
const value = new SpeakClient([process.execPath, fake, ...args]);
clients.push(value);
return value;
}
it("drives setup, greeting recognition, streamed synthesis, cancellation, and shutdown through one child", async () => {
const speak = client("--scenario", "greeting");
const events: SpeakEvent[] = [];
speak.onEvent((event) => events.push(event));
const info = await speak.start();
expect(info.io_mode).toBe("fake");
expect(info.sounds).toHaveLength(4);
const plan = await speak.request<{ plan: { id: string } }>("assets.plan", {
profile: "basic",
});
const install = await speak.request<{ operation: string }>("assets.install", {
plan: plan.plan.id,
approved: true,
accepted_licenses: [],
});
expect(
(await speak.waitForOperation(install.operation, { timeoutMs: 1_000 }))
.outcome,
).toBe("completed");
const opened = await speak.request<{
resource: string;
epoch: number;
operation: string;
}>("resource.open", { profile: "basic" });
expect(
(await speak.waitForOperation(opened.operation, { timeoutMs: 1_000 }))
.outcome,
).toBe("completed");
const recognition = await speak.request<{ operation: string }>(
"recognition.start",
{ resource: opened.resource, epoch: opened.epoch },
);
await vi.waitFor(
() =>
expect(
events.find((event) => event.method === "recognition.final")?.params
.data["text"],
).toBe("Hello."),
{ timeout: 1000, interval: 5 },
);
await speak.request("recognition.ack", {
operation: recognition.operation,
segment: "segment",
});
const synthesis = await speak.request<{ operation: string }>(
"synthesis.start",
{ resource: opened.resource, epoch: opened.epoch },
);
await speak.request("synthesis.append", {
operation: synthesis.operation,
index: 0,
text: "Hello. ",
});
await speak.request("synthesis.append", {
operation: synthesis.operation,
index: 1,
text: "Ready.",
});
await speak.request("synthesis.finish", { operation: synthesis.operation });
expect(
(await speak.waitForOperation(synthesis.operation, { timeoutMs: 1_000 }))
.outcome,
).toBe("completed");
expect(
events.some(
(event) =>
event.method === "playback.progress" &&
event.params.data["played_text"] === "Hello. Ready.",
),
).toBe(true);
const sound = await speak.request<{ operation: string }>("sound.play", {
resource: opened.resource,
epoch: opened.epoch,
sound: "bell",
});
const cancelled = await speak.request<{ outcome: string }>(
"operation.cancel",
{ operation: sound.operation },
);
expect(cancelled.outcome).toBe("cancelled");
expect((await speak.waitForOperation(sound.operation)).outcome).toBe(
"cancelled",
);
await speak.close();
});
it("preserves an explicit serve subcommand before native fixture arguments", async () => {
const speak = client("serve", "--scenario", "quiet");
expect((await speak.start()).io_mode).toBe("fake");
});
it("handles fragmented frames and calls onResult before a batched following notification", async () => {
const fragmented = client("--scenario", "fragment");
expect((await fragmented.start()).io_mode).toBe("fake");
const speak = client("--scenario", "batched");
const order: string[] = [];
speak.onEvent(() => {
throw new Error("broken event subscriber");
});
speak.onEvent(() => order.push("event"));
await speak.start();
await speak.request(
"service.ping",
{},
{ onResult: () => order.push("result") },
);
expect(order).toEqual(["result", "event"]);
});
it("requires preview revisions to start at one", () => {
const params = {
instance: "fake1",
seq: 1,
resource: "resource",
epoch: 1,
operation: "recognition",
data: { segment: "segment", revision: 1, text: "First preview" },
};
expect(
parseEvent("recognition.preview", params)?.params.data["revision"],
).toBe(1);
for (const revision of [0, -1])
expect(() =>
parseEvent("recognition.preview", {
...params,
data: { ...params.data, revision },
}),
).toThrow();
});
const levelParams = {
instance: "peer",
seq: 1,
resource: "resource",
epoch: 1,
operation: null,
data: { input: 0, output: 0, waveform: [0], playing: false, busy: false },
};
it("accepts legitimate silence telemetry", () => {
expect(parseEvent("audio.level", levelParams)).toMatchObject({
method: "audio.level",
params: { data: { input: 0, output: 0, waveform: [0] } },
});
});
it.each([
["negative input", { input: -0.1 }],
["negative output", { output: -0.1 }],
["nonfinite input", { input: Number.NaN }],
["nonfinite output", { output: Number.POSITIVE_INFINITY }],
["negative waveform", { waveform: [-0.1] }],
["oversized waveform", { waveform: Array<number>(33).fill(0) }],
])("rejects %s telemetry rather than hiding a peer defect", (_name, patch) => {
expect(() =>
parseEvent("audio.level", {
...levelParams,
data: { ...levelParams.data, ...patch },
}),
).toThrow();
});
it.each([
[
"null service.info result",
"service.info",
{ jsonrpc: "2.0", id: "c1", result: null },
],
[
"malformed ping error",
"service.ping",
{ jsonrpc: "2.0", id: "c2", error: { code: "bad", message: "no" } },
],
])(
"rejects pending request and reaps child for %s",
async (_case, method, response) => {
const root = await mkdtemp(join(tmpdir(), "voice-malformed-"));
const pidFile = join(root, "child.pid");
const source = `
require("node:fs").writeFileSync(${JSON.stringify(pidFile)}, String(process.pid));
const info = {
instance: "fake1", io_mode: "fake", profiles: [], devices: [], sounds: [],
capabilities: { capture: false, render: false, aec: false, recognition: false, preview: false, hotwords: false, synthesis: false, sounds: false, test_io: false },
limits: { line_bytes: 65536, pending_requests: 32, active_operations: 8, resources: 1, text_chars: 8000, queued_text_chars: 16000, unacked_segments: 32, hotwords: 20, hotword_chars: 256, waveform_bins: 32, output_queue_bytes: 262144, instance_requests: 16384, instance_operations: 4096 }
};
process.stdin.setEncoding("utf8");
process.stdin.on("data", chunk => {
for (const line of chunk.split("\\n")) {
if (!line) continue;
const request = JSON.parse(line);
if (request.method === "service.info" && ${JSON.stringify(method)} === "service.info") process.stdout.write(JSON.stringify(${JSON.stringify(response)}) + "\\n");
else if (request.method === "service.info") process.stdout.write(JSON.stringify({jsonrpc:"2.0", id:request.id, result:info}) + "\\n");
else if (request.method === "service.ping") process.stdout.write(JSON.stringify(${JSON.stringify(response)}) + "\\n");
}
});
process.on("SIGTERM", () => process.exit(0));
`;
const speak = new SpeakClient([process.execPath, "-e", source, _case]);
clients.push(speak);
try {
if (method === "service.info") {
await expect(speak.start()).rejects.toThrow();
} else {
await speak.start();
await expect(speak.request("service.ping")).rejects.toThrow();
}
await speak.close();
const pid = Number(await readFile(pidFile, "utf8"));
expect(Number.isSafeInteger(pid) && pid > 0).toBe(true);
expect(() => process.kill(pid, 0)).toThrow();
} finally {
await speak.close();
await rm(root, { recursive: true, force: true });
}
},
1500,
);
it("does not send preaborted or oversized requests", async () => {
const aborted = client("--scenario", "preabort");
const { instance } = await aborted.start();
const signal = AbortSignal.abort();
await expect(aborted.request("assets.plan", {}, { signal })).rejects.toThrow(
"aborted",
);
await expect(
aborted.request("assets.plan", { text: "x".repeat(70_000) }),
).rejects.toThrow("outgoing frame exceeds limit");
await expect(aborted.request("service.ping")).resolves.toEqual({ instance });
});
it("fails uncertain stalled requests and reports idle child death once", async () => {
const stalled = client("--scenario", "stall");
await stalled.start();
const stalledFailures: Error[] = [];
stalled.onFailure((error) => stalledFailures.push(error));
await expect(
stalled.request("service.ping", {}, { timeoutMs: 20 }),
).rejects.toThrow("timed out");
await expect(stalled.request("service.ping")).rejects.toThrow("timed out");
expect(stalledFailures).toHaveLength(1);
const dying = client("--scenario", "idle-exit");
const death = new Promise<Error>((resolve) => dying.onFailure(resolve));
await dying.start();
await expect(death).resolves.toMatchObject({
message: expect.stringContaining("exited"),
});
});
it("rejects malformed known DTOs and closes concurrently without a failure notification", async () => {
const malformed = client("--scenario", "malformed-info");
await expect(malformed.start()).rejects.toThrow("service.info");
await expect(malformed.start()).rejects.toThrow("service.info");
const speak = client();
await speak.start();
const failures: Error[] = [];
speak.onFailure((error) => failures.push(error));
const first = speak.close();
expect(speak.close()).toBe(first);
await first;
expect(failures).toEqual([]);
});
it.each(["malformed", "exit"])("fails closed when peer %s", async (fault) => {
const speak = client("--scenario", fault);
await expect(speak.start()).rejects.toThrow();
});