Skip to content

Commit 3e0e5ea

Browse files
committed
Fix received draft confirmation and helper session boundaries
1 parent c3af0d8 commit 3e0e5ea

11 files changed

Lines changed: 280 additions & 80 deletions

‎Helpers/AgentCatalogMCP.swift‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,8 @@ import Foundation
153153
case "duplicate": tool(id, "Already received. Nothing new was opened or played.", extra: ["status": "duplicate"])
154154
case "conflict": tool(id, "Retry key already used for different content.", failed: true)
155155
case "busy": tool(id, "Open documents have reached their limit. Close a tab and retry with the same key.", failed: true, extra: ["status": "busy"])
156+
case "session_limit":
157+
tool(id, "This helper session has reached its draft-key limit. Ask the user to disconnect and enable a new session.", failed: true, extra: ["status": "session_limit"])
156158
case "rate_limited": tool(id, "This session’s receipt rate limit was reached.", failed: true)
157159
case "instruction_required":
158160
tool(id, "A saved instruction is selected. Read the current selection and send with submit_explanation_draft, or ask the user to clear the selection.", failed: true, extra: ["status": "instruction_required"])

‎Sources/App/AgentSessionController.swift‎

Lines changed: 42 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import Combine
2+
import CryptoKit
23
import CoreFoundation
34
import Darwin
45
import 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)

