From 5d0e8bac82d121c5a2dbb651852c8ef8ed84ed6f Mon Sep 17 00:00:00 2001 From: OnlyHelion Date: Sun, 6 Dec 2026 00:45:20 +0100 Subject: [PATCH 1/2] Windows support, live dictation, and redesigned model settings Windows: managed whisper.cpp runtime auto-downloaded on first use (pinned ggml-org release, checksum-verified, extracted to %LOCALAPPDATA%\opencode-dictation\bin); whisper-cli.exe and whisper-server.exe are looked up there first. macOS paths are unchanged (Homebrew dirs, brew install hint). Live dictation (optional, off by default): rolling audio windows are resampled and transcribed by a resident whisper-server that keeps the model warm across chunks, with a per-chunk fallback to whisper-cli; a final full-recording pass on stop replaces the draft and repairs chunk seams; plain Enter stops the session through the same path as the shortcut. Settings: model row with presets, folder Browse listing .bin files inline, and a Custom typed name; title column pinned to the row top; equal-width Browse/Apply; live-dictation toggle. Tests: 37 unit tests across chunks, server parsing, model-row helpers, settings and discovery. README and AGENTS.md updated for Windows. Signed-off-by: OnlyHelion --- AGENTS.md | 5 +- README.md | 25 ++- dist/gui-experimental.cjs | 11 +- package.json | 4 +- src/chunks.ts | 82 ++++++++ src/gui.tsx | 414 +++++++++++++++++++++++++++++++++---- src/model-row.ts | 55 +++++ src/recorder.ts | 92 ++++++++- src/server.ts | 421 +++++++++++++++++++++++++++++++++++++ src/settings-page.tsx | 423 ++++++++++++++++++++++++++++++++++++-- src/settings.ts | 15 +- src/whisper.ts | 183 ++++++++++++++++- test/chunks.test.ts | 75 +++++++ test/model-row.test.ts | 68 ++++++ test/server.test.ts | 90 ++++++++ test/settings.test.ts | 48 +++++ test/whisper.test.ts | 44 +++- 17 files changed, 1978 insertions(+), 77 deletions(-) create mode 100644 src/chunks.ts create mode 100644 src/model-row.ts create mode 100644 src/server.ts create mode 100644 test/chunks.test.ts create mode 100644 test/model-row.test.ts create mode 100644 test/server.test.ts create mode 100644 test/settings.test.ts diff --git a/AGENTS.md b/AGENTS.md index 61437e3..19db16b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # AGENTS.md - opencode-dictation -OpenCode Desktop GUI plugin, macOS only, whisper.cpp only. No TUI part, no LLM. +OpenCode Desktop GUI plugin, macOS and Windows, whisper.cpp only. No TUI part, no LLM. ## Key invariants @@ -14,6 +14,9 @@ OpenCode Desktop GUI plugin, macOS only, whisper.cpp only. No TUI part, no LLM. `whisper-cli` work lives there. - The Ipc id must start with the package name: `opencode-dictation.whisper`. - Desktop's PATH is minimal, so `whisper-cli` is looked up in Homebrew dirs too. + On Windows the managed runtime dir (`%LOCALAPPDATA%\opencode-dictation\bin`, + auto-downloaded from the pinned ggml-org release and checksum-verified) is + checked first, and `whisper-cli.exe` is the binary name. - Settings live in plugin storage (`Store.global`) and are edited in Settings → Dictation. `opencode.jsonc` options are not read. The window passes model and language on each Ipc call, and main validates them again. diff --git a/README.md b/README.md index b1fa7a7..c0da63e 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # opencode-dictation -Local voice dictation for the [OpenCode](https://opencode.ai) Desktop app on macOS. +Local voice dictation for the [OpenCode](https://opencode.ai) Desktop app on macOS and Windows. ![Dictating a message into the OpenCode prompt](assets/demo.gif) @@ -11,33 +11,36 @@ Local voice dictation for the [OpenCode](https://opencode.ai) Desktop app on mac ## Requirements -- macOS, OpenCode Desktop 2.2.5 or later -- whisper.cpp: +- OpenCode Desktop 2.2.5 or later +- macOS: whisper.cpp: ```bash brew install whisper-cpp ``` +- Windows: nothing to install. The official whisper.cpp CPU build is downloaded, checksum-verified, and extracted on first dictation. + ## Install ```bash opencode plugin add github:qonto/opencode-dictation ``` -Then restart Desktop. +Then restart Desktop. To load from a local checkout instead, put the repo's absolute path in the `plugins` list of `~/.config/opencode/opencode.jsonc`. ## Usage -Press `⌘D` to start recording, and again to stop. The transcript goes into the +Press `⌘D` (macOS) or `Ctrl+D` (Windows) to start recording, and again to stop. The transcript goes into the prompt. Change the key in **Settings → Shortcuts**. ## Settings Open **Settings → Dictation**. -| Setting | Default | What it does | -| ------------------ | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | -| Push-to-talk | Off | Hold the shortcut while you talk, and let go to stop. Off: press once to start, once to stop. | -| Send automatically | Off | Send the transcript as soon as it is ready. | -| Language | `en` | A whisper language code such as `fr`, or `auto` to detect it (adds a short delay). | -| Model | `large-v3-turbo-q5_0` | Any [whisper.cpp model](https://huggingface.co/ggerganov/whisper.cpp/tree/main), without `ggml-` and `.bin`. Downloads on first use. | +| Setting | Default | What it does | +| ------------------ | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Push-to-talk | Off | Hold the shortcut while you talk, and let go to stop. Off: press once to start, once to stop. | +| Send automatically | Off | Send the transcript as soon as it is ready. | +| Live dictation | Off | Transcribe while you speak; text updates as you talk. The final pass cleans up boundaries. | +| Language | `en` | A whisper language code such as `fr`, or `auto` to detect it (adds a short delay). | +| Model | `small.en` | Preset dropdown or Custom…: any [whisper.cpp model](https://huggingface.co/ggerganov/whisper.cpp/tree/main), without `ggml-` and `.bin`. Downloads on first use. | diff --git a/dist/gui-experimental.cjs b/dist/gui-experimental.cjs index b19955a..0ecc9b9 100644 --- a/dist/gui-experimental.cjs +++ b/dist/gui-experimental.cjs @@ -1,2 +1,9 @@ -"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const l=require("solid-js/web"),h=require("effect"),_=require("solid-js"),w=require("@opencode/plugin/gui"),ne=require("node:child_process"),re=require("node:crypto"),m=require("node:fs"),j=require("node:os"),S=require("node:path"),ie=require("node:stream"),oe=require("node:stream/promises"),M=16e3,z=600,I=44,se=I+(z+10)*M*2;function ae(e){if(e.length>se)throw new Error(`Recording too long (max ${z/60} min)`);if(e.lengthString.fromCharCode(...e.subarray(t,t+4));if(!(i(0)==="RIFF"&&i(8)==="WAVE"&&i(12)==="fmt "&&i(36)==="data"&&n.getUint16(20,!0)===1&&n.getUint16(22,!0)===1&&n.getUint32(24,!0)===M&&n.getUint16(34,!0)===16&&n.getUint32(40,!0)===e.length-I))throw new Error("Invalid WAV")}function ce(e,n=M){const i=new Uint8Array(44+e.length*2),r=new DataView(i.buffer),t=(o,a)=>{for(let c=0;c{const c=Math.max(-1,Math.min(1,o));r.setInt16(44+a*2,c<0?c*32768:c*32767,!0)}),i}async function le(){const e=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0}}),n=new MediaRecorder(e),i=[];n.ondataavailable=c=>i.push(c.data),n.start();const r=new AudioContext,t=r.createAnalyser();r.createMediaStreamSource(e).connect(t);const o=new Float32Array(t.fftSize),a=()=>{e.getTracks().forEach(c=>c.stop()),r.close()};return{level:()=>(t.getFloatTimeDomainData(o),Math.sqrt(o.reduce((c,d)=>c+d*d,0)/o.length)),stop:async()=>{const c=new Promise(f=>n.onstop=f);n.stop(),await c,a();const d=await new Blob(i).arrayBuffer(),v=new AudioContext({sampleRate:M});try{const f=await v.decodeAudioData(d);return ce(f.getChannelData(0))}finally{await v.close()}},cancel:()=>{n.onstop=null,n.state!=="inactive"&&n.stop(),a()}}}const E="large-v3-turbo-q5_0",T="en",L="https://huggingface.co/ggerganov/whisper.cpp/tree/main",de=h.Schema.Struct({autoSend:h.Schema.Boolean,pushToTalk:h.Schema.Boolean,model:h.Schema.String,language:h.Schema.String}),ue={autoSend:!1,pushToTalk:!1,model:E,language:T},x=e=>/^[\w.-]+$/.test(e)&&!e.startsWith("."),G=e=>/^(auto|[a-z]{2,3})$/.test(e);function A(e){if(e===void 0||e==="")return E;if(typeof e=="string"&&x(e))return e;throw new Error(`Invalid model name "${e}"`)}function he(e){if(e===void 0||e==="")return T;if(typeof e=="string"&&G(e))return e;throw new Error(`Invalid language "${e}"`)}var ge=l.template('

