Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

123 Commits

Folders and files

Repository files navigation

opencode-voice-input

Voice input for the OpenCode v2 (TUI). Press a global hotkey, speak, transcription is done locally (faster-whisper), and the message is sent straight to the current session of OpenCode — without relying on window focus.

CTRL+SHIFT+SPACE → listening starts → 🎤 speak, pause → local transcription → sent to chat

The default mode is continuous (dictation): the app listens to the microphone, detects when you speak and, on the pause, transcribes and sends — without pressing anything for each phrase. There is also toggle and push-to-talk in recording.mode.

  • 100% local: no audio leaves the machine, no telemetry, nothing sensitive persisted (metrics/latency data only).
  • Audio in memory: no temporary files on disk.
  • Windows + WSL2: the app runs natively on Windows and reaches OpenCode inside WSL.

Requirements

  • Windows 11 with WSL2 (where OpenCode v2 runs)
  • Python 3.10+ installed on Windows (the app runs on Windows)
  • OpenCode v2 running inside WSL (opencode2)

The app runs natively on Windows because the microphone/hotkey/tray use Windows APIs. Audio is never captured inside WSL.

Installation

git clone https://github.com/Nyxis-Studio/gossip-opencode
cd gossip-opencode
python -m venv .venv
.venv\Scripts\activate
pip install -e .

This installs the opencode-voice command.

Whisper model installation

The model is downloaded automatically on first run (log message: loading whisper model). After that it is cached in %USERPROFILE%\.cache\huggingface\hub and reused.

Model small (~460 MB) — a good precision/latency balance. On the first run startup takes longer (download); on subsequent runs, the model is already local.

Configuration

The app uses %USERPROFILE%\.config\opencode-voice\config.yaml. Copy the example:

New-Item -ItemType Directory -Force $env:USERPROFILE\.config\opencode-voice
Copy-Item config.example.yaml $env:USERPROFILE\.config\opencode-voice\config.yaml
notepad $env:USERPROFILE\.config\opencode-voice\config.yaml

Main options:

hotkey: ctrl+shift+space
cancel_hotkey: esc

recording:
  mode: continuous       # toggle | push-to-talk | continuous
  device: default
  vad:
    silence_threshold: 0.01
    min_speech_ms: 300
    min_silence_ms: 900  # pause that ends the phrase
    pre_roll_ms: 400
    max_utterance_ms: 20000

transcription:
  engine: faster-whisper
  model: small          # tiny | base | small | medium | large-v3
  language: pt          # "auto" or language code
  warmup: true
  vocabulary: [NestJS, Prisma, TypeScript, ...]  # Whisper initial_prompt

opencode:
  host: localhost
  port: auto            # auto = discovers the service (recommended)
  injector: auto        # auto | tui-event | clipboard | session-send | none
  directory: null       # TUI directory; null = detected automatically

behavior:
  autoSubmit: true      # true = sends straight to chat; false = inserts into the prompt (clipboard)

notifications:
  enabled: true

# Text-to-speech: reads the assistant's reply aloud in the current session.
# Requires: pip install edge-tts
tts:
  enabled: false       # set true to read replies aloud
  engine: edge-tts
  voice: pt-BR-FranciscaNeural  # edge-tts voice (the TTS model) — see edge-tts --list-voices
  language: pt-BR
  rate: +0%            # speaking rate, e.g. "+10%" / "-10%"
  pitch: +0Hz
  volume: 0.8          # playback volume (0.0..1.0)
  read_on_response: true
  summary:
    enabled: true      # condense the reply via the LLM before reading
    max_chars: 400

logging:
  level: info

The technical vocabulary is used as prompt conditioning for Whisper (initial_prompt) to favor the spelling of terms like NestJS/Prisma — there is no post-processing substitution.

How text reaches OpenCode

behavior.autoSubmit opencode.injector Behavior
true (default) auto → session-send Text sent as your message in the current session. Does not depend on focus, does not use clipboard
false auto → clipboard Text goes to the clipboard + Ctrl+V in the prompt (needs focus; you press ENTER)
any session-send (explicit) Always sends straight to chat
any none Does not deliver; only transcribes and logs

In session-send mode, the app discovers the correct session by the TUI working directory (cwd of the opencode2 process in WSL) and sends via POST /api/session/{id}/prompt. If you prefer to fix the directory, use opencode.directory.

Running

opencode-voice

Expected output:

OpenCode Voice Input
Whisper: small
Language: pt
Hotkey: Ctrl+Shift+Space
OpenCode: http://localhost:49374
Status: ready

Recording modes (recording.mode):

  • continuous (default): press CTRL+SHIFT+SPACE to start listening. Speak normally; when you pause (min_silence_ms), the phrase is transcribed and sent to chat automatically. Press the hotkey again to pause listening. ESC discards pending phrases (keeps listening).
  • toggle: CTRL+SHIFT+SPACE starts recording; press again to stop, transcribe, and send.
  • push-to-talk: hold CTRL+SHIFT+SPACE to record, release to send.

