Repository Public
1import Foundation2import Observation3import SwiftUI4import SheetCore5import SheetUI67public enum RunState: Sendable {8 case idle9 case running10 case done(ToolResult)11 case failed(String)12 case cancelled13}1415/// State of one studio (or of the What-If inspector) for one workbook session: the selected tool, the form of16/// every tool, and the running computation.17@MainActor @Observable18public final class ToolSessionModel {19 public let studio: String20 public let tools: [ToolDescriptor]21 public var selectedID: String {22 didSet { if selectedID != oldValue { status = nil } }23 }24 public private(set) var values: [String: FormValues] = [:]25 public private(set) var states: [String: RunState] = [:]26 public private(set) var progress: Double = 027 public private(set) var runningID: String?28 /// Feedback of the last output action ("Report written to …").29 public var status: String?3031 // Report destination32 public var writeToNewSheet = true33 public var destinationCell = ""34 public var includeCharts = true3536 @ObservationIgnored private var flag: CancelFlag?37 @ObservationIgnored private var presetDone = Set<String>()38 @ObservationIgnored private var generation = 03940 public init(studio: String, tools: [ToolDescriptor]) {41 self.studio = studio42 self.tools = tools43 selectedID = tools.first?.id ?? ""44 for t in tools { values[t.id] = FormValues(defaults: t.fields) }45 }4647 public var selected: ToolDescriptor? { tools.first { $0.id == selectedID } }48 public func tool(_ id: String) -> ToolDescriptor? { tools.first { $0.id == id } }49 public func state(_ id: String) -> RunState { states[id] ?? .idle }50 public func formValues(_ id: String) -> FormValues { values[id] ?? FormValues() }51 public func setValues(_ v: FormValues, for id: String) { values[id] = v }52 public var isRunning: Bool { runningID != nil }5354 /// Groups in order of first appearance.55 public var groups: [(name: String, tools: [ToolDescriptor])] {56 var order = [String](), map = [String: [ToolDescriptor]]()57 for t in tools {58 if map[t.group] == nil { order.append(t.group) }59 map[t.group, default: []].append(t)60 }61 return order.map { ($0, map[$0] ?? []) }62 }6364 /// Fills the range fields of a tool from the selection the first time it is shown.65 public func prepare(_ id: String, session: WorkbookSession) {66 guard !presetDone.contains(id), let tool = tool(id) else { return }67 presetDone.insert(id)68 var v = formValues(id)69 ToolInputResolver.preset(tool, values: &v, session: session)70 values[id] = v71 }7273 /// Selects a tool and fills its form with the tool's demo values (preview harness).74 public func loadDemo(_ id: String, session: WorkbookSession) {75 guard let tool = tool(id) else { return }76 selectedID = id77 presetDone.insert(id)78 var v = FormValues(defaults: tool.fields)79 if let demo = tool.demo {80 demo(session, &v)81 // demo values name ranges; choose default columns for anything the demo left unset82 let chosen = v83 ToolInputResolver.applyColumnDefaults(tool, values: &v, session: session)84 for (k, val) in chosen.storage {85 switch val {86 case .column(let i) where i != nil: v[k] = val87 case .columns(let list) where !list.isEmpty: v[k] = val88 default: break89 }90 }91 } else {92 ToolInputResolver.preset(tool, values: &v, session: session)93 }94 values[id] = v95 }9697 public func cancel() { flag?.cancel() }9899 /// Runs the selected tool off the main actor. Returns when the computation has finished.100 @discardableResult101 public func run(_ id: String, session: WorkbookSession) async -> RunState {102 guard let tool = tool(id), runningID == nil else { return state(id) }103 let flag = CancelFlag()104 self.flag = flag105 status = nil106 generation += 1107 let gen = generation108 let reporter = ProgressRelay { [weak self] p in109 guard let self, self.generation == gen else { return }110 self.progress = p111 }112 let input: ToolInput113 do {114 input = try ToolInputResolver.resolve(tool, values: formValues(id), session: session,115 progress: { reporter.report($0) }, isCancelled: { flag.isCancelled })116 } catch {117 states[id] = .failed(ToolError.describe(error))118 return state(id)119 }120 runningID = id121 progress = 0122 states[id] = .running123 let run = tool.run124 let outcome: RunState = await Task.detached(priority: .userInitiated) {125 do {126 let result = try run(input)127 return flag.isCancelled && result.blocks.isEmpty ? .cancelled : .done(result)128 } catch is CancellationError {129 return .cancelled130 } catch {131 return flag.isCancelled ? .cancelled : .failed(ToolError.describe(error))132 }133 }.value134 states[id] = outcome135 runningID = nil136 self.flag = nil137 return outcome138 }139140 /// Writes the result of a tool as a report (one undoable step).141 public func writeReport(_ id: String, session: WorkbookSession) {142 guard case .done(let result) = state(id) else { return }143 let destination: ReportWriter.Destination144 if writeToNewSheet {145 destination = .newSheet146 } else {147 guard let cell = RangeReader.cells(destinationCell, workbook: session.workbook, sheet: session.sheetIndex)?.first else {148 status = L("Enter the top-left cell of the report (for example %@).", "H2")149 return150 }151 destination = .cell(cell)152 }153 let outcome = ReportWriter.write(result, to: destination, includeCharts: includeCharts, session: session)154 status = L("Report written to %@", session.workbook.sheets[outcome.sheet].name + "!" + outcome.range.a1)155 }156157 public func perform(_ action: ResultAction, session: WorkbookSession) {158 do { status = try action.perform(session) ?? status }159 catch { status = ToolError.describe(error) }160 }161}162163/// Throttles progress callbacks from a worker thread to the main actor.164final class ProgressRelay: @unchecked Sendable {165 private let apply: @MainActor (Double) -> Void166 private var last = 0.0167 private let lock = NSLock()168 init(_ apply: @escaping @MainActor (Double) -> Void) { self.apply = apply }169 func report(_ p: Double) {170 let now = CFAbsoluteTimeGetCurrent()171 lock.lock()172 let due = now - last > 0.06 || p >= 1173 if due { last = now }174 lock.unlock()175 guard due else { return }176 let apply = self.apply177 DispatchQueue.main.async { MainActor.assumeIsolated { apply(min(max(p, 0), 1)) } }178 }179}180181/// Keeps one `ToolSessionModel` per (session, studio) so a studio keeps its state while the user navigates.182@MainActor public enum StudioStore {183 private final class Entry { weak var session: WorkbookSession?; var models: [String: ToolSessionModel] = [:] }184 private static var entries: [ObjectIdentifier: Entry] = [:]185186 public static func model(studio: String, session: WorkbookSession, tools: @autoclosure () -> [ToolDescriptor]) -> ToolSessionModel {187 entries = entries.filter { $0.value.session != nil }188 let key = ObjectIdentifier(session)189 let entry = entries[key] ?? Entry()190 entry.session = session191 entries[key] = entry192 if let m = entry.models[studio] { return m }193 let m = ToolSessionModel(studio: studio, tools: tools())194 entry.models[studio] = m195 return m196 }197}198