Skip to content

Commit 0bbf67b

Browse files
Lee Seongjooclaude
andcommitted
Keep focus on the source app during Services playback
A regular Dock app comes forward when its Service is invoked, stealing keyboard focus from where the user is working. Capture the frontmost app at the moment the Service fires (in ServiceProvider, before our app can activate) and re-activate it after triggering playback, so the source window keeps focus while the floating HUD plays. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent 9af5c2b commit 0bbf67b

2 files changed

Lines changed: 17 additions & 3 deletions

File tree

‎Sources/App/AppDelegate.swift‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,11 +54,22 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
5454
}
5555

5656
/// Called by ServiceProvider when the user picks "Codebasic TTS": synthesize
57-
/// the selected text (cache-first) and play it — without stealing focus.
58-
func handleSelectedText(_ text: String) {
57+
/// the selected text (cache-first) and play it. `source` is the app the user
58+
/// triggered the Service from — we re-activate it so playing audio never
59+
/// steals keyboard focus from where they're working.
60+
func handleSelectedText(_ text: String, source: NSRunningApplication? = nil) {
5961
let preview = text.replacingOccurrences(of: "\n", with: " ").prefix(60)
6062
Log.app.info("handleSelectedText: \(text.count) chars — \"\(preview, privacy: .public)\"")
6163
appState.synthesize(text)
64+
65+
guard let source, source.processIdentifier != getpid() else { return }
66+
// The overlay shows on the next runloop; re-assert the source app's focus
67+
// a few times to cover whenever our app might have come forward.
68+
for delay in [0.0, 0.12, 0.30] {
69+
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
70+
source.activate()
71+
}
72+
}
6273
}
6374

6475
// MARK: - Main menu (regular app needs one for ⌘Q and text-editing shortcuts)

‎Sources/Service/ServiceProvider.swift‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,11 @@ final class ServiceProvider: NSObject {
1919
}
2020

2121
Log.service.info("Service fired: received \(text.count) chars")
22+
// Capture the app the user invoked the Service from, NOW (before our app
23+
// can come forward), so we can hand keyboard focus back to it.
24+
let source = NSWorkspace.shared.frontmostApplication
2225
Task { @MainActor in
23-
AppDelegate.shared?.handleSelectedText(text)
26+
AppDelegate.shared?.handleSelectedText(text, source: source)
2427
}
2528
}
2629
}

0 commit comments

Comments
 (0)