Skip to content

Commit 2094563

Browse files
Lee Seongjooclaude
andcommitted
M2: app speaks selected text via ElevenLabs
Wire the menu-bar app to actually synthesize and play: - ElevenLabsBackend: real TTSBackend over the ElevenLabs HTTP API (xi-api-key, /stream endpoint, mp3). The app calls it directly — no sidecar (that's the local MLX path). Verified end-to-end (key -> request -> valid mp3). - AudioPlayer: AVAudioPlayer wrapper with a completion callback. - AppDelegate (@mainactor): on a selected-text service, synthesize with the user's cloned voice (성주, eleven_flash_v2_5) and play; menu-bar shows ⏳/🔈/⚠️ states; adds a Stop (⌘.) item. - Secrets: read the API key from a plaintext file in Application Support (Keychain hardening deferred); build.sh installs it from Sidecar/.eleven_key. - Also restore the local CLI end marker to '…' (the ' ^ ^' buffer caused clicks). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent ab3c650 commit 2094563

9 files changed

Lines changed: 185 additions & 37 deletions

File tree

‎.gitignore‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,8 @@ __pycache__/
1212

1313
# macOS
1414
.DS_Store
15+
16+
# ElevenLabs API key (never commit)
17+
.eleven_key
18+
*.key
19+
*.mp3

‎Sidecar/clone.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -340,7 +340,7 @@ def main():
340340
help="fade-out over the speech end, click safety (default 25; 0=off)")
341341
ap.add_argument("--end-marker", default="…",
342342
help="non-vocalized marker appended so the last syllable isn't clipped "
343-
"(default '…'; ' ^' also works; empty string disables)")
343+
"(default '…'; empty string disables). Model still clips occasionally.")
344344
ap.add_argument("--gap-ms", type=float, default=180.0,
345345
help="silence between sentences in per-sentence fallback (default 180)")
346346
ap.add_argument("--trunc-ratio", type=float, default=2.0,

‎Sources/App/AppDelegate.swift‎

Lines changed: 62 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,51 @@
11
import AppKit
22

3+
@MainActor
34
final class AppDelegate: NSObject, NSApplicationDelegate {
45

56
/// Singleton-ish handle so the Services provider can reach the running app.
67
static private(set) var shared: AppDelegate?
78

89
private var statusItem: NSStatusItem!
910
private let serviceProvider = ServiceProvider()
11+
private let player = AudioPlayer()
1012
private var lastSelection: String = ""
13+
private var speakTask: Task<Void, Never>?
1114

12-
// Active backend. M1 just logs through it; later milestones swap in
13-
// ElevenLabsBackend / Qwen3MLXBackend behind this same protocol.
14-
private let backend: TTSBackend = StubBackend()
15+
// Active backend: ElevenLabs (cloud) when a key is present, else a no-op stub.
16+
private var backend: TTSBackend = StubBackend()
17+
18+
// The user's cloned ElevenLabs voice (성주) + the low-latency model.
19+
private let voice = VoiceConfig(voiceId: "Yp1WZJMrN7OSdP8PG9sm",
20+
modelId: "eleven_flash_v2_5",
21+
settingsHash: "")
1522

1623
func applicationDidFinishLaunching(_ notification: Notification) {
1724
AppDelegate.shared = self
1825

26+
if let key = Secrets.elevenLabsKey {
27+
backend = ElevenLabsBackend(apiKey: key)
28+
} else {
29+
Log.app.error("No ElevenLabs key at \(Secrets.appSupportDir)/eleven_key — speech disabled")
30+
}
31+
1932
setUpStatusItem()
2033
registerServices()
34+
player.onFinish = { [weak self] in self?.setIcon(.idle) }
2135

22-
Log.app.info("SelectedTextTTS launched. Active backend: \(self.backend.identity, privacy: .public)")
36+
Log.app.info("Codebasic TTS launched. Backend: \(self.backend.identity, privacy: .public)")
2337
}
2438

2539
// MARK: - Menu bar
2640

41+
private enum Icon: String { case idle = "🔊", working = "⏳", speaking = "🔈", error = "⚠️" }
42+
private enum MenuTag: Int { case lastSelection = 100 }
43+
44+
private func setIcon(_ icon: Icon) { statusItem.button?.title = icon.rawValue }
45+
2746
private func setUpStatusItem() {
2847
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
29-
statusItem.button?.title = "🔊"
48+
setIcon(.idle)
3049

3150
let menu = NSMenu()
3251
menu.addItem(withTitle: "Codebasic TTS", action: nil, keyEquivalent: "")
@@ -37,46 +56,65 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
3756
lastItem.isEnabled = false
3857
menu.addItem(lastItem)
3958

59+
menu.addItem(withTitle: "Stop", action: #selector(stopSpeaking), keyEquivalent: ".")
4060
menu.addItem(.separator())
4161
menu.addItem(withTitle: "Quit", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
4262

4363
statusItem.menu = menu
4464
}
4565

46-
private enum MenuTag: Int {
47-
case lastSelection = 100
66+
@objc private func stopSpeaking() {
67+
speakTask?.cancel()
68+
player.stop()
69+
setIcon(.idle)
4870
}
4971

5072
// MARK: - Services
5173

5274
private func registerServices() {
53-
// Wire the provider so the runtime can dispatch the Services menu item.
5475
NSApp.servicesProvider = serviceProvider
55-
// Force a refresh of the dynamic services so the menu item shows up
56-
// without requiring a logout/login on the very first run.
5776
NSUpdateDynamicServices()
5877
}
5978

6079
// MARK: - Entry point from the Services menu
6180

62-
/// Called by ServiceProvider when the user picks "Read with SelectedTextTTS".
63-
/// M1: log + reflect in the menu bar. M2+: hand to Segmenter → Cache → Player.
81+
/// Called by ServiceProvider when the user picks "Codebasic TTS": synthesize
82+
/// the selected text and play it.
6483
func handleSelectedText(_ text: String) {
65-
lastSelection = text
66-
let preview = text.replacingOccurrences(of: "\n", with: " ").prefix(60)
84+
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
85+
guard !trimmed.isEmpty else { return }
86+
lastSelection = trimmed
87+
88+
let preview = trimmed.replacingOccurrences(of: "\n", with: " ").prefix(60)
89+
if let item = statusItem.menu?.item(withTag: MenuTag.lastSelection.rawValue) {
90+
item.title = "Last selection: \(preview)\(trimmed.count > 60 ? "…" : "")"
91+
}
92+
Log.app.info("handleSelectedText: \(trimmed.count) chars — \"\(preview, privacy: .public)\"")
93+
94+
speak(trimmed)
95+
}
6796

68-
DispatchQueue.main.async { [weak self] in
97+
private func speak(_ text: String) {
98+
speakTask?.cancel()
99+
player.stop()
100+
setIcon(.working)
101+
102+
speakTask = Task { [weak self] in
69103
guard let self else { return }
70-
if let item = self.statusItem.menu?.item(withTag: MenuTag.lastSelection.rawValue) {
71-
item.title = "Last selection: \(preview)\(text.count > 60 ? "…" : "")"
72-
}
73-
// Brief visual confirmation that the service fired.
74-
self.statusItem.button?.title = "🔈"
75-
DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) {
76-
self.statusItem.button?.title = "🔊"
104+
do {
105+
for try await chunk in self.backend.stream(segment: text, voice: self.voice) {
106+
try Task.checkCancellation()
107+
self.setIcon(.speaking)
108+
try self.player.play(chunk)
109+
}
110+
} catch is CancellationError {
111+
// user pressed Stop / new selection
112+
} catch {
113+
Log.app.error("speak failed: \(error.localizedDescription)")
114+
self.setIcon(.error)
115+
try? await Task.sleep(nanoseconds: 1_500_000_000)
116+
self.setIcon(.idle)
77117
}
78118
}
79-
80-
Log.app.info("handleSelectedText: \(text.count) chars — \"\(preview, privacy: .public)\"")
81119
}
82120
}

‎Sources/App/Secrets.swift‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import Foundation
2+
3+
/// API key access. MVP reads a plaintext key file from Application Support
4+
/// (user-readable only); build.sh installs it there from Sidecar/.eleven_key.
5+
/// Keychain hardening is a later milestone.
6+
enum Secrets {
7+
static let appSupportDir = ("~/Library/Application Support/Codebasic TTS"
8+
as NSString).expandingTildeInPath
9+
10+
static var elevenLabsKey: String? {
11+
let path = (appSupportDir as NSString).appendingPathComponent("eleven_key")
12+
guard let raw = try? String(contentsOfFile: path, encoding: .utf8) else { return nil }
13+
let key = raw.trimmingCharacters(in: .whitespacesAndNewlines)
14+
return key.isEmpty ? nil : key
15+
}
16+
}

‎Sources/App/main.swift‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,12 @@ import AppKit
44
// LSUIElement in Info.plist already makes this an agent app, but we also set
55
// the activation policy explicitly as belt-and-suspenders so it never grabs a
66
// Dock icon even when launched directly during development.
7-
let app = NSApplication.shared
8-
let delegate = AppDelegate()
9-
app.delegate = delegate
10-
app.setActivationPolicy(.accessory)
11-
app.run()
7+
// Program start runs on the main thread; assume the main actor so we can touch
8+
// the @MainActor AppDelegate.
9+
MainActor.assumeIsolated {
10+
let app = NSApplication.shared
11+
let delegate = AppDelegate()
12+
app.delegate = delegate
13+
app.setActivationPolicy(.accessory)
14+
app.run()
15+
}

‎Sources/Core/AudioPlayer.swift‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import AVFoundation
2+
3+
/// Minimal playback: hold an AVAudioPlayer and play in-memory audio (mp3 Data).
4+
/// Retaining the player is required — otherwise it deallocates and goes silent.
5+
final class AudioPlayer: NSObject, AVAudioPlayerDelegate {
6+
private var player: AVAudioPlayer?
7+
var onFinish: (() -> Void)?
8+
9+
func play(_ data: Data) throws {
10+
let p = try AVAudioPlayer(data: data)
11+
p.delegate = self
12+
player = p
13+
p.prepareToPlay()
14+
p.play()
15+
}
16+
17+
func stop() {
18+
player?.stop()
19+
player = nil
20+
}
21+
22+
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
23+
onFinish?()
24+
}
25+
}

‎Sources/Service/ServiceProvider.swift‎

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

2121
Log.service.info("Service fired: received \(text.count) chars")
22-
AppDelegate.shared?.handleSelectedText(text)
22+
Task { @MainActor in
23+
AppDelegate.shared?.handleSelectedText(text)
24+
}
2325
}
2426
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import Foundation
2+
3+
/// Cloud TTS backend: ElevenLabs HTTP API. The app calls this directly (no
4+
/// sidecar — that's only for the local MLX engine). ElevenLabs renders the whole
5+
/// text server-side, so it doesn't have the local model's end-clipping issues.
6+
struct ElevenLabsBackend: TTSBackend {
7+
let identity = "elevenlabs"
8+
let apiKey: String
9+
10+
/// Synthesize `segment` and emit the (mp3) audio. For now the full response
11+
/// is collected and yielded as one chunk; the caller plays it. `voice`
12+
/// carries the ElevenLabs voiceId + modelId.
13+
func stream(segment: String, voice: VoiceConfig) -> AsyncThrowingStream<Data, Error> {
14+
AsyncThrowingStream { continuation in
15+
let task = Task {
16+
do {
17+
let url = URL(string:
18+
"https://api.elevenlabs.io/v1/text-to-speech/\(voice.voiceId)/stream"
19+
+ "?output_format=mp3_44100_128")!
20+
var req = URLRequest(url: url)
21+
req.httpMethod = "POST"
22+
req.setValue(apiKey, forHTTPHeaderField: "xi-api-key")
23+
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
24+
req.httpBody = try JSONSerialization.data(withJSONObject: [
25+
"text": segment,
26+
"model_id": voice.modelId,
27+
])
28+
29+
let (bytes, response) = try await URLSession.shared.bytes(for: req)
30+
guard let http = response as? HTTPURLResponse else {
31+
throw URLError(.badServerResponse)
32+
}
33+
var buffer = Data()
34+
for try await byte in bytes { buffer.append(byte) }
35+
guard http.statusCode == 200 else {
36+
let msg = String(data: buffer, encoding: .utf8) ?? "<binary>"
37+
throw NSError(domain: "ElevenLabs", code: http.statusCode,
38+
userInfo: [NSLocalizedDescriptionKey: msg])
39+
}
40+
continuation.yield(buffer)
41+
continuation.finish()
42+
} catch {
43+
continuation.finish(throwing: error)
44+
}
45+
}
46+
continuation.onTermination = { _ in task.cancel() }
47+
}
48+
}
49+
}

‎build.sh‎

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,17 @@ install_and_register() {
4949
rm -rf "$INSTALL_DIR/$APP_NAME.app"
5050
cp -R "$APP_DIR" "$INSTALL_DIR/$APP_NAME.app"
5151

52+
echo "==> Installing ElevenLabs key into Application Support (if present)"
53+
local appsup="$HOME/Library/Application Support/Codebasic TTS"
54+
if [ -f "$HERE/Sidecar/.eleven_key" ]; then
55+
mkdir -p "$appsup"
56+
tr -d ' \n\r' < "$HERE/Sidecar/.eleven_key" > "$appsup/eleven_key"
57+
chmod 600 "$appsup/eleven_key"
58+
echo " key -> $appsup/eleven_key"
59+
else
60+
echo " (no Sidecar/.eleven_key — speech will be disabled)"
61+
fi
62+
5263
echo "==> Registering with Launch Services"
5364
"$LSREGISTER" -f "$INSTALL_DIR/$APP_NAME.app"
5465

@@ -61,13 +72,11 @@ install_and_register() {
6172

6273
cat <<EOF
6374
64-
Done. To smoke-test M1:
75+
Done. To smoke-test:
6576
1. In TextEdit (or any app), select some text.
66-
2. Right-click → Services → "Read with SelectedTextTTS"
67-
(or app menu → Services). If it is missing, see README "Service not appearing".
68-
3. Watch the log: ./build.sh logs
69-
You should see: 'Service fired: received N chars'.
70-
The 🔊 menu-bar icon briefly flips to 🔈 and its menu shows the last selection.
77+
2. Right-click → Services → "Codebasic TTS" (or app menu → Services).
78+
3. It should speak via ElevenLabs (🔊 → ⏳ → 🔈). Watch logs: ./build.sh logs
79+
Menu-bar: ⏳ synthesizing, 🔈 speaking, ⚠️ error. "Stop" (⌘.) halts playback.
7180
EOF
7281
}
7382

0 commit comments

Comments
 (0)