@senad-d/micme 0.2.0 → 0.3.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.
package/src/settings.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  import { DynamicBorder, type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import {
3
3
  Container,
4
+ decodeKittyPrintable,
4
5
  fuzzyFilter,
5
6
  Key,
6
7
  matchesKey,
8
+ parseKey,
7
9
  type Component,
8
10
  type SelectItem,
9
11
  SelectList,
@@ -14,32 +16,29 @@ import {
14
16
  } from "@earendil-works/pi-tui";
15
17
  import { basename } from "node:path";
16
18
  import {
17
- DEFAULT_MACOS_PRINTABLE_SHORTCUT,
18
19
  DEFAULT_RECORD_SAMPLE_RATE,
19
- DEFAULT_SHORTCUT,
20
20
  DEFAULT_STREAM_VAD_THRESHOLD,
21
21
  DEFAULT_STREAM_FLUSH_MS,
22
22
  DEFAULT_TRANSCRIBE_SAMPLE_RATE,
23
- DEFAULT_WHISPER_CPP_MODEL_NAME,
24
- PYTHON_WHISPER_MODEL_NAMES,
25
- WHISPER_CPP_MODEL_NAMES,
26
23
  } from "./constants.ts";
27
24
  import {
28
25
  env,
29
26
  expandConfigPath,
27
+ getShortcutSettingValue,
30
28
  getTranscriptionMode,
31
29
  getTranscriptionModeProfile,
32
30
  reloadMicmeConfig,
33
31
  writeMicmeConfigValues,
34
32
  } from "./config.ts";
35
33
  import { discoverAudioDevices } from "./audio.ts";
36
- import { discoverWhisperCppModels, ensureWhisperCppModel, getDefaultWhisperCppModelPath } from "./models.ts";
34
+ import { formatBackendLabel, resolveTranscriptionPlan } from "./backends.ts";
35
+ import { discoverPythonWhisperModels, discoverWhisperCppModels, ensureWhisperCppModel, resolveWhisperCppModel } from "./models.ts";
37
36
  import { findExecutable } from "./processes.ts";
38
- import type { AudioDeviceCandidate, ModelCandidate } from "./types.ts";
37
+ import type { AudioDeviceCandidate, ModelCandidate, ResolvedTranscriptionPlan } from "./types.ts";
39
38
 
40
39
  type MicmeTheme = ExtensionContext["ui"]["theme"];
41
40
 
42
- type ConfigurationCategoryId = "general" | "transcription" | "streaming" | "audio" | "shortcuts" | "diagnostics";
41
+ type ConfigurationCategoryId = "general" | "transcription" | "streaming" | "audio";
43
42
  type FocusedPane = "categories" | "settings";
44
43
  type DisplayKind = "boolean" | "number" | "path" | "slider" | "text" | "model";
45
44
 
@@ -55,6 +54,7 @@ interface ConfigurationItem extends SettingItem {
55
54
  displayKind?: DisplayKind;
56
55
  emptyLabel?: string;
57
56
  valueLabels?: Record<string, string>;
57
+ visibleWhen?: (plan: ResolvedTranscriptionPlan) => boolean;
58
58
  }
59
59
 
60
60
  const CONFIGURATION_CATEGORIES: ConfigurationCategory[] = [
@@ -62,8 +62,6 @@ const CONFIGURATION_CATEGORIES: ConfigurationCategory[] = [
62
62
  { id: "transcription", label: "Transcription", description: "Backend model, mode, and transcription fallback settings." },
63
63
  { id: "streaming", label: "Streaming", description: "Low-latency live transcription behavior." },
64
64
  { id: "audio", label: "Audio", description: "Recording, preprocessing, and metering settings." },
65
- { id: "shortcuts", label: "Shortcuts", description: "Terminal and printable-character shortcut bindings." },
66
- { id: "diagnostics", label: "Diagnostics", description: "Debug and timing output." },
67
65
  ];
68
66
 
69
67
  const TWO_PANE_MIN_WIDTH = 72;
@@ -81,9 +79,10 @@ export async function showConfiguration(ctx: ExtensionContext) {
81
79
  }
82
80
  const audioDevices = await discoverAudioDevices();
83
81
  const modelCandidates = discoverWhisperCppModels(ctx.cwd);
82
+ const pythonModelCandidates = await discoverPythonWhisperModels();
84
83
 
85
84
  await ctx.ui.custom<void>((tui, theme, _keybindings, done) => {
86
- const items = buildConfigurationItems(modelCandidates, audioDevices, theme);
85
+ const items = buildConfigurationItems(modelCandidates, pythonModelCandidates, audioDevices, theme);
87
86
  return new ConfigurationScreen({
88
87
  configPath: configState.path,
89
88
  items,
@@ -111,6 +110,8 @@ class ConfigurationScreen implements Component {
111
110
  private searchQuery = "";
112
111
  private selectedSearchIndex = 0;
113
112
  private submenuComponent: Component | null = null;
113
+ private editingShortcutItem: ConfigurationItem | null = null;
114
+ private pendingShortcutValue = "";
114
115
  private saving = false;
115
116
  private statusText = "";
116
117
 
@@ -134,6 +135,7 @@ class ConfigurationScreen implements Component {
134
135
  }
135
136
 
136
137
  render(width: number): string[] {
138
+ this.refreshDerivedItems();
137
139
  if (this.submenuComponent) return this.submenuComponent.render(width);
138
140
  if (width < TWO_PANE_MIN_WIDTH) return this.renderNarrow(width);
139
141
  return this.renderTwoPane(width);
@@ -149,6 +151,11 @@ class ConfigurationScreen implements Component {
149
151
  return;
150
152
  }
151
153
 
154
+ if (this.editingShortcutItem) {
155
+ this.handleShortcutCaptureInput(data);
156
+ return;
157
+ }
158
+
152
159
  if (matchesKey(data, Key.ctrl("c")) || data === "q" || data === "Q") {
153
160
  this.onDone();
154
161
  return;
@@ -349,14 +356,19 @@ class ConfigurationScreen implements Component {
349
356
  const selected = this.getSelectedSetting();
350
357
  const category = this.currentCategory();
351
358
  const selection = this.getSelectionText();
359
+ if (this.editingShortcutItem) {
360
+ const hint = this.pendingShortcutValue ? `Captured ${this.pendingShortcutValue} • Enter save • Esc cancel` : "Press desired key or key combination • Enter save • Esc cancel";
361
+ return `${selection} • ${this.statusText || hint}`;
362
+ }
352
363
  const search = this.searchActive ? `Search: ${this.searchQuery || "type to filter all settings"}` : "";
353
- const lead = this.statusText || search || "↑↓ move • Tab pane • Enter edit • / search • Esc back • q quit";
364
+ const lead = this.statusText || search;
354
365
  const description = selected?.description ?? category.description;
355
- return `${lead} • ${selection} • ${description}`;
366
+ return lead ? `${lead} • ${selection} • ${description}` : `${selection} • ${description}`;
356
367
  }
357
368
 
358
369
  private formatValue(item: ConfigurationItem, width: number) {
359
370
  if (width <= 0) return "";
371
+ if (this.editingShortcutItem?.id === item.id) return this.pendingShortcutValue ? this.theme.fg("accent", fitAnsi(this.pendingShortcutValue, width)) : "";
360
372
  const raw = item.rawValue;
361
373
  if (!raw) return this.theme.fg("dim", fitAnsi(item.emptyLabel ?? displayConfigurationValue(item.id, raw), width));
362
374
 
@@ -409,12 +421,22 @@ class ConfigurationScreen implements Component {
409
421
  }
410
422
 
411
423
  private getCategoryItems(categoryId = this.currentCategory().id) {
412
- return this.items.filter((item) => item.categoryId === categoryId);
424
+ const plan = this.getCurrentPlan();
425
+ return this.items.filter((item) => item.categoryId === categoryId && this.isItemVisible(item, plan));
426
+ }
427
+
428
+ private getVisibleItems() {
429
+ const plan = this.getCurrentPlan();
430
+ return this.items.filter((item) => this.isItemVisible(item, plan));
431
+ }
432
+
433
+ private isItemVisible(item: ConfigurationItem, plan: ResolvedTranscriptionPlan) {
434
+ return item.visibleWhen ? item.visibleWhen(plan) : true;
413
435
  }
414
436
 
415
437
  private getDisplaySettings() {
416
438
  if (!this.hasSearchQuery()) return this.getCategoryItems();
417
- return fuzzyFilter(this.items, this.searchQuery, (item) => `${item.label} ${item.id} ${item.description ?? ""} ${this.getCategory(item.categoryId).label}`);
439
+ return fuzzyFilter(this.getVisibleItems(), this.searchQuery, (item) => `${item.label} ${item.id} ${item.description ?? ""} ${this.getCategory(item.categoryId).label}`);
418
440
  }
419
441
 
420
442
  private getSelectedSetting() {
@@ -456,6 +478,11 @@ class ConfigurationScreen implements Component {
456
478
  const item = displayItems[this.getSelectedSettingIndex(displayItems.length)];
457
479
  if (!item) return;
458
480
 
481
+ if (item.id === "MICME_SHORTCUT") {
482
+ this.startShortcutCapture(item);
483
+ return;
484
+ }
485
+
459
486
  if (item.submenu) {
460
487
  this.submenuComponent = item.submenu(item.rawValue, (selectedValue?: string) => {
461
488
  this.submenuComponent = null;
@@ -471,6 +498,50 @@ class ConfigurationScreen implements Component {
471
498
  this.saveSetting(item, nextValue);
472
499
  }
473
500
 
501
+ private startShortcutCapture(item: ConfigurationItem) {
502
+ this.editingShortcutItem = item;
503
+ this.pendingShortcutValue = "";
504
+ this.statusText = "";
505
+ this.requestRender();
506
+ }
507
+
508
+ private handleShortcutCaptureInput(data: string) {
509
+ const item = this.editingShortcutItem;
510
+ if (!item) return;
511
+
512
+ if (matchesKey(data, Key.escape)) {
513
+ this.editingShortcutItem = null;
514
+ this.pendingShortcutValue = "";
515
+ this.statusText = "";
516
+ this.requestRender();
517
+ return;
518
+ }
519
+
520
+ if (matchesKey(data, Key.enter)) {
521
+ if (!this.pendingShortcutValue) {
522
+ this.statusText = "Press a shortcut before confirming";
523
+ this.requestRender();
524
+ return;
525
+ }
526
+ const nextValue = this.pendingShortcutValue;
527
+ this.editingShortcutItem = null;
528
+ this.pendingShortcutValue = "";
529
+ this.saveSetting(item, nextValue);
530
+ return;
531
+ }
532
+
533
+ const captured = getShortcutInput(data);
534
+ if (!captured) {
535
+ this.statusText = "Shortcut input not recognized";
536
+ this.requestRender();
537
+ return;
538
+ }
539
+
540
+ this.pendingShortcutValue = captured;
541
+ this.statusText = "";
542
+ this.requestRender();
543
+ }
544
+
474
545
  private saveSetting(item: ConfigurationItem, nextValue: string) {
475
546
  this.saving = true;
476
547
  this.statusText = `Saving ${item.id}…`;
@@ -479,7 +550,8 @@ class ConfigurationScreen implements Component {
479
550
  void this.onSave(item.id, nextValue)
480
551
  .then((updatedValues) => {
481
552
  this.updateValues(updatedValues);
482
- this.refreshDerivedDefaults();
553
+ this.refreshDerivedItems();
554
+ this.clampSelections();
483
555
  this.statusText = formatSaveStatus(item.id, nextValue);
484
556
  })
485
557
  .catch((error) => {
@@ -501,14 +573,41 @@ class ConfigurationScreen implements Component {
501
573
  }
502
574
  }
503
575
 
504
- private refreshDerivedDefaults() {
505
- if (env("MICME_WHISPER_CPP_MODEL") !== undefined) return;
506
- const item = this.items.find((candidate) => candidate.id === "MICME_WHISPER_CPP_MODEL");
507
- if (!item) return;
508
- item.rawValue = getDefaultWhisperCppModelPath();
509
- item.currentValue = displayConfigurationValue(item.id, item.rawValue);
576
+ private refreshDerivedItems() {
577
+ const plan = this.getCurrentPlan();
578
+ const backend = this.items.find((candidate) => candidate.id === "MICME_TRANSCRIBE_BACKEND");
579
+ if (backend && !["whisper.cpp", "python"].includes(backend.rawValue)) {
580
+ backend.rawValue = getUiBackendValue(plan);
581
+ backend.currentValue = displayConfigurationValue(backend.id, backend.rawValue);
582
+ }
583
+
584
+ const model = this.items.find((candidate) => candidate.id === "MICME_WHISPER_CPP_MODEL");
585
+ if (model) {
586
+ model.rawValue = getCurrentWhisperCppModelValue();
587
+ model.currentValue = displayConfigurationValue(model.id, model.rawValue);
588
+ }
589
+
590
+ const mode = this.items.find((candidate) => candidate.id === "MICME_TRANSCRIPTION_MODE");
591
+ if (mode) {
592
+ const base = "Changing this applies the matching profile: stable clip defaults or low-latency stream settings.";
593
+ mode.description = plan.requestedBackend === "python" || plan.requestedBackend === "custom"
594
+ ? `${base} Streaming mode requires whisper.cpp. Switch to clip mode or choose auto/whisper.cpp.`
595
+ : base;
596
+ }
597
+ }
598
+
599
+ private getCurrentPlan() {
600
+ return resolveTranscriptionPlan({ transcriptionMode: getTranscriptionMode() });
510
601
  }
511
602
 
603
+ private clampSelections() {
604
+ for (const category of CONFIGURATION_CATEGORIES) {
605
+ const count = this.getCategoryItems(category.id).length;
606
+ this.selectedByCategory.set(category.id, clamp(this.selectedByCategory.get(category.id) ?? 0, 0, Math.max(0, count - 1)));
607
+ }
608
+ }
609
+
610
+
512
611
  private handleSearchInput(data: string) {
513
612
  if (matchesKey(data, Key.slash)) {
514
613
  this.searchActive = true;
@@ -549,8 +648,16 @@ class ConfigurationScreen implements Component {
549
648
  }
550
649
  }
551
650
 
552
- export function buildConfigurationItems(modelCandidates: ModelCandidate[], audioDevices: AudioDeviceCandidate[], theme: MicmeTheme): ConfigurationItem[] {
553
- const currentModel = env("MICME_WHISPER_CPP_MODEL") ?? getDefaultWhisperCppModelPath();
651
+ export function buildConfigurationItems(
652
+ modelCandidates: ModelCandidate[],
653
+ pythonModelCandidatesOrAudioDevices: ModelCandidate[] | AudioDeviceCandidate[],
654
+ audioDevicesOrTheme: AudioDeviceCandidate[] | MicmeTheme,
655
+ maybeTheme?: MicmeTheme,
656
+ ): ConfigurationItem[] {
657
+ const pythonModelCandidates = maybeTheme ? (pythonModelCandidatesOrAudioDevices as ModelCandidate[]) : [];
658
+ const audioDevices = maybeTheme ? (audioDevicesOrTheme as AudioDeviceCandidate[]) : (pythonModelCandidatesOrAudioDevices as AudioDeviceCandidate[]);
659
+ const theme = maybeTheme ?? (audioDevicesOrTheme as MicmeTheme);
660
+ const currentModelPath = getCurrentWhisperCppModelValue();
554
661
  const currentDevice = env("MICME_AUDIO_DEVICE") ?? "0";
555
662
  const audioValues = audioDevices.length > 0 ? audioDevices.map((device) => device.value) : [currentDevice];
556
663
  if (!audioValues.includes(currentDevice)) audioValues.unshift(currentDevice);
@@ -558,7 +665,16 @@ export function buildConfigurationItems(modelCandidates: ModelCandidate[], audio
558
665
  const whisperCppBinValues = uniqueStrings([env("MICME_WHISPER_CPP_BIN") ?? "", findExecutable(["whisper-cli"]) ?? "", findExecutable(["whisper-cpp"]) ?? "", "whisper-cli", "whisper-cpp"]);
559
666
  const whisperStreamBinValues = uniqueStrings([env("MICME_WHISPER_STREAM_BIN") ?? "", findExecutable(["whisper-stream"]) ?? "", "whisper-stream"]);
560
667
  const audioFilter = env("MICME_AUDIO_FILTER") ?? "highpass=f=80,lowpass=f=7600";
561
- const macosPrintableShortcut = env("MICME_PRINTABLE_SHORTCUTS") ?? (process.platform === "darwin" ? DEFAULT_MACOS_PRINTABLE_SHORTCUT : "");
668
+ const shortcut = getShortcutSettingValue();
669
+ const plan = resolveTranscriptionPlan({ transcriptionMode: getTranscriptionMode() });
670
+ const backendValues = ["whisper.cpp", "python"] as const;
671
+ const backendLabels = Object.fromEntries(backendValues.map((value) => [value, formatBackendLabel(value)]));
672
+ const uiBackendValue = getUiBackendValue(plan);
673
+ const whisperCppVisible = (candidate: ResolvedTranscriptionPlan) => getUiBackendValue(candidate) === "whisper.cpp";
674
+ const pythonVisible = (candidate: ResolvedTranscriptionPlan) => getUiBackendValue(candidate) === "python";
675
+ const pythonModelValues = uniqueStrings([env("MICME_WHISPER_MODEL") ?? "base.en", ...pythonModelCandidates.map((candidate) => candidate.value)]);
676
+ const pythonModelLabels = Object.fromEntries(pythonModelCandidates.map((candidate) => [candidate.value, candidate.label]));
677
+ const modelPathCandidates = [{ label: "Use default model", value: "", description: "Clear explicit path override and use Micme's default whisper.cpp model path.", installed: true, kind: "path" as const }, ...modelCandidates];
562
678
 
563
679
  return [
564
680
  {
@@ -571,16 +687,6 @@ export function buildConfigurationItems(modelCandidates: ModelCandidate[], audio
571
687
  values: ["1", "0"],
572
688
  displayKind: "boolean",
573
689
  },
574
- {
575
- id: "MICME_DEFAULT_WHISPER_CPP_MODEL",
576
- categoryId: "general",
577
- label: "Default model name",
578
- description: "Used when no explicit whisper.cpp model path is configured.",
579
- rawValue: env("MICME_DEFAULT_WHISPER_CPP_MODEL") ?? DEFAULT_WHISPER_CPP_MODEL_NAME,
580
- currentValue: env("MICME_DEFAULT_WHISPER_CPP_MODEL") ?? DEFAULT_WHISPER_CPP_MODEL_NAME,
581
- values: [...WHISPER_CPP_MODEL_NAMES],
582
- displayKind: "text",
583
- },
584
690
  {
585
691
  id: "MICME_LANGUAGE",
586
692
  categoryId: "general",
@@ -601,38 +707,54 @@ export function buildConfigurationItems(modelCandidates: ModelCandidate[], audio
601
707
  values: ["clip", "stream"],
602
708
  displayKind: "text",
603
709
  },
710
+ {
711
+ id: "MICME_TRANSCRIBE_BACKEND",
712
+ categoryId: "transcription",
713
+ label: "Backend",
714
+ description: "Choose the transcription backend.",
715
+ rawValue: uiBackendValue,
716
+ currentValue: uiBackendValue,
717
+ values: [...backendValues],
718
+ valueLabels: backendLabels,
719
+ displayKind: "text",
720
+ },
604
721
  {
605
722
  id: "MICME_WHISPER_CPP_MODEL",
606
723
  categoryId: "transcription",
607
- label: "Whisper.cpp model",
608
- description: "Local ggml/gguf Whisper model. Use small.en/medium.en if base.en is too weak.",
609
- rawValue: currentModel,
610
- currentValue: displayConfigurationValue("MICME_WHISPER_CPP_MODEL", currentModel),
724
+ label: "Model",
725
+ description: "Whisper.cpp ggml/gguf model file.",
726
+ rawValue: currentModelPath,
727
+ currentValue: displayConfigurationValue("MICME_WHISPER_CPP_MODEL", currentModelPath),
611
728
  displayKind: "model",
612
729
  emptyLabel: "not set",
613
- submenu: (_currentValue, done) => createModelSelector(modelCandidates, theme, done),
730
+ submenu: (_currentValue, done) => createModelSelector(modelPathCandidates, theme, done),
731
+ visibleWhen: whisperCppVisible,
614
732
  },
615
733
  {
616
734
  id: "MICME_WHISPER_CPP_BIN",
617
735
  categoryId: "transcription",
618
- label: "Whisper.cpp binary",
736
+ label: "Binary",
619
737
  description: "Command/path for whisper.cpp transcription. Leave unset to use whisper-cli/whisper-cpp from PATH.",
620
738
  rawValue: env("MICME_WHISPER_CPP_BIN") ?? "",
621
739
  currentValue: displayConfigurationValue("MICME_WHISPER_CPP_BIN", env("MICME_WHISPER_CPP_BIN") ?? ""),
622
740
  values: whisperCppBinValues,
623
741
  displayKind: "path",
624
742
  emptyLabel: "not set",
743
+ visibleWhen: whisperCppVisible,
625
744
  },
626
745
  {
627
746
  id: "MICME_WHISPER_MODEL",
628
747
  categoryId: "transcription",
629
- label: "Python fallback model",
630
- description: "Used only when whisper.cpp model is not configured.",
748
+ label: "Model",
749
+ description: "Model name passed to the OpenAI Whisper Python CLI.",
631
750
  rawValue: env("MICME_WHISPER_MODEL") ?? "base.en",
632
751
  currentValue: env("MICME_WHISPER_MODEL") ?? "base.en",
633
- values: [...PYTHON_WHISPER_MODEL_NAMES],
752
+ values: pythonModelValues,
753
+ valueLabels: pythonModelLabels,
634
754
  displayKind: "text",
755
+ visibleWhen: pythonVisible,
635
756
  },
757
+
636
758
  {
637
759
  id: "MICME_WHISPER_STREAM_BIN",
638
760
  categoryId: "streaming",
@@ -718,12 +840,22 @@ export function buildConfigurationItems(modelCandidates: ModelCandidate[], audio
718
840
  {
719
841
  id: "MICME_RECORD_SAMPLE_RATE",
720
842
  categoryId: "audio",
721
- label: "Record sample rate",
722
- description: "Raw recording sample rate. 48000 is usually best for macOS devices.",
843
+ label: "Sample rate override",
844
+ description: "Advanced. Leave auto so ffmpeg uses the selected input's native sample rate.",
723
845
  rawValue: env("MICME_RECORD_SAMPLE_RATE") ?? String(DEFAULT_RECORD_SAMPLE_RATE),
724
846
  currentValue: env("MICME_RECORD_SAMPLE_RATE") ?? String(DEFAULT_RECORD_SAMPLE_RATE),
725
- values: ["48000", "44100", "16000"],
726
- displayKind: "number",
847
+ values: ["auto", "48000", "44100", "16000", "96000"],
848
+ displayKind: "text",
849
+ },
850
+ {
851
+ id: "MICME_RECORD_SYNC",
852
+ categoryId: "audio",
853
+ label: "Record timing sync",
854
+ description: "Automatically preserve wall-clock recording duration from ffmpeg timestamps. Keep on unless debugging recorder timing.",
855
+ rawValue: env("MICME_RECORD_SYNC") ?? "1",
856
+ currentValue: env("MICME_RECORD_SYNC") ?? "1",
857
+ values: ["1", "0"],
858
+ displayKind: "boolean",
727
859
  },
728
860
  {
729
861
  id: "MICME_TRANSCRIBE_SAMPLE_RATE",
@@ -735,6 +867,30 @@ export function buildConfigurationItems(modelCandidates: ModelCandidate[], audio
735
867
  values: ["16000", "48000", "44100"],
736
868
  displayKind: "number",
737
869
  },
870
+ {
871
+ id: "MICME_RECORD_METER",
872
+ categoryId: "audio",
873
+ label: "Live meter pipe",
874
+ description: "Stream a second PCM branch from ffmpeg for the waveform meter. Leave off if recordings crackle or sound shortened.",
875
+ rawValue: env("MICME_RECORD_METER") ?? "0",
876
+ currentValue: env("MICME_RECORD_METER") ?? "0",
877
+ values: ["0", "1"],
878
+ displayKind: "boolean",
879
+ },
880
+ ...(process.platform === "darwin"
881
+ ? [
882
+ {
883
+ id: "MICME_AVFOUNDATION_DROP_LATE_FRAMES",
884
+ categoryId: "audio" as const,
885
+ label: "AVF drop late frames",
886
+ description: "macOS only. Keep off to preserve audio timing when devices or virtual routes lag.",
887
+ rawValue: env("MICME_AVFOUNDATION_DROP_LATE_FRAMES") ?? "0",
888
+ currentValue: env("MICME_AVFOUNDATION_DROP_LATE_FRAMES") ?? "0",
889
+ values: ["0", "1"],
890
+ displayKind: "boolean" as const,
891
+ },
892
+ ]
893
+ : []),
738
894
  {
739
895
  id: "MICME_AUDIO_FILTER",
740
896
  categoryId: "audio",
@@ -780,7 +936,7 @@ export function buildConfigurationItems(modelCandidates: ModelCandidate[], audio
780
936
  id: "MICME_KEEP_AUDIO",
781
937
  categoryId: "audio",
782
938
  label: "Keep audio",
783
- description: "Keep raw.wav and clip.wav in /tmp after successful transcription for debugging.",
939
+ description: "Keep raw.wav and clip.wav under ./micme-rec/rec-###/ after successful transcription for debugging.",
784
940
  rawValue: env("MICME_KEEP_AUDIO") ?? "0",
785
941
  currentValue: env("MICME_KEEP_AUDIO") ?? "0",
786
942
  values: ["0", "1"],
@@ -788,28 +944,17 @@ export function buildConfigurationItems(modelCandidates: ModelCandidate[], audio
788
944
  },
789
945
  {
790
946
  id: "MICME_SHORTCUT",
791
- categoryId: "shortcuts",
792
- label: "Terminal shortcut",
793
- description: "Shortcut when your terminal sends real Alt/Ctrl keys. Requires /reload or restart after changing.",
794
- rawValue: env("MICME_SHORTCUT") ?? DEFAULT_SHORTCUT,
795
- currentValue: env("MICME_SHORTCUT") ?? DEFAULT_SHORTCUT,
796
- values: ["alt+m", "ctrl+shift+m", "ctrl+space", "f8", "f9"],
797
- displayKind: "text",
798
- },
799
- {
800
- id: "MICME_PRINTABLE_SHORTCUTS",
801
- categoryId: "shortcuts",
802
- label: "macOS printable shortcut",
803
- description: "Toggle-only fallback for terminals where Option+M inserts a character instead of sending Alt+M. Use /reload after changing.",
804
- rawValue: macosPrintableShortcut,
805
- currentValue: displayConfigurationValue("MICME_PRINTABLE_SHORTCUTS", macosPrintableShortcut),
806
- values: [DEFAULT_MACOS_PRINTABLE_SHORTCUT, "µ", ""],
947
+ categoryId: "general",
948
+ label: "Shortcut",
949
+ description: "Press Enter, then press the desired key or key combination, and press Enter again to confirm.",
950
+ rawValue: shortcut,
951
+ currentValue: displayConfigurationValue("MICME_SHORTCUT", shortcut),
807
952
  displayKind: "text",
808
953
  emptyLabel: "not set",
809
954
  },
810
955
  {
811
956
  id: "MICME_STREAM_DIAGNOSTICS",
812
- categoryId: "diagnostics",
957
+ categoryId: "general",
813
958
  label: "Stream diagnostics",
814
959
  description: "Show opt-in whisper-stream frame/state diagnostics and first-output timing notifications.",
815
960
  rawValue: env("MICME_STREAM_DIAGNOSTICS") ?? "0",
@@ -861,7 +1006,7 @@ export function createModelSelector(candidates: ModelCandidate[], theme: MicmeTh
861
1006
  export async function saveConfigurationValue(ctx: ExtensionContext, id: string, value: string): Promise<Record<string, string>> {
862
1007
  if (!id.startsWith("MICME_")) return {};
863
1008
 
864
- const valuesToWrite = id === "MICME_TRANSCRIPTION_MODE" ? getTranscriptionModeProfile(value === "stream" ? "stream" : "clip") : { [id]: value };
1009
+ const valuesToWrite = getConfigurationValuesToWrite(id, value);
865
1010
  if (id === "MICME_WHISPER_CPP_MODEL" && value) {
866
1011
  await ensureWhisperCppModel(expandConfigPath(value), ctx);
867
1012
  }
@@ -876,10 +1021,21 @@ export async function saveConfigurationValue(ctx: ExtensionContext, id: string,
876
1021
 
877
1022
  export function displayConfigurationValue(id: string, value: string) {
878
1023
  if (id === "MICME_WHISPER_CPP_MODEL") return value ? basename(value) : "not set";
1024
+ if (id === "MICME_TRANSCRIBE_COMMAND") return value ? "configured" : "not set";
879
1025
  if (id === "MICME_AUDIO_FILTER") return value || "<empty>";
880
1026
  return value || "not set";
881
1027
  }
882
1028
 
1029
+ function getUiBackendValue(plan: ResolvedTranscriptionPlan): "whisper.cpp" | "python" {
1030
+ if (plan.requestedBackend === "python" || plan.requestedBackend === "whisper.cpp") return plan.requestedBackend;
1031
+ return plan.effectiveBackend === "python" ? "python" : "whisper.cpp";
1032
+ }
1033
+
1034
+ function getCurrentWhisperCppModelValue() {
1035
+ const explicit = env("MICME_WHISPER_CPP_MODEL")?.trim();
1036
+ return explicit ? expandConfigPath(explicit) : resolveWhisperCppModel().path;
1037
+ }
1038
+
883
1039
  export function uniqueStrings(values: string[]) {
884
1040
  const seen = new Set<string>();
885
1041
  const output: string[] = [];
@@ -892,13 +1048,19 @@ export function uniqueStrings(values: string[]) {
892
1048
  return output.length > 0 ? output : [""];
893
1049
  }
894
1050
 
1051
+ function getConfigurationValuesToWrite(id: string, value: string) {
1052
+ if (id === "MICME_TRANSCRIPTION_MODE") return getTranscriptionModeProfile(value === "stream" ? "stream" : "clip");
1053
+ if (id === "MICME_SHORTCUT") return { MICME_SHORTCUT: value, MICME_PRINTABLE_SHORTCUTS: undefined };
1054
+ return { [id]: value };
1055
+ }
1056
+
895
1057
  function formatSaveStatus(id: string, value: string) {
896
- const writtenKeys = id === "MICME_TRANSCRIPTION_MODE" ? Object.keys(getTranscriptionModeProfile(value === "stream" ? "stream" : "clip")) : [id];
1058
+ const writtenKeys = Object.keys(getConfigurationValuesToWrite(id, value));
897
1059
  const overriddenKeys = writtenKeys.filter((key) => process.env[key] !== undefined);
898
1060
  const reloadHint = id === "MICME_SHORTCUT" ? "/reload required for shortcut changes" : id === "MICME_PRINTABLE_SHORTCUTS" ? "/reload recommended for printable shortcuts" : "";
899
1061
 
900
1062
  if (id === "MICME_TRANSCRIPTION_MODE" && overriddenKeys.length) return `Shell env still overrides ${overriddenKeys.join(", ")}`;
901
- if (overriddenKeys.includes(id)) return reloadHint ? `Shell env still overrides ${id} • ${reloadHint}` : `Shell env still overrides ${id}`;
1063
+ if (overriddenKeys.length) return reloadHint ? `Shell env still overrides ${overriddenKeys.join(", ")} • ${reloadHint}` : `Shell env still overrides ${overriddenKeys.join(", ")}`;
902
1064
  return reloadHint;
903
1065
  }
904
1066
 
@@ -944,6 +1106,12 @@ function isTruthyConfigValue(value: string) {
944
1106
  return /^(1|true|yes|on)$/i.test(value);
945
1107
  }
946
1108
 
1109
+ function getShortcutInput(data: string) {
1110
+ const parsed = parseKey(data);
1111
+ if (parsed && parsed !== "enter" && parsed !== "escape" && parsed !== "esc") return parsed;
1112
+ return decodeKittyPrintable(data) ?? getPrintableInput(data);
1113
+ }
1114
+
947
1115
  function getPrintableInput(data: string) {
948
1116
  if (!data || data.includes("\x1b")) return "";
949
1117
  if (matchesKey(data, Key.space)) return " ";
@@ -2,31 +2,31 @@ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { existsSync } from "node:fs";
3
3
  import { readFile } from "node:fs/promises";
4
4
  import { basename, join } from "node:path";
5
- import { env, expandConfigPath, getTranscribeTimeoutMs } from "./config.ts";
6
- import { ensureWhisperCppModel, getDefaultWhisperCppModelPath } from "./models.ts";
7
- import { findExecutable, formatRunExit, replacePlaceholders, runProcess, runShell } from "./processes.ts";
5
+ import { resolveTranscriptionPlan, formatTranscriptionPlan } from "./backends.ts";
6
+ import { env, getTranscribeTimeoutMs } from "./config.ts";
7
+ import { ensureWhisperCppModel } from "./models.ts";
8
+ import { formatRunExit, replacePlaceholders, runProcess, runShell } from "./processes.ts";
8
9
 
9
- export async function transcribe(audioPath: string, tempDir: string, ctx?: ExtensionContext): Promise<string> {
10
- const custom = env("MICME_TRANSCRIBE_COMMAND");
11
- if (custom?.trim()) {
12
- return transcribeWithCustomCommand(custom, audioPath, tempDir);
13
- }
14
-
15
- const whisperCppBinary = getWhisperCppBinary();
16
- const whisperCppModel = env("MICME_WHISPER_CPP_MODEL") || (whisperCppBinary ? getDefaultWhisperCppModelPath() : undefined);
17
- if (whisperCppModel && whisperCppBinary) {
18
- return transcribeWithWhisperCpp(whisperCppBinary, expandConfigPath(whisperCppModel), audioPath, tempDir, ctx);
19
- }
10
+ export { getWhisperCppBinary, getWhisperStreamBinary, resolveExecutableConfig } from "./backends.ts";
20
11
 
21
- const openAiWhisper = findExecutable(["whisper"]);
22
- if (openAiWhisper) {
23
- return transcribeWithOpenAiWhisper(openAiWhisper, audioPath, tempDir);
12
+ export async function transcribe(audioPath: string, tempDir: string, ctx?: ExtensionContext): Promise<string> {
13
+ const plan = resolveTranscriptionPlan({ transcriptionMode: "clip" });
14
+
15
+ switch (plan.effectiveBackend) {
16
+ case "custom":
17
+ if (!plan.command) break;
18
+ return transcribeWithCustomCommand(plan.command, audioPath, tempDir);
19
+ case "whisper.cpp":
20
+ if (!plan.binary || !plan.modelPath) break;
21
+ return transcribeWithWhisperCpp(plan.binary, plan.modelPath, audioPath, tempDir, ctx, { allowDownload: plan.modelDownloadable !== false });
22
+ case "python":
23
+ if (!plan.binary) break;
24
+ return transcribeWithOpenAiWhisper(plan.binary, audioPath, tempDir, plan.modelName);
25
+ case "none":
26
+ break;
24
27
  }
25
28
 
26
- throw new Error(
27
- "No Micme transcription backend found. Install whisper-cpp and set MICME_WHISPER_CPP_MODEL, " +
28
- "install openai-whisper, or set MICME_TRANSCRIBE_COMMAND.",
29
- );
29
+ throw new Error(formatTranscriptionPlan(plan));
30
30
  }
31
31
 
32
32
  export async function transcribeWithCustomCommand(template: string, audioPath: string, tempDir: string) {
@@ -45,8 +45,15 @@ export async function transcribeWithCustomCommand(template: string, audioPath: s
45
45
  return result.stdout;
46
46
  }
47
47
 
48
- export async function transcribeWithWhisperCpp(binary: string, modelPath: string, audioPath: string, tempDir: string, ctx?: ExtensionContext) {
49
- await ensureWhisperCppModel(modelPath, ctx);
48
+ export async function transcribeWithWhisperCpp(
49
+ binary: string,
50
+ modelPath: string,
51
+ audioPath: string,
52
+ tempDir: string,
53
+ ctx?: ExtensionContext,
54
+ options: { allowDownload?: boolean } = {},
55
+ ) {
56
+ await ensureWhisperCppModel(modelPath, ctx, options);
50
57
  const outputBase = join(tempDir, "whisper-cpp");
51
58
  const args = ["-m", modelPath, "-f", audioPath, "-otxt", "-of", outputBase, "-nt", "-np", "-nf", "-sns"];
52
59
  const language = env("MICME_LANGUAGE");
@@ -66,8 +73,8 @@ export async function transcribeWithWhisperCpp(binary: string, modelPath: string
66
73
  return result.stdout;
67
74
  }
68
75
 
69
- export async function transcribeWithOpenAiWhisper(binary: string, audioPath: string, tempDir: string) {
70
- const model = env("MICME_WHISPER_MODEL") || "base.en";
76
+ export async function transcribeWithOpenAiWhisper(binary: string, audioPath: string, tempDir: string, modelName?: string) {
77
+ const model = modelName || env("MICME_WHISPER_MODEL") || "base.en";
71
78
  const args = [
72
79
  audioPath,
73
80
  "--model",
@@ -106,26 +113,3 @@ export async function transcribeWithOpenAiWhisper(binary: string, audioPath: str
106
113
 
107
114
  return result.stdout;
108
115
  }
109
-
110
- export function getWhisperCppBinary() {
111
- const configured = env("MICME_WHISPER_CPP_BIN")?.trim();
112
- if (configured) return resolveExecutableConfig(configured, "MICME_WHISPER_CPP_BIN");
113
- return findExecutable(["whisper-cli", "whisper-cpp"]);
114
- }
115
-
116
- export function getWhisperStreamBinary() {
117
- const configured = env("MICME_WHISPER_STREAM_BIN")?.trim();
118
- if (configured) return resolveExecutableConfig(configured, "MICME_WHISPER_STREAM_BIN");
119
- return findExecutable(["whisper-stream"]);
120
- }
121
-
122
- export function resolveExecutableConfig(value: string, configName: string) {
123
- const expanded = expandConfigPath(value);
124
- if (/[/\\]/.test(expanded)) {
125
- if (!existsSync(expanded)) throw new Error(`${configName} is set but not found: ${expanded}`);
126
- return expanded;
127
- }
128
- const executable = findExecutable([expanded]);
129
- if (!executable) throw new Error(`${configName} is set but not found on PATH: ${expanded}`);
130
- return executable;
131
- }