Skip to content

armgit / andee

Public Imported from GitHub
0

Andee lives on your phone or Mac and uses any app like you do—no integrations, no root, any model; memory and passwords never leave your device | Andee 住进你的手机或 Mac,像你一样操作任何 App——无需集成、无需 Root、支持任意模型,记忆和密码绝不离开设备。

fix(mac): find the notification store on every macOS, and say why when it cannot

heycharging4f6481aa6188
diff --git a/CLAUDE.md b/CLAUDE.md
index e75638d..4255904 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -660,6 +660,7 @@ meetings, gear, friends) and lists exactly the tools some provider handles. What
ball steal the first one's state. Both use `ballTaps(ballActions(…))`, the phone's vocabulary: tap stops and
listens, double-tap stops and types, long-press opens the window; a sideways drag on the chat ball switches
character.
+- **Notifications come from `usernoted`'s SQLite store, and where it is depends on the macOS version** (`notifCandidates` in `AndeeMac.swift`): macOS 15 keeps it in `~/Library/Group Containers/group.com.apple.usernoted/db2`, earlier systems under `confstr(_CS_DARWIN_USER_DIR)` + `com.apple.notificationcenter/db2` (never derive that from `$TMPDIR` — the JVM replaces it). Only the first was tried, and a store that was not there was reported as missing Full Disk Access, so the user granted it and was told the same thing forever. `andee_notif_latest_id` now answers -2 for "no store anywhere" (`State.NOT_FOUND`, no permission button) and -1 for "exists but refuses us" (`NO_ACCESS`), and reads in process through `libsqlite3` (read-only, busy timeout, since `usernoted` is writing the WAL) instead of forking `/usr/bin/sqlite3`, which swallowed the reason.
- **A prompt card appears beside the ball** (`PromptWindow`), which may be on a screen the user is not looking
at. A friend's request therefore plays a sound and waves the ball first — the first one timed out unseen.
diff --git a/desktop/build.gradle b/desktop/build.gradle
index e05ab00..90b0076 100644
--- a/desktop/build.gradle
+++ b/desktop/build.gradle
@@ -43,7 +43,7 @@ tasks.register('buildBridge', Exec) {
inputs.file(src)
outputs.file(out)
doFirst { out.parentFile.mkdirs() }
- commandLine 'swiftc', '-O', '-target', swiftTarget, '-emit-library', '-framework', 'CoreDisplay', '-framework', 'CoreLocation', src.path, '-o', out.path
+ commandLine 'swiftc', '-O', '-target', swiftTarget, '-emit-library', '-framework', 'CoreDisplay', '-framework', 'CoreLocation', '-lsqlite3', src.path, '-o', out.path
}
tasks.register('buildNative') { dependsOn('buildTrashTool', 'buildBridge') }
sourceSets.main.resources.srcDir(nativeOut)
diff --git a/desktop/native/AndeeMac.swift b/desktop/native/AndeeMac.swift
index 765998b..0734537 100644
--- a/desktop/native/AndeeMac.swift
+++ b/desktop/native/AndeeMac.swift
@@ -6,6 +6,7 @@
// swiftc -O -target arm64-apple-macos14 -emit-library AndeeMac.swift -o libandeemac.dylib
// macOS 14 is the floor: ScreenCaptureKit's one-shot screenshot arrived there.
+import SQLite3
import AppKit
import ApplicationServices
import AVFoundation
@@ -436,54 +437,102 @@ public func andee_set_own_alpha(_ alpha: Double) -> Int32 {
/// Watching that file's directory tells us within moments that something new
/// arrived, whether or not a banner was shown (Focus and per-app banner
/// settings do not stop the write). Read-only; never touches the file.
-private let notifDir = (NSHomeDirectory() as NSString)
- .appendingPathComponent("Library/Group Containers/group.com.apple.usernoted/db2")
-
-private func notifQuery(_ sql: String) -> [[String: Any]]? {
- let p = Process()
- p.executableURL = URL(fileURLWithPath: "/usr/bin/sqlite3")
- p.arguments = ["-readonly", "-json", "file:\(notifDir)/db?mode=ro", sql]
- let out = Pipe(), err = Pipe()
- p.standardOutput = out; p.standardError = err
- do { try p.run() } catch { return nil }
- let data = out.fileHandleForReading.readDataToEndOfFile()
- p.waitUntilExit()
- if p.terminationStatus != 0 { return nil }
- if data.isEmpty { return [] }
- return (try? JSONSerialization.jsonObject(with: data)) as? [[String: Any]]
-}
-
-/// Can the store be read at all (Full Disk Access may be required): -1 unreadable, else the newest record id.
+///
+/// **Where that file is depends on the macOS version**, and assuming one place
+/// is how a Mac ended up "without permission" forever: the store was not there,
+/// the failed read was reported as a missing Full Disk Access grant, and granting
+/// it changed nothing. macOS 15 keeps it in the usernoted group container; earlier
+/// systems keep it under the per-user Darwin directory
+/// (`confstr(_CS_DARWIN_USER_DIR)`, i.e. `/var/folders/…/0/`). Asked of the system
+/// rather than derived from `$TMPDIR`, which the JVM replaces with its own.
+private func notifCandidates() -> [String] {
+ var out = [(NSHomeDirectory() as NSString)
+ .appendingPathComponent("Library/Group Containers/group.com.apple.usernoted/db2")]
+ var buf = [CChar](repeating: 0, count: Int(PATH_MAX))
+ if confstr(_CS_DARWIN_USER_DIR, &buf, buf.count) > 0 {
+ out.append((String(cString: buf) as NSString).appendingPathComponent("com.apple.notificationcenter/db2"))
+ }
+ return out
+}
+
+/// Where the store is: a readable directory, nowhere we know of, or somewhere we are not allowed to read.
+private enum NotifStore { case at(String), missing, denied }
+
+/// First candidate whose `db` opens. A path that exists but refuses us (EPERM/EACCES — the TCC answer) is
+/// "denied"; only when no candidate exists at all is it "missing" — two different fixes, so two answers.
+private func notifLocate() -> NotifStore {
+ var denied = false
+ for dir in notifCandidates() {
+ let fd = open(dir + "/db", O_RDONLY)
+ if fd >= 0 { close(fd); return .at(dir) }
+ if errno == EPERM || errno == EACCES { denied = true }
+ }
+ return denied ? .denied : .missing
+}
+
+/// One query, in process, through the system's own SQLite, read-only. `usernoted` is writing to the same
+/// file (its WAL is where new rows land first), so a short busy timeout rather than failing on its lock.
+/// Nil when it cannot be opened or the statement fails.
+private func notifQuery(_ dir: String, _ sql: String) -> [[String: Any]]? {
+ var db: OpaquePointer?
+ guard sqlite3_open_v2(dir + "/db", &db, SQLITE_OPEN_READONLY, nil) == SQLITE_OK, let db = db else {
+ sqlite3_close(db)
+ return nil
+ }
+ defer { sqlite3_close(db) }
+ sqlite3_busy_timeout(db, 1000)
+ var st: OpaquePointer?
+ guard sqlite3_prepare_v2(db, sql, -1, &st, nil) == SQLITE_OK, let st = st else { return nil }
+ defer { sqlite3_finalize(st) }
+ var rows: [[String: Any]] = []
+ while true {
+ let rc = sqlite3_step(st)
+ if rc == SQLITE_DONE { break }
+ if rc != SQLITE_ROW { return nil }
+ var row: [String: Any] = [:]
+ for i in 0..<sqlite3_column_count(st) {
+ let name = String(cString: sqlite3_column_name(st, i))
+ switch sqlite3_column_type(st, i) {
+ case SQLITE_INTEGER: row[name] = NSNumber(value: sqlite3_column_int64(st, i))
+ case SQLITE_FLOAT: row[name] = NSNumber(value: sqlite3_column_double(st, i))
+ case SQLITE_TEXT: row[name] = String(cString: sqlite3_column_text(st, i))
+ case SQLITE_BLOB:
+ let n = Int(sqlite3_column_bytes(st, i))
+ if let p = sqlite3_column_blob(st, i) { row[name] = Data(bytes: p, count: n) }
+ default: break
+ }
+ }
+ rows.append(row)
+ }
+ return rows
+}
+
+/// Can the store be read at all: the newest record id, -1 when it exists and refuses us (Full Disk Access),
+/// -2 when there is no store at any place this Mac's macOS is known to keep it.
@_cdecl("andee_notif_latest_id")
public func andee_notif_latest_id() -> Int64 {
- guard let rows = notifQuery("select coalesce(max(rec_id),0) m from record"),
- let m = (rows.first?["m"] as? NSNumber)?.int64Value else { return -1 }
- return m
-}
-
-private func hexData(_ s: String) -> Data? {
- var d = Data(capacity: s.count / 2)
- var i = s.startIndex
- while i < s.endIndex {
- let j = s.index(i, offsetBy: 2)
- guard let b = UInt8(s[i..<j], radix: 16) else { return nil }
- d.append(b); i = j
+ switch notifLocate() {
+ case .missing: return -2
+ case .denied: return -1
+ case .at(let dir):
+ guard let rows = notifQuery(dir, "select coalesce(max(rec_id),0) m from record"),
+ let m = (rows.first?["m"] as? NSNumber)?.int64Value else { return -1 }
+ return m
}
- return d
}
/// Every record newer than [afterId], decoded: id, app bundle id, app name, title, subtitle, body, delivered (epoch ms).
@_cdecl("andee_notif_since")
public func andee_notif_since(_ afterId: Int64) -> UnsafeMutablePointer<CChar> {
- let sql = "select r.rec_id id, a.identifier bundle, r.delivered_date d, hex(r.data) data from record r join app a using(app_id) where r.rec_id > \(afterId) order by r.rec_id limit 50"
- guard let rows = notifQuery(sql) else { return json(["error": "unreadable"]) }
+ let sql = "select r.rec_id id, a.identifier bundle, r.delivered_date d, r.data data from record r join app a using(app_id) where r.rec_id > \(afterId) order by r.rec_id limit 50"
+ guard case .at(let dir) = notifLocate(), let rows = notifQuery(dir, sql) else { return json(["error": "unreadable"]) }
var out: [[String: Any]] = []
for r in rows {
let id = (r["id"] as? NSNumber)?.int64Value ?? 0
let bundle = (r["bundle"] as? String) ?? ""
var o: [String: Any] = ["id": id, "bundle": bundle]
if let d = (r["d"] as? NSNumber)?.doubleValue { o["when"] = Int64((d + 978_307_200) * 1000) }
- if let h = r["data"] as? String, let blob = hexData(h),
+ if let blob = r["data"] as? Data,
let pl = try? PropertyListSerialization.propertyList(from: blob, format: nil) as? [String: Any],
let req = pl["req"] as? [String: Any] {
o["title"] = req["titl"] as? String ?? ""
@@ -508,6 +557,7 @@ public func andee_notif_watch(_ cb: NotifCallback) -> Int32 {
notifKeep.forEach { $0.cancel() }
let q = DispatchQueue(label: "andee.notif")
var sources: [DispatchSourceFileSystemObject] = []
+ guard case .at(let notifDir) = notifLocate() else { notifKeep = []; return 0 }
for path in [notifDir, notifDir + "/db-wal", notifDir + "/db"] {
let fd = open(path, O_EVTONLY)
if fd < 0 { continue }
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Cards.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Cards.kt
index 038c620..1467615 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Cards.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Cards.kt
@@ -63,10 +63,19 @@ fun SelfCheckCard(onDone: () -> Unit, onOpenSettings: () -> Unit) {
add(CheckRow("rec", if (zh) "录屏" else "Screen Recording", rec,
if (rec) if (zh) "能看见屏幕" else "Can see the screen" else if (zh) "截图拿不到" else "Screenshots are blocked",
{ openPane("Privacy_ScreenCapture") }))
- val fda = net.kuafuai.andee.desktop.mac.MacNotifications.state != net.kuafuai.andee.desktop.mac.MacNotifications.State.NO_ACCESS
- add(CheckRow("fda", if (zh) "完全磁盘访问" else "Full Disk Access", fda,
- if (fda) if (zh) "能读通知" else "Can read notifications" else if (zh) "读不到通知数据库" else "Cannot read the notification store",
- { openPane("Privacy_AllFiles") }))
+ val notif = net.kuafuai.andee.desktop.mac.MacNotifications.state
+ if (notif == net.kuafuai.andee.desktop.mac.MacNotifications.State.NOT_FOUND) {
+ // Not a permission row in disguise: no store at any known place. No button — Full Disk Access is
+ // exactly the fix that does not work here, and a button to it is how this used to go wrong.
+ add(CheckRow("fda", if (zh) "通知" else "Notifications", false,
+ if (zh) "这台 Mac 上找不到通知数据库,不是权限问题,开完全磁盘访问也没用" else "No notification store found on this Mac — not a permission problem; Full Disk Access will not help",
+ null))
+ } else {
+ val fda = notif != net.kuafuai.andee.desktop.mac.MacNotifications.State.NO_ACCESS
+ add(CheckRow("fda", if (zh) "完全磁盘访问" else "Full Disk Access", fda,
+ if (fda) if (zh) "能读通知" else "Can read notifications" else if (zh) "读不到通知数据库" else "Cannot read the notification store",
+ { openPane("Privacy_AllFiles") }))
+ }
// Asked of the backend in force, not of one key's name: under CodeFlying the key is codeflying_key,
// and the same key carries the voice. Reading llm_api_key there said "missing" for a Mac that worked.
val cf = Assistant.config().mode == net.kuafuai.andee.config.BrainConfig.BRAIN_CODEFLYING
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/SettingsScreen.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/SettingsScreen.kt
index 2d7c056..f116c22 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/SettingsScreen.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/SettingsScreen.kt
@@ -206,6 +206,13 @@ fun SettingsScreen(
color = Palette.warn, fontSize = 12.sp, modifier = Modifier.padding(top = 4.dp),
)
}
+ if (net.kuafuai.andee.desktop.mac.MacNotifications.state == net.kuafuai.andee.desktop.mac.MacNotifications.State.NOT_FOUND) {
+ Text(
+ t("这台 Mac 上找不到通知数据库,暂时读不了通知。这不是权限问题,开完全磁盘访问也没用。",
+ "No notification store found on this Mac, so notifications cannot be read yet. This is not a permission problem; Full Disk Access will not help."),
+ color = Palette.warn, fontSize = 12.sp, modifier = Modifier.padding(top = 4.dp),
+ )
+ }
}
// ---- 主动招呼: how often a bubble may go up beside the ball. 关 leftmost, as everywhere ----
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/Bridge.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/Bridge.kt
index c2e7a4c..bf46139 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/Bridge.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/Bridge.kt
@@ -111,7 +111,7 @@ object Bridge {
fun brightnessSet(b: Double) = lib?.andee_brightness_set(b) == 1
fun location(): JSONObject = JSONObject(str(need().andee_location()))
- /** Newest record id in the system notification store; -1 when it cannot be read (Full Disk Access). */
+ /** Newest record id in the system notification store; -1 when it refuses us (Full Disk Access), -2 when there is no store where this macOS keeps it. */
fun notifLatestId(): Long = lib?.andee_notif_latest_id() ?: -1
/** Records after [afterId]: id, bundle, app, title, subtitle, body, when. */
fun notifSince(afterId: Long): JSONObject = JSONObject(str(need().andee_notif_since(afterId)))
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacDevice.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacDevice.kt
index dcbbb31..b057d6c 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacDevice.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacDevice.kt
@@ -279,14 +279,18 @@ class MacDevice : DesktopBrainHost.ToolProvider {
val granted = JSONArray(); val missing = JSONArray()
(if (Bridge.axTrusted()) granted else missing).put(JSONObject().put("id", "accessibility").put("feature", "operate other apps"))
(if (Bridge.screenCaptureAllowed()) granted else missing).put(JSONObject().put("id", "screen_recording").put("feature", "see the screen"))
- (if (MacNotifications.state != MacNotifications.State.NO_ACCESS) granted else missing)
- .put(JSONObject().put("id", "full_disk_access").put("feature", "read notifications"))
+ // A store that is not there says nothing about the grant either way, so it is reported as neither.
+ if (MacNotifications.state != MacNotifications.State.NOT_FOUND) {
+ (if (MacNotifications.state != MacNotifications.State.NO_ACCESS) granted else missing)
+ .put(JSONObject().put("id", "full_disk_access").put("feature", "read notifications"))
+ }
return JSONObject().put("granted", granted).put("missing", missing)
.put("note", "Calendar, Reminders and Contacts ask for permission the first time they are used.")
.also { o ->
if (!Bridge.axTrusted()) o.put("accessibility_fix", PermissionHelp.ACCESSIBILITY)
if (!Bridge.screenCaptureAllowed()) o.put("screen_recording_fix", PermissionHelp.SCREEN_RECORDING)
if (MacNotifications.state == MacNotifications.State.NO_ACCESS) o.put("full_disk_access_fix", MacNotifications.NO_ACCESS_NOTE)
+ if (MacNotifications.state == MacNotifications.State.NOT_FOUND) o.put("notifications_unavailable", MacNotifications.NOT_FOUND_NOTE)
}
}
diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacNotifications.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacNotifications.kt
index 4a69a3d..27435be 100644
--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacNotifications.kt
+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/mac/MacNotifications.kt
@@ -54,7 +54,21 @@ object MacNotifications {
fun act(text: String)
}
- enum class State { OFF, WATCHING, NO_ACCESS }
+ /**
+ * [NO_ACCESS] and [NOT_FOUND] are two different fixes and must never be reported as each other: the first
+ * is Full Disk Access, the second is a macOS that keeps the store somewhere Andee does not know (see
+ * `notifCandidates` in AndeeMac.swift). A missing store used to read as [NO_ACCESS], so the user granted
+ * the permission, restarted, and was told the same thing again, forever.
+ */
+ enum class State { OFF, WATCHING, NO_ACCESS, NOT_FOUND }
+
+ /** The bridge's answer for the newest record id: -2 no store, -1 refused, else an id. */
+ private fun stateFor(id: Long): State = when {
+ id == -2L -> State.NOT_FOUND
+ id < 0 -> State.NO_ACCESS
+ Bridge.notifWatch(onChange) -> State.WATCHING
+ else -> State.NO_ACCESS
+ }
@Volatile var state = State.OFF
private set
@@ -74,11 +88,7 @@ object MacNotifications {
fun start(h: Host) = exec.execute {
host = h
lastId = Bridge.notifLatestId()
- state = when {
- lastId < 0 -> State.NO_ACCESS
- Bridge.notifWatch(onChange) -> State.WATCHING
- else -> State.NO_ACCESS
- }
+ state = stateFor(lastId)
Log.i(TAG, "notification store: $state (from record $lastId)")
}
@@ -95,11 +105,7 @@ object MacNotifications {
val id = Bridge.notifLatestId()
if (id > lastId) lastId = id
if (state == State.WATCHING) return
- state = when {
- id < 0 -> State.NO_ACCESS
- Bridge.notifWatch(onChange) -> State.WATCHING
- else -> State.NO_ACCESS
- }
+ state = stateFor(id)
Log.i(TAG, "notification store re-checked: $state (from record $lastId)")
}
@@ -193,6 +199,7 @@ object MacNotifications {
.put("scope", Settings.get("notify").ifEmpty { "off" })
.put("items", arr)
if (state == State.NO_ACCESS) o.put("how_to_enable", NO_ACCESS_NOTE)
+ else if (state == State.NOT_FOUND) o.put("note", NOT_FOUND_NOTE)
else if (Settings.get("notify").let { it != "chat" && it != "all" }) {
o.put("note", "Notifications are recorded but Andee does not act on them: the user has the Notifications setting off.")
}
@@ -220,6 +227,11 @@ object MacNotifications {
"click + and add ${PermissionHelp.appPath() ?: "Andee.app"}, switch it on, then quit and reopen Andee (⌘Q). " +
"If Andee is already listed and on, remove it with − and add it again (it belongs to an earlier build)."
+ val NOT_FOUND_NOTE: String get() =
+ "Andee cannot find the Mac's notification store at any place this version of macOS is known to keep it. " +
+ "This is not a permission problem — Full Disk Access will not change it. Tell the user plainly that reading " +
+ "notifications does not work on this Mac yet, and do not send them to System Settings for it."
+
/** Apps a person writes to you from, by bundle id (lowercased). */
private val CHAT_APPS = setOf(
"com.tencent.xinwechat", "com.tencent.qq", "com.electron.lark", "com.bytedance.lark",