Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
name: CI
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
native:
name: Native macOS
runs-on: macos-15
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
- run: scripts/test-native.sh
- run: scripts/build-app.sh
- run: python3 scripts/check-distribution.py
worker:
name: Worker
runs-on: ubuntu-latest
timeout-minutes: 10
defaults:
run:
working-directory: worker
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: npm
cache-dependency-path: worker/package-lock.json
- run: npm ci
- run: npm test
- run: npm run typecheck
- run: npm run build
local-api:
name: Local API
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- run: python -m unittest discover -s local-stt -v
- run: python scripts/check-distribution.py
28 changes: 28 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
.build/
.build-cache/
dist/
worker/node_modules/
worker/.wrangler/
worker/.dev.vars*
*.log
.DS_Store
work/

__pycache__/
.pytest_cache/

# Private/runtime data must never enter Git history.
.env
.env.*
!.env.example
*.pem
*.key
worker-secrets.json
secrets.json
service-config.json
.runtime/
.venv/
venv/
models/
recordings/
history.json
30 changes: 30 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Contributor instructions

ClearFlow is an independent macOS dictation app with self-hosted transcription.
No proprietary application code or assets belong here.

## Architecture

- `Sources/ClearFlow`: SwiftUI/AppKit capture, shortcut, settings, authenticated API client and guarded paste.
- `Sources/ClearFlowCore`: pure lifecycle, meter and endpoint validation.
- `local-stt`: loopback HTTP API backed by MLX Whisper on Apple Silicon.
- `worker`: optional Cloudflare Workers AI Nova 3 API, deployed to each operator's own account.
- `docs/media`: reproducible UI renders using synthetic content only.

## Workflow

Read README.md and the relevant backend README before editing. Inspect branch, remote and uncommitted work. Use focused feature/fix branches, coherent commits and PRs; do not push implementation directly to main or force-push shared history. Push completed work and verify the remote SHA. Review the diff and wait for current-revision CI before an authorized merge. Sync the local default branch afterward.

Never commit credentials, actual service endpoints, account IDs, local machine paths, personal transcripts, recordings, runtime logs, caches, dependencies or weights. Examples use localhost or reserved example domains. Release builds must contain only the loopback default. Use anonymous synthetic fixtures in documentation and demos. Keep private operational notes outside this repository.

## Validation

```sh
scripts/test-native.sh
scripts/build-app.sh
python3 -m unittest discover -s local-stt -v
python3 scripts/check-distribution.py
cd worker && npm ci && npm test && npm run typecheck && npm run build
```

CI checks native compilation/core behavior, local HTTP/setup contracts, Worker tests/types/dry-run and distribution privacy rules. Real microphone capture, cross-app insertion and model inference require device validation; never claim those from mocked tests. Never bypass macOS permissions. Public releases are ad-hoc signed until a maintainer supplies Developer ID signing and notarization.
13 changes: 13 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// swift-tools-version: 6.0
import PackageDescription
let package = Package(
name: "ClearFlow",
platforms: [.macOS(.v14)],
products: [.executable(name: "ClearFlow", targets: ["ClearFlow"])],
targets: [
.target(name: "ClearFlowCore"),
.executableTarget(name: "ClearFlow", dependencies: ["ClearFlowCore"]),
.executableTarget(name: "ClearFlowCoreChecks", dependencies: ["ClearFlowCore"], path: "Tests/ClearFlowCoreTests")
],
swiftLanguageModes: [.v5]
)
95 changes: 94 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,96 @@
# ClearFlow

Independent macOS dictation with self-hosted local Whisper.
**Speak naturally. Keep your words on your own hardware.**

ClearFlow is an open-source macOS menu bar dictation app. Press **Option–Shift–Space**, speak, and press again to transcribe into the selected text field. Run **Whisper large-v3-turbo locally through MLX** on your own Apple Silicon Mac. You can also use another Mac you control, or explicitly configure your own Cloudflare Workers AI Nova 3 service.

No account with ClearFlow, bundled hosted service, or automatic cloud fallback. Independent project; not affiliated with Wispr.

![ClearFlow app with synthetic sample dictation](docs/media/screenshot.png)

## Demo

