11import Combine
2+ import CryptoKit
23import CoreFoundation
34import Darwin
45import Foundation
@@ -68,7 +69,7 @@ import Foundation
6869 // Bounded in-memory event codes only, with no user strings or identifiers.
6970 private( set) var selectionDiagnostics : [ SelectionStatus ] = [ ]
7071 @ Published private( set) var waitingForReceiveHelper = false
71- @ Published private( set) var hasInstructionScope = false
72+ @ Published private( set) var instructionScope : String ?
7273 private var pendingReceive : ReceiveRequest ?
7374 private var pendingReceiveTask : Task < Void , Never > ?
7475 private var pendingSelection : PendingSelection ?
@@ -81,6 +82,8 @@ import Foundation
8182 private var receiptTask : Task < Void , Never > ?
8283 private var watch : DispatchSourceProcess ?
8384 private var rate = AgentRateLimit ( )
85+ private var receiptKeys : [ String : SHA256 . Digest ] = [ : ]
86+ private static let maxReceiptKeys = 128
8487 private var receiveDeadline : ContinuousClock . Instant ?
8588 private let directory : String
8689 private let bundledHelper : ( ) -> Data ?
@@ -114,11 +117,16 @@ import Foundation
114117 self . disconnect ( )
115118 }
116119 if let pair = self . pair , pair . peer != peer { response . set ( " other_agent " ) ; return }
117- if self . pair == nil && ! self . bind ( peer : peer , leaf : leaf , helperHash : hash ) {
118- response . set ( " unavailable " ) ; return
120+ if self . pair == nil {
121+ guard let approval = self . pendingReceive , ContinuousClock . now < approval . deadline else {
122+ response . set ( " approval_required " ) ; return
123+ }
124+ guard self . bind ( peer : peer , leaf : leaf , helperHash : hash ) else {
125+ response . set ( " unavailable " ) ; return
126+ }
119127 }
120128 response . set ( self . receiving
121- ? ( self . shared != nil ? " ready " : ( self . hasInstructionScope ? " instruction_required " : " receiving_only " ) )
129+ ? ( self . shared != nil ? " ready " : ( self . instructionScope != nil ? " instruction_required " : " receiving_only " ) )
122130 : ( self . shared == nil ? " approval_required " : " reading_only " ) )
123131 }
124132 guard signal . wait ( timeout : deadline ) == . success else { return Self . reply ( " unavailable " ) }
@@ -163,7 +171,7 @@ import Foundation
163171 current : @escaping @MainActor ( String ) -> AgentInstructionSnapshot ? ,
164172 deliveryGate : @escaping ( @escaping ( ) -> Void ) -> Void = { $0 ( ) } ) -> Bool {
165173 clearSelection ( )
166- hasInstructionScope = true
174+ instructionScope = snapshot . selector
167175 guard snapshot . shareable else { note ( . invalidInstruction ) ; return false }
168176 guard pairingSocket != nil else { note ( . pairingUnavailable ) ; return false }
169177 let deadline = ContinuousClock . now . advanced ( by : selectionWaiting )
@@ -196,15 +204,15 @@ import Foundation
196204 note ( . active )
197205 }
198206
199- func rejectSelection ( _ reason : SelectionStatus ) {
207+ func rejectSelection ( _ selector : String , reason : SelectionStatus ) {
200208 clearSelection ( )
201- hasInstructionScope = true
209+ instructionScope = selector
202210 note ( reason )
203211 }
204212
205213 func revokeSelection ( ) {
206214 clearSelection ( )
207- hasInstructionScope = false
215+ instructionScope = nil
208216 note ( . canceled )
209217 }
210218
@@ -293,7 +301,7 @@ import Foundation
293301 guard let self , self . pendingReceive ? . id == request . id else { return }
294302 self . cancelPendingReceive ( )
295303 self . clearSelection ( )
296- self . hasInstructionScope = false
304+ self . instructionScope = nil
297305 self . note ( . notSelected )
298306 self . status = " 연결 대기 시간이 지났습니다. "
299307 }
@@ -305,7 +313,7 @@ import Foundation
305313 cancelPendingReceive ( )
306314 guard ContinuousClock . now < request . deadline else {
307315 clearSelection ( )
308- hasInstructionScope = false
316+ instructionScope = nil
309317 note ( . notSelected )
310318 status = " 연결 대기 시간이 지났습니다. "
311319 return
@@ -318,7 +326,7 @@ import Foundation
318326 cancelPendingReceive ( )
319327 stopReceipt ( )
320328 clearSelection ( )
321- hasInstructionScope = false
329+ instructionScope = nil
322330 note ( . notSelected )
323331 status = " "
324332 }
@@ -375,21 +383,28 @@ import Foundation
375383 } else {
376384 // This is enforced here, not just by a potentially stale MCP tool status.
377385 // A selected-but-not-yet-shareable request also cannot fall back generically.
378- guard ! self . hasInstructionScope , self . shared == nil , self . pendingSelection == nil else {
386+ guard self . instructionScope == nil , self . shared == nil , self . pendingSelection == nil else {
379387 response . set ( " instruction_required " ) ; return
380388 }
381389 origin = nil
382390 }
383391 let scopedKey = AgentBytes . hash ( Data ( ( pair . id . uuidString + " \0 " + clientKey ) . utf8 ) )
384392 guard let draft = ExplanationDraft ( id : scopedKey , display : display , speech : speech ,
385- provenance : origin , sourceSession : pair . id ) else {
393+ provenance : origin ) else {
386394 response . set ( " invalid " ) ; return
387395 }
388- let previous = workspace . preflightDocument ( draft )
389- guard previous == . accepted else { response . set ( previous . rawValue ) ; return }
396+ let fingerprint = draft . fingerprint
397+ if let previous = self . receiptKeys [ clientKey ] {
398+ response . set ( previous == fingerprint ? " duplicate " : " conflict " ) ; return
399+ }
400+ guard self . receiptKeys . count < Self . maxReceiptKeys else { response . set ( " session_limit " ) ; return }
401+ guard workspace . canReceiveDocument ( ) else { response . set ( " busy " ) ; return }
390402 guard self . rate . canAccept ( ) else { response . set ( " rate_limited " ) ; return }
391403 let result = workspace . receiveDocument ( draft )
392- if result == . accepted { self . rate . mark ( ) }
404+ if result == . accepted {
405+ self . receiptKeys [ clientKey ] = fingerprint
406+ self . rate . mark ( )
407+ }
393408 response . set ( result . rawValue )
394409 }
395410 guard signal . wait ( timeout : responseDeadline ) == . success else { return Self . reply ( " unconfirmed " ) }
@@ -409,7 +424,7 @@ import Foundation
409424 do { try await ContinuousClock ( ) . sleep ( until : deadline ) } catch { return }
410425 self ? . stopReceipt ( workspace : workspace )
411426 self ? . clearSelection ( )
412- self ? . hasInstructionScope = false
427+ self ? . instructionScope = nil
413428 self ? . note ( . notSelected )
414429 self ? . status = " 대본 수신 연결이 만료되었습니다. "
415430 }
@@ -420,11 +435,18 @@ import Foundation
420435 private weak var receiptWorkspace : ExplanationDraftWorkspace ?
421436
422437 func invalidate ( _ selector : String , deleted : Bool ) {
438+ guard instructionScope == selector else { return }
439+ if deleted {
440+ clearSelection ( )
441+ instructionScope = nil
442+ note ( . notSelected )
443+ return
444+ }
423445 if shared ? . selector == selector || pendingSelection ? . snapshot . selector == selector {
424446 clearSelection ( )
425447 note ( . changed )
426448 }
427- // Previously received previews remain, but cannot reactivate access .
449+ // Previously received documents remain editable .
428450 }
429451
430452 func stopShare ( ) {
@@ -449,7 +471,8 @@ import Foundation
449471 cancelPendingReceive ( )
450472 stopReceipt ( )
451473 clearSelection ( )
452- hasInstructionScope = false
474+ instructionScope = nil
475+ receiptKeys . removeAll ( )
453476 pair = nil
454477 status = " "
455478 note ( . notSelected )
0 commit comments