Your team of AI agents, on your Mac, Windows or Linux. Agents that talk in channels, write code, review each other and use your tools, on the Claude Code, Codex, OpenCode or Pi you already have. Anything that touches the real world waits for your yes.
TypeScript agent-teamagentic-aiai-agentsai-assistantclaude-codecodexcursorelectrongrokgrok-bot-alternativelinuxlocal-firstmacosmcpmulti-agentopenclaw-alternativeopencodewindows
Dictate messages with whisper, turned on with one click (#60)
Rayanne B. Lima3556ad01f7d6
diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.ymlindex 91c49f1..3839011 100644--- a/.github/workflows/linux.yml+++ b/.github/workflows/linux.yml@@ -55,6 +55,7 @@ jobs:sudo gem install --no-document fpm- run: npm ci- run: npm run build+ - run: node scripts/whisper.mjs linux ${{ matrix.arch }} # dictation's whisper-cli, packed in the app- name: Build the .deb and the AppImagerun: npx electron-builder --linux deb AppImage --${{ matrix.arch }} --publish never --config.directories.output=dist-linuxenv:diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.ymlindex 6b97d92..49c45de 100644--- a/.github/workflows/windows.yml+++ b/.github/workflows/windows.yml@@ -44,6 +44,7 @@ jobs:cache: npm- run: npm ci- run: npm run build+ - run: node scripts/whisper.mjs win x64 # dictation's whisper-cli, packed in the app- name: Build the installerrun: npx electron-builder --win nsis --x64 --publish never --config.directories.output=dist-win- run: ls -la dist-win && cat dist-win/latest.ymldiff --git a/.gitignore b/.gitignoreindex 9e56a59..9215306 100644--- a/.gitignore+++ b/.gitignore@@ -5,3 +5,4 @@ dist.DS_Store.tucano.wrangler+build/whisperdiff --git a/build/entitlements.mac.plist b/build/entitlements.mac.plistindex 1be75a0..daa1d38 100644--- a/build/entitlements.mac.plist+++ b/build/entitlements.mac.plist@@ -13,5 +13,8 @@<!-- "Open in Terminal" drives the Terminal app with osascript. --><key>com.apple.security.automation.apple-events</key><true/>+ <!-- Dictation in the composer. -->+ <key>com.apple.security.device.audio-input</key>+ <true/></dict></plist>diff --git a/package.json b/package.jsonindex ceb8494..a0d4f96 100644--- a/package.json+++ b/package.json@@ -82,7 +82,8 @@"entitlementsInherit": "build/entitlements.mac.plist","notarize": false,"extendInfo": {- "NSAppleEventsUsageDescription": "Tucano opens the Terminal for you when you ask it to."+ "NSAppleEventsUsageDescription": "Tucano opens the Terminal for you when you ask it to.",+ "NSMicrophoneUsageDescription": "Tucano listens only while you dictate, from your click on the microphone until the next one, to turn what you say into text on this computer."}},"win": {@@ -139,6 +140,14 @@{"from": "build/icon.png","to": "icon.png"+ },+ {+ "from": "build/whisper/${os}-${arch}",+ "to": "whisper",+ "filter": [+ "**/*",+ "!VERSION"+ ]}]}diff --git a/scripts/release.sh b/scripts/release.shindex cb0b380..3633669 100755--- a/scripts/release.sh+++ b/scripts/release.sh@@ -57,6 +57,9 @@ IDENTITY="${TUCANO_SIGN_IDENTITY:-$(security find-identity -v -p codesigning | aexport APPLE_KEYCHAIN_PROFILE="${TUCANO_NOTARY_PROFILE:-tucano}"npm run build+# Dictation's whisper-cli, built for each chip and signed with the app (scripts/whisper.mjs).+node scripts/whisper.mjs mac arm64+node scripts/whisper.mjs mac x64npx electron-builder --mac dmg zip --arm64 --x64 --publish never \--config.directories.output="$OUT" \--config.mac.identity="$IDENTITY" \diff --git a/scripts/whisper.mjs b/scripts/whisper.mjsnew file mode 100644index 0000000..4e04319--- /dev/null+++ b/scripts/whisper.mjs@@ -0,0 +1,98 @@+#!/usr/bin/env node+// The whisper-cli that dictation runs, packed inside the app so nobody has to install it:+// build/whisper/<os>-<arch>/, which electron-builder copies to Resources/whisper.+//+// node scripts/whisper.mjs mac arm64 builds it from whisper.cpp's source (Metal, static)+// node scripts/whisper.mjs win x64 takes whisper.cpp's own build of the same version+// node scripts/whisper.mjs linux x64|arm64+//+// Same version everywhere. A download is checked against its SHA-256 before it's opened.+import { execFileSync } from 'node:child_process'+import { createHash } from 'node:crypto'+import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { homedir, tmpdir } from 'node:os'+import { join } from 'node:path'++const TAG = 'v1.9.5' // the source, for the Mac+const BUILD = 'b5454' // whisper.cpp's own binaries of that version, for Windows and Linux+const PREBUILT = {+ 'win-x64': { file: 'whisper-bin-x64.zip', sha256: '6ba69e3482d7826214f90a6a9c84ca07782aec1e1d0c6a7c30c994fd5d816ccb' },+ 'linux-x64': { file: 'whisper-bin-ubuntu-x64.tar.gz', sha256: 'a72becf15d7917f990f6313867a52638b82b7f9ef237fb0c980dac56a135781c' },+ 'linux-arm64': { file: 'whisper-bin-ubuntu-arm64.tar.gz', sha256: '6b95ebfc60447df48e70ef00a73bdc3f41679ed2d01ef465827206a2ff325149' }+}++const [os, arch] = process.argv.slice(2)+const target = `${os}-${arch}`+const root = join(import.meta.dirname, '..')+const out = join(root, 'build', 'whisper', target)+const stamp = join(out, 'VERSION')+const want = os === 'mac' ? TAG : BUILD+if (existsSync(stamp) && readFileSync(stamp, 'utf8').trim() === want) {+ console.log(`whisper-cli ${want} for ${target}: already there`)+ process.exit(0)+}+const run = (cmd, args, opts = {}) => execFileSync(cmd, args, { stdio: 'inherit', ...opts })+rmSync(out, { recursive: true, force: true })+mkdirSync(out, { recursive: true })++if (os === 'mac') {+ if (arch !== 'arm64' && arch !== 'x64') throw new Error(`no Mac build for ${arch}`)+ const cache = join(homedir(), 'Library', 'Caches', 'tucano')+ // cmake: the one on the PATH, or one kept in a venv of our own (nothing installed system-wide)+ let cmake = 'cmake'+ try {+ execFileSync(cmake, ['--version'], { stdio: 'ignore' })+ } catch {+ const venv = join(cache, 'cmake-venv')+ cmake = join(venv, 'bin', 'cmake')+ if (!existsSync(cmake)) {+ run('python3', ['-m', 'venv', venv])+ run(join(venv, 'bin', 'pip'), ['install', '-q', 'cmake'])+ }+ }+ const src = join(cache, `whisper.cpp-${TAG}`)+ if (!existsSync(join(src, 'CMakeLists.txt'))) run('git', ['clone', '-q', '--depth', '1', '--branch', TAG, 'https://github.com/ggml-org/whisper.cpp.git', src])+ const dir = join(src, `build-${arch}`)+ const flags = [+ '-DCMAKE_BUILD_TYPE=Release',+ `-DCMAKE_OSX_ARCHITECTURES=${arch === 'x64' ? 'x86_64' : 'arm64'}`,+ '-DCMAKE_OSX_DEPLOYMENT_TARGET=12.0',+ '-DBUILD_SHARED_LIBS=OFF', // one file, nothing to load beside it+ '-DGGML_METAL=ON',+ '-DGGML_METAL_EMBED_LIBRARY=ON',+ '-DGGML_NATIVE=OFF', // for every Mac of that kind, not just this one+ '-DWHISPER_BUILD_TESTS=OFF',+ '-DWHISPER_BUILD_SERVER=OFF',+ '-DWHISPER_SDL2=OFF',+ ...(arch === 'x64' ? ['-DGGML_AVX=ON', '-DGGML_AVX2=ON', '-DGGML_FMA=ON', '-DGGML_F16C=ON'] : [])+ ]+ run(cmake, ['-S', src, '-B', dir, ...flags], { stdio: 'ignore' })+ run(cmake, ['--build', dir, '--config', 'Release', '-j', '8', '--target', 'whisper-cli'], { stdio: 'ignore' })+ copyFileSync(join(dir, 'bin', 'whisper-cli'), join(out, 'whisper-cli'))+} else {+ const pre = PREBUILT[target]+ if (!pre) throw new Error(`no whisper-cli for ${target}`)+ const tmp = mkdtempSync(join(tmpdir(), 'whisper-'))+ try {+ const file = join(tmp, pre.file)+ run('curl', ['-fsSL', '-o', file, `https://github.com/ggml-org/whisper.cpp/releases/download/${BUILD}/${pre.file}`])+ const got = createHash('sha256').update(readFileSync(file)).digest('hex')+ if (got !== pre.sha256) throw new Error(`${pre.file}: SHA-256 ${got}, expected ${pre.sha256}`)+ // Windows' own unzip: the tar first on a runner's PATH is Git's, which reads "C:" as a host and opens no .zip+ if (os === 'win') run('powershell', ['-NoProfile', '-Command', `Expand-Archive -LiteralPath '${file}' -DestinationPath '${tmp}' -Force`])+ else run('tar', ['-xf', file, '-C', tmp])+ // the program and the libraries it loads from its own folder; not the tests, benchmarks or server+ const from = readdirSync(tmp, { withFileTypes: true }).find((e) => e.isDirectory())+ if (!from) throw new Error(`${pre.file} has no folder`)+ const dir = join(tmp, from.name)+ // on Linux, the names whisper-cli asks for (each library is there three times, by its links)+ // and the CPU variants ggml picks from at start+ const keep = (n) => (os === 'win' ? n === 'whisper-cli.exe' || n.endsWith('.dll') : n === 'whisper-cli' || /^lib(whisper|ggml|ggml-base)\.so\.\d+$/.test(n) || /^libggml-cpu-[\w-]+\.so$/.test(n))+ for (const n of readdirSync(dir).filter(keep)) copyFileSync(join(dir, n), join(out, n))+ if (!existsSync(join(out, os === 'win' ? 'whisper-cli.exe' : 'whisper-cli'))) throw new Error(`${pre.file} has no whisper-cli`)+ } finally {+ rmSync(tmp, { recursive: true, force: true })+ }+}+writeFileSync(stamp, `${want}\n`)+console.log(`whisper-cli ${want} for ${target}: ${out}`)diff --git a/src/core/index.ts b/src/core/index.tsindex 5c34961..2236c44 100644--- a/src/core/index.ts+++ b/src/core/index.ts@@ -1,6 +1,8 @@// The core runs in an Electron utility process: database, engines and runs// live here so the window never waits on agent work. The renderer talks to it// over a MessagePort handed out by the main process.+import { voiceRefusal } from '../shared/voice'+import { ModelDownload, Transcriber, voiceStatus, warmUp } from './transcribe'import { createHash } from 'node:crypto'import { execFile, spawn } from 'node:child_process'import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'@@ -376,6 +378,14 @@ const chrome =: undefinedconst host: BrowserHost = chrome ? (agentId, op, args) => chrome.run(agentId, op, args) : electronHost+const transcriber = new Transcriber()+// Dictation's places: the whisper-cli inside the app, and the folder for the models it downloads.+const voicePlaces = { ...(process.env['TUCANO_WHISPER'] ? { bundled: process.env['TUCANO_WHISPER'] } : {}), models: join(dataDir, 'voice') }+const modelDownload = new ModelDownload(voicePlaces.models, () => emit({ type: 'voice' }), fetch, undefined, () => void dictation().then((s) => warmUp(transcriber, s)))+const dictation = async () => {+ const s = voiceStatus(settings().voice, await loginEnv(), undefined, voicePlaces)+ return { ...s, ...(modelDownload.progress ? { downloading: modelDownload.progress } : {}), ...(modelDownload.error ? { error: modelDownload.error } : {}) }+}// Out of the environment before anything starts: commands the agents run inherit it.const localKey = process.env['TUCANO_LOCAL_KEY']delete process.env['TUCANO_LOCAL_KEY']@@ -918,7 +928,19 @@ const api: Api = {return { ok: true, message: L(`${m.id} respondeu em ${secs} s: “${text.trim().slice(0, 60)}”`, `${m.id} answered in ${secs} s: “${text.trim().slice(0, 60)}”`) }},+ voiceStatus: () => dictation(),+ transcribe: async ({ id, audio }) => {+ const voice = settings().voice+ return { text: await transcriber.transcribe(id, audio, await dictation(), voice?.detect ? undefined : settings().language) }+ },+ voiceDownload: ({ model }) => void modelDownload.start(model),+ voiceCancelDownload: () => modelDownload.cancel(),+ voiceRemoveModel: ({ model }) => modelDownload.remove(model),+ cancelTranscribe: ({ id }) => transcriber.cancel(id),+updateSettings: ({ patch: { jevKey: _computed, telegram: _phone, accounts: _own, ...patch } }) => {+ const why = voiceRefusal(patch.voice)+ if (why) throw new Error(why)db.setSettings(patch)if (patch.paused !== undefined) runner.setPaused(patch.paused)if (patch.openAtLogin !== undefined) toMain({ type: 'login_item', open: patch.openAtLogin })diff --git a/src/core/transcribe.ts b/src/core/transcribe.tsnew file mode 100644index 0000000..d5092a2--- /dev/null+++ b/src/core/transcribe.ts@@ -0,0 +1,193 @@+// Dictation: audio from the window, turned into text on this machine with whisper-cli. The+// program comes inside the app (scripts/whisper.mjs); the model, hundreds of MB, is downloaded+// when the person turns dictation on. One already installed (Homebrew, a path in Settings) is+// used as is. The audio leaves no file behind.+import { spawn, type ChildProcess } from 'node:child_process'+import { createHash } from 'node:crypto'+import { createWriteStream, existsSync, mkdirSync, mkdtempSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs'+import { homedir, tmpdir } from 'node:os'+import { delimiter, join } from 'node:path'+import { L } from '../shared/lang'+import type { VoiceModelId, VoiceSettings, VoiceStatus } from '../shared/types'+import { encodeWav } from '../shared/wav'+import { executableNames, isWin, killTree } from './platform'++export const MAX_AUDIO_BASE64 = 30_000_000 // about 15 minutes of 16 kHz mono+const TIMEOUT_MS = 5 * 60_000++// The two the app offers. Pinned by size and SHA-256: a download that doesn't match is thrown away.+export const VOICE_MODELS: Record<VoiceModelId, { file: string; bytes: number; sha256: string }> = {+ recommended: { file: 'ggml-large-v3-turbo-q5_0.bin', bytes: 574_041_195, sha256: '394221709cd5ad1f40c46e6031ca61bce88931e6e088c188294c6d5a55ffa7e2' },+ light: { file: 'ggml-small-q5_1.bin', bytes: 190_085_487, sha256: 'ae85e4a935d7a567bd102fe55afc16bb595bdb618e11b2fc7591bc08120411bb' }+}+const MODEL_URL = (file: string): string => `https://huggingface.co/ggerganov/whisper.cpp/resolve/main/${file}`++const BIN_DIRS = ['/opt/homebrew/bin', '/usr/local/bin']+const MODEL_DIRS = (home: string): string[] => [join(home, '.cache', 'whisper-cpp'), '/opt/homebrew/share/whisper-cpp', '/usr/local/share/whisper-cpp']++export interface VoicePlaces {+ bundled?: string // the folder with the whisper-cli that came with the app+ models: string // where the app keeps the models it downloads+}++const findBin = (path: string | undefined, bundled?: string): string | undefined =>+ [...(bundled ? [bundled] : []), ...(path ?? '').split(delimiter).filter(Boolean), ...BIN_DIRS].flatMap((d) => executableNames('whisper-cli').map((name) => join(d, name))).find((f) => existsSync(f))++const modelsIn = (dir: string): string[] => {+ try {+ return readdirSync(dir).filter((f) => /^ggml-.*\.bin$/.test(f)).map((f) => join(dir, f))+ } catch {+ return []+ }+}++// The best one there: the app's own first, and turbo before the rest, since it's what's fast enough to dictate with.+function findModel(home: string, own?: string): string | undefined {+ const mine = own ? modelsIn(own) : []+ const all = [...mine, ...MODEL_DIRS(home).flatMap(modelsIn)]+ return all.find((f) => f.includes('turbo')) ?? all.sort().at(-1)+}++// Which of the app's models is downloaded, if any.+export const downloaded = (dir: string): VoiceModelId[] => (Object.keys(VOICE_MODELS) as VoiceModelId[]).filter((id) => existsSync(join(dir, VOICE_MODELS[id].file)))++export function voiceStatus(voice: VoiceSettings | undefined, env: NodeJS.ProcessEnv = process.env, home = homedir(), places?: VoicePlaces): VoiceStatus {+ const bin = voice?.bin ? (existsSync(voice.bin) ? voice.bin : undefined) : findBin(env['PATH'] ?? env['Path'], places?.bundled)+ const model = voice?.model ? (existsSync(voice.model) ? voice.model : undefined) : findModel(home, places?.models)+ const ownModel = places ? (Object.keys(VOICE_MODELS) as VoiceModelId[]).find((id) => model === join(places.models, VOICE_MODELS[id].file)) : undefined+ return { bin, model, ready: !!bin && !!model, ...(ownModel ? { ownModel } : {}), ...(places ? { downloaded: downloaded(places.models) } : {}) }+}++// The model, fetched once: to a .part file, hashed on the way, and moved into place only if it's+// the file it should be. One download at a time; a new one replaces what's going on.+export class ModelDownload {+ progress: { model: VoiceModelId; received: number; total: number } | null = null+ error: string | null = null+ private abort: AbortController | null = null++ constructor(+ private dir: string,+ private changed: () => void,+ private fetcher: typeof fetch = fetch,+ private models: Record<VoiceModelId, { file: string; bytes: number; sha256: string }> = VOICE_MODELS, // tests use small ones+ private downloaded: () => void = () => {}+ ) {}++ async start(id: VoiceModelId): Promise<void> {+ const m = this.models[id]+ this.cancel()+ const abort = new AbortController()+ this.abort = abort+ this.error = null+ this.progress = { model: id, received: 0, total: m.bytes }+ this.changed()+ mkdirSync(this.dir, { recursive: true })+ const part = join(this.dir, `${m.file}.part`)+ let last = 0+ try {+ const res = await this.fetcher(MODEL_URL(m.file), { signal: abort.signal, redirect: 'follow' })+ if (!res.ok || !res.body) throw new Error(L(`O download respondeu ${res.status}.`, `The download answered ${res.status}.`))+ const hash = createHash('sha256')+ const out = createWriteStream(part)+ const reader = res.body.getReader()+ try {+ for (;;) {+ const { done, value } = await reader.read()+ if (done) break+ hash.update(value)+ if (!out.write(value)) await new Promise((r) => out.once('drain', r))+ this.progress.received += value.length+ // a few updates a second are enough for a bar+ if (Date.now() - last > 250) (last = Date.now()), this.changed()+ }+ } finally {+ await new Promise<void>((r) => out.end(r))+ }+ if (this.progress.received !== m.bytes || hash.digest('hex') !== m.sha256) throw new Error(L('O arquivo baixado não é o esperado. Tente de novo.', "The downloaded file isn't the expected one. Try again."))+ renameSync(part, join(this.dir, m.file))+ this.downloaded()+ } catch (e) {+ rmSync(part, { force: true })+ if (!abort.signal.aborted) this.error = e instanceof Error ? e.message : String(e)+ } finally {+ if (this.abort === abort) {+ this.abort = null+ this.progress = null+ }+ this.changed()+ }+ }++ cancel(): void {+ this.abort?.abort()+ }++ // A model the app downloaded, gone; one installed some other way isn't the app's to delete.+ remove(id: VoiceModelId): void {+ rmSync(join(this.dir, this.models[id].file), { force: true })+ this.changed()+ }+}++// What whisper prints for silence, not words.+const NOT_SPEECH = /^[[(][^\])]*[\])]$/+export const cleanTranscript = (out: string): string =>+ out+ .split('\n')+ .map((l) => l.trim())+ .filter((l) => l && !NOT_SPEECH.test(l))+ .join(' ')++// The first run of whisper on a Mac builds its GPU programs, which takes a while (14 s here);+// the system keeps them after that. Done once with a second of silence, right after the model+// arrives, so the person's first dictation is as quick as the rest.+export async function warmUp(transcriber: Transcriber, status: VoiceStatus): Promise<void> {+ if (!status.ready) return+ const silence = Buffer.from(encodeWav(new Float32Array(16_000), 16_000)).toString('base64')+ await transcriber.transcribe(`warm-${Date.now()}`, silence, status, 'en').catch(() => {})+}++export class Transcriber {+ private running = new Map<string, { proc: ChildProcess; cancelled: boolean }>()++ async transcribe(id: string, base64: string, status: VoiceStatus, language: string | undefined): Promise<string> {+ if (!status.bin || !status.model) throw new Error(L('O ditado ainda não está ativado. Veja em Configurações › Geral.', "Dictation isn't turned on yet. See Settings › General."))+ if (base64.length > MAX_AUDIO_BASE64) throw new Error(L('Esse áudio é longo demais.', 'That recording is too long.'))+ const dir = mkdtempSync(join(tmpdir(), 'tucano-voz-'))+ try {+ const file = join(dir, 'audio.wav')+ writeFileSync(file, Buffer.from(base64, 'base64'), { mode: 0o600 })+ return cleanTranscript(await this.run(id, status.bin, ['-m', status.model, '-f', file, '-nt', '-np', '-l', language ?? 'auto']))+ } finally {+ rmSync(dir, { recursive: true, force: true })+ }+ }++ cancel(id: string): void {+ const r = this.running.get(id)+ if (!r) return+ r.cancelled = true+ if (r.proc.pid) killTree(r.proc.pid)+ }++ private run(id: string, bin: string, args: string[]): Promise<string> {+ return new Promise((resolve, reject) => {+ const proc = spawn(bin, args, { stdio: ['ignore', 'pipe', 'pipe'], detached: !isWin })+ const entry = { proc, cancelled: false }+ this.running.set(id, entry)+ const timer = setTimeout(() => this.cancel(id), TIMEOUT_MS)+ let out = ''+ let err = ''+ proc.stdout.on('data', (d: Buffer) => (out += d.toString()))+ proc.stderr.on('data', (d: Buffer) => (err = (err + d.toString()).slice(-500)))+ proc.on('error', (e) => done(e))+ proc.on('close', (code) => done(code === 0 && !entry.cancelled ? undefined : new Error(entry.cancelled ? L('Cancelado.', 'Cancelled.') : L(`O whisper-cli falhou: ${err.trim().split('\n').at(-1) ?? code}`, `whisper-cli failed: ${err.trim().split('\n').at(-1) ?? code}`))))+ const done = (e?: Error): void => {+ clearTimeout(timer)+ this.running.delete(id)+ if (e) reject(e)+ else resolve(out)+ }+ })+ }+}diff --git a/src/main/index.ts b/src/main/index.tsindex 3de7fba..0a8b069 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1,6 +1,6 @@import { randomBytes } from 'node:crypto'import { verifyLocalUrl } from '../core/local-paths'-import { app, BrowserWindow, dialog, ipcMain, Menu, MessageChannelMain, nativeImage, nativeTheme, net, Notification, powerMonitor, powerSaveBlocker, protocol, safeStorage, shell, Tray, utilityProcess, type UtilityProcess } from 'electron'+import { app, BrowserWindow, session, type MediaAccessPermissionRequest, dialog, ipcMain, Menu, MessageChannelMain, nativeImage, nativeTheme, net, Notification, powerMonitor, powerSaveBlocker, protocol, safeStorage, shell, Tray, utilityProcess, type UtilityProcess } from 'electron'import { execFile } from 'node:child_process'import { mkdirSync, rmSync, writeFileSync } from 'node:fs'import { dirname, join, normalize, sep } from 'node:path'@@ -57,7 +57,7 @@ const localKey = randomBytes(32).toString('hex')function startCore(): UtilityProcess {const child = utilityProcess.fork(join(import.meta.dirname, 'core.js'), [], {serviceName: 'tucano-core',- env: { ...process.env, TUCANO_DATA: dataDir(), TUCANO_PACKAGED: app.isPackaged ? '1' : '0', TUCANO_LOCAL_KEY: localKey, TUCANO_LOCALE: systemLocale ?? '' }+ env: { ...process.env, TUCANO_DATA: dataDir(), TUCANO_PACKAGED: app.isPackaged ? '1' : '0', TUCANO_WHISPER: whisperDir(), TUCANO_LOCAL_KEY: localKey, TUCANO_LOCALE: systemLocale ?? '' }})child.on('message', (msg: CoreRequest) => handleCore(child, msg))child.on('exit', (code) => {@@ -91,6 +91,8 @@ ipcMain.on('viewing', (_e, id: unknown) => {// you, two notes when the work is done. Never more than one at a time.let chirpedAt = 0const resource = (name: string): string => (app.isPackaged ? join(process.resourcesPath, name) : join(app.getAppPath(), 'build', name))+// Dictation's whisper-cli, packed with the app (scripts/whisper.mjs); in development, the one built for this machine.+const whisperDir = (): string => (app.isPackaged ? join(process.resourcesPath, 'whisper') : join(app.getAppPath(), 'build', 'whisper', `${({ darwin: 'mac', win32: 'win' } as Record<string, string>)[process.platform] ?? process.platform}-${process.arch}`))// The system's own player: afplay on a Mac; on Windows .NET's SoundPlayer, with nothing// to install; on Linux PipeWire's or PulseAudio's, else ALSA's.const player = ((): ((file: string) => [string, string[]]) | null => {@@ -450,6 +452,13 @@ if (moved === 'old-app-open' || moved === 'keychain-denied') {app.exit(0)})} else if (primary) app.whenReady().then(() => {+ // Dictation: audio, for the app's own page. A service open in the side panel or anything else asks in vain.+ session.defaultSession.setPermissionRequestHandler((contents, permission, done, details) => {+ if (permission !== 'media') return done(true)+ const media = details as MediaAccessPermissionRequest+ const own = !!BrowserWindow.fromWebContents(contents) && (media.requestingUrl ?? '').startsWith(process.env['ELECTRON_RENDERER_URL'] ?? 'file://')+ done(own && !!media.mediaTypes?.length && media.mediaTypes.every((t) => t === 'audio'))+ })setMenu()protocol.handle('tucano', serveArtifact)core = startCore()diff --git a/src/renderer/src/components/Conversation.tsx b/src/renderer/src/components/Conversation.tsxindex 475e2dd..dede962 100644--- a/src/renderer/src/components/Conversation.tsx+++ b/src/renderer/src/components/Conversation.tsx@@ -38,8 +38,13 @@ import {type Step,IMAGE_MIMES,MAX_IMAGES_PER_MESSAGE,- isTeam+ isTeam,+ cancelTranscribe,+ transcribe,+ voiceStatus} from '../store'+import { canRecord, NoSound, record, type Recording } from '../voice'+import { useVoice, VoicePopover } from './VoiceSetup'import { AgentAvatar, Icon, MeAvatar, duration, time, tokens, usd } from './ui'import { ArtifactCard, BrowserCard, ServiceCard, SidePanel } from './Panel'import { when } from './Routines'@@ -794,6 +799,238 @@ async function prepareImage(file: File): Promise<Attached | string> {// lose the message you were typing.const drafts = new Map<string, { text: string; images: Attached[] }>()+type DictationState = 'idle' | 'starting' | 'recording' | 'transcribing'+type DictationControls = { press: () => void; release: () => void; stop: () => void; cancel: () => void; startedAt: () => number }++const NOT_READY = (): string => L('Para ditar, clique no microfone e ative o ditado.', 'To dictate, click the microphone and turn dictation on.')+const SHORT_MS = 300+const HOLD_MS = 400 // held at least this long, letting go ends it (push to talk); a click starts it, the next one ends it++// Click to record, click again to transcribe (or hold and let go). The text goes to the field to be reviewed, never sent:+// dictation gets names wrong, and a message sets an agent working.+function useDictation(insert: (text: string) => void, setNote: (note: string) => void, conversationId: string): [DictationState, DictationControls] {+ const [state, setState] = useState<DictationState>('idle')+ const rec = useRef<Recording | null>(null)+ const startedAt = useRef(0)+ const job = useRef<string | null>(null)+ const released = useRef(false)+ const attempt = useRef(0) // a microphone that opens after this one was given up on gets closed+ const platform = useStore((s) => s.platform)++ const cancel = (): void => {+ released.current = true+ rec.current?.cancel()+ rec.current = null+ if (job.current) void cancelTranscribe(job.current)+ job.current = null+ setState('idle')+ }++ const stop = (): void => {+ released.current = true+ const r = rec.current+ if (!r) return+ rec.current = null+ if (Date.now() - startedAt.current < SHORT_MS) {+ r.cancel()+ setState('idle')+ setNote(L('Curto demais: clique, fale e clique de novo.', 'Too short: click, speak, and click again.'))+ return+ }+ setState('transcribing')+ const id = crypto.randomUUID()+ job.current = id+ void r+ .stop()+ .then((audio) => transcribe(id, audio))+ .then(+ (said) => {+ if (job.current !== id) return+ if (said) insert(said)+ else setNote(L('Não ouvi nada nessa gravação.', "I didn't hear anything in that recording."))+ },+ (e: unknown) => {+ if (job.current !== id) return+ if (e instanceof NoSound)+ setNote(+ platform === 'mac'+ ? L('Não chegou som do microfone. Confira qual está em uso em Ajustes do Sistema › Som.', 'No sound came from the microphone. Check which one is in use in System Settings › Sound.')+ : L('Não chegou som do microfone. Confira qual está em uso nas configurações de som do sistema.', 'No sound came from the microphone. Check which one is in use in the system’s sound settings.')+ )+ else setNote(e instanceof Error ? e.message.replace(/^Error invoking.*?: /, '') : String(e))+ }+ )+ .finally(() => {+ if (job.current !== id) return+ job.current = null+ setState('idle')+ })+ }++ const start = (): void => {+ if (state !== 'idle') return+ released.current = false+ const mine = ++attempt.current+ setNote('')+ setState('starting')+ void voiceStatus()+ .then((status) => {+ if (!status.ready) throw new Error(NOT_READY())+ return record()+ })+ .then(+ (r) => {+ if (mine !== attempt.current) return r.cancel()+ // Let go while the microphone was still opening: nothing to record.+ if (released.current) {+ r.cancel()+ setState('idle')+ return+ }+ rec.current = r+ startedAt.current = Date.now()+ setState('recording')+ },+ (e: unknown) => {+ if (mine !== attempt.current) return+ setState('idle')+ const name = e instanceof Error ? e.name : ''+ setNote(+ name === 'NotAllowedError'+ ? platform === 'mac'+ ? L('O microfone está bloqueado. Libere o Tucano em Ajustes do Sistema › Privacidade e Segurança › Microfone.', 'The microphone is blocked. Allow Tucano in System Settings › Privacy & Security › Microphone.')+ : L('O microfone está bloqueado. Libere o Tucano nas configurações de privacidade do sistema.', 'The microphone is blocked. Allow Tucano in the system’s privacy settings.')+ : name === 'NotFoundError' ? L('Não encontrei um microfone.', "I couldn't find a microphone.")+ : e instanceof Error ? e.message.replace(/^Error invoking.*?: /, '') : String(e)+ )+ }+ )+ }++ useEffect(() => cancel, [conversationId]) // leaving the conversation drops what's going on++ // The key can be let go anywhere, and no event reaches the field after the window loses focus.+ // A press starts it, or ends one going on. Let go after holding it a while ends it too.+ const pressedAt = useRef(0)+ const toggled = useRef(false) // this press ended a recording: its release does nothing+ const press = (): void => {+ if (state === 'recording' || state === 'starting') return (toggled.current = true), stop()+ if (state !== 'idle') return+ toggled.current = false+ pressedAt.current = Date.now()+ start()+ }+ const release = (): void => {+ if (toggled.current || !pressedAt.current) return+ const held = Date.now() - pressedAt.current+ pressedAt.current = 0+ if (held >= HOLD_MS) stop()+ }++ const listening = state === 'starting' || state === 'recording'+ useEffect(() => {+ if (!listening) return+ // the key can be let go anywhere; Esc drops it from anywhere+ const up = (e: KeyboardEvent): void => {+ if (e.code === 'Space') release()+ }+ const esc = (e: KeyboardEvent): void => {+ if (e.key === 'Escape') cancel()+ }+ // held when the window lost focus: no release will come, so that's the end of it+ const blur = (): void => {+ if (pressedAt.current && Date.now() - pressedAt.current >= HOLD_MS) release()+ }+ document.addEventListener('keyup', up)+ document.addEventListener('keydown', esc)+ window.addEventListener('blur', blur)+ return () => {+ document.removeEventListener('keyup', up)+ document.removeEventListener('keydown', esc)+ window.removeEventListener('blur', blur)+ }+ }, [listening])++ return [state, { press, release, stop, cancel, startedAt: () => startedAt.current }]+}++function VoiceButton({ controls, state }: { controls: DictationControls; state: DictationState }): ReactNode {+ const platform = useStore((s) => s.platform)+ const hidden = useStore((s) => !!s.settings.voice?.hidden)+ const status = useVoice()+ const [open, setOpen] = useState(false)+ // Once it's turned on from the balloon, the balloon says how to use it, then gets out of the way.+ if (!canRecord() || hidden || !status) return null // no secure context, or the person hid it+ if (!status.ready)+ return (+ <span className="voice-wrap">+ <button+ className={`icon-btn voice-btn is-off ${status.downloading ? 'is-loading' : ''}`}+ aria-label={L('Ditar mensagens', 'Dictate messages')}+ aria-expanded={open}+ title={status.downloading ? L('Baixando o modelo de voz…', 'Downloading the voice model…') : L('Ditar mensagens: ativar', 'Dictate messages: turn on')}+ onClick={() => setOpen(!open)}+ >+ <Icon name="mic" size={15} />+ </button>+ {open && <VoicePopover status={status} onClose={() => setOpen(false)} />}+ </span>+ )+ if (open)+ return (+ <span className="voice-wrap">+ <button className="icon-btn voice-btn" aria-label={L('Ditar mensagens', 'Dictate messages')} onClick={() => setOpen(false)}>+ <Icon name="mic" size={15} />+ </button>+ <VoicePopover status={status} onClose={() => setOpen(false)} />+ </span>+ )+ if (state === 'transcribing')+ return (+ <button className="btn btn--xs" title={L('Cancelar', 'Cancel')} onClick={controls.cancel}>+ {L('Transcrevendo…', 'Transcribing…')} <Icon name="x" size={11} />+ </button>+ )+ const on = state === 'recording'+ return (+ <span className="voice-wrap">+ <button+ className={`icon-btn voice-btn ${on ? 'is-recording' : ''}`}+ aria-label={on ? L('Terminar e transcrever', 'Finish and transcribe') : L('Falar', 'Speak')}+ aria-pressed={on}+ title={on ? L('Clique para terminar (Esc cancela)', 'Click to finish (Esc cancels)') : L(`Clique para falar, e de novo para terminar (${platform === 'mac' ? '⌥' : 'Ctrl+'}Espaço)`, `Click to speak, and again to finish (${platform === 'mac' ? '⌥' : 'Ctrl+'}Space)`)}+ onPointerDown={(e) => {+ e.currentTarget.setPointerCapture(e.pointerId)+ controls.press()+ }}+ onPointerUp={controls.release}+ onPointerCancel={controls.cancel}+ onContextMenu={(e) => e.preventDefault()}+ >+ <Icon name="mic" size={15} />+ </button>+ {on && <RecordingClock since={controls.startedAt()} />}+ </span>+ )+}++// While it records: for how long, and how to end it.+function RecordingClock({ since }: { since: number }): ReactNode {+ const [, tick] = useState(0)+ useEffect(() => {+ const t = setInterval(() => tick((n) => n + 1), 500)+ return () => clearInterval(t)+ }, [])+ const s = Math.max(0, Math.floor((Date.now() - since) / 1000))+ return (+ <span className="voice-clock" aria-live="off">+ <i />+ {Math.floor(s / 60)}:{String(s % 60).padStart(2, '0')}+ <span className="muted"> · {L('clique para terminar', 'click to finish')}</span>+ </span>+ )+}+export function Composer({ conversationId, members, placeholder }: { conversationId: string; members: Agent[]; placeholder: string }): ReactNode {// The field starts with the conversation's draft, not empty: StrictMode (in dev) unmounts// and mounts again at once, and saving an empty first render would wipe the draft.@@ -805,6 +1042,7 @@ export function Composer({ conversationId, members, placeholder }: { conversatioconst [mention, setMention] = useState<{ query: string; start: number } | null>(null)const [active, setActive] = useState(0)const ref = useRef<HTMLTextAreaElement>(null)+ const platform = useStore((s) => s.platform)const allAgents = useStore((s) => s.agents.filter(isTeam))const isDm = useStore((s) => s.conversations.find((c) => c.id === conversationId)?.kind === 'dm')const working = useStore((s) => s.messages.filter((m) => m.conversationId === conversationId && m.author.kind === 'agent' && m.run?.status === 'working'))@@ -912,6 +1150,19 @@ export function Composer({ conversationId, members, placeholder }: { conversatio})}+ const insert = (said: string): void => {+ const el = ref.current+ const start = el?.selectionStart ?? text.length+ const end = el?.selectionEnd ?? start+ setText((cur) => {+ const before = cur.slice(0, start)+ const glue = before && !/\s$/.test(before) ? ' ' : ''+ return `${before}${glue}${said}${cur.slice(end)}`+ })+ el?.focus()+ }+ const [voice, voiceControls] = useDictation(insert, setNote, conversationId)+const submit = (): void => {if (!text.trim() && images.length === 0) returnsendMessage(@@ -993,6 +1244,12 @@ export function Composer({ conversationId, members, placeholder }: { conversatiovoid addFiles(files)}}onKeyDown={(e) => {+ if (e.code === 'Space' && (platform === 'mac' ? e.altKey : e.ctrlKey) && canRecord()) {+ e.preventDefault()+ if (!e.repeat) voiceControls.press()+ return+ }+ if (e.key === 'Escape' && voice !== 'idle') return voiceControls.cancel()if (mention && options.length > 0) {if (e.key === 'ArrowDown') return (e.preventDefault(), setActive((active + 1) % options.length))if (e.key === 'ArrowUp') return (e.preventDefault(), setActive((active - 1 + options.length) % options.length))@@ -1006,6 +1263,7 @@ export function Composer({ conversationId, members, placeholder }: { conversatio}}/><div className="composer__bar">+ <VoiceButton controls={voiceControls} state={voice} /><button className="icon-btn" title={L('Anexar imagem (ou arraste e solte, ou cole)', 'Attach an image (or drag and drop, or paste)')} onClick={() => picker.current?.click()}><Icon name="image" size={15} /></button>diff --git a/src/renderer/src/components/Pages.tsx b/src/renderer/src/components/Pages.tsxindex b921200..572dc33 100644--- a/src/renderer/src/components/Pages.tsx+++ b/src/renderer/src/components/Pages.tsx@@ -58,8 +58,14 @@ import {type Skill,type ToolClass,isTeam,- reachable+ reachable,+ voiceDownload,+ voiceRemoveModel,+ type VoiceModelId,+ type VoiceSettings} from '../store'+import { voiceRefusal } from '../../../shared/voice'+import { useVoice, VOICE_CHOICES, VoiceSetup } from './VoiceSetup'import { AccountPicker, AccountsCard, HarnessList, HarnessMcps, ModelPicker, onGateway, OutsideGateway, usableEngines } from './Harness'import { AppsCard } from './Apps'import { ApprovalCard } from './Conversation'@@ -1736,6 +1742,67 @@ export function JevKey({ saved, hint }: { saved: boolean; hint?: string }): Reac)}+function VoiceCard(): ReactNode {+ const voice = useStore((s) => s.settings.voice)+ const status = useVoice()+ const [error, setError] = useState('')+ const save = (patch: VoiceSettings): void => {+ const next = { ...voice, ...patch }+ const why = voiceRefusal(next)+ setError(why ?? '')+ if (!why) updateSettings({ voice: next })+ }+ const choice = (id: VoiceModelId) => VOICE_CHOICES().find((c) => c.id === id)!+ const other = status?.ownModel === 'recommended' ? 'light' : 'recommended'+ return (+ <Card title={L('Ditado', 'Dictation')} lead={L('Fale em vez de digitar: clique no microfone do campo de mensagem, ou ⌥ Espaço no Mac e Ctrl+Espaço nos outros, e clique de novo para terminar. O áudio vira texto neste computador, sem internet, e o texto fica no campo para você revisar antes de enviar.', 'Speak instead of typing: click the microphone in the message field, or ⌥ Space on a Mac and Ctrl+Space elsewhere, and click again to finish. The audio becomes text on this computer, offline, and the text stays in the field for you to review before sending.')}>+ {status && !status.ready && <VoiceSetup status={status} />}+ {status?.ready && (+ <div className="voice-on">+ <p className="small">+ <Icon name="check" size={13} />{' '}+ {status.ownModel+ ? L(`Ativado, com o modelo ${choice(status.ownModel).name} (${choice(status.ownModel).size}).`, `On, with the ${choice(status.ownModel).name} model (${choice(status.ownModel).size}).`)+ : L(`Ativado, com o modelo que já estava instalado: ${status.model?.split(/[\\/]/).pop()}.`, `On, with the model already installed: ${status.model?.split(/[\\/]/).pop()}.`)}+ </p>+ {status.downloading ? (+ <VoiceSetup status={status} />+ ) : (+ status.ownModel && (+ <div className="row">+ <button className="btn btn--sm" onClick={() => void voiceDownload(other)}>+ {L(`Trocar pelo ${choice(other).name} (${choice(other).size})`, `Switch to ${choice(other).name} (${choice(other).size})`)}+ </button>+ <button className="btn btn--ghost btn--sm" onClick={() => void voiceRemoveModel(status.ownModel!)}>+ {L('Remover o modelo', 'Remove the model')}+ </button>+ </div>+ )+ )}+ {status.error && <p className="field__error">{status.error}</p>}+ </div>+ )}+ <label className="row row--center small">+ <input type="checkbox" checked={!voice?.hidden} onChange={(e) => save({ hidden: !e.target.checked })} />+ {L('Mostrar o microfone no campo de mensagem', 'Show the microphone in the message field')}+ </label>+ <details className="voice-advanced">+ <summary className="small muted">{L('Avançado', 'Advanced')}</summary>+ <label className="row row--center small">+ <input type="checkbox" checked={!!voice?.detect} onChange={(e) => save({ detect: e.target.checked })} />+ {L('Detectar o idioma, em vez de usar o do app', 'Detect the language, instead of using the app’s')}+ </label>+ <Field label={L('Caminho do whisper-cli', 'Path to whisper-cli')} hint={status?.bin && !voice?.bin ? L(`Em uso: ${status.bin}`, `In use: ${status.bin}`) : L('Opcional: sem isso, o app usa o que veio com ele.', 'Optional: without it, the app uses the one it came with.')}>+ <input defaultValue={voice?.bin ?? ''} placeholder="/opt/homebrew/bin/whisper-cli" onBlur={(e) => save({ bin: e.target.value.trim() || undefined })} />+ </Field>+ <Field label={L('Caminho do modelo', 'Path to the model')} hint={status?.model && !voice?.model ? L(`Em uso: ${status.model}`, `In use: ${status.model}`) : L('Opcional: um modelo ggml (.bin) que você já tenha.', 'Optional: a ggml model (.bin) you already have.')} error={error}>+ <input defaultValue={voice?.model ?? ''} placeholder="/caminho/para/ggml-large-v3-turbo.bin" onBlur={(e) => save({ model: e.target.value.trim() || undefined })} />+ </Field>+ </details>+ </Card>+ )+}+export function SettingsPage(): ReactNode {const settings = useStore((s) => s.settings)const packaged = useStore((s) => s.packaged)@@ -1774,6 +1841,8 @@ export function SettingsPage(): ReactNode {</Card>)}+ {pane('geral') && <VoiceCard />}+{pane('geral') && (<Card title={L('Notificações', 'Notifications')}><div className="key-row">diff --git a/src/renderer/src/components/VoiceSetup.tsx b/src/renderer/src/components/VoiceSetup.tsxnew file mode 100644index 0000000..76e448f--- /dev/null+++ b/src/renderer/src/components/VoiceSetup.tsx@@ -0,0 +1,98 @@+// Turning dictation on: pick a model, and the app downloads it, with a bar and a way to stop.+// The same piece in the balloon over the microphone and in Settings.+import { useEffect, useState, type ReactNode } from 'react'+import { L } from '../../../shared/lang'+import { updateSettings, useStore, voiceCancelDownload, voiceDownload, voiceStatus, type VoiceModelId, type VoiceStatus } from '../store'+import { Icon } from './ui'++export const VOICE_CHOICES = (): { id: VoiceModelId; name: string; size: string; about: string }[] => [+ { id: 'recommended', name: L('Recomendado', 'Recommended'), size: '574 MB', about: L('O mais preciso, inclusive em português.', 'The most accurate, in any language.') },+ { id: 'light', name: L('Leve', 'Light'), size: '190 MB', about: L('Baixa mais rápido e erra um pouco mais.', 'Downloads faster, and gets a bit more wrong.') }+]++// Dictation's state, read again whenever the core says it changed.+export function useVoice(): VoiceStatus | null {+ const rev = useStore((s) => s.voiceRev)+ const voice = useStore((s) => s.settings.voice)+ const [status, setStatus] = useState<VoiceStatus | null>(null)+ useEffect(() => void voiceStatus().then(setStatus), [rev, voice])+ return status+}++const mb = (n: number): string => `${Math.round(n / 1_000_000)} MB`++export function VoiceSetup({ status }: { status: VoiceStatus }): ReactNode {+ const [pick, setPick] = useState<VoiceModelId>('recommended')+ const d = status.downloading+ if (d)+ return (+ <div className="voice-setup">+ <div className="voice-setup__bar" role="progressbar" aria-valuemin={0} aria-valuemax={d.total} aria-valuenow={d.received}>+ <i style={{ width: `${Math.min(100, (d.received / d.total) * 100)}%` }} />+ </div>+ <div className="voice-setup__row">+ <span className="small muted">+ {L('Baixando o modelo de voz', 'Downloading the voice model')} · {mb(d.received)} {L('de', 'of')} {mb(d.total)}+ </span>+ <button className="btn btn--ghost btn--xs" onClick={() => void voiceCancelDownload()}>+ {L('Cancelar', 'Cancel')}+ </button>+ </div>+ </div>+ )+ return (+ <div className="voice-setup">+ <div className="voice-setup__choices" role="radiogroup">+ {VOICE_CHOICES().map((c) => (+ <button key={c.id} type="button" role="radio" aria-checked={pick === c.id} className={`voice-choice ${pick === c.id ? 'is-on' : ''}`} onClick={() => setPick(c.id)}>+ <span>+ <b>{c.name}</b> <span className="muted">· {c.size}</span>+ </span>+ <small>{c.about}</small>+ </button>+ ))}+ </div>+ {status.error && <p className="field__error">{status.error}</p>}+ <button className="btn btn--primary btn--sm" onClick={() => void voiceDownload(pick)}>+ <Icon name="mic" size={13} /> {status.error ? L('Tentar de novo', 'Try again') : L('Ativar ditado', 'Turn dictation on')}+ </button>+ </div>+ )+}++// Over the microphone, the first time: what it is, and the way to turn it on (or not see it again).+export function VoicePopover({ status, onClose }: { status: VoiceStatus; onClose: () => void }): ReactNode {+ const platform = useStore((s) => s.platform)+ const voice = useStore((s) => s.settings.voice)+ useEffect(() => {+ const onKey = (e: KeyboardEvent): void => void (e.key === 'Escape' && onClose())+ window.addEventListener('keydown', onKey)+ return () => window.removeEventListener('keydown', onKey)+ })+ const key = platform === 'mac' ? '⌥ Espaço' : 'Ctrl+Espaço'+ return (+ <div className="voice-pop" role="dialog" aria-label={L('Ditar mensagens', 'Dictate messages')}>+ <button className="voice-pop__close icon-btn" aria-label={L('Fechar', 'Close')} onClick={onClose}>+ <Icon name="x" size={13} />+ </button>+ {status.ready ? (+ <>+ <b>{L('Pronto para ditar', 'Ready to dictate')}</b>+ <p className="small muted">{L(`Clique no microfone, ou ${key}, e fale. Clique de novo para terminar: o texto aparece aqui para você revisar. Na primeira vez, o sistema pede para liberar o microfone.`, `Click the microphone, or ${key.replace('Espaço', 'Space')}, and speak. Click again to finish: the text shows up here to review. The first time, the system asks to allow the microphone.`)}</p>+ <button className="btn btn--sm" onClick={onClose}>+ {L('Entendi', 'Got it')}+ </button>+ </>+ ) : (+ <>+ <b>{L('Ditar mensagens', 'Dictate messages')}</b>+ <p className="small muted">{L('Fale em vez de digitar. Funciona neste computador, sem internet e sem custo: nada do que você fala sai daqui. Precisa baixar um modelo de voz uma vez.', 'Speak instead of typing. It runs on this computer, offline and free: nothing you say leaves it. It needs a voice model, downloaded once.')}</p>+ <VoiceSetup status={status} />+ <button className="text-btn voice-pop__hide" onClick={() => (onClose(), updateSettings({ voice: { ...voice, hidden: true } }))}>+ {L('Não mostrar o microfone', "Don't show the microphone")}+ </button>+ </>+ )}+ </div>+ )+}diff --git a/src/renderer/src/components/ui.tsx b/src/renderer/src/components/ui.tsxindex 7c19aaf..d9e91d9 100644--- a/src/renderer/src/components/ui.tsx+++ b/src/renderer/src/components/ui.tsx@@ -15,6 +15,7 @@ const PATHS: Record<string, ReactNode> = {</>),plus: <path d="M12 5v14M5 12h14" />,+ mic: <path d="M12 3a3 3 0 0 0-3 3v6a3 3 0 0 0 6 0V6a3 3 0 0 0-3-3ZM5 11a7 7 0 0 0 14 0M12 18v3" />,image: (<><rect x="3" y="4" width="18" height="16" rx="2" />diff --git a/src/renderer/src/store.ts b/src/renderer/src/store.tsindex 7f2da01..ec20441 100644--- a/src/renderer/src/store.ts+++ b/src/renderer/src/store.ts@@ -38,7 +38,9 @@ import {type Trigger,type ImageUpload,type Os,- type LocalInfo+ type LocalInfo,+ type VoiceModelId,+ type VoiceStatus} from '../../shared/types'import { call, connect } from './rpc'@@ -79,6 +81,7 @@ export interface State {routines: Routine[]skills: Skill[]wikiRev: number // goes up when a wiki page changes: the wiki screens read again+ voiceRev: number // goes up when dictation's model changes (downloading, done, removed)platform: Ospackaged: booleanpanel: Panel | null // the side panel next to a conversation@@ -102,6 +105,7 @@ const initials = (name: string): string =>let state: State = {ready: false,wikiRev: 0,+ voiceRev: 0,navOpen: false,view: null,me: { name: 'Eu', initials: 'EU' },@@ -263,6 +267,8 @@ function apply(e: CoreEvent): void {return { ...s, skills: s.skills.filter((k) => k.id !== e.id) }case 'wiki':return { ...s, wikiRev: s.wikiRev + 1 }+ case 'voice':+ return { ...s, voiceRev: s.voiceRev + 1 }}})}@@ -336,6 +342,12 @@ export function updateSettings(patch: Partial<Omit<Settings, 'engines'>>): void}export const refreshEngines = (): void => void call('refreshEngines')+export const voiceStatus = (): Promise<VoiceStatus> => call('voiceStatus')+export const voiceDownload = (model: VoiceModelId): Promise<void> => call('voiceDownload', { model })+export const voiceCancelDownload = (): Promise<void> => call('voiceCancelDownload')+export const voiceRemoveModel = (model: VoiceModelId): Promise<void> => call('voiceRemoveModel', { model })+export const transcribe = async (id: string, audio: string): Promise<string> => (await call('transcribe', { id, audio })).text+export const cancelTranscribe = (id: string): Promise<void> => call('cancelTranscribe', { id })export const loginEngine = (engine: keyof Settings['engines']): Promise<{ opened: boolean; command: string }> => call('loginEngine', { engine })// More logins of Claude Code and Codex, each signed into in a terminal.export const addAccount = (engine: AccountEngine, name: string): Promise<Account> => call('addAccount', { engine, name })diff --git a/src/renderer/src/styles.css b/src/renderer/src/styles.cssindex 674271d..c10b4bf 100644--- a/src/renderer/src/styles.css+++ b/src/renderer/src/styles.css@@ -6670,6 +6670,16 @@ kbd {overflow: visible;}+/* Dictation */+.voice-btn {+ touch-action: none;+}+.voice-btn.is-recording,+.voice-btn.is-recording:hover {+ color: #fff;+ background: var(--danger);+}+/* Channel groups */.channel-group__head {display: flex;@@ -6989,3 +6999,32 @@ button.wk-pill.is-on { box-shadow: 0 0 0 1.5px var(--k); background: color-mix(i.channel-group > [draggable] .nav-item {padding-left: 12px;}++/* Dictation: turning it on, over the microphone and in Settings */+.voice-wrap { position: relative; display: inline-flex; }+.voice-btn.is-off { opacity: 0.55; }+.voice-btn.is-off:hover { opacity: 1; }+.voice-btn.is-loading { opacity: 1; color: var(--accent); }+.voice-pop { position: absolute; z-index: 30; left: -8px; bottom: calc(100% + 10px); width: 360px; display: grid; gap: 8px; padding: 16px 16px 14px; border-radius: 14px; background: var(--panel); box-shadow: var(--shadow-lg), 0 0 0 1px var(--border); text-align: left; }+.voice-pop > b { font-size: 14px; padding-right: 24px; }+.voice-pop p { margin: 0; line-height: 1.45; }+.voice-pop__close { position: absolute; top: 8px; right: 8px; }+.voice-pop__hide { justify-self: start; font-size: 12px; color: var(--text-3); }+.voice-setup { display: grid; gap: 10px; justify-items: start; }+.voice-setup__choices { display: grid; gap: 6px; width: 100%; }+.voice-choice { display: grid; gap: 2px; width: 100%; padding: 9px 12px; border-radius: 10px; border: 1px solid var(--border); background: var(--panel); font: inherit; font-size: 13px; color: var(--text); text-align: left; cursor: pointer; }+.voice-choice small { color: var(--text-2); font-size: 12px; }+.voice-choice:hover { border-color: var(--border-strong); }+.voice-choice.is-on { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); background: var(--accent-soft); }+.voice-setup__bar { width: 100%; height: 6px; border-radius: 3px; background: var(--hover); overflow: hidden; }+.voice-setup__bar i { display: block; height: 100%; border-radius: 3px; background: var(--accent); transition: width 0.25s; }+.voice-setup__row { display: flex; align-items: center; justify-content: space-between; gap: 10px; width: 100%; }+.voice-on { display: grid; gap: 8px; }+.voice-on p { margin: 0; display: flex; align-items: center; gap: 6px; }+.voice-advanced { display: grid; gap: 10px; }+.voice-advanced summary { cursor: pointer; }+.voice-pop > .btn { justify-self: start; }+.voice-btn.is-recording { animation: voice-pulse 1.6s ease-in-out infinite; }+@keyframes voice-pulse { 50% { box-shadow: 0 0 0 5px color-mix(in srgb, var(--danger) 22%, transparent); } }+.voice-clock { display: inline-flex; align-items: center; gap: 6px; margin-left: 6px; font-size: 12px; font-variant-numeric: tabular-nums; color: var(--danger); white-space: nowrap; }+.voice-clock i { width: 7px; height: 7px; border-radius: 50%; background: var(--danger); }diff --git a/src/renderer/src/voice.ts b/src/renderer/src/voice.tsnew file mode 100644index 0000000..5326783--- /dev/null+++ b/src/renderer/src/voice.ts@@ -0,0 +1,50 @@+// Records the microphone while held. An AudioContext at 16 kHz resamples what comes in, and+// ScriptProcessor needs no worklet file to load from the app's restricted origin.+import { encodeWav } from '../../shared/wav'++const RATE = 16_000+const SILENCE = 0.0005 // loudness below this is no sound at all: a muted or blocked microphone++// Given silence, whisper makes words up ("E aí"), and they'd land in the message.+export class NoSound extends Error {}++export interface Recording {+ stop(): Promise<string> // the WAV, in base64+ cancel(): void+}++export const canRecord = (): boolean => !!navigator.mediaDevices?.getUserMedia++export async function record(): Promise<Recording> {+ const stream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true } })+ const context = new AudioContext({ sampleRate: RATE })+ const source = context.createMediaStreamSource(stream)+ const node = context.createScriptProcessor(4096, 1, 1)+ const chunks: Float32Array[] = []+ node.onaudioprocess = (e) => chunks.push(new Float32Array(e.inputBuffer.getChannelData(0)))+ source.connect(node)+ node.connect(context.destination)+ const finish = (): void => {+ node.disconnect()+ source.disconnect()+ stream.getTracks().forEach((t) => t.stop())+ void context.close()+ }+ return {+ cancel: finish,+ stop: async () => {+ finish()+ const samples = new Float32Array(chunks.reduce((n, c) => n + c.length, 0))+ let at = 0+ for (const c of chunks) {+ samples.set(c, at)+ at += c.length+ }+ if (Math.sqrt(samples.reduce((sum, s) => sum + s * s, 0) / (samples.length || 1)) < SILENCE) throw new NoSound()+ let binary = ''+ const wav = encodeWav(samples, RATE)+ for (let i = 0; i < wav.length; i += 0x8000) binary += String.fromCharCode(...wav.subarray(i, i + 0x8000))+ return btoa(binary)+ }+ }+}diff --git a/src/shared/rpc.ts b/src/shared/rpc.tsindex 40054e1..17490d5 100644--- a/src/shared/rpc.ts+++ b/src/shared/rpc.ts@@ -1,6 +1,6 @@// The contract between the renderer and the core, carried over a MessagePort.import type { WikiChange, WikiHit, WikiPage, WikiImport, WikiPageInfo, WikiReview, WikiSource, WikiVersion } from './types'-import type { Os, Account, AccountEngine, Agent, BrowserInput, Approval, Artifact, ImageUpload, BrowserView, ComputerInfo, Connector, ConnectorInput, ConnectorTool, HarnessMcp, Conversation, EngineId, Memory, MemoryScope, Message, Routine, RoutineInput, Report, Settings, LocalSkill, Skill, SkillInput, SkillVersion, Trigger, UsageReport, LocalInfo } from './types'+import type { Os, Account, AccountEngine, Agent, BrowserInput, Approval, Artifact, ImageUpload, BrowserView, ComputerInfo, Connector, ConnectorInput, ConnectorTool, HarnessMcp, Conversation, EngineId, Memory, MemoryScope, Message, Routine, RoutineInput, Report, Settings, LocalSkill, Skill, SkillInput, SkillVersion, Trigger, UsageReport, LocalInfo, VoiceModelId, VoiceStatus } from './types'export interface Snapshot {settings: Settings@@ -40,6 +40,12 @@ export interface Api {settleDraft(p: { messageId: string; agentId?: string }): void // the card is done: created elsewhere (the introduction), or dismissedupdateSettings(p: { patch: Partial<Omit<Settings, 'engines'>> }): voidrefreshEngines(): void+ voiceStatus(): Promise<VoiceStatus>+ transcribe(p: { id: string; audio: string }): Promise<{ text: string }> // a WAV in base64; turned into text on this machine+ cancelTranscribe(p: { id: string }): void+ voiceDownload(p: { model: VoiceModelId }): void // in the background; 'voice' events say how it goes+ voiceCancelDownload(): void+ voiceRemoveModel(p: { model: VoiceModelId }): voidlocalPath(p: { messageId: string; path: string }): LocalInfo | null // what a path this agent cited can do; null: it stays textopenLocal(p: { messageId: string; path: string; how: 'open' | 'reveal' }): voidloginEngine(p: { engine: EngineId }): { opened: boolean; command: string } // not opened: no terminal to open, the person runs the command@@ -141,6 +147,7 @@ export type Params<M extends Method> = Parameters<Api[M]>[0]export type Result<M extends Method> = Awaited<ReturnType<Api[M]>>export type CoreEvent =+ | { type: 'voice' } // dictation's model: downloading, done, removed| { type: 'message'; message: Message }| { type: 'delta'; id: string; text: string } // appended to message text while streaming| { type: 'agent'; agent: Agent }diff --git a/src/shared/types.ts b/src/shared/types.tsindex 22c6b1d..3347b5a 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -200,6 +200,26 @@ export interface Message {routine?: RoutineRun // set on the message a routine posts (author kind 'routine')}+// Dictation with whisper-cli. Unset paths are looked for in the usual places.+export interface VoiceSettings {+ bin?: string+ model?: string+ detect?: boolean // I speak other languages: whisper finds out which, instead of using the app's+ hidden?: boolean // no microphone button in the message field+}++export type VoiceModelId = 'recommended' | 'light' // the models the app downloads by itself++export interface VoiceStatus {+ bin?: string+ model?: string+ ready: boolean+ ownModel?: VoiceModelId // the model in use is one the app downloaded+ downloaded?: VoiceModelId[]+ downloading?: { model: VoiceModelId; received: number; total: number }+ error?: string // the last download failed+}+export interface LocalInfo {kind: 'image' | 'video' | 'pdf' | 'folder' | 'file'url?: string // to see it here: images and videos@@ -211,6 +231,7 @@ export interface Settings {engines: Record<EngineId, EngineStatus>routerModel: string // a model id, or 'jev' for TypeSafe's Jev (falls back to Haiku)jevKey?: boolean // a TypeSafe key is saved (the key itself never leaves the core)+ voice?: VoiceSettingschannelLayout?: ChannelLayout // the person's order and groups in the sidebarbrowserJev?: boolean // Jev finds what agents click in their browsers (each click sends the page to TypeSafe)memoryModel: string // summarizes conversations and extracts memoriesdiff --git a/src/shared/voice.ts b/src/shared/voice.tsnew file mode 100644index 0000000..b5fcb07--- /dev/null+++ b/src/shared/voice.ts@@ -0,0 +1,11 @@+import { L } from './lang'+import type { VoiceSettings } from './types'++const absolute = (p: string): boolean => /^(\/|[a-zA-Z]:[\\/])/.test(p)++// Only an absolute path to a whisper binary: this setting is run as a program.+export function voiceRefusal(voice: VoiceSettings | undefined): string | null {+ if (voice?.bin && (!absolute(voice.bin) || !/^whisper/i.test(voice.bin.split(/[\\/]/).pop() ?? ''))) return L('Use o caminho completo do whisper-cli.', 'Use the full path to whisper-cli.')+ if (voice?.model && (!absolute(voice.model) || !voice.model.endsWith('.bin'))) return L('Use o caminho completo do modelo, um arquivo .bin.', 'Use the full path to the model, a .bin file.')+ return null+}diff --git a/src/shared/wav.ts b/src/shared/wav.tsnew file mode 100644index 0000000..02e338a--- /dev/null+++ b/src/shared/wav.ts@@ -0,0 +1,20 @@+// PCM WAV, which whisper reads as is: with this, ffmpeg isn't a requirement.+export function encodeWav(samples: Float32Array, sampleRate: number): Uint8Array {+ const bytes = new Uint8Array(44 + samples.length * 2)+ const view = new DataView(bytes.buffer)+ const text = (at: number, s: string): void => [...s].forEach((c, i) => view.setUint8(at + i, c.charCodeAt(0)))+ text(0, 'RIFF')+ view.setUint32(4, 36 + samples.length * 2, true)+ text(8, 'WAVEfmt ')+ view.setUint32(16, 16, true)+ view.setUint16(20, 1, true) // PCM+ view.setUint16(22, 1, true) // mono+ view.setUint32(24, sampleRate, true)+ view.setUint32(28, sampleRate * 2, true)+ view.setUint16(32, 2, true)+ view.setUint16(34, 16, true)+ text(36, 'data')+ view.setUint32(40, samples.length * 2, true)+ samples.forEach((s, i) => view.setInt16(44 + i * 2, Math.max(-1, Math.min(1, s)) * 0x7fff, true))+ return bytes+}diff --git a/test/transcribe.test.ts b/test/transcribe.test.tsnew file mode 100644index 0000000..4f29362--- /dev/null+++ b/test/transcribe.test.ts@@ -0,0 +1,167 @@+import { createHash } from 'node:crypto'+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { beforeEach, describe, expect, it } from 'vitest'+import { executableNames } from '../src/core/platform'+import { cleanTranscript, ModelDownload, Transcriber, voiceStatus } from '../src/core/transcribe'+import { voiceRefusal } from '../src/shared/voice'+import { encodeWav } from '../src/shared/wav'++const script = (dir: string, body: string): string => {+ const file = join(dir, 'whisper-cli')+ writeFileSync(file, `#!/bin/sh\n${body}\n`)+ chmodSync(file, 0o755)+ return file+}+const leftovers = (): string[] => readdirSync(tmpdir()).filter((f) => f.startsWith('tucano-voz-'))++const unix = process.platform !== 'win32' // the fake binary is a shell script++describe.runIf(unix)('finding whisper', () => {+ let dir = ''+ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'ad-voice-'))+ })++ it('finds the binary on the PATH and prefers the turbo model', () => {+ const bin = script(dir, 'exit 0')+ const models = join(dir, '.cache', 'whisper-cpp')+ mkdirSync(models, { recursive: true })+ for (const m of ['ggml-tiny.bin', 'ggml-large-v3-turbo.bin', 'outro.txt']) writeFileSync(join(models, m), '')+ expect(voiceStatus(undefined, { PATH: dir }, dir)).toEqual({ bin, model: join(models, 'ggml-large-v3-turbo.bin'), ready: true })+ })++ it('a path set by the person wins, and one that is gone is not ready', () => {+ const bin = script(dir, 'exit 0')+ const model = join(dir, 'meu.bin')+ writeFileSync(model, '')+ expect(voiceStatus({ bin, model }, { PATH: '' }, dir)).toEqual({ bin, model, ready: true })+ expect(voiceStatus({ bin: join(dir, 'whisper-sumiu'), model }, { PATH: '' }, dir).ready).toBe(false)+ })++ it('only takes a whisper binary and a .bin model, as full paths', () => {+ expect(voiceRefusal({ bin: '/bin/sh' })).toMatch(/whisper-cli/)+ expect(voiceRefusal({ bin: 'whisper-cli' })).toMatch(/whisper-cli/)+ expect(voiceRefusal({ model: '/tmp/x.txt' })).toMatch(/\.bin/)+ expect(voiceRefusal({ bin: '/opt/homebrew/bin/whisper-cli', model: '/tmp/x.bin' })).toBeNull()+ expect(voiceRefusal(undefined)).toBeNull()+ })+})++describe.runIf(unix)('transcribing', () => {+ let dir = ''+ let model = ''+ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'ad-voice-'))+ model = join(dir, 'm.bin')+ writeFileSync(model, '')+ })+ const status = (bin: string) => ({ bin, model, ready: true })+ const audio = Buffer.from('RIFF').toString('base64')++ it('gets the text, with the language and the audio, and leaves no file', async () => {+ const before = leftovers().length+ const bin = script(dir, 'echo "args: $*" > "$(dirname "$0")/args"; cat "$4" > "$(dirname "$0")/ouvido"; echo " Revisar o post do blog. "')+ expect(await new Transcriber().transcribe('a', audio, status(bin), 'pt')).toBe('Revisar o post do blog.')+ const args = (await import('node:fs')).readFileSync(join(dir, 'args'), 'utf8')+ expect(args).toContain('-l pt')+ expect(args).toContain(`-m ${model}`)+ expect((await import('node:fs')).readFileSync(join(dir, 'ouvido'), 'utf8')).toBe('RIFF')+ expect(leftovers()).toHaveLength(before)+ })++ it('an error says so and leaves no file', async () => {+ const before = leftovers().length+ const bin = script(dir, 'echo "modelo invalido" >&2; exit 3')+ await expect(new Transcriber().transcribe('a', audio, status(bin), 'pt')).rejects.toThrow(/modelo invalido/)+ expect(leftovers()).toHaveLength(before)+ })++ it('cancelling stops the process and leaves no file', async () => {+ const before = leftovers().length+ const bin = script(dir, 'sleep 30; echo tarde')+ const t = new Transcriber()+ const going = t.transcribe('a', audio, status(bin), 'pt')+ await new Promise((r) => setTimeout(r, 100))+ t.cancel('a')+ await expect(going).rejects.toThrow(/Cancelado/)+ expect(leftovers()).toHaveLength(before)+ })++ it('refuses without a binary, or with too much audio', async () => {+ await expect(new Transcriber().transcribe('a', audio, { ready: false }, 'pt')).rejects.toThrow(/Configurações/)+ await expect(new Transcriber().transcribe('a', 'x'.repeat(30_000_001), status(script(dir, 'exit 0')), 'pt')).rejects.toThrow(/longo/)+ expect(existsSync(join(dir, 'args'))).toBe(false)+ })++ it('drops what whisper prints for silence', () => {+ expect(cleanTranscript('[BLANK_AUDIO]\n (Música) \n')).toBe('')+ expect(cleanTranscript(' Primeira linha\n [inaudível]\n segunda linha\n')).toBe('Primeira linha segunda linha')+ })+})++describe('encodeWav', () => {+ it('writes a 16 kHz mono PCM header and clamps the samples', () => {+ const wav = encodeWav(new Float32Array([0, 1, -2]), 16_000)+ const v = new DataView(wav.buffer)+ expect(new TextDecoder().decode(wav.subarray(0, 4))).toBe('RIFF')+ expect(v.getUint16(22, true)).toBe(1)+ expect(v.getUint32(24, true)).toBe(16_000)+ expect(v.getUint32(40, true)).toBe(6)+ expect([v.getInt16(44, true), v.getInt16(46, true), v.getInt16(48, true)]).toEqual([0, 0x7fff, -0x7fff])+ })+})++describe('turning dictation on: the model download', () => {+ const body = Buffer.from('ggml model bytes, for a test')+ const sha = createHash('sha256').update(body).digest('hex')+ const models = { recommended: { file: 'ggml-test-turbo.bin', bytes: body.length, sha256: sha }, light: { file: 'ggml-test-small.bin', bytes: body.length, sha256: '0'.repeat(64) } }+ const serve = (bytes: Buffer, status = 200) =>+ (async () => new Response(new ReadableStream({ start: (c) => (c.enqueue(new Uint8Array(bytes.subarray(0, 10))), c.enqueue(new Uint8Array(bytes.subarray(10))), c.close()) }), { status })) as unknown as typeof fetch++ it('downloads, checks the hash, and the status finds it', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'voice-'))+ const changes: number[] = []+ const d = new ModelDownload(dir, () => changes.push(d.progress?.received ?? -1), serve(body), models)+ await d.start('recommended')+ expect(existsSync(join(dir, 'ggml-test-turbo.bin'))).toBe(true)+ expect(existsSync(join(dir, 'ggml-test-turbo.bin.part'))).toBe(false)+ expect(d.progress).toBeNull()+ expect(d.error).toBeNull()+ expect(changes.at(-1)).toBe(-1) // the last word: done+ // the app's bundled program and its own model folder come first+ const bundled = join(dir, 'bin')+ mkdirSync(bundled)+ writeFileSync(join(bundled, executableNames('whisper-cli')[0]!), '')+ const st = voiceStatus(undefined, { PATH: '' }, join(dir, 'nohome'), { bundled, models: dir })+ expect(st).toMatchObject({ ready: true, bin: join(bundled, executableNames('whisper-cli')[0]!), model: join(dir, 'ggml-test-turbo.bin') })+ })++ it("throws away a file that isn't the one expected, and says so", async () => {+ const dir = mkdtempSync(join(tmpdir(), 'voice-'))+ const d = new ModelDownload(dir, () => {}, serve(body), models)+ await d.start('light') // its hash doesn't match+ expect(readdirSync(dir)).toEqual([])+ expect(d.error).toMatch(/esperado|expected/)+ const d2 = new ModelDownload(dir, () => {}, serve(body, 404), models)+ await d2.start('recommended')+ expect(d2.error).toMatch(/404/)+ expect(readdirSync(dir)).toEqual([])+ })++ it('a cancelled download leaves nothing behind and no error', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'voice-'))+ const never = (async (_u: string, init: RequestInit) =>+ new Response(new ReadableStream({ start: (c) => (c.enqueue(new Uint8Array(body.subarray(0, 5))), init.signal!.addEventListener('abort', () => c.error(new DOMException('aborted', 'AbortError')))) }))) as unknown as typeof fetch+ const d = new ModelDownload(dir, () => {}, never, models)+ const going = d.start('recommended')+ await new Promise((r) => setTimeout(r, 20))+ expect(d.progress).toMatchObject({ model: 'recommended', received: 5 })+ d.cancel()+ await going+ expect(d.error).toBeNull()+ expect(d.progress).toBeNull()+ expect(readdirSync(dir)).toEqual([])+ })+})