'),me=l.template('
'),fe=l.template("
"),pe=l.template("
"),we=l.template("Not bound"),Se=l.template("Hugging Face");function ve(e){return[(()=>{var n=ge(),i=n.firstChild,r=i.firstChild,t=r.firstChild,o=t.nextSibling;return l.insert(t,()=>e.title),l.insert(o,()=>e.description),n})(),(()=>{var n=me(),i=n.firstChild,r=i.firstChild;return l.insert(r,()=>e.children),n})()]}function C(e){return(()=>{var n=fe(),i=n.firstChild,r=i.firstChild,t=r.nextSibling,o=i.nextSibling;return l.insert(r,()=>e.title),l.insert(t,()=>e.description),l.insert(o,()=>e.children),n})()}function H(e){const[n,i]=_.createSignal(e.value),r=()=>n()===""||e.valid(n()),t=()=>n()!==e.value,o=()=>{r()&&t()&&e.save(n())};return l.createComponent(C,{get title(){return e.title},get description(){return e.description},get children(){var a=pe(),c=a.firstChild;return l.insert(c,l.createComponent(e.ui.TextInput,{get label(){return e.title},get value(){return n()},get placeholder(){return e.placeholder},onInput:i,onSubmit:o,get invalid(){return!r()}})),l.insert(a,l.createComponent(e.ui.Button,{variant:"neutral",get disabled(){return!r()||!t()},onClick:o,children:"Apply"}),null),a}})}function ye(e){const n=()=>e.settings.value,i=(t,o)=>e.settings.update(a=>{a[t]=o}),r=()=>{const t=e.keys();return t.length?l.createComponent(e.ui.Keybind,{keys:t}):we()};return l.createComponent(ve,{title:"Dictation",description:"Voice dictation on your Mac with whisper.cpp. No audio leaves the machine.",get children(){return[l.createComponent(C,{title:"Shortcut",description:"Change it in Settings → Shortcuts, under Dictation: record / transcribe.",get children(){return r()}}),l.createComponent(C,{title:"Push-to-talk",description:"Hold the shortcut while you talk, and let go to stop. Off: press once to start, once to stop.",get children(){return l.createComponent(e.ui.Switch,{label:"Push-to-talk",hideLabel:!0,get checked(){return n().pushToTalk},onChange:t=>i("pushToTalk",t)})}}),l.createComponent(C,{title:"Send automatically",description:"Send the transcript as soon as it is ready.",get children(){return l.createComponent(e.ui.Switch,{label:"Send automatically",hideLabel:!0,get checked(){return n().autoSend},onChange:t=>i("autoSend",t)})}}),l.createComponent(H,{get ui(){return e.ui},title:"Language",get value(){return n().language},placeholder:T,valid:G,save:t=>i("language",t||T),description:"A whisper language code such as en or fr, or auto to detect it (adds a short delay)."}),l.createComponent(H,{get ui(){return e.ui},title:"Model",get value(){return n().model},placeholder:E,valid:x,save:t=>i("model",t||E),get description(){return["Any whisper.cpp model from"," ",(()=>{var t=Se();return t.$$click=o=>{o.preventDefault(),e.system.openExternal(L)},l.setAttribute(t,"href",L),t})(),", named without ggml- and .bin. Downloads on first use."]}})]}})}l.delegateEvents(["click"]);const be={[E]:"394221709cd5ad1f40c46e6031ca61bce88931e6e088c188294c6d5a55ffa7e2"},ke=4e9,U=S.join(j.homedir(),".local","share","whisper-cpp"),Ee=[U,"/opt/homebrew/share/whisper-cpp/models","/usr/local/share/whisper-cpp/models"],$e=["/opt/homebrew/bin","/usr/local/bin"],De=12e4,R=e=>`ggml-${e}.bin`,X=e=>`https://huggingface.co/ggerganov/whisper.cpp/resolve/main/${R(e)}`;function W(e){return Ee.map(n=>S.join(n,R(e))).find(n=>m.existsSync(n))}const _e=e=>{try{return m.accessSync(e,m.constants.X_OK),m.statSync(e).isFile()}catch{return!1}};function V(){return[...$e,...(process.env.PATH??"").split(S.delimiter)].filter(n=>S.isAbsolute(n)).map(n=>S.join(n,"whisper-cli")).find(_e)}function Y(e){return e>=1e9?`${(e/1e9).toFixed(1)} GB`:`${Math.round(e/1e6)} MB`}async function J(e){const n=await fetch(X(e),{method:"HEAD",redirect:"manual"});if(n.status===404)throw new Error(`Unknown model "${e}". See ${L}`);if(n.status>=400)throw new Error(`Model lookup failed: HTTP ${n.status}`);const i=n.headers.get("x-linked-etag")?.replaceAll('"',"")??"",r=Number(n.headers.get("x-linked-size"));if(!/^[0-9a-f]{64}$/.test(i)||!(r>0))throw new Error("Model lookup failed: no size or checksum");if(r>ke)throw new Error(`Model too large: ${Y(r)}`);return{sha256:i,size:r}}async function Ce(e){return Y((await J(e)).size)}async function Te(e,n,i){const r=re.createHash("sha256");let t=0;if(await oe.pipeline(e,async function*(o){for await(const a of o){if(t+=a.length,t>i.size)throw new Error("Model download is larger than expected");r.update(a),yield a}},m.createWriteStream(n)),t!==i.size||r.digest("hex")!==i.sha256)throw new Error("Model download failed the integrity check")}async function Me(e){const n=await J(e),i=be[e]??n.sha256,r=await fetch(X(e));if(!r.ok||!r.body)throw new Error(`Download failed: HTTP ${r.status}`);m.mkdirSync(U,{recursive:!0});const t=S.join(U,R(e)),o=`${t}.part`;try{await Te(ie.Readable.fromWeb(r.body),o,{sha256:i,size:n.size}),m.renameSync(o,t)}catch(a){throw m.rmSync(o,{force:!0}),a}}function Ae(e){return e.replace(/\[.*?\]/g,"").replace(/\(.*?\)/g,"").replace(/\s+/g," ").trim()}async function Ie(e,n){const i=m.mkdtempSync(S.join(j.tmpdir(),"opencode-dictation-")),r=S.join(i,"recording.wav");try{ae(e),m.writeFileSync(r,e);const t=["-m",n.model,"-f",r,"-l",n.language,"-np","-nt"],{code:o,stdout:a,stderr:c}=await Le(n.binary,t),d=c.match(/error: unknown language '([^']+)'/);if(d)throw new Error(`Unknown whisper language: ${d[1]}`);if(o!==0)throw new Error(c.trim().split(` -`).pop()||`whisper-cli exited (${o})`);return Ae(a)}finally{m.rmSync(i,{recursive:!0,force:!0})}}function Le(e,n){return new Promise((i,r)=>{const t=ne.spawn(e,n,{stdio:["ignore","pipe","pipe"]});let o="",a="";t.stdout.on("data",d=>o+=d),t.stderr.on("data",d=>a+=d);const c=setTimeout(()=>{t.kill("SIGKILL"),r(new Error("Transcription timed out"))},De);t.on("error",d=>{clearTimeout(c),r(d)}),t.on("close",d=>{clearTimeout(c),i({code:d,stdout:o,stderr:a})})})}const Ue=.01,ze=1e3,Re=100,Oe={Meta:"metaKey",Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey"},Fe=e=>{const n=Math.floor(e/1e3);return`${Math.floor(n/60)}:${String(n%60).padStart(2,"0")}`},K=w.Ipc.define({id:"opencode-dictation.whisper",methods:{check:{input:h.Schema.String,output:h.Schema.Struct({whisper:h.Schema.Boolean,model:h.Schema.Boolean,name:h.Schema.String,size:h.Schema.String,error:h.Schema.optional(h.Schema.String)})},download:{input:h.Schema.String},transcribe:{input:h.Schema.Struct({wav:h.Schema.Uint8Array,model:h.Schema.String,language:h.Schema.String}),output:h.Schema.String}}}),Be=w.Plugin.define({os:["macos"],stores:{settings:w.Store.global(de,ue),intro:w.Store.global(h.Schema.Struct({seen:h.Schema.Boolean}),{seen:!1})},setup(e){const n=e.main(K),i=()=>e.stores.settings.value,r=`${e.id}.record`;let t,o,a=!1,c,d;const[v,f]=_.createSignal(),y=s=>{c?.dismiss(),c=e.toast.show(s)},Q=s=>{const u=Date.now();let p=0;const b=()=>{const g=Date.now();if(g-u>=z*1e3){k();return}s.level()>Ue&&(p=g),f({kind:"dictating",elapsed:g-u,heard:g-p{o&&!e.stores.intro.value.seen&&e.stores.intro.set({seen:!0}),clearInterval(d),d=void 0,o=void 0,f(void 0)},$=()=>{o?.cancel(),O()};_.onCleanup($);const F=()=>e.keybinds.keybind(r).join(""),Z=async()=>{const s=await n.check(i().model);if(s.error)return y({title:s.error,variant:"error"}),!1;if(!s.whisper)return y({title:"whisper-cli not found",description:"Install it with: brew install whisper-cpp",variant:"error"}),!1;if(s.model)return!0;if(!await e.dialogs.confirm({title:"Download the speech model?",description:`Dictation needs the ${s.name} whisper model (${s.size}). It is downloaded once from Hugging Face.`,confirm:"Download"}))return!1;f({kind:"downloading",size:s.size});try{await n.download(s.name)}finally{f(void 0)}return!0},ee=async s=>{if(!e.screen.current()?.composer){y({title:"Open a session first",variant:"error"});return}if(await Z()){if(o=await le(),s&&!t){$(),y({title:`Hold ${F()} while you talk`});return}c?.dismiss(),Q(o)}},te=async s=>{O(),f({kind:"transcribing"});let u;try{const{model:g,language:D}=i();u=await n.transcribe({wav:await s.stop(),model:g,language:D})}finally{f(void 0)}if(!u){y({title:"No speech detected"});return}const p=e.screen.current()?.composer,b=e.sessions.current();if(!p||!b){await e.system.copy(u),y({title:"No session open: transcript copied to clipboard"});return}if(i().autoSend&&p.text().trim()===""){const g=p.model(),{client:D}=b.server;g&&await D.session.switchModel({sessionID:b.id,model:{id:g.modelID,providerID:g.providerID,variant:g.variant}}),await D.session.prompt({sessionID:b.id,text:u});return}p.insert(u),p.focus()},k=async(s=!1)=>{if(!a){a=!0;try{await(o?te(o):ee(s))}catch(u){$(),y({title:u instanceof Error?u.message:String(u),variant:"error"})}finally{a=!1}}};e.add(w.ComposerPill,{id:"status",show:()=>{const s=v();if(s?.kind==="downloading")return{label:`Downloading speech model (${s.size})…`,icon:"download"};if(s?.kind==="transcribing")return{label:"Transcribing…",icon:"pencil-line"};if(s?.kind!=="dictating")return;const u=F(),p=u?` · ${i().pushToTalk?`Release ${u}`:u} to stop`:"";return{label:`Dictating ${Fe(s.elapsed)}${p}`,icon:s.heard?"waveform":"dash",tone:s.heard?"success":"warning",title:s.heard?"The mic hears you. Click to stop":"No sound from the mic",run:()=>{k()}}}}),e.add(w.ComposerPill,{id:"intro",order:1,show:()=>v()?.kind==="dictating"&&!e.stores.intro.value.seen?{label:"Dictation settings",icon:"info",run:()=>e.layout.settings("dictation")}:void 0});const B=()=>{t=void 0,o&&k()},q=s=>{i().pushToTalk&&(s.repeat||!e.keybinds.matches(r,s)||(t=s,o||k(!0)))},N=s=>{if(!t)return;const u=Oe[s.key];(s.code===t.code||u&&t[u])&&B()},P=()=>{t&&B()};window.addEventListener("keydown",q,!0),window.addEventListener("keyup",N,!0),window.addEventListener("blur",P),_.onCleanup(()=>{window.removeEventListener("keydown",q,!0),window.removeEventListener("keyup",N,!0),window.removeEventListener("blur",P)}),e.add(w.SettingsPage,{id:"dictation",title:"Dictation",icon:"waveform",entries:[{id:"dictation",title:"Dictation",description:"Voice dictation with whisper.cpp",keywords:"voice speech whisper microphone auto-send push-to-talk model language"}],render:()=>l.createComponent(ye,{get ui(){return e.ui},get system(){return e.system},get settings(){return e.stores.settings},keys:()=>e.keybinds.keybind(r)})}),e.add(w.Command,()=>({id:"record",title:"Dictation: record / transcribe",section:"prompt",bind:"mod+d",editable:!0,run:()=>{setTimeout(()=>{t||k()})}})),e.add(w.Command,()=>({id:"cancel",title:"Dictation: cancel recording",section:"prompt",run:()=>{o&&$()}}))},main(e){const n=(r,t)=>e.log.write(r,`[dictation] ${t}`);let i;e.provide(K,{check:async r=>{try{const t=A(r),o=W(t)!==void 0;return{whisper:V()!==void 0,model:o,name:t,size:o?"":await Ce(t)}}catch(t){return{whisper:!1,model:!1,name:"",size:"",error:t instanceof Error?t.message:String(t)}}},download:async r=>{const t=A(r);i??=Me(t).then(()=>n("info",`Downloaded model ${t}`)).finally(()=>i=void 0),await i},transcribe:async({wav:r,model:t,language:o})=>{const a=W(A(t)),c=V();if(!a||!c)throw new Error("Speech model or whisper-cli missing");const d=Date.now(),v=await Ie(r,{binary:c,model:a,language:he(o)});return n("debug",`Transcribed ${r.length} bytes in ${Date.now()-d} ms`),v}})}});exports.default=Be; +"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const a=require("solid-js/web"),f=require("effect"),b=require("solid-js"),R=require("@opencode/plugin/gui"),Re=require("node:child_process"),Ue=require("node:http"),Ye=require("node:net"),Xe=require("node:crypto"),w=require("node:fs"),Y=require("node:os"),y=require("node:path"),Be=require("node:stream"),Je=require("node:stream/promises"),Ze=2e3,Qe=3e3;function et(e,t,n){const r=new Float32Array(Math.max(0,Math.floor(e.length*n/t))),o=t/n;for(let i=0;ie.toLowerCase().replace(/[^\p{L}\p{N}]/gu,""),_e=e=>e.trim().split(/\s+/).filter(t=>t!==""),tt=6;function nt(e){const t=e.map(pe);for(let n=1;n<=tt&&n*3<=t.length;n++){let r=1;for(;t.length>=(r+1)*n&&t.slice(t.length-(r+1)*n,t.length-r*n).every((o,i)=>o===t[t.length-n+i]);)r++;if(r>=3)return e.slice(0,e.length-(r-1)*n)}return e}function rt(e,t){const n=nt(_e(t)),r=_e(e);for(let o=Math.min(r.length,n.length);o>=1;o--){const i=[];for(let c=0;cot)throw new Error(`Recording too long (max ${ke/60} min)`);if(e.lengthString.fromCharCode(...e.subarray(o,o+4));if(!(n(0)==="RIFF"&&n(8)==="WAVE"&&n(12)==="fmt "&&n(36)==="data"&&t.getUint16(20,!0)===1&&t.getUint16(22,!0)===1&&t.getUint32(24,!0)===K&&t.getUint16(34,!0)===16&&t.getUint32(40,!0)===e.length-ge))throw new Error("Invalid WAV")}function ee(e,t=K){const n=new Uint8Array(44+e.length*2),r=new DataView(n.buffer),o=(i,c)=>{for(let l=0;l{const l=Math.max(-1,Math.min(1,i));r.setInt16(44+c*2,l<0?l*32768:l*32767,!0)}),n}const at=.01;async function st(){const e=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0}}),t=new MediaRecorder(e),n=[];t.ondataavailable=g=>n.push(g.data),t.start();const r=new AudioContext,o=r.createAnalyser(),i=r.createMediaStreamSource(e);i.connect(o);const c=new Float32Array(o.fftSize),l=r.createScriptProcessor(4096,1,1),d=r.createGain();d.gain.value=0,i.connect(l),l.connect(d),d.connect(r.destination);const E=[];let S=0;l.onaudioprocess=g=>{const h=g.inputBuffer.getChannelData(0);E.push(new Float32Array(h)),S+=h.length};const P=Math.round(r.sampleRate*Ze/1e3),T=Math.round(r.sampleRate*Qe/1e3);let v=0,U=!1;const F=(g,h)=>{const $=new Float32Array(h);let x=0,p=0;for(const k of E){if(p+k.length<=g){p+=k.length;continue}const L=Math.max(0,g-p),C=Math.min(k.length,g+h-p);if(C>L&&$.set(k.subarray(L,C),x),x+=C-L,p+=k.length,x===h)break}return $},O=()=>{U=!0,e.getTracks().forEach(g=>g.stop()),r.close()};return{level:()=>(o.getFloatTimeDomainData(c),Math.sqrt(c.reduce((g,h)=>g+h*h,0)/c.length)),chunk:()=>{if(U||S-vC+A*A,0)/k.length){const g=new Promise(x=>t.onstop=x);t.stop(),await g,O();const h=await new Blob(n).arrayBuffer();if(h.byteLength===0)return ee(new Float32Array(0));const $=new AudioContext({sampleRate:K});try{const x=await $.decodeAudioData(h);return ee(x.getChannelData(0))}catch{return ee(new Float32Array(0))}finally{await $.close()}},cancel:()=>{t.onstop=null,t.state!=="inactive"&&t.stop(),O()}}}const de="small.en",ae="en",we="https://huggingface.co/ggerganov/whisper.cpp/tree/main",ct=f.Schema.Struct({autoSend:f.Schema.Boolean,liveDictation:f.Schema.Boolean,pushToTalk:f.Schema.Boolean,model:f.Schema.String,language:f.Schema.String}),lt={autoSend:!1,liveDictation:!1,pushToTalk:!1,model:de,language:ae},dt=e=>/^[\w.-]+$/.test(e)&&!e.startsWith("."),se=e=>e.endsWith(".bin")&&(/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("/")),Pe=e=>dt(e)||se(e),Oe=e=>/^(auto|[a-z]{2,3})$/.test(e);function j(e){if(e===void 0||e==="")return de;if(typeof e=="string"&&Pe(e))return e;throw new Error(`Invalid model name "${e}"`)}function he(e){if(e===void 0||e==="")return ae;if(typeof e=="string"&&Oe(e))return e;throw new Error(`Invalid language "${e}"`)}const ut={"large-v3-turbo-q5_0":"394221709cd5ad1f40c46e6031ca61bce88931e6e088c188294c6d5a55ffa7e2",[de]:"c6138d6d58ecc8322097e0f987c32f1be8bb0a18532a3f88f734d1bbf9c41e5d"},ht=4e9,ce=y.join(Y.homedir(),".local","share","whisper-cpp"),ft=[ce,"/opt/homebrew/share/whisper-cpp/models","/usr/local/share/whisper-cpp/models"],mt=["/opt/homebrew/bin","/usr/local/bin"],pt=12e4,Fe="b5907",gt=`https://api.github.com/repos/ggml-org/whisper.cpp/releases/tags/${Fe}`,wt=1e8,X=typeof process>"u"?void 0:process,J=X?.platform==="win32",Ne=J?"whisper-cli.exe":"whisper-cli",fe=X?.arch==="arm64"?"whisper-bin-win-cpu-arm64.zip":"whisper-bin-x64.zip",le=J?y.join(X?.env.LOCALAPPDATA??y.join(Y.homedir(),"AppData","Local"),"opencode-dictation","bin"):y.join(ce,"runtime"),Ce=e=>`ggml-${e}.bin`,ze=e=>`https://huggingface.co/ggerganov/whisper.cpp/resolve/main/${Ce(e)}`;function vt(e){if(!y.isAbsolute(e))throw new Error(`Not an absolute folder path: ${e}`);if(!w.existsSync(e)||!w.statSync(e).isDirectory())throw new Error(`Folder not found: ${e}`);return w.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isFile()&&t.name.endsWith(".bin")).map(t=>{const n=y.join(e,t.name);return{path:n,name:t.name,size:w.statSync(n).size}}).sort((t,n)=>t.name.localeCompare(n.name))}function te(e){return se(e)?w.existsSync(e)?e:void 0:ft.map(t=>y.join(t,Ce(e))).find(t=>w.existsSync(t))}const ve=e=>{try{return w.accessSync(e,w.constants.X_OK),w.statSync(e).isFile()}catch{return!1}};function yt(e,t){const n=y.join(e,t);if(ve(n))return n;if(!(!J||!w.existsSync(e)))return w.readdirSync(e,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>y.join(e,r.name,t)).find(ve)}function We(e){const t=[...J?[le]:[],...mt,...(X?.env.PATH??"").split(y.delimiter)].filter(n=>y.isAbsolute(n));for(const n of t){const r=n===le?yt(n,e):y.join(n,e);if(r!==void 0&&ve(r))return r}}function oe(){return We(Ne)}function $e(e){return e>=1e9?`${(e/1e9).toFixed(1)} GB`:`${Math.round(e/1e6)} MB`}async function qe(e){const t=await fetch(ze(e),{method:"HEAD",redirect:"manual"});if(t.status===404)throw new Error(`Unknown model "${e}". See ${we}`);if(t.status>=400)throw new Error(`Model lookup failed: HTTP ${t.status}`);const n=t.headers.get("x-linked-etag")?.replaceAll('"',"")??"",r=Number(t.headers.get("x-linked-size"));if(!/^[0-9a-f]{64}$/.test(n)||!(r>0))throw new Error("Model lookup failed: no size or checksum");if(r>ht)throw new Error(`Model too large: ${$e(r)}`);return{sha256:n,size:r}}async function St(e){return $e((await qe(e)).size)}async function je(e,t,n){const r=Xe.createHash("sha256");let o=0;if(await Je.pipeline(e,async function*(i){for await(const c of i){if(o+=c.length,o>n.size)throw new Error("Model download is larger than expected");r.update(c),yield c}},w.createWriteStream(t)),o!==n.size||r.digest("hex")!==n.sha256)throw new Error("Model download failed the integrity check")}async function bt(e){const t=await qe(e),n=ut[e]??t.sha256,r=await fetch(ze(e));if(!r.ok||!r.body)throw new Error(`Download failed: HTTP ${r.status}`);w.mkdirSync(ce,{recursive:!0});const o=y.join(ce,Ce(e)),i=`${o}.part`;try{await je(Be.Readable.fromWeb(r.body),i,{sha256:n,size:t.size}),w.renameSync(i,o)}catch(c){throw w.rmSync(i,{force:!0}),c}}let me;async function Et(){const e=await fetch(gt,{headers:{Accept:"application/vnd.github+json","User-Agent":"opencode-dictation"}});if(!e.ok)throw new Error(`whisper.cpp release lookup failed: HTTP ${e.status}`);const n=(await e.json()).assets?.find(i=>i.name===fe),r=/^sha256:([0-9a-f]{64})$/.exec(n?.digest??"")?.[1],o=n?.size??0;if(!n?.browser_download_url||!r||!(o>0))throw new Error(`No verified ${fe} in whisper.cpp release ${Fe}`);if(o>wt)throw new Error("whisper.cpp runtime is larger than expected");return{name:fe,url:n.browser_download_url,size:o,sha256:r}}function kt(){const e=me??Et().catch(t=>{throw me=void 0,t});return me=e,e}async function Ct(){const e=await kt();w.mkdirSync(le,{recursive:!0});const t=w.mkdtempSync(y.join(Y.tmpdir(),"opencode-dictation-")),n=y.join(t,e.name);try{const r=await fetch(e.url);if(!r.ok||!r.body)throw new Error(`Runtime download failed: HTTP ${r.status}`);await je(Be.Readable.fromWeb(r.body),n,{sha256:e.sha256,size:e.size});const o=y.join(X?.env.SystemRoot??"C:\\Windows","System32","tar.exe");let i;try{i=await He(o,["-xf",n,"-C",le])}catch{throw new Error("Could not run tar.exe; Windows 10 version 1803 or later is required")}const{code:c,stderr:l}=i;if(c!==0)throw new Error(`Extraction failed: ${l.trim().split(` +`).pop()}`);const d=oe();if(!d)throw new Error(`${Ne} not found after extraction`);return d}finally{w.rmSync(t,{recursive:!0,force:!0})}}function ye(){return Math.max(1,Math.min(Y.cpus().length,16))}function $t(e){return e.replace(/\[.*?\]/g,"").replace(/\(.*?\)/g,"").replace(/\s+/g," ").trim()}async function xt(e,t){const n=w.mkdtempSync(y.join(Y.tmpdir(),"opencode-dictation-")),r=y.join(n,"recording.wav");try{it(e),w.writeFileSync(r,e);const o=["-m",t.model,"-f",r,"-l",t.language,"-np","-nt","-t",String(ye())],{code:i,stdout:c,stderr:l}=await He(t.binary,o),d=l.match(/error: unknown language '([^']+)'/);if(d)throw new Error(`Unknown whisper language: ${d[1]}`);if(i!==0)throw new Error(l.trim().split(` +`).pop()||`whisper-cli exited (${i})`);return $t(c)}finally{w.rmSync(n,{recursive:!0,force:!0})}}function He(e,t){return new Promise((n,r)=>{const o=Re.spawn(e,t,{stdio:["ignore","pipe","pipe"]});let i="",c="";o.stdout.on("data",d=>i+=d),o.stderr.on("data",d=>c+=d);const l=setTimeout(()=>{o.kill("SIGKILL"),r(new Error("Transcription timed out"))},pt);o.on("error",d=>{clearTimeout(l),r(d)}),o.on("close",d=>{clearTimeout(l),n({code:d,stdout:i,stderr:c})})})}class Ve extends Error{constructor(t="whisper-server is unavailable"){super(t),this.name="ChunkServerUnavailable"}}const _t=J?"whisper-server.exe":"whisper-server",Me=3e4,Mt=250,Tt=2e3,Dt=3e4,At=12e4,It=64*1024;let D,G=!1,Se,W,ie=0;function Te(){return We(_t)}function Lt(){const e=[];let t=0;return{push(n){for(e.push(n),t+=n.length;t>It&&e.length>1;)t-=e.shift()?.length??0},tail:()=>e.join("")}}function Rt(){return new Promise((e,t)=>{const n=Ye.createServer();n.once("error",t),n.listen(0,"127.0.0.1",()=>{const r=n.address();n.close(()=>{r!==null&&typeof r=="object"?e(r.port):t(new Error("Could not pick a free port"))})})})}const Ut=e=>new Promise(t=>setTimeout(t,e));function Bt(e,t){const n=Lt(),r=Re.spawn(e.binary,["-m",e.model,"-t",String(e.threads),"-l",e.language,"-nt","-sns","--host","127.0.0.1","--port",String(t)],{stdio:["ignore","pipe","pipe"]});return r.stdout?.on("data",o=>n.push(o.toString("utf8"))),r.stderr?.on("data",o=>n.push(o.toString("utf8"))),{proc:r,log:n}}function Pt(e){return new Promise(t=>{let n=!1;const r=i=>{n||(n=!0,t(i))},o=Ue.get(`http://127.0.0.1:${e}/`,i=>{i.resume(),r(!0)});o.setTimeout(Tt,()=>o.destroy()),o.on("error",()=>r(!1)),o.on("close",()=>r(!1))})}class be extends Error{}function Ot(e,t){const n=t.tail().trim();return n===""?e:`${e}; server log: ${n}`}async function Ft(e){const t=new Promise(r=>{e.proc.once("error",o=>r(new be(`whisper-server failed to start: ${o.message}`))),e.proc.once("close",o=>r(new be(`whisper-server exited (code ${String(o)}) during startup`)))}),n=Date.now()+Me;for(;;){if(await Pt(e.port))return;const r=await Promise.race([Ut(Mt),t]);if(r!==void 0)throw r;if(Date.now()>=n)throw new Error(`whisper-server did not become ready within ${Me/1e3} s`)}}function xe(e){try{e.kill()}catch{}}async function Nt(e){let t;for(let n=0;n<2;n++){const r=await Rt(),{proc:o,log:i}=Bt(e,r),c={proc:o,port:r,model:e.model,language:e.language,log:i,dead:!1};try{return await Ft(c),c}catch(l){const d=l instanceof Error?l:new Error(String(l));if(xe(o),t=new Error(Ot(d.message,i)),!(d instanceof be))break}}throw t??new Error("whisper-server failed to start")}async function De(e){if(G)throw new Ve("whisper-server failed earlier in this session");if(!(D!==void 0&&!D.dead&&D.model===e.model&&D.language===e.language))return Se??=zt(e),Se}async function zt(e){ue();const t=ie;try{const n=await Nt(e);if(t!==ie){xe(n.proc);return}n.proc.once("close",()=>{D===n&&(D.dead=!0)}),D=n,Ge()}catch(n){throw t===ie&&(G=!0),n}finally{Se=void 0}}function Wt(e){let t;try{t=JSON.parse(e)}catch{throw new Error("whisper-server returned invalid JSON")}const n=typeof t=="object"&&t!==null?t:{};if(typeof n.text!="string")throw new Error("whisper-server response has no text field");return n.text.trim()}function qt(e){const t=`opencode-dictation-${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`,n=Buffer.from(`--${t}\r +Content-Disposition: form-data; name="file"; filename="chunk.wav"\r +Content-Type: audio/wav\r +\r +`,"utf8"),r=Buffer.from(`\r +--${t}--\r +`,"utf8");return{contentType:`multipart/form-data; boundary=${t}`,body:Buffer.concat([n,e,r])}}const jt=()=>typeof fetch=="function"&&typeof FormData=="function"&&typeof Blob=="function";async function Ht(e,t,n){const r=new AbortController,o=setTimeout(()=>r.abort(),n);try{const i=new FormData;i.append("file",new Blob([t.slice()],{type:"audio/wav"}),"chunk.wav");const c=await fetch(`http://127.0.0.1:${e}/inference`,{method:"POST",body:i,signal:r.signal});if(c.status!==200)throw new Error(`whisper-server inference failed: HTTP ${c.status}`);return await c.text()}finally{clearTimeout(o)}}function Vt(e,t,n){const{contentType:r,body:o}=qt(t);return new Promise((i,c)=>{const l=Ue.request({host:"127.0.0.1",port:e,path:"/inference",method:"POST",headers:{"content-type":r,"content-length":String(o.byteLength)}},d=>{const E=[];d.on("data",S=>E.push(S)),d.on("error",c),d.on("end",()=>{d.statusCode!==200?c(new Error(`whisper-server inference failed: HTTP ${String(d.statusCode)}`)):i(Buffer.concat(E).toString("utf8"))})});l.setTimeout(n,()=>l.destroy(new Error("whisper-server inference timed out"))),l.on("error",c),l.end(o)})}async function Kt(e,t=Dt){const n=D;if(G||n===void 0||n.dead)throw new Ve("whisper-server is not running");try{const r=jt()?await Ht(n.port,e,t):await Vt(n.port,e,t),o=Wt(r);return Ge(),o}catch(r){throw ue(),G=!0,r}}function Ke(){W!==void 0&&(clearTimeout(W),W=void 0)}function Ge(){Ke(),W=setTimeout(()=>{W=void 0,ue()},At),W?.unref?.()}function ue(){ie+=1,Ke(),D!==void 0&&(D.dead=!0,xe(D.proc),D=void 0)}function Gt(){ue(),G=!1}function Yt(e){const t=e.replace(/[\\/]+$/,""),n=Math.max(t.lastIndexOf("\\"),t.lastIndexOf("/")),r=n===-1?t:t.slice(n+1);return r===""||/^[A-Za-z]:$/.test(r)?e:r}function Xt(e){return`Using ${e.name}`}function H(e){const t=Math.max(e.lastIndexOf("\\"),e.lastIndexOf("/"));return t===-1?e:e.slice(t+1)}function Ae(e,t=32){return e.length<=t?e:`${e.slice(0,t-1)}…`}var Jt=a.template('

'),Zt=a.template('
'),Qt=a.template("
"),en=a.template("
"),tn=a.template(''),nn=a.template("
"),rn=a.template(''),on=a.template('
'),an=a.template(""),sn=a.template('
'),cn=a.template('
No .bin files in that folder.'),ln=a.template('