ucode-agent 1.62.8 → 1.63.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 CHANGED
@@ -368,6 +368,7 @@ Everything after the frontmatter is the instruction.
368
368
  | `/undo` | put back every file the last turn changed |
369
369
  | `/look [url]` | open the running app and report what is on the page |
370
370
  | `/deploy [folder]` | put the app online and get its link |
371
+ | `/mic` | say what you want instead of typing it — same as `ctrl+t` |
371
372
  | `/stats` | time, steps and tokens this session |
372
373
  | `/doctor` | check that everything ucode needs is working |
373
374
  | `/skills` | what it knows how to do, and what is loaded |
@@ -380,6 +381,18 @@ Everything after the frontmatter is the instruction.
380
381
  `↑ ↓` scroll the conversation, or walk history once you are typing ·
381
382
  `tab` completes a command
382
383
 
384
+ ### Speak instead of typing
385
+
386
+ Press `ctrl+t` (or click `mic`, or type `/mic`) and say what you want —
387
+ "make me a quiz app about planets". The chip turns red while it listens.
388
+ `enter` stops and sends it; `ctrl+t` stops and puts the words in the box to
389
+ check first; `esc` throws it away. It stops by itself after two minutes.
390
+
391
+ Gemini writes down what you said, so nothing extra is needed beyond your key.
392
+ Recording uses what the computer already has: Windows' built-in recorder, `sox`
393
+ or `ffmpeg` on macOS (`brew install sox`), `arecord` or `sox` on Linux. If a
394
+ quiet mic is taken for silence, set `UCODE_MIC_QUIET` lower than 800.
395
+
383
396
  ## Options
384
397
 
385
398
  ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ucode-agent",
3
- "version": "1.62.8",
3
+ "version": "1.63.0",
4
4
  "description": "ucode - a terminal coding agent that reads, edits and runs your code, on Google Gemini models.",
5
5
  "type": "module",
6
6
  "main": "ucode.js",
package/src/core/loop.js CHANGED
@@ -28,7 +28,7 @@ import { spawn } from 'node:child_process';
28
28
 
29
29
  import {
30
30
  ask, model, setModel, modelName, modelList, contextLimit, rateLimits,
31
- estimateConversation, MODELS, DEFAULT_MODEL, PROVIDER, fallbackFor, backupFor,
31
+ estimateConversation, MODELS, DEFAULT_MODEL, PROVIDER, fallbackFor, backupFor, transcribe,
32
32
  } from './provider.js';
33
33
  import {
34
34
  tools, runTool, describe, setRoot, setConfirm, setRequest,
@@ -54,6 +54,7 @@ import { MAX_FILE_OUTPUT } from '../tools/shared.js';
54
54
  import { openInBrowser } from './opener.js';
55
55
  import { withScope, isNoise } from './scope.js';
56
56
  import { chooseFile, projectFiles, loadAttachments } from './attach.js';
57
+ import { startRecording, isSilent, cleanTranscript, MAX_RECORD_MS } from './voice.js';
57
58
  import { runDoctor } from './doctor.js';
58
59
  import { JS_LOGIC } from './jslogic.js';
59
60
  import { deploy } from '../tools/deploy.js';
@@ -1028,6 +1029,7 @@ export class Agent {
1028
1029
  };
1029
1030
  this.ui.onModeChange = () => this.showHeader({ clear: false });
1030
1031
  this.ui.onAttach = () => { this.attachFile().catch(() => {}); };
1032
+ this.ui.onMic = (action) => { this.mic(action).catch((err) => this.ui.error(err, { debug: this.debug })); };
1031
1033
  }
1032
1034
 
1033
1035
  for (const problem of this.skills.problems ?? []) {
@@ -1827,6 +1829,59 @@ export class Agent {
1827
1829
  }
1828
1830
  }
1829
1831
 
