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、支持任意模型,记忆和密码绝不离开设备。
feat(desktop): device.look, device.brightness, device.location
booboosui5d21a8dc5ba5
diff --git a/desktop/build.gradle b/desktop/build.gradleindex 6c80077..8fdae21 100644--- a/desktop/build.gradle+++ b/desktop/build.gradle@@ -30,7 +30,7 @@ tasks.register('buildBridge', Exec) {inputs.file(src)outputs.file(out)doFirst { out.parentFile.mkdirs() }- commandLine 'swiftc', '-O', '-target', 'arm64-apple-macos14', '-emit-library', src.path, '-o', out.path+ commandLine 'swiftc', '-O', '-target', 'arm64-apple-macos14', '-emit-library', '-framework', 'CoreDisplay', '-framework', 'CoreLocation', src.path, '-o', out.path}tasks.register('buildNative') { dependsOn('buildTrashTool', 'buildBridge') }sourceSets.main.resources.srcDir(nativeOut)@@ -84,6 +84,8 @@ compose.desktop {<string>Andee looks up contacts when you ask it to.</string><key>NSCameraUsageDescription</key><string>Andee looks through the camera only when you ask it to.</string>+ <key>NSLocationUsageDescription</key>+ <string>Andee reads this Mac's location only when you ask where it is.</string>'''}}diff --git a/desktop/entitlements.plist b/desktop/entitlements.plistindex 35830b4..4e6d54b 100644--- a/desktop/entitlements.plist+++ b/desktop/entitlements.plist@@ -20,6 +20,9 @@<!-- Looking through the camera when asked. --><key>com.apple.security.device.camera</key><true/>+ <!-- device.location: where this Mac is, when asked. -->+ <key>com.apple.security.personal-information.location</key>+ <true/><!-- Calendar, Reminders, Contacts and other apps, via AppleScript. --><key>com.apple.security.automation.apple-events</key><true/>diff --git a/desktop/native/AndeeMac.swift b/desktop/native/AndeeMac.swiftindex 4ffb33c..e1422df 100644--- a/desktop/native/AndeeMac.swift+++ b/desktop/native/AndeeMac.swift@@ -8,6 +8,8 @@import AppKitimport ApplicationServices+import AVFoundation+import CoreLocationimport CoreGraphicsimport Foundationimport ScreenCaptureKit@@ -511,3 +513,131 @@ public func andee_own_window_at(_ x: Double, _ y: Double) -> Int32 {}return 0}++// MARK: - camera (device.look: one frame through the lens)++private final class PhotoTaker: NSObject, AVCapturePhotoCaptureDelegate {+ let done = DispatchSemaphore(value: 0)+ var jpeg: Data?+ func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {+ jpeg = photo.fileDataRepresentation()+ done.signal()+ }+}++/// Capture one frame from the camera to [path] as PNG, downscaled to [maxSide] on the long edge.+/// The Mac's honest analog of the phone's look session: one frame per call, no+/// persistent viewfinder. Returns 1 on success; 0 when there is no camera or+/// permission is missing (Camera usage is in the entitlements/Info.plist).+@_cdecl("andee_camera_shot")+public func andee_camera_shot(_ path: UnsafePointer<CChar>, _ front: Int32, _ maxSide: Int32) -> Int32 {+ let discovery = AVCaptureDevice.DiscoverySession(+ deviceTypes: [.builtInWideAngleCamera],+ mediaType: .video,+ position: front != 0 ? .front : .back+ )+ guard let device = discovery.devices.first(where: { front != 0 ? $0.position == .front : $0.position == .back })+ ?? discovery.devices.first ?? AVCaptureDevice.default(for: .video) else { return 0 }+ let session = AVCaptureSession()+ session.sessionPreset = .high+ guard let input = try? AVCaptureDeviceInput(device: device), session.canAddInput(input) else { return 0 }+ session.addInput(input)+ let output = AVCapturePhotoOutput()+ guard session.canAddOutput(output) else { return 0 }+ session.addOutput(output)+ let taker = PhotoTaker()+ session.startRunning()+ // Give the exposure a moment to settle (the phone's EXPOSURE_SETTLE_MS, for+ // the same reason: the first frame after start is washed out or near-black).+ usleep(400_000)+ output.capturePhoto(with: AVCapturePhotoSettings(), delegate: taker)+ let got = taker.done.wait(timeout: .now() + 5) == .success+ session.stopRunning()+ guard got, var data = taker.jpeg else { return 0 }+ let out = URL(fileURLWithPath: String(cString: path))+ if maxSide > 0, let src = CGImageSourceCreateWithData(data as CFData, nil),+ let img = CGImageSourceCreateImageAtIndex(src, 0, nil) {+ let w = img.width, h = img.height+ let long = max(w, h)+ let scale = min(1.0, Double(maxSide) / Double(long))+ let tw = max(1, Int(Double(w) * scale)), th = max(1, Int(Double(h) * scale))+ if let cs = CGColorSpace(name: CGColorSpace.sRGB),+ let ctx = CGContext(data: nil, width: tw, height: th, bitsPerComponent: 8, bytesPerRow: 0, space: cs,+ bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) {+ ctx.interpolationQuality = .high+ ctx.draw(img, in: CGRect(x: 0, y: 0, width: tw, height: th))+ if let small = ctx.makeImage(),+ let j = CFDataCreateMutable(nil, 0) {+ let dest = CGImageDestinationCreateWithData(j, "public.png" as CFString, 1, nil)!+ CGImageDestinationAddImage(dest, small, nil)+ if CGImageDestinationFinalize(dest) { data = j as Data }+ }+ }+ }+ return (try? data.write(to: out)) != nil ? 1 : 0+}++// MARK: - brightness & location (device.brightness / device.location)++@_silgen_name("CoreDisplay_Display_GetUserBrightness")+private func cdGetBrightness(_ d: CGDirectDisplayID) -> Double+@_silgen_name("CoreDisplay_Display_SetUserBrightness")+private func cdSetBrightness(_ d: CGDirectDisplayID, _ b: Double)++/// The main display's brightness, 0–1. CoreDisplay works on the built-in panel; -1 when it cannot.+@_cdecl("andee_brightness_get")+public func andee_brightness_get() -> Double {+ return cdGetBrightness(CGMainDisplayID())+}++@_cdecl("andee_brightness_set")+public func andee_brightness_set(_ b: Double) -> Int32 {+ cdSetBrightness(CGMainDisplayID(), min(1.0, max(0.0, b)))+ return 1+}++private final class Locator: NSObject, CLLocationManagerDelegate {+ let done = DispatchSemaphore(value: 0)+ var loc: CLLocation?+ var err: String?+ func locationManager(_ m: CLLocationManager, didUpdateLocations locs: [CLLocation]) {+ loc = locs.last; done.signal()+ }+ func locationManager(_ m: CLLocationManager, didFailWithError e: Error) {+ err = e.localizedDescription; done.signal()+ }+}+private var locatorKeep: (CLLocationManager, Locator)?++/// One-shot location. CoreLocation on a Mac is Wi-Fi/IP-based and often off or+/// imprecise; that is what it returns, not a phone-grade GPS fix.+@_cdecl("andee_location")+public func andee_location() -> UnsafeMutablePointer<CChar> {+ let out = DispatchSemaphore(value: 0)+ var result: [String: Any] = [:]+ DispatchQueue.main.async {+ guard CLLocationManager.locationServicesEnabled() else {+ result["error"] = "Location Services are off on this Mac"+ out.signal(); return+ }+ let m = CLLocationManager()+ let l = Locator()+ m.delegate = l+ locatorKeep = (m, l)+ m.desiredAccuracy = kCLLocationAccuracyHundredMeters+ m.requestLocation()+ let got = l.done.wait(timeout: .now() + 8) == .success+ locatorKeep = nil+ if let c = l.loc {+ result["lat"] = c.coordinate.latitude+ result["lng"] = c.coordinate.longitude+ result["accuracy_m"] = c.horizontalAccuracy+ } else {+ result["error"] = l.err ?? "no fix (Location Services may be off or not promptable here)"+ }+ _ = got+ out.signal()+ }+ _ = out.wait(timeout: .now() + 10)+ return json(result)+}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.ktindex 2c080e4..d3fb951 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@@ -39,6 +39,10 @@ object Bridge {fun andee_set_own_alpha(alpha: Double): Intfun andee_notif_latest_id(): Longfun andee_own_window_at(x: Double, y: Double): Int+ fun andee_camera_shot(path: String, front: Int, maxSide: Int): Int+ fun andee_brightness_get(): Double+ fun andee_brightness_set(b: Double): Int+ fun andee_location(): Pointerfun andee_notif_since(afterId: Long): Pointerfun andee_notif_watch(cb: NotifCallback): Int}@@ -96,6 +100,14 @@ object Bridge {/** True when one of Andee's visible windows covers (x, y); unknown counts as yes. */fun ownWindowAt(x: Double, y: Double) = lib?.andee_own_window_at(x, y) != 0+ /** Capture one camera frame to [path] as PNG; false when there is no camera or permission. */+ fun cameraShot(path: String, front: Boolean, maxSide: Int = 1280) = lib?.andee_camera_shot(path, if (front) 1 else 0, maxSide) == 1++ /** The main display's brightness, 0–1. */+ fun brightnessGet(): Double = lib?.andee_brightness_get() ?: -1.0+ 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). */fun notifLatestId(): Long = lib?.andee_notif_latest_id() ?: -1/** Records after [afterId]: id, bundle, app, title, subtitle, body, when. */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.ktindex ca631d0..078e4b3 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@@ -53,6 +53,10 @@ class MacDevice : DesktopBrainHost.ToolProvider {"device.permissions" -> permissions()"device.permissions.request" -> requestPermissions(p)"device.notifications" -> MacNotifications.snapshot(p.optLong("since_ms", 0L), p.optInt("limit", 20).coerceIn(1, 50))+ "device.look" -> look(p.optBoolean("front", false))+ "device.look_stop" -> JSONObject().put("closed", true)+ "device.brightness" -> brightness(p)+ "device.location" -> Bridge.location()"device.vault.list" -> MacVault.list()"device.vault.get" -> MacVault.get(p.optString("entry"), p.optString("field"))"device.vault.fill" -> MacVault.fill(p.optString("entry"))@@ -217,6 +221,27 @@ class MacDevice : DesktopBrainHost.ToolProvider {return JSONObject().put("contacts", arr).put("count", arr.length())}+ /** Brightness uses the phone's 1..255 scale on the wire; CoreDisplay wants 0–1. */+ private fun brightness(p: JSONObject): JSONObject {+ val raw = p.optInt("brightness", -1)+ if (raw < 0) return JSONObject().put("brightness", (Bridge.brightnessGet() * 255).toInt().coerceIn(1, 255))+ Bridge.brightnessSet(raw / 255.0)+ return JSONObject().put("brightness", raw)+ }++ /** One frame through the lens. The Mac has no persistent viewfinder, so each call is one shot; the privacy tell is the scrollback row. */+ private fun look(front: Boolean): JSONObject {+ val f = File.createTempFile("andee-look", ".png")+ try {+ if (!Bridge.cameraShot(f.path, front)) {+ return JSONObject().put("error", "The camera could not be used on this Mac (no camera, or the Camera permission is missing). Say so; do not claim to see.")+ }+ val b64 = java.util.Base64.getEncoder().encodeToString(f.readBytes())+ Scrollback.add(Scrollback.Role.ASSISTANT, "📷 " + (if (Strings.lang() == "zh") "看了一眼(" else "Looked (") + (if (front) "front" else "back") + ")")+ return JSONObject().put("png_base64", b64).put("camera", if (front) "front" else "back")+ } finally { f.delete() }+ }+/*** The polite permission concierge, the phone's PermissionsController on the* Mac: says exactly what is missing in one sentence, and on confirm fires@@ -291,7 +316,7 @@ class MacDevice : DesktopBrainHost.ToolProvider {val METHODS = setOf("device.launch", "device.open_url", "device.apps", "device.battery", "device.connectivity", "device.volume","device.facts", "device.calendar", "device.calendar.add", "device.alarm", "device.contacts",- "device.permissions", "device.permissions.request", "device.notifications", "device.vault.list", "device.vault.get", "device.vault.fill",+ "device.permissions", "device.permissions.request", "device.notifications", "device.look", "device.look_stop", "device.brightness", "device.location", "device.vault.list", "device.vault.get", "device.vault.fill",)}}