Repository Public
1import MCCCore2import SwiftUI34enum JobsLogic {5 /// Active first (running, queued), then the most recent.6 static func sorted(_ jobs: [API.Job]) -> [API.Job] {7 func rank(_ s: API.JobState) -> Int { s == .running ? 0 : s == .queued ? 1 : 2 }8 return jobs.sorted { rank($0.state) == rank($1.state) ? $0.createdAt > $1.createdAt : rank($0.state) < rank($1.state) }9 }1011 /// Progress as a ratio in 0…1, or nil when the job reports none (never drawn as 0 %).12 static func progressRatio(_ p: Double?) -> Double? {13 guard let p, p.isFinite else { return nil }14 return min(1, max(0, p > 1 ? p / 100 : p))15 }1617 static func duration(_ j: API.Job, now: Date = Date()) -> TimeInterval? {18 guard let s = j.startedAt else { return nil }19 return max(0, (j.finishedAt ?? (j.state.isTerminal ? s : now)).timeIntervalSince(s))20 }2122 static func placementText(_ p: API.JobPlacement, alias: (String) -> String?) -> String? {23 let parts = [p.nodeId.map { alias($0) ?? $0 }, p.site, p.role, p.tags.flatMap { $0.isEmpty ? nil : $0.joined(separator: ", ") }].compactMap { $0 }24 return parts.isEmpty ? nil : parts.joined(separator: " · ")25 }2627 static func everyText(_ seconds: Int) -> String { Format.duration(seconds: Double(seconds)) }28}2930struct JobsScreen: View {31 @Environment(\.mccTheme) private var theme32 @Session private var session3334 var body: some View {35 ScreenStack {36 Text(tr("jobs.list")).font(.headline).foregroundStyle(theme.textPrimary).accessibilityAddTraits(.isHeader)37 ResourceSection(resource: session.jobs.jobs) { jobs in38 VStack(alignment: .leading, spacing: Tokens.Space.s3) {39 if jobs.isEmpty { EmptyStateView(tr("jobs.empty"), systemImage: "list.bullet.rectangle") }40 ForEach(JobsLogic.sorted(jobs), id: \.id) { j in41 RouteRow(route: .job(j.id), identifier: "job-row") { JobRowContent(job: j) }42 }43 }44 }45 SectionCard(tr("jobs.templates")) {46 InlineResource(resource: session.jobs.templates) { templates in47 if templates.isEmpty { Text(tr("jobs.templates.none")).font(.callout).foregroundStyle(theme.textSecondary) }48 ForEach(templates, id: \.name) { t in49 VStack(alignment: .leading, spacing: Tokens.Space.s1) {50 AdaptiveLine(spacing: Tokens.Space.s3) {51 Text(t.title).font(.callout.weight(.medium)).foregroundStyle(theme.textPrimary)52 StatusLabel(tr(t.available ? "jobs.template.available" : "jobs.template.unavailable"), tone: t.available ? .ok : .neutral).font(.footnote)53 }54 Text(t.name).font(.footnote.monospaced()).foregroundStyle(theme.textSecondary)55 if !t.description.isEmpty { Text(t.description).font(.footnote).foregroundStyle(theme.textSecondary) }56 Text(tr("jobs.template.limits", Format.duration(seconds: Double(t.timeoutS)), t.maxAttempts)).font(.footnote).foregroundStyle(theme.textTertiary)57 }58 .frame(maxWidth: .infinity, alignment: .leading)59 .accessibilityElement(children: .combine)60 .accessibilityIdentifier("job-template-" + t.name)61 }62 }63 }64 SectionCard(tr("jobs.schedules")) {65 InlineResource(resource: session.jobs.schedules) { schedules in66 if schedules.isEmpty { Text(tr("jobs.schedules.none")).font(.callout).foregroundStyle(theme.textSecondary) }67 ForEach(schedules, id: \.id) { s in68 VStack(alignment: .leading, spacing: Tokens.Space.s1) {69 AdaptiveLine(spacing: Tokens.Space.s3) {70 Text(s.name).font(.callout.weight(.medium)).foregroundStyle(theme.textPrimary)71 StatusLabel(tr(s.enabled ? "jobs.schedule.enabled" : "jobs.schedule.disabled"), tone: s.enabled ? .ok : .neutral).font(.footnote)72 }73 Text(tr("jobs.schedule.every", s.template, JobsLogic.everyText(s.everySeconds))).font(.footnote).foregroundStyle(theme.textSecondary)74 Text(tr("jobs.schedule.next", Format.dateTime(s.nextRunAt)) + (s.lastRunAt.map { " · " + tr("jobs.schedule.last", Format.dateTime($0)) } ?? ""))75 .font(.footnote).foregroundStyle(theme.textTertiary)76 }77 .frame(maxWidth: .infinity, alignment: .leading)78 .accessibilityElement(children: .combine)79 .accessibilityIdentifier("job-schedule-row")80 }81 }82 }83 }84 .screen("jobs", title: tr("section.jobs"), load: { await load(force: false) }, reload: { await load(force: true) })85 }8687 private func load(force: Bool) async {88 async let a: Void = force ? session.jobs.jobs.load() : session.jobs.jobs.loadIfNeeded()89 async let b: Void = force ? session.jobs.templates.load() : session.jobs.templates.loadIfNeeded(maxAge: 300)90 async let c: Void = force ? session.jobs.schedules.load() : session.jobs.schedules.loadIfNeeded(maxAge: 60)91 _ = await (a, b, c)92 }93}9495struct JobRowContent: View {96 @Environment(\.mccTheme) private var theme97 let job: API.Job98 var body: some View {99 VStack(alignment: .leading, spacing: Tokens.Space.s2) {100 AdaptiveLine(spacing: Tokens.Space.s3) {101 Text(job.template).font(.headline).foregroundStyle(theme.textPrimary)102 StatusBadge(job.state.label, tone: job.state.tone, compact: true)103 }104 Text([job.nodeAlias, job.ownerDisplayName, Format.relative(job.createdAt)].compactMap { $0 }.joined(separator: " · "))105 .font(.footnote).foregroundStyle(theme.textSecondary)106 if job.state == .running { JobProgress(progress: job.progress) }107 }108 }109}110111/// Progress bar with its figure, or the explicit "not reported".112struct JobProgress: View {113 @Environment(\.mccTheme) private var theme114 let progress: Double?115 var body: some View {116 if let r = JobsLogic.progressRatio(progress) {117 ProgressView(value: r) { Text(tr("jobs.progress")).font(.footnote).foregroundStyle(theme.textSecondary) }118 currentValueLabel: { Text(Format.percent(ratio: r)).font(.footnote.monospacedDigit()) }119 .accessibilityValue(Format.percent(ratio: r))120 } else {121 HeadlineChip(label: tr("jobs.progress"), value: nil)122 }123 }124}125126struct JobDetailScreen: View {127 @Environment(Navigator.self) private var nav128 @Environment(\.mccTheme) private var theme129 @Session private var session130 let jobID: String131 @State private var fetched: API.Job?132 @State private var fetchedAt: Date?133 @State private var fetchError: APIError?134 @State private var runner = MutationRunner()135 @State private var confirmCancel = false136137 /// The live list wins (it is patched by events); the direct fetch covers jobs outside the bounded list.138 private var job: API.Job? { session.jobs.jobs.value?.first { $0.id == jobID } ?? fetched }139140 var body: some View {141 ScreenStack {142 if let j = job {143 content(j)144 } else if let e = fetchError {145 ErrorStateView(error: e) { Task { await fetch() } }146 } else {147 ProgressView(tr("state.loading")).frame(maxWidth: .infinity, minHeight: 160)148 }149 }150 .screen("job-detail", title: job?.template ?? tr("jobs.job"), load: { if job == nil { await fetch() } }, reload: fetch)151 .navigationBarTitleDisplayMode(.inline)152 .mutationError(runner)153 .confirmationDialog(tr("jobs.cancel.confirm"), isPresented: $confirmCancel, titleVisibility: .visible) {154 Button(tr("jobs.cancel"), role: .destructive) {155 Task { if let j = await runner.run({ try await session.jobs.cancel(id: jobID) }) { fetched = j; fetchedAt = Date() } }156 }157 Button(tr("common.cancel"), role: .cancel) {}158 }159 }160161 private func fetch() async {162 do {163 fetched = try await session.job(id: jobID)164 fetchedAt = Date()165 fetchError = nil166 } catch {167 let e = APIError.from(error)168 if !e.isCancelled { fetchError = e }169 }170 }171172 @ViewBuilder private func content(_ j: API.Job) -> some View {173 Card {174 VStack(alignment: .leading, spacing: Tokens.Space.s3) {175 AdaptiveLine(spacing: Tokens.Space.s3) {176 Text(j.template).font(.title2.weight(.semibold)).foregroundStyle(theme.textPrimary).accessibilityAddTraits(.isHeader)177 StatusBadge(j.state.label, tone: j.state.tone).accessibilityIdentifier("job-state")178 }179 if j.state == .running { JobProgress(progress: j.progress) }180 if let e = j.error, !e.isEmpty { InfoBanner(tone: .critical, title: tr("jobs.error"), message: e) }181 if !j.state.isTerminal {182 MutationButton(title: tr("jobs.cancel"), systemImage: "xmark.circle", role: .destructive, permission: "jobs.submit", identifier: "job-cancel") {183 confirmCancel = true184 }185 .disabled(runner.isRunning)186 }187 if let a = j.actionId {188 Button { nav.go(to: .action(a)) } label: { Label(tr("jobs.see_action"), systemImage: "bolt") }189 .frame(minHeight: Tokens.Size.touchMin)190 .accessibilityIdentifier("job-action")191 }192 }193 }194 SectionCard(tr("jobs.details")) {195 InfoRow(tr("jobs.node"), j.nodeAlias ?? j.nodeId)196 InfoRow(tr("jobs.placement"), JobsLogic.placementText(j.placement, alias: { session.nodes.alias($0) }) ?? tr("jobs.placement.any"))197 InfoRow(tr("jobs.owner"), j.ownerDisplayName)198 InfoRow(tr("jobs.attempt"), tr("jobs.attempt.value", j.attempt, j.maxAttempts))199 InfoRow(tr("jobs.created"), Format.dateTime(j.createdAt))200 InfoRow(tr("jobs.started"), j.startedAt.map { Format.dateTime($0) })201 InfoRow(tr("jobs.finished"), j.finishedAt.map { Format.dateTime($0) })202 InfoRow(tr("jobs.duration"), JobsLogic.duration(j).map { Format.duration(seconds: $0) })203 if let n = j.nextAttemptAt { InfoRow(tr("jobs.next_attempt"), Format.dateTime(n)) }204 if !j.dependsOn.isEmpty { InfoRow(tr("jobs.depends_on"), j.dependsOn.joined(separator: ", "), monospaced: true) }205 InfoRow(tr("jobs.id"), j.id, monospaced: true)206 }207 json(tr("jobs.params"), JSONValue(j.params.additionalProperties))208 if let r = j.result { json(tr("jobs.result"), JSONValue(r.additionalProperties)) }209 if let u = j.usage { json(tr("jobs.usage"), JSONValue(u.additionalProperties)) }210 let live = session.jobs.jobs.value?.contains { $0.id == jobID } == true211 DataStamp(receivedAt: live ? session.jobs.jobs.receivedAt : fetchedAt, stale: live && session.jobs.jobs.isShowingStaleData)212 }213214 private func json(_ title: String, _ value: JSONValue) -> some View {215 SectionCard(title) {216 Text(value.prettyPrinted()).font(.footnote.monospaced()).foregroundStyle(theme.textPrimary).textSelection(.enabled)217 .frame(maxWidth: .infinity, alignment: .leading)218 }219 }220}221