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
2 changes: 1 addition & 1 deletion Sources/Hushtype/CloudSync.swift
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ final class CloudSync {
if let value = bool(Key.soundsEnabled), value != settings.soundsEnabled { settings.soundsEnabled = value }
if let value = bool(Key.handsFree), value != settings.handsFree {
settings.handsFree = value
controller.restartHotkey()
controller.applyHandsFreeSetting()
}
if let value = bool(Key.learnFromCorrections), value != settings.learnFromCorrections {
settings.learnFromCorrections = value
Expand Down
53 changes: 38 additions & 15 deletions Sources/Hushtype/DictationController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,11 @@ final class DictationController: ObservableObject {
private var focusCapture: Task<(context: DictationContext, field: FocusedField?), Never>?
private var errorDismissTask: Task<Void, Never>?
private var coolDownTask: Task<Void, Never>?
/// True while the Mac is asleep or the screen is locked; the mic is always closed then.
private var micSuspended = false
/// The mic is always closed while the Mac is asleep or the screen is locked. The two are
/// tracked apart, since the Mac wakes (and would reopen the mic) before the screen unlocks.
private var asleep = false
private var screenLocked = false
private var micSuspended: Bool { asleep || screenLocked }
private var systemObservers: [NSObjectProtocol] = []
/// ⌃⌘V pastes the last dictation again, for when a paste missed.
private var pasteLastShortcut: GlobalShortcut?
Expand Down Expand Up @@ -125,22 +128,29 @@ final class DictationController: ObservableObject {
private func observeSleepAndLock() {
let workspace = NSWorkspace.shared.notificationCenter
let distributed = DistributedNotificationCenter.default()
let suspend: @Sendable (Notification) -> Void = { [weak self] _ in
Task { @MainActor in self?.suspendMic(true) }
}
let resume: @Sendable (Notification) -> Void = { [weak self] _ in
Task { @MainActor in self?.suspendMic(false) }
func on(_ change: @escaping @Sendable @MainActor (DictationController) -> Void) -> @Sendable (Notification) -> Void {
{ [weak self] _ in
Task { @MainActor in
guard let self else { return }
let wasSuspended = self.micSuspended
change(self)
if self.micSuspended != wasSuspended { self.suspendMic(self.micSuspended) }
}
}
}
systemObservers = [
workspace.addObserver(forName: NSWorkspace.willSleepNotification, object: nil, queue: .main, using: suspend),
workspace.addObserver(forName: NSWorkspace.didWakeNotification, object: nil, queue: .main, using: resume),
distributed.addObserver(forName: .init("com.apple.screenIsLocked"), object: nil, queue: .main, using: suspend),
distributed.addObserver(forName: .init("com.apple.screenIsUnlocked"), object: nil, queue: .main, using: resume),
workspace.addObserver(forName: NSWorkspace.willSleepNotification, object: nil, queue: .main,
using: on { $0.asleep = true }),
workspace.addObserver(forName: NSWorkspace.didWakeNotification, object: nil, queue: .main,
using: on { $0.asleep = false }),
distributed.addObserver(forName: .init("com.apple.screenIsLocked"), object: nil, queue: .main,
using: on { $0.screenLocked = true }),
distributed.addObserver(forName: .init("com.apple.screenIsUnlocked"), object: nil, queue: .main,
using: on { $0.screenLocked = false }),
]
}

private func suspendMic(_ suspended: Bool) {
micSuspended = suspended
if suspended {
coolDownTask?.cancel()
if phase == .recording { cancelRecording() }
Expand Down Expand Up @@ -170,10 +180,17 @@ final class DictationController: ObservableObject {
}

func restartHotkey() {
// Restarting forgets the held key, so its release would never end a recording.
if phase == .recording { cancelRecording() }
hotkey.stop()
start()
}

/// Call when the hands-free setting changes. Takes effect without restarting the listener.
func applyHandsFreeSetting() {
hotkey.handsFreeEnabled = settings.handsFree
}

/// Types the most recent dictation again at the cursor.
func pasteLast(delay: Double = 0) {
guard let last = history.first else { return NSSound.beep() }
Expand Down Expand Up @@ -288,7 +305,9 @@ final class DictationController: ObservableObject {
snippets: snippets)
let result = try await pipeline.polish(transcript, releasedAt: releasedAt,
transcribedAt: transcribedAt) {
Task { @MainActor in self.phase = .cleaning }
// Only while still waiting: a fast reply can land before this hop runs, and
// must not leave the menu bar stuck on "Polishing…".
Task { @MainActor in if self.phase == .transcribing { self.phase = .cleaning } }
}
deliver(result, into: captured)
} catch HushtypeError.noSpeech {
Expand Down Expand Up @@ -441,6 +460,9 @@ final class DictationController: ObservableObject {
}

private func show(notice message: String) {
// A message still waiting to be dismissed would otherwise clear this one, or a recording
// started after it.
errorDismissTask?.cancel()
phase = .notice(message)
overlay.show()
errorDismissTask = Task { [weak self] in
Expand All @@ -451,12 +473,13 @@ final class DictationController: ObservableObject {
}

private func show(error message: String) {
errorDismissTask?.cancel()
phase = .error(message)
overlay.show()
errorDismissTask = Task { [weak self] in
try? await Task.sleep(for: .seconds(4))
guard !Task.isCancelled else { return }
self?.reset()
guard !Task.isCancelled, let self, self.isError else { return }
self.reset()
}
}
}
7 changes: 5 additions & 2 deletions Sources/Hushtype/History.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ import HushtypeCore
/// Only text and timings are kept, never audio.
enum HistoryStore {
static let limit = 200
/// Saves and erases run in order here, so an older save can't land after a newer one or
/// bring back history that was just cleared.
private static let queue = DispatchQueue(label: "app.hushtype.history", qos: .utility)

private static var fileURL: URL? {
guard let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
Expand All @@ -21,7 +24,7 @@ enum HistoryStore {
static func save(_ items: [DictationResult]) {
guard let url = fileURL else { return }
let items = Array(items.prefix(limit))
DispatchQueue.global(qos: .utility).async {
queue.async {
try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
guard let data = try? JSONEncoder().encode(items) else { return }
try? data.write(to: url, options: [.atomic, .completeFileProtection])
Expand All @@ -30,7 +33,7 @@ enum HistoryStore {

static func erase() {
guard let url = fileURL else { return }
try? FileManager.default.removeItem(at: url)
queue.async { try? FileManager.default.removeItem(at: url) }
}
}

Expand Down
18 changes: 13 additions & 5 deletions Sources/Hushtype/HotkeyMonitor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ final class HotkeyMonitor {
switch type {
case .tapDisabledByTimeout, .tapDisabledByUserInput:
if let tap { CGEvent.tapEnable(tap: tap, enable: true) }
// While the tap was off the key may have been let go; without its release a
// push-to-talk recording would never finish.
if !triggerKey.isDown(in: CGEventSource.flagsState(.combinedSessionState)) {
perform(gesture.keyUp(at: ProcessInfo.processInfo.systemUptime))
}
case .keyDown:
let keyCode = event.getIntegerValueField(.keyboardEventKeycode)
perform(gesture.otherKey(isEscape: keyCode == 53)) // kVK_Escape
Expand All @@ -80,7 +85,7 @@ final class HotkeyMonitor {
}
guard keyCode == triggerKey.keyCode else { return }
let now = ProcessInfo.processInfo.systemUptime
perform(event.flags.contains(triggerKey.flag) ? gesture.keyDown(at: now) : gesture.keyUp(at: now))
perform(triggerKey.isDown(in: event.flags) ? gesture.keyDown(at: now) : gesture.keyUp(at: now))
default:
break
}
Expand Down Expand Up @@ -112,11 +117,14 @@ extension TriggerKey {
}
}

var flag: CGEventFlags {
/// Whether this key is held in `flags`. The right-hand keys are checked with their device bits
/// (NX_DEVICERALTKEYMASK, NX_DEVICERCMDKEYMASK), since the plain Option and Command flags stay
/// set while the left-hand key is held, which would hide the trigger's release.
func isDown(in flags: CGEventFlags) -> Bool {
switch self {
case .fn: return .maskSecondaryFn
case .rightOption: return .maskAlternate
case .rightCommand: return .maskCommand
case .fn: return flags.contains(.maskSecondaryFn)
case .rightOption: return flags.rawValue & 0x40 != 0
case .rightCommand: return flags.rawValue & 0x10 != 0
}
}
}
8 changes: 5 additions & 3 deletions Sources/Hushtype/OverlayPanel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ final class OverlayPanel {
private let panel: NSPanel

init(controller: DictationController) {
panel = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 380, height: 44),
// Wider than the pill needs: the panel is invisible and ignores the mouse, and the room
// keeps longer notices and errors from being cut off.
panel = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 720, height: 44),
styleMask: [.nonactivatingPanel, .borderless],
backing: .buffered, defer: true)
panel.isFloatingPanel = true
Expand Down Expand Up @@ -58,10 +60,10 @@ private struct OverlayView: View {
: controller.phase == .transcribing ? "Transcribing…" : "Polishing…")
case .error(let message):
Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(.yellow)
Text(message).lineLimit(1)
Text(message).lineLimit(1).truncationMode(.middle)
case .notice(let message):
Image(systemName: "info.circle.fill").foregroundStyle(.white.opacity(0.8))
Text(message).lineLimit(1)
Text(message).lineLimit(1).truncationMode(.middle)
case .idle:
EmptyView()
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/Hushtype/SettingsWindow.swift
Original file line number Diff line number Diff line change
Expand Up @@ -646,7 +646,7 @@ private struct DictationPane: View {
}
.animation(.easeOut(duration: 0.2), value: settings.triggerKey)
.onChange(of: settings.triggerKey) { controller.restartHotkey() }
.onChange(of: settings.handsFree) { controller.restartHotkey() }
.onChange(of: settings.handsFree) { controller.applyHandsFreeSetting() }
.onChange(of: settings.language) { controller.prepareSpeechModel() }
.onChange(of: settings.alwaysReadyMic) { controller.applyMicMode() }
}
Expand Down
20 changes: 19 additions & 1 deletion Sources/HushtypeCore/HushtypeError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public enum HushtypeError: LocalizedError, Equatable {
case .missingAPIKey(let service):
return "Add your \(service) API key in Settings."
case .http(let service, let status, let body):
return "\(service) returned HTTP \(status): \(body.prefix(200))"
return Self.describe(service: service, status: status, body: body)
case .badResponse(let detail):
return "Unexpected response: \(detail)"
case .speechUnavailable(let detail):
Expand All @@ -21,6 +21,24 @@ public enum HushtypeError: LocalizedError, Equatable {
return "No speech detected."
}
}

/// A short, readable line for an HTTP failure, instead of the raw JSON body.
static func describe(service: String, status: Int, body: String) -> String {
struct Envelope: Decodable {
struct Detail: Decodable { let message: String? }
let error: Detail?
}
let message = (try? JSONDecoder().decode(Envelope.self, from: Data(body.utf8)))?.error?.message?
.trimmingCharacters(in: .whitespacesAndNewlines)
switch status {
case 401: return "\(service) didn't accept your API key. Check it in Settings."
case 429: return "\(service) rate limit reached. Try again in a moment."
case 500...599: return "\(service) is having trouble right now (HTTP \(status)). Try again shortly."
default:
if let message, !message.isEmpty { return "\(service): \(message.prefix(160))" }
return "\(service) returned HTTP \(status)."
}
}
}

enum HTTP {
Expand Down
6 changes: 6 additions & 0 deletions Sources/HushtypeCore/TranscriptCleaner.swift
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,11 @@ public struct TranscriptCleaner: Sendable {

struct Timeout: Error {}

/// Claude hit `max_tokens`, so its reply is missing the end and must not replace the transcript.
struct Truncated: LocalizedError {
var errorDescription: String? { "Claude's reply was cut short, so the transcript was inserted as heard." }
}

/// Streams a reply, giving up when the first token or the whole reply takes too long.
func streamWithDeadline(_ request: URLRequest,
firstTokenTimeout: Duration = TranscriptCleaner.firstTokenTimeout,
Expand Down Expand Up @@ -210,6 +215,7 @@ public struct TranscriptCleaner: Sendable {
text += delta
case .stop(let reason):
if reason == "refusal" { return nil }
if reason == "max_tokens" { throw Truncated() }
case .error(let message):
throw HushtypeError.badResponse("Anthropic: \(message)")
case .end:
Expand Down
15 changes: 15 additions & 0 deletions Tests/HushtypeCoreTests/HushtypeCoreTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -294,3 +294,18 @@ final class SnippetSyncTests: XCTestCase {
XCTAssertEqual(merged.first?.expansion, "new")
}
}

final class HushtypeErrorTests: XCTestCase {
func testHTTPErrorsReadAsSentences() {
let rejected = HushtypeError.http(service: "Anthropic", status: 401,
body: #"{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}"#)
XCTAssertEqual(rejected.localizedDescription, "Anthropic didn't accept your API key. Check it in Settings.")
let credit = HushtypeError.http(service: "Anthropic", status: 400,
body: #"{"type":"error","error":{"type":"invalid_request_error","message":"Your credit balance is too low."}}"#)
XCTAssertEqual(credit.localizedDescription, "Anthropic: Your credit balance is too low.")
XCTAssertEqual(HushtypeError.http(service: "Anthropic", status: 529, body: "").localizedDescription,
"Anthropic is having trouble right now (HTTP 529). Try again shortly.")
XCTAssertEqual(HushtypeError.http(service: "Anthropic", status: 404, body: "<html>").localizedDescription,
"Anthropic returned HTTP 404.")
}
}
Loading