Repository Public
1import AppKit2import SwiftUI3import SheetCore4import SheetUI5import SheetIntelligence6import FeatureIntelligence7import FunctionsNumeric8import FunctionsText9import FunctionsLookup1011// Development harness for the ORIX Intelligence panel.12// intelligence-preview [--shot out.png] [--dark] [--size WxH] [--lang fr-CA] [--panel-only]13// [--task explain|suggest|review|describe|charts|plan|statistics|python|document] [--request "text"] [--idle]14// The task runs against the REAL on-device model when it is available; when it is not, the window shows the real15// unavailable state. With --shot the window renders itself to a PNG once the task has finished, then exits.16// Debug builds only: --simulate-unavailable <reason> shows an unavailable state through the scripted test backend,17// under a visible "SCRIPTED PREVIEW" marker.1819/// Clearly synthetic demo data.20@MainActor func demoSession() -> WorkbookSession {21 let wb = Workbook(sheetNames: ["Synthetic sales", "Parameters"])22 let session = WorkbookSession(workbook: wb, locale: Locale(identifier: "en_US"))23 let regions = ["North", "South", "East", "West"], products = ["Widget", "Gadget", "Gizmo"], prices = [9.5, 14.0, 22.25]24 let parser = session.parser25 session.perform("Demo") { e in26 func put(_ sheet: Int, _ a1: String, _ text: String) {27 let c = CellRef(a1: a1)!28 try? e.setInput(sheet: sheet, row: c.row, col: c.col, text, parser: parser)29 }30 put(0, "A1", "Synthetic demo data — not real sales")31 for (k, h) in ["Region", "Product", "Units", "Unit Price", "Revenue", "Date"].enumerated() { put(0, "\(A1.columnName(k))3", h) }32 for i in 0..<20 {33 let row = i + 434 put(0, "A\(row)", regions[i % 4]); put(0, "B\(row)", products[i % 3])35 put(0, "C\(row)", String(5 + (i * 7) % 23)); put(0, "D\(row)", String(prices[i % 3]))36 put(0, "E\(row)", "=C\(row)*D\(row)")37 put(0, "F\(row)", String(format: "2026-%02d-%02d", i / 7 + 1, (i * 3) % 27 + 1))38 }39 put(0, "H3", "Summary")40 put(0, "H4", "North share"); put(0, "I4", "=SUMIF(A4:A23,\"North\",E4:E23)/SUM(E4:E23)")41 put(0, "H5", "Revenue with tax"); put(0, "I5", "=SUM(E4:E23)*(1+TaxRate)")42 put(0, "H6", "West revenue")43 put(0, "H7", "Per unit check"); put(0, "I7", "=E4/(C4-C4)")44 put(1, "A1", "Tax rate"); put(1, "B1", "0.15")45 e.setDefinedName(DefinedName(name: "TaxRate", formula: "Parameters!$B$1"))46 e.setStyle(sheet: 0, range: RangeRef(a1: "A1")!) { $0.bold = true; $0.fontSize = 15 }47 e.setStyle(sheet: 0, range: RangeRef(a1: "A3:F3")!) { $0.bold = true; $0.fill = RGBA(hex: 0x0891B2); $0.textColor = .white }48 e.setStyle(sheet: 0, range: RangeRef(a1: "H3")!) { $0.bold = true }49 e.setStyle(sheet: 0, range: RangeRef(a1: "D4:E23")!) { $0.numberFormat = "#,##0.00" }50 e.setStyle(sheet: 0, range: RangeRef(a1: "I4")!) { $0.numberFormat = "0.0%" }51 e.setStyle(sheet: 0, range: RangeRef(a1: "I5:I6")!) { $0.numberFormat = "#,##0.00" }52 e.editMeta(sheet: 0) { m in m.colWidths[7] = 120; m.colWidths[5] = 90; m.rowHeights[0] = 28 }53 }54 session.showSidebar = false55 return session56}5758final class AppDelegate: NSObject, NSApplicationDelegate {59 var window: NSWindow!60 var session: WorkbookSession!61 var started = Date()6263 func applicationDidFinishLaunching(_ notification: Notification) {64 let args = CommandLine.arguments65 func value(_ flag: String) -> String? { args.firstIndex(of: flag).flatMap { $0 + 1 < args.count ? args[$0 + 1] : nil } }66 var size = NSSize(width: 1280, height: 860)67 if let s = value("--size")?.split(separator: "x").compactMap({ Double($0) }), s.count == 2 { size = NSSize(width: s[0], height: s[1]) }68 if args.contains("--dark") { NSApp.appearance = NSAppearance(named: .darkAqua) }69 let locale = Locale(identifier: value("--lang") ?? "en-US")70 if let lang = value("--lang") { IntelligenceLocalization.forceLanguage(lang) }7172 NumericFunctions.register(); TextFunctions.register(); LookupFunctions.register(); FinancialFunctions.register()73 var factory: () -> Intelligence = { Intelligence(locale: locale) }74 #if DEBUG75 if let code = value("--simulate-unavailable") {76 let reasons: [String: UnavailableReason] = ["osTooOld": .osTooOld, "deviceNotEligible": .deviceNotEligible, "appleIntelligenceNotEnabled": .appleIntelligenceNotEnabled,77 "modelNotReady": .modelNotReady, "frameworkMissing": .frameworkMissing]78 let reason = reasons[code] ?? .other(code)79 factory = { Intelligence(backend: ScriptedBackend(responses: [], availability: .unavailable(reason: reason)), locale: locale) }80 }81 #endif82 IntelligenceFeature.setIntelligenceFactory(factory)83 IntelligenceFeature.register()8485 session = demoSession()86 let task = AssistantTask(rawValue: value("--task") ?? "explain") ?? .explain87 let model = IntelligenceFeature.model(for: session)88 switch task {89 case .explain: session.select(RangeRef(a1: "I4")!, active: CellRef(a1: "I4")!)90 case .suggest, .python, .plan: session.select(RangeRef(a1: "I6")!, active: CellRef(a1: "I6")!)91 default: session.select(RangeRef(a1: "C6")!, active: CellRef(a1: "C6")!)92 }93 let defaults: [AssistantTask: String] = [.suggest: "Total revenue for the West region", .plan: "Total revenue per region, highest first",94 .python: "Compute total revenue per region and write it starting at cell K3"]95 model.task = task96 model.request = value("--request") ?? defaults[task] ?? ""97 session.inspectorPane = IntelligenceFeature.paneID9899 if args.contains("--panel-only") {100 // the panel alone in a borderless window, which may be taller than the screen: the whole answer is visible101 if value("--size") == nil { size = NSSize(width: 400, height: 1100) }102 window = NSWindow(contentRect: NSRect(origin: .zero, size: size), styleMask: [.borderless], backing: .buffered, defer: false)103 window.contentView = NSHostingView(rootView: IntelligenceFeature.panel(for: session).frame(width: size.width, height: size.height))104 } else {105 window = NSWindow(contentRect: NSRect(origin: .zero, size: size), styleMask: [.titled, .closable, .resizable, .miniaturizable], backing: .buffered, defer: false)106 window.title = "ORIX Intelligence — preview"107 window.contentView = NSHostingView(rootView: WorkbookView(session: session))108 window.center()109 }110 window.makeKeyAndOrderFront(nil)111 NSApp.activate(ignoringOtherApps: false)112113 let shot = value("--shot")114 let idle = args.contains("--idle")115 Task { @MainActor in116 await model.refreshAvailability()117 model.refresh(self.session, force: true)118 if task == .review { model.runAuditor(self.session) }119 var job: Task<Void, Never>?120 if !idle, model.isAvailable { job = model.run(self.session) }121 guard let shot else { return }122 // wait for the real generation to finish (bounded), then let SwiftUI lay the result out123 let waiter = Task { await job?.value }124 let deadline = Date().addingTimeInterval(180)125 while model.isRunning, Date() < deadline { try? await Task.sleep(nanoseconds: 200_000_000) }126 waiter.cancel()127 try? await Task.sleep(nanoseconds: 1_200_000_000)128 guard let view = self.window.contentView, let rep = view.bitmapImageRepForCachingDisplay(in: view.bounds) else { exit(2) }129 view.cacheDisplay(in: view.bounds, to: rep)130 try? rep.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: shot))131 let state: String132 switch model.availability {133 case .available(let m): state = "real on-device model (\(m)); phase \(model.phase); \(String(format: "%.1f", Date().timeIntervalSince(self.started))) s"134 case .unavailable(let r): state = "model unavailable (\(r.code))"135 case nil: state = "availability unknown"136 }137 print("shot \(shot): task \(task.rawValue), \(model.debugMarker ?? state)")138 exit(0)139 }140 }141 func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true }142}143144// --lang must be set before AppKit reads the preferred languages145if let i = CommandLine.arguments.firstIndex(of: "--lang"), i + 1 < CommandLine.arguments.count {146 UserDefaults.standard.set([CommandLine.arguments[i + 1]], forKey: "AppleLanguages")147}148let app = NSApplication.shared149let delegate = AppDelegate()150app.delegate = delegate151app.setActivationPolicy(CommandLine.arguments.contains("--shot") ? .accessory : .regular)152app.run()153