Skip to content

Commit f3ddb9a

Browse files
committed
Adopt approvals changed by others; fail closed when the file disappears (#31)
Third review (Codex objected, Antigravity agreed): - The socket holder notices when the approvals file changed since its own last read or write (for example an older app version running beside it) and adopts it before proving, approving or any change. A missing or unreadable file after approvals were known means no trust and receipt off; revocations are kept, and an unsaved denial is merged on top of what is on disk. - A change attempted without the socket first tries to take it over, so a window left after the previous holder quit works; the refusal message clears once it holds the socket. - Screen lock and an inactive console session are tracked separately; receipt resumes only when neither holds. - Retry restarts the "no session" check. Docs and comments say the old-version notice stays until the user turns receipt on or off. - Fixture reconnect waits: 3 s (one signal interval plus jitter and margin). Agent: Claude Code Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015LJG7KnMPqFcfTZ8A1C2qh
1 parent 4da03f7 commit f3ddb9a

6 files changed

Lines changed: 97 additions & 28 deletions

File tree

‎Sources/App/AgentSessionController.swift‎

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,7 @@ import Security
170170
/// The latest reconnect result per remembered app, as the app saw it. Memory only.
171171
@Published private(set) var lastAttempts: [UUID: Attempt] = [:]
172172
private var readySequence = 0
173+
private var lockReasons: Set<String> = []
173174
private var noSessionTask: Task<Void, Never>?
174175
private let noSessionDelay: Duration
175176
private let trust: AgentTrustStore
@@ -271,7 +272,8 @@ import Security
271272
pairingActive = true
272273
// Another instance may have held the socket until now and changed approvals.
273274
adoptStoreAfterTakeover()
274-
if status == LocalApprovedSocket.unknownPathMessage || status.hasPrefix("다른 앱 인스턴스") { status = "" }
275+
if status == LocalApprovedSocket.unknownPathMessage || status.hasPrefix("다른 앱 인스턴스")
276+
|| status.hasPrefix("다른 Codebasic TTS가") { status = "" }
275277
postReady("launch")
276278
return true
277279
}
@@ -387,6 +389,8 @@ import Security
387389
if locked { return ["status": "locked"] }
388390
if blockedPeers.contains(peer) { return ["status": "revoked"] }
389391
if let binding = binding(for: peer) { return bound(binding) }
392+
adoptIfChanged()
393+
if blockedPeers.contains(peer) { return ["status": "revoked"] }
390394
let lookup = trust.lookup(keyID: claim.keyID, host: claim.host ?? "")
391395
let outcome: [String: String]
392396
switch lookup {
@@ -686,7 +690,9 @@ import Security
686690
}
687691

