// 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)importCottonKitimportCoreGraphicsimportFoundationimport osfinalclassAlbumsFeed: 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.privatelet 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).privatelet waiting = OSAllocatedUnfairLock(initialState: 0)init(core: any CottonCalling) {self.core = corelet (stream, continuation) = AsyncStream<@Sendable () async -> Void>.makeStream() queue = continuationTask.detached(priority: .utility) {forawait 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] inlet started = ContinuousClock.nowawait 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 }) }privatelet 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? awaitTask.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..<min($0 + 1000, assets.count)]) }if batches.isEmpty { batches = [[]] }for (n, batch) in batches.enumerated() {var body: [String: Any] = ["items": batch.map { Self.item($0, sizes[$0.id]) }]if n == 0, !removed.isEmpty { body["removed"] = removed }if n == batches.count - 1, let all { body["all_ids"] = all }await call("albums.library.take", body) } }/// What one batch of the pass saw: the picture as grey at the size it came (never scaled up), with Vision's/// findings; `null` when the phone gave no picture.func looks(_ found: [(id: String, state: AlbumsItem.State, look: AlbumsLook?)], network: Bool = false) async {let looks: [[String: Any]] = found.compactMap { one inswitch one.state {case .looked, .small:guardlet look = one.look else { returnnil }var row: [String: Any] = ["id": one.id, "network": network, "platform": Self.platform(look)]iflet grey = look.grey { row["grey"] = ["width": grey.width, "height": grey.height, "pixels": grey.pixels.base64EncodedString()] }return rowcase .onlyInCloud, .failed:return ["id": one.id, "network": network, "grey": NSNull()]default:returnnil } }guard !looks.isEmpty else { return }await call("albums.look.take", ["looks": looks]) }enumPassState: String { case running, pausedBattery = "paused_battery", pausedClosed = "paused_closed" }func lines(_ state: PassState, charging: Bool) async {await call("albums.pass.lines", ["state": state.rawValue, "charging": charging]) }/// People: every face with a vector and his names go to the core's GROUPING 1 (`albums.faces.group`); the groups/// that come back replace the store's. Answers the groups shown, or nil when the core did not answer. @discardableResultfunc group(_ store: AlbumsStore) async -> 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.nowguardlet out = await answer("albums.faces.group", ["faces": faces, "names": names]),let groups = out["groups"] as? [[String: Any]] else { returnnil }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).countLog.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]? {guardlet 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 { returnnil }iflet error = envelope["error"] {// Once a run per method: a core without `albums.*` (or a refusal repeated each batch) is said, not spammed.ifSelf.first(method) { Log.write("albums: \(method) refused: \(error)") }returnnil }return envelope["data"] as? [String: Any] } nonisolated(unsafe) privatestaticvar said = Set<String>()privatestaticlet saying = NSLock()privatestaticfunc first(_ method: String) -> Bool { saying.withLock { said.insert(method).inserted } }privatefunc call(_ method: String, _ body: [String: Any]) async { _ = await answer(method, body) }// MARK: The contract's shapesstaticfunc 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.iflet size, size.exact, size.bytes > 0 { row["bytes"] = size.bytes }iflet 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.iflet lat = a.latitude, let lon = a.longitude { row["latitude"] = lat; row["longitude"] = lon }return row }staticfunc 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.iflet a = look.aesthetic { p["aesthetics"] = a }iflet best = look.faces.compactMap(\.quality).max() { p["face_quality"] = best }return p }}#endif