Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions Sources/Clavis/State/ApplicationSettingsModel.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import AppKit
import ClavisCore

@MainActor
final class ApplicationSettingsModel: ObservableObject {
@Published private(set) var snapshot: ApplicationRegistrySnapshot?
@Published private(set) var isBusy = false
@Published private(set) var message: String?
@Published var selection: UUID?
private let agent: AgentControlling

init(agent: AgentControlling = AgentLifecycleManager.shared) { self.agent = agent }
var applications: [RegisteredApplication] { snapshot?.applications.filter { !$0.removed } ?? [] }

func load() async {
guard !isBusy else { return }
isBusy = true
defer { isBusy = false }
let agent = agent
snapshot = await Task.detached { agent.applicationRegistry() }.value
message = snapshot == nil ? "Could not load applications. Check that the Clavis daemon is running and up to date." : nil
if !applications.contains(where: { $0.id == selection }) { selection = nil }
}

func classify(_ app: RegisteredApplication, as classification: ApplicationClassification) async {
guard app.classification != classification else { return }
var changed = app
changed.classification = classification
await perform(.set(changed))
}

func removeSelected() async {
guard let app = applications.first(where: { $0.id == selection }) else { return }
await perform(.remove(app.identity))
}

func add(url: URL) async {
guard !isBusy else { return }
do {
let executable = Bundle(url: url)?.executableURL ?? url
let identity = try ApplicationIdentityVerifier.identity(forExecutable: executable)
if let existing = applications.first(where: { $0.identity == identity }) {
selection = existing.id
return
}
let app = RegisteredApplication(
identity: identity,
name: url.deletingPathExtension().lastPathComponent,
path: url.path, classification: .bot
)
await perform(.set(app))
selection = applications.first(where: { $0.identity == identity })?.id
} catch {
message = "Could not identify the selected application or executable."
}
}

private func perform(_ change: ApplicationPolicyChange) async {
guard !isBusy, snapshot != nil else { return }
isBusy = true
message = nil
defer { isBusy = false }
let agent = agent
let result = await Task.detached {
let applied = agent.changeApplicationPolicy(change)
return (applied, applied ? agent.applicationRegistry() : nil)
}.value
guard result.0 else {
message = "The change was not applied. The previous policy remains in effect."
return
}
guard let fresh = result.1 else {
message = "The daemon accepted the change, but its updated settings could not be loaded."
return
}
snapshot = fresh
if !applications.contains(where: { $0.id == selection }) { selection = nil }
}
}
163 changes: 163 additions & 0 deletions Sources/Clavis/Views/Sheets/SettingsNavigation.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
import SwiftUI
import AppKit
import ClavisCore

private enum SettingsTab: String, CaseIterable {
case general = "General"
case bots = "Bots"
var symbol: String { self == .general ? "gearshape" : "desktopcomputer" }
}

struct SettingsNavigation<General: View>: View {
let general: General
@AppStorage("clavis.settings.tab") private var selectedTab = SettingsTab.general.rawValue
@StateObject private var applications: ApplicationSettingsModel

init(general: General, agent: any AgentControlling) {
self.general = general
_applications = StateObject(wrappedValue: ApplicationSettingsModel(agent: agent))
}

var body: some View {
VStack(spacing: 0) {
ZStack {
general
.opacity(selectedTab == SettingsTab.general.rawValue ? 1 : 0)
.disabled(selectedTab != SettingsTab.general.rawValue)
.allowsHitTesting(selectedTab == SettingsTab.general.rawValue)
.accessibilityHidden(selectedTab != SettingsTab.general.rawValue)
ApplicationSettingsPane(model: applications)
.opacity(selectedTab == SettingsTab.bots.rawValue ? 1 : 0)
.disabled(selectedTab != SettingsTab.bots.rawValue)
.allowsHitTesting(selectedTab == SettingsTab.bots.rawValue)
.accessibilityHidden(selectedTab != SettingsTab.bots.rawValue)
}
HStack(spacing: 3) {
ForEach(SettingsTab.allCases, id: \.rawValue) { tab in
Button {
selectedTab = tab.rawValue
} label: {
VStack(spacing: 3) {
Image(systemName: tab.symbol).font(.system(size: 14))
Text(tab.rawValue).font(.system(size: 10, weight: .medium))
}
.foregroundStyle(selectedTab == tab.rawValue ? Color.accentColor : Color.secondary)
.frame(width: 66, height: 42)
.background {
if selectedTab == tab.rawValue {
Capsule().fill(.quaternary)
}
}
.contentShape(Capsule())
}
.buttonStyle(.plain)
.accessibilityLabel("\(tab.rawValue) settings")
.accessibilityAddTraits(selectedTab == tab.rawValue ? [.isSelected] : [])
}
}
.padding(4)
.liquidGlassCapsuleControl()
.padding(.vertical, 12)
.frame(maxWidth: .infinity)
}
.onAppear {
if SettingsTab(rawValue: selectedTab) == nil { selectedTab = SettingsTab.general.rawValue }
}
}
}

