morph-transcribe, which returns the final text 195 ms after you stop talking (median on a 10.5 second clip) for $0.18 per audio hour. While you talk, morph-transcribe-live types your words into the input as you say them, and the final text replaces them in place when you let go.
How it works
The app opens one realtime transcription socket at launch and keeps it open. While you hold the key, it streams 16 kHz PCM in 100 ms chunks. When you let go, it sendsinput_audio_buffer.commit. The audio is already on the server, so the only wait is the model running on your turn. The app then replaces the words it typed while you talked with that transcript.
To type while you talk, each dictation also opens a short morph-transcribe-live session that gets the same audio and returns text as you speak, and the app types it at your cursor. The app closes it when you let go, because an open live session holds live capacity. The text left in your input always comes from morph-transcribe: the app deletes only the live words that differ from it and types the rest. With typing as you talk turned off, the app pastes the transcript when you let go, through the clipboard, and puts back what was on the clipboard before.
The open socket costs nothing between dictations; you pay only for the audio in each one: $0.18 per hour on `morph-transcribe`, plus $0.198 for typing as you talk on morph-transcribe-live. Dictating an hour a day comes to about $11.34 a month, or $5.40 with typing as you talk turned off in the app’s settings.
Copy the prompt
ReplaceYOUR_API_KEY with a key from the dashboard, or copy the prompt from the speech to text post while signed in to get your key filled in. The agent stores the key in your system keychain, never in the code.
- macOS
- Windows
- Linux
macOS build prompt
# Build me a dictation app for macOS
I want my own version of Wispr Flow: I hold a hotkey, talk, let go, and the text appears wherever my cursor is, in any app. While I talk, my words appear right there in the input as I say them, and when I let go the final text replaces them in place.
It runs on Morph's speech-to-text API with two models. morph-transcribe (NVIDIA Nemotron 3.5 Transcribe) in dictation mode writes the text that gets inserted: measured from the moment I stop talking, it returns the final text in about 195 ms (the median on a 10.5 second clip), at $0.18 per hour of audio. morph-transcribe-live (NVIDIA Nemotron 3.5 ASR Streaming, a much smaller model) returns text while I am still talking, and the app uses it only to type my words as I say them, at $0.198 per hour of audio. The whole design exists to keep the final text fast: audio streams to the server while I am still talking, so when I let go there is nothing left to upload.
This document is the full spec. Read all of it before you start. The "Morph realtime API" section is a complete reference for everything this app needs. Do not invent fields or events it doesn't describe; if something is unclear, read the docs linked there.
Codex built a macOS version of this app from this spec, and it's open source (MIT) at https://github.com/skeptrunedev/morph-dictation. When this spec leaves a macOS detail open, look at how that app handles it. Where the two disagree, follow this spec.
## How to work
1. Plan first. Before writing any code, show me the project layout, the modules and what each one owns, the state machine, the libraries you will use and why, and anything you need me to install or approve. Wait for my OK.
2. Build in this order, and get each step running before starting the next:
a. The API client, plus a command-line smoke test that streams a WAV file through the exact code path the app uses and prints the transcript and the latency.
b. Microphone capture streaming into that client.
c. The global hotkey.
d. Text insertion into the focused app: typing as I talk, the swap to the final text, and the paste.
e. The menu bar UI, the recording overlay, the setup window and the settings window.
f. Key storage, launch at login, history and polish.
3. Ask me before anything system-wide: installing system packages, changing group membership, adding login items or granting permissions.
4. When it all works, launch it, walk me through the setup window and every permission prompt, and do a first test dictation with me in its test box.
## Stack
Build it as a native Swift menu bar app (SwiftUI and AppKit, no Dock icon). The macOS section at the end has the APIs to use and the traps on this OS. Follow it.
## What the app does
### Setup window
- One window takes me from a fresh install to a working dictation, and shows at a glance whether the app works. It opens on every launch until my first successful dictation, and after that from the menu (Open Morph Dictation).
- Top to bottom: the API key (paste, Save, and the result of a live connection test), then each permission this OS needs, showing its live state, with a button that is disabled once that permission is granted.
- Once the key works and every permission is granted, the window says in large type "Press and hold Right Option to dictate", naming the hotkey actually set in Settings, plus "Double tap for hands-free" when that mode is on. Until then, the same line says what is missing ("Add your API key", or the permission still needed).
- Under that line, a multi-line text box to try it in. I click into it, hold the hotkey, talk and let go, and the text lands in the box through the same insertion path every other app gets. The text wraps to the box's visible width with a small margin on both sides and scrolls only vertically, so no line is ever cut off. My words appear in the box as I talk, exactly as they will in any other app. Under the box, show where that dictation is: Listening, Transcribing, then "Inserted in 212 ms", or the exact error.
- A connection line: Connected, Reconnecting, or the exact error.
### Hotkey
- Hold-to-talk on a global hotkey, Right Option by default and changeable in settings. Key down starts recording; key up ends the dictation.
- A single press shorter than 200 ms is an accident: discard it, send input_audio_buffer.clear, and insert nothing.
- Hands-free mode: a double tap (two taps within 300 ms) starts recording without holding the key, and the next tap stops it.
- Esc while recording cancels: stop capture, send input_audio_buffer.clear, insert nothing.
- Ignore key auto-repeat. Never swallow the hotkey or any other key; other apps must still see them.
- The hotkey works in every app, including full-screen ones.
### Recording overlay
- While recording, show a pill near the bottom center of the screen with a live input level meter. While transcribing, show a spinner. Hide the pill once the final text is in. The macOS section says how to build it on this OS.
- The pill never shows my words. They go into the input I am dictating into (see Typing as I talk), never into a preview at the bottom of the screen.
- The overlay must never take focus or receive clicks. If it steals focus, my words land in the overlay instead of my app.
### Typing as I talk
- With Type as I talk on, the words from the live session (see Live session below) are typed into whatever has focus as they arrive, at the cursor, as if I were typing them. The macOS section says how to type on this OS. Typing never touches the clipboard.
- When the final transcript arrives, it replaces the typed words in place. Keep the longest common start of what was typed and the final text, comparing whole characters, press Backspace once for each typed character after it, then type the rest of the final text, plus the trailing space when that setting is on. Ignore live words that arrive after the final transcript. The input ends up holding the final transcript exactly once: never the live words and the final text together.
- Esc and a short tap delete everything that dictation typed.
- Only ever delete what the dictation itself typed. Note the focused app and element when typing starts. If focus moves, or I press any key other than the hotkey while it is typing, stop typing for that dictation and leave that input alone. When its final transcript arrives, put it on the clipboard and show "Copied. Press Cmd+V to paste." instead of replacing anything.
- Dictations stay in order: a new dictation's words wait to be typed until every earlier dictation's final text is in.
- If nothing was typed (Type as I talk is off, the live session was refused or failed before its first word, or this OS can't type into the focused app), paste the final transcript as below.
### Pasting the final text
- When nothing was typed while I talked, paste the final transcript into whatever has focus when the text is ready: save the current clipboard (every format on it, not only text), put the transcript on it, send Cmd+V, wait about 1 second, then restore the saved clipboard. Slow apps read the clipboard late, and a shorter wait pastes my old clipboard instead of the dictation. If something else changed the clipboard during that wait, don't restore over it.
- Trim surrounding whitespace. A setting, on by default, adds one trailing space after each insertion so consecutive dictations don't run together.
- An empty transcript (I held the key and said nothing) inserts nothing and shows "No speech" for a moment.
- If the paste can't be delivered, leave the transcript on the clipboard and show "Copied. Press Cmd+V to paste."
- Never lose a transcript silently. If it can't be inserted, it goes to the clipboard and to History, with a notification.
### Menu bar menu
- The icon shows the state: idle, recording (animated), transcribing, waiting for a permission, copied to the clipboard, error or disconnected.
- Menu items: a status line that says "Hold Right Option to dictate" when everything works (or what is missing) and the last latency ("Last: 212 ms"), Open Morph Dictation, Recent dictations (the last 10; click one to copy it), Settings, Pause dictation / Resume dictation, and Quit.
### Settings
- Morph API key: stored in the macOS Keychain. Show only its last 4 characters once saved, with a Test button that connects and reports OK or the exact error.
- Hotkey and mode: hold-to-talk, hands-free double tap, or both.
- Language: Auto-detect, or one language from the list in the API section.
- Style: Clean (default) or Verbatim.
- Vocabulary: names and jargon I want spelled right, sent as keyterms (at most 100 terms).
- Type as I talk: on by default. Turning it off skips the live model entirely, along with its cost, and the final text is pasted when I let go.
- Microphone: the system default or a specific device.
- Sounds: subtle start and stop sounds, off by default.
- Trailing space on or off. History on or off, and Clear history. Launch at login.
- Settings persist in the platform's usual per-user location. Changing language, style or vocabulary sends a new session.update, which applies from the next dictation.
### History
- Keep the last 50 transcripts locally, with timestamps, for the Recent dictations menu. It has an off switch and a Clear button. Audio is never stored.
## Audio pipeline
- Start the microphone the instant the hotkey goes down and keep every sample from that moment on. The first syllable is the one most often lost. Don't keep the microphone open while idle, because that shows the system's microphone-in-use indicator all day.
- Convert to 16 kHz, mono, 16-bit signed little-endian PCM. Resample on the device with a proper resampler, never by dropping samples.
- Send a chunk every 100 ms (3,200 bytes at 16 kHz) while recording. Never hold audio back until key-up. Audio captured before the session is ready waits in memory and goes out the moment it is.
- On key-up, stop capture, send the last partial chunk, then commit.
- Compute the level meter from the same buffers (RMS, smoothed), so it costs nothing extra.
- When the input device changes mid-session (AirPods connect, a USB mic is unplugged), restart capture on the new device. If that happens mid-dictation, keep the audio captured so far.
- Keep each dictation's PCM in memory until its transcript arrives, so it can be sent again if the connection drops (see Reliability). Free it afterwards.
- If the computer goes to sleep while I'm recording, cancel that dictation (send input_audio_buffer.clear) and release the microphone.
## Morph realtime API
Morph's realtime API speaks OpenAI's realtime transcription protocol, with Morph's models. The app uses two sockets:
- The dictation socket, open all the time. It carries every dictation and returns the text to insert. Connect, Configure the session, One dictation and Reliability below are about this socket.
- A live socket for each dictation, open only while I am recording. Its words are the ones typed as I talk. See Live session below.
### Connect
wss://api.morphllm.com/v1/realtime?intent=transcription&model=morph-transcribe
Authorization: Bearer <API key>
- Keep model=morph-transcribe in the URL. A session that doesn't name a model starts on morph-transcribe-live (the streaming model for voice agents) with 24 kHz audio and server-side voice activity detection. The session.update below sets everything explicitly as well.
- Open the socket at launch and keep it open, so a dictation never waits on a TLS handshake. An open socket costs nothing; only audio in committed dictations is billed.
- If the server refuses the WebSocket upgrade, the HTTP response body is JSON: {"error": {"message": "...", "type": "...", "code": "...", "param": null}}.
- 401, authentication_error: stop retrying and ask me for a valid key.
- 402, quota_exceeded_error: stop retrying and tell me to check billing at https://www.morphllm.com/dashboard.
- 429, rate_limit_error: retry with backoff.
### Configure the session
The server's first message is session.created. Send this right away, and wait for the session.updated reply before the first append:
{"type": "session.update", "session": {"type": "transcription", "audio": {"input": {
"format": {"type": "audio/pcm", "rate": 16000},
"turn_detection": null,
"transcription": {"model": "morph-transcribe", "language": "en", "style": "clean", "keyterms": ["Morph"]}
}}}}
- turn_detection null means the client decides when a dictation ends: my key release. Without it, the server ends turns on its own at pauses.
- format: audio/pcm is 16-bit little-endian mono, at rate 16000 or 24000.
- language: leave it out to detect the language automatically. Supported codes: ar, bg, bn, cs, da, de, el, en, es, et, fi, fr, he, hi, hr, hu, id, it, ja, ko, lt, lv, mr, mt, nl, pl, pt, ro, ru, sk, sl, sv, ta, te, th, tl, tr, uk, vi, zh.
- style: "clean" drops fillers like "um" and repeated words and returns punctuated text. "verbatim", the server default, keeps everything.
- keyterms: up to 100 plain strings for names and jargon. Angle brackets and control characters are stripped. prompt is an optional free-text hint about what I dictate (for example "Software engineering notes."). keyterms and prompt together must stay under 2,000 characters.
- Send session.update again whenever I change these settings. A change applies to dictations that start after the server's session.updated reply; a dictation already in progress keeps the settings it started with.
- A bad value comes back as an error event whose param names the field, for example session.audio.input.transcription.keyterms.
### One dictation
The client sends:
- {"type": "input_audio_buffer.append", "audio": "<base64 PCM>"} every 100 ms while recording. The first append after a commit (or after connecting) starts a new dictation.
- {"type": "input_audio_buffer.commit"} on key-up.
- {"type": "input_audio_buffer.clear"} to cancel. A cleared dictation is never transcribed or billed. The server replies input_audio_buffer.cleared.
- Every client event is a JSON object sent as a text frame. Any client event may carry an "event_id"; an error it causes echoes that id back.
For each dictation, the server sends, in order:
- input_audio_buffer.committed with item_id and previous_item_id: the dictation is closed, and item_id names it from here on.
- conversation.item.input_audio_transcription.delta with item_id and delta: text as it is written. Don't type or paste these: the words typed while I talk come from the live session.
- conversation.item.input_audio_transcription.completed with item_id, transcript and usage: the final text. Insert this. usage reports the audio that dictation used; log it.
- Or, instead of completed, conversation.item.input_audio_transcription.failed with item_id and error {type, code, message}. Only that dictation failed; the socket stays usable.
The server can also send error with {type, code, message, param, event_id} when a client event is invalid. The socket stays open.
Rules:
- Never commit a dictation you sent no audio for. An empty commit returns an error with code input_audio_buffer_commit_empty. Taps under 200 ms send clear instead.
- Dictations can overlap. After a commit, the next dictation can start immediately, before the previous transcript arrives. committed events arrive in the order you committed, so pair each one with your oldest uncommitted dictation, then match delta, completed and failed by item_id. Insert transcripts in commit order, holding a later one back until the earlier one has been inserted or has failed.
- Long dictations: once a dictation passes about 45 seconds, the server cuts it at pauses and transcribes the pieces in parallel after key-up. Deltas then arrive one whole piece at a time, in order, and completed carries the joined text. The client doesn't change.
- A dictation holds at most 60 minutes of audio; past that it fails with code audio_too_long. Stop recording automatically at 59 minutes, commit, and tell me why.
- failed with type quota_exceeded_error: stop and tell me to check billing. With type server_error or rate_limit_error: retry once (see Reliability). Anything else: show the message.
### Reliability
- Keepalive: send a WebSocket ping every 20 seconds and treat the connection as dead if no pong arrives within 10 seconds. Proxies along the way can drop a connection that has been quiet for a while.
- Reconnect whenever the socket closes, with exponential backoff and jitter (0.5 s, doubling, capped at 10 s), and immediately when the network comes back, when traffic moves to a different network interface, or on wake from sleep. Other network notifications are noise: a socket whose pings are answered is healthy, so leave it alone. After reconnecting, send session.update again and wait for session.updated.
- A dictation that was in flight when the socket died (still recording, or committed with no completed yet) is sent again on the new socket from the PCM kept in memory: append all of it in 100 ms chunks, then commit once the recording has ended. The same goes for failed with type server_error or rate_limit_error, after waiting 1 second. Retry at most once per dictation.
- If I press the hotkey while disconnected, record anyway. The audio waits in memory and goes out as soon as the session is ready.
### Live session
A second session, on morph-transcribe-live, returns my words while I talk, and the app types them (see Typing as I talk). Skip all of this when Type as I talk is off.
- Open it at hotkey down, on the same URL with model=morph-transcribe-live instead of model=morph-transcribe, and close it when the dictation ends. Never keep it open between dictations: an open live session holds a slot on Morph's live workers.
- After session.created, send this and wait for session.updated before the first append:
{"type": "session.update", "session": {"type": "transcription", "audio": {"input": {
"format": {"type": "audio/pcm", "rate": 16000},
"turn_detection": null,
"transcription": {"model": "morph-transcribe-live", "language": "en", "chunk_ms": 320}
}}}}
- language: the dictation's language if it is one of ar, bg, cs, da, de, en, es, et, fi, fr, hi, hr, hu, it, ja, ko, nl, pl, pt, ro, ru, sk, sv, tr, uk, vi, zh. For any other language, or Auto, leave it out and the live model detects it. The live model takes no style, keyterms or prompt; sending any of them is an error.
- chunk_ms is how much audio the model reads per step: 80, 160, 320, 560 or 1120. 320 types new words about three times a second.
- Send it the same 100 ms chunks as the dictation socket, starting with the audio captured before it was ready.
- conversation.item.input_audio_transcription.delta events carry new text. Deltas only ever append, so type each one as it arrives: the deltas joined in order are exactly what was typed.
- At key-up, send input_audio_buffer.commit, then close the socket when its completed arrives or after 1 second, whichever comes first. On Esc or a short tap, send input_audio_buffer.clear and close it.
- The live session must never slow down or block a dictation. If its connection is refused (429 when live capacity is full) or anything on it fails, stop typing, keep what was typed, and carry on: the final text still replaces it as usual. Don't retry it within that dictation.
### Billing
- Dictation socket: only audio in committed dictations is billed, at $0.18 per hour of audio. An idle open socket is free, and so is a cleared dictation.
- Live session: every second of audio appended to a live session is billed, at $0.198 per hour of audio, as one usage row when the session closes.
- With Type as I talk on, an hour of dictation costs about $0.38.
### Docs
- https://docs.morphllm.com/models/speech-to-text
- https://docs.morphllm.com/api-reference/endpoint/realtime-transcription
### API key
My Morph API key is YOUR_API_KEY (keys live at https://www.morphllm.com/dashboard/api-keys). Before the first launch, put it into the macOS Keychain for me through the app's own code, for example a hidden --store-key-stdin mode that reads the key from stdin and exits, so the app works the first time I open it and I never paste the key myself. Never pass the key as a command-line argument, and never put it in source code, a config file, a log or git.
## State machine
Write the states down in code as one explicit enum with its transitions. Don't scatter booleans.
- Idle -> Recording: hotkey down, or a double tap in hands-free mode.
- Recording -> Idle: released within 200 ms, or Esc (send clear).
- Recording -> Transcribing: released (commit).
- Transcribing -> Inserting: completed arrives for the oldest pending dictation.
- Inserting -> Idle: the final text has replaced the typed words, or was pasted and the clipboard restored.
- Any state -> Error: show the message in the menu and in the overlay for 3 seconds, then return to Idle. Dictation keeps working after an error.
- Starting a new recording while an earlier dictation is still transcribing is allowed (see "Dictations can overlap").
## Latency
Measure these for every dictation and write them to the debug log:
- Hotkey down -> first chunk sent. Target under 150 ms; it is mostly microphone start-up.
- Hotkey down -> first word typed. It includes the live socket's connection, so log it rather than chasing a target.
- Hotkey up -> commit sent. Target under 20 ms.
- Commit -> completed. This is the server: about 195 ms median on a 10 second dictation.
- Completed -> text visible in the app. Target under 50 ms.
The menu's "Last" figure is hotkey up -> text inserted. If a stage is slow, fix that stage. Don't add delays anywhere except the clipboard-restore wait.
## Privacy and logging
- Audio never touches disk. Transcripts are stored only in History, and only while History is on.
- Logs go to the platform's usual log location, rotate at 5 MB, and record timings, event types, item_ids and error codes. They never contain the API key, and never contain transcript text unless I turn on a debug switch.
- No analytics, no crash reporters, and no network calls other than the Morph sockets.
## Checks
Don't write unit tests. I want only these two checks, because they run the real thing:
- The smoke test from step 2a streams a generated speech WAV through the real client against the real API (the macOS section says how to make one), on both sockets, then prints the live words as they arrive, the final transcript, the replacement it would make (characters kept, deleted and typed), and the commit -> completed latency. Run it before wiring up the microphone. Don't mock the server in it.
- A launch check, from step 2e on: after every build, start the packaged app the way I will (the installed app, not a binary in the build folder) and confirm it is still running 10 seconds later. The smoke test runs outside the packaged app, so it misses crashes that only happen inside it, like lookups that depend on the app's identifier or bundled resources.
## Acceptance checklist
Run through this with me at the end and tell me which items pass:
1. After setup, the setup window says "Press and hold Right Option to dictate", and a dictation into its test box lands there with its latency.
2. Hold Right Option, say "testing one two three" and release in a text editor: my words appear in the editor as I say them, the final text replaces them within about half a second of letting go, and the editor ends up with the sentence exactly once.
3. Turn Type as I talk off and dictate: nothing is typed while I talk, the text is pasted when I let go, and no live socket opens.
4. Tap Right Option quickly: nothing is inserted and no error shows.
5. Start dictating, then press Esc: the words typed so far are deleted, and nothing else is inserted.
6. Click into a different window halfway through a dictation: nothing is deleted in either window, and the final text is on the clipboard with a notice.
7. Copy a word, dictate a sentence with Type as I talk on, then paste manually: the word I copied comes back.
8. Copy a word, dictate a sentence, then paste manually: the word I copied comes back.
9. Dictate twice in quick succession: both transcripts appear, in order.
10. Turn Wi-Fi off, dictate, turn Wi-Fi back on: the dictation is transcribed and inserted after the reconnect.
11. Dictate for 60 seconds straight: one complete transcript.
12. Set language to Auto and dictate in a second language, if I speak one: the text is in that language.
13. Add a made-up name to Vocabulary and dictate it: it comes out spelled the way I wrote it (if not, show me what came back).
14. Quit and relaunch: settings and the key are kept, and the key is in no plain file.
15. Dictate into a full-screen app and on a second Space: both work.
16. Hold Right Option and dictate into Terminal and a browser text field: the words come out as plain text, with no Option characters and no shortcuts firing.
17. Rebuild and relaunch the app: it is either still allowed, or it clears the old Accessibility entry and asks again, and one switch in System Settings gets it working.
18. Connect AirPods (or another mic) while the app runs: the next dictation uses the new default input.
## Deliverables
- The source in a new git repository, with a README covering build, run, permissions, where settings and logs live, and troubleshooting for every error message the app can show.
- One command to build and run.
- The smoke test command.
- An uninstall command that quits the app and removes it, its settings, history, logs and stored API key, and resets its permissions (on macOS, tccutil reset All <bundle id>).
- A short list of anything you couldn't make work, and why.
## macOS
Target macOS 13 Ventura or newer, Swift 5.9 or newer, with SwiftUI for the setup and settings windows and AppKit for the menu bar item and the overlay.
Project setup
- Full Xcode is optional, and I don't want to install it just for this. Check xcode-select -p. If only the Command Line Tools are installed, build with Swift Package Manager plus a script that assembles the .app bundle (Contents/MacOS, Contents/Resources, Contents/Info.plist) and signs it with codesign. If full Xcode is installed, an Xcode project is fine too.
- Build a real .app bundle. Its Info.plist needs LSUIElement = YES (no Dock icon) and NSMicrophoneUsageDescription. Without the usage string the app crashes the first time it touches the microphone.
- Sign it with a stable identity, such as my Apple Development certificate if I have one. macOS ties the Accessibility grant to the code signature, so an ad-hoc signed rebuild can silently lose the permission. If we have to ad-hoc sign, the app handles that itself: it saves a build identifier (a build number or its code directory hash) at each launch, and when that changed since the last launch and AXIsProcessTrusted() is false, it runs tccutil reset Accessibility <bundle id> and asks again. Otherwise the old entry stays switched on in System Settings while the new build is refused.
- Install the built app to /Applications (or ~/Applications) and always run it from there, so permission grants stick to one path.
- Leave no other copy of the bundle on disk after installing: move it into place, or delete the build copy. macOS finds apps by bundle identifier, and a permission I grant can attach to a stale copy in the build folder, so the installed app never sees it.
- Only one instance may run. If the app is launched while it is already running, the new instance exits and the running one shows its setup window.
- Build and run from the command line, and give me the exact commands.
Hotkey
- Watch flagsChanged, plus keyDown for Esc while recording, with NSEvent.addGlobalMonitorForEvents and the same mask with NSEvent.addLocalMonitorForEvents. A global monitor never sees events sent to this app's own windows, so without the local one the hotkey does nothing in the setup window's test box. Both need only Accessibility. Monitors observe and can't swallow keys, which is what we want.
- Right Option is key code 61 and Left Option is 58. The hotkey is down when a flagsChanged event for key code 61 has the Option flag set, and up when one arrives without it.
- Caps Lock can't be the hotkey: macOS toggles it and never sends a release. Refuse it in Settings.
- Offer Fn (the globe key, key code 63) as an alternative hotkey. If I pick it, tell me to set System Settings > Keyboard > "Press globe key to" to "Do nothing" so macOS stops opening the emoji picker.
- Password fields turn on Secure Input, which hides keystrokes from monitors. Check IsSecureEventInputEnabled() and show "Hotkey paused: a password field is active" in the menu while it is on.
Permissions
- Accessibility is needed to see the hotkey in other apps and to post Cmd+V. The setup window explains why. Its Accessibility button calls AXIsProcessTrustedWithOptions with the prompt option and opens the pane directly (x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility).
- Microphone: AVCaptureDevice.requestAccess(for: .audio), from the setup window's Microphone button.
- Poll AXIsProcessTrusted() every half second and start working as soon as the grant lands. No relaunch is needed, so don't offer one.
Audio
- Use AVAudioEngine. Install the tap on inputNode bus 0 using the node's own input format; asking the tap for a different sample rate raises an exception. Convert each buffer with AVAudioConverter to 16 kHz mono Int16 interleaved, then cut it into 3,200-byte chunks.
- Start the engine on hotkey down and stop it on release, so the orange microphone indicator shows only while I dictate. After each dictation, release the input completely: even a prepared, idle input unit can hold Bluetooth headphones such as AirPods in their low-quality headset mode.
- Don't enable voice processing (setVoiceProcessingEnabled). It slows the start and turns down other audio while I talk.
- Log the time from key down to the first captured buffer on every dictation. If it is often over 150 ms (Bluetooth headsets are the usual cause), tell me and add a "Keep microphone ready" setting, off by default, whose description says it keeps AirPods in headset mode.
- Observe AVAudioEngineConfigurationChange and rebuild the tap and converter when the device or its format changes. The notification also fires for changes the app causes itself, such as starting or stopping the engine, so compare the input device and format with the current ones and rebuild only when one of them actually changed.
- Microphone list: enumerate Core Audio devices that have input streams (kAudioHardwarePropertyDevices, then kAudioDevicePropertyStreams on the input scope) and set the chosen one on the input node's audio unit with kAudioOutputUnitProperty_CurrentDevice. Save the device's UID (kAudioDevicePropertyDeviceUID), never its AudioDeviceID, which changes across reboots and replugs.
Text insertion
- NSPasteboard.general: snapshot every pasteboard item with all of its types and data, write the transcript as a string, note the changeCount, post Cmd+V, wait 1 second, then restore the snapshot only if changeCount is still the one your write produced.
- Cmd+V is a CGEvent with the Command flag from a CGEventSource(stateID: .hidSystemState), posted to the HID event tap. Get the V key's code from the current keyboard layout (UCKeyTranslate on TISCopyCurrentKeyboardLayoutInputSource) instead of hard-coding 9, so Dvorak and other layouts paste too.
- Typing as I talk: post keyboard CGEvents that carry the text with CGEventKeyboardSetUnicodeString, a key-down and a key-up for each piece, with at most 20 UTF-16 units per event and never splitting a character. Typing never touches the pasteboard.
- Set every posted event's flags to none. Right Option is held the whole time I talk, and an event that picks up that flag types Option characters (å, ∂, ß) or fires shortcuts instead of my words. Backspace is key code 51 (kVK_Delete), with no flags either.
- Tag every event the app posts by setting kCGEventSourceUserData to a fixed value, and have both hotkey monitors ignore tagged events, so the app never takes its own typing for me pressing a key.
- For the focus guard in Typing as I talk, the focused app is the frontmost application's process id and the focused element is kAXFocusedUIElementAttribute, compared with CFEqual.
- Before pasting, ask the Accessibility API what has focus (kAXFocusedUIElementAttribute, then its role and kAXIsEditableAttribute). If it is clearly not a text control (a button, checkbox, radio button or menu item), skip the paste and leave the transcript on the clipboard with "Copied". Treat a failed query or a container role such as AXWindow as unknown and paste anyway: Electron apps, Firefox and terminals report those while a text field has focus.
Overlay
- An NSPanel with the nonactivatingPanel style, level statusBar, ignoresMouseEvents = true, collectionBehavior canJoinAllSpaces plus fullScreenAuxiliary, and canBecomeKey and canBecomeMain returning false. Show it on the screen under the mouse pointer.
Networking
- URLSessionWebSocketTask built from a URLRequest that carries the Authorization header. Receive in a loop, sendPing every 20 seconds, and reconnect on NSWorkspace.didWakeNotification.
- Watch the network with NWPathMonitor, but reconnect only when the path goes from unsatisfied to satisfied or the interface it uses changes. It reports many other updates (VPNs such as Tailscale trigger them constantly), and a socket whose pings are answered is healthy, so leave it alone.
Storage
- API key: a Keychain generic password (SecItemAdd, SecItemCopyMatching, SecItemUpdate) with the service set to the app's bundle id.
- Never call the Keychain on the main thread. After every ad-hoc rebuild, macOS asks me whether the new build may read the item, and the call blocks until I answer; on the main thread that freezes the whole app, menu and Quit included. While such a prompt is up, the setup window says "Waiting for Keychain access".
- Settings in UserDefaults.standard. Never UserDefaults(suiteName:) with the app's own bundle id: inside the packaged app it returns nil, and force-unwrapping it crashes at launch, while the smoke test, which runs outside the bundle, still passes. History as a JSON file in Application Support. Logs through os.Logger with a subsystem, plus a rotating file in ~/Library/Logs/<app name>.
- Launch at login with SMAppService.mainApp.
Test speech for the smoke test: say --file-format=WAVE --data-format=LEI16@16000 -o /tmp/dictation-test.wav "Testing one two three. This is a dictation test."
Windows build prompt
# Build me a dictation app for Windows
I want my own version of Wispr Flow: I hold a hotkey, talk, let go, and the text appears wherever my cursor is, in any app. While I talk, my words appear right there in the input as I say them, and when I let go the final text replaces them in place.
It runs on Morph's speech-to-text API with two models. morph-transcribe (NVIDIA Nemotron 3.5 Transcribe) in dictation mode writes the text that gets inserted: measured from the moment I stop talking, it returns the final text in about 195 ms (the median on a 10.5 second clip), at $0.18 per hour of audio. morph-transcribe-live (NVIDIA Nemotron 3.5 ASR Streaming, a much smaller model) returns text while I am still talking, and the app uses it only to type my words as I say them, at $0.198 per hour of audio. The whole design exists to keep the final text fast: audio streams to the server while I am still talking, so when I let go there is nothing left to upload.
This document is the full spec. Read all of it before you start. The "Morph realtime API" section is a complete reference for everything this app needs. Do not invent fields or events it doesn't describe; if something is unclear, read the docs linked there.
Codex built a macOS version of this app from this spec, and it's open source (MIT) at https://github.com/skeptrunedev/morph-dictation. Its Sources/DictationCore folder has the realtime clients, the dictation state machine and the live-text swap, which carry over to Windows. Read it to check your logic, not to port Swift line by line.
## How to work
1. Plan first. Before writing any code, show me the project layout, the modules and what each one owns, the state machine, the libraries you will use and why, and anything you need me to install or approve. Wait for my OK.
2. Build in this order, and get each step running before starting the next:
a. The API client, plus a command-line smoke test that streams a WAV file through the exact code path the app uses and prints the transcript and the latency.
b. Microphone capture streaming into that client.
c. The global hotkey.
d. Text insertion into the focused app: typing as I talk, the swap to the final text, and the paste.
e. The tray UI, the recording overlay, the setup window and the settings window.
f. Key storage, launch at login, history and polish.
3. Ask me before anything system-wide: installing system packages, changing group membership, adding login items or granting permissions.
4. When it all works, launch it, walk me through the setup window and every permission prompt, and do a first test dictation with me in its test box.
## Stack
Build it as a C# .NET 8 system tray app (WinForms). The Windows section at the end has the APIs to use and the traps on this OS. Follow it.
## What the app does
### Setup window
- One window takes me from a fresh install to a working dictation, and shows at a glance whether the app works. It opens on every launch until my first successful dictation, and after that from the menu (Open Morph Dictation).
- Top to bottom: the API key (paste, Save, and the result of a live connection test), then each permission this OS needs, showing its live state, with a button that is disabled once that permission is granted.
- Once the key works and every permission is granted, the window says in large type "Press and hold Right Ctrl to dictate", naming the hotkey actually set in Settings, plus "Double tap for hands-free" when that mode is on. Until then, the same line says what is missing ("Add your API key", or the permission still needed).
- Under that line, a multi-line text box to try it in. I click into it, hold the hotkey, talk and let go, and the text lands in the box through the same insertion path every other app gets. The text wraps to the box's visible width with a small margin on both sides and scrolls only vertically, so no line is ever cut off. My words appear in the box as I talk, exactly as they will in any other app. Under the box, show where that dictation is: Listening, Transcribing, then "Inserted in 212 ms", or the exact error.
- A connection line: Connected, Reconnecting, or the exact error.
### Hotkey
- Hold-to-talk on a global hotkey, Right Ctrl by default and changeable in settings. Key down starts recording; key up ends the dictation.
- A single press shorter than 200 ms is an accident: discard it, send input_audio_buffer.clear, and insert nothing.
- Hands-free mode: a double tap (two taps within 300 ms) starts recording without holding the key, and the next tap stops it.
- Esc while recording cancels: stop capture, send input_audio_buffer.clear, insert nothing.
- Ignore key auto-repeat. Never swallow the hotkey or any other key; other apps must still see them.
- The hotkey works in every app, including full-screen ones.
### Recording overlay
- While recording, show a pill near the bottom center of the screen with a live input level meter. While transcribing, show a spinner. Hide the pill once the final text is in. The Windows section says how to build it on this OS.
- The pill never shows my words. They go into the input I am dictating into (see Typing as I talk), never into a preview at the bottom of the screen.
- The overlay must never take focus or receive clicks. If it steals focus, my words land in the overlay instead of my app.
### Typing as I talk
- With Type as I talk on, the words from the live session (see Live session below) are typed into whatever has focus as they arrive, at the cursor, as if I were typing them. The Windows section says how to type on this OS. Typing never touches the clipboard.
- When the final transcript arrives, it replaces the typed words in place. Keep the longest common start of what was typed and the final text, comparing whole characters, press Backspace once for each typed character after it, then type the rest of the final text, plus the trailing space when that setting is on. Ignore live words that arrive after the final transcript. The input ends up holding the final transcript exactly once: never the live words and the final text together.
- Esc and a short tap delete everything that dictation typed.
- Only ever delete what the dictation itself typed. Note the focused app and element when typing starts. If focus moves, or I press any key other than the hotkey while it is typing, stop typing for that dictation and leave that input alone. When its final transcript arrives, put it on the clipboard and show "Copied. Press Ctrl+V to paste." instead of replacing anything.
- Dictations stay in order: a new dictation's words wait to be typed until every earlier dictation's final text is in.
- If nothing was typed (Type as I talk is off, the live session was refused or failed before its first word, or this OS can't type into the focused app), paste the final transcript as below.
### Pasting the final text
- When nothing was typed while I talked, paste the final transcript into whatever has focus when the text is ready: save the current clipboard (every format on it, not only text), put the transcript on it, send Ctrl+V, wait about 1 second, then restore the saved clipboard. Slow apps read the clipboard late, and a shorter wait pastes my old clipboard instead of the dictation. If something else changed the clipboard during that wait, don't restore over it.
- Trim surrounding whitespace. A setting, on by default, adds one trailing space after each insertion so consecutive dictations don't run together.
- An empty transcript (I held the key and said nothing) inserts nothing and shows "No speech" for a moment.
- If the paste can't be delivered, leave the transcript on the clipboard and show "Copied. Press Ctrl+V to paste."
- Never lose a transcript silently. If it can't be inserted, it goes to the clipboard and to History, with a notification.
### Tray menu
- The icon shows the state: idle, recording (animated), transcribing, waiting for a permission, copied to the clipboard, error or disconnected.
- Menu items: a status line that says "Hold Right Ctrl to dictate" when everything works (or what is missing) and the last latency ("Last: 212 ms"), Open Morph Dictation, Recent dictations (the last 10; click one to copy it), Settings, Pause dictation / Resume dictation, and Quit.
### Settings
- Morph API key: stored in Windows Credential Manager. Show only its last 4 characters once saved, with a Test button that connects and reports OK or the exact error.
- Hotkey and mode: hold-to-talk, hands-free double tap, or both.
- Language: Auto-detect, or one language from the list in the API section.
- Style: Clean (default) or Verbatim.
- Vocabulary: names and jargon I want spelled right, sent as keyterms (at most 100 terms).
- Type as I talk: on by default. Turning it off skips the live model entirely, along with its cost, and the final text is pasted when I let go.
- Microphone: the system default or a specific device.
- Sounds: subtle start and stop sounds, off by default.
- Trailing space on or off. History on or off, and Clear history. Launch at login.
- Settings persist in the platform's usual per-user location. Changing language, style or vocabulary sends a new session.update, which applies from the next dictation.
### History
- Keep the last 50 transcripts locally, with timestamps, for the Recent dictations menu. It has an off switch and a Clear button. Audio is never stored.
## Audio pipeline
- Start the microphone the instant the hotkey goes down and keep every sample from that moment on. The first syllable is the one most often lost. Don't keep the microphone open while idle, because that shows the system's microphone-in-use indicator all day.
- Convert to 16 kHz, mono, 16-bit signed little-endian PCM. Resample on the device with a proper resampler, never by dropping samples.
- Send a chunk every 100 ms (3,200 bytes at 16 kHz) while recording. Never hold audio back until key-up. Audio captured before the session is ready waits in memory and goes out the moment it is.
- On key-up, stop capture, send the last partial chunk, then commit.
- Compute the level meter from the same buffers (RMS, smoothed), so it costs nothing extra.
- When the input device changes mid-session (AirPods connect, a USB mic is unplugged), restart capture on the new device. If that happens mid-dictation, keep the audio captured so far.
- Keep each dictation's PCM in memory until its transcript arrives, so it can be sent again if the connection drops (see Reliability). Free it afterwards.
- If the computer goes to sleep while I'm recording, cancel that dictation (send input_audio_buffer.clear) and release the microphone.
## Morph realtime API
Morph's realtime API speaks OpenAI's realtime transcription protocol, with Morph's models. The app uses two sockets:
- The dictation socket, open all the time. It carries every dictation and returns the text to insert. Connect, Configure the session, One dictation and Reliability below are about this socket.
- A live socket for each dictation, open only while I am recording. Its words are the ones typed as I talk. See Live session below.
### Connect
wss://api.morphllm.com/v1/realtime?intent=transcription&model=morph-transcribe
Authorization: Bearer <API key>
- Keep model=morph-transcribe in the URL. A session that doesn't name a model starts on morph-transcribe-live (the streaming model for voice agents) with 24 kHz audio and server-side voice activity detection. The session.update below sets everything explicitly as well.
- Open the socket at launch and keep it open, so a dictation never waits on a TLS handshake. An open socket costs nothing; only audio in committed dictations is billed.
- If the server refuses the WebSocket upgrade, the HTTP response body is JSON: {"error": {"message": "...", "type": "...", "code": "...", "param": null}}.
- 401, authentication_error: stop retrying and ask me for a valid key.
- 402, quota_exceeded_error: stop retrying and tell me to check billing at https://www.morphllm.com/dashboard.
- 429, rate_limit_error: retry with backoff.
### Configure the session
The server's first message is session.created. Send this right away, and wait for the session.updated reply before the first append:
{"type": "session.update", "session": {"type": "transcription", "audio": {"input": {
"format": {"type": "audio/pcm", "rate": 16000},
"turn_detection": null,
"transcription": {"model": "morph-transcribe", "language": "en", "style": "clean", "keyterms": ["Morph"]}
}}}}
- turn_detection null means the client decides when a dictation ends: my key release. Without it, the server ends turns on its own at pauses.
- format: audio/pcm is 16-bit little-endian mono, at rate 16000 or 24000.
- language: leave it out to detect the language automatically. Supported codes: ar, bg, bn, cs, da, de, el, en, es, et, fi, fr, he, hi, hr, hu, id, it, ja, ko, lt, lv, mr, mt, nl, pl, pt, ro, ru, sk, sl, sv, ta, te, th, tl, tr, uk, vi, zh.
- style: "clean" drops fillers like "um" and repeated words and returns punctuated text. "verbatim", the server default, keeps everything.
- keyterms: up to 100 plain strings for names and jargon. Angle brackets and control characters are stripped. prompt is an optional free-text hint about what I dictate (for example "Software engineering notes."). keyterms and prompt together must stay under 2,000 characters.
- Send session.update again whenever I change these settings. A change applies to dictations that start after the server's session.updated reply; a dictation already in progress keeps the settings it started with.
- A bad value comes back as an error event whose param names the field, for example session.audio.input.transcription.keyterms.
### One dictation
The client sends:
- {"type": "input_audio_buffer.append", "audio": "<base64 PCM>"} every 100 ms while recording. The first append after a commit (or after connecting) starts a new dictation.
- {"type": "input_audio_buffer.commit"} on key-up.
- {"type": "input_audio_buffer.clear"} to cancel. A cleared dictation is never transcribed or billed. The server replies input_audio_buffer.cleared.
- Every client event is a JSON object sent as a text frame. Any client event may carry an "event_id"; an error it causes echoes that id back.
For each dictation, the server sends, in order:
- input_audio_buffer.committed with item_id and previous_item_id: the dictation is closed, and item_id names it from here on.
- conversation.item.input_audio_transcription.delta with item_id and delta: text as it is written. Don't type or paste these: the words typed while I talk come from the live session.
- conversation.item.input_audio_transcription.completed with item_id, transcript and usage: the final text. Insert this. usage reports the audio that dictation used; log it.
- Or, instead of completed, conversation.item.input_audio_transcription.failed with item_id and error {type, code, message}. Only that dictation failed; the socket stays usable.
The server can also send error with {type, code, message, param, event_id} when a client event is invalid. The socket stays open.
Rules:
- Never commit a dictation you sent no audio for. An empty commit returns an error with code input_audio_buffer_commit_empty. Taps under 200 ms send clear instead.
- Dictations can overlap. After a commit, the next dictation can start immediately, before the previous transcript arrives. committed events arrive in the order you committed, so pair each one with your oldest uncommitted dictation, then match delta, completed and failed by item_id. Insert transcripts in commit order, holding a later one back until the earlier one has been inserted or has failed.
- Long dictations: once a dictation passes about 45 seconds, the server cuts it at pauses and transcribes the pieces in parallel after key-up. Deltas then arrive one whole piece at a time, in order, and completed carries the joined text. The client doesn't change.
- A dictation holds at most 60 minutes of audio; past that it fails with code audio_too_long. Stop recording automatically at 59 minutes, commit, and tell me why.
- failed with type quota_exceeded_error: stop and tell me to check billing. With type server_error or rate_limit_error: retry once (see Reliability). Anything else: show the message.
### Reliability
- Keepalive: send a WebSocket ping every 20 seconds and treat the connection as dead if no pong arrives within 10 seconds. Proxies along the way can drop a connection that has been quiet for a while.
- Reconnect whenever the socket closes, with exponential backoff and jitter (0.5 s, doubling, capped at 10 s), and immediately when the network comes back, when traffic moves to a different network interface, or on wake from sleep. Other network notifications are noise: a socket whose pings are answered is healthy, so leave it alone. After reconnecting, send session.update again and wait for session.updated.
- A dictation that was in flight when the socket died (still recording, or committed with no completed yet) is sent again on the new socket from the PCM kept in memory: append all of it in 100 ms chunks, then commit once the recording has ended. The same goes for failed with type server_error or rate_limit_error, after waiting 1 second. Retry at most once per dictation.
- If I press the hotkey while disconnected, record anyway. The audio waits in memory and goes out as soon as the session is ready.
### Live session
A second session, on morph-transcribe-live, returns my words while I talk, and the app types them (see Typing as I talk). Skip all of this when Type as I talk is off.
- Open it at hotkey down, on the same URL with model=morph-transcribe-live instead of model=morph-transcribe, and close it when the dictation ends. Never keep it open between dictations: an open live session holds a slot on Morph's live workers.
- After session.created, send this and wait for session.updated before the first append:
{"type": "session.update", "session": {"type": "transcription", "audio": {"input": {
"format": {"type": "audio/pcm", "rate": 16000},
"turn_detection": null,
"transcription": {"model": "morph-transcribe-live", "language": "en", "chunk_ms": 320}
}}}}
- language: the dictation's language if it is one of ar, bg, cs, da, de, en, es, et, fi, fr, hi, hr, hu, it, ja, ko, nl, pl, pt, ro, ru, sk, sv, tr, uk, vi, zh. For any other language, or Auto, leave it out and the live model detects it. The live model takes no style, keyterms or prompt; sending any of them is an error.
- chunk_ms is how much audio the model reads per step: 80, 160, 320, 560 or 1120. 320 types new words about three times a second.
- Send it the same 100 ms chunks as the dictation socket, starting with the audio captured before it was ready.
- conversation.item.input_audio_transcription.delta events carry new text. Deltas only ever append, so type each one as it arrives: the deltas joined in order are exactly what was typed.
- At key-up, send input_audio_buffer.commit, then close the socket when its completed arrives or after 1 second, whichever comes first. On Esc or a short tap, send input_audio_buffer.clear and close it.
- The live session must never slow down or block a dictation. If its connection is refused (429 when live capacity is full) or anything on it fails, stop typing, keep what was typed, and carry on: the final text still replaces it as usual. Don't retry it within that dictation.
### Billing
- Dictation socket: only audio in committed dictations is billed, at $0.18 per hour of audio. An idle open socket is free, and so is a cleared dictation.
- Live session: every second of audio appended to a live session is billed, at $0.198 per hour of audio, as one usage row when the session closes.
- With Type as I talk on, an hour of dictation costs about $0.38.
### Docs
- https://docs.morphllm.com/models/speech-to-text
- https://docs.morphllm.com/api-reference/endpoint/realtime-transcription
### API key
My Morph API key is YOUR_API_KEY (keys live at https://www.morphllm.com/dashboard/api-keys). Before the first launch, put it into Windows Credential Manager for me through the app's own code, for example a hidden --store-key-stdin mode that reads the key from stdin and exits, so the app works the first time I open it and I never paste the key myself. Never pass the key as a command-line argument, and never put it in source code, a config file, a log or git.
## State machine
Write the states down in code as one explicit enum with its transitions. Don't scatter booleans.
- Idle -> Recording: hotkey down, or a double tap in hands-free mode.
- Recording -> Idle: released within 200 ms, or Esc (send clear).
- Recording -> Transcribing: released (commit).
- Transcribing -> Inserting: completed arrives for the oldest pending dictation.
- Inserting -> Idle: the final text has replaced the typed words, or was pasted and the clipboard restored.
- Any state -> Error: show the message in the menu and in the overlay for 3 seconds, then return to Idle. Dictation keeps working after an error.
- Starting a new recording while an earlier dictation is still transcribing is allowed (see "Dictations can overlap").
## Latency
Measure these for every dictation and write them to the debug log:
- Hotkey down -> first chunk sent. Target under 150 ms; it is mostly microphone start-up.
- Hotkey down -> first word typed. It includes the live socket's connection, so log it rather than chasing a target.
- Hotkey up -> commit sent. Target under 20 ms.
- Commit -> completed. This is the server: about 195 ms median on a 10 second dictation.
- Completed -> text visible in the app. Target under 50 ms.
The menu's "Last" figure is hotkey up -> text inserted. If a stage is slow, fix that stage. Don't add delays anywhere except the clipboard-restore wait.
## Privacy and logging
- Audio never touches disk. Transcripts are stored only in History, and only while History is on.
- Logs go to the platform's usual log location, rotate at 5 MB, and record timings, event types, item_ids and error codes. They never contain the API key, and never contain transcript text unless I turn on a debug switch.
- No analytics, no crash reporters, and no network calls other than the Morph sockets.
## Checks
Don't write unit tests. I want only these two checks, because they run the real thing:
- The smoke test from step 2a streams a generated speech WAV through the real client against the real API (the Windows section says how to make one), on both sockets, then prints the live words as they arrive, the final transcript, the replacement it would make (characters kept, deleted and typed), and the commit -> completed latency. Run it before wiring up the microphone. Don't mock the server in it.
- A launch check, from step 2e on: after every build, start the packaged app the way I will (the installed app, not a binary in the build folder) and confirm it is still running 10 seconds later. The smoke test runs outside the packaged app, so it misses crashes that only happen inside it, like lookups that depend on the app's identifier or bundled resources.
## Acceptance checklist
Run through this with me at the end and tell me which items pass:
1. After setup, the setup window says "Press and hold Right Ctrl to dictate", and a dictation into its test box lands there with its latency.
2. Hold Right Ctrl, say "testing one two three" and release in a text editor: my words appear in the editor as I say them, the final text replaces them within about half a second of letting go, and the editor ends up with the sentence exactly once.
3. Turn Type as I talk off and dictate: nothing is typed while I talk, the text is pasted when I let go, and no live socket opens.
4. Tap Right Ctrl quickly: nothing is inserted and no error shows.
5. Start dictating, then press Esc: the words typed so far are deleted, and nothing else is inserted.
6. Click into a different window halfway through a dictation: nothing is deleted in either window, and the final text is on the clipboard with a notice.
7. Copy a word, dictate a sentence with Type as I talk on, then paste manually: the word I copied comes back.
8. Copy a word, dictate a sentence, then paste manually: the word I copied comes back.
9. Dictate twice in quick succession: both transcripts appear, in order.
10. Turn Wi-Fi off, dictate, turn Wi-Fi back on: the dictation is transcribed and inserted after the reconnect.
11. Dictate for 60 seconds straight: one complete transcript.
12. Set language to Auto and dictate in a second language, if I speak one: the text is in that language.
13. Add a made-up name to Vocabulary and dictate it: it comes out spelled the way I wrote it (if not, show me what came back).
14. Quit and relaunch: settings and the key are kept, and the key is in no plain file.
15. Dictate into an app running as administrator: it pastes, or falls back to the clipboard with a notice.
16. Sleep and wake the PC, then dictate: it works without restarting the app.
17. Plug in a USB headset while the app runs: the next dictation uses it if it became the default.
## Deliverables
- The source in a new git repository, with a README covering build, run, permissions, where settings and logs live, and troubleshooting for every error message the app can show.
- One command to build and run.
- The smoke test command.
- An uninstall command that quits the app and removes it, its settings, history, logs and stored API key, and resets its permissions (on macOS, tccutil reset All <bundle id>).
- A short list of anything you couldn't make work, and why.
## Windows
Target Windows 10 and 11, .NET 8, C#. Make it a WinForms app (TargetFramework net8.0-windows) run by an ApplicationContext that owns a NotifyIcon, with no window at startup other than the setup window. Allow a single instance only, using a named mutex.
Hotkey
- Install a low-level keyboard hook (SetWindowsHookEx with WH_KEYBOARD_LL) on a thread that runs a message loop. RegisterHotKey cannot do hold-to-talk on a lone modifier, which is why the hook is needed.
- Right Ctrl reports as VK_RCONTROL (0xA3). Watch its key down and key up, plus Esc while recording. Always call CallNextHookEx and never swallow a key.
- Return from the hook callback immediately and post the event to a queue. Windows silently removes a low-level hook whose callback takes too long.
Audio
- Use NAudio. WaveInEvent with WaveFormat(16000, 16, 1) and BufferMilliseconds = 100 hands you 100 ms chunks in exactly the format the API wants; Windows converts from the device format. Choose the device by DeviceNumber from the list in Settings. Start capture on hotkey down and stop it on release.
- Watch for default device changes with NAudio's MMDeviceEnumerator.RegisterEndpointNotificationCallback and reopen capture when the default input changes.
Text insertion
- Clipboard calls must run on an STA thread. Snapshot every format on the clipboard (GetFormats, then GetData for each one you can read; skip any that throw), write the transcript with SetText, send Ctrl+V with SendInput (Ctrl down, V down, V up, Ctrl up), wait 1 second, then restore the snapshot only if GetClipboardSequenceNumber still equals the value right after your write.
- Another app can hold the clipboard open for a moment. Retry a few times with 20 ms waits before giving up.
- Typing as I talk: SendInput with KEYEVENTF_UNICODE, a key-down and a key-up INPUT for each UTF-16 unit (a surrogate pair is two units, sent back to back), and VK_BACK for Backspace. Typing never touches the clipboard.
- Set dwExtraInfo on every INPUT the app sends to a fixed value, and have the keyboard hook ignore events that carry it, so the app never takes its own typing for me pressing a key.
- Right Ctrl is held the whole time I talk. Check in Notepad, a browser text field and Windows Terminal that the typed words arrive as plain text and fire no Ctrl shortcuts, and tell me if any app misbehaves.
- For the focus guard in Typing as I talk, the focused window is GetForegroundWindow and the focused control is hwndFocus from GetGUIThreadInfo on that window's thread.
- Windows blocks input injected into an app running as administrator when this app is not elevated (UIPI). Detect an elevated foreground window (GetForegroundWindow, GetWindowThreadProcessId, then OpenProcess and GetTokenInformation with TokenElevation) and fall back to leaving the text on the clipboard with a notification. Don't type into such a window while I talk either.
Overlay
- A borderless TopMost Form with ShowWithoutActivation = true and the extended styles WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW, WS_EX_TRANSPARENT and WS_EX_LAYERED, shown on the monitor of the foreground window (MonitorFromWindow on GetForegroundWindow).
Networking
- System.Net.WebSockets.ClientWebSocket with Options.SetRequestHeader("Authorization", ...) and Options.KeepAliveInterval set to 20 seconds. Reconnect on NetworkChange.NetworkAvailabilityChanged and on SystemEvents.PowerModeChanged with PowerModes.Resume.
Storage
- API key: Windows Credential Manager through CredWrite and CredRead (P/Invoke to advapi32), as a generic credential whose target name is the app's name.
- Settings and history as JSON in %APPDATA%\<app name>. Logs in %LOCALAPPDATA%\<app name>\logs.
- Launch at login with a value under HKCU\Software\Microsoft\Windows\CurrentVersion\Run.
Permissions
- Settings > Privacy & security > Microphone must allow desktop apps to use the microphone. Detect access denied when capture opens and tell me exactly where to turn it on.
- The app needs no administrator rights; never ask for them.
Build
- dotnet publish -c Release -r win-x64 --self-contained -p:PublishSingleFile=true. Give me the exact command and the output path. SmartScreen will warn about an unsigned exe the first time; tell me how to run it anyway.
Test speech for the smoke test: use System.Speech (the System.Speech NuGet package) with SpeechSynthesizer.SetOutputToWaveFile and SpeechAudioFormatInfo(16000, AudioBitsPerSample.Sixteen, AudioChannel.Mono).
Linux build prompt
# Build me a dictation app for Linux
I want my own version of Wispr Flow: I hold a hotkey, talk, let go, and the text appears wherever my cursor is, in any app. While I talk, my words appear right there in the input as I say them, and when I let go the final text replaces them in place.
It runs on Morph's speech-to-text API with two models. morph-transcribe (NVIDIA Nemotron 3.5 Transcribe) in dictation mode writes the text that gets inserted: measured from the moment I stop talking, it returns the final text in about 195 ms (the median on a 10.5 second clip), at $0.18 per hour of audio. morph-transcribe-live (NVIDIA Nemotron 3.5 ASR Streaming, a much smaller model) returns text while I am still talking, and the app uses it only to type my words as I say them, at $0.198 per hour of audio. The whole design exists to keep the final text fast: audio streams to the server while I am still talking, so when I let go there is nothing left to upload.
This document is the full spec. Read all of it before you start. The "Morph realtime API" section is a complete reference for everything this app needs. Do not invent fields or events it doesn't describe; if something is unclear, read the docs linked there.
Codex built a macOS version of this app from this spec, and it's open source (MIT) at https://github.com/skeptrunedev/morph-dictation. Its Sources/DictationCore folder has the realtime clients, the dictation state machine and the live-text swap, which carry over to Linux. Read it to check your logic, not to port Swift line by line.
## How to work
1. Plan first. Before writing any code, show me the project layout, the modules and what each one owns, the state machine, the libraries you will use and why, and anything you need me to install or approve. Wait for my OK.
2. Build in this order, and get each step running before starting the next:
a. The API client, plus a command-line smoke test that streams a WAV file through the exact code path the app uses and prints the transcript and the latency.
b. Microphone capture streaming into that client.
c. The global hotkey.
d. Text insertion into the focused app: typing as I talk, the swap to the final text, and the paste.
e. The tray UI, the recording overlay, the setup window and the settings window.
f. Key storage, launch at login, history and polish.
3. Ask me before anything system-wide: installing system packages, changing group membership, adding login items or granting permissions.
4. When it all works, launch it, walk me through the setup window and every permission prompt, and do a first test dictation with me in its test box.
## Stack
Build it as a Python 3 tray app. The Linux section at the end has the APIs to use and the traps on this OS. Follow it.
## What the app does
### Setup window
- One window takes me from a fresh install to a working dictation, and shows at a glance whether the app works. It opens on every launch until my first successful dictation, and after that from the menu (Open Morph Dictation).
- Top to bottom: the API key (paste, Save, and the result of a live connection test), then each permission this OS needs, showing its live state, with a button that is disabled once that permission is granted.
- Once the key works and every permission is granted, the window says in large type "Press and hold Right Ctrl to dictate", naming the hotkey actually set in Settings, plus "Double tap for hands-free" when that mode is on. Until then, the same line says what is missing ("Add your API key", or the permission still needed).
- Under that line, a multi-line text box to try it in. I click into it, hold the hotkey, talk and let go, and the text lands in the box through the same insertion path every other app gets. The text wraps to the box's visible width with a small margin on both sides and scrolls only vertically, so no line is ever cut off. My words appear in the box as I talk, exactly as they will in any other app. Under the box, show where that dictation is: Listening, Transcribing, then "Inserted in 212 ms", or the exact error.
- A connection line: Connected, Reconnecting, or the exact error.
### Hotkey
- Hold-to-talk on a global hotkey, Right Ctrl by default and changeable in settings. Key down starts recording; key up ends the dictation.
- A single press shorter than 200 ms is an accident: discard it, send input_audio_buffer.clear, and insert nothing.
- Hands-free mode: a double tap (two taps within 300 ms) starts recording without holding the key, and the next tap stops it.
- Esc while recording cancels: stop capture, send input_audio_buffer.clear, insert nothing.
- Ignore key auto-repeat. Never swallow the hotkey or any other key; other apps must still see them.
- The hotkey works in every app, including full-screen ones.
### Recording overlay
- While recording, show a pill near the bottom center of the screen with a live input level meter. While transcribing, show a spinner. Hide the pill once the final text is in. The Linux section says how to build it on this OS.
- The pill never shows my words. They go into the input I am dictating into (see Typing as I talk), never into a preview at the bottom of the screen.
- The overlay must never take focus or receive clicks. If it steals focus, my words land in the overlay instead of my app.
### Typing as I talk
- With Type as I talk on, the words from the live session (see Live session below) are typed into whatever has focus as they arrive, at the cursor, as if I were typing them. The Linux section says how to type on this OS. Typing never touches the clipboard.
- When the final transcript arrives, it replaces the typed words in place. Keep the longest common start of what was typed and the final text, comparing whole characters, press Backspace once for each typed character after it, then type the rest of the final text, plus the trailing space when that setting is on. Ignore live words that arrive after the final transcript. The input ends up holding the final transcript exactly once: never the live words and the final text together.
- Esc and a short tap delete everything that dictation typed.
- Only ever delete what the dictation itself typed. Note the focused app and element when typing starts. If focus moves, or I press any key other than the hotkey while it is typing, stop typing for that dictation and leave that input alone. When its final transcript arrives, put it on the clipboard and show "Copied. Press Ctrl+V to paste." instead of replacing anything.
- Dictations stay in order: a new dictation's words wait to be typed until every earlier dictation's final text is in.
- If nothing was typed (Type as I talk is off, the live session was refused or failed before its first word, or this OS can't type into the focused app), paste the final transcript as below.
### Pasting the final text
- When nothing was typed while I talked, paste the final transcript into whatever has focus when the text is ready: save the current clipboard (every format on it, not only text), put the transcript on it, send Ctrl+V, wait about 1 second, then restore the saved clipboard. Slow apps read the clipboard late, and a shorter wait pastes my old clipboard instead of the dictation. If something else changed the clipboard during that wait, don't restore over it.
- Trim surrounding whitespace. A setting, on by default, adds one trailing space after each insertion so consecutive dictations don't run together.
- An empty transcript (I held the key and said nothing) inserts nothing and shows "No speech" for a moment.
- If the paste can't be delivered, leave the transcript on the clipboard and show "Copied. Press Ctrl+V to paste."
- Never lose a transcript silently. If it can't be inserted, it goes to the clipboard and to History, with a notification.
### Tray menu
- The icon shows the state: idle, recording (animated), transcribing, waiting for a permission, copied to the clipboard, error or disconnected.
- Menu items: a status line that says "Hold Right Ctrl to dictate" when everything works (or what is missing) and the last latency ("Last: 212 ms"), Open Morph Dictation, Recent dictations (the last 10; click one to copy it), Settings, Pause dictation / Resume dictation, and Quit.
### Settings
- Morph API key: stored in the system keyring (the keyring package). Show only its last 4 characters once saved, with a Test button that connects and reports OK or the exact error.
- Hotkey and mode: hold-to-talk, hands-free double tap, or both.
- Language: Auto-detect, or one language from the list in the API section.
- Style: Clean (default) or Verbatim.
- Vocabulary: names and jargon I want spelled right, sent as keyterms (at most 100 terms).
- Type as I talk: on by default. Turning it off skips the live model entirely, along with its cost, and the final text is pasted when I let go.
- Microphone: the system default or a specific device.
- Sounds: subtle start and stop sounds, off by default.
- Trailing space on or off. History on or off, and Clear history. Launch at login.
- Settings persist in the platform's usual per-user location. Changing language, style or vocabulary sends a new session.update, which applies from the next dictation.
### History
- Keep the last 50 transcripts locally, with timestamps, for the Recent dictations menu. It has an off switch and a Clear button. Audio is never stored.
## Audio pipeline
- Start the microphone the instant the hotkey goes down and keep every sample from that moment on. The first syllable is the one most often lost. Don't keep the microphone open while idle, because that shows the system's microphone-in-use indicator all day.
- Convert to 16 kHz, mono, 16-bit signed little-endian PCM. Resample on the device with a proper resampler, never by dropping samples.
- Send a chunk every 100 ms (3,200 bytes at 16 kHz) while recording. Never hold audio back until key-up. Audio captured before the session is ready waits in memory and goes out the moment it is.
- On key-up, stop capture, send the last partial chunk, then commit.
- Compute the level meter from the same buffers (RMS, smoothed), so it costs nothing extra.
- When the input device changes mid-session (AirPods connect, a USB mic is unplugged), restart capture on the new device. If that happens mid-dictation, keep the audio captured so far.
- Keep each dictation's PCM in memory until its transcript arrives, so it can be sent again if the connection drops (see Reliability). Free it afterwards.
- If the computer goes to sleep while I'm recording, cancel that dictation (send input_audio_buffer.clear) and release the microphone.
## Morph realtime API
Morph's realtime API speaks OpenAI's realtime transcription protocol, with Morph's models. The app uses two sockets:
- The dictation socket, open all the time. It carries every dictation and returns the text to insert. Connect, Configure the session, One dictation and Reliability below are about this socket.
- A live socket for each dictation, open only while I am recording. Its words are the ones typed as I talk. See Live session below.
### Connect
wss://api.morphllm.com/v1/realtime?intent=transcription&model=morph-transcribe
Authorization: Bearer <API key>
- Keep model=morph-transcribe in the URL. A session that doesn't name a model starts on morph-transcribe-live (the streaming model for voice agents) with 24 kHz audio and server-side voice activity detection. The session.update below sets everything explicitly as well.
- Open the socket at launch and keep it open, so a dictation never waits on a TLS handshake. An open socket costs nothing; only audio in committed dictations is billed.
- If the server refuses the WebSocket upgrade, the HTTP response body is JSON: {"error": {"message": "...", "type": "...", "code": "...", "param": null}}.
- 401, authentication_error: stop retrying and ask me for a valid key.
- 402, quota_exceeded_error: stop retrying and tell me to check billing at https://www.morphllm.com/dashboard.
- 429, rate_limit_error: retry with backoff.
### Configure the session
The server's first message is session.created. Send this right away, and wait for the session.updated reply before the first append:
{"type": "session.update", "session": {"type": "transcription", "audio": {"input": {
"format": {"type": "audio/pcm", "rate": 16000},
"turn_detection": null,
"transcription": {"model": "morph-transcribe", "language": "en", "style": "clean", "keyterms": ["Morph"]}
}}}}
- turn_detection null means the client decides when a dictation ends: my key release. Without it, the server ends turns on its own at pauses.
- format: audio/pcm is 16-bit little-endian mono, at rate 16000 or 24000.
- language: leave it out to detect the language automatically. Supported codes: ar, bg, bn, cs, da, de, el, en, es, et, fi, fr, he, hi, hr, hu, id, it, ja, ko, lt, lv, mr, mt, nl, pl, pt, ro, ru, sk, sl, sv, ta, te, th, tl, tr, uk, vi, zh.
- style: "clean" drops fillers like "um" and repeated words and returns punctuated text. "verbatim", the server default, keeps everything.
- keyterms: up to 100 plain strings for names and jargon. Angle brackets and control characters are stripped. prompt is an optional free-text hint about what I dictate (for example "Software engineering notes."). keyterms and prompt together must stay under 2,000 characters.
- Send session.update again whenever I change these settings. A change applies to dictations that start after the server's session.updated reply; a dictation already in progress keeps the settings it started with.
- A bad value comes back as an error event whose param names the field, for example session.audio.input.transcription.keyterms.
### One dictation
The client sends:
- {"type": "input_audio_buffer.append", "audio": "<base64 PCM>"} every 100 ms while recording. The first append after a commit (or after connecting) starts a new dictation.
- {"type": "input_audio_buffer.commit"} on key-up.
- {"type": "input_audio_buffer.clear"} to cancel. A cleared dictation is never transcribed or billed. The server replies input_audio_buffer.cleared.
- Every client event is a JSON object sent as a text frame. Any client event may carry an "event_id"; an error it causes echoes that id back.
For each dictation, the server sends, in order:
- input_audio_buffer.committed with item_id and previous_item_id: the dictation is closed, and item_id names it from here on.
- conversation.item.input_audio_transcription.delta with item_id and delta: text as it is written. Don't type or paste these: the words typed while I talk come from the live session.
- conversation.item.input_audio_transcription.completed with item_id, transcript and usage: the final text. Insert this. usage reports the audio that dictation used; log it.
- Or, instead of completed, conversation.item.input_audio_transcription.failed with item_id and error {type, code, message}. Only that dictation failed; the socket stays usable.
The server can also send error with {type, code, message, param, event_id} when a client event is invalid. The socket stays open.
Rules:
- Never commit a dictation you sent no audio for. An empty commit returns an error with code input_audio_buffer_commit_empty. Taps under 200 ms send clear instead.
- Dictations can overlap. After a commit, the next dictation can start immediately, before the previous transcript arrives. committed events arrive in the order you committed, so pair each one with your oldest uncommitted dictation, then match delta, completed and failed by item_id. Insert transcripts in commit order, holding a later one back until the earlier one has been inserted or has failed.
- Long dictations: once a dictation passes about 45 seconds, the server cuts it at pauses and transcribes the pieces in parallel after key-up. Deltas then arrive one whole piece at a time, in order, and completed carries the joined text. The client doesn't change.
- A dictation holds at most 60 minutes of audio; past that it fails with code audio_too_long. Stop recording automatically at 59 minutes, commit, and tell me why.
- failed with type quota_exceeded_error: stop and tell me to check billing. With type server_error or rate_limit_error: retry once (see Reliability). Anything else: show the message.
### Reliability
- Keepalive: send a WebSocket ping every 20 seconds and treat the connection as dead if no pong arrives within 10 seconds. Proxies along the way can drop a connection that has been quiet for a while.
- Reconnect whenever the socket closes, with exponential backoff and jitter (0.5 s, doubling, capped at 10 s), and immediately when the network comes back, when traffic moves to a different network interface, or on wake from sleep. Other network notifications are noise: a socket whose pings are answered is healthy, so leave it alone. After reconnecting, send session.update again and wait for session.updated.
- A dictation that was in flight when the socket died (still recording, or committed with no completed yet) is sent again on the new socket from the PCM kept in memory: append all of it in 100 ms chunks, then commit once the recording has ended. The same goes for failed with type server_error or rate_limit_error, after waiting 1 second. Retry at most once per dictation.
- If I press the hotkey while disconnected, record anyway. The audio waits in memory and goes out as soon as the session is ready.
### Live session
A second session, on morph-transcribe-live, returns my words while I talk, and the app types them (see Typing as I talk). Skip all of this when Type as I talk is off.
- Open it at hotkey down, on the same URL with model=morph-transcribe-live instead of model=morph-transcribe, and close it when the dictation ends. Never keep it open between dictations: an open live session holds a slot on Morph's live workers.
- After session.created, send this and wait for session.updated before the first append:
{"type": "session.update", "session": {"type": "transcription", "audio": {"input": {
"format": {"type": "audio/pcm", "rate": 16000},
"turn_detection": null,
"transcription": {"model": "morph-transcribe-live", "language": "en", "chunk_ms": 320}
}}}}
- language: the dictation's language if it is one of ar, bg, cs, da, de, en, es, et, fi, fr, hi, hr, hu, it, ja, ko, nl, pl, pt, ro, ru, sk, sv, tr, uk, vi, zh. For any other language, or Auto, leave it out and the live model detects it. The live model takes no style, keyterms or prompt; sending any of them is an error.
- chunk_ms is how much audio the model reads per step: 80, 160, 320, 560 or 1120. 320 types new words about three times a second.
- Send it the same 100 ms chunks as the dictation socket, starting with the audio captured before it was ready.
- conversation.item.input_audio_transcription.delta events carry new text. Deltas only ever append, so type each one as it arrives: the deltas joined in order are exactly what was typed.
- At key-up, send input_audio_buffer.commit, then close the socket when its completed arrives or after 1 second, whichever comes first. On Esc or a short tap, send input_audio_buffer.clear and close it.
- The live session must never slow down or block a dictation. If its connection is refused (429 when live capacity is full) or anything on it fails, stop typing, keep what was typed, and carry on: the final text still replaces it as usual. Don't retry it within that dictation.
### Billing
- Dictation socket: only audio in committed dictations is billed, at $0.18 per hour of audio. An idle open socket is free, and so is a cleared dictation.
- Live session: every second of audio appended to a live session is billed, at $0.198 per hour of audio, as one usage row when the session closes.
- With Type as I talk on, an hour of dictation costs about $0.38.
### Docs
- https://docs.morphllm.com/models/speech-to-text
- https://docs.morphllm.com/api-reference/endpoint/realtime-transcription
### API key
My Morph API key is YOUR_API_KEY (keys live at https://www.morphllm.com/dashboard/api-keys). Before the first launch, put it into the system keyring (the keyring package) for me through the app's own code, for example a hidden --store-key-stdin mode that reads the key from stdin and exits, so the app works the first time I open it and I never paste the key myself. Never pass the key as a command-line argument, and never put it in source code, a config file, a log or git.
## State machine
Write the states down in code as one explicit enum with its transitions. Don't scatter booleans.
- Idle -> Recording: hotkey down, or a double tap in hands-free mode.
- Recording -> Idle: released within 200 ms, or Esc (send clear).
- Recording -> Transcribing: released (commit).
- Transcribing -> Inserting: completed arrives for the oldest pending dictation.
- Inserting -> Idle: the final text has replaced the typed words, or was pasted and the clipboard restored.
- Any state -> Error: show the message in the menu and in the overlay for 3 seconds, then return to Idle. Dictation keeps working after an error.
- Starting a new recording while an earlier dictation is still transcribing is allowed (see "Dictations can overlap").
## Latency
Measure these for every dictation and write them to the debug log:
- Hotkey down -> first chunk sent. Target under 150 ms; it is mostly microphone start-up.
- Hotkey down -> first word typed. It includes the live socket's connection, so log it rather than chasing a target.
- Hotkey up -> commit sent. Target under 20 ms.
- Commit -> completed. This is the server: about 195 ms median on a 10 second dictation.
- Completed -> text visible in the app. Target under 50 ms.
The menu's "Last" figure is hotkey up -> text inserted. If a stage is slow, fix that stage. Don't add delays anywhere except the clipboard-restore wait.
## Privacy and logging
- Audio never touches disk. Transcripts are stored only in History, and only while History is on.
- Logs go to the platform's usual log location, rotate at 5 MB, and record timings, event types, item_ids and error codes. They never contain the API key, and never contain transcript text unless I turn on a debug switch.
- No analytics, no crash reporters, and no network calls other than the Morph sockets.
## Checks
Don't write unit tests. I want only these two checks, because they run the real thing:
- The smoke test from step 2a streams a generated speech WAV through the real client against the real API (the Linux section says how to make one), on both sockets, then prints the live words as they arrive, the final transcript, the replacement it would make (characters kept, deleted and typed), and the commit -> completed latency. Run it before wiring up the microphone. Don't mock the server in it.
- A launch check, from step 2e on: after every build, start the packaged app the way I will (the installed app, not a binary in the build folder) and confirm it is still running 10 seconds later. The smoke test runs outside the packaged app, so it misses crashes that only happen inside it, like lookups that depend on the app's identifier or bundled resources.
## Acceptance checklist
Run through this with me at the end and tell me which items pass:
1. After setup, the setup window says "Press and hold Right Ctrl to dictate", and a dictation into its test box lands there with its latency.
2. Hold Right Ctrl, say "testing one two three" and release in a text editor: my words appear in the editor as I say them, the final text replaces them within about half a second of letting go, and the editor ends up with the sentence exactly once.
3. Turn Type as I talk off and dictate: nothing is typed while I talk, the text is pasted when I let go, and no live socket opens.
4. Tap Right Ctrl quickly: nothing is inserted and no error shows.
5. Start dictating, then press Esc: the words typed so far are deleted, and nothing else is inserted.
6. Click into a different window halfway through a dictation: nothing is deleted in either window, and the final text is on the clipboard with a notice.
7. Copy a word, dictate a sentence with Type as I talk on, then paste manually: the word I copied comes back.
8. Copy a word, dictate a sentence, then paste manually: the word I copied comes back.
9. Dictate twice in quick succession: both transcripts appear, in order.
10. Turn Wi-Fi off, dictate, turn Wi-Fi back on: the dictation is transcribed and inserted after the reconnect.
11. Dictate for 60 seconds straight: one complete transcript.
12. Set language to Auto and dictate in a second language, if I speak one: the text is in that language.
13. Add a made-up name to Vocabulary and dictate it: it comes out spelled the way I wrote it (if not, show me what came back).
14. Quit and relaunch: settings and the key are kept, and the key is in no plain file.
15. Works in my session type (tell me whether you tested X11, Wayland or both).
16. Dictate into a terminal: on X11 the words appear as I talk, and on both X11 and Wayland the final text comes out right.
17. Plug in an external keyboard after launch: its Right Ctrl works as the hotkey.
## Deliverables
- The source in a new git repository, with a README covering build, run, permissions, where settings and logs live, and troubleshooting for every error message the app can show.
- One command to build and run.
- The smoke test command.
- An uninstall command that quits the app and removes it, its settings, history, logs and stored API key, and resets its permissions (on macOS, tccutil reset All <bundle id>).
- A short list of anything you couldn't make work, and why.
## Linux
Target Python 3.11 or newer, packaged as a pipx-installable project with a console entry point, so I install it with pipx and run it as a command.
Libraries: sounddevice (PortAudio) for the microphone, websockets 14 or newer for the socket, evdev for the hotkey, keyring for the API key, and a tray that speaks StatusNotifierItem/AppIndicator (pystray with its appindicator backend, or AyatanaAppIndicator3 through PyGObject). Tell me the exact system packages to install on my distro (PortAudio, the GObject and AppIndicator bindings, and the paste tools below). On GNOME the tray icon needs the AppIndicator extension; detect a missing tray and tell me.
Hotkey
- Read key events straight from /dev/input with evdev. That works the same on X11 and Wayland. It needs my user in the input group (sudo usermod -aG input $USER, then log out and back in). Ask me before running that, and tell me why it matters: the input group can read every key on the system, so the app must act only on its hotkey and must never log key events.
- Keyboards are the devices that report EV_KEY with both KEY_A and KEY_RIGHTCTRL. Read all of them concurrently with asyncio (async_read_loop). A value of 1 is key down, 0 is key up and 2 is auto-repeat, which you ignore. Never grab the devices.
- Pick up keyboards plugged in after launch: rescan /dev/input every few seconds, or watch it with pyudev.
Audio
- sounddevice.RawInputStream(samplerate=16000, channels=1, dtype="int16", blocksize=1600) delivers 100 ms blocks; PipeWire or PulseAudio resamples from the device's rate. The callback runs on PortAudio's thread: copy the bytes and hand them to the asyncio loop with loop.call_soon_threadsafe, and never block inside the callback.
- Open the stream on hotkey down and close it on release.
Text insertion
- Check XDG_SESSION_TYPE.
- X11: xclip for the clipboard (save the text and image targets you can read, write the transcript, restore afterwards) and xdotool key --clearmodifiers ctrl+v for the keystroke.
- Wayland: wl-copy and wl-paste for the clipboard, and ydotool for the keystroke (ydotool key 29:1 47:1 47:0 29:0 is Ctrl+V). ydotool needs the ydotoold daemon running with access to /dev/uinput. Set that up as a systemd user service and tell me exactly what you changed.
- Typing as I talk on X11: xdotool type --clearmodifiers --delay 0 for the words and xdotool key --clearmodifiers BackSpace to delete. --clearmodifiers lifts the Right Ctrl I am holding while it types and puts it back afterwards. xdotool's events never pass through /dev/input, so the evdev hotkey reader doesn't see them. For the focus guard, the focused window is xdotool getactivewindow.
- On Wayland, skip typing as I talk and paste the final text when I let go. ydotool types through a virtual keyboard while my Right Ctrl is still held, so the compositor turns the letters into Ctrl shortcuts, and it only knows the characters of a US layout.
- Terminals paste with Ctrl+Shift+V. On X11, read the focused window's class with xdotool getactivewindow getwindowclassname and send Ctrl+Shift+V to known terminals (gnome-terminal, konsole, kitty, alacritty, wezterm, xterm). Wayland has no general way to learn the focused app, so add a setting for the paste shortcut, plus a "Type instead of paste" mode (xdotool type or ydotool type) that works everywhere but is slower and limited to characters on my keyboard layout.
Overlay
- On X11, a small undecorated, always-on-top GTK window that never takes focus (accept-focus false, skip the taskbar, click-through) is fine.
- On Wayland, skip the floating overlay: compositors don't let a normal app float a window like that, and GNOME has no layer-shell. Use the tray icon's state, plus a desktop notification for errors.
Networking
- websockets.connect(url, additional_headers={"Authorization": "Bearer ..."}, ping_interval=20, ping_timeout=10). Reconnect when the connection drops. If D-Bus is available, also reconnect on NetworkManager state changes and on systemd-logind's PrepareForSleep signal (resume); otherwise the ping timeout catches a dead connection.
Storage
- API key: keyring (Secret Service, so GNOME Keyring or KWallet). If no keyring backend is available, stop and tell me. Never fall back to a plaintext file.
- Settings in $XDG_CONFIG_HOME/<app name>/ (default ~/.config). History and logs in $XDG_STATE_HOME/<app name>/ (default ~/.local/state).
- Launch at login with a .desktop file in ~/.config/autostart.
Test speech for the smoke test: espeak-ng -w /tmp/dictation-test.wav "Testing one two three. This is a dictation test." The smoke test resamples it to 16 kHz mono.
What to expect
The agent plans first and waits for your OK. It then builds in stages, starting with a smoke test that streams a generated speech file through the real API, and finishes in the app’s setup window, where you grant permissions and try a first dictation in a test box. Once it reads “Press and hold” with your hotkey, the app is ready.- macOS builds with the Command Line Tools; full Xcode isn’t needed. The app asks for Microphone and Accessibility permission. Without a signing certificate it is ad-hoc signed, so each rebuild needs a fresh Accessibility grant; the app clears its old entry and asks again.
- Windows needs no admin rights. Desktop apps must be allowed to use the microphone (Settings > Privacy & security > Microphone).
- Linux reads the hotkey from
/dev/input, which needs your user in theinputgroup. On Wayland it pastes throughydotool.
Troubleshooting
401 when the app connects. The API key is wrong or was deleted. Paste a current one from the dashboard into the app’s settings. 402 when the app connects, or a dictation fails withquota_exceeded_error. The account’s monthly quota is used up. Check billing.
Nothing happens when you press the hotkey. On macOS, check that the app is enabled under System Settings > Privacy & Security > Accessibility, and note that password fields block hotkeys while they have focus. On Linux, log out and back in after joining the input group.
The text lands on the clipboard instead of in the app. On Windows, the focused app is running as administrator, which blocks synthesized keystrokes from non-elevated apps. On Linux, terminals paste with Ctrl+Shift+V; set the paste shortcut in the app’s settings.
No words appear while you talk. Type as I talk is off in settings, you’re on Linux under Wayland, or live capacity was full when the dictation started (the live session is refused with 429). The dictation itself still works.
The first word goes missing. Bluetooth microphones take a moment to start. On macOS, turn on “Keep microphone ready” in the app’s settings if the agent added it.