@senad-d/micme 0.3.1 → 0.3.3

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/audio.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { sliceByColumn, visibleWidth, type Component } from "@earendil-works/pi-tui";
3
- import { join } from "node:path";
3
+ import { dirname, join } from "node:path";
4
4
  import { AUDIO_VALIDATION_TIMEOUT_MS } from "./constants.ts";
5
5
  import { env, envFlag, getAudioFilter, getAvfoundationDropLateFrames, getAvfoundationInputSampleRate, getMinMaxVolumeDb, getRecordMeter, getRecordSampleRate, getRecordSync, getTranscribeSampleRate } from "./config.ts";
6
- import { findExecutable, formatRunExit, replacePlaceholders, runProcess, shellCommand, shellQuote } from "./processes.ts";
6
+ import { findExecutable, formatProcessOutput, formatRunExit, replacePlaceholders, runProcess, shellCommand, shellQuote } from "./processes.ts";
7
+ import { sanitizeTerminalText } from "./terminal-text.ts";
7
8
  import type { AudioDeviceCandidate, AudioDiagnostics, CommandSpec, RunResult } from "./types.ts";
8
9
 
9
10
  type DeviceBackend = "avfoundation" | "pulse" | "dshow" | "unsupported";
@@ -226,8 +227,8 @@ export function parseAvfoundationDevices(output: string): ParsedDeviceInventory
226
227
 
227
228
  const match = line.match(/\[(\d+)\]\s+(.+)$/);
228
229
  if (!match) continue;
229
- const id = match[1] ?? "";
230
- const name = (match[2] ?? "").trim();
230
+ const id = sanitizeDeviceField(match[1] ?? "");
231
+ const name = sanitizeDeviceField(match[2] ?? "");
231
232
  if (!name) continue;
232
233
  inventory[section].push({ id, name });
233
234
  }
@@ -251,9 +252,9 @@ function parsePulseAudioDevices(output: string): ParsedDeviceInventory {
251
252
  const sourceLine = line.replace(/^\*\s*/, "");
252
253
  const match = sourceLine.match(/^([^\s\[]+)(?:\s+\[(.+)\])?$/);
253
254
  if (!match) continue;
254
- const id = (match[1] ?? "").trim();
255
+ const id = sanitizeDeviceField(match[1] ?? "");
255
256
  if (!id || id.includes(":")) continue;
256
- let name = (match[2] ?? "").trim();
257
+ let name = sanitizeDeviceField(match[2] ?? "");
257
258
  if (id === "default" && (!name || /^default$/i.test(name))) name = "PulseAudio default source";
258
259
  inventory.audio.push({ id, name });
259
260
  }
@@ -280,7 +281,7 @@ function parseDirectShowDevices(output: string): ParsedDeviceInventory {
280
281
  if (!section || /Alternative name/i.test(line)) continue;
281
282
 
282
283
  const match = line.match(/^"(.+)"$/) ?? line.match(/"([^"]+)"/);
283
- const name = (match?.[1] ?? "").trim();
284
+ const name = sanitizeDeviceField(match?.[1] ?? "");
284
285
  if (!name) continue;
285
286
  inventory[section].push({ name });
286
287
  }
@@ -292,6 +293,10 @@ function stripFfmpegLogPrefix(line: string) {
292
293
  return line.replace(/^(?:\[[^\]]+\]\s*)+/, "");
293
294
  }
294
295
 
296
+ function sanitizeDeviceField(value: string) {
297
+ return sanitizeTerminalText(value);
298
+ }
299
+
295
300
  function hasMacosPermissionIssue(output: string) {
296
301
  return /(?:not authorized|authorization|privacy|permission|operation not permitted|microphone access|access.*microphone|microphone.*blocked)/i.test(output);
297
302
  }
@@ -373,18 +378,19 @@ function isDeviceBackend(value: unknown): value is DeviceBackend {
373
378
  }
374
379
 