![ClearFlow UI walkthrough: select a field, speak, transcribe, insert](docs/media/demo.gif)

The walkthrough renders the app’s actual recording-bar component with synthetic text and waveform data. It illustrates the interaction; it is not a recording of live transcription or a latency benchmark. The screenshot uses sample history only. [Reproduce these visuals](docs/media/README.md).

## Run it yourself — local Whisper

You need an **Apple Silicon Mac (M1 or newer), macOS 14+, Python 3.12**, and several GB of free disk space for the model and dependencies. Source builds need Xcode 16+ or compatible Command Line Tools with Swift 6. The native app and bundled MLX backend do not currently support Windows or Linux; other compatible backends may be added separately.

### 1. Get the app and source

Download `ClearFlow-macOS-arm64.zip` from [Releases](../../releases), extract it and move ClearFlow.app to Applications. Download the matching source archive, or clone this repository. Open a terminal in the source directory.

Alternatively, build it yourself:

```sh
scripts/build-app.sh
```

This creates `dist/ClearFlow.app`. Builds are ad-hoc signed, **not notarized**. macOS may require explicit approval in System Settings → Privacy & Security. Review/build the source if preferred; do not disable Gatekeeper. The downloadable app contains no model or access credentials.

### 2. Install and start Whisper

```sh
python3.12 local-stt/setup.py
python3.12 local-stt/run.py
```

Setup installs pinned Python dependencies and downloads the pinned open-weight model from Hugging Face. It creates a unique token in your private runtime directory. The service then runs on `http://127.0.0.1:8768` in offline model mode. Leave this terminal running; cold startup can take a moment.

In another terminal:

```sh
curl --fail http://127.0.0.1:8768/health
python3.12 local-stt/run.py --configure-app /Applications/ClearFlow.app
# For a source build, use --configure-app dist/ClearFlow.app instead.
```

The configuration command sends the token directly into macOS Keychain without displaying it or putting it in command-line arguments. Run it from your logged-in macOS desktop terminal so Keychain is available. Restart ClearFlow after configuring it. No Cloudflare account or Tailscale installation is needed for same-Mac use.

### 3. Dictate

1. Open ClearFlow. In Settings → General, allow Microphone and Accessibility through the normal macOS prompts.
2. Select an editable field in another app. Press **Option–Shift–Space** to start; the compact meter follows microphone input.
3. Speak, then press the shortcut again. Keep the selected field and cursor unchanged while transcription runs.
4. If insertion cannot be verified or the destination changed, ClearFlow keeps the transcript on the clipboard for manual paste. Check the app’s status for details.

The recording limit is 4 minutes 55 seconds. Cancel with the overlay’s ×; pressing the shortcut while processing cancels delivery. Retry returns text for review and never pastes at an old cursor.

[Full local setup, custom storage, startup at login, remote Mac and troubleshooting](local-stt/README.md).

## Optional: your own Cloudflare service

Deploy the supplied Worker in **your own account**, generate your own secret, and enter its HTTPS endpoint/token in Settings → Transcription. See [Worker setup](worker/README.md). This uses Deepgram Nova 3 on Cloudflare Workers AI and sends audio to Cloudflare; usage charges may apply. There is no preconfigured hosted endpoint.

## Privacy

- The only bundled endpoint is loopback. Audio and vocabulary go only to the address you explicitly configure. No automatic provider fallback.
- Local Whisper holds request audio in memory and does not log audio or transcripts. Setup downloads dependencies/model weights; runtime uses the local model with Hugging Face offline mode.
- Recording uses temporary WAV files, deleted on normal finish/cancel. A crash can leave a temporary file. Failed requests may keep audio in memory for retry.
- Field content is read locally to guard insertion and is not uploaded. Known secure fields are rejected.
- History is memory-only by default. Opt-in saved history stores up to 50 transcripts on your Mac. Clipboard fallback leaves the transcript available until replaced.
- Your endpoint is stored in macOS preferences; the token is stored in Keychain. Keep credentials, recordings, personal endpoints and runtime data out of Git.

## Development

```sh
scripts/test-native.sh
scripts/build-app.sh
python3 -m unittest discover -s local-stt -v
python3 scripts/check-distribution.py
cd worker
npm ci
npm test
npm run typecheck
npm run build
```

