Skip to content

Commit b87646c

Browse files
committed
Connect approved agent apps when the Agent tab is open (#31)
Opening the Agent tab turns draft receipt on unless the user turned it off, and posts a content-free ready signal. Live helpers listen for it and run the normal status/hello/prove exchange again, so approved apps connect without a click or tool call; unreachable apps are retried with backoff. Closing the tab keeps connections. New apps still need one approval. Receipt saved off by an older version stays off with a one-time notice. Agent: Claude Code Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015LJG7KnMPqFcfTZ8A1C2qh
1 parent 0d961e0 commit b87646c

12 files changed

Lines changed: 535 additions & 12 deletions

‎Helpers/AgentCatalogMCP.swift‎

Lines changed: 85 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import CoreFoundation
22
import Darwin
33
import Foundation
4+
import os
45
import Security
56

67
/// One native signed helper per MCP session. This executable owns both local
@@ -74,6 +75,84 @@ import Security
7475
static let registeredHost = AgentPeerSigning.registeredHost(pid: getpid())
7576
static var slot: Int?
7677

78+
// MARK: Reconnecting without a tool call
79+
//
80+
// The MCP loop and background attempts share `slot`, `clientKey` and the socket
81+
// exchange; `stateLock` serializes them. The reconnect bookkeeping below is
82+
// touched only on `pairingQueue`. Background attempts never write to stdout.
83+
static let stateLock = NSLock()
84+
static let pairingQueue = DispatchQueue(label: "codebasic-tts.agent-helper.pairing")
85+
static let log = Logger(subsystem: TTSRuntime.appID, category: "agent")
86+
static var readyToken: Int32 = 0
87+
static var attempt = 0
88+
static var retryGeneration = 0
89+
static var stopped = false
90+
static var lastSignal: ContinuousClock.Instant?
91+
static var signalPending = false
92+
93+
/// After the session's first pairing: listen for the app's ready signal and
94+
/// retry while the app is unreachable.
95+
static func startReconnecting(after status: String) {
96+
let name = AgentPairing.readyNotification(appID: AgentPeerSigning.appID)
97+
let registered = notify_register_dispatch(name, &readyToken, pairingQueue) { _ in onReadySignal() }
98+
if registered != 0 { log.error("[AGENT-CONN] helper listen result=\(registered, privacy: .public)") }
99+
pairingQueue.async { schedule(after: status) }
100+
}
101+
102+
/// Folds bursts of signals (or someone else posting the name in a loop)
103+
/// into at most one attempt per `AgentReconnect.signalInterval`.
104+
static func onReadySignal() {
105+
let now = ContinuousClock.now
106+
let interval = Duration.milliseconds(Int64(AgentReconnect.signalInterval * 1000))
107+
if let last = lastSignal, now - last < interval {
108+
guard !signalPending else { return }
109+
signalPending = true
110+
pairingQueue.asyncAfter(deadline: .now() + AgentReconnect.signalInterval) {
111+
signalPending = false
112+
lastSignal = .now
113+
attempt = 0
114+
backgroundAttempt("ready")
115+
}
116+
return
117+
}
118+
lastSignal = now
119+
attempt = 0
120+
backgroundAttempt("ready")
121+
}
122+
123+
static func backgroundAttempt(_ trigger: String) {
124+
guard !stopped else { return }
125+
stateLock.lock()
126+
let status = pairingStatus()
127+
let key = clientKey.map { String(AgentBytes.hash($0.publicKey).prefix(12)) } ?? "none"
128+
stateLock.unlock()
129+
log.info("[AGENT-CONN] helper attempt trigger=\(trigger, privacy: .public) key=\(key, privacy: .public) result=\(status, privacy: .public)")
130+
schedule(after: status)
131+
}
132+
133+
static func schedule(after status: String) {
134+
retryGeneration += 1
135+
switch AgentReconnect.next(after: status, attempt: attempt) {
136+
case .done:
137+
attempt = 0
138+
case .waitForSignal:
139+
attempt = 0
140+
log.info("[AGENT-CONN] helper wait reason=\(status, privacy: .public)")
141+
case .stop:
142+
stopped = true
143+
log.info("[AGENT-CONN] helper wait reason=terminal:\(status, privacy: .public)")
144+
case .retry(let base):
145+
let delay = AgentReconnect.jittered(base, unit: Double.random(in: 0...1))
146+
attempt += 1
147+
let generation = retryGeneration
148+
log.info("[AGENT-CONN] helper retry attempt=\(attempt, privacy: .public) delay_ms=\(Int(delay * 1000), privacy: .public) reason=\(status, privacy: .public)")
149+
pairingQueue.asyncAfter(deadline: .now() + delay) {
150+
guard generation == retryGeneration else { return }
151+
backgroundAttempt("retry")
152+
}
153+
}
154+
}
155+
77156
static func main() {
78157
// A keychain dialog raised by a background helper would block the agent's
79158
// tool call. An inaccessible registered credential stays unavailable.
@@ -91,6 +170,8 @@ import Security
91170
var initialized = false, ready = false
92171
var proofs: [Proof] = []
93172
while let input = readFrame() {
173+
stateLock.lock()
174+
defer { stateLock.unlock() }
94175
if input.isEmpty { emit(error(nil, -32700, "Malformed or oversized frame")); continue }
95176
guard let frame = decode(input), frame["jsonrpc"] as? String == "2.0",
96177
let method = frame["method"] as? String else {
@@ -99,7 +180,10 @@ import Security
99180
guard let id = frame["id"] else {
100181
if method == "notifications/initialized", initialized, !ready {
101182
ready = true
102-
_ = pairingStatus()
183+
let status = pairingStatus()
184+
let key = clientKey.map { String(AgentBytes.hash($0.publicKey).prefix(12)) } ?? "none"
185+
log.info("[AGENT-CONN] helper attempt trigger=initialized key=\(key, privacy: .public) result=\(status, privacy: .public)")
186+
startReconnecting(after: status)
103187
}
104188
continue
105189
}

‎Sources/App/AgentSessionController.swift‎

Lines changed: 96 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -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
}

‎Sources/App/AppDelegate.swift‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
256256
}
257257
appState.agentAccess.$autoReceive.sink { [weak self] in self?.draftReceiptMenu?.state = $0 ? .on : .off }
258258
.store(in: &cancellables)
259+
// The Agent tab is "open" while it is selected and its window is on screen.
260+
// Opening it connects approved agent apps; closing it keeps them connected.
261+
Publishers.CombineLatest(appState.$selectedTab, appState.$mainWindowVisible)
262+
.map { (tab: $0, visible: $1) }
263+
.removeDuplicates { ($0.tab == 1 && $0.visible) == ($1.tab == 1 && $1.visible) }
264+
.sink { [weak self] state in
265+
self?.appState.agentAccess.setPresence(state.tab == 1 && state.visible,
266+
detail: "tab=\(state.tab) window=\(state.visible ? "visible" : "hidden")")
267+
}
268+
.store(in: &cancellables)
259269
appState.$phase
260270
.receive(on: RunLoop.main)
261271
.sink { [weak self] phase in

‎Sources/App/AppState.swift‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,8 @@ final class AppState: ObservableObject {
196196
!lastSegment.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
197197
}
198198
@Published var selectedTab = 0 // RootView TabView selection
199+
/// The management window is on screen (not closed, minimized, hidden or covered).
200+
@Published var mainWindowVisible = false
199201

200202
// Per-role endpoint reference + model memory. A role points at an endpoint
201203
// (id) and remembers the model last picked for it; an unset role model

0 commit comments

Comments
 (0)