Skip to content

Commit 8f2f86b

Browse files
committed
Add opt-in local MCP speech and instruction profiles
1 parent aba9183 commit 8f2f86b

28 files changed

Lines changed: 2232 additions & 87 deletions

‎README.md‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,10 @@ macOS용 TTS 앱: **텍스트를 선택하고 단축키 한 번으로 AI 음성
5656
|---|---|
5757
| 선택 텍스트 읽기 | ⌃⌥⌘R 또는 우클릭 → Services → "Codebasic TTS" |
5858
| 선택 코드 해설 후 읽기 | ⌃⌥⌘E 또는 Services → "Codebasic TTS: 코드 해설" |
59-
| 일시정지 / 정지 | 재생 HUD 또는 메뉴 막대 아이콘 메뉴 |
60-
| 스크립트 편집 · 해설 보기 | 메뉴 막대 아이콘 클릭 → 관리 창 |
59+
| 일시정지 / 정지 | 재생 HUD에서 일시정지·중지 / 앱 메뉴에서 재생 중지 |
60+
| 스크립트 편집 · 해설 보기 | Dock 아이콘 클릭 → 관리 창 |
61+
62+
창을 닫아도 Dock 아이콘과 실행 중인 앱은 유지됩니다. Dock에서 다시 열거나 `⌘Q`로 앱을 완전히 종료하세요.
6163

6264
## 설정
6365

