import Foundation import Observation /// The list's order belongs to the server. Viewer fields have an event /// sequence of their own: shared revisions alone cannot order personal names. @MainActor @Observable public final class ProjectCatalog { public private(set) var projects: [String: ThinProject] = [:] private var order: [String] = [] public private(set) var connections: [ProjectConnection] = [] private var reachable: [ReachableProject] = [] public private(set) var loaded = false public private(set) var notice: String? public private(set) var pending: Set = [] public var selection: ThinProject? { didSet { if selection != nil { selectionNotice = nil } } } public private(set) var selectionNotice: String? private var listSequence: Int64 = -1 var client: EquipoClient let lifetime: SignInLifetime private var sequence: [String: Int64] = [:] private var generation = 0 var snapshotGeneration: Int { generation } private var reading = false private var readAgain = false init(client: EquipoClient, lifetime: SignInLifetime) { self.client = client; self.lifetime = lifetime } /// The engine's owner form is on the project page, with its current revision. public func detailsURL(_ project: ThinProject) -> URL { client.origin.appendingPathComponent("projects").appendingPathComponent(project.id) } public var items: [ThinProject] { order.compactMap { projects[$0] }.filter { $0.state == "active" } } public var available: [ReachableProject] { reachable.filter { repo in connections.contains { $0.id == repo.connectionId && $0.canAdd } } } /// The next composer send consumes both its project and any released-selection notice. func takeSelection() -> String? { let id = selection?.id selection = nil selectionNotice = nil return id } public func refresh() async { guard lifetime.isActive else { return } if reading { readAgain = true; return } reading = true defer { reading = false } repeat { readAgain = false let started = generation do { let list = try await client.projects() guard lifetime.isActive else { return } // A write or streamed viewer update overtook this read. Read // again; do not restore a personal name or an old star meanwhile. guard started == generation else { readAgain = true; continue } let values = list.items ?? [] listSequence = max(listSequence, list.cursor ?? -1) order = values.map(\.id) for p in values where p.revision >= (projects[p.id]?.revision ?? -1) { projects[p.id] = p } let ids = Set(order) projects = projects.filter { ids.contains($0.key) } connections = list.connections ?? []; reachable = list.canAdd ?? [] loaded = true; notice = nil reconcileSelection() } catch { guard lifetime.isActive else { return } notice = ProjectNotice.text(error) } } while readAgain && lifetime.isActive && !Task.isCancelled } func applySnapshot(_ values: [ThinProject], cursor: Int64, generation expected: Int? = nil) { guard lifetime.isActive, cursor >= listSequence, expected == nil || expected == generation else { return } for p in values where cursor >= (sequence[p.id] ?? -1) && p.revision >= (projects[p.id]?.revision ?? -1) { projects[p.id] = p sequence[p.id] = cursor } generation += 1 } func applyEvent(_ project: ThinProject, cursor: Int64) { guard lifetime.isActive, cursor > max(listSequence, sequence[project.id] ?? -1), project.revision >= (projects[project.id]?.revision ?? -1) else { return } sequence[project.id] = cursor generation += 1 projects[project.id] = project reconcileSelection() } private func reconcileSelection() { guard let selected = selection else { return } if projects[selected.id]?.state != "active" { releaseSelection(selected.id) } } func releaseSelection(_ id: String) { if selection?.id == id { selection = nil } selectionNotice = EquipoStrings.text("projects.selection_lost") } public func setStar(_ project: ThinProject, _ starred: Bool) async { guard lifetime.isActive, pending.insert(project.id).inserted else { return } generation += 1 let started = generation let old = projects[project.id] projects[project.id]?.starred = starred defer { pending.remove(project.id) } do { let answer = try await client.setStar(project.id, starred) guard lifetime.isActive else { return } if started == generation { projects[project.id] = answer } generation += 1 notice = nil // Restore the server's ordering after the optimistic toggle. await refresh() } catch { guard lifetime.isActive else { return } projects[project.id]?.starred = old?.starred notice = ProjectNotice.text(error) } } public func forgetName(_ name: String, in project: ThinProject) async { guard lifetime.isActive, pending.insert(project.id).inserted else { return } generation += 1 let started = generation defer { pending.remove(project.id) } do { try await client.forgetName(name, projectID: project.id) guard lifetime.isActive else { return } if started == generation { let remaining = (projects[project.id]?.personalNames ?? []).filter { $0.caseInsensitiveCompare(name) != .orderedSame } projects[project.id]?.personalNames = remaining } generation += 1 notice = nil } catch { if lifetime.isActive { notice = ProjectNotice.text(error) } } } public func add(_ repo: ReachableProject) async { guard lifetime.isActive, available.contains(repo), pending.insert(repo.id).inserted else { return } generation += 1 defer { pending.remove(repo.id) } do { _ = try await client.addProject(repo.repo) guard lifetime.isActive else { return } await refresh() } catch { if lifetime.isActive { notice = ProjectNotice.text(error) } } } } /// Error copy keys are data, never arbitrary format strings. Resolve only /// catalog entries we know; otherwise retain the existing native failure copy. public enum ProjectNotice { public static func text(_ error: Error) -> String { knownText(error) ?? EquipoStrings.text(error as? EquipoAPIError == .offline ? "card.offline" : "card.failed") } public static func knownText(_ error: Error) -> String? { if case EquipoAPIError.server(_, let body) = error, ["api.not_found", "api.invalid_input", "api.repo_not_allowed", "api.forbidden", "api.idempotency_conflict", "api.card_answered", "api.card_stale", "api.confirmation_required", "api.coordinator_busy", "api.hold_bar", "api.models_not_allowed", "api.not_active", "api.not_askable", "api.not_mergeable", "api.not_retryable", "api.question_ended", "api.runner_offline", "api.task_busy", "api.task_ended", "api.task_merging", "api.turn_ended"].contains(body.copyKey) { let text = EquipoStrings.text(String.LocalizationValue(body.copyKey)) if text != body.copyKey { return text } } return nil } }