@thegitai/cli 1.7.0 → 1.9.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.
@@ -71,6 +71,44 @@ function normalizeChildMessage(raw) {
71
71
  offset: Number(raw.offset ?? 0),
72
72
  };
73
73
  }
74
+ if (raw.kind === 'voiceStarted') {
75
+ return {
76
+ op: 'event',
77
+ kind: 'voiceStarted',
78
+ recorder: String(raw.recorder ?? ''),
79
+ ...(typeof raw.path === 'string' ? { path: raw.path } : {}),
80
+ };
81
+ }
82
+ if (raw.kind === 'voiceLevel') {
83
+ return {
84
+ op: 'event',
85
+ kind: 'voiceLevel',
86
+ level: Number(raw.level ?? 0),
87
+ ...(typeof raw.audio === 'string' ? { audio: raw.audio } : {}),
88
+ ...(typeof raw.path === 'string' ? { path: raw.path } : {}),
89
+ };
90
+ }
91
+ if (raw.kind === 'voiceDone') {
92
+ return { op: 'event', kind: 'voiceDone', path: String(raw.path ?? ''), seconds: Number(raw.seconds ?? 0) };
93
+ }
94
+ if (raw.kind === 'voiceError') {
95
+ return {
96
+ op: 'event',
97
+ kind: 'voiceError',
98
+ code: String(raw.code ?? 'failed'),
99
+ detail: String(raw.detail ?? ''),
100
+ ...(typeof raw.path === 'string' ? { path: raw.path } : {}),
101
+ };
102
+ }
103
+ if (raw.kind === 'voiceProbe') {
104
+ return {
105
+ op: 'event',
106
+ kind: 'voiceProbe',
107
+ ok: raw.ok === true,
108
+ code: String(raw.code ?? ''),
109
+ detail: String(raw.detail ?? ''),
110
+ };
111
+ }
74
112
  if (raw.kind !== 'key') {
75
113
  return null;
76
114
  }
