@senad-d/micme 0.3.2 → 0.3.4

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/backends.ts CHANGED
@@ -5,8 +5,10 @@ import { env, expandConfigPath, getTranscribeBackend, getTranslateToEnglishLangu
5
5
  import { getPythonWhisperModelName, isEnglishOnlyWhisperModelName, isTranslationUnsupportedWhisperModelName, resolveWhisperCppModel } from "./models.ts";
6
6
  import { findExecutable, isExecutableFile } from "./processes.ts";
7
7
 
8
+ export type RequestedTranscribeBackend = TranscribeBackend | (string & Record<never, never>);
9
+
8
10
  export type ResolveTranscriptionPlanOptions = {
9
- requestedBackend?: TranscribeBackend | string;
11
+ requestedBackend?: RequestedTranscribeBackend;
10
12
  transcriptionMode?: TranscriptionMode;
11
13
  customCommand?: string | null;
12
14
  whisperCppBinary?: string | null;
@@ -32,34 +34,34 @@ export function resolveTranscriptionPlan(options: ResolveTranscriptionPlanOption
32
34
  customCommand: customCommand ?? undefined,
33
35
  whisperCppModel,
34
36
  warnings,
35
- whisperStreamBinary: getExecutableOption(options, "whisperStreamBinary", "whisperStreamBinaryError", getWhisperStreamBinary),
37
+ whisperStreamBinary: getExecutableOption(options, "whisperStreamBinary", "whisperStreamBinaryError", getWhisperStreamBinary, warnings),
36
38
  });
37
39
  }
38
40
 
39
- const whisperCppBinary = getExecutableOption(options, "whisperCppBinary", "whisperCppBinaryError", getWhisperCppBinary);
41
+ const whisperCppBinary = getExecutableOption(options, "whisperCppBinary", "whisperCppBinaryError", getWhisperCppBinary, warnings);
40
42
  const pythonWhisperBinary = getOptionValue(options, "pythonWhisperBinary", getPythonWhisperBinary);
41
43
 
42
44
  if (requestedBackend === "custom") {
43
45
  return customCommand
44
- ? customPlan(requestedBackend, customCommand, "MICME_TRANSCRIBE_BACKEND=custom")
46
+ ? customPlan(requestedBackend, customCommand, "MICME_TRANSCRIBE_BACKEND=custom", warnings)
45
47
  : nonePlan(requestedBackend, "MICME_TRANSCRIBE_BACKEND=custom but MICME_TRANSCRIBE_COMMAND is not set.", warnings);
46
48
  }
47
49
 
48
50
  if (requestedBackend === "whisper.cpp") {
49
51
  return whisperCppBinary
50
- ? whisperCppPlan(requestedBackend, whisperCppBinary, whisperCppModel, "MICME_TRANSCRIBE_BACKEND=whisper.cpp")
52
+ ? whisperCppPlan(requestedBackend, whisperCppBinary, whisperCppModel, "MICME_TRANSCRIBE_BACKEND=whisper.cpp", warnings)
51
53
  : nonePlan(requestedBackend, "MICME_TRANSCRIBE_BACKEND=whisper.cpp but whisper.cpp was not found.", warnings);
52
54
  }
53
55
 
54
56
  if (requestedBackend === "python") {
55
57
  return pythonWhisperBinary
56
- ? pythonPlan(requestedBackend, pythonWhisperBinary, pythonModelName, "MICME_TRANSCRIBE_BACKEND=python")
58
+ ? pythonPlan(requestedBackend, pythonWhisperBinary, pythonModelName, "MICME_TRANSCRIBE_BACKEND=python", warnings)
57
59
  : nonePlan(requestedBackend, "MICME_TRANSCRIBE_BACKEND=python but the `whisper` CLI was not found.", warnings);
58
60
  }
59
61
 
60
- if (customCommand) return customPlan(requestedBackend, customCommand, "auto selected custom command because MICME_TRANSCRIBE_COMMAND is configured");
61
- if (whisperCppBinary) return whisperCppPlan(requestedBackend, whisperCppBinary, whisperCppModel, "auto selected whisper.cpp because a whisper.cpp binary is available");
62
- if (pythonWhisperBinary) return pythonPlan(requestedBackend, pythonWhisperBinary, pythonModelName, "auto selected Python Whisper because whisper.cpp is unavailable");
62
+ if (customCommand) return customPlan(requestedBackend, customCommand, "auto selected custom command because MICME_TRANSCRIBE_COMMAND is configured", warnings);
63
+ if (whisperCppBinary) return whisperCppPlan(requestedBackend, whisperCppBinary, whisperCppModel, "auto selected whisper.cpp because a whisper.cpp binary is available", warnings);
64
+ if (pythonWhisperBinary) return pythonPlan(requestedBackend, pythonWhisperBinary, pythonModelName, "auto selected Python Whisper because whisper.cpp is unavailable", warnings);
63
65
 
