Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions Interceptor/Automation/PackageCatalogDatabase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ protocol PackageCatalogStoring: AnyObject {
func detail(in record: RepositoryRecord, entryID: UUID) throws -> PluginPackagePresentation?
func packageBytes(in record: RepositoryRecord, entry: IndexEntry) throws -> Data?
func reusableBytes(sha256: String) throws -> Data?
/// Background-only accepted content read and bounded package validation for display.
func icon(sha256: String) async throws -> PluginIcon?
func isComplete(_ snapshot: VerifiedSnapshot) throws -> Bool
}

Expand Down Expand Up @@ -189,6 +191,10 @@ final class PackageCatalogDatabase: PackageCatalogStoring {
try content(sha256: sha256, size: nil, in: readContext())
}

func icon(sha256: String) async throws -> PluginIcon? {
try await writer.icon(sha256: sha256)
}

func isComplete(_ snapshot: VerifiedSnapshot) throws -> Bool {
let context = readContext()
let snapshotKey = PackageCatalogKeys.snapshot(snapshot)
Expand Down Expand Up @@ -278,6 +284,13 @@ actor PackageCatalogWriter {
return context
}

func icon(sha256: String) throws -> PluginIcon? {
let context = makeContext()
guard let content = try context.fetch(FetchDescriptor<CatalogContentModel>(predicate: #Predicate { $0.sha256 == sha256 })).first,
content.bytes.count <= Limits.package, Digest.sha256Hex(content.bytes) == sha256 else { throw PackageCatalogError.contentMismatch }
return try PluginPackage.validate(content.bytes).icon
}

func stage(_ snapshot: VerifiedSnapshot, packages: [PluginPackage], leaseID: UUID) throws {
let plugins = snapshot.index.plugins
guard plugins.count <= Limits.plugins, packages.count == plugins.count else { throw PackageCatalogError.invalidSnapshot }
Expand Down
13 changes: 13 additions & 0 deletions Interceptor/Automation/PluginBrowserModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,19 @@ final class PluginBrowserModel {

init(controller: AutomationController) { self.controller = controller }

/// Selected installed content takes precedence over an advertised repository update.
func iconSource(for family: PluginBrowserFamilyID, entry: IndexEntry?, record: RepositoryRecord?) -> PluginIconSource? {
if let selected = selectedRevision(for: family) { return .bundled(selected.package) }
guard let entry, let record, entry.id == family.manifestID, record.url.canonical == family.source,
let current = currentRecord(record), current.repositoryID == record.repositoryID,
current.snapshot?.index.plugins.contains(entry) == true,
let database = controller.packageCatalog else { return nil }
let sha = entry.sha256
return PluginIconSource(id: sha + ":" + String(controller.packageCatalogRevision), cacheKey: sha) {
try await database.icon(sha256: sha)
}
}

var canDismissQueue: Bool { !isProcessing }

var hasSourceRefreshFailures: Bool {
Expand Down
111 changes: 111 additions & 0 deletions Interceptor/Automation/PluginIconLoader.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import AutomationCore
import Foundation
import ImageIO
import UIKit

/// Display-only input. Repository reads use accepted local content; this closure never fetches a URL.
struct PluginIconSource: Sendable {
let id: String
let cacheKey: String
let load: @Sendable () async throws -> PluginIcon?

static func bundled(_ package: PluginPackage) -> PluginIconSource? {
guard let icon = package.icon else { return nil }
let key = Digest.sha256Hex(icon.data)
return .init(id: key, cacheKey: key, load: { icon })
}
}

/// UIImage is immutable after construction; decoding happens away from the UI actor.
struct DecodedPluginIcon: @unchecked Sendable {
let image: UIImage
let cost: Int
}

/// Bounded thumbnails shared by list, hero and queue. Missing catalog content is not negatively cached.
actor PluginIconLoader {
static let shared = PluginIconLoader()
private struct Loaded: Sendable {
let available: Bool
let image: DecodedPluginIcon?
}
private var entries: [String: Loaded] = [:]
private var order: [String] = []
private var absent = Set<String>()
private var absentOrder: [String] = []
private let absentLimit = Limits.plugins * Limits.repositories
private struct PendingKey: Hashable { let revision: String; let generation: String }
private var pending: [PendingKey: (id: UUID, task: Task<Loaded, Never>)] = [:]
private var cost = 0
private let countLimit: Int
private let costLimit: Int

init(countLimit: Int = 64, costLimit: Int = 8 * 1024 * 1024) {
self.countLimit = max(1, countLimit)
self.costLimit = max(0, costLimit)
}

func image(for source: PluginIconSource) async -> DecodedPluginIcon? {
if absent.contains(source.cacheKey) { return nil }
if let hit = entries[source.cacheKey] {
touch(source.cacheKey)
return hit.image
}
let pendingKey = PendingKey(revision: source.cacheKey, generation: source.id)
let task: Task<Loaded, Never>
let taskID: UUID
if let existing = pending[pendingKey] {
task = existing.task
taskID = existing.id
} else {
taskID = UUID()
task = Task.detached(priority: .utility) {
do {
let icon = try await source.load()
return Loaded(available: true, image: icon.flatMap(Self.decode))
} catch {
return Loaded(available: false, image: nil)
}
}
pending[pendingKey] = (taskID, task)
}
let loaded = await task.value
// Only the first waiter inserts this result.
guard pending[pendingKey]?.id == taskID else { return loaded.image }
pending.removeValue(forKey: pendingKey)
if loaded.available, loaded.image == nil {
absent.insert(source.cacheKey)
absentOrder.removeAll { $0 == source.cacheKey }
absentOrder.append(source.cacheKey)
if absentOrder.count > absentLimit { absent.remove(absentOrder.removeFirst()) }
} else if loaded.available {
cost -= entries[source.cacheKey]?.image?.cost ?? 0
entries[source.cacheKey] = loaded
cost += loaded.image?.cost ?? 0
touch(source.cacheKey)
while order.count > countLimit || cost > costLimit {
let key = order.removeFirst()
cost -= entries.removeValue(forKey: key)?.image?.cost ?? 0
}
}
return loaded.image
}

private func touch(_ key: String) {
order.removeAll { $0 == key }
order.append(key)
}

nonisolated private static func decode(_ icon: PluginIcon) -> DecodedPluginIcon? {
guard let source = CGImageSourceCreateWithData(icon.data as CFData, nil),
CGImageSourceGetCount(source) == 1,
let image = CGImageSourceCreateThumbnailAtIndex(source, 0, [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceThumbnailMaxPixelSize: 192,
kCGImageSourceShouldCacheImmediately: true,
kCGImageSourceCreateThumbnailWithTransform: true,
] as CFDictionary)
else { return nil }
return DecodedPluginIcon(image: UIImage(cgImage: image), cost: image.bytesPerRow * image.height)
}
}
62 changes: 45 additions & 17 deletions Interceptor/Views/Automation/PluginBrowserComponents.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import SwiftUI
import AutomationCore
import UIKit

/// Shared browser colors follow the selected Sileo reference in both appearances.
Expand All @@ -16,14 +17,15 @@ struct PluginPackageRow: View {
let author: String?
let version: String
let summary: String
var iconSource: PluginIconSource?
var systemImage = "shippingbox"
var iconColor = PluginBrowserColor.accent
var isInstalled = false
var accessibilityPrefix = "plugins.package"

var body: some View {
HStack(alignment: .top, spacing: 14) {
PluginBrowserIcon(systemImage: systemImage, color: iconColor, isInstalled: isInstalled)
PluginBrowserIcon(systemImage: systemImage, color: iconColor, isInstalled: isInstalled, source: iconSource)
VStack(alignment: .leading, spacing: 2) {
Text(verbatim: name)
.font(.body.weight(.semibold))
Expand Down Expand Up @@ -104,6 +106,7 @@ struct PluginPackageModifyActions {
struct PluginPackageHero: View {
let name: String
let targetHosts: [String]
var iconSource: PluginIconSource?
var systemImage = "shippingbox"
var iconColor = PluginBrowserColor.accent
var actionTitle: LocalizedStringKey?
Expand All @@ -123,6 +126,7 @@ struct PluginPackageHero: View {
systemImage: systemImage,
color: iconColor,
size: horizontalSizeClass == .compact ? 56 : 60,
source: iconSource,
)
VStack(alignment: .leading, spacing: 4) {
Text(verbatim: name)
Expand Down Expand Up @@ -234,6 +238,7 @@ struct PluginInstallQueueDisplayEntry: Identifiable {
let version: String
var detail: LocalizedStringKey = "AUTO_BROWSER_QUEUE_WAITING"
var isValid = true
var iconSource: PluginIconSource?
var systemImage = "shippingbox"
var iconColor = PluginBrowserColor.accent
}
Expand Down Expand Up @@ -317,7 +322,7 @@ struct PluginInstallSheetContent: View {
.disabled(isBusy)
.accessibilityLabel(Text("AUTO_BROWSER_QUEUE_REMOVE \(entry.name)"))
.accessibilityIdentifier("plugins.queue.remove." + entry.id)
PluginBrowserIcon(systemImage: entry.systemImage, color: entry.iconColor)
PluginBrowserIcon(systemImage: entry.systemImage, color: entry.iconColor, source: entry.iconSource)
VStack(alignment: .leading, spacing: 3) {
Text(verbatim: entry.name).font(.body.weight(.semibold))
(Text(verbatim: entry.version) + Text(" · ") + Text(isBusy ? LocalizedStringKey("AUTO_BROWSER_INSTALLING") : entry.detail))
Expand Down Expand Up @@ -382,23 +387,46 @@ private struct PluginBrowserIcon: View {
let color: Color
var size: CGFloat = 40
var isInstalled = false
var source: PluginIconSource?
@State private var decoded: DecodedPluginIcon?
@State private var loadedKey: String?

var body: some View {
Image(systemName: systemImage)
.font(.system(size: size * 0.58, weight: .regular))
.foregroundStyle(.white)
.frame(width: size, height: size)
.background(color, in: RoundedRectangle(cornerRadius: size * 0.225))
.overlay(alignment: .bottomTrailing) {
if isInstalled {
Image(systemName: "checkmark")
.font(.system(size: 9, weight: .heavy))
.foregroundStyle(.white)
.frame(width: 14, height: 14)
.background(AutomationStatusColor.ok, in: Circle())
.offset(x: 4, y: 4)
}
Group {
if loadedKey == source?.cacheKey, let decoded {
Image(uiImage: decoded.image)
.resizable()
.scaledToFit()
} else {
Image(systemName: systemImage)
.font(.system(size: size * 0.58, weight: .regular))
.foregroundStyle(.white)
}
}
.frame(width: size, height: size)
.background(color, in: RoundedRectangle(cornerRadius: size * 0.225))
.clipShape(RoundedRectangle(cornerRadius: size * 0.225))
.overlay(alignment: .bottomTrailing) {
if isInstalled {
Image(systemName: "checkmark")
.font(.system(size: 9, weight: .heavy))
.foregroundStyle(.white)
.frame(width: 14, height: 14)
.background(AutomationStatusColor.ok, in: Circle())
.offset(x: 4, y: 4)
}
.accessibilityHidden(true)
}
.task(id: source?.id) {
if loadedKey != source?.cacheKey {
decoded = nil
loadedKey = nil
}
guard let source else { return }
let image = await PluginIconLoader.shared.image(for: source)
guard !Task.isCancelled else { return }
decoded = image
loadedKey = source.cacheKey
}
.accessibilityHidden(true)
}
}
Loading