Skip to content
Open
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
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ In **Settings → General**, click the shortcut, then press your new key combina

Transcripts are cleaned up before insertion: hesitations such as “um” and “uh”, stutters and stray spacing are removed, a standalone “new line” or “new paragraph” becomes a line break, and spacing and capitalization follow the text at the cursor. Wording is not rewritten. Turn this off under Settings → General → Clean up transcripts.

Optionally, **Polish with Claude** (Settings → Transcription, off by default) sends the cleaned transcript text and your vocabulary to the Anthropic Messages API with your own API key to fix grammar, punctuation and self-corrections. It defaults to `claude-opus-5-5` at low effort with server-side refusal fallback; set another model ID, such as `claude-haiku-5-5`, for faster replies. Polish adds network and model time. If it fails, takes longer than 8 seconds, or returns something that no longer reads as the same dictation (for example, an answer to a dictated question), the cleaned text is inserted instead and the status says why.

There is no elapsed-time cutoff: recording continues until you finish or cancel. After you finish, longer recordings are transcribed sequentially in parts of at most four minutes and combined into one result. Nothing is uploaded or inserted while you are recording. A word spanning a part boundary may be less accurate. Device interruptions or disk errors can still stop capture. A persistent warning appears and ClearFlow attempts to transcribe the available audio into Recent Dictations without pasting at a stale cursor. Low disk space triggers an advance warning; a sudden hardware failure cannot always be predicted. Quitting during capture or transcription asks for confirmation and retains audio.

Transcripts are saved locally **before insertion**, with history enabled by default. Under **Saved Recordings**, choose **Recover** for unfinished audio from an interruption, failed request or previous launch, or **Discard** to delete it. Recovery never automatically pastes. Cancel with the overlay’s × while recording to discard that recording; cancelling while transcribing pauses delivery and keeps the audio. Damaged or unfinalized audio after a crash may not be transcribable, but is retained for inspection or explicit discard.
Expand All @@ -84,6 +86,7 @@ Deploy the supplied Worker in **your own account**, generate your own secret, an
- 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.
- Audio is stored in ~/Library/Application Support/ClearFlow/Recordings with private file permissions. It is deleted after successful transcription (and history persistence when enabled) or explicit discard. Failed, interrupted or paused requests retain audio across new recordings and app restarts. Review or delete these files under Saved Recordings; no automatic expiry. Existing temporary files from older versions are not imported.
- Field content is read locally to confirm insertion and is not uploaded. Known secure fields are rejected.
- With Polish with Claude turned on, transcript text and vocabulary (never audio or field content) are sent to Anthropic under your API key, which is stored in Keychain. It is off by default.
- Transcript history is saved on this Mac by default, without automatic pruning, in ~/Library/Application Support/ClearFlow/history.json. Existing explicit history-off preferences are respected. Disable it in Settings → Data & privacy and save to remove stored history; ordinary completed dictations then stay in memory only. Interrupted audio remains recoverable until discarded. Clear recent history removes transcripts, not unfinished audio. Clipboard fallback leaves text 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.

Expand All @@ -104,7 +107,7 @@ 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.
The app currently transcribes after recording stops. Streaming partials, correction learning and cross-device history sync are not implemented. The local backend uses MLX and requires Apple Silicon.

## License

