@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/models.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { once } from "node:events";
3
- import { createWriteStream, existsSync, readdirSync, statSync } from "node:fs";
3
+ import { createWriteStream, existsSync, readdirSync, statSync, type WriteStream } from "node:fs";
4
4
  import { mkdir, rename, unlink } from "node:fs/promises";
5
5
  import { homedir } from "node:os";
6
6
  import { basename, dirname, extname, join } from "node:path";
@@ -15,9 +15,11 @@ import {
15
15
  } from "./constants.ts";
16
16
  import { env, expandConfigPath, getTranslateToEnglishLanguage } from "./config.ts";
17
17
  import { findExecutable, runProcess } from "./processes.ts";
18
+ import { sanitizeTerminalText } from "./terminal-text.ts";
18
19
  import type { ModelCandidate, ResolvedWhisperCppModel } from "./types.ts";
19
20
 
20
21
  const modelDownloads = new Map<string, Promise<void>>();
22
+ const PYTHON_WHISPER_MODELS_SCRIPT = "import whisper; print('\\n'.join(whisper.available_models()))";
21
23
 
22
24
  export function discoverWhisperCppModels(cwd: string): ModelCandidate[] {
23
25
  const candidates: ModelCandidate[] = [];
@@ -32,11 +34,12 @@ export function discoverWhisperCppModels(cwd: string): ModelCandidate[] {
32
34
  const current = env("MICME_WHISPER_CPP_MODEL");
33
35
  if (current) {
34
36
  const expanded = expandConfigPath(current);
37
+ const installed = isRegularFile(expanded);
35
38
  add({
36
39
  label: basename(expanded),
37
40
  value: expanded,
38
- description: existsSync(expanded) ? `current explicit path: ${expanded}` : `current explicit path is missing: ${expanded}`,
39
- installed: existsSync(expanded),
41
+ description: installed ? `current explicit path: ${expanded}` : `current explicit path is missing or not a file: ${expanded}`,
42
+ installed,
40
43
  kind: "path",
41
44
  });
42
45
  }
@@ -48,11 +51,12 @@ export function discoverWhisperCppModels(cwd: string): ModelCandidate[] {
48
51
  const cacheDir = getWhisperCppModelCacheDir();
49
52
  for (const modelName of WHISPER_CPP_MODEL_NAMES) {
50
53
  const path = join(cacheDir, `ggml-${modelName}.bin`);
54
+ const installed = isRegularFile(path);
51
55
  add({
52
56
  label: modelName,
53
57
  value: path,
54
- description: `${describeWhisperModel(modelName)} • ${basename(path)}${existsSync(path) ? "" : " (expected path; download model first)"}`,
55
- installed: existsSync(path),
58
+ description: `${describeWhisperModel(modelName)} • ${basename(path)}${installed ? "" : " (expected path; download model first)"}`,
59
+ installed,
56
60
  kind: "model-name",
57
61
  });
58
62
  }
@@ -161,7 +165,7 @@ function buildResolvedWhisperCppModel(
161
165
  modelName: metadata.modelName,
162
166
  source: metadata.source,
163
167
  configuredValue: metadata.configuredValue,
164
- exists: existsSync(path),
168
+ exists: isRegularFile(path),
165
169
  downloadable: isDownloadableWhisperCppModelPath(path),
166
170
  translationFallbackFrom: metadata.translationFallbackFrom,
167
171
  };
@@ -222,7 +226,7 @@ export async function queryPythonWhisperModelNames(): Promise<string[]> {
222
226
  if (!python) return [];
223
227
 
224
228
  try {
225
- const result = await runProcess(python, ["-c", "import whisper; print('\\n'.join(whisper.available_models()))"], 2_000);
229
+ const result = await runProcess(python, getPythonWhisperModelQueryArgs(), 2_000);
226
230
  if (result.code !== 0 || result.timedOut) return [];
227
231
  return uniqueModelNames(result.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean));
228
232
  } catch {
@@ -230,6 +234,11 @@ export async function queryPythonWhisperModelNames(): Promise<string[]> {
230
234
  }
231
235
  }
232
236
 
237
+ export function getPythonWhisperModelQueryArgs() {
238
+ // Isolated mode prevents project-local Python files (for example ./whisper.py) or PYTHONPATH from executing during model discovery.
239
+ return ["-I", "-c", PYTHON_WHISPER_MODELS_SCRIPT];
240
+ }
241
+
233
242
  export function uniqueModelNames(names: string[]) {
234
243
  const seen = new Set<string>();
235
244
  const output: string[] = [];
@@ -243,7 +252,8 @@ export function uniqueModelNames(names: string[]) {
243
252
  }
244
253
 
245
254
  export async function ensureWhisperCppModel(modelPath: string, ctx?: ExtensionContext, options: { allowDownload?: boolean } = {}) {
246
- if (existsSync(modelPath)) return;
255
+ assertDownloadTargetIsUsable(modelPath, "Micme model path");
256
+ if (isRegularFile(modelPath)) return;
247
257
  if (options.allowDownload === false) {
248
258
  throw new Error(`Micme model is missing: ${modelPath}`);
249
259
  }
@@ -253,7 +263,7 @@ export async function ensureWhisperCppModel(modelPath: string, ctx?: ExtensionCo
253
263
 
254
264
  const existingDownload = modelDownloads.get(modelPath);
255
265
  if (existingDownload) {
256
- ctx?.ui.setStatus(STATUS_KEY, `waiting for ${basename(modelPath)} download…`);
266
+ ctx?.ui.setStatus(STATUS_KEY, `waiting for ${safeBasename(modelPath)} download…`);
257
267
  try {
258
268
  await existingDownload;
259
269
  } finally {
@@ -278,16 +288,19 @@ export async function ensureWhisperCppModel(modelPath: string, ctx?: ExtensionCo
278
288
  }
279
289
 
280
290
  export async function downloadWhisperCppModel(modelName: string, modelPath: string, ctx?: ExtensionContext) {
281
- if (existsSync(modelPath)) return;
291
+ assertDownloadTargetIsUsable(modelPath, "Micme model path");
292
+ if (isRegularFile(modelPath)) return;
282
293
  const url = getWhisperCppModelUrl(modelName);
283
- ctx?.ui.setStatus(STATUS_KEY, `downloading ${basename(modelPath)}…`);
284
- ctx?.ui.notify(`Downloading ${basename(modelPath)}. This can take a while the first time.`, "info");
294
+ const displayName = safeBasename(modelPath);
295
+ ctx?.ui.setStatus(STATUS_KEY, `downloading ${displayName}…`);
296
+ ctx?.ui.notify(`Downloading ${displayName}. This can take a while the first time.`, "info");
285
297
  await downloadFile(url, modelPath, ctx);
286
- ctx?.ui.notify(`Downloaded ${basename(modelPath)}.`, "info");
298
+ ctx?.ui.notify(`Downloaded ${displayName}.`, "info");
287
299
  }
288
300
 
289
301
  export async function downloadFile(url: string, targetPath: string, ctx?: ExtensionContext) {
290
- if (existsSync(targetPath)) return;
302
+ assertDownloadTargetIsUsable(targetPath, "Download target");
303
+ if (isRegularFile(targetPath)) return;
291
304
  await mkdir(dirname(targetPath), { recursive: true });
292
305
  const tempPath = `${targetPath}.download-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
293
306
 
@@ -299,6 +312,8 @@ export async function downloadFile(url: string, targetPath: string, ctx?: Extens
299
312
  const totalBytes = Number(response.headers.get("content-length") || "0");
300
313
  const reader = response.body.getReader();
301
314
  const output = createWriteStream(tempPath, { flags: "wx" });
315
+ const outputFinished = finished(output);
316
+ outputFinished.catch(() => undefined);
302
317
  let downloadedBytes = 0;
303
318
  let lastUpdate = 0;
304
319
 
@@ -308,31 +323,38 @@ export async function downloadFile(url: string, targetPath: string, ctx?: Extens
308
323
  if (done) break;
309
324
  if (!value) continue;
310
325
  downloadedBytes += value.byteLength;
311
- if (!output.write(Buffer.from(value))) {
312
- await once(output, "drain");
313
- }
326
+ await writeDownloadChunk(output, Buffer.from(value), outputFinished);
314
327
 
315
328
  const now = Date.now();
316
329
  if (ctx && now - lastUpdate > 1_000) {
317
- ctx.ui.setStatus(STATUS_KEY, `downloading ${basename(targetPath)} ${formatDownloadProgress(downloadedBytes, totalBytes)}`);
330
+ ctx.ui.setStatus(STATUS_KEY, `downloading ${safeBasename(targetPath)} ${formatDownloadProgress(downloadedBytes, totalBytes)}`);
318
331
  lastUpdate = now;
319
332
  }
320
333
  }
321
334
 
322
335
  output.end();
323
- await finished(output);
324
- if (existsSync(targetPath)) {
336
+ await outputFinished;
337
+ if (isRegularFile(targetPath)) {
325
338
  await unlink(tempPath).catch(() => undefined);
326
339
  return;
327
340
  }
341
+ assertDownloadTargetIsUsable(targetPath, "Download target");
328
342
  await rename(tempPath, targetPath);
329
343
  } catch (error) {
344
+ await reader.cancel().catch(() => undefined);
330
345
  output.destroy();
346
+ await outputFinished.catch(() => undefined);
331
347
  await unlink(tempPath).catch(() => undefined);
332
348
  throw error;
333
349
  }
334
350
  }
335
351
 
352
+ async function writeDownloadChunk(output: WriteStream, chunk: Buffer, outputFinished: Promise<void>) {
353
+ if (output.destroyed) await outputFinished;
354
+ if (output.write(chunk)) return;
355
+ await Promise.race([once(output, "drain"), outputFinished]);
356
+ }
357
+
336
358
  export function getWhisperCppModelNameFromPath(modelPath: string) {
337
359
  const match = basename(modelPath).match(/^ggml-(.+)\.(?:bin|gguf)$/i);
338
360
  return match?.[1];
@@ -383,3 +405,29 @@ export function formatBytes(bytes: number) {
383
405
  }
384
406
  return `${value.toFixed(value >= 10 ? 0 : 1)} ${unit}`;
385
407
  }
408
+
409
+ function safeBasename(path: string) {
410
+ return sanitizeTerminalText(basename(path)) || "model";
411
+ }
412
+
413
+ function isRegularFile(path: string) {
414
+ try {
415
+ return statSync(path).isFile();
416
+ } catch {
417
+ return false;
418
+ }
419
+ }
420
+
421
+ function assertDownloadTargetIsUsable(path: string, label: string) {
422
+ try {
423
+ if (statSync(path).isFile()) return;
424
+ } catch (error) {
425
+ if (isNotFoundError(error)) return;
426
+ throw error;
427
+ }
428
+ throw new Error(`${label} exists but is not a file: ${path}`);
429
+ }
430
+
431
+ function isNotFoundError(error: unknown) {
432
+ return typeof error === "object" && error !== null && "code" in error && (error as NodeJS.ErrnoException).code === "ENOENT";
433
+ }
package/src/processes.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  import { spawn } from "node:child_process";
2
- import { existsSync } from "node:fs";
2
+ import { accessSync, constants as fsConstants, statSync } from "node:fs";
3
3
  import { rm, stat } from "node:fs/promises";
4
4
  import { delimiter, join } from "node:path";
5
5
  import { MAX_CAPTURED_OUTPUT_CHARS, MIN_AUDIO_BYTES, RECORDER_STOP_GRACE_MS } from "./constants.ts";
6
6
  import { pcm16BufferLevel } from "./audio-level.ts";
7
+ import { sanitizeTerminalOutput, stripTerminalControlSequences } from "./terminal-text.ts";
7
8
  import type { CommandSpec, ExitResult, Recording, RunResult } from "./types.ts";
8
9
 
9
10
  export function spawnRecording(command: CommandSpec, audioPath: string, tempDir: string): Recording {
@@ -17,6 +18,8 @@ export function spawnRecording(command: CommandSpec, audioPath: string, tempDir:
17
18
  let settled = false;
18
19
  let audioLevel = 0;
19
20
 
21
+ child.stdin?.on("error", () => undefined);
22
+
20
23
  if (command.meterFromStdout) {
21
24
  child.stdout?.on("data", (chunk: Buffer) => {
22
25
  audioLevel = audioLevel * 0.35 + pcm16BufferLevel(chunk) * 0.65;
@@ -97,7 +100,7 @@ export async function stopRecorder(active: Recording) {
97
100
 
98
101
  const audioStats = await stat(active.audioPath).catch(() => undefined);
99
102
  if (!audioStats || audioStats.size < MIN_AUDIO_BYTES) {
100
- const stderr = active.stderr().trim();
103
+ const stderr = formatProcessOutput(active.stderr());
101
104
  const suffix = stderr ? `\nRecorder output:\n${stderr}` : "";
102
105
  throw new Error(`Micme recorder did not produce usable audio.${suffix}`);
103
106
  }
@@ -152,7 +155,7 @@ export function runProcess(command: string, args: string[], timeoutMs: number):
152
155
  }
153
156
 
154
157
  export function normalizeTranscript(text: string) {
155
- return text
158
+ return stripTerminalControlSequences(text)
156
159
  .replace(/\r\n/g, "\n")
157
160
  .split("\n")
158
161
  .map((line) => line.trim())
@@ -163,12 +166,11 @@ export function normalizeTranscript(text: string) {
163
166
  }
164
167
 
165
168
  export function replacePlaceholders(template: string, values: Record<string, string>) {
166
- let output = template;
167
- for (const [key, value] of Object.entries(values)) {
168
- output = output.replaceAll(`{${key}}`, shellQuote(value));
169
- output = output.replaceAll(`{${key}Raw}`, value);
170
- }
171
- return output;
169
+ return template.replace(/\{([A-Za-z][A-Za-z0-9]*?)(Raw)?\}/g, (placeholder, key: string, rawSuffix: string | undefined) => {
170
+ if (!Object.prototype.hasOwnProperty.call(values, key)) return placeholder;
171
+ const value = values[key] ?? "";
172
+ return rawSuffix ? value : shellQuote(value);
173
+ });
172
174
  }
173
175
 
174
176
  export function findExecutable(names: string[]) {
@@ -179,18 +181,38 @@ export function findExecutable(names: string[]) {
179
181
  for (const dir of dirs) {
180
182
  for (const extension of extensions) {
181
183
  const candidate = join(dir, process.platform === "win32" && !/\.[^.]+$/.test(name) ? `${name}${extension}` : name);
182
- if (existsSync(candidate)) return candidate;
184
+ if (isExecutableFile(candidate)) return candidate;
183
185
  }
184
186
  }
185
187
  }
186
188
  return undefined;
187
189
  }
188
190
 
191
+ export function isExecutableFile(path: string) {
192
+ try {
193
+ const stats = statSync(path);
194
+ if (!stats.isFile()) return false;
195
+ if (process.platform === "win32") return true;
196
+ accessSync(path, fsConstants.X_OK);
197
+ return true;
198
+ } catch {
199
+ return false;
200
+ }
201
+ }
202
+
189
203
  export function appendCapped(current: string, chunk: string) {
190
204
  const next = current + chunk;
191
205
  return next.length > MAX_CAPTURED_OUTPUT_CHARS ? next.slice(-MAX_CAPTURED_OUTPUT_CHARS) : next;
192
206
  }
193
207
 
208
+ export function formatProcessOutput(...outputs: string[]) {
209
+ for (const output of outputs) {
210
+ const sanitized = sanitizeTerminalOutput(output);
211
+ if (sanitized) return sanitized;
212
+ }
213
+ return "";
214
+ }
215
+
194
216
  export function raceWithTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T | undefined> {
195
217
  return new Promise((resolve) => {
196
218
  const timer = setTimeout(() => resolve(undefined), timeoutMs);
@@ -1,4 +1,4 @@
1
- import { mkdir, mkdtemp, readdir } from "node:fs/promises";
1
+ import { lstat, mkdir, mkdtemp, readdir } from "node:fs/promises";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
4
 
@@ -14,6 +14,7 @@ export async function createRecordingDirectory(cwd: string, keepAudio: boolean,
14
14
  export async function createProjectRecordingDirectory(cwd: string) {
15
15
  const recordingsRoot = join(cwd, PROJECT_RECORDINGS_DIR);
16
16
  await mkdir(recordingsRoot, { recursive: true });
17
+ await assertSafeRecordingsRoot(recordingsRoot);
17
18
 
18
19
  const nextIndex = await getNextRecordingIndex(recordingsRoot);
19
20
 
@@ -31,6 +32,16 @@ export async function createProjectRecordingDirectory(cwd: string) {
31
32
  throw new Error(`Unable to create a Micme recording directory under ${recordingsRoot}.`);
32
33
  }
33
34
 
35
+ async function assertSafeRecordingsRoot(recordingsRoot: string) {
36
+ const stats = await lstat(recordingsRoot);
37
+ if (stats.isSymbolicLink()) {
38
+ throw new Error(`Refusing to keep Micme audio in a symbolic-link recordings directory: ${recordingsRoot}`);
39
+ }
40
+ if (!stats.isDirectory()) {
41
+ throw new Error(`Micme recordings path is not a directory: ${recordingsRoot}`);
42
+ }
43
+ }
44
+
34
45
  async function getNextRecordingIndex(recordingsRoot: string) {
35
46
  const entries = await readdir(recordingsRoot, { withFileTypes: true });
36
47
  let maxIndex = 0;
package/src/settings.ts CHANGED
@@ -32,6 +32,7 @@ import {
32
32
  } from "./config.ts";
33
33
  import { discoverAudioDevices } from "./audio.ts";
34
34
  import { formatBackendLabel, resolveTranscriptionPlan } from "./backends.ts";
35
+ import { sanitizeTerminalOutput, sanitizeTerminalText } from "./terminal-text.ts";
35
36
  import { discoverPythonWhisperModels, discoverWhisperCppModels, ensureWhisperCppModel, getPythonWhisperModelName, resolveWhisperCppModel } from "./models.ts";
36
37
  import { findExecutable } from "./processes.ts";
37
38
  import type { AudioDeviceCandidate, ModelCandidate, ResolvedTranscriptionPlan } from "./types.ts";
@@ -88,6 +89,15 @@ const TRANSLATE_FROM_VALUE_LABELS: Record<string, string> = {
88
89
  ...Object.fromEntries(TRANSLATION_SOURCE_LANGUAGE_VALUES.map((language) => [language, `${LANGUAGE_LABELS[language] ?? language} → English`])),
89
90
  };
90
91
 
92
+ type ConfigurationDiscoveryKey = "audio devices" | "whisper.cpp models" | "Python Whisper models";
93
+
94
+ type ConfigurationDiscoveryState = {
95
+ audioDevices: AudioDeviceCandidate[];
96
+ modelCandidates: ModelCandidate[];
97
+ pythonModelCandidates: ModelCandidate[];
98
+ pending: Set<ConfigurationDiscoveryKey>;
99
+ };
100
+
91
101
  export async function showConfiguration(ctx: ExtensionContext) {
92
102
  if (ctx.mode !== "tui") {
93
103
  ctx.ui.notify("/micme conf requires interactive TUI mode.", "warning");
@@ -96,29 +106,115 @@ export async function showConfiguration(ctx: ExtensionContext) {
96
106
 
97
107
  const configState = reloadMicmeConfig();
98
108
  if (configState.error) {
99
- ctx.ui.notify(`Micme config is invalid at ${configState.path}: ${configState.error}. Fix it before saving settings.`, "warning");
109
+ notifySanitized(ctx, `Micme config is invalid at ${configState.path}: ${configState.error}. Fix it before saving settings.`, "warning");
100
110
  }
101
- const audioDevices = await discoverAudioDevices();
102
- const modelCandidates = discoverWhisperCppModels(ctx.cwd);
103
- const pythonModelCandidates = await discoverPythonWhisperModels();
104
-
105
111
  await ctx.ui.custom<void>((tui, theme, _keybindings, done) => {
106
- const items = buildConfigurationItems(modelCandidates, pythonModelCandidates, audioDevices, theme);
107
- return new ConfigurationScreen({
108
- configPath: configState.path,
109
- items,
112
+ const discovery = createInitialConfigurationDiscovery();
113
+ let closed = false;
114
+ const screen = new ConfigurationScreen({
115
+ configPath: sanitizeTerminalOutput(configState.path) || "micme.json",
116
+ items: buildConfigurationItems(discovery.modelCandidates, discovery.pythonModelCandidates, discovery.audioDevices, theme),
110
117
  theme,
111
- onDone: done,
112
- onError: (error) => ctx.ui.notify(error instanceof Error ? error.message : String(error), "error"),
118
+ onDone: () => {
119
+ closed = true;
120
+ done();
121
+ },
122
+ onError: (error) => notifySanitized(ctx, error instanceof Error ? error.message : String(error), "error"),
113
123
  onSave: (id, newValue) => saveConfigurationValue(ctx, id, newValue),
114
124
  requestRender: () => tui.requestRender(),
125
+ statusText: formatDiscoveryStatus(discovery.pending),
126
+ });
127
+
128
+ startConfigurationDiscovery({
129
+ ctx,
130
+ cwd: ctx.cwd,
131
+ theme,
132
+ discovery,
133
+ screen,
134
+ isClosed: () => closed,
135
+ });
136
+
137
+ return screen;
138
+ });
139
+ }
140
+
141
+ function createInitialConfigurationDiscovery(): ConfigurationDiscoveryState {
142
+ return {
143
+ audioDevices: [],
144
+ modelCandidates: [],
145
+ pythonModelCandidates: [],
146
+ pending: new Set(["audio devices", "whisper.cpp models", "Python Whisper models"]),
147
+ };
148
+ }
149
+
150
+ function startConfigurationDiscovery(options: {
151
+ ctx: ExtensionContext;
152
+ cwd: string;
153
+ theme: MicmeTheme;
154
+ discovery: ConfigurationDiscoveryState;
155
+ screen: ConfigurationScreen;
156
+ isClosed: () => boolean;
157
+ }) {
158
+ void loadConfigurationDiscovery(options, "audio devices", deferDiscovery(discoverAudioDevices), (audioDevices) => {
159
+ options.discovery.audioDevices = audioDevices;
160
+ });
161
+ void loadConfigurationDiscovery(options, "whisper.cpp models", deferDiscovery(() => discoverWhisperCppModels(options.cwd)), (modelCandidates) => {
162
+ options.discovery.modelCandidates = modelCandidates;
163
+ });
164
+ void loadConfigurationDiscovery(options, "Python Whisper models", deferDiscovery(discoverPythonWhisperModels), (pythonModelCandidates) => {
165
+ options.discovery.pythonModelCandidates = pythonModelCandidates;
166
+ });
167
+ }
168
+
169
+ async function loadConfigurationDiscovery<T>(
170
+ options: {
171
+ ctx: ExtensionContext;
172
+ theme: MicmeTheme;
173
+ discovery: ConfigurationDiscoveryState;
174
+ screen: ConfigurationScreen;
175
+ isClosed: () => boolean;
176
+ },
177
+ key: ConfigurationDiscoveryKey,
178
+ promise: Promise<T>,
179
+ applyResult: (value: T) => void,
180
+ ) {
181
+ try {
182
+ applyResult(await promise);
183
+ } catch (error) {
184
+ if (!options.isClosed()) notifySanitized(options.ctx, `Micme could not load ${key}: ${error instanceof Error ? error.message : String(error)}`, "warning");
185
+ } finally {
186
+ options.discovery.pending.delete(key);
187
+ if (!options.isClosed()) {
188
+ options.screen.updateDiscoveredItems(
189
+ buildConfigurationItems(options.discovery.modelCandidates, options.discovery.pythonModelCandidates, options.discovery.audioDevices, options.theme),
190
+ formatDiscoveryStatus(options.discovery.pending),
191
+ );
192
+ }
193
+ }
194
+ }
195
+
196
+ function deferDiscovery<T>(load: () => T | Promise<T>): Promise<T> {
197
+ return new Promise((resolve, reject) => {
198
+ setImmediate(() => {
199
+ Promise.resolve()
200
+ .then(load)
201
+ .then(resolve, reject);
115
202
  });
116
203
  });
117
204
  }
118
205
 
206
+ function formatDiscoveryStatus(pending: Set<ConfigurationDiscoveryKey>) {
207
+ if (pending.size === 0) return "";
208
+ return `Loading ${[...pending].join(", ")}…`;
209
+ }
210
+
211
+ function notifySanitized(ctx: ExtensionContext, message: string, level: "warning" | "error") {
212
+ ctx.ui.notify(sanitizeTerminalOutput(message) || "Micme configuration message was empty.", level);
213
+ }
214
+
119
215
  class ConfigurationScreen implements Component {
120
216
  private readonly configPath: string;
121
- private readonly items: ConfigurationItem[];
217
+ private items: ConfigurationItem[];
122
218
  private readonly theme: MicmeTheme;
123
219
  private readonly onDone: () => void;
124
220
  private readonly onError: (error: unknown) => void;
@@ -144,6 +240,7 @@ class ConfigurationScreen implements Component {
144
240
  onError: (error: unknown) => void;
145
241
  onSave: (id: string, newValue: string) => Promise<Record<string, string>>;
146
242
  requestRender: () => void;
243
+ statusText?: string;
147
244
  }) {
148
245
  this.configPath = options.configPath;
149
246
  this.items = options.items;
@@ -152,9 +249,20 @@ class ConfigurationScreen implements Component {
152
249
  this.onError = options.onError;
153
250
  this.onSave = options.onSave;
154
251
  this.requestRender = options.requestRender;
252
+ this.statusText = options.statusText ?? "";
155
253
  for (const category of CONFIGURATION_CATEGORIES) this.selectedByCategory.set(category.id, 0);
156
254
  }
157
255
 
256
+ updateDiscoveredItems(items: ConfigurationItem[], statusText: string) {
257
+ this.items = items;
258
+ this.refreshDerivedItems();
259
+ this.clampSelections();
260
+ if (!this.saving && (!this.statusText || this.statusText.startsWith("Loading "))) {
261
+ this.statusText = statusText;
262
+ }
263
+ this.requestRender();
264
+ }
265
+
158
266
  render(width: number): string[] {
159
267
  this.refreshDerivedItems();
160
268
  if (this.submenuComponent) return this.submenuComponent.render(width);
@@ -169,6 +277,7 @@ class ConfigurationScreen implements Component {
169
277
  handleInput(data: string): void {
170
278
  if (this.submenuComponent) {
171
279
  this.submenuComponent.handleInput?.(data);
280
+ this.requestRender();
172
281
  return;
173
282
  }
174
283
 
@@ -182,20 +291,26 @@ class ConfigurationScreen implements Component {
182
291
  return;
183
292
  }
184
293
 
185
- if (this.handleSearchInput(data)) return;
294
+ if (this.handleSearchInput(data)) {
295
+ this.requestRender();
296
+ return;
297
+ }
186
298
 
187
299
  if (matchesKey(data, Key.tab) || matchesKey(data, Key.shift("tab"))) {
188
300
  this.focusedPane = this.focusedPane === "categories" ? "settings" : "categories";
301
+ this.requestRender();
189
302
  return;
190
303
  }
191
304
 
192
305
  if (matchesKey(data, Key.up)) {
193
306
  this.moveSelection(-1);
307
+ this.requestRender();
194
308
  return;
195
309
  }
196
310
 
197
311
  if (matchesKey(data, Key.down)) {
198
312
  this.moveSelection(1);
313
+ this.requestRender();
199
314
  return;
200
315
  }
201
316
 
@@ -205,17 +320,20 @@ class ConfigurationScreen implements Component {
205
320
  } else {
206
321
  this.activateSelectedSetting();
207
322
  }
323
+ this.requestRender();
208
324
  return;
209
325
  }
210
326
 
211
327
  if (matchesKey(data, Key.space) && this.focusedPane === "settings") {
212
328
  this.activateSelectedSetting();
329
+ this.requestRender();
213
330
  return;
214
331
  }
215
332
 
216
333
  if (matchesKey(data, Key.escape)) {
217
334
  if (this.focusedPane === "settings") {
218
335
  this.focusedPane = "categories";
336
+ this.requestRender();
219
337
  } else {
220
338
  this.onDone();
221
339
  }
@@ -407,7 +525,7 @@ class ConfigurationScreen implements Component {
407
525
 
408
526
  private formatSlider(item: ConfigurationItem, width: number) {
409
527
  const value = Number(item.rawValue);
410
- const valueText = Number.isFinite(value) ? value.toFixed(2) : item.rawValue;
528
+ const valueText = Number.isFinite(value) ? value.toFixed(2) : sanitizeTerminalText(item.rawValue);
411
529
  if (width < valueText.length + 5) return fitAnsi(valueText, width);
412
530
 
413
531
  const ratio = item.id === "MICME_STREAM_VAD_THRESHOLD" ? clamp(value, 0, 1) : clamp(value / 2, 0, 1);
@@ -1007,11 +1125,14 @@ export function buildConfigurationItems(
1007
1125
  }
1008
1126
 
1009
1127
  export function createModelSelector(candidates: ModelCandidate[], theme: MicmeTheme, done: (selectedValue?: string) => void): Component {
1010
- const items: SelectItem[] = candidates.map((candidate) => ({
1011
- value: candidate.value,
1012
- label: candidate.installed ? `✓ ${candidate.label}` : `○ ${candidate.label}`,
1013
- description: candidate.description,
1014
- }));
1128
+ const items: SelectItem[] = candidates.map((candidate) => {
1129
+ const label = sanitizeTerminalText(candidate.label) || "model";
1130
+ return {
1131
+ value: candidate.value,
1132
+ label: candidate.installed ? `✓ ${label}` : `○ ${label}`,
1133
+ description: sanitizeTerminalText(candidate.description),
1134
+ };
1135
+ });
1015
1136
 
1016
1137
  const container = new Container();
1017
1138
  container.addChild(new DynamicBorder((s: string) => theme.fg("accent", s)));
@@ -1061,10 +1182,10 @@ export async function saveConfigurationValue(ctx: ExtensionContext, id: string,
1061
1182
  }
1062
1183
 
1063
1184
  export function displayConfigurationValue(id: string, value: string) {
1064
- if (id === "MICME_WHISPER_CPP_MODEL") return value ? basename(value) : "not set";
1185
+ if (id === "MICME_WHISPER_CPP_MODEL") return value ? sanitizeTerminalText(basename(value)) || "model" : "not set";
1065
1186
  if (id === "MICME_TRANSCRIBE_COMMAND") return value ? "configured" : "not set";
1066
- if (id === "MICME_AUDIO_FILTER") return value || "<empty>";
1067
- return value || "not set";
1187
+ if (id === "MICME_AUDIO_FILTER") return sanitizeTerminalText(value) || "<empty>";
1188
+ return sanitizeTerminalText(value) || "not set";
1068
1189
  }
1069
1190
 
1070
1191
  function getUiBackendValue(plan: ResolvedTranscriptionPlan): "whisper.cpp" | "python" {
@@ -1091,6 +1212,7 @@ export function uniqueStrings(values: string[]) {
1091
1212
  function getConfigurationValuesToWrite(id: string, value: string) {
1092
1213
  if (id === "MICME_TRANSCRIPTION_MODE") return getTranscriptionModeProfile(value === "stream" ? "stream" : "clip");
1093
1214
  if (id === "MICME_SHORTCUT") return { MICME_SHORTCUT: value, MICME_PRINTABLE_SHORTCUTS: undefined };
1215
+ if (id === "MICME_WHISPER_CPP_MODEL" && !value) return { MICME_WHISPER_CPP_MODEL: undefined };
1094
1216
  return { [id]: value };
1095
1217
  }
1096
1218
 
package/src/streaming.ts CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  } from "./config.ts";
16
16
  import { pasteOrSubmitTranscript } from "./transcript-delivery.ts";
17
17
  import { shellQuote } from "./processes.ts";
18
+ import { sanitizeTerminalText } from "./terminal-text.ts";
18
19
  import type { CommandSpec, Recording, StreamingState } from "./types.ts";
19
20
 
20
21
  export type StreamingFrameMode = "cumulative" | "incremental" | "rolling" | "duplicate" | "reset";
@@ -155,7 +156,7 @@ export function sanitizeStreamingText(text: string) {
155
156
  }
156
157
 
157
158
  export function stripStreamingControls(text: string) {
158
- return text.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, " ").replace(/\s+/g, " ").trim();
159
+ return sanitizeTerminalText(text);
159
160
  }
160
161
 
161
162
  export function diffStreamingText(previous: string, current: string) {
@@ -327,8 +328,7 @@ export function getStreamingTranscript(state: StreamingState) {
327
328
 
328
329
  export function renderStreamingPreview(ctx: ExtensionContext, state: StreamingState, trailingSpace: boolean) {
329
330
  const transcript = getStreamingTranscript(state);
330
- const suffix = transcript ? `${transcript}${trailingSpace ? " " : ""}` : "";
331
- const nextText = `${state.baseText}${suffix}`;
331
+ const nextText = appendTranscriptToBaseText(state.baseText, transcript, trailingSpace);
332
332
  if (nextText === state.previewText) return;
333
333
  ctx.ui.setEditorText(nextText);
334
334
  state.previewText = nextText;
@@ -354,8 +354,7 @@ export async function pasteOrSubmitFinalStreamingTranscript(ctx: ExtensionContex
354
354
  return;
355
355
  }
356
356
 
357
- const suffix = /\s$/.test(transcript) ? transcript : `${transcript} `;
358
- const nextText = `${state.baseText}${suffix}`;
357
+ const nextText = appendTranscriptToBaseText(state.baseText, transcript, true);
359
358
  ctx.ui.setEditorText(nextText);
360
359
  state.previewText = nextText;
361
360
  }
@@ -366,6 +365,17 @@ export function clearStreamingFlush(state: StreamingState) {
366
365
  state.flushTimer = undefined;
367
366
  }
368
367
 
368
+ function appendTranscriptToBaseText(baseText: string, transcript: string, trailingSpace: boolean) {
369
+ if (!transcript) return baseText;
370
+ const separator = needsStreamingSeparator(baseText, transcript) ? " " : "";
371
+ const suffix = /\s$/.test(transcript) || !trailingSpace ? transcript : `${transcript} `;
372
+ return `${baseText}${separator}${suffix}`;
373
+ }
374
+
375
+ function needsStreamingSeparator(baseText: string, transcript: string) {
376
+ return Boolean(baseText && transcript && !/\s$/u.test(baseText) && !/^[\s.,!?;:)}\]]/u.test(transcript));
377
+ }
378
+
369
379
  function queueRollingStreamingWords(state: StreamingState, words: string[]) {
370
380
  const overlap = streamingWordOverlap(state.candidateWords, words);
371
381
  if (overlap <= 0) {