repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by admin
extensions/voice/__serial__/native-command-race.test.ts
Rawimport { tmpdir } from "node:os";
import path from "node:path";
import type {
ExtensionAPI,
ExtensionContext,
} from "@earendil-works/pi-coding-agent";
import { expect, it, vi } from "vitest";
const fixtures = vi.hoisted(() => ({ setup: vi.fn() }));
vi.mock("../src/pi-ext-settings.ts", async (importOriginal) => ({
...(await importOriginal<typeof import("../src/pi-ext-settings.ts")>()),
resolveSetting: (
_pi: unknown,
_ctx: unknown,
declaration: { default: unknown },
) => ({ ok: true, value: declaration.default }),
}));
vi.mock("../src/native-setup-ui.ts", () => ({
runNativeSetup: fixtures.setup,
}));
import voice from "../index.ts";
import { NativeVoiceCall } from "../src/native-call.ts";
type Handler = (args: string, ctx: ExtensionContext) => Promise<void>;
function fixture() {
const registered: { handler?: Handler } = {};
const pi = {
on: vi.fn(),
registerShortcut: vi.fn(),
registerCommand(_name: string, command: { handler: Handler }) {
registered.handler = command.handler;
},
} as unknown as ExtensionAPI;
const ctx = {
cwd: tmpdir(),
hasUI: true,
ui: { notify: vi.fn(), setWidget: vi.fn() },
} as unknown as ExtensionContext;
voice(pi);
if (!registered.handler) throw new Error("Voice command not registered");
return { handler: registered.handler, ctx };
}
const prepared = {
client: { close: vi.fn(async () => {}) },
command: ["node", "fake.mjs"],
profile: {
id: "fake",
label: "fake",
description: "fake",
installed: true,
capabilities: {},
},
preview: true,
} as never;
it("bare /voice stops the old call, approves setup and mounts the widget before startup", async () => {
const stop = vi.spyOn(NativeVoiceCall.prototype, "stop").mockResolvedValue();
const start = vi
.spyOn(NativeVoiceCall.prototype, "start")
.mockResolvedValue();
fixtures.setup.mockReset().mockResolvedValue(prepared);
try {
const { handler, ctx } = fixture();
await handler("--root /approved", ctx);
expect(start).toHaveBeenCalledOnce();
expect(start).toHaveBeenCalledWith(
ctx,
expect.objectContaining({
backend: prepared,
historyDirectory: path.join("/approved", "history"),
}),
);
expect(fixtures.setup.mock.calls[0]?.[1]).not.toHaveProperty("root");
expect(stop.mock.invocationCallOrder[0]).toBeLessThan(
fixtures.setup.mock.invocationCallOrder[0] ?? 0,
);
const widgets = vi.mocked(ctx.ui.setWidget);
expect(widgets.mock.calls.at(-1)?.[1]).toBeTypeOf("function");
expect(widgets.mock.invocationCallOrder.at(-1)).toBeLessThan(
start.mock.invocationCallOrder[0] ?? 0,
);
} finally {
stop.mockRestore();
start.mockRestore();
}
});
it.each(["decline", "failure", "setup"] as const)(
"clears terminal setup widget after %s",
async (outcome) => {
fixtures.setup.mockReset();
if (outcome === "failure")
fixtures.setup.mockRejectedValue(new Error("setup failed"));
else
fixtures.setup.mockResolvedValue(
outcome === "decline" ? undefined : prepared,
);
const stop = vi
.spyOn(NativeVoiceCall.prototype, "stop")
.mockResolvedValue();
const start = vi
.spyOn(NativeVoiceCall.prototype, "start")
.mockResolvedValue();
try {
const { handler, ctx } = fixture();
await handler(outcome === "setup" ? "setup" : "", ctx);
expect(start).not.toHaveBeenCalled();
expect(vi.mocked(ctx.ui.setWidget).mock.calls.at(-1)).toEqual([
"voice",
undefined,
]);
} finally {
stop.mockRestore();
start.mockRestore();
}
},
);
it("stop during pending setup clears its widget without allowing late startup", async () => {
let resolveSetup: ((value: typeof prepared) => void) | undefined;
fixtures.setup.mockReset().mockImplementation(
() =>
new Promise<typeof prepared>((resolve) => {
resolveSetup = resolve;
}),
);
const stop = vi.spyOn(NativeVoiceCall.prototype, "stop").mockResolvedValue();
const start = vi
.spyOn(NativeVoiceCall.prototype, "start")
.mockResolvedValue();
try {
const { handler, ctx } = fixture();
const pending = handler("", ctx);
await Promise.resolve();
await Promise.resolve();
await handler("stop", ctx);
expect(vi.mocked(ctx.ui.setWidget).mock.calls.at(-1)).toEqual([
"voice",
undefined,
]);
const calls = vi.mocked(ctx.ui.setWidget).mock.calls.length;
resolveSetup?.(prepared);
await pending;
expect(start).not.toHaveBeenCalled();
expect(ctx.ui.setWidget).toHaveBeenCalledTimes(calls);
} finally {
resolveSetup?.(prepared);
stop.mockRestore();
start.mockRestore();
}
});
it("late old setup cannot start audio or replace the newer call widget", async () => {
let approveOld: ((value: typeof prepared) => void) | undefined;
fixtures.setup
.mockReset()
.mockResolvedValue(prepared)
.mockImplementationOnce(
() =>
new Promise<typeof prepared>((resolve) => {
approveOld = resolve;
}),
);
const stop = vi.spyOn(NativeVoiceCall.prototype, "stop").mockResolvedValue();
const start = vi
.spyOn(NativeVoiceCall.prototype, "start")
.mockResolvedValue();
try {
const { handler, ctx } = fixture();
const older = handler("", ctx);
await Promise.resolve();
await Promise.resolve();
expect(fixtures.setup).toHaveBeenCalledOnce();
await handler("start", ctx);
const count = vi.mocked(ctx.ui.setWidget).mock.calls.length;
approveOld?.(prepared);
await older;
expect(start).toHaveBeenCalledOnce();
expect(ctx.ui.setWidget).toHaveBeenCalledTimes(count);
} finally {
approveOld?.(prepared);
stop.mockRestore();
start.mockRestore();
}
});