688692
private func turnOnReceive(byUser: Bool, reason: String) -> Bool {
689-
guard !locked, startPairing(), setAutoReceive(true, byUser: byUser) else { return false }
693+
guard !locked, startPairing() else { return false }
694+
adoptIfChanged()
695+
guard setAutoReceive(true, byUser: byUser) else { return false }
690696
Log.agent.info("[AGENT-CONN] receipt choice=\(self.receiptChoice.rawValue, privacy: .public) set=on reason=\(reason, privacy: .public)")
691697
dropIfGone()
692698
for binding in bindings.values { _ = activateReceive(binding) }
@@ -716,6 +722,11 @@ import Security
716722
noAgentSession = false
717723
guard open else { return }
718724
connectForPresence()
725+
scheduleNoSessionCheck()
726+
}
727+
728+
private func scheduleNoSessionCheck() {
729+
noSessionTask?.cancel()
719730
let delay = noSessionDelay
720731
noSessionTask = Task { [weak self] in
721732
do { try await ContinuousClock().sleep(for: delay) } catch { return }
@@ -748,24 +759,37 @@ import Security
748759
func retryPairing() {
749760
guard startPairing() else { return }
750761
noAgentSession = false
751-
if presenceOpen { connectForPresence() }
762+
if presenceOpen {
763+
connectForPresence()
764+
scheduleNoSessionCheck()
765+
}
752766
}
753767

754768
/// Only the instance holding the pairing socket changes approvals or receipt.
755769
/// A second instance shows them but cannot write over the holder's file.
756770
private func ownsPolicy() -> Bool {
771+
// The previous holder may have quit since; take the socket over if free.
772+
if pairingSocket == nil { _ = startPairing() }
757773
guard pairingSocket != nil else {
758774
status = "다른 Codebasic TTS가 에이전트 연결을 관리하고 있어 이 창에서는 바꿀 수 없습니다."
759775
Log.agent.info("[AGENT-CONN] policy change refused reason=not_socket_owner")
760776
return false
761777
}
778+
adoptIfChanged()
762779
return true
763780
}
764781

782+
/// Something other than this instance wrote the approvals file.
783+
private func adoptIfChanged() {
784+
guard trust.changedOnDisk else { return }
785+
Log.agent.info("[AGENT-CONN] policy adopt reason=external_change")
786+
adoptStoreAfterTakeover()
787+
}
788+
765789
/// Adopts what the previous socket holder saved: a revoked or forgotten app
766790
/// loses any live lease, and receipt turned off there stays off here.
767791
private func adoptStoreAfterTakeover() {
768-
trust.reloadForTakeover()
792+
trust.adoptDisk()
769793
let wasOn = autoReceive
770794
trusted = trust.clients
771795
autoReceive = trust.autoReceive
@@ -830,7 +854,11 @@ import Security
830854
}
831855

832856
/// Unlocking leaves each receipt stopped until the remembered peer proves its key.
833-
func setLocked(_ value: Bool) {
857+
/// Screen lock and an inactive console session are separate reasons; receipt
858+
/// resumes only when neither holds.
859+
func setLocked(_ value: Bool, reason: String = "screen") {
860+
if value { lockReasons.insert(reason) } else { lockReasons.remove(reason) }
861+
let value = !lockReasons.isEmpty
834862
guard locked != value else { return }
835863
locked = value
836864
defer { refreshConnections() }

‎Sources/App/AppDelegate.swift‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -187,18 +187,18 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
187187
private func observeSessionLock() {
188188
let access = appState.agentAccess
189189
if let session = CGSessionCopyCurrentDictionary() as? [String: Any],
190-
(session["CGSSessionScreenIsLocked"] as? Bool) == true { access.setLocked(true) }
190+
(session["CGSSessionScreenIsLocked"] as? Bool) == true { access.setLocked(true, reason: "screen") }
191191
let distributed = DistributedNotificationCenter.default()
192192
for (name, value) in [("com.apple.screenIsLocked", true), ("com.apple.screenIsUnlocked", false)] {
193193
distributed.addObserver(forName: Notification.Name(name), object: nil, queue: .main) { _ in
194-
MainActor.assumeIsolated { access.setLocked(value) }
194+
MainActor.assumeIsolated { access.setLocked(value, reason: "screen") }
195195
}
196196
}
197197
let workspace = NSWorkspace.shared.notificationCenter
198198
for (name, value) in [(NSWorkspace.sessionDidResignActiveNotification, true),
199199
(NSWorkspace.sessionDidBecomeActiveNotification, false)] {
200200
workspace.addObserver(forName: name, object: nil, queue: .main) { _ in
201-
MainActor.assumeIsolated { access.setLocked(value) }
201+
MainActor.assumeIsolated { access.setLocked(value, reason: "session") }
202202
}
203203
}
204204
}

‎Sources/Core/AgentTrustStore.swift‎

Lines changed: 44 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ final class AgentTrustStore {
7373
private var hasUnsavedDenial = false
7474
/// The file existed and was ours when the app started.
7575
private let loadedExisting: Bool
76+
private var diskStamp: [Int64]?
7677

7778
init(url: URL, now: @escaping () -> Date = Date.init,
7879
write: @escaping (Data, URL) throws -> Void = AgentTrustStore.writePrivately) {
@@ -82,6 +83,7 @@ final class AgentTrustStore {
8283
if let loaded = Self.read(url) {
8384
file = loaded
8485
loadedExisting = true
86+
diskStamp = Self.stamp(url)
8587
} else {
8688
file = File()
8789
loadedExisting = false
@@ -92,20 +94,48 @@ final class AgentTrustStore {
9294
}
9395
}
9496

95-
/// Only the instance that holds the pairing socket writes this file. When a
96-
/// standby instance takes the socket over, it reads what the previous holder
97-
/// saved. If the file cannot be read, nothing is trusted and receipt is off;
98-
/// an unsaved denial of this instance stays in force.
99-
func reloadForTakeover() {
97+
/// Only the instance that holds the pairing socket writes this file. It
98+
/// adopts the file again when it takes the socket over, and whenever the file
99+
/// changed since its own last read or write (an older app version running
100+
/// beside it does not check ownership). Missing or unreadable after this
101+
/// instance knew approvals: nothing is trusted and receipt is off. Keys this
102+
/// instance revoked stay revoked, and an unsaved denial is kept on top.
103+
func adoptDisk() {
104+
defer { diskStamp = Self.stamp(url) }
100105
if let loaded = Self.read(url) {
101-
guard !hasUnsavedDenial else { return }
102-
file = loaded
103-
} else if !hasUnsavedDenial {
104-
var meta = stat()
105-
let missing = lstat(url.path, &meta) != 0 && errno == ENOENT
106-
// A missing file keeps a first launch's in-memory choice; anything else fails closed.
107-
if !missing { file = File(); file.receiptChoice = .off }
106+
guard hasUnsavedDenial else { file = loaded; return }
107+
var merged = loaded
108+
merged.revoked = loaded.revoked + file.revoked.filter { !loaded.revoked.contains($0) }
109+
merged.clients = loaded.clients.compactMap { disk in
110+
guard !merged.revoked.contains(disk.keyID),
111+
let mine = file.clients.first(where: { $0.id == disk.id }) else { return nil }
112+
var client = disk
113+
client.receivesDrafts = disk.receiptEnabled && mine.receiptEnabled
114+
return client
115+
}
116+
merged.autoReceive = loaded.autoReceive && file.autoReceive
117+
if !file.autoReceive { merged.receiptChoice = .off }
118+
file = merged
119+
return
108120
}
121+
var meta = stat()
122+
let missing = lstat(url.path, &meta) != 0 && errno == ENOENT
123+
// A first launch that never had a file keeps its in-memory choice.
124+
guard !missing || loadedExisting || diskStamp != nil || !file.clients.isEmpty else { return }
125+
var closed = File()
126+
closed.receiptChoice = .off
127+
closed.revoked = file.revoked
128+
file = closed
129+
hasUnsavedDenial = true
130+
}
131+
132+
/// The file is not what this instance last read or wrote.
133+
var changedOnDisk: Bool { Self.stamp(url) != diskStamp }
134+
135+
private static func stamp(_ url: URL) -> [Int64]? {
136+
var meta = stat()
137+
guard lstat(url.path, &meta) == 0 else { return nil }
138+
return [Int64(meta.st_ino), Int64(meta.st_mtimespec.tv_sec), Int64(meta.st_mtimespec.tv_nsec), Int64(meta.st_size)]
109139
}
110140

111141
var clients: [AgentTrustedClient] { file.clients }
@@ -115,7 +145,7 @@ final class AgentTrustStore {
115145
/// tell whether the user turned it off, so it stays off and the app says so once.
116146
var receiptChoice: AgentReceiptChoice { file.receiptChoice ?? (file.autoReceive ? .auto : .off) }
117147

118-
/// True until the user turns receipt on or off once in this version.
148+
/// Shown until the user turns receipt on or off in this version.
119149
var legacyReceiptOff: Bool { loadedExisting && file.receiptChoice == nil && !file.autoReceive }
120150

121151
/// `byUser: false` is the Agent tab turning receipt on by itself; it keeps the
@@ -210,6 +240,7 @@ final class AgentTrustStore {
210240
guard let bytes = try? JSONEncoder().encode(next), (try? write(bytes, url)) != nil else { return false }
211241
file = next
212242
hasUnsavedDenial = false
243+
diskStamp = Self.stamp(url)
213244
return true
214245
}
215246

‎Tests/AgentTrustStoreTests.swift‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,13 +60,23 @@ import Foundation
6060
let sharedClient = try holder.trust(publicKey: sharedKey, label: "Agent", host: hostA)
6161
precondition(holder.setAutoReceive(true))
6262
precondition(holder.forget(sharedClient.id) && holder.setAutoReceive(false))
63-
standby.reloadForTakeover()
63+
standby.adoptDisk()
6464
precondition(standby.clients.isEmpty && !standby.autoReceive && standby.receiptChoice == .off)
6565
precondition(standby.lookup(keyID: AgentPairingProof.keyID(sharedKey)!, host: hostA) == .revoked)
6666
precondition(!standby.setAutoReceive(true, byUser: false) && !standby.autoReceive)
6767
let onBadFile = AgentTrustStore(url: directory.appendingPathComponent("fresh.json"))
68+
// An older app writing beside the holder is noticed; a deleted file after
69+
// approvals were known means no trust, with the revocation kept.
70+
let readd = try holder.trust(publicKey: P256.Signing.PrivateKey().publicKey.x963Representation, label: "B", host: hostB)
71+
precondition(!holder.changedOnDisk && standby.changedOnDisk)
72+
standby.adoptDisk()
73+
precondition(standby.clients.map(\.id) == [readd.id] && !standby.changedOnDisk)
74+
precondition(unlink(sharedURL.path) == 0 && standby.changedOnDisk)
75+
standby.adoptDisk()
76+
precondition(standby.clients.isEmpty && standby.receiptChoice == .off && !standby.autoReceive)
77+
precondition(standby.lookup(keyID: AgentPairingProof.keyID(sharedKey)!, host: hostA) == .revoked)
6878
precondition(chmod(directory.appendingPathComponent("fresh.json").path, 0o644) == 0)
69-
onBadFile.reloadForTakeover()
79+
onBadFile.adoptDisk()
7080
precondition(onBadFile.clients.isEmpty && onBadFile.receiptChoice == .off && !onBadFile.autoReceive)
7181

7282
// Reconnect policy shared with the helper.

‎Tests/Fixtures/run_agent_app_connections.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -392,13 +392,13 @@ def connect_state(server):
392392

393393
server.end()
394394
server = app()
395-
assert wait_for(lambda: state_of(server, client_a["id"]) == "receiving", timeout=2.0), clients(server)
395+
assert wait_for(lambda: state_of(server, client_a["id"]) == "receiving", timeout=3.0), clients(server)
396396
check("after an app restart the live helper reattaches on the ready signal, without a tool call")
397397

398398
assert server("lock") == "ok"
399399
assert state_of(server, client_a["id"]) == "locked"
400400
assert server("unlock") == "ok"
401-
assert wait_for(lambda: state_of(server, client_a["id"]) == "receiving", timeout=2.0), clients(server)
401+
assert wait_for(lambda: state_of(server, client_a["id"]) == "receiving", timeout=3.0), clients(server)
402402
check("unlock reconnects the approved app without a tool call")
403403

404404
assert server("disable") == "ok"
@@ -410,7 +410,7 @@ def connect_state(server):
410410
time.sleep(1.5)
411411
assert state_of(server, client_a["id"]) == "paused" and requests(server) == []
412412
assert server("enable") == "ok"
413-
assert wait_for(lambda: state_of(server, client_a["id"]) == "receiving", timeout=2.0), clients(server)
413+
assert wait_for(lambda: state_of(server, client_a["id"]) == "receiving", timeout=3.0), clients(server)
414414
check("receipt the user turned off stays off when the tab opens; turning it on reconnects at once")
415415

416416
server.end()

‎docs/mcp-explanation-drafts.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,9 +80,9 @@ Helpers/tts_mcp_client.py --helper "<앱>/Contents/Helpers/CodebasicAgentMCP" se
8080

8181
앱은 탭 열림 외에 앱 시작(받기 켜짐일 때), 화면 잠금 해제, 전체·앱별 받기 켜기, 도우미 프로세스 종료 때도 신호를 보냅니다. 도우미는 신호에 따른 시도를 앞 시도가 끝난 뒤 최소 1초 간격으로, 0~250ms 지터를 두고 합니다. 앱에 닿지 못한 도우미(`app_unavailable`, `unavailable`)는 2초부터 두 배씩 최대 5분 간격(±20%)으로 다시 시도하고, `locked`·`disabled`·`other_agent`·`approval_required`는 다음 신호를 기다리며, `revoked`·`signing_required`·`upgrade_required`에서는 도우미를 다시 시작할 때까지 멈춥니다.
8282

83-
승인·받기 설정은 페어링 소켓을 가진 앱 인스턴스만 바꿉니다. 같은 앱을 하나 더 띄우면 그 창에서는 바꿀 수 없다고 안내하고 `policy change refused reason=not_socket_owner`를 남기며, 나중에 소켓을 넘겨받을 때 저장된 파일을 한 번 다시 읽습니다(읽을 수 없으면 승인 없음·받기 꺼짐).
83+
승인·받기 설정은 페어링 소켓을 가진 앱 인스턴스만 바꿉니다. 같은 앱을 하나 더 띄우면 그 창에서는 바꿀 수 없다고 안내하고 `policy change refused reason=not_socket_owner`를 남기며, 소켓을 넘겨받을 때와, 파일이 자신이 마지막으로 읽거나 쓴 뒤 바뀌었을 때(예: 함께 실행 중인 이전 버전이 쓴 경우) 저장된 파일을 다시 읽습니다(`policy adopt reason=external_change`). 승인을 알고 있던 상태에서 파일이 사라졌거나 읽을 수 없으면 승인 없음·받기 꺼짐으로 보고, 이미 철회한 키는 계속 철회 상태로 둡니다. 화면 잠금과 콘솔 사용자 전환은 따로 추적해 둘 다 풀렸을 때만 받기를 다시 엽니다.
8484

85-
사용자가 `전체 받기 끄기`를 누르면 그 선택(`receiptChoice=off`)이 저장되어, 탭을 열어도 다시 켜지지 않습니다. 이 기능 이전 버전에서 받기가 꺼진 채 저장된 파일도 같은 이유로 꺼진 채 두고 탭에 한 번 안내합니다.
85+
사용자가 `전체 받기 끄기`를 누르면 그 선택(`receiptChoice=off`)이 저장되어, 탭을 열어도 다시 켜지지 않습니다. 이 기능 이전 버전에서 받기가 꺼진 채 저장된 파일도 같은 이유로 꺼진 채 두고, 사용자가 받기를 켜거나 끌 때까지 탭에 안내합니다.
8686

8787
앱과 도우미는 같은 subsystem에 다음 줄을 남깁니다(도우미 줄도 같은 명령으로 모입니다).
8888

0 commit comments

Comments
 (0)