Sources: Google eng-practices · thoughtbot/guides · joho/awesome-code-review
Summary
Overall, this is a sophisticated and well-architected macOS dictation tool with impressive features. The single-file Lua architecture is intentional and largely well-executed. However, the 3000+ line hammerspoon/init.lua has accumulated significant complexity, particularly in state management and async pipeline coordination. The biggest concerns are race conditions in the streaming transcription pipeline, timer lifecycle management, and moderate shell injection risks. Code health is Needs Work — functional and creative, but would benefit from systematic refactoring for maintainability and reliability.
Findings
🔴 Critical
hammerspoon/init.lua#L2755-L2850 — Race condition in meeting window pipeline meetingActiveTasks stores tasks by token, but the released flag and task cleanup happen in nested callbacks. If the watchdog fires while the pipeline callback is executing, both can call release(), leading to double-decrement of meetingPendingTranscriptions (goes negative) or premature maybeFinalizeMeetingSave() execution. Fix: Add atomic guard at top of release(): if released then return end; released = true — already present, but move ALL state changes (counter decrement, timer stop) inside this guard.
hammerspoon/init.lua#L1510-L1580 — Parallel whisper calls without serialization dispatchSegment() spawns multiple whisper-cli processes concurrently (one per segment). According to meeting mode comments (line 2561), whisper.cpp + Metal GPU doesn't tolerate concurrent invocations well (deadlock risk). The meeting pipeline serializes via meetingProcessing, but the main dictation pipeline at line 1510-1580 does not. Fix: Apply the same serialization pattern from meeting mode to the main dictation pipeline: queue segments and process one at a time when GPU is involved.
hammerspoon/init.lua#L316 — Shell injection via @tmpfile in curl refineWithOllama() writes JSON payload to WHISPER_TMP .. "/refine_payload.json" and passes it to curl via -d "@$tmpPayload". If an attacker controls transcribed text (e.g., pre-recorded audio played during dictation), they can inject newlines or special shell chars that break out of the JSON structure. Fix: Use hs.task with proper argument array (not shell pipeline) and pass JSON via stdin pipe, OR sanitize/validate JSON payload before writing to disk.
🟠 High
hammerspoon/init.lua#L1243-L1278 — Timer accumulation risk pulseTimer, clockTimer, partialTimer, silenceTimer, streamTimer, warmupTimer, meetingTranscribeTimer, meetingControlTimer are started in various code paths. While most have if timer then timer:stop() guards, the emergencyStop() function only stops a
** — Timer accumulation risk pulseTimer, clockTimer, partialTimer, silenceTimer, streamTimer, warmupTimer, meetingTranscribeTimer, meetingControlTimer are started in various code paths. While most have if timer then timer:stop() guards, the emergencyStop() function only stops a subset. If a user rapidly starts/stops recording or hits edge cases, timers can leak. Fix: Consolidate all timer cleanup into a single stopAllTimers() function called from emergencyStop(), stopRecording(), and stopMeeting(). Keep a registry table of all active timers for bulletproof cleanup.
hammerspoon/init.lua#L1425-L1520 — Pipeline state not reset on error pipelineReset() clears results array and counters, but if a segment's whisper call fails (exit code != 0), the pipeline continues counting it as "done" (onPipelineDone called with empty text). If multiple segments fail, pipelineFinalizing logic can finalize with partial data without user awareness. Fix: Track failed segments separately; show a warning overlay if any segment failed, and log which chunks were dropped.
hammerspoon/init.lua#L860-L900 — Canvas mouse callback cannot delete canvas
Close button (X) at line 860 calls canvas:delete() inside its own mouseDown callback, which is silently ignored by Hammerspoon. The workaround (canvas:hide() + deferred delete) is in place, but comments don't explain WHY this is necessary. Future maintainers may "simplify" it back to broken code. Fix: Add prominent comment explaining the Hammerspoon canvas limitation. Consider extracting this pattern into a helper function safeDeleteCanvas(canvas, delay).
hammerspoon/init.lua#L1780-L1850 — FFmpeg process not cleaned up on warmup failure tryWarmup() spawns ffmpeg with -f null to test device responsiveness. If all attempts fail, isWarmingUp is set to false and the overlay is hidden, but warmupTask:interrupt() is only called inside the retry timer. If the timer is killed before the interrupt fires, the ffmpeg process can linger. Fix: Always call warmupTask:interrupt() when exiting warmup failure path, not just in the timer.
hammerspoon/init.lua#L2260-L2330 — Meeting aggregate output restoration race restorePriorOutput() at line 2260 restores the user's default audio output device. If stopMeeting() is called while meeting transcription is still in flight, and the user closes Hammerspoon before maybeFinalizeMeetingSave() completes, the restoration never happens and the user is stranded on the aggregate. Fix: Add hs.shutdownCallback guard that unconditionally restores audio output if meetingPriorOutputUID is set, regardless of meetingStopping state.
🟡 Medium
hammerspoon/init.lua#L1-L3000 — Monolithic file (3000+ lines)
All runtime logic lives in one file. While the single-file architecture is intentional (per AGENTS.md), it's now difficult to navigate. State variables are scattered across the file, and it's hard to track dependencies. Suggestion: Consider splitting into logical modules WHILE KEEPING the single-file deployment (concatenate at install time). OR use Lua's module system with require() for dev, and a build step to inline everything into init.lua for production. Keep the single-file runtime, but improve dev ergonomics.
hammerspoon/init.lua#L1200-L1250 — Progress bar logic interleaved with recording state barState table at line 1071 holds progress bar state (txnSecs, maxSecs, segChunks), but updates happen in scattered locations: onPipelineDone(), updateProgressBar(), startRecordingIndicator(). This makes it hard to reason about when the bar is accurate. Fix: Encapsulate all progress bar logic into a single ProgressBar object with clear methods: start(), updateRecording(elapsed), updateTranscription(segN), freeze(), hide().
hammerspoon/init.lua#L350-L430 — splitAtSilence() assumes 1-second chunks
Function at line 350 uses hardcoded RMS threshold (300) and assumes all chunks are exactly 1 second. If ffmpeg's segment timing drifts (happens near EOF or when audio device stalls), the split logic can cut mid-word. Fix: Make chunk duration configurable, or read actual duration from WAV header instead of assuming 1s.
hammerspoon/init.lua#L2140-L2200 — Meeting mode: BlackHole 2ch device string hardcoded getBlackHoleDevice() at line 2140 searches for exactly "BlackHole 2ch". If the user has BlackHole 16ch or a renamed device, meeting mode fails silently. Fix: Search for any device starting with "BlackHole" and log which variant was found. OR make it configurable in ~/.local-whisper/meeting_device.
hammerspoon/init.lua#L450-L480 — Action hooks: no timeout on user callbacks
wraps user action functions in , but if a user's hook contains an infinite loop or blocks on I/O, the entire Hammerspoon event loop freezes.
: Add a timeout wrapper using + coroutine, OR document clearly in that hooks must return quickly.
🟢 Nit (non-blocking)
hammerspoon/init.lua#L10 — Nit: HOME and TMPDIR loaded from env vars, but no fallback if unset. macOS always has these, but defensive programming would add: HOME = os.getenv("HOME") or error("$HOME not set").
hammerspoon/init.lua#L166 — Nit: log() function opens/closes file on every call. For high-frequency logging (e.g., partial transcription), this is slow. Consider buffering or keeping the file handle open.
hammerspoon/init.lua#L1071 — Nit: barState is a global table, but pulseAlpha and pulseFading are separate locals. Inconsistent grouping makes state hard to track.
hammerspoon/init.lua#L1240 — Nit: updateMenuBar() defines makeWaveformIcon() inline. This function could be defined once at module level and reused.
hammerspoon/init.lua#L460-L480 — Nit: reloadActionConfig() at line 481 sets actionConfigMtime = 0 then calls loadActionConfig(), which recomputes mtime. Simpler to just set actionConfig = nil and call load.
hammerspoon/init.lua#L2400-L2450 — Nit: stripOverlap() at line 2400 is clever but complex. Add more inline comments explaining the K-word sliding window logic for future maintainers.
hammerspoon/local_whisper_actions.example.lua#L40-L60 — Nit: "voice command note" at line 47 uses origStripped:match() to re-extract text, but this duplicates work. Save the cleaned prefix once.
install.sh#L180-L190 — Nit: Tiny model download warns on failure but continues. Consider making this a hard error if live preview is important.
setup.sh#L75-L95 — Nit: run_with_timeout() at line 75 spawns a watchdog process but doesn't clean it up properly if the main command exits early. Use trap to ensure watchdog is killed.
tests/test_refine.sh#L60-L80 — Nit: Python inline JSON construction could fail if model name contains quotes. Use json.dumps() for the whole payload, not string interpolation.
Refactoring Plan Checklist
Below is a prioritized checklist for improving code health. Each item links to the finding above and provides an actionable task.
Phase 1: Critical Fixes (do first)
[CR-001] Fix race condition in meeting window pipeline release logic
→ Add atomic guard to release() function, ensure all state changes happen inside the guard
[CR-002] Serialize whisper calls in main dictation pipeline
→ Implement queue + processing flag like meeting mode (or unify both pipelines)
[CR-003] Eliminate shell injection risk in Ollama refinement
→ Replace curl -d "@file" with hs.task + stdin pipe, OR validate JSON payload
[CR-004] Add comprehensive timer cleanup
→ Create stopAllTimers() function and call from all
** — Nit: Python inline JSON construction could fail if model name contains quotes. Use json.dumps() for the whole payload, not string interpolation.
Refactoring Plan Checklist
Below is a prioritized checklist for improving code health. Each item links to the finding above and provides an actionable task.
Phase 1: Critical Fixes (do first)
[CR-001] Fix race condition in meeting window pipeline release logic
→ Add atomic guard to release() function, ensure all state changes happen inside the guard
[CR-002] Serialize whisper calls in main dictation pipeline
→ Implement queue + processing flag like meeting mode (or unify both pipelines)
[CR-003] Eliminate shell injection risk in Ollama refinement
→ Replace curl -d "@file" with hs.task + stdin pipe, OR validate JSON payload
[CR-004] Add comprehensive timer cleanup
→ Create stopAllTimers() function and call from all stop/abort paths
[CR-005] Fix warmup ffmpeg process leak on failure
→ Always call warmupTask:interrupt() when exiting failure path
Phase 2: High-Priority Improvements
[CR-006] Track failed pipeline segments separately
→ Show warning if any segment failed, log which chunks were dropped
[CR-007] Add shutdown callback for audio output restoration
→ Unconditionally restore meetingPriorOutputUID if set, prevent user getting stranded
[CR-008] Secure ctx:runShell() method
→ Use hs.task with argument array OR document that command must be hardcoded
[CR-010] Add timeout wrapper for action hooks
→ OR document clearly that hooks must return quickly (no blocking I/O)
Phase 3: Code Organization
[CR-011] Encapsulate progress bar logic
→ Create ProgressBar object with clear API: start(), updateRecording(), updateTranscription(), freeze(), hide()
[CR-012] Consolidate scattered state variables
→ Group related state into tables (RecordingState, PipelineState, MeetingState, UIState)
[CR-013] Extract utility functions
→ Move helpers like shellQuote(), normalizeText(), expandPath() to top of file or separate section
[CR-014] Consider modular architecture for development
→ Split into logical modules (recording.lua, transcription.lua, meeting.lua, ui.lua, actions.lua) with build step to concatenate into single init.lua for production
Phase 4: Medium-Priority Improvements
[CR-015] Make chunk duration configurable in splitAtSilence()
→ OR read actual duration from WAV header instead of assuming 1s
[CR-016] Improve BlackHole device detection
→ Search for any device starting with "BlackHole" instead of exact match, OR make configurable
[CR-017] Improve filler word removal logic
→ Use better word boundary anchors OR move filler removal to LLM refinement
[CR-018] Make warmup sound optional/configurable
→ Check system volume, add config option to disable warmup sound
[CR-019] Make meeting window timeout configurable
→ Scale based on window size OR make it a user setting
[CR-020] Buffer log file writes
→ Keep file handle open OR batch writes for high-frequency logging
Phase 5: Polish & Documentation
[CR-021] Add defensive checks for environment variables
→ Validate HOME, TMPDIR, etc. with fallbacks or clear errors
[CR-022] Consolidate state grouping
→ Move pulseAlpha, pulseFading into barState table for consistency
[CR-023] Extract makeWaveformIcon() to module level
→ Define once and reuse instead of inline definition
[CR-024] Simplify reloadActionConfig()
→ Just set actionConfig = nil instead of zeroing mtime
[CR-025] Add inline comments to complex algorithms
→ Especially stripOverlap() K-word sliding window logic
[CR-026] Clean up action config text extraction
→ Save cleaned prefix once instead of re-matching
[CR-027] Fix run_with_timeout() watchdog cleanup
→ Use trap to ensure watchdog process is killed
[CR-028] Fix Python JSON construction in test script
→ Use json.dumps() for entire payload, avoid string interpolation
[CR-029] Make tiny model download failure a hard error (optional)
→ IF live preview is critical, stop install on tiny model failure
3000-line monolithic file is hard to navigate and maintain
State management is scattered and error-prone
Multiple async pipelines with race condition risks
Some moderate security issues with shell command construction
Dataset releases
Not yet included in a published release.
hammerspoon/init.lua#L545-L565 — ctx:runShell() uses shell pipeline with unsanitized input
Action context method ctx:runShell(command, inputText) writes inputText to a temp file and runs command < tempfile via hs.execute(). If command contains unquoted variables or pipes, and the transcribed text (self.text) is attacker-controlled, shell injection is possible. Fix: Use hs.task with proper argument array instead of shell pipeline. OR document clearly that command must be hardcoded by the user (not derived from transcribed text).
safeHookCall()
pcall()
Fix
hs.timer.doAfter()
local_whisper_actions.example.lua
hammerspoon/init.lua#L265-L290 — postProcess() strips fillers with regex, but misses context
Line 265 removes "um", "uh", "hmm" as standalone words, but doesn't handle "umm yeah" or "uh-huh". Also removes "like," with trailing comma (line 271), which breaks "I, like, love this" → "I love this" (meaning changed). Fix: Use word boundary anchors more carefully: \b[Ll]ike,\s+ should only match when "like" is clearly filler (preceded by pause word or start). Consider moving filler removal to LLM refinement instead of regex.
hammerspoon/init.lua#L1900-L2000 — Warmup sound volume hardcoded warmupTick at line 1897 sets volume to 0.15 (15%). No user control, and no check if system volume is already muted. Fix: Read system volume first; if muted, skip sound. OR make warmup sound optional via config.
hammerspoon/init.lua#L2700-L2850 — Meeting window timeout hardcoded at 60s MEETING_WINDOW_TIMEOUT_SECONDS = 60 at line 2082. If whisper runs on a slow Mac (Intel, no GPU), this may not be enough for long audio windows. Fix: Make timeout configurable, OR scale it based on window size (e.g., 2x the audio duration).