Pick your OS and paste this build spec into Claude Code, Codex or Cursor. Your agent builds an app that types your words wherever your cursor is as you talk, then swaps in the final text from morph-transcribe when you let go.
# 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."