Repository Public License
1// ORIX Convert — App/Sources/Features/Queue/QueueModel.swift2// Description: Main-actor mirror of the conversion queue, fed by ConversionQueue.events(). One observable object per3// job so a progress tick redraws one row. Tracks the current run for the global progress and summary.4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import AppKit6import ConvertCore7import Observation8import SwiftUI910@Observable final class JobItem: Identifiable {11 let id: UUID12 var job: ConversionJob13 init(_ job: ConversionJob) { id = job.id; self.job = job }14}1516/// Totals of one run of the queue (from the first job added while idle until the queue is idle again).17struct RunSummary: Equatable, Sendable {18 var total = 0, finished = 0, failed = 0, skipped = 0, cancelled = 019 var bytesBefore: Int64 = 020 var bytesAfter: Int64 = 021 /// Wall-clock seconds from the first start to the last end.22 var elapsed: TimeInterval = 023 var outputs: [URL] = []24}2526@Observable final class QueueModel {27 @ObservationIgnored unowned let app: AppModel28 @ObservationIgnored private var queue: ConversionQueue { app.manager.queue }29 private(set) var items: [UUID: JobItem] = [:]30 private(set) var order: [UUID] = []31 private(set) var status: QueueStatus?32 var selection: Set<UUID> = []33 /// Jobs of the current run.34 private(set) var runIDs: Set<UUID> = []35 private(set) var runStartedAt: Date?36 /// Summary of the last completed run, until dismissed or a new run starts.37 var lastSummary: RunSummary?38 var logJobID: UUID?39 @ObservationIgnored private var eventTask: Task<Void, Never>?4041 init(app: AppModel) { self.app = app }4243 func start() {44 guard eventTask == nil else { return }45 let queue = queue46 eventTask = Task { [weak self] in47 let events = await queue.events()48 let snapshot = await queue.snapshot()49 self?.apply(snapshot)50 for await event in events {51 guard let self else { return }52 self.handle(event)53 }54 }55 }5657 // MARK: Derived state5859 var jobs: [JobItem] { order.compactMap { items[$0] } }60 var isEmpty: Bool { order.isEmpty }61 var isPaused: Bool { status?.isPaused ?? false }62 var activeCount: Int { items.values.filter { $0.job.state.isActive }.count }63 var waitingCount: Int { items.values.filter { $0.job.state == .queued || $0.job.state == .paused }.count }64 var awaitingDecision: [JobItem] { jobs.filter { $0.job.state == .awaitingDecision } }65 var hasUnfinishedWork: Bool { items.values.contains { !$0.job.state.isTerminal } }66 var isRunning: Bool { !runIDs.isEmpty && runIDs.contains { items[$0].map { !$0.job.state.isSettled } ?? false } }67 var settledCount: Int { items.values.filter { $0.job.state.isTerminal }.count }68 var selectedJobs: [JobItem] { order.filter { selection.contains($0) }.compactMap { items[$0] } }6970 /// Measured progress of the current run: settled jobs plus the measured fractions of the running ones, over the71 /// number of jobs. `nil` when nothing is running or when nothing has been measured yet.72 var runProgress: (fraction: Double?, done: Int, total: Int)? {73 guard isRunning else { return nil }74 let run = runIDs.compactMap { items[$0]?.job }75 guard !run.isEmpty else { return nil }76 let done = run.filter { $0.state.isSettled }.count77 let partial = run.filter { $0.state.isActive }.compactMap { $0.progress.fraction }.reduce(0, +)78 let measured = done > 0 || partial > 079 return (measured ? min(1, (Double(done) + partial) / Double(run.count)) : nil, done, run.count)80 }8182 // MARK: Events8384 private func apply(_ snapshot: QueueSnapshot) {85 order = snapshot.jobs.map(\.id)86 var next: [UUID: JobItem] = [:]87 for job in snapshot.jobs {88 if let item = items[job.id] { item.job = job; next[job.id] = item } else { next[job.id] = JobItem(job) }89 }90 items = next91 status = snapshot.status92 selection.formIntersection(Set(order))93 }9495 private func handle(_ event: QueueEvent) {96 switch event {97 case .jobAdded(let job):98 joinRun(job.id)99 // A batch enqueued from the app is already mirrored by `enqueue` (one snapshot instead of n events).100 if let item = items[job.id] { item.job = job } else {101 items[job.id] = JobItem(job)102 order.append(job.id)103 }104 case .jobChanged(let job):105 if let item = items[job.id] { item.job = job } else { items[job.id] = JobItem(job); order.append(job.id) }106 if !job.state.isTerminal, !runIDs.contains(job.id) {107 // A retried or resolved job joins the current run.108 if !isRunning { runIDs = []; runStartedAt = Date(); lastSummary = nil }109 runIDs.insert(job.id)110 }111 checkRunEnd()112 case .jobProgress(let id, let progress, let eta):113 items[id]?.job.progress = progress114 items[id]?.job.estimatedSecondsRemaining = eta115 case .jobLog(let id, let line):116 items[id]?.job.log.append(line)117 case .jobWarning(let id, let warning):118 if let item = items[id], !item.job.warnings.contains(warning) { item.job.warnings.append(warning) }119 case .jobRemoved(let id):120 items[id] = nil121 order.removeAll { $0 == id }122 runIDs.remove(id)123 selection.remove(id)124 case .queueChanged(let status):125 self.status = status126 case .idle:127 checkRunEnd()128 }129 app.queueDidChange()130 }131132 /// Adds a job to the current run, starting a new run when none is in progress.133 private func joinRun(_ id: UUID) {134 if runIDs.isEmpty || !isRunning {135 runIDs = []136 runStartedAt = Date()137 lastSummary = nil138 }139 runIDs.insert(id)140 }141142 private func checkRunEnd() {143 guard !runIDs.isEmpty, !isRunning else { return }144 let run = runIDs.compactMap { items[$0]?.job }145 // Jobs waiting for a decision keep the run open in the list, but the summary is only made once.146 var summary = RunSummary(total: run.count)147 for job in run {148 switch job.state {149 case .finished: summary.finished += 1150 case .failed: summary.failed += 1151 case .skipped: summary.skipped += 1152 case .cancelled: summary.cancelled += 1153 default: break154 }155 if job.state == .finished {156 summary.bytesBefore += job.bytesBefore ?? 0157 summary.bytesAfter += job.bytesAfter ?? 0158 summary.outputs += job.outputs.filter { $0.outcome != .skipped }.map(\.url)159 }160 }161 if let start = run.compactMap(\.startedAt).min(), let end = run.compactMap(\.finishedAt).max() { summary.elapsed = end.timeIntervalSince(start) }162 guard run.contains(where: { $0.state.isTerminal }) else { return }163 let pendingDecisions = run.contains { $0.state == .awaitingDecision }164 if lastSummary != summary {165 lastSummary = summary166 if !pendingDecisions || summary.finished + summary.failed > 0 { app.runDidFinish(summary, awaitingDecisions: awaitingDecision.count) }167 }168 if !pendingDecisions { runIDs = [] }169 }170171 func resync() async {172 apply(await queue.snapshot())173 }174175 // MARK: Actions176177 func enqueue(_ requests: [ConversionJobRequest]) async -> [UUID] {178 let ids = await queue.enqueue(batch: requests)179 // Mirror the whole batch at once: a 500-file batch appears immediately instead of one row per event.180 let snapshot = await queue.snapshot()181 if let first = ids.first, !runIDs.contains(first) { joinRun(first) }182 runIDs.formUnion(ids)183 apply(snapshot)184 return ids185 }186187 func togglePause() {188 Task { if await queue.isPaused { await queue.resume() } else { await queue.pause() } }189 }190191 func cancel(_ ids: [UUID]) { Task { for id in ids { await queue.cancel(id) } } }192 func cancelAll() { Task { await queue.cancelAll() } }193 func retry(_ ids: [UUID]) { Task { for id in ids { await queue.retry(id) } } }194 func pauseJobs(_ ids: [UUID]) { Task { for id in ids { await queue.pauseJob(id) } } }195 func resumeJobs(_ ids: [UUID]) { Task { for id in ids { await queue.resumeJob(id) } } }196 func setPriority(_ priority: JobPriority, for ids: [UUID]) { Task { for id in ids { await queue.setPriority(priority, for: id) } } }197198 func remove(_ ids: [UUID]) {199 Task {200 for id in ids {201 if await queue.remove(id) == false { await queue.cancel(id) }202 }203 }204 }205206 func clearSettled() { Task { await queue.clearSettled() } }207208 func resolve(_ id: UUID, policy: ConflictPolicy, allowReplacingSource: Bool = false) {209 Task { await queue.resolveConflict(id, policy: policy, allowReplacingSource: allowReplacingSource) }210 }211212 func resolveAll(policy: ConflictPolicy) {213 let ids = awaitingDecision.map(\.id)214 Task { for id in ids { await queue.resolveConflict(id, policy: policy) } }215 }216217 /// Drag-reorder in the list: the display order is the start order within a priority.218 func move(from offsets: IndexSet, to destination: Int) {219 var next = order220 next.move(fromOffsets: offsets, toOffset: destination)221 let moved = offsets.map { order[$0] }222 order = next223 Task {224 for id in moved { if let index = next.firstIndex(of: id) { await queue.move(id, to: index) } }225 await resync()226 }227 }228229 func moveToTop(_ ids: [UUID]) {230 Task {231 for (offset, id) in ids.enumerated() { await queue.move(id, to: offset) }232 await resync()233 }234 }235}236237// MARK: - Presentation helpers238239extension JobState {240 var title: String {241 switch self {242 case .queued: L("Waiting")243 case .preparing: L("Preparing")244 case .running: L("Converting")245 case .validating: L("Verifying")246 case .awaitingDecision: L("Needs a decision")247 case .paused: L("Paused")248 case .finished: L("Done")249 case .failed: L("Failed")250 case .cancelled: L("Cancelled")251 case .skipped: L("Skipped")252 }253 }254255 var symbol: String {256 switch self {257 case .queued: "clock"258 case .preparing: "magnifyingglass"259 case .running: "arrow.triangle.2.circlepath"260 case .validating: "checkmark.shield"261 case .awaitingDecision: "questionmark.diamond.fill"262 case .paused: "pause.circle"263 case .finished: "checkmark.circle.fill"264 case .failed: "xmark.octagon.fill"265 case .cancelled: "slash.circle"266 case .skipped: "arrow.uturn.right.circle"267 }268 }269270 var color: Color {271 switch self {272 case .queued, .paused, .cancelled, .skipped: ORIX.Palette.textSecondary273 case .preparing, .running, .validating: ORIX.Palette.accent274 case .awaitingDecision: ORIX.Palette.caution275 case .finished: ORIX.Palette.success276 case .failed: ORIX.Palette.danger277 }278 }279}280281extension JobPriority {282 var title: String {283 switch self {284 case .low: L("Low")285 case .normal: L("Normal")286 case .high: L("High")287 }288 }289}290291extension ConversionJob {292 var displayName: String {293 guard let first = request.sources.first else { return "—" }294 if request.sources.count > 1 { return L("%@ and %lld more", first.lastPathComponent, request.sources.count - 1) }295 return first.lastPathComponent296 }297298 var writtenOutputs: [URL] { outputs.filter { $0.outcome != .skipped }.map(\.url) }299300 /// Operation title or destination name.301 var targetTitle: String {302 if let title = plan?.steps.last?.title { return LE(title) }303 return request.destinationFormat.displayName304 }305306 /// Source bytes handled per second, from the measured fraction; `nil` when it cannot be derived.307 func throughput(now: Date = Date()) -> Double? {308 guard state == .running, let fraction = progress.fraction, fraction > 0.01, let bytes = bytesBefore, bytes > 0, let startedAt else { return nil }309 let elapsed = now.timeIntervalSince(startedAt)310 return elapsed > 0.5 ? Double(bytes) * fraction / elapsed : nil311 }312313 /// Everything about the job as plain text, for "Copy details".314 var detailsText: String {315 var lines = ["ORIX Convert — \(displayName)", "State: \(state.rawValue)"]316 lines.append("Sources: " + request.sources.map(\.path).joined(separator: ", "))317 lines.append("Conversion: \(sourceFormat?.rawValue ?? "?") → \(request.destinationFormat.rawValue)\(request.operation.map { " (\($0))" } ?? "")")318 if let plan { lines.append("Engines: " + plan.engines.joined(separator: " + ")) }319 if let error { lines.append("Error: \(error)") }320 for warning in warnings { lines.append("Warning [\(warning.severity.rawValue)/\(warning.code)]: \(warning.message)") }321 for check in checks { lines.append("Check \(check.passed ? "PASS" : "FAIL") \(check.name): \(check.detail)") }322 for (key, value) in facts.sorted(by: { $0.key < $1.key }) { lines.append("Fact \(key): \(value)") }323 for output in outputs { lines.append("Output (\(output.outcome.rawValue)): \(output.url.path)") }324 let options = request.options.redactingSecrets().values.sorted { $0.key < $1.key }.map { "\($0.key)=\($0.value.plainText)" }325 if !options.isEmpty { lines.append("Options: " + options.joined(separator: ", ")) }326 lines.append("--- Log ---")327 let formatter = ISO8601DateFormatter()328 for line in log { lines.append("\(formatter.string(from: line.date)) [\(line.level.rawValue)] \(line.message)") }329 return lines.joined(separator: "\n")330 }331}332333extension OptionValue {334 var plainText: String {335 switch self {336 case .bool(let v): v ? "true" : "false"337 case .int(let v): String(v)338 case .double(let v): String(v)339 case .string(let v): v340 }341 }342}343