@senad-d/micme 0.1.2 → 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/README.md +9 -2
- package/micme.example.json +2 -1
- package/micme.schema.json +13 -0
- package/package.json +3 -2
- package/src/audio.ts +539 -34
- package/src/config.ts +14 -4
- package/src/constants.ts +3 -1
- package/src/extension.ts +17 -4
- package/src/settings.ts +24 -41
- package/src/streaming.ts +229 -34
- package/src/types.ts +2 -1
package/README.md
CHANGED
|
@@ -164,7 +164,10 @@ Common settings:
|
|
|
164
164
|
| Variable | Meaning |
|
|
165
165
|
| --- | --- |
|
|
166
166
|
| `MICME_TRANSCRIPTION_MODE=clip` | Stable default: transcribe after recording stops. |
|
|
167
|
-
| `MICME_TRANSCRIPTION_MODE=stream` | Experimental live
|
|
167
|
+
| `MICME_TRANSCRIPTION_MODE=stream` | Experimental append-only live dictation with `whisper-stream`. |
|
|
168
|
+
| `MICME_STREAM_KEEP_CONTEXT=0` | Stream default: avoid Whisper prompt carry-over so live chunks are less likely to rewrite each other. |
|
|
169
|
+
| `MICME_STREAM_FLUSH_MS=650` | Stream profile quiet interval before tentative words are committed append-only. |
|
|
170
|
+
| `MICME_STREAM_FINALIZE_WITH_CLIP=0` | Keep the append-only live transcript on stop. Set `1` to opt in to final clip replacement. |
|
|
168
171
|
| `MICME_AUTO_SUBMIT=0` | Paste for review. Set `1` to send automatically. |
|
|
169
172
|
| `MICME_SHORTCUT=alt+m` | Toggle shortcut. Restart or `/reload` after changing. |
|
|
170
173
|
| `MICME_PRINTABLE_SHORTCUTS=§` | macOS Option-key fallback. |
|
|
@@ -174,6 +177,8 @@ Common settings:
|
|
|
174
177
|
|
|
175
178
|
See [`micme.example.json`](micme.example.json) for the full JSON template.
|
|
176
179
|
|
|
180
|
+
Streaming mode treats `whisper-stream` output as repeated, overlapping hypotheses rather than committed word deltas. Micme only appends committed words to the editor during live streaming; tentative words are held internally and committed after agreement, overlap, stop, or the quiet interval configured by `MICME_STREAM_FLUSH_MS`. If `MICME_STREAM_FINALIZE_WITH_CLIP=1`, the stop-time clip transcript can intentionally replace the live append-only text.
|
|
181
|
+
|
|
177
182
|
---
|
|
178
183
|
|
|
179
184
|
## Commands
|
|
@@ -182,7 +187,7 @@ See [`micme.example.json`](micme.example.json) for the full JSON template.
|
|
|
182
187
|
| --- | --- |
|
|
183
188
|
| `/micme` | Toggle recording. |
|
|
184
189
|
| `/micme conf` | Open the TUI configuration screen. |
|
|
185
|
-
| `/micme devices` |
|
|
190
|
+
| `/micme devices` | Show compact audio/video capture device inventory. |
|
|
186
191
|
| `/micme last` | Paste the previous transcript again. |
|
|
187
192
|
| `/micme audio` | Show the last kept audio directory. |
|
|
188
193
|
| `/micme help` | Show short help. |
|
|
@@ -239,6 +244,8 @@ npm run doctor
|
|
|
239
244
|
|
|
240
245
|
The doctor checks Node, pi, `ffmpeg`, whisper.cpp, optional `whisper-stream`, model paths, and macOS devices when available. Custom command values are redacted.
|
|
241
246
|
|
|
247
|
+
For stream state investigation, start pi with `MICME_STREAM_DIAGNOSTICS=1`. Diagnostics are opt-in and include sanitized frames, extraction mode, committed words, and tentative candidate words.
|
|
248
|
+
|
|
242
249
|
---
|
|
243
250
|
|
|
244
251
|
## Update and Uninstall
|
package/micme.example.json
CHANGED
|
@@ -19,11 +19,12 @@
|
|
|
19
19
|
"MICME_METER_GAIN": "1",
|
|
20
20
|
"MICME_STREAM_CAPTURE": "-1",
|
|
21
21
|
"MICME_STREAM_WORDS_PER_CHUNK": "5",
|
|
22
|
+
"MICME_STREAM_FLUSH_MS": "650",
|
|
22
23
|
"MICME_STREAM_STEP_MS": "500",
|
|
23
24
|
"MICME_STREAM_LENGTH_MS": "3000",
|
|
24
25
|
"MICME_STREAM_KEEP_MS": "300",
|
|
25
26
|
"MICME_STREAM_MAX_TOKENS": "32",
|
|
26
|
-
"MICME_STREAM_KEEP_CONTEXT": "
|
|
27
|
+
"MICME_STREAM_KEEP_CONTEXT": "0",
|
|
27
28
|
"MICME_STREAM_FINALIZE_WITH_CLIP": "0",
|
|
28
29
|
"MICME_STREAM_VAD_THRESHOLD": "0.35",
|
|
29
30
|
"MICME_STREAM_DIAGNOSTICS": "0"
|
package/micme.schema.json
CHANGED
|
@@ -46,6 +46,19 @@
|
|
|
46
46
|
"MICME_KEEP_AUDIO": {
|
|
47
47
|
"$ref": "#/$defs/stringFlag"
|
|
48
48
|
},
|
|
49
|
+
"MICME_STREAM_KEEP_CONTEXT": {
|
|
50
|
+
"$ref": "#/$defs/stringFlag",
|
|
51
|
+
"description": "Pass --keep-context to whisper-stream. Defaults to off for append-only dictation."
|
|
52
|
+
},
|
|
53
|
+
"MICME_STREAM_FINALIZE_WITH_CLIP": {
|
|
54
|
+
"$ref": "#/$defs/stringFlag",
|
|
55
|
+
"description": "When enabled, stop-time clip transcription may replace the append-only live stream transcript."
|
|
56
|
+
},
|
|
57
|
+
"MICME_STREAM_FLUSH_MS": {
|
|
58
|
+
"type": ["string", "number"],
|
|
59
|
+
"default": "700",
|
|
60
|
+
"description": "Quiet interval in milliseconds before tentative stream words are committed append-only."
|
|
61
|
+
},
|
|
49
62
|
"MICME_RECORD_COMMAND": {
|
|
50
63
|
"type": "string",
|
|
51
64
|
"description": "Advanced shell command hook. Use only trusted commands."
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@senad-d/micme",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Local voice-to-text for pi, optimized for fast Whisper-style backends.",
|
|
6
6
|
"license": "MIT",
|
|
@@ -45,10 +45,11 @@
|
|
|
45
45
|
"scripts": {
|
|
46
46
|
"doctor": "node scripts/doctor.mjs",
|
|
47
47
|
"check": "node --check scripts/doctor.mjs && node --check scripts/check-package-contents.mjs && node --check scripts/publish-npm.mjs",
|
|
48
|
+
"test": "node --test test/streaming.test.mjs",
|
|
48
49
|
"typecheck": "tsc --noEmit",
|
|
49
50
|
"pack:dry-run": "npm pack --dry-run --json",
|
|
50
51
|
"check:pack": "node scripts/check-package-contents.mjs",
|
|
51
|
-
"validate": "npm run typecheck && npm run check && npm run check:pack",
|
|
52
|
+
"validate": "npm run typecheck && npm run test && npm run check && npm run check:pack",
|
|
52
53
|
"publish:npm": "node scripts/publish-npm.mjs",
|
|
53
54
|
"prepublishOnly": "npm run validate"
|
|
54
55
|
},
|
package/src/audio.ts
CHANGED
|
@@ -1,35 +1,551 @@
|
|
|
1
|
-
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { sliceByColumn, visibleWidth, type Component } from "@earendil-works/pi-tui";
|
|
2
3
|
import { join } from "node:path";
|
|
3
4
|
import { AUDIO_VALIDATION_TIMEOUT_MS } from "./constants.ts";
|
|
4
5
|
import { env, envFlag, getAudioFilter, getMinMaxVolumeDb, getRecordSampleRate, getTranscribeSampleRate } from "./config.ts";
|
|
5
6
|
import { findExecutable, formatRunExit, replacePlaceholders, runProcess, shellCommand, shellQuote } from "./processes.ts";
|
|
6
7
|
import type { AudioDeviceCandidate, AudioDiagnostics, CommandSpec, RunResult } from "./types.ts";
|
|
7
8
|
|
|
8
|
-
|
|
9
|
+
type DeviceBackend = "avfoundation" | "pulse" | "dshow" | "unsupported";
|
|
10
|
+
type DeviceKind = "audio" | "video";
|
|
11
|
+
|
|
12
|
+
type ListedDevice = {
|
|
13
|
+
id?: string;
|
|
14
|
+
name: string;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
type ParsedDeviceInventory = {
|
|
18
|
+
audio: ListedDevice[];
|
|
19
|
+
video: ListedDevice[];
|
|
20
|
+
sawDeviceSection: boolean;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
type DeviceBackendInfo =
|
|
24
|
+
| {
|
|
25
|
+
backend: Exclude<DeviceBackend, "unsupported">;
|
|
26
|
+
sourceLabel: string;
|
|
27
|
+
args: string[];
|
|
28
|
+
includeVideo: boolean;
|
|
29
|
+
}
|
|
30
|
+
| {
|
|
31
|
+
backend: "unsupported";
|
|
32
|
+
sourceLabel: string;
|
|
33
|
+
includeVideo: false;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
type DevicePanelOptions = {
|
|
37
|
+
sourceLabel: string;
|
|
38
|
+
backend: DeviceBackend;
|
|
39
|
+
audio?: ListedDevice[];
|
|
40
|
+
video?: ListedDevice[];
|
|
41
|
+
includeVideo?: boolean;
|
|
42
|
+
warning?: string;
|
|
43
|
+
errorLines?: string[];
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
type DevicePanelStyle = {
|
|
47
|
+
plain: boolean;
|
|
48
|
+
separator: string;
|
|
49
|
+
audioLabel: string;
|
|
50
|
+
videoLabel: string;
|
|
51
|
+
warningLabel: string;
|
|
52
|
+
errorLabel: string;
|
|
53
|
+
ellipsis: string;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const DEVICE_SCAN_TIMEOUT_MS = 8_000;
|
|
57
|
+
const DEVICE_PANEL_MESSAGE_TYPE = "micme-devices";
|
|
58
|
+
const DEVICE_PANEL_DEFAULT_WIDTH = 92;
|
|
59
|
+
const DEVICE_PANEL_MAX_WIDTH = 100;
|
|
60
|
+
const DEVICE_PANEL_MIN_WIDTH = 36;
|
|
61
|
+
|
|
62
|
+
let deviceMessageRendererRegistered = false;
|
|
63
|
+
|
|
64
|
+
type DevicePanelMessage = {
|
|
65
|
+
customType: string;
|
|
66
|
+
content: string;
|
|
67
|
+
display: boolean;
|
|
68
|
+
details?: unknown;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
type DeviceMessageRendererOptions = {
|
|
72
|
+
expanded?: boolean;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
type DeviceMessageApi = {
|
|
76
|
+
registerMessageRenderer?: (
|
|
77
|
+
customType: string,
|
|
78
|
+
renderer: (message: DevicePanelMessage, options: DeviceMessageRendererOptions, theme: ExtensionContext["ui"]["theme"]) => Component,
|
|
79
|
+
) => void;
|
|
80
|
+
sendMessage?: (message: DevicePanelMessage, options?: { triggerTurn?: boolean; deliverAs?: "steer" | "followUp" | "nextTurn" }) => void;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
export function registerDeviceMessageRenderer(pi: ExtensionAPI) {
|
|
84
|
+
const api = pi as ExtensionAPI & DeviceMessageApi;
|
|
85
|
+
if (!api.registerMessageRenderer) return;
|
|
86
|
+
api.registerMessageRenderer(DEVICE_PANEL_MESSAGE_TYPE, (message) => new DevicePanelMessageComponent(readDevicePanelOptions(message.details)));
|
|
87
|
+
deviceMessageRendererRegistered = true;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export async function listAudioDevices(ctx: ExtensionContext, pi?: ExtensionAPI) {
|
|
91
|
+
const backend = getCurrentDeviceBackend();
|
|
92
|
+
if (backend.backend === "unsupported") {
|
|
93
|
+
await showDevicePanel(ctx, pi, {
|
|
94
|
+
sourceLabel: backend.sourceLabel,
|
|
95
|
+
backend: backend.backend,
|
|
96
|
+
errorLines: ["Device listing is not implemented for this platform"],
|
|
97
|
+
});
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
|
|
9
101
|
const ffmpeg = findExecutable(["ffmpeg"]);
|
|
10
102
|
if (!ffmpeg) {
|
|
11
|
-
ctx
|
|
103
|
+
await showDevicePanel(ctx, pi, {
|
|
104
|
+
sourceLabel: backend.sourceLabel,
|
|
105
|
+
backend: backend.backend,
|
|
106
|
+
errorLines: ["ffmpeg not found", "Install ffmpeg or configure a custom recorder before listing devices."],
|
|
107
|
+
});
|
|
12
108
|
return;
|
|
13
109
|
}
|
|
14
110
|
|
|
15
|
-
let title = "Micme audio devices";
|
|
16
111
|
let result: RunResult;
|
|
17
|
-
|
|
18
|
-
result = await runProcess(ffmpeg,
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
title = "Micme Windows DirectShow devices";
|
|
26
|
-
} else {
|
|
27
|
-
ctx.ui.notify(`Device listing is not implemented for ${process.platform}.`, "warning");
|
|
112
|
+
try {
|
|
113
|
+
result = await runProcess(ffmpeg, backend.args, DEVICE_SCAN_TIMEOUT_MS);
|
|
114
|
+
} catch {
|
|
115
|
+
await showDevicePanel(ctx, pi, {
|
|
116
|
+
sourceLabel: backend.sourceLabel,
|
|
117
|
+
backend: backend.backend,
|
|
118
|
+
errorLines: ["Device scan failed", "Could not start ffmpeg to list capture devices."],
|
|
119
|
+
});
|
|
28
120
|
return;
|
|
29
121
|
}
|
|
30
122
|
|
|
31
|
-
|
|
32
|
-
|
|
123
|
+
await showDevicePanel(ctx, pi, buildDevicePanelFromRun(backend, result));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function getCurrentDeviceBackend(): DeviceBackendInfo {
|
|
127
|
+
if (process.platform === "darwin") {
|
|
128
|
+
return {
|
|
129
|
+
backend: "avfoundation",
|
|
130
|
+
sourceLabel: "macOS · AVF",
|
|
131
|
+
args: ["-hide_banner", "-f", "avfoundation", "-list_devices", "true", "-i", ""],
|
|
132
|
+
includeVideo: true,
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
if (process.platform === "linux") {
|
|
137
|
+
return {
|
|
138
|
+
backend: "pulse",
|
|
139
|
+
sourceLabel: "Linux · Pulse",
|
|
140
|
+
args: ["-hide_banner", "-sources", "pulse"],
|
|
141
|
+
includeVideo: false,
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (process.platform === "win32") {
|
|
146
|
+
return {
|
|
147
|
+
backend: "dshow",
|
|
148
|
+
sourceLabel: "Windows · DShow",
|
|
149
|
+
args: ["-hide_banner", "-list_devices", "true", "-f", "dshow", "-i", "dummy"],
|
|
150
|
+
includeVideo: true,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
return { backend: "unsupported", sourceLabel: `${process.platform} · unsupported`, includeVideo: false };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function buildDevicePanelFromRun(backend: Extract<DeviceBackendInfo, { args: string[] }>, result: RunResult): DevicePanelOptions {
|
|
158
|
+
const output = combineRunOutput(result);
|
|
159
|
+
const parsed = parseDeviceInventory(backend.backend, output);
|
|
160
|
+
const hasDevices = parsed.audio.length > 0 || parsed.video.length > 0;
|
|
161
|
+
|
|
162
|
+
if (result.timedOut) {
|
|
163
|
+
return {
|
|
164
|
+
sourceLabel: backend.sourceLabel,
|
|
165
|
+
backend: backend.backend,
|
|
166
|
+
errorLines: ["Device scan timed out", "FFmpeg did not return device information within 8s."],
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
if (!hasDevices && backend.backend === "avfoundation" && hasMacosPermissionIssue(output)) {
|
|
171
|
+
return {
|
|
172
|
+
sourceLabel: backend.sourceLabel,
|
|
173
|
+
backend: backend.backend,
|
|
174
|
+
errorLines: ["macOS microphone permission may be blocked", "Allow microphone access for the terminal app, then try again."],
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
if (!hasDevices && result.code !== 0) {
|
|
179
|
+
return {
|
|
180
|
+
sourceLabel: backend.sourceLabel,
|
|
181
|
+
backend: backend.backend,
|
|
182
|
+
audio: parsed.audio,
|
|
183
|
+
video: parsed.video,
|
|
184
|
+
includeVideo: backend.includeVideo,
|
|
185
|
+
errorLines: [getNoParseableDeviceMessage(backend.backend)],
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
return {
|
|
190
|
+
sourceLabel: backend.sourceLabel,
|
|
191
|
+
backend: backend.backend,
|
|
192
|
+
audio: parsed.audio,
|
|
193
|
+
video: parsed.video,
|
|
194
|
+
includeVideo: backend.includeVideo,
|
|
195
|
+
warning: getDeviceScanWarning(backend.backend, result, output, hasDevices),
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function combineRunOutput(result: RunResult) {
|
|
200
|
+
return `${result.stdout || ""}\n${result.stderr || ""}`;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function parseDeviceInventory(backend: Exclude<DeviceBackend, "unsupported">, output: string): ParsedDeviceInventory {
|
|
204
|
+
if (backend === "avfoundation") return parseAvfoundationDevices(output);
|
|
205
|
+
if (backend === "pulse") return parsePulseAudioDevices(output);
|
|
206
|
+
return parseDirectShowDevices(output);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export function parseAvfoundationDevices(output: string): ParsedDeviceInventory {
|
|
210
|
+
const inventory: ParsedDeviceInventory = { audio: [], video: [], sawDeviceSection: false };
|
|
211
|
+
let section: DeviceKind | undefined;
|
|
212
|
+
|
|
213
|
+
for (const line of output.split(/\r?\n/)) {
|
|
214
|
+
if (line.includes("AVFoundation video devices:")) {
|
|
215
|
+
section = "video";
|
|
216
|
+
inventory.sawDeviceSection = true;
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
if (line.includes("AVFoundation audio devices:")) {
|
|
220
|
+
section = "audio";
|
|
221
|
+
inventory.sawDeviceSection = true;
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
if (!section) continue;
|
|
225
|
+
|
|
226
|
+
const match = line.match(/\[(\d+)\]\s+(.+)$/);
|
|
227
|
+
if (!match) continue;
|
|
228
|
+
const id = match[1] ?? "";
|
|
229
|
+
const name = (match[2] ?? "").trim();
|
|
230
|
+
if (!name) continue;
|
|
231
|
+
inventory[section].push({ id, name });
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
return inventory;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function parsePulseAudioDevices(output: string): ParsedDeviceInventory {
|
|
238
|
+
const inventory: ParsedDeviceInventory = { audio: [], video: [], sawDeviceSection: false };
|
|
239
|
+
let inSources = false;
|
|
240
|
+
|
|
241
|
+
for (const rawLine of output.split(/\r?\n/)) {
|
|
242
|
+
const line = stripFfmpegLogPrefix(rawLine).trim();
|
|
243
|
+
if (/Auto-detected sources for pulse|sources for pulse/i.test(line)) {
|
|
244
|
+
inSources = true;
|
|
245
|
+
inventory.sawDeviceSection = true;
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
if (!inSources || !line || /^(Cannot|Error|Failed|Unknown)\b/i.test(line)) continue;
|
|
249
|
+
|
|
250
|
+
const sourceLine = line.replace(/^\*\s*/, "");
|
|
251
|
+
const match = sourceLine.match(/^([^\s\[]+)(?:\s+\[(.+)\])?$/);
|
|
252
|
+
if (!match) continue;
|
|
253
|
+
const id = (match[1] ?? "").trim();
|
|
254
|
+
if (!id || id.includes(":")) continue;
|
|
255
|
+
let name = (match[2] ?? "").trim();
|
|
256
|
+
if (id === "default" && (!name || /^default$/i.test(name))) name = "PulseAudio default source";
|
|
257
|
+
inventory.audio.push({ id, name });
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
return inventory;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function parseDirectShowDevices(output: string): ParsedDeviceInventory {
|
|
264
|
+
const inventory: ParsedDeviceInventory = { audio: [], video: [], sawDeviceSection: false };
|
|
265
|
+
let section: DeviceKind | undefined;
|
|
266
|
+
|
|
267
|
+
for (const rawLine of output.split(/\r?\n/)) {
|
|
268
|
+
const line = stripFfmpegLogPrefix(rawLine).trim();
|
|
269
|
+
if (/DirectShow video devices/i.test(line)) {
|
|
270
|
+
section = "video";
|
|
271
|
+
inventory.sawDeviceSection = true;
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
if (/DirectShow audio devices/i.test(line)) {
|
|
275
|
+
section = "audio";
|
|
276
|
+
inventory.sawDeviceSection = true;
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
if (!section || /Alternative name/i.test(line)) continue;
|
|
280
|
+
|
|
281
|
+
const match = line.match(/^"(.+)"$/) ?? line.match(/"([^"]+)"/);
|
|
282
|
+
const name = (match?.[1] ?? "").trim();
|
|
283
|
+
if (!name) continue;
|
|
284
|
+
inventory[section].push({ name });
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
return inventory;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function stripFfmpegLogPrefix(line: string) {
|
|
291
|
+
return line.replace(/^(?:\[[^\]]+\]\s*)+/, "");
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function hasMacosPermissionIssue(output: string) {
|
|
295
|
+
return /(?:not authorized|authorization|privacy|permission|operation not permitted|microphone access|access.*microphone|microphone.*blocked)/i.test(output);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function getDeviceScanWarning(backend: Exclude<DeviceBackend, "unsupported">, result: RunResult, output: string, hasDevices: boolean) {
|
|
299
|
+
if (!hasDevices) return undefined;
|
|
300
|
+
if (backend === "avfoundation" && hasAvfoundationIoWarning(output)) return "AVFoundation I/O warning after scan";
|
|
301
|
+
if (backend === "dshow" && /Immediate exit requested/i.test(output)) return undefined;
|
|
302
|
+
if (result.code !== 0 || result.signal) return `${getBackendLongName(backend)} warning after scan`;
|
|
303
|
+
if (hasFfmpegWarningAfterScan(output)) return `${getBackendLongName(backend)} warning after scan`;
|
|
304
|
+
return undefined;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function hasAvfoundationIoWarning(output: string) {
|
|
308
|
+
return /(?:Input\/output error|I\/O error|Error opening input|Error opening input file|Error opening input files)/i.test(output);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function hasFfmpegWarningAfterScan(output: string) {
|
|
312
|
+
return /\b(?:warning|error|failed|cannot|unable)\b/i.test(output);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function getNoParseableDeviceMessage(backend: Exclude<DeviceBackend, "unsupported">) {
|
|
316
|
+
if (backend === "avfoundation") return "No parseable AVFoundation device output";
|
|
317
|
+
if (backend === "pulse") return "No parseable PulseAudio source output";
|
|
318
|
+
return "No parseable DirectShow device output";
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function getBackendLongName(backend: Exclude<DeviceBackend, "unsupported">) {
|
|
322
|
+
if (backend === "avfoundation") return "AVFoundation";
|
|
323
|
+
if (backend === "pulse") return "PulseAudio";
|
|
324
|
+
return "DirectShow";
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
async function showDevicePanel(ctx: ExtensionContext, pi: ExtensionAPI | undefined, options: DevicePanelOptions) {
|
|
328
|
+
if (sendDevicePanelMessage(pi, options)) return;
|
|
329
|
+
ctx.ui.setWidget(DEVICE_PANEL_MESSAGE_TYPE, renderDevicePanel(options).split("\n"));
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function sendDevicePanelMessage(pi: ExtensionAPI | undefined, options: DevicePanelOptions) {
|
|
333
|
+
const api = pi as (ExtensionAPI & DeviceMessageApi) | undefined;
|
|
334
|
+
if (!deviceMessageRendererRegistered || !api?.sendMessage) return false;
|
|
335
|
+
api.sendMessage({ customType: DEVICE_PANEL_MESSAGE_TYPE, content: "Micme devices", display: true, details: options });
|
|
336
|
+
return true;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
class DevicePanelMessageComponent implements Component {
|
|
340
|
+
constructor(private readonly options: DevicePanelOptions) {}
|
|
341
|
+
|
|
342
|
+
render(width: number): string[] {
|
|
343
|
+
return renderDevicePanel(this.options, Math.min(width, DEVICE_PANEL_MAX_WIDTH)).split("\n");
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
invalidate(): void {}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function readDevicePanelOptions(value: unknown): DevicePanelOptions {
|
|
350
|
+
if (!isDevicePanelOptions(value)) {
|
|
351
|
+
return {
|
|
352
|
+
sourceLabel: "unknown · unsupported",
|
|
353
|
+
backend: "unsupported",
|
|
354
|
+
errorLines: ["Could not render Micme devices panel"],
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
return value;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function isDevicePanelOptions(value: unknown): value is DevicePanelOptions {
|
|
361
|
+
if (!value || typeof value !== "object") return false;
|
|
362
|
+
const candidate = value as DevicePanelOptions;
|
|
363
|
+
return typeof candidate.sourceLabel === "string" && isDeviceBackend(candidate.backend);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function isDeviceBackend(value: unknown): value is DeviceBackend {
|
|
367
|
+
return value === "avfoundation" || value === "pulse" || value === "dshow" || value === "unsupported";
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
export function renderDevicePanel(options: DevicePanelOptions, width = getDevicePanelWidth()) {
|
|
371
|
+
const style = getDevicePanelStyle();
|
|
372
|
+
const panelWidth = Math.max(2, Math.floor(width));
|
|
373
|
+
const lines = [buildDevicePanelHeader(panelWidth, options.sourceLabel, style)];
|
|
374
|
+
const hasInventory = options.audio !== undefined || options.video !== undefined || !options.errorLines?.length;
|
|
375
|
+
|
|
376
|
+
if (hasInventory) {
|
|
377
|
+
lines.push(buildDeviceRow("audio", options.audio ?? [], style, panelWidth));
|
|
378
|
+
if (options.includeVideo) lines.push(buildDeviceRow("video", options.video ?? [], style, panelWidth));
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
if (options.warning) lines.push(buildStatusRow("warning", options.warning, style, panelWidth));
|
|
382
|
+
for (const [index, line] of (options.errorLines ?? []).entries()) {
|
|
383
|
+
lines.push(buildErrorRow(line, index === 0, style, panelWidth));
|
|
384
|
+
}
|
|
385
|
+
lines.push(buildDevicePanelFooter(panelWidth, style));
|
|
386
|
+
|
|
387
|
+
return lines.filter(Boolean).join("\n");
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
function getDevicePanelWidth() {
|
|
391
|
+
const columns = process.stdout.columns;
|
|
392
|
+
if (Number.isFinite(columns) && columns > 0) {
|
|
393
|
+
const capped = Math.min(columns, DEVICE_PANEL_MAX_WIDTH);
|
|
394
|
+
return capped < DEVICE_PANEL_MIN_WIDTH ? Math.max(2, capped) : capped;
|
|
395
|
+
}
|
|
396
|
+
return DEVICE_PANEL_DEFAULT_WIDTH;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
function getDevicePanelStyle(): DevicePanelStyle {
|
|
400
|
+
const plain = shouldUsePlainDevicePanel();
|
|
401
|
+
return {
|
|
402
|
+
plain,
|
|
403
|
+
separator: plain ? " | " : " │ ",
|
|
404
|
+
audioLabel: plain ? "audio" : "🎙",
|
|
405
|
+
videoLabel: plain ? "video" : "🎥",
|
|
406
|
+
warningLabel: plain ? "warn" : "⚠",
|
|
407
|
+
errorLabel: plain ? "error" : "✕",
|
|
408
|
+
ellipsis: plain ? "..." : "…",
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
function shouldUsePlainDevicePanel() {
|
|
413
|
+
const locale = [process.env.LC_ALL, process.env.LC_CTYPE, process.env.LANG].filter(Boolean).join(" ");
|
|
414
|
+
return envFlag("MICME_PLAIN") || envFlag("MICME_ASCII") || envFlag("MICME_NO_UNICODE") || process.env.TERM === "dumb" || (locale.length > 0 && !/utf-?8/i.test(locale));
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function formatSourceLabel(sourceLabel: string, style: DevicePanelStyle) {
|
|
418
|
+
return style.plain ? sourceLabel.replace(/\s*·\s*/g, " - ") : sourceLabel;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
function buildDevicePanelHeader(width: number, sourceLabel: string, style: DevicePanelStyle) {
|
|
422
|
+
const title = "Micme devices";
|
|
423
|
+
if (width < 18) return fitLine(style.plain ? `+-- ${title}` : `╭─ ${title}`, width, style);
|
|
424
|
+
|
|
425
|
+
const overhead = style.plain ? 10 : 8;
|
|
426
|
+
const availableTextWidth = Math.max(1, width - overhead - 1);
|
|
427
|
+
const sourceBudget = Math.max(4, Math.min(visibleWidth(sourceLabel), Math.floor(availableTextWidth * 0.45)));
|
|
428
|
+
let source = ellipsize(formatSourceLabel(sourceLabel, style), sourceBudget, style);
|
|
429
|
+
let titleText = ellipsize(title, Math.max(4, availableTextWidth - visibleWidth(source)), style);
|
|
430
|
+
if (visibleWidth(titleText) + visibleWidth(source) > availableTextWidth) {
|
|
431
|
+
source = ellipsize(source, Math.max(1, availableTextWidth - visibleWidth(titleText)), style);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
const fillerWidth = Math.max(1, width - overhead - visibleWidth(titleText) - visibleWidth(source));
|
|
435
|
+
const filler = (style.plain ? "-" : "─").repeat(fillerWidth);
|
|
436
|
+
return style.plain ? `+-- ${titleText} ${filler} ${source} --+` : `╭─ ${titleText} ${filler} ${source} ─╮`;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function buildDevicePanelFooter(width: number, style: DevicePanelStyle) {
|
|
440
|
+
if (width < 2) return style.plain ? "+" : "╰";
|
|
441
|
+
const horizontal = (style.plain ? "-" : "─").repeat(Math.max(0, width - 2));
|
|
442
|
+
return style.plain ? `+${horizontal}+` : `╰${horizontal}╯`;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function buildDeviceRow(kind: DeviceKind, devices: ListedDevice[], style: DevicePanelStyle, width: number) {
|
|
446
|
+
const prefix = style.plain ? ` ${kind.padEnd(5)} ${devices.length}` : ` ${kind === "audio" ? style.audioLabel : style.videoLabel} ${devices.length}`;
|
|
447
|
+
if (devices.length === 0) return fitLine(`${prefix}${style.separator}no ${kind} devices found`, width, style);
|
|
448
|
+
|
|
449
|
+
const displayNames = compactDeviceNames(devices);
|
|
450
|
+
let row = prefix;
|
|
451
|
+
let shown = 0;
|
|
452
|
+
|
|
453
|
+
for (let index = 0; index < devices.length; index++) {
|
|
454
|
+
const remainingAfter = devices.length - index - 1;
|
|
455
|
+
const overflow = remainingAfter > 0 ? `${style.separator}+${remainingAfter} more` : "";
|
|
456
|
+
const chip = formatDeviceChip(devices[index]!, displayNames[index]!);
|
|
457
|
+
const candidate = `${row}${style.separator}${chip}${overflow}`;
|
|
458
|
+
if (visibleWidth(candidate) <= width) {
|
|
459
|
+
row = `${row}${style.separator}${chip}`;
|
|
460
|
+
shown = index + 1;
|
|
461
|
+
continue;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
const availableForChip = width - visibleWidth(`${row}${style.separator}${overflow}`);
|
|
465
|
+
if (availableForChip >= getMinimumDeviceChipWidth(devices[index]!)) {
|
|
466
|
+
row = `${row}${style.separator}${truncateDeviceChip(devices[index]!, displayNames[index]!, availableForChip, style)}`;
|
|
467
|
+
shown = index + 1;
|
|
468
|
+
}
|
|
469
|
+
break;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
const hidden = devices.length - shown;
|
|
473
|
+
if (hidden > 0) {
|
|
474
|
+
const overflow = `${style.separator}+${hidden} more`;
|
|
475
|
+
if (visibleWidth(`${row}${overflow}`) <= width) row = `${row}${overflow}`;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
return fitLine(row, width, style);
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
function buildStatusRow(kind: "warning", message: string, style: DevicePanelStyle, width: number) {
|
|
482
|
+
if (style.plain) return fitLine(` ${style.warningLabel.padEnd(7)}${style.separator}${message}`, width, style);
|
|
483
|
+
return fitLine(` ${kind === "warning" ? style.warningLabel : "✓"} ${message}`, width, style);
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
function buildErrorRow(message: string, primary: boolean, style: DevicePanelStyle, width: number) {
|
|
487
|
+
if (style.plain) return fitLine(` ${(primary ? style.errorLabel : "").padEnd(7)}${style.separator}${message}`, width, style);
|
|
488
|
+
return fitLine(primary ? ` ${style.errorLabel} ${message}` : ` ${message}`, width, style);
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
function compactDeviceNames(devices: ListedDevice[]) {
|
|
492
|
+
const originals = devices.map((device) => device.name || (device.id ? "" : "unknown"));
|
|
493
|
+
const proposed = originals.map((name) => (name ? compactLowValueDevicePrefix(name) : ""));
|
|
494
|
+
const counts = new Map<string, number>();
|
|
495
|
+
for (const name of proposed) {
|
|
496
|
+
if (name) counts.set(name.toLowerCase(), (counts.get(name.toLowerCase()) ?? 0) + 1);
|
|
497
|
+
}
|
|
498
|
+
return devices.map((device, index) => {
|
|
499
|
+
const compacted = proposed[index] || originals[index] || "";
|
|
500
|
+
if (compacted !== device.name && compacted && counts.get(compacted.toLowerCase()) === 1) return compacted;
|
|
501
|
+
return originals[index] || "";
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
function compactLowValueDevicePrefix(name: string) {
|
|
506
|
+
return name
|
|
507
|
+
.replace(/^Microsoft\s+Teams\s+Audio$/i, "Teams Audio")
|
|
508
|
+
.replace(/^Microsoft\s+Teams\b/i, "Teams")
|
|
509
|
+
.replace(/^Microsoft\s+/i, "")
|
|
510
|
+
.trim();
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
function formatDeviceChip(device: ListedDevice, displayName: string) {
|
|
514
|
+
const id = device.id?.trim();
|
|
515
|
+
if (!id) return displayName;
|
|
516
|
+
return displayName ? `${id} ${displayName}` : id;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
function truncateDeviceChip(device: ListedDevice, displayName: string, width: number, style: DevicePanelStyle) {
|
|
520
|
+
const id = device.id?.trim();
|
|
521
|
+
if (!id) return ellipsize(displayName, width, style);
|
|
522
|
+
if (visibleWidth(id) >= width) return ellipsize(id, width, style);
|
|
523
|
+
const prefix = `${id} `;
|
|
524
|
+
const nameWidth = width - visibleWidth(prefix);
|
|
525
|
+
if (nameWidth <= 0) return id;
|
|
526
|
+
return `${prefix}${ellipsize(displayName, nameWidth, style)}`;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
function getMinimumDeviceChipWidth(device: ListedDevice) {
|
|
530
|
+
const id = device.id?.trim();
|
|
531
|
+
if (id) return device.name ? visibleWidth(id) + 2 : visibleWidth(id);
|
|
532
|
+
return Math.min(4, Math.max(1, visibleWidth(device.name || "unknown")));
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
function fitLine(line: string, width: number, style: DevicePanelStyle) {
|
|
536
|
+
return visibleWidth(line) <= width ? line : ellipsize(line, width, style);
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
function ellipsize(value: string, width: number, style: DevicePanelStyle) {
|
|
540
|
+
if (width <= 0) return "";
|
|
541
|
+
if (visibleWidth(value) <= width) return value;
|
|
542
|
+
const ellipsisWidth = visibleWidth(style.ellipsis);
|
|
543
|
+
if (width <= ellipsisWidth) return sliceByColumn(style.ellipsis, 0, width) || ".".repeat(width);
|
|
544
|
+
let truncated = sliceByColumn(value, 0, width - ellipsisWidth).trimEnd();
|
|
545
|
+
while (truncated && visibleWidth(`${truncated}${style.ellipsis}`) > width) {
|
|
546
|
+
truncated = sliceByColumn(truncated, 0, Math.max(0, visibleWidth(truncated) - 1)).trimEnd();
|
|
547
|
+
}
|
|
548
|
+
return `${truncated || sliceByColumn(value, 0, Math.max(0, width - ellipsisWidth))}${style.ellipsis}`;
|
|
33
549
|
}
|
|
34
550
|
|
|
35
551
|
export async function discoverAudioDevices(): Promise<AudioDeviceCandidate[]> {
|
|
@@ -37,7 +553,7 @@ export async function discoverAudioDevices(): Promise<AudioDeviceCandidate[]> {
|
|
|
37
553
|
if (!ffmpeg) return [];
|
|
38
554
|
|
|
39
555
|
if (process.platform === "darwin") {
|
|
40
|
-
const result = await runProcess(ffmpeg, ["-hide_banner", "-f", "avfoundation", "-list_devices", "true", "-i", ""],
|
|
556
|
+
const result = await runProcess(ffmpeg, ["-hide_banner", "-f", "avfoundation", "-list_devices", "true", "-i", ""], DEVICE_SCAN_TIMEOUT_MS);
|
|
41
557
|
return parseAvfoundationAudioDevices(`${result.stdout}\n${result.stderr}`);
|
|
42
558
|
}
|
|
43
559
|
|
|
@@ -53,22 +569,11 @@ export async function discoverAudioDevices(): Promise<AudioDeviceCandidate[]> {
|
|
|
53
569
|
}
|
|
54
570
|
|
|
55
571
|
export function parseAvfoundationAudioDevices(output: string): AudioDeviceCandidate[] {
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
continue;
|
|
62
|
-
}
|
|
63
|
-
if (inAudioDevices && line.includes("Error opening input")) break;
|
|
64
|
-
if (!inAudioDevices) continue;
|
|
65
|
-
const match = line.match(/\[(\d+)\]\s+(.+)$/);
|
|
66
|
-
if (!match) continue;
|
|
67
|
-
const value = match[1] ?? "";
|
|
68
|
-
const name = (match[2] ?? "").trim();
|
|
69
|
-
devices.push({ label: `${value}: ${name}`, value, description: name });
|
|
70
|
-
}
|
|
71
|
-
return devices;
|
|
572
|
+
return parseAvfoundationDevices(output).audio.map((device) => ({
|
|
573
|
+
label: `${device.id ?? ""}: ${device.name}`,
|
|
574
|
+
value: device.id ?? "",
|
|
575
|
+
description: device.name,
|
|
576
|
+
}));
|
|
72
577
|
}
|
|
73
578
|
|
|
74
579
|
export async function prepareAudioForTranscription(inputPath: string, tempDir: string) {
|
package/src/config.ts
CHANGED
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
DEFAULT_STREAM_MAX_TOKENS,
|
|
14
14
|
DEFAULT_STREAM_STEP_MS,
|
|
15
15
|
DEFAULT_STREAM_VAD_THRESHOLD,
|
|
16
|
+
DEFAULT_STREAM_FLUSH_MS,
|
|
16
17
|
DEFAULT_TRANSCRIBE_SAMPLE_RATE,
|
|
17
18
|
DEFAULT_TRANSCRIBE_TIMEOUT_MS,
|
|
18
19
|
DEFAULT_MIN_MAX_VOLUME_DB,
|
|
@@ -22,6 +23,7 @@ import {
|
|
|
22
23
|
STREAM_PROFILE_STEP_MS,
|
|
23
24
|
STREAM_PROFILE_VAD_THRESHOLD,
|
|
24
25
|
STREAM_PROFILE_WORDS_PER_CHUNK,
|
|
26
|
+
STREAM_PROFILE_FLUSH_MS,
|
|
25
27
|
} from "./constants.ts";
|
|
26
28
|
|
|
27
29
|
const MICME_CONFIG_FILE = "micme.json";
|
|
@@ -106,7 +108,9 @@ export function getTranscriptionModeProfile(mode: TranscriptionMode): Record<str
|
|
|
106
108
|
MICME_STREAM_KEEP_MS: String(STREAM_PROFILE_KEEP_MS),
|
|
107
109
|
MICME_STREAM_MAX_TOKENS: String(STREAM_PROFILE_MAX_TOKENS),
|
|
108
110
|
MICME_STREAM_WORDS_PER_CHUNK: String(STREAM_PROFILE_WORDS_PER_CHUNK),
|
|
109
|
-
|
|
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",
|
|
110
114
|
MICME_STREAM_FINALIZE_WITH_CLIP: "0",
|
|
111
115
|
MICME_STREAM_VAD_THRESHOLD: String(STREAM_PROFILE_VAD_THRESHOLD),
|
|
112
116
|
};
|
|
@@ -119,7 +123,8 @@ export function getTranscriptionModeProfile(mode: TranscriptionMode): Record<str
|
|
|
119
123
|
MICME_STREAM_KEEP_MS: String(DEFAULT_STREAM_KEEP_MS),
|
|
120
124
|
MICME_STREAM_MAX_TOKENS: String(DEFAULT_STREAM_MAX_TOKENS),
|
|
121
125
|
MICME_STREAM_WORDS_PER_CHUNK: "10",
|
|
122
|
-
|
|
126
|
+
MICME_STREAM_FLUSH_MS: String(DEFAULT_STREAM_FLUSH_MS),
|
|
127
|
+
MICME_STREAM_KEEP_CONTEXT: "0",
|
|
123
128
|
MICME_STREAM_FINALIZE_WITH_CLIP: "1",
|
|
124
129
|
MICME_STREAM_VAD_THRESHOLD: String(DEFAULT_STREAM_VAD_THRESHOLD),
|
|
125
130
|
};
|
|
@@ -196,12 +201,17 @@ export function getStreamVadThreshold() {
|
|
|
196
201
|
|
|
197
202
|
export function getStreamKeepContext() {
|
|
198
203
|
const value = env("MICME_STREAM_KEEP_CONTEXT");
|
|
199
|
-
return value === undefined ?
|
|
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;
|
|
200
210
|
}
|
|
201
211
|
|
|
202
212
|
export function getStreamFinalizeWithClip() {
|
|
203
213
|
const value = env("MICME_STREAM_FINALIZE_WITH_CLIP");
|
|
204
|
-
return value === undefined ?
|
|
214
|
+
return value === undefined ? false : /^(1|true|yes|on)$/i.test(value);
|
|
205
215
|
}
|
|
206
216
|
|
|
207
217
|
export function getStreamWordsPerChunk() {
|
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 =
|
|
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
|
@@ -12,7 +12,7 @@ import {
|
|
|
12
12
|
getTranscriptionMode,
|
|
13
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 {
|
|
@@ -52,6 +52,7 @@ let lastShortcutInputAt = 0;
|
|
|
52
52
|
|
|
53
53
|
export default function micmeExtension(pi: ExtensionAPI) {
|
|
54
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);
|
|
@@ -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 = {
|
|
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
|
|
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,13 +12,13 @@ import {
|
|
|
12
12
|
truncateToWidth,
|
|
13
13
|
visibleWidth,
|
|
14
14
|
} from "@earendil-works/pi-tui";
|
|
15
|
-
import { homedir } from "node:os";
|
|
16
15
|
import { basename } from "node:path";
|
|
17
16
|
import {
|
|
18
17
|
DEFAULT_MACOS_PRINTABLE_SHORTCUT,
|
|
19
18
|
DEFAULT_RECORD_SAMPLE_RATE,
|
|
20
19
|
DEFAULT_SHORTCUT,
|
|
21
20
|
DEFAULT_STREAM_VAD_THRESHOLD,
|
|
21
|
+
DEFAULT_STREAM_FLUSH_MS,
|
|
22
22
|
DEFAULT_TRANSCRIBE_SAMPLE_RATE,
|
|
23
23
|
DEFAULT_WHISPER_CPP_MODEL_NAME,
|
|
24
24
|
PYTHON_WHISPER_MODEL_NAMES,
|
|
@@ -27,7 +27,6 @@ import {
|
|
|
27
27
|
import {
|
|
28
28
|
env,
|
|
29
29
|
expandConfigPath,
|
|
30
|
-
getMicmeConfigPath,
|
|
31
30
|
getTranscriptionMode,
|
|
32
31
|
getTranscriptionModeProfile,
|
|
33
32
|
reloadMicmeConfig,
|
|
@@ -659,20 +658,30 @@ export function buildConfigurationItems(modelCandidates: ModelCandidate[], audio
|
|
|
659
658
|
id: "MICME_STREAM_KEEP_CONTEXT",
|
|
660
659
|
categoryId: "streaming",
|
|
661
660
|
label: "Stream context",
|
|
662
|
-
description: "Keep Whisper prompt context between chunks for
|
|
663
|
-
rawValue: env("MICME_STREAM_KEEP_CONTEXT") ?? "
|
|
664
|
-
currentValue: env("MICME_STREAM_KEEP_CONTEXT") ?? "
|
|
665
|
-
values: ["
|
|
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"],
|
|
666
665
|
displayKind: "boolean",
|
|
667
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
|
+
},
|
|
668
677
|
{
|
|
669
678
|
id: "MICME_STREAM_FINALIZE_WITH_CLIP",
|
|
670
679
|
categoryId: "streaming",
|
|
671
680
|
label: "Stream final pass",
|
|
672
|
-
description: "
|
|
673
|
-
rawValue: env("MICME_STREAM_FINALIZE_WITH_CLIP") ?? "
|
|
674
|
-
currentValue: env("MICME_STREAM_FINALIZE_WITH_CLIP") ?? "
|
|
675
|
-
values: ["
|
|
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"],
|
|
676
685
|
displayKind: "boolean",
|
|
677
686
|
},
|
|
678
687
|
{
|
|
@@ -802,7 +811,7 @@ export function buildConfigurationItems(modelCandidates: ModelCandidate[], audio
|
|
|
802
811
|
id: "MICME_STREAM_DIAGNOSTICS",
|
|
803
812
|
categoryId: "diagnostics",
|
|
804
813
|
label: "Stream diagnostics",
|
|
805
|
-
description: "Show
|
|
814
|
+
description: "Show opt-in whisper-stream frame/state diagnostics and first-output timing notifications.",
|
|
806
815
|
rawValue: env("MICME_STREAM_DIAGNOSTICS") ?? "0",
|
|
807
816
|
currentValue: env("MICME_STREAM_DIAGNOSTICS") ?? "0",
|
|
808
817
|
values: ["0", "1"],
|
|
@@ -860,19 +869,6 @@ export async function saveConfigurationValue(ctx: ExtensionContext, id: string,
|
|
|
860
869
|
await writeMicmeConfigValues(valuesToWrite);
|
|
861
870
|
reloadMicmeConfig();
|
|
862
871
|
|
|
863
|
-
const configLabel = formatConfigPathForMessage(getMicmeConfigPath());
|
|
864
|
-
const overriddenKeys = Object.keys(valuesToWrite).filter((key) => process.env[key] !== undefined);
|
|
865
|
-
if (id === "MICME_TRANSCRIPTION_MODE") {
|
|
866
|
-
const mode = valuesToWrite.MICME_TRANSCRIPTION_MODE === "stream" ? "stream" : "clip";
|
|
867
|
-
const detail = mode === "stream" ? "low-latency stream profile" : "stable clip profile";
|
|
868
|
-
const sourceSuffix = overriddenKeys.length ? `; shell env still overrides ${overriddenKeys.join(", ")}` : ` (${configLabel})`;
|
|
869
|
-
ctx.ui.notify(`Saved ${mode} mode and applied ${detail}${sourceSuffix}.`, overriddenKeys.length ? "warning" : "info");
|
|
870
|
-
} else {
|
|
871
|
-
const overrideSuffix = overriddenKeys.includes(id) ? `, but shell env still overrides ${id}` : ` (${configLabel})`;
|
|
872
|
-
const reloadSuffix = id === "MICME_SHORTCUT" ? " • /reload required" : id === "MICME_PRINTABLE_SHORTCUTS" ? " • /reload recommended" : "";
|
|
873
|
-
ctx.ui.notify(`Saved ${id}=${displayConfigurationValue(id, value)}${overrideSuffix}${reloadSuffix}`, overriddenKeys.includes(id) ? "warning" : "info");
|
|
874
|
-
}
|
|
875
|
-
|
|
876
872
|
const effectiveValues: Record<string, string> = {};
|
|
877
873
|
for (const key of Object.keys(valuesToWrite)) effectiveValues[key] = env(key) ?? "";
|
|
878
874
|
return effectiveValues;
|
|
@@ -899,24 +895,11 @@ export function uniqueStrings(values: string[]) {
|
|
|
899
895
|
function formatSaveStatus(id: string, value: string) {
|
|
900
896
|
const writtenKeys = id === "MICME_TRANSCRIPTION_MODE" ? Object.keys(getTranscriptionModeProfile(value === "stream" ? "stream" : "clip")) : [id];
|
|
901
897
|
const overriddenKeys = writtenKeys.filter((key) => process.env[key] !== undefined);
|
|
902
|
-
const
|
|
903
|
-
if (id === "MICME_TRANSCRIPTION_MODE") {
|
|
904
|
-
const mode = value === "stream" ? "stream" : "clip";
|
|
905
|
-
const detail = mode === "stream" ? "low-latency stream profile" : "stable clip profile";
|
|
906
|
-
const sourceSuffix = overriddenKeys.length ? ` • shell env still overrides ${overriddenKeys.join(", ")}` : ` • ${configLabel}`;
|
|
907
|
-
return `Saved MICME_TRANSCRIPTION_MODE=${mode} and applied ${detail}${sourceSuffix}`;
|
|
908
|
-
}
|
|
909
|
-
|
|
910
|
-
const sourceSuffix = overriddenKeys.includes(id) ? `, but shell env still overrides ${id}` : ` (${configLabel})`;
|
|
911
|
-
const reloadSuffix = id === "MICME_SHORTCUT" ? " • /reload required" : id === "MICME_PRINTABLE_SHORTCUTS" ? " • /reload recommended" : "";
|
|
912
|
-
return `Saved ${id}=${displayConfigurationValue(id, value)}${sourceSuffix}${reloadSuffix}`;
|
|
913
|
-
}
|
|
898
|
+
const reloadHint = id === "MICME_SHORTCUT" ? "/reload required for shortcut changes" : id === "MICME_PRINTABLE_SHORTCUTS" ? "/reload recommended for printable shortcuts" : "";
|
|
914
899
|
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
if (home && path.startsWith(`${home}/`)) return `~/${path.slice(home.length + 1)}`;
|
|
919
|
-
return path;
|
|
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;
|
|
920
903
|
}
|
|
921
904
|
|
|
922
905
|
function fitAnsi(text: string, width: number, ellipsis = "…") {
|
package/src/streaming.ts
CHANGED
|
@@ -1,11 +1,9 @@
|
|
|
1
1
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import {
|
|
3
|
-
MAX_CAPTURED_OUTPUT_CHARS,
|
|
4
|
-
STREAM_MIN_INITIAL_WORDS,
|
|
5
|
-
} from "./constants.ts";
|
|
2
|
+
import { MAX_CAPTURED_OUTPUT_CHARS } from "./constants.ts";
|
|
6
3
|
import {
|
|
7
4
|
env,
|
|
8
5
|
envFlag,
|
|
6
|
+
getStreamFlushMs,
|
|
9
7
|
getStreamKeepContext,
|
|
10
8
|
getStreamKeepMs,
|
|
11
9
|
getStreamLengthMs,
|
|
@@ -18,6 +16,22 @@ import { pasteOrSubmitTranscript } from "./transcript-delivery.ts";
|
|
|
18
16
|
import { shellQuote } from "./processes.ts";
|
|
19
17
|
import type { CommandSpec, Recording, StreamingState } from "./types.ts";
|
|
20
18
|
|
|
19
|
+
export type StreamingFrameMode = "cumulative" | "incremental" | "rolling" | "duplicate" | "reset";
|
|
20
|
+
|
|
21
|
+
export type StreamingExtraction = {
|
|
22
|
+
mode: StreamingFrameMode;
|
|
23
|
+
newWords: string[];
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
type StreamingDiagnosticDetails = {
|
|
27
|
+
rawFrame?: string;
|
|
28
|
+
sanitizedText?: string;
|
|
29
|
+
frameWords?: string[];
|
|
30
|
+
extractionMode: StreamingFrameMode | "ignored" | "flush";
|
|
31
|
+
newWords?: string[];
|
|
32
|
+
reason?: string;
|
|
33
|
+
};
|
|
34
|
+
|
|
21
35
|
export function buildWhisperStreamCommand(binary: string, modelPath: string, tempDir: string): CommandSpec {
|
|
22
36
|
const args = [
|
|
23
37
|
"-m",
|
|
@@ -52,25 +66,54 @@ export function handleStreamingOutput(ctx: ExtensionContext, active: Recording,
|
|
|
52
66
|
|
|
53
67
|
export function drainStreamingOutput(ctx: ExtensionContext, active: Recording, force: boolean, chunk = "") {
|
|
54
68
|
if (!active.streaming) return;
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
69
|
+
const state = active.streaming;
|
|
70
|
+
|
|
71
|
+
for (const rawFrame of readStreamingOutputFrames(state, chunk, force)) {
|
|
72
|
+
const sanitizedText = sanitizeStreamingText(rawFrame);
|
|
73
|
+
const frameWords = splitStreamingWords(sanitizedText);
|
|
74
|
+
|
|
75
|
+
if (!sanitizedText) {
|
|
76
|
+
if (shouldResetStreamingPending(rawFrame)) {
|
|
77
|
+
clearStreamingFlush(state);
|
|
78
|
+
state.candidateWords = [];
|
|
79
|
+
state.lastHypothesisWords = [];
|
|
80
|
+
state.lastText = "";
|
|
81
|
+
renderStreamingPreview(ctx, state, false);
|
|
82
|
+
showStreamingFrameDiagnostics(ctx, state, {
|
|
83
|
+
rawFrame,
|
|
84
|
+
sanitizedText,
|
|
85
|
+
frameWords,
|
|
86
|
+
extractionMode: "reset",
|
|
87
|
+
newWords: [],
|
|
88
|
+
reason: "reset/hallucination frame",
|
|
89
|
+
});
|
|
90
|
+
} else {
|
|
91
|
+
showStreamingFrameDiagnostics(ctx, state, {
|
|
92
|
+
rawFrame,
|
|
93
|
+
sanitizedText,
|
|
94
|
+
frameWords,
|
|
95
|
+
extractionMode: "ignored",
|
|
96
|
+
newWords: [],
|
|
97
|
+
reason: "empty frame",
|
|
98
|
+
});
|
|
61
99
|
}
|
|
62
100
|
continue;
|
|
63
101
|
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
renderStreamingPreview(ctx, active.streaming, false);
|
|
70
|
-
continue;
|
|
71
|
-
}
|
|
102
|
+
|
|
103
|
+
clearStreamingFlush(state);
|
|
104
|
+
if (!state.firstOutputAt) state.firstOutputAt = Date.now();
|
|
105
|
+
const extraction = extractStreamingCandidate(state, frameWords);
|
|
106
|
+
state.lastText = sanitizedText;
|
|
72
107
|
active.audioLevel = () => 0.55;
|
|
73
|
-
queueStableStreamingWords(ctx,
|
|
108
|
+
queueStableStreamingWords(ctx, state, extraction.newWords, extraction.mode);
|
|
109
|
+
state.lastHypothesisWords = frameWords;
|
|
110
|
+
showStreamingFrameDiagnostics(ctx, state, {
|
|
111
|
+
rawFrame,
|
|
112
|
+
sanitizedText,
|
|
113
|
+
frameWords,
|
|
114
|
+
extractionMode: extraction.mode,
|
|
115
|
+
newWords: extraction.newWords,
|
|
116
|
+
});
|
|
74
117
|
}
|
|
75
118
|
}
|
|
76
119
|
|
|
@@ -117,6 +160,32 @@ export function diffStreamingText(previous: string, current: string) {
|
|
|
117
160
|
return currentWords.slice(overlap).join(" ");
|
|
118
161
|
}
|
|
119
162
|
|
|
163
|
+
export function extractStreamingCandidate(state: StreamingState, frameWords: string[]): StreamingExtraction {
|
|
164
|
+
const words = frameWords.filter(Boolean);
|
|
165
|
+
if (words.length === 0) return { mode: "reset", newWords: [] };
|
|
166
|
+
|
|
167
|
+
const emittedOverlap = streamingWordOverlap(state.emittedWords.slice(-160), words);
|
|
168
|
+
if (emittedOverlap === words.length) return { mode: "duplicate", newWords: [] };
|
|
169
|
+
if (emittedOverlap > 0) return { mode: "cumulative", newWords: words.slice(emittedOverlap) };
|
|
170
|
+
|
|
171
|
+
if (state.candidateWords.length > 0) {
|
|
172
|
+
if (streamingWordsEqual(state.candidateWords, words)) return { mode: "duplicate", newWords: words };
|
|
173
|
+
if (isStreamingWordsPrefix(state.candidateWords, words)) return { mode: "cumulative", newWords: words };
|
|
174
|
+
if (streamingWordOverlap(state.candidateWords, words) > 0) return { mode: "rolling", newWords: words };
|
|
175
|
+
if (looksLikeStreamingCorrection(state.candidateWords, words)) return { mode: "reset", newWords: words };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
if (state.lastHypothesisWords.length > 0) {
|
|
179
|
+
if (streamingWordsEqual(state.lastHypothesisWords, words)) return { mode: "duplicate", newWords: words };
|
|
180
|
+
if (isStreamingWordsPrefix(state.lastHypothesisWords, words)) return { mode: "cumulative", newWords: trimCommittedStreamingPrefix(state, words) };
|
|
181
|
+
if (streamingWordOverlap(state.lastHypothesisWords, words) > 0) return { mode: "rolling", newWords: words };
|
|
182
|
+
if (looksLikeStreamingCorrection(state.lastHypothesisWords, words)) return { mode: "reset", newWords: words };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const isFirstHypothesis = state.emittedWords.length === 0 && state.candidateWords.length === 0 && state.lastHypothesisWords.length === 0;
|
|
186
|
+
return { mode: isFirstHypothesis ? "cumulative" : "incremental", newWords: words };
|
|
187
|
+
}
|
|
188
|
+
|
|
120
189
|
export function isLikelyStreamingHallucination(text: string) {
|
|
121
190
|
if (!text) return true;
|
|
122
191
|
const normalized = text.toLowerCase().replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, "");
|
|
@@ -133,28 +202,74 @@ export function shouldResetStreamingPending(text: string) {
|
|
|
133
202
|
return /^\[[^\]]+\]$/.test(cleaned) || /^\([^)]*\)$/.test(cleaned);
|
|
134
203
|
}
|
|
135
204
|
|
|
136
|
-
export function queueStableStreamingWords(ctx: ExtensionContext, state: StreamingState, currentWords: string[]) {
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
205
|
+
export function queueStableStreamingWords(ctx: ExtensionContext, state: StreamingState, currentWords: string[], mode: StreamingFrameMode = "cumulative") {
|
|
206
|
+
const words = currentWords.filter(Boolean);
|
|
207
|
+
|
|
208
|
+
if (mode === "reset") {
|
|
209
|
+
state.candidateWords = trimCommittedStreamingPrefix(state, words);
|
|
210
|
+
renderStreamingPreview(ctx, state, false);
|
|
211
|
+
scheduleStreamingFlush(ctx, state);
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
if (mode === "incremental") {
|
|
216
|
+
commitStreamingCandidate(state);
|
|
217
|
+
state.candidateWords = trimCommittedStreamingPrefix(state, words);
|
|
218
|
+
renderStreamingPreview(ctx, state, false);
|
|
219
|
+
scheduleStreamingFlush(ctx, state);
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
if (mode === "rolling") {
|
|
224
|
+
queueRollingStreamingWords(state, words);
|
|
225
|
+
renderStreamingPreview(ctx, state, false);
|
|
226
|
+
scheduleStreamingFlush(ctx, state);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
if (mode === "duplicate" && words.length === 0) {
|
|
231
|
+
renderStreamingPreview(ctx, state, false);
|
|
232
|
+
scheduleStreamingFlush(ctx, state);
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const stableCount = commonStreamingPrefixLength(state.candidateWords, words);
|
|
237
|
+
const confirmedCount = Math.min(stableCount, getStreamWordsPerChunk());
|
|
238
|
+
if (confirmedCount > 0) queueStreamingWords(state, words.slice(0, confirmedCount));
|
|
239
|
+
state.candidateWords = words.slice(confirmedCount);
|
|
143
240
|
renderStreamingPreview(ctx, state, false);
|
|
241
|
+
scheduleStreamingFlush(ctx, state);
|
|
144
242
|
}
|
|
145
243
|
|
|
146
|
-
export function flushPendingStreamingWords(ctx: ExtensionContext, state: StreamingState) {
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
244
|
+
export function flushPendingStreamingWords(ctx: ExtensionContext, state: StreamingState, trailingSpace = true) {
|
|
245
|
+
clearStreamingFlush(state);
|
|
246
|
+
commitStreamingCandidate(state);
|
|
247
|
+
renderStreamingPreview(ctx, state, trailingSpace);
|
|
248
|
+
showStreamingFrameDiagnostics(ctx, state, {
|
|
249
|
+
extractionMode: "flush",
|
|
250
|
+
newWords: [],
|
|
251
|
+
reason: trailingSpace ? "stop flush" : "pause flush",
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export function scheduleStreamingFlush(ctx: ExtensionContext, state: StreamingState) {
|
|
256
|
+
clearStreamingFlush(state);
|
|
257
|
+
if (state.candidateWords.length === 0) return;
|
|
258
|
+
const delayMs = getStreamFlushMs();
|
|
259
|
+
state.flushTimer = setTimeout(() => {
|
|
260
|
+
state.flushTimer = undefined;
|
|
261
|
+
flushPendingStreamingWords(ctx, state, false);
|
|
262
|
+
}, delayMs);
|
|
263
|
+
unrefStreamingTimer(state.flushTimer);
|
|
152
264
|
}
|
|
153
265
|
|
|
154
266
|
export function queueStreamingWords(state: StreamingState, words: string[]) {
|
|
155
267
|
const nextWords = words.filter(Boolean);
|
|
156
268
|
if (nextWords.length === 0) return;
|
|
157
|
-
state.emittedWords
|
|
269
|
+
const overlap = streamingWordOverlap(state.emittedWords, nextWords);
|
|
270
|
+
const appendWords = nextWords.slice(overlap);
|
|
271
|
+
if (appendWords.length === 0) return;
|
|
272
|
+
state.emittedWords.push(...appendWords);
|
|
158
273
|
}
|
|
159
274
|
|
|
160
275
|
export function splitStreamingWords(text: string) {
|
|
@@ -181,6 +296,15 @@ export function commonStreamingPrefixLength(previousWords: string[], currentWord
|
|
|
181
296
|
return count;
|
|
182
297
|
}
|
|
183
298
|
|
|
299
|
+
export function commonStreamingSuffixLength(previousWords: string[], currentWords: string[]) {
|
|
300
|
+
const maxSuffix = Math.min(previousWords.length, currentWords.length);
|
|
301
|
+
let count = 0;
|
|
302
|
+
while (count < maxSuffix && normalizeStreamingWord(previousWords[previousWords.length - 1 - count] ?? "") === normalizeStreamingWord(currentWords[currentWords.length - 1 - count] ?? "")) {
|
|
303
|
+
count++;
|
|
304
|
+
}
|
|
305
|
+
return count;
|
|
306
|
+
}
|
|
307
|
+
|
|
184
308
|
export function streamingWordsEqual(left: string[], right: string[]) {
|
|
185
309
|
if (left.length !== right.length) return false;
|
|
186
310
|
return left.every((word, index) => normalizeStreamingWord(word) === normalizeStreamingWord(right[index] ?? ""));
|
|
@@ -192,7 +316,7 @@ export function normalizeStreamingWord(word: string) {
|
|
|
192
316
|
}
|
|
193
317
|
|
|
194
318
|
export function getStreamingTranscript(state: StreamingState) {
|
|
195
|
-
return
|
|
319
|
+
return state.emittedWords.join(" ");
|
|
196
320
|
}
|
|
197
321
|
|
|
198
322
|
export function renderStreamingPreview(ctx: ExtensionContext, state: StreamingState, trailingSpace: boolean) {
|
|
@@ -235,3 +359,74 @@ export function clearStreamingFlush(state: StreamingState) {
|
|
|
235
359
|
clearTimeout(state.flushTimer);
|
|
236
360
|
state.flushTimer = undefined;
|
|
237
361
|
}
|
|
362
|
+
|
|
363
|
+
function queueRollingStreamingWords(state: StreamingState, words: string[]) {
|
|
364
|
+
const overlap = streamingWordOverlap(state.candidateWords, words);
|
|
365
|
+
if (overlap <= 0) {
|
|
366
|
+
commitStreamingCandidate(state);
|
|
367
|
+
state.candidateWords = trimCommittedStreamingPrefix(state, words);
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
const previousCandidatePrefix = state.candidateWords.slice(0, state.candidateWords.length - overlap);
|
|
372
|
+
queueStreamingWords(state, previousCandidatePrefix);
|
|
373
|
+
const confirmedOverlap = Math.min(overlap, getStreamWordsPerChunk());
|
|
374
|
+
queueStreamingWords(state, words.slice(0, confirmedOverlap));
|
|
375
|
+
state.candidateWords = trimCommittedStreamingPrefix(state, words.slice(confirmedOverlap));
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function commitStreamingCandidate(state: StreamingState) {
|
|
379
|
+
if (state.candidateWords.length === 0) return;
|
|
380
|
+
queueStreamingWords(state, state.candidateWords);
|
|
381
|
+
state.candidateWords = [];
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function trimCommittedStreamingPrefix(state: StreamingState, words: string[]) {
|
|
385
|
+
const overlap = streamingWordOverlap(state.emittedWords, words);
|
|
386
|
+
return words.slice(overlap);
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function isStreamingWordsPrefix(prefixWords: string[], words: string[]) {
|
|
390
|
+
if (prefixWords.length === 0 || prefixWords.length > words.length) return false;
|
|
391
|
+
return streamingWordsEqual(prefixWords, words.slice(0, prefixWords.length));
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function looksLikeStreamingCorrection(previousWords: string[], currentWords: string[]) {
|
|
395
|
+
if (previousWords.length === 0 || currentWords.length === 0) return false;
|
|
396
|
+
if (previousWords.length === 1 && currentWords.length === 1) return false;
|
|
397
|
+
if (commonStreamingPrefixLength(previousWords, currentWords) > 0) return true;
|
|
398
|
+
if (commonStreamingSuffixLength(previousWords, currentWords) > 0) return true;
|
|
399
|
+
const previousNormalized = new Set(previousWords.map(normalizeStreamingWord));
|
|
400
|
+
const sharedCount = currentWords.filter((word) => previousNormalized.has(normalizeStreamingWord(word))).length;
|
|
401
|
+
return previousWords.length > 1 && currentWords.length > 1 && sharedCount >= Math.ceil(Math.min(previousWords.length, currentWords.length) / 2);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function showStreamingFrameDiagnostics(ctx: ExtensionContext, state: StreamingState, details: StreamingDiagnosticDetails) {
|
|
405
|
+
if (!envFlag("MICME_STREAM_DIAGNOSTICS")) return;
|
|
406
|
+
const payload = {
|
|
407
|
+
rawFrame: details.rawFrame === undefined ? undefined : truncateStreamingDiagnostic(stripStreamingControls(details.rawFrame)),
|
|
408
|
+
sanitizedText: details.sanitizedText === undefined ? undefined : truncateStreamingDiagnostic(details.sanitizedText),
|
|
409
|
+
frameWords: limitStreamingDiagnosticWords(details.frameWords ?? []),
|
|
410
|
+
emittedWords: limitStreamingDiagnosticWords(state.emittedWords),
|
|
411
|
+
candidateWords: limitStreamingDiagnosticWords(state.candidateWords),
|
|
412
|
+
previewText: truncateStreamingDiagnostic(getStreamingTranscript(state)),
|
|
413
|
+
extractionMode: details.extractionMode,
|
|
414
|
+
newWords: limitStreamingDiagnosticWords(details.newWords ?? []),
|
|
415
|
+
reason: details.reason,
|
|
416
|
+
};
|
|
417
|
+
ctx.ui.notify(`Micme stream frame: ${JSON.stringify(payload)}`, "info");
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function limitStreamingDiagnosticWords(words: string[]) {
|
|
421
|
+
return words.slice(-16);
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
function truncateStreamingDiagnostic(value: string) {
|
|
425
|
+
return value.length > 160 ? `${value.slice(0, 157)}...` : value;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
function unrefStreamingTimer(timer: ReturnType<typeof setTimeout>) {
|
|
429
|
+
if (typeof timer !== "object" || timer === null || !("unref" in timer)) return;
|
|
430
|
+
const unref = timer.unref;
|
|
431
|
+
if (typeof unref === "function") unref.call(timer);
|
|
432
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -35,8 +35,9 @@ export type StreamingState = {
|
|
|
35
35
|
previewText: string;
|
|
36
36
|
outputBuffer: string;
|
|
37
37
|
lastText: string;
|
|
38
|
-
pendingWords: string[];
|
|
39
38
|
emittedWords: string[];
|
|
39
|
+
candidateWords: string[];
|
|
40
|
+
lastHypothesisWords: string[];
|
|
40
41
|
startedAt: number;
|
|
41
42
|
firstOutputAt?: number;
|
|
42
43
|
firstPreviewAt?: number;
|