Expand Down
26 changes: 24 additions & 2 deletions Sources/ClearFlow/DictationModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ import ClearFlowCore
@Published var vocabulary = AppSettings.vocabulary
@Published var saveHistory = AppSettings.saveHistory
@Published var cleanUp = AppSettings.cleanUp
@Published var polish = AppSettings.polish
@Published var polishModel = AppSettings.polishModel
@Published var claudeKey = ""
@Published var hasClaudeKey = false
@Published var settingsMessage = ""
@Published var hasAccessibility = AXIsProcessTrusted()
@Published var microphoneGranted = AVCaptureDevice.authorizationStatus(for: .audio) == .authorized
Expand Down Expand Up @@ -92,6 +96,7 @@ import ClearFlowCore
}
history = HistoryStore.load()
hasToken = !TokenStore.read().isEmpty
hasClaudeKey = !TokenStore.read(account: TokenStore.claudeAccount).isEmpty
lastExternalApp = NSWorkspace.shared.frontmostApplication
workspaceObserver = NSWorkspace.shared.notificationCenter.addObserver(
forName: NSWorkspace.didActivateApplicationNotification, object: nil, queue: .main) { [weak self] note in
Expand Down Expand Up @@ -241,6 +246,8 @@ import ClearFlowCore
let endpoint = AppSettings.endpoint, token = transcribeRecording == nil ? TokenStore.read() : ""
let language = AppSettings.language, vocabulary = AppSettings.vocabulary
let cleanUp = AppSettings.cleanUp
let polishKey = AppSettings.polish && transcribeRecording == nil ? TokenStore.read(account: TokenStore.claudeAccount) : ""
let polishModel = AppSettings.polishModel
requestTask = Task {
do {
let reply: TranscriptionReply
Expand All @@ -252,7 +259,15 @@ import ClearFlowCore
}) }
guard !Task.isCancelled, gate.acceptResult(id) else { return }
let raw = reply.text.trimmingCharacters(in: .whitespacesAndNewlines)
let text = cleanUp ? TranscriptCleanup.clean(raw) : raw
var text = cleanUp ? TranscriptCleanup.clean(raw) : raw
var polishNote = ""
if !polishKey.isEmpty, !text.isEmpty {
status = "Polishing…"
do { text = try await TranscriptPolish.polish(text, apiKey: polishKey, model: polishModel, vocabulary: vocabulary) }
catch is CancellationError { return }
catch { polishNote = " Polish skipped: " + ((error as? LocalizedError)?.errorDescription ?? "Claude was unavailable or changed too much.") }
guard !Task.isCancelled, currentID == id else { return }
}
guard !text.isEmpty else {
mode = .error; status = "No speech was detected. Audio saved for recovery."
recordingNotice = status; refreshRecoveries(); return
Expand All @@ -278,7 +293,7 @@ import ClearFlowCore
else if let insertTranscript { outcome = await insertTranscript(text) }
else { outcome = await TextInsertion.insert(text, target: target, captureIssue: captureIssue, fitToCursor: cleanUp) }
guard !Task.isCancelled, currentID == id else { return }
status = outcome; mode = .ready
status = outcome + polishNote; mode = .ready
// History-off is an explicit privacy choice; retain interrupted audio until discarded.
if saveHistory || !interrupted {
do { try audio.discard(); pendingAudio = nil }
Expand Down Expand Up @@ -362,10 +377,17 @@ import ClearFlowCore
}
do {
if !token.isEmpty { try TokenStore.save(token); token = "" }
if !claudeKey.isEmpty {
try TokenStore.save(claudeKey, account: TokenStore.claudeAccount); claudeKey = ""; hasClaudeKey = true
}
if polish && !hasClaudeKey { settingsMessage = "Enter a Claude API key to polish transcripts."; return }
guard !TokenStore.read().isEmpty else { settingsMessage = "Enter your private service token."; return }
AppSettings.endpoint = url.absoluteString; endpoint = url.absoluteString
AppSettings.language = lang; language = lang
AppSettings.vocabulary = vocabulary; AppSettings.saveHistory = saveHistory; AppSettings.cleanUp = cleanUp
AppSettings.polish = polish
let model = polishModel.trimmingCharacters(in: .whitespacesAndNewlines)
AppSettings.polishModel = model.isEmpty ? Polish.defaultModel : model; polishModel = AppSettings.polishModel
if saveHistory { try HistoryStore.save(history) } else { try HistoryStore.clear() }
hasToken = true; settingsMessage = "Saved. Your access token is in macOS Keychain."
} catch { settingsMessage = error.localizedDescription }
Expand Down
13 changes: 11 additions & 2 deletions Sources/ClearFlow/SettingsStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,14 @@ struct AppSettings {
get { defaults.object(forKey: "cleanUpTranscripts") as? Bool ?? true }
set { defaults.set(newValue, forKey: "cleanUpTranscripts") }
}
static var polish: Bool {
get { defaults.bool(forKey: "polishWithClaude") }
set { defaults.set(newValue, forKey: "polishWithClaude") }
}
static var polishModel: String {
get { defaults.string(forKey: "polishModel") ?? Polish.defaultModel }
set { defaults.set(newValue, forKey: "polishModel") }
}
static var saveHistory: Bool {
get { defaults.object(forKey: "saveHistory") as? Bool ?? true }
set { defaults.set(newValue, forKey: "saveHistory") }
Expand All @@ -33,7 +41,8 @@ struct AppSettings {
enum TokenStore {
static let service = "org.clearflow.app"
static let account = "service-token"
static func read() -> String {
static let claudeAccount = "claude-api-key"
static func read(account: String = account) -> String {
let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service, kSecAttrAccount as String: account,
kSecReturnData as String: true, kSecMatchLimit as String: kSecMatchLimitOne]
Expand All @@ -42,7 +51,7 @@ enum TokenStore {
let data = result as? Data else { return "" }
return String(data: data, encoding: .utf8) ?? ""
}
static func save(_ token: String) throws {
static func save(_ token: String, account: String = account) throws {
let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service, kSecAttrAccount as String: account]
let value = Data(token.trimmingCharacters(in: .whitespacesAndNewlines).utf8)
Expand Down
33 changes: 33 additions & 0 deletions Sources/ClearFlow/TranscriptPolish.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import Foundation
import ClearFlowCore

/// Sends a cleaned transcript to Claude for a light copy edit. Opt-in; on any error,
/// timeout or implausible reply the caller keeps the cleaned text.
enum TranscriptPolish {
static let endpoint = URL(string: "https://api.anthropic.com/v1/messages")!
static let timeout: TimeInterval = 8
static let session: URLSession = {
let config = URLSessionConfiguration.ephemeral
config.timeoutIntervalForRequest = timeout
config.timeoutIntervalForResource = timeout
config.urlCache = nil
return URLSession(configuration: config, delegate: NoRedirectDelegate.shared, delegateQueue: nil)
}()
static func polish(_ text: String, apiKey: String, model: String, vocabulary: String) async throws -> String {
var request = URLRequest(url: endpoint)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue(apiKey, forHTTPHeaderField: "x-api-key")
request.setValue(Polish.apiVersion, forHTTPHeaderField: "anthropic-version")
request.setValue(Polish.fallbackBeta, forHTTPHeaderField: "anthropic-beta")
request.httpBody = try JSONEncoder().encode(Polish.request(for: text, vocabulary: vocabulary, model: model))
let (data, response) = try await session.data(for: request)
try Task.checkCancellation()
guard let status = (response as? HTTPURLResponse)?.statusCode else { throw Polish.Failure.invalidResponse }
guard status == 200 else {
throw AppError.message(status == 401 ? "Claude rejected the API key." : "Claude returned HTTP \(status).")
}
guard let edited = Polish.accept(try Polish.text(from: data), original: text) else { throw Polish.Failure.rejected }
return edited
}
}
13 changes: 12 additions & 1 deletion Sources/ClearFlow/Views.swift
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,17 @@ private struct FlowSettings: View {
SecureField(model.hasToken ? "Saved in Keychain — leave blank to keep" : "Private service token", text: $model.token)
.textFieldStyle(.roundedBorder).padding(.top, 10)
Button("Check connection") { model.testConnection() }.buttonStyle(FlowButton()).padding(.top, 20)
rule()
Toggle("Polish with Claude", isOn: $model.polish).font(.system(size: 13, weight: .medium))
Text("Optional. After cleanup, sends the transcript text (not audio) and your vocabulary to Anthropic to fix grammar, punctuation and self-corrections. Adds a few seconds; if Claude is slow, unavailable or changes the meaning, the cleaned text is used instead.")
.font(.system(size: 12)).foregroundStyle(FlowTheme.muted).lineSpacing(3).padding(.top, 8)
if model.polish {
SecureField(model.hasClaudeKey ? "Claude API key saved in Keychain — leave blank to keep" : "Claude API key", text: $model.claudeKey)
.textFieldStyle(.roundedBorder).padding(.top, 12)
TextField(Polish.defaultModel, text: $model.polishModel).textFieldStyle(.roundedBorder).padding(.top, 8)
Text("Model ID. A smaller model such as claude-haiku-5-5 responds faster.")
.font(.system(size: 11)).foregroundStyle(FlowTheme.muted).padding(.top, 6)
}
Text("Recording continues until you stop or cancel. Longer recordings are transcribed in parts after you stop.")
.font(.system(size: 12)).foregroundStyle(FlowTheme.muted).lineSpacing(3).padding(.top, 20)
}
Expand All @@ -406,7 +417,7 @@ private struct FlowSettings: View {
Text("Your audio").font(.system(size: 14, weight: .medium))
Text("After recording ends, audio is sent only to the service address you configure, including recovery after an unexpected stop. Local Whisper runs on your own hardware; a cloud endpoint sends audio to that provider. There is no automatic cloud fallback. Recordings are stored privately on this Mac until transcription succeeds or you explicitly discard them. Interrupted or failed recordings survive restarting; recover or discard them under Saved Recordings. Cancel while recording discards that recording; cancel while transcribing preserves it for recovery.")
.font(.system(size: 12)).foregroundStyle(FlowTheme.muted).lineSpacing(4).padding(.top, 9)
Text("No screen content is uploaded.").font(.system(size: 12)).padding(.top, 12)
Text("No screen content is uploaded. If Polish with Claude is on, transcript text is sent to Anthropic.").font(.system(size: 12)).padding(.top, 12)
rule()
Button("Clear recent history") { model.clearHistory() }.buttonStyle(FlowButton())
}
Expand Down
Loading
Loading