@@ -149,6 +149,26 @@ import Security
149149 @ Published private( set) var trusted : [ AgentTrustedClient ] = [ ]
150150 @ Published private( set) var autoReceive = false
151151 @ Published private( set) var locked = false
152+ /// `off` only after the user turned receipt off; opening the Agent tab then
153+ /// leaves it off.
154+ @ Published private( set) var receiptChoice : AgentReceiptChoice = . auto
155+ /// Receipt was saved as off by a version that could not tell why. Shown once.
156+ @ Published private( set) var legacyReceiptOff = false
157+ @ Published private( set) var pairingActive = false
158+ /// The Agent tab is selected and its window is on screen.
159+ @ Published private( set) var presenceOpen = false
160+ /// The tab has been open for a while and no helper has shown up.
161+ @ Published private( set) var noAgentSession = false
162+
163+ struct Attempt {
164+ let at : Date
165+ let result : String
166+ }
167+ /// The latest reconnect result per remembered app, as the app saw it. Memory only.
168+ @ Published private( set) var lastAttempts : [ UUID : Attempt ] = [ : ]
169+ private var readySequence = 0
170+ private var noSessionTask : Task < Void , Never > ?
171+ private let noSessionDelay : Duration
152172 private let trust : AgentTrustStore
153173 private var context : ReceiveContext ?
154174 private var challenges : [ Challenge ] = [ ]
@@ -170,22 +190,28 @@ import Security
170190 init ( directory : String = LocalApprovedSocket . defaultDirectory ,
171191 bundledHelper : @escaping ( ) -> Data ? = AgentPeerSigning . bundledHelperHash ,
172192 selectionWaiting : Duration = . seconds ( 90 ) ,
193+ noSessionDelay : Duration = . seconds ( 5 ) ,
173194 trust : AgentTrustStore = AgentTrustStore (
174195 url : TTSRuntime . applicationSupport ( ) . appendingPathComponent ( " agent-clients.json " ) ) ) {
175196 self . directory = directory
176197 self . bundledHelper = bundledHelper
177198 self . selectionWaiting = selectionWaiting
199+ self . noSessionDelay = noSessionDelay
178200 self . trust = trust
179201 trusted = trust . clients
180202 autoReceive = trust . autoReceive
203+ receiptChoice = trust . receiptChoice
204+ legacyReceiptOff = trust . legacyReceiptOff
181205 refreshConnections ( )
182206 }
183207
184208 /// Where received drafts go. Needed before an approved client can resume
185209 /// without a click, so the app sets it at launch.
186210 func configure ( current : @escaping @MainActor ( String ) -> AgentInstructionSnapshot ? ,
187211 workspace : ExplanationDraftWorkspace ) {
212+ let first = context == nil
188213 context = ReceiveContext ( current : current , workspace : workspace )
214+ if first { postReady ( " configure " ) }
189215 }
190216
191217 @ discardableResult
@@ -239,12 +265,16 @@ import Security
239265 return false
240266 }
241267 pairingSocket = socket
268+ pairingActive = true
269+ if status == LocalApprovedSocket . unknownPathMessage || status . hasPrefix ( " 다른 앱 인스턴스 " ) { status = " " }
270+ postReady ( " launch " )
242271 return true
243272 }
244273
245274 /// Quitting drops live leases while preserving the user's saved choices.
246275 func stopPairing ( ) {
247276 pairingSocket ? . stop ( ) ; pairingSocket = nil
277+ pairingActive = false
248278 clearApprovals ( )
249279 for client in Array ( bindings . keys ) { dropBinding ( client , keepSelection : false ) }
250280 }
@@ -253,6 +283,7 @@ import Security
253283 let receivingPairs = bindings . values . filter { $0 . receipt != nil }
254284 let hasReceipt = ! receivingPairs . isEmpty
255285 if receiving != hasReceipt { receiving = hasReceipt }
286+ if noAgentSession , ! bindings . isEmpty { noAgentSession = false }
256287 context ? . workspace . setReceiver ( receivingPairs . first ? . pair . peer . pid )
257288 let remembered = trusted . map { record in
258289 let live = bindings [ record . id ]
@@ -364,6 +395,9 @@ import Security
364395 outcome = [ " status " : requestApproval ( claim , leaf : leaf , helperHash : helperHash ) ]
365396 }
366397 Self . logConnect ( claim : claim , lookup : lookup , result : outcome [ " status " ] ?? " ? " )
398+ if case . trusted ( let record ) = lookup {
399+ lastAttempts [ record . id ] = Attempt ( at : Date ( ) , result : outcome [ " status " ] ?? " ? " )
400+ }
367401 return outcome
368402 }
369403
@@ -485,6 +519,8 @@ import Security
485519 watcher . setEventHandler { [ weak self ] in
486520 guard let self , self . bindings [ client ] ? . pair . id == next . id else { return }
487521 self . dropBinding ( client , keepSelection : next . persistent )
522+ // Another session of the same app may have been told other_agent.
523+ self . postReady ( " binding_drop " )
488524 }
489525 let binding = Binding ( pair : next , watch : watcher )
490526 bindings [ client ] = binding
@@ -632,23 +668,73 @@ import Security
632668 @ discardableResult
633669 func enableReceive ( current : @escaping @MainActor ( String ) -> AgentInstructionSnapshot ? ,
634670 workspace : ExplanationDraftWorkspace ) -> Bool {
635- guard ! locked , startPairing ( ) , setAutoReceive ( true ) else { return false }
671+ configure ( current : current , workspace : workspace )
672+ guard turnOnReceive ( byUser : true , reason : " user " ) else { return false }
636673 // Turning receipt back on by hand starts every client's allowance over.
637674 rates . removeAll ( )
638- configure ( current : current , workspace : workspace )
675+ return true
676+ }
677+
678+ private func turnOnReceive ( byUser : Bool , reason : String ) -> Bool {
679+ guard ! locked , startPairing ( ) , setAutoReceive ( true , byUser : byUser ) else { return false }
680+ Log . agent . info ( " [AGENT-CONN] receipt choice= \( self . receiptChoice . rawValue , privacy : . public ) set=on reason= \( reason , privacy : . public ) " )
639681 dropIfGone ( )
640682 for binding in bindings . values { _ = activateReceive ( binding ) }
641683 refreshConnections ( )
684+ postReady ( byUser ? " receipt_on " : reason )
642685 return true
643686 }
644687
645- private func setAutoReceive ( _ value : Bool ) -> Bool {
646- let saved = trust . setAutoReceive ( value )
688+ private func setAutoReceive ( _ value : Bool , byUser : Bool = true ) -> Bool {
689+ let saved = trust . setAutoReceive ( value , byUser : byUser )
647690 if ! saved { status = " 대본 받기 설정을 저장하지 못했습니다. " }
648691 if saved || ! value { autoReceive = value }
692+ receiptChoice = trust . receiptChoice
693+ legacyReceiptOff = trust . legacyReceiptOff
649694 return saved
650695 }
651696
697+ /// The Agent tab opened or closed. Opening it is the user's sign to be
698+ /// connected: receipt turns on unless the user turned it off, and live helpers
699+ /// are asked to prove themselves again. Closing it changes nothing; approved
700+ /// apps keep sending while the window is closed.
701+ func setPresence ( _ open : Bool , detail : String = " " ) {
702+ guard presenceOpen != open else { return }
703+ presenceOpen = open
704+ Log . agent . info ( " [AGENT-CONN] presence state= \( open ? " open " : " closed " , privacy : . public ) \( detail , privacy : . public ) " )
705+ noSessionTask ? . cancel ( ) ; noSessionTask = nil
706+ noAgentSession = false
707+ guard open else { return }
708+ if pairingSocket == nil { _ = startPairing ( ) }
709+ if ! autoReceive {
710+ if locked {
711+ Log . agent . info ( " [AGENT-CONN] receipt choice= \( self . receiptChoice . rawValue , privacy : . public ) skip reason=locked " )
712+ } else if receiptChoice == . off {
713+ Log . agent . info ( " [AGENT-CONN] receipt choice=off skip reason= \( self . legacyReceiptOff ? " migration " : " user_off " , privacy : . public ) " )
714+ } else if context != nil {
715+ _ = turnOnReceive ( byUser : false , reason : " tab_open " )
716+ }
717+ }
718+ postReady ( " tab_open " )
719+ let delay = noSessionDelay
720+ noSessionTask = Task { [ weak self ] in
721+ do { try await ContinuousClock ( ) . sleep ( for : delay ) } catch { return }
722+ guard let self , self . presenceOpen else { return }
723+ self . noAgentSession = self . bindings . isEmpty && self . approvalRequests . isEmpty
724+ if self . noAgentSession { Log . agent . info ( " [AGENT-CONN] presence no_session after_ms= \( delay . components . seconds * 1000 , privacy : . public ) " ) }
725+ }
726+ }
727+
728+ /// Wakes every live helper of this app. Only sent when a helper could
729+ /// actually connect now.
730+ private func postReady ( _ reason : String ) {
731+ guard pairingSocket != nil , context != nil , autoReceive , ! locked else { return }
732+ readySequence += 1
733+ let name = AgentPairing . readyNotification ( appID : AgentPeerSigning . appID )
734+ let result = notify_post ( name )
735+ Log . agent . info ( " [AGENT-CONN] ready post reason= \( reason , privacy : . public ) seq= \( self . readySequence , privacy : . public ) result= \( result == 0 ? " ok " : String ( result ) , privacy : . public ) " )
736+ }
737+
652738 @ discardableResult
653739 private func activateReceive ( _ binding : Binding ) -> Bool {
654740 guard let context , autoReceive , ! locked , binding . receiptEnabled else { return false }
@@ -662,6 +748,7 @@ import Security
662748 clearApprovals ( )
663749 status = " "
664750 _ = setAutoReceive ( false )
751+ Log . agent . info ( " [AGENT-CONN] receipt choice=off set=off reason=user " )
665752 for binding in bindings . values { stopReceipt ( binding ) }
666753 clearSelection ( )
667754 instructionScope = nil
@@ -675,7 +762,7 @@ import Security
675762 guard locked != value else { return }
676763 locked = value
677764 defer { refreshConnections ( ) }
678- guard value else { status = " " ; return }
765+ guard value else { status = " " ; postReady ( " unlock " ) ; return }
679766 clearApprovals ( )
680767 for ( client , binding ) in Array ( bindings ) { dropBinding ( client , keepSelection : binding . pair . persistent ) }
681768 status = " 화면이 잠겨 대본 받기를 멈췄습니다. "
@@ -715,7 +802,10 @@ import Security
715802 defer { refreshConnections ( ) }
716803 // Resuming this client by hand starts its allowance over.
717804 rates [ client ] = nil
718- guard let binding = bindings [ client ] else { return row . persistent }
805+ guard let binding = bindings [ client ] else {
806+ if row . persistent { postReady ( " resume " ) }
807+ return row . persistent
808+ }
719809 binding . receiptEnabled = true
720810 return activateReceive ( binding )
721811 }
0 commit comments