private struct ApplicationSettingsPane: View {
@ObservedObject var model: ApplicationSettingsModel

var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 14) {
Text("Applications").font(.headline)
Text("Personal apps can use all keys. Bots can use Bot keys.")
.font(.callout).foregroundStyle(.secondary)
VStack(spacing: 0) {
if model.applications.isEmpty {
Text(model.snapshot == nil ? "Applications unavailable" : "No applications added")
.font(.callout).foregroundStyle(.secondary)
.frame(maxWidth: .infinity, minHeight: 84)
}
if !model.applications.isEmpty {
List(selection: $model.selection) {
ForEach(model.applications) { app in
HStack(spacing: 10) {
Image(nsImage: NSWorkspace.shared.icon(forFile: app.path))
.resizable().frame(width: 28, height: 28)
.accessibilityHidden(true)
Text(app.name).font(.system(size: 12, weight: .medium))
.lineLimit(1).truncationMode(.middle).help(app.path)
Spacer(minLength: 8)
Picker("Access for \(app.name)", selection: Binding(
get: { app.classification },
set: { value in Task { await model.classify(app, as: value) } }
)) {
ForEach(ApplicationClassification.allCases, id: \.self) { classification in
Text(classification.title).tag(classification)
}
}
.labelsHidden().frame(width: 110)
}
.padding(.horizontal, 14).padding(.vertical, 12)
.background(model.selection == app.id ? Color.accentColor.opacity(0.12) : .clear)
.contentShape(Rectangle())
.tag(app.id)
.listRowInsets(EdgeInsets())
}
}
.listStyle(.inset)
.scrollContentBackground(.hidden)
.frame(height: CGFloat(min(model.applications.count, 6)) * 54)
.onDeleteCommand { Task { await model.removeSelected() } }
}
HStack(spacing: 0) {
Button(action: chooseApplication) { Image(systemName: "plus").frame(width: 30, height: 28) }
.help("Add application or executable")
.accessibilityLabel("Add application or executable")
.disabled(model.snapshot == nil)
Divider().frame(height: 20)
Button { Task { await model.removeSelected() } } label: {
Image(systemName: "minus").frame(width: 30, height: 28)
}
.help("Remove selected application")
.accessibilityLabel("Remove selected application")
.disabled(model.selection == nil)
Spacer()
if model.isBusy { ProgressView().controlSize(.small).padding(.trailing, 10) }
}
.buttonStyle(.borderless)
.background(.quaternary.opacity(0.5))
}
.disabled(model.isBusy)
.background(Color(nsColor: .controlBackgroundColor))
.clipShape(RoundedRectangle(cornerRadius: 12))
.overlay(RoundedRectangle(cornerRadius: 12).strokeBorder(.quaternary))
Text("Changes require Touch ID or your macOS password. Removing an app blocks it and revokes its approvals.")
.font(.caption).foregroundStyle(.secondary)
if let message = model.message {
Text(message).font(.callout).foregroundStyle(.secondary)
Button("Reload") { Task { await model.load() } }.disabled(model.isBusy)
}
}
.padding(22)
}
.task { await model.load() }
}

private func chooseApplication() {
let panel = NSOpenPanel()
panel.title = "Add application or executable"
panel.prompt = "Add"
panel.canChooseDirectories = false
panel.canChooseFiles = true
panel.allowsMultipleSelection = false
panel.treatsFilePackagesAsDirectories = false
panel.begin { response in
guard response == .OK, let url = panel.url else { return }
Task { @MainActor in await model.add(url: url) }
}
}
}
Loading
Loading