Repository Public
1// ORIX Docs2// File: App/Sources/Inspector/IntelligenceInspector.swift3// Description: The Intelligence inspector tab: on-device writing actions that always end in a proposal to accept or reject,4// and the rule-based text analysis that needs no model.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import DocModel10import DocAutomation1112struct IntelligenceInspector: View {13 let session: DocumentSession14 @State private var model: IntelligenceModel15 @State private var tools: TextToolsModel16 @State private var showTones = false17 private let settings = AppSettings.shared1819 init(session: DocumentSession) {20 self.session = session21 _model = State(initialValue: IntelligenceModel(session: session, engine: IntelligenceInspector.engine()))22 _tools = State(initialValue: TextToolsModel(session: session))23 }2425 /// The on-device engine. In debug builds, screenshots of the warning state use a scripted answer26 /// (`-ORIXIntelligenceDemo warning`); release builds only ever use the system model.27 private static func engine() -> any TextIntelligence {28 #if DEBUG29 if UserDefaults.standard.string(forKey: "ORIXIntelligenceDemo") == "warning" {30 return ScriptedIntelligence(contextSize: 8192) { request in31 let body = request.prompt.components(separatedBy: "-----").dropFirst().first?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""32 let first = TextChunker.sentences(body).first ?? body33 return first + " This is consistent with earlier findings (Hartmann & Ruiz, 2019) and with the survey data [14]."34 }35 }36 #endif37 return FoundationModelsEngine()38 }3940 var body: some View {41 ScrollView {42 VStack(alignment: .leading, spacing: 0) {43 InspectorSection(title: "On-Device Writing") { generative }44 InspectorSection(title: "Text Analysis · Rule-Based") { TextToolsView(model: tools) }45 }46 }47 .background(ORIX.Palette.chrome)48 .accessibilityIdentifier("inspector.intelligence")49 .onChange(of: session.selectionRevision, initial: true) { _, _ in model.selectionChanged() }50 .task {51 // The system may finish preparing the model while the panel is open.52 if let demo = UserDefaults.standard.string(forKey: "ORIXIntelligenceAction"), let action = IntelligenceAction.all.first(where: { $0.id == demo }) {53 try? await Task.sleep(for: .milliseconds(700))54 model.selectionChanged()55 model.run(action)56 #if DEBUG57 // Visual checks of applying a proposal: `-ORIXIntelligenceApply accept|insert|undo`.58 if let apply = UserDefaults.standard.string(forKey: "ORIXIntelligenceApply") {59 for _ in 0..<600 where model.phase != .proposal { try? await Task.sleep(for: .milliseconds(100)) }60 if apply == "insert" { model.insertBelow() } else { model.accept() }61 if apply == "undo" { session.undoManager?.undo() }62 }63 #endif64 }65 #if DEBUG66 if let name = UserDefaults.standard.string(forKey: "ORIXIntelligenceTool"), let tool = TextTool(rawValue: name) {67 try? await Task.sleep(for: .milliseconds(700))68 tools.run(tool)69 }70 #endif71 while !Task.isCancelled {72 model.refreshAvailability()73 try? await Task.sleep(for: .seconds(model.availability == .modelNotReady ? 3 : 20))74 }75 }76 }7778 // MARK: Generative part7980 @ViewBuilder private var generative: some View {81 status82 if !settings.intelligenceEnabled {83 notice(String(localized: "ORIX Intelligence is turned off. The writing actions are disabled; the text analysis below still works."), symbol: "power")84 Button(String(localized: "Open Settings…")) { NSApp.sendAction(#selector(AppDelegate.showSettings(_:)), to: nil, from: nil) }85 .buttonStyle(.link).font(ORIX.Font.label)86 .accessibilityIdentifier("intelligence.openSettings")87 } else if !model.availability.isAvailable {88 notice(model.availability.explanation, symbol: "info.circle")89 }90 if model.phase != .idle {91 ProposalView(model: model)92 } else {93 scopePicker94 actionList.disabled(!model.generationEnabled).opacity(model.generationEnabled ? 1 : 0.45)95 Text("Every result is a proposal: nothing changes in your document until you accept it, and Undo restores the original.")96 .font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)97 }98 }99100 private var status: some View {101 let ready = model.generationEnabled102 return HStack(spacing: ORIX.Space.s) {103 Image(systemName: ready ? "checkmark.circle.fill" : (model.availability == .modelNotReady ? "arrow.down.circle" : "minus.circle"))104 .foregroundStyle(ready ? ORIX.Palette.positive : ORIX.Palette.textTertiary)105 VStack(alignment: .leading, spacing: 1) {106 Text(settings.intelligenceEnabled ? model.availability.headline : String(localized: "Turned off in Settings"))107 .font(.system(size: 12, weight: .semibold)).foregroundStyle(ORIX.Palette.text)108 Text("Runs on this Mac. Your text never leaves it.").font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textSecondary)109 }110 Spacer(minLength: 0)111 }112 .accessibilityElement(children: .combine)113 .accessibilityIdentifier("intelligence.status")114 }115116 private func notice(_ text: String, symbol: String) -> some View {117 Label { Text(text).font(ORIX.Font.label).fixedSize(horizontal: false, vertical: true) } icon: { Image(systemName: symbol) }118 .foregroundStyle(ORIX.Palette.textSecondary)119 .padding(ORIX.Space.s)120 .frame(maxWidth: .infinity, alignment: .leading)121 .background(RoundedRectangle(cornerRadius: ORIX.Radius.m).fill(ORIX.Palette.text.opacity(0.05)))122 .accessibilityIdentifier("intelligence.unavailable")123 }124125 private var scopePicker: some View {126 VStack(alignment: .leading, spacing: ORIX.Space.xs) {127 Picker(String(localized: "Work on"), selection: Binding(get: { model.scope }, set: { model.choose($0) })) {128 ForEach(IntelligenceScope.allCases) { scope in129 Text(scope.title).tag(scope)130 }131 }132 .pickerStyle(.segmented).labelsHidden().controlSize(.small)133 .accessibilityLabel(Text("Text to work on"))134 .accessibilityIdentifier("intelligence.scope")135 scopeSummary136 }137 }138139 private var scopeSummary: some View {140 let _ = session.selectionRevision141 let _ = session.revision142 let text: String143 if model.scope == .selection, session.selection.isCaret {144 text = String(localized: "Nothing is selected: the paragraph at the caret is used.")145 } else if let source = model.currentSource(for: model.scope == .selection && session.selection.isCaret ? .paragraph : model.scope) {146 text = model.scope == .document147 ? String(localized: "\(source.words) words in the document. Rewriting actions use the selection or the paragraph.")148 : String(localized: "\(source.words) words")149 } else {150 text = String(localized: "No text here. Place the caret in a paragraph or select some text.")151 }152 return Text(text).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)153 }154155 private var actionList: some View {156 VStack(alignment: .leading, spacing: ORIX.Space.m) {157 group("Rewrite") {158 ActionRow(action: .rewrite) { model.run(.rewrite) }159 ActionRow(action: .improveClarity) { model.run(.improveClarity) }160 Button { showTones.toggle() } label: {161 ActionLabel(symbol: "dial.medium", title: String(localized: "Adjust Tone"), trailing: showTones ? "chevron.down" : "chevron.right")162 }163 .buttonStyle(.plain)164 .help("Rewrite in a formal, friendly, concise or academic tone")165 .accessibilityLabel(Text("Adjust Tone"))166 .accessibilityHint(Text("Shows the tones"))167 .accessibilityIdentifier("intelligence.action.tone")168 if showTones {169 HStack(spacing: ORIX.Space.xs) {170 ForEach(IntelligenceTone.allCases, id: \.self) { tone in171 Button(tone.title) { model.run(.adjustTone(tone)) }172 .buttonStyle(ORIXButtonStyle(prominent: false)).controlSize(.small)173 .accessibilityIdentifier("intelligence.action.tone-\(tone.rawValue)")174 }175 }176 .padding(.leading, ORIX.Space.s)177 }178 }179 group("Understand") {180 ActionRow(action: .summarise) { model.run(.summarise) }181 ActionRow(action: .explain) { model.run(.explain) }182 ActionRow(action: .actionItems) { model.run(.actionItems) }183 }184 group("Structure") {185 ActionRow(action: .suggestHeadings) { model.run(.suggestHeadings) }186 ActionRow(action: .outline) { model.run(.outline) }187 ActionRow(action: .suggestStructure) { model.run(.suggestStructure) }188 }189 }190 }191192 private func group<Content: View>(_ title: LocalizedStringKey, @ViewBuilder content: () -> Content) -> some View {193 VStack(alignment: .leading, spacing: 2) {194 Text(title).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary).padding(.leading, ORIX.Space.s)195 .accessibilityAddTraits(.isHeader)196 content()197 }198 }199}200201private struct ActionLabel: View {202 let symbol: String203 let title: String204 var trailing: String?205 var hover = false206 var body: some View {207 HStack(spacing: ORIX.Space.s) {208 Image(systemName: symbol).font(.system(size: 12, weight: .medium)).frame(width: 18).foregroundStyle(ORIX.Palette.accent)209 Text(title).font(ORIX.Font.body).foregroundStyle(ORIX.Palette.text)210 Spacer(minLength: 0)211 if let trailing { Image(systemName: trailing).font(.system(size: 9, weight: .semibold)).foregroundStyle(ORIX.Palette.textTertiary) }212 }213 .padding(.horizontal, ORIX.Space.s).padding(.vertical, 6)214 .background(RoundedRectangle(cornerRadius: ORIX.Radius.m).fill(hover ? ORIX.Palette.text.opacity(0.07) : .clear))215 .contentShape(Rectangle())216 }217}218219private struct ActionRow: View {220 let action: IntelligenceAction221 let run: () -> Void222 @State private var hover = false223 var body: some View {224 Button(action: run) { ActionLabel(symbol: action.symbol, title: action.title, hover: hover) }225 .buttonStyle(.plain)226 .onHover { hover = $0 }227 .help(action.help)228 .accessibilityLabel(Text(action.title))229 .accessibilityHint(Text(action.help))230 .accessibilityIdentifier("intelligence.action.\(action.id)")231 }232}233