superbased 1.4.0 → 1.6.1

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.
Files changed (79) hide show
  1. package/SUPERBASED_SKILL.md +129 -34
  2. package/dist/electron/core/platform.d.ts +2 -0
  3. package/dist/electron/core/platform.d.ts.map +1 -1
  4. package/dist/electron/main.js +95 -13
  5. package/dist/electron/modules/active-window.d.ts.map +1 -1
  6. package/dist/electron/modules/active-window.js +8 -0
  7. package/dist/electron/modules/active-window.js.map +1 -1
  8. package/dist/electron/modules/api-server.d.ts.map +1 -1
  9. package/dist/electron/modules/api-server.js +232 -4
  10. package/dist/electron/modules/api-server.js.map +1 -1
  11. package/dist/electron/modules/azure-speech-realtime.d.ts +13 -3
  12. package/dist/electron/modules/azure-speech-realtime.d.ts.map +1 -1
  13. package/dist/electron/modules/azure-speech-realtime.js +187 -54
  14. package/dist/electron/modules/azure-speech-realtime.js.map +1 -1
  15. package/dist/electron/modules/capture.d.ts.map +1 -1
  16. package/dist/electron/modules/capture.js +27 -8
  17. package/dist/electron/modules/capture.js.map +1 -1
  18. package/dist/electron/modules/dictation.d.ts +2 -0
  19. package/dist/electron/modules/dictation.d.ts.map +1 -1
  20. package/dist/electron/modules/dictation.js +145 -20
  21. package/dist/electron/modules/dictation.js.map +1 -1
  22. package/dist/electron/modules/ocr.d.ts.map +1 -1
  23. package/dist/electron/modules/ocr.js +15 -3
  24. package/dist/electron/modules/ocr.js.map +1 -1
  25. package/dist/electron/modules/recording/capture-queue.d.ts.map +1 -1
  26. package/dist/electron/modules/recording/capture-queue.js +43 -10
  27. package/dist/electron/modules/recording/capture-queue.js.map +1 -1
  28. package/dist/electron/modules/recording/index.d.ts.map +1 -1
  29. package/dist/electron/modules/recording/index.js +12 -6
  30. package/dist/electron/modules/recording/index.js.map +1 -1
  31. package/dist/electron/modules/recording/monitor-analyzer.d.ts +40 -0
  32. package/dist/electron/modules/recording/monitor-analyzer.d.ts.map +1 -0
  33. package/dist/electron/modules/recording/monitor-analyzer.js +220 -0
  34. package/dist/electron/modules/recording/monitor-analyzer.js.map +1 -0
  35. package/dist/electron/modules/recording/providers/change-detect-provider.d.ts +28 -0
  36. package/dist/electron/modules/recording/providers/change-detect-provider.d.ts.map +1 -0
  37. package/dist/electron/modules/recording/providers/change-detect-provider.js +181 -0
  38. package/dist/electron/modules/recording/providers/change-detect-provider.js.map +1 -0
  39. package/dist/electron/modules/recording/providers/provider-factory.d.ts +8 -2
  40. package/dist/electron/modules/recording/providers/provider-factory.d.ts.map +1 -1
  41. package/dist/electron/modules/recording/providers/provider-factory.js +33 -12
  42. package/dist/electron/modules/recording/providers/provider-factory.js.map +1 -1
  43. package/dist/electron/modules/recording/providers/uiohook-provider.d.ts.map +1 -1
  44. package/dist/electron/modules/recording/providers/uiohook-provider.js +9 -5
  45. package/dist/electron/modules/recording/providers/uiohook-provider.js.map +1 -1
  46. package/dist/electron/modules/recording/recording-session.d.ts +5 -1
  47. package/dist/electron/modules/recording/recording-session.d.ts.map +1 -1
  48. package/dist/electron/modules/recording/recording-session.js +78 -6
  49. package/dist/electron/modules/recording/recording-session.js.map +1 -1
  50. package/dist/electron/modules/recording/trigger-engine.d.ts.map +1 -1
  51. package/dist/electron/modules/recording/trigger-engine.js +10 -3
  52. package/dist/electron/modules/recording/trigger-engine.js.map +1 -1
  53. package/dist/electron/modules/store.js +2 -2
  54. package/dist/electron/modules/store.js.map +1 -1
  55. package/dist/electron/modules/uiohook-manager.d.ts +19 -0
  56. package/dist/electron/modules/uiohook-manager.d.ts.map +1 -0
  57. package/dist/electron/modules/uiohook-manager.js +101 -0
  58. package/dist/electron/modules/uiohook-manager.js.map +1 -0
  59. package/dist/headless/electron/modules/active-window.js +8 -0
  60. package/dist/headless/electron/modules/api-server.js +137 -3
  61. package/dist/headless/electron/modules/azure-speech-realtime.js +187 -54
  62. package/dist/headless/electron/modules/dictation.js +122 -0
  63. package/dist/headless/headless/dictation-hotkey.js +212 -47
  64. package/dist/headless/headless/dictation-overlay.js +218 -0
  65. package/dist/headless/headless/mic-capture.js +95 -1
  66. package/dist/headless/headless/platform-headless.js +103 -3
  67. package/dist/headless/headless/win32-text-injector.js +359 -0
  68. package/dist/headless/mic-capture.d.ts +21 -1
  69. package/dist/headless/mic-capture.d.ts.map +1 -1
  70. package/dist/headless/mic-capture.js +95 -1
  71. package/dist/headless/mic-capture.js.map +1 -1
  72. package/dist/shared/constants.d.ts +1 -1
  73. package/dist/shared/constants.js +1 -1
  74. package/dist/shared/constants.js.map +1 -1
  75. package/dist/shared/recording-types.d.ts +12 -0
  76. package/dist/shared/recording-types.d.ts.map +1 -1
  77. package/mcp-server/dist/api-client.js +9 -0
  78. package/mcp-server/dist/index.js +91 -6
  79. package/package.json +2 -2
