| 1 | import Foundation |
| 2 | import Observation |
| 3 | |
| 4 | /// The list's order belongs to the server. Viewer fields have an event |
| 5 | /// sequence of their own: shared revisions alone cannot order personal names. |
| 6 | @MainActor @Observable public final class ProjectCatalog { |
| 7 | public private(set) var projects: [String: ThinProject] = [:] |
| 8 | private var order: [String] = [] |
| 9 | public private(set) var connections: [ProjectConnection] = [] |
| 10 | private var reachable: [ReachableProject] = [] |
| 11 | public private(set) var loaded = false |
| 12 | public private(set) var notice: String? |
| 13 | public private(set) var pending: Set<String> = [] |
| 14 | public var selection: ThinProject? { didSet { if selection != nil { selectionNotice = nil } } } |
| 15 | public private(set) var selectionNotice: String? |
| 16 | private var listSequence: Int64 = -1 |
| 17 | var client: EquipoClient |
| 18 | let lifetime: SignInLifetime |
| 19 | private var sequence: [String: Int64] = [:] |
| 20 | private var generation = 0 |
| 21 | var snapshotGeneration: Int { generation } |
| 22 | private var reading = false |
| 23 | private var readAgain = false |
| 24 | |
| 25 | init(client: EquipoClient, lifetime: SignInLifetime) { self.client = client; self.lifetime = lifetime } |
| 26 | /// The engine's owner form is on the project page, with its current revision. |
| 27 | public func detailsURL(_ project: ThinProject) -> URL { |
| 28 | client.origin.appendingPathComponent("projects").appendingPathComponent(project.id) |
| 29 | } |
| 30 | public var items: [ThinProject] { order.compactMap { projects[$0] }.filter { $0.state == "active" } } |
| 31 | public var available: [ReachableProject] { |
| 32 | reachable.filter { repo in connections.contains { $0.id == repo.connectionId && $0.canAdd } } |
| 33 | } |
| 34 | |
| 35 | /// The next composer send consumes both its project and any released-selection notice. |
| 36 | func takeSelection() -> String? { |
| 37 | let id = selection?.id |
| 38 | selection = nil |
| 39 | selectionNotice = nil |
| 40 | return id |
| 41 | } |
| 42 | |
| 43 | public func refresh() async { |
| 44 | guard lifetime.isActive else { return } |
| 45 | if reading { readAgain = true; return } |
| 46 | reading = true |
| 47 | defer { reading = false } |
| 48 | repeat { |
| 49 | readAgain = false |
| 50 | let started = generation |
| 51 | do { |
| 52 | let list = try await client.projects() |
| 53 | guard lifetime.isActive else { return } |
| 54 | // A write or streamed viewer update overtook this read. Read |
| 55 | // again; do not restore a personal name or an old star meanwhile. |
| 56 | guard started == generation else { readAgain = true; continue } |
| 57 | let values = list.items ?? [] |
| 58 | listSequence = max(listSequence, list.cursor ?? -1) |
| 59 | order = values.map(\.id) |
| 60 | for p in values where p.revision >= (projects[p.id]?.revision ?? -1) { projects[p.id] = p } |
| 61 | let ids = Set(order) |
| 62 | projects = projects.filter { ids.contains($0.key) } |
| 63 | connections = list.connections ?? []; reachable = list.canAdd ?? [] |
| 64 | loaded = true; notice = nil |
| 65 | reconcileSelection() |
| 66 | } catch { |
| 67 | guard lifetime.isActive else { return } |
| 68 | notice = ProjectNotice.text(error) |
| 69 | } |
| 70 | } while readAgain && lifetime.isActive && !Task.isCancelled |
| 71 | } |
| 72 | |
| 73 | func applySnapshot(_ values: [ThinProject], cursor: Int64, generation expected: Int? = nil) { |
| 74 | guard lifetime.isActive, cursor >= listSequence, expected == nil || expected == generation else { return } |
| 75 | for p in values where cursor >= (sequence[p.id] ?? -1) && p.revision >= (projects[p.id]?.revision ?? -1) { |
| 76 | projects[p.id] = p |
| 77 | sequence[p.id] = cursor |
| 78 | } |
| 79 | generation += 1 |
| 80 | } |
| 81 | func applyEvent(_ project: ThinProject, cursor: Int64) { |
| 82 | guard lifetime.isActive, cursor > max(listSequence, sequence[project.id] ?? -1), |
| 83 | project.revision >= (projects[project.id]?.revision ?? -1) else { return } |
| 84 | sequence[project.id] = cursor |
| 85 | generation += 1 |
| 86 | projects[project.id] = project |
| 87 | reconcileSelection() |
| 88 | } |
| 89 | |
| 90 | private func reconcileSelection() { |
| 91 | guard let selected = selection else { return } |
| 92 | if projects[selected.id]?.state != "active" { releaseSelection(selected.id) } |
| 93 | } |
| 94 | func releaseSelection(_ id: String) { |
| 95 | if selection?.id == id { selection = nil } |
| 96 | selectionNotice = EquipoStrings.text("projects.selection_lost") |
| 97 | } |
| 98 | |
| 99 | public func setStar(_ project: ThinProject, _ starred: Bool) async { |
| 100 | guard lifetime.isActive, pending.insert(project.id).inserted else { return } |
| 101 | generation += 1 |
| 102 | let started = generation |
| 103 | let old = projects[project.id] |
| 104 | projects[project.id]?.starred = starred |
| 105 | defer { pending.remove(project.id) } |
| 106 | do { |
| 107 | let answer = try await client.setStar(project.id, starred) |
| 108 | guard lifetime.isActive else { return } |
| 109 | if started == generation { projects[project.id] = answer } |
| 110 | generation += 1 |
| 111 | notice = nil |
| 112 | // Restore the server's ordering after the optimistic toggle. |
| 113 | await refresh() |
| 114 | } catch { |
| 115 | guard lifetime.isActive else { return } |
| 116 | projects[project.id]?.starred = old?.starred |
| 117 | notice = ProjectNotice.text(error) |
| 118 | } |
| 119 | } |
| 120 | public func forgetName(_ name: String, in project: ThinProject) async { |
| 121 | guard lifetime.isActive, pending.insert(project.id).inserted else { return } |
| 122 | generation += 1 |
| 123 | let started = generation |
| 124 | defer { pending.remove(project.id) } |
| 125 | do { |
| 126 | try await client.forgetName(name, projectID: project.id) |
| 127 | guard lifetime.isActive else { return } |
| 128 | if started == generation { |
| 129 | let remaining = (projects[project.id]?.personalNames ?? []).filter { $0.caseInsensitiveCompare(name) != .orderedSame } |
| 130 | projects[project.id]?.personalNames = remaining |
| 131 | } |
| 132 | generation += 1 |
| 133 | notice = nil |
| 134 | } catch { if lifetime.isActive { notice = ProjectNotice.text(error) } } |
| 135 | } |
| 136 | public func add(_ repo: ReachableProject) async { |
| 137 | guard lifetime.isActive, available.contains(repo), pending.insert(repo.id).inserted else { return } |
| 138 | generation += 1 |
| 139 | defer { pending.remove(repo.id) } |
| 140 | do { |
| 141 | _ = try await client.addProject(repo.repo) |
| 142 | guard lifetime.isActive else { return } |
| 143 | await refresh() |
| 144 | } catch { if lifetime.isActive { notice = ProjectNotice.text(error) } } |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | /// Error copy keys are data, never arbitrary format strings. Resolve only |
| 149 | /// catalog entries we know; otherwise retain the existing native failure copy. |
| 150 | public enum ProjectNotice { |
| 151 | public static func text(_ error: Error) -> String { |
| 152 | knownText(error) ?? EquipoStrings.text(error as? EquipoAPIError == .offline ? "card.offline" : "card.failed") |
| 153 | } |
| 154 | public static func knownText(_ error: Error) -> String? { |
| 155 | if case EquipoAPIError.server(_, let body) = error, |
| 156 | ["api.not_found", "api.invalid_input", "api.repo_not_allowed", "api.forbidden", "api.idempotency_conflict", |
| 157 | "api.card_answered", "api.card_stale", "api.confirmation_required", "api.coordinator_busy", "api.hold_bar", |
| 158 | "api.models_not_allowed", "api.not_active", "api.not_askable", "api.not_mergeable", "api.not_retryable", |
| 159 | "api.question_ended", "api.runner_offline", "api.task_busy", "api.task_ended", "api.task_merging", "api.turn_ended"].contains(body.copyKey) { |
| 160 | let text = EquipoStrings.text(String.LocalizationValue(body.copyKey)) |
| 161 | if text != body.copyKey { return text } |
| 162 | } |
| 163 | return nil |
| 164 | } |
| 165 | } |
| 166 | |