‎Sources/App/AppDelegate.swift‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
118118
return
119119
}
120120
localInstructionSocket = socket
121-
if appState.agentAccess.selectionStatus == .waitingForHelper {
122-
appState.agentAccess.rejectSelection(.legacySharing)
121+
if appState.agentAccess.selectionStatus == .waitingForHelper,
122+
let selector = appState.agentAccess.instructionScope {
123+
appState.agentAccess.rejectSelection(selector, reason: .legacySharing)
123124
}
124125
appState.sharedInstructionProfile = profile.name
125126
localInstructionMenu?.state = .on
@@ -149,19 +150,19 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
149150
let access = appState.agentAccess
150151
let custom = LocalInstructionProfile.Name(rawValue: selector) == nil
151152
guard localInstructionSocket == nil else {
152-
access.rejectSelection(.legacySharing)
153+
access.rejectSelection(selector, reason: .legacySharing)
153154
return
154155
}
155156
guard !custom || appState.agentCatalog.refresh() else {
156-
access.rejectSelection(.catalogUnavailable)
157+
access.rejectSelection(selector, reason: .catalogUnavailable)
157158
return
158159
}
159160
guard let snapshot = appState.agentSnapshot(selector) else {
160-
access.rejectSelection(.catalogUnavailable)
161+
access.rejectSelection(selector, reason: .catalogUnavailable)
161162
return
162163
}
163164
guard snapshot.shareable else {
164-
access.rejectSelection(.invalidInstruction)
165+
access.rejectSelection(selector, reason: .invalidInstruction)
165166
return
166167
}
167168
_ = access.select(snapshot, current: { [weak self] in self?.currentAgentSnapshot($0) },

‎Sources/Core/ExplanationDraftWorkspace.swift‎

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,9 @@ struct ExplanationDraft: Identifiable, Sendable {
99
let display: String
1010
let speech: String?
1111
let provenance: AgentDraftOrigin?
12-
let sourceSession: UUID?
1312
var displayHash: String { AgentBytes.hash(Data(display.utf8)) }
1413

15-
init?(id: String, display: String, speech: String?, provenance: AgentDraftOrigin? = nil, sourceSession: UUID? = nil) {
14+
init?(id: String, display: String, speech: String?, provenance: AgentDraftOrigin? = nil) {
1615
guard (1...128).contains(id.utf8.count),
1716
id.utf8.allSatisfy({ (48...57).contains($0) || (65...90).contains($0)
1817
|| (97...122).contains($0) || $0 == 45 || $0 == 46 || $0 == 95 }),
@@ -21,7 +20,6 @@ struct ExplanationDraft: Identifiable, Sendable {
2120
self.display = display
2221
self.speech = speech
2322
self.provenance = provenance
24-
self.sourceSession = sourceSession
2523
}
2624

2725
private static func validText(_ value: String) -> Bool {
@@ -32,7 +30,7 @@ struct ExplanationDraft: Identifiable, Sendable {
3230
var fingerprint: SHA256.Digest {
3331
// The separator cannot occur in either field. Missing speech is distinct
3432
// from every valid (nonblank) supplied speech string.
35-
let scope = provenance.map { "\($0.principal.uuidString)\0\($0.selector)\0\($0.revision.uuidString)\0" } ?? sourceSession.map { "\($0.uuidString)\0unassociated\0" } ?? ""
33+
let scope = provenance.map { "\($0.principal.uuidString)\0\($0.selector)\0\($0.revision.uuidString)\0" } ?? ""
3634
return SHA256.hash(data: Data((scope + display + "\0" + (speech ?? "")).utf8))
3735
}
3836
}
@@ -76,7 +74,9 @@ final class ExplanationDraftWorkspace: ObservableObject {
7674
@Published private(set) var activeOriginal: ExplanationDraft?
7775
@Published private var parked: [String: ParkedDocument] = [:]
7876
@Published private var tabOrder: [String] = []
77+
private var untitledDocumentID = UUID().uuidString
7978

79+
var editorDocumentID: String { activeDocumentID ?? untitledDocumentID }
8080
var canRevertReceived: Bool { activeOriginal != nil && capturedDocument.dirty }
8181
var documentTabs: [DocumentTab] {
8282
tabOrder.compactMap { id in
@@ -122,47 +122,40 @@ final class ExplanationDraftWorkspace: ObservableObject {
122122
let retained = parked.values.compactMap(\.original) + [activeOriginal].compactMap { $0 }
123123
let previous = recent[draft.id] ?? (retained + pending).first(where: { $0.id == draft.id })?.fingerprint
124124
if let previous { return previous == draft.fingerprint ? .duplicate : .conflict }
125-
if (draft.provenance != nil || draft.sourceSession != nil) && (recent.values.contains(draft.fingerprint)
125+
if draft.provenance != nil && (recent.values.contains(draft.fingerprint)
126126
|| (retained + pending).contains(where: { $0.fingerprint == draft.fingerprint })) { return .duplicate }
127127
return pending.count < Self.maxPending ? .accepted : .busy
128128
}
129129

130-
func preflightDocument(_ draft: ExplanationDraft) -> Receipt {
131-
let result = preflight(draft)
132-
guard result == .accepted else { return result }
130+
func canReceiveDocument() -> Bool {
133131
let active = capturedDocument
134132
let preserve = active.dirty
135-
guard parked.count + (preserve ? 2 : 1) <= Self.maxDocuments else { return .busy }
133+
guard parked.count + (preserve ? 2 : 1) <= Self.maxDocuments else { return false }
136134
let bytes = parked.values.reduce(0) { $0 + $1.display.utf8.count + $1.speech.utf8.count }
137-
guard !preserve || bytes + active.display.utf8.count + active.speech.utf8.count <= Self.maxParkedBytes else {
138-
return .busy
139-
}
140-
return .accepted
135+
return !preserve || bytes + active.display.utf8.count + active.speech.utf8.count <= Self.maxParkedBytes
141136
}
142137

143138
/// Live agent receipt updates the visible editor and never starts playback.
144139
/// Only a clean active document may be replaced. Dirty documents turn into tabs.
145140
func receiveDocument(_ draft: ExplanationDraft) -> Receipt {
146-
let result = preflightDocument(draft)
147-
guard result == .accepted else { return result }
141+
guard canReceiveDocument() else { return .busy }
148142
let active = capturedDocument
149143
let preserve = active.dirty
150144
if preserve {
151-
let id = activeDocumentID ?? UUID().uuidString
145+
let id = editorDocumentID
152146
if !tabOrder.contains(id) { tabOrder.append(id) }
153147
parked[id] = active
154148
} else if let id = activeDocumentID {
155149
tabOrder.removeAll { $0 == id }
156150
}
157-
recordReceipt(draft)
158151
installReceived(draft)
159152
return .accepted
160153
}
161154

162155
func selectDocument(_ id: String) {
163156
guard id != activeDocumentID, let next = parked[id] else { return }
164157
let active = capturedDocument
165-
let currentID = activeDocumentID ?? UUID().uuidString
158+
let currentID = editorDocumentID
166159
parked.removeValue(forKey: id)
167160
if activeDocumentID != nil || active.dirty {
168161
parked[currentID] = active
@@ -259,8 +252,15 @@ final class ExplanationDraftWorkspace: ObservableObject {
259252
speechNeedsReview = false
260253
}
261254

262-
func clearEditor() {
255+
func clearEditor(expectedDocumentID: String) {
256+
guard expectedDocumentID == editorDocumentID else { return }
257+
if activeOriginal != nil {
258+
editDisplay("")
259+
editSpeech("")
260+
return
261+
}
263262
if let id = activeDocumentID { tabOrder.removeAll { $0 == id } }
263+
untitledDocumentID = UUID().uuidString
264264
activeDocumentID = nil
265265
activeOriginal = nil
266266
display = ""

0 commit comments

Comments
 (0)