375
380
  export function renderDevicePanel(options: DevicePanelOptions, width = getDevicePanelWidth()) {
381
+ const safeOptions = sanitizeDevicePanelOptions(options);
376
382
  const style = getDevicePanelStyle();
377
383
  const panelWidth = Math.max(2, Math.floor(width));
378
- const lines = [buildDevicePanelHeader(panelWidth, options.sourceLabel, style)];
379
- const hasInventory = options.audio !== undefined || options.video !== undefined || !options.errorLines?.length;
384
+ const lines = [buildDevicePanelHeader(panelWidth, safeOptions.sourceLabel, style)];
385
+ const hasInventory = safeOptions.audio !== undefined || safeOptions.video !== undefined || !safeOptions.errorLines?.length;
380
386
 
381
387
  if (hasInventory) {
382
- lines.push(buildDeviceRow("audio", options.audio ?? [], style, panelWidth));
383
- if (options.includeVideo) lines.push(buildDeviceRow("video", options.video ?? [], style, panelWidth));
388
+ lines.push(buildDeviceRow("audio", safeOptions.audio ?? [], style, panelWidth));
389
+ if (safeOptions.includeVideo) lines.push(buildDeviceRow("video", safeOptions.video ?? [], style, panelWidth));
384
390
  }
385
391
 
386
- if (options.warning) lines.push(buildStatusRow("warning", options.warning, style, panelWidth));
387
- for (const [index, line] of (options.errorLines ?? []).entries()) {
392
+ if (safeOptions.warning) lines.push(buildStatusRow("warning", safeOptions.warning, style, panelWidth));
393
+ for (const [index, line] of (safeOptions.errorLines ?? []).entries()) {
388
394
  lines.push(buildErrorRow(line, index === 0, style, panelWidth));
389
395
  }
390
396
  lines.push(buildDevicePanelFooter(panelWidth, style));
@@ -392,6 +398,25 @@ export function renderDevicePanel(options: DevicePanelOptions, width = getDevice
392
398
  return lines.filter(Boolean).join("\n");
393
399
  }
394
400
 
401
+ function sanitizeDevicePanelOptions(options: DevicePanelOptions): DevicePanelOptions {
402
+ const errorLines = Array.isArray(options.errorLines) ? options.errorLines.map((line) => sanitizeTerminalText(String(line))).filter(Boolean) : undefined;
403
+ return {
404
+ ...options,
405
+ sourceLabel: sanitizeTerminalText(options.sourceLabel) || "unknown",
406
+ warning: typeof options.warning === "string" ? sanitizeTerminalText(options.warning) : undefined,
407
+ errorLines,
408
+ audio: sanitizeListedDevices(options.audio),
409
+ video: sanitizeListedDevices(options.video),
410
+ };
411
+ }
412
+
413
+ function sanitizeListedDevices(devices: ListedDevice[] | undefined) {
414
+ if (!Array.isArray(devices)) return undefined;
415
+ return devices
416
+ .map((device) => ({ id: device.id ? sanitizeDeviceField(String(device.id)) : undefined, name: sanitizeDeviceField(String(device.name ?? "")) }))
417
+ .filter((device) => device.id || device.name);
418
+ }
419
+
395
420
  function getDevicePanelWidth() {
396
421
  const columns = process.stdout.columns;
397
422
  if (Number.isFinite(columns) && columns > 0) {
@@ -595,7 +620,7 @@ export async function prepareAudioForTranscription(inputPath: string, tempDir: s
595
620
 
596
621
  const result = await runProcess(ffmpeg, args, AUDIO_VALIDATION_TIMEOUT_MS);
597
622
  if (result.code !== 0) {
598
- throw new Error(`Micme audio preprocessing failed (${formatRunExit(result)}):\n${result.stderr || result.stdout}`);
623
+ throw new Error(`Micme audio preprocessing failed (${formatRunExit(result)}):\n${formatProcessOutput(result.stderr, result.stdout)}`);
599
624
  }
600
625
 
601
626
  return outputPath;
@@ -608,7 +633,7 @@ export async function validateRecordedAudio(audioPath: string): Promise<AudioDia
608
633
  if (!ffmpeg) return undefined;
609
634
 
610
635
  const result = await runProcess(ffmpeg, ["-hide_banner", "-nostats", "-i", audioPath, "-af", "volumedetect", "-f", "null", "-"], AUDIO_VALIDATION_TIMEOUT_MS);
611
- const raw = `${result.stdout}\n${result.stderr}`.trim();
636
+ const raw = formatProcessOutput(`${result.stdout}\n${result.stderr}`);
612
637
  if (result.code !== 0) {
613
638
  throw new Error(`Micme could not inspect recorded audio (${formatRunExit(result)}):\n${raw}`);
614
639
  }
@@ -637,10 +662,10 @@ export function parseVolumeDb(output: string, label: "mean_volume" | "max_volume
637
662
  return match[1]?.toLowerCase() === "-inf" ? Number.NEGATIVE_INFINITY : Number(match[1]);
638
663
  }
639
664
 
640
- export function buildRecorderCommand(audioPath: string): CommandSpec {
665
+ export function buildRecorderCommand(audioPath: string, tempDir = dirname(audioPath)): CommandSpec {
641
666
  const custom = env("MICME_RECORD_COMMAND");
642
667
  if (custom?.trim()) {
643
- const expanded = replacePlaceholders(custom, { audio: audioPath });
668
+ const expanded = replacePlaceholders(custom, { audio: audioPath, tempDir, transcript: join(tempDir, "transcript.txt") });
644
669
  return shellCommand(expanded);
645
670
  }
646
671
 
package/src/backends.ts CHANGED
@@ -3,7 +3,7 @@ import type { TranscribeBackend, TranscriptionMode, ResolvedTranscriptionPlan, R
3
3
  import { DEFAULT_TRANSCRIBE_BACKEND } from "./constants.ts";
4
4
  import { env, expandConfigPath, getTranscribeBackend, getTranslateToEnglishLanguage, isTranscribeBackend } from "./config.ts";
5
5
  import { getPythonWhisperModelName, isEnglishOnlyWhisperModelName, isTranslationUnsupportedWhisperModelName, resolveWhisperCppModel } from "./models.ts";
6
- import { findExecutable } from "./processes.ts";
6
+ import { findExecutable, isExecutableFile } from "./processes.ts";
7
7
 
8
8
  export type ResolveTranscriptionPlanOptions = {
9
9
  requestedBackend?: TranscribeBackend | string;
@@ -32,34 +32,34 @@ export function resolveTranscriptionPlan(options: ResolveTranscriptionPlanOption
32
32
  customCommand: customCommand ?? undefined,
33
33
  whisperCppModel,
34
34
  warnings,
35
- whisperStreamBinary: getExecutableOption(options, "whisperStreamBinary", "whisperStreamBinaryError", getWhisperStreamBinary),
35
+ whisperStreamBinary: getExecutableOption(options, "whisperStreamBinary", "whisperStreamBinaryError", getWhisperStreamBinary, warnings),
36
36
  });
37
37
  }
38
38
 
39
- const whisperCppBinary = getExecutableOption(options, "whisperCppBinary", "whisperCppBinaryError", getWhisperCppBinary);
39
+ const whisperCppBinary = getExecutableOption(options, "whisperCppBinary", "whisperCppBinaryError", getWhisperCppBinary, warnings);
40
40
  const pythonWhisperBinary = getOptionValue(options, "pythonWhisperBinary", getPythonWhisperBinary);
41
41
 
42
42
  if (requestedBackend === "custom") {
43
43
  return customCommand
44
- ? customPlan(requestedBackend, customCommand, "MICME_TRANSCRIBE_BACKEND=custom")
44
+ ? customPlan(requestedBackend, customCommand, "MICME_TRANSCRIBE_BACKEND=custom", warnings)
45
45
  : nonePlan(requestedBackend, "MICME_TRANSCRIBE_BACKEND=custom but MICME_TRANSCRIBE_COMMAND is not set.", warnings);
46
46
  }
47
47
 
48
48
  if (requestedBackend === "whisper.cpp") {
49
49
  return whisperCppBinary
50
- ? whisperCppPlan(requestedBackend, whisperCppBinary, whisperCppModel, "MICME_TRANSCRIBE_BACKEND=whisper.cpp")
50
+ ? whisperCppPlan(requestedBackend, whisperCppBinary, whisperCppModel, "MICME_TRANSCRIBE_BACKEND=whisper.cpp", warnings)
51
51
  : nonePlan(requestedBackend, "MICME_TRANSCRIBE_BACKEND=whisper.cpp but whisper.cpp was not found.", warnings);
52
52
  }
53
53
 
54
54
  if (requestedBackend === "python") {
55
55
  return pythonWhisperBinary
56
- ? pythonPlan(requestedBackend, pythonWhisperBinary, pythonModelName, "MICME_TRANSCRIBE_BACKEND=python")
56
+ ? pythonPlan(requestedBackend, pythonWhisperBinary, pythonModelName, "MICME_TRANSCRIBE_BACKEND=python", warnings)
57
57
  : nonePlan(requestedBackend, "MICME_TRANSCRIBE_BACKEND=python but the `whisper` CLI was not found.", warnings);
58
58
  }
59
59
 
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");
60
+ if (customCommand) return customPlan(requestedBackend, customCommand, "auto selected custom command because MICME_TRANSCRIBE_COMMAND is configured", warnings);
61
+ if (whisperCppBinary) return whisperCppPlan(requestedBackend, whisperCppBinary, whisperCppModel, "auto selected whisper.cpp because a whisper.cpp binary is available", warnings);
62
+ if (pythonWhisperBinary) return pythonPlan(requestedBackend, pythonWhisperBinary, pythonModelName, "auto selected Python Whisper because whisper.cpp is unavailable", warnings);
63
63
 
64
64
  return nonePlan(
65
65
  requestedBackend,
@@ -88,6 +88,7 @@ export function resolveExecutableConfig(value: string, configName: string) {
88
88
  const expanded = expandConfigPath(value);
89
89
  if (/[/\\]/.test(expanded)) {
90
90
  if (!existsSync(expanded)) throw new Error(`${configName} is set but not found: ${expanded}`);
91
+ if (!isExecutableFile(expanded)) throw new Error(`${configName} is set but is not an executable file: ${expanded}`);
91
92
  return expanded;
92
93
  }
93
94
  const executable = findExecutable([expanded]);
@@ -152,10 +153,10 @@ function resolveStreamingPlan(options: {
152
153
  : "MICME_TRANSCRIBE_BACKEND=whisper.cpp and MICME_TRANSCRIPTION_MODE=stream but whisper-stream was not found.";
153
154
  return nonePlan(requestedBackend, reason, warnings);
154
155
  }
155
- return whisperCppPlan(requestedBackend, whisperStreamBinary, whisperCppModel, "streaming selected whisper.cpp because whisper-stream is available");
156
+ return whisperCppPlan(requestedBackend, whisperStreamBinary, whisperCppModel, "streaming selected whisper.cpp because whisper-stream is available", warnings);
156
157
  }
157
158
 
158
- function customPlan(requestedBackend: TranscribeBackend, command: string, reason: string): ResolvedTranscriptionPlan {
159
+ function customPlan(requestedBackend: TranscribeBackend, command: string, reason: string, inheritedWarnings: string[] = []): ResolvedTranscriptionPlan {
159
160
  return {
160
161
  requestedBackend,
161
162
  effectiveBackend: "custom",
@@ -163,12 +164,12 @@ function customPlan(requestedBackend: TranscribeBackend, command: string, reason
163
164
  command,
164
165
  modelName: "unknown",
165
166
  modelSource: "custom-command",
166
- warnings: [],
167
+ warnings: [...inheritedWarnings],
167
168
  };
168
169
  }
169
170
 
170
- function whisperCppPlan(requestedBackend: TranscribeBackend, binary: string, model: ResolvedWhisperCppModel, reason: string): ResolvedTranscriptionPlan {
171
- const warnings: string[] = [];
171
+ function whisperCppPlan(requestedBackend: TranscribeBackend, binary: string, model: ResolvedWhisperCppModel, reason: string, inheritedWarnings: string[] = []): ResolvedTranscriptionPlan {
172
+ const warnings: string[] = [...inheritedWarnings];
172
173
  if (model.source === "explicit-path" && !model.exists && !model.downloadable) {
173
174
  warnings.push(`MICME_WHISPER_CPP_MODEL is set but not found: ${model.path}`);
174
175
  } else if (!model.exists && !model.downloadable) {
@@ -191,7 +192,7 @@ function whisperCppPlan(requestedBackend: TranscribeBackend, binary: string, mod
191
192
  };
192
193
  }
193
194
 
194
- function pythonPlan(requestedBackend: TranscribeBackend, binary: string, modelName: string, reason: string): ResolvedTranscriptionPlan {
195
+ function pythonPlan(requestedBackend: TranscribeBackend, binary: string, modelName: string, reason: string, inheritedWarnings: string[] = []): ResolvedTranscriptionPlan {
195
196
  return {
196
197
  requestedBackend,
197
198
  effectiveBackend: "python",
@@ -199,7 +200,7 @@ function pythonPlan(requestedBackend: TranscribeBackend, binary: string, modelNa
199
200
  binary,
200
201
  modelName,
201
202
  modelSource: "python-name",
202
- warnings: getTranslationModelWarnings(modelName),
203
+ warnings: [...inheritedWarnings, ...getTranslationModelWarnings(modelName)],
203
204
  };
204
205
  }
205
206
 
@@ -245,16 +246,21 @@ function getExecutableOption(
245
246
  key: "whisperCppBinary" | "whisperStreamBinary",
246
247
  errorKey: "whisperCppBinaryError" | "whisperStreamBinaryError",
247
248
  fallback: () => string | undefined,
249
+ warnings: string[] = [],
248
250
  ) {
249
251
  const error = options[errorKey];
250
- if (error) return undefined;
252
+ if (error) {
253
+ warnings.push(error);
254
+ return undefined;
255
+ }
251
256
  if (Object.prototype.hasOwnProperty.call(options, key)) {
252
257
  const value = options[key];
253
258
  return typeof value === "string" && value.trim() ? value.trim() : undefined;
254
259
  }
255
260
  try {
256
261
  return fallback();
257
- } catch {
262
+ } catch (error) {
263
+ warnings.push(error instanceof Error ? error.message : String(error));
258
264
  return undefined;
259
265
  }
260
266
  }
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,6 +38,7 @@ 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
43
  import type { Recording } from "./types.ts";
42
44
 
@@ -86,13 +88,13 @@ export default function micmeExtension(pi: ExtensionAPI) {
86
88
  await pasteOrSubmitTranscript(ctx, pi, lastTranscript);
87
89
  return;
88
90
  case "audio":
89
- ctx.ui.notify(lastAudioDir ? `Last Micme audio directory: ${lastAudioDir}` : "No kept Micme audio yet. Set MICME_KEEP_AUDIO=1.", "info");
91
+ ctx.ui.notify(lastAudioDir ? `Last Micme audio directory: ${sanitizeTerminalOutput(lastAudioDir)}` : "No kept Micme audio yet. Set MICME_KEEP_AUDIO=1.", "info");
90
92
  return;
91
93
  case "help":
92
94
  ctx.ui.notify(getHelpText(), "info");
93
95
  return;
94
96
  default:
95
- ctx.ui.notify(`Unknown micme action: ${action}. Try /micme help`, "warning");
97
+ ctx.ui.notify(`Unknown micme action: ${sanitizeTerminalOutput(action) || "(empty)"}. Try /micme help`, "warning");
96
98
  }
97
99
  } catch (error) {
98
100
  handleExtensionError(ctx, error);
@@ -121,6 +123,7 @@ export default function micmeExtension(pi: ExtensionAPI) {
121
123
  });
122
124
 
123
125
  pi.on("session_shutdown", async (_event, ctx) => {
126
+ ctx.ui.setStatus(STATUS_KEY, undefined);
124
127
  clearRecordingWidget(ctx);
125
128
  if (!recording) return;
126
129
  const active = recording;
@@ -143,7 +146,7 @@ function createMicmeEditorHandlers(ctx: ExtensionContext, toggle: (ctx: Extensio
143
146
 
144
147
  function handleExtensionError(ctx: ExtensionContext, error: unknown) {
145
148
  ctx.ui.setStatus(STATUS_KEY, undefined);
146
- ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
149
+ ctx.ui.notify(sanitizeTerminalOutput(error instanceof Error ? error.message : String(error)) || "Micme failed with an empty error message.", "error");
147
150
  }
148
151
 
149
152
  function isStillStarting(active: Recording) {
@@ -158,7 +161,7 @@ function isShortcutAutoRepeat() {
158
161
  }
159
162
 
160
163
  function getHelpText() {
161
- const shortcut = getShortcut();
164
+ const shortcut = sanitizeTerminalOutput(getShortcut()) || "not set";
162
165
  const actions = MICME_ACTIONS.filter((action) => action !== "help").join("|");
163
166
  return `Usage: /micme [${actions}]. Shortcut: ${shortcut} toggles recording; tap once to start, tap again to stop/transcribe.`;
164
167
  }
@@ -173,24 +176,38 @@ async function startRecording(ctx: ExtensionContext, stopHint = getShortcut()) {
173
176
  }
174
177
 
175
178
  const tempDir = await createRecordingDirectory(ctx.cwd, envFlag("MICME_KEEP_AUDIO"), "micme-");
176
- const audioPath = join(tempDir, "raw.wav");
177
- const command = buildRecorderCommand(audioPath);
178
- const active = spawnRecording(command, audioPath, tempDir);
179
- recording = active;
180
-
181
- const earlyExit = await raceWithTimeout(active.exitPromise, RECORDER_STARTUP_GRACE_MS);
182
- if (earlyExit) {
183
- if (active.stopRequested) return;
184
- recording = undefined;
185
- clearRecordingWidget(ctx);
186
- await cleanup(tempDir).catch(() => undefined);
187
- const stderr = active.stderr().trim();
188
- const suffix = stderr ? `\n${stderr}` : "";
189
- throw new Error(`Micme recorder exited early (${formatExit(earlyExit)}).${suffix}`);
179
+ let active: Recording | undefined;
180
+
181
+ try {
182
+ const audioPath = join(tempDir, "raw.wav");
183
+ const command = buildRecorderCommand(audioPath);
184
+ active = spawnRecording(command, audioPath, tempDir);
185
+ recording = active;
186
+
187
+ const earlyExit = await raceWithTimeout(active.exitPromise, RECORDER_STARTUP_GRACE_MS);
188
+ if (earlyExit) {
189
+ if (active.stopRequested) return;
190
+ const stderr = formatProcessOutput(active.stderr());
191
+ const suffix = stderr ? `\n${stderr}` : "";
192
+ throw new Error(`Micme recorder exited early (${formatExit(earlyExit)}).${suffix}`);
193
+ }
194
+
195
+ ctx.ui.setStatus(STATUS_KEY, `● recording (${sanitizeTerminalOutput(stopHint) || "shortcut"} or /micme)`);
196
+ startRecordingWidget(ctx, active);
197
+ } catch (error) {
198
+ await cleanupFailedRecordingStart(ctx, tempDir, active);
199
+ throw error;
190
200
  }
201
+ }
191
202
 
192
- ctx.ui.setStatus(STATUS_KEY, `● recording (${stopHint} or /micme)`);
193
- startRecordingWidget(ctx, active);
203
+ async function cleanupFailedRecordingStart(ctx: ExtensionContext, tempDir: string, active: Recording | undefined) {
204
+ if (active && recording === active) recording = undefined;
205
+ clearRecordingWidget(ctx);
206
+ if (active) {
207
+ await stopProcess(active).catch(() => undefined);
208
+ if (active.clipRecording) await stopProcess(active.clipRecording).catch(() => undefined);
209
+ }
210
+ await cleanup(tempDir).catch(() => undefined);
194
211
  }
195
212
 
196
213
  async function stopAndTranscribe(ctx: ExtensionContext, pi: ExtensionAPI) {
@@ -233,8 +250,8 @@ async function stopAndTranscribe(ctx: ExtensionContext, pi: ExtensionAPI) {
233
250
  } catch (error) {
234
251
  ctx.ui.setStatus(STATUS_KEY, undefined);
235
252
  lastAudioDir = active.tempDir;
236
- const message = error instanceof Error ? error.message : String(error);
237
- throw new Error(`${message}\nAudio kept for debugging: ${active.tempDir}`);
253
+ const message = sanitizeTerminalOutput(error instanceof Error ? error.message : String(error));
254
+ throw new Error(`${message}\nAudio kept for debugging: ${sanitizeTerminalOutput(active.tempDir)}`);
238
255
  } finally {
239
256
  if (completed && !envFlag("MICME_KEEP_AUDIO")) {
240
257
  await cleanup(active.tempDir).catch(() => undefined);
@@ -251,49 +268,53 @@ async function startStreamingTranscription(ctx: ExtensionContext, stopHint = get
251
268
  await ensureWhisperCppModel(plan.modelPath, ctx, { allowDownload: plan.modelDownloadable !== false });
252
269
 
253
270
  const tempDir = await createRecordingDirectory(ctx.cwd, envFlag("MICME_KEEP_AUDIO"), "micme-stream-");
254
- const command = buildWhisperStreamCommand(plan.binary, plan.modelPath, tempDir);
255
- const active = spawnRecording(command, "", tempDir);
256
- const baseText = ctx.ui.getEditorText();
257
- active.streaming = {
258
- baseText,
259
- previewText: baseText,
260
- outputBuffer: "",
261
- lastText: "",
262
- emittedWords: [],
263
- candidateWords: [],
264
- lastHypothesisWords: [],
265
- startedAt: Date.now(),
266
- };
267
- if (getStreamFinalizeWithClip()) {
268
- const audioPath = join(tempDir, "raw.wav");
269
- active.clipRecording = spawnRecording(buildRecorderCommand(audioPath), audioPath, tempDir);
270
- }
271
- recording = active;
271
+ let active: Recording | undefined;
272
272
 
273
- active.process.stdout?.on("data", (chunk: Buffer | string) => {
274
- const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
275
- handleStreamingOutput(ctx, active, text);
276
- });
273
+ try {
274
+ const command = buildWhisperStreamCommand(plan.binary, plan.modelPath, tempDir);
275
+ const clipAudioPath = getStreamFinalizeWithClip() ? join(tempDir, "raw.wav") : undefined;
276
+ const clipCommand = clipAudioPath ? buildRecorderCommand(clipAudioPath) : undefined;
277
+ active = spawnRecording(command, "", tempDir);
278
+ const streamRecording = active;
279
+ const baseText = ctx.ui.getEditorText();
280
+ streamRecording.streaming = {
281
+ baseText,
282
+ previewText: baseText,
283
+ outputBuffer: "",
284
+ lastText: "",
285
+ emittedWords: [],
286
+ candidateWords: [],
287
+ lastHypothesisWords: [],
288
+ startedAt: Date.now(),
289
+ };
290
+ if (clipCommand && clipAudioPath) {
291
+ streamRecording.clipRecording = spawnRecording(clipCommand, clipAudioPath, tempDir);
292
+ }
293
+ recording = streamRecording;
277
294
 
278
- const [earlyExit, recorderEarlyExit] = await Promise.all([
279
- raceWithTimeout(active.exitPromise, RECORDER_STARTUP_GRACE_MS),
280
- active.clipRecording ? raceWithTimeout(active.clipRecording.exitPromise, RECORDER_STARTUP_GRACE_MS) : Promise.resolve(undefined),
281
- ]);
282
- if (earlyExit || recorderEarlyExit) {
283
- if (active.stopRequested || active.clipRecording?.stopRequested) return;
284
- recording = undefined;
285
- clearRecordingWidget(ctx);
286
- await stopProcess(active).catch(() => undefined);
287
- if (active.clipRecording) await stopProcess(active.clipRecording).catch(() => undefined);
288
- await cleanup(tempDir).catch(() => undefined);
289
- const failed = earlyExit ? active : active.clipRecording;
290
- const stderr = failed?.stderr().trim();
291
- const suffix = stderr ? `\n${stderr}` : "";
292
- throw new Error(`Micme streaming exited early (${formatExit(earlyExit ?? recorderEarlyExit!)}).${suffix}`);
293
- }
295
+ streamRecording.process.stdout?.on("data", (chunk: Buffer | string) => {
296
+ const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
297
+ handleStreamingOutput(ctx, streamRecording, text);
298
+ });
294
299
 
295
- ctx.ui.setStatus(STATUS_KEY, `● streaming (${stopHint} or /micme)`);
296
- startRecordingWidget(ctx, active);
300
+ const [earlyExit, recorderEarlyExit] = await Promise.all([
301
+ raceWithTimeout(streamRecording.exitPromise, RECORDER_STARTUP_GRACE_MS),
302
+ streamRecording.clipRecording ? raceWithTimeout(streamRecording.clipRecording.exitPromise, RECORDER_STARTUP_GRACE_MS) : Promise.resolve(undefined),
303
+ ]);
304
+ if (earlyExit || recorderEarlyExit) {
305
+ if (streamRecording.stopRequested || streamRecording.clipRecording?.stopRequested) return;
306
+ const failed = earlyExit ? streamRecording : streamRecording.clipRecording;
307
+ const stderr = failed ? formatProcessOutput(failed.stderr()) : "";
308
+ const suffix = stderr ? `\n${stderr}` : "";
309
+ throw new Error(`Micme streaming exited early (${formatExit(earlyExit ?? recorderEarlyExit!)}).${suffix}`);
310
+ }
311
+
312
+ ctx.ui.setStatus(STATUS_KEY, `● streaming (${sanitizeTerminalOutput(stopHint) || "shortcut"} or /micme)`);
313
+ startRecordingWidget(ctx, streamRecording);
314
+ } catch (error) {
315
+ await cleanupFailedRecordingStart(ctx, tempDir, active);
316
+ throw error;
317
+ }
297
318
  }
298
319
 
299
320
  async function stopStreamingTranscription(ctx: ExtensionContext, pi: ExtensionAPI, active: Recording) {
@@ -351,8 +372,8 @@ async function stopStreamingTranscription(ctx: ExtensionContext, pi: ExtensionAP
351
372
  if (liveTranscript) lastTranscript = liveTranscript;
352
373
  lastAudioDir = active.tempDir;
353
374
  keepTempDir = true;
354
- const message = error instanceof Error ? error.message : String(error);
355
- ctx.ui.notify(`Micme kept the live append-only stream transcript because final clip transcription failed: ${message}\nAudio kept for debugging: ${active.tempDir}`, "warning");
375
+ const message = sanitizeTerminalOutput(error instanceof Error ? error.message : String(error));
376
+ 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");
356
377
  }
357
378
  }
358
379