1832
+ /**
1833
+ * The mic button (ctrl+t, a click, or /mic). 'toggle' starts listening, or
1834
+ * stops and puts the words in the box; 'send' stops and sends them; 'cancel'
1835
+ * throws the recording away.
1836
+ */
1837
+ async mic(action = 'toggle') {
1838
+ const state = this.ui.listening;
1839
+ if (state === 'starting' || state === 'writing') return;
1840
+
1841
+ if (state !== 'listening') {
1842
+ if (action !== 'toggle') return;
1843
+ this.ui.setListening('starting');
1844
+ try {
1845
+ this.recording = await startRecording();
1846
+ } catch (err) {
1847
+ this.ui.setListening(null);
1848
+ this.ui.note(`mic: ${err.message}`);
1849
+ return;
1850
+ }
1851
+ this.ui.setListening('listening');
1852
+ this.micTimer = setTimeout(() => this.ui.onMic?.('toggle'), MAX_RECORD_MS);
1853
+ return;
1854
+ }
1855
+
1856
+ clearTimeout(this.micTimer);
1857
+ // Taken and the state moved on before any await, so a second press
1858
+ // while this one finishes finds nothing to stop.
1859
+ const recording = this.recording;
1860
+ this.recording = null;
1861
+ if (!recording) return;
1862
+ if (action === 'cancel') {
1863
+ this.ui.setListening(null);
1864
+ this.ui.flash('stopped listening');
1865
+ await recording.cancel();
1866
+ return;
1867
+ }
1868
+
1869
+ this.ui.setListening('writing');
1870
+ let text = '';
1871
+ try {
1872
+ const wav = await recording.stop();
1873
+ if (!wav || isSilent(wav)) {
1874
+ this.ui.note('mic: heard nothing — check the microphone is on, then speak a little louder');
1875
+ return;
1876
+ }
1877
+ text = cleanTranscript(await transcribe(wav));
1878
+ if (!text) this.ui.note('mic: could not make out any words — try again, closer to the microphone');
1879
+ } finally {
1880
+ this.ui.setListening(null);
1881
+ }
1882
+ if (text) this.ui.insertText(text, { send: action === 'send' });
1883
+ }
1884
+
1830
1885
  /** Show a URL or a page in the project in the desktop browser (see opener.js). UCODE_OPEN=0 turns it off. */
1831
1886
  openInBrowser(target) {
1832
1887
  if (!this.full || process.env.UCODE_OPEN === '0') return false;
@@ -2961,6 +3016,9 @@ export class Agent {
2961
3016
  case '/doctor': return this.cmdDoctor();
2962
3017
  case '/look': return this.cmdLook(arg);
2963
3018
  case '/deploy': return this.cmdDeploy(arg);
3019
+ case '/mic':
3020
+ if (this.ui.onMic) return this.mic('toggle');
3021
+ return this.ui.note('the mic works in the full-screen view — start ucode in a terminal window');
2964
3022
  case '/exit':
2965
3023
  case '/quit': return 'exit';
2966
3024
 
@@ -3031,6 +3089,7 @@ ${out.content}` });
3031
3089
  ['/doctor', 'check that everything ucode needs is working'],
3032
3090
  ['/look [url]', 'open the running app and report what is on the page'],
3033
3091
  ['/deploy [folder]', 'put the app online and get its link'],
3092
+ ['/mic', 'say what you want instead of typing it (or ctrl+t)'],
3034
3093
  ['/model', 'show the models and switch between them'],
3035
3094
  ['/resume', 'pick up an earlier conversation'],
3036
3095
  ['/new', 'save this one and start fresh'],
@@ -3049,6 +3108,7 @@ ${out.content}` });
3049
3108
  this.ui.blank();
3050
3109
  this.ui.write(dim(' /models, /session and /sessions do the same as /model and /resume.'));
3051
3110
  this.ui.write(dim(' ctrl+b swaps plan and build · + file (or ctrl+o) adds a picture or file · esc stops a running turn · ctrl+d quits'));
