@senad-d/micme 0.3.2 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/settings.ts CHANGED
@@ -32,6 +32,7 @@ import {
32
32
  } from "./config.ts";
33
33
  import { discoverAudioDevices } from "./audio.ts";
34
34
  import { formatBackendLabel, resolveTranscriptionPlan } from "./backends.ts";
35
+ import { sanitizeTerminalOutput, sanitizeTerminalText } from "./terminal-text.ts";
35
36
  import { discoverPythonWhisperModels, discoverWhisperCppModels, ensureWhisperCppModel, getPythonWhisperModelName, resolveWhisperCppModel } from "./models.ts";
36
37
  import { findExecutable } from "./processes.ts";
37
38
  import type { AudioDeviceCandidate, ModelCandidate, ResolvedTranscriptionPlan } from "./types.ts";
@@ -105,20 +106,20 @@ export async function showConfiguration(ctx: ExtensionContext) {
105
106
 
106
107
  const configState = reloadMicmeConfig();
107
108
  if (configState.error) {
108
- ctx.ui.notify(`Micme config is invalid at ${configState.path}: ${configState.error}. Fix it before saving settings.`, "warning");
109
+ notifySanitized(ctx, `Micme config is invalid at ${configState.path}: ${configState.error}. Fix it before saving settings.`, "warning");
109
110
  }
110
111
  await ctx.ui.custom<void>((tui, theme, _keybindings, done) => {
111
112
  const discovery = createInitialConfigurationDiscovery();
112
113
  let closed = false;
113
114
  const screen = new ConfigurationScreen({
114
- configPath: configState.path,
115
+ configPath: sanitizeTerminalOutput(configState.path) || "micme.json",
115
116
  items: buildConfigurationItems(discovery.modelCandidates, discovery.pythonModelCandidates, discovery.audioDevices, theme),
116
117
  theme,
117
118
  onDone: () => {
118
119
  closed = true;
119
120
  done();
120
121
  },
121
- onError: (error) => ctx.ui.notify(error instanceof Error ? error.message : String(error), "error"),
122
+ onError: (error) => notifySanitized(ctx, error instanceof Error ? error.message : String(error), "error"),
122
123
  onSave: (id, newValue) => saveConfigurationValue(ctx, id, newValue),
123
124
  requestRender: () => tui.requestRender(),
124
125
  statusText: formatDiscoveryStatus(discovery.pending),
@@ -180,7 +181,7 @@ async function loadConfigurationDiscovery<T>(
180
181
  try {
181
182
  applyResult(await promise);
182
183
  } catch (error) {
183
- if (!options.isClosed()) options.ctx.ui.notify(`Micme could not load ${key}: ${error instanceof Error ? error.message : String(error)}`, "warning");
184
+ if (!options.isClosed()) notifySanitized(options.ctx, `Micme could not load ${key}: ${error instanceof Error ? error.message : String(error)}`, "warning");
184
185
  } finally {
185
186
  options.discovery.pending.delete(key);
186
187
  if (!options.isClosed()) {
@@ -207,6 +208,10 @@ function formatDiscoveryStatus(pending: Set<ConfigurationDiscoveryKey>) {
207
208
  return `Loading ${[...pending].join(", ")}…`;
208
209
  }
209
210
 
211
+ function notifySanitized(ctx: ExtensionContext, message: string, level: "warning" | "error") {
212
+ ctx.ui.notify(sanitizeTerminalOutput(message) || "Micme configuration message was empty.", level);
213
+ }
214
+
210
215
  class ConfigurationScreen implements Component {
211
216
  private readonly configPath: string;
212
217
  private items: ConfigurationItem[];
@@ -217,7 +222,7 @@ class ConfigurationScreen implements Component {
217
222
  private readonly requestRender: () => void;
218
223
  private focusedPane: FocusedPane = "categories";
219
224
  private categoryIndex = 0;
220
- private selectedByCategory = new Map<ConfigurationCategoryId, number>();
225
+ private readonly selectedByCategory = new Map<ConfigurationCategoryId, number>();
221
226
  private searchActive = false;
222
227
  private searchQuery = "";
223
228
  private selectedSearchIndex = 0;
@@ -270,58 +275,83 @@ class ConfigurationScreen implements Component {
270
275
  }
271
276
 
272
277
  handleInput(data: string): void {
273
- if (this.submenuComponent) {
274
- this.submenuComponent.handleInput?.(data);
275
- return;
276
- }
278
+ if (this.forwardSubmenuInput(data)) return;
279
+ if (this.forwardShortcutCaptureInput(data)) return;
280
+ if (this.handleCloseInput(data)) return;
277
281
 
278
- if (this.editingShortcutItem) {
279
- this.handleShortcutCaptureInput(data);
282
+ if (this.handleSearchInput(data)) {
283
+ this.requestRender();
280
284
  return;
281
285
  }
282
286
 
283
- if (matchesKey(data, Key.ctrl("c")) || data === "q" || data === "Q") {
284
- this.onDone();
285
- return;
286
- }
287
+ if (this.handlePaneSwitchInput(data)) return;
288
+ if (this.handleSelectionMoveInput(data)) return;
289
+ if (this.handleSettingActivationInput(data)) return;
290
+ this.handleEscapeNavigation(data);
291
+ }
292
+
293
+ private forwardSubmenuInput(data: string) {
294
+ if (!this.submenuComponent) return false;
295
+ this.submenuComponent.handleInput?.(data);
296
+ this.requestRender();
297
+ return true;
298
+ }
287
299
 
288
- if (this.handleSearchInput(data)) return;
300
+ private forwardShortcutCaptureInput(data: string) {
301
+ if (!this.editingShortcutItem) return false;
302
+ this.handleShortcutCaptureInput(data);
303
+ return true;
304
+ }
289
305
 
290
- if (matchesKey(data, Key.tab) || matchesKey(data, Key.shift("tab"))) {
291
- this.focusedPane = this.focusedPane === "categories" ? "settings" : "categories";
292
- return;
293
- }
306
+ private handleCloseInput(data: string) {
307
+ if (!matchesKey(data, Key.ctrl("c")) && data !== "q" && data !== "Q") return false;
308
+ this.onDone();
309
+ return true;
310
+ }
294
311
 
312
+ private handlePaneSwitchInput(data: string) {
313
+ if (!matchesKey(data, Key.tab) && !matchesKey(data, Key.shift("tab"))) return false;
314
+ this.focusedPane = this.focusedPane === "categories" ? "settings" : "categories";
315
+ this.requestRender();
316
+ return true;
317
+ }
318
+
319
+ private handleSelectionMoveInput(data: string) {
295
320
  if (matchesKey(data, Key.up)) {
296
321
  this.moveSelection(-1);
297
- return;
298
- }
299
-
300
- if (matchesKey(data, Key.down)) {
301
- this.moveSelection(1);
302
- return;
322
+ this.requestRender();
323
+ return true;
303
324
  }
325
+ if (!matchesKey(data, Key.down)) return false;
326
+ this.moveSelection(1);
327
+ this.requestRender();
328
+ return true;
329
+ }
304
330
 
331
+ private handleSettingActivationInput(data: string) {
305
332
  if (matchesKey(data, Key.enter)) {
306
333
  if (this.focusedPane === "categories") {
307
334
  this.focusedPane = "settings";
308
335
  } else {
309
336
  this.activateSelectedSetting();
310
337
  }
311
- return;
338
+ this.requestRender();
339
+ return true;
312
340
  }
313
341
 
314
- if (matchesKey(data, Key.space) && this.focusedPane === "settings") {
315
- this.activateSelectedSetting();
316
- return;
317
- }
342
+ if (!matchesKey(data, Key.space) || this.focusedPane !== "settings") return false;
343
+ this.activateSelectedSetting();
344
+ this.requestRender();
345
+ return true;
346
+ }
318
347
 
319
- if (matchesKey(data, Key.escape)) {
320
- if (this.focusedPane === "settings") {
321
- this.focusedPane = "categories";
322
- } else {
323
- this.onDone();
324
- }
348
+ private handleEscapeNavigation(data: string) {
349
+ if (!matchesKey(data, Key.escape)) return;
350
+ if (this.focusedPane === "settings") {
351
+ this.focusedPane = "categories";
352
+ this.requestRender();
353
+ } else {
354
+ this.onDone();
325
355
  }
326
356
  }
327
357
 
@@ -335,10 +365,12 @@ class ConfigurationScreen implements Component {
335
365
  const paneHeight = Math.max(categoryLines.length, settingsLines.length, 8);
336
366
  const lines: string[] = [];
337
367
 
338
- lines.push(this.renderTitleBorder(width, this.currentHeaderLabel()));
339
- lines.push(this.renderFullLine(width, this.renderConfigSourceText(width)));
340
- lines.push(this.renderFullLine(width, "↑↓ move Tab pane Enter edit / search Esc back q quit"));
341
- lines.push(this.renderPaneSeparator(width, leftWidth, rightWidth, "top"));
368
+ lines.push(
369
+ this.renderTitleBorder(width, this.currentHeaderLabel()),
370
+ this.renderFullLine(width, this.renderConfigSourceText(width)),
371
+ this.renderFullLine(width, "↑↓ move Tab pane Enter edit / search Esc back q quit"),
372
+ this.renderPaneSeparator(width, leftWidth, rightWidth, "top"),
373
+ );
342
374
 
343
375
  for (let index = 0; index < paneHeight; index++) {
344
376
  const left = categoryLines[index] ?? "";
@@ -346,9 +378,11 @@ class ConfigurationScreen implements Component {
346
378
  lines.push(this.renderPaneLine(left, right, leftWidth, rightWidth));
347
379
  }
348
380
 
349
- lines.push(this.renderPaneSeparator(width, leftWidth, rightWidth, "bottom"));
350
- lines.push(this.renderFullLine(width, this.renderFooterText()));
351
- lines.push(this.colorBorder(`╰${"─".repeat(Math.max(0, width - 2))}╯`, width));
381
+ lines.push(
382
+ this.renderPaneSeparator(width, leftWidth, rightWidth, "bottom"),
383
+ this.renderFullLine(width, this.renderFooterText()),
384
+ this.colorBorder(`╰${"─".repeat(Math.max(0, width - 2))}╯`, width),
385
+ );
352
386
  return lines.map((line) => truncateToWidth(line, width, ""));
353
387
  }
354
388
 
@@ -360,14 +394,18 @@ class ConfigurationScreen implements Component {
360
394
  const bodyLines = showCategories ? this.renderCategoryPaneLines(innerWidth) : this.renderSettingsPaneLines(innerWidth);
361
395
  const lines: string[] = [];
362
396
 
363
- lines.push(this.renderTitleBorder(width, this.currentHeaderLabel()));
364
- lines.push(this.renderFullLine(width, this.renderConfigSourceText(width)));
365
- lines.push(this.renderFullLine(width, showCategories ? "↑↓ category Enter open / search q quit" : "↑↓ move Enter edit Esc categories / search q quit"));
366
- lines.push(this.colorBorder(`├${"─".repeat(innerWidth)}┤`, width));
397
+ lines.push(
398
+ this.renderTitleBorder(width, this.currentHeaderLabel()),
399
+ this.renderFullLine(width, this.renderConfigSourceText(width)),
400
+ this.renderFullLine(width, showCategories ? "↑↓ category Enter open / search q quit" : "↑↓ move Enter edit Esc categories / search q quit"),
401
+ this.colorBorder(`├${"─".repeat(innerWidth)}┤`, width),
402
+ );
367
403
  for (const line of bodyLines) lines.push(this.renderFullLine(width, line));
368
- lines.push(this.colorBorder(`├${"─".repeat(innerWidth)}┤`, width));
369
- lines.push(this.renderFullLine(width, this.renderFooterText()));
370
- lines.push(this.colorBorder(`╰${"─".repeat(innerWidth)}╯`, width));
404
+ lines.push(
405
+ this.colorBorder(`├${"─".repeat(innerWidth)}┤`, width),
406
+ this.renderFullLine(width, this.renderFooterText()),
407
+ this.colorBorder(`╰${"─".repeat(innerWidth)}╯`, width),
408
+ );
371
409
  return lines.map((line) => truncateToWidth(line, width, ""));
372
410
  }
373
411
 
@@ -432,10 +470,12 @@ class ConfigurationScreen implements Component {
432
470
  return CONFIGURATION_CATEGORIES.map((category, index) => {
433
471
  const selected = index === this.categoryIndex;
434
472
  const focused = this.focusedPane === "categories";
473
+ const selectedColor = focused ? "accent" : "muted";
435
474
  const prefix = selected ? "▶ " : " ";
436
- const styledPrefix = selected ? this.theme.fg(focused ? "accent" : "muted", prefix) : prefix;
475
+ const styledPrefix = selected ? this.theme.fg(selectedColor, prefix) : prefix;
437
476
  const label = fitAnsi(category.label, Math.max(0, width - 2));
438
- const styledLabel = selected ? this.theme.fg(focused ? "accent" : "muted", focused ? this.theme.bold(label) : label) : this.theme.fg("dim", label);
477
+ const selectedLabel = focused ? this.theme.bold(label) : label;
478
+ const styledLabel = selected ? this.theme.fg(selectedColor, selectedLabel) : this.theme.fg("dim", label);
439
479
  return padRightAnsi(`${styledPrefix}${styledLabel}`, width);
440
480
  });
441
481
  }
@@ -465,13 +505,15 @@ class ConfigurationScreen implements Component {
465
505
 
466
506
  private renderSettingLine(item: ConfigurationItem, selected: boolean, width: number) {
467
507
  const focused = this.focusedPane === "settings";
508
+ const selectedColor = focused ? "accent" : "muted";
468
509
  const prefix = selected ? "▶ " : " ";
469
- const styledPrefix = selected ? this.theme.fg(focused ? "accent" : "muted", prefix) : prefix;
510
+ const styledPrefix = selected ? this.theme.fg(selectedColor, prefix) : prefix;
470
511
  const valueWidth = Math.max(0, Math.min(28, Math.floor(width * 0.4)));
471
512
  const labelWidth = Math.max(1, width - 2 - 1 - valueWidth);
472
513
  const labelText = this.hasSearchQuery() ? `${item.label} (${this.getCategory(item.categoryId).label})` : item.label;
473
514
  const label = fitAnsi(labelText, labelWidth);
474
- const styledLabel = selected ? this.theme.fg(focused ? "accent" : "muted", focused ? this.theme.bold(label) : label) : label;
515
+ const selectedLabel = focused ? this.theme.bold(label) : label;
516
+ const styledLabel = selected ? this.theme.fg(selectedColor, selectedLabel) : label;
475
517
  const value = this.formatValue(item, valueWidth);
476
518
  return padRightAnsi(`${styledPrefix}${padRightAnsi(styledLabel, labelWidth)} ${padLeftAnsi(value, valueWidth)}`, width);
477
519
  }
@@ -510,7 +552,7 @@ class ConfigurationScreen implements Component {
510
552
 
511
553
  private formatSlider(item: ConfigurationItem, width: number) {
512
554
  const value = Number(item.rawValue);
513
- const valueText = Number.isFinite(value) ? value.toFixed(2) : item.rawValue;
555
+ const valueText = Number.isFinite(value) ? value.toFixed(2) : sanitizeTerminalText(item.rawValue);
514
556
  if (width < valueText.length + 5) return fitAnsi(valueText, width);
515
557
 
516
558
  const ratio = item.id === "MICME_STREAM_VAD_THRESHOLD" ? clamp(value, 0, 1) : clamp(value / 2, 0, 1);
@@ -1110,11 +1152,14 @@ export function buildConfigurationItems(
1110
1152
  }
1111
1153
 
1112
1154
  export function createModelSelector(candidates: ModelCandidate[], theme: MicmeTheme, done: (selectedValue?: string) => void): Component {
1113
- const items: SelectItem[] = candidates.map((candidate) => ({
1114
- value: candidate.value,
1115
- label: candidate.installed ? `✓ ${candidate.label}` : `○ ${candidate.label}`,
1116
- description: candidate.description,
1117
- }));
1155
+ const items: SelectItem[] = candidates.map((candidate) => {
1156
+ const label = sanitizeTerminalText(candidate.label) || "model";
1157
+ return {
1158
+ value: candidate.value,
1159
+ label: candidate.installed ? `✓ ${label}` : `○ ${label}`,
1160
+ description: sanitizeTerminalText(candidate.description),
1161
+ };
1162
+ });
1118
1163
 
1119
1164
  const container = new Container();
1120
1165
  container.addChild(new DynamicBorder((s: string) => theme.fg("accent", s)));
@@ -1164,10 +1209,10 @@ export async function saveConfigurationValue(ctx: ExtensionContext, id: string,
1164
1209
  }
1165
1210
 
1166
1211
  export function displayConfigurationValue(id: string, value: string) {
1167
- if (id === "MICME_WHISPER_CPP_MODEL") return value ? basename(value) : "not set";
1212
+ if (id === "MICME_WHISPER_CPP_MODEL") return value ? sanitizeTerminalText(basename(value)) || "model" : "not set";
1168
1213
  if (id === "MICME_TRANSCRIBE_COMMAND") return value ? "configured" : "not set";
1169
- if (id === "MICME_AUDIO_FILTER") return value || "<empty>";
1170
- return value || "not set";
1214
+ if (id === "MICME_AUDIO_FILTER") return sanitizeTerminalText(value) || "<empty>";
1215
+ return sanitizeTerminalText(value) || "not set";
1171
1216
  }
1172
1217
 
1173
1218
  function getUiBackendValue(plan: ResolvedTranscriptionPlan): "whisper.cpp" | "python" {
@@ -1201,13 +1246,19 @@ function getConfigurationValuesToWrite(id: string, value: string) {
1201
1246
  function formatSaveStatus(id: string, value: string) {
1202
1247
  const writtenKeys = Object.keys(getConfigurationValuesToWrite(id, value));
1203
1248
  const overriddenKeys = writtenKeys.filter((key) => process.env[key] !== undefined);
1204
- const reloadHint = id === "MICME_SHORTCUT" ? "/reload required for shortcut changes" : id === "MICME_PRINTABLE_SHORTCUTS" ? "/reload recommended for printable shortcuts" : "";
1249
+ const reloadHint = getConfigurationReloadHint(id);
1205
1250
 
1206
1251
  if (id === "MICME_TRANSCRIPTION_MODE" && overriddenKeys.length) return `Shell env still overrides ${overriddenKeys.join(", ")}`;
1207
1252
  if (overriddenKeys.length) return reloadHint ? `Shell env still overrides ${overriddenKeys.join(", ")} • ${reloadHint}` : `Shell env still overrides ${overriddenKeys.join(", ")}`;
1208
1253
  return reloadHint;
1209
1254
  }
1210
1255
 
1256
+ function getConfigurationReloadHint(id: string) {
1257
+ if (id === "MICME_SHORTCUT") return "/reload required for shortcut changes";
1258
+ if (id === "MICME_PRINTABLE_SHORTCUTS") return "/reload recommended for printable shortcuts";
1259
+ return "";
1260
+ }
1261
+
1211
1262
  function fitAnsi(text: string, width: number, ellipsis = "…") {
1212
1263
  if (width <= 0) return "";
1213
1264
  return truncateToWidth(text, width, ellipsis);
package/src/streaming.ts CHANGED
@@ -34,7 +34,7 @@ type StreamingDiagnosticDetails = {
34
34
  reason?: string;
35
35
  };
36
36
 
37
- export function buildWhisperStreamCommand(binary: string, modelPath: string, tempDir: string): CommandSpec {
37
+ export function buildWhisperStreamCommand(binary: string, modelPath: string, _tempDir: string): CommandSpec {
38
38
  const args = [
39
39
  "-m",
40
40
  modelPath,
@@ -130,8 +130,8 @@ export function readStreamingOutputFrames(state: StreamingState, chunk: string,
130
130
  const frames: string[] = [];
131
131
 
132
132
  while (true) {
133
- const match = state.outputBuffer.match(/[\r\n]/);
134
- if (!match || match.index === undefined) break;
133
+ const match = /[\r\n]/.exec(state.outputBuffer);
134
+ if (match?.index === undefined) break;
135
135
  frames.push(state.outputBuffer.slice(0, match.index));
136
136
  state.outputBuffer = state.outputBuffer.slice(match.index + 1).replace(/^[\r\n]+/, "");
137
137
  }
@@ -145,20 +145,89 @@ export function readStreamingOutputFrames(state: StreamingState, chunk: string,
145
145
  }
146
146
 
147
147
  export function sanitizeStreamingText(text: string) {
148
- const cleaned = stripStreamingControls(text)
149
- .replace(/<\|[^|]*\|>/g, " ")
150
- .replace(/^\s*#+\s*Transcription\s+\d+\s+END\s*$/i, " ")
151
- .replace(/\[[^\]]*\]/g, " ")
152
- .replace(/\([^)]*\)/g, " ")
153
- .replace(/\s+/g, " ")
154
- .trim();
148
+ const textWithoutTokens = stripWhisperControlTokens(stripStreamingControls(text));
149
+ const textWithoutHeading = removeTranscriptionEndHeading(textWithoutTokens);
150
+ const textWithoutBracketedSegments = stripStreamingDelimitedSegments(textWithoutHeading, "[", "]");
151
+ const textWithoutParenthesizedSegments = stripStreamingDelimitedSegments(textWithoutBracketedSegments, "(", ")");
152
+ const cleaned = textWithoutParenthesizedSegments.replace(/\s+/g, " ").trim();
155
153
  return isLikelyStreamingHallucination(cleaned) ? "" : cleaned;
156
154
  }
157
155
 
156
+ function stripStreamingDelimitedSegments(text: string, startDelimiter: string, endDelimiter: string) {
157
+ let cleaned = "";
158
+ let index = 0;
159
+
160
+ while (index < text.length) {
161
+ const startIndex = text.indexOf(startDelimiter, index);
162
+ if (startIndex === -1) return `${cleaned}${text.slice(index)}`;
163
+
164
+ const endIndex = text.indexOf(endDelimiter, startIndex + startDelimiter.length);
165
+ if (endIndex === -1) return `${cleaned}${text.slice(index)}`;
166
+
167
+ cleaned = `${cleaned}${text.slice(index, startIndex)} `;
168
+ index = endIndex + endDelimiter.length;
169
+ }
170
+
171
+ return cleaned;
172
+ }
173
+
158
174
  export function stripStreamingControls(text: string) {
159
175
  return sanitizeTerminalText(text);
160
176
  }
161
177
 
178
+ function stripWhisperControlTokens(text: string) {
179
+ let cleaned = "";
180
+ let index = 0;
181
+
182
+ while (index < text.length) {
183
+ const startIndex = text.indexOf("<|", index);
184
+ if (startIndex === -1) return `${cleaned}${text.slice(index)}`;
185
+
186
+ const endIndex = text.indexOf("|>", startIndex + 2);
187
+ if (endIndex === -1) return `${cleaned}${text.slice(index)}`;
188
+
189
+ const tokenBody = text.slice(startIndex + 2, endIndex);
190
+ if (tokenBody.includes("|")) {
191
+ cleaned = `${cleaned}${text.slice(index, startIndex + 2)}`;
192
+ index = startIndex + 2;
193
+ continue;
194
+ }
195
+
196
+ cleaned = `${cleaned}${text.slice(index, startIndex)} `;
197
+ index = endIndex + 2;
198
+ }
199
+
200
+ return cleaned;
201
+ }
202
+
203
+ function removeTranscriptionEndHeading(text: string) {
204
+ return isTranscriptionEndHeading(text) ? " " : text;
205
+ }
206
+
207
+ function isTranscriptionEndHeading(text: string) {
208
+ const trimmed = text.trim();
209
+ if (!trimmed.startsWith("#")) return false;
210
+
211
+ let index = 0;
212
+ while (trimmed.at(index) === "#") index++;
213
+ while (isWhitespaceCharacter(trimmed.at(index))) index++;
214
+
215
+ const words = trimmed.slice(index).split(/\s+/u);
216
+ return words.length === 3 && words[0].toLowerCase() === "transcription" && isAsciiDigits(words[1]) && words[2].toLowerCase() === "end";
217
+ }
218
+
219
+ function isAsciiDigits(value: string) {
220
+ if (!value) return false;
221
+ for (const character of value) {
222
+ if (character < "0" || character > "9") return false;
223
+ }
224
+ return true;
225
+ }
226
+
227
+ function isWhitespaceCharacter(character: string | undefined) {
228
+ return character?.trim() === "";
229
+ }
230
+
162
231
  export function diffStreamingText(previous: string, current: string) {
163
232
  const previousWords = splitStreamingWords(previous);
164
233
  const currentWords = splitStreamingWords(current);
@@ -171,31 +240,41 @@ export function extractStreamingCandidate(state: StreamingState, frameWords: str
171
240
  const words = frameWords.filter(Boolean);
172
241
  if (words.length === 0) return { mode: "reset", newWords: [] };
173
242
 
243
+ const emittedExtraction = extractEmittedStreamingCandidate(state, words);
244
+ if (emittedExtraction) return emittedExtraction;
245
+
246
+ const candidateExtraction = extractReferencedStreamingCandidate(state.candidateWords, words, words);
247
+ if (candidateExtraction) return candidateExtraction;
248
+
249
+ const hypothesisExtraction = extractReferencedStreamingCandidate(state.lastHypothesisWords, words, trimCommittedStreamingPrefix(state, words));
250
+ if (hypothesisExtraction) return hypothesisExtraction;
251
+
252
+ return { mode: isFirstStreamingHypothesis(state) ? "cumulative" : "incremental", newWords: words };
253
+ }
254
+
255
+ function extractEmittedStreamingCandidate(state: StreamingState, words: string[]): StreamingExtraction | undefined {
174
256
  const emittedOverlap = streamingWordOverlap(state.emittedWords.slice(-160), words);
175
257
  if (emittedOverlap === words.length) return { mode: "duplicate", newWords: [] };
176
258
  if (emittedOverlap > 0) return { mode: "cumulative", newWords: words.slice(emittedOverlap) };
259
+ return undefined;
260
+ }
177
261
 
178
- if (state.candidateWords.length > 0) {
179
- if (streamingWordsEqual(state.candidateWords, words)) return { mode: "duplicate", newWords: words };
180
- if (isStreamingWordsPrefix(state.candidateWords, words)) return { mode: "cumulative", newWords: words };
181
- if (streamingWordOverlap(state.candidateWords, words) > 0) return { mode: "rolling", newWords: words };
182
- if (looksLikeStreamingCorrection(state.candidateWords, words)) return { mode: "reset", newWords: words };
183
- }
184
-
185
- if (state.lastHypothesisWords.length > 0) {
186
- if (streamingWordsEqual(state.lastHypothesisWords, words)) return { mode: "duplicate", newWords: words };
187
- if (isStreamingWordsPrefix(state.lastHypothesisWords, words)) return { mode: "cumulative", newWords: trimCommittedStreamingPrefix(state, words) };
188
- if (streamingWordOverlap(state.lastHypothesisWords, words) > 0) return { mode: "rolling", newWords: words };
189
- if (looksLikeStreamingCorrection(state.lastHypothesisWords, words)) return { mode: "reset", newWords: words };
190
- }
262
+ function extractReferencedStreamingCandidate(referenceWords: string[], words: string[], prefixWords: string[]): StreamingExtraction | undefined {
263
+ if (referenceWords.length === 0) return undefined;
264
+ if (streamingWordsEqual(referenceWords, words)) return { mode: "duplicate", newWords: words };
265
+ if (isStreamingWordsPrefix(referenceWords, words)) return { mode: "cumulative", newWords: prefixWords };
266
+ if (streamingWordOverlap(referenceWords, words) > 0) return { mode: "rolling", newWords: words };
267
+ if (looksLikeStreamingCorrection(referenceWords, words)) return { mode: "reset", newWords: words };
268
+ return undefined;
269
+ }
191
270
 
192
- const isFirstHypothesis = state.emittedWords.length === 0 && state.candidateWords.length === 0 && state.lastHypothesisWords.length === 0;
193
- return { mode: isFirstHypothesis ? "cumulative" : "incremental", newWords: words };
271
+ function isFirstStreamingHypothesis(state: StreamingState) {
272
+ return state.emittedWords.length === 0 && state.candidateWords.length === 0 && state.lastHypothesisWords.length === 0;
194
273
  }
195
274
 
196
275
  export function isLikelyStreamingHallucination(text: string) {
197
276
  if (!text) return true;
198
- const normalized = text.toLowerCase().replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, "");
277
+ const normalized = trimStreamingWordEdges(text.toLowerCase());
199
278
  if (/^(?:start speaking|blank audio)$/i.test(normalized)) return true;
200
279
  if (/^(?:you|yeah|okay|ok|uh|um|hmm)$/i.test(normalized)) return true;
201
280
  if (/^(?:thank you|thanks for watching|thank you very much)$/i.test(normalized)) return true;
@@ -206,7 +285,17 @@ export function shouldResetStreamingPending(text: string) {
206
285
  const cleaned = stripStreamingControls(text);
207
286
  if (!cleaned) return false;
208
287
  if (isLikelyStreamingHallucination(cleaned)) return true;
209
- return /^\[[^\]]+\]$/.test(cleaned) || /^\([^)]*\)$/.test(cleaned);
288
+ return isBracketedStreamingResetFrame(cleaned) || isParenthesizedStreamingResetFrame(cleaned);
289
+ }
290
+
291
+ function isBracketedStreamingResetFrame(text: string) {
292
+ if (text.length <= 2) return false;
293
+ return text.startsWith("[") && text.endsWith("]") && !text.slice(1, -1).includes("]");
294
+ }
295
+
296
+ function isParenthesizedStreamingResetFrame(text: string) {
297
+ if (text.length < 2) return false;
298
+ return text.startsWith("(") && text.endsWith(")") && !text.slice(1, -1).includes(")");
210
299
  }
211
300
 
212
301
  export function queueStableStreamingWords(ctx: ExtensionContext, state: StreamingState, currentWords: string[], mode: StreamingFrameMode = "cumulative") {
@@ -318,18 +407,32 @@ export function streamingWordsEqual(left: string[], right: string[]) {
318
407
  }
319
408
 
320
409
  export function normalizeStreamingWord(word: string) {
321
- const normalized = word.toLowerCase().replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, "");
410
+ const normalized = trimStreamingWordEdges(word.toLowerCase());
322
411
  return normalized || word.toLowerCase();
323
412
  }
324
413
 
414
+ function trimStreamingWordEdges(text: string) {
415
+ const characters = Array.from(text);
416
+ let start = 0;
417
+ while (start < characters.length && !isStreamingWordCharacter(characters[start] ?? "")) start++;
418
+
419
+ let end = characters.length;
420
+ while (end > start && !isStreamingWordCharacter(characters[end - 1] ?? "")) end--;
421
+
422
+ return characters.slice(start, end).join("");
423
+ }
424
+
425
+ function isStreamingWordCharacter(character: string) {
426
+ return /[\p{L}\p{N}]/u.test(character);
427
+ }
428
+
325
429
  export function getStreamingTranscript(state: StreamingState) {
326
430
  return state.emittedWords.join(" ");
327
431
  }
328
432
 
329
433
  export function renderStreamingPreview(ctx: ExtensionContext, state: StreamingState, trailingSpace: boolean) {
330
434
  const transcript = getStreamingTranscript(state);
331
- const suffix = transcript ? `${transcript}${trailingSpace ? " " : ""}` : "";
332
- const nextText = `${state.baseText}${suffix}`;
435
+ const nextText = appendTranscriptToBaseText(state.baseText, transcript, trailingSpace);
333
436
  if (nextText === state.previewText) return;
334
437
  ctx.ui.setEditorText(nextText);
335
438
  state.previewText = nextText;
@@ -355,8 +458,7 @@ export async function pasteOrSubmitFinalStreamingTranscript(ctx: ExtensionContex
355
458
  return;
356
459
  }
357
460
 
358
- const suffix = /\s$/.test(transcript) ? transcript : `${transcript} `;
359
- const nextText = `${state.baseText}${suffix}`;
461
+ const nextText = appendTranscriptToBaseText(state.baseText, transcript, true);
360
462
  ctx.ui.setEditorText(nextText);
361
463
  state.previewText = nextText;
362
464
  }
@@ -367,6 +469,23 @@ export function clearStreamingFlush(state: StreamingState) {
367
469
  state.flushTimer = undefined;
368
470
  }
369
471
 
472
+ function appendTranscriptToBaseText(baseText: string, transcript: string, trailingSpace: boolean) {
473
+ if (!transcript) return baseText;
474
+ const separator = needsStreamingSeparator(baseText, transcript) ? " " : "";
475
+ const suffix = /\s$/.test(transcript) || !trailingSpace ? transcript : `${transcript} `;
476
+ return `${baseText}${separator}${suffix}`;
477
+ }
478
+
479
+ function needsStreamingSeparator(baseText: string, transcript: string) {
480
+ if (!baseText || !transcript) return false;
481
+ return !isWhitespaceCharacter(baseText.at(-1)) && !isStreamingLeadingSeparator(transcript.at(0));
482
+ }
483
+
484
+ function isStreamingLeadingSeparator(character: string | undefined) {
485
+ if (isWhitespaceCharacter(character)) return true;
486
+ return character !== undefined && ".,!?;:)}]".includes(character);
487
+ }
488
+
370
489
  function queueRollingStreamingWords(state: StreamingState, words: string[]) {
371
490
  const overlap = streamingWordOverlap(state.candidateWords, words);
372
491
  if (overlap <= 0) {
@@ -1,11 +1,49 @@
1
+ const ESCAPE_CONTROL_CHARACTER = String.fromCodePoint(0x1B);
2
+ const BELL_CONTROL_CHARACTER = String.fromCodePoint(0x07);
3
+ const NON_PRINTABLE_CONTROL_CHARACTER_RANGES = [
4
+ [0x00, 0x08],
5
+ [0x0B, 0x0C],
6
+ [0x0E, 0x1F],
7
+ [0x7F, 0x7F],
8
+ ] as const;
9
+ const OPERATING_SYSTEM_COMMAND_SEQUENCE_PATTERN = new RegExp(
10
+ String.raw`${ESCAPE_CONTROL_CHARACTER}\][^${BELL_CONTROL_CHARACTER}]*(?:${BELL_CONTROL_CHARACTER}|${ESCAPE_CONTROL_CHARACTER}\\)`,
11
+ "g",
12
+ );
13
+ const TERMINAL_STRING_CONTROL_SEQUENCE_PATTERN = new RegExp(
14
+ String.raw`${ESCAPE_CONTROL_CHARACTER}[PX^_][\s\S]*?(?:${BELL_CONTROL_CHARACTER}|${ESCAPE_CONTROL_CHARACTER}\\)`,
15
+ "g",
16
+ );
17
+ const CONTROL_SEQUENCE_INTRODUCER_PATTERN = new RegExp(String.raw`${ESCAPE_CONTROL_CHARACTER}\[[0-?]*[ -/]*[@-~]`, "g");
18
+ const ESCAPE_SEQUENCE_PATTERN = new RegExp(`${ESCAPE_CONTROL_CHARACTER}[ -/]*[@-~]`, "g");
19
+ const NON_PRINTABLE_CONTROL_CHARACTER_PATTERN = new RegExp(`[${NON_PRINTABLE_CONTROL_CHARACTER_RANGES.map(formatControlCharacterRange).join("")}]`, "g");
20
+
1
21
  export function stripTerminalControlSequences(value: string) {
2
22
  return value
3
- .replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, " ")
4
- .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, " ")
5
- .replace(/\x1b[ -/]*[@-~]/g, " ")
6
- .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, " ");
23
+ .replace(OPERATING_SYSTEM_COMMAND_SEQUENCE_PATTERN, " ")
24
+ .replace(TERMINAL_STRING_CONTROL_SEQUENCE_PATTERN, " ")
25
+ .replace(CONTROL_SEQUENCE_INTRODUCER_PATTERN, " ")
26
+ .replace(ESCAPE_SEQUENCE_PATTERN, " ")
27
+ .replace(NON_PRINTABLE_CONTROL_CHARACTER_PATTERN, " ");
28
+ }
29
+
30
+ function formatControlCharacterRange(range: readonly [number, number]) {
31
+ const [first, last] = range;
32
+ const firstCharacter = String.fromCodePoint(first);
33
+ const lastCharacter = String.fromCodePoint(last);
34
+ return first === last ? firstCharacter : `${firstCharacter}-${lastCharacter}`;
7
35
  }
8
36
 
9
37
  export function sanitizeTerminalText(value: string) {
10
38
  return stripTerminalControlSequences(value).replace(/\s+/g, " ").trim();
11
39
  }
40
+
41
+ export function sanitizeTerminalOutput(value: string) {
42
+ return stripTerminalControlSequences(value)
43
+ .replaceAll("\r\n", "\n")
44
+ .replaceAll("\r", "\n")
45
+ .split("\n")
46
+ .map((line) => line.trimEnd())
47
+ .join("\n")
48
+ .trim();
49
+ }