64
66
  return nonePlan(
65
67
  requestedBackend,
@@ -153,10 +155,10 @@ function resolveStreamingPlan(options: {
153
155
  : "MICME_TRANSCRIBE_BACKEND=whisper.cpp and MICME_TRANSCRIPTION_MODE=stream but whisper-stream was not found.";
154
156
  return nonePlan(requestedBackend, reason, warnings);
155
157
  }
156
- return whisperCppPlan(requestedBackend, whisperStreamBinary, whisperCppModel, "streaming selected whisper.cpp because whisper-stream is available");
158
+ return whisperCppPlan(requestedBackend, whisperStreamBinary, whisperCppModel, "streaming selected whisper.cpp because whisper-stream is available", warnings);
157
159
  }
158
160
 
159
- function customPlan(requestedBackend: TranscribeBackend, command: string, reason: string): ResolvedTranscriptionPlan {
161
+ function customPlan(requestedBackend: TranscribeBackend, command: string, reason: string, inheritedWarnings: string[] = []): ResolvedTranscriptionPlan {
160
162
  return {
161
163
  requestedBackend,
162
164
  effectiveBackend: "custom",
@@ -164,12 +166,12 @@ function customPlan(requestedBackend: TranscribeBackend, command: string, reason
164
166
  command,
165
167
  modelName: "unknown",
166
168
  modelSource: "custom-command",
167
- warnings: [],
169
+ warnings: [...inheritedWarnings],
168
170
  };
169
171
  }
170
172
 
171
- function whisperCppPlan(requestedBackend: TranscribeBackend, binary: string, model: ResolvedWhisperCppModel, reason: string): ResolvedTranscriptionPlan {
172
- const warnings: string[] = [];
173
+ function whisperCppPlan(requestedBackend: TranscribeBackend, binary: string, model: ResolvedWhisperCppModel, reason: string, inheritedWarnings: string[] = []): ResolvedTranscriptionPlan {
174
+ const warnings: string[] = [...inheritedWarnings];
173
175
  if (model.source === "explicit-path" && !model.exists && !model.downloadable) {
174
176
  warnings.push(`MICME_WHISPER_CPP_MODEL is set but not found: ${model.path}`);
175
177
  } else if (!model.exists && !model.downloadable) {
@@ -192,7 +194,7 @@ function whisperCppPlan(requestedBackend: TranscribeBackend, binary: string, mod
192
194
  };
193
195
  }
194
196
 
195
- function pythonPlan(requestedBackend: TranscribeBackend, binary: string, modelName: string, reason: string): ResolvedTranscriptionPlan {
197
+ function pythonPlan(requestedBackend: TranscribeBackend, binary: string, modelName: string, reason: string, inheritedWarnings: string[] = []): ResolvedTranscriptionPlan {
196
198
  return {
197
199
  requestedBackend,
198
200
  effectiveBackend: "python",
@@ -200,7 +202,7 @@ function pythonPlan(requestedBackend: TranscribeBackend, binary: string, modelNa
200
202
  binary,
201
203
  modelName,
202
204
  modelSource: "python-name",
203
- warnings: getTranslationModelWarnings(modelName),
205
+ warnings: [...inheritedWarnings, ...getTranslationModelWarnings(modelName)],
204
206
  };
205
207
  }
206
208
 
@@ -220,7 +222,7 @@ function nonePlan(requestedBackend: TranscribeBackend, reason: string, warnings:
220
222
  };
221
223
  }
222
224
 
223
- function parseRequestedBackend(value: TranscribeBackend | string | undefined, warnings: string[]) {
225
+ function parseRequestedBackend(value: RequestedTranscribeBackend | undefined, warnings: string[]) {
224
226
  const raw = value ?? env("MICME_TRANSCRIBE_BACKEND")?.trim();
225
227
  if (!raw) return getTranscribeBackend();
226
228
  if (isTranscribeBackend(raw)) return raw;
@@ -233,7 +235,7 @@ function getOptionValue<K extends keyof ResolveTranscriptionPlanOptions>(
233
235
  key: K,
234
236
  fallback: () => Extract<ResolveTranscriptionPlanOptions[K], string | null | undefined>,
235
237
  ) {
236
- if (Object.prototype.hasOwnProperty.call(options, key)) {
238
+ if (Object.hasOwn(options, key)) {
237
239
  const value = options[key];
238
240
  return typeof value === "string" && value.trim() ? value.trim() : undefined;
239
241
  }
@@ -246,16 +248,21 @@ function getExecutableOption(
246
248
  key: "whisperCppBinary" | "whisperStreamBinary",
247
249
  errorKey: "whisperCppBinaryError" | "whisperStreamBinaryError",
248
250
  fallback: () => string | undefined,
251
+ warnings: string[] = [],
249
252
  ) {
250
253
  const error = options[errorKey];
251
- if (error) return undefined;
252
- if (Object.prototype.hasOwnProperty.call(options, key)) {
254
+ if (error) {
255
+ warnings.push(error);
256
+ return undefined;
257
+ }
258
+ if (Object.hasOwn(options, key)) {
253
259
  const value = options[key];
254
260
  return typeof value === "string" && value.trim() ? value.trim() : undefined;
255
261
  }
256
262
  try {
257
263
  return fallback();
258
- } catch {
264
+ } catch (error) {
265
+ warnings.push(error instanceof Error ? error.message : String(error));
259
266
  return undefined;
260
267
  }
261
268
  }
package/src/config.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { existsSync, readFileSync } from "node:fs";
2
3
  import { mkdir, rename, rm, writeFile } from "node:fs/promises";
3
4
  import { createRequire } from "node:module";
@@ -6,7 +7,6 @@ import { dirname, join, resolve } from "node:path";
6
7
  import type { MicmeConfigState, TranscribeBackend, TranscriptionMode } from "./types.ts";
7
8
  import {
8
9
  DEFAULT_MACOS_PRINTABLE_SHORTCUT,
9
- DEFAULT_RECORD_SAMPLE_RATE,
10
10
  DEFAULT_SHORTCUT,
11
11
  DEFAULT_STREAM_KEEP_MS,
12
12
  DEFAULT_STREAM_LENGTH_MS,
@@ -94,7 +94,7 @@ export async function writeMicmeConfigValues(values: Record<string, string | und
94
94
  }
95
95
 
96
96
  await mkdir(configDir, { recursive: true });
97
- const tempPath = join(configDir, `.micme.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);
97
+ const tempPath = join(configDir, `.micme.${process.pid}.${Date.now()}.${randomUUID()}.tmp`);
98
98
  try {
99
99
  await writeFile(tempPath, `${JSON.stringify(next, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
100
100
  await rename(tempPath, configPath);
@@ -143,7 +143,7 @@ export function expandConfigPath(value: string) {
143
143
 
144
144
  export function expandEnvReferences(value: string, configValues: Record<string, string>) {
145
145
  const withHome = value.startsWith("~/") && process.env.HOME ? `${process.env.HOME}${value.slice(1)}` : value;
146
- return withHome.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (_match, braced: string | undefined, bare: string | undefined) => {
146
+ return withHome.replace(/\$\{([A-Za-z_]\w*)\}|\$([A-Za-z_]\w*)/g, (_match, braced: string | undefined, bare: string | undefined) => {
147
147
  const key = braced ?? bare ?? "";
148
148
  return process.env[key] ?? configValues[key] ?? "";
149
149
  });
@@ -190,13 +190,32 @@ export function isTranscribeBackend(value: string | undefined): value is Transcr
190
190
  return value === "auto" || value === "whisper.cpp" || value === "python" || value === "custom";
191
191
  }
192
192
 
193
+ const NAMED_TERMINAL_KEYS = new Set([
194
+ "escape",
195
+ "esc",
196
+ "enter",
197
+ "return",
198
+ "tab",
199
+ "space",
200
+ "backspace",
201
+ "delete",
202
+ "insert",
203
+ "clear",
204
+ "home",
205
+ "end",
206
+ "pageup",
207
+ "pagedown",
208
+ "up",
209
+ "down",
210
+ "left",
211
+ "right",
212
+ ]);
213
+ const FUNCTION_TERMINAL_KEY_PATTERN = /^f\d{1,2}$/i;
214
+ const MODIFIED_TERMINAL_KEY_PATTERN = /^(?:(?:ctrl|control|alt|option|meta|cmd|command|shift|super)\+)+.+$/i;
215
+
193
216
  export function getPrintableShortcuts() {
194
217
  const shortcut = env("MICME_SHORTCUT");
195
- if (shortcut !== undefined) {
196
- if (shortcut && !isTerminalShortcut(shortcut)) return splitShortcutValues(shortcut);
197
- const legacyConfigured = env("MICME_PRINTABLE_SHORTCUTS");
198
- return legacyConfigured !== undefined ? splitShortcutValues(legacyConfigured) : [];
199
- }
218
+ if (shortcut !== undefined) return getPrintableShortcutsForUnifiedShortcut(shortcut);
200
219
 
201
220
  const legacyConfigured = env("MICME_PRINTABLE_SHORTCUTS");
202
221
  if (legacyConfigured !== undefined) return splitShortcutValues(legacyConfigured);
@@ -209,7 +228,29 @@ export function matchesPrintableMicmeShortcut(data: string) {
209
228
 
210
229
  export function isTerminalShortcut(value: string) {
211
230
  const normalized = value.trim();
212
- return /^[\x20-\x7E]$/.test(normalized) || /^(?:escape|esc|enter|return|tab|space|backspace|delete|insert|clear|home|end|pageUp|pageDown|up|down|left|right|f\d{1,2}|(?:(?:ctrl|control|alt|option|meta|cmd|command|shift|super)\+)+.+)$/i.test(normalized);
231
+ return isPrintableAsciiCharacter(normalized) || isNamedTerminalKey(normalized) || FUNCTION_TERMINAL_KEY_PATTERN.test(normalized) || MODIFIED_TERMINAL_KEY_PATTERN.test(normalized);
232
+ }
233
+
234
+ function getPrintableShortcutsForUnifiedShortcut(shortcut: string) {
235
+ if (shortcut && isTerminalShortcut(shortcut)) return getConfiguredLegacyPrintableShortcuts();
236
+ if (shortcut) return splitShortcutValues(shortcut);
237
+ return getConfiguredLegacyPrintableShortcuts();
238
+ }
239
+
240
+ function getConfiguredLegacyPrintableShortcuts() {
241
+ const legacyConfigured = env("MICME_PRINTABLE_SHORTCUTS");
242
+ return legacyConfigured === undefined ? [] : splitShortcutValues(legacyConfigured);
243
+ }
244
+
245
+ function isPrintableAsciiCharacter(value: string) {
246
+ const characters = Array.from(value);
247
+ if (characters.length !== 1) return false;
248
+ const codePoint = characters[0]?.codePointAt(0);
249
+ return codePoint !== undefined && codePoint >= 0x20 && codePoint <= 0x7E;
250
+ }
251
+
252
+ function isNamedTerminalKey(value: string) {
253
+ return NAMED_TERMINAL_KEYS.has(value.toLowerCase());
213
254
  }
214
255
 
215
256
  function firstShortcutValue(value: string | undefined) {
@@ -346,7 +387,7 @@ function readMicmeJsonObjectForWrite(configPath: string): JsonObject {
346
387
  return parsed;
347
388
  } catch (error) {
348
389
  const message = error instanceof Error ? error.message : String(error);
349
- throw new Error(`Cannot save Micme config: ${configPath} is invalid JSON (${message}). Fix or remove it first.`);
390
+ throw new Error(`Cannot save Micme config: ${configPath} is invalid JSON (${message}). Fix or remove it first.`, { cause: error });
350
391
  }
351
392
  }
352
393
 
package/src/editor.ts CHANGED
@@ -30,7 +30,12 @@ class MicmeEditor extends CustomEditor {
30
30
 
31
31
  function handleMicmeEditorInput(data: string, handlers: MicmeEditorInputHandlers) {
32
32
  const printable = decodeKittyPrintable(data);
33
- const printableShortcut = matchesPrintableMicmeShortcut(data) ? data : printable !== undefined && matchesPrintableMicmeShortcut(printable) ? printable : undefined;
33
+ let printableShortcut: string | undefined;
34
+ if (matchesPrintableMicmeShortcut(data)) {
35
+ printableShortcut = data;
36
+ } else if (printable !== undefined && matchesPrintableMicmeShortcut(printable)) {
37
+ printableShortcut = printable;
38
+ }
34
39
  if (printableShortcut !== undefined) {
35
40
  if (!isPrintableShortcutAutoRepeat(printableShortcut)) void handlers.toggle();
36
41
  return true;
package/src/extension.ts CHANGED
@@ -16,6 +16,7 @@ import { ensureWhisperCppModel } from "./models.ts";
16
16
  import {
17
17
  cleanup,
18
18
  formatExit,
19
+ formatProcessOutput,
19
20
  normalizeTranscript,
20
21
  raceWithTimeout,
21
22
  spawnRecording,
@@ -37,13 +38,16 @@ import {
37
38
  showStreamingDiagnostics,
38
39
  } from "./streaming.ts";
39
40
  import { pasteOrSubmitTranscript } from "./transcript-delivery.ts";
41
+ import { sanitizeTerminalOutput } from "./terminal-text.ts";
40
42
  import { transcribe } from "./transcription.ts";
41
- import type { Recording } from "./types.ts";
43
+ import type { Recording, ResolvedTranscriptionPlan } from "./types.ts";
42
44
 
43
45
  const MICME_ACTIONS = ["devices", "conf", "last", "audio", "help"] as const;
44
46
 
45
47
  const SHORTCUT_REPEAT_GUARD_MS = 1_000;
46
48
 
49
+ type StreamingTranscriptionPlan = ResolvedTranscriptionPlan & { effectiveBackend: "whisper.cpp"; binary: string; modelPath: string };
50
+
47
51
  let recording: Recording | undefined;
48
52
  let lastTranscript = "";
49
53
  let lastAudioDir = "";
@@ -86,13 +90,13 @@ export default function micmeExtension(pi: ExtensionAPI) {
86
90
  await pasteOrSubmitTranscript(ctx, pi, lastTranscript);
87
91
  return;
88
92
  case "audio":
89
- ctx.ui.notify(lastAudioDir ? `Last Micme audio directory: ${lastAudioDir}` : "No kept Micme audio yet. Set MICME_KEEP_AUDIO=1.", "info");
93
+ ctx.ui.notify(lastAudioDir ? `Last Micme audio directory: ${sanitizeTerminalOutput(lastAudioDir)}` : "No kept Micme audio yet. Set MICME_KEEP_AUDIO=1.", "info");
90
94
  return;
91
95
  case "help":
92
96
  ctx.ui.notify(getHelpText(), "info");
93
97
  return;
94
98
  default:
95
- ctx.ui.notify(`Unknown micme action: ${action}. Try /micme help`, "warning");
99
+ ctx.ui.notify(`Unknown micme action: ${sanitizeTerminalOutput(action) || "(empty)"}. Try /micme help`, "warning");
96
100
  }
97
101
  } catch (error) {
98
102
  handleExtensionError(ctx, error);
@@ -121,6 +125,7 @@ export default function micmeExtension(pi: ExtensionAPI) {
121
125
  });
122
126
 
123
127
  pi.on("session_shutdown", async (_event, ctx) => {
128
+ ctx.ui.setStatus(STATUS_KEY, undefined);
124
129
  clearRecordingWidget(ctx);
125
130
  if (!recording) return;
126
131
  const active = recording;
@@ -143,7 +148,7 @@ function createMicmeEditorHandlers(ctx: ExtensionContext, toggle: (ctx: Extensio
143
148
 
144
149
  function handleExtensionError(ctx: ExtensionContext, error: unknown) {
145
150
  ctx.ui.setStatus(STATUS_KEY, undefined);
146
- ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
151
+ ctx.ui.notify(sanitizeTerminalOutput(error instanceof Error ? error.message : String(error)) || "Micme failed with an empty error message.", "error");
147
152
  }
148
153
 
149
154
  function isStillStarting(active: Recording) {
@@ -158,7 +163,7 @@ function isShortcutAutoRepeat() {
158
163
  }
159
164
 
160
165
  function getHelpText() {
161
- const shortcut = getShortcut();
166
+ const shortcut = sanitizeTerminalOutput(getShortcut()) || "not set";
162
167
  const actions = MICME_ACTIONS.filter((action) => action !== "help").join("|");
163
168
  return `Usage: /micme [${actions}]. Shortcut: ${shortcut} toggles recording; tap once to start, tap again to stop/transcribe.`;
164
169
  }
@@ -184,12 +189,12 @@ async function startRecording(ctx: ExtensionContext, stopHint = getShortcut()) {
184
189
  const earlyExit = await raceWithTimeout(active.exitPromise, RECORDER_STARTUP_GRACE_MS);
185
190
  if (earlyExit) {
186
191
  if (active.stopRequested) return;
187
- const stderr = active.stderr().trim();
192
+ const stderr = formatProcessOutput(active.stderr());
188
193
  const suffix = stderr ? `\n${stderr}` : "";
189
194
  throw new Error(`Micme recorder exited early (${formatExit(earlyExit)}).${suffix}`);
190
195
  }
191
196
 
192
- ctx.ui.setStatus(STATUS_KEY, `● recording (${stopHint} or /micme)`);
197
+ ctx.ui.setStatus(STATUS_KEY, `● recording (${sanitizeTerminalOutput(stopHint) || "shortcut"} or /micme)`);
193
198
  startRecordingWidget(ctx, active);
194
199
  } catch (error) {
195
200
  await cleanupFailedRecordingStart(ctx, tempDir, active);
@@ -247,8 +252,8 @@ async function stopAndTranscribe(ctx: ExtensionContext, pi: ExtensionAPI) {
247
252
  } catch (error) {
248
253
  ctx.ui.setStatus(STATUS_KEY, undefined);
249
254
  lastAudioDir = active.tempDir;
250
- const message = error instanceof Error ? error.message : String(error);
251
- throw new Error(`${message}\nAudio kept for debugging: ${active.tempDir}`);
255
+ const message = sanitizeTerminalOutput(error instanceof Error ? error.message : String(error));
256
+ throw new Error(`${message}\nAudio kept for debugging: ${sanitizeTerminalOutput(active.tempDir)}`, { cause: error });
252
257
  } finally {
253
258
  if (completed && !envFlag("MICME_KEEP_AUDIO")) {
254
259
  await cleanup(active.tempDir).catch(() => undefined);
@@ -257,56 +262,21 @@ async function stopAndTranscribe(ctx: ExtensionContext, pi: ExtensionAPI) {
257
262
  }
258
263
 
259
264
  async function startStreamingTranscription(ctx: ExtensionContext, stopHint = getShortcut()) {
260
- const plan = resolveTranscriptionPlan({ transcriptionMode: "stream" });
261
- if (plan.effectiveBackend !== "whisper.cpp" || !plan.binary || !plan.modelPath) {
262
- throw new Error(formatTranscriptionPlan(plan));
263
- }
264
-
265
+ const plan = resolveStreamingTranscriptionPlan();
265
266
  await ensureWhisperCppModel(plan.modelPath, ctx, { allowDownload: plan.modelDownloadable !== false });
266
267
 
267
268
  const tempDir = await createRecordingDirectory(ctx.cwd, envFlag("MICME_KEEP_AUDIO"), "micme-stream-");
268
269
  let active: Recording | undefined;
269
270
 
270
271
  try {
271
- const command = buildWhisperStreamCommand(plan.binary, plan.modelPath, tempDir);
272
- const clipAudioPath = getStreamFinalizeWithClip() ? join(tempDir, "raw.wav") : undefined;
273
- const clipCommand = clipAudioPath ? buildRecorderCommand(clipAudioPath) : undefined;
274
- active = spawnRecording(command, "", tempDir);
275
- const streamRecording = active;
276
- const baseText = ctx.ui.getEditorText();
277
- streamRecording.streaming = {
278
- baseText,
279
- previewText: baseText,
280
- outputBuffer: "",
281
- lastText: "",
282
- emittedWords: [],
283
- candidateWords: [],
284
- lastHypothesisWords: [],
285
- startedAt: Date.now(),
286
- };
287
- if (clipCommand && clipAudioPath) {
288
- streamRecording.clipRecording = spawnRecording(clipCommand, clipAudioPath, tempDir);
289
- }
272
+ const streamRecording = spawnWhisperStreamingRecording(plan, tempDir);
273
+ active = streamRecording;
274
+ initializeStreamingRecording(ctx, streamRecording);
275
+ startOptionalClipRecording(streamRecording, tempDir);
290
276
  recording = streamRecording;
291
277
 
292
- streamRecording.process.stdout?.on("data", (chunk: Buffer | string) => {
293
- const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
294
- handleStreamingOutput(ctx, streamRecording, text);
295
- });
296
-
297
- const [earlyExit, recorderEarlyExit] = await Promise.all([
298
- raceWithTimeout(streamRecording.exitPromise, RECORDER_STARTUP_GRACE_MS),
299
- streamRecording.clipRecording ? raceWithTimeout(streamRecording.clipRecording.exitPromise, RECORDER_STARTUP_GRACE_MS) : Promise.resolve(undefined),
300
- ]);
301
- if (earlyExit || recorderEarlyExit) {
302
- if (streamRecording.stopRequested || streamRecording.clipRecording?.stopRequested) return;
303
- const failed = earlyExit ? streamRecording : streamRecording.clipRecording;
304
- const stderr = failed?.stderr().trim();
305
- const suffix = stderr ? `\n${stderr}` : "";
306
- throw new Error(`Micme streaming exited early (${formatExit(earlyExit ?? recorderEarlyExit!)}).${suffix}`);
307
- }
308
-
309
- ctx.ui.setStatus(STATUS_KEY, `● streaming (${stopHint} or /micme)`);
278
+ await ensureStreamingRecorderStarted(streamRecording);
279
+ ctx.ui.setStatus(STATUS_KEY, `● streaming (${sanitizeTerminalOutput(stopHint) || "shortcut"} or /micme)`);
310
280
  startRecordingWidget(ctx, streamRecording);
311
281
  } catch (error) {
312
282
  await cleanupFailedRecordingStart(ctx, tempDir, active);
@@ -314,68 +284,163 @@ async function startStreamingTranscription(ctx: ExtensionContext, stopHint = get
314
284
  }
315
285
  }
316
286
 
287
+ function resolveStreamingTranscriptionPlan(): StreamingTranscriptionPlan {
288
+ const plan = resolveTranscriptionPlan({ transcriptionMode: "stream" });
289
+ if (plan.effectiveBackend !== "whisper.cpp" || !plan.binary || !plan.modelPath) {
290
+ throw new Error(formatTranscriptionPlan(plan));
291
+ }
292
+ return plan as StreamingTranscriptionPlan;
293
+ }
294
+
295
+ function spawnWhisperStreamingRecording(plan: StreamingTranscriptionPlan, tempDir: string) {
296
+ const command = buildWhisperStreamCommand(plan.binary, plan.modelPath, tempDir);
297
+ return spawnRecording(command, "", tempDir);
298
+ }
299
+
300
+ function initializeStreamingRecording(ctx: ExtensionContext, streamRecording: Recording) {
301
+ const baseText = ctx.ui.getEditorText();
302
+ streamRecording.streaming = {
303
+ baseText,
304
+ previewText: baseText,
305
+ outputBuffer: "",
306
+ lastText: "",
307
+ emittedWords: [],
308
+ candidateWords: [],
309
+ lastHypothesisWords: [],
310
+ startedAt: Date.now(),
311
+ };
312
+ streamRecording.process.stdout?.on("data", (chunk: Buffer | string) => {
313
+ const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
314
+ handleStreamingOutput(ctx, streamRecording, text);
315
+ });
316
+ }
317
+
318
+ function startOptionalClipRecording(streamRecording: Recording, tempDir: string) {
319
+ const clipAudioPath = getStreamFinalizeWithClip() ? join(tempDir, "raw.wav") : undefined;
320
+ if (!clipAudioPath) return;
321
+ streamRecording.clipRecording = spawnRecording(buildRecorderCommand(clipAudioPath), clipAudioPath, tempDir);
322
+ }
323
+
324
+ async function ensureStreamingRecorderStarted(streamRecording: Recording) {
325
+ const [earlyExit, recorderEarlyExit] = await Promise.all([
326
+ raceWithTimeout(streamRecording.exitPromise, RECORDER_STARTUP_GRACE_MS),
327
+ streamRecording.clipRecording ? raceWithTimeout(streamRecording.clipRecording.exitPromise, RECORDER_STARTUP_GRACE_MS) : Promise.resolve(undefined),
328
+ ]);
329
+ const failedExit = earlyExit ?? recorderEarlyExit;
330
+ if (!failedExit) return;
331
+ if (streamRecording.stopRequested || streamRecording.clipRecording?.stopRequested) return;
332
+ const failed = earlyExit ? streamRecording : streamRecording.clipRecording;
333
+ const stderr = failed ? formatProcessOutput(failed.stderr()) : "";
334
+ const suffix = stderr ? `\n${stderr}` : "";
335
+ throw new Error(`Micme streaming exited early (${formatExit(failedExit)}).${suffix}`);
336
+ }
337
+
317
338
  async function stopStreamingTranscription(ctx: ExtensionContext, pi: ExtensionAPI, active: Recording) {
318
339
  const state = active.streaming;
319
- let keepTempDir = false;
320
- const clipStopPromise = active.clipRecording ? stopRecorder(active.clipRecording).then(() => undefined, (error: unknown) => error) : undefined;
321
-
322
- if (state) {
323
- drainStreamingOutput(ctx, active, false);
324
- renderStreamingPreview(ctx, state, false);
325
- clearStreamingFlush(state);
326
- }
340
+ const clipStopPromise = stopClipRecording(active);
327
341
 
342
+ prepareStreamingStop(ctx, active, state);
328
343
  await stopProcess(active);
329
344
 
330
- if (state) {
331
- drainStreamingOutput(ctx, active, true);
332
- showStreamingDiagnostics(ctx, state);
333
- if (!active.clipRecording) {
334
- flushPendingStreamingWords(ctx, state);
335
- const liveTranscript = normalizeTranscript(getStreamingTranscript(state));
336
- if (liveTranscript) {
337
- lastTranscript = liveTranscript;
338
- if (envFlag("MICME_AUTO_SUBMIT")) {
339
- ctx.ui.setEditorText(state.baseText);
340
- await pasteOrSubmitTranscript(ctx, pi, liveTranscript);
341
- }
342
- }
343
- } else {
344
- renderStreamingPreview(ctx, state, false);
345
- }
345
+ const keepTempDir = state ? await completeStreamingStop(ctx, pi, active, state, clipStopPromise) : false;
346
+ if (!keepTempDir) await cleanup(active.tempDir).catch(() => undefined);
347
+ ctx.ui.setStatus(STATUS_KEY, undefined);
348
+ }
349
+
350
+ function stopClipRecording(active: Recording) {
351
+ return active.clipRecording ? stopRecorder(active.clipRecording).then(() => undefined, (error: unknown) => error) : undefined;
352
+ }
353
+
354
+ function prepareStreamingStop(ctx: ExtensionContext, active: Recording, state: Recording["streaming"]) {
355
+ if (!state) return;
356
+ drainStreamingOutput(ctx, active, false);
357
+ renderStreamingPreview(ctx, state, false);
358
+ clearStreamingFlush(state);
359
+ }
360
+
361
+ async function completeStreamingStop(
362
+ ctx: ExtensionContext,
363
+ pi: ExtensionAPI,
364
+ active: Recording,
365
+ state: NonNullable<Recording["streaming"]>,
366
+ clipStopPromise: ReturnType<typeof stopClipRecording>,
367
+ ) {
368
+ drainStreamingOutput(ctx, active, true);
369
+ showStreamingDiagnostics(ctx, state);
370
+ const clipRecording = active.clipRecording;
371
+ if (!clipRecording) {
372
+ await useLiveStreamingTranscript(ctx, pi, state);
346
373
  clearStreamingFlush(state);
374
+ return false;
347
375
  }
348
376
 
349
- if (active.clipRecording && state) {
350
- ctx.ui.setStatus(STATUS_KEY, "finalizing stream…");
351
- try {
352
- const clipStopError = await clipStopPromise;
353
- if (clipStopError) throw clipStopError;
354
- const preparedAudioPath = await prepareAudioForTranscription(active.clipRecording.audioPath, active.tempDir);
355
- await validateRecordedAudio(preparedAudioPath);
356
- const transcript = await transcribe(preparedAudioPath, active.tempDir, ctx);
357
- const normalized = normalizeTranscript(transcript);
358
- if (!normalized) throw new Error("Micme did not receive any final transcript text.");
359
-
360
- lastTranscript = normalized;
361
- await pasteOrSubmitFinalStreamingTranscript(ctx, pi, state, normalized);
362
- if (envFlag("MICME_KEEP_AUDIO")) {
363
- lastAudioDir = active.tempDir;
364
- keepTempDir = true;
365
- }
366
- } catch (error) {
367
- flushPendingStreamingWords(ctx, state);
368
- const liveTranscript = normalizeTranscript(getStreamingTranscript(state));
369
- if (liveTranscript) lastTranscript = liveTranscript;
370
- lastAudioDir = active.tempDir;
371
- keepTempDir = true;
372
- const message = error instanceof Error ? error.message : String(error);
373
- ctx.ui.notify(`Micme kept the live append-only stream transcript because final clip transcription failed: ${message}\nAudio kept for debugging: ${active.tempDir}`, "warning");
374
- }
377
+ renderStreamingPreview(ctx, state, false);
378
+ clearStreamingFlush(state);
379
+ return finalizeStreamingClip(ctx, pi, active, clipRecording, state, clipStopPromise);
380
+ }
381
+
382
+ async function useLiveStreamingTranscript(ctx: ExtensionContext, pi: ExtensionAPI, state: NonNullable<Recording["streaming"]>) {
383
+ flushPendingStreamingWords(ctx, state);
384
+ const liveTranscript = normalizeTranscript(getStreamingTranscript(state));
385
+ if (!liveTranscript) return;
386
+
387
+ lastTranscript = liveTranscript;
388
+ if (!envFlag("MICME_AUTO_SUBMIT")) return;
389
+ ctx.ui.setEditorText(state.baseText);
390
+ await pasteOrSubmitTranscript(ctx, pi, liveTranscript);
391
+ }
392
+
393
+ async function finalizeStreamingClip(
394
+ ctx: ExtensionContext,
395
+ pi: ExtensionAPI,
396
+ active: Recording,
397
+ clipRecording: Recording,
398
+ state: NonNullable<Recording["streaming"]>,
399
+ clipStopPromise: ReturnType<typeof stopClipRecording>,
400
+ ) {
401
+ ctx.ui.setStatus(STATUS_KEY, "finalizing stream…");
402
+ try {
403
+ await transcribeFinalStreamingClip(ctx, pi, active, clipRecording, state, clipStopPromise);
404
+ return keepCompletedStreamingClipAudio(active);
405
+ } catch (error) {
406
+ handleFinalStreamingClipError(ctx, active, state, error);
407
+ return true;
375
408
  }
409
+ }
376
410
 
377
- if (!keepTempDir) await cleanup(active.tempDir).catch(() => undefined);
378
- ctx.ui.setStatus(STATUS_KEY, undefined);
411
+ async function transcribeFinalStreamingClip(
412
+ ctx: ExtensionContext,
413
+ pi: ExtensionAPI,
414
+ active: Recording,
415
+ clipRecording: Recording,
416
+ state: NonNullable<Recording["streaming"]>,
417
+ clipStopPromise: ReturnType<typeof stopClipRecording>,
418
+ ) {
419
+ const clipStopError = clipStopPromise ? await clipStopPromise : undefined;
420
+ if (clipStopError) throw clipStopError;
421
+ const preparedAudioPath = await prepareAudioForTranscription(clipRecording.audioPath, active.tempDir);
422
+ await validateRecordedAudio(preparedAudioPath);
423
+ const transcript = await transcribe(preparedAudioPath, active.tempDir, ctx);
424
+ const normalized = normalizeTranscript(transcript);
425
+ if (!normalized) throw new Error("Micme did not receive any final transcript text.");
426
+
427
+ lastTranscript = normalized;
428
+ await pasteOrSubmitFinalStreamingTranscript(ctx, pi, state, normalized);
429
+ }
430
+
431
+ function keepCompletedStreamingClipAudio(active: Recording) {
432
+ if (!envFlag("MICME_KEEP_AUDIO")) return false;
433
+ lastAudioDir = active.tempDir;
434
+ return true;
435
+ }
436
+
437
+ function handleFinalStreamingClipError(ctx: ExtensionContext, active: Recording, state: NonNullable<Recording["streaming"]>, error: unknown) {
438
+ flushPendingStreamingWords(ctx, state);
439
+ const liveTranscript = normalizeTranscript(getStreamingTranscript(state));
440
+ if (liveTranscript) lastTranscript = liveTranscript;
441
+ lastAudioDir = active.tempDir;
442
+ const message = sanitizeTerminalOutput(error instanceof Error ? error.message : String(error));
443
+ ctx.ui.notify(`Micme kept the live append-only stream transcript because final clip transcription failed: ${message}\nAudio kept for debugging: ${sanitizeTerminalOutput(active.tempDir)}`, "warning");
379
444
  }
380
445
 
381
446