3111
+ this.ui.write(dim(' ctrl+t (or the mic button) listens: speak, then enter to send, ctrl+t to check it first, esc to cancel'));
3052
3112
  this.ui.blank();
3053
3113
  }
3054
3114
 
@@ -276,6 +276,37 @@ export function resetConnection() {
276
276
  client = null;
277
277
  }
278
278
 
279
+ const TRANSCRIBE_PROMPT =
280
+ 'Transcribe the speech in this recording word for word, in the language spoken. ' +
281
+ 'Reply with only the words spoken - no quotes, no notes. If nothing is said, reply with nothing.';
282
+
283
+ /**
284
+ * Write down what was said in a WAV recording (the mic button). Uses the
285
+ * session's model, and the backup model when that one is overloaded.
286
+ */
287
+ export async function transcribe(wav, { timeout = 45_000 } = {}) {
288
+ const request = (id) => connection().chat.completions.create({
289
+ model: id,
290
+ messages: [{
291
+ role: 'user',
292
+ content: [
293
+ { type: 'text', text: TRANSCRIBE_PROMPT },
294
+ { type: 'input_audio', input_audio: { data: wav.toString('base64'), format: 'wav' } },
295
+ ],
296
+ }],
297
+ }, { timeout });
298
+
299
+ let res;
300
+ try {
301
+ res = await request(current);
302
+ } catch (err) {
303
+ const backup = backupFor(current);
304
+ if (!backup) throw explain(err, current);
305
+ res = await request(backup).catch((again) => { throw explain(again, backup); });
306
+ }
307
+ return res.choices?.[0]?.message?.content ?? '';
308
+ }
309
+
279
310
  // ---------------------------------------------------------------------------
280
311
  // Live quota, taken from whatever rate-limit headers come back
281
312
  // ---------------------------------------------------------------------------