CI validates native compilation/core checks, local API/setup tests, Worker tests/types/dry-run and distribution checks. Hardware inference, permissions and insertion across every editor are not proven by CI. [Contributor workflow](AGENTS.md).

The app currently transcribes after recording stops. Streaming partials, generative rewriting, correction learning and cross-device history sync are not implemented. The local backend uses MLX and requires Apple Silicon.

## License

[MIT](LICENSE). Third-party dependencies and model weights retain their own licenses; the model is downloaded separately. No proprietary Wispr code or assets are included.
53 changes: 53 additions & 0 deletions Sources/ClearFlow/AudioCapture.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import Foundation
import AVFoundation

@MainActor final class AudioCapture: NSObject, AVAudioRecorderDelegate {
private var recorder: AVAudioRecorder?
private var file: URL?
var onAutomaticStop: (() -> Void)?
var seconds: Double { recorder?.currentTime ?? 0 }
var level: Double {
guard let recorder else { return 0 }
recorder.updateMeters()
return max(0, min(1, (Double(recorder.averagePower(forChannel: 0)) + 55) / 55))
}
func start() throws {
let directory = FileManager.default.temporaryDirectory.appendingPathComponent("ClearFlow", isDirectory: true)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true,
attributes: [.posixPermissions: 0o700])
let url = directory.appendingPathComponent(UUID().uuidString).appendingPathExtension("wav")
let settings: [String: Any] = [
AVFormatIDKey: kAudioFormatLinearPCM, AVSampleRateKey: 16000,
AVNumberOfChannelsKey: 1, AVLinearPCMBitDepthKey: 16,
AVLinearPCMIsBigEndianKey: false, AVLinearPCMIsFloatKey: false
]
let r = try AVAudioRecorder(url: url, settings: settings)
r.delegate = self; r.isMeteringEnabled = true
guard r.prepareToRecord(), r.record(forDuration: 295) else {
try? FileManager.default.removeItem(at: url)
throw AppError.message("The microphone could not start. Check the selected input in System Settings.")
}
recorder = r; file = url
}
func stop() throws -> Data {
guard let recorder, let file else { throw AppError.message("No recording is active.") }
recorder.delegate = nil
recorder.stop()
self.recorder = nil; self.file = nil
defer { try? FileManager.default.removeItem(at: file) }
let data = try Data(contentsOf: file)
guard data.count > 8044 else { throw AppError.message("That recording was too short. Speak for at least a moment.") }
return data
}
func cancel() {
recorder?.delegate = nil; recorder?.stop(); recorder = nil
if let file { try? FileManager.default.removeItem(at: file) }
file = nil
}
nonisolated func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
Task { @MainActor [weak self] in self?.onAutomaticStop?() }
}
nonisolated func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) {
Task { @MainActor [weak self] in self?.onAutomaticStop?() }
}
}
113 changes: 113 additions & 0 deletions Sources/ClearFlow/ClearFlowApp.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import AppKit
import SwiftUI
import Combine
import ClearFlowCore

@main @MainActor enum ClearFlowMain {
static func main() {
let args = CommandLine.arguments
if args.count == 3 && args[1] == "--render-media" {
do { try MediaPreview.render(to: URL(fileURLWithPath: args[2])) }
catch { fputs("Media rendering failed\n", stderr); exit(1) }
return
}
if args.count >= 3 && args[1] == "--configure" {
guard let endpoint = Endpoint.validated(args[2]) else { fputs("Invalid endpoint\n", stderr); exit(1) }
let data = FileHandle.standardInput.readDataToEndOfFile()
let token = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
guard token.count >= 32 else { fputs("Provide the private service token on stdin\n", stderr); exit(1) }
do { try TokenStore.save(token); AppSettings.endpoint = endpoint.absoluteString; print("ClearFlow configured. Token stored in Keychain.") }
catch { fputs("\(error.localizedDescription)\n", stderr); exit(1) }
return
}
if args.count >= 3 && args[1] == "--transcribe-file" {
let path = args[2], endpoint = AppSettings.endpoint, token = TokenStore.read()
Task.detached {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path))
let reply = try await TranscriptionClient.transcribe(audio: data, id: UUID(), endpoint: endpoint,
token: token, language: "en", vocabulary: "")
print(reply.text); exit(0)
} catch { fputs("\(error.localizedDescription)\n", stderr); exit(1) }
}
dispatchMain()
}
let app = NSApplication.shared
let delegate = AppDelegate()
app.delegate = delegate
withExtendedLifetime(delegate) { app.run() }
}
}

