@@ -19,6 +19,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
1919 private var localInstructionSocket : LocalInstructionSocket ?
2020 private var localInstructionMenu : NSMenuItem ?
2121 private var localInstructionExpiry : DispatchWorkItem ?
22+ private var draftReceiptSocket : LocalExplanationDraftSocket ?
23+ private var draftReceiptExpiry : DispatchWorkItem ?
24+ private var draftReceiptMenu : NSMenuItem ?
2225
2326 func applicationDidFinishLaunching ( _ notification : Notification ) {
2427 AppDelegate . shared = self
@@ -28,9 +31,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
2831 registerHotKeys ( )
2932 observeState ( )
3033
31- // Review-only 해설 (auto-play off): surface the window so it can be checked.
32- appState . onRequestReview = { [ weak self ] in self ? . mainWindow . show ( ) }
33- if appState . keyPresent { appState . refreshVoices ( ) }
34+ // Opening the app does not refresh cloud voices. Settings already
35+ // loads voice/model inventory when the user opens it.
3436 mainWindow . show ( ) // open the management window on launch
3537
3638 Log . app . info ( " Codebasic TTS launched. Backend: \( self . appState . backendIdentity , privacy : . public ) " )
@@ -60,7 +62,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
6062 }
6163
6264 // Separate consent: enabling speech must never publish instructions.
63- @ objc private func toggleLocalInstructions ( ) {
65+ @ objc private func toggleLocalInstructions ( ) { toggleInstructionSharing ( ) }
66+
67+ func toggleInstructionSharing ( preselect : LocalInstructionProfile . Name ? = nil ) {
6468 if localInstructionSocket != nil { revokeLocalInstructions ( ) ; return }
6569 let selection = NSAlert ( )
6670 selection . messageText = " 로컬 MCP 지시 공유 (이번 실행) "
@@ -71,14 +75,18 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
7175 pidField . placeholderString = " 지시 도우미 PID "
7276 let picker = NSPopUpButton ( frame : NSRect ( x : 0 , y : 0 , width : 390 , height : 26 ) )
7377 picker . addItems ( withTitles : [ " 해설 " , " 이어서 해설 " , " 음성 대본 정규화 (사전·힌트 제외) " ] )
78+ if let preselect , let index = LocalInstructionProfile . Name . allCases . firstIndex ( of : preselect ) {
79+ picker . selectItem ( at : index )
80+ picker . isEnabled = false
81+ }
7482 let fields = NSView ( frame : NSRect ( x : 0 , y : 0 , width : 390 , height : 60 ) )
7583 fields . addSubview ( pidField ) ; fields . addSubview ( picker )
7684 selection . accessoryView = fields
7785 guard selection . runModal ( ) == . alertFirstButtonReturn else { return }
7886 let names = LocalInstructionProfile . Name . allCases
7987 guard let pid = Int32 ( pidField . stringValue . trimmingCharacters ( in : . whitespacesAndNewlines ) ) ,
8088 let peer = LocalInstructionPeer . current ( pid : pid ) , names . indices . contains ( picker . indexOfSelectedItem ) ,
81- let profile = instructionSnapshot ( names [ picker . indexOfSelectedItem ] ) else {
89+ let profile = appState . instructionSnapshot ( names [ picker . indexOfSelectedItem ] ) else {
8290 showInstructionShareError ( " 같은 계정에서 계속 실행 중인 도우미의 PID와 공유할 수 있는 길이의 지시가 필요합니다. " )
8391 return
8492 }
@@ -93,8 +101,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
93101 preview . isRichText = false
94102 preview . string = profile . text ; preview . isEditable = false ; preview . isSelectable = true
95103 approval . accessoryView = scroll
96- guard approval . runModal ( ) == . alertFirstButtonReturn else { return }
97- guard instructionSnapshot ( profile . name ) ? . revision == profile . revision else {
104+ guard approval . runModal ( ) == . alertFirstButtonReturn , localInstructionSocket == nil else { return }
105+ guard appState . instructionSnapshot ( profile . name ) ? . revision == profile . revision else {
98106 showInstructionShareError ( " 미리 보는 동안 지시가 바뀌었습니다. 새 내용을 확인한 뒤 다시 공유하세요. " )
99107 return
100108 }
@@ -104,6 +112,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
104112 return
105113 }
106114 localInstructionSocket = socket
115+ appState . sharedInstructionProfile = profile . name
107116 localInstructionMenu ? . state = . on
108117 let expiry = DispatchWorkItem { [ weak self , weak socket ] in
109118 guard let self , let socket , self . localInstructionSocket === socket else { return }
@@ -113,19 +122,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
113122 DispatchQueue . main . asyncAfter ( deadline : . now ( ) + . seconds ( 600 ) , execute : expiry )
114123 }
115124
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-
129125 private func showInstructionShareError ( _ reason : String ) {
130126 let alert = NSAlert ( )
131127 alert . messageText = " 로컬 MCP 지시를 공유하지 않았습니다 "
@@ -136,12 +132,62 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
136132 private func revokeLocalInstructions ( ) {
137133 localInstructionExpiry ? . cancel ( ) ; localInstructionExpiry = nil
138134 localInstructionSocket ? . stop ( ) ; localInstructionSocket = nil
135+ appState . sharedInstructionProfile = nil
139136 localInstructionMenu ? . state = . off
140137 }
141138
139+ @ objc func toggleDraftReceipt ( ) {
140+ if draftReceiptSocket != nil { revokeDraftReceipt ( ) ; return }
141+ let alert = NSAlert ( )
142+ alert . messageText = " 외부 에이전트 대본 받기 "
143+ alert . informativeText = " 지정한 도우미의 대본만 최대 10분 동안 임시 보관함에 받습니다. 화면을 덮어쓰거나 재생하지 않으며, 지시문 조회도 허용하지 않습니다. "
144+ alert . addButton ( withTitle : " 이 도우미만 허용 " )
145+ alert . addButton ( withTitle : " 취소 " )
146+ let field = NSTextField ( frame : NSRect ( x : 0 , y : 0 , width : 360 , height : 24 ) )
147+ field . placeholderString = " 대본 도우미 PID "
148+ alert . accessoryView = field
149+ guard alert . runModal ( ) == . alertFirstButtonReturn , draftReceiptSocket == nil else { return }
150+ guard let pid = Int32 ( field . stringValue . trimmingCharacters ( in : . whitespacesAndNewlines ) ) ,
151+ let peer = LocalInstructionPeer . current ( pid : pid ) else {
152+ showDraftReceiptError ( " 같은 Mac 계정에서 현재 실행 중인 대본 도우미 PID가 필요합니다. " )
153+ return
154+ }
155+
156+ let workspace = appState . explanationDrafts
157+ let socket = LocalExplanationDraftSocket ( peer : peer ) { draft in workspace . receive ( draft ) }
158+ guard socket . start ( ) else {
159+ showDraftReceiptError ( " 도우미가 종료됐거나 대본 소켓 경로가 이미 사용 중입니다. " )
160+ return
161+ }
162+ draftReceiptSocket = socket
163+ workspace . setReceiver ( pid )
164+ draftReceiptMenu ? . state = . on
165+ let expiry = DispatchWorkItem { [ weak self , weak socket ] in
166+ guard let self , let socket , self . draftReceiptSocket === socket else { return }
167+ self . revokeDraftReceipt ( )
168+ }
169+ draftReceiptExpiry = expiry
170+ DispatchQueue . main . asyncAfter ( deadline : . now ( ) + . seconds ( 600 ) , execute : expiry )
171+ }
172+
173+ private func showDraftReceiptError ( _ message : String ) {
174+ let alert = NSAlert ( )
175+ alert . messageText = " 대본 받기를 허용하지 않았습니다 "
176+ alert . informativeText = message
177+ alert . runModal ( )
178+ }
179+
180+ private func revokeDraftReceipt ( ) {
181+ draftReceiptExpiry ? . cancel ( ) ; draftReceiptExpiry = nil
182+ draftReceiptSocket ? . stop ( ) ; draftReceiptSocket = nil
183+ appState . explanationDrafts . setReceiver ( nil )
184+ draftReceiptMenu ? . state = . off
185+ }
186+
142187 func applicationWillTerminate ( _ notification : Notification ) {
143188 localSpeechSocket ? . stop ( )
144189 revokeLocalInstructions ( )
190+ revokeDraftReceipt ( )
145191 }
146192
147193 @ objc private func openWindow ( ) { mainWindow . show ( ) }
@@ -183,21 +229,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
183229
184230 private let hotKeys = HotKeyCenter ( )
185231
186- /// ⌃⌥⌘E → explain the selection, ⌃⌥⌘R → read it aloud. The selection is
232+ /// ⌃⌥⌘R → read the selection aloud. The selection is
187233 /// grabbed via a clipboard-preserving copy, so it works even where the
188234 /// Services menu is hidden (VS Code). First use prompts for Accessibility.
189235 private func registerHotKeys ( ) {
190236 let mods = controlKey | optionKey | cmdKey
191- hotKeys . register ( id : 1 , keyCode : kVK_ANSI_E , modifiers : mods ) { [ weak self ] in
192- self ? . appState . captureHUDTarget ( ) // before the async grab: mouse is still on the target screen
193- SelectionGrabber . grab { text in
194- guard let self , let text else { return }
195- MainActor . assumeIsolated {
196- self . appState . selectedTab = 1
197- self . appState . explainAndSpeak ( text )
198- }
199- }
200- }
201237 hotKeys . register ( id : 2 , keyCode : kVK_ANSI_R , modifiers : mods ) { [ weak self ] in
202238 self ? . appState . captureHUDTarget ( ) // before the async grab: mouse is still on the target screen
203239 SelectionGrabber . grab { text in
@@ -207,24 +243,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
207243 }
208244 }
209245
210- // MARK: - ⌘V paste (intercept to attach screenshots in the 해설 탭)
211-
212- /// The Edit-menu 붙여넣기 (⌘V) routes here. In the 해설 탭, an image on the
213- /// clipboard is attached as a screenshot; otherwise (and for text) the paste
214- /// is forwarded to the first responder for normal handling.
215- @ objc func handlePaste ( _ sender : Any ? ) {
216- if appState . selectedTab == 1 {
217- let pb = NSPasteboard . general
218- let hasImage = ( pb . readObjects ( forClasses : [ NSImage . self ] , options : nil ) as? [ NSImage ] ) ?
219- . contains { ! $0 . size . equalTo ( . zero ) } ?? false
220- if hasImage {
221- appState . pasteImagesFromClipboard ( )
222- if ! pb . canReadObject ( forClasses : [ NSString . self ] , options : nil ) { return } // image-only → done
223- }
224- }
225- NSApp . sendAction ( #selector( NSText . paste ( _ : ) ) , to : nil , from : sender ) // normal text paste
226- }
227-
228246 // MARK: - Services
229247
230248 private func registerServices ( ) {
@@ -241,17 +259,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
241259 appState . speakSelected ( text )
242260 }
243261
244- /// Called by ServiceProvider when the user picks "코드 해설": explain the
245- /// selected code via the LLM, then speak the commentary (코드 → 해설 → 대본 →
246- /// 음성). Surfaces the 해설 tab so the result is visible.
247- func handleCodeText ( _ code : String ) {
248- let preview = code . replacingOccurrences ( of : " \n " , with : " " ) . prefix ( 60 )
249- Log . app . info ( " handleCodeText: \( code . count ) chars — \" \( preview , privacy : . public ) \" " )
250- appState . captureHUDTarget ( )
251- appState . selectedTab = 1 // 해설 탭 (2번째)
252- appState . explainAndSpeak ( code )
253- }
254-
255262 // MARK: - Main menu (regular app needs one for ⌘Q and text-editing shortcuts)
256263
257264 private func setUpMainMenu ( ) {
@@ -272,6 +279,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
272279 action : #selector( toggleLocalInstructions ) , keyEquivalent : " " )
273280 instructions . target = self
274281 localInstructionMenu = instructions
282+ let draftReceipt = appMenu . addItem ( withTitle : " 외부 대본 받기 허용 (이번 실행)… " ,
283+ action : #selector( toggleDraftReceipt ) , keyEquivalent : " " )
284+ draftReceipt . target = self
285+ draftReceiptMenu = draftReceipt
275286 appMenu . addItem ( . separator ( ) )
276287 appMenu . addItem ( withTitle : " Codebasic TTS 가리기 " , action : #selector( NSApplication . hide ( _ : ) ) , keyEquivalent : " h " )
277288 appMenu . addItem ( withTitle : " 다른 항목 가리기 " ,
@@ -289,9 +300,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
289300 editMenu . addItem ( . separator ( ) )
290301 editMenu . addItem ( withTitle : " 오려두기 " , action : #selector( NSText . cut ( _ : ) ) , keyEquivalent : " x " )
291302 editMenu . addItem ( withTitle : " 복사 " , action : #selector( NSText . copy ( _ : ) ) , keyEquivalent : " c " )
292- let pasteItem = NSMenuItem ( title : " 붙여넣기 " , action : #selector( handlePaste ( _ : ) ) , keyEquivalent : " v " )
293- pasteItem . target = self
294- editMenu . addItem ( pasteItem )
303+ editMenu . addItem ( withTitle : " 붙여넣기 " , action : #selector( NSText . paste ( _ : ) ) , keyEquivalent : " v " )
295304 editMenu . addItem ( withTitle : " 전체 선택 " , action : #selector( NSText . selectAll ( _ : ) ) , keyEquivalent : " a " )
296305
297306 let windowItem = NSMenuItem ( )
0 commit comments