@@ -0,0 +1,172 @@
1
+ /**
2
+ * voice.js — the mic button: say what you want instead of typing it.
3
+ *
4
+ * Recording uses what the computer already has, so there is nothing to
5
+ * install on Windows: its own sound recorder API (winmm, driven through
6
+ * PowerShell). macOS uses sox or ffmpeg, Linux arecord or sox, whichever is
7
+ * there. The recording is sent to the same Gemini model as everything else,
8
+ * which writes down what was said (see transcribe in provider.js).
9
+ */
10
+
11
+ import { spawn } from 'node:child_process';
12
+ import { promises as fs } from 'node:fs';
13
+ import os from 'node:os';
14
+ import path from 'node:path';
15
+
16
+ /** Longest a recording runs before it stops by itself. */
17
+ export const MAX_RECORD_MS = 2 * 60_000;
18
+
19
+ /**
20
+ * Loudest sample (of 32767) below which a recording counts as silence. A quiet
21
+ * room measured ~400 on a laptop mic, speech ~3,000 and up. UCODE_MIC_QUIET
22
+ * tunes it for a mic that reads differently.
23
+ */
24
+ export const quietBelow = () => Number(process.env.UCODE_MIC_QUIET) || 800;
25
+
26
+ // winmm's MCI strings refuse long paths (error 304), so the file sits directly
27
+ // in the temp folder with a short name. The script says "ready" once it is
28
+ // recording, and saves when a line arrives on stdin.
29
+ const WINDOWS_SCRIPT = [
30
+ '$sig = \'[DllImport("winmm.dll", CharSet = CharSet.Unicode)] public static extern int mciSendString(string c, System.Text.StringBuilder r, int l, System.IntPtr h);\'',
31
+ '$w = Add-Type -MemberDefinition $sig -Name Mci -Namespace UcodeMic -PassThru',
32
+ 'function mci($c) { $r = $w::mciSendString($c, $null, 0, [IntPtr]::Zero); if ($r -ne 0) { [Console]::Out.WriteLine("mci-error $r"); exit 1 } }',
33
+ 'mci "open new type waveaudio alias ucodemic"',
34
+ 'mci "set ucodemic bitspersample 16 channels 1 samplespersec 16000 bytespersec 32000 alignment 2"',
35
+ 'mci "record ucodemic"',
36
+ '[Console]::Out.WriteLine("ready")',
37
+ '[void][Console]::In.ReadLine()',
38
+ 'mci "stop ucodemic"',
39
+ 'mci (\'save ucodemic "\' + $env:UCODE_MIC_FILE + \'"\')',
40
+ 'mci "close ucodemic"',
41
+ ].join('\n');
42
+
43
+ /**
44
+ * The recorders to try on this platform, in order. `stop` is how each is told
45
+ * to finish and write its file: a line on stdin, "q" on stdin, or SIGINT.
46
+ */
47
+ export function recordersFor(platform, file) {
48
+ if (platform === 'win32') {
49
+ const encoded = Buffer.from(WINDOWS_SCRIPT, 'utf16le').toString('base64');
50
+ return [{
51
+ cmd: 'powershell.exe',
52
+ args: ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded],
53
+ stop: 'line',
54
+ saysReady: true,
55
+ }];
56
+ }
57
+ const sox = { cmd: 'rec', args: ['-q', '-c', '1', '-r', '16000', '-b', '16', file], stop: 'SIGINT' };
58
+ if (platform === 'darwin') {
59
+ return [sox, {
60
+ cmd: 'ffmpeg',
61
+ args: ['-loglevel', 'error', '-f', 'avfoundation', '-i', ':0', '-ac', '1', '-ar', '16000', '-y', file],
62
+ stop: 'q',
63
+ }];
64
+ }
65
+ return [{ cmd: 'arecord', args: ['-q', '-f', 'S16_LE', '-r', '16000', '-c', '1', file], stop: 'SIGINT' }, sox];
66
+ }
67
+
68
+ const NO_RECORDER = {
69
+ darwin: 'No recorder found. Install one with: brew install sox',
70
+ linux: 'No recorder found. Install one with: sudo apt install alsa-utils',
71
+ };
72
+
73
+ /** Start one recorder; resolves once it is listening, rejects with the reason it could not. */
74
+ function launch(rec, file, run) {
75
+ return new Promise((resolve, reject) => {
76
+ const child = run(rec.cmd, rec.args, {
77
+ env: { ...process.env, UCODE_MIC_FILE: file },
78
+ windowsHide: true,
79
+ stdio: ['pipe', 'pipe', 'pipe'],
80
+ });
81
+ let out = '';
82
+ let settled = false;
83
+ const done = (fn, value) => { if (!settled) { settled = true; fn(value); } };
84
+
85
+ child.on('error', (err) => done(reject, err));
86
+ child.stdout?.on('data', (d) => {
87
+ out += d;
88
+ if (rec.saysReady && out.includes('ready')) done(resolve, child);
89
+ const code = /mci-error (\d+)/.exec(out)?.[1];
90
+ if (code) done(reject, new Error(`Windows could not use the microphone (error ${code}). Check one is plugged in and allowed in Settings › Privacy › Microphone.`));
91
+ });
92
+ child.on('exit', (code) => done(reject, new Error(`The recorder stopped before listening (exit ${code}). Check a microphone is connected.`)));
93
+ if (!rec.saysReady) child.on('spawn', () => done(resolve, child));
94
+ });
95
+ }
96
+
97
+ /**
98
+ * Start recording from the default microphone.
99
+ * Resolves to { stop() → Promise<Buffer|null>, cancel() → Promise<void> } once listening.
100
+ */
101
+ export async function startRecording({ platform = process.platform, run = spawn, dir = os.tmpdir() } = {}) {
102
+ // A private folder of its own, so no other user can guess or pre-place the file.
103
+ const folder = await fs.mkdtemp(path.join(dir, 'ucm-'));
104
+ const file = path.join(folder, 'mic.wav');
105
+ const remove = () => fs.rm(folder, { recursive: true, force: true }).catch(() => {});
106
+
107
+ let child = null;
108
+ let rec = null;
109
+ try {
110
+ for (const candidate of recordersFor(platform, file)) {
111
+ try {
112
+ child = await launch(candidate, file, run);
113
+ rec = candidate;
114
+ break;
115
+ } catch (err) {
116
+ if (err.code !== 'ENOENT') throw err;
117
+ }
118
+ }
119
+ } catch (err) {
120
+ await remove();
121
+ throw err;
122
+ }
123
+ if (!child) {
124
+ await remove();
125
+ throw new Error(NO_RECORDER[platform] ?? 'No sound recorder found on this computer.');
126
+ }
127
+
128
+ const closed = new Promise((resolve) => child.on('close', resolve));
129
+ // A recorder that will not finish is killed rather than waited on forever.
130
+ const finished = async () => {
131
+ const timer = setTimeout(() => child.kill('SIGKILL'), 10_000);
132
+ await closed;
133
+ clearTimeout(timer);
134
+ };
135
+
136
+ return {
137
+ async stop() {
138
+ if (rec.stop === 'line') child.stdin.write('\n');
139
+ else if (rec.stop === 'q') child.stdin.write('q');
140
+ else child.kill('SIGINT');
141
+ await finished();
142
+ const wav = await fs.readFile(file).catch(() => null);
143
+ await remove();
144
+ return wav;
145
+ },
146
+ async cancel() {
147
+ child.kill();
148
+ await finished();
149
+ await remove();
150
+ },
151
+ };
152
+ }
153
+
154
+ /** True when a 16-bit PCM WAV holds nothing louder than room noise, or under a third of a second. */
155
+ export function isSilent(wav, threshold = quietBelow()) {
156
+ const at = wav.indexOf('data');
157
+ const start = at >= 0 ? at + 8 : 44;
158
+ if (wav.length - start < 16000 * 2 / 3) return true;
159
+ for (let i = start; i + 1 < wav.length; i += 2) {
160
+ if (Math.abs(wav.readInt16LE(i)) >= threshold) return false;
161
+ }
162
+ return true;
163
+ }
164
+
165
+ /** What the model heard, as one line for the input box: no quotes, no line breaks. */
166
+ export function cleanTranscript(text) {
167
+ return String(text ?? '')
168
+ .replace(/\s+/g, ' ')
169
+ .trim()
170
+ .replace(/^["'“”]+|["'“”]+$/g, '')
171
+ .trim();
172
+ }
package/src/ui/screen.js CHANGED
@@ -40,7 +40,7 @@ import {
40
40
  theme, blue, sky, deep, dim, edge, ADDED, REMOVED, BANNER, BANNER_WIDTH, SPINNER,
41
41
  boxTop, boxBottom, boxRow, visLen, padVis, clip, wrapAnsi,
42
42
  shortenPath, asLabel, ensureColour, planLine, bare, narration, narrationMark, groupKind, groupLabel, groupTarget, runLine, planRows, tidyReply, trimAnswer,
43
- bannerPaint, RAIL, modeChip, ADD_CHIP, asNarrationLine } from './theme.js';
43
+ bannerPaint, RAIL, modeChip, ADD_CHIP, micChip, asNarrationLine } from './theme.js';
44
44
  import { FRAME_MS, spinnerGlyph, formatDuration, doneLine, workingLine, bannerSweep, SWEEP_MS } from './activity.js';
45
45
  import { gitBranch } from '../core/git.js';
46
46
  import { renderer, render } from './markdown.js';
@@ -60,7 +60,7 @@ export function isLabel(text) {
60
60
  export const COMMANDS = [
61
61
  '/help', '/model', '/models', '/session', '/sessions', '/resume',
62
62
  '/new', '/remember', '/skills', '/clear', '/search', '/copy', '/exit',
63
- '/stats', '/doctor', '/deploy', '/look', '/undo',
63
+ '/stats', '/doctor', '/deploy', '/look', '/undo', '/mic',
64
64
  ];
65
65
 
66
66
  // ANSI ----------------------------------------------------------------------
@@ -215,6 +215,12 @@ export class Screen {
215
215
  this.plusTo = 0;
216
216
  this.attachments = [];
217
217
  this.onAttach = null;
218
+ // The mic button: null when idle, else 'starting' | 'listening' | 'writing'.
219
+ // Ctrl+T starts and stops it; while it listens, enter stops and sends.
220
+ this.micFrom = 0;
221
+ this.micTo = 0;
222
+ this.listening = null;
223
+ this.onMic = null;
218
224
  this.onInterrupt = null;
219
225
  this.onModeChange = null;
220
226
  this.spinTimer = null;
@@ -808,7 +814,7 @@ export class Screen {
808
814
  ['dir', value(shortenPath(this.facts.cwd ?? this.cwd, room - 10))],
809
815
  branch && ['branch', value(branch)],
810
816
  VERSION && ['version', value(this.facts.update ? `${VERSION} → ${this.facts.update} next start` : VERSION)],
811
- ['keys', value('/help · esc interrupts · ctrl+b plan · ctrl+o file')],
817
+ ['keys', value('/help · ctrl+t mic · ctrl+o file · ctrl+b plan · esc stops')],
812
818
  ].filter(Boolean).slice(0, BANNER.length - 1);
813
819
 
814
820
  while (facts.length < BANNER.length - 1) facts.push(['', '']);
@@ -986,7 +992,8 @@ export class Screen {
986
992
  statusRow(width = this.width()) {
987
993
  const inner = width - 2; // the space between the two borders
988
994
  const chip = this.modeChip();
989
- const left = ` ${chip} ${ADD_CHIP} ${chalk.white(this.model || '—')}`;
995
+ const mic = micChip(this.listening);
996
+ const buttons = ` ${chip} ${ADD_CHIP} ${mic}`;
990
997
 
991
998
  // How long the turn has taken, back in the box beside the other two facts
992
999
  // about the session. It is not on the live line: that line says what is
@@ -996,16 +1003,24 @@ export class Screen {
996
1003
  const since = this.activity?.start ?? this.status.since ?? 0;
997
1004
  const running = this.busy() && since && now - since >= 1000;
998
1005
  const right = `${running ? `${dim(formatDuration(now - since))} ` : ''}${this.percentChip()} `;
1006
+ // On a narrow terminal the model name goes before any button does.
1007
+ const withModel = `${buttons} ${chalk.white(this.model || '—')}`;
1008
+ const left = visLen(withModel) + visLen(right) < inner ? withModel : buttons;
999
1009
 
1000
1010
  // Where a click on the bottom row still counts as hitting the mode chip.
1001
1011
  this.chipTo = 2 + visLen(chip);
1002
1012
  this.plusFrom = this.chipTo + 3; // after the two spaces
1003
1013
  this.plusTo = this.plusFrom + visLen(ADD_CHIP) - 1;
1014
+ this.micFrom = this.plusTo + 3;
1015
+ this.micTo = this.micFrom + visLen(mic) - 1;
1004
1016
 
1005
1017
  const between = Math.max(1, inner - visLen(left) - visLen(right));
1006
1018
  const files = this.attachments.map((f) => path.basename(f)).join(', ');
1007
- const middle = this.flashText ? dim(clip(this.flashText, between - 2))
1008
- : files ? sky(clip(`+ ${files}`, between - 2)) : '';
1019
+ // Room for the three spaces after it and at least one before.
1020
+ const room = between - 4;
1021
+ const middle = this.listening === 'listening' ? sky(clip('speak now · enter sends · ctrl+t stops · esc cancels', room))
1022
+ : this.flashText ? dim(clip(this.flashText, room))
1023
+ : files ? sky(clip(`+ ${files}`, room)) : '';
1009
1024
 
1010
1025
  const tail = middle ? `${middle} ` : '';
1011
1026
  const pad = Math.max(1, inner - visLen(left) - visLen(tail) - visLen(right));
@@ -1430,12 +1445,30 @@ export class Screen {
1430
1445
  if (row !== statusRow) return;
1431
1446
  if (col > g.left + 1 && col <= g.left + this.chipTo) this.toggleMode();
1432
1447
  else if (col >= g.left + this.plusFrom && col <= g.left + this.plusTo) this.onAttach?.();
1448
+ else if (col >= g.left + this.micFrom && col <= g.left + this.micTo) this.onMic?.('toggle');
1433
1449
  return;
1434
1450
  }
1435
- // The mode chip and the "+ file" button, at the left of the bottom row.
1451
+ // The mode chip, "+ file" and mic buttons, at the left of the bottom row.
1436
1452
  if (row !== this.rows - 1) return;
1437
1453
  if (col >= 2 && col <= this.chipTo) this.toggleMode();
1438
1454
  else if (col >= this.plusFrom && col <= this.plusTo) this.onAttach?.();
1455
+ else if (col >= this.micFrom && col <= this.micTo) this.onMic?.('toggle');
1456
+ }
1457
+
1458
+ /** The mic's state, for the chip: null, 'starting', 'listening' or 'writing'. */
1459
+ setListening(state) {
1460
+ this.listening = state;
1461
+ this.render();
1462
+ }
1463
+
1464
+ /** Words from the mic, into the box at the cursor; `send` presses enter for them. */
1465
+ insertText(text, { send = false } = {}) {
1466
+ const before = this.buffer.slice(0, this.cursor);
1467
+ const joined = before && !before.endsWith(' ') ? `${before} ${text}` : before + text;
1468
+ this.buffer = joined + this.buffer.slice(this.cursor);
1469
+ this.cursor = joined.length;
1470
+ if (send) this.onKey('\r');
1471
+ else this.render();
1439
1472
  }
1440
1473
 
1441
1474
  /** A file chosen with "+ file", to go with the next message. */
@@ -1470,6 +1503,12 @@ export class Screen {
1470
1503
  return;
1471
1504
  }
1472
1505
 
1506
+ // While the mic listens, enter means "done, send it" and esc means "never mind".
1507
+ if (this.listening === 'listening') {
1508
+ if (key === '\r' || key === '\n') { this.onMic?.('send'); return; }
1509
+ if (key === ESC || key === '\x03') { this.onMic?.('cancel'); return; }
1510
+ }
1511
+
1473
1512
  switch (key) {
1474
1513
  case '\r':
1475
1514
  case '\n': {
@@ -1516,6 +1555,10 @@ export class Screen {
1516
1555
  this.onAttach?.();
1517
1556
  return;
1518
1557
 
1558
+ case '\x14': // ctrl+t — the mic button: start listening, or stop and put the words in the box
1559
+ this.onMic?.('toggle');
1560
+ return;
1561
+
1519
1562
  case '\x15': // ctrl+u — clear the line; on an empty line, the attached files
1520
1563
  if (!this.buffer) this.attachments = [];
1521
1564
  this.buffer = this.buffer.slice(this.cursor);
package/src/ui/theme.js CHANGED
@@ -130,6 +130,13 @@ export const modeChip = (mode) =>
130
130
  /** The "+ file" button beside the mode chip, in the quieter of the two chip styles. */
131
131
  export const ADD_CHIP = PLAN_CHIP(' + file ');
132
132
 
133
+ /** The mic button beside it: quiet when idle, red while it is listening. */
134
+ const LISTEN_CHIP = chalk.bgHex('#e5484d').hex('#ffffff').bold;
135
+ export const micChip = (state) =>
136
+ state === 'listening' ? LISTEN_CHIP(' ● listening ')
137
+ : state ? PLAN_CHIP(` ${state === 'starting' ? 'starting' : 'writing'}… `)
138
+ : PLAN_CHIP(' mic ');
139
+
133
140
  /** The spinner. Braille dots, because they animate in place without jitter. */
134
141
  export const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
135
142