@@ -39,7 +39,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
39
39
  return (mod && mod.__esModule) ? mod : { "default": mod };
40
40
  };
41
41
  Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.normalizeTechnicalTerms = normalizeTechnicalTerms;
42
43
  exports.removeFillerWords = removeFillerWords;
44
+ exports.normalizeShortPhrase = normalizeShortPhrase;
43
45
  exports.deduplicateConsecutiveWords = deduplicateConsecutiveWords;
44
46
  exports.handleAudioReady = handleAudioReady;
45
47
  exports.initializeDictation = initializeDictation;
@@ -386,6 +388,126 @@ function normalizeTechnicalTerms(text) {
386
388
  result = result.replace(/(\w)\s+(?:pipe|vertical bar)\s+(\w)/gi, '$1|$2');
387
389
  result = result.replace(/(\w)\s+(?:tilde|til-duh)\s+(\w)/gi, '$1~$2');
388
390
  result = result.replace(/(\w)\s+(?:equals|equal sign|equal)\s+(\w)/gi, '$1=$2');
391
+ // ── STEP 5: Brand / product name normalization ──
392
+ // Speech engines often split or phonetically mangle brand names.
393
+ // Fix common misrecognitions for AI, dev tools, and tech terms.
394
+ const brandMap = [
395
+ // SuperBased & product
396
+ [/\bsuper ?bas[es]d?\b/gi, 'SuperBased'],
397
+ [/\bsuper ?bass\b/gi, 'SuperBased'],
398
+ [/\bgaja a\.?i\.?\b/gi, 'Gaja AI'],
399
+ // LLM providers & models
400
+ [/\b(?:cloud|clod|clawed|claud) code\b/gi, 'Claude Code'],
401
+ [/\b(?:cloud|clod|clawed) opus\b/gi, 'Claude Opus'],
402
+ [/\b(?:cloud|clod|clawed) sonnet\b/gi, 'Claude Sonnet'],
403
+ [/\b(?:cloud|clod|clawed) haiku\b/gi, 'Claude Haiku'],
404
+ [/\bclaude code\b/gi, 'Claude Code'],
405
+ [/\bclaude opus\b/gi, 'Claude Opus'],
406
+ [/\bclaude sonnet\b/gi, 'Claude Sonnet'],
407
+ [/\bclaude haiku\b/gi, 'Claude Haiku'],
408
+ [/\banthropic\b/gi, 'Anthropic'],
409
+ [/\bopen a\.?i\.?\b/gi, 'OpenAI'],
410
+ [/\bdeep seek\b/gi, 'DeepSeek'],
411
+ [/\bmix tral\b/gi, 'Mixtral'],
412
+ [/\b(?:ou|oh|o) ?llama\b/gi, 'Ollama'],
413
+ [/\bllama\b/g, 'Llama'], // case-sensitive: don't touch if already correct
414
+ [/\bgemini\b/gi, 'Gemini'],
415
+ [/\bmistral\b/gi, 'Mistral'],
416
+ [/\bgroq\b/gi, 'Groq'],
417
+ [/\bperplexity\b/gi, 'Perplexity'],
418
+ [/\bco ?here\b/gi, 'Cohere'],
419
+ [/\bhugging face\b/gi, 'Hugging Face'],
420
+ [/\bx a\.?i\.?\b/gi, 'xAI'],
421
+ [/\bmeta a\.?i\.?\b/gi, 'Meta AI'],
422
+ [/\bstability a\.?i\.?\b/gi, 'Stability AI'],
423
+ [/\bgoogle deep ?mind\b/gi, 'Google DeepMind'],
424
+ [/\btogether a\.?i\.?\b/gi, 'Together AI'],
425
+ [/\bfireworks a\.?i\.?\b/gi, 'Fireworks AI'],
426
+ [/\bsamba ?nova\b/gi, 'SambaNova'],
427
+ [/\bdeep ?infra\b/gi, 'DeepInfra'],
428
+ [/\beleven ?labs\b/gi, 'ElevenLabs'],
429
+ [/\bdeep ?gram\b/gi, 'Deepgram'],
430
+ [/\bassembly a\.?i\.?\b/gi, 'AssemblyAI'],
431
+ [/\bopen ?router\b/gi, 'OpenRouter'],
432
+ [/\bL\.?M\.? ?studio\b/gi, 'LM Studio'],
433
+ // AI coding tools
434
+ [/\bcursor\b/g, 'Cursor'],
435
+ [/\bwind ?surf\b/gi, 'Windsurf'],
436
+ [/\bcline\b/gi, 'Cline'],
437
+ [/\baider\b/gi, 'Aider'],
438
+ [/\bco ?pilot\b/gi, 'Copilot'],
439
+ [/\bgit ?hub co ?pilot\b/gi, 'GitHub Copilot'],
440
+ [/\bcode ?ium\b/gi, 'Codeium'],
441
+ [/\btab ?nine\b/gi, 'Tabnine'],
442
+ [/\bsuper ?maven\b/gi, 'Supermaven'],
443
+ [/\bopen ?code\b/gi, 'OpenCode'],
444
+ [/\bzed a\.?i\.?\b/gi, 'Zed AI'],
445
+ // AI frameworks
446
+ [/\blang ?chain\b/gi, 'LangChain'],
447
+ [/\blang ?graph\b/gi, 'LangGraph'],
448
+ [/\bllama ?index\b/gi, 'LlamaIndex'],
449
+ [/\bcrew a\.?i\.?\b/gi, 'CrewAI'],
450
+ [/\bauto ?gen\b/gi, 'AutoGen'],
451
+ [/\bsemantic kernel\b/gi, 'Semantic Kernel'],
452
+ [/\bhay ?stack\b/gi, 'Haystack'],
453
+ [/\bvercel a\.?i\.? ?s\.?d\.?k\.?\b/gi, 'Vercel AI SDK'],
454
+ [/\bpydantic a\.?i\.?\b/gi, 'Pydantic AI'],
455
+ [/\bD\.?S\.?P\.?Y\.?\b/g, 'DSPy'],
456
+ // AI infra & concepts
457
+ [/\bM\.?C\.?P\.?\b/g, 'MCP'],
458
+ [/\bmodel context protocol\b/gi, 'Model Context Protocol'],
459
+ [/\bR\.?A\.?G\.?\b/g, 'RAG'],
460
+ [/\bretrieval augmented generation\b/gi, 'retrieval augmented generation'],
461
+ [/\bR\.?L\.?H\.?F\.?\b/g, 'RLHF'],
462
+ [/\blo ?ra\b/gi, 'LoRA'],
463
+ [/\bQ\.? ?lo ?ra\b/gi, 'QLoRA'],
464
+ [/\bP\.?E\.?F\.?T\.?\b/g, 'PEFT'],
465
+ [/\bV\.? ?L\.?L\.?M\.?\b/g, 'vLLM'],
466
+ [/\bG\.?G\.?U\.?F\.?\b/g, 'GGUF'],
467
+ [/\bO\.?N\.?N\.?X\.?\b/g, 'ONNX'],
468
+ [/\btensor ?R\.?T\.?\b/gi, 'TensorRT'],
469
+ [/\bfine ?tune\b/gi, 'fine-tune'],
470
+ [/\bfine ?tuning\b/gi, 'fine-tuning'],
471
+ [/\bmulti ?modal\b/gi, 'multimodal'],
472
+ [/\bcontext window\b/gi, 'context window'],
473
+ [/\bprompt engineering\b/gi, 'prompt engineering'],
474
+ [/\bfunction calling\b/gi, 'function calling'],
475
+ [/\btool calling\b/gi, 'tool calling'],
476
+ [/\btool use\b/gi, 'tool use'],
477
+ [/\bagentic\b/gi, 'agentic'],
478
+ // Vector DBs
479
+ [/\bpine ?cone\b/gi, 'Pinecone'],
480
+ [/\bweaviate\b/gi, 'Weaviate'],
481
+ [/\bq ?drant\b/gi, 'Qdrant'],
482
+ [/\bchroma\b/gi, 'Chroma'],
483
+ [/\bmilvus\b/gi, 'Milvus'],
484
+ [/\bpg ?vector\b/gi, 'pgvector'],
485
+ // Media AI
486
+ [/\bdall[ -]?e\b/gi, 'DALL-E'],
487
+ [/\bmid ?journey\b/gi, 'Midjourney'],
488
+ [/\bstable diffusion\b/gi, 'Stable Diffusion'],
489
+ // Dev tools
490
+ [/\bsupa ?base\b/gi, 'Supabase'],
491
+ [/\bnext ?\.?j\.?s\.?\b/gi, 'Next.js'],
492
+ [/\bsvelte ?kit\b/gi, 'SvelteKit'],
493
+ [/\btailwind\b/gi, 'Tailwind'],
494
+ [/\btype ?script\b/gi, 'TypeScript'],
495
+ [/\bjava ?script\b/gi, 'JavaScript'],
496
+ [/\bpost ?gres\b/gi, 'Postgres'],
497
+ [/\bred is\b/gi, 'Redis'],
498
+ [/\bcloud ?flare\b/gi, 'Cloudflare'],
499
+ [/\bterraform\b/gi, 'Terraform'],
500
+ [/\bkubernetes\b/gi, 'Kubernetes'],
501
+ [/\bV\.?S\.? ?code\b/gi, 'VS Code'],
502
+ [/\bt\.?R\.?P\.?C\.?\b/g, 'tRPC'],
503
+ [/\bdrizzle ?O\.?R\.?M\.?\b/gi, 'Drizzle ORM'],
504
+ // Observability
505
+ [/\blang ?fuse\b/gi, 'Langfuse'],
506
+ [/\blang ?smith\b/gi, 'LangSmith'],
507
+ ];
508
+ for (const [pattern, replacement] of brandMap) {
509
+ result = result.replace(pattern, replacement);
510
+ }
389
511
  // Standalone symbol words (not between two words)
390
512
  result = result.replace(/\b(?:fat |thick )?arrow\b/gi, '=>');
391
513
  result = result.replace(/\bthin arrow\b/gi, '->');
@@ -63,6 +63,10 @@ let hookStarted = false;
63
63
  let transcriptionMode = 'batch';
64
64
  let azureConfig = null;
65
65
  let realtimeActive = false;
66
+ // Pre-saved clipboard content from before dictation (saved during tail window)
67
+ let pendingClipboardRestore = null;
68
+ // Pre-created VBScript for SendKeys paste — avoids PowerShell spawn overhead (~230ms → ~50ms)
69
+ let sendKeysVbsPath = null;
66
70
  // Pre-cached imports for speed — avoids dynamic import() on every dictation
67
71
  let cachedRt = null;
68
72
  let cachedUserPhrases = null;
@@ -70,6 +74,62 @@ let cachedCleanupFns = null;
70
74
  // Timing helpers
71
75
  function ts() { return performance.now(); }
72
76
  function elapsed(start) { return `${(performance.now() - start).toFixed(0)}ms`; }
77
+ // ── Terminal UI indicators ──
78
+ const ANSI = {
79
+ reset: '\x1b[0m',
80
+ red: '\x1b[31m',
81
+ green: '\x1b[32m',
82
+ yellow: '\x1b[33m',
83
+ cyan: '\x1b[36m',
84
+ dim: '\x1b[2m',
85
+ bold: '\x1b[1m',
86
+ clearLine: '\r\x1b[K',
87
+ };
88
+ const REC_FRAMES = ['● ', '◉ ', '● ', '○ '];
89
+ let indicatorInterval = null;
90
+ let indicatorFrame = 0;
91
+ let lastIntermediateText = '';
92
+ function showRecording() {
93
+ stopIndicator();
94
+ indicatorFrame = 0;
95
+ indicatorInterval = setInterval(() => {
96
+ const dot = REC_FRAMES[indicatorFrame % REC_FRAMES.length];
97
+ const label = lastIntermediateText
98
+ ? `${ANSI.clearLine}${ANSI.red}${dot}${ANSI.reset}${ANSI.dim}${lastIntermediateText}${ANSI.reset}`
99
+ : `${ANSI.clearLine}${ANSI.red}${dot}REC${ANSI.reset} ${ANSI.dim}listening...${ANSI.reset}`;
100
+ process.stderr.write(label);
101
+ indicatorFrame++;
102
+ }, 400);
103
+ }
104
+ function updateIntermediate(text) {
105
+ lastIntermediateText = text;
106
+ const dot = REC_FRAMES[indicatorFrame % REC_FRAMES.length];
107
+ process.stderr.write(`${ANSI.clearLine}${ANSI.red}${dot}${ANSI.reset}${text}`);
108
+ }
109
+ function showTranscribing() {
110
+ stopIndicator();
111
+ const SPIN = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
112
+ let frame = 0;
113
+ indicatorInterval = setInterval(() => {
114
+ process.stderr.write(`${ANSI.clearLine}${ANSI.yellow}${SPIN[frame % SPIN.length]} transcribing...${ANSI.reset}`);
115
+ frame++;
116
+ }, 80);
117
+ }
118
+ function showDone(text) {
119
+ stopIndicator();
120
+ process.stderr.write(`${ANSI.clearLine}${ANSI.green}${ANSI.bold}✓${ANSI.reset} ${text}\n`);
121
+ }
122
+ function showError(msg) {
123
+ stopIndicator();
124
+ process.stderr.write(`${ANSI.clearLine}${ANSI.red}✗${ANSI.reset} ${msg}\n`);
125
+ }
126
+ function stopIndicator() {
127
+ if (indicatorInterval) {
128
+ clearInterval(indicatorInterval);
129
+ indicatorInterval = null;
130
+ }
131
+ lastIntermediateText = '';
132
+ }
73
133
  function updateRequiredKeycodes() {
74
134
  requiredKeycodes = new Set();
75
135
  for (const mod of shortcutModifiers) {
@@ -132,29 +192,38 @@ async function startDictation() {
132
192
  if (state !== 'idle')
133
193
  return;
134
194
  if (!(0, auth_1.isAuthenticated)()) {
135
- process.stderr.write('[dictation] Not signed in — run: superbased auth login\n');
195
+ showError('Not signed in — run: superbased auth login');
136
196
  return;
137
197
  }
138
198
  if (!(0, mic_capture_1.isMicAvailable)()) {
139
- process.stderr.write('[dictation] No mic backend — install ffmpeg\n');
199
+ showError('No mic backend — install ffmpeg');
140
200
  return;
141
201
  }
142
202
  const t0 = ts();
143
203
  state = 'recording';
204
+ // Pre-save clipboard NOW (async, non-blocking) so it's ready by the time
205
+ // we need to paste. Moves ~200-300ms PowerShell spawn out of the stop path.
206
+ pendingClipboardRestore = null;
207
+ if (!(0, platform_1.getPlatform)().isElectron() && process.platform === 'win32') {
208
+ const { exec } = require('child_process');
209
+ exec('powershell -command "Get-Clipboard -Raw"', { encoding: 'utf-8', timeout: 3000 }, (err, stdout) => {
210
+ pendingClipboardRestore = err ? '' : (stdout || '').trim();
211
+ });
212
+ }
144
213
  try {
145
214
  const maxDuration = (0, json_store_1.getSetting)('dictationSettings')?.maxDurationSeconds || 120;
146
215
  if (transcriptionMode === 'realtime' && azureConfig) {
147
- process.stderr.write('[dictation] Recording (realtime)... (release keys to stop)\n');
216
+ showRecording();
148
217
  await startRealtimeRecording(maxDuration, t0);
149
218
  }
150
219
  else {
151
- process.stderr.write('[dictation] Recording... (release keys to stop)\n');
220
+ showRecording();
152
221
  currentRecording = (0, mic_capture_1.startRecording)(maxDuration);
153
222
  file_logger_1.default.info(`[Dictation] [PERF] ffmpeg spawn: ${elapsed(t0)}`);
154
223
  }
155
224
  }
156
225
  catch (err) {
157
- process.stderr.write(`[dictation] Failed to start: ${err}\n`);
226
+ showError(`Failed to start: ${err}`);
158
227
  state = 'idle';
159
228
  }
160
229
  }
@@ -164,23 +233,30 @@ async function startRealtimeRecording(maxDuration, t0) {
164
233
  const tPreBuf = ts();
165
234
  rt.startPreBuffering();
166
235
  file_logger_1.default.info(`[Dictation] [PERF] pre-buffer start: ${elapsed(t0)}`);
167
- // Start ffmpeg mic capture
168
- const tFfmpeg = ts();
169
- currentRecording = (0, mic_capture_1.startRecording)(maxDuration);
170
- realtimeActive = true;
171
- file_logger_1.default.info(`[Dictation] [PERF] ffmpeg spawn: ${elapsed(t0)} (ffmpeg only: ${elapsed(tFfmpeg)})`);
172
- // Wire PCM streaming: ffmpeg stdout → Azure SDK (real-time)
236
+ // Wire PCM streaming: mic → Azure SDK (real-time)
173
237
  let chunkCount = 0;
174
- let firstChunkTime = 0;
175
- currentRecording.onPcmChunk((chunk) => {
238
+ const pcmHandler = (chunk) => {
176
239
  chunkCount++;
177
240
  if (chunkCount === 1) {
178
- firstChunkTime = ts();
179
241
  file_logger_1.default.info(`[Dictation] [PERF] first PCM chunk: ${elapsed(t0)}`);
180
242
  }
181
243
  const ab = chunk.buffer.slice(chunk.byteOffset, chunk.byteOffset + chunk.byteLength);
182
244
  rt.pushAudioData(ab);
183
- });
245
+ };
246
+ // Use warm mic if available (instant start, no ffmpeg spawn delay).
247
+ // Falls back to cold start if warm mic isn't running.
248
+ const tFfmpeg = ts();
249
+ if ((0, mic_capture_1.isWarmMicRunning)()) {
250
+ (0, mic_capture_1.startWarmCapture)(pcmHandler);
251
+ realtimeActive = true;
252
+ file_logger_1.default.info(`[Dictation] [PERF] warm mic attached: ${elapsed(t0)} (instant)`);
253
+ }
254
+ else {
255
+ currentRecording = (0, mic_capture_1.startRecording)(maxDuration);
256
+ realtimeActive = true;
257
+ currentRecording.onPcmChunk(pcmHandler);
258
+ file_logger_1.default.info(`[Dictation] [PERF] ffmpeg spawn: ${elapsed(t0)} (ffmpeg only: ${elapsed(tFfmpeg)})`);
259
+ }
184
260
  // Read settings with desktop-matching defaults
185
261
  const settings = (0, json_store_1.getSetting)('dictationSettings');
186
262
  const endSilenceMs = settings?.endSilenceMs ?? 5000;
@@ -199,7 +275,7 @@ async function startRealtimeRecording(maxDuration, t0) {
199
275
  const tAzure = ts();
200
276
  await rt.startRealtimeRecognition(azureConfig.apiKey, azureConfig.region, settings?.language || 'en-US', {
201
277
  onIntermediate: (text) => {
202
- process.stderr.write(`\r\x1b[K[dictation] ${text}`);
278
+ updateIntermediate(text);
203
279
  },
204
280
  onFinal: (text) => {
205
281
  file_logger_1.default.info('[Dictation] RT final:', text.substring(0, 50));
@@ -212,28 +288,40 @@ async function startRealtimeRecording(maxDuration, t0) {
212
288
  file_logger_1.default.info(`[Dictation] [PERF] PCM chunks sent during init: ${chunkCount}`);
213
289
  }
214
290
  async function stopDictation() {
215
- if (state !== 'recording' || !currentRecording)
291
+ if (state !== 'recording')
292
+ return;
293
+ if (!currentRecording && !realtimeActive)
216
294
  return;
217
295
  const t0 = ts();
218
296
  state = 'transcribing';
219
- process.stderr.write('\n');
297
+ showTranscribing();
220
298
  try {
221
299
  let rawText;
222
300
  if (realtimeActive && azureConfig) {
223
301
  // Realtime mode: audio already streamed to Azure.
224
- // Stop ffmpeg in background (don't await — Azure has the audio)
302
+ // Clipboard was pre-saved at recording start (async) — pendingClipboardRestore is ready.
303
+ // Keep capturing for a brief tail window after key release so the
304
+ // last syllable isn't clipped, then stop forwarding.
305
+ const tTail = ts();
306
+ await new Promise((r) => setTimeout(r, 200));
307
+ file_logger_1.default.info(`[Dictation] [PERF] audio tail: ${elapsed(tTail)}`);
225
308
  const tStop = ts();
226
- currentRecording.stop().catch(() => { });
227
- currentRecording = null;
228
- file_logger_1.default.info(`[Dictation] [PERF] ffmpeg stop fired: ${elapsed(tStop)}`);
309
+ if (currentRecording) {
310
+ currentRecording.stop().catch(() => { });
311
+ currentRecording = null;
312
+ }
313
+ else {
314
+ (0, mic_capture_1.stopWarmCapture)();
315
+ }
316
+ file_logger_1.default.info(`[Dictation] [PERF] mic stop: ${elapsed(tStop)}`);
229
317
  // Get final result from Azure
230
318
  const tAzureStop = ts();
231
319
  const rt = cachedRt || await Promise.resolve().then(() => __importStar(require('../electron/modules/azure-speech-realtime')));
232
320
  rawText = await rt.stopRealtimeRecognition();
233
321
  realtimeActive = false;
234
- file_logger_1.default.info(`[Dictation] [PERF] Azure stop + final result: ${elapsed(tAzureStop)}`);
322
+ file_logger_1.default.info(`[Dictation] [PERF] azure stop: ${elapsed(tAzureStop)}`);
235
323
  }
236
- else {
324
+ else if (currentRecording) {
237
325
  // Batch mode: need the audio buffer
238
326
  const tStop = ts();
239
327
  const audioBuffer = await currentRecording.stop();
@@ -245,41 +333,97 @@ async function stopDictation() {
245
333
  rawText = await transcribeViaBackend(audioBase64, undefined, 'dictation-hotkey');
246
334
  file_logger_1.default.info(`[Dictation] [PERF] Whisper round-trip: ${elapsed(tWhisper)}`);
247
335
  }
336
+ else {
337
+ rawText = '';
338
+ }
248
339
  if (!rawText || rawText.trim().length === 0) {
249
- process.stderr.write('[dictation] No speech detected\n');
340
+ showError('No speech detected');
250
341
  state = 'idle';
251
342
  return;
252
343
  }
253
- // Text cleanup (cached — avoids 250ms dynamic import)
344
+ // Text cleanup — same pipeline as desktop: dedup → technical terms → fillers → short phrase
254
345
  const tCleanup = ts();
255
346
  let finalText = rawText;
256
347
  if (cachedCleanupFns) {
257
- finalText = cachedCleanupFns.deduplicateConsecutiveWords(cachedCleanupFns.removeFillerWords(rawText));
348
+ finalText = cachedCleanupFns.deduplicateConsecutiveWords(finalText);
349
+ finalText = cachedCleanupFns.normalizeTechnicalTerms(finalText);
350
+ finalText = cachedCleanupFns.removeFillerWords(finalText);
351
+ finalText = cachedCleanupFns.normalizeShortPhrase(finalText);
258
352
  }
259
- file_logger_1.default.info(`[Dictation] [PERF] text cleanup: ${elapsed(tCleanup)}`);
260
- // Save clipboard → write text → paste → restore clipboard
353
+ const cleanupMs = elapsed(tCleanup);
354
+ file_logger_1.default.info(`[Dictation] [PERF] cleanup: ${cleanupMs}`);
355
+ // Write text → paste → restore clipboard.
356
+ // Clipboard was pre-saved during the tail window (pendingClipboardRestore).
357
+ // On Windows: use clip.exe for write (instant), WScript.Shell for SendKeys,
358
+ // then restore via clip.exe in background after a delay.
261
359
  const tPaste = ts();
262
- const previousClipboard = (0, platform_1.getPlatform)().getClipboardText();
263
- (0, platform_1.getPlatform)().setClipboardText(finalText);
264
- try {
265
- const { simulatePaste } = require('../electron/modules/keystroke');
266
- await simulatePaste();
267
- // Brief delay to let the paste complete before restoring
268
- await new Promise((r) => setTimeout(r, 50));
360
+ if (!(0, platform_1.getPlatform)().isElectron() && process.platform === 'win32') {
361
+ try {
362
+ const { execSync: execSyncPaste } = require('child_process');
363
+ // Write text to clipboard via clip.exe (much faster than PowerShell Set-Clipboard)
364
+ execSyncPaste('clip', { input: finalText, timeout: 2000, stdio: ['pipe', 'pipe', 'pipe'] });
365
+ // Send Ctrl+V — use pre-created VBScript via cscript (much faster than PowerShell)
366
+ if (sendKeysVbsPath) {
367
+ execSyncPaste(`cscript //nologo "${sendKeysVbsPath}"`, { timeout: 2000, stdio: 'pipe' });
368
+ }
369
+ else {
370
+ execSyncPaste('powershell -command "(New-Object -ComObject WScript.Shell).SendKeys(\'^v\')"', { timeout: 3000, stdio: 'pipe' });
371
+ }
372
+ // Restore clipboard in background after target app processes the paste
373
+ if (pendingClipboardRestore) {
374
+ const prev = pendingClipboardRestore;
375
+ pendingClipboardRestore = null;
376
+ setTimeout(() => {
377
+ try {
378
+ const { execSync: execSyncBg } = require('child_process');
379
+ execSyncBg('clip', { input: prev, timeout: 2000, stdio: ['pipe', 'pipe', 'pipe'] });
380
+ }
381
+ catch { /* ignore */ }
382
+ }, 500);
383
+ }
384
+ }
385
+ catch (err) {
386
+ file_logger_1.default.warn('[Dictation] Paste failed:', err);
387
+ }
269
388
  }
270
- catch {
271
- // keystroke module may not be available
389
+ else if (!(0, platform_1.getPlatform)().isElectron()) {
390
+ // macOS / Linux: use platform clipboard + osascript/xdotool
391
+ const { execSync: execSyncPaste } = require('child_process');
392
+ const previousClipboard = (0, platform_1.getPlatform)().getClipboardText();
393
+ (0, platform_1.getPlatform)().setClipboardText(finalText);
394
+ try {
395
+ if (process.platform === 'darwin') {
396
+ execSyncPaste('osascript -e \'tell application "System Events" to keystroke "v" using command down\'', { timeout: 3000, stdio: 'pipe' });
397
+ }
398
+ else {
399
+ execSyncPaste('xdotool key ctrl+v 2>/dev/null', { timeout: 3000, stdio: 'pipe' });
400
+ }
401
+ }
402
+ catch { /* paste failed */ }
403
+ // Restore clipboard in background
404
+ if (previousClipboard) {
405
+ setTimeout(() => { (0, platform_1.getPlatform)().setClipboardText(previousClipboard); }, 500);
406
+ }
272
407
  }
273
- // Restore previous clipboard contents
274
- if (previousClipboard) {
275
- (0, platform_1.getPlatform)().setClipboardText(previousClipboard);
408
+ else {
409
+ // Desktop/Electron: use nut-js
410
+ const previousClipboard = (0, platform_1.getPlatform)().getClipboardText();
411
+ (0, platform_1.getPlatform)().setClipboardText(finalText);
412
+ try {
413
+ const { simulatePaste } = require('../electron/modules/keystroke');
414
+ await simulatePaste();
415
+ }
416
+ catch { /* not available */ }
417
+ await new Promise((r) => setTimeout(r, 50));
418
+ if (previousClipboard)
419
+ (0, platform_1.getPlatform)().setClipboardText(previousClipboard);
276
420
  }
277
- file_logger_1.default.info(`[Dictation] [PERF] clipboard + paste + restore: ${elapsed(tPaste)}`);
278
- file_logger_1.default.info(`[Dictation] [PERF] total stop→paste: ${elapsed(t0)}`);
279
- process.stderr.write(`[dictation] "${finalText}"\n`);
421
+ file_logger_1.default.info(`[Dictation] [PERF] paste: ${elapsed(tPaste)}`);
422
+ file_logger_1.default.info(`[Dictation] [PERF] TOTAL stop→paste: ${elapsed(t0)}`);
423
+ showDone(`${finalText} ${ANSI.dim}(${elapsed(t0)})${ANSI.reset}`);
280
424
  }
281
425
  catch (err) {
282
- process.stderr.write(`[dictation] Transcription failed: ${err}\n`);
426
+ showError(`Transcription failed: ${err}`);
283
427
  realtimeActive = false;
284
428
  }
285
429
  finally {
@@ -297,10 +441,24 @@ async function initDictationHotkey() {
297
441
  return;
298
442
  }
299
443
  (0, mic_capture_1.prewarm)();
444
+ // Pre-create VBScript for SendKeys paste (cscript is ~180ms faster than PowerShell)
445
+ if (process.platform === 'win32') {
446
+ try {
447
+ const os = require('os');
448
+ const path = require('path');
449
+ const fs = require('fs');
450
+ sendKeysVbsPath = path.join(os.tmpdir(), 'superbased-paste.vbs');
451
+ fs.writeFileSync(sendKeysVbsPath, 'CreateObject("WScript.Shell").SendKeys "^v"');
452
+ }
453
+ catch { /* ignore */ }
454
+ }
455
+ // Start warm mic — keeps ffmpeg process alive so dictation starts instantly
456
+ // (eliminates ~800ms dshow device open delay on each dictation)
457
+ (0, mic_capture_1.startWarmMic)();
300
458
  // Pre-cache text cleanup functions (avoids 250ms dynamic import on first dictation)
301
459
  try {
302
- const { removeFillerWords, deduplicateConsecutiveWords } = require('../electron/modules/dictation');
303
- cachedCleanupFns = { removeFillerWords, deduplicateConsecutiveWords };
460
+ const { removeFillerWords, deduplicateConsecutiveWords, normalizeTechnicalTerms, normalizeShortPhrase } = require('../electron/modules/dictation');
461
+ cachedCleanupFns = { removeFillerWords, deduplicateConsecutiveWords, normalizeTechnicalTerms, normalizeShortPhrase };
304
462
  }
305
463
  catch { /* not available */ }
306
464
  // Fetch Azure config + pre-load SDK (non-blocking)
@@ -333,6 +491,7 @@ async function initDictationHotkey() {
333
491
  }
334
492
  }
335
493
  async function teardownDictationHotkey() {
494
+ (0, mic_capture_1.shutdownWarmMic)();
336
495
  if (currentRecording) {
337
496
  currentRecording.cancel();
338
497
  currentRecording = null;
@@ -345,6 +504,12 @@ async function teardownDictationHotkey() {
345
504
  catch { /* ignore */ }
346
505
  realtimeActive = false;
347
506
  }
507
+ // Fully shut down the persistent Azure recognizer on exit
508
+ try {
509
+ const rt = cachedRt || await Promise.resolve().then(() => __importStar(require('../electron/modules/azure-speech-realtime')));
510
+ await rt.shutdownRecognizer();
511
+ }
512
+ catch { /* ignore */ }
348
513
  try {
349
514
  const { uIOhook } = await Promise.resolve().then(() => __importStar(require('uiohook-napi')));
350
515
  uIOhook.off('keydown', onKeyDown);