Repository Public
1import Foundation2import SheetCore3import SheetUI4import SheetAutomation5import AutomationPDF67/// What the run sheet is asking.8public enum RunPrompt: Identifiable, Hashable, Sendable {9 /// Parameter values, with the problems found in the previous attempt.10 case parameters(problems: [String])11 /// Confirmation for a workflow that is not approved: everything it reads and writes.12 case trust(accesses: [WorkflowFileAccess])13 public var id: String { if case .parameters = self { "parameters" } else { "trust" } }14}1516extension AutomationModel {17 public var isRunning: Bool { phase == .running }1819 /// Parameter values to start from: the last ones entered, else the defaults.20 public func draftValues(for workflow: Workflow) -> [String: String] {21 var values = parameterValues[workflow.id] ?? [:]22 for p in workflow.parameters where values[p.name] == nil { values[p.name] = p.defaultValue ?? "" }23 return values24 }2526 /// Run button: asks for parameters, then for confirmation when the workflow is not approved, then runs.27 public func requestRun() {28 guard let workflow, !isRunning else { return }29 revalidate()30 guard errorCount == 0 else {31 tab = .editor32 show(L("Fix the %d problem(s) marked in the workflow before running it.", errorCount), error: true)33 return34 }35 if workflow.parameters.isEmpty { submitParameters([:]) } else { prompt = .parameters(problems: []) }36 }3738 /// Called by the parameter sheet (or directly when there is no parameter).39 public func submitParameters(_ values: [String: String]) {40 guard let workflow else { return }41 parameterValues[workflow.id] = values42 // files and folders the user typed or picked as parameter values are theirs to use43 let problems = WorkflowValidator.validate(workflow, parameters: values, host: permissiveHost, hasWorkbook: runsOnOpenWorkbook)44 .filter { $0.severity == .error }.map(\.message)45 guard problems.isEmpty else { prompt = .parameters(problems: problems); return }46 if isTrusted {47 prompt = nil48 start(workflow, values: values)49 } else {50 prompt = .trust(accesses: WorkflowValidator.fileAccesses(workflow, parameters: values, host: permissiveHost))51 }52 }5354 /// Called by the confirmation sheet.55 public func confirmTrust(always: Bool) {56 guard let workflow else { return }57 if always { WorkflowTrust.approve(workflow) }58 prompt = nil59 start(workflow, values: parameterValues[workflow.id] ?? [:])60 }6162 public func cancelPrompt() { prompt = nil }6364 public func stop() { engine?.cancel() }6566 /// The host of a confirmed run: exactly the locations listed in the confirmation, plus those picked in panels.67 func runHost(_ workflow: Workflow, values: [String: String]) -> StandardWorkflowHost {68 var readable = Array(grantedForReading), writable = Array(grantedForWriting)69 let resolved = WorkflowValidator.resolvedParameters(workflow, values)70 for access in WorkflowValidator.fileAccesses(workflow, parameters: values, host: permissiveHost) {71 var url: URL?72 if access.isDynamic {73 // "{{outputFolder}}/{{input.basename}}.xlsx": the fixed folder in front of the first run-time value74 let known = resolved.filter { !$0.value.isEmpty }75 var prefix = access.path76 for ref in WorkflowVariables.references(in: access.path) {77 if known[ref.name] == nil || !ref.modifiers.isEmpty && ["input", "last", "index", "workbook"].contains(ref.name) {78 if let r = prefix.range(of: ref.text) { prefix = String(prefix[..<r.lowerBound]) }79 break80 }81 }82 prefix = (try? WorkflowVariables.substitute(prefix, values: known)) ?? ""83 if prefix.hasSuffix("/"), prefix.count > 1 { url = WorkflowPaths.resolve(prefix, base: baseDirectory) }84 } else {85 url = URL(fileURLWithPath: access.path)86 }87 guard let url else { continue }88 if access.access == .write { writable.append(url) } else { readable.append(url) }89 }90 return StandardWorkflowHost(baseDirectory: baseDirectory, readable: readable, writable: writable, pdfRenderer: PrintPDFRenderer())91 }9293 func start(_ workflow: Workflow, values: [String: String]) {94 Task { await self.run(workflow, values: values) }95 }9697 /// Runs the selected workflow without prompts (tests, previews, App Intents on an open document).98 public func runSelected(values: [String: String] = [:]) async {99 guard let workflow else { return }100 parameterValues[workflow.id] = values101 await run(workflow, values: values)102 }103104 func run(_ workflow: Workflow, values: [String: String]) async {105 guard !isRunning else { return }106 let onWorkbook = runsOnOpenWorkbook107 let engine = WorkflowEngine(host: runHost(workflow, values: values))108 self.engine = engine109 runGeneration += 1110 let generation = runGeneration111 phase = .running112 liveSteps = []113 progress = 0114 lastRun = nil115 appliedSummary = nil116 runningName = workflow.name117 tab = .run118 notice = nil119120 var copy: Workbook?121 if onWorkbook, let session {122 session.runCalc()123 // the engine works on a private copy; the open workbook changes only if the run ends well124 copy = session.engine.lock.withLock { session.workbook.clone() }125 }126 do {127 let (run, result) = try await engine.run(workflow, parameters: values, workbook: copy) { [weak self] progress in128 Task { @MainActor in self?.handle(progress, generation: generation) }129 }130 // progress events hop to the main actor one by one; let the last ones land before the summary131 await Task.yield()132 finish(run, result: onWorkbook ? result : nil, workflow: workflow)133 } catch {134 phase = .finished135 show((error as? LocalizedError)?.errorDescription ?? String(describing: error), error: true)136 }137 self.engine = nil138 }139140 func handle(_ p: WorkflowProgress, generation: Int) {141 guard generation == runGeneration, phase == .running else { return }142 progress = max(progress, p.fraction)143 let key = p.path.map(String.init).joined(separator: ".") + "|" + (p.iteration ?? "")144 switch p.phase {145 case .started:146 liveSteps.removeAll { $0.id == key }147 liveSteps.append(LiveStep(id: key, path: p.path, kind: nil, title: p.title, iteration: p.iteration, status: nil))148 case .detail(let text):149 if let i = liveSteps.lastIndex(where: { $0.path == p.path && $0.status == nil }) { liveSteps[i].detail = text }150 case .finished(let result):151 let row = LiveStep(id: key, path: p.path, kind: result.kind, title: result.title, iteration: result.iteration, status: result.status,152 duration: result.duration, message: result.message, outputs: result.outputs, issues: result.issues)153 if let i = liveSteps.firstIndex(where: { $0.id == key }) { liveSteps[i] = row } else { liveSteps.append(row) }154 }155 }156157 /// Rows of the run view rebuilt from a recorded run (also what the history tab shows).158 public static func rows(of run: WorkflowRun) -> [LiveStep] {159 run.stepResults.map { r in160 LiveStep(id: r.id.uuidString, path: r.path, kind: r.kind, title: r.title, iteration: r.iteration, status: r.status, duration: r.duration,161 message: r.message, outputs: r.outputs, issues: r.issues)162 }163 }164165 func finish(_ run: WorkflowRun, result: Workbook?, workflow: Workflow) {166 liveSteps = AutomationModel.rows(of: run)167 progress = 1168 lastRun = run169 WorkflowHistory.append(run)170 history = WorkflowHistory.recent(limit: 200)171 selectedRunID = run.id172 if let result, let session, run.status == .succeeded || run.status == .completedWithErrors {173 // ONE undoable step: the difference between the open workbook and the engine's result, written174 // through engine operations inside a single `perform` (see WorkbookMerge for why it is a difference)175 let label = L("Run Workflow “%@”", workflow.name)176 appliedSummary = session.perform(label) { engine in WorkbookMerge.apply(result, to: engine, label: label) }177 workbookFlows = WorkflowStore.load(from: session.workbook)178 }179 phase = .finished180 }181182 // MARK: Schedule183184 /// The file a scheduled run reads: the workflow must live in the user's library.185 public var scheduleWorkflowFile: URL? {186 guard let workflow, selectedSource == .library else { return nil }187 return WorkflowPaths.library.appendingPathComponent("\(workflow.id.uuidString).\(Workflow.fileExtension)")188 }189190 /// Arguments of the scheduled command. `tool` is nil outside the installed app.191 public func scheduleArguments(tool: URL? = WorkflowSchedule.bundledTool()) -> [String]? {192 guard let workflow, let file = scheduleWorkflowFile else { return nil }193 let shown = tool ?? URL(fileURLWithPath: "/Applications/ORIX Sheet.app/Contents/MacOS/orix-sheet")194 return WorkflowSchedule.arguments(tool: shown, workflowFile: file, parameters: parameterValues[workflow.id] ?? [:],195 baseDirectory: baseDirectory)196 }197198 /// Why the selected workflow cannot run unattended (a scheduled run has no open workbook and nobody to ask).199 public var scheduleProblems: [String] {200 guard let workflow else { return [] }201 return WorkflowValidator.validate(workflow, parameters: draftValues(for: workflow), host: permissiveHost, hasWorkbook: false)202 .filter { $0.severity == .error }.map(\.message)203 }204205 public var scheduleIsInstalled: Bool { workflow.map { wf in installedSchedules.contains { $0.workflowID == wf.id } } ?? false }206207 public func installSchedule() {208 guard let workflow, let tool = WorkflowSchedule.bundledTool(), let arguments = scheduleArguments(tool: tool) else { return }209 do {210 try WorkflowSchedule.install(workflowID: workflow.id, arguments: arguments, spec: schedule)211 show(L("“%@” is scheduled.", workflow.name))212 } catch { show(error.localizedDescription, error: true) }213 installedSchedules = WorkflowSchedule.installed()214 }215216 public func uninstallSchedule(_ id: UUID) {217 do { try WorkflowSchedule.uninstall(workflowID: id) } catch { show(error.localizedDescription, error: true) }218 installedSchedules = WorkflowSchedule.installed()219 }220221 public func workflowName(_ id: UUID) -> String {222 (libraryFlows + workbookFlows + templates).first { $0.id == id }?.name ?? history.first { $0.workflowID == id }?.workflowName ?? id.uuidString223 }224}225