Repository Public
1// ORIX Docs2// File: App/Sources/Automation/AutomationModel.swift3// Description: State of the workflow sheet: the workflow list (built-in and saved), the chosen inputs and output folder, the4// running batch with its per-file progress, the results and the execution history.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import AppKit9import Observation10import UniformTypeIdentifiers11import DocModel12import DocContainer13import DocAutomation1415extension WorkflowStep {16 /// The step in plain language, localised.17 var localizedSummary: String {18 switch self {19 case .importDocument(let path):20 if let path { return String(localized: "Open “\((path as NSString).lastPathComponent)”") }21 return String(localized: "Open the document")22 case .applyTheme(let name): return String(localized: "Apply the “\(name)” theme")23 case .applyTemplateStyles: return summary24 case .setPageSetup: return summary == "Set the page setup" ? String(localized: "Set the page setup") : summary25 case .acceptAllChanges: return String(localized: "Accept all tracked changes")26 case .rejectAllChanges: return String(localized: "Reject all tracked changes")27 case .removeComments: return String(localized: "Remove all comments")28 case .tableOfContents(_, let level): return String(localized: "Insert or refresh the table of contents (levels 1–\(level))")29 case .insertBibliography: return String(localized: "Insert the bibliography when sources are cited")30 case .setCitationStyle: return summary31 case .recalculateTables: return String(localized: "Recalculate table formulas")32 case .setMetadata: return String(localized: "Set document properties")33 case .audit(let profile, let fail):34 return fail ? String(localized: "Audit the document (\(profile.rawValue) profile) and stop on errors") : String(localized: "Audit the document (\(profile.rawValue) profile)")35 case .export(let format, _, _): return String(localized: "Export as \(format.displayName)")36 case .writeAuditReport(let format, _): return String(localized: "Write the audit report (\(format.uppercased()))")37 }38 }3940 var symbol: String {41 switch self {42 case .importDocument: return "doc.badge.arrow.up"43 case .applyTheme, .applyTemplateStyles: return "paintpalette"44 case .setPageSetup: return "doc.richtext"45 case .acceptAllChanges, .rejectAllChanges: return "checkmark.rectangle.stack"46 case .removeComments: return "text.bubble"47 case .tableOfContents: return "list.bullet.indent"48 case .insertBibliography, .setCitationStyle: return "quote.opening"49 case .recalculateTables: return "function"50 case .setMetadata: return "info.circle"51 case .audit, .writeAuditReport: return "checklist"52 case .export: return "square.and.arrow.up"53 }54 }55}5657@Observable58final class AutomationModel {59 struct Item: Identifiable, Hashable {60 var workflow: Workflow61 var isBuiltin: Bool62 var id: String { (isBuiltin ? "builtin:" : "saved:") + workflow.id }63 }64 enum InputMode: Hashable { case currentDocument, files }65 struct FileProgress: Identifiable {66 enum State: Equatable { case waiting, running, succeeded, failed, cancelled }67 var id: String68 var name: String69 var state: State = .waiting70 var stepName = ""71 var fraction = 0.072 var run: WorkflowRun?73 }7475 @ObservationIgnored unowned let session: DocumentSession76 private(set) var items: [Item] = []77 /// Saved workflow files that were refused, with the reason.78 private(set) var rejected: [(name: String, problem: String)] = []79 var selectedID: String?80 var inputMode: InputMode = .currentDocument81 private(set) var files: [URL] = []82 var outputFolder: URL83 var replaceExisting = false84 private(set) var progress: [FileProgress] = []85 private(set) var isRunning = false86 private(set) var lastDuration: Double?87 private(set) var history: [WorkflowRun] = []88 @ObservationIgnored private var task: Task<Void, Never>?89 @ObservationIgnored private let historyStore = WorkflowHistoryStore.shared9091 init(session: DocumentSession) {92 self.session = session93 let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first ?? URL(fileURLWithPath: NSHomeDirectory())94 outputFolder = documents.appendingPathComponent("ORIX Docs Exports", isDirectory: true)95 reload()96 selectedID = items.first?.id97 }9899 var selected: Workflow? { items.first { $0.id == selectedID }?.workflow }100 var documentName: String {101 let name = session.document?.displayName ?? session.doc.meta.title102 let base = (name as NSString).deletingPathExtension103 return base.isEmpty ? String(localized: "Untitled") : base104 }105 var inputCount: Int { inputMode == .currentDocument ? 1 : files.count }106 var canRun: Bool { !isRunning && selected != nil && inputCount > 0 }107 var chosenFiles: [URL] { files }108109 func reload() {110 let entries = WorkflowLibrary().entries()111 items = BuiltinWorkflows.all.map { Item(workflow: $0, isBuiltin: true) } + entries.compactMap { e in e.workflow.map { Item(workflow: $0, isBuiltin: false) } }112 rejected = entries.compactMap { e in e.problem.map { (e.url.lastPathComponent, $0) } }113 history = historyStore.load()114 }115116 // MARK: Choosing files117118 func chooseFiles() {119 let panel = NSOpenPanel()120 panel.allowsMultipleSelection = true121 panel.canChooseDirectories = false122 panel.allowedContentTypes = DocumentConverter.importFormats.compactMap { UTType(filenameExtension: $0.fileExtension) }123 panel.prompt = String(localized: "Choose")124 panel.message = String(localized: "Choose the documents to process")125 guard panel.runModal() == .OK else { return }126 files = panel.urls127 if !files.isEmpty { inputMode = .files }128 }129130 func chooseOutputFolder() {131 let panel = NSOpenPanel()132 panel.canChooseDirectories = true133 panel.canChooseFiles = false134 panel.canCreateDirectories = true135 panel.prompt = String(localized: "Choose")136 panel.message = String(localized: "Choose the folder that receives the results")137 guard panel.runModal() == .OK, let url = panel.url else { return }138 outputFolder = url139 }140141 /// Imports a workflow file into the saved workflows. A file with an unknown step or an unsafe path is refused with the reason.142 func importWorkflow() -> String? {143 let panel = NSOpenPanel()144 panel.allowedContentTypes = [.json]145 panel.message = String(localized: "Choose a workflow file (JSON)")146 guard panel.runModal() == .OK, let url = panel.url else { return nil }147 do {148 let workflow = try Workflow.load(contentsOf: url)149 try WorkflowLibrary().save(workflow)150 reload()151 selectedID = items.first { !$0.isBuiltin && $0.workflow.name == workflow.name }?.id ?? selectedID152 return nil153 } catch {154 return String(localized: "“\(url.lastPathComponent)” was not added: \(String(describing: error))")155 }156 }157158 // MARK: Running159160 func run() {161 guard canRun, let workflow = selected else { return }162 let runner = WorkflowRunner(outputDirectory: outputFolder, existingFiles: replaceExisting ? .overwrite : .rename, history: historyStore)163 let started = Date()164 isRunning = true165 lastDuration = nil166 if inputMode == .currentDocument {167 let name = documentName168 let document = session.doc169 progress = [FileProgress(id: "document", name: name, state: .running)]170 task = Task { [weak self] in171 let result = await runner.run(workflow, input: .document(document, name: name)) { step in172 Task { @MainActor in self?.update(index: 0, step: step) }173 }174 self?.finish(index: 0, run: result.record)175 self?.completed(started)176 }177 } else {178 let inputs = files179 progress = inputs.map { FileProgress(id: $0.path, name: $0.lastPathComponent) }180 let jobs = min(4, max(1, ProcessInfo.processInfo.activeProcessorCount / 2))181 task = Task { [weak self] in182 let result = await runner.runBatch(workflow, inputs: inputs, maxConcurrent: jobs) { p in183 Task { @MainActor in184 if let run = p.finished { self?.finish(index: p.fileIndex, run: run) } else if let step = p.step { self?.update(index: p.fileIndex, step: step) }185 }186 }187 // Progress callbacks hop to the main actor one by one; the final records are authoritative.188 for (i, run) in result.runs.enumerated() { self?.finish(index: i, run: run) }189 self?.completed(started)190 }191 }192 }193194 private func update(index: Int, step: WorkflowProgress) {195 guard progress.indices.contains(index), progress[index].run == nil else { return }196 progress[index].state = .running197 progress[index].stepName = step.stepName198 progress[index].fraction = max(progress[index].fraction, step.fraction)199 }200201 private func finish(index: Int, run: WorkflowRun) {202 guard progress.indices.contains(index) else { return }203 progress[index].run = run204 progress[index].fraction = 1205 switch run.status {206 case .succeeded: progress[index].state = .succeeded207 case .failed: progress[index].state = .failed208 case .cancelled: progress[index].state = .cancelled209 }210 }211212 private func completed(_ started: Date) {213 isRunning = false214 task = nil215 lastDuration = Date().timeIntervalSince(started)216 history = historyStore.load()217 }218219 /// Stops after the step in progress; files not started yet are not processed.220 func cancel() { task?.cancel() }221222 var overallFraction: Double { progress.isEmpty ? 0 : progress.reduce(0) { $0 + $1.fraction } / Double(progress.count) }223 var outputs: [URL] { progress.flatMap { $0.run?.outputs ?? [] }.map { URL(fileURLWithPath: $0) } }224225 func showInFinder(_ urls: [URL]) {226 let existing = urls.filter { FileManager.default.fileExists(atPath: $0.path) }227 if existing.isEmpty { NSWorkspace.shared.open(outputFolder) } else { NSWorkspace.shared.activateFileViewerSelecting(existing) }228 }229230 func clearHistory() { historyStore.clear(); history = [] }231}232