@senad-d/micme 0.1.1 → 0.2.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/config.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
- import { writeFile } from "node:fs/promises";
3
- import { join } from "node:path";
4
- import type { DotEnvState, TranscriptionMode } from "./types.ts";
2
+ import { mkdir, rename, rm, writeFile } from "node:fs/promises";
3
+ import { createRequire } from "node:module";
4
+ import { homedir } from "node:os";
5
+ import { dirname, join, resolve } from "node:path";
6
+ import type { MicmeConfigState, TranscriptionMode } from "./types.ts";
5
7
  import {
6
8
  DEFAULT_MACOS_PRINTABLE_SHORTCUT,
7
9
  DEFAULT_RECORD_SAMPLE_RATE,
@@ -11,6 +13,7 @@ import {
11
13
  DEFAULT_STREAM_MAX_TOKENS,
12
14
  DEFAULT_STREAM_STEP_MS,
13
15
  DEFAULT_STREAM_VAD_THRESHOLD,
16
+ DEFAULT_STREAM_FLUSH_MS,
14
17
  DEFAULT_TRANSCRIBE_SAMPLE_RATE,
15
18
  DEFAULT_TRANSCRIBE_TIMEOUT_MS,
16
19
  DEFAULT_MIN_MAX_VOLUME_DB,
@@ -20,13 +23,80 @@ import {
20
23
  STREAM_PROFILE_STEP_MS,
21
24
  STREAM_PROFILE_VAD_THRESHOLD,
22
25
  STREAM_PROFILE_WORDS_PER_CHUNK,
26
+ STREAM_PROFILE_FLUSH_MS,
23
27
  } from "./constants.ts";
24
28
 
25
- let dotEnvState: DotEnvState = { path: "", values: {} };
29
+ const MICME_CONFIG_FILE = "micme.json";
30
+ const MICME_SCHEMA_URL = "https://raw.githubusercontent.com/senad-d/micme/main/micme.schema.json";
31
+ const requireModule = createRequire(import.meta.url);
26
32
 
27
- export function reloadDotEnv(cwd: string) {
28
- dotEnvState = loadDotEnv(cwd);
29
- return dotEnvState;
33
+ type JsonObject = Record<string, unknown>;
34
+
35
+ let piAgentDirChecked = false;
36
+ let piAgentDir: string | undefined;
37
+ let micmeConfigState: MicmeConfigState = loadMicmeJson();
38
+
39
+ export function getMicmeAgentDir() {
40
+ const configured = process.env.PI_CODING_AGENT_DIR?.trim();
41
+ if (configured) return resolve(configured);
42
+
43
+ const exported = getPiExportedAgentDir();
44
+ if (exported) return resolve(exported);
45
+
46
+ return join(homedir(), ".pi", "agent");
47
+ }
48
+
49
+ export function getMicmeConfigPath() {
50
+ return join(getMicmeAgentDir(), MICME_CONFIG_FILE);
51
+ }
52
+
53
+ export function reloadMicmeConfig() {
54
+ micmeConfigState = loadMicmeJson();
55
+ return micmeConfigState;
56
+ }
57
+
58
+ export function loadMicmeJson(): MicmeConfigState {
59
+ const path = getMicmeConfigPath();
60
+ if (!existsSync(path)) return { path, values: {} };
61
+
62
+ try {
63
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8").replace(/^\uFEFF/, ""));
64
+ if (!isJsonObject(parsed)) {
65
+ return { path, values: {}, error: "top-level value must be a JSON object" };
66
+ }
67
+ return { path, values: extractMicmeValues(parsed) };
68
+ } catch (error) {
69
+ return { path, values: {}, error: error instanceof Error ? error.message : String(error) };
70
+ }
71
+ }
72
+
73
+ export async function writeMicmeConfigValue(key: string, value: string) {
74
+ await writeMicmeConfigValues({ [key]: value });
75
+ }
76
+
77
+ export async function writeMicmeConfigValues(values: Record<string, string>) {
78
+ for (const key of Object.keys(values)) {
79
+ if (!key.startsWith("MICME_")) throw new Error(`Micme config keys must start with MICME_: ${key}`);
80
+ }
81
+
82
+ const configPath = getMicmeConfigPath();
83
+ const configDir = dirname(configPath);
84
+ const existing = readMicmeJsonObjectForWrite(configPath);
85
+ const next: JsonObject = { ...existing };
86
+
87
+ for (const [key, value] of Object.entries(values)) next[key] = String(value);
88
+
89
+ await mkdir(configDir, { recursive: true });
90
+ const tempPath = join(configDir, `.micme.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);
91
+ try {
92
+ await writeFile(tempPath, `${JSON.stringify(next, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
93
+ await rename(tempPath, configPath);
94
+ } catch (error) {
95
+ await rm(tempPath, { force: true }).catch(() => undefined);
96
+ throw error;
97
+ }
98
+
99
+ reloadMicmeConfig();
30
100
  }
31
101
 
32
102
  export function getTranscriptionModeProfile(mode: TranscriptionMode): Record<string, string> {
@@ -38,7 +108,9 @@ export function getTranscriptionModeProfile(mode: TranscriptionMode): Record<str
38
108
  MICME_STREAM_KEEP_MS: String(STREAM_PROFILE_KEEP_MS),
39
109
  MICME_STREAM_MAX_TOKENS: String(STREAM_PROFILE_MAX_TOKENS),
40
110
  MICME_STREAM_WORDS_PER_CHUNK: String(STREAM_PROFILE_WORDS_PER_CHUNK),
41
- MICME_STREAM_KEEP_CONTEXT: "1",
111
+ MICME_STREAM_FLUSH_MS: String(STREAM_PROFILE_FLUSH_MS),
112
+ // whisper-stream's upstream default is no prompt carry-over. Keep it disabled for Micme's append-only stream profile so raw dictation is less likely to rewrite short chunks contextually.
113
+ MICME_STREAM_KEEP_CONTEXT: "0",
42
114
  MICME_STREAM_FINALIZE_WITH_CLIP: "0",
43
115
  MICME_STREAM_VAD_THRESHOLD: String(STREAM_PROFILE_VAD_THRESHOLD),
44
116
  };
@@ -51,96 +123,27 @@ export function getTranscriptionModeProfile(mode: TranscriptionMode): Record<str
51
123
  MICME_STREAM_KEEP_MS: String(DEFAULT_STREAM_KEEP_MS),
52
124
  MICME_STREAM_MAX_TOKENS: String(DEFAULT_STREAM_MAX_TOKENS),
53
125
  MICME_STREAM_WORDS_PER_CHUNK: "10",
54
- MICME_STREAM_KEEP_CONTEXT: "1",
126
+ MICME_STREAM_FLUSH_MS: String(DEFAULT_STREAM_FLUSH_MS),
127
+ MICME_STREAM_KEEP_CONTEXT: "0",
55
128
  MICME_STREAM_FINALIZE_WITH_CLIP: "1",
56
129
  MICME_STREAM_VAD_THRESHOLD: String(DEFAULT_STREAM_VAD_THRESHOLD),
57
130
  };
58
131
  }
59
132
 
60
- export async function writeDotEnvValue(cwd: string, key: string, value: string) {
61
- const path = join(cwd, ".env");
62
- const lines = existsSync(path) ? readFileSync(path, "utf8").split(/\r?\n/) : [];
63
- const matcher = new RegExp(`^\\s*(?:export\\s+)?${escapeRegExp(key)}\\s*=`);
64
- let found = false;
65
- const nextLines = lines.map((line) => {
66
- if (!matcher.test(line)) return line;
67
- found = true;
68
- return `${key}=${formatDotEnvValue(value)}`;
69
- });
70
-
71
- if (!found) {
72
- if (nextLines.length > 0 && nextLines[nextLines.length - 1] !== "") nextLines.push("");
73
- nextLines.push(`${key}=${formatDotEnvValue(value)}`);
74
- }
75
-
76
- await writeFile(path, `${nextLines.join("\n").replace(/\n*$/, "")}\n`, "utf8");
77
- }
78
-
79
- export function formatDotEnvValue(value: string) {
80
- if (value === "") return "";
81
- if (/^[A-Za-z0-9_./:@%+=,-]+$/.test(value)) return value;
82
- return JSON.stringify(value);
83
- }
84
-
85
- export function escapeRegExp(value: string) {
86
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
87
- }
88
-
89
133
  export function expandConfigPath(value: string) {
90
- return expandEnvReferences(value, dotEnvState.values);
91
- }
92
-
93
- export function loadDotEnv(cwd: string): DotEnvState {
94
- const path = join(cwd, ".env");
95
- if (!existsSync(path)) return { path: "", values: {} };
96
-
97
- try {
98
- const values: Record<string, string> = {};
99
- const content = readFileSync(path, "utf8").replace(/^\uFEFF/, "");
100
- for (const line of content.split(/\r?\n/)) {
101
- const parsed = parseDotEnvLine(line, values);
102
- if (!parsed) continue;
103
- values[parsed.key] = parsed.value;
104
- }
105
- return { path, values };
106
- } catch (error) {
107
- return { path, values: {}, error: error instanceof Error ? error.message : String(error) };
108
- }
134
+ return expandEnvReferences(value, micmeConfigState.values);
109
135
  }
110
136
 
111
- export function parseDotEnvLine(line: string, previousValues: Record<string, string>) {
112
- const trimmed = line.trim();
113
- if (!trimmed || trimmed.startsWith("#")) return undefined;
114
-
115
- const match = trimmed.match(/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
116
- if (!match) return undefined;
117
-
118
- const key = match[1] ?? "";
119
- if (!key.startsWith("MICME_")) return undefined;
120
-
121
- let value = match[2] ?? "";
122
- if (value.startsWith('"') && value.endsWith('"')) {
123
- value = value.slice(1, -1).replace(/\\n/g, "\n").replace(/\\r/g, "\r").replace(/\\t/g, "\t").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
124
- } else if (value.startsWith("'") && value.endsWith("'")) {
125
- value = value.slice(1, -1);
126
- } else {
127
- value = value.replace(/\s+#.*$/, "").trim();
128
- }
129
-
130
- value = expandEnvReferences(value, previousValues);
131
- return { key, value };
132
- }
133
-
134
- export function expandEnvReferences(value: string, previousValues: Record<string, string>) {
137
+ export function expandEnvReferences(value: string, configValues: Record<string, string>) {
135
138
  const withHome = value.startsWith("~/") && process.env.HOME ? `${process.env.HOME}${value.slice(1)}` : value;
136
139
  return withHome.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (_match, braced: string | undefined, bare: string | undefined) => {
137
140
  const key = braced ?? bare ?? "";
138
- return previousValues[key] ?? process.env[key] ?? "";
141
+ return process.env[key] ?? configValues[key] ?? "";
139
142
  });
140
143
  }
141
144
 
142
145
  export function env(name: string) {
143
- return process.env[name] ?? dotEnvState.values[name];
146
+ return process.env[name] ?? micmeConfigState.values[name];
144
147
  }
145
148
 
146
149
  export function getShortcut() {
@@ -198,12 +201,17 @@ export function getStreamVadThreshold() {
198
201
 
199
202
  export function getStreamKeepContext() {
200
203
  const value = env("MICME_STREAM_KEEP_CONTEXT");
201
- return value === undefined ? true : /^(1|true|yes|on)$/i.test(value);
204
+ return value === undefined ? false : /^(1|true|yes|on)$/i.test(value);
205
+ }
206
+
207
+ export function getStreamFlushMs() {
208
+ const value = Number(env("MICME_STREAM_FLUSH_MS"));
209
+ return Number.isFinite(value) && value > 0 ? Math.round(value) : DEFAULT_STREAM_FLUSH_MS;
202
210
  }
203
211
 
204
212
  export function getStreamFinalizeWithClip() {
205
213
  const value = env("MICME_STREAM_FINALIZE_WITH_CLIP");
206
- return value === undefined ? true : /^(1|true|yes|on)$/i.test(value);
214
+ return value === undefined ? false : /^(1|true|yes|on)$/i.test(value);
207
215
  }
208
216
 
209
217
  export function getStreamWordsPerChunk() {
@@ -254,3 +262,46 @@ export function getMeterGain() {
254
262
  export function envFlag(name: string) {
255
263
  return /^(1|true|yes|on)$/i.test(env(name) || "");
256
264
  }
265
+
266
+ function readMicmeJsonObjectForWrite(configPath: string): JsonObject {
267
+ if (!existsSync(configPath)) return { $schema: MICME_SCHEMA_URL };
268
+
269
+ try {
270
+ const parsed: unknown = JSON.parse(readFileSync(configPath, "utf8").replace(/^\uFEFF/, ""));
271
+ if (!isJsonObject(parsed)) throw new Error("top-level value must be a JSON object");
272
+ return parsed;
273
+ } catch (error) {
274
+ const message = error instanceof Error ? error.message : String(error);
275
+ throw new Error(`Cannot save Micme config: ${configPath} is invalid JSON (${message}). Fix or remove it first.`);
276
+ }
277
+ }
278
+
279
+ function extractMicmeValues(json: JsonObject) {
280
+ const values: Record<string, string> = {};
281
+ for (const [key, value] of Object.entries(json)) {
282
+ if (!key.startsWith("MICME_")) continue;
283
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") values[key] = String(value);
284
+ }
285
+ return values;
286
+ }
287
+
288
+ function isJsonObject(value: unknown): value is JsonObject {
289
+ return typeof value === "object" && value !== null && !Array.isArray(value);
290
+ }
291
+
292
+ function getPiExportedAgentDir() {
293
+ if (piAgentDirChecked) return piAgentDir;
294
+ piAgentDirChecked = true;
295
+
296
+ try {
297
+ const piModule = requireModule("@earendil-works/pi-coding-agent") as { getAgentDir?: unknown };
298
+ if (typeof piModule.getAgentDir === "function") {
299
+ const value = piModule.getAgentDir();
300
+ if (typeof value === "string" && value.trim()) piAgentDir = value;
301
+ }
302
+ } catch {
303
+ // Some pi runtimes may not expose this helper or may be ESM-only. Falling back is safe.
304
+ }
305
+
306
+ return piAgentDir;
307
+ }
package/src/constants.ts CHANGED
@@ -9,18 +9,20 @@ export const RECORDER_STARTUP_GRACE_MS = 700;
9
9
  export const RECORDER_STOP_GRACE_MS = 3_000;
10
10
  export const MIN_AUDIO_BYTES = 512;
11
11
  export const MAX_CAPTURED_OUTPUT_CHARS = 100_000;
12
- export const STREAM_MIN_INITIAL_WORDS = 2;
12
+ export const STREAM_MIN_INITIAL_WORDS = 1;
13
13
  export const DEFAULT_STREAM_STEP_MS = 1_000;
14
14
  export const DEFAULT_STREAM_LENGTH_MS = 5_000;
15
15
  export const DEFAULT_STREAM_KEEP_MS = 500;
16
16
  export const DEFAULT_STREAM_MAX_TOKENS = 64;
17
17
  export const DEFAULT_STREAM_VAD_THRESHOLD = 0.45;
18
+ export const DEFAULT_STREAM_FLUSH_MS = 700;
18
19
  export const STREAM_PROFILE_STEP_MS = 500;
19
20
  export const STREAM_PROFILE_LENGTH_MS = 3_000;
20
21
  export const STREAM_PROFILE_KEEP_MS = 300;
21
22
  export const STREAM_PROFILE_MAX_TOKENS = 32;
22
23
  export const STREAM_PROFILE_WORDS_PER_CHUNK = 5;
23
24
  export const STREAM_PROFILE_VAD_THRESHOLD = 0.35;
25
+ export const STREAM_PROFILE_FLUSH_MS = 650;
24
26
  export const DEFAULT_MIN_MAX_VOLUME_DB = -50;
25
27
  export const AUDIO_VALIDATION_TIMEOUT_MS = 30_000;
26
28
  export const DEFAULT_WHISPER_CPP_MODEL_NAME = "small.en";
package/src/extension.ts CHANGED
@@ -10,9 +10,9 @@ import {
10
10
  getShortcut,
11
11
  getStreamFinalizeWithClip,
12
12
  getTranscriptionMode,
13
- reloadDotEnv,
13
+ reloadMicmeConfig,
14
14
  } from "./config.ts";
15
- import { buildRecorderCommand, listAudioDevices, prepareAudioForTranscription, validateRecordedAudio } from "./audio.ts";
15
+ import { buildRecorderCommand, listAudioDevices, prepareAudioForTranscription, registerDeviceMessageRenderer, validateRecordedAudio } from "./audio.ts";
16
16
  import { installMicmeEditorFallback, type MicmeEditorInputHandlers } from "./editor.ts";
17
17
  import { getDefaultWhisperCppModelPath, ensureWhisperCppModel } from "./models.ts";
18
18
  import {
@@ -51,7 +51,8 @@ let lastAudioDir = "";
51
51
  let lastShortcutInputAt = 0;
52
52
 
53
53
  export default function micmeExtension(pi: ExtensionAPI) {
54
- reloadDotEnv(process.cwd());
54
+ reloadMicmeConfig();
55
+ registerDeviceMessageRenderer(pi);
55
56
 
56
57
  async function toggle(ctx: ExtensionContext) {
57
58
  if (recording) {
@@ -77,7 +78,7 @@ export default function micmeExtension(pi: ExtensionAPI) {
77
78
  await toggle(ctx);
78
79
  return;
79
80
  case "devices":
80
- await listAudioDevices(ctx);
81
+ await listAudioDevices(ctx, pi);
81
82
  return;
82
83
  case "conf":
83
84
  await showConfiguration(ctx);
@@ -113,7 +114,7 @@ export default function micmeExtension(pi: ExtensionAPI) {
113
114
  });
114
115
 
115
116
  pi.on("session_start", async (_event, ctx) => {
116
- reloadDotEnv(ctx.cwd);
117
+ reloadMicmeConfig();
117
118
  installMicmeEditorFallback(ctx, createMicmeEditorHandlers(ctx, toggle));
118
119
  });
119
120
 
@@ -251,7 +252,16 @@ async function startStreamingTranscription(ctx: ExtensionContext, stopHint = get
251
252
  const command = buildWhisperStreamCommand(whisperStream, whisperCppModel, tempDir);
252
253
  const active = spawnRecording(command, "", tempDir);
253
254
  const baseText = ctx.ui.getEditorText();
254
- active.streaming = { baseText, previewText: baseText, outputBuffer: "", lastText: "", pendingWords: [], emittedWords: [], startedAt: Date.now() };
255
+ active.streaming = {
256
+ baseText,
257
+ previewText: baseText,
258
+ outputBuffer: "",
259
+ lastText: "",
260
+ emittedWords: [],
261
+ candidateWords: [],
262
+ lastHypothesisWords: [],
263
+ startedAt: Date.now(),
264
+ };
255
265
  if (getStreamFinalizeWithClip()) {
256
266
  const audioPath = join(tempDir, "raw.wav");
257
267
  active.clipRecording = spawnRecording(buildRecorderCommand(audioPath), audioPath, tempDir);
@@ -334,10 +344,13 @@ async function stopStreamingTranscription(ctx: ExtensionContext, pi: ExtensionAP
334
344
  keepTempDir = true;
335
345
  }
336
346
  } catch (error) {
347
+ flushPendingStreamingWords(ctx, state);
348
+ const liveTranscript = normalizeTranscript(getStreamingTranscript(state));
349
+ if (liveTranscript) lastTranscript = liveTranscript;
337
350
  lastAudioDir = active.tempDir;
338
351
  keepTempDir = true;
339
352
  const message = error instanceof Error ? error.message : String(error);
340
- ctx.ui.notify(`Micme kept the live stream preview because final clip transcription failed: ${message}\nAudio kept for debugging: ${active.tempDir}`, "warning");
353
+ ctx.ui.notify(`Micme kept the live append-only stream transcript because final clip transcription failed: ${message}\nAudio kept for debugging: ${active.tempDir}`, "warning");
341
354
  }
342
355
  }
343
356
 
package/src/settings.ts CHANGED
@@ -12,12 +12,13 @@ import {
12
12
  truncateToWidth,
13
13
  visibleWidth,
14
14
  } from "@earendil-works/pi-tui";
15
- import { basename, join } from "node:path";
15
+ import { basename } from "node:path";
16
16
  import {
17
17
  DEFAULT_MACOS_PRINTABLE_SHORTCUT,
18
18
  DEFAULT_RECORD_SAMPLE_RATE,
19
19
  DEFAULT_SHORTCUT,
20
20
  DEFAULT_STREAM_VAD_THRESHOLD,
21
+ DEFAULT_STREAM_FLUSH_MS,
21
22
  DEFAULT_TRANSCRIBE_SAMPLE_RATE,
22
23
  DEFAULT_WHISPER_CPP_MODEL_NAME,
23
24
  PYTHON_WHISPER_MODEL_NAMES,
@@ -28,8 +29,8 @@ import {
28
29
  expandConfigPath,
29
30
  getTranscriptionMode,
30
31
  getTranscriptionModeProfile,
31
- reloadDotEnv,
32
- writeDotEnvValue,
32
+ reloadMicmeConfig,
33
+ writeMicmeConfigValues,
33
34
  } from "./config.ts";
34
35
  import { discoverAudioDevices } from "./audio.ts";
35
36
  import { discoverWhisperCppModels, ensureWhisperCppModel, getDefaultWhisperCppModelPath } from "./models.ts";
@@ -74,14 +75,17 @@ export async function showConfiguration(ctx: ExtensionContext) {
74
75
  return;
75
76
  }
76
77
 
77
- reloadDotEnv(ctx.cwd);
78
+ const configState = reloadMicmeConfig();
79
+ if (configState.error) {
80
+ ctx.ui.notify(`Micme config is invalid at ${configState.path}: ${configState.error}. Fix it before saving settings.`, "warning");
81
+ }
78
82
  const audioDevices = await discoverAudioDevices();
79
83
  const modelCandidates = discoverWhisperCppModels(ctx.cwd);
80
84
 
81
85
  await ctx.ui.custom<void>((tui, theme, _keybindings, done) => {
82
86
  const items = buildConfigurationItems(modelCandidates, audioDevices, theme);
83
87
  return new ConfigurationScreen({
84
- cwd: ctx.cwd,
88
+ configPath: configState.path,
85
89
  items,
86
90
  theme,
87
91
  onDone: done,
@@ -93,7 +97,7 @@ export async function showConfiguration(ctx: ExtensionContext) {
93
97
  }
94
98
 
95
99
  class ConfigurationScreen implements Component {
96
- private readonly cwd: string;
100
+ private readonly configPath: string;
97
101
  private readonly items: ConfigurationItem[];
98
102
  private readonly theme: MicmeTheme;
99
103
  private readonly onDone: () => void;
@@ -111,7 +115,7 @@ class ConfigurationScreen implements Component {
111
115
  private statusText = "";
112
116
 
113
117
  constructor(options: {
114
- cwd: string;
118
+ configPath: string;
115
119
  items: ConfigurationItem[];
116
120
  theme: MicmeTheme;
117
121
  onDone: () => void;
@@ -119,7 +123,7 @@ class ConfigurationScreen implements Component {
119
123
  onSave: (id: string, newValue: string) => Promise<Record<string, string>>;
120
124
  requestRender: () => void;
121
125
  }) {
122
- this.cwd = options.cwd;
126
+ this.configPath = options.configPath;
123
127
  this.items = options.items;
124
128
  this.theme = options.theme;
125
129
  this.onDone = options.onDone;
@@ -201,7 +205,7 @@ class ConfigurationScreen implements Component {
201
205
  const lines: string[] = [];
202
206
 
203
207
  lines.push(this.renderTitleBorder(width, this.currentHeaderLabel()));
204
- lines.push(this.renderFullLine(width, `writes ${join(this.cwd, ".env")} • shell env overrides .env`));
208
+ lines.push(this.renderFullLine(width, this.renderConfigSourceText(width)));
205
209
  lines.push(this.renderFullLine(width, "↑↓ move Tab pane Enter edit / search Esc back q quit"));
206
210
  lines.push(this.renderPaneSeparator(width, leftWidth, rightWidth, "top"));
207
211
 
@@ -226,7 +230,7 @@ class ConfigurationScreen implements Component {
226
230
  const lines: string[] = [];
227
231
 
228
232
  lines.push(this.renderTitleBorder(width, this.currentHeaderLabel()));
229
- lines.push(this.renderFullLine(width, `writes ${join(this.cwd, ".env")} • shell env overrides .env`));
233
+ lines.push(this.renderFullLine(width, this.renderConfigSourceText(width)));
230
234
  lines.push(this.renderFullLine(width, showCategories ? "↑↓ category Enter open / search q quit" : "↑↓ move Enter edit Esc categories / search q quit"));
231
235
  lines.push(this.colorBorder(`├${"─".repeat(innerWidth)}┤`, width));
232
236
  for (const line of bodyLines) lines.push(this.renderFullLine(width, line));
@@ -284,6 +288,15 @@ class ConfigurationScreen implements Component {
284
288
  return this.theme.fg("accent", fitAnsi(line, width, ""));
285
289
  }
286
290
 
291
+ private renderConfigSourceText(width: number) {
292
+ const innerWidth = Math.max(0, width - 2);
293
+ const prefix = "writes ";
294
+ const suffix = " • shell env overrides Micme settings";
295
+ const pathWidth = Math.max(0, innerWidth - visibleWidth(prefix) - visibleWidth(suffix));
296
+ const path = pathWidth > 0 ? fitPath(this.configPath, pathWidth) : "micme.json";
297
+ return `${prefix}${path}${suffix}`;
298
+ }
299
+
287
300
  private renderCategoryPaneLines(width: number) {
288
301
  return CONFIGURATION_CATEGORIES.map((category, index) => {
289
302
  const selected = index === this.categoryIndex;
@@ -645,20 +658,30 @@ export function buildConfigurationItems(modelCandidates: ModelCandidate[], audio
645
658
  id: "MICME_STREAM_KEEP_CONTEXT",
646
659
  categoryId: "streaming",
647
660
  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"],
661
+ description: "Keep Whisper prompt context between chunks. Off by default for append-only dictation; turn on for more contextual correction.",
662
+ rawValue: env("MICME_STREAM_KEEP_CONTEXT") ?? "0",
663
+ currentValue: env("MICME_STREAM_KEEP_CONTEXT") ?? "0",
664
+ values: ["0", "1"],
652
665
  displayKind: "boolean",
653
666
  },
667
+ {
668
+ id: "MICME_STREAM_FLUSH_MS",
669
+ categoryId: "streaming",
670
+ label: "Stream flush delay",
671
+ description: "Quiet interval before tentative stream words are committed append-only into the editor.",
672
+ rawValue: env("MICME_STREAM_FLUSH_MS") ?? String(DEFAULT_STREAM_FLUSH_MS),
673
+ currentValue: env("MICME_STREAM_FLUSH_MS") ?? String(DEFAULT_STREAM_FLUSH_MS),
674
+ values: ["400", "650", "700", "1000"],
675
+ displayKind: "number",
676
+ },
654
677
  {
655
678
  id: "MICME_STREAM_FINALIZE_WITH_CLIP",
656
679
  categoryId: "streaming",
657
680
  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"],
681
+ description: "Opt in to replace the append-only live stream with a final clip-mode transcript on stop.",
682
+ rawValue: env("MICME_STREAM_FINALIZE_WITH_CLIP") ?? "0",
683
+ currentValue: env("MICME_STREAM_FINALIZE_WITH_CLIP") ?? "0",
684
+ values: ["0", "1"],
662
685
  displayKind: "boolean",
663
686
  },
664
687
  {
@@ -788,7 +811,7 @@ export function buildConfigurationItems(modelCandidates: ModelCandidate[], audio
788
811
  id: "MICME_STREAM_DIAGNOSTICS",
789
812
  categoryId: "diagnostics",
790
813
  label: "Stream diagnostics",
791
- description: "Show timing notifications for first whisper-stream output and first editor preview.",
814
+ description: "Show opt-in whisper-stream frame/state diagnostics and first-output timing notifications.",
792
815
  rawValue: env("MICME_STREAM_DIAGNOSTICS") ?? "0",
793
816
  currentValue: env("MICME_STREAM_DIAGNOSTICS") ?? "0",
794
817
  values: ["0", "1"],
@@ -843,21 +866,8 @@ export async function saveConfigurationValue(ctx: ExtensionContext, id: string,
843
866
  await ensureWhisperCppModel(expandConfigPath(value), ctx);
844
867
  }
845
868
 
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
- }
869
+ await writeMicmeConfigValues(valuesToWrite);
870
+ reloadMicmeConfig();
861
871
 
862
872
  const effectiveValues: Record<string, string> = {};
863
873
  for (const key of Object.keys(valuesToWrite)) effectiveValues[key] = env(key) ?? "";
@@ -885,16 +895,11 @@ export function uniqueStrings(values: string[]) {
885
895
  function formatSaveStatus(id: string, value: string) {
886
896
  const writtenKeys = id === "MICME_TRANSCRIPTION_MODE" ? Object.keys(getTranscriptionModeProfile(value === "stream" ? "stream" : "clip")) : [id];
887
897
  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
- }
898
+ const reloadHint = id === "MICME_SHORTCUT" ? "/reload required for shortcut changes" : id === "MICME_PRINTABLE_SHORTCUTS" ? "/reload recommended for printable shortcuts" : "";
894
899
 
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}`;
900
+ 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}`;
902
+ return reloadHint;
898
903
  }
899
904
 
900
905
  function fitAnsi(text: string, width: number, ellipsis = "…") {