@@ -191,6 +229,18 @@ export function createRatatuiBridge() {
191
229
  setTitle(title) {
192
230
  writeParent({ op: 'title', text: title });
193
231
  },
232
+ voiceStart(path, maxSeconds) {
233
+ writeParent({ op: 'voiceStart', path, maxSeconds });
234
+ },
235
+ voiceStop() {
236
+ writeParent({ op: 'voiceStop' });
237
+ },
238
+ voiceCancel() {
239
+ writeParent({ op: 'voiceCancel' });
240
+ },
241
+ voiceProbe() {
242
+ writeParent({ op: 'voiceProbe' });
243
+ },
194
244
  async close() {
195
245
  if (closed)
196
246
  return;
@@ -1,4 +1,5 @@
1
1
  import { shortcutLabel } from '../../keyboard-shortcuts.js';
2
+ import { joinDictatedText, VOICE_GRADIENT, voiceClock, voiceHint, voiceLevelGlyph, voiceSpinner, voiceWave, } from './voice-dictation.js';
2
3
  import { modelPickerWindow, modelPickerScrollLabel } from './model-picker-window.js';
3
4
  import { fitModelLabel } from './model-label.js';
4
5
  import { projectModelEffort } from '../../project-model-preferences.js';
@@ -50,6 +51,28 @@ export function footerNotificationHint(status) {
50
51
  return '';
51
52
  }
52
53
  const OVERLAY_PANEL_MAX_WIDTH = 86;
54
+ function voiceTitle(state, at = Date.now()) {
55
+ const activity = state.voice;
56
+ if (!activity)
57
+ return null;
58
+ const muted = { color: mutedColor() };
59
+ if (activity.phase === 'warmup')
60
+ return line(span(' keep holding… ', muted));
61
+ if (activity.phase === 'starting')
62
+ return line(span(' ○ starting… ', muted));
63
+ if (activity.phase === 'transcribing') {
64
+ return line(span(` ${voiceSpinner(activity.tick)} `, { color: 'cyan' }), span('transcribing… ', muted));
65
+ }
66
+ const pulse = Math.floor(at / 500) % 2 === 0;
67
+ return line(span(' ● ', { color: 'red', bold: pulse, dim: !pulse }), span(`${voiceClock(activity, at)} `, muted), ...voiceWave(activity.levels).map((glyph, index) => span(glyph, { color: VOICE_GRADIENT[index] })), span(' listening… ', muted));
68
+ }
69
+ function voiceCursor(state, at = Date.now()) {
70
+ const activity = state.voice;
71
+ if (!activity || activity.phase !== 'recording')
72
+ return null;
73
+ const level = activity.levels[activity.levels.length - 1] ?? 0;
74
+ return span(voiceLevelGlyph(level), { color: VOICE_GRADIENT[Math.floor(at / 150) % VOICE_GRADIENT.length] });
75
+ }
53
76
  const USER_INPUT_PANEL_MAX_WIDTH = 120;
54
77
  const OVERLAY_PANEL_MARGIN_LINES = 2;
55
78
  const OVERLAY_PANEL_MARGIN_MIN_ROWS = 30;
@@ -73,13 +96,13 @@ function composerMarkerMask(text) {
73
96
  }
74
97
  return mask;
75
98
  }
76
- function composerRowSpans(text, mask, cursorCol) {
99
+ function composerRowSpans(text, mask, cursorCol, dim = [], cursorSpan = null) {
77
100
  const spans = [];
78
- const push = (value, marker, cursor) => {
101
+ const push = (value, marker, cursor, faded = false) => {
79
102
  if (!value)
80
103
  return;
81
104
  spans.push(span(value, {
82
- ...(marker ? { color: 'cyan' } : {}),
105
+ ...(marker ? { color: 'cyan' } : faded ? { color: mutedColor() } : {}),
83
106
  ...(cursor ? { inverse: true } : {}),
84
107
  }));
85
108
  };
@@ -87,10 +110,11 @@ function composerRowSpans(text, mask, cursorCol) {
87
110
  const flushTo = (end) => {
88
111
  while (cut < end) {
89
112
  const marker = mask[cut] ?? false;
113
+ const faded = dim[cut] ?? false;
90
114
  let runEnd = cut + 1;
91
- while (runEnd < end && (mask[runEnd] ?? false) === marker)
115
+ while (runEnd < end && (mask[runEnd] ?? false) === marker && (dim[runEnd] ?? false) === faded)
92
116
  runEnd += 1;
93
- push(text.slice(cut, runEnd), marker, false);
117
+ push(text.slice(cut, runEnd), marker, false, faded);
94
118
  cut = runEnd;
95
119
  }
96
120
  };
@@ -99,15 +123,18 @@ function composerRowSpans(text, mask, cursorCol) {
99
123
  return spans;
100
124
  }
101
125
  flushTo(Math.min(cursorCol, text.length));
102
- push(text[cursorCol] ?? ' ', mask[cursorCol] ?? false, true);
126
+ if (cursorSpan && cursorCol >= text.length)
127
+ spans.push(cursorSpan);
128
+ else
129
+ push(text[cursorCol] ?? ' ', mask[cursorCol] ?? false, true);
103
130
  cut = Math.min(cursorCol + 1, text.length);
104
131
  flushTo(text.length);
105
132
  return spans;
106
133
  }
107
- function buildComposerInputLines(input, cursor, promptLabel, placeholder, width) {
134
+ function buildComposerInputLines(input, cursor, promptLabel, placeholder, width, { dim, cursorSpan = null } = {}) {
108
135
  if (!input) {
109
136
  return [
110
- line(span(promptLabel, { color: 'cyan' }), span(' ', { inverse: true }), span(placeholder, { color: mutedColor() })),
137
+ line(span(promptLabel, { color: 'cyan' }), cursorSpan ?? span(' ', { inverse: true }), span(placeholder, { color: mutedColor() })),
111
138
  ];
112
139
  }
113
140
  const labelWidth = promptLabel.length;
@@ -121,6 +148,11 @@ function buildComposerInputLines(input, cursor, promptLabel, placeholder, width)
121
148
  consumed += row.length;
122
149
  }
123
150
  const mask = composerMarkerMask(rows.join(''));
151
+ const rowsOffset = (offset) => offset - (input.slice(0, offset).match(/[\r\n]/g)?.length ?? 0);
152
+ const [dimStart, dimEnd] = dim ? [rowsOffset(dim[0]), rowsOffset(dim[1])] : [0, 0];
153
+ const dimMask = dim
154
+ ? Array.from({ length: consumed }, (_, index) => index >= dimStart && index < dimEnd)
155
+ : [];
124
156
  return rows
125
157
  .slice(firstRow, firstRow + COMPOSER_INPUT_MAX_ROWS)
126
158
  .map((text, index) => {
@@ -129,7 +161,7 @@ function buildComposerInputLines(input, cursor, promptLabel, placeholder, width)
129
161
  const label = index === 0
130
162
  ? span(promptLabel, { color: 'cyan' })
131
163
  : span(' '.repeat(labelWidth));
132
- return line(label, ...composerRowSpans(text, mask.slice(rowStart, rowStart + text.length), absoluteRow === cursorRow ? cursorCol : null));
164
+ return line(label, ...composerRowSpans(text, mask.slice(rowStart, rowStart + text.length), absoluteRow === cursorRow ? cursorCol : null, dimMask.slice(rowStart, rowStart + text.length), cursorSpan));
133
165
  });
134
166
  }
135
167
  function getEntryColor(kind) {
@@ -1649,14 +1681,27 @@ export function buildTuiFrame(state, cols, rows, spinnerFrame, elapsedSeconds, n
1649
1681
  }
1650
1682
  else {
1651
1683
  const promptLabel = composerPromptLabel(state);
1652
- const placeholder = state.busy
1684
+ const basePlaceholder = state.busy
1653
1685
  ? 'Type to queue the next message'
1654
1686
  : 'Type a request or /help';
1655
- composerLines.push(...buildComposerInputLines(state.input, state.cursor, promptLabel, placeholder, contentWidth));
1687
+ const placeholder = state.voice
1688
+ ? ''
1689
+ : state.voiceEnabled && state.voiceHint
1690
+ ? `${basePlaceholder} · ${voiceHint({ shortcuts: state.shortcuts ?? {}, voiceMode: state.voiceMode ?? 'hold' })}`
1691
+ : basePlaceholder;
1692
+ const interim = state.voice?.interim.trim() ?? '';
1693
+ const shown = interim
1694
+ ? joinDictatedText(state.input, state.cursor, interim)
1695
+ : { input: state.input, cursor: state.cursor };
1696
+ composerLines.push(...buildComposerInputLines(shown.input, shown.cursor, promptLabel, placeholder, contentWidth, {
1697
+ ...(interim ? { dim: [shown.cursor - interim.length, shown.cursor] } : {}),
1698
+ cursorSpan: voiceCursor(state),
1699
+ }));
1656
1700
  }
1657
1701
  sections.push({
1658
1702
  kind: 'composer',
1659
1703
  lines: [...composerLines, plainLine(''), ...composerFooterLines(state, contentWidth)],
1704
+ ...(voiceTitle(state) ? { title: voiceTitle(state) } : {}),
1660
1705
  });
1661
1706
  }
1662
1707
  if (state.userInputPrompt) {
@@ -228,6 +228,8 @@ export function handleShellKeyEvent(store, handlers, event) {
228
228
  if (event.kind !== 'key')
229
229
  return;
230
230
  const key = event;
231
+ if (handlers.onVoiceKey?.(key))
232
+ return;
231
233
  const state = store.getState();
232
234
  const commandPaletteActive = shouldShowCommandPalette(state);
233
235
  const commandSuggestions = commandPaletteActive
@@ -6,6 +6,7 @@ export function shortcutsPanelAvailable(state) {
6
6
  !state.sudoPrompt &&
7
7
  !state.userInputPrompt &&
8
8
  !state.queuedMessage &&
9
+ !state.voice &&
9
10
  !state.input &&
10
11
  (state.cursor ?? 0) === 0 &&
11
12
  (state.pastedChunks?.length ?? 0) === 0 &&
@@ -29,6 +30,7 @@ export function buildShortcutGroups(platform = process.platform, shortcuts = {})
29
30
  { keys: 'Esc', description: 'Clear the composer' },
30
31
  { keys: 'Ctrl+C', description: 'Clear the composer, or quit when empty' },
31
32
  { keys: key('notifications'), description: 'Desktop notifications - toggle on or off' },
33
+ { keys: `Hold ${key('pushToTalk')}`, description: 'Dictate into the message, once /voice is on' },
32
34
  { keys: '/keybindings', description: 'Change these shortcuts' },
33
35
  ],
34
36
  },
@@ -0,0 +1,438 @@
1
+ import { existsSync, readFileSync, rmSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { matchesShortcut, shortcutLabel } from '../../keyboard-shortcuts.js';
5
+ export const VOICE_MAX_SECONDS = 120;
6
+ const REPEAT_GAP_MS = 150;
7
+ const RUN_RESET_MS = 1000;
8
+ const FIRST_RELEASE_MS = 750;
9
+ const MIN_RELEASE_MS = 260;
10
+ const TAP_DEBOUNCE_MS = 180;
11
+ const MIN_SECONDS = 0.4;
12
+ const SPEECH_LEVEL = 12;
13
+ const LOUD_LEVEL = 30;
14
+ const SILENCE_STOP_MS = 15_000;
15
+ const LEVEL_HISTORY = 8;
16
+ const PROBE_TIMEOUT_MS = 5000;
17
+ const UNHEARD_BEFORE_HINT = 3;
18
+ export function voiceKeyLabel(shortcuts = {}) {
19
+ return shortcutLabel('pushToTalk', shortcuts);
20
+ }
21
+ export function voiceHint(state) {
22
+ return `${state.voiceMode === 'tap' ? 'tap' : 'hold'} ${voiceKeyLabel(state.shortcuts).toLowerCase()} to speak`;
23
+ }
24
+ function isPlainSpace(key) {
25
+ return key.input === ' ' && !key.ctrl && !key.meta;
26
+ }
27
+ function isCancelKey(key) {
28
+ return key.escape || (key.ctrl && !key.meta && key.input.toLowerCase() === 'c');
29
+ }
30
+ export function joinDictatedText(input, cursor, text) {
31
+ const clean = text.trim();
32
+ if (!clean)
33
+ return { input, cursor };
34
+ const before = input.slice(0, cursor);
35
+ const after = input.slice(cursor);
36
+ const lead = before && !/\s$/.test(before) ? ' ' : '';
37
+ const trail = after && !/^\s/.test(after) ? ' ' : '';
38
+ const inserted = `${lead}${clean}${trail}`;
39
+ return { input: `${before}${inserted}${after}`, cursor: before.length + lead.length + clean.length };
40
+ }
41
+ export function createVoiceDictation(deps) {
42
+ const now = deps.now ?? (() => Date.now());
43
+ let run = null;
44
+ let lastPush = 0;
45
+ let pushes = 0;
46
+ let releaseAfter = FIRST_RELEASE_MS;
47
+ let started = false;
48
+ let stopRequested = false;
49
+ let maxLevel = 0;
50
+ let lastLoud = 0;
51
+ let file = null;
52
+ let timer = null;
53
+ let upload = null;
54
+ let probeWaiter = null;
55
+ let stream = null;
56
+ let spinner = null;
57
+ let warmupTimer = null;
58
+ let unheard = 0;
59
+ const heardNothing = () => {
60
+ unheard += 1;
61
+ if (unheard < UNHEARD_BEFORE_HINT)
62
+ return;
63
+ unheard = 0;
64
+ deps.notice(`Nothing was heard in the last ${UNHEARD_BEFORE_HINT} recordings. ${voiceErrorMessage('silent')}`);
65
+ };
66
+ const activityOf = (phase, mode, startedAt = null) => ({
67
+ phase,
68
+ mode,
69
+ startedAt,
70
+ levels: [],
71
+ interim: '',
72
+ tick: 0,
73
+ });
74
+ const setActivity = (activity) => deps.update((state) => ({ ...state, voice: activity }));
75
+ const patchActivity = (patch) => deps.update((state) => (state.voice ? { ...state, voice: { ...state.voice, ...patch } } : state));
76
+ const closeStream = () => {
77
+ stream?.close();
78
+ stream = null;
79
+ };
80
+ const removeFile = () => {
81
+ if (file)
82
+ rmSync(file, { force: true });
83
+ file = null;
84
+ };
85
+ const clearTimer = () => {
86
+ if (timer)
87
+ clearInterval(timer);
88
+ timer = null;
89
+ };
90
+ const endWarmup = () => {
91
+ if (warmupTimer)
92
+ clearTimeout(warmupTimer);
93
+ warmupTimer = null;
94
+ if (deps.getState().voice?.phase === 'warmup')
95
+ setActivity(null);
96
+ };
97
+ const reset = () => {
98
+ clearTimer();
99
+ closeStream();
100
+ if (spinner)
101
+ clearInterval(spinner);
102
+ spinner = null;
103
+ removeFile();
104
+ run = null;
105
+ started = false;
106
+ stopRequested = false;
107
+ setActivity(null);
108
+ };
109
+ const pushKey = (key, shortcuts) => matchesShortcut('pushToTalk', key, shortcuts);
110
+ const begin = (mode) => {
111
+ const at = now();
112
+ file = path.join(deps.scratchDir(), `voice-${randomUUID()}.wav`);
113
+ started = false;
114
+ stopRequested = false;
115
+ maxLevel = 0;
116
+ lastLoud = at;
117
+ lastPush = at;
118
+ pushes = 0;
119
+ if (warmupTimer)
120
+ clearTimeout(warmupTimer);
121
+ warmupTimer = null;
122
+ setActivity(activityOf('starting', mode));
123
+ closeStream();
124
+ stream = deps.openStream?.((text) => {
125
+ const phase = deps.getState().voice?.phase;
126
+ if (phase === 'starting' || phase === 'recording' || phase === 'transcribing')
127
+ patchActivity({ interim: text });
128
+ }) ?? null;
129
+ deps.start(file, VOICE_MAX_SECONDS);
130
+ clearTimer();
131
+ timer = setInterval(tick, 50);
132
+ };
133
+ const finish = () => {
134
+ if (stopRequested)
135
+ return;
136
+ stopRequested = true;
137
+ clearTimer();
138
+ if (!started) {
139
+ deps.cancel();
140
+ reset();
141
+ return;
142
+ }
143
+ closeStream();
144
+ deps.stop();
145
+ };
146
+ const tick = () => {
147
+ const state = deps.getState();
148
+ const activity = state.voice;
149
+ if (!activity || activity.phase === 'transcribing')
150
+ return;
151
+ if (!deps.canDictate(state)) {
152
+ finish();
153
+ return;
154
+ }
155
+ const at = now();
156
+ if (activity.mode === 'hold' && at - lastPush > releaseAfter) {
157
+ finish();
158
+ return;
159
+ }
160
+ if (activity.mode === 'tap' && started && at - lastLoud > SILENCE_STOP_MS) {
161
+ deps.status('Stopped after 15 seconds of silence');
162
+ finish();
163
+ }
164
+ };
165
+ const cancel = () => {
166
+ const activity = deps.getState().voice;
167
+ if (!activity)
168
+ return;
169
+ upload?.abort();
170
+ upload = null;
171
+ if (activity.phase !== 'transcribing')
172
+ deps.cancel();
173
+ reset();
174
+ };
175
+ const handleKey = (key) => {
176
+ const state = deps.getState();
177
+ const activity = state.voice;
178
+ const at = now();
179
+ if (activity && activity.phase !== 'warmup') {
180
+ if (!deps.canDictate(state)) {
181
+ if (activity.phase !== 'transcribing')
182
+ finish();
183
+ if (activity.mode !== 'hold' || !pushKey(key, state.shortcuts))
184
+ return false;
185
+ const held = at - lastPush < releaseAfter;
186
+ if (held)
187
+ lastPush = at;
188
+ return held;
189
+ }
190
+ if (isCancelKey(key)) {
191
+ cancel();
192
+ return true;
193
+ }
194
+ if (key.returnKey) {
195
+ if (activity.phase !== 'transcribing')
196
+ finish();
197
+ return true;
198
+ }
199
+ if (!pushKey(key, state.shortcuts))
200
+ return false;
201
+ if (activity.phase === 'transcribing')
202
+ return true;
203
+ if (activity.mode === 'hold') {
204
+ const gap = at - lastPush;
205
+ lastPush = at;
206
+ pushes += 1;
207
+ if (pushes > 1 || gap < REPEAT_GAP_MS) {
208
+ releaseAfter = Math.min(FIRST_RELEASE_MS, Math.max(MIN_RELEASE_MS, gap * 3));
209
+ }
210
+ return true;
211
+ }
212
+ const gap = at - lastPush;
213
+ lastPush = at;
214
+ if (gap > TAP_DEBOUNCE_MS)
215
+ finish();
216
+ return true;
217
+ }
218
+ if (!state.voiceEnabled || !pushKey(key, state.shortcuts) || !deps.canDictate(state)) {
219
+ endWarmup();
220
+ run = null;
221
+ return false;
222
+ }
223
+ const space = isPlainSpace(key);
224
+ if (state.voiceMode === 'tap') {
225
+ if (space && (state.input || state.cursor))
226
+ return false;
227
+ begin('tap');
228
+ return true;
229
+ }
230
+ if (!space) {
231
+ releaseAfter = FIRST_RELEASE_MS;
232
+ begin('hold');
233
+ return true;
234
+ }
235
+ if (!run || at - run.times[run.times.length - 1] > RUN_RESET_MS) {
236
+ endWarmup();
237
+ run = { times: [at], input: state.input, cursor: state.cursor };
238
+ return false;
239
+ }
240
+ run.times.push(at);
241
+ const gaps = run.times.slice(1).map((time, index) => time - run.times[index]);
242
+ const fast = gaps.slice(-2).filter((gap) => gap < REPEAT_GAP_MS).length;
243
+ if (fast < 2) {
244
+ if (fast === 1) {
245
+ setActivity(activityOf('warmup', 'hold'));
246
+ if (warmupTimer)
247
+ clearTimeout(warmupTimer);
248
+ warmupTimer = setTimeout(endWarmup, REPEAT_GAP_MS * 2);
249
+ }
250
+ else
251
+ endWarmup();
252
+ return false;
253
+ }
254
+ const snapshot = run;
255
+ run = null;
256
+ releaseAfter = Math.max(MIN_RELEASE_MS, gaps[gaps.length - 1] * 3);
257
+ deps.update((current) => ({ ...current, input: snapshot.input, cursor: snapshot.cursor }));
258
+ begin('hold');
259
+ return true;
260
+ };
261
+ const transcribe = async (recording, seconds) => {
262
+ if (seconds < MIN_SECONDS) {
263
+ reset();
264
+ return;
265
+ }
266
+ if (maxLevel < SPEECH_LEVEL) {
267
+ reset();
268
+ heardNothing();
269
+ return;
270
+ }
271
+ patchActivity({ phase: 'transcribing', levels: [] });
272
+ if (spinner)
273
+ clearInterval(spinner);
274
+ spinner = setInterval(() => patchActivity({ tick: (deps.getState().voice?.tick ?? 0) + 1 }), 120);
275
+ const controller = new AbortController();
276
+ upload = controller;
277
+ try {
278
+ const audio = readFileSync(recording);
279
+ removeFile();
280
+ const text = await deps.transcribe(audio, controller.signal);
281
+ if (controller.signal.aborted)
282
+ return;
283
+ upload = null;
284
+ reset();
285
+ if (!text.trim()) {
286
+ heardNothing();
287
+ return;
288
+ }
289
+ unheard = 0;
290
+ deps.update((state) => ({ ...state, ...joinDictatedText(state.input, state.cursor, text) }));
291
+ }
292
+ catch (error) {
293
+ if (controller.signal.aborted)
294
+ return;
295
+ upload = null;
296
+ reset();
297
+ deps.report(error.message || "Couldn't transcribe that, try again.");
298
+ }
299
+ };
300
+ const handleEvent = (event) => {
301
+ if (event.kind === 'voiceProbe') {
302
+ probeWaiter?.({ ok: event.ok, code: event.code, detail: event.detail });
303
+ probeWaiter = null;
304
+ return;
305
+ }
306
+ const activity = deps.getState().voice;
307
+ if (event.kind !== 'voiceDone' && event.path !== undefined && event.path !== file)
308
+ return;
309
+ if (event.kind === 'voiceStarted') {
310
+ if (!activity || activity.phase !== 'starting')
311
+ return;
312
+ started = true;
313
+ lastLoud = now();
314
+ patchActivity({ phase: 'recording', startedAt: now() });
315
+ return;
316
+ }
317
+ if (event.kind === 'voiceLevel') {
318
+ if (!activity || activity.phase !== 'recording')
319
+ return;
320
+ maxLevel = Math.max(maxLevel, event.level);
321
+ if (event.level >= LOUD_LEVEL)
322
+ lastLoud = now();
323
+ if (event.audio && stream)
324
+ stream.send(Buffer.from(event.audio, 'base64'));
325
+ patchActivity({ levels: [...activity.levels, event.level].slice(-LEVEL_HISTORY) });
326
+ return;
327
+ }
328
+ if (event.kind === 'voiceDone') {
329
+ if (!activity || activity.phase === 'transcribing' || event.path !== file) {
330
+ rmSync(event.path, { force: true });
331
+ return;
332
+ }
333
+ clearTimer();
334
+ closeStream();
335
+ if (!stopRequested && activity.startedAt && now() - activity.startedAt >= VOICE_MAX_SECONDS * 1000 - 500) {
336
+ deps.status('Stopped at the 2-minute limit');
337
+ }
338
+ void transcribe(event.path, event.seconds);
339
+ return;
340
+ }
341
+ if (event.kind === 'voiceError') {
342
+ if (!activity)
343
+ return;
344
+ const quiet = stopRequested && !started;
345
+ reset();
346
+ if (event.code === 'silent')
347
+ heardNothing();
348
+ else if (!quiet)
349
+ deps.report(voiceErrorMessage(event.code, event.detail));
350
+ }
351
+ };
352
+ const probe = () => new Promise((resolve) => {
353
+ probeWaiter?.({ ok: false, code: 'failed', detail: '' });
354
+ const timeout = setTimeout(() => {
355
+ if (probeWaiter === done)
356
+ probeWaiter = null;
357
+ resolve({ ok: true, code: '', detail: '' });
358
+ }, PROBE_TIMEOUT_MS);
359
+ const done = (result) => {
360
+ clearTimeout(timeout);
361
+ resolve(result);
362
+ };
363
+ probeWaiter = done;
364
+ deps.probe();
365
+ });
366
+ const dispose = () => {
367
+ upload?.abort();
368
+ upload = null;
369
+ closeStream();
370
+ if (spinner)
371
+ clearInterval(spinner);
372
+ if (warmupTimer)
373
+ clearTimeout(warmupTimer);
374
+ warmupTimer = null;
375
+ if (deps.getState().voice && deps.getState().voice?.phase !== 'transcribing')
376
+ deps.cancel();
377
+ clearTimer();
378
+ removeFile();
379
+ };
380
+ return { handleKey, handleEvent, cancel, probe, dispose };
381
+ }
382
+ function linuxInstallHint() {
383
+ const has = (program) => (process.env.PATH ?? '').split(':').some((entry) => entry && existsSync(path.join(entry, program)));
384
+ if (has('apt'))
385
+ return 'sudo apt install alsa-utils';
386
+ if (has('dnf'))
387
+ return 'sudo dnf install alsa-utils';
388
+ if (has('pacman'))
389
+ return 'sudo pacman -S alsa-utils';
390
+ if (has('zypper'))
391
+ return 'sudo zypper install alsa-utils';
392
+ if (has('apk'))
393
+ return 'sudo apk add alsa-utils';
394
+ return 'install alsa-utils, pulseaudio-utils or pipewire';
395
+ }
396
+ export function voiceErrorMessage(code, detail = '', platform = process.platform) {
397
+ if (code === 'noRecorder') {
398
+ return `Voice dictation needs an audio recorder (pw-record, parecord or arecord). Install one, then try again: ${linuxInstallHint()}`;
399
+ }
400
+ if (code === 'noMicrophone')
401
+ return 'No microphone found. Connect one or check your sound input settings, then try again.';
402
+ if (code === 'denied' || code === 'silent') {
403
+ if (platform === 'darwin') {
404
+ return code === 'denied'
405
+ ? 'Microphone access is off for your terminal. Open System Settings > Privacy & Security > Microphone, allow your terminal app, then restart it.'
406
+ : 'No sound from the microphone. If your terminal is not allowed yet, open System Settings > Privacy & Security > Microphone, allow it, then restart it.';
407
+ }
408
+ if (platform === 'win32') {
409
+ return code === 'denied'
410
+ ? 'Microphone access is blocked. Open Settings > Privacy & security > Microphone and turn on "Let desktop apps access your microphone".'
411
+ : 'No sound from the microphone. Check Settings > System > Sound > Input, and that desktop apps may use the microphone.';
412
+ }
413
+ return code === 'denied'
414
+ ? `Microphone access was denied${detail ? `: ${detail}` : '.'}`
415
+ : 'No sound from the microphone. Check your input device and its level in your sound settings.';
416
+ }
417
+ return `Couldn't start recording${detail ? `: ${detail}` : '.'}`;
418
+ }
419
+ export function isRemoteSession(env = process.env) {
420
+ return Boolean(env.SSH_CONNECTION || env.SSH_CLIENT || env.SSH_TTY);
421
+ }
422
+ export const VOICE_GRADIENT = [51, 45, 39, 33, 69, 105, 141, 177].map((index) => `ansi256(${index})`);
423
+ const LEVEL_GLYPHS = '▁▂▃▄▅▆▇█';
424
+ const SPINNER = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏';
425
+ export function voiceClock(activity, at = Date.now()) {
426
+ const elapsed = Math.max(0, Math.floor((at - (activity.startedAt ?? at)) / 1000));
427
+ return `${Math.floor(elapsed / 60)}:${String(elapsed % 60).padStart(2, '0')}`;
428
+ }
429
+ export function voiceLevelGlyph(level) {
430
+ return LEVEL_GLYPHS[Math.min(LEVEL_GLYPHS.length - 1, Math.max(0, Math.floor((level / 100) * LEVEL_GLYPHS.length)))];
431
+ }
432
+ export function voiceSpinner(tick) {
433
+ return SPINNER[tick % SPINNER.length];
434
+ }
435
+ export function voiceWave(levels) {
436
+ const recent = levels.slice(-LEVEL_HISTORY);
437
+ return [...Array(Math.max(0, LEVEL_HISTORY - recent.length)).fill(0), ...recent].map(voiceLevelGlyph);
438
+ }