@@ -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
0 commit comments