To quit: Ctrl+C in the terminal or the tray icon → Exit.

Other options:

opencode-voice --config path\config.yaml
opencode-voice --no-tray

Windows + WSL setup

  1. The app reads the OpenCode service registry inside WSL: ~/.local/state/opencode/service.json (via wsl.exe).
  2. The service.json contains the service url + password.
  3. The URL http://127.0.0.1:<port> is rewritten to localhost (WSL2 NAT has localhostForwarding on Windows 11). If localhost cannot be reached, the app resolves the WSL IP automatically (wsl.exe hostname -I) — no hardcoding.
  4. Authentication: HTTP Basic opencode:<password>.

If you use more than one WSL distro, set opencode.wsl_distro.

Manually check if the server is reachable

Inside WSL:

cat ~/.local/state/opencode/service.json

From Windows PowerShell, the same file via WSL:

wsl.exe bash -lc 'cat ~/.local/state/opencode/service.json'

To test the API (inside WSL):

opencode2 api get /api/health

Global hotkey

  • CTRL+SHIFT+SPACE (default): toggle — first press records, second stops.
  • ESC (default): cancels while recording. ESC is only captured during recording, so it does not interfere with other apps.
  • Can be changed in hotkey and cancel_hotkey in the YAML (pynput format).

Sending to OpenCode (session-send)

The OpenCode v2 investigation (see docs/opencode-integration.md) concluded that the TUI processes the tui.prompt.append event (inserts into the prompt without sending), but the server still does not expose how to publish it (endpoint/plugin). Therefore:

  1. behavior.autoSubmit: true (default) → session-send: the message is sent via the API (POST /api/session/{id}/prompt) straight to the current session — it appears in the chat as your message, without needing focus or clipboard.
  2. behavior.autoSubmit: false → clipboard fallback: copies to the clipboard and sends Ctrl+V (inserts into the prompt without sending, requires terminal focus).
  3. tui-event is ready for when OpenCode exposes the publication.

Session identification: the app detects the TUI working directory (cwd of the opencode2 process in WSL) and picks the most recent session for that directory; if none exists, it creates one. Use opencode.directory to set it manually.

Reading replies aloud (TTS)

opencode-voice can read the assistant's reply in the current session aloud. Requires the optional dependencies:

pip install "opencode-voice-input[tts]"

Enable it in the config:

tts:
  enabled: true                        # master switch
  voice: pt-BR-FranciscaNeural         # the TTS model — see `edge-tts --list-voices`
  language: pt-BR
  rate: +0%                            # "+10%" faster / "-10%" slower
  volume: 0.8                          # playback volume (0.0..1.0)
  read_on_response: true               # read each reply automatically
  summary:
    enabled: true                      # narrate what happened via the LLM first
    max_chars: 200                     # upper bound on the spoken narration

How it works: a background watcher polls the current OpenCode session (the same one session-send uses). When the assistant finishes a reply, it is rewritten into a short, conversational narration of what happened (via POST /api/generate, the default model) and spoken with edge-tts — like a voice keeping you posted, not reading the screen. File names, function names and paths are hidden behind what they do, so only the essential detail of a direct answer is read. Each narrated reply is also injected into the chat as a synthetic message (tts.show_in_chat) — it appears in the conversation, so it can be re-read when the audio was unclear. If the LLM is unavailable, the reply is converted locally (markdown removed, symbols expanded) as a fallback. When OpenCode is closed the watcher backs off (up to 30s) instead of polling a dead service and resumes automatically when it comes back.

Playback uses pygame-ce (pygame module). Without it the reader only logs the text. Phrases are queued and spoken one after another, so a long task keeps a fluid conversation instead of cutting mid-sentence. Sending a new message (or pressing ESC) stops the current narration and drops the queue, so the voice always follows the conversation.

When running the OpenCode TUI plugin (.opencode/plugins/tui/), the plugin owns the desktop app's lifecycle: it starts opencode-voice automatically when the TUI opens and stops it on close (desktopApp option — the Windows exe path as seen from WSL), so the reader never needs to be launched by hand. An instance you started manually is detected and left alone.

Performance metrics

Every stage of the voice pipeline is timed and logged, so you can see where the seconds go when something feels slow. Stages measured:

Stage What it measures
model-load loading the whisper model (once, at startup)
transcribe faster-whisper inference for one utterance
connect connecting to the OpenCode service (when needed)
send delivering the text to OpenCode (session resolution + HTTP)
poll the TTS watcher's session message fetch
summarize the LLM /api/generate call that condenses the reply
synthesize edge-tts turning the summary into an MP3 file
play pygame playing the audio back (≈ the spoken phrase length)

