Skip to content

Instantly share code, notes, and snippets.

@Siedrix
Created November 17, 2026 00:11
Show Gist options
  • Select an option

  • Save Siedrix/c0ff3fbfb653887576ec05dca37ac8fe to your computer and use it in GitHub Desktop.

Select an option

Save Siedrix/c0ff3fbfb653887576ec05dca37ac8fe to your computer and use it in GitHub Desktop.
Harness
# Prompt 2: Claude Code sessions from the UI, with a configurable workflow
> How to use: run this in the app built with `01-electron-shell.md`. Say "Follow @~/playground/elektron/playbook/02-claude-sessions.md". Claude will interview you about your workflow before it builds anything.
> Distilled from Raven (see Raven's `desktop/src/claude.js`, `terminal.js`, `sessions.js`, `renderer/chat-panel.js`, `renderer/chat-render.js`, `docs/specs/sessions.md`, `docs/specs/claude-chat.md`).
---
Add **sessions** to this app: I create a session from the UI, chat with Claude Code inside it, and the session moves through the stages of a **workflow**. The workflow is **data, not code**, so this app can use one flow and another app (or project) a different one. Raven's flow was *plan → build in a git worktree → move to branch → PR*. The first app I'll use this for is **writing blog posts**, so the flow will be different.
## Step 0: interview me first (required)
Before planning, ask me about my workflow. Use short batches of questions (3 or 4 at a time, with suggested answers I can pick), and keep going until each stage is defined. At least cover:
1. **The thing a session produces.** A blog post? A Markdown file in a git repo, a draft in a CMS, something else? Where does it live, and what's its frontmatter (title, slug, date, tags, cover image, status)?
2. **The stages, in order,** and for each one:
- its name and goal (for example idea → research → outline → draft → edit → publish);
- what Claude does in it and what it must **not** do (for example "don't write prose in the outline stage");
- the files it may write (an allowlist of globs) and the tools it gets (web search? Bash? none?);
- what it produces (an outline file, a draft, a list of sources);
- the **exit condition**, and who moves it on: me with a button, Claude asking me, or automatic;
- whether it can go back to an earlier stage.
3. **Isolation.** Should each post get its own git worktree and branch (like Raven) or work in the main folder? Does "PR" map to anything (a review PR on GitHub, a preview deploy, nothing)?
4. **My voice.** Is there a style guide, past posts to learn from, or words to avoid? Where should that live so every stage reads it (a `STYLE.md`, a skill)?
5. **Review and publishing.** Who reviews, what "published" means, and whether the app should do the publishing step or just hand off.
6. **Interaction.** Which stages are a chat with me, and which should run on their own and notify me when they're done?
Write the answers into the plan as the first workflow definition. Then show me the plan and wait for my OK.
## Workflow as data
- A workflow is a file the app reads, for example `workflows/<id>.json` (or YAML) in the project or the app's `userData`. Sketch:
```jsonc
{
"id": "blog-post", "version": 1,
"stages": [
{
"id": "outline", "title": "Outline",
"goal": "Agree on the structure before any prose",
"mode": "chat", // "chat" (turn-by-turn with me) or "agent" (runs until done)
"systemPrompt": "prompts/outline.md", // stage instructions, a file so I can edit it
"tools": ["Read", "Write", "Edit", "Glob", "Grep", "WebSearch"],
"writable": ["posts/{slug}/outline.md"],
"produces": ["posts/{slug}/outline.md"],
"exit": { "by": "user", "label": "Start drafting" },
"next": "draft", "back": ["research"]
}
]
}
```
- The session record (in the local store from prompt 1) holds: `id`, `title`, `workflowId`, `stage`, `folder`/`worktree`, `branch`, artifact paths, `claudeSessionId` if used, timestamps, and a `history` of stage moves.
- **Stage moves are compare-and-set in main:** `moveStage(id, from, to)` fails if the session isn't in `from` anymore, and only transitions the workflow allows are accepted. Raven learned this the hard way: two windows both started a build, and an old chat kept offering actions for a stage that had already moved on. The current stage is the **single source of truth**: the UI derives everything (which panel, which buttons, which board column) from it.
- Each stage's system prompt is built in **main**, from the workflow file plus session data, never from text the renderer sends.
- Add a **Board** view (a column per stage) and a session page (a stepper showing the stages, the chat, and a side column with the stage's artifacts and its exit button).
## Running Claude Code
Raven spawns the user's own `claude` CLI, so it needs no API key and uses the user's Claude Code login and settings. Keep that approach unless the interview shows a reason to change. In the plan, also weigh the **Claude Agent SDK** (`@anthropic-ai/claude-agent-sdk`: resumable sessions, streaming input, a `canUseTool` callback for permission cards, in-process MCP tools); check its current auth requirements and tell me the trade-off.
**Chat turns (headless):** each turn is one process:
```ts
const args = [
'-p', '--output-format', 'stream-json', '--verbose', '--include-partial-messages',
'--strict-mcp-config', // don't load the user's MCP servers
'--tools', stage.tools.join(','),
'--allowedTools', allowedRules.join(','), // e.g. Edit(posts/my-slug/**)
'--append-system-prompt', systemPrompt,
'--model', modelAlias,
]
const child = spawn(claudeBin, args, { cwd: session.folder, env: childEnv(), stdio: ['pipe', 'pipe', 'pipe'], detached: true })
child.stdin.end(prompt) // prompt on stdin: long histories don't fit in argv
```
- History: either pass `--no-session-persistence` and resend the whole conversation each turn wrapped in `<conversation_history>` (Raven caps it at about 400k characters, keeping the newest), or use `--session-id`/`--resume`. Pick one in the plan.
- Parse stdout line by line into a small event union and stream it to the renderer over IPC (`claude:event`, keyed by a validated stream id, sent only to the window that started it): `stream_event` text deltas → `{kind:'text'}`, `tool_use` → `{kind:'tool', name, input}`, `tool_result` → `{kind:'tool-done', error, denied}`, a `result` with `is_error` → `{kind:'error'}`, and always a final `{kind:'done'}`.
- Headless mode can't ask for approval, so any tool call outside the allow rules is just refused. Detect the refusal in the result and tell me in the UI why it happened.
- **Stop:** the child is `detached` (its own process group). Send `SIGTERM` to the group (`process.kill(-pid)`), then `SIGKILL` after 3 s. Don't report the resulting exit code 143 as an error. Kill all children on quit.
- Short one-shot helpers (titles, commit messages, summaries): `claude -p --output-format json --tools '' --system-prompt ...`.
**Agent stages (long-running):** if a stage should run on its own (for example "write the full draft"), run interactive `claude` in a PTY (`node-pty`, rendered with xterm.js or ghostty-web), started with `--session-id <uuid>` and later `--resume <uuid>`.
- Detect "finished" and "needs permission" with Claude Code **hooks**: write a settings file with `Stop` and `Notification` hooks that append their JSON input to a per-app events file, pass it with `--settings`, and `fs.watch` that file in main.
- Gotcha: `--mcp-config` accepts several files and swallows the next argument, so put `--session-id`/`--resume` and the prompt after it.
- Send text to a running PTY as a bracketed paste (`\x1b[200~` + text + `\x1b[201~`), then `\r` about 60 ms later.
**Questions from Claude: options cards.** Instead of a special tool, the stage system prompt tells Claude to ask choices with a fenced block:
````
```options
? Which angle should the intro take?
Personal story (recommended)
Problem first
```
````
The renderer turns all such blocks in one reply into **one** card with a button per option and an **Other…** field per question. Picks can be changed until **Submit**, which sends `Go with: <label>` (or `<question>: <label>` per line). If I type a message instead, the card marks itself "Not picked". While a reply is streaming, hide the card's buttons (don't just disable them) and show "Waiting for Claude…". Raven tried detecting numbered lists first, which was too fragile.
## Git worktrees (if the interview says yes)
- Worktrees go under the app's own root, for example `~/.<app>/sessions/<repo>/<id8>`, on a branch made from a freshly fetched `main`: `git branch --no-track <branch> origin/main`, then `git worktree add <folder> <branch>`.
- **Time-box every git call** (Raven uses 20 s per call, 30 s per step) and disable auto gc in them. A stuck hook once froze a whole stage move.
- Commit stage artifacts after each turn (`git add <paths>`, never `git add -A`).
- Raven's final lesson: don't open PRs from throwaway worktree branches. Finish the build in the worktree, then a guided **Move to branch** step switches the real project folder to a named branch (only if the folder is clean), copies uncommitted files and Claude transcripts so `--resume` still works, removes the worktree, and continues there. The app never switches my project folder without me clicking.
- PRs via `gh pr create --draft --base <base> --head <branch> --title <t> --body-file -`. Guard against the throwaway branch pattern in code, not only in the prompt.
## Chat UI
- A reusable `<ChatPanel>` (messages + composer) used by every chat. Render Markdown with `marked` (or `react-markdown`) and **sanitize** it (DOMPurify). Highlight code. Show tool calls as compact rows (name + a one-line summary of the input, expandable).
- A shared `<Composer>`: autosizing textarea, Enter sends and Shift+Enter adds a line, Send turns into **Stop** while a reply runs, a model select, attachments, a per-session draft saved to `localStorage` (debounced 300 ms). Leave a slot for the dictation button from prompt 3.
- Attachments are sent as path lines that Claude opens with Read (`[Image: /abs/path]`, `[File: /abs/path]`). Copy files from outside the project into a private temp dir (`0700`, files `0600`) and clean up after 24 h.
- Sessions are created on the **first send**, not when I open "New session". Creating them eagerly left orphans after crashes.
- Notify me (Electron `Notification` + dock badge, and an unseen dot in the UI) when a turn ends while the window isn't focused. Notify **before** running post-turn jobs (commits, store updates), and give each of those jobs a timeout: one hung job once swallowed every notification.
## Done when
1. The interview answers are in the plan, and `workflows/blog-post.json` (plus its stage prompt files) encodes them.
2. I can create a session from the UI, chat in the first stage, answer an options card, and move through every stage with the exit buttons; going to a stage the workflow forbids is rejected.
3. Stop works mid-reply, and nothing is left running after quitting the app.
4. Sessions and their stages survive a restart. The Board shows them in the right columns.
5. A second workflow file (for example a 2-stage "quick note") works without code changes.
6. Specs describe sessions, the workflow format and the chat, and a module file lists the manual tests.
# Prompt 1: Electron shell (local state, React, frameless chrome)
> How to use: start Claude Code in an empty folder and say "Follow @~/playground/elektron/playbook/01-electron-shell.md" (or paste everything below the line). Fill in the `<APP_NAME>` placeholders first, or let Claude ask.
> Distilled from how Raven was built (see Raven's `desktop/src/main.js`, `preload.js`, `renderer/titlebar.js`, `docs/specs/projects.md`).
---
You are scaffolding a new desktop app called **<APP_NAME>**: an Electron app for macOS (first) that keeps all of its state locally. There is **no server and no database service**. The Electron main process owns the state and persists it to disk. The renderer is **React + TypeScript + React Router + shadcn/ui**.
Before writing code, ask me (in one batch of questions) anything you need that isn't covered here: the app's name, its first screens, and the main entities it stores. Then write a short plan, wait for my OK, and build it.
## Stack
- **pnpm** workspace (never npm or yarn). Pin `packageManager` in the root `package.json`. pnpm 10+ blocks dependency build scripts, so allow them in `pnpm-workspace.yaml` (`allowBuilds: { electron: true }`, plus any native module you add, like `node-pty`).
- **electron-vite** for main, preload and renderer builds (one config, HMR for the renderer, TypeScript everywhere). Latest stable Electron.
- Renderer: React 19, TypeScript (strict), **React Router** with `createHashRouter` (the app loads from `file://` in production, where browser-history routes break), **Tailwind v4 + shadcn/ui** (init with the shadcn CLI, add components as needed, `lucide-react` icons). Dark theme by default.
- Main and preload in TypeScript too. Main is the only place that touches the filesystem, child processes and native APIs.
## Process boundaries and IPC
- `webPreferences`: `contextIsolation: true`, `nodeIntegration: false`, `sandbox: true`, a `preload` script. The preload only uses `contextBridge`, `ipcRenderer` and `webUtils`.
- Expose **one** global, `window.<appName>`, namespaced by domain: `window.app.projects.list()`, `window.app.window.onLightsChange(cb)`, and so on. Put its type in a shared `src/shared/api.ts` so the renderer gets full types (`declare global { interface Window { app: AppApi } }`).
- IPC channel names are `domain:verb` (`projects:list`, `projects:create`, `store:changed`).
- Request/response: `ipcMain.handle` + `ipcRenderer.invoke`.
- Fire-and-forget streams (keystrokes, resize): `ipcMain.on` + `ipcRenderer.send`.
- Push events: `event.sender.send(...)` to the window that asked, never broadcast blindly.
- Write two preload helpers:
- `invoke(channel, ...args)`: strips Electron's `Error invoking remote method '…':` prefix so the UI shows clean messages. If the error says "No handler registered", throw "Restart the app to load this feature" (this happens when main changed but only the renderer reloaded).
- `subscribe(channel, cb)`: returns an unsubscribe function, for use in `useEffect` cleanups.
- Validate and coerce every IPC argument in main (strings, ids by regex, size limits). Handlers return data or throw `Error`s with user-facing messages.
## Local state
- A small store module in main: `src/main/store.ts`. One JSON file per collection (or one `state.json`, your call; say which in the plan) under `app.getPath('userData')`.
- Every write is **atomic**: write `.<name>.<random>.tmp` with `flag: 'wx'`, then `fs.rename` over the target, and remove the temp file on error. Serialize writes per file through a promise queue so two quick saves can't interleave. Keep a schema `version` field and a `migrate()` step from day one.
- Main loads the store at startup, keeps it in memory, and after each change sends `store:changed` (with the collection name) to all windows. In the renderer, a tiny hook (`useStore('projects')`) refetches on that event. Don't add a state library unless the plan shows a need.
- Use `localStorage` only for throwaway UI conveniences (last tab, draft text). Anything that matters goes through the store.
- If the app later needs real queries, SQLite (`better-sqlite3`) is the upgrade path. Don't start with it.
## Window chrome: no title bar, traffic lights on hover
The top bar wastes space and looks heavy. The window has **no title bar**, and the macOS traffic lights (close/minimize/zoom) appear **only when the mouse hovers over the top-left corner**.
Main (`BrowserWindow`):
```ts
new BrowserWindow({
width: 1100, height: 780, show: false,
backgroundColor: '#1c1c1e', // match the CSS --background, so there's no white flash
...(process.platform === 'darwin' && {
titleBarStyle: 'hidden',
trafficLightPosition: { x: 20, y: 26 }, // vertically centred in a 64px header
}),
webPreferences: { /* as above */ },
})
win.once('ready-to-show', () => win.show())
```
- Right after creating the window, call `win.setWindowButtonVisibility(false)`.
- Hover zone: `LIGHTS_ZONE = { width: 96, height: 64 }` in window coordinates. The renderer has an invisible absolutely positioned `div` there. On `pointerenter` it sends `window:hover-lights`.
- On that message, main shows the buttons, sends `window:lights` `true` to the renderer, and then **polls** `screen.getCursorScreenPoint()` every 100 ms against the window bounds. When the cursor leaves the zone, it hides the buttons, sends `false` and stops polling. You must poll because the page gets no pointer events while the cursor is over the native buttons.
- Full screen: on `enter-full-screen` force the buttons visible (macOS shows them in its slide-down bar). On `leave-full-screen` hide them again.
- While the lights are visible, the renderer fades out whatever sits under them (the logo) with `opacity: 0` and a short transition.
- Other platforms: keep the normal frame for now (or `titleBarOverlay` on Windows later). Expose `window.app.window.lights` only on darwin, and add a `frameless` class on `<body>` only then.
Renderer layout and drag regions:
- The top `<header>` (64px, same height as `LIGHTS_ZONE`) holds the lights zone, the logo, the main nav (React Router `NavLink`s styled as tabs) and a settings button. It is the window's drag handle:
```css
.frameless header { -webkit-app-region: drag; user-select: none; }
.frameless header :is(button, a, input, [role="tab"]) { -webkit-app-region: no-drag; }
.lights-zone { position: absolute; left: 0; top: 0; width: 96px; height: 64px; -webkit-app-region: no-drag; }
```
Leave a left padding of about 96px in the header so content doesn't sit under the lights.
- Gotcha: shadcn popovers, dropdowns and dialogs render in a portal. Make sure they're outside the drag region or have `no-drag`, otherwise clicks fall through to window dragging. Put `no-drag` on `[data-radix-popper-content-wrapper]` and `[role="dialog"]`.
- Gotcha: don't style a bare `header` element globally. Raven's global `header` rule later clipped an in-page `<header>`. Use a class (`.app-header`), and use `<div>` for inner headers.
## Safety and app behaviour
- `setWindowOpenHandler`: deny, and open `http(s)` URLs with `shell.openExternal`. In `will-navigate`, call `preventDefault()` unless it's a reload.
- Permission handlers (`session.setPermissionRequestHandler` and `setPermissionCheckHandler`): without them Electron grants everything. Allow only what the app uses, and only for the app's own origin.
- Handle `dragover`/`drop` on the document. An unhandled file drop navigates the window to that file. Use `webUtils.getPathForFile(file)` in the preload to get a path (`File.path` is gone in recent Electron).
- `nativeTheme.themeSource = 'dark'`. Set the dock icon in dev with `app.dock?.setIcon(...)`.
- macOS lifecycle: re-create the window on `activate`, quit on `window-all-closed` only off macOS, clean up child processes on `before-quit`.
- **PATH gotcha:** an app launched from the Dock doesn't get the shell's PATH. When you spawn a CLI (git, gh, claude, brew tools), find it with a `findBinary(name)` helper: try `$SHELL -lc 'command -v name'`, then fall back to known dirs (`~/.local/bin`, `/opt/homebrew/bin`, `/usr/local/bin`). Build the child `env` with those dirs added to PATH. Test with fish as the login shell too.
- If the app was launched from inside Claude Code, strip `CLAUDECODE` and `CLAUDE_CODE_*` from child environments.
- Notifications in dev: the pnpm-installed `Electron.app` may be badly signed, and then every notification fails ("UNErrorDomain error 1"). Add a postinstall script that runs `codesign --verify --deep --strict` on it and, if that fails, `codesign --force --deep --sign -`. It must never fail the install.
- Native modules (only if added): rebuild them for Electron in postinstall (`electron-rebuild -f -w <module>`) and pin exact versions.
## Repo conventions (copy Raven's)
Create a `CLAUDE.md` that says:
- Use pnpm only. List the commands (`pnpm dev`, `pnpm build`, `pnpm typecheck`, `pnpm lint`).
- Every session starts on a new `<type>/<slug>` branch from the latest `main`. Commit, push or open PRs only when asked.
- When main or preload code changes, restart the app; a renderer reload alone isn't enough.
- Never kill processes by port (an Electron network process can share it); stop only the PIDs you started.
- Docs lifecycle:
```
docs/
├── roadmap/ plans not built yet
├── plans/ plans that were implemented (the record of intent)
└── specs/ how the system works now, edited in place
└── modules/ one file per product module: manual tests + a newest-first "Test runs" table
```
A plan has frontmatter (title, status, created, branches, prs, specs) and sections: Goal, Current behavior, Options considered, Proposed changes, Decisions, Tasks, Testing, Open questions. One plan, one branch, one PR. When a change alters behavior a spec describes, update that spec in the same branch.
## First milestone (what "done" looks like)
1. `pnpm install && pnpm dev` opens a frameless window, maximized or at the default size, dark, with no white flash.
2. The traffic lights are hidden, appear when the cursor enters the top-left corner, and hide again when it leaves. Full screen keeps them visible. Dragging the header moves the window; buttons and tabs in it still click.
3. Two routes (for example Home and Settings) switch with the header tabs. A shadcn Dialog and a DropdownMenu opened from the header both work and don't drag the window.
4. One sample entity (for example "projects" with a name and folder picked with `dialog.showOpenDialog`) can be created, listed and deleted. It survives a restart and is stored atomically under `userData`.
5. `pnpm typecheck` and `pnpm build` pass.
6. A `docs/specs/` file describes the window chrome and the store, and `docs/specs/modules/shell.md` lists manual tests for the five points above.
# Prompt 3: Speech to text in every chat
> How to use: run this in the app built with `01-electron-shell.md` and `02-claude-sessions.md`. Say "Follow @~/playground/elektron/playbook/03-dictation.md".
> Distilled from Raven (see Raven's `desktop/src/dictation.js`, `renderer/dictation.js`, `renderer/dictation-worklet.js`, `renderer/dictation-button.js`, `docs/specs/dictation.md`).
---
Add **local dictation** to every chat composer (and to any embedded Claude Code terminal): I click a mic (or press **Cmd+Shift+D**), talk, and the text lands in the composer for me to edit. Everything runs on this Mac. No audio leaves it. Write a plan first and wait for my OK.
## Engine: whisper.cpp CLI
- Use **`whisper-cli` from whisper.cpp**, installed by me with `brew install whisper-cpp`. The app doesn't bundle or build it. Find it with the `findBinary` helper from prompt 1 (a login shell's `command -v`, then `/opt/homebrew/bin` and other known dirs).
- Model: **`ggml-base.en.bin`** (about 142 MB) from `https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-base.en.bin`, stored in `~/.<app>/models/`. Download it only when I ask:
- stream to `<name>.part` and rename when complete, and treat a short download as an error;
- a second request while one runs joins it, and its window also gets progress;
- send progress (`dictation:progress {received, total}`) at most every 100 ms;
- delete a leftover `.part` at startup.
- Make the model a setting with `base.en` as default (`small.en` is the more accurate option). If I speak Spanish too, ask me whether to use a multilingual model and pass `-l auto` or a language.
- Rejected in Raven, don't use: Node whisper addons (another native module to rebuild for Electron, and they lag behind whisper.cpp), transformers.js/WebGPU in the renderer (slow, heavy, blocks the UI), a Swift `SFSpeechRecognizer` helper (a build step, Mac only, no model choice), and the Web Speech API (sends audio to Google and doesn't work in Electron).
- Known cost: the model reloads for every clip (about 0.3–0.5 s). If that becomes annoying, the upgrade path is a long-running `whisper-server`.
## Capture (renderer)
- `getUserMedia({ audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true }, video: false })`.
- `new AudioContext({ sampleRate: 16000 })`. If the browser refuses that rate, use the default rate and resample linearly to 16 kHz.
- An **AudioWorklet** posts Float32 blocks to the page. It must be its **own file** loaded by URL: a CSP with `script-src 'self'` blocks `blob:` worklets. (With Vite, import it with `?url`.) Don't use MediaRecorder: it gives compressed formats whisper can't read directly.
- On stop, concatenate the blocks and encode a **16 kHz, 16-bit PCM, mono WAV** by hand (a 44-byte header plus samples).
- Report an input level about 30 times a second (RMS × 4, smoothed with decay 0.85) for the mic animation.
- Hard stop at **2 minutes**. Never send clips shorter than 0.25 s.
- On stop or cancel, stop every track, so the macOS mic indicator goes off. Use a generation counter so a `start()` that is still waiting for permission is aborted if I cancel.
## Transcription (main)
- IPC `dictation:transcribe` takes the WAV as a `Uint8Array`. Validate it: between 44 bytes and 16 MB, with a `RIFF` header.
- Write it to `$TMPDIR/<app>-dictation/<uuid>.wav`, run `execFile(whisperCli, ['-m', model, '-f', wav, '-l', 'en', '-nt', '-np'], { timeout: 60_000, maxBuffer: 4 MB, env: childEnv() })`, and **always** delete the WAV afterwards. Log nothing about the content.
- Serialize transcriptions through a promise queue.
- Clean the output: remove `[BLANK_AUDIO]`, `(silence)`, `[MUSIC]` and similar markers, and trim. Empty → the UI says "Didn't catch anything."
- Errors: the first line of stderr, or "Transcription took too long." on timeout.
## Electron permissions
- Mic status: `systemPreferences.getMediaAccessStatus('microphone')` (treat it as granted on Linux). Ask with `systemPreferences.askForMediaAccess('microphone')`. macOS only asks once; after a denial, offer **Open Privacy Settings**, which opens `x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone` with `shell.openExternal` from main.
- The permission handlers from prompt 1 must allow `media` only when every requested media type is `audio` and the request comes from the app's own origin.
- In dev (`pnpm dev`), macOS attributes mic access to the **terminal app** that launched Electron, so grant it there. A packaged build needs `NSMicrophoneUsageDescription` in its Info.plist; add it to the packaging config if there is one.
- IPC: `dictation:status` (`{ cli: {installed, path}, model: {present, path, bytes}, mic }`, with a `refresh` flag), `dictation:ask-mic`, `dictation:open-privacy`, `dictation:download-model`, `dictation:transcribe`, and the `dictation:progress` event.
## UI: one shared hook and button
- `useDictation()` hook (capture + transcribe + state) and a `<DictationButton>` component built on it. Every composer and terminal uses them; don't copy the logic per screen (Raven extracted it after the second copy).
- States: `idle` → `recording` → `transcribing` → `idle`. While recording, the button shows a ring whose size follows the level (a CSS variable). While transcribing, a spinner and the button is disabled. Errors and "Didn't catch anything." show as a small note under the composer.
- Interaction is a **toggle**, not hold-to-talk (easier on a trackpad):
- click or **Cmd+Shift+D** starts;
- click, Cmd+Shift+D or **Enter** stops and inserts;
- **Esc** cancels and drops the audio.
- While recording, the placeholder reads "Listening… ↵ to insert, esc to cancel", and Enter must **not** send the message.
- **Never auto-send.** Insert at the cursor: replace the selection, add a leading space unless the text before ends in whitespace, put the caret after the inserted text, refit the textarea and focus it.
- Shortcut scope: only the visible composer responds to Cmd+Shift+D (ignore it while a dialog is open). If a page shows several composers, only the one with focus responds.
- Cancel the recording when its composer leaves the screen (an IntersectionObserver), is disabled, or its draft is discarded; drop any transcript that arrives for a cancelled run (a run id).
- **Setup popover** opened by the mic when something is missing, one row each:
1. whisper.cpp: the `brew install whisper-cpp` command with a copy button and **Check again**;
2. the model: **Download** with a progress bar (progress shared by all mic buttons);
3. the microphone: **Allow**, or **Open Privacy Settings** if denied.
Re-check when the window regains focus. When everything is ready, close it and note "Dictation is ready".
Also show a Dictation row in Settings with the same status.
- If a `NotAllowedError` happens later (permission revoked), reset the ready state so the next click re-checks.
## Embedded terminals (if the app has them)
- Put the mic next to the terminal and show it only while the session is running.
- Listen in the **capture phase** and stop propagation for Enter/Esc while recording; otherwise Esc interrupts Claude Code and Enter sends.
- Insert as a bracketed paste with a trailing space and **no** Enter: `\x1b[200~${text} \x1b[201~`.
- Remember which session was showing when recording started, and drop the text if that session is no longer shown or running.
## Done when
1. With whisper.cpp missing, the mic opens the setup popover; after installing it and downloading the model, it says ready.
2. Click, talk, click: the text appears at the cursor in the session chat and in every other composer, and isn't sent. Enter inserts, Esc cancels, Cmd+Shift+D works only in the visible composer.
3. The mic indicator in the macOS menu bar turns off after each clip, and no WAV is left in the temp folder.
4. Denying the mic shows the Open Privacy Settings path.
5. A spec (`docs/specs/dictation.md`) and a module file with manual tests. Note that a real transcript can only be tested by hand with a real mic; automated checks can only cover the popover and states.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment