// THE CORE'S FEED (SHELL BRIEF, "What the shell does itself" 1–3): the library and the pass hand the core's phone-only // index (`albums.*`, crates/cotton-ffi/src/phone/albums_app.rs) what they read and saw, and the screens draw what the // core answers. Only facts go in: items (`albums.library.take`), what each picture showed (`albums.look.take`) and the // pass's state (`albums.pass.lines`). No act goes to the core from here (coordinator, 27 Nov: none until CORE 1b). // // Absence never removes a choice (rule A): `all_ids` is sent only when the read was complete with full access; items // leave otherwise only when PhotoKit's persistent changes name them deleted. #if os(iOS) import CottonKit import CoreGraphics import Foundation import os final class AlbumsFeed: Sendable { let core: any CottonCalling /// One call at a time, in the order given; the pass hands work over and never waits for the core. private let queue: AsyncStream<@Sendable () async -> Void>.Continuation /// Work handed over and not yet done. The pass waits on it (`caughtUp`), so what waits for the core stays a few /// batches long: an unbounded queue held every look's prints and faces in memory while the core fell behind /// (64,000 synthetic items on the simulator: the footprint rose in steps to 747 MB). private let waiting = OSAllocatedUnfairLock(initialState: 0) init(core: any CottonCalling) { self.core = core let (stream, continuation) = AsyncStream<@Sendable () async -> Void>.makeStream() queue = continuation Task.detached(priority: .utility) { for await work in stream { await work() } } } /// Hands `work` to the feed's queue and returns at once. func later(_ work: @escaping @Sendable (AlbumsFeed) async -> Void) { waiting.withLock { $0 += 1 } queue.yield { [self] in let started = ContinuousClock.now await work(self) let took = started.duration(to: .now) busy.withLock { $0 += Double(took.components.seconds) + Double(took.components.attoseconds) / 1e18 } waiting.withLock { $0 -= 1 } } } /// Seconds the core has spent on the feed's work since launch (how fast it keeps up, for the pass's log line). var busySeconds: Int { Int(busy.withLock { $0 }) } private let busy = OSAllocatedUnfairLock(initialState: 0.0) /// Work waiting for the core now. var pending: Int { waiting.withLock { $0 } } /// Returns once no more than `most` pieces of work wait for the core: the pass never runs further ahead of it. func caughtUp(most: Int) async { while pending > most { try? await Task.sleep(for: .milliseconds(50)) } } /// Items in batches of 1,000; `all` (every id in the library) only after a complete read with full access. func take(_ assets: [LibraryAsset], sizes: [String: LibrarySize], all: [String]? = nil, removed: [String] = []) async { var batches = stride(from: 0, to: assets.count, by: 1000).map { Array(assets[$0.. Int? { let names = store.names() let faces: [[String: Any]] = store.faceInputs().map { ["key": $0.key, "photo": $0.photo, "vector": $0.vector.base64EncodedString()] } let started = ContinuousClock.now guard let out = await answer("albums.faces.group", ["faces": faces, "names": names]), let groups = out["groups"] as? [[String: Any]] else { return nil } let parsed = groups.map { g in (faces: g["faces"] as? [String] ?? [], shown: g["shown"] as? Bool ?? false, person: g["person"] as? String) } store.setGroups(parsed) let shown = parsed.filter(\.shown).count Log.write("albums: \(faces.count) faces grouped in \(started.duration(to: .now)), \(groups.count) groups, \(shown) shown") return shown } /// The core's answer, for the Dev measurements; nil on any error. func answer(_ method: String, _ body: [String: Any] = [:]) async -> [String: Any]? { guard let data = try? JSONSerialization.data(withJSONObject: body), let raw = try? await core.callRaw(method, requestJSON: String(decoding: data, as: UTF8.self)), let envelope = try? JSONSerialization.jsonObject(with: Data(raw.utf8)) as? [String: Any] else { return nil } if let error = envelope["error"] { // Once a run per method: a core without `albums.*` (or a refusal repeated each batch) is said, not spammed. if Self.first(method) { Log.write("albums: \(method) refused: \(error)") } return nil } return envelope["data"] as? [String: Any] } nonisolated(unsafe) private static var said = Set() private static let saying = NSLock() private static func first(_ method: String) -> Bool { saying.withLock { said.insert(method).inserted } } private func call(_ method: String, _ body: [String: Any]) async { _ = await answer(method, body) } // MARK: The contract's shapes static func item(_ a: LibraryAsset, _ size: LibrarySize?) -> [String: Any] { var flags: [String] = [] if a.flags.contains(.screenshot) { flags.append("screenshot") } if a.flags.contains(.screenRecording) { flags.append("screen_recording") } if a.flags.contains(.live) { flags.append("live") } if a.burst != nil { flags.append("burst") } if a.flags.contains(.panorama) { flags.append("panorama") } if a.flags.contains(.hdr) { flags.append("hdr") } if a.flags.contains(.favourite) { flags.append("favourite") } if a.flags.contains(.hidden) { flags.append("hidden") } var row: [String: Any] = [ "id": a.id, "kind": a.kind == .video ? "video" : "photo", "taken_at_ms": Int64(((a.created ?? a.modified ?? .distantPast).timeIntervalSince1970 * 1000).rounded()), "width": a.width, "height": a.height, "duration_ms": Int64((a.duration * 1000).rounded()), "flags": flags, ] // Bytes only when the phone said: never zero for unknown. if let size, size.exact, size.bytes > 0 { row["bytes"] = size.bytes } if let name = size?.filename, !name.isEmpty { row["path"] = name } // Where it was taken, for trips and places (the core's rules/media/albums.rs): read by the core once its // `albums.*` methods take it; until then serde leaves an unknown key alone. if let lat = a.latitude, let lon = a.longitude { row["latitude"] = lat; row["longitude"] = lon } return row } static func platform(_ look: AlbumsLook) -> [String: Any] { var p: [String: Any] = ["utility": look.utility, "document": look.document, "faces": look.faces.count] // Vision's print stays in this phone's own store (coordinator, 27 Nov): the core keeps only its own hash. if let a = look.aesthetic { p["aesthetics"] = a } if let best = look.faces.compactMap(\.quality).max() { p["face_quality"] = best } return p } } #endif