@MainActor final class AppDelegate: NSObject, NSApplicationDelegate {
let model = DictationModel()
private let shortcut = GlobalShortcut()
private var statusItem: NSStatusItem!
private var window: NSWindow?
private var overlay: NSPanel!
private var subscription: AnyCancellable?
private var startItem: NSMenuItem!
private var statusMenuItem: NSMenuItem!
func applicationDidFinishLaunching(_ notification: Notification) {
NSApp.setActivationPolicy(.accessory)
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
statusItem.button?.image = NSImage(systemSymbolName: "waveform", accessibilityDescription: "ClearFlow")
let menu = NSMenu()
statusMenuItem = NSMenuItem(title: model.status, action: nil, keyEquivalent: "")
menu.addItem(statusMenuItem); menu.addItem(.separator())
startItem = NSMenuItem(title: "Start dictation ⌥⇧Space", action: #selector(toggle), keyEquivalent: "")
startItem.target = self; menu.addItem(startItem)
let open = NSMenuItem(title: "Open ClearFlow…", action: #selector(showWindow), keyEquivalent: "")
open.target = self; menu.addItem(open)
menu.addItem(.separator())
let quit = NSMenuItem(title: "Quit ClearFlow", action: #selector(quit), keyEquivalent: "q")
quit.target = self; menu.addItem(quit)
statusItem.menu = menu
overlay = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 118, height: 46),
styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
overlay.title = "ClearFlow Dictation"
overlay.isOpaque = false; overlay.backgroundColor = .clear; overlay.hasShadow = true
overlay.level = .floating; overlay.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
overlay.contentView = NSHostingView(rootView: OverlayView(model: model))
model.showWindow = { [weak self] in self?.showWindow() }
shortcut.onPress = { [weak self] in self?.model.toggle() }
model.shortcutAvailable = shortcut.register()
subscription = model.$mode.combineLatest(model.$status).sink { [weak self] _, _ in
DispatchQueue.main.async { self?.refresh() }
}
// Open the controls at launch; recording still requires an explicit action.
showWindow()
}
private func refresh() {
statusMenuItem.title = String(model.status.prefix(85))
startItem.title = model.mode == .recording ? "Finish dictation ⌥⇧Space" : model.busy ? "Cancel ⌥⇧Space" : "Start dictation ⌥⇧Space"
statusItem.button?.image = NSImage(systemSymbolName: model.mode == .recording ? "mic.fill" : model.mode == .transcribing ? "hourglass" : "waveform",
accessibilityDescription: "ClearFlow")
if model.busy {
let screen = NSScreen.screens.first { NSMouseInRect(NSEvent.mouseLocation, $0.frame, false) } ?? NSScreen.main
if let screen {
overlay.setFrameOrigin(NSPoint(x: screen.visibleFrame.midX - overlay.frame.width / 2, y: screen.visibleFrame.minY + 34))
}
overlay.orderFrontRegardless()
} else { overlay.orderOut(nil) }
}
@objc func toggle() { model.toggle() }
@objc func showWindow() {
if window == nil {
let controller = NSHostingController(rootView: MainView(model: model))
let w = NSWindow(contentViewController: controller)
w.title = "ClearFlow"; w.setContentSize(NSSize(width: 1120, height: 780))
w.styleMask = [.titled, .closable, .miniaturizable, .resizable]
w.minSize = NSSize(width: 960, height: 680)
w.isReleasedWhenClosed = false; w.center()
window = w
}
model.refreshPermissions()
NSApp.activate(ignoringOtherApps: true)
window?.makeKeyAndOrderFront(nil)
}
@objc func quit() { NSApp.terminate(nil) }
func applicationWillTerminate(_ notification: Notification) {
model.cancel(); shortcut.unregister()
}
}
Loading
Loading