Each handled item logs a breakdown line, e.g.:

[metrics] INFO tts-audio cycle 6.5s = synthesize 3.9s + play 2.6s
[metrics] INFO utterance cycle 1.4s = transcribe 1.2s + send 0.2s

and every 50 records a summary with count/avg/min/max/p95 per stage (slowest average first). Disable with logging.metrics: false.

Metrics dashboard

Every timing sample is also appended to a JSONL file (~/.config/opencode-voice/metrics.jsonl by default) — one line per measurement, including the per-utterance cycle:utterance total and a queue-wait sample that measures how long an utterance sat in the worker queue (visible when whisper is busy). To watch the latency trend live:

opencode-voice dashboard

This starts a tiny local server, opens a page in your browser and refreshes it every 2 seconds. The page shows a summary per stage (count/avg/p95 + whether the latency is improving or getting worse) and a chart of each stage over time (raw samples + moving average + moving p95) — pick the stage with the buttons above the chart. The bottom panel shows the tail of the app log (when logging.log_file is set). Options: --port 8611, --no-browser. To change the data source: logging.metrics_path.

Troubleshooting

Problem Solution
hotkey active does not appear Windows with elevated (admin) terminal? Hotkeys from non-elevated processes do not reach elevated windows. Run opencode-voice as admin or the terminal without elevation.
OpenCode not detected at startup Run opencode2 (TUI) first; check service.json (section above). The app reconnects before each send.
Message went to the wrong session Check the detected directory in the log ([voice] detected TUI directory: ...) and set opencode.directory if needed.
Message created a new session The TUI was open but had no session in that directory; the app creates one. Normal on first use.
autoSubmit: false and text landed in another app The Ctrl+V goes to the focused window. Focus the TUI terminal before stopping the recording (or use autoSubmit: true).
Nothing recognized Speak slower/clearer; switch the model (small → medium); check the microphone (below).
Model does not load Check the network on the first run (model download) and disk space.
Tray missing pystray can fail in some environments; use the hotkey (main) or --no-tray to suppress it.
Notifications not showing notifications.enabled: true; toasts require Windows 10+. The fallback is the log.

OpenCode connection troubleshooting

  • Make sure OpenCode is running inside WSL and the service is registered: opencode2 service status (inside WSL).

  • From Windows, test http://localhost:<port>/api/health in the browser. If it does not respond, test the WSL IP: wsl.exe hostname -I.

  • If OpenCode runs outside WSL (natively on Windows), the app reads %USERPROFILE%\.local\state\opencode\service.json as a fallback.

  • For a fixed instance (e.g., remote), set:

    opencode:
      port: 4096
      host: localhost

Changing microphone

recording:
  device: default        # default Windows microphone

To list devices (Windows):

python -c "import sounddevice as sd; print(sd.query_devices())"

Use the index (number) or the name in recording.device:

recording:
  device: 2              # or "Microphone (Realtek Audio)"

Changing Whisper model

transcription:
  model: small   # tiny | base | small | medium | large-v3
  language: pt   # "auto" to detect

Bigger models = more accurate and slower. language: auto disables the language lock. Changing the model requires restarting opencode-voice (the model stays loaded in memory).

Structure

src/opencode_voice/
├── app.py            Application: orchestration + state machine + mutex
├── state.py          StateMachine (IDLE/RECORDING/TRANSCRIBING/SENDING/CANCELLED)
├── config.py         Config (pydantic) + YAML loading
├── hotkey.py         GlobalHotkey (pynput)
├── notifier.py       Notifier (winotify / log)
├── tray.py           Tray (pystray)
├── audio/recorder.py Recorder (sounddevice, in-memory buffer)
├── transcription/    Transcriber + FasterWhisperTranscriber + vocabulary
├── tts/              text → speech-friendly (summarizer + rule-based text)
└── opencode/         discovery + client (httpx) + injector (PromptInjector)

Detailed documentation: docs/architecture.md and docs/opencode-integration.md.

TUI plugin (opencode-voice-tui)

Besides the Windows app, there is a TUI plugin in tui-plugin/ that runs inside OpenCode — no external application: keybind in the TUI, Python worker (mic via WSLg + faster-whisper), and sending via client.session.prompt in the active session. See tui-plugin/README.md.

Windows app TUI plugin
Installation pip install copy 2 files to .opencode/plugins/tui/
Hotkey global only with TUI focused
Microphone native Windows WSLg PulseAudio
Send to chat ✓ ✓
Tray ✓ ✗

Roadmap

  • Official tui.prompt.append injector when OpenCode exposes the publication
  • Standalone packaging (PyInstaller) for distribution
  • VAD improvements (Silero) to reduce broken phrases in noise

License

MIT

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages