@senad-d/micme 0.1.0

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.
@@ -0,0 +1,948 @@
1
+ import { DynamicBorder, type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ Container,
4
+ fuzzyFilter,
5
+ Key,
6
+ matchesKey,
7
+ type Component,
8
+ type SelectItem,
9
+ SelectList,
10
+ type SettingItem,
11
+ Text,
12
+ truncateToWidth,
13
+ visibleWidth,
14
+ } from "@earendil-works/pi-tui";
15
+ import { basename, join } from "node:path";
16
+ import {
17
+ DEFAULT_MACOS_PRINTABLE_SHORTCUT,
18
+ DEFAULT_RECORD_SAMPLE_RATE,
19
+ DEFAULT_SHORTCUT,
20
+ DEFAULT_STREAM_VAD_THRESHOLD,
21
+ DEFAULT_TRANSCRIBE_SAMPLE_RATE,
22
+ DEFAULT_WHISPER_CPP_MODEL_NAME,
23
+ PYTHON_WHISPER_MODEL_NAMES,
24
+ WHISPER_CPP_MODEL_NAMES,
25
+ } from "./constants.ts";
26
+ import {
27
+ env,
28
+ expandConfigPath,
29
+ getTranscriptionMode,
30
+ getTranscriptionModeProfile,
31
+ reloadDotEnv,
32
+ writeDotEnvValue,
33
+ } from "./config.ts";
34
+ import { discoverAudioDevices } from "./audio.ts";
35
+ import { discoverWhisperCppModels, ensureWhisperCppModel, getDefaultWhisperCppModelPath } from "./models.ts";
36
+ import { findExecutable } from "./processes.ts";
37
+ import type { AudioDeviceCandidate, ModelCandidate } from "./types.ts";
38
+
39
+ type MicmeTheme = ExtensionContext["ui"]["theme"];
40
+
41
+ type ConfigurationCategoryId = "general" | "transcription" | "streaming" | "audio" | "shortcuts" | "diagnostics";
42
+ type FocusedPane = "categories" | "settings";
43
+ type DisplayKind = "boolean" | "number" | "path" | "slider" | "text" | "model";
44
+
45
+ interface ConfigurationCategory {
46
+ id: ConfigurationCategoryId;
47
+ label: string;
48
+ description: string;
49
+ }
50
+
51
+ interface ConfigurationItem extends SettingItem {
52
+ categoryId: ConfigurationCategoryId;
53
+ rawValue: string;
54
+ displayKind?: DisplayKind;
55
+ emptyLabel?: string;
56
+ valueLabels?: Record<string, string>;
57
+ }
58
+
59
+ const CONFIGURATION_CATEGORIES: ConfigurationCategory[] = [
60
+ { id: "general", label: "General", description: "Core defaults used by Micme." },
61
+ { id: "transcription", label: "Transcription", description: "Backend model, mode, and transcription fallback settings." },
62
+ { id: "streaming", label: "Streaming", description: "Low-latency live transcription behavior." },
63
+ { id: "audio", label: "Audio", description: "Recording, preprocessing, and metering settings." },
64
+ { id: "shortcuts", label: "Shortcuts", description: "Terminal and printable-character shortcut bindings." },
65
+ { id: "diagnostics", label: "Diagnostics", description: "Debug and timing output." },
66
+ ];
67
+
68
+ const TWO_PANE_MIN_WIDTH = 72;
69
+ const MAX_SETTINGS_ROWS = 10;
70
+
71
+ export async function showConfiguration(ctx: ExtensionContext) {
72
+ if (ctx.mode !== "tui") {
73
+ ctx.ui.notify("/micme conf requires interactive TUI mode.", "warning");
74
+ return;
75
+ }
76
+
77
+ reloadDotEnv(ctx.cwd);
78
+ const audioDevices = await discoverAudioDevices();
79
+ const modelCandidates = discoverWhisperCppModels(ctx.cwd);
80
+
81
+ await ctx.ui.custom<void>((tui, theme, _keybindings, done) => {
82
+ const items = buildConfigurationItems(modelCandidates, audioDevices, theme);
83
+ return new ConfigurationScreen({
84
+ cwd: ctx.cwd,
85
+ items,
86
+ theme,
87
+ onDone: done,
88
+ onError: (error) => ctx.ui.notify(error instanceof Error ? error.message : String(error), "error"),
89
+ onSave: (id, newValue) => saveConfigurationValue(ctx, id, newValue),
90
+ requestRender: () => tui.requestRender(),
91
+ });
92
+ });
93
+ }
94
+
95
+ class ConfigurationScreen implements Component {
96
+ private readonly cwd: string;
97
+ private readonly items: ConfigurationItem[];
98
+ private readonly theme: MicmeTheme;
99
+ private readonly onDone: () => void;
100
+ private readonly onError: (error: unknown) => void;
101
+ private readonly onSave: (id: string, newValue: string) => Promise<Record<string, string>>;
102
+ private readonly requestRender: () => void;
103
+ private focusedPane: FocusedPane = "categories";
104
+ private categoryIndex = 0;
105
+ private selectedByCategory = new Map<ConfigurationCategoryId, number>();
106
+ private searchActive = false;
107
+ private searchQuery = "";
108
+ private selectedSearchIndex = 0;
109
+ private submenuComponent: Component | null = null;
110
+ private saving = false;
111
+ private statusText = "";
112
+
113
+ constructor(options: {
114
+ cwd: string;
115
+ items: ConfigurationItem[];
116
+ theme: MicmeTheme;
117
+ onDone: () => void;
118
+ onError: (error: unknown) => void;
119
+ onSave: (id: string, newValue: string) => Promise<Record<string, string>>;
120
+ requestRender: () => void;
121
+ }) {
122
+ this.cwd = options.cwd;
123
+ this.items = options.items;
124
+ this.theme = options.theme;
125
+ this.onDone = options.onDone;
126
+ this.onError = options.onError;
127
+ this.onSave = options.onSave;
128
+ this.requestRender = options.requestRender;
129
+ for (const category of CONFIGURATION_CATEGORIES) this.selectedByCategory.set(category.id, 0);
130
+ }
131
+
132
+ render(width: number): string[] {
133
+ if (this.submenuComponent) return this.submenuComponent.render(width);
134
+ if (width < TWO_PANE_MIN_WIDTH) return this.renderNarrow(width);
135
+ return this.renderTwoPane(width);
136
+ }
137
+
138
+ invalidate(): void {
139
+ this.submenuComponent?.invalidate?.();
140
+ }
141
+
142
+ handleInput(data: string): void {
143
+ if (this.submenuComponent) {
144
+ this.submenuComponent.handleInput?.(data);
145
+ return;
146
+ }
147
+
148
+ if (matchesKey(data, Key.ctrl("c")) || data === "q" || data === "Q") {
149
+ this.onDone();
150
+ return;
151
+ }
152
+
153
+ if (this.handleSearchInput(data)) return;
154
+
155
+ if (matchesKey(data, Key.tab) || matchesKey(data, Key.shift("tab"))) {
156
+ this.focusedPane = this.focusedPane === "categories" ? "settings" : "categories";
157
+ return;
158
+ }
159
+
160
+ if (matchesKey(data, Key.up)) {
161
+ this.moveSelection(-1);
162
+ return;
163
+ }
164
+
165
+ if (matchesKey(data, Key.down)) {
166
+ this.moveSelection(1);
167
+ return;
168
+ }
169
+
170
+ if (matchesKey(data, Key.enter)) {
171
+ if (this.focusedPane === "categories") {
172
+ this.focusedPane = "settings";
173
+ } else {
174
+ this.activateSelectedSetting();
175
+ }
176
+ return;
177
+ }
178
+
179
+ if (matchesKey(data, Key.space) && this.focusedPane === "settings") {
180
+ this.activateSelectedSetting();
181
+ return;
182
+ }
183
+
184
+ if (matchesKey(data, Key.escape)) {
185
+ if (this.focusedPane === "settings") {
186
+ this.focusedPane = "categories";
187
+ } else {
188
+ this.onDone();
189
+ }
190
+ }
191
+ }
192
+
193
+ private renderTwoPane(width: number): string[] {
194
+ if (width < 24) return this.renderTiny(width);
195
+
196
+ const leftWidth = Math.min(22, Math.max(16, Math.floor(width * 0.27)));
197
+ const rightWidth = Math.max(10, width - leftWidth - 3);
198
+ const categoryLines = this.renderCategoryPaneLines(leftWidth);
199
+ const settingsLines = this.renderSettingsPaneLines(rightWidth);
200
+ const paneHeight = Math.max(categoryLines.length, settingsLines.length, 8);
201
+ const lines: string[] = [];
202
+
203
+ lines.push(this.renderTitleBorder(width, this.currentHeaderLabel()));
204
+ lines.push(this.renderFullLine(width, `writes ${join(this.cwd, ".env")} • shell env overrides .env`));
205
+ lines.push(this.renderFullLine(width, "↑↓ move Tab pane Enter edit / search Esc back q quit"));
206
+ lines.push(this.renderPaneSeparator(width, leftWidth, rightWidth, "top"));
207
+
208
+ for (let index = 0; index < paneHeight; index++) {
209
+ const left = categoryLines[index] ?? "";
210
+ const right = settingsLines[index] ?? "";
211
+ lines.push(this.renderPaneLine(left, right, leftWidth, rightWidth));
212
+ }
213
+
214
+ lines.push(this.renderPaneSeparator(width, leftWidth, rightWidth, "bottom"));
215
+ lines.push(this.renderFullLine(width, this.renderFooterText()));
216
+ lines.push(this.colorBorder(`╰${"─".repeat(Math.max(0, width - 2))}╯`, width));
217
+ return lines.map((line) => truncateToWidth(line, width, ""));
218
+ }
219
+
220
+ private renderNarrow(width: number): string[] {
221
+ if (width < 24) return this.renderTiny(width);
222
+
223
+ const innerWidth = width - 2;
224
+ const showCategories = this.focusedPane === "categories" && !this.hasSearchQuery();
225
+ const bodyLines = showCategories ? this.renderCategoryPaneLines(innerWidth) : this.renderSettingsPaneLines(innerWidth);
226
+ const lines: string[] = [];
227
+
228
+ lines.push(this.renderTitleBorder(width, this.currentHeaderLabel()));
229
+ lines.push(this.renderFullLine(width, `writes ${join(this.cwd, ".env")} • shell env overrides .env`));
230
+ lines.push(this.renderFullLine(width, showCategories ? "↑↓ category Enter open / search q quit" : "↑↓ move Enter edit Esc categories / search q quit"));
231
+ lines.push(this.colorBorder(`├${"─".repeat(innerWidth)}┤`, width));
232
+ for (const line of bodyLines) lines.push(this.renderFullLine(width, line));
233
+ lines.push(this.colorBorder(`├${"─".repeat(innerWidth)}┤`, width));
234
+ lines.push(this.renderFullLine(width, this.renderFooterText()));
235
+ lines.push(this.colorBorder(`╰${"─".repeat(innerWidth)}╯`, width));
236
+ return lines.map((line) => truncateToWidth(line, width, ""));
237
+ }
238
+
239
+ private renderTiny(width: number): string[] {
240
+ const selected = this.getSelectedSetting();
241
+ return [
242
+ fitAnsi("Micme Configuration", width),
243
+ fitAnsi(this.currentHeaderLabel(), width),
244
+ fitAnsi(selected ? `${selected.label}: ${this.formatValue(selected, Math.max(0, width - selected.label.length - 2))}` : "No settings", width),
245
+ fitAnsi("q quit", width),
246
+ ];
247
+ }
248
+
249
+ private renderTitleBorder(width: number, rightLabel: string) {
250
+ const innerWidth = Math.max(0, width - 2);
251
+ const title = "─ Micme Configuration ";
252
+ const right = ` ${rightLabel} ─`;
253
+ const fillWidth = innerWidth - visibleWidth(title) - visibleWidth(right);
254
+ let inner: string;
255
+ if (fillWidth >= 0) {
256
+ inner = `${title}${"─".repeat(fillWidth)}${right}`;
257
+ } else {
258
+ inner = padRightAnsi(fitAnsi(`─ Micme Configuration ${rightLabel}`, innerWidth), innerWidth);
259
+ }
260
+ return this.colorBorder(`╭${inner}╮`, width);
261
+ }
262
+
263
+ private renderFullLine(width: number, text: string) {
264
+ const innerWidth = Math.max(0, width - 2);
265
+ return `${this.theme.fg("accent", "│")}${padRightAnsi(text, innerWidth)}${this.theme.fg("accent", "│")}`;
266
+ }
267
+
268
+ private renderPaneSeparator(width: number, leftWidth: number, rightWidth: number, position: "top" | "bottom") {
269
+ const middle = position === "top" ? "┬" : "┴";
270
+ return this.colorBorder(`├${"─".repeat(leftWidth)}${middle}${"─".repeat(rightWidth)}┤`, width);
271
+ }
272
+
273
+ private renderPaneLine(left: string, right: string, leftWidth: number, rightWidth: number) {
274
+ return [
275
+ this.theme.fg("accent", "│"),
276
+ padRightAnsi(left, leftWidth),
277
+ this.theme.fg("accent", "│"),
278
+ padRightAnsi(right, rightWidth),
279
+ this.theme.fg("accent", "│"),
280
+ ].join("");
281
+ }
282
+
283
+ private colorBorder(line: string, width: number) {
284
+ return this.theme.fg("accent", fitAnsi(line, width, ""));
285
+ }
286
+
287
+ private renderCategoryPaneLines(width: number) {
288
+ return CONFIGURATION_CATEGORIES.map((category, index) => {
289
+ const selected = index === this.categoryIndex;
290
+ const focused = this.focusedPane === "categories";
291
+ const prefix = selected ? "▶ " : " ";
292
+ const styledPrefix = selected ? this.theme.fg(focused ? "accent" : "muted", prefix) : prefix;
293
+ const label = fitAnsi(category.label, Math.max(0, width - 2));
294
+ const styledLabel = selected ? this.theme.fg(focused ? "accent" : "muted", focused ? this.theme.bold(label) : label) : this.theme.fg("dim", label);
295
+ return padRightAnsi(`${styledPrefix}${styledLabel}`, width);
296
+ });
297
+ }
298
+
299
+ private renderSettingsPaneLines(width: number) {
300
+ const displayItems = this.getDisplaySettings();
301
+ const selectedIndex = this.getSelectedSettingIndex(displayItems.length);
302
+ const scope = this.getSettingsScopeTitle();
303
+ const titleColor = this.focusedPane === "settings" ? "accent" : "dim";
304
+ const title = this.theme.fg(titleColor, this.theme.bold(fitAnsi(scope, Math.max(0, width - 8))));
305
+ const counter = displayItems.length > 0 ? `${selectedIndex + 1}/${displayItems.length}` : "0/0";
306
+ const lines = [padRightAnsi(`${title}${" ".repeat(Math.max(1, width - visibleWidth(title) - visibleWidth(counter)))}${this.theme.fg("dim", counter)}`, width)];
307
+
308
+ if (displayItems.length === 0) {
309
+ lines.push(padRightAnsi(this.theme.fg("warning", " No matching settings"), width));
310
+ return lines;
311
+ }
312
+
313
+ const [startIndex, endIndex] = getVisibleRange(selectedIndex, displayItems.length, MAX_SETTINGS_ROWS);
314
+ for (let index = startIndex; index < endIndex; index++) {
315
+ const item = displayItems[index];
316
+ if (!item) continue;
317
+ lines.push(this.renderSettingLine(item, index === selectedIndex, width));
318
+ }
319
+ return lines;
320
+ }
321
+
322
+ private renderSettingLine(item: ConfigurationItem, selected: boolean, width: number) {
323
+ const focused = this.focusedPane === "settings";
324
+ const prefix = selected ? "▶ " : " ";
325
+ const styledPrefix = selected ? this.theme.fg(focused ? "accent" : "muted", prefix) : prefix;
326
+ const valueWidth = Math.max(0, Math.min(28, Math.floor(width * 0.4)));
327
+ const labelWidth = Math.max(1, width - 2 - 1 - valueWidth);
328
+ const labelText = this.hasSearchQuery() ? `${item.label} (${this.getCategory(item.categoryId).label})` : item.label;
329
+ const label = fitAnsi(labelText, labelWidth);
330
+ const styledLabel = selected ? this.theme.fg(focused ? "accent" : "muted", focused ? this.theme.bold(label) : label) : label;
331
+ const value = this.formatValue(item, valueWidth);
332
+ return padRightAnsi(`${styledPrefix}${padRightAnsi(styledLabel, labelWidth)} ${padLeftAnsi(value, valueWidth)}`, width);
333
+ }
334
+
335
+ private renderFooterText() {
336
+ const selected = this.getSelectedSetting();
337
+ const category = this.currentCategory();
338
+ const selection = this.getSelectionText();
339
+ const search = this.searchActive ? `Search: ${this.searchQuery || "type to filter all settings"}` : "";
340
+ const lead = this.statusText || search || "↑↓ move • Tab pane • Enter edit • / search • Esc back • q quit";
341
+ const description = selected?.description ?? category.description;
342
+ return `${lead} • ${selection} • ${description}`;
343
+ }
344
+
345
+ private formatValue(item: ConfigurationItem, width: number) {
346
+ if (width <= 0) return "";
347
+ const raw = item.rawValue;
348
+ if (!raw) return this.theme.fg("dim", fitAnsi(item.emptyLabel ?? displayConfigurationValue(item.id, raw), width));
349
+
350
+ if (item.displayKind === "boolean") {
351
+ const enabled = isTruthyConfigValue(raw);
352
+ return enabled ? this.theme.fg("success", fitAnsi("ON", width)) : this.theme.fg("dim", fitAnsi("OFF", width));
353
+ }
354
+
355
+ if (item.displayKind === "slider") return this.formatSlider(item, width);
356
+
357
+ const label = item.valueLabels?.[raw] ?? displayConfigurationValue(item.id, raw);
358
+ if (item.displayKind === "path" || item.displayKind === "model") return fitPath(label, width);
359
+ return fitAnsi(label, width);
360
+ }
361
+
362
+ private formatSlider(item: ConfigurationItem, width: number) {
363
+ const value = Number(item.rawValue);
364
+ const valueText = Number.isFinite(value) ? value.toFixed(2) : item.rawValue;
365
+ if (width < valueText.length + 5) return fitAnsi(valueText, width);
366
+
367
+ const ratio = item.id === "MICME_STREAM_VAD_THRESHOLD" ? clamp(value, 0, 1) : clamp(value / 2, 0, 1);
368
+ const barWidth = Math.max(3, Math.min(10, width - valueText.length - 4));
369
+ const filled = clamp(Math.round(ratio * barWidth), 0, barWidth);
370
+ const bar = `[${"█".repeat(filled)}${"░".repeat(barWidth - filled)}]`;
371
+ return fitAnsi(`${this.theme.fg("accent", bar)} ${valueText}`, width);
372
+ }
373
+
374
+ private currentHeaderLabel() {
375
+ if (this.hasSearchQuery()) return "Search";
376
+ return this.currentCategory().label;
377
+ }
378
+
379
+ private getSettingsScopeTitle() {
380
+ if (this.hasSearchQuery()) return `SEARCH ${this.searchQuery}`.toUpperCase();
381
+ return this.currentCategory().label.toUpperCase();
382
+ }
383
+
384
+ private getSelectionText() {
385
+ const displayItems = this.getDisplaySettings();
386
+ if (displayItems.length === 0) return "0/0";
387
+ return `${this.getSelectedSettingIndex(displayItems.length) + 1}/${displayItems.length}`;
388
+ }
389
+
390
+ private currentCategory() {
391
+ return CONFIGURATION_CATEGORIES[this.categoryIndex] ?? CONFIGURATION_CATEGORIES[0]!;
392
+ }
393
+
394
+ private getCategory(id: ConfigurationCategoryId) {
395
+ return CONFIGURATION_CATEGORIES.find((category) => category.id === id) ?? CONFIGURATION_CATEGORIES[0]!;
396
+ }
397
+
398
+ private getCategoryItems(categoryId = this.currentCategory().id) {
399
+ return this.items.filter((item) => item.categoryId === categoryId);
400
+ }
401
+
402
+ private getDisplaySettings() {
403
+ if (!this.hasSearchQuery()) return this.getCategoryItems();
404
+ return fuzzyFilter(this.items, this.searchQuery, (item) => `${item.label} ${item.id} ${item.description ?? ""} ${this.getCategory(item.categoryId).label}`);
405
+ }
406
+
407
+ private getSelectedSetting() {
408
+ const displayItems = this.getDisplaySettings();
409
+ return displayItems[this.getSelectedSettingIndex(displayItems.length)];
410
+ }
411
+
412
+ private getSelectedSettingIndex(total: number) {
413
+ if (total <= 0) return 0;
414
+ if (this.hasSearchQuery()) {
415
+ this.selectedSearchIndex = clamp(this.selectedSearchIndex, 0, total - 1);
416
+ return this.selectedSearchIndex;
417
+ }
418
+ const categoryId = this.currentCategory().id;
419
+ const selected = clamp(this.selectedByCategory.get(categoryId) ?? 0, 0, total - 1);
420
+ this.selectedByCategory.set(categoryId, selected);
421
+ return selected;
422
+ }
423
+
424
+ private moveSelection(delta: number) {
425
+ if (this.focusedPane === "categories") {
426
+ this.categoryIndex = wrapIndex(this.categoryIndex + delta, CONFIGURATION_CATEGORIES.length);
427
+ return;
428
+ }
429
+
430
+ const items = this.getDisplaySettings();
431
+ if (items.length === 0) return;
432
+ const next = wrapIndex(this.getSelectedSettingIndex(items.length) + delta, items.length);
433
+ if (this.hasSearchQuery()) {
434
+ this.selectedSearchIndex = next;
435
+ } else {
436
+ this.selectedByCategory.set(this.currentCategory().id, next);
437
+ }
438
+ }
439
+
440
+ private activateSelectedSetting() {
441
+ if (this.saving) return;
442
+ const displayItems = this.getDisplaySettings();
443
+ const item = displayItems[this.getSelectedSettingIndex(displayItems.length)];
444
+ if (!item) return;
445
+
446
+ if (item.submenu) {
447
+ this.submenuComponent = item.submenu(item.rawValue, (selectedValue?: string) => {
448
+ this.submenuComponent = null;
449
+ if (selectedValue !== undefined) this.saveSetting(item, selectedValue);
450
+ this.requestRender();
451
+ });
452
+ return;
453
+ }
454
+
455
+ if (!item.values || item.values.length === 0) return;
456
+ const currentIndex = item.values.indexOf(item.rawValue);
457
+ const nextValue = item.values[(currentIndex + 1) % item.values.length] ?? item.values[0] ?? "";
458
+ this.saveSetting(item, nextValue);
459
+ }
460
+
461
+ private saveSetting(item: ConfigurationItem, nextValue: string) {
462
+ this.saving = true;
463
+ this.statusText = `Saving ${item.id}…`;
464
+ this.requestRender();
465
+
466
+ void this.onSave(item.id, nextValue)
467
+ .then((updatedValues) => {
468
+ this.updateValues(updatedValues);
469
+ this.refreshDerivedDefaults();
470
+ this.statusText = formatSaveStatus(item.id, nextValue);
471
+ })
472
+ .catch((error) => {
473
+ this.statusText = "Save failed";
474
+ this.onError(error);
475
+ })
476
+ .finally(() => {
477
+ this.saving = false;
478
+ this.requestRender();
479
+ });
480
+ }
481
+
482
+ private updateValues(values: Record<string, string>) {
483
+ for (const [id, rawValue] of Object.entries(values)) {
484
+ const item = this.items.find((candidate) => candidate.id === id);
485
+ if (!item) continue;
486
+ item.rawValue = rawValue;
487
+ item.currentValue = displayConfigurationValue(id, rawValue);
488
+ }
489
+ }
490
+
491
+ private refreshDerivedDefaults() {
492
+ if (env("MICME_WHISPER_CPP_MODEL") !== undefined) return;
493
+ const item = this.items.find((candidate) => candidate.id === "MICME_WHISPER_CPP_MODEL");
494
+ if (!item) return;
495
+ item.rawValue = getDefaultWhisperCppModelPath();
496
+ item.currentValue = displayConfigurationValue(item.id, item.rawValue);
497
+ }
498
+
499
+ private handleSearchInput(data: string) {
500
+ if (matchesKey(data, Key.slash)) {
501
+ this.searchActive = true;
502
+ this.searchQuery = "";
503
+ this.selectedSearchIndex = 0;
504
+ this.focusedPane = "settings";
505
+ return true;
506
+ }
507
+
508
+ if (this.searchActive && matchesKey(data, Key.backspace)) {
509
+ const chars = Array.from(this.searchQuery);
510
+ chars.pop();
511
+ this.searchQuery = chars.join("");
512
+ this.selectedSearchIndex = 0;
513
+ if (!this.searchQuery) this.searchActive = false;
514
+ return true;
515
+ }
516
+
517
+ if (this.searchActive && matchesKey(data, Key.escape)) {
518
+ this.searchActive = false;
519
+ this.searchQuery = "";
520
+ this.selectedSearchIndex = 0;
521
+ this.focusedPane = "categories";
522
+ return true;
523
+ }
524
+
525
+ const printable = getPrintableInput(data);
526
+ if (!printable || (!this.searchActive && printable === " ")) return false;
527
+ this.searchActive = true;
528
+ this.searchQuery += printable;
529
+ this.selectedSearchIndex = 0;
530
+ this.focusedPane = "settings";
531
+ return true;
532
+ }
533
+
534
+ private hasSearchQuery() {
535
+ return this.searchQuery.trim().length > 0;
536
+ }
537
+ }
538
+
539
+ export function buildConfigurationItems(modelCandidates: ModelCandidate[], audioDevices: AudioDeviceCandidate[], theme: MicmeTheme): ConfigurationItem[] {
540
+ const currentModel = env("MICME_WHISPER_CPP_MODEL") ?? getDefaultWhisperCppModelPath();
541
+ const currentDevice = env("MICME_AUDIO_DEVICE") ?? "0";
542
+ const audioValues = audioDevices.length > 0 ? audioDevices.map((device) => device.value) : [currentDevice];
543
+ if (!audioValues.includes(currentDevice)) audioValues.unshift(currentDevice);
544
+ const audioLabels = Object.fromEntries(audioDevices.map((device) => [device.value, device.label]));
545
+ const whisperCppBinValues = uniqueStrings([env("MICME_WHISPER_CPP_BIN") ?? "", findExecutable(["whisper-cli"]) ?? "", findExecutable(["whisper-cpp"]) ?? "", "whisper-cli", "whisper-cpp"]);
546
+ const whisperStreamBinValues = uniqueStrings([env("MICME_WHISPER_STREAM_BIN") ?? "", findExecutable(["whisper-stream"]) ?? "", "whisper-stream"]);
547
+ const audioFilter = env("MICME_AUDIO_FILTER") ?? "highpass=f=80,lowpass=f=7600";
548
+ const macosPrintableShortcut = env("MICME_PRINTABLE_SHORTCUTS") ?? (process.platform === "darwin" ? DEFAULT_MACOS_PRINTABLE_SHORTCUT : "");
549
+
550
+ return [
551
+ {
552
+ id: "MICME_AUTO_DOWNLOAD_MODEL",
553
+ categoryId: "general",
554
+ label: "Auto-download models",
555
+ description: "Download missing whisper.cpp models automatically when selected or first used.",
556
+ rawValue: env("MICME_AUTO_DOWNLOAD_MODEL") ?? "1",
557
+ currentValue: env("MICME_AUTO_DOWNLOAD_MODEL") ?? "1",
558
+ values: ["1", "0"],
559
+ displayKind: "boolean",
560
+ },
561
+ {
562
+ id: "MICME_DEFAULT_WHISPER_CPP_MODEL",
563
+ categoryId: "general",
564
+ label: "Default model name",
565
+ description: "Used when no explicit whisper.cpp model path is configured.",
566
+ rawValue: env("MICME_DEFAULT_WHISPER_CPP_MODEL") ?? DEFAULT_WHISPER_CPP_MODEL_NAME,
567
+ currentValue: env("MICME_DEFAULT_WHISPER_CPP_MODEL") ?? DEFAULT_WHISPER_CPP_MODEL_NAME,
568
+ values: [...WHISPER_CPP_MODEL_NAMES],
569
+ displayKind: "text",
570
+ },
571
+ {
572
+ id: "MICME_LANGUAGE",
573
+ categoryId: "general",
574
+ label: "Language",
575
+ description: "Use a fixed language for accuracy/speed, or auto for detection.",
576
+ rawValue: env("MICME_LANGUAGE") ?? "en",
577
+ currentValue: env("MICME_LANGUAGE") ?? "en",
578
+ values: ["en", "auto", "bs", "hr", "sr", "de", "es", "fr", "it", "pt", "nl", "pl", "tr"],
579
+ displayKind: "text",
580
+ },
581
+ {
582
+ id: "MICME_TRANSCRIPTION_MODE",
583
+ categoryId: "transcription",
584
+ label: "Transcription mode",
585
+ description: "Changing this applies the matching profile: stable clip defaults or low-latency stream settings.",
586
+ rawValue: getTranscriptionMode(),
587
+ currentValue: getTranscriptionMode(),
588
+ values: ["clip", "stream"],
589
+ displayKind: "text",
590
+ },
591
+ {
592
+ id: "MICME_WHISPER_CPP_MODEL",
593
+ categoryId: "transcription",
594
+ label: "Whisper.cpp model",
595
+ description: "Local ggml/gguf Whisper model. Use small.en/medium.en if base.en is too weak.",
596
+ rawValue: currentModel,
597
+ currentValue: displayConfigurationValue("MICME_WHISPER_CPP_MODEL", currentModel),
598
+ displayKind: "model",
599
+ emptyLabel: "not set",
600
+ submenu: (_currentValue, done) => createModelSelector(modelCandidates, theme, done),
601
+ },
602
+ {
603
+ id: "MICME_WHISPER_CPP_BIN",
604
+ categoryId: "transcription",
605
+ label: "Whisper.cpp binary",
606
+ description: "Command/path for whisper.cpp transcription. Leave unset to use whisper-cli/whisper-cpp from PATH.",
607
+ rawValue: env("MICME_WHISPER_CPP_BIN") ?? "",
608
+ currentValue: displayConfigurationValue("MICME_WHISPER_CPP_BIN", env("MICME_WHISPER_CPP_BIN") ?? ""),
609
+ values: whisperCppBinValues,
610
+ displayKind: "path",
611
+ emptyLabel: "not set",
612
+ },
613
+ {
614
+ id: "MICME_WHISPER_MODEL",
615
+ categoryId: "transcription",
616
+ label: "Python fallback model",
617
+ description: "Used only when whisper.cpp model is not configured.",
618
+ rawValue: env("MICME_WHISPER_MODEL") ?? "base.en",
619
+ currentValue: env("MICME_WHISPER_MODEL") ?? "base.en",
620
+ values: [...PYTHON_WHISPER_MODEL_NAMES],
621
+ displayKind: "text",
622
+ },
623
+ {
624
+ id: "MICME_WHISPER_STREAM_BIN",
625
+ categoryId: "streaming",
626
+ label: "Whisper-stream binary",
627
+ description: "Command/path for whisper-stream. Required when transcription mode is stream.",
628
+ rawValue: env("MICME_WHISPER_STREAM_BIN") ?? "",
629
+ currentValue: displayConfigurationValue("MICME_WHISPER_STREAM_BIN", env("MICME_WHISPER_STREAM_BIN") ?? ""),
630
+ values: whisperStreamBinValues,
631
+ displayKind: "path",
632
+ emptyLabel: "not set",
633
+ },
634
+ {
635
+ id: "MICME_STREAM_CAPTURE",
636
+ categoryId: "streaming",
637
+ label: "Stream capture device",
638
+ description: "whisper-stream/SDL capture id. Use -1 for the system default; ffmpeg device ids may not match.",
639
+ rawValue: env("MICME_STREAM_CAPTURE") ?? "-1",
640
+ currentValue: env("MICME_STREAM_CAPTURE") ?? "-1",
641
+ values: ["-1", "0", "1", "2", "3", "4", "5"],
642
+ displayKind: "number",
643
+ },
644
+ {
645
+ id: "MICME_STREAM_KEEP_CONTEXT",
646
+ categoryId: "streaming",
647
+ label: "Stream context",
648
+ description: "Keep Whisper prompt context between chunks for better fast/accented speech continuity.",
649
+ rawValue: env("MICME_STREAM_KEEP_CONTEXT") ?? "1",
650
+ currentValue: env("MICME_STREAM_KEEP_CONTEXT") ?? "1",
651
+ values: ["1", "0"],
652
+ displayKind: "boolean",
653
+ },
654
+ {
655
+ id: "MICME_STREAM_FINALIZE_WITH_CLIP",
656
+ categoryId: "streaming",
657
+ label: "Stream final pass",
658
+ description: "On stop, replace the live preview with the stable clip-mode transcript.",
659
+ rawValue: env("MICME_STREAM_FINALIZE_WITH_CLIP") ?? "1",
660
+ currentValue: env("MICME_STREAM_FINALIZE_WITH_CLIP") ?? "1",
661
+ values: ["1", "0"],
662
+ displayKind: "boolean",
663
+ },
664
+ {
665
+ id: "MICME_STREAM_VAD_THRESHOLD",
666
+ categoryId: "streaming",
667
+ label: "Stream VAD threshold",
668
+ description: "Lower is more sensitive; raise it if background noise causes hallucinations.",
669
+ rawValue: env("MICME_STREAM_VAD_THRESHOLD") ?? String(DEFAULT_STREAM_VAD_THRESHOLD),
670
+ currentValue: env("MICME_STREAM_VAD_THRESHOLD") ?? String(DEFAULT_STREAM_VAD_THRESHOLD),
671
+ values: ["0.35", "0.45", "0.60", "0.75"],
672
+ displayKind: "slider",
673
+ },
674
+ {
675
+ id: "MICME_STREAM_WORDS_PER_CHUNK",
676
+ categoryId: "streaming",
677
+ label: "Stream word chunk",
678
+ description: "Maximum stable words committed per streaming update.",
679
+ rawValue: env("MICME_STREAM_WORDS_PER_CHUNK") ?? "10",
680
+ currentValue: env("MICME_STREAM_WORDS_PER_CHUNK") ?? "10",
681
+ values: ["3", "5", "8", "10"],
682
+ displayKind: "number",
683
+ },
684
+ {
685
+ id: "MICME_AUDIO_DEVICE",
686
+ categoryId: "audio",
687
+ label: "Microphone device",
688
+ description: audioDevices.length > 0 ? "macOS avfoundation audio device id" : "Audio device id/source used by ffmpeg recorder.",
689
+ rawValue: currentDevice,
690
+ currentValue: currentDevice,
691
+ values: audioValues,
692
+ displayKind: "text",
693
+ valueLabels: audioLabels,
694
+ },
695
+ {
696
+ id: "MICME_RECORD_SAMPLE_RATE",
697
+ categoryId: "audio",
698
+ label: "Record sample rate",
699
+ description: "Raw recording sample rate. 48000 is usually best for macOS devices.",
700
+ rawValue: env("MICME_RECORD_SAMPLE_RATE") ?? String(DEFAULT_RECORD_SAMPLE_RATE),
701
+ currentValue: env("MICME_RECORD_SAMPLE_RATE") ?? String(DEFAULT_RECORD_SAMPLE_RATE),
702
+ values: ["48000", "44100", "16000"],
703
+ displayKind: "number",
704
+ },
705
+ {
706
+ id: "MICME_TRANSCRIBE_SAMPLE_RATE",
707
+ categoryId: "audio",
708
+ label: "Transcribe sample rate",
709
+ description: "Sample rate for clip.wav sent to Whisper.",
710
+ rawValue: env("MICME_TRANSCRIBE_SAMPLE_RATE") ?? String(DEFAULT_TRANSCRIBE_SAMPLE_RATE),
711
+ currentValue: env("MICME_TRANSCRIBE_SAMPLE_RATE") ?? String(DEFAULT_TRANSCRIBE_SAMPLE_RATE),
712
+ values: ["16000", "48000", "44100"],
713
+ displayKind: "number",
714
+ },
715
+ {
716
+ id: "MICME_AUDIO_FILTER",
717
+ categoryId: "audio",
718
+ label: "Audio filter",
719
+ description: "ffmpeg filter for preprocessing. Empty disables filtering while keeping conversion.",
720
+ rawValue: audioFilter,
721
+ currentValue: displayConfigurationValue("MICME_AUDIO_FILTER", audioFilter),
722
+ values: ["highpass=f=80,lowpass=f=7600", "", "highpass=f=80,lowpass=f=9000", "afftdn=nf=-25,highpass=f=80,lowpass=f=7600"],
723
+ displayKind: "text",
724
+ emptyLabel: "<empty>",
725
+ },
726
+ {
727
+ id: "MICME_METER_GAIN",
728
+ categoryId: "audio",
729
+ label: "Meter gain",
730
+ description: "Recording widget sensitivity. Increase if the bars feel too quiet.",
731
+ rawValue: env("MICME_METER_GAIN") ?? "1",
732
+ currentValue: env("MICME_METER_GAIN") ?? "1",
733
+ values: ["0.75", "1", "1.5", "2", "3"],
734
+ displayKind: "slider",
735
+ },
736
+ {
737
+ id: "MICME_PROCESS_AUDIO",
738
+ categoryId: "audio",
739
+ label: "Preprocess audio",
740
+ description: "Create a clean 16 kHz clip.wav from raw.wav before transcription.",
741
+ rawValue: env("MICME_PROCESS_AUDIO") ?? "1",
742
+ currentValue: env("MICME_PROCESS_AUDIO") ?? "1",
743
+ values: ["1", "0"],
744
+ displayKind: "boolean",
745
+ },
746
+ {
747
+ id: "MICME_VALIDATE_AUDIO",
748
+ categoryId: "audio",
749
+ label: "Silence guard",
750
+ description: "Reject near-silent clips before Whisper can hallucinate text.",
751
+ rawValue: env("MICME_VALIDATE_AUDIO") ?? "1",
752
+ currentValue: env("MICME_VALIDATE_AUDIO") ?? "1",
753
+ values: ["1", "0"],
754
+ displayKind: "boolean",
755
+ },
756
+ {
757
+ id: "MICME_KEEP_AUDIO",
758
+ categoryId: "audio",
759
+ label: "Keep audio",
760
+ description: "Keep raw.wav and clip.wav in /tmp after successful transcription for debugging.",
761
+ rawValue: env("MICME_KEEP_AUDIO") ?? "0",
762
+ currentValue: env("MICME_KEEP_AUDIO") ?? "0",
763
+ values: ["0", "1"],
764
+ displayKind: "boolean",
765
+ },
766
+ {
767
+ id: "MICME_SHORTCUT",
768
+ categoryId: "shortcuts",
769
+ label: "Terminal shortcut",
770
+ description: "Shortcut when your terminal sends real Alt/Ctrl keys. Requires /reload or restart after changing.",
771
+ rawValue: env("MICME_SHORTCUT") ?? DEFAULT_SHORTCUT,
772
+ currentValue: env("MICME_SHORTCUT") ?? DEFAULT_SHORTCUT,
773
+ values: ["alt+m", "ctrl+shift+m", "ctrl+space", "f8", "f9"],
774
+ displayKind: "text",
775
+ },
776
+ {
777
+ id: "MICME_PRINTABLE_SHORTCUTS",
778
+ categoryId: "shortcuts",
779
+ label: "macOS printable shortcut",
780
+ description: "Toggle-only fallback for terminals where Option+M inserts a character instead of sending Alt+M. Use /reload after changing.",
781
+ rawValue: macosPrintableShortcut,
782
+ currentValue: displayConfigurationValue("MICME_PRINTABLE_SHORTCUTS", macosPrintableShortcut),
783
+ values: [DEFAULT_MACOS_PRINTABLE_SHORTCUT, "µ", ""],
784
+ displayKind: "text",
785
+ emptyLabel: "not set",
786
+ },
787
+ {
788
+ id: "MICME_STREAM_DIAGNOSTICS",
789
+ categoryId: "diagnostics",
790
+ label: "Stream diagnostics",
791
+ description: "Show timing notifications for first whisper-stream output and first editor preview.",
792
+ rawValue: env("MICME_STREAM_DIAGNOSTICS") ?? "0",
793
+ currentValue: env("MICME_STREAM_DIAGNOSTICS") ?? "0",
794
+ values: ["0", "1"],
795
+ displayKind: "boolean",
796
+ },
797
+ ];
798
+ }
799
+
800
+ export function createModelSelector(candidates: ModelCandidate[], theme: MicmeTheme, done: (selectedValue?: string) => void): Component {
801
+ const items: SelectItem[] = candidates.map((candidate) => ({
802
+ value: candidate.value,
803
+ label: candidate.installed ? `✓ ${candidate.label}` : `○ ${candidate.label}`,
804
+ description: candidate.description,
805
+ }));
806
+
807
+ const container = new Container();
808
+ container.addChild(new DynamicBorder((s: string) => theme.fg("accent", s)));
809
+ container.addChild(new Text(theme.fg("accent", theme.bold("Select whisper.cpp model")), 1, 0));
810
+ container.addChild(new Text(theme.fg("dim", "✓ found locally • ○ missing; selecting downloads automatically when enabled"), 1, 0));
811
+
812
+ const list = new SelectList(items, Math.min(items.length, 16), {
813
+ selectedPrefix: (text) => theme.fg("accent", text),
814
+ selectedText: (text) => theme.fg("accent", text),
815
+ description: (text) => theme.fg("muted", text),
816
+ scrollInfo: (text) => theme.fg("dim", text),
817
+ noMatch: (text) => theme.fg("warning", text),
818
+ });
819
+ list.onSelect = (item) => done(item.value);
820
+ list.onCancel = () => done(undefined);
821
+ container.addChild(list);
822
+ container.addChild(new Text(theme.fg("dim", "↑↓ navigate • type to search • enter select • esc back"), 1, 0));
823
+ container.addChild(new DynamicBorder((s: string) => theme.fg("accent", s)));
824
+
825
+ return {
826
+ render(width: number) {
827
+ return container.render(width);
828
+ },
829
+ invalidate() {
830
+ container.invalidate();
831
+ },
832
+ handleInput(data: string) {
833
+ list.handleInput(data);
834
+ },
835
+ };
836
+ }
837
+
838
+ export async function saveConfigurationValue(ctx: ExtensionContext, id: string, value: string): Promise<Record<string, string>> {
839
+ if (!id.startsWith("MICME_")) return {};
840
+
841
+ const valuesToWrite = id === "MICME_TRANSCRIPTION_MODE" ? getTranscriptionModeProfile(value === "stream" ? "stream" : "clip") : { [id]: value };
842
+ if (id === "MICME_WHISPER_CPP_MODEL" && value) {
843
+ await ensureWhisperCppModel(expandConfigPath(value), ctx);
844
+ }
845
+
846
+ for (const [key, nextValue] of Object.entries(valuesToWrite)) {
847
+ await writeDotEnvValue(ctx.cwd, key, nextValue);
848
+ }
849
+
850
+ reloadDotEnv(ctx.cwd);
851
+ const overriddenKeys = Object.keys(valuesToWrite).filter((key) => process.env[key] !== undefined);
852
+ if (id === "MICME_TRANSCRIPTION_MODE") {
853
+ const mode = valuesToWrite.MICME_TRANSCRIPTION_MODE === "stream" ? "stream" : "clip";
854
+ const detail = mode === "stream" ? "low-latency stream profile" : "stable clip profile";
855
+ const overrideSuffix = overriddenKeys.length ? `; shell env still overrides ${overriddenKeys.join(", ")}` : "";
856
+ ctx.ui.notify(`Saved ${mode} mode and applied ${detail}${overrideSuffix}.`, overriddenKeys.length ? "warning" : "info");
857
+ } else {
858
+ const source = overriddenKeys.includes(id) ? "shell env still overrides .env" : ".env";
859
+ ctx.ui.notify(`Saved ${id}=${displayConfigurationValue(id, value)} (${source})`, overriddenKeys.includes(id) ? "warning" : "info");
860
+ }
861
+
862
+ const effectiveValues: Record<string, string> = {};
863
+ for (const key of Object.keys(valuesToWrite)) effectiveValues[key] = env(key) ?? "";
864
+ return effectiveValues;
865
+ }
866
+
867
+ export function displayConfigurationValue(id: string, value: string) {
868
+ if (id === "MICME_WHISPER_CPP_MODEL") return value ? basename(value) : "not set";
869
+ if (id === "MICME_AUDIO_FILTER") return value || "<empty>";
870
+ return value || "not set";
871
+ }
872
+
873
+ export function uniqueStrings(values: string[]) {
874
+ const seen = new Set<string>();
875
+ const output: string[] = [];
876
+ for (const value of values) {
877
+ const normalized = value.trim();
878
+ if (seen.has(normalized)) continue;
879
+ seen.add(normalized);
880
+ output.push(normalized);
881
+ }
882
+ return output.length > 0 ? output : [""];
883
+ }
884
+
885
+ function formatSaveStatus(id: string, value: string) {
886
+ const writtenKeys = id === "MICME_TRANSCRIPTION_MODE" ? Object.keys(getTranscriptionModeProfile(value === "stream" ? "stream" : "clip")) : [id];
887
+ const overriddenKeys = writtenKeys.filter((key) => process.env[key] !== undefined);
888
+ if (id === "MICME_TRANSCRIPTION_MODE") {
889
+ const mode = value === "stream" ? "stream" : "clip";
890
+ const detail = mode === "stream" ? "low-latency stream profile" : "stable clip profile";
891
+ const overrideSuffix = overriddenKeys.length ? ` • shell env still overrides ${overriddenKeys.join(", ")}` : "";
892
+ return `Saved MICME_TRANSCRIPTION_MODE=${mode} and applied ${detail}${overrideSuffix}`;
893
+ }
894
+
895
+ const overrideSuffix = overriddenKeys.includes(id) ? `, but shell env still overrides ${id}` : "";
896
+ const reloadSuffix = id === "MICME_SHORTCUT" ? " • /reload required" : id === "MICME_PRINTABLE_SHORTCUTS" ? " • /reload recommended" : "";
897
+ return `Saved ${id}=${displayConfigurationValue(id, value)} (.env${overrideSuffix})${reloadSuffix}`;
898
+ }
899
+
900
+ function fitAnsi(text: string, width: number, ellipsis = "…") {
901
+ if (width <= 0) return "";
902
+ return truncateToWidth(text, width, ellipsis);
903
+ }
904
+
905
+ function fitPath(text: string, width: number) {
906
+ if (width <= 0) return "";
907
+ if (visibleWidth(text) <= width) return text;
908
+ if (width <= 1) return fitAnsi(text, width);
909
+ const tail = Array.from(text).slice(-(width - 1)).join("");
910
+ return `…${tail}`;
911
+ }
912
+
913
+ function padRightAnsi(text: string, width: number) {
914
+ const fitted = fitAnsi(text, width);
915
+ return `${fitted}${" ".repeat(Math.max(0, width - visibleWidth(fitted)))}`;
916
+ }
917
+
918
+ function padLeftAnsi(text: string, width: number) {
919
+ const fitted = fitAnsi(text, width);
920
+ return `${" ".repeat(Math.max(0, width - visibleWidth(fitted)))}${fitted}`;
921
+ }
922
+
923
+ function getVisibleRange(selectedIndex: number, total: number, maxVisible: number): [number, number] {
924
+ if (total <= maxVisible) return [0, total];
925
+ const start = Math.max(0, Math.min(selectedIndex - Math.floor(maxVisible / 2), total - maxVisible));
926
+ return [start, Math.min(total, start + maxVisible)];
927
+ }
928
+
929
+ function wrapIndex(index: number, length: number) {
930
+ if (length <= 0) return 0;
931
+ return ((index % length) + length) % length;
932
+ }
933
+
934
+ function clamp(value: number, min: number, max: number) {
935
+ return Math.min(max, Math.max(min, value));
936
+ }
937
+
938
+ function isTruthyConfigValue(value: string) {
939
+ return /^(1|true|yes|on)$/i.test(value);
940
+ }
941
+
942
+ function getPrintableInput(data: string) {
943
+ if (!data || data.includes("\x1b")) return "";
944
+ if (matchesKey(data, Key.space)) return " ";
945
+ if (matchesKey(data, Key.enter) || matchesKey(data, Key.tab) || matchesKey(data, Key.backspace) || matchesKey(data, Key.delete)) return "";
946
+ if (/^[^\x00-\x1F\x7F]+$/u.test(data)) return data;
947
+ return "";
948
+ }