@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/src/settings.ts CHANGED
@@ -15,16 +15,18 @@ import {
15
15
  visibleWidth,
16
16
  } from "@earendil-works/pi-tui";
17
17
  import { basename } from "node:path";
18
- import {
19
- DEFAULT_RECORD_SAMPLE_RATE,
20
- DEFAULT_STREAM_VAD_THRESHOLD,
21
- DEFAULT_STREAM_FLUSH_MS,
22
- DEFAULT_TRANSCRIBE_SAMPLE_RATE,
23
- } from "./constants.ts";
24
18
  import {
25
19
  env,
26
20
  expandConfigPath,
21
+ getAutoDownloadModel,
22
+ getRecordSampleRate,
23
+ getRecordSync,
27
24
  getShortcutSettingValue,
25
+ getStreamCapture,
26
+ getStreamFlushMs,
27
+ getStreamVadThreshold,
28
+ getStreamWordsPerChunk,
29
+ getTranscribeSampleRate,
28
30
  getTranscriptionMode,
29
31
  getTranscriptionModeProfile,
30
32
  reloadMicmeConfig,
@@ -110,6 +112,7 @@ export async function showConfiguration(ctx: ExtensionContext) {
110
112
  }
111
113
  await ctx.ui.custom<void>((tui, theme, _keybindings, done) => {
112
114
  const discovery = createInitialConfigurationDiscovery();
115
+ const controller = new AbortController();
113
116
  let closed = false;
114
117
  const screen = new ConfigurationScreen({
115
118
  configPath: sanitizeTerminalOutput(configState.path) || "micme.json",
@@ -117,10 +120,11 @@ export async function showConfiguration(ctx: ExtensionContext) {
117
120
  theme,
118
121
  onDone: () => {
119
122
  closed = true;
123
+ controller.abort();
120
124
  done();
121
125
  },
122
126
  onError: (error) => notifySanitized(ctx, error instanceof Error ? error.message : String(error), "error"),
123
- onSave: (id, newValue) => saveConfigurationValue(ctx, id, newValue),
127
+ onSave: (id, newValue) => saveConfigurationValue(ctx, id, newValue, { signal: controller.signal }),
124
128
  requestRender: () => tui.requestRender(),
125
129
  statusText: formatDiscoveryStatus(discovery.pending),
126
130
  });
@@ -231,6 +235,7 @@ class ConfigurationScreen implements Component {
231
235
  private pendingShortcutValue = "";
232
236
  private saving = false;
233
237
  private statusText = "";
238
+ private closed = false;
234
239
 
235
240
  constructor(options: {
236
241
  configPath: string;
@@ -254,6 +259,7 @@ class ConfigurationScreen implements Component {
254
259
  }
255
260
 
256
261
  updateDiscoveredItems(items: ConfigurationItem[], statusText: string) {
262
+ if (this.closed) return;
257
263
  this.items = items;
258
264
  this.refreshDerivedItems();
259
265
  this.clampSelections();
@@ -275,6 +281,7 @@ class ConfigurationScreen implements Component {
275
281
  }
276
282
 
277
283
  handleInput(data: string): void {
284
+ if (this.closed) return;
278
285
  if (this.forwardSubmenuInput(data)) return;
279
286
  if (this.forwardShortcutCaptureInput(data)) return;
280
287
  if (this.handleCloseInput(data)) return;
@@ -305,10 +312,16 @@ class ConfigurationScreen implements Component {
305
312
 
306
313
  private handleCloseInput(data: string) {
307
314
  if (!matchesKey(data, Key.ctrl("c")) && data !== "q" && data !== "Q") return false;
308
- this.onDone();
315
+ this.close();
309
316
  return true;
310
317
  }
311
318
 
319
+ private close() {
320
+ if (this.closed) return;
321
+ this.closed = true;
322
+ this.onDone();
323
+ }
324
+
312
325
  private handlePaneSwitchInput(data: string) {
313
326
  if (!matchesKey(data, Key.tab) && !matchesKey(data, Key.shift("tab"))) return false;
314
327
  this.focusedPane = this.focusedPane === "categories" ? "settings" : "categories";
@@ -351,7 +364,7 @@ class ConfigurationScreen implements Component {
351
364
  this.focusedPane = "categories";
352
365
  this.requestRender();
353
366
  } else {
354
- this.onDone();
367
+ this.close();
355
368
  }
356
369
  }
357
370
 
@@ -715,16 +728,19 @@ class ConfigurationScreen implements Component {
715
728
 
716
729
  void this.onSave(item.id, nextValue)
717
730
  .then((updatedValues) => {
731
+ if (this.closed) return;
718
732
  this.updateValues(updatedValues);
719
733
  this.refreshDerivedItems();
720
734
  this.clampSelections();
721
735
  this.statusText = formatSaveStatus(item.id, nextValue);
722
736
  })
723
737
  .catch((error) => {
738
+ if (this.closed) return;
724
739
  this.statusText = "Save failed";
725
740
  this.onError(error);
726
741
  })
727
742
  .finally(() => {
743
+ if (this.closed) return;
728
744
  this.saving = false;
729
745
  this.requestRender();
730
746
  });
@@ -856,8 +872,8 @@ export function buildConfigurationItems(
856
872
  categoryId: "general",
857
873
  label: "Auto-download models",
858
874
  description: "Download missing whisper.cpp models automatically when selected or first used.",
859
- rawValue: env("MICME_AUTO_DOWNLOAD_MODEL") ?? "1",
860
- currentValue: env("MICME_AUTO_DOWNLOAD_MODEL") ?? "1",
875
+ rawValue: getAutoDownloadModel() ? "1" : "0",
876
+ currentValue: getAutoDownloadModel() ? "1" : "0",
861
877
  values: ["1", "0"],
862
878
  displayKind: "boolean",
863
879
  },
@@ -956,9 +972,9 @@ export function buildConfigurationItems(
956
972
  id: "MICME_STREAM_CAPTURE",
957
973
  categoryId: "streaming",
958
974
  label: "Stream capture device",
959
- description: "whisper-stream/SDL capture id. Use -1 for the system default; ffmpeg device ids may not match.",
960
- rawValue: env("MICME_STREAM_CAPTURE") ?? "-1",
961
- currentValue: env("MICME_STREAM_CAPTURE") ?? "-1",
975
+ description: "whisper-stream/SDL capture id from -1 through 255. Use -1 for the system default; ffmpeg device ids may not match.",
976
+ rawValue: String(getStreamCapture()),
977
+ currentValue: String(getStreamCapture()),
962
978
  values: ["-1", "0", "1", "2", "3", "4", "5"],
963
979
  displayKind: "number",
964
980
  },
@@ -976,9 +992,9 @@ export function buildConfigurationItems(
976
992
  id: "MICME_STREAM_FLUSH_MS",
977
993
  categoryId: "streaming",
978
994
  label: "Stream flush delay",
979
- description: "Quiet interval before tentative stream words are committed append-only into the editor.",
980
- rawValue: env("MICME_STREAM_FLUSH_MS") ?? String(DEFAULT_STREAM_FLUSH_MS),
981
- currentValue: env("MICME_STREAM_FLUSH_MS") ?? String(DEFAULT_STREAM_FLUSH_MS),
995
+ description: "Quiet interval from 100 through 60000 ms before tentative stream words are committed append-only into the editor.",
996
+ rawValue: String(getStreamFlushMs()),
997
+ currentValue: String(getStreamFlushMs()),
982
998
  values: ["400", "650", "700", "1000"],
983
999
  displayKind: "number",
984
1000
  },
@@ -996,9 +1012,9 @@ export function buildConfigurationItems(
996
1012
  id: "MICME_STREAM_VAD_THRESHOLD",
997
1013
  categoryId: "streaming",
998
1014
  label: "Stream VAD threshold",
999
- description: "Lower is more sensitive; raise it if background noise causes hallucinations.",
1000
- rawValue: env("MICME_STREAM_VAD_THRESHOLD") ?? String(DEFAULT_STREAM_VAD_THRESHOLD),
1001
- currentValue: env("MICME_STREAM_VAD_THRESHOLD") ?? String(DEFAULT_STREAM_VAD_THRESHOLD),
1015
+ description: "Value from 0.01 through 0.99. Lower is more sensitive; raise it if background noise causes hallucinations.",
1016
+ rawValue: String(getStreamVadThreshold()),
1017
+ currentValue: String(getStreamVadThreshold()),
1002
1018
  values: ["0.35", "0.45", "0.60", "0.75"],
1003
1019
  displayKind: "slider",
1004
1020
  },
@@ -1006,9 +1022,9 @@ export function buildConfigurationItems(
1006
1022
  id: "MICME_STREAM_WORDS_PER_CHUNK",
1007
1023
  categoryId: "streaming",
1008
1024
  label: "Stream word chunk",
1009
- description: "Maximum stable words committed per streaming update.",
1010
- rawValue: env("MICME_STREAM_WORDS_PER_CHUNK") ?? "10",
1011
- currentValue: env("MICME_STREAM_WORDS_PER_CHUNK") ?? "10",
1025
+ description: "Maximum stable words from 1 through 10 committed per streaming update.",
1026
+ rawValue: String(getStreamWordsPerChunk()),
1027
+ currentValue: String(getStreamWordsPerChunk()),
1012
1028
  values: ["3", "5", "8", "10"],
1013
1029
  displayKind: "number",
1014
1030
  },
@@ -1027,9 +1043,9 @@ export function buildConfigurationItems(
1027
1043
  id: "MICME_RECORD_SAMPLE_RATE",
1028
1044
  categoryId: "audio",
1029
1045
  label: "Sample rate override",
1030
- description: "Advanced. Leave auto so ffmpeg uses the selected input's native sample rate.",
1031
- rawValue: env("MICME_RECORD_SAMPLE_RATE") ?? String(DEFAULT_RECORD_SAMPLE_RATE),
1032
- currentValue: env("MICME_RECORD_SAMPLE_RATE") ?? String(DEFAULT_RECORD_SAMPLE_RATE),
1046
+ description: "Advanced. Leave auto so ffmpeg uses the selected input's native sample rate, or use 8000 through 384000 Hz.",
1047
+ rawValue: String(getRecordSampleRate() ?? "auto"),
1048
+ currentValue: String(getRecordSampleRate() ?? "auto"),
1033
1049
  values: ["auto", "48000", "44100", "16000", "96000"],
1034
1050
  displayKind: "text",
1035
1051
  },
@@ -1038,8 +1054,8 @@ export function buildConfigurationItems(
1038
1054
  categoryId: "audio",
1039
1055
  label: "Record timing sync",
1040
1056
  description: "Automatically preserve wall-clock recording duration from ffmpeg timestamps. Keep on unless debugging recorder timing.",
1041
- rawValue: env("MICME_RECORD_SYNC") ?? "1",
1042
- currentValue: env("MICME_RECORD_SYNC") ?? "1",
1057
+ rawValue: getRecordSync() ? "1" : "0",
1058
+ currentValue: getRecordSync() ? "1" : "0",
1043
1059
  values: ["1", "0"],
1044
1060
  displayKind: "boolean",
1045
1061
  },
@@ -1047,9 +1063,9 @@ export function buildConfigurationItems(
1047
1063
  id: "MICME_TRANSCRIBE_SAMPLE_RATE",
1048
1064
  categoryId: "audio",
1049
1065
  label: "Transcribe sample rate",
1050
- description: "Sample rate for clip.wav sent to Whisper.",
1051
- rawValue: env("MICME_TRANSCRIBE_SAMPLE_RATE") ?? String(DEFAULT_TRANSCRIBE_SAMPLE_RATE),
1052
- currentValue: env("MICME_TRANSCRIBE_SAMPLE_RATE") ?? String(DEFAULT_TRANSCRIBE_SAMPLE_RATE),
1066
+ description: "Sample rate from 8000 through 384000 Hz for clip.wav sent to Whisper.",
1067
+ rawValue: String(getTranscribeSampleRate()),
1068
+ currentValue: String(getTranscribeSampleRate()),
1053
1069
  values: ["16000", "48000", "44100"],
1054
1070
  displayKind: "number",
1055
1071
  },
@@ -1112,7 +1128,7 @@ export function buildConfigurationItems(
1112
1128
  id: "MICME_VALIDATE_AUDIO",
1113
1129
  categoryId: "audio",
1114
1130
  label: "Silence guard",
1115
- description: "Reject near-silent clips before Whisper can hallucinate text.",
1131
+ description: "Reject near-silent or unverified clips before Whisper can hallucinate text.",
1116
1132
  rawValue: env("MICME_VALIDATE_AUDIO") ?? "1",
1117
1133
  currentValue: env("MICME_VALIDATE_AUDIO") ?? "1",
1118
1134
  values: ["1", "0"],
@@ -1192,15 +1208,17 @@ export function createModelSelector(candidates: ModelCandidate[], theme: MicmeTh
1192
1208
  };
1193
1209
  }
1194
1210
 
1195
- export async function saveConfigurationValue(ctx: ExtensionContext, id: string, value: string): Promise<Record<string, string>> {
1211
+ export async function saveConfigurationValue(ctx: ExtensionContext, id: string, value: string, options: { signal?: AbortSignal } = {}): Promise<Record<string, string>> {
1196
1212
  if (!id.startsWith("MICME_")) return {};
1213
+ options.signal?.throwIfAborted();
1197
1214
 
1198
1215
  const valuesToWrite = getConfigurationValuesToWrite(id, value);
1199
1216
  if (id === "MICME_WHISPER_CPP_MODEL" && value) {
1200
- await ensureWhisperCppModel(expandConfigPath(value), ctx);
1217
+ await ensureWhisperCppModel(expandConfigPath(value), ctx, { signal: options.signal });
1201
1218
  }
1202
1219
 
1203
- await writeMicmeConfigValues(valuesToWrite);
1220
+ options.signal?.throwIfAborted();
1221
+ await writeMicmeConfigValues(valuesToWrite, { signal: options.signal });
1204
1222
  reloadMicmeConfig();
1205
1223
 
1206
1224
  const effectiveValues: Record<string, string> = {};
package/src/streaming.ts CHANGED
@@ -3,6 +3,7 @@ import { MAX_CAPTURED_OUTPUT_CHARS } from "./constants.ts";
3
3
  import {
4
4
  env,
5
5
  envFlag,
6
+ getStreamCapture,
6
7
  getTranslateToEnglishLanguage,
7
8
  getStreamFlushMs,
8
9
  getStreamKeepContext,
@@ -53,8 +54,7 @@ export function buildWhisperStreamCommand(binary: string, modelPath: string, _te
53
54
 
54
55
  if (getStreamKeepContext()) args.push("--keep-context");
55
56
 
56
- const capture = env("MICME_STREAM_CAPTURE");
57
- if (capture?.trim()) args.push("--capture", capture.trim());
57
+ args.push("--capture", String(getStreamCapture()));
58
58
 
59
59
  const translateLanguage = getTranslateToEnglishLanguage();
60
60
  if (translateLanguage) {
@@ -9,19 +9,19 @@ import { formatProcessOutput, formatRunExit, replacePlaceholders, runProcess, ru
9
9
 
10
10
  export { getWhisperCppBinary, getWhisperStreamBinary, resolveExecutableConfig } from "./backends.ts";
11
11
 
12
- export async function transcribe(audioPath: string, tempDir: string, ctx?: ExtensionContext): Promise<string> {
12
+ export async function transcribe(audioPath: string, tempDir: string, ctx?: ExtensionContext, signal?: AbortSignal): Promise<string> {
13
13
  const plan = resolveTranscriptionPlan({ transcriptionMode: "clip" });
14
14
 
15
15
  switch (plan.effectiveBackend) {
16
16
  case "custom":
17
17
  if (!plan.command) break;
18
- return transcribeWithCustomCommand(plan.command, audioPath, tempDir);
18
+ return transcribeWithCustomCommand(plan.command, audioPath, tempDir, signal);
19
19
  case "whisper.cpp":
20
20
  if (!plan.binary || !plan.modelPath) break;
21
- return transcribeWithWhisperCpp(plan.binary, plan.modelPath, audioPath, tempDir, ctx, { allowDownload: plan.modelDownloadable !== false });
21
+ return transcribeWithWhisperCpp(plan.binary, plan.modelPath, audioPath, tempDir, ctx, { allowDownload: plan.modelDownloadable !== false, signal });
22
22
  case "python":
23
23
  if (!plan.binary) break;
24
- return transcribeWithOpenAiWhisper(plan.binary, audioPath, tempDir, plan.modelName);
24
+ return transcribeWithOpenAiWhisper(plan.binary, audioPath, tempDir, plan.modelName, signal);
25
25
  case "none":
26
26
  break;
27
27
  }
@@ -29,10 +29,10 @@ export async function transcribe(audioPath: string, tempDir: string, ctx?: Exten
29
29
  throw new Error(formatTranscriptionPlan(plan));
30
30
  }
31
31
 
32
- export async function transcribeWithCustomCommand(template: string, audioPath: string, tempDir: string) {
32
+ export async function transcribeWithCustomCommand(template: string, audioPath: string, tempDir: string, signal?: AbortSignal) {
33
33
  const transcriptPath = join(tempDir, "transcript.txt");
34
34
  const command = replacePlaceholders(template, { audio: audioPath, tempDir, transcript: transcriptPath });
35
- const result = await runShell(command, getTranscribeTimeoutMs());
35
+ const result = await runShell(command, getTranscribeTimeoutMs(), { signal });
36
36
  if (result.code !== 0) {
37
37
  throw new Error(`MICME_TRANSCRIBE_COMMAND failed (${formatRunExit(result)}):\n${formatProcessOutput(result.stderr, result.stdout)}`);
38
38
  }
@@ -51,7 +51,7 @@ export async function transcribeWithWhisperCpp(
51
51
  audioPath: string,
52
52
  tempDir: string,
53
53
  ctx?: ExtensionContext,
54
- options: { allowDownload?: boolean } = {},
54
+ options: { allowDownload?: boolean; signal?: AbortSignal } = {},
55
55
  ) {
56
56
  await ensureWhisperCppModel(modelPath, ctx, options);
57
57
  const outputBase = join(tempDir, "whisper-cpp");
@@ -64,7 +64,7 @@ export async function transcribeWithWhisperCpp(
64
64
  if (language?.trim()) args.push("-l", language.trim());
65
65
  }
66
66
 
67
- const result = await runProcess(binary, args, getTranscribeTimeoutMs());
67
+ const result = await runProcess(binary, args, getTranscribeTimeoutMs(), { signal: options.signal });
68
68
  if (result.code !== 0) {
69
69
  throw new Error(`whisper.cpp failed (${formatRunExit(result)}):\n${formatProcessOutput(result.stderr, result.stdout)}`);
70
70
  }
@@ -78,7 +78,7 @@ export async function transcribeWithWhisperCpp(
78
78
  return result.stdout;
79
79
  }
80
80
 
81
- export async function transcribeWithOpenAiWhisper(binary: string, audioPath: string, tempDir: string, modelName?: string) {
81
+ export async function transcribeWithOpenAiWhisper(binary: string, audioPath: string, tempDir: string, modelName?: string, signal?: AbortSignal) {
82
82
  const model = modelName || getPythonWhisperModelName();
83
83
  const args = [
84
84
  audioPath,
@@ -109,7 +109,7 @@ export async function transcribeWithOpenAiWhisper(binary: string, audioPath: str
109
109
  if (fp16?.trim()) args.push("--fp16", fp16.trim());
110
110
  else args.push("--fp16", "False");
111
111
 
112
- const result = await runProcess(binary, args, getTranscribeTimeoutMs());
112
+ const result = await runProcess(binary, args, getTranscribeTimeoutMs(), { signal });
113
113
  if (result.code !== 0) {
114
114
  throw new Error(`openai-whisper failed (${formatRunExit(result)}):\n${formatProcessOutput(result.stderr, result.stdout)}`);
115
115
  }
package/src/types.ts CHANGED
@@ -35,6 +35,7 @@ export type CommandSpec = {
35
35
  display: string;
36
36
  meterFromStdout?: boolean;
37
37
  stopInput?: string;
38
+ signalStopExitCodes?: number[];
38
39
  };
39
40
 
40
41
  export type RunResult = {
@@ -43,6 +44,7 @@ export type RunResult = {
43
44
  stdout: string;
44
45
  stderr: string;
45
46
  timedOut: boolean;
47
+ cancelled?: boolean;
46
48
  };
47
49
 
48
50
  export type ExitResult = {
@@ -53,10 +55,14 @@ export type ExitResult = {
53
55
 
54
56
  export type AudioDiagnostics = {
55
57
  meanVolumeDb?: number;
56
- maxVolumeDb?: number;
58
+ maxVolumeDb: number;
57
59
  raw: string;
58
60
  };
59
61
 
62
+ export type AudioValidationOutcome =
63
+ | { status: "validated"; diagnostics: AudioDiagnostics }
64
+ | { status: "skipped"; reason: "disabled" | "ffmpeg-unavailable" };
65
+
60
66
  export type StreamingState = {
61
67
  baseText: string;
62
68
  previewText: string;
@@ -81,6 +87,8 @@ export type Recording = {
81
87
  streaming?: StreamingState;
82
88
  clipRecording?: Recording;
83
89
  stopRequested?: boolean;
90
+ stopSignals?: Set<NodeJS.Signals>;
91
+ stopPromise?: Promise<ExitResult>;
84
92
  exitPromise: Promise<ExitResult>;
85
93
  isSettled: () => boolean;
86
94
  stdout: () => string;
package/tsconfig.json CHANGED
@@ -11,5 +11,5 @@
11
11
  "allowImportingTsExtensions": true,
12
12
  "types": ["node"]
13
13
  },
14
- "include": ["src/**/*.ts"]
14
+ "include": ["src/**/*.ts", "test/pi-contract-types.ts"]
15
15
  }