SPB Git

Repository Public

JobsView.swift 19.4 KB 348 lines swift

1import MCCCore2import SwiftUI34/// Jobs, recurring schedules and the templates declared by the agents.5struct JobsView: View {6    enum Tab: String, CaseIterable, Identifiable {7        case jobs, schedules, templates8        var id: String { rawValue }9        var title: String { Localization.shared.string("jobs.tab." + rawValue) }10    }1112    @Environment(AppModel.self) private var app13    @SceneStorage("mcc.jobs.tab") private var storedTab = Tab.jobs.rawValue14    @State private var tab: Tab = .jobs1516    var body: some View {17        Page(title: tr("nav.jobs"), subtitle: tr("jobs.subtitle"), scrolls: false) {18            SectionTabs(selection: $tab) { $0.title }.accessibilityLabel(tr("jobs.tabs.label")).accessibilityIdentifier("jobs-tabs")19        } content: {20            switch tab {21            case .jobs: JobsListView()22            case .schedules: SchedulesView()23            case .templates: TemplatesView()24            }25        }26        .onAppear { if app.focus == nil, let t = Tab(rawValue: storedTab) { tab = t } }27        .onChange(of: tab) { _, new in storedTab = new.rawValue }28        .onChange(of: app.focus, initial: true) { _, focus in if case .job = focus { tab = .jobs } }29        .task {30            await app.session.jobs.templates.loadIfNeeded(maxAge: 120)31            await app.session.nodes.list.loadIfNeeded(maxAge: 60)32        }33    }34}3536struct JobsListView: View {37    @Environment(AppModel.self) private var app38    @Environment(\.mccTheme) private var theme39    @State private var filter = JobFilter()40    @State private var sortOrder: [KeyPathComparator<JobRow>] = [KeyPathComparator(\.created, order: .reverse)]41    @State private var selection: String?42    @State private var inspector = true43    @State private var creating = false44    @State private var focused: API.Job?4546    private var resource: Resource<[API.Job]> { app.session.jobs.jobs }4748    var body: some View {49        ResourceView(resource) { jobs in50            let rows = filter.apply(jobs).map(JobRow.init).sorted(using: sortOrder)51            VStack(alignment: .leading, spacing: Tokens.Space.s3) {52                filterBar(jobs: jobs, count: rows.count)53                if rows.isEmpty {54                    EmptyStateView(jobs.isEmpty ? tr("jobs.empty.title") : tr("jobs.empty.filtered"),55                                   message: jobs.isEmpty ? tr("jobs.empty.message") : nil, systemImage: "list.bullet.rectangle")56                } else {57                    table(rows)58                }59            }60            .padding(.horizontal, Tokens.Space.s7)61            .padding(.bottom, Tokens.Space.s5)62        }63        .sidePane(isPresented: $inspector) {64            Group {65                if let id = selection, let job = resource.value?.first(where: { $0.id == id }) ?? (focused?.id == id ? focused : nil) {66                    JobDetailPane(job: job)67                } else {68                    EmptyStateView(tr("jobs.detail.none"), systemImage: "list.bullet.rectangle")69                }70            }71            .frame(width: 400)72        }73        .task { await resource.loadIfNeeded() }74        .onChange(of: app.focus, initial: true) { _, focus in75            guard case .job(let id) = focus else { return }76            filter = JobFilter()77            selection = id78            inspector = true79            app.focus = nil80            // The list is bounded: a job outside it is fetched on its own.81            if resource.value?.contains(where: { $0.id == id }) != true {82                Task { focused = try? await app.session.job(id: id) }83            }84        }85        .sheet(isPresented: $creating) { JobCreateSheet() }86    }8788    private func filterBar(jobs: [API.Job], count: Int) -> some View {89        HStack(spacing: Tokens.Space.s3) {90            Toggle(tr("jobs.filter.active"), isOn: $filter.activeOnly).toggleStyle(.checkbox)91            Picker(tr("jobs.col.state"), selection: $filter.state) {92                Text(tr("jobs.filter.any_state")).tag(API.JobState?.none)93                ForEach(API.JobState.allCases, id: \.self) { Text($0.label).tag(API.JobState?.some($0)) }94            }.fixedSize()95            Picker(tr("jobs.col.template"), selection: $filter.template) {96                Text(tr("jobs.filter.any_template")).tag(String?.none)97                ForEach(Array(Set(jobs.map(\.template))).sorted(), id: \.self) { Text($0).tag(String?.some($0)) }98            }.fixedSize()99            NodeFilterPicker(title: tr("jobs.col.node"), selection: $filter.nodeID)100            TextField(tr("jobs.filter.search"), text: $filter.text).textFieldStyle(.roundedBorder).frame(maxWidth: 200)101                .accessibilityLabel(tr("jobs.filter.search"))102            Spacer(minLength: 0)103            Text(tr("jobs.count", count, jobs.count)).font(.callout).foregroundStyle(theme.textSecondary).monospacedDigit()104            Button { creating = true } label: { Label(tr("jobs.create"), systemImage: "plus") }105                .mutation(app, permission: "jobs.submit")106                .accessibilityIdentifier("job-create")107        }108        .labelsHidden()109    }110111    private func table(_ rows: [JobRow]) -> some View {112        Table(rows, selection: $selection, sortOrder: $sortOrder) {113            TableColumn(tr("jobs.col.template"), value: \.template).width(min: 120, ideal: 180)114            TableColumn(tr("jobs.col.state"), value: \.stateRank) { r in StatusLabel(r.job.state.label, tone: r.job.state.tone) }.width(min: 90, ideal: 110)115            TableColumn(tr("jobs.col.node"), value: \.node) { r in OptionalValueText(r.job.nodeAlias) }.width(min: 70, ideal: 90)116            TableColumn(tr("jobs.col.owner"), value: \.owner) { r in OptionalValueText(r.job.ownerDisplayName) }.width(min: 80, ideal: 120)117            TableColumn(tr("jobs.col.progress"), value: \.progress) { r in118                if let p = r.job.progress {119                    ProgressView(value: min(1, max(0, p))).frame(maxWidth: 90)120                        .accessibilityLabel(tr("jobs.col.progress")).accessibilityValue(Format.percent(ratio: p))121                        .help(Format.percent(ratio: p))122                } else {123                    Text("—").foregroundStyle(theme.textTertiary).accessibilityLabel(tr("jobs.progress.unknown"))124                }125            }.width(min: 70, ideal: 100)126            TableColumn(tr("jobs.col.attempt"), value: \.attempt) { r in Text(verbatim: "\(r.job.attempt)/\(r.job.maxAttempts)").monospacedDigit() }127                .width(min: 50, ideal: 60)128            TableColumn(tr("jobs.col.created"), value: \.created) { r in Text(Format.dateTime(r.job.createdAt)) }.width(min: 110, ideal: 140)129            TableColumn(tr("jobs.col.started"), value: \.started) { r in OptionalValueText(r.job.startedAt.map { Format.dateTime($0) }) }.width(min: 110, ideal: 140)130            TableColumn(tr("jobs.col.finished"), value: \.finished) { r in OptionalValueText(r.job.finishedAt.map { Format.dateTime($0) }) }.width(min: 110, ideal: 140)131        }132        .accessibilityIdentifier("jobs-table")133    }134}135136struct JobDetailPane: View {137    @Environment(AppModel.self) private var app138    @Environment(\.mccTheme) private var theme139    let job: API.Job140    @State private var confirmCancel = false141142    var body: some View {143        InspectorPane {144            VStack(alignment: .leading, spacing: Tokens.Space.s2) {145                Text(job.template).font(.headline).foregroundStyle(theme.textPrimary)146                StatusBadge(job.state.label, tone: job.state.tone)147                if let p = job.progress {148                    ProgressView(value: min(1, max(0, p))).accessibilityLabel(tr("jobs.col.progress")).accessibilityValue(Format.percent(ratio: p))149                }150            }151            DetailSection(title: tr("jobs.detail.facts")) {152                HStack { KeyValueRow(tr("jobs.detail.id"), job.id, monospaced: true); CopyButton(value: job.id) }153                if let alias = job.nodeAlias {154                    HStack {155                        KeyValueRow(tr("jobs.col.node"), alias)156                        if let id = job.nodeId { LinkButton(title: tr("action.open")) { app.openNode(id) } }157                    }158                } else {159                    KeyValueRow(tr("jobs.col.node"), tr("jobs.node.unassigned"))160                }161                KeyValueRow(tr("jobs.placement.title"), PlacementDraft.describe(job.placement) { app.session.nodes.alias($0) })162                KeyValueRow(tr("jobs.col.owner"), job.ownerDisplayName ?? tr("metric.not_reported"))163                KeyValueRow(tr("jobs.col.attempt"), "\(job.attempt) / \(job.maxAttempts)")164                KeyValueRow(tr("jobs.col.created"), Format.dateTime(job.createdAt))165                KeyValueRow(tr("jobs.col.started"), job.startedAt.map { Format.dateTime($0) } ?? tr("jobs.not_started"))166                KeyValueRow(tr("jobs.col.finished"), job.finishedAt.map { Format.dateTime($0) } ?? tr("jobs.not_finished"))167                if let s = job.startedAt, let f = job.finishedAt { KeyValueRow(tr("jobs.detail.duration"), Format.duration(seconds: f.timeIntervalSince(s))) }168                if let n = job.nextAttemptAt { KeyValueRow(tr("jobs.detail.next_attempt"), Format.dateTime(n)) }169                if job.scheduleId != nil { KeyValueRow(tr("jobs.detail.schedule"), app.session.jobs.schedules.value?.first { $0.id == job.scheduleId }?.name ?? String(job.scheduleId!.prefix(8))) }170                if !job.dependsOn.isEmpty { KeyValueRow(tr("jobs.detail.depends_on"), job.dependsOn.map { String($0.prefix(8)) }.joined(separator: ", "), monospaced: true) }171                if let a = job.actionId {172                    HStack {173                        KeyValueRow(tr("jobs.detail.action"), String(a.prefix(8)), monospaced: true)174                        LinkButton(title: tr("action.open")) { app.openAction(a) }.accessibilityIdentifier("job-open-action")175                    }176                }177            }178            if let e = job.error, !e.isEmpty {179                DetailSection(title: tr("jobs.detail.error")) {180                    Text(e).font(.callout.monospaced()).foregroundStyle(theme.textPrimary).textSelection(.enabled)181                }182            }183            DetailSection(title: tr("jobs.detail.params")) { JSONBlock(value: JSONValue(job.params.additionalProperties)) }184            DetailSection(title: tr("jobs.detail.result")) {185                if let r = job.result { JSONBlock(value: JSONValue(r.additionalProperties)) }186                else { Text(tr("jobs.detail.no_result")).font(.callout).foregroundStyle(theme.textSecondary) }187            }188            DetailSection(title: tr("jobs.detail.usage")) {189                if let u = job.usage { JSONBlock(value: JSONValue(u.additionalProperties)) }190                else { Text(tr("metric.not_measured")).font(.callout).foregroundStyle(theme.textSecondary) }191            }192            if !job.state.isTerminal {193                Button(tr("jobs.cancel"), role: .destructive) { confirmCancel = true }194                    .mutation(app, permission: "jobs.submit")195                    .accessibilityIdentifier("job-cancel")196            }197        }198        .confirmationDialog(tr("jobs.cancel.title"), isPresented: $confirmCancel) {199            Button(tr("jobs.cancel"), role: .destructive) { Task { await app.perform { _ = try await app.session.jobs.cancel(id: job.id) } } }200        } message: { Text(job.template) }201        .accessibilityIdentifier("job-detail")202    }203}204205/// Placement editor shared by the job and schedule forms.206struct PlacementEditor: View {207    @Binding var draft: PlacementDraft208    var allowedNodeIDs: [String]?209    @Environment(AppModel.self) private var app210    var body: some View {211        VStack(alignment: .leading, spacing: Tokens.Space.s2) {212            Picker(tr("jobs.col.node"), selection: $draft.nodeID) {213                Text(tr("jobs.placement.any")).tag(String?.none)214                ForEach((app.session.nodes.list.value ?? []).filter { allowedNodeIDs == nil || allowedNodeIDs!.contains($0.id) }215                    .sorted { $0.alias.localizedCaseInsensitiveCompare($1.alias) == .orderedAscending }, id: \.id) { n in216                    Text(n.alias).tag(String?.some(n.id))217                }218            }.labelsHidden().fixedSize().accessibilityLabel(tr("jobs.col.node"))219            HStack {220                TextField(tr("jobs.placement.site"), text: $draft.site).textFieldStyle(.roundedBorder).accessibilityLabel(tr("jobs.placement.site"))221                TextField(tr("jobs.placement.role"), text: $draft.role).textFieldStyle(.roundedBorder).accessibilityLabel(tr("jobs.placement.role"))222                TextField(tr("jobs.placement.tags"), text: $draft.tagsText).textFieldStyle(.roundedBorder).accessibilityLabel(tr("jobs.placement.tags"))223            }224        }225    }226}227228/// Template chooser: available templates are selectable, the others are listed disabled.229struct TemplatePicker: View {230    @Environment(AppModel.self) private var app231    @Binding var selection: String?232    var body: some View {233        let templates = app.session.jobs.templates.value ?? []234        Picker(tr("jobs.col.template"), selection: $selection) {235            Text(tr("jobs.template.choose")).tag(String?.none)236            ForEach(templates.sorted { $0.title < $1.title }, id: \.name) { t in237                Text(t.available ? t.title : tr("jobs.template.unavailable", t.title)).tag(String?.some(t.name)).disabled(!t.available)238            }239        }240        .labelsHidden().fixedSize()241        .accessibilityIdentifier("template-picker")242    }243}244245struct JobCreateSheet: View {246    @Environment(AppModel.self) private var app247    @Environment(\.mccTheme) private var theme248    @State private var draft = JobDraft()249    @State private var tracker = IdempotencyTracker()250    @State private var error: APIError?251    var preset: String?252253    private var template: API.JobTemplate? { app.session.jobs.templates.value?.first { $0.name == draft.template } }254255    var body: some View {256        FormSheet(title: tr("jobs.create"), confirmTitle: tr("jobs.create.confirm"), canConfirm: draft.isComplete && template?.available == true, width: 600) {257            do {258                let request = try draft.request()259                // Same content re-sent (timeout, step-up) = same key: the server returns the original job.260                let key = tracker.key(forBody: try draft.canonicalBody())261                _ = try await app.session.jobs.submit(request, idempotencyKey: key)262                tracker.complete()263                return true264            } catch {265                let e = APIError.from(error)266                if !e.isPasskeyCancelled { self.error = e }267                return false268            }269        } content: {270            if app.session.jobs.templates.value == nil {271                ResourceView(app.session.jobs.templates) { _ in EmptyView() }.frame(minHeight: 120)272            } else {273                FieldRow(label: tr("jobs.col.template"), help: template?.description) { TemplatePicker(selection: $draft.template) }274                if let t = template {275                    Text(tr("jobs.template.limits", Format.duration(seconds: Double(t.timeoutS)), t.maxAttempts)).font(.caption).foregroundStyle(theme.textTertiary)276                    FieldRow(label: tr("jobs.detail.params")) {277                        SchemaFormView(fields: draft.params.fields, values: $draft.params.values, rawJSON: $draft.params.rawJSON,278                                       missing: draft.params.missing, invalid: draft.params.invalid)279                    }280                    FieldRow(label: tr("jobs.placement.title"), help: tr("jobs.placement.help")) {281                        PlacementEditor(draft: $draft.placement, allowedNodeIDs: t.nodeIds)282                    }283                    FieldRow(label: tr("jobs.max_attempts"), help: tr("jobs.max_attempts.help", t.maxAttempts)) {284                        TextField(tr("jobs.max_attempts"), text: $draft.maxAttempts).textFieldStyle(.roundedBorder).frame(width: 80)285                    }286                }287                if let error { InlineErrorView(error) }288            }289        }290        .onAppear { if draft.template == nil, let preset { draft.template = preset } }291        .onChange(of: draft.template, initial: true) { _, _ in292            draft.params = template.map { ParamsDraft(schema: JSONValue($0.paramsSchema.additionalProperties)) } ?? ParamsDraft()293        }294        .onChange(of: draft) { _, _ in error = nil }295        .task { await app.session.jobs.templates.loadIfNeeded(maxAge: 120) }296    }297}298299struct TemplatesView: View {300    @Environment(AppModel.self) private var app301    @Environment(\.mccTheme) private var theme302    @State private var creating: String?303304    var body: some View {305        ResourceView(app.session.jobs.templates) { templates in306            if templates.isEmpty {307                EmptyStateView(tr("jobs.templates.empty.title"), message: tr("jobs.templates.empty.message"), systemImage: "doc.badge.gearshape")308            } else {309                ScrollView {310                    LazyVStack(alignment: .leading, spacing: Tokens.Space.s4) {311                        ForEach(templates.sorted { $0.title < $1.title }, id: \.name) { t in312                            Card {313                                VStack(alignment: .leading, spacing: Tokens.Space.s2) {314                                    HStack {315                                        Text(t.title).font(.headline).foregroundStyle(theme.textPrimary)316                                        Text(t.name).font(.callout.monospaced()).foregroundStyle(theme.textSecondary)317                                        StatusBadge(t.available ? tr("jobs.template.available") : tr("jobs.template.not_available"), tone: t.available ? .ok : .offline, compact: true)318                                        Spacer()319                                        Button(tr("jobs.create")) { creating = t.name }320                                            .disabled(!t.available)321                                            .mutation(app, permission: "jobs.submit")322                                    }323                                    Text(t.description).font(.callout).foregroundStyle(theme.textSecondary)324                                    Text(tr("jobs.template.limits", Format.duration(seconds: Double(t.timeoutS)), t.maxAttempts)).font(.caption).foregroundStyle(theme.textTertiary)325                                    if let ids = t.nodeIds {326                                        Text(tr("jobs.template.nodes", ids.map { app.session.nodes.alias($0) ?? String($0.prefix(8)) }.sorted().joined(separator: ", ")))327                                            .font(.caption).foregroundStyle(theme.textTertiary)328                                    }329                                    let fields = SchemaField.fields(from: JSONValue(t.paramsSchema.additionalProperties))330                                    if !fields.isEmpty {331                                        Text(tr("jobs.template.params", fields.map { $0.required ? "\($0.name)*" : $0.name }.joined(separator: ", ")))332                                            .font(.caption.monospaced()).foregroundStyle(theme.textTertiary)333                                    }334                                }335                            }336                            .accessibilityElement(children: .contain)337                        }338                    }339                    .padding(.horizontal, Tokens.Space.s7)340                    .padding(.bottom, Tokens.Space.s5)341                }342            }343        }344        .task { await app.session.jobs.templates.loadIfNeeded(maxAge: 120) }345        .sheet(isPresented: Binding(get: { creating != nil }, set: { if !$0 { creating = nil } })) { JobCreateSheet(preset: creating) }346    }347}348
Files main
Menu

Theme