Skip to content

Commit 07b0a5c

Browse files
committed
fix(cli): read Ctrl-C from the whisper child, and re-check the Parakeet runtime after a repair
A whisper fallback killed by SIGINT or SIGTERM is a cancel (exit 130), the same rule decode and runFfmpeg use; the loop-turn wait is gone. The runtime probe treats a child stopped by Ctrl-C as a cancel and keeps the runtime; a reinstall is probed again and fails with the loader's error if it still does not load. media-use keeps the CLI's last lines, stdout included, when hyperframes transcribe fails.
1 parent 88fbc71 commit 07b0a5c

9 files changed

Lines changed: 148 additions & 31 deletions

File tree

‎packages/cli/src/commands/models.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ const sherpa = {
77
sherpaUnsupportedReason: vi.fn(),
88
installSherpaRuntime: vi.fn(),
99
ensureParakeetModel: vi.fn(),
10+
DecodeCancelled: class extends Error {},
1011
};
1112
vi.mock("../whisper/sherpa.js", () => sherpa);
1213

@@ -79,6 +80,13 @@ describe("models install parakeet --json", () => {
7980
expect(sherpa.ensureParakeetModel).not.toHaveBeenCalled();
8081
});
8182

83+
it("stops with exit 130 when Ctrl-C stops the runtime check before any listener runs", async () => {
84+
sherpa.installSherpaRuntime.mockRejectedValue(new sherpa.DecodeCancelled("cancelled"));
85+
const { exitCode, out } = await install();
86+
expect(exitCode).toBe(130);
87+
expect(out).toMatchObject({ ok: false, error: expect.stringMatching(/cancelled/) });
88+
});
89+
8290
it("stops with exit 130 when cancelled mid-download", async () => {
8391
sherpa.ensureParakeetModel.mockImplementation(async ({ signal }: { signal: AbortSignal }) => {
8492
cancel.abort();

‎packages/cli/src/commands/models.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,10 @@ async function installMissing(sherpa: Sherpa, spin: Spinner, signal: AbortSignal
4646
return runtimeInstalled || modelFetched;
4747
}
4848

49+
/** A synchronous child's Ctrl-C shows as its error before the scope's listener runs. */
50+
const wasCancelled = (err: unknown, signal: AbortSignal, sherpa: Sherpa) =>
51+
signal.aborted || err instanceof sherpa.DecodeCancelled;
52+
4953
async function installParakeet(json: boolean): Promise<void> {
5054
const sherpa = await import("../whisper/sherpa.js");
5155
const unsupported = sherpa.sherpaUnsupportedReason();
@@ -65,7 +69,7 @@ async function installParakeet(json: boolean): Promise<void> {
6569
);
6670
}
6771
} catch (err) {
68-
const cancelled = cancellation.signal.aborted;
72+
const cancelled = wasCancelled(err, cancellation.signal, sherpa);
6973
spin?.stop(
7074
cancelled ? c.warn("Parakeet install cancelled") : c.error("Parakeet install failed"),
7175
);

‎packages/cli/src/commands/transcribe.test.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -199,9 +199,8 @@ describe("transcribe command", () => {
199199

200200
it("exits 130 when Ctrl-C stops the whisper fallback too", async () => {
201201
crashChild("SIGABRT");
202-
// A real signal reaches the listener only when the loop turns after the synchronous whisper run.
202+
// No signal reaches the listener in time: the synchronous whisper child's own signal decides.
203203
transcribeMock.mockImplementation(async () => {
204-
setImmediate(() => process.emit("SIGINT"));
205204
throw Object.assign(new Error("Command failed: whisper-cli"), { signal: "SIGINT" });
206205
});
207206
Object.assign(runners, { sherpa: true, mlx: false });

‎packages/cli/src/commands/transcribe.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,11 @@ async function transcribeAudio(
371371
try {
372372
result = await run(runner);
373373
} catch (fallbackErr) {
374+
// Whisper runs synchronously, so Ctrl-C shows as its child's signal before any listener runs.
375+
const { code, signal } = fallbackErr as { code?: string; signal?: string };
376+
if (!code && (signal === "SIGINT" || signal === "SIGTERM")) {
377+
throw new DecodeCancelled("Transcription cancelled");
378+
}
374379
const why = normalizeErrorMessage(fallbackErr);
375380
throw new Error(`${parakeetError}. The ${runner} fallback failed too: ${why}`);
376381
}
@@ -416,8 +421,6 @@ async function transcribeAudio(
416421
);
417422
}
418423
} catch (err) {
419-
// A signal that landed during a synchronous whisper run is only handled once the loop turns.
420-
if (cancellation) await new Promise((resolve) => setImmediate(resolve));
421424
if (err instanceof DecodeCancelled || cancellation?.signal.aborted) {
422425
const message = "Transcription cancelled";
423426
if (opts.json) console.log(JSON.stringify({ ok: false, error: message }));

‎packages/cli/src/whisper/sherpa.test.ts‎

Lines changed: 41 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ import {
1717
installSherpaRuntime,
1818
SHERPA_RUNTIME_DIR,
1919
sherpaPlatformPackage,
20-
sherpaRuntimeLoads,
20+
DecodeCancelled,
21+
sherpaRuntimeLoadError,
2122
sherpaUnsupportedReason,
2223
type ModelFile,
2324
} from "./sherpa.js";
@@ -66,28 +67,27 @@ describe("installSherpaRuntime", () => {
6667
});
6768

6869
/** A stand-in runtime in `root` whose entry point loads, or throws as a missing library does. */
69-
function fakeRuntime(root: string, loads: boolean) {
70+
const LOADS = "module.exports = {};";
71+
const BROKEN = 'throw new Error("libonnxruntime.so: cannot open\\n shared object");';
72+
function fakeRuntime(root: string, body: string) {
7073
const pkg = join(root, "node_modules", "sherpa-onnx-node");
7174
mkdirSync(pkg, { recursive: true });
7275
writeFileSync(join(pkg, "package.json"), '{"name":"sherpa-onnx-node","main":"index.js"}');
73-
const body = loads
74-
? "module.exports = {};"
75-
: 'throw new Error("libonnxruntime.so: cannot open");';
7676
writeFileSync(join(pkg, "index.js"), body);
7777
}
7878

7979
it("reinstalls a runtime that is present but does not load", async () => {
8080
const dir = mkdtempSync(join(tmpdir(), "hf-sherpa-runtime-"));
8181
try {
82-
fakeRuntime(dir, false);
83-
expect(sherpaRuntimeLoads(dir)).toBe(false);
82+
fakeRuntime(dir, BROKEN);
83+
expect(sherpaRuntimeLoadError(dir)).toBe("libonnxruntime.so: cannot open shared object");
8484
const run = vi.fn(async (args: string[]) =>
85-
fakeRuntime(args[args.indexOf("--prefix") + 1]!, true),
85+
fakeRuntime(args[args.indexOf("--prefix") + 1]!, LOADS),
8686
);
8787

8888
expect(await installSherpaRuntime({ run, dir })).toBe(true);
8989
expect(run).toHaveBeenCalledTimes(1);
90-
expect(sherpaRuntimeLoads(dir)).toBe(true);
90+
expect(sherpaRuntimeLoadError(dir)).toBeNull();
9191
} finally {
9292
rmSync(dir, { recursive: true, force: true });
9393
}
@@ -96,7 +96,7 @@ describe("installSherpaRuntime", () => {
9696
it("leaves a runtime that loads alone", async () => {
9797
const dir = mkdtempSync(join(tmpdir(), "hf-sherpa-runtime-"));
9898
try {
99-
fakeRuntime(dir, true);
99+
fakeRuntime(dir, LOADS);
100100
const run = vi.fn();
101101
expect(await installSherpaRuntime({ run, dir })).toBe(false);
102102
expect(run).not.toHaveBeenCalled();
@@ -105,6 +105,36 @@ describe("installSherpaRuntime", () => {
105105
}
106106
});
107107

108+
it("fails with the loader's error when the reinstalled runtime still does not load", async () => {
109+
const dir = mkdtempSync(join(tmpdir(), "hf-sherpa-runtime-"));
110+
try {
111+
const run = vi.fn(async (args: string[]) =>
112+
fakeRuntime(args[args.indexOf("--prefix") + 1]!, BROKEN),
113+
);
114+
await expect(installSherpaRuntime({ run, dir })).rejects.toThrow(
115+
"The sherpa-onnx runtime installed but does not load: libonnxruntime.so: cannot open shared object",
116+
);
117+
} finally {
118+
rmSync(dir, { recursive: true, force: true });
119+
}
120+
});
121+
122+
it.skipIf(process.platform === "win32")(
123+
"treats a probe stopped by Ctrl-C as a cancel and keeps the runtime",
124+
async () => {
125+
const dir = mkdtempSync(join(tmpdir(), "hf-sherpa-runtime-"));
126+
try {
127+
fakeRuntime(dir, 'process.kill(process.pid, "SIGINT");');
128+
const run = vi.fn();
129+
await expect(installSherpaRuntime({ run, dir })).rejects.toBeInstanceOf(DecodeCancelled);
130+
expect(run).not.toHaveBeenCalled();
131+
expect(existsSync(join(dir, "node_modules", "sherpa-onnx-node", "index.js"))).toBe(true);
132+
} finally {
133+
rmSync(dir, { recursive: true, force: true });
134+
}
135+
},
136+
);
137+
108138
it("keeps each platform and arch in its own runtime dir", () => {
109139
expect(SHERPA_RUNTIME_DIR).toMatch(
110140
new RegExp(`sherpa-onnx-node@1\\.13\\.8-${process.platform}-${process.arch}$`),
@@ -132,7 +162,7 @@ describe("sherpaParakeetInstalled", () => {
132162
writeFileSync(join(sherpa.PARAKEET_MODEL_DIR, name), "");
133163
truncateSync(join(sherpa.PARAKEET_MODEL_DIR, name), bytes);
134164
}
135-
expect(sherpa.sherpaRuntimeLoads()).toBe(false);
165+
expect(sherpa.sherpaRuntimeLoadError()).not.toBeNull();
136166
expect(sherpa.sherpaParakeetInstalled()).toBe(true);
137167
} finally {
138168
vi.unstubAllEnvs();

‎packages/cli/src/whisper/sherpa.ts‎

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -113,15 +113,29 @@ export function sherpaUnsupportedReason(host: Host = currentHost()): string | nu
113113
const nativePackageName = (platform: string, arch: string) =>
114114
`sherpa-onnx-${platform === "win32" ? "win" : platform}-${arch}`;
115115

116-
/** Loads it in a child as the decode worker does: only a load shows a missing library or bad binary. */
117-
export function sherpaRuntimeLoads(dir = SHERPA_RUNTIME_DIR): boolean {
118-
if (!isInstalled(dir, RUNTIME)) return false;
119-
const load = `require("node:module").createRequire(process.env.HF_SHERPA_MANIFEST)("${RUNTIME}")`;
116+
const LOAD_RUNTIME = `try {
117+
require("node:module").createRequire(process.env.HF_SHERPA_MANIFEST)("${RUNTIME}");
118+
} catch (e) {
119+
process.stderr.write(String(e && e.message).replace(/\\s+/g, " "));
120+
process.exitCode = 1;
121+
}`;
122+
123+
/** Loads it in a child as the decode worker does: null when it loads, else the loader's error. */
124+
export function sherpaRuntimeLoadError(dir = SHERPA_RUNTIME_DIR): string | null {
125+
if (!isInstalled(dir, RUNTIME)) return `${RUNTIME} is not installed in ${dir}`;
120126
const env = { ...process.env, HF_SHERPA_MANIFEST: join(dir, "package.json") };
121-
return (
122-
spawnSync(process.execPath, ["-e", load], { env, stdio: "ignore", timeout: 60_000 }).status ===
123-
0
124-
);
127+
const probe = spawnSync(process.execPath, ["-e", LOAD_RUNTIME], {
128+
env,
129+
encoding: "utf8",
130+
stdio: ["ignore", "ignore", "pipe"],
131+
timeout: 60_000,
132+
});
133+
if (probe.status === 0) return null;
134+
// Ctrl-C reaches the probe too: a cancel, never proof that a working runtime is broken.
135+
if (!probe.error && (probe.signal === "SIGINT" || probe.signal === "SIGTERM")) {
136+
throw new DecodeCancelled("Parakeet install cancelled");
137+
}
138+
return bounded(probe.stderr?.trim() || probe.error?.message || `exited with ${probe.status}`);
125139
}
126140

127141
/** The native package, pinned too: the runtime's own optionalDependencies accept any 1.13.x. */
@@ -135,11 +149,14 @@ export async function installSherpaRuntime({
135149
signal,
136150
dir = SHERPA_RUNTIME_DIR,
137151
}: { run?: typeof runNpm; signal?: AbortSignal; dir?: string } = {}): Promise<boolean> {
138-
if (sherpaRuntimeLoads(dir)) return false;
152+
if (sherpaRuntimeLoadError(dir) === null) return false;
139153
// install() keeps any dir holding the runtime manifest, so a broken one goes first.
140154
rmSync(dir, { recursive: true, force: true });
141155
const native = sherpaPlatformPackage();
142156
await install(dir, RUNTIME, RUNTIME_VERSION, (args) => run([...args, native], signal));
157+
const stillBroken = sherpaRuntimeLoadError(dir);
158+
if (stillBroken)
159+
throw new Error(`The sherpa-onnx runtime installed but does not load: ${stillBroken}`);
143160
return true;
144161
}
145162

@@ -244,10 +261,12 @@ function recognizerConfig(): object {
244261
};
245262
}
246263

247-
/** Ctrl-C or a SIGTERM stopped the decode: the user's cancel, never a reason to fall back. */
264+
/** Ctrl-C or a SIGTERM stopped a Parakeet child: the user's cancel, never a reason to fall back. */
248265
export class DecodeCancelled extends Error {}
249266

250267
const MAX_REASON_CHARS = 600;
268+
const bounded = (why: string) =>
269+
why.length > MAX_REASON_CHARS ? `${why.slice(0, MAX_REASON_CHARS)}…` : why;
251270

252271
function failureReason(err: ExecFileException | null, stderr: string): string {
253272
const how = !err
@@ -265,7 +284,7 @@ function failureReason(err: ExecFileException | null, stderr: string): string {
265284
lines.find((line) => line.startsWith(SHERPA_ERROR_PREFIX))?.slice(SHERPA_ERROR_PREFIX.length) ??
266285
lines.at(-1);
267286
if (!why) return how;
268-
return `${how}: ${why.length > MAX_REASON_CHARS ? `${why.slice(0, MAX_REASON_CHARS)}…` : why}`;
287+
return `${how}: ${bounded(why)}`;
269288
}
270289

271290
/** Decodes in a child process: onnxruntime aborts the whole process on some inputs, uncatchably. */

‎skills-manifest.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@
5454
"files": 1
5555
},
5656
"media-use": {
57-
"hash": "11611ba718ad3616",
57+
"hash": "7709fc6e787c70cb",
5858
"files": 101
5959
},
6060
"motion-graphics": {

‎skills/media-use/scripts/transcribe.mjs‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
} from "node:fs";
1313
import { homedir, tmpdir } from "node:os";
1414
import { basename, extname, join, resolve } from "node:path";
15-
import { parseArgs } from "node:util";
15+
import { parseArgs, stripVTControlCharacters } from "node:util";
1616
import { mergeTokensToWords } from "./lib/parakeet-words.mjs";
1717
import { track } from "./lib/telemetry.mjs";
1818
import { resolveNpxInvocation } from "./lib/npx-sync.mjs";
@@ -137,7 +137,21 @@ function runCli(cliEngine) {
137137
["hyperframes", "transcribe", inputPath, "--dir", workDir, "--engine", cliEngine, "--json"],
138138
{ stdio: ["ignore", "pipe", "pipe"], timeout: 1_800_000 },
139139
);
140-
const stdout = String(execFileSync(resolved.cmd, resolved.args, resolved.opts));
140+
let stdout;
141+
try {
142+
stdout = String(execFileSync(resolved.cmd, resolved.args, resolved.opts));
143+
} catch (e) {
144+
// stderr holds spinner redraws and --json prints the reason on stdout, so keep the last lines.
145+
const tail = stripVTControlCharacters(`${e.stderr ?? ""}\n${e.stdout ?? ""}`)
146+
.split(/[\r\n]+/)
147+
.map((l) => l.trim())
148+
.filter((l) => l && l !== "│")
149+
.slice(-3)
150+
.join("\n");
151+
throw new Error(
152+
`hyperframes transcribe failed (exit ${e.status ?? e.code})${tail ? `:\n${tail}` : ""}`,
153+
);
154+
}
141155
const produced = join(workDir, "transcript.json");
142156
if (!existsSync(produced))
143157
throw new Error("hyperframes transcribe produced no transcript.json");

‎skills/media-use/scripts/transcribe.test.mjs‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import assert from "node:assert/strict";
2-
import { execFileSync } from "node:child_process";
2+
import { execFileSync, spawnSync } from "node:child_process";
33
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
44
import { tmpdir } from "node:os";
55
import { join } from "node:path";
@@ -69,3 +69,43 @@ test(
6969
assert.equal(result.engine, "parakeet");
7070
},
7171
);
72+
73+
test(
74+
"a failed --engine parakeet run reports the reason the CLI printed on stdout",
75+
{ skip: process.platform === "win32" },
76+
() => {
77+
const root = mkdtempSync(join(tmpdir(), "media-use-transcribe-"));
78+
try {
79+
const bin = join(root, "bin");
80+
mkdirSync(bin);
81+
const reason =
82+
"Parakeet is not installed. Install it with: hyperframes models install parakeet";
83+
writeFileSync(
84+
join(bin, "npx"),
85+
`#!/bin/sh\necho '{"ok":false,"error":"${reason}"}'\nexit 1\n`,
86+
);
87+
chmodSync(join(bin, "npx"), 0o755);
88+
const input = join(root, "in.wav");
89+
writeFileSync(input, "");
90+
const script = fileURLToPath(new URL("./transcribe.mjs", import.meta.url));
91+
const res = spawnSync(
92+
process.execPath,
93+
[script, "--input", input, "--engine", "parakeet", "--json"],
94+
{
95+
encoding: "utf8",
96+
env: {
97+
...process.env,
98+
PATH: `${bin}:${process.env.PATH}`,
99+
HOME: root,
100+
HYPERFRAMES_MEDIA_HOME: join(root, "home"),
101+
HYPERFRAMES_NO_TELEMETRY: "1",
102+
},
103+
},
104+
);
105+
assert.equal(res.status, 1);
106+
assert.match(JSON.parse(res.stdout.trim()).error, /hyperframes models install parakeet/);
107+
} finally {
108+
rmSync(root, { recursive: true, force: true });
109+
}
110+
},
111+
);

0 commit comments

Comments
 (0)