Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Features/Search/CommandPalette.swift3// Description: AI Command Center (⌘K): floating palette over actions, conversations, models (whole catalogue), projects, prompts and settings sections; fuzzy search, fully keyboard driven.4import SwiftUI5import SPChatCore67struct PaletteItem: Identifiable {8 enum Section: String, CaseIterable { case actions = "Actions", conversations = "Conversations", models = "Modèles", projects = "Projets", prompts = "Prompts", settings = "Réglages" }9 let id: String10 var section: Section = .actions11 let title: String12 let subtitle: String13 let systemImage: String14 var model: AIModel?15 let run: () -> Void16}1718enum Fuzzy {19 /// Subsequence match, diacritics- and case-insensitive. Higher is better; nil = no match.20 static func score(_ query: String, in text: String) -> Int? {21 let q = Array(query.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: nil)), t = Array(text.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: nil))22 if q.isEmpty { return 0 }23 var qi = 0, score = 0, streak = 024 for (i, c) in t.enumerated() where qi < q.count {25 if c == q[qi] { streak += 1; score += 2 + streak * 2 + (i == 0 || t[i - 1] == " " ? 6 : 0); qi += 1 } else { streak = 0 }26 }27 return qi == q.count ? score - t.count / 8 : nil28 }29}3031/// Settings tabs reachable from the palette and the menus.32enum SettingsTab: String, CaseIterable, Identifiable {33 case general, chat, assistant, providers, server, security, data34 var id: String { rawValue }35 var title: String {36 switch self { case .general: "Général"; case .chat: "Conversation"; case .assistant: "Assistant"; case .providers: "Fournisseurs"; case .server: "Mémoire et dépenses"; case .security: "Sécurité"; case .data: "Données" }37 }38 var systemImage: String {39 switch self { case .general: "gearshape"; case .chat: "bubble.left.and.bubble.right"; case .assistant: "sparkles"; case .providers: "key.horizontal"; case .server: "brain"; case .security: "lock.shield"; case .data: "externaldrive" }40 }41}4243struct CommandPalette: View {44 @Bindable var window: WindowModel45 let dismiss: () -> Void46 @Environment(AppEnvironment.self) private var env47 @Environment(\.openSettings) private var openSettings48 @Environment(\.accessibilityReduceMotion) private var reduceMotion49 @State private var query = ""50 @State private var selected = 051 @State private var appeared = false52 @FocusState private var focused: Bool5354 private var currentChat: ChatViewModel? { if case .chat(let id) = window.destination { return env.chat(conversationId: id, draftKey: window.draftKey) }; return nil }5556 /// Builds the list for the query. Everything acts on real state: no item is a stub.57 static func items(query: String, window: WindowModel, env: AppEnvironment, chat: ChatViewModel?, openSettings: @escaping (SettingsTab) -> Void) -> [PaletteItem] {58 let p = env.preferences59 var actions: [PaletteItem] = [60 PaletteItem(id: "new", title: "Nouvelle conversation", subtitle: "⌘N", systemImage: "square.and.pencil") { window.newConversation() },61 PaletteItem(id: "search", title: "Rechercher dans les conversations", subtitle: "⌘F", systemImage: "magnifyingglass") { window.searchFocus += 1 },62 PaletteItem(id: "arena", title: "Démarrer une Arena", subtitle: chat?.currentModel.map { "avec \($0.shortName)" } ?? "comparer des modèles", systemImage: "rectangle.split.3x1") {63 window.arenaModelIds = [chat?.settings.modelId].compactMap { $0 }; window.destination = .library(.compare)64 },65 PaletteItem(id: "explorer", title: "Explorer le catalogue de modèles", subtitle: "\(env.catalog.selectableModels.count) modèles", systemImage: "square.grid.2x2") { window.destination = .library(.models) },66 PaletteItem(id: "panel.inspector", title: "Panneau : contexte", subtitle: "⌥⌘I", systemImage: PanelTab.inspector.systemImage) { window.showPanel(.inspector, preferences: p) },67 PaletteItem(id: "panel.timeline", title: "Panneau : chronologie et relecture", subtitle: "⌥⌘T", systemImage: PanelTab.timeline.systemImage) { window.showPanel(.timeline, preferences: p) },68 PaletteItem(id: "panel.lens", title: "Panneau : Response Lens", subtitle: "⌥⌘L", systemImage: PanelTab.lens.systemImage) { window.showPanel(.lens, preferences: p) },69 PaletteItem(id: "panel.branches", title: "Panneau : branches", subtitle: "⌥⌘B", systemImage: PanelTab.branches.systemImage) { window.showPanel(.branches, preferences: p) },70 PaletteItem(id: "reasoning", title: p.showReasoning ? "Masquer le raisonnement" : "Afficher le raisonnement", subtitle: "Affichage", systemImage: "brain") { p.showReasoning.toggle() },71 PaletteItem(id: "dock", title: p.showDock ? "Masquer le dock des modèles" : "Afficher le dock des modèles", subtitle: "Affichage", systemImage: "dock.rectangle") { p.showDock.toggle() },72 PaletteItem(id: "refresh", title: "Actualiser les conversations", subtitle: "⌘R", systemImage: "arrow.clockwise") { Task { await env.conversations.refresh() } },73 PaletteItem(id: "quick", title: "Chat rapide", subtitle: "⇧⌘Espace", systemImage: "bolt.horizontal") { (NSApp.delegate as? AppDelegate)?.toggleQuickChat() },74 PaletteItem(id: "lock", title: "Se déconnecter de ce Mac", subtitle: "Compte", systemImage: "lock") { Task { await env.session.signOut() } },75 ]76 if let chat {77 actions.insert(PaletteItem(id: "web", title: chat.settings.webSearch ? "Désactiver la recherche web" : "Activer la recherche web", subtitle: "⇧⌘I · prochain tour", systemImage: "globe") { chat.settings.webSearch.toggle() }, at: 2)78 actions.insert(PaletteItem(id: "tools", title: chat.settings.toolsEnabled ? "Désactiver les outils" : "Activer les outils", subtitle: "prochain tour", systemImage: "wrench.and.screwdriver") { chat.settings.toolsEnabled.toggle() }, at: 3)79 actions.insert(PaletteItem(id: "pick", title: "Choisir le modèle…", subtitle: "⇧⌘M", systemImage: "cpu") { window.modelPickerToken += 1 }, at: 4)80 for mode in RoutingMode.allCases where mode != .manual {81 actions.append(PaletteItem(id: "route:" + mode.rawValue, title: "Routage : \(mode.label)", subtitle: "le serveur choisit le modèle", systemImage: "arrow.triangle.branch") { chat.settings.presetId = nil; chat.settings.routingMode = mode })82 }83 }84 actions += LibrarySection.allCases.filter { $0 != .models }.map { s in PaletteItem(id: "lib:" + s.rawValue, title: s.title, subtitle: "Espace de travail", systemImage: s.systemImage) { window.destination = .library(s) } }8586 let settings = SettingsTab.allCases.map { t in PaletteItem(id: "settings:" + t.rawValue, section: .settings, title: "Réglages : \(t.title)", subtitle: t == .general ? "⌘," : "", systemImage: t.systemImage) { openSettings(t) } }87 let projects = env.catalog.projects.map { pr in88 PaletteItem(id: "project:" + pr.id, section: .projects, title: "Nouvelle conversation dans « \(pr.name) »", subtitle: pr.conversationCount.map { "\($0) conversations" } ?? "Projet", systemImage: "folder") {89 window.newConversation(); env.chat(conversationId: nil, draftKey: window.draftKey).projectId = pr.id90 }91 }92 let prompts = env.catalog.prompts.map { pm in93 PaletteItem(id: "prompt:" + pm.id, section: .prompts, title: pm.title, subtitle: PromptTemplate.variables(in: pm.body).isEmpty ? "insérer dans le message" : "variables à remplir", systemImage: "text.quote") {94 guard let chat else { env.pendingComposerText = pm.body; return }95 // a prompt with variables goes through the composer's command list, which asks for the values96 if PromptTemplate.variables(in: pm.body).isEmpty { chat.appendToDraft(pm.body); Task { try? await env.api.updatePrompt(pm.id, used: true) } } else { chat.draft = "/" + pm.title }97 window.composerFocus += 198 }99 }100 func modelItem(_ m: AIModel) -> PaletteItem {101 PaletteItem(id: "model:" + m.id, section: .models, title: m.displayName, subtitle: m.factsLine, systemImage: "cpu", model: m) {102 if let chat { chat.selectModel(m) } else { window.explorerModelId = m.id; window.destination = .library(.models) }103 }104 }105 let conversations = env.conversations.items.map { c in PaletteItem(id: "conv:" + c.id, section: .conversations, title: c.title, subtitle: Format.relative(c.sortDate), systemImage: "bubble.left") { window.open(c.id) } }106107 let q = query.trimmingCharacters(in: .whitespaces)108 if q.isEmpty {109 return Array(actions.prefix(8)) + Array(conversations.prefix(5)) + (env.catalog.favorites + env.catalog.recents).prefix(4).map(modelItem) + Array(settings.prefix(2))110 }111 func rank(_ list: [PaletteItem], _ limit: Int) -> [PaletteItem] { list.compactMap { item in Fuzzy.score(q, in: item.title).map { ($0, item) } }.sorted { $0.0 > $1.0 }.prefix(limit).map(\.1) }112 var mq = ModelQuery(); mq.text = q113 return rank(actions, 6) + rank(conversations, 6) + env.catalog.index.search(mq).prefix(7).map(modelItem) + rank(projects, 4) + rank(prompts, 5) + rank(settings, 4)114 }115116 var body: some View {117 let list = Self.items(query: query, window: window, env: env, chat: currentChat) { tab in env.settingsTab = tab; openSettings() }118 VStack(spacing: 0) {119 HStack(spacing: 10) {120 Image(systemName: "command").font(.system(size: 14, weight: .medium)).foregroundStyle(DS.C.muted)121 TextField("Action, conversation, modèle, projet, prompt, réglage…", text: $query).textFieldStyle(.plain).font(.system(size: 17)).focused($focused)122 .onSubmit { run(list) }.accessibilityIdentifier("palette-field")123 Text("esc").font(DS.F.micro).foregroundStyle(DS.C.muted).padding(.horizontal, 5).padding(.vertical, 2).overlay(RoundedRectangle(cornerRadius: 4).strokeBorder(DS.C.border))124 }125 .padding(.horizontal, 16).padding(.vertical, 14)126 Rectangle().fill(DS.C.border).frame(height: 1)127 ScrollViewReader { proxy in128 ScrollView {129 LazyVStack(alignment: .leading, spacing: 1) {130 ForEach(Array(list.enumerated()), id: \.element.id) { i, item in131 if i == 0 || list[i - 1].section != item.section {132 Text(item.section.rawValue.uppercased()).font(DS.F.micro).tracking(0.5).foregroundStyle(DS.C.muted).padding(.horizontal, 10).padding(.top, i == 0 ? 6 : 12).padding(.bottom, 3)133 }134 Button { selected = i; run(list) } label: { row(item, isSelected: i == selected) }135 .buttonStyle(.plain).id(i).accessibilityIdentifier("palette-item")136 // results stagger in (24 ms per item, first 8) — skipped under Reduce Motion137 .opacity(appeared ? 1 : 0).offset(y: appeared || reduceMotion ? 0 : 4)138 .animation(reduceMotion ? DS.Motion.fade : DS.Motion.snappy.delay(Double(min(i, 8)) * 0.024), value: appeared)139 }140 if list.isEmpty { Text("Aucun résultat pour « \(query) »").font(DS.F.uiRegular).foregroundStyle(DS.C.muted).frame(maxWidth: .infinity).padding(30) }141 }142 .padding(6)143 }144 .onChange(of: selected) { _, s in proxy.scrollTo(s) }145 }146 }147 .frame(width: 640, height: 440)148 .floatSurface(radius: DS.R.float)149 .scaleEffect(appeared || reduceMotion ? 1 : 0.98).opacity(appeared ? 1 : 0)150 .onAppear {151 withAnimation(DS.Motion.resolve(DS.Motion.snappy, reduceMotion: reduceMotion)) { appeared = true }152 // the composer's AppKit text view holds the keyboard: it is released first, then the field takes the focus153 NSApp.keyWindow?.makeFirstResponder(nil)154 focused = true155 Task { try? await Task.sleep(for: .milliseconds(60)); focused = true }156 }157 .onChange(of: query) { selected = 0 }158 .onKeyPress(.downArrow) { selected = min(selected + 1, max(list.count - 1, 0)); return .handled }159 .onKeyPress(.upArrow) { selected = max(selected - 1, 0); return .handled }160 .onKeyPress(.escape) { dismiss(); return .handled }161 .task { await env.catalog.loadPromptsIfNeeded() }162 .accessibilityAddTraits(.isModal)163 }164165 private func row(_ item: PaletteItem, isSelected: Bool) -> some View {166 HStack(spacing: 10) {167 if let m = item.model { ModelMark(m, size: 17).frame(width: 22) } else { Image(systemName: item.systemImage).font(.system(size: 13)).frame(width: 22).foregroundStyle(isSelected ? DS.C.accent : DS.C.text2) }168 Text(item.title).font(.system(size: 13.5)).foregroundStyle(DS.C.text).lineLimit(1)169 if let m = item.model { RouteBadge(route: m.route) }170 Spacer(minLength: 8)171 Text(item.subtitle).font(.system(size: 11.5).monospacedDigit()).foregroundStyle(DS.C.muted).lineLimit(1)172 }173 .padding(.horizontal, 10).frame(height: 34).contentShape(Rectangle())174 .background(isSelected ? DS.C.accentSoft : .clear, in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))175 }176177 private func run(_ list: [PaletteItem]) {178 guard list.indices.contains(selected) else { return }179 let item = list[selected]180 dismiss(); item.run()181 }182}183184/// Presents the palette as a centred floating panel over the window (not a sheet): scales in from 0.98, closes fast.185struct CommandPaletteOverlay: ViewModifier {186 @Bindable var window: WindowModel187 func body(content: Content) -> some View {188 content.overlay {189 if window.showPalette {190 ZStack(alignment: .top) {191 Color.black.opacity(0.18).ignoresSafeArea().onTapGesture { window.showPalette = false }.accessibilityHidden(true)192 CommandPalette(window: window) { window.showPalette = false }.padding(.top, 90)193 }194 .transition(.opacity.animation(.easeOut(duration: 0.12)))195 }196 }197 }198}199