@@ -281,9 +283,9 @@ Sidecar/tts -m 4bit # 양자화 선택 (4bit|5bit|6bit|8bit|bf16)
281283
```
282284
Codebasic-TTS/
283285
├── build.sh # swiftc 빌드 + 번들 조립 + Launch Services 등록
284-
├── Resources/Info.plist # LSUIElement + NSServices 정의
286+
├── Resources/Info.plist # Dock 앱 정보 및 NSServices 정의
285287
├── Sources/
286-
│ ├── App/ # 진입점, 메뉴 막대, 전역 단축키, 엔드포인트/시크릿
288+
│ ├── App/ # 진입점, 앱 메뉴, 전역 단축키, 엔드포인트/시크릿
287289
│ ├── Service/ServiceProvider.swift # NSServices 핸들러 (read/explain)
288290
│ ├── Core/ # 문장 분할, 캐시, 큐 재생, 원문 정규화
289291
│ ├── TTS/ # TTSBackend 프로토콜 + ElevenLabs/로컬 Qwen3 백엔드

‎Resources/Info.plist‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,6 @@
2121
<key>LSMinimumSystemVersion</key>
2222
<string>13.0</string>
2323

24-
<!-- Start as a focus-safe agent; MainWindow flips to a Dock app (.regular)
25-
while its window is open. Keeps background Services playback from
26-
stealing focus. -->
27-
<key>LSUIElement</key>
28-
<true/>
29-
3024
<!-- macOS Services registration. NSMessage maps to the selector
3125
readSelectedText:userData:error: in ServiceProvider.swift. -->
3226
<key>NSServices</key>

‎Sources/App/AppDelegate.swift‎

Lines changed: 142 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -12,83 +12,168 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
1212
let appState = AppState()
1313
private lazy var mainWindow = MainWindow(appState: appState)
1414
private lazy var overlay = OverlayWindow(app: appState)
15-
private var statusItem: NSStatusItem!
1615
private var cancellables = Set<AnyCancellable>()
16+
private var localSpeechSocket: LocalSpeechSocket?
17+
private var localSpeechGate: LocalSpeechGate?
18+
private var localSpeechMenu: NSMenuItem?
19+
private var localInstructionSocket: LocalInstructionSocket?
20+
private var localInstructionMenu: NSMenuItem?
21+
private var localInstructionExpiry: DispatchWorkItem?
1722

1823
func applicationDidFinishLaunching(_ notification: Notification) {
1924
AppDelegate.shared = self
2025

2126
setUpMainMenu()
22-
setUpStatusItem()
2327
registerServices()
2428
registerHotKeys()
2529
observeState()
2630

2731
// Review-only 해설 (auto-play off): surface the window so it can be checked.
28-
appState.onRequestReview = { [weak self] in
29-
self?.mainWindow.show()
30-
NSApp.activate(ignoringOtherApps: true)
31-
}
32+
appState.onRequestReview = { [weak self] in self?.mainWindow.show() }
3233
if appState.keyPresent { appState.refreshVoices() }
3334
mainWindow.show() // open the management window on launch
3435

3536
Log.app.info("Codebasic TTS launched. Backend: \(self.appState.backendIdentity, privacy: .public)")
3637
}
3738

38-
// MARK: - Status item (persistent, focus-safe affordance to reopen the UI)
39+
// MARK: - Local MCP opt-in
3940

40-
/// Menu-bar glyph: a monochrome SF Symbol template (adapts to light/dark
41-
/// menu bar), swapped per playback phase.
42-
private func setStatusSymbol(_ name: String) {
43-
let img = NSImage(systemSymbolName: name, accessibilityDescription: "Codebasic TTS")
44-
img?.isTemplate = true
45-
statusItem.button?.image = img
46-
statusItem.button?.title = ""
41+
@objc private func toggleLocalSpeech() {
42+
if let socket = localSpeechSocket {
43+
socket.stop(); localSpeechSocket = nil; localSpeechGate = nil
44+
localSpeechMenu?.state = .off
45+
return
46+
}
47+
let gate = LocalSpeechGate()
48+
let socket = LocalSpeechSocket { [weak self, gate] text, key in
49+
guard let self, self.localSpeechGate === gate else { return "disabled" }
50+
return gate.accept(text: text, key: key, app: self.appState)
51+
}
52+
guard socket.start() else {
53+
let alert = NSAlert()
54+
alert.messageText = "로컬 MCP 음성 입력을 시작할 수 없습니다"
55+
alert.informativeText = "소켓 경로가 이미 있거나 안전하지 않습니다. 기존 실행과 경로를 확인하세요."
56+
alert.runModal()
57+
return
58+
}
59+
localSpeechGate = gate; localSpeechSocket = socket; localSpeechMenu?.state = .on
4760
}
4861

49-
private func setUpStatusItem() {
50-
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
51-
setStatusSymbol("waveform")
52-
53-
let menu = NSMenu()
54-
menu.autoenablesItems = false
55-
let open = NSMenuItem(title: "Codebasic TTS 열기", action: #selector(openWindow), keyEquivalent: "")
56-
open.target = self
57-
menu.addItem(open)
58-
menu.addItem(.separator())
59-
let stop = NSMenuItem(title: "재생 중지", action: #selector(stopSpeaking), keyEquivalent: "")
60-
stop.target = self
61-
menu.addItem(stop)
62-
menu.addItem(.separator())
63-
menu.addItem(withTitle: "종료", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
64-
statusItem.menu = menu
62+
// Separate consent: enabling speech must never publish instructions.
63+
@objc private func toggleLocalInstructions() {
64+
if localInstructionSocket != nil { revokeLocalInstructions(); return }
65+
let selection = NSAlert()
66+
selection.messageText = "로컬 MCP 지시 공유 (이번 실행)"
67+
selection.informativeText = "연결하려는 지시 도우미의 PID와 공유할 프로필 한 개를 지정하세요. 자동 공유되지 않습니다."
68+
selection.addButton(withTitle: "미리 보기")
69+
selection.addButton(withTitle: "취소")
70+
let pidField = NSTextField(frame: NSRect(x: 0, y: 33, width: 390, height: 24))
71+
pidField.placeholderString = "지시 도우미 PID"
72+
let picker = NSPopUpButton(frame: NSRect(x: 0, y: 0, width: 390, height: 26))
73+
picker.addItems(withTitles: ["해설", "이어서 해설", "음성 대본 정규화 (사전·힌트 제외)"])
74+
let fields = NSView(frame: NSRect(x: 0, y: 0, width: 390, height: 60))
75+
fields.addSubview(pidField); fields.addSubview(picker)
76+
selection.accessoryView = fields
77+
guard selection.runModal() == .alertFirstButtonReturn else { return }
78+
let names = LocalInstructionProfile.Name.allCases
79+
guard let pid = Int32(pidField.stringValue.trimmingCharacters(in: .whitespacesAndNewlines)),
80+
let peer = LocalInstructionPeer.current(pid: pid), names.indices.contains(picker.indexOfSelectedItem),
81+
let profile = instructionSnapshot(names[picker.indexOfSelectedItem]) else {
82+
showInstructionShareError("같은 계정에서 계속 실행 중인 도우미의 PID와 공유할 수 있는 길이의 지시가 필요합니다.")
83+
return
84+
}
85+
let approval = NSAlert()
86+
approval.messageText = "PID \(pid)에 아래 지시를 공유할까요?"
87+
approval.informativeText = "최대 10분, 이 프로필만 읽습니다. 원격 모델을 사용하는 에이전트는 지시를 해당 서비스로 보낼 수 있습니다. 비밀이나 외부 공개할 수 없는 내용이 있으면 취소하세요."
88+
approval.addButton(withTitle: "이 프로필만 공유")
89+
approval.addButton(withTitle: "취소")
90+
let scroll = NSTextView.scrollableTextView()
91+
scroll.frame = NSRect(x: 0, y: 0, width: 430, height: 214)
92+
guard let preview = scroll.documentView as? NSTextView else { return }
93+
preview.isRichText = false
94+
preview.string = profile.text; preview.isEditable = false; preview.isSelectable = true
95+
approval.accessoryView = scroll
96+
guard approval.runModal() == .alertFirstButtonReturn else { return }
97+
guard instructionSnapshot(profile.name)?.revision == profile.revision else {
98+
showInstructionShareError("미리 보는 동안 지시가 바뀌었습니다. 새 내용을 확인한 뒤 다시 공유하세요.")
99+
return
100+
}
101+
let socket = LocalInstructionSocket(peer: peer, profile: profile)
102+
guard socket.start() else {
103+
showInstructionShareError("도우미가 종료됐거나 이전 소켓 경로가 남아 있습니다. 새 도우미와 소켓 상태를 확인하세요.")
104+
return
105+
}
106+
localInstructionSocket = socket
107+
localInstructionMenu?.state = .on
108+
let expiry = DispatchWorkItem { [weak self, weak socket] in
109+
guard let self, let socket, self.localInstructionSocket === socket else { return }
110+
self.revokeLocalInstructions()
111+
}
112+
localInstructionExpiry = expiry
113+
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(600), execute: expiry)
114+
}
115+
116+
private func instructionSnapshot(_ name: LocalInstructionProfile.Name) -> LocalInstructionProfile? {
117+
let text: String
118+
switch name {
119+
case .explain:
120+
text = CodeExplanation.effectiveInstruction(appState.explainPrompt)
121+
case .continue:
122+
text = CodeExplanation.effectiveInstruction(appState.explainPrompt) + "\n\n" + CodeExplanation.continueInstruction
123+
case .normalize:
124+
text = appState.normalizePrompt.isEmpty ? TextNormalizer.defaultInstruction : appState.normalizePrompt
125+
}
126+
return LocalInstructionProfile(name: name, text: text)
127+
}
128+
129+
private func showInstructionShareError(_ reason: String) {
130+
let alert = NSAlert()
131+
alert.messageText = "로컬 MCP 지시를 공유하지 않았습니다"
132+
alert.informativeText = reason
133+
alert.runModal()
134+
}
135+
136+
private func revokeLocalInstructions() {
137+
localInstructionExpiry?.cancel(); localInstructionExpiry = nil
138+
localInstructionSocket?.stop(); localInstructionSocket = nil
139+
localInstructionMenu?.state = .off
140+
}
141+
142+
func applicationWillTerminate(_ notification: Notification) {
143+
localSpeechSocket?.stop()
144+
revokeLocalInstructions()
65145
}
66146

67147
@objc private func openWindow() { mainWindow.show() }
148+
@objc private func openSettings() { appState.selectedTab = 4; mainWindow.show() }
149+
@objc private func openHistory() { appState.selectedTab = 2; mainWindow.show() }
68150
@objc private func stopSpeaking() { appState.stop() }
69151

70-
/// Keep running as a background TTS service after the window is closed, so the
71-
/// Services menu still works.
152+
/// Close hides only the window; the same Dock process keeps Services and MCP available.
72153
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { false }
73154

74-
/// Clicking the Dock icon with no window reopens the management window.
155+
/// Route Dock reopen to the management window, even when only the HUD is visible.
75156
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
76-
if !flag { mainWindow.show() }
77-
return true
157+
mainWindow.show()
158+
return false // window ordering was handled here
78159
}
79160

80-
// MARK: - State → status icon + overlay
161+
// MARK: - Playback overlay
81162

82163
private func observeState() {
164+
appState.$explainPrompt.dropFirst()
165+
.removeDuplicates(by: { $0.utf8.elementsEqual($1.utf8) })
166+
.sink { [weak self] _ in self?.revokeLocalInstructions() }.store(in: &cancellables)
167+
appState.$normalizePrompt.dropFirst()
168+
.removeDuplicates(by: { $0.utf8.elementsEqual($1.utf8) })
169+
.sink { [weak self] _ in self?.revokeLocalInstructions() }.store(in: &cancellables)
83170
appState.$phase
84171
.receive(on: RunLoop.main)
85172
.sink { [weak self] phase in
86173
guard let self else { return }
87174
switch phase {
88-
case .idle: self.setStatusSymbol("waveform"); self.overlay.hide()
89-
case .synthesizing: self.setStatusSymbol("ellipsis"); self.overlay.show()
90-
case .playing: self.setStatusSymbol("speaker.wave.2.fill"); self.overlay.show()
91-
case .paused: self.setStatusSymbol("pause.fill"); self.overlay.show()
175+
case .idle: self.overlay.hide()
176+
case .synthesizing, .playing, .paused: self.overlay.show()
92177
}
93178
}
94179
.store(in: &cancellables)
@@ -148,8 +233,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
148233
}
149234

150235
/// Called by ServiceProvider when the user picks "Codebasic TTS": synthesize
151-
/// the selected text (cache-first) and play it. With the app idling as an
152-
/// .accessory agent (window closed), background playback never steals focus.
236+
/// the selected text (cache-first) and play it without opening the window.
153237
func handleSelectedText(_ text: String) {
154238
let preview = text.replacingOccurrences(of: "\n", with: " ").prefix(60)
155239
Log.app.info("handleSelectedText: \(text.count) chars — \"\(preview, privacy: .public)\"")
@@ -175,8 +259,20 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
175259

176260
let appItem = NSMenuItem()
177261
main.addItem(appItem)
178-
let appMenu = NSMenu()
262+
let appMenu = NSMenu(title: "Codebasic TTS")
179263
appItem.submenu = appMenu
264+
appMenu.addItem(withTitle: "설정…", action: #selector(openSettings), keyEquivalent: ",").target = self
265+
appMenu.addItem(.separator())
266+
appMenu.addItem(withTitle: "재생 중지", action: #selector(stopSpeaking), keyEquivalent: "").target = self
267+
let local = appMenu.addItem(withTitle: "로컬 MCP 음성 입력 허용 (이번 실행)",
268+
action: #selector(toggleLocalSpeech), keyEquivalent: "")
269+
local.target = self
270+
localSpeechMenu = local
271+
let instructions = appMenu.addItem(withTitle: "로컬 MCP 지시 공유 (이번 실행)…",
272+
action: #selector(toggleLocalInstructions), keyEquivalent: "")
273+
instructions.target = self
274+
localInstructionMenu = instructions
275+
appMenu.addItem(.separator())
180276
appMenu.addItem(withTitle: "Codebasic TTS 가리기", action: #selector(NSApplication.hide(_:)), keyEquivalent: "h")
181277
appMenu.addItem(withTitle: "다른 항목 가리기",
182278
action: #selector(NSApplication.hideOtherApplications(_:)), keyEquivalent: "h")
@@ -204,6 +300,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
204300
windowItem.submenu = windowMenu
205301
windowMenu.addItem(withTitle: "최소화", action: #selector(NSWindow.performMiniaturize(_:)), keyEquivalent: "m")
206302
windowMenu.addItem(withTitle: "닫기", action: #selector(NSWindow.performClose(_:)), keyEquivalent: "w")
303+
windowMenu.addItem(.separator())
304+
windowMenu.addItem(withTitle: "Codebasic TTS 열기", action: #selector(openWindow), keyEquivalent: "").target = self
305+
windowMenu.addItem(withTitle: "재생 기록", action: #selector(openHistory), keyEquivalent: "").target = self
207306
NSApp.windowsMenu = windowMenu
208307

209308
NSApp.mainMenu = main

‎Sources/App/AppState.swift‎

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -485,23 +485,14 @@ final class AppState: ObservableObject {
485485
/// `displayText` is the human-readable source to show as the subtitle (원문 for
486486
/// TTS, 해설 prose for commentary) while `text` is what's actually synthesized
487487
/// (the 대본). When omitted, the subtitle is the spoken text.
488-
func synthesize(_ text: String, displayText: String? = nil) {
489-
// cleanInput both sides: collapse the stray line breaks a web selection or
490-
// an LLM 대본 carries (esp. math/markdown), so paragraph chunking is by
491-
// blank lines — otherwise the spoken and display chunk counts diverge and
492-
// the subtitle falls back to the 대본.
493-
let t = TextSplitter.cleanInput(text)
494-
guard !t.isEmpty else { return }
495-
let chunks = TextSplitter.paragraphs(t, maxChars: maxChunkChars)
496-
guard !chunks.isEmpty else { return }
497-
488+
func synthesize(_ text: String, displayText: String? = nil, preserveLiteral: Bool = false) {
489+
guard let input = TextSplitter.synthesisInput(text, displayText: displayText, preserveLiteral: preserveLiteral,
490+
maxChars: maxChunkChars) else { return }
491+
let chunks = input.chunks
498492
cancelActiveWork() // supersede any prior command (LLM/synthesis/playback)
499-
currentText = t // overlay label (the spoken text); do NOT touch inputText
500-
spokenChunks = chunks // spoken 대본 chunks (drive crawlFraction)
501-
// Subtitle is the human-readable source, decoupled from the audio chunking
502-
// — so it's always the 원본/해설, never the 대본, regardless of how the LLM
503-
// reformatted paragraphs (web-selected math, etc.).
504-
subtitleText = TextSplitter.cleanInput(displayText ?? t)
493+
currentText = input.text // overlay label; do not touch inputText
494+
spokenChunks = chunks
495+
subtitleText = input.displayText // human-readable source, not necessarily the spoken script
505496
chunkSentenceTimes = Array(repeating: [], count: chunks.count)
506497
telemetry.reset()
507498
player.start(expected: chunks.count)
@@ -547,6 +538,7 @@ final class AppState: ObservableObject {
547538
try Task.checkCancellation(); data.append(c)
548539
}
549540
}
541+
try Task.checkCancellation() // provider may finish without yielding or after cancel
550542
MemoryDiagnostics.sample("audio.ready", details: "audioBytes=\(data.count) timingValues=\(times.count)")
551543
self.chunkSentenceTimes[ci] = times
552544
if self.useCache {
@@ -570,8 +562,10 @@ final class AppState: ObservableObject {
570562
}
571563
self.historyRevision += 1
572564
} catch is CancellationError {
573-
self.finish()
565+
if !Task.isCancelled { self.finish() }
574566
} catch {
567+
// A superseded task must not tear down a newer run or overwrite its status.
568+
guard !Task.isCancelled else { return }
575569
// Tear playback down like finish() (stop the timer + player) but keep
576570
// the error message. Without stopTimer() a mid-playback synthesis
577571
// error left the 10 Hz timer running forever, growing memory at idle.

0 commit comments

Comments
 (0)