@senad-d/micme 0.3.4 → 0.3.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1 -0
- package/README.md +20 -5
- package/micme.example.json +7 -7
- package/micme.schema.json +117 -9
- package/package.json +8 -7
- package/scripts/doctor.mjs +57 -258
- package/src/audio.ts +59 -23
- package/src/config.ts +216 -52
- package/src/constants.ts +25 -0
- package/src/editor.ts +6 -8
- package/src/extension.ts +411 -188
- package/src/models.ts +208 -51
- package/src/processes.ts +104 -28
- package/src/settings.ts +53 -35
- package/src/streaming.ts +2 -2
- package/src/transcription.ts +10 -10
- package/src/types.ts +9 -1
- package/tsconfig.json +1 -1
package/src/models.ts
CHANGED
|
@@ -9,17 +9,43 @@ import { finished } from "node:stream/promises";
|
|
|
9
9
|
import {
|
|
10
10
|
DEFAULT_PYTHON_WHISPER_MODEL_NAME,
|
|
11
11
|
DEFAULT_WHISPER_CPP_MODEL_NAME,
|
|
12
|
+
MODEL_DOWNLOAD_INACTIVITY_TIMEOUT_MS,
|
|
12
13
|
PYTHON_WHISPER_MODEL_NAMES,
|
|
13
14
|
STATUS_KEY,
|
|
14
15
|
WHISPER_CPP_MODEL_BASE_URL,
|
|
15
16
|
WHISPER_CPP_MODEL_NAMES,
|
|
16
17
|
} from "./constants.ts";
|
|
17
|
-
import { env, expandConfigPath, getTranslateToEnglishLanguage } from "./config.ts";
|
|
18
|
+
import { env, expandConfigPath, getAutoDownloadModel, getTranslateToEnglishLanguage } from "./config.ts";
|
|
18
19
|
import { findExecutable, runProcess } from "./processes.ts";
|
|
19
20
|
import { sanitizeTerminalText } from "./terminal-text.ts";
|
|
20
21
|
import type { ModelCandidate, ResolvedWhisperCppModel } from "./types.ts";
|
|
21
22
|
|
|
22
|
-
|
|
23
|
+
export type ModelDownloadOptions = {
|
|
24
|
+
signal?: AbortSignal;
|
|
25
|
+
inactivityTimeoutMs?: number;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
type DownloadFileOptions = ModelDownloadOptions & {
|
|
29
|
+
onProgress?: (downloadedBytes: number, totalBytes: number) => void;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
type ModelDownloadWaiter = {
|
|
33
|
+
ctx?: ExtensionContext;
|
|
34
|
+
signal?: AbortSignal;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
type SharedModelDownload = {
|
|
38
|
+
controller: AbortController;
|
|
39
|
+
promise: Promise<void>;
|
|
40
|
+
waiters: Map<symbol, ModelDownloadWaiter>;
|
|
41
|
+
settled: boolean;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export class ModelDownloadTimeoutError extends Error {
|
|
45
|
+
override name = "ModelDownloadTimeoutError";
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const modelDownloads = new Map<string, SharedModelDownload>();
|
|
23
49
|
const PYTHON_WHISPER_MODELS_SCRIPT = String.raw`import whisper; print('\n'.join(whisper.available_models()))`;
|
|
24
50
|
|
|
25
51
|
export function discoverWhisperCppModels(cwd: string): ModelCandidate[] {
|
|
@@ -254,110 +280,241 @@ export function uniqueModelNames(names: string[]) {
|
|
|
254
280
|
return output;
|
|
255
281
|
}
|
|
256
282
|
|
|
257
|
-
export async function ensureWhisperCppModel(modelPath: string, ctx?: ExtensionContext, options: { allowDownload?: boolean } = {}) {
|
|
283
|
+
export async function ensureWhisperCppModel(modelPath: string, ctx?: ExtensionContext, options: ModelDownloadOptions & { allowDownload?: boolean } = {}) {
|
|
284
|
+
options.signal?.throwIfAborted();
|
|
258
285
|
assertDownloadTargetIsUsable(modelPath, "Micme model path");
|
|
259
286
|
if (isRegularFile(modelPath)) return;
|
|
260
287
|
if (options.allowDownload === false) {
|
|
261
288
|
throw new Error(`Micme model is missing: ${modelPath}`);
|
|
262
289
|
}
|
|
263
|
-
if (
|
|
290
|
+
if (!getAutoDownloadModel()) {
|
|
264
291
|
throw new Error(`Micme model is missing and auto-download is disabled: ${modelPath}`);
|
|
265
292
|
}
|
|
266
293
|
|
|
267
|
-
const existingDownload = modelDownloads.get(modelPath);
|
|
268
|
-
if (existingDownload) {
|
|
269
|
-
ctx?.ui.setStatus(STATUS_KEY, `waiting for ${safeBasename(modelPath)} download…`);
|
|
270
|
-
try {
|
|
271
|
-
await existingDownload;
|
|
272
|
-
} finally {
|
|
273
|
-
ctx?.ui.setStatus(STATUS_KEY, undefined);
|
|
274
|
-
}
|
|
275
|
-
return;
|
|
276
|
-
}
|
|
277
|
-
|
|
278
294
|
const modelName = getDownloadableWhisperCppModelName(modelPath);
|
|
279
295
|
if (!modelName) {
|
|
280
296
|
throw new Error(`Micme model is missing and cannot infer a standard download URL: ${modelPath}`);
|
|
281
297
|
}
|
|
282
298
|
|
|
283
|
-
|
|
284
|
-
|
|
299
|
+
let download = modelDownloads.get(modelPath);
|
|
300
|
+
if (download?.controller.signal.aborted) download = await waitForActiveModelDownload(modelPath, download, options.signal);
|
|
301
|
+
const created = !download;
|
|
302
|
+
download ??= createSharedModelDownload(modelName, modelPath, options.inactivityTimeoutMs);
|
|
303
|
+
await waitForSharedModelDownload(download, modelPath, ctx, options.signal, created);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
export async function downloadWhisperCppModel(modelName: string, modelPath: string, ctx?: ExtensionContext, options: ModelDownloadOptions = {}) {
|
|
307
|
+
options.signal?.throwIfAborted();
|
|
308
|
+
assertDownloadTargetIsUsable(modelPath, "Micme model path");
|
|
309
|
+
if (isRegularFile(modelPath)) return;
|
|
310
|
+
const displayName = safeBasename(modelPath);
|
|
311
|
+
setActiveDownloadStatus(ctx, options.signal, `downloading ${displayName}…`);
|
|
312
|
+
if (!options.signal?.aborted) ctx?.ui.notify(`Downloading ${displayName}. This can take a while the first time.`, "info");
|
|
313
|
+
|
|
285
314
|
try {
|
|
286
|
-
await
|
|
315
|
+
await performWhisperCppModelDownload(modelName, modelPath, {
|
|
316
|
+
...options,
|
|
317
|
+
onProgress: updateContextDownloadProgress.bind(undefined, ctx, options.signal, modelPath),
|
|
318
|
+
});
|
|
319
|
+
options.signal?.throwIfAborted();
|
|
320
|
+
ctx?.ui.notify(`Downloaded ${displayName}.`, "info");
|
|
287
321
|
} finally {
|
|
288
|
-
modelDownloads.delete(modelPath);
|
|
289
322
|
ctx?.ui.setStatus(STATUS_KEY, undefined);
|
|
290
323
|
}
|
|
291
324
|
}
|
|
292
325
|
|
|
293
|
-
|
|
326
|
+
async function performWhisperCppModelDownload(modelName: string, modelPath: string, options: DownloadFileOptions) {
|
|
294
327
|
assertDownloadTargetIsUsable(modelPath, "Micme model path");
|
|
295
328
|
if (isRegularFile(modelPath)) return;
|
|
296
|
-
|
|
297
|
-
const displayName = safeBasename(modelPath);
|
|
298
|
-
ctx?.ui.setStatus(STATUS_KEY, `downloading ${displayName}…`);
|
|
299
|
-
ctx?.ui.notify(`Downloading ${displayName}. This can take a while the first time.`, "info");
|
|
300
|
-
await downloadFile(url, modelPath, ctx);
|
|
301
|
-
ctx?.ui.notify(`Downloaded ${displayName}.`, "info");
|
|
329
|
+
await downloadFile(getWhisperCppModelUrl(modelName), modelPath, undefined, options);
|
|
302
330
|
}
|
|
303
331
|
|
|
304
|
-
export async function downloadFile(url: string, targetPath: string, ctx?: ExtensionContext) {
|
|
332
|
+
export async function downloadFile(url: string, targetPath: string, ctx?: ExtensionContext, options: DownloadFileOptions = {}) {
|
|
333
|
+
options.signal?.throwIfAborted();
|
|
305
334
|
assertDownloadTargetIsUsable(targetPath, "Download target");
|
|
306
335
|
if (isRegularFile(targetPath)) return;
|
|
307
336
|
await mkdir(dirname(targetPath), { recursive: true });
|
|
308
337
|
const tempPath = `${targetPath}.download-${process.pid}-${Date.now()}-${randomUUID()}`;
|
|
309
|
-
|
|
310
|
-
const
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
const totalBytes = Number(response.headers.get("content-length") || "0");
|
|
316
|
-
const reader = response.body.getReader();
|
|
317
|
-
const output = createWriteStream(tempPath, { flags: "wx" });
|
|
318
|
-
const outputFinished = finished(output);
|
|
319
|
-
outputFinished.catch(() => undefined);
|
|
338
|
+
const timeoutMs = getDownloadInactivityTimeout(options.inactivityTimeoutMs);
|
|
339
|
+
const timeoutController = new AbortController();
|
|
340
|
+
const signal = options.signal ? AbortSignal.any([options.signal, timeoutController.signal]) : timeoutController.signal;
|
|
341
|
+
let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
|
|
342
|
+
let output: WriteStream | undefined;
|
|
343
|
+
let outputFinished: Promise<void> | undefined;
|
|
320
344
|
let downloadedBytes = 0;
|
|
321
345
|
let lastUpdate = 0;
|
|
322
346
|
|
|
323
347
|
try {
|
|
348
|
+
const response = await waitForDownloadActivity(fetch(url, { signal }), signal, timeoutController, timeoutMs, "response headers");
|
|
349
|
+
if (!response.ok || !response.body) {
|
|
350
|
+
throw new Error(`Failed to download ${url}: HTTP ${response.status} ${response.statusText}`);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
const totalBytes = Number(response.headers.get("content-length") || "0");
|
|
354
|
+
reader = response.body.getReader();
|
|
355
|
+
output = createWriteStream(tempPath, { flags: "wx" });
|
|
356
|
+
outputFinished = finished(output);
|
|
357
|
+
outputFinished.catch(ignoreDownloadFailure);
|
|
358
|
+
|
|
324
359
|
while (true) {
|
|
325
|
-
const
|
|
326
|
-
if (done) break;
|
|
327
|
-
if (!value) continue;
|
|
328
|
-
downloadedBytes += value.byteLength;
|
|
329
|
-
await writeDownloadChunk(output, Buffer.from(value), outputFinished);
|
|
360
|
+
const result = await waitForDownloadActivity(reader.read(), signal, timeoutController, timeoutMs, "response body data");
|
|
361
|
+
if (result.done) break;
|
|
362
|
+
if (!result.value) continue;
|
|
363
|
+
downloadedBytes += result.value.byteLength;
|
|
364
|
+
await waitForDownloadActivity(writeDownloadChunk(output, Buffer.from(result.value), outputFinished), signal, timeoutController, timeoutMs, "file output");
|
|
330
365
|
|
|
331
366
|
const now = Date.now();
|
|
332
|
-
if (
|
|
333
|
-
ctx.
|
|
367
|
+
if (now - lastUpdate > 1_000) {
|
|
368
|
+
updateContextDownloadProgress(ctx, options.signal, targetPath, downloadedBytes, totalBytes);
|
|
369
|
+
options.onProgress?.(downloadedBytes, totalBytes);
|
|
334
370
|
lastUpdate = now;
|
|
335
371
|
}
|
|
336
372
|
}
|
|
337
373
|
|
|
338
374
|
output.end();
|
|
339
|
-
await outputFinished;
|
|
375
|
+
await waitForDownloadActivity(outputFinished, signal, timeoutController, timeoutMs, "file completion");
|
|
340
376
|
if (isRegularFile(targetPath)) {
|
|
341
|
-
await unlink(tempPath).catch(
|
|
377
|
+
await unlink(tempPath).catch(ignoreDownloadFailure);
|
|
342
378
|
return;
|
|
343
379
|
}
|
|
344
380
|
assertDownloadTargetIsUsable(targetPath, "Download target");
|
|
381
|
+
options.signal?.throwIfAborted();
|
|
345
382
|
await rename(tempPath, targetPath);
|
|
346
383
|
} catch (error) {
|
|
347
|
-
|
|
348
|
-
output
|
|
349
|
-
await outputFinished.catch(
|
|
350
|
-
await unlink(tempPath).catch(
|
|
384
|
+
cancelDownloadReader(reader);
|
|
385
|
+
output?.destroy();
|
|
386
|
+
if (outputFinished) await outputFinished.catch(ignoreDownloadFailure);
|
|
387
|
+
await unlink(tempPath).catch(ignoreDownloadFailure);
|
|
351
388
|
throw error;
|
|
352
389
|
}
|
|
353
390
|
}
|
|
354
391
|
|
|
392
|
+
function createSharedModelDownload(modelName: string, modelPath: string, inactivityTimeoutMs: number | undefined) {
|
|
393
|
+
const controller = new AbortController();
|
|
394
|
+
const download: SharedModelDownload = {
|
|
395
|
+
controller,
|
|
396
|
+
promise: Promise.resolve(),
|
|
397
|
+
waiters: new Map(),
|
|
398
|
+
settled: false,
|
|
399
|
+
};
|
|
400
|
+
const options: DownloadFileOptions = {
|
|
401
|
+
signal: controller.signal,
|
|
402
|
+
inactivityTimeoutMs,
|
|
403
|
+
onProgress: reportSharedModelDownloadProgress.bind(undefined, download, modelPath),
|
|
404
|
+
};
|
|
405
|
+
download.promise = performWhisperCppModelDownload(modelName, modelPath, options).finally(settleSharedModelDownload.bind(undefined, modelPath, download));
|
|
406
|
+
download.promise.catch(ignoreDownloadFailure);
|
|
407
|
+
modelDownloads.set(modelPath, download);
|
|
408
|
+
return download;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
async function waitForActiveModelDownload(modelPath: string, download: SharedModelDownload | undefined, signal: AbortSignal | undefined) {
|
|
412
|
+
while (download?.controller.signal.aborted) {
|
|
413
|
+
try {
|
|
414
|
+
await waitForPromiseWithSignal(download.promise, signal);
|
|
415
|
+
} catch {
|
|
416
|
+
signal?.throwIfAborted();
|
|
417
|
+
}
|
|
418
|
+
download = modelDownloads.get(modelPath);
|
|
419
|
+
}
|
|
420
|
+
return download;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
async function waitForSharedModelDownload(download: SharedModelDownload, modelPath: string, ctx: ExtensionContext | undefined, signal: AbortSignal | undefined, created: boolean) {
|
|
424
|
+
const waiterId = Symbol(modelPath);
|
|
425
|
+
download.waiters.set(waiterId, { ctx, signal });
|
|
426
|
+
const displayName = safeBasename(modelPath);
|
|
427
|
+
setActiveDownloadStatus(ctx, signal, created ? `downloading ${displayName}…` : `waiting for ${displayName} download…`);
|
|
428
|
+
if (created && !signal?.aborted) ctx?.ui.notify(`Downloading ${displayName}. This can take a while the first time.`, "info");
|
|
429
|
+
let failed = false;
|
|
430
|
+
let failure: unknown;
|
|
431
|
+
|
|
432
|
+
try {
|
|
433
|
+
await waitForPromiseWithSignal(download.promise, signal);
|
|
434
|
+
signal?.throwIfAborted();
|
|
435
|
+
ctx?.ui.notify(`Downloaded ${displayName}.`, "info");
|
|
436
|
+
} catch (error) {
|
|
437
|
+
failed = true;
|
|
438
|
+
failure = error;
|
|
439
|
+
} finally {
|
|
440
|
+
download.waiters.delete(waiterId);
|
|
441
|
+
ctx?.ui.setStatus(STATUS_KEY, undefined);
|
|
442
|
+
if (download.waiters.size === 0 && !download.settled) {
|
|
443
|
+
download.controller.abort();
|
|
444
|
+
await download.promise.catch(ignoreDownloadFailure);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
if (failed) throw failure;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
function reportSharedModelDownloadProgress(download: SharedModelDownload, modelPath: string, downloadedBytes: number, totalBytes: number) {
|
|
452
|
+
for (const waiter of download.waiters.values()) {
|
|
453
|
+
updateContextDownloadProgress(waiter.ctx, waiter.signal, modelPath, downloadedBytes, totalBytes);
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
function updateContextDownloadProgress(ctx: ExtensionContext | undefined, signal: AbortSignal | undefined, modelPath: string, downloadedBytes: number, totalBytes: number) {
|
|
458
|
+
setActiveDownloadStatus(ctx, signal, `downloading ${safeBasename(modelPath)} ${formatDownloadProgress(downloadedBytes, totalBytes)}`);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
function setActiveDownloadStatus(ctx: ExtensionContext | undefined, signal: AbortSignal | undefined, status: string) {
|
|
462
|
+
if (!signal?.aborted) ctx?.ui.setStatus(STATUS_KEY, status);
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
function settleSharedModelDownload(modelPath: string, download: SharedModelDownload) {
|
|
466
|
+
download.settled = true;
|
|
467
|
+
if (modelDownloads.get(modelPath) === download) modelDownloads.delete(modelPath);
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
async function waitForDownloadActivity<T>(work: Promise<T>, signal: AbortSignal, timeoutController: AbortController, timeoutMs: number, activity: string) {
|
|
471
|
+
const timeout = setTimeout(() => {
|
|
472
|
+
timeoutController.abort(new ModelDownloadTimeoutError(`Micme model download timed out after ${timeoutMs} ms without ${activity}.`));
|
|
473
|
+
}, timeoutMs);
|
|
474
|
+
try {
|
|
475
|
+
return await waitForPromiseWithSignal(work, signal);
|
|
476
|
+
} finally {
|
|
477
|
+
clearTimeout(timeout);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
async function waitForPromiseWithSignal<T>(work: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
|
|
482
|
+
if (!signal) return work;
|
|
483
|
+
signal.throwIfAborted();
|
|
484
|
+
let rejectAbort: (reason?: unknown) => void = ignoreDownloadFailure;
|
|
485
|
+
const aborted = new Promise<never>((_resolve, reject) => {
|
|
486
|
+
rejectAbort = reject;
|
|
487
|
+
});
|
|
488
|
+
const onAbort = () => rejectAbort(signal.reason);
|
|
489
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
490
|
+
try {
|
|
491
|
+
return await Promise.race([work, aborted]);
|
|
492
|
+
} finally {
|
|
493
|
+
signal.removeEventListener("abort", onAbort);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
function getDownloadInactivityTimeout(value: number | undefined) {
|
|
498
|
+
if (value === undefined) return MODEL_DOWNLOAD_INACTIVITY_TIMEOUT_MS;
|
|
499
|
+
if (!Number.isFinite(value) || value <= 0) throw new Error("inactivityTimeoutMs must be a positive finite number");
|
|
500
|
+
return Math.ceil(value);
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
function cancelDownloadReader(reader: ReadableStreamDefaultReader<Uint8Array> | undefined) {
|
|
504
|
+
if (!reader) return;
|
|
505
|
+
void Promise.resolve().then(reader.cancel.bind(reader)).catch(ignoreDownloadFailure);
|
|
506
|
+
}
|
|
507
|
+
|
|
355
508
|
async function writeDownloadChunk(output: WriteStream, chunk: Buffer, outputFinished: Promise<void>) {
|
|
356
509
|
if (output.destroyed) await outputFinished;
|
|
357
510
|
if (output.write(chunk)) return;
|
|
358
511
|
await Promise.race([once(output, "drain"), outputFinished]);
|
|
359
512
|
}
|
|
360
513
|
|
|
514
|
+
function ignoreDownloadFailure() {
|
|
515
|
+
// Best-effort cleanup must not replace the download failure already being handled.
|
|
516
|
+
}
|
|
517
|
+
|
|
361
518
|
export function getWhisperCppModelNameFromPath(modelPath: string) {
|
|
362
519
|
const match = /^ggml-(.+)\.(?:bin|gguf)$/i.exec(basename(modelPath));
|
|
363
520
|
return match?.[1];
|
package/src/processes.ts
CHANGED
|
@@ -60,27 +60,42 @@ export function spawnRecording(command: CommandSpec, audioPath: string, tempDir:
|
|
|
60
60
|
};
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
-
export
|
|
64
|
-
if (active.
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
63
|
+
export function stopProcess(active: Recording) {
|
|
64
|
+
if (active.stopPromise) return active.stopPromise;
|
|
65
|
+
active.stopPromise = stopProcessOnce(active);
|
|
66
|
+
return active.stopPromise;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function stopProcessOnce(active: Recording) {
|
|
70
|
+
if (active.isSettled()) return active.exitPromise;
|
|
71
|
+
|
|
72
|
+
active.stopRequested = true;
|
|
73
|
+
let exit: ExitResult | undefined;
|
|
74
|
+
if (sendStopInput(active)) {
|
|
75
|
+
exit = await raceWithTimeout(active.exitPromise, RECORDER_STOP_GRACE_MS);
|
|
76
|
+
}
|
|
77
|
+
if (!exit) {
|
|
78
|
+
sendStopSignal(active, "SIGINT");
|
|
79
|
+
exit = await raceWithTimeout(active.exitPromise, RECORDER_STOP_GRACE_MS);
|
|
80
|
+
}
|
|
81
|
+
if (!exit) {
|
|
82
|
+
sendStopSignal(active, "SIGTERM");
|
|
83
|
+
exit = await raceWithTimeout(active.exitPromise, 1_000);
|
|
84
|
+
}
|
|
85
|
+
if (!exit) {
|
|
86
|
+
sendStopSignal(active, "SIGKILL");
|
|
87
|
+
exit = await active.exitPromise;
|
|
88
|
+
}
|
|
89
|
+
return exit;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function sendStopSignal(active: Recording, signal: NodeJS.Signals) {
|
|
93
|
+
try {
|
|
94
|
+
if (!active.process.kill(signal)) return;
|
|
95
|
+
active.stopSignals ??= new Set();
|
|
96
|
+
active.stopSignals.add(signal);
|
|
97
|
+
} catch {
|
|
98
|
+
// The exit promise remains authoritative when the process settles during escalation.
|
|
84
99
|
}
|
|
85
100
|
}
|
|
86
101
|
|
|
@@ -96,7 +111,8 @@ export function sendStopInput(active: Recording) {
|
|
|
96
111
|
}
|
|
97
112
|
|
|
98
113
|
export async function stopRecorder(active: Recording) {
|
|
99
|
-
await stopProcess(active);
|
|
114
|
+
const exit = await stopProcess(active);
|
|
115
|
+
assertExpectedProcessExit(active, exit, "recorder");
|
|
100
116
|
|
|
101
117
|
const audioStats = await stat(active.audioPath).catch(() => undefined);
|
|
102
118
|
if (!audioStats || audioStats.size < MIN_AUDIO_BYTES) {
|
|
@@ -106,9 +122,9 @@ export async function stopRecorder(active: Recording) {
|
|
|
106
122
|
}
|
|
107
123
|
}
|
|
108
124
|
|
|
109
|
-
export function runShell(command: string, timeoutMs: number) {
|
|
125
|
+
export function runShell(command: string, timeoutMs: number, options: RunProcessOptions = {}) {
|
|
110
126
|
const spec = shellCommand(command);
|
|
111
|
-
return runProcess(spec.command, spec.args, timeoutMs);
|
|
127
|
+
return runProcess(spec.command, spec.args, timeoutMs, options);
|
|
112
128
|
}
|
|
113
129
|
|
|
114
130
|
export function shellCommand(command: string): CommandSpec {
|
|
@@ -118,18 +134,41 @@ export function shellCommand(command: string): CommandSpec {
|
|
|
118
134
|
return { command: "sh", args: ["-lc", command], display: command };
|
|
119
135
|
}
|
|
120
136
|
|
|
121
|
-
export
|
|
137
|
+
export type RunProcessOptions = {
|
|
138
|
+
signal?: AbortSignal;
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
export function runProcess(command: string, args: string[], timeoutMs: number, options: RunProcessOptions = {}): Promise<RunResult> {
|
|
122
142
|
return new Promise((resolve, reject) => {
|
|
143
|
+
if (options.signal?.aborted) {
|
|
144
|
+
resolve({ code: null, signal: null, stdout: "", stderr: "", timedOut: false, cancelled: true });
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
|
|
123
148
|
const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
|
|
124
149
|
let stdout = "";
|
|
125
150
|
let stderr = "";
|
|
126
151
|
let timedOut = false;
|
|
152
|
+
let cancelled = false;
|
|
127
153
|
let settled = false;
|
|
154
|
+
let abortTimer: ReturnType<typeof setTimeout> | undefined;
|
|
128
155
|
|
|
129
156
|
const timer = setTimeout(() => {
|
|
130
157
|
timedOut = true;
|
|
131
158
|
child.kill("SIGKILL");
|
|
132
159
|
}, timeoutMs);
|
|
160
|
+
const abort = () => {
|
|
161
|
+
if (settled) return;
|
|
162
|
+
cancelled = true;
|
|
163
|
+
child.kill("SIGTERM");
|
|
164
|
+
abortTimer = setTimeout(() => child.kill("SIGKILL"), 1_000);
|
|
165
|
+
};
|
|
166
|
+
const finish = () => {
|
|
167
|
+
clearTimeout(timer);
|
|
168
|
+
if (abortTimer) clearTimeout(abortTimer);
|
|
169
|
+
options.signal?.removeEventListener("abort", abort);
|
|
170
|
+
};
|
|
171
|
+
options.signal?.addEventListener("abort", abort, { once: true });
|
|
133
172
|
|
|
134
173
|
child.stdout?.setEncoding("utf8");
|
|
135
174
|
child.stderr?.setEncoding("utf8");
|
|
@@ -142,15 +181,16 @@ export function runProcess(command: string, args: string[], timeoutMs: number):
|
|
|
142
181
|
child.once("error", (error) => {
|
|
143
182
|
if (settled) return;
|
|
144
183
|
settled = true;
|
|
145
|
-
|
|
184
|
+
finish();
|
|
146
185
|
reject(error);
|
|
147
186
|
});
|
|
148
187
|
child.once("close", (code, signal) => {
|
|
149
188
|
if (settled) return;
|
|
150
189
|
settled = true;
|
|
151
|
-
|
|
152
|
-
resolve({ code, signal, stdout, stderr, timedOut });
|
|
190
|
+
finish();
|
|
191
|
+
resolve({ code, signal, stdout, stderr, timedOut, ...(cancelled ? { cancelled: true } : {}) });
|
|
153
192
|
});
|
|
193
|
+
if (options.signal?.aborted) abort();
|
|
154
194
|
});
|
|
155
195
|
}
|
|
156
196
|
|
|
@@ -263,7 +303,43 @@ export function formatExit(exit: ExitResult) {
|
|
|
263
303
|
return `code ${exit.code}`;
|
|
264
304
|
}
|
|
265
305
|
|
|
306
|
+
export function assertExpectedProcessExit(active: Recording, exit: ExitResult, label: string) {
|
|
307
|
+
if (isExpectedProcessExit(active, exit)) return;
|
|
308
|
+
const action = active.stopRequested ? "failed while stopping" : "exited unexpectedly";
|
|
309
|
+
const reason = formatProcessOutput(appendCapped("", formatExit(exit))) || "unknown process result";
|
|
310
|
+
const stderr = formatProcessOutput(active.stderr());
|
|
311
|
+
const suffix = stderr ? `\n${formatProcessLabel(label)} output:\n${stderr}` : "";
|
|
312
|
+
throw new Error(`Micme ${label} ${action} (${reason}).${suffix}`);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function isExpectedProcessExit(active: Recording, exit: ExitResult) {
|
|
316
|
+
if (!active.stopRequested || exit.error) return false;
|
|
317
|
+
if (exit.code === 0) return true;
|
|
318
|
+
if (exit.signal) return active.stopSignals?.has(exit.signal) ?? false;
|
|
319
|
+
if (exit.code === null || !active.stopSignals?.size) return false;
|
|
320
|
+
if (active.command.signalStopExitCodes?.includes(exit.code)) return true;
|
|
321
|
+
return [...active.stopSignals].some((signal) => exit.code === getSignalExitCode(signal));
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function getSignalExitCode(signal: NodeJS.Signals) {
|
|
325
|
+
switch (signal) {
|
|
326
|
+
case "SIGINT":
|
|
327
|
+
return 130;
|
|
328
|
+
case "SIGTERM":
|
|
329
|
+
return 143;
|
|
330
|
+
case "SIGKILL":
|
|
331
|
+
return 137;
|
|
332
|
+
default:
|
|
333
|
+
return undefined;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function formatProcessLabel(label: string) {
|
|
338
|
+
return label ? `${label[0]?.toUpperCase()}${label.slice(1)}` : "Process";
|
|
339
|
+
}
|
|
340
|
+
|
|
266
341
|
export function formatRunExit(result: RunResult) {
|
|
342
|
+
if (result.cancelled) return "cancelled";
|
|
267
343
|
if (result.timedOut) return "timeout";
|
|
268
344
|
if (result.signal) return `signal ${result.signal}`;
|
|
269
345
|
return `code ${result.code}`;
|