Skip to content
15 changes: 11 additions & 4 deletions Sources/App/AppState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,17 @@ final class AppState: ObservableObject {
// External workspace is never connected to the legacy generator buffers.
/// Received and written drafts are kept in a private database, so the list
/// is not limited by memory and survives a restart. Without a usable file the
/// list still works for this run.
let explanationDrafts = ExplanationDraftWorkspace(
store: SQLiteDraftStore(url: TTSRuntime.applicationSupport().appendingPathComponent("drafts.sqlite"))
?? MemoryDraftStore())
/// list still works for this run, but agent drafts are refused (`busy`)
/// rather than accepted and lost at quit, and the tab says so.
let explanationDrafts = AppState.makeDraftWorkspace()

private static func makeDraftWorkspace() -> ExplanationDraftWorkspace {
if let store = SQLiteDraftStore(url: TTSRuntime.applicationSupport().appendingPathComponent("drafts.sqlite")) {
return ExplanationDraftWorkspace(store: store)
}
Log.app.error("[DRAFTS] store unavailable; agent drafts refused for this run")
return ExplanationDraftWorkspace(store: MemoryDraftStore(), acceptsExternal: false)
}
let agentCatalog = AgentCatalog(url: URL(fileURLWithPath: Secrets.appSupportDir)
.appendingPathComponent("agent-instructions-v1.json"))
let agentAccess = AgentSessionController()
Expand Down
2 changes: 1 addition & 1 deletion Sources/App/LocalSpeechSocket.swift
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ final class LocalSpeechSocket {
let semaphore = DispatchSemaphore(value: 0)
let deadline = DispatchTime.now() + .milliseconds(1000)
let lock = NSLock()
var result = "busy"
var result = "unconfirmed" // the main-queue block did not run in time
DispatchQueue.main.async { [handler] in
guard DispatchTime.now() < deadline else { semaphore.signal(); return }
let value = MainActor.assumeIsolated { handler(text, key) }
Expand Down
165 changes: 108 additions & 57 deletions Sources/Core/AgentTrustStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,12 @@ final class AgentTrustStore {
}

static let maxClients = AgentPairing.slotCount
/// Revocations are never dropped: any cut-off would let a restored older
/// copy bring a dropped key back. At about 70 bytes each, thousands fit
/// under this read limit; a file that would exceed it is not written, and
/// the denial stays pending (in effect here) and is retried.
static let maxFileBytes = 256 * 1024
/// The read and write limit. Revocations have no count limit; at about 70
/// bytes each, this holds some 240,000 of them. Near it, approvals are no
/// longer saved, and a new revocation of an app without an approval row stays
/// in effect for this run only rather than push a saved one out.
static let defaultMaxFileBytes = 16 * 1024 * 1024
let maxFileBytes: Int
// Approval does not expire. An approved app stays approved until the user
// revokes it, its key changes, or it is launched by a different app.

Expand All @@ -107,15 +108,18 @@ final class AgentTrustStore {
/// Builds before this one (never released) used another file name; their
/// approvals are not imported, so those builds never share a file with this one.
init(url: URL, now: @escaping () -> Date = Date.init,
write: @escaping (Data, URL) throws -> Void = AgentTrustStore.writePrivately) {
write: @escaping (Data, URL) throws -> Void = AgentTrustStore.writePrivately,
maxFileBytes: Int = AgentTrustStore.defaultMaxFileBytes) {
self.url = url
self.maxFileBytes = maxFileBytes
self.now = now
self.write = write
switch Self.readDisk(url) {
switch Self.readDisk(url, limit: maxFileBytes) {
case .loaded(let loaded, let stamp):
file = loaded
onDisk = loaded
lastGood = loaded
savedRevoked = Set(loaded.revoked)
loadedExisting = true
diskStamp = stamp
case .missing:
Expand Down Expand Up @@ -144,7 +148,7 @@ final class AgentTrustStore {
/// write stays pending for when it takes the socket over.
func adoptDisk(writeBack: Bool = true) {
let known = file.revoked
let disk = Self.readDisk(url)
let disk = Self.readDisk(url, limit: maxFileBytes)
guard case .loaded(let loaded, let stamp) = disk else {
// What was last read is no longer what the file holds.
onDisk = nil
Expand All @@ -171,6 +175,7 @@ final class AgentTrustStore {
diskStamp = stamp
onDisk = loaded
lastGood = loaded
savedRevoked.formUnion(loaded.revoked)
needsAdopt = false
// Revocations are never undone (a revoked key cannot be approved again),
// so every revocation this run knows is kept, also over a restored older
Expand Down Expand Up @@ -198,46 +203,70 @@ final class AgentTrustStore {
needsAdopt = false
return
}
_ = commit(merged, byUser: false)
_ = commit(merged, byUser: false, denial: true)
}

private static func encodedSize(_ file: File) -> Int {
(try? JSONEncoder().encode(file))?.count ?? Int.max
}

/// What is written when `file` would pass the read limit: every revocation
/// that removes a row of the file last read (that app would connect again),
/// every revocation that file already holds, then the newest others that fit.
/// Nil when even the first two do not fit. Memory keeps all of them either way.
private static func fitting(_ file: File, onDisk: File?) -> File? {
let rows = Set((onDisk?.clients ?? []).map(\.keyID))
let own = Set(onDisk?.revoked ?? [])
let required = file.revoked.filter { rows.contains($0) || own.contains($0) }
// Newest first, so the oldest are the first left out.
var others = Array(file.revoked.filter { !rows.contains($0) && !own.contains($0) }.reversed())
/// Room kept below the limit for writes that are not denials (an approval,
/// a key change, a reconnect time, turning receipt on). Past the limit less
/// this, such a write is refused if it would make the file larger, so this
/// room is only ever used by denials.
static let reserveBytes = 8 * 1024
/// Room a denial that adds a revocation of an app without a row leaves free,
/// for receipt offs (at most a few hundred bytes for all slots), so turning
/// receipt off never has to push a saved revocation out.
static let flagReserveBytes = 1024

/// What a denial writes when `file` would pass the limit less
/// `flagReserveBytes`. A saved revocation is never pushed out by this app's
/// own writes:
/// - every revocation that removes a row of the last intact file;
/// - that file's own revocations, then those this run saw saved in an earlier
/// file (a restored copy may predate them), newest first, up to the limit:
/// they only miss it if a file came from elsewhere already near the limit;
/// - revocations the user asked for that are not saved yet, then any others,
/// newest first, up to the limit less `flagReserveBytes`.
/// What is left out stays in effect for this run. Nil only if the rows'
/// revocations alone do not fit, which the client limit rules out.
private static func fitting(_ file: File, lastGood: File?, saved: Set<String>, asked: Set<String>, limit: Int) -> File? {
let rows = Set((lastGood?.clients ?? []).map(\.keyID))
let own = Set(lastGood?.revoked ?? [])
let required = file.revoked.filter { rows.contains($0) }
var fitted = file
func build() -> [String] {
let kept = Set(required).union(others)
return file.revoked.filter { kept.contains($0) }
}
fitted.revoked = required
guard encodedSize(fitted) <= maxFileBytes else { return nil }
// Each entry adds its quoted bytes and a comma; trim to that estimate,
// then drop the oldest others until the exact size fits.
var budget = maxFileBytes - encodedSize(fitted)
var count = 0
for keyID in others {
let cost = keyID.utf8.count + 3
guard cost <= budget else { break }
budget -= cost
count += 1
}
others = Array(others.prefix(count))
fitted.revoked = build()
while encodedSize(fitted) > maxFileBytes, !others.isEmpty {
others.removeLast()
guard encodedSize(fitted) <= limit else { return nil }
var kept = Set(required)
func build() -> [String] { file.revoked.filter { kept.contains($0) } }
// Takes entries in order while the exact size stays within `cap`.
func take(_ entries: [String], cap: Int) {
var size = encodedSize(fitted)
var empty = kept.isEmpty
for keyID in entries {
// Its quoted bytes, and a comma unless the list was empty.
let cost = keyID.utf8.count + 2 + (empty ? 0 : 1)
guard size + cost <= cap else { break }
size += cost
empty = false
kept.insert(keyID)
}
fitted.revoked = build()
var taken = entries.filter { kept.contains($0) }
while encodedSize(fitted) > cap, let last = taken.popLast() {
kept.remove(last)
fitted.revoked = build()
}
}
let rest = file.revoked.filter { !rows.contains($0) }
take(Array(rest.filter { own.contains($0) }.reversed()), cap: limit)
take(Array(rest.filter { !own.contains($0) && saved.contains($0) }.reversed()), cap: limit)
let small = limit - flagReserveBytes
take(Array(rest.filter { !own.contains($0) && !saved.contains($0) && asked.contains($0) }.reversed()),
cap: max(encodedSize(fitted), small))
take(Array(rest.filter { !own.contains($0) && !saved.contains($0) && !asked.contains($0) }.reversed()),
cap: max(encodedSize(fitted), small))
return fitted
}

Expand Down Expand Up @@ -365,7 +394,7 @@ final class AgentTrustStore {
guard let index = file.clients.firstIndex(where: { $0.id == id }) else { return }
var next = file
next.clients[index].lastSeen = now()
_ = commit(next, byUser: false)
_ = commit(next, byUser: false, denial: false)
}

/// Forgetting tombstones the key, so the same credential cannot come back
Expand Down Expand Up @@ -421,7 +450,7 @@ final class AgentTrustStore {
private func deny(_ next: File, _ denial: Denial) -> Bool {
if !pending.contains(denial) { pending.append(denial) }
file = next
if !closedByDisk { _ = commit(next, byUser: false) }
if !closedByDisk { _ = commit(next, byUser: false, denial: true) }
guard pending.contains(denial) else { return true }
// Try again at the next check, even if nothing else changes the file.
if !closedByDisk || readFailed { needsAdopt = true }
Expand All @@ -435,7 +464,7 @@ final class AgentTrustStore {
/// on top) and the grant is refused.
private func grant(_ next: File, byUser: Bool) -> Bool {
let before = file
guard commit(next, byUser: byUser) else { return false }
guard commit(next, byUser: byUser, denial: false) else { return false }
guard lastCommitSeen else {
// Nothing granted stays in memory, even if the file is now gone.
file = before
Expand All @@ -449,7 +478,7 @@ final class AgentTrustStore {
/// file shows up there, its own writes do not settle pending denials.
private var recreated = false

private func commit(_ next: File, byUser: Bool) -> Bool {
private func commit(_ next: File, byUser: Bool, denial: Bool) -> Bool {
lastCommitSeen = false
// A file written where the last one vanished may be replaced by the
// original again, so pending denials are not settled by it.
Expand All @@ -459,26 +488,44 @@ final class AgentTrustStore {
needsAdopt = true
return false
}
// Never replace the file with one that could not be read back. Past the
// Never replace the file with one that could not be read back. Near the
// limit only the most important revocations are written; the rest stay in
// effect here and pending.
var toWrite = next
if Self.encodedSize(next) > Self.maxFileBytes {
guard let fitted = Self.fitting(next, onDisk: lastGood) else {
if denial || readFailed {
// A denial, or the user's turning receipt on over an unreadable file.
if Self.encodedSize(next) > maxFileBytes - Self.flagReserveBytes {
let asked = Set(pending.compactMap { item -> String? in
if case .revoke(let keyID) = item { return keyID }
return nil
})
guard let fitted = Self.fitting(next, lastGood: lastGood, saved: savedRevoked, asked: asked, limit: maxFileBytes) else {
if !pending.isEmpty { needsAdopt = true }
return false
}
toWrite = fitted
}
} else if Self.encodedSize(next) > maxFileBytes - Self.reserveBytes {
// Not a denial: only the revocations the file holds are written, and
// the file may not grow past the limit less the reserve.
let base = onDisk ?? lastGood
let keep = Set((base?.revoked ?? []) + (base?.clients ?? []).map(\.keyID))
toWrite.revoked = next.revoked.filter { keep.contains($0) }
let bound = min(maxFileBytes, max(maxFileBytes - Self.reserveBytes, base.map(Self.encodedSize) ?? 0))
guard Self.encodedSize(toWrite) <= bound else {
if !pending.isEmpty { needsAdopt = true }
return false
}
toWrite = fitted
if !readFailed, !closedByDisk, toWrite == onDisk, diskStamp != nil, Self.stamp(url) == diskStamp {
// Nothing more fits: the file already holds all it can.
file = next
needsAdopt = false
lastCommitSeen = true
if !recreated { pending.removeAll { Self.holds(toWrite, $0) } }
return true
}
}
guard let bytes = try? JSONEncoder().encode(toWrite), bytes.count <= Self.maxFileBytes,
if toWrite != next, !readFailed, !closedByDisk, toWrite == onDisk, diskStamp != nil, Self.stamp(url) == diskStamp {
// Nothing more fits: the file already holds all it can.
file = next
needsAdopt = false
lastCommitSeen = true
if !recreated { pending.removeAll { Self.holds(toWrite, $0) } }
return true
}
guard let bytes = try? JSONEncoder().encode(toWrite), bytes.count <= maxFileBytes,
(try? write(bytes, url)) != nil else {
if !pending.isEmpty { needsAdopt = true }
return false
Expand All @@ -489,10 +536,11 @@ final class AgentTrustStore {
// Remember the file only if it is what was just written. Otherwise (another
// writer got in between, or it is gone) the next check reads it again and
// the user's denials are applied to it once more.
if case .loaded(let disk, let stamp) = Self.readDisk(url), disk == toWrite {
if case .loaded(let disk, let stamp) = Self.readDisk(url, limit: maxFileBytes), disk == toWrite {
diskStamp = stamp
onDisk = disk
lastGood = disk
savedRevoked.formUnion(disk.revoked)
needsAdopt = false
lastCommitSeen = true
if !recreated { pending.removeAll { Self.holds(toWrite, $0) } }
Expand All @@ -507,14 +555,17 @@ final class AgentTrustStore {
/// The last file read or written intact, kept while the file is missing or
/// unreadable: what it held is still what the fit keeps first.
private var lastGood: File?
/// Every revocation this run has seen in an intact file, also one a restored
/// copy dropped since: the fit keeps these before any other.
private var savedRevoked: Set<String> = []

/// The last write was read back unchanged.
private var lastCommitSeen = false

/// Denials made here that the file does not hold yet.
var hasUnsavedDenials: Bool { !pending.isEmpty }

private static func readDisk(_ url: URL) -> Disk {
private static func readDisk(_ url: URL, limit maxFileBytes: Int) -> Disk {
let fd = Darwin.open(url.path, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC)
guard fd >= 0 else { return errno == ENOENT ? .missing : .unreadable(nil) }
let reader = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
Expand Down
2 changes: 2 additions & 0 deletions Sources/Core/DraftStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,9 @@ final class SQLiteDraftStore: DraftStoring {
fingerprint TEXT, body BLOB NOT NULL);
CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY, value TEXT);
""") else {
// deinit still runs for a failed init; close the handle only once.
sqlite3_close(db)
db = nil
return nil
}
}
Expand Down
9 changes: 8 additions & 1 deletion Sources/Core/ExplanationDraftWorkspace.swift
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,14 @@ final class ExplanationDraftWorkspace: ObservableObject {
private let store: DraftStoring
private var saveTask: Task<Void, Never>?

init(store: DraftStoring = MemoryDraftStore()) {
/// False when the private database could not be opened and the list lives
/// only in memory: agent drafts are then refused with `busy` instead of being
/// accepted and lost at quit.
let acceptsExternal: Bool

init(store: DraftStoring = MemoryDraftStore(), acceptsExternal: Bool = true) {
self.store = store
self.acceptsExternal = acceptsExternal
index = store.summaries()
if let id = store.activeID, let document = store.load(id) { activate(id, document) }
}
Expand Down Expand Up @@ -154,6 +160,7 @@ final class ExplanationDraftWorkspace: ObservableObject {
/// trims another document. The new draft is written to the store first; if
/// that fails nothing else changes and the sender is told it was not taken.
func receiveDocument(_ draft: ExplanationDraft) -> Receipt {
guard acceptsExternal else { return .busy }
if let known = documentTabs.first(where: { $0.id == draft.id }) {
// Also true after a restart: the stored original answers for its key.
return known.fingerprint == draft.fingerprintHex ? .duplicate : .conflict
Expand Down
5 changes: 5 additions & 0 deletions Sources/UI/ExplainWorkspace.swift
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,11 @@ struct ExplainWorkspace: View {
Text("‘\(client.label)’에 공유 중: \(title(shared.selector))")
.font(.caption).foregroundStyle(.secondary)
}
if !drafts.acceptsExternal {
Label("대본 저장소를 열 수 없어 에이전트 대본을 받지 않습니다. 이번 실행에서 쓴 글은 종료하면 사라집니다.",
systemImage: "externaldrive.badge.exclamationmark")
.font(.caption).foregroundStyle(.orange)
}
if let notice = access.receiptNotice {
Label(notice, systemImage: "tray.and.arrow.down").font(.caption).foregroundStyle(